code
stringlengths
4
1.01M
language
stringclasses
2 values
vimrc CHANGELOG =============== This file is used to list changes made in each version of the vimrc cookbook. 0.1.0 ----- - [your_name] - Initial release of vimrc - - - Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown. The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown.
Java
<?php /** * @package jCart * @copyright Copyright (C) 2009 - 2012 softPHP,http://www.soft-php.com * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html */ // no direct access defined( '_JEXEC' ) or die( 'Restricted access' ); $_['text_sub_total'] = 'Sub-Total'; ?>
Java
/* * This file contains pieces of the Linux TCP/IP stack needed for modular * TOE support. * * Copyright (C) 2006-2009 Chelsio Communications. All rights reserved. * See the corresponding files in the Linux tree for copyrights of the * original Linux code a lot of this file is based on. * * Written by Dimitris Michailidis (dm@chelsio.com) * * 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 LICENSE file included in this * release for licensing terms and conditions. */ /* The following tags are used by the out-of-kernel Makefile to identify * supported kernel versions if a module_support-<kver> file is not found. * Do not remove these tags. * $SUPPORTED KERNEL 2.6.23$ * $SUPPORTED KERNEL 2.6.24$ * $SUPPORTED KERNEL 2.6.25$ * $SUPPORTED KERNEL 2.6.26$ * $SUPPORTED KERNEL 2.6.27$ * $SUPPORTED KERNEL 2.6.28$ * $SUPPORTED KERNEL 2.6.29$ * $SUPPORTED KERNEL 2.6.30$ * $SUPPORTED KERNEL 2.6.31$ * $SUPPORTED KERNEL 2.6.32$ * $SUPPORTED KERNEL 2.6.33$ * $SUPPORTED KERNEL 2.6.34$ * $SUPPORTED KERNEL 2.6.35$ * $SUPPORTED KERNEL 2.6.36$ * $SUPPORTED KERNEL 2.6.37$ */ #include <net/tcp.h> #include <linux/pkt_sched.h> #include <linux/kprobes.h> #include "defs.h" #include <asm/tlbflush.h> #if defined(CONFIG_SMP) && !defined(PPC64_TLB_BATCH_NR) static unsigned long (*kallsyms_lookup_name_p)(const char *name); static void (*flush_tlb_mm_p)(struct mm_struct *mm); static void (*flush_tlb_page_p)(struct vm_area_struct *vma, unsigned long va); void flush_tlb_mm_offload(struct mm_struct *mm); #endif void flush_tlb_page_offload(struct vm_area_struct *vma, unsigned long addr) { #if defined(CONFIG_SMP) && !defined(PPC64_TLB_BATCH_NR) flush_tlb_page_p(vma, addr); #endif } int sysctl_tcp_window_scaling = 1; int sysctl_tcp_adv_win_scale = 2; #define ECN_OR_COST(class) TC_PRIO_##class const __u8 ip_tos2prio[16] = { TC_PRIO_BESTEFFORT, ECN_OR_COST(FILLER), TC_PRIO_BESTEFFORT, ECN_OR_COST(BESTEFFORT), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_BULK, ECN_OR_COST(BULK), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE, ECN_OR_COST(INTERACTIVE), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK), TC_PRIO_INTERACTIVE_BULK, ECN_OR_COST(INTERACTIVE_BULK) }; /* * Adapted from tcp_minisocks.c */ void tcp_time_wait(struct sock *sk, int state, int timeo) { struct inet_timewait_sock *tw = NULL; const struct inet_connection_sock *icsk = inet_csk(sk); const struct tcp_sock *tp = tcp_sk(sk); int recycle_ok = 0; if (tcp_death_row.tw_count < tcp_death_row.sysctl_max_tw_buckets) tw = inet_twsk_alloc(sk, state); if (tw != NULL) { struct tcp_timewait_sock *tcptw = tcp_twsk((struct sock *)tw); const int rto = (icsk->icsk_rto << 2) - (icsk->icsk_rto >> 1); tw->tw_rcv_wscale = tp->rx_opt.rcv_wscale; tcptw->tw_rcv_nxt = tp->rcv_nxt; tcptw->tw_snd_nxt = tp->snd_nxt; tcptw->tw_rcv_wnd = tcp_receive_window(tp); tcptw->tw_ts_recent = tp->rx_opt.ts_recent; tcptw->tw_ts_recent_stamp = tp->rx_opt.ts_recent_stamp; /* Linkage updates. */ __inet_twsk_hashdance(tw, sk, &tcp_hashinfo); /* Get the TIME_WAIT timeout firing. */ if (timeo < rto) timeo = rto; if (recycle_ok) { tw->tw_timeout = rto; } else { tw->tw_timeout = TCP_TIMEWAIT_LEN; if (state == TCP_TIME_WAIT) timeo = TCP_TIMEWAIT_LEN; } inet_twsk_schedule(tw, &tcp_death_row, timeo, TCP_TIMEWAIT_LEN); inet_twsk_put(tw); } else { /* Sorry, if we're out of memory, just CLOSE this * socket up. We've got bigger problems than * non-graceful socket closings. */ if (net_ratelimit()) printk(KERN_INFO "TCP: time wait bucket table overflow\n"); } tcp_done(sk); } void flush_tlb_mm_offload(struct mm_struct *mm) { #if defined(CONFIG_SMP) && !defined(PPC64_TLB_BATCH_NR) if (flush_tlb_mm_p) flush_tlb_mm_p(mm); #endif } #if defined(CONFIG_SMP) && !defined(PPC64_TLB_BATCH_NR) static int find_kallsyms_lookup_name(void) { int err = 0; #if defined(KPROBES_KALLSYMS) struct kprobe kp; memset(&kp, 0, sizeof kp); kp.symbol_name = "kallsyms_lookup_name"; err = register_kprobe(&kp); if (!err) { kallsyms_lookup_name_p = (void *)kp.addr; unregister_kprobe(&kp); } #else kallsyms_lookup_name_p = (void *)KALLSYMS_LOOKUP; #endif if (!err) err = kallsyms_lookup_name_p == NULL; return err; } #endif int prepare_tom_for_offload(void) { #if defined(CONFIG_SMP) && !defined(PPC64_TLB_BATCH_NR) if (!kallsyms_lookup_name_p) { int err = find_kallsyms_lookup_name(); if (err) return err; } flush_tlb_mm_p = (void *)kallsyms_lookup_name_p("flush_tlb_mm"); if (!flush_tlb_mm_p) { printk(KERN_ERR "Could not locate flush_tlb_mm"); return -1; } flush_tlb_page_p = (void *)kallsyms_lookup_name_p("flush_tlb_page"); if (!flush_tlb_page_p) { printk(KERN_ERR "Could not locate flush_tlb_page"); return -1; } #endif return 0; }
Java
/** Copyright 2011 Red Hat, Inc. This software is licensed to you under the GNU General Public License as published by the Free Software Foundation; either version 2 of the License (GPLv2) or (at your option) any later version. There is NO WARRANTY for this software, express or implied, including the implied warranties of MERCHANTABILITY, NON-INFRINGEMENT, 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. */ KT.panel.list.registerPage('gpg_keys', { create : 'new_gpg_key', extra_create_data : function(){ return { 'gpg_key[name]' : $('#gpg_key_name').val() }; } }); $(document).ready(function(){ $('#upload_gpg_key').live('click', function(event){ KT.gpg_key.upload(); }); $('#upload_new_gpg_key').live('submit', function(e){ e.preventDefault(); KT.gpg_key.upload(); }); $('#update_upload_gpg_key').live('click', function(event){ KT.gpg_key.upload_update(); }); $('#gpg_key_content').live('input keyup paste', function(){ if( $(this).val() !== '' ){ $('#gpg_key_content_upload').attr('disabled', 'disabled'); $('#upload_gpg_key').attr('disabled', 'disabled'); $('#clear_gpg_key').removeAttr('disabled'); } else { $('#gpg_key_content_upload').removeAttr('disabled'); $('#upload_gpg_key').removeAttr('disabled'); $('#clear_gpg_key').attr('disabled', 'disabled'); } }); $('#gpg_key_content_upload').live('change', function(){ if( $(this).val() !== '' ){ $('#gpg_key_content').attr('disabled', 'disabled'); $('#save_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); } else { $('#gpg_key_content').removeAttr('disabled'); $('#save_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); } }); $('#clear_upload_gpg_key').live('click', function(){ $('#gpg_key_content_upload').val(''); $('#gpg_key_content').removeAttr('disabled'); $('#save_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_gpg_key').attr('disabled', 'disabled'); }); $('#clear_gpg_key').live('click', function(){ $('#gpg_key_content').val(''); $('#gpg_key_content_upload').removeAttr('disabled'); $('#upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_gpg_key').attr('disabled', 'disabled'); }); $('#gpg_key_content_upload_update').live('change', function(){ if( $(this).val() !== '' ){ $('#update_upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); } else { $('#update_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); } }); $('#clear_upload_gpg_key').live('click', function(){ $('#update_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#gpg_key_content_upload_update').val(''); }); }); KT.gpg_key = (function($){ var self = this, get_buttons = function(){ return { 'gpg_key_save' : $('#save_gpg_key'), 'gpg_key_upload': $('#upload_gpg_key') } }, enable_buttons = function(){ var buttons = get_buttons(); buttons.gpg_key_save.removeAttr('disabled'); buttons.gpg_key_upload.removeAttr('disabled'); }, disable_buttons = function(){ var buttons = get_buttons(); buttons.gpg_key_save.attr('disabled', 'disabled'); buttons.gpg_key_upload.attr('disabled', 'disabled'); }; self.upload = function(){ var submit_data = { 'gpg_key[name]' : $('#gpg_key_name').val() }; disable_buttons(); $('#upload_new_gpg_key').ajaxSubmit({ url : KT.routes['gpg_keys_path'](), type : 'POST', data : submit_data, iframe : true, success : function(data, status, xhr){ var parsed_data = $(data); if( parsed_data.get(0).tagName === 'PRE' ){ notices.displayNotice('error', parsed_data.html()); } else { KT.panel.list.createSuccess(data); } enable_buttons(); }, error : function(){ enable_buttons(); notices.checkNotices(); } }); }; self.upload_update = function(){ $('#update_upload_gpg_key').attr('disabled', 'disabled'); $('#clear_upload_gpg_key').attr('disabled', 'disabled'); $('#upload_gpg_key').ajaxSubmit({ url : $(this).data('url'), type : 'POST', iframe : true, success : function(data, status, xhr){ if( !data.match(/notices/) ){ $('#gpg_key_content').html(data); $('#upload_gpg_key').val(''); } notices.checkNotices(); $('#update_upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); }, error : function(){ $('#update_upload_gpg_key').removeAttr('disabled'); $('#clear_upload_gpg_key').removeAttr('disabled'); notices.checkNotices(); } }); }; return self; })(jQuery);
Java
.pane-sliders > .panel { border: none !important; font-family:arial; } .pane-sliders >.panel > h3 { background:url(../images/header-bg.gif) repeat-x!important; height:37px; line-height:37px; padding:0; } .pane-sliders >.panel h3 span{ text-transform:uppercase; color:#c16306; } .pane-toggler-down { border-bottom:none!important; } .pane-toggler-down span { background: url("../images/arrow-down.gif") no-repeat scroll 8px 50% transparent!important; padding-left: 26px!important; } .pane-toggler span { background: url("../images/arrow-up.gif") no-repeat scroll 10px 50% transparent!important; padding-left: 26px!important; } .pane-sliders > .panel{ border:1px solid #cacaca!important; border-top:1px solid #da710a!important; border-radius:5px 5px 5px 5px; padding:0 1px; } fieldset.panelform{ padding:10px!important; } fieldset.panelform li > label, fieldset.panelform div.paramrow label, fieldset.panelform span.faux-label { max-width: 30% !important; min-width: 30% !important; } #module-sliders .spacer h3{ padding-top:3px; margin:0px; background:#fff!important; } #module-sliders .adminform{ padding:0; } #module-sliders fieldset > ul > li > label { color: #505050; font-size: 11px; line-height:18px; font-weight: bold; max-width: 30% !important; min-width: 30% !important; text-align: left; } #module-sliders fieldset > ul.adminformlist > li { border-bottom: 1px dotted #c4c4c4; min-height:35px; padding:0px; margin:5px; } #btss-dialog li{ list-style:none; } /* Fix chosen*/ #module-sliders .chzn-container ul.chzn-results{ min-width:95%; } #module-sliders .chzn-container-single .chzn-single div{ height:100%!important; } fieldset.adminform fieldset.radio, fieldset.panelform fieldset.radio, fieldset.adminform-legacy fieldset.radio { border: 0 none; float: left; margin: 0 0 5px; max-width: 68% !important; min-width: 68% !important; padding: 0; } #module-sliders input[type=text],#module-sliders textarea { background:-moz-linear-gradient(center bottom , white 85%, #EEEEEE 99%) repeat scroll 0 0 transparent; border: 1px solid #AAAAAA; font-family: sans-serif; font-size:11px; margin: 1px 0; outline: 0 none; padding: 6px 20px 6px 5px; border-radius: 4px 4px 4px 4px; } .bt-desc{ line-height:200%; } .bt-desc img{ margin-right:10px; } .bt-license{ border-top: 1px dotted #c4c4c4; padding:10px 0px; } .bt-desc p a{ display: inline-block; height: 28px; margin-right: 7px; text-indent: -999px; width: 28px; text-decoration:none; margin-top:10px; } .social-f { background: url("../images/icon_f.png") no-repeat scroll left top transparent; } .social-f:hover { background: url("../images/icon_f_hover.png") no-repeat scroll left top transparent; } .social-t { background: url("../images/icon_t.png") no-repeat scroll left top transparent; } .social-t:hover { background: url("../images/icon_t_hover.png") no-repeat scroll left top transparent; } .social-rss { background: url("../images/icon_rss.png") no-repeat scroll left top transparent; } .social-rss:hover { background: url("../images/icon_rss_hover.png") no-repeat scroll left top transparent; } .social-g { background: url("../images/icon_group.png") no-repeat scroll left top transparent; } .social-g:hover { background: url("../images/icon_group_hover.png") no-repeat scroll left top transparent; } .switcher-yes,.switcher-no { background: url("../images/switcher-yesno.png") no-repeat scroll 0 0 transparent; cursor: pointer; float: left; height: 20px; margin-top: 4px; width: 64px; } .switcher-no { background-position: 0 -20px; } .switcher-on,.switcher-off { background: url("../images/switcher-onoff.png") no-repeat scroll 0 0 transparent; cursor: pointer; float: left; height: 20px; margin-top: 4px; width: 64px; } .switcher-off { background-position: 0 -20px; } #btnGetImages, #btnDeleteAll{ background: url(../images/button.png) no-repeat; width: 110px; height: 35px; text-align: center; line-height: 33px; border: none; color: #ffffff; margin-top: 0px !important; } #layout-demo{ width: 88px; height: 18px; background: url(../images/demo.png) no-repeat; float: left; margin: 5px 10px; text-align: center; } #layout-demo a{ color: #ffffff; font-family: arial; font-size: 11px; line-height: 17px; } #jform_params_layout_chzn{ float:left; } div.colorpicker{ z-index:999; } div.colorpicker input[type="text"] { height: auto!important; width: auto!important; padding:0; margin:0; background:none; border:none; } #btss-dialog label{ width:120px; display:inline-block; }
Java
/* UnknownTypeException.java -- Thrown by an unknown type. Copyright (C) 2012 Free Software Foundation, Inc. This file is part of GNU Classpath. GNU Classpath 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. GNU Classpath 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 Classpath; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Linking this library statically or dynamically with other modules is making a combined work based on this library. Thus, the terms and conditions of the GNU General Public License cover the whole combination. As a special exception, the copyright holders of this library give you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you may extend this exception to your version of the library, but you are not obligated to do so. If you do not wish to do so, delete this exception statement from your version. */ package javax.lang.model.type; /** * Thrown when an unknown type is encountered, * usually by a {@link TypeVisitor}. * * @author Andrew John Hughes (gnu_andrew@member.fsf.org) * @since 1.6 * @see TypeVisitor#visitUnknown(TypeMirror,P) */ public class UnknownTypeException extends RuntimeException { private static final long serialVersionUID = 269L; /** * The unknown type. */ private TypeMirror type; /** * The additional parameter. */ private Object param; /** * Constructs a new {@code UnknownTypeException} * for the specified type. An additional * object may also be passed to give further context as * to where the exception occurred, such as the additional parameter * used by visitor classes. * * @param type the unknown type or {@code null}. * @param param the additional parameter or {@code null}. */ public UnknownTypeException(TypeMirror type, Object param) { this.type = type; this.param = param; } /** * Returns the additional parameter or {@code null} if * unavailable. * * @return the additional parameter. */ public Object getArgument() { return param; } /** * Returns the unknown type or {@code null} * if unavailable. The type may be {@code null} if * the value is not {@link java.io.Serializable} but the * exception has been serialized and read back in. * * @return the unknown type. */ public TypeMirror getUnknownType() { return type; } }
Java
/* * Synopsys DesignWare I2C adapter driver (master only). * * Partly based on code of similar driver from U-Boot: * Copyright (C) 2009 ST Micoelectronics * * and corresponding code from Linux Kernel * Copyright (C) 2006 Texas Instruments. * Copyright (C) 2007 MontaVista Software Inc. * Copyright (C) 2009 Provigent Ltd. * * Copyright (C) 2015 Andrey Smirnov <andrew.smirnov@gmail.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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 <clock.h> #include <common.h> #include <driver.h> #include <init.h> #include <of.h> #include <malloc.h> #include <types.h> #include <xfuncs.h> #include <linux/clk.h> #include <linux/err.h> #include <linux/math64.h> #include <io.h> #include <i2c/i2c.h> #define DW_I2C_BIT_RATE 100000 #define DW_IC_CON 0x0 #define DW_IC_CON_MASTER (1 << 0) #define DW_IC_CON_SPEED_STD (1 << 1) #define DW_IC_CON_SPEED_FAST (1 << 2) #define DW_IC_CON_SLAVE_DISABLE (1 << 6) #define DW_IC_TAR 0x4 #define DW_IC_DATA_CMD 0x10 #define DW_IC_DATA_CMD_CMD (1 << 8) #define DW_IC_DATA_CMD_STOP (1 << 9) #define DW_IC_SS_SCL_HCNT 0x14 #define DW_IC_SS_SCL_LCNT 0x18 #define DW_IC_FS_SCL_HCNT 0x1c #define DW_IC_FS_SCL_LCNT 0x20 #define DW_IC_INTR_MASK 0x30 #define DW_IC_RAW_INTR_STAT 0x34 #define DW_IC_INTR_RX_UNDER (1 << 0) #define DW_IC_INTR_RX_OVER (1 << 1) #define DW_IC_INTR_RX_FULL (1 << 2) #define DW_IC_INTR_TX_OVER (1 << 3) #define DW_IC_INTR_TX_EMPTY (1 << 4) #define DW_IC_INTR_RD_REQ (1 << 5) #define DW_IC_INTR_TX_ABRT (1 << 6) #define DW_IC_INTR_RX_DONE (1 << 7) #define DW_IC_INTR_ACTIVITY (1 << 8) #define DW_IC_INTR_STOP_DET (1 << 9) #define DW_IC_INTR_START_DET (1 << 10) #define DW_IC_INTR_GEN_CALL (1 << 11) #define DW_IC_RX_TL 0x38 #define DW_IC_TX_TL 0x3c #define DW_IC_CLR_INTR 0x40 #define DW_IC_CLR_TX_ABRT 0x54 #define DW_IC_SDA_HOLD 0x7c #define DW_IC_ENABLE 0x6c #define DW_IC_ENABLE_ENABLE (1 << 0) #define DW_IC_STATUS 0x70 #define DW_IC_STATUS_TFNF (1 << 1) #define DW_IC_STATUS_TFE (1 << 2) #define DW_IC_STATUS_RFNE (1 << 3) #define DW_IC_STATUS_MST_ACTIVITY (1 << 5) #define DW_IC_TX_ABRT_SOURCE 0x80 #define DW_IC_ENABLE_STATUS 0x9c #define DW_IC_ENABLE_STATUS_IC_EN (1 << 0) #define DW_IC_COMP_VERSION 0xf8 #define DW_IC_SDA_HOLD_MIN_VERS 0x3131312A #define DW_IC_COMP_TYPE 0xfc #define DW_IC_COMP_TYPE_VALUE 0x44570140 #define MAX_T_POLL_COUNT 100 #define DW_TIMEOUT_IDLE (40 * MSECOND) #define DW_TIMEOUT_TX (2 * MSECOND) #define DW_TIMEOUT_RX (2 * MSECOND) #define DW_IC_SDA_HOLD_RX_SHIFT 16 #define DW_IC_SDA_HOLD_RX_MASK GENMASK(23, DW_IC_SDA_HOLD_RX_SHIFT) struct dw_i2c_dev { void __iomem *base; struct clk *clk; struct i2c_adapter adapter; u32 sda_hold_time; }; static inline struct dw_i2c_dev *to_dw_i2c_dev(struct i2c_adapter *a) { return container_of(a, struct dw_i2c_dev, adapter); } static void i2c_dw_enable(struct dw_i2c_dev *dw, bool enable) { u32 reg = 0; /* * This subrotine is an implementation of an algorithm * described in "Cyclone V Hard Processor System Technical * Reference * Manual" p. 20-19, "Disabling the I2C Controller" */ int timeout = MAX_T_POLL_COUNT; if (enable) reg |= DW_IC_ENABLE_ENABLE; do { uint32_t ic_enable_status; writel(reg, dw->base + DW_IC_ENABLE); ic_enable_status = readl(dw->base + DW_IC_ENABLE_STATUS); if ((ic_enable_status & DW_IC_ENABLE_STATUS_IC_EN) == enable) return; udelay(250); } while (timeout--); dev_warn(&dw->adapter.dev, "timeout in %sabling adapter\n", enable ? "en" : "dis"); } /* * All of the code pertaining to tming calculation is taken from * analogous driver in Linux kernel */ static uint32_t i2c_dw_scl_hcnt(uint32_t ic_clk, uint32_t tSYMBOL, uint32_t tf, int cond, int offset) { /* * DesignWare I2C core doesn't seem to have solid strategy to meet * the tHD;STA timing spec. Configuring _HCNT based on tHIGH spec * will result in violation of the tHD;STA spec. */ if (cond) /* * Conditional expression: * * IC_[FS]S_SCL_HCNT + (1+4+3) >= IC_CLK * tHIGH * * This is based on the DW manuals, and represents an ideal * configuration. The resulting I2C bus speed will be * faster than any of the others. * * If your hardware is free from tHD;STA issue, try this one. */ return (ic_clk * tSYMBOL + 500000) / 1000000 - 8 + offset; else /* * Conditional expression: * * IC_[FS]S_SCL_HCNT + 3 >= IC_CLK * (tHD;STA + tf) * * This is just experimental rule; the tHD;STA period turned * out to be proportinal to (_HCNT + 3). With this setting, * we could meet both tHIGH and tHD;STA timing specs. * * If unsure, you'd better to take this alternative. * * The reason why we need to take into account "tf" here, * is the same as described in i2c_dw_scl_lcnt(). */ return (ic_clk * (tSYMBOL + tf) + 500000) / 1000000 - 3 + offset; } static uint32_t i2c_dw_scl_lcnt(uint32_t ic_clk, uint32_t tLOW, uint32_t tf, int offset) { /* * Conditional expression: * * IC_[FS]S_SCL_LCNT + 1 >= IC_CLK * (tLOW + tf) * * DW I2C core starts counting the SCL CNTs for the LOW period * of the SCL clock (tLOW) as soon as it pulls the SCL line. * In order to meet the tLOW timing spec, we need to take into * account the fall time of SCL signal (tf). Default tf value * should be 0.3 us, for safety. */ return ((ic_clk * (tLOW + tf) + 500000) / 1000000) - 1 + offset; } static void i2c_dw_setup_timings(struct dw_i2c_dev *dw) { uint32_t hcnt, lcnt; u32 reg; const uint32_t sda_falling_time = 300; /* ns */ const uint32_t scl_falling_time = 300; /* ns */ const unsigned int input_clock_khz = clk_get_rate(dw->clk) / 1000; /* Set SCL timing parameters for standard-mode */ hcnt = i2c_dw_scl_hcnt(input_clock_khz, 4000, /* tHD;STA = tHIGH = 4.0 us */ sda_falling_time, 0, /* 0: DW default, 1: Ideal */ 0); /* No offset */ lcnt = i2c_dw_scl_lcnt(input_clock_khz, 4700, /* tLOW = 4.7 us */ scl_falling_time, 0); /* No offset */ writel(hcnt, dw->base + DW_IC_SS_SCL_HCNT); writel(lcnt, dw->base + DW_IC_SS_SCL_LCNT); hcnt = i2c_dw_scl_hcnt(input_clock_khz, 600, /* tHD;STA = tHIGH = 0.6 us */ sda_falling_time, 0, /* 0: DW default, 1: Ideal */ 0); /* No offset */ lcnt = i2c_dw_scl_lcnt(input_clock_khz, 1300, /* tLOW = 1.3 us */ scl_falling_time, 0); /* No offset */ writel(hcnt, dw->base + DW_IC_FS_SCL_HCNT); writel(lcnt, dw->base + DW_IC_FS_SCL_LCNT); /* Configure SDA Hold Time if required */ reg = readl(dw->base + DW_IC_COMP_VERSION); if (reg >= DW_IC_SDA_HOLD_MIN_VERS) { u32 ht; int ret; ret = of_property_read_u32(dw->adapter.dev.device_node, "i2c-sda-hold-time-ns", &ht); if (ret) { /* Keep previous hold time setting if no one set it */ dw->sda_hold_time = readl(dw->base + DW_IC_SDA_HOLD); } else if (ht) { dw->sda_hold_time = div_u64((u64)input_clock_khz * ht + 500000, 1000000); } /* * Workaround for avoiding TX arbitration lost in case I2C * slave pulls SDA down "too quickly" after falling egde of * SCL by enabling non-zero SDA RX hold. Specification says it * extends incoming SDA low to high transition while SCL is * high but it apprears to help also above issue. */ if (!(dw->sda_hold_time & DW_IC_SDA_HOLD_RX_MASK)) dw->sda_hold_time |= 1 << DW_IC_SDA_HOLD_RX_SHIFT; dev_dbg(&dw->adapter.dev, "adjust SDA hold time.\n"); writel(dw->sda_hold_time, dw->base + DW_IC_SDA_HOLD); } } static int i2c_dw_wait_for_bits(struct dw_i2c_dev *dw, uint32_t offset, uint32_t mask, uint32_t value, uint64_t timeout) { const uint64_t start = get_time_ns(); do { const uint32_t reg = readl(dw->base + offset); if ((reg & mask) == value) return 0; } while (!is_timeout(start, timeout)); return -ETIMEDOUT; } static int i2c_dw_wait_for_idle(struct dw_i2c_dev *dw) { const uint32_t mask = DW_IC_STATUS_MST_ACTIVITY | DW_IC_STATUS_TFE; const uint32_t value = DW_IC_STATUS_TFE; return i2c_dw_wait_for_bits(dw, DW_IC_STATUS, mask, value, DW_TIMEOUT_IDLE); } static int i2c_dw_wait_for_tx_fifo_not_full(struct dw_i2c_dev *dw) { const uint32_t mask = DW_IC_STATUS_TFNF; const uint32_t value = DW_IC_STATUS_TFNF; return i2c_dw_wait_for_bits(dw, DW_IC_STATUS, mask, value, DW_TIMEOUT_TX); } static int i2c_dw_wait_for_rx_fifo_not_empty(struct dw_i2c_dev *dw) { const uint32_t mask = DW_IC_STATUS_RFNE; const uint32_t value = DW_IC_STATUS_RFNE; return i2c_dw_wait_for_bits(dw, DW_IC_STATUS, mask, value, DW_TIMEOUT_RX); } static void i2c_dw_reset(struct dw_i2c_dev *dw) { i2c_dw_enable(dw, false); i2c_dw_enable(dw, true); } static void i2c_dw_abort_tx(struct dw_i2c_dev *dw) { i2c_dw_reset(dw); } static void i2c_dw_abort_rx(struct dw_i2c_dev *dw) { i2c_dw_reset(dw); } static int i2c_dw_read(struct dw_i2c_dev *dw, const struct i2c_msg *msg) { int i; for (i = 0; i < msg->len; i++) { int ret; const bool last_byte = i == msg->len - 1; uint32_t ic_cmd_data = DW_IC_DATA_CMD_CMD; if (last_byte) ic_cmd_data |= DW_IC_DATA_CMD_STOP; writel(ic_cmd_data, dw->base + DW_IC_DATA_CMD); ret = i2c_dw_wait_for_rx_fifo_not_empty(dw); if (ret < 0) { i2c_dw_abort_rx(dw); return ret; } msg->buf[i] = (uint8_t)readl(dw->base + DW_IC_DATA_CMD); } return msg->len; } static int i2c_dw_write(struct dw_i2c_dev *dw, const struct i2c_msg *msg) { int i; uint32_t ic_int_stat; for (i = 0; i < msg->len; i++) { int ret; uint32_t ic_cmd_data; const bool last_byte = i == msg->len - 1; ic_int_stat = readl(dw->base + DW_IC_RAW_INTR_STAT); if (ic_int_stat & DW_IC_INTR_TX_ABRT) return -EIO; ret = i2c_dw_wait_for_tx_fifo_not_full(dw); if (ret < 0) { i2c_dw_abort_tx(dw); return ret; } ic_cmd_data = msg->buf[i]; if (last_byte) ic_cmd_data |= DW_IC_DATA_CMD_STOP; writel(ic_cmd_data, dw->base + DW_IC_DATA_CMD); } return msg->len; } static int i2c_dw_wait_for_stop(struct dw_i2c_dev *dw) { const uint32_t mask = DW_IC_INTR_STOP_DET; const uint32_t value = DW_IC_INTR_STOP_DET; return i2c_dw_wait_for_bits(dw, DW_IC_RAW_INTR_STAT, mask, value, DW_TIMEOUT_IDLE); } static int i2c_dw_finish_xfer(struct dw_i2c_dev *dw) { int ret; uint32_t ic_int_stat; /* * We expect the controller to signal STOP condition on the * bus, so we are going to wait for that first. */ ret = i2c_dw_wait_for_stop(dw); if (ret < 0) return ret; /* * Now that we now that the stop condition has been signaled * we need to wait for controller to go into IDLE state to * make sure all of the possible error conditions on the bus * have been propagated to apporpriate status * registers. Experiment shows that not doing so often results * in false positive "successful" transfers */ ret = i2c_dw_wait_for_idle(dw); if (ret >= 0) { ic_int_stat = readl(dw->base + DW_IC_RAW_INTR_STAT); if (ic_int_stat & DW_IC_INTR_TX_ABRT) return -EIO; } return ret; } static int i2c_dw_set_address(struct dw_i2c_dev *dw, uint8_t address) { int ret; uint32_t ic_tar; /* * As per "Cyclone V Hard Processor System Technical Reference * Manual" p. 20-19, we have to wait for controller to be in * idle state in order to be able to set the address * dynamically */ ret = i2c_dw_wait_for_idle(dw); if (ret < 0) return ret; ic_tar = readl(dw->base + DW_IC_TAR); ic_tar &= 0xfffffc00; writel(ic_tar | address, dw->base + DW_IC_TAR); return 0; } static int i2c_dw_xfer(struct i2c_adapter *adapter, struct i2c_msg *msgs, int num) { int i, ret = 0; struct dw_i2c_dev *dw = to_dw_i2c_dev(adapter); for (i = 0; i < num; i++) { if (msgs[i].flags & I2C_M_DATA_ONLY) return -ENOTSUPP; ret = i2c_dw_set_address(dw, msgs[i].addr); if (ret < 0) break; if (msgs[i].flags & I2C_M_RD) ret = i2c_dw_read(dw, &msgs[i]); else ret = i2c_dw_write(dw, &msgs[i]); if (ret < 0) break; ret = i2c_dw_finish_xfer(dw); if (ret < 0) break; } if (ret == -EIO) { /* * If we got -EIO it means that transfer was for some * reason aborted, so we should figure out the reason * and take steps to clear that condition */ const uint32_t ic_tx_abrt_source = readl(dw->base + DW_IC_TX_ABRT_SOURCE); dev_dbg(&dw->adapter.dev, "<%s> ic_tx_abrt_source: 0x%04x\n", __func__, ic_tx_abrt_source); readl(dw->base + DW_IC_CLR_TX_ABRT); return ret; } if (ret < 0) { i2c_dw_reset(dw); return ret; } return num; } static int i2c_dw_probe(struct device_d *pdev) { struct resource *iores; struct dw_i2c_dev *dw; struct i2c_platform_data *pdata; int ret, bitrate; uint32_t ic_con, ic_comp_type_value; pdata = pdev->platform_data; dw = xzalloc(sizeof(*dw)); if (IS_ENABLED(CONFIG_COMMON_CLK)) { dw->clk = clk_get(pdev, NULL); if (IS_ERR(dw->clk)) { ret = PTR_ERR(dw->clk); goto fail; } } dw->adapter.master_xfer = i2c_dw_xfer; dw->adapter.nr = pdev->id; dw->adapter.dev.parent = pdev; dw->adapter.dev.device_node = pdev->device_node; iores = dev_request_mem_resource(pdev, 0); if (IS_ERR(iores)) { ret = PTR_ERR(iores); goto fail; } dw->base = IOMEM(iores->start); ic_comp_type_value = readl(dw->base + DW_IC_COMP_TYPE); if (ic_comp_type_value != DW_IC_COMP_TYPE_VALUE) { dev_err(pdev, "unknown DesignWare IP block 0x%08x", ic_comp_type_value); ret = -ENODEV; goto fail; } i2c_dw_enable(dw, false); if (IS_ENABLED(CONFIG_COMMON_CLK)) i2c_dw_setup_timings(dw); bitrate = (pdata && pdata->bitrate) ? pdata->bitrate : DW_I2C_BIT_RATE; /* * We have to clear 'ic_10bitaddr_master' in 'ic_tar' * register, otherwise 'ic_10bitaddr_master' in 'ic_con' * wouldn't clear. We don't care about preserving the contents * of that register so we set it to zero. */ writel(0, dw->base + DW_IC_TAR); switch (bitrate) { case 400000: ic_con = DW_IC_CON_SPEED_FAST; break; default: dev_warn(pdev, "requested bitrate (%d) is not supported." " Falling back to 100kHz", bitrate); case 100000: /* FALLTHROUGH */ ic_con = DW_IC_CON_SPEED_STD; break; } ic_con |= DW_IC_CON_MASTER | DW_IC_CON_SLAVE_DISABLE; writel(ic_con, dw->base + DW_IC_CON); /* * Since we will be working in polling mode set both * thresholds to their minimum */ writel(0, dw->base + DW_IC_RX_TL); writel(0, dw->base + DW_IC_TX_TL); /* Disable and clear all interrrupts */ writel(0, dw->base + DW_IC_INTR_MASK); readl(dw->base + DW_IC_CLR_INTR); i2c_dw_enable(dw, true); ret = i2c_add_numbered_adapter(&dw->adapter); fail: if (ret < 0) kfree(dw); return ret; } static __maybe_unused struct of_device_id i2c_dw_dt_ids[] = { { .compatible = "snps,designware-i2c", }, { /* sentinel */ } }; static struct driver_d i2c_dw_driver = { .probe = i2c_dw_probe, .name = "i2c-designware", .of_compatible = DRV_OF_COMPAT(i2c_dw_dt_ids), }; coredevice_platform_driver(i2c_dw_driver);
Java
/*---------------------------------------------------------------------------*\ ## #### ###### | ## ## ## | Copyright: ICE Stroemungsfoschungs GmbH ## ## #### | ## ## ## | http://www.ice-sf.at ## #### ###### | ------------------------------------------------------------------------------- ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright (C) 1991-2008 OpenCFD Ltd. \\/ M anipulation | ------------------------------------------------------------------------------- License This file is based on OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA Class Foam::fvcSpreadFunctionPlugin Description SourceFiles fvcSpreadPluginfunction.C Contributors/Copyright: 2015-2017 Bernhard F.W. Gschaider <bgschaid@hfd-research.com> SWAK Revision: $Id$ \*---------------------------------------------------------------------------*/ #ifndef fvcSpreadPluginfunction_H #define fvcSpreadPluginfunction_H #include "FieldValuePluginFunction.H" // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // namespace Foam { /*---------------------------------------------------------------------------*\ Class fvcSpreadPluginFunction Declaration \*---------------------------------------------------------------------------*/ class fvcSpreadPluginFunction : public FieldValuePluginFunction { //- Disallow default bitwise assignment void operator=(const fvcSpreadPluginFunction &); fvcSpreadPluginFunction(const fvcSpreadPluginFunction &); //- number of layers label nLayers_; //- difference of alpha scalar alphaDiff_; //- maximum of alpha scalar alphaMax_; //- minimum of alpha scalar alphaMin_; //- the field to be spreaded autoPtr<volScalarField> field_; //- the field to be spreaded with autoPtr<volScalarField> alpha_; public: fvcSpreadPluginFunction( const FieldValueExpressionDriver &parentDriver, const word &name ); virtual ~fvcSpreadPluginFunction() {} TypeName("fvcSpreadPluginFunction"); void doEvaluation(); void setArgument( label index, const string &content, const CommonValueExpressionDriver &driver ); void setArgument(label index,const scalar &); void setArgument(label index,const label &); }; // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // } // End namespace Foam // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // #endif // ************************************************************************* //
Java
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; using Shoot__n_Loot.Scenes; namespace Shoot__n_Loot { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Microsoft.Xna.Framework.Game { public static Point ScreenSize { get { return new Point(1200, 750); } } public static Random random; public static bool exit; GraphicsDeviceManager graphics; SpriteBatch spriteBatch; public Game1() { Window.Title = "Escape from Zombie Island"; graphics = new GraphicsDeviceManager(this); graphics.PreferredBackBufferWidth = ScreenSize.X; graphics.PreferredBackBufferHeight = ScreenSize.Y; Content.RootDirectory = "Content"; IsMouseVisible = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { Input.Initialize(); Camera.FollowSpeed = .3f; Camera.Scale = 1; Camera.Origin = new Vector2(GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height) / (2 * Camera.Scale); random = new Random(); Music music = new Music(Content.Load<Song>("track1")); music.Initialize(); base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); TextureManager.Load(Content); SoundManager.Load(Content); SceneManager.LoadAll(); } /// <summary> /// UnloadContent will be called once per game and is the place to unload /// all content. /// </summary> protected override void UnloadContent() { } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { if (exit) Exit(); Input.Update(); SceneManager.CurrentScene.Update(); base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { GraphicsDevice.Clear(new Color(0, 3, 73)); spriteBatch.Begin(SpriteSortMode.BackToFront, null, null, null, null, null, Camera.Transform); SceneManager.CurrentScene.Draw(spriteBatch); spriteBatch.End(); base.Draw(gameTime); } } }
Java
/* Name: usbdrv.c * Project: AVR USB driver * Author: Christian Starkjohann * Creation Date: 2004-12-29 * Tabsize: 4 * Copyright: (c) 2005 by OBJECTIVE DEVELOPMENT Software GmbH * License: GNU GPL v2 (see License.txt) or proprietary (CommercialLicense.txt) * This Revision: $Id: usbdrv.c,v 1.1.1.1 2008-01-22 20:28:25 raph Exp $ */ #include "iarcompat.h" #ifndef __IAR_SYSTEMS_ICC__ # include <avr/io.h> # include <avr/pgmspace.h> #endif #include "usbdrv.h" #include "oddebug.h" /* General Description: This module implements the C-part of the USB driver. See usbdrv.h for a documentation of the entire driver. */ #ifndef IAR_SECTION #define IAR_SECTION(arg) #define __no_init #endif /* The macro IAR_SECTION is a hack to allow IAR-cc compatibility. On gcc, it * is defined to nothing. __no_init is required on IAR. */ /* ------------------------------------------------------------------------- */ /* raw USB registers / interface to assembler code: */ uchar usbRxBuf[2*USB_BUFSIZE]; /* raw RX buffer: PID, 8 bytes data, 2 bytes CRC */ uchar usbInputBufOffset; /* offset in usbRxBuf used for low level receiving */ uchar usbDeviceAddr; /* assigned during enumeration, defaults to 0 */ uchar usbNewDeviceAddr; /* device ID which should be set after status phase */ uchar usbConfiguration; /* currently selected configuration. Administered by driver, but not used */ volatile schar usbRxLen; /* = 0; number of bytes in usbRxBuf; 0 means free, -1 for flow control */ uchar usbCurrentTok; /* last token received, if more than 1 rx endpoint: MSb=endpoint */ uchar usbRxToken; /* token for data we received; if more than 1 rx endpoint: MSb=endpoint */ uchar usbMsgLen = 0xff; /* remaining number of bytes, no msg to send if -1 (see usbMsgPtr) */ volatile uchar usbTxLen = USBPID_NAK; /* number of bytes to transmit with next IN token or handshake token */ uchar usbTxBuf[USB_BUFSIZE];/* data to transmit with next IN, free if usbTxLen contains handshake token */ # if USB_COUNT_SOF volatile uchar usbSofCount; /* incremented by assembler module every SOF */ # endif #if USB_CFG_HAVE_INTRIN_ENDPOINT volatile uchar usbTxLen1 = USBPID_NAK; /* TX count for endpoint 1 */ uchar usbTxBuf1[USB_BUFSIZE]; /* TX data for endpoint 1 */ #if USB_CFG_HAVE_INTRIN_ENDPOINT3 volatile uchar usbTxLen3 = USBPID_NAK; /* TX count for endpoint 3 */ uchar usbTxBuf3[USB_BUFSIZE]; /* TX data for endpoint 3 */ #endif #endif /* USB status registers / not shared with asm code */ uchar *usbMsgPtr; /* data to transmit next -- ROM or RAM address */ static uchar usbMsgFlags; /* flag values see below */ #define USB_FLG_TX_PACKET (1<<0) /* Leave free 6 bits after TX_PACKET. This way we can increment usbMsgFlags to toggle TX_PACKET */ #define USB_FLG_MSGPTR_IS_ROM (1<<6) #define USB_FLG_USE_DEFAULT_RW (1<<7) /* optimizing hints: - do not post/pre inc/dec integer values in operations - assign value of PRG_RDB() to register variables and don't use side effects in arg - use narrow scope for variables which should be in X/Y/Z register - assign char sized expressions to variables to force 8 bit arithmetics */ /* ------------------------------------------------------------------------- */ #if USB_CFG_DESCR_PROPS_STRINGS == 0 #if USB_CFG_DESCR_PROPS_STRING_0 == 0 #undef USB_CFG_DESCR_PROPS_STRING_0 #define USB_CFG_DESCR_PROPS_STRING_0 sizeof(usbDescriptorString0) PROGMEM const char usbDescriptorString0[] = { /* language descriptor */ 4, /* sizeof(usbDescriptorString0): length of descriptor in bytes */ 3, /* descriptor type */ 0x09, 0x04, /* language index (0x0409 = US-English) */ }; #endif #if USB_CFG_DESCR_PROPS_STRING_VENDOR == 0 && USB_CFG_VENDOR_NAME_LEN #undef USB_CFG_DESCR_PROPS_STRING_VENDOR #define USB_CFG_DESCR_PROPS_STRING_VENDOR sizeof(usbDescriptorStringVendor) PROGMEM const int usbDescriptorStringVendor[] = { USB_STRING_DESCRIPTOR_HEADER(USB_CFG_VENDOR_NAME_LEN), USB_CFG_VENDOR_NAME }; #endif #if USB_CFG_DESCR_PROPS_STRING_PRODUCT == 0 && USB_CFG_DEVICE_NAME_LEN #undef USB_CFG_DESCR_PROPS_STRING_PRODUCT #define USB_CFG_DESCR_PROPS_STRING_PRODUCT sizeof(usbDescriptorStringDevice) PROGMEM const int usbDescriptorStringDevice[] = { USB_STRING_DESCRIPTOR_HEADER(USB_CFG_DEVICE_NAME_LEN), USB_CFG_DEVICE_NAME }; #endif #if USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER == 0 && USB_CFG_SERIAL_NUMBER_LEN #undef USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER #define USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER sizeof(usbDescriptorStringSerialNumber) PROGMEM int usbDescriptorStringSerialNumber[] = { USB_STRING_DESCRIPTOR_HEADER(USB_CFG_SERIAL_NUMBER_LEN), USB_CFG_SERIAL_NUMBER }; #endif #endif /* USB_CFG_DESCR_PROPS_STRINGS == 0 */ #if USB_CFG_DESCR_PROPS_DEVICE == 0 #undef USB_CFG_DESCR_PROPS_DEVICE #define USB_CFG_DESCR_PROPS_DEVICE sizeof(usbDescriptorDevice) PROGMEM char usbDescriptorDevice[] = { /* USB device descriptor */ 18, /* sizeof(usbDescriptorDevice): length of descriptor in bytes */ USBDESCR_DEVICE, /* descriptor type */ 0x10, 0x01, /* USB version supported */ USB_CFG_DEVICE_CLASS, USB_CFG_DEVICE_SUBCLASS, 0, /* protocol */ 8, /* max packet size */ USB_CFG_VENDOR_ID, /* 2 bytes */ USB_CFG_DEVICE_ID, /* 2 bytes */ USB_CFG_DEVICE_VERSION, /* 2 bytes */ USB_CFG_DESCR_PROPS_STRING_VENDOR != 0 ? 1 : 0, /* manufacturer string index */ USB_CFG_DESCR_PROPS_STRING_PRODUCT != 0 ? 2 : 0, /* product string index */ USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER != 0 ? 3 : 0, /* serial number string index */ 1, /* number of configurations */ }; #endif #if USB_CFG_DESCR_PROPS_HID_REPORT != 0 && USB_CFG_DESCR_PROPS_HID == 0 #undef USB_CFG_DESCR_PROPS_HID #define USB_CFG_DESCR_PROPS_HID 9 /* length of HID descriptor in config descriptor below */ #endif #if USB_CFG_DESCR_PROPS_CONFIGURATION == 0 #undef USB_CFG_DESCR_PROPS_CONFIGURATION #define USB_CFG_DESCR_PROPS_CONFIGURATION sizeof(usbDescriptorConfiguration) PROGMEM char usbDescriptorConfiguration[] = { /* USB configuration descriptor */ 9, /* sizeof(usbDescriptorConfiguration): length of descriptor in bytes */ USBDESCR_CONFIG, /* descriptor type */ 18 + 7 * USB_CFG_HAVE_INTRIN_ENDPOINT + (USB_CFG_DESCR_PROPS_HID & 0xff), 0, /* total length of data returned (including inlined descriptors) */ 1, /* number of interfaces in this configuration */ 1, /* index of this configuration */ 0, /* configuration name string index */ #if USB_CFG_IS_SELF_POWERED USBATTR_SELFPOWER, /* attributes */ #else USBATTR_BUSPOWER, /* attributes */ #endif USB_CFG_MAX_BUS_POWER/2, /* max USB current in 2mA units */ /* interface descriptor follows inline: */ 9, /* sizeof(usbDescrInterface): length of descriptor in bytes */ USBDESCR_INTERFACE, /* descriptor type */ 0, /* index of this interface */ 0, /* alternate setting for this interface */ USB_CFG_HAVE_INTRIN_ENDPOINT, /* endpoints excl 0: number of endpoint descriptors to follow */ USB_CFG_INTERFACE_CLASS, USB_CFG_INTERFACE_SUBCLASS, USB_CFG_INTERFACE_PROTOCOL, 0, /* string index for interface */ #if (USB_CFG_DESCR_PROPS_HID & 0xff) /* HID descriptor */ 9, /* sizeof(usbDescrHID): length of descriptor in bytes */ USBDESCR_HID, /* descriptor type: HID */ 0x01, 0x01, /* BCD representation of HID version */ 0x00, /* target country code */ 0x01, /* number of HID Report (or other HID class) Descriptor infos to follow */ 0x22, /* descriptor type: report */ USB_CFG_HID_REPORT_DESCRIPTOR_LENGTH, 0, /* total length of report descriptor */ #endif #if USB_CFG_HAVE_INTRIN_ENDPOINT /* endpoint descriptor for endpoint 1 */ 7, /* sizeof(usbDescrEndpoint) */ USBDESCR_ENDPOINT, /* descriptor type = endpoint */ 0x81, /* IN endpoint number 1 */ 0x03, /* attrib: Interrupt endpoint */ 8, 0, /* maximum packet size */ USB_CFG_INTR_POLL_INTERVAL, /* in ms */ #endif }; #endif /* We don't use prog_int or prog_int16_t for compatibility with various libc * versions. Here's an other compatibility hack: */ #ifndef PRG_RDB #define PRG_RDB(addr) pgm_read_byte(addr) #endif typedef union{ unsigned word; uchar *ptr; uchar bytes[2]; }converter_t; /* We use this union to do type conversions. This is better optimized than * type casts in gcc 3.4.3 and much better than using bit shifts to build * ints from chars. Byte ordering is not a problem on an 8 bit platform. */ /* ------------------------------------------------------------------------- */ #if USB_CFG_HAVE_INTRIN_ENDPOINT USB_PUBLIC void usbSetInterrupt(uchar *data, uchar len) { uchar *p, i; #if USB_CFG_IMPLEMENT_HALT if(usbTxLen1 == USBPID_STALL) return; #endif #if 0 /* No runtime checks! Caller is responsible for valid data! */ if(len > 8) /* interrupt transfers are limited to 8 bytes */ len = 8; #endif if(usbTxLen1 & 0x10){ /* packet buffer was empty */ usbTxBuf1[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */ }else{ usbTxLen1 = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */ } p = usbTxBuf1 + 1; for(i=len;i--;) *p++ = *data++; usbCrc16Append(&usbTxBuf1[1], len); usbTxLen1 = len + 4; /* len must be given including sync byte */ DBG2(0x21, usbTxBuf1, len + 3); } #endif #if USB_CFG_HAVE_INTRIN_ENDPOINT3 USB_PUBLIC void usbSetInterrupt3(uchar *data, uchar len) { uchar *p, i; if(usbTxLen3 & 0x10){ /* packet buffer was empty */ usbTxBuf3[0] ^= USBPID_DATA0 ^ USBPID_DATA1; /* toggle token */ }else{ usbTxLen3 = USBPID_NAK; /* avoid sending outdated (overwritten) interrupt data */ } p = usbTxBuf3 + 1; for(i=len;i--;) *p++ = *data++; usbCrc16Append(&usbTxBuf3[1], len); usbTxLen3 = len + 4; /* len must be given including sync byte */ DBG2(0x23, usbTxBuf3, len + 3); } #endif static uchar usbRead(uchar *data, uchar len) { #if USB_CFG_IMPLEMENT_FN_READ if(usbMsgFlags & USB_FLG_USE_DEFAULT_RW){ #endif uchar i = len, *r = usbMsgPtr; if(usbMsgFlags & USB_FLG_MSGPTR_IS_ROM){ /* ROM data */ while(i--){ uchar c = PRG_RDB(r); /* assign to char size variable to enforce byte ops */ *data++ = c; r++; } }else{ /* RAM data */ while(i--) *data++ = *r++; } usbMsgPtr = r; return len; #if USB_CFG_IMPLEMENT_FN_READ }else{ if(len != 0) /* don't bother app with 0 sized reads */ return usbFunctionRead(data, len); return 0; } #endif } #define GET_DESCRIPTOR(cfgProp, staticName) \ if(cfgProp){ \ if((cfgProp) & USB_PROP_IS_RAM) \ flags &= ~USB_FLG_MSGPTR_IS_ROM; \ if((cfgProp) & USB_PROP_IS_DYNAMIC){ \ replyLen = usbFunctionDescriptor(rq); \ }else{ \ replyData = (uchar *)(staticName); \ SET_REPLY_LEN((cfgProp) & 0xff); \ } \ } /* We use if() instead of #if in the macro above because #if can't be used * in macros and the compiler optimizes constant conditions anyway. */ /* Don't make this function static to avoid inlining. * The entire function would become too large and exceed the range of * relative jumps. * 2006-02-25: Either gcc 3.4.3 is better than the gcc used when the comment * above was written, or other parts of the code have changed. We now get * better results with an inlined function. Test condition: PowerSwitch code. */ static void usbProcessRx(uchar *data, uchar len) { usbRequest_t *rq = (void *)data; uchar replyLen = 0, flags = USB_FLG_USE_DEFAULT_RW; /* We use if() cascades because the compare is done byte-wise while switch() * is int-based. The if() cascades are therefore more efficient. */ /* usbRxToken can be: * 0x2d 00101101 (USBPID_SETUP for endpoint 0) * 0xe1 11100001 (USBPID_OUT for endpoint 0) * 0xff 11111111 (USBPID_OUT for endpoint 1) */ DBG2(0x10 + ((usbRxToken >> 1) & 3), data, len); /* SETUP0=12; OUT0=10; OUT1=13 */ #ifdef USB_RX_USER_HOOK USB_RX_USER_HOOK(data, len) #endif #if USB_CFG_IMPLEMENT_FN_WRITEOUT if(usbRxToken == 0xff){ usbFunctionWriteOut(data, len); return; /* no reply expected, hence no usbMsgPtr, usbMsgFlags, usbMsgLen set */ } #endif if(usbRxToken == (uchar)USBPID_SETUP){ usbTxLen = USBPID_NAK; /* abort pending transmit */ if(len == 8){ /* Setup size must be always 8 bytes. Ignore otherwise. */ uchar type = rq->bmRequestType & USBRQ_TYPE_MASK; if(type == USBRQ_TYPE_STANDARD){ #define SET_REPLY_LEN(len) replyLen = (len); usbMsgPtr = replyData /* This macro ensures that replyLen and usbMsgPtr are always set in the same way. * That allows optimization of common code in if() branches */ uchar *replyData = usbTxBuf + 9; /* there is 3 bytes free space at the end of the buffer */ replyData[0] = 0; /* common to USBRQ_GET_STATUS and USBRQ_GET_INTERFACE */ if(rq->bRequest == USBRQ_GET_STATUS){ /* 0 */ uchar __attribute__((__unused__)) recipient = rq->bmRequestType & USBRQ_RCPT_MASK; /* assign arith ops to variables to enforce byte size */ #if USB_CFG_IS_SELF_POWERED if(recipient == USBRQ_RCPT_DEVICE) replyData[0] = USB_CFG_IS_SELF_POWERED; #endif #if USB_CFG_HAVE_INTRIN_ENDPOINT && USB_CFG_IMPLEMENT_HALT if(recipient == USBRQ_RCPT_ENDPOINT && rq->wIndex.bytes[0] == 0x81) /* request status for endpoint 1 */ replyData[0] = usbTxLen1 == USBPID_STALL; #endif replyData[1] = 0; SET_REPLY_LEN(2); }else if(rq->bRequest == USBRQ_SET_ADDRESS){ /* 5 */ usbNewDeviceAddr = rq->wValue.bytes[0]; }else if(rq->bRequest == USBRQ_GET_DESCRIPTOR){ /* 6 */ flags = USB_FLG_MSGPTR_IS_ROM | USB_FLG_USE_DEFAULT_RW; if(rq->wValue.bytes[1] == USBDESCR_DEVICE){ /* 1 */ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_DEVICE, usbDescriptorDevice) }else if(rq->wValue.bytes[1] == USBDESCR_CONFIG){ /* 2 */ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_CONFIGURATION, usbDescriptorConfiguration) }else if(rq->wValue.bytes[1] == USBDESCR_STRING){ /* 3 */ #if USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC if(USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_RAM) flags &= ~USB_FLG_MSGPTR_IS_ROM; replyLen = usbFunctionDescriptor(rq); #else /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */ if(rq->wValue.bytes[0] == 0){ /* descriptor index */ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_0, usbDescriptorString0) }else if(rq->wValue.bytes[0] == 1){ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_VENDOR, usbDescriptorStringVendor) }else if(rq->wValue.bytes[0] == 2){ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_PRODUCT, usbDescriptorStringDevice) }else if(rq->wValue.bytes[0] == 3){ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_STRING_SERIAL_NUMBER, usbDescriptorStringSerialNumber) }else if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){ replyLen = usbFunctionDescriptor(rq); } #endif /* USB_CFG_DESCR_PROPS_STRINGS & USB_PROP_IS_DYNAMIC */ #if USB_CFG_DESCR_PROPS_HID_REPORT /* only support HID descriptors if enabled */ }else if(rq->wValue.bytes[1] == USBDESCR_HID){ /* 0x21 */ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID, usbDescriptorConfiguration + 18) }else if(rq->wValue.bytes[1] == USBDESCR_HID_REPORT){ /* 0x22 */ GET_DESCRIPTOR(USB_CFG_DESCR_PROPS_HID_REPORT, usbDescriptorHidReport) #endif /* USB_CFG_DESCR_PROPS_HID_REPORT */ }else if(USB_CFG_DESCR_PROPS_UNKNOWN & USB_PROP_IS_DYNAMIC){ replyLen = usbFunctionDescriptor(rq); } }else if(rq->bRequest == USBRQ_GET_CONFIGURATION){ /* 8 */ replyData = &usbConfiguration; /* send current configuration value */ SET_REPLY_LEN(1); }else if(rq->bRequest == USBRQ_SET_CONFIGURATION){ /* 9 */ usbConfiguration = rq->wValue.bytes[0]; #if USB_CFG_IMPLEMENT_HALT usbTxLen1 = USBPID_NAK; #endif }else if(rq->bRequest == USBRQ_GET_INTERFACE){ /* 10 */ SET_REPLY_LEN(1); #if USB_CFG_HAVE_INTRIN_ENDPOINT }else if(rq->bRequest == USBRQ_SET_INTERFACE){ /* 11 */ USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */ # if USB_CFG_HAVE_INTRIN_ENDPOINT3 USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */ # endif # if USB_CFG_IMPLEMENT_HALT usbTxLen1 = USBPID_NAK; }else if(rq->bRequest == USBRQ_CLEAR_FEATURE || rq->bRequest == USBRQ_SET_FEATURE){ /* 1|3 */ if(rq->wValue.bytes[0] == 0 && rq->wIndex.bytes[0] == 0x81){ /* feature 0 == HALT for endpoint == 1 */ usbTxLen1 = rq->bRequest == USBRQ_CLEAR_FEATURE ? USBPID_NAK : USBPID_STALL; USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */ # if USB_CFG_HAVE_INTRIN_ENDPOINT3 USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */ # endif } # endif #endif }else{ /* the following requests can be ignored, send default reply */ /* 1: CLEAR_FEATURE, 3: SET_FEATURE, 7: SET_DESCRIPTOR */ /* 12: SYNCH_FRAME */ } #undef SET_REPLY_LEN }else{ /* not a standard request -- must be vendor or class request */ replyLen = usbFunctionSetup(data); } #if USB_CFG_IMPLEMENT_FN_READ || USB_CFG_IMPLEMENT_FN_WRITE if(replyLen == 0xff){ /* use user-supplied read/write function */ if((rq->bmRequestType & USBRQ_DIR_MASK) == USBRQ_DIR_DEVICE_TO_HOST){ replyLen = rq->wLength.bytes[0]; /* IN transfers only */ } flags &= ~USB_FLG_USE_DEFAULT_RW; /* we have no valid msg, use user supplied read/write functions */ }else /* The 'else' prevents that we limit a replyLen of 0xff to the maximum transfer len. */ #endif if(!rq->wLength.bytes[1] && replyLen > rq->wLength.bytes[0]) /* limit length to max */ replyLen = rq->wLength.bytes[0]; } /* make sure that data packets which are sent as ACK to an OUT transfer are always zero sized */ }else{ /* DATA packet from out request */ #if USB_CFG_IMPLEMENT_FN_WRITE if(!(usbMsgFlags & USB_FLG_USE_DEFAULT_RW)){ uchar rval = usbFunctionWrite(data, len); replyLen = 0xff; if(rval == 0xff){ /* an error occurred */ usbMsgLen = 0xff; /* cancel potentially pending data packet for ACK */ usbTxLen = USBPID_STALL; }else if(rval != 0){ /* This was the final package */ replyLen = 0; /* answer with a zero-sized data packet */ } flags = 0; /* start with a DATA1 package, stay with user supplied write() function */ } #endif } usbMsgFlags = flags; usbMsgLen = replyLen; } /* ------------------------------------------------------------------------- */ static void usbBuildTxBlock(void) { uchar wantLen, len, txLen, token; wantLen = usbMsgLen; if(wantLen > 8) wantLen = 8; usbMsgLen -= wantLen; token = USBPID_DATA1; if(usbMsgFlags & USB_FLG_TX_PACKET) token = USBPID_DATA0; usbMsgFlags++; len = usbRead(usbTxBuf + 1, wantLen); if(len <= 8){ /* valid data packet */ usbCrc16Append(&usbTxBuf[1], len); txLen = len + 4; /* length including sync byte */ if(len < 8) /* a partial package identifies end of message */ usbMsgLen = 0xff; }else{ txLen = USBPID_STALL; /* stall the endpoint */ usbMsgLen = 0xff; } usbTxBuf[0] = token; usbTxLen = txLen; DBG2(0x20, usbTxBuf, txLen-1); } static inline uchar isNotSE0(void) { uchar rval; /* We want to do * return (USBIN & USBMASK); * here, but the compiler does int-expansion acrobatics. * We can avoid this by assigning to a char-sized variable. */ rval = USBIN & USBMASK; return rval; } /* ------------------------------------------------------------------------- */ USB_PUBLIC void usbPoll(void) { schar len; uchar i; if((len = usbRxLen) > 0){ /* We could check CRC16 here -- but ACK has already been sent anyway. If you * need data integrity checks with this driver, check the CRC in your app * code and report errors back to the host. Since the ACK was already sent, * retries must be handled on application level. * unsigned crc = usbCrc16(buffer + 1, usbRxLen - 3); */ usbProcessRx(usbRxBuf + USB_BUFSIZE + 1 - usbInputBufOffset, len - 3); #if USB_CFG_HAVE_FLOWCONTROL if(usbRxLen > 0) /* only mark as available if not inactivated */ usbRxLen = 0; #else usbRxLen = 0; /* mark rx buffer as available */ #endif } if(usbTxLen & 0x10){ /* transmit system idle */ if(usbMsgLen != 0xff){ /* transmit data pending? */ usbBuildTxBlock(); } } for(i = 10; i > 0; i--){ if(isNotSE0()) break; } if(i == 0){ /* RESET condition, called multiple times during reset */ usbNewDeviceAddr = 0; usbDeviceAddr = 0; #if USB_CFG_IMPLEMENT_HALT usbTxLen1 = USBPID_NAK; #if USB_CFG_HAVE_INTRIN_ENDPOINT3 usbTxLen3 = USBPID_NAK; #endif #endif DBG1(0xff, 0, 0); } } /* ------------------------------------------------------------------------- */ USB_PUBLIC void usbInit(void) { #if USB_INTR_CFG_SET != 0 USB_INTR_CFG |= USB_INTR_CFG_SET; #endif #if USB_INTR_CFG_CLR != 0 USB_INTR_CFG &= ~(USB_INTR_CFG_CLR); #endif USB_INTR_ENABLE |= (1 << USB_INTR_ENABLE_BIT); #if USB_CFG_HAVE_INTRIN_ENDPOINT USB_SET_DATATOKEN1(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */ # if USB_CFG_HAVE_INTRIN_ENDPOINT3 USB_SET_DATATOKEN3(USB_INITIAL_DATATOKEN); /* reset data toggling for interrupt endpoint */ # endif #endif } /* ------------------------------------------------------------------------- */
Java
package com.citypark.api.task; import com.citypark.api.parser.CityParkStartPaymentParser; import android.content.Context; import android.os.AsyncTask; import android.text.format.Time; public class StopPaymentTask extends AsyncTask<Void, Void, Boolean> { private Context context; private String sessionId; private String paymentProviderName; private double latitude; private double longitude; private String operationStatus; public StopPaymentTask(Context context, String sessionId, String paymentProviderName, double latitude, double longitude, String operationStatus) { super(); this.context = context; this.sessionId = sessionId; this.paymentProviderName = paymentProviderName; this.latitude = latitude; this.longitude = longitude; this.operationStatus = operationStatus; } @Override protected Boolean doInBackground(Void... params) { //update citypark through API on success or failure CityParkStartPaymentParser parser = new CityParkStartPaymentParser(context, sessionId, paymentProviderName, latitude, longitude, operationStatus); parser.parse(); return true; } }
Java
/* ScummVM - Graphic Adventure Engine * * ScummVM is the legal property of its developers, whose names * are too numerous to list here. Please refer to the COPYRIGHT * file distributed with this source distribution. * * 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 "graphics/fontman.h" #include "backends/platform/tizen/form.h" #include "backends/platform/tizen/system.h" #include "backends/platform/tizen/graphics.h" // // TizenGraphicsManager // TizenGraphicsManager::TizenGraphicsManager(TizenAppForm *appForm) : _appForm(appForm), _eglDisplay(EGL_DEFAULT_DISPLAY), _eglSurface(EGL_NO_SURFACE), _eglConfig(NULL), _eglContext(EGL_NO_CONTEXT), _initState(true) { assert(appForm != NULL); _videoMode.fullscreen = true; } TizenGraphicsManager::~TizenGraphicsManager() { logEntered(); if (_eglDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(_eglDisplay, NULL, NULL, NULL); if (_eglContext != EGL_NO_CONTEXT) { eglDestroyContext(_eglDisplay, _eglContext); } } } const Graphics::Font *TizenGraphicsManager::getFontOSD() { return FontMan.getFontByUsage(Graphics::FontManager::kBigGUIFont); } bool TizenGraphicsManager::moveMouse(int16 &x, int16 &y) { int16 currentX = _cursorState.x; int16 currentY = _cursorState.y; // save the current hardware coordinates _cursorState.x = x; _cursorState.y = y; // return x/y as game coordinates adjustMousePosition(x, y); // convert current x/y to game coordinates adjustMousePosition(currentX, currentY); // return whether game coordinates have changed return (currentX != x || currentY != y); } Common::List<Graphics::PixelFormat> TizenGraphicsManager::getSupportedFormats() const { logEntered(); Common::List<Graphics::PixelFormat> res; res.push_back(Graphics::PixelFormat(2, 4, 4, 4, 4, 12, 8, 4, 0)); res.push_back(Graphics::PixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0)); res.push_back(Graphics::PixelFormat(2, 5, 5, 5, 1, 11, 6, 1, 0)); res.push_back(Graphics::PixelFormat::createFormatCLUT8()); return res; } bool TizenGraphicsManager::hasFeature(OSystem::Feature f) { bool result = (f == OSystem::kFeatureFullscreenMode || f == OSystem::kFeatureVirtualKeyboard || OpenGLGraphicsManager::hasFeature(f)); return result; } void TizenGraphicsManager::setFeatureState(OSystem::Feature f, bool enable) { if (f == OSystem::kFeatureVirtualKeyboard && enable) { _appForm->showKeypad(); } else { OpenGLGraphicsManager::setFeatureState(f, enable); } } void TizenGraphicsManager::setReady() { _initState = false; } void TizenGraphicsManager::updateScreen() { if (_transactionMode == kTransactionNone) { internUpdateScreen(); } } bool TizenGraphicsManager::loadEgl() { logEntered(); EGLint numConfigs = 1; EGLint eglConfigList[] = { EGL_RED_SIZE, 5, EGL_GREEN_SIZE, 6, EGL_BLUE_SIZE, 5, EGL_ALPHA_SIZE, 0, EGL_DEPTH_SIZE, 8, EGL_SURFACE_TYPE, EGL_WINDOW_BIT, EGL_RENDERABLE_TYPE, EGL_OPENGL_ES_BIT, EGL_NONE }; EGLint eglContextList[] = { EGL_CONTEXT_CLIENT_VERSION, 1, EGL_NONE }; eglBindAPI(EGL_OPENGL_ES_API); if (_eglDisplay) { unloadGFXMode(); } _eglDisplay = eglGetDisplay((EGLNativeDisplayType) EGL_DEFAULT_DISPLAY); if (EGL_NO_DISPLAY == _eglDisplay) { systemError("eglGetDisplay() failed"); return false; } if (EGL_FALSE == eglInitialize(_eglDisplay, NULL, NULL) || EGL_SUCCESS != eglGetError()) { systemError("eglInitialize() failed"); return false; } if (EGL_FALSE == eglChooseConfig(_eglDisplay, eglConfigList, &_eglConfig, 1, &numConfigs) || EGL_SUCCESS != eglGetError()) { systemError("eglChooseConfig() failed"); return false; } if (!numConfigs) { systemError("eglChooseConfig() failed. Matching config does not exist \n"); return false; } _eglSurface = eglCreateWindowSurface(_eglDisplay, _eglConfig, (EGLNativeWindowType)_appForm, NULL); if (EGL_NO_SURFACE == _eglSurface || EGL_SUCCESS != eglGetError()) { systemError("eglCreateWindowSurface() failed. EGL_NO_SURFACE"); return false; } _eglContext = eglCreateContext(_eglDisplay, _eglConfig, EGL_NO_CONTEXT, eglContextList); if (EGL_NO_CONTEXT == _eglContext || EGL_SUCCESS != eglGetError()) { systemError("eglCreateContext() failed"); return false; } if (false == eglMakeCurrent(_eglDisplay, _eglSurface, _eglSurface, _eglContext) || EGL_SUCCESS != eglGetError()) { systemError("eglMakeCurrent() failed"); return false; } logLeaving(); return true; } bool TizenGraphicsManager::loadGFXMode() { logEntered(); if (!loadEgl()) { unloadGFXMode(); return false; } int x, y, width, height; _appForm->GetBounds(x, y, width, height); _videoMode.overlayWidth = _videoMode.hardwareWidth = width; _videoMode.overlayHeight = _videoMode.hardwareHeight = height; _videoMode.scaleFactor = 4; // for proportional sized cursor in the launcher AppLog("screen size: %dx%d", _videoMode.hardwareWidth, _videoMode.hardwareHeight); return OpenGLGraphicsManager::loadGFXMode(); } void TizenGraphicsManager::loadTextures() { logEntered(); OpenGLGraphicsManager::loadTextures(); } void TizenGraphicsManager::internUpdateScreen() { if (!_initState) { OpenGLGraphicsManager::internUpdateScreen(); eglSwapBuffers(_eglDisplay, _eglSurface); } } void TizenGraphicsManager::unloadGFXMode() { logEntered(); if (_eglDisplay != EGL_NO_DISPLAY) { eglMakeCurrent(_eglDisplay, NULL, NULL, NULL); if (_eglContext != EGL_NO_CONTEXT) { eglDestroyContext(_eglDisplay, _eglContext); _eglContext = EGL_NO_CONTEXT; } if (_eglSurface != EGL_NO_SURFACE) { eglDestroySurface(_eglDisplay, _eglSurface); _eglSurface = EGL_NO_SURFACE; } eglTerminate(_eglDisplay); _eglDisplay = EGL_NO_DISPLAY; } _eglConfig = NULL; OpenGLGraphicsManager::unloadGFXMode(); logLeaving(); }
Java
# -*- coding: utf-8 -*- """ *************************************************************************** SplitRGBBands.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * *************************************************************************** """ from processing.tools.system import * from processing.tools import dataobjects from processing.saga.SagaUtils import SagaUtils __author__ = 'Victor Olaya' __date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from PyQt4 import QtGui from processing.core.GeoAlgorithm import GeoAlgorithm from processing.parameters.ParameterRaster import ParameterRaster from processing.outputs.OutputRaster import OutputRaster import os class SplitRGBBands(GeoAlgorithm): INPUT = "INPUT" R = "R" G = "G" B = "B" def getIcon(self): return QtGui.QIcon(os.path.dirname(__file__) + "/../images/saga.png") def defineCharacteristics(self): self.name = "Split RGB bands" self.group = "Grid - Tools" self.addParameter(ParameterRaster(SplitRGBBands.INPUT, "Input layer", False)) self.addOutput(OutputRaster(SplitRGBBands.R, "Output R band layer")) self.addOutput(OutputRaster(SplitRGBBands.G, "Output G band layer")) self.addOutput(OutputRaster(SplitRGBBands.B, "Output B band layer")) def processAlgorithm(self, progress): #TODO:check correct num of bands input = self.getParameterValue(SplitRGBBands.INPUT) temp = getTempFilename(None).replace('.',''); basename = os.path.basename(temp) validChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" safeBasename = ''.join(c for c in basename if c in validChars) temp = os.path.join(os.path.dirname(temp), safeBasename) r = self.getOutputValue(SplitRGBBands.R) g = self.getOutputValue(SplitRGBBands.G) b = self.getOutputValue(SplitRGBBands.B) commands = [] if isWindows(): commands.append("io_gdal 0 -GRIDS \"" + temp + "\" -FILES \"" + input+"\"") commands.append("io_gdal 1 -GRIDS \"" + temp + "_0001.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + r + "\""); commands.append("io_gdal 1 -GRIDS \"" + temp + "_0002.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + g + "\""); commands.append("io_gdal 1 -GRIDS \"" + temp + "_0003.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + b + "\""); else: commands.append("libio_gdal 0 -GRIDS \"" + temp + "\" -FILES \"" + input + "\"") commands.append("libio_gdal 1 -GRIDS \"" + temp + "_0001.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + r + "\""); commands.append("libio_gdal 1 -GRIDS \"" + temp + "_0002.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + g + "\""); commands.append("libio_gdal 1 -GRIDS \"" + temp + "_0003.sgrd\" -FORMAT 1 -TYPE 0 -FILE \"" + b + "\""); SagaUtils.createSagaBatchJobFileFromSagaCommands(commands) SagaUtils.executeSaga(progress);
Java
# Copyright (C) 2016-2017 SUSE LLC # # 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/>. package OpenQA::WebAPI::Plugin::AMQP; use strict; use warnings; use parent 'Mojolicious::Plugin'; use Cpanel::JSON::XS; use Mojo::IOLoop; use OpenQA::Utils; use OpenQA::Jobs::Constants; use OpenQA::Schema::Result::Jobs; use Mojo::RabbitMQ::Client; my @job_events = qw(job_create job_delete job_cancel job_duplicate job_restart job_update_result job_done); my @comment_events = qw(comment_create comment_update comment_delete); sub new { my $class = shift; my $self = $class->SUPER::new(@_); $self->{app} = undef; $self->{config} = undef; $self->{client} = undef; $self->{channel} = undef; $self->{reconnecting} = 0; return $self; } sub register { my $self = shift; $self->{app} = shift; $self->{config} = $self->{app}->config; my $ioloop = Mojo::IOLoop->singleton; $ioloop->next_tick( sub { $self->connect(); # register for events for my $e (@job_events) { $ioloop->on("openqa_$e" => sub { shift; $self->on_job_event(@_) }); } for my $e (@comment_events) { $ioloop->on("openqa_$e" => sub { shift; $self->on_comment_event(@_) }); } }); } sub reconnect { my $self = shift; return if $self->{reconnecting}; $self->{reconnecting} = 1; OpenQA::Utils::log_info("AMQP reconnecting in $self->{config}->{amqp}{reconnect_timeout} seconds"); Mojo::IOLoop->timer( $self->{config}->{amqp}{reconnect_timeout} => sub { $self->{reconnecting} = 0; $self->connect(); }); } sub connect { my $self = shift; OpenQA::Utils::log_info("Connecting to AMQP server"); $self->{client} = Mojo::RabbitMQ::Client->new(url => $self->{config}->{amqp}{url}); $self->{client}->heartbeat_timeout($self->{config}->{amqp}{heartbeat_timeout} // 60); $self->{client}->on( open => sub { OpenQA::Utils::log_info("AMQP connection established"); my ($client) = @_; $self->{channel} = Mojo::RabbitMQ::Client::Channel->new(); $self->{channel}->catch(sub { OpenQA::Utils::log_warning("Error on AMQP channel received: " . $_[1]); }); $self->{channel}->on( open => sub { my ($channel) = @_; $channel->declare_exchange( exchange => $self->{config}->{amqp}{exchange}, type => 'topic', passive => 1, durable => 1 )->deliver(); }); $self->{channel}->on( close => sub { OpenQA::Utils::log_warning("AMQP channel closed"); }); $client->open_channel($self->{channel}); }); $self->{client}->on( close => sub { OpenQA::Utils::log_warning("AMQP connection closed"); $self->reconnect(); }); $self->{client}->on( error => sub { my ($client, $error) = @_; OpenQA::Utils::log_warning("AMQP connection error: $error"); $self->reconnect(); }); $self->{client}->on( disconnect => sub { OpenQA::Utils::log_warning("AMQP connection closed"); $self->reconnect(); }); $self->{client}->on( timeout => sub { OpenQA::Utils::log_warning("AMQP connection closed"); $self->reconnect(); }); $self->{client}->connect(); } sub log_event { my ($self, $event, $event_data) = @_; unless ($self->{channel} && $self->{channel}->is_open) { OpenQA::Utils::log_warning("Error sending AMQP event: Channel is not open"); return; } # use dot separators $event =~ s/_/\./; $event =~ s/_/\./; my $topic = $self->{config}->{amqp}{topic_prefix} . '.' . $event; # convert data to JSON, with reliable key ordering (helps the tests) $event_data = Cpanel::JSON::XS->new->canonical(1)->allow_blessed(1)->ascii(1)->encode($event_data); OpenQA::Utils::log_debug("Sending AMQP event: $topic"); $self->{channel}->publish( exchange => $self->{config}->{amqp}{exchange}, routing_key => $topic, body => $event_data )->deliver(); } sub on_job_event { my ($self, $args) = @_; my ($user_id, $connection_id, $event, $event_data) = @$args; # find count of pending jobs for the same build # this is so we can tell when all tests for a build are done my $job = $self->{app}->db->resultset('Jobs')->find({id => $event_data->{id}}); my $build = $job->BUILD; $event_data->{group_id} = $job->group_id; $event_data->{remaining} = $self->{app}->db->resultset('Jobs')->search( { 'me.BUILD' => $build, state => [OpenQA::Jobs::Constants::PENDING_STATES], })->count; # add various useful properties for consumers if not there already for my $detail (qw(BUILD TEST ARCH MACHINE FLAVOR)) { $event_data->{$detail} //= $job->$detail; } for my $detail (qw(ISO HDD_1)) { $event_data->{$detail} //= $job->settings_hash->{$detail} if ($job->settings_hash->{$detail}); } $self->log_event($event, $event_data); } sub on_comment_event { my ($self, $args) = @_; my ($comment_id, $connection_id, $event, $event_data) = @$args; # find comment in database my $comment = $self->{app}->db->resultset('Comments')->find($event_data->{id}); return unless $comment; # just send the hash already used for JSON representation my $hash = $comment->hash; # also include comment id, job_id, and group_id $hash->{id} = $comment->id; $hash->{job_id} = $comment->job_id; $hash->{group_id} = $comment->group_id; $self->log_event($event, $hash); } 1;
Java
/* * Copyright (C) 2005-2012 MaNGOS <http://getmangos.com/> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * 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 */ /// \addtogroup world The World /// @{ /// \file #ifndef __WORLD_H #define __WORLD_H #include "Common.h" #include "Timer.h" #include "Policies/Singleton.h" #include "SharedDefines.h" #include "ObjectLock.h" #include "Util.h" #include <map> #include <set> #include <list> class Object; class WorldPacket; class WorldSession; class Player; class Weather; class SqlResultQueue; class QueryResult; class WorldSocket; // ServerMessages.dbc enum ServerMessageType { SERVER_MSG_SHUTDOWN_TIME = 1, SERVER_MSG_RESTART_TIME = 2, SERVER_MSG_CUSTOM = 3, SERVER_MSG_SHUTDOWN_CANCELLED = 4, SERVER_MSG_RESTART_CANCELLED = 5, SERVER_MSG_BG_SHUTDOWN_TIME = 6, SERVER_MSG_BG_RESTART_TIME = 7, SERVER_MSG_INSTANCE_SHUTDOWN_TIME = 8, SERVER_MSG_INSTANCE_RESTART_TIME = 9, }; enum ShutdownMask { SHUTDOWN_MASK_RESTART = 1, SHUTDOWN_MASK_IDLE = 2, }; enum ShutdownExitCode { SHUTDOWN_EXIT_CODE = 0, ERROR_EXIT_CODE = 1, RESTART_EXIT_CODE = 2, }; /// Timers for different object refresh rates enum WorldTimers { WUPDATE_AUCTIONS = 0, WUPDATE_WEATHERS = 1, WUPDATE_UPTIME = 2, WUPDATE_CORPSES = 3, WUPDATE_EVENTS = 4, WUPDATE_DELETECHARS = 5, WUPDATE_AHBOT = 6, WUPDATE_AUTOBROADCAST = 7, WUPDATE_WORLDSTATE = 8, WUPDATE_COUNT = 9 }; /// Configuration elements enum eConfigUInt32Values { CONFIG_UINT32_COMPRESSION = 0, CONFIG_UINT32_INTERVAL_SAVE, CONFIG_UINT32_INTERVAL_GRIDCLEAN, CONFIG_UINT32_INTERVAL_MAPUPDATE, CONFIG_UINT32_INTERVAL_CHANGEWEATHER, CONFIG_UINT32_MAPUPDATE_MAXVISITORS, CONFIG_UINT32_MAPUPDATE_MAXVISITS, CONFIG_UINT32_PORT_WORLD, CONFIG_UINT32_GAME_TYPE, CONFIG_UINT32_REALM_ZONE, CONFIG_UINT32_STRICT_PLAYER_NAMES, CONFIG_UINT32_STRICT_CHARTER_NAMES, CONFIG_UINT32_STRICT_PET_NAMES, CONFIG_UINT32_MIN_PLAYER_NAME, CONFIG_UINT32_MIN_CHARTER_NAME, CONFIG_UINT32_MIN_PET_NAME, CONFIG_UINT32_CHARACTERS_CREATING_DISABLED, CONFIG_UINT32_CHARACTERS_PER_ACCOUNT, CONFIG_UINT32_CHARACTERS_PER_REALM, CONFIG_UINT32_HEROIC_CHARACTERS_PER_REALM, CONFIG_UINT32_MIN_LEVEL_FOR_HEROIC_CHARACTER_CREATING, CONFIG_UINT32_SKIP_CINEMATICS, CONFIG_UINT32_MAX_PLAYER_LEVEL, CONFIG_UINT32_START_PLAYER_LEVEL, CONFIG_UINT32_START_HEROIC_PLAYER_LEVEL, CONFIG_UINT32_START_PLAYER_MONEY, CONFIG_UINT32_MAX_HONOR_POINTS, CONFIG_UINT32_START_HONOR_POINTS, CONFIG_UINT32_MAX_ARENA_POINTS, CONFIG_UINT32_START_ARENA_POINTS, CONFIG_UINT32_INSTANCE_RESET_TIME_HOUR, CONFIG_UINT32_INSTANCE_UNLOAD_DELAY, CONFIG_UINT32_MAX_SPELL_CASTS_IN_CHAIN, CONFIG_UINT32_BIRTHDAY_TIME, CONFIG_UINT32_MAX_PRIMARY_TRADE_SKILL, CONFIG_UINT32_TRADE_SKILL_GMIGNORE_MAX_PRIMARY_COUNT, CONFIG_UINT32_TRADE_SKILL_GMIGNORE_LEVEL, CONFIG_UINT32_TRADE_SKILL_GMIGNORE_SKILL, CONFIG_UINT32_MIN_PETITION_SIGNS, CONFIG_UINT32_GM_LOGIN_STATE, CONFIG_UINT32_GM_VISIBLE_STATE, CONFIG_UINT32_GM_ACCEPT_TICKETS, CONFIG_UINT32_GM_CHAT, CONFIG_UINT32_GM_WISPERING_TO, CONFIG_UINT32_GM_LEVEL_IN_GM_LIST, CONFIG_UINT32_GM_LEVEL_IN_WHO_LIST, CONFIG_UINT32_START_GM_LEVEL, CONFIG_UINT32_GM_INVISIBLE_AURA, CONFIG_UINT32_GROUP_VISIBILITY, CONFIG_UINT32_MAIL_DELIVERY_DELAY, CONFIG_UINT32_MASS_MAILER_SEND_PER_TICK, CONFIG_UINT32_UPTIME_UPDATE, CONFIG_UINT32_AUCTION_DEPOSIT_MIN, CONFIG_UINT32_SKILL_CHANCE_ORANGE, CONFIG_UINT32_SKILL_CHANCE_YELLOW, CONFIG_UINT32_SKILL_CHANCE_GREEN, CONFIG_UINT32_SKILL_CHANCE_GREY, CONFIG_UINT32_SKILL_CHANCE_MINING_STEPS, CONFIG_UINT32_SKILL_CHANCE_SKINNING_STEPS, CONFIG_UINT32_SKILL_GAIN_CRAFTING, CONFIG_UINT32_SKILL_GAIN_DEFENSE, CONFIG_UINT32_SKILL_GAIN_GATHERING, CONFIG_UINT32_SKILL_GAIN_WEAPON, CONFIG_UINT32_MAX_OVERSPEED_PINGS, CONFIG_UINT32_EXPANSION, CONFIG_UINT32_CHATFLOOD_MESSAGE_COUNT, CONFIG_UINT32_CHATFLOOD_MESSAGE_DELAY, CONFIG_UINT32_CHATFLOOD_MUTE_TIME, CONFIG_UINT32_CREATURE_FAMILY_ASSISTANCE_DELAY, CONFIG_UINT32_CREATURE_FAMILY_FLEE_DELAY, CONFIG_UINT32_WORLD_BOSS_LEVEL_DIFF, CONFIG_UINT32_QUEST_DAILY_RESET_HOUR, CONFIG_UINT32_QUEST_WEEKLY_RESET_WEEK_DAY, CONFIG_UINT32_QUEST_WEEKLY_RESET_HOUR, CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_SEVERITY, CONFIG_UINT32_CHAT_STRICT_LINK_CHECKING_KICK, CONFIG_UINT32_CORPSE_DECAY_NORMAL, CONFIG_UINT32_CORPSE_DECAY_RARE, CONFIG_UINT32_CORPSE_DECAY_ELITE, CONFIG_UINT32_CORPSE_DECAY_RAREELITE, CONFIG_UINT32_CORPSE_DECAY_WORLDBOSS, CONFIG_UINT32_INSTANT_LOGOUT, CONFIG_UINT32_BATTLEGROUND_INVITATION_TYPE, CONFIG_UINT32_BATTLEGROUND_PREMATURE_FINISH_TIMER, CONFIG_UINT32_BATTLEGROUND_PREMADE_GROUP_WAIT_FOR_MATCH, CONFIG_UINT32_BATTLEGROUND_QUEUE_ANNOUNCER_JOIN, CONFIG_UINT32_ARENA_MAX_RATING_DIFFERENCE, CONFIG_UINT32_ARENA_RATING_DISCARD_TIMER, CONFIG_UINT32_ARENA_AUTO_DISTRIBUTE_INTERVAL_DAYS, CONFIG_UINT32_CLIENTCACHE_VERSION, CONFIG_UINT32_GUILD_EVENT_LOG_COUNT, CONFIG_UINT32_GUILD_BANK_EVENT_LOG_COUNT, CONFIG_UINT32_TIMERBAR_FATIGUE_GMLEVEL, CONFIG_UINT32_TIMERBAR_FATIGUE_MAX, CONFIG_UINT32_TIMERBAR_BREATH_GMLEVEL, CONFIG_UINT32_TIMERBAR_BREATH_MAX, CONFIG_UINT32_TIMERBAR_FIRE_GMLEVEL, CONFIG_UINT32_TIMERBAR_FIRE_MAX, CONFIG_UINT32_MIN_LEVEL_STAT_SAVE, CONFIG_UINT32_CHARDELETE_KEEP_DAYS, CONFIG_UINT32_CHARDELETE_METHOD, CONFIG_UINT32_CHARDELETE_MIN_LEVEL, CONFIG_UINT32_GUID_RESERVE_SIZE_CREATURE, CONFIG_UINT32_GUID_RESERVE_SIZE_GAMEOBJECT, CONFIG_UINT32_ANTICHEAT_GMLEVEL, CONFIG_UINT32_ANTICHEAT_ACTION_DELAY, CONFIG_UINT32_NUMTHREADS, CONFIG_UINT32_RANDOM_BG_RESET_HOUR, CONFIG_UINT32_LOSERNOCHANGE, CONFIG_UINT32_LOSERHALFCHANGE, CONFIG_UINT32_RAF_MAXGRANTLEVEL, CONFIG_UINT32_RAF_MAXREFERALS, CONFIG_UINT32_RAF_MAXREFERERS, CONFIG_UINT32_LFG_MAXKICKS, CONFIG_UINT32_MIN_LEVEL_FOR_RAID, CONFIG_UINT32_PLAYERBOT_MAXBOTS, CONFIG_UINT32_PLAYERBOT_RESTRICTLEVEL, CONFIG_UINT32_PLAYERBOT_MINBOTLEVEL, CONFIG_UINT32_GEAR_CALC_BASE, CONFIG_UINT32_ARENA_AURAS_DURATION, CONFIG_UINT32_VMSS_MAXTHREADBREAKS, CONFIG_UINT32_VMSS_TBREMTIME, CONFIG_UINT32_VMSS_MAPFREEMETHOD, CONFIG_UINT32_VMSS_FREEZECHECKPERIOD, CONFIG_UINT32_VMSS_FREEZEDETECTTIME, CONFIG_UINT32_VMSS_FORCEUNLOADDELAY, CONFIG_UINT32_WORLD_STATE_EXPIRETIME, CONFIG_UINT32_VALUE_COUNT }; /// Configuration elements enum eConfigInt32Values { CONFIG_INT32_DEATH_SICKNESS_LEVEL = 0, CONFIG_INT32_ARENA_STARTRATING, CONFIG_INT32_ARENA_STARTPERSONALRATING, CONFIG_INT32_QUEST_LOW_LEVEL_HIDE_DIFF, CONFIG_INT32_QUEST_HIGH_LEVEL_HIDE_DIFF, CONFIG_INT32_VALUE_COUNT }; /// Server config enum eConfigFloatValues { CONFIG_FLOAT_RATE_HEALTH = 0, CONFIG_FLOAT_RATE_POWER_MANA, CONFIG_FLOAT_RATE_POWER_RAGE_INCOME, CONFIG_FLOAT_RATE_POWER_RAGE_LOSS, CONFIG_FLOAT_RATE_POWER_RUNICPOWER_INCOME, CONFIG_FLOAT_RATE_POWER_RUNICPOWER_LOSS, CONFIG_FLOAT_RATE_POWER_FOCUS, CONFIG_FLOAT_RATE_POWER_ENERGY, CONFIG_FLOAT_RATE_SKILL_DISCOVERY, CONFIG_FLOAT_RATE_DROP_ITEM_POOR, CONFIG_FLOAT_RATE_DROP_ITEM_NORMAL, CONFIG_FLOAT_RATE_DROP_ITEM_UNCOMMON, CONFIG_FLOAT_RATE_DROP_ITEM_RARE, CONFIG_FLOAT_RATE_DROP_ITEM_EPIC, CONFIG_FLOAT_RATE_DROP_ITEM_LEGENDARY, CONFIG_FLOAT_RATE_DROP_ITEM_ARTIFACT, CONFIG_FLOAT_RATE_DROP_ITEM_REFERENCED, CONFIG_FLOAT_RATE_DROP_MONEY, CONFIG_FLOAT_RATE_XP_KILL, CONFIG_FLOAT_RATE_XP_QUEST, CONFIG_FLOAT_RATE_XP_EXPLORE, CONFIG_FLOAT_RATE_RAF_XP, CONFIG_FLOAT_RATE_RAF_LEVELPERLEVEL, CONFIG_FLOAT_RATE_REPUTATION_GAIN, CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_KILL, CONFIG_FLOAT_RATE_REPUTATION_LOWLEVEL_QUEST, CONFIG_FLOAT_RATE_CREATURE_NORMAL_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_HP, CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_HP, CONFIG_FLOAT_RATE_CREATURE_NORMAL_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_DAMAGE, CONFIG_FLOAT_RATE_CREATURE_NORMAL_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_ELITE_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RAREELITE_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_WORLDBOSS_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_ELITE_RARE_SPELLDAMAGE, CONFIG_FLOAT_RATE_CREATURE_AGGRO, CONFIG_FLOAT_RATE_REST_INGAME, CONFIG_FLOAT_RATE_REST_OFFLINE_IN_TAVERN_OR_CITY, CONFIG_FLOAT_RATE_REST_OFFLINE_IN_WILDERNESS, CONFIG_FLOAT_RATE_DAMAGE_FALL, CONFIG_FLOAT_RATE_AUCTION_TIME, CONFIG_FLOAT_RATE_AUCTION_DEPOSIT, CONFIG_FLOAT_RATE_AUCTION_CUT, CONFIG_FLOAT_RATE_HONOR, CONFIG_FLOAT_RATE_MINING_AMOUNT, CONFIG_FLOAT_RATE_MINING_NEXT, CONFIG_FLOAT_RATE_TALENT, CONFIG_FLOAT_RATE_CORPSE_DECAY_LOOTED, CONFIG_FLOAT_RATE_INSTANCE_RESET_TIME, CONFIG_FLOAT_RATE_TARGET_POS_RECALCULATION_RANGE, CONFIG_FLOAT_RATE_DURABILITY_LOSS_DAMAGE, CONFIG_FLOAT_RATE_DURABILITY_LOSS_PARRY, CONFIG_FLOAT_RATE_DURABILITY_LOSS_ABSORB, CONFIG_FLOAT_RATE_DURABILITY_LOSS_BLOCK, CONFIG_FLOAT_SIGHT_GUARDER, CONFIG_FLOAT_SIGHT_MONSTER, CONFIG_FLOAT_LISTEN_RANGE_SAY, CONFIG_FLOAT_LISTEN_RANGE_YELL, CONFIG_FLOAT_LISTEN_RANGE_TEXTEMOTE, CONFIG_FLOAT_CREATURE_FAMILY_FLEE_ASSISTANCE_RADIUS, CONFIG_FLOAT_CREATURE_FAMILY_ASSISTANCE_RADIUS, CONFIG_FLOAT_GROUP_XP_DISTANCE, CONFIG_FLOAT_THREAT_RADIUS, CONFIG_FLOAT_GHOST_RUN_SPEED_WORLD, CONFIG_FLOAT_GHOST_RUN_SPEED_BG, CONFIG_FLOAT_PLAYERBOT_MINDISTANCE, CONFIG_FLOAT_PLAYERBOT_MAXDISTANCE, CONFIG_FLOAT_CROWDCONTROL_HP_BASE, CONFIG_FLOAT_LOADBALANCE_HIGHVALUE, CONFIG_FLOAT_LOADBALANCE_LOWVALUE, CONFIG_FLOAT_VALUE_COUNT }; /// Configuration elements enum eConfigBoolValues { CONFIG_BOOL_GRID_UNLOAD = 0, CONFIG_BOOL_SAVE_RESPAWN_TIME_IMMEDIATELY, CONFIG_BOOL_OFFHAND_CHECK_AT_TALENTS_RESET, CONFIG_BOOL_ALLOW_TWO_SIDE_ACCOUNTS, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHAT, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_CHANNEL, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GROUP, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_GUILD, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_AUCTION, CONFIG_BOOL_ALLOW_TWO_SIDE_INTERACTION_MAIL, CONFIG_BOOL_ALLOW_TWO_SIDE_WHO_LIST, CONFIG_BOOL_ALLOW_TWO_SIDE_ADD_FRIEND, CONFIG_BOOL_INSTANCE_IGNORE_LEVEL, CONFIG_BOOL_INSTANCE_IGNORE_RAID, CONFIG_BOOL_CAST_UNSTUCK, CONFIG_BOOL_GM_LOG_TRADE, CONFIG_BOOL_GM_LOWER_SECURITY, CONFIG_BOOL_GM_ALLOW_ACHIEVEMENT_GAINS, CONFIG_BOOL_GM_ANNOUNCE_BAN, CONFIG_BOOL_SKILL_PROSPECTING, CONFIG_BOOL_ALWAYS_MAX_SKILL_FOR_LEVEL, CONFIG_BOOL_WEATHER, CONFIG_BOOL_EVENT_ANNOUNCE, CONFIG_BOOL_QUEST_IGNORE_RAID, CONFIG_BOOL_DETECT_POS_COLLISION, CONFIG_BOOL_RESTRICTED_LFG_CHANNEL, CONFIG_BOOL_SILENTLY_GM_JOIN_TO_CHANNEL, CONFIG_BOOL_TALENTS_INSPECTING, CONFIG_BOOL_CHAT_FAKE_MESSAGE_PREVENTING, CONFIG_BOOL_CHAT_STRICT_LINK_CHECKING_SEVERITY, CONFIG_BOOL_CHAT_STRICT_LINK_CHECKING_KICK, CONFIG_BOOL_ADDON_CHANNEL, CONFIG_BOOL_CORPSE_EMPTY_LOOT_SHOW, CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVP, CONFIG_BOOL_DEATH_CORPSE_RECLAIM_DELAY_PVE, CONFIG_BOOL_DEATH_BONES_WORLD, CONFIG_BOOL_DEATH_BONES_BG_OR_ARENA, CONFIG_BOOL_ALL_TAXI_PATHS, CONFIG_BOOL_DECLINED_NAMES_USED, CONFIG_BOOL_SKILL_MILLING, CONFIG_BOOL_SKILL_FAIL_LOOT_FISHING, CONFIG_BOOL_SKILL_FAIL_GAIN_FISHING, CONFIG_BOOL_SKILL_FAIL_POSSIBLE_FISHINGPOOL, CONFIG_BOOL_BATTLEGROUND_CAST_DESERTER, CONFIG_BOOL_BATTLEGROUND_QUEUE_ANNOUNCER_START, CONFIG_BOOL_ARENA_AUTO_DISTRIBUTE_POINTS, CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_JOIN, CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_EXIT, CONFIG_BOOL_ARENA_QUEUE_ANNOUNCER_START, CONFIG_BOOL_OUTDOORPVP_SI_ENABLED, CONFIG_BOOL_OUTDOORPVP_EP_ENABLED, CONFIG_BOOL_OUTDOORPVP_HP_ENABLED, CONFIG_BOOL_OUTDOORPVP_ZM_ENABLED, CONFIG_BOOL_OUTDOORPVP_TF_ENABLED, CONFIG_BOOL_OUTDOORPVP_NA_ENABLED, CONFIG_BOOL_OUTDOORPVP_GH_ENABLED, CONFIG_BOOL_OUTDOORPVP_WG_ENABLED, CONFIG_BOOL_KICK_PLAYER_ON_BAD_PACKET, CONFIG_BOOL_STATS_SAVE_ONLY_ON_LOGOUT, CONFIG_BOOL_CLEAN_CHARACTER_DB, CONFIG_BOOL_VMAP_INDOOR_CHECK, CONFIG_BOOL_LOOT_CHESTS_IGNORE_DB, CONFIG_BOOL_PET_UNSUMMON_AT_MOUNT, CONFIG_BOOL_RAID_FLAGS_UNIQUE, CONFIG_BOOL_ANTICHEAT_ENABLE, CONFIG_BOOL_ANTICHEAT_WARDEN, CONFIG_BOOL_ALLOW_FLIGHT_ON_OLD_MAPS, CONFIG_BOOL_LFG_ENABLE, CONFIG_BOOL_LFR_ENABLE, CONFIG_BOOL_LFG_DEBUG_ENABLE, CONFIG_BOOL_LFR_EXTEND, CONFIG_BOOL_LFG_ONLYLASTENCOUNTER, CONFIG_BOOL_PLAYERBOT_DISABLE, CONFIG_BOOL_PLAYERBOT_DEBUGWHISPER, CONFIG_BOOL_PLAYERBOT_SHAREDBOTS, CONFIG_BOOL_ALLOW_CUSTOM_MAPS, CONFIG_BOOL_ALLOW_HONOR_KILLS_TITLES, CONFIG_BOOL_PET_SAVE_ALL, CONFIG_BOOL_THREADS_DYNAMIC, CONFIG_BOOL_VMSS_ENABLE, CONFIG_BOOL_VMSS_TRYSKIPFIRST, CONFIG_BOOL_PLAYERBOT_ALLOW_SUMMON_OPPOSITE_FACTION, CONFIG_BOOL_PLAYERBOT_COLLECT_COMBAT, CONFIG_BOOL_PLAYERBOT_COLLECT_QUESTS, CONFIG_BOOL_PLAYERBOT_COLLECT_PROFESSION, CONFIG_BOOL_PLAYERBOT_COLLECT_LOOT, CONFIG_BOOL_PLAYERBOT_COLLECT_SKIN, CONFIG_BOOL_PLAYERBOT_COLLECT_OBJECTS, CONFIG_BOOL_PLAYERBOT_SELL_TRASH, CONFIG_BOOL_MMAP_ENABLED, CONFIG_BOOL_RESET_DUEL_AREA_ENABLED, CONFIG_BOOL_PET_ADVANCED_AI, CONFIG_BOOL_RESILENCE_ALTERNATIVE_CALCULATION, CONFIG_BOOL_VALUE_COUNT }; /// Can be used in SMSG_AUTH_RESPONSE packet enum BillingPlanFlags { SESSION_NONE = 0x00, SESSION_UNUSED = 0x01, SESSION_RECURRING_BILL = 0x02, SESSION_FREE_TRIAL = 0x04, SESSION_IGR = 0x08, SESSION_USAGE = 0x10, SESSION_TIME_MIXTURE = 0x20, SESSION_RESTRICTED = 0x40, SESSION_ENABLE_CAIS = 0x80, }; /// Type of server, this is values from second column of Cfg_Configs.dbc (1.12.1 have another numeration) enum RealmType { REALM_TYPE_NORMAL = 0, REALM_TYPE_PVP = 1, REALM_TYPE_NORMAL2 = 4, REALM_TYPE_RP = 6, REALM_TYPE_RPPVP = 8, REALM_TYPE_FFA_PVP = 16 // custom, free for all pvp mode like arena PvP in all zones except rest activated places and sanctuaries // replaced by REALM_PVP in realm list }; /// This is values from first column of Cfg_Categories.dbc (1.12.1 have another numeration) enum RealmZone { REALM_ZONE_UNKNOWN = 0, // any language REALM_ZONE_DEVELOPMENT = 1, // any language REALM_ZONE_UNITED_STATES = 2, // extended-Latin REALM_ZONE_OCEANIC = 3, // extended-Latin REALM_ZONE_LATIN_AMERICA = 4, // extended-Latin REALM_ZONE_TOURNAMENT_5 = 5, // basic-Latin at create, any at login REALM_ZONE_KOREA = 6, // East-Asian REALM_ZONE_TOURNAMENT_7 = 7, // basic-Latin at create, any at login REALM_ZONE_ENGLISH = 8, // extended-Latin REALM_ZONE_GERMAN = 9, // extended-Latin REALM_ZONE_FRENCH = 10, // extended-Latin REALM_ZONE_SPANISH = 11, // extended-Latin REALM_ZONE_RUSSIAN = 12, // Cyrillic REALM_ZONE_TOURNAMENT_13 = 13, // basic-Latin at create, any at login REALM_ZONE_TAIWAN = 14, // East-Asian REALM_ZONE_TOURNAMENT_15 = 15, // basic-Latin at create, any at login REALM_ZONE_CHINA = 16, // East-Asian REALM_ZONE_CN1 = 17, // basic-Latin at create, any at login REALM_ZONE_CN2 = 18, // basic-Latin at create, any at login REALM_ZONE_CN3 = 19, // basic-Latin at create, any at login REALM_ZONE_CN4 = 20, // basic-Latin at create, any at login REALM_ZONE_CN5 = 21, // basic-Latin at create, any at login REALM_ZONE_CN6 = 22, // basic-Latin at create, any at login REALM_ZONE_CN7 = 23, // basic-Latin at create, any at login REALM_ZONE_CN8 = 24, // basic-Latin at create, any at login REALM_ZONE_TOURNAMENT_25 = 25, // basic-Latin at create, any at login REALM_ZONE_TEST_SERVER = 26, // any language REALM_ZONE_TOURNAMENT_27 = 27, // basic-Latin at create, any at login REALM_ZONE_QA_SERVER = 28, // any language REALM_ZONE_CN9 = 29, // basic-Latin at create, any at login REALM_ZONE_TEST_SERVER_2 = 30, // any language // in 3.x REALM_ZONE_CN10 = 31, // basic-Latin at create, any at login REALM_ZONE_CTC = 32, REALM_ZONE_CNC = 33, REALM_ZONE_CN1_4 = 34, // basic-Latin at create, any at login REALM_ZONE_CN2_6_9 = 35, // basic-Latin at create, any at login REALM_ZONE_CN3_7 = 36, // basic-Latin at create, any at login REALM_ZONE_CN5_8 = 37 // basic-Latin at create, any at login }; /// Storage class for commands issued for delayed execution struct CliCommandHolder { typedef void Print(void*, const char*); typedef void CommandFinished(void*, bool success); uint32 m_cliAccountId; // 0 for console and real account id for RA/soap AccountTypes m_cliAccessLevel; void* m_callbackArg; char *m_command; Print* m_print; CommandFinished* m_commandFinished; CliCommandHolder(uint32 accountId, AccountTypes cliAccessLevel, void* callbackArg, const char *command, Print* zprint, CommandFinished* commandFinished) : m_cliAccountId(accountId), m_cliAccessLevel(cliAccessLevel), m_callbackArg(callbackArg), m_print(zprint), m_commandFinished(commandFinished) { size_t len = strlen(command)+1; m_command = new char[len]; memcpy(m_command, command, len); } ~CliCommandHolder() { delete[] m_command; } }; /// The World class World { public: static volatile uint32 m_worldLoopCounter; World(); ~World(); WorldSession* FindSession(uint32 id) const; void AddSession(WorldSession *s); void SendBroadcast(); bool RemoveSession(uint32 id); /// Get the number of current active sessions void UpdateMaxSessionCounters(); uint32 GetActiveAndQueuedSessionCount() const { return m_sessions.size(); } uint32 GetActiveSessionCount() const { return m_sessions.size() - m_QueuedSessions.size(); } uint32 GetQueuedSessionCount() const { return m_QueuedSessions.size(); } /// Get the maximum number of parallel sessions on the server since last reboot uint32 GetMaxQueuedSessionCount() const { return m_maxQueuedSessionCount; } uint32 GetMaxActiveSessionCount() const { return m_maxActiveSessionCount; } Player* FindPlayerInZone(uint32 zone); Weather* FindWeather(uint32 id) const; Weather* AddWeather(uint32 zone_id); void RemoveWeather(uint32 zone_id); /// Get the active session server limit (or security level limitations) uint32 GetPlayerAmountLimit() const { return m_playerLimit >= 0 ? m_playerLimit : 0; } AccountTypes GetPlayerSecurityLimit() const { return m_playerLimit <= 0 ? AccountTypes(-m_playerLimit) : SEC_PLAYER; } /// Set the active session server limit (or security level limitation) void SetPlayerLimit(int32 limit, bool needUpdate = false); //player Queue typedef std::list<WorldSession*> Queue; void AddQueuedSession(WorldSession*); bool RemoveQueuedSession(WorldSession* session); int32 GetQueuedSessionPos(WorldSession*); /// \todo Actions on m_allowMovement still to be implemented /// Is movement allowed? bool getAllowMovement() const { return m_allowMovement; } /// Allow/Disallow object movements void SetAllowMovement(bool allow) { m_allowMovement = allow; } /// Set a new Message of the Day void SetMotd(const std::string& motd) { m_motd = motd; } /// Get the current Message of the Day const char* GetMotd() const { return m_motd.c_str(); } LocaleConstant GetDefaultDbcLocale() const { return m_defaultDbcLocale; } /// Get the path where data (dbc, maps) are stored on disk std::string GetDataPath() const { return m_dataPath; } /// When server started? time_t const& GetStartTime() const { return m_startTime; } /// What time is it? time_t const& GetGameTime() const { return m_gameTime; } /// Uptime (in secs) uint32 GetUptime() const { return uint32(m_gameTime - m_startTime); } /// Update time uint32 GetUpdateTime() const { return m_updateTime; } /// Next daily quests reset time time_t GetNextDailyQuestsResetTime() const { return m_NextDailyQuestReset; } time_t GetNextWeeklyQuestsResetTime() const { return m_NextWeeklyQuestReset; } time_t GetNextRandomBGResetTime() const { return m_NextRandomBGReset; } /// Get the maximum skill level a player can reach uint16 GetConfigMaxSkillValue() const { uint32 lvl = getConfig(CONFIG_UINT32_MAX_PLAYER_LEVEL); return lvl > 60 ? 300 + ((lvl - 60) * 75) / 10 : lvl*5; } void SetInitialWorldSettings(); void LoadConfigSettings(bool reload = false); void SendWorldText(int32 string_id, ...); void SendWorldTextWithSecurity(AccountTypes security, int32 string_id, ...); void SendGlobalMessage(WorldPacket* packet, WorldSession* self = NULL, Team team = TEAM_NONE, AccountTypes security = SEC_PLAYER); void SendZoneMessage(uint32 zone, WorldPacket* packet, WorldSession* self = NULL, Team team = TEAM_NONE); void SendZoneText(uint32 zone, const char* text, WorldSession* self = NULL, Team team = TEAM_NONE); void SendServerMessage(ServerMessageType type, const char* text = "", Player* player = NULL); void SendZoneUnderAttackMessage(uint32 zoneId, Team team); void SendDefenseMessage(uint32 zoneId, int32 textId); /// Are we in the middle of a shutdown? bool IsShutdowning() const { return m_ShutdownTimer > 0; } void ShutdownServ(uint32 time, uint32 options, uint8 exitcode); void ShutdownCancel(); void ShutdownMsg(bool show = false, Player* player = NULL); static uint8 GetExitCode() { return m_ExitCode; } static void StopNow(uint8 exitcode) { m_stopEvent = true; m_ExitCode = exitcode; } static bool IsStopped() { return m_stopEvent; } void Update(uint32 diff); void UpdateSessions( uint32 diff ); /// Get a server configuration element (see #eConfigFloatValues) void setConfig(eConfigFloatValues index,float value) { m_configFloatValues[index]=value; } /// Get a server configuration element (see #eConfigFloatValues) float getConfig(eConfigFloatValues rate) const { return m_configFloatValues[rate]; } /// Set a server configuration element (see #eConfigUInt32Values) void setConfig(eConfigUInt32Values index, uint32 value) { m_configUint32Values[index]=value; } /// Get a server configuration element (see #eConfigUInt32Values) uint32 getConfig(eConfigUInt32Values index) const { return m_configUint32Values[index]; } /// Set a server configuration element (see #eConfigInt32Values) void setConfig(eConfigInt32Values index, int32 value) { m_configInt32Values[index]=value; } /// Get a server configuration element (see #eConfigInt32Values) int32 getConfig(eConfigInt32Values index) const { return m_configInt32Values[index]; } /// Set a server configuration element (see #eConfigBoolValues) void setConfig(eConfigBoolValues index, bool value) { m_configBoolValues[index]=value; } /// Get a server configuration element (see #eConfigBoolValues) bool getConfig(eConfigBoolValues index) const { return m_configBoolValues[index]; } /// Are we on a "Player versus Player" server? bool IsPvPRealm() { return (getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_PVP || getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_RPPVP || getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_FFA_PVP); } bool IsFFAPvPRealm() { return getConfig(CONFIG_UINT32_GAME_TYPE) == REALM_TYPE_FFA_PVP; } void KickAll(); void KickAllLess(AccountTypes sec); BanReturn BanAccount(BanMode mode, std::string nameOrIP, uint32 duration_secs, std::string reason, std::string author); bool RemoveBanAccount(BanMode mode, std::string nameOrIP); // for max speed access static float GetMaxVisibleDistanceOnContinents() { return m_MaxVisibleDistanceOnContinents; } static float GetMaxVisibleDistanceInInstances() { return m_MaxVisibleDistanceInInstances; } static float GetMaxVisibleDistanceInBGArenas() { return m_MaxVisibleDistanceInBGArenas; } static float GetMaxVisibleDistanceInFlight() { return m_MaxVisibleDistanceInFlight; } static float GetVisibleUnitGreyDistance() { return m_VisibleUnitGreyDistance; } static float GetVisibleObjectGreyDistance() { return m_VisibleObjectGreyDistance; } static float GetRelocationLowerLimitSq() { return m_relocation_lower_limit_sq; } static uint32 GetRelocationAINotifyDelay() { return m_relocation_ai_notify_delay; } void ProcessCliCommands(); void QueueCliCommand(CliCommandHolder* commandHolder) { cliCmdQueue.add(commandHolder); } void UpdateResultQueue(); void InitResultQueue(); LocaleConstant GetAvailableDbcLocale(LocaleConstant locale) const { if(m_availableDbcLocaleMask & (1 << locale)) return locale; else return m_defaultDbcLocale; } //used World DB version void LoadDBVersion(); char const* GetDBVersion() { return m_DBVersion.c_str(); } char const* GetCreatureEventAIVersion() { return m_CreatureEventAIVersion.c_str(); } // multithread locking (World locking used only if object map == NULL) ObjectLockType& GetLock(MapLockType _locktype = MAP_LOCK_TYPE_DEFAULT) { return i_lock[_locktype]; } // reset duel system void setDuelResetEnableAreaIds(const char* areas); bool IsAreaIdEnabledDuelReset(uint32 areaId); protected: void _UpdateGameTime(); void InitDailyQuestResetTime(); void InitWeeklyQuestResetTime(); void SetMonthlyQuestResetTime(bool initialize = true); void ResetDailyQuests(); void ResetWeeklyQuests(); void ResetMonthlyQuests(); void InitRandomBGResetTime(); void ResetRandomBG(); private: void setConfig(eConfigUInt32Values index, char const* fieldname, uint32 defvalue); void setConfig(eConfigInt32Values index, char const* fieldname, int32 defvalue); void setConfig(eConfigFloatValues index, char const* fieldname, float defvalue); void setConfig(eConfigBoolValues index, char const* fieldname, bool defvalue); void setConfigPos(eConfigFloatValues index, char const* fieldname, float defvalue); void setConfigMin(eConfigUInt32Values index, char const* fieldname, uint32 defvalue, uint32 minvalue); void setConfigMin(eConfigInt32Values index, char const* fieldname, int32 defvalue, int32 minvalue); void setConfigMin(eConfigFloatValues index, char const* fieldname, float defvalue, float minvalue); void setConfigMinMax(eConfigUInt32Values index, char const* fieldname, uint32 defvalue, uint32 minvalue, uint32 maxvalue); void setConfigMinMax(eConfigInt32Values index, char const* fieldname, int32 defvalue, int32 minvalue, int32 maxvalue); void setConfigMinMax(eConfigFloatValues index, char const* fieldname, float defvalue, float minvalue, float maxvalue); bool configNoReload(bool reload, eConfigUInt32Values index, char const* fieldname, uint32 defvalue); bool configNoReload(bool reload, eConfigInt32Values index, char const* fieldname, int32 defvalue); bool configNoReload(bool reload, eConfigFloatValues index, char const* fieldname, float defvalue); bool configNoReload(bool reload, eConfigBoolValues index, char const* fieldname, bool defvalue); static volatile bool m_stopEvent; static uint8 m_ExitCode; uint32 m_ShutdownTimer; uint32 m_ShutdownMask; time_t m_startTime; time_t m_gameTime; IntervalTimer m_timers[WUPDATE_COUNT]; uint32 mail_timer; uint32 mail_timer_expires; uint32 m_updateTime; typedef UNORDERED_MAP<uint32, Weather*> WeatherMap; WeatherMap m_weathers; typedef UNORDERED_MAP<uint32, WorldSession*> SessionMap; SessionMap m_sessions; uint32 m_maxActiveSessionCount; uint32 m_maxQueuedSessionCount; uint32 m_configUint32Values[CONFIG_UINT32_VALUE_COUNT]; int32 m_configInt32Values[CONFIG_INT32_VALUE_COUNT]; float m_configFloatValues[CONFIG_FLOAT_VALUE_COUNT]; bool m_configBoolValues[CONFIG_BOOL_VALUE_COUNT]; int32 m_playerLimit; LocaleConstant m_defaultDbcLocale; // from config for one from loaded DBC locales uint32 m_availableDbcLocaleMask; // by loaded DBC void DetectDBCLang(); bool m_allowMovement; std::string m_motd; std::string m_dataPath; // for max speed access static float m_MaxVisibleDistanceOnContinents; static float m_MaxVisibleDistanceInInstances; static float m_MaxVisibleDistanceInBGArenas; static float m_MaxVisibleDistanceInFlight; static float m_VisibleUnitGreyDistance; static float m_VisibleObjectGreyDistance; static float m_relocation_lower_limit_sq; static uint32 m_relocation_ai_notify_delay; // CLI command holder to be thread safe ACE_Based::LockedQueue<CliCommandHolder*,ACE_Thread_Mutex> cliCmdQueue; // next daily quests reset time time_t m_NextDailyQuestReset; time_t m_NextWeeklyQuestReset; time_t m_NextMonthlyQuestReset; time_t m_NextRandomBGReset; //Player Queue Queue m_QueuedSessions; //sessions that are added async void AddSession_(WorldSession* s); ACE_Based::LockedQueue<WorldSession*, ACE_Thread_Mutex> addSessQueue; //used versions std::string m_DBVersion; std::string m_CreatureEventAIVersion; // World locking for global (not-in-map) objects. mutable ObjectLockType i_lock[MAP_LOCK_TYPE_MAX]; // reset duel system std::set<uint32> areaEnabledIds; //set of areaIds where is enabled the Duel reset system }; extern uint32 realmID; #define sWorld MaNGOS::Singleton<World>::Instance() #endif /// @}
Java
<!DOCTYPE html> <html> <!-- Mirrored from www.w3schools.com/html/tryhtml_images_map.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:08:51 GMT --> <body> <p>Click on the sun or on one of the planets to watch it closer:</p> <img src="planets.gif" alt="Planets" usemap="#planetmap" style="width:145px;height:126px"> <map name="planetmap"> <area shape="rect" coords="0,0,82,126" alt="Sun" href="sun.html"> <area shape="circle" coords="90,58,3" alt="Mercury" href="mercur.html"> <area shape="circle" coords="124,58,8" alt="Venus" href="venus.html"> </map> </body> <!-- Mirrored from www.w3schools.com/html/tryhtml_images_map.htm by HTTrack Website Copier/3.x [XR&CO'2014], Fri, 23 Jan 2015 08:08:51 GMT --> </html>
Java
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> <meta name="categories" content="docking"> <meta name="profile" content="!Elements"> <meta name="product" content="Glide"> <title>Glide &mdash; Edit Feature Dialog Box</title> <link rel="stylesheet" type="text/css" href="../support/help.css"> </head> <script type="text/javascript"> function setTitle() { top.document.title = document.title + " - " + parent.parent.WINDOW_TITLE; } </script> <body onload="setTitle();"> <table border=0 cellspacing=0 bgcolor=#dcdcdc width=100%> <tr><td> <p><img src="../support/schrodinger_logo.gif" border=0 alt="" align="left" vspace=5 hspace=5 /></p> </td></tr> <tr><td> <h1 class=title><span class="glide">Glide &mdash; Edit Feature Dialog Box</span></h1> </td></tr> </table> <ul> <li><a href="#summary">Summary</a></li> <li><a href="#opening">Opening the <span class="GUI">Edit Feature</span> Dialog Box</a></li> <li><a href="#using">Using the <span class="GUI">Edit Feature</span> Dialog Box</a></li> <li><a href="#features"><span class="GUI">Edit Feature</span> Dialog Box Features</a></li> <li><a href="#links">Related Topics</a></li> </ul> <a name="summary"></a> <h2>Summary</h2> <p>The <span class="GUI">Edit Features</span> dialog box allows you to edit the features that the ligand must match. Features are defined in terms of SMARTS patterns. You can add patterns, edit and delete custom patterns, and you can exclude patterns in a feature definition.</p> <a name="opening"></a> <h2>Opening the Edit Feature Dialog Box</h2> <p>To open the <span class="GUI">Edit Feature</span> dialog box</p> <ul> <li><p>Click <span class="GUI">Edit Feature</span> in the <span class="GUI">Constraints</span> tab of the Glide <span class="GUI">Ligand Docking</span> panel.</p></li> </ul> <a name="using"></a> <h2>Using the Edit Feature Dialog Box</h2> <h3>Loading and Saving Feature Sets</h3> <p>Built-in feature sets are stored with the distribution. <p>You can import a feature set for the selected constraint from a file by clicking <span class="GUI">Import</span>, and navigating to the feature file. When you import a feature set, the definitions of all features are replaced, not just the selected feature. The feature definitions are replaced only for the selected constraint, but are replaced for that constraint in all groups. <p>Feature sets can be saved to a file by clicking <span class="GUI">Export</span>, and specifying the file location in the file selector that is displayed. </p> <p>The patterns that define a feature are displayed in the <span class="GUI">Pattern list</span> table when you choose the feature from the <span class="GUI">Feature</span> option menu.</p> <h3>Adding, Editing, and Deleting Patterns</h3> <p>If the patterns in a given feature definition do not cover all the functional groups that you want to include in the feature, you can add extra patterns. To add a new SMARTS pattern, click the table row above which you want the pattern to be inserted, then click <span class="GUI">New</span>. In the <a href="new_pattern.html"><span class="GUI">New Pattern</span> dialog box</a>, you can enter a SMARTS pattern and enter the atom numbers in the pattern that must satisfy the constraint.</p> <p>To edit a pattern, select the table row for the pattern, then click <span class="GUI">Edit</span>. In the <a href="edit_pattern.html"><span class="GUI">Edit Pattern</span> dialog box</a>, you can modify the SMARTS pattern and the atoms in the pattern that must match.</p> <p>To delete a pattern, select the table row for the pattern, then click <span class="GUI">Delete</span>.</p> <h3>Setting the Status of Patterns</h3> <p>Matching of patterns to ligand structures is done in the order specified in the <span class="GUI">Pattern list</span> table. You cannot change the order of the patterns once they are in the table, so you must add new patterns in the appropriate place. If you want to move patterns, you must delete them then add them back in the appropriate place. Excluded patterns are processed first, regardless of their position in the table.</p> <p>If you want to ensure that certain functional groups are not matched, you can select the check box in the <span class="GUI">Exclude</span> column for the pattern for that group. For example, you might want to exclude a carboxylic acid group from being considered as a hydrogen bond donor, because it will be ionized under physiological conditions.</p> <h3>Visualizing Patterns</h3> <p>If you want to see a pattern for a given ligand or group of ligands, you can select the check box in the <span class="GUI">Mark</span> column for the pattern. Any occurrences of the pattern are marked in the Workspace.</p> <p>You can display markers for more than one pattern, but the markers do not distinguish between patterns. If you want to see the atoms and bonds as well as the markers, select <span class="GUI">Apply marker offset</span>.</p> <a name="features"></a> <h2>Edit Feature Dialog Box Features</h2> <ul> <li><a href="#feature1"><span class="GUI">Feature</span> controls</a></li> <li><a href="#feature2"><span class="GUI">Pattern list</span> table</a></li> <li><a href="#feature3">Pattern editing buttons</a></li> </ul> <a name="feature1"></a> <h3>Feature Controls</h3> <p>This section has three controls:</p> <dl> <dt><span class="GUI">Feature</span> option menu</dt> <dd><p>Select a feature type. The selected feature type is assigned to the constraint and appears in the <span class="GUI">Available constraints</span> table of the <span class="GUI">Constraints</span> tab. The patterns that define the selected feature type are listed in the <span class="GUI">Pattern list</span> table. You must select a feature type to edit its definition. </p></dd> <dt><span class="GUI">Import</span> button</dt> <dd><p>Opens a file selector in which you can browse for feature files. </p></dd> <dt><span class="GUI">Export</span> button</dt> <dd><p>Opens a file selector in which you can browse to a location to write a feature file. </p></dd> </dl> <a name="feature2"></a> <h3>Pattern list table</h3> <p>The <span class="GUI">Pattern list</span> table lists all the patterns that are used to define the feature. You can only select one row at a time in the table, and the text fields are not editable. The table columns are described below. </p> <dl> <a name="feature2.1"></a> <dt><span class="GUI">Mark</span></dt> <dd><p>Column of check boxes. Selecting a check box marks the pattern on any structures that are displayed in the Workspace. </p></dd> <a name="feature2.2"></a> <dt><span class="GUI">Pattern</span></dt> <dd><p>Pattern definition. The definitions are SMARTS strings. </p></dd> <a name="feature2.5"></a> <dt><span class="GUI">Atoms</span></dt> <dd><p>The list of atoms that must satisfy the constraint, numbered according to the SMARTS string. </p></dd> <a name="feature2.6"></a> <dt><span class="GUI">Exclude</span></dt> <dd><p>Column of check boxes. If a check box is selected, atoms in a ligand are matched by other patterns only if they do not match this pattern. This is essentially a NOT operator. Excluded patterns are processed before other patterns. </p></dd> </dl> <a name="feature3"></a> <h3>Pattern Editing Buttons</h3> <dl> <a name="feature3.1"></a> <dt><span class="GUI">New</span> button</dt> <dd><p>Opens the <a href="new_pattern.html"><span class="GUI">New Pattern</span> dialog box</a>, in which you can enter a SMARTS pattern and choose the atoms that are used to match the ligand feature. </p></dd> <a name="feature3.2"></a> <dt><span class="GUI">Edit</span> button</dt> <dd><p>Opens the <a href="edit_pattern.html"><span class="GUI">Edit Pattern</span> dialog box</a>, in which you can edit the selected pattern. </p></dd> <a name="feature3.3"></a> <dt><span class="GUI">Delete</span> button</dt> <dd><p>Deletes the selected pattern. </p></dd> </dl> <a name="links"></a> <h2>Related Topics</h2> <ul> <li><a href="dock_constraints.html">Glide Docking Constraints Tab</a></li> <li><a href="new_pattern.html">Glide New Pattern Dialog Box</a></li> <li><a href="edit_pattern.html">Glide Edit Pattern Dialog Box</a></li> </ul> <hr /> <table width="100%"> <td><p class="small"><a href="../support/legal_notice.html" target="LegalNoticeWindow">Legal Notice</a></p></td> <td> <table align="right"> <td><p class="small"> File: glide/edit_feature.html<br /> Last updated: 10 Jan 2012 </p></td> </table> </td> </table> </body> </html>
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="style/style.css"> <link rel="stylesheet" type="text/css" media="only screen and (min-device-width: 360px)" href="style-compact.css"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-74917613-1', 'auto'); ga('send', 'pageview'); </script> </head> <body> <div class="dungeonBackgroundContainer"> <img class="dungeonFrame" src="dungeon_battle_collection/baseDungeonFrame.png" /> <img class="dungeonImage" src="dungeon_battle_collection/dungeon_battle_80007.jpg" /> </div> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_3.png" /> </div> <div class="speakerName"><a href="http://i.imgur.com/ZLwSPY7.png">Avani</a></div> <div class="speakerMessage">This place looks...different from when I last came here. </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_3.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">It seems like even sacred places like this one aren’t spared from Azurai’s reign…</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_3.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">And where could Allanon be? Although I would rather not see him, we need his help now more than ever.</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80041_1.png" /> </div> <div class="speakerName"><a href="http://i.imgur.com/4uoeaL0.png">Nyami</a></div> <div class="speakerMessage"><div style="display:inline;font-size:12px">He...must have found...something fun.</div></div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_0.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">I’m pretty sure he’s found more than just something fun. </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_0.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">An entire Morokai city without anyone to stop him...it must be like a giant playground for him. </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_3.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">He’d better not forget the reason we’re here in the first place…</div> </div> <br> <div class="dialogueSeparator" > <img src="navi_chara_collection/dialogueSeparator.png" align="middle" /> </div> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/blank.png" /> </div> <div class="speakerName">Mysterious Voice</div> <div class="speakerMessage">Hahaha… Why am I not surprised?</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/blank.png" /> </div> <div class="speakerName">Mysterious Voice</div> <div class="speakerMessage">Even after all these years that fool hasn’t changed one bit.</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_2.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">The voice from within the sandstorm…</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_2.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage">Where is Ezra! <div style="display:inline;font-size:15px">SHOW YOURSELF!</div></div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80038_2.png" /> </div> <div class="speakerName">Avani</div> <div class="speakerMessage"><div style="display:inline;font-size:15px">You will pay for what you have done!</div></div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80041_2.png" /> </div> <div class="speakerName">Nyami</div> <div class="speakerMessage">*Hissss*!!!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/blank.png" /> </div> <div class="speakerName">Mysterious Voice</div> <div class="speakerMessage">Foolish child… </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/blank.png" /> </div> <div class="speakerName">Mysterious Voice</div> <div class="speakerMessage">very well then. </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80047.png" /> </div> <div class="speakerName"><a href="http://i.imgur.com/pm6hOA7.png">Aranvis</a></div> <div class="speakerMessage">Allow me to introduce myself.</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80047.png" /> </div> <div class="speakerName">Aranvis</div> <div class="speakerMessage">High Inquisitor Aranvis, at your service. </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80047.png" /> </div> <div class="speakerName">Aranvis</div> <div class="speakerMessage">I hope you can entertain me. </div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="navi_chara_collection/navi_chara80047.png" /> </div> <div class="speakerName">Aranvis</div> <div class="speakerMessage">Now let me see what you’re capable of!</div> </div> <br> <div class="dialogueSeparator" > <img src="navi_chara_collection/dialogueSeparator.png" align="middle" /> </div> </body> </html> <!-- contact me at reddit /u/blackrobe199 -->
Java
/*************************************************************************** FluxIntegral.cpp - Integrates Lx dx L (x1, x2) = int^x2_x1 dx Lx ------------------- begin : December 2006 copyright : (C) 2006 by Maurice Leutenegger email : maurice@astro.columbia.edu ***************************************************************************/ /* 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 "FluxIntegral.h" #include <iostream> using namespace std; FluxIntegral::FluxIntegral (Lx* lx) : Integral (), itsLx (lx), itsXKink (itsLx->getXKink ()), itsXOcc (itsLx->getXOcc ()) { return; } FluxIntegral::~FluxIntegral () { return; } double FluxIntegral::integrand (double x) { return itsLx->getLx (x); } /* Integrates Lx over [y,x]. Will mostly be called with y < x, but if not, it swaps them. Note: is there code somewhere else to deal with an unresolved profile? (The code below only deals with the case where it's known to be completely unresolved in advance.) */ Real FluxIntegral::getFlux (Real x, Real y) { if (compare (y, x) == 1) { Real temp = x; x = y; y = temp; } bool xInRange = (compare (fabs(x), 1.) == -1); bool yInRange = (compare (fabs(y), 1.) == -1); if (!xInRange && !yInRange) return 0.; if (!xInRange) x = 1.; if (!yInRange) y = -1.; if ((compare (itsXKink, y) == 1) && (compare (itsXKink, x) == -1)) { return (qag (y, itsXKink) + qag (itsXKink, x)); } if ((compare (itsXOcc, y) == 1) && (compare (itsXOcc, x) == -1)) { return (qag (y, itsXOcc) + qag (itsXOcc, x)); } return qag (y, x); /* The kink coordinate gives the point at which many profiles have a kink at negative x on the blue side of the profile. This kink occurs at the x where the cutoff u0 starts to become important. (At zero optical depth, the profile becomes flat at this point). The "occ" coordinate gives the point in x where occultation begins to become important. I choose to place this not at p = 1 but at p = 1 + e, to avoid edge effects. */ /* if (xInRange && yInRange) { return qag (y, x); } else if (xInRange && !yInRange) { return qag (-1., x); } else if (!xInRange && yInRange) { return qag (y, 1.); } else { return 0.; } */ } // Integrate on x in [-1:1] Real FluxIntegral::getFlux () { return (qag (-1., itsXKink) + qag (itsXKink, itsXOcc) + qag (itsXOcc, 1.)); }
Java
<?php session_start(); ?> <!DOCTYPE html> <!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]--> <!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]--> <!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]--> <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]--> <head> <title>Somali Taekwondo - About us</title> <?php include('inc/metatags.inc') ?> </head> <body> <!--[if lt IE 7]> <p class="chromeframe">You are using an <strong>outdated</strong> browser. Please <a href="http://browsehappy.com/">upgrade your browser</a> or <a href="http://www.google.com/chromeframe/?redirect=true">activate Google Chrome Frame</a> to improve your experience.</p> <![endif]--> <header> <div class="navbar-wrapper"> <!-- Wrap the .navbar in .container to center it within the absolutely positioned parent. --> <div class="container"> <div class="navbar navbar-inverse"> <div class="navbar-inner"> <a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </a> <a class="brand" href="/home"><img src="img/logo.png" alt="gotkd" width="150" /></a> <?php include('inc/nav.inc') ?> </div> </div> </div> </div> </header> <section id="container" class="container aboutus"> <br /> <br /> <br /> <div class="page-header"> <h1>About us</h1> </div> <div class="row-fluid media"> <div class="span7"> <p>Having its headquarters in Switzerland, Somali Taekwondo was established in 2012 and is responsible for all aspects of Somali National Team around the world helping athletes achieve their full potential, and preparing them for major competition, as well as selecting athlete to compete at African Championship, World Championships, and of course the Olympic Games.</p> <p>After emerging from decades of civil war and social upheaval, Somali Taekwondo use the sport to promote a better image of Somali and helping the country climb out of poverty.</p> <p>Somali Taekwondo use funds provided from donations of people from all around the world to promote Somali image, giving an assistance to the sport, focusing on improving opportunities for the somalian athletes participate in many tournament, giving a hope for the country.</p> <p>Every donation will be indented for the developing of each somalian athlete giving the oportunity to participate to every tournement recognized by the World Taekwondo Federation and the Somali Olympic Committee. Donations that will be more than needed will be given to an ONG that helps against the somali poverty.</p> </div> <div class="span5 thumbnail"> <img src="https://fbcdn-sphotos-a-a.akamaihd.net/hphotos-ak-ash3/942859_162735743901850_517590466_n.jpg" alt="" /> </div> </div> <?php include('inc/footer.inc') ?> </section> <!-- /container --> <?php include('inc/js.inc') ?> </body> </html>
Java
<?php namespace Drush\Boot; use Consolidation\AnnotatedCommand\AnnotationData; use Drush\Log\DrushLog; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Drupal\Core\DrupalKernel; use Drush\Drush; use Drush\Drupal\DrushServiceModifier; use Drush\Log\LogLevel; class DrupalBoot8 extends DrupalBoot implements AutoloaderAwareInterface { use AutoloaderAwareTrait; /** * @var \Drupal\Core\DrupalKernelInterface */ protected $kernel; /** * @var \Symfony\Component\HttpFoundation\Request */ protected $request; /** * @return \Symfony\Component\HttpFoundation\Request */ public function getRequest() { return $this->request; } /** * @param \Symfony\Component\HttpFoundation\Request $request */ public function setRequest($request) { $this->request = $request; } /** * @return \Drupal\Core\DrupalKernelInterface */ public function getKernel() { return $this->kernel; } public function validRoot($path) { if (!empty($path) && is_dir($path) && file_exists($path . '/autoload.php')) { // Additional check for the presence of core/composer.json to // grant it is not a Drupal 7 site with a base folder named "core". $candidate = 'core/includes/common.inc'; if (file_exists($path . '/' . $candidate) && file_exists($path . '/core/core.services.yml')) { if (file_exists($path . '/core/misc/drupal.js') || file_exists($path . '/core/assets/js/drupal.js')) { return $candidate; } } } } public function getVersion($drupal_root) { // Are the class constants available? if (!$this->hasAutoloader()) { throw new \Exception('Cannot access Drupal 8 class constants - Drupal autoloader not loaded yet.'); } // Drush depends on bootstrap being loaded at this point. require_once $drupal_root .'/core/includes/bootstrap.inc'; if (defined('\Drupal::VERSION')) { return \Drupal::VERSION; } } public function confPath($require_settings = true, $reset = false) { if (\Drupal::hasService('kernel')) { $site_path = \Drupal::service('kernel')->getSitePath(); } if (!isset($site_path) || empty($site_path)) { $site_path = DrupalKernel::findSitePath($this->getRequest(), $require_settings); } return $site_path; } public function addLogger() { // Provide a logger which sends // output to drush_log(). This should catch every message logged through every // channel. $container = \Drupal::getContainer(); $parser = $container->get('logger.log_message_parser'); $drushLogger = Drush::logger(); $logger = new DrushLog($parser, $drushLogger); $container->get('logger.factory')->addLogger($logger); } public function bootstrapDrupalCore($drupal_root) { $core = DRUPAL_ROOT . '/core'; return $core; } public function bootstrapDrupalSiteValidate() { parent::bootstrapDrupalSiteValidate(); // Normalize URI. $uri = rtrim($this->uri, '/') . '/'; $parsed_url = parse_url($uri); // Account for users who omit the http:// prefix. if (empty($parsed_url['scheme'])) { $this->uri = 'http://' . $this->uri; $parsed_url = parse_url($this->uri); } $server = [ 'SCRIPT_FILENAME' => getcwd() . '/index.php', 'SCRIPT_NAME' => isset($parsed_url['path']) ? $parsed_url['path'] . 'index.php' : '/index.php', ]; $request = Request::create($this->uri, 'GET', [], [], [], $server); $this->setRequest($request); $confPath = drush_bootstrap_value('confPath', $this->confPath(true, true)); drush_bootstrap_value('site', $request->getHttpHost()); return true; } public function bootstrapDrupalConfigurationValidate() { $conf_file = $this->confPath() . '/settings.php'; if (!file_exists($conf_file)) { $msg = dt("Could not find a Drupal settings.php file at !file.", ['!file' => $conf_file]); $this->logger->debug($msg); // Cant do this because site:install deliberately bootstraps to configure without a settings.php file. // return drush_set_error($msg); } return true; } public function bootstrapDrupalDatabaseValidate() { return parent::bootstrapDrupalDatabaseValidate() && $this->bootstrapDrupalDatabaseHasTable('key_value'); } public function bootstrapDrupalDatabase() { // D8 omits this bootstrap level as nothing special needs to be done. parent::bootstrapDrupalDatabase(); } public function bootstrapDrupalConfiguration(AnnotationData $annotationData = null) { // Default to the standard kernel. $kernel = Kernels::DRUPAL; if (!empty($annotationData)) { $kernel = $annotationData->get('kernel', Kernels::DRUPAL); } $classloader = $this->autoloader(); $request = $this->getRequest(); $kernel_factory = Kernels::getKernelFactory($kernel); $allow_dumping = $kernel !== Kernels::UPDATE; /** @var \Drupal\Core\DrupalKernelInterface kernel */ $this->kernel = $kernel_factory($request, $classloader, 'prod', $allow_dumping); // Include Drush services in the container. // @see Drush\Drupal\DrupalKernel::addServiceModifier() $this->kernel->addServiceModifier(new DrushServiceModifier()); // Unset drupal error handler and restore Drush's one. restore_error_handler(); // Disable automated cron if the module is enabled. $GLOBALS['config']['automated_cron.settings']['interval'] = 0; parent::bootstrapDrupalConfiguration(); } public function bootstrapDrupalFull() { $this->logger->debug(dt('Start bootstrap of the Drupal Kernel.')); $this->kernel->boot(); $this->kernel->prepareLegacyRequest($this->getRequest()); $this->logger->debug(dt('Finished bootstrap of the Drupal Kernel.')); parent::bootstrapDrupalFull(); $this->addLogger(); // Get a list of the modules to ignore $ignored_modules = drush_get_option_list('ignored-modules', []); $application = Drush::getApplication(); $runner = Drush::runner(); // We have to get the service command list from the container, because // it is constructed in an indirect way during the container initialization. // The upshot is that the list of console commands is not available // until after $kernel->boot() is called. $container = \Drupal::getContainer(); // Set the command info alterers. if ($container->has(DrushServiceModifier::DRUSH_COMMAND_INFO_ALTERER_SERVICES)) { $serviceCommandInfoAltererlist = $container->get(DrushServiceModifier::DRUSH_COMMAND_INFO_ALTERER_SERVICES); $commandFactory = Drush::commandFactory(); foreach ($serviceCommandInfoAltererlist->getCommandList() as $altererHandler) { $commandFactory->addCommandInfoAlterer($altererHandler); $this->logger->debug(dt('Commands are potentially altered in !class.', ['!class' => get_class($altererHandler)])); } } $serviceCommandlist = $container->get(DrushServiceModifier::DRUSH_CONSOLE_SERVICES); if ($container->has(DrushServiceModifier::DRUSH_CONSOLE_SERVICES)) { foreach ($serviceCommandlist->getCommandList() as $command) { if (!$this->commandIgnored($command, $ignored_modules)) { $this->inflect($command); $this->logger->log(LogLevel::DEBUG_NOTIFY, dt('Add a command: !name', ['!name' => $command->getName()])); $application->add($command); } } } // Do the same thing with the annotation commands. if ($container->has(DrushServiceModifier::DRUSH_COMMAND_SERVICES)) { $serviceCommandlist = $container->get(DrushServiceModifier::DRUSH_COMMAND_SERVICES); foreach ($serviceCommandlist->getCommandList() as $commandHandler) { if (!$this->commandIgnored($commandHandler, $ignored_modules)) { $this->inflect($commandHandler); $this->logger->log(LogLevel::DEBUG_NOTIFY, dt('Add a commandfile class: !name', ['!name' => get_class($commandHandler)])); $runner->registerCommandClass($application, $commandHandler); } } } } public function commandIgnored($command, $ignored_modules) { if (empty($ignored_modules)) { return false; } $ignored_regex = '#\\\\(' . implode('|', $ignored_modules) . ')\\\\#'; $class = new \ReflectionClass($command); $commandNamespace = $class->getNamespaceName(); return preg_match($ignored_regex, $commandNamespace); } /** * {@inheritdoc} */ public function terminate() { parent::terminate(); if ($this->kernel) { $response = Response::create(''); $this->kernel->terminate($this->getRequest(), $response); } } }
Java
/* ** rq_xml_util.h ** ** Written by Brett Hutley - brett@hutley.net ** ** Copyright (C) 2009 Brett Hutley ** ** This file is part of the Risk Quantify Library ** ** Risk Quantify 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. ** ** Risk Quantify 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 Risk Quantify; if not, write to the Free ** Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef rq_xml_util_h #define rq_xml_util_h #ifdef __cplusplus extern "C" { #if 0 } // purely to not screw up my indenting... #endif #endif #include "rq_stream.h" /** Get the start and end position of a valid piece of XML. */ RQ_EXPORT rq_error_code rq_xml_util_get_start_end_pos(rq_stream_t stream, const char *tag, long *start_pos, long *end_pos); #ifdef __cplusplus #if 0 { // purely to not screw up my indenting... #endif }; #endif #endif
Java
<!DOCTYPE html> <html class=""> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width" /> <link rel="stylesheet" href="/css/styles.css?0" media="all" /> <link rel="stylesheet" href="/css/demo.css?0" media="all" /> <!-- Begin Pattern Lab (Required for Pattern Lab to run properly) --> <!-- never cache patterns --> <meta http-equiv="cache-control" content="max-age=0" /> <meta http-equiv="cache-control" content="no-cache" /> <meta http-equiv="expires" content="0" /> <meta http-equiv="expires" content="Tue, 01 Jan 1980 1:00:00 GMT" /> <meta http-equiv="pragma" content="no-cache" /> <link rel="stylesheet" href="../../styleguide/css/styleguide.min.css?0" media="all"> <link rel="stylesheet" href="../../styleguide/css/prism-typeahead.min.css?0" media="all" /> <!-- End Pattern Lab --> <link rel="stylesheet" href="/css/styleguide.css?0" media="all" /> </head> <body class=""> <a class="button is-secondary is-light " href="#">Knap titel</a> <!--DO NOT REMOVE--> <script type="text/json" id="sg-pattern-data-footer" class="sg-pattern-data"> {"cssEnabled":false,"lineage":[],"lineageR":[],"patternBreadcrumb":{"patternType":"elements","patternSubtype":"buttons"},"patternDesc":"","patternExtension":"twig","patternName":"button secondary light","patternPartial":"elements-button-secondary-light","patternState":"","extraOutput":[]} </script> <script> /*! * scriptLoader - v0.1 * * Copyright (c) 2014 Dave Olsen, http://dmolsen.com * Licensed under the MIT license * */ var scriptLoader = { run: function(js,cb,target) { var s = document.getElementById(target+'-'+cb); for (var i = 0; i < js.length; i++) { var src = (typeof js[i] != 'string') ? js[i].src : js[i]; var c = document.createElement('script'); c.src = '../../'+src+'?'+cb; if (typeof js[i] != 'string') { if (js[i].dep !== undefined) { c.onload = function(dep,cb,target) { return function() { scriptLoader.run(dep,cb,target); } }(js[i].dep,cb,target); } } s.parentNode.insertBefore(c,s); } } } </script> <script id="pl-js-polyfill-insert-0"> (function() { if (self != top) { var cb = '0'; var js = []; if (typeof document !== 'undefined' && !('classList' in document.documentElement)) { js.push('styleguide/bower_components/classList.min.js'); } scriptLoader.run(js,cb,'pl-js-polyfill-insert'); } })(); </script> <script id="pl-js-insert-0"> (function() { if (self != top) { var cb = '0'; var js = [ { 'src': 'styleguide/bower_components/jwerty.min.js', 'dep': [ 'styleguide/js/patternlab-pattern.min.js' ] } ]; scriptLoader.run(js,cb,'pl-js-insert'); } })(); </script> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script> <script src="/assets/js/hamburger-menu.js"></script> <script src="/assets/js/menu.js"></script> <script src="/assets/js/filters.js"></script> <script src="/assets/js/delete-activity.js"></script> <script src="/assets/js/floating-help.js"></script> <script src="/assets/js/image-upload.js"></script> </body> </html>
Java
// _________ __ __ // / _____// |_____________ _/ |______ ____ __ __ ______ // \_____ \\ __\_ __ \__ \\ __\__ \ / ___\| | \/ ___/ // / \| | | | \// __ \| | / __ \_/ /_/ > | /\___ | // /_______ /|__| |__| (____ /__| (____ /\___ /|____//____ > // \/ \/ \//_____/ \/ // ______________________ ______________________ // T H E W A R B E G I N S // Stratagus - A free fantasy real time strategy game engine // /**@name mainscr.cpp - The main screen. */ // // (c) Copyright 1998-2007 by Lutz Sammer, Valery Shchedrin, and // Jimmy Salmon // // 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; only 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. // // 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. // //@{ /*---------------------------------------------------------------------------- -- Includes ----------------------------------------------------------------------------*/ #include "stratagus.h" #include "action/action_built.h" #include "action/action_research.h" #include "action/action_train.h" #include "action/action_upgradeto.h" #include "font.h" #include "icons.h" #include "interface.h" #include "map.h" #include "menus.h" #include "network.h" #include "player.h" #include "settings.h" #include "sound.h" #include "spells.h" #include "translate.h" #include "trigger.h" #include "ui/contenttype.h" #include "ui.h" #include "unit.h" #include "unitsound.h" #include "unittype.h" #include "upgrade.h" #include "video.h" #ifdef DEBUG #include "../ai/ai_local.h" #endif #include <sstream> /*---------------------------------------------------------------------------- -- UI BUTTONS ----------------------------------------------------------------------------*/ static void DrawMenuButtonArea_noNetwork() { if (UI.MenuButton.X != -1) { DrawUIButton(UI.MenuButton.Style, (ButtonAreaUnderCursor == ButtonAreaMenu && ButtonUnderCursor == ButtonUnderMenu ? MI_FLAGS_ACTIVE : 0) | (GameMenuButtonClicked ? MI_FLAGS_CLICKED : 0), UI.MenuButton.X, UI.MenuButton.Y, UI.MenuButton.Text); } } static void DrawMenuButtonArea_Network() { if (UI.NetworkMenuButton.X != -1) { DrawUIButton(UI.NetworkMenuButton.Style, (ButtonAreaUnderCursor == ButtonAreaMenu && ButtonUnderCursor == ButtonUnderNetworkMenu ? MI_FLAGS_ACTIVE : 0) | (GameMenuButtonClicked ? MI_FLAGS_CLICKED : 0), UI.NetworkMenuButton.X, UI.NetworkMenuButton.Y, UI.NetworkMenuButton.Text); } if (UI.NetworkDiplomacyButton.X != -1) { DrawUIButton(UI.NetworkDiplomacyButton.Style, (ButtonAreaUnderCursor == ButtonAreaMenu && ButtonUnderCursor == ButtonUnderNetworkDiplomacy ? MI_FLAGS_ACTIVE : 0) | (GameDiplomacyButtonClicked ? MI_FLAGS_CLICKED : 0), UI.NetworkDiplomacyButton.X, UI.NetworkDiplomacyButton.Y, UI.NetworkDiplomacyButton.Text); } } /** ** Draw menu button area. */ void DrawMenuButtonArea() { if (!IsNetworkGame()) { DrawMenuButtonArea_noNetwork(); } else { DrawMenuButtonArea_Network(); } } void DrawUserDefinedButtons() { for (size_t i = 0; i < UI.UserButtons.size(); ++i) { const CUIUserButton &button = UI.UserButtons[i]; if (button.Button.X != -1) { DrawUIButton(button.Button.Style, (ButtonAreaUnderCursor == ButtonAreaUser && size_t(ButtonUnderCursor) == i ? MI_FLAGS_ACTIVE : 0) | (button.Clicked ? MI_FLAGS_CLICKED : 0), button.Button.X, button.Button.Y, button.Button.Text); } } } /*---------------------------------------------------------------------------- -- Icons ----------------------------------------------------------------------------*/ /** ** Draw life bar of a unit at x,y. ** Placed under icons on top-panel. ** ** @param unit Pointer to unit. ** @param x Screen X position of icon ** @param y Screen Y position of icon */ static void UiDrawLifeBar(const CUnit &unit, int x, int y) { // FIXME: add icon borders int hBar, hAll; if (Preference.IconsShift) { hBar = 6; hAll = 10; } else { hBar = 5; hAll = 7; } y += unit.Type->Icon.Icon->G->Height; Video.FillRectangleClip(ColorBlack, x - 4, y + 2, unit.Type->Icon.Icon->G->Width + 8, hAll); if (unit.Variable[HP_INDEX].Value) { Uint32 color; int f = (100 * unit.Variable[HP_INDEX].Value) / unit.Variable[HP_INDEX].Max; if (f > 75) { color = ColorDarkGreen; } else if (f > 50) { color = ColorYellow; } else if (f > 25) { color = ColorOrange; } else { color = ColorRed; } f = (f * (unit.Type->Icon.Icon->G->Width + 6)) / 100; Video.FillRectangleClip(color, x - 2, y + 4, f > 1 ? f - 2 : 0, hBar); } } /** ** Draw mana bar of a unit at x,y. ** Placed under icons on top-panel. ** ** @param unit Pointer to unit. ** @param x Screen X position of icon ** @param y Screen Y position of icon */ static void UiDrawManaBar(const CUnit &unit, int x, int y) { // FIXME: add icon borders y += unit.Type->Icon.Icon->G->Height; Video.FillRectangleClip(ColorBlack, x, y + 3, unit.Type->Icon.Icon->G->Width, 4); if (unit.Stats->Variables[MANA_INDEX].Max) { int f = (100 * unit.Variable[MANA_INDEX].Value) / unit.Variable[MANA_INDEX].Max; f = (f * (unit.Type->Icon.Icon->G->Width)) / 100; Video.FillRectangleClip(ColorBlue, x + 1, y + 3 + 1, f, 2); } } /** ** Tell if we can show the content. ** verify each sub condition for that. ** ** @param condition condition to verify. ** @param unit unit that certain condition can refer. ** ** @return 0 if we can't show the content, else 1. */ static bool CanShowContent(const ConditionPanel *condition, const CUnit &unit) { if (!condition) { return true; } if ((condition->ShowOnlySelected && !unit.Selected) || (unit.Player->Type == PlayerNeutral && condition->HideNeutral) || (ThisPlayer->IsEnemy(unit) && !condition->ShowOpponent) || (ThisPlayer->IsAllied(unit) && (unit.Player != ThisPlayer) && condition->HideAllied)) { return false; } if (condition->BoolFlags && !unit.Type->CheckUserBoolFlags(condition->BoolFlags)) { return false; } if (condition->Variables) { for (unsigned int i = 0; i < UnitTypeVar.GetNumberVariable(); ++i) { if (condition->Variables[i] != CONDITION_TRUE) { if ((condition->Variables[i] == CONDITION_ONLY) ^ unit.Variable[i].Enable) { return false; } } } } return true; } enum UStrIntType { USTRINT_STR, USTRINT_INT }; struct UStrInt { union {const char *s; int i;}; UStrIntType type; }; /** ** Return the value corresponding. ** ** @param unit Unit. ** @param index Index of the variable. ** @param e Component of the variable. ** @param t Which var use (0:unit, 1:Type, 2:Stats) ** ** @return Value corresponding */ UStrInt GetComponent(const CUnit &unit, int index, EnumVariable e, int t) { UStrInt val; CVariable *var; Assert((unsigned int) index < UnitTypeVar.GetNumberVariable()); switch (t) { case 0: // Unit: var = &unit.Variable[index]; break; case 1: // Type: var = &unit.Type->DefaultStat.Variables[index]; break; case 2: // Stats: var = &unit.Stats->Variables[index]; break; default: DebugPrint("Bad value for GetComponent: t = %d" _C_ t); var = &unit.Variable[index]; break; } switch (e) { case VariableValue: val.type = USTRINT_INT; val.i = var->Value; break; case VariableMax: val.type = USTRINT_INT; val.i = var->Max; break; case VariableIncrease: val.type = USTRINT_INT; val.i = var->Increase; break; case VariableDiff: val.type = USTRINT_INT; val.i = var->Max - var->Value; break; case VariablePercent: Assert(unit.Variable[index].Max != 0); val.type = USTRINT_INT; val.i = 100 * var->Value / var->Max; break; case VariableName: if (index == GIVERESOURCE_INDEX) { val.type = USTRINT_STR; val.i = unit.Type->GivesResource; val.s = DefaultResourceNames[unit.Type->GivesResource].c_str(); } else if (index == CARRYRESOURCE_INDEX) { val.type = USTRINT_STR; val.i = unit.CurrentResource; val.s = DefaultResourceNames[unit.CurrentResource].c_str(); } else { val.type = USTRINT_STR; val.i = index; val.s = UnitTypeVar.VariableNameLookup[index]; } break; } return val; } UStrInt GetComponent(const CUnitType &type, int index, EnumVariable e, int t) { UStrInt val; CVariable *var; Assert((unsigned int) index < UnitTypeVar.GetNumberVariable()); switch (t) { case 0: // Unit: var = &type.Stats[ThisPlayer->Index].Variables[index];; break; case 1: // Type: var = &type.DefaultStat.Variables[index]; break; case 2: // Stats: var = &type.Stats[ThisPlayer->Index].Variables[index]; break; default: DebugPrint("Bad value for GetComponent: t = %d" _C_ t); var = &type.Stats[ThisPlayer->Index].Variables[index]; break; } switch (e) { case VariableValue: val.type = USTRINT_INT; val.i = var->Value; break; case VariableMax: val.type = USTRINT_INT; val.i = var->Max; break; case VariableIncrease: val.type = USTRINT_INT; val.i = var->Increase; break; case VariableDiff: val.type = USTRINT_INT; val.i = var->Max - var->Value; break; case VariablePercent: Assert(type.Stats[ThisPlayer->Index].Variables[index].Max != 0); val.type = USTRINT_INT; val.i = 100 * var->Value / var->Max; break; case VariableName: if (index == GIVERESOURCE_INDEX) { val.type = USTRINT_STR; val.i = type.GivesResource; val.s = DefaultResourceNames[type.GivesResource].c_str(); } else { val.type = USTRINT_STR; val.i = index; val.s = UnitTypeVar.VariableNameLookup[index]; } break; } return val; } static void DrawUnitInfo_Training(const CUnit &unit) { if (unit.Orders.size() == 1 || unit.Orders[1]->Action != UnitActionTrain) { if (!UI.SingleTrainingText.empty()) { CLabel label(*UI.SingleTrainingFont); label.Draw(UI.SingleTrainingTextX, UI.SingleTrainingTextY, UI.SingleTrainingText); } if (UI.SingleTrainingButton) { const COrder_Train &order = *static_cast<COrder_Train *>(unit.CurrentOrder()); CIcon &icon = *order.GetUnitType().Icon.Icon; const unsigned int flags = (ButtonAreaUnderCursor == ButtonAreaTraining && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.SingleTrainingButton->X, UI.SingleTrainingButton->Y); icon.DrawUnitIcon(*UI.SingleTrainingButton->Style, flags, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } } else { if (!UI.TrainingText.empty()) { CLabel label(*UI.TrainingFont); label.Draw(UI.TrainingTextX, UI.TrainingTextY, UI.TrainingText); } if (!UI.TrainingButtons.empty()) { for (size_t i = 0; i < unit.Orders.size() && i < UI.TrainingButtons.size(); ++i) { if (unit.Orders[i]->Action == UnitActionTrain) { const COrder_Train &order = *static_cast<COrder_Train *>(unit.Orders[i]); CIcon &icon = *order.GetUnitType().Icon.Icon; const int flag = (ButtonAreaUnderCursor == ButtonAreaTraining && static_cast<size_t>(ButtonUnderCursor) == i) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.TrainingButtons[i].X, UI.TrainingButtons[i].Y); icon.DrawUnitIcon(*UI.TrainingButtons[i].Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } } } } } static void DrawUnitInfo_portrait(const CUnit &unit) { const CUnitType &type = *unit.Type; #ifdef USE_MNG if (type.Portrait.Num) { type.Portrait.Mngs[type.Portrait.CurrMng]->Draw( UI.SingleSelectedButton->X, UI.SingleSelectedButton->Y); if (type.Portrait.Mngs[type.Portrait.CurrMng]->iteration == type.Portrait.NumIterations) { type.Portrait.Mngs[type.Portrait.CurrMng]->Reset(); // FIXME: should be configurable if (type.Portrait.CurrMng == 0) { type.Portrait.CurrMng = (SyncRand() % (type.Portrait.Num - 1)) + 1; type.Portrait.NumIterations = 1; } else { type.Portrait.CurrMng = 0; type.Portrait.NumIterations = SyncRand() % 16 + 1; } } return; } #endif if (UI.SingleSelectedButton) { const PixelPos pos(UI.SingleSelectedButton->X, UI.SingleSelectedButton->Y); const int flag = (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; type.Icon.Icon->DrawUnitIcon(*UI.SingleSelectedButton->Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } } static bool DrawUnitInfo_single_selection(const CUnit &unit) { switch (unit.CurrentAction()) { case UnitActionTrain: { // Building training units. DrawUnitInfo_Training(unit); return true; } case UnitActionUpgradeTo: { // Building upgrading to better type. if (UI.UpgradingButton) { const COrder_UpgradeTo &order = *static_cast<COrder_UpgradeTo *>(unit.CurrentOrder()); CIcon &icon = *order.GetUnitType().Icon.Icon; unsigned int flag = (ButtonAreaUnderCursor == ButtonAreaUpgrading && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.UpgradingButton->X, UI.UpgradingButton->Y); icon.DrawUnitIcon(*UI.UpgradingButton->Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } return true; } case UnitActionResearch: { // Building research new technology. if (UI.ResearchingButton) { COrder_Research &order = *static_cast<COrder_Research *>(unit.CurrentOrder()); CIcon &icon = *order.GetUpgrade().Icon; int flag = (ButtonAreaUnderCursor == ButtonAreaResearching && ButtonUnderCursor == 0) ? (IconActive | (MouseButtons & LeftButton)) : 0; PixelPos pos(UI.ResearchingButton->X, UI.ResearchingButton->Y); icon.DrawUnitIcon(*UI.ResearchingButton->Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); } return true; } default: return false; } } static void DrawUnitInfo_transporter(CUnit &unit) { CUnit *uins = unit.UnitInside; size_t j = 0; for (int i = 0; i < unit.InsideCount; ++i, uins = uins->NextContained) { if (!uins->Boarded || j >= UI.TransportingButtons.size()) { continue; } CIcon &icon = *uins->Type->Icon.Icon; int flag = (ButtonAreaUnderCursor == ButtonAreaTransporting && static_cast<size_t>(ButtonUnderCursor) == j) ? (IconActive | (MouseButtons & LeftButton)) : 0; const PixelPos pos(UI.TransportingButtons[j].X, UI.TransportingButtons[j].Y); icon.DrawUnitIcon(*UI.TransportingButtons[j].Style, flag, pos, "", unit.RescuedFrom ? GameSettings.Presets[unit.RescuedFrom->Index].PlayerColor : GameSettings.Presets[unit.Player->Index].PlayerColor); UiDrawLifeBar(*uins, pos.x, pos.y); if (uins->Type->CanCastSpell && uins->Variable[MANA_INDEX].Max) { UiDrawManaBar(*uins, pos.x, pos.y); } if (ButtonAreaUnderCursor == ButtonAreaTransporting && static_cast<size_t>(ButtonUnderCursor) == j) { UI.StatusLine.Set(uins->Type->Name); } ++j; } } /** ** Draw the unit info into top-panel. ** ** @param unit Pointer to unit. */ static void DrawUnitInfo(CUnit &unit) { UpdateUnitVariables(unit); for (size_t i = 0; i != UI.InfoPanelContents.size(); ++i) { if (CanShowContent(UI.InfoPanelContents[i]->Condition, unit)) { for (std::vector<CContentType *>::const_iterator content = UI.InfoPanelContents[i]->Contents.begin(); content != UI.InfoPanelContents[i]->Contents.end(); ++content) { if (CanShowContent((*content)->Condition, unit)) { (*content)->Draw(unit, UI.InfoPanelContents[i]->DefaultFont); } } } } const CUnitType &type = *unit.Type; Assert(&type); // Draw IconUnit DrawUnitInfo_portrait(unit); if (unit.Player != ThisPlayer && !ThisPlayer->IsAllied(*unit.Player)) { return; } // Show progress if they are selected. if (IsOnlySelected(unit)) { if (DrawUnitInfo_single_selection(unit)) { return; } } // Transporting units. if (type.CanTransport() && unit.BoardCount && CurrentButtonLevel == unit.Type->ButtonLevelForTransporter) { DrawUnitInfo_transporter(unit); return; } } /*---------------------------------------------------------------------------- -- RESOURCES ----------------------------------------------------------------------------*/ /** ** Draw the player resource in top line. ** ** @todo FIXME : make DrawResources more configurable (format, font). */ void DrawResources() { CLabel label(GetGameFont()); // Draw all icons of resource. for (int i = 0; i <= FreeWorkersCount; ++i) { if (UI.Resources[i].G) { UI.Resources[i].G->DrawFrameClip(UI.Resources[i].IconFrame, UI.Resources[i].IconX, UI.Resources[i].IconY); } } for (int i = 0; i < MaxCosts; ++i) { if (UI.Resources[i].TextX != -1) { const int resourceAmount = ThisPlayer->Resources[i]; if (ThisPlayer->MaxResources[i] != -1) { const int resAmount = ThisPlayer->StoredResources[i] + ThisPlayer->Resources[i]; char tmp[256]; snprintf(tmp, sizeof(tmp), "%d (%d)", resAmount, ThisPlayer->MaxResources[i] - ThisPlayer->StoredResources[i]); label.SetFont(GetSmallFont()); label.Draw(UI.Resources[i].TextX, UI.Resources[i].TextY + 3, tmp); } else { label.SetFont(resourceAmount > 99999 ? GetSmallFont() : GetGameFont()); label.Draw(UI.Resources[i].TextX, UI.Resources[i].TextY + (resourceAmount > 99999) * 3, resourceAmount); } } } if (UI.Resources[FoodCost].TextX != -1) { char tmp[256]; snprintf(tmp, sizeof(tmp), "%d/%d", ThisPlayer->Demand, ThisPlayer->Supply); label.SetFont(GetGameFont()); if (ThisPlayer->Supply < ThisPlayer->Demand) { label.DrawReverse(UI.Resources[FoodCost].TextX, UI.Resources[FoodCost].TextY, tmp); } else { label.Draw(UI.Resources[FoodCost].TextX, UI.Resources[FoodCost].TextY, tmp); } } if (UI.Resources[ScoreCost].TextX != -1) { const int score = ThisPlayer->Score; label.SetFont(score > 99999 ? GetSmallFont() : GetGameFont()); label.Draw(UI.Resources[ScoreCost].TextX, UI.Resources[ScoreCost].TextY + (score > 99999) * 3, score); } if (UI.Resources[FreeWorkersCount].TextX != -1) { const int workers = ThisPlayer->FreeWorkers.size(); label.SetFont(GetGameFont()); label.Draw(UI.Resources[FreeWorkersCount].TextX, UI.Resources[FreeWorkersCount].TextY, workers); } } /*---------------------------------------------------------------------------- -- MESSAGE ----------------------------------------------------------------------------*/ #define MESSAGES_MAX 10 /// How many can be displayed static char MessagesEvent[MESSAGES_MAX][256]; /// Array of event messages static Vec2i MessagesEventPos[MESSAGES_MAX]; /// coordinate of event static int MessagesEventCount; /// Number of event messages static int MessagesEventIndex; /// FIXME: docu class MessagesDisplay { public: MessagesDisplay() : show(true) { #ifdef DEBUG showBuilList = false; #endif CleanMessages(); } void UpdateMessages(); void AddUniqueMessage(const char *s); void DrawMessages(); void CleanMessages(); void ToggleShowMessages() { show = !show; } #ifdef DEBUG void ToggleShowBuilListMessages() { showBuilList = !showBuilList; } #endif protected: void ShiftMessages(); void AddMessage(const char *msg); bool CheckRepeatMessage(const char *msg); private: char Messages[MESSAGES_MAX][256]; /// Array of messages int MessagesCount; /// Number of messages int MessagesSameCount; /// Counts same message repeats int MessagesScrollY; unsigned long MessagesFrameTimeout; /// Frame to expire message bool show; #ifdef DEBUG bool showBuilList; #endif }; /** ** Shift messages array by one. */ void MessagesDisplay::ShiftMessages() { if (MessagesCount) { --MessagesCount; for (int z = 0; z < MessagesCount; ++z) { strcpy_s(Messages[z], sizeof(Messages[z]), Messages[z + 1]); } } } /** ** Update messages ** ** @todo FIXME: make scroll speed configurable. */ void MessagesDisplay::UpdateMessages() { if (!MessagesCount) { return; } // Scroll/remove old message line const unsigned long ticks = GetTicks(); if (MessagesFrameTimeout < ticks) { ++MessagesScrollY; if (MessagesScrollY == UI.MessageFont->Height() + 1) { MessagesFrameTimeout = ticks + UI.MessageScrollSpeed * 1000; MessagesScrollY = 0; ShiftMessages(); } } } /** ** Draw message(s). ** ** @todo FIXME: make message font configurable. */ void MessagesDisplay::DrawMessages() { if (show && Preference.ShowMessages) { CLabel label(*UI.MessageFont); #ifdef DEBUG if (showBuilList && ThisPlayer->Ai) { char buffer[256]; int count = ThisPlayer->Ai->UnitTypeBuilt.size(); // Draw message line(s) for (int z = 0; z < count; ++z) { if (z == 0) { PushClipping(); SetClipping(UI.MapArea.X + 8, UI.MapArea.Y + 8, Video.Width - 1, Video.Height - 1); } snprintf(buffer, 256, "%s (%d/%d) Wait %lu [%d,%d]", ThisPlayer->Ai->UnitTypeBuilt[z].Type->Name.c_str(), ThisPlayer->Ai->UnitTypeBuilt[z].Made, ThisPlayer->Ai->UnitTypeBuilt[z].Want, ThisPlayer->Ai->UnitTypeBuilt[z].Wait, ThisPlayer->Ai->UnitTypeBuilt[z].Pos.x, ThisPlayer->Ai->UnitTypeBuilt[z].Pos.y); label.DrawClip(UI.MapArea.X + 8, UI.MapArea.Y + 8 + z * (UI.MessageFont->Height() + 1), buffer); if (z == 0) { PopClipping(); } } } else { #endif // background so the text is easier to read if (MessagesCount) { int textHeight = MessagesCount * (UI.MessageFont->Height() + 1); Uint32 color = Video.MapRGB(TheScreen->format, 38, 38, 78); Video.FillTransRectangleClip(color, UI.MapArea.X + 7, UI.MapArea.Y + 7, UI.MapArea.EndX - UI.MapArea.X - 16, textHeight - MessagesScrollY + 1, 0x80); Video.DrawRectangle(color, UI.MapArea.X + 6, UI.MapArea.Y + 6, UI.MapArea.EndX - UI.MapArea.X - 15, textHeight - MessagesScrollY + 2); } // Draw message line(s) for (int z = 0; z < MessagesCount; ++z) { if (z == 0) { PushClipping(); SetClipping(UI.MapArea.X + 8, UI.MapArea.Y + 8, Video.Width - 1, Video.Height - 1); } /* * Due parallel drawing we have to force message copy due temp * std::string(Messages[z]) creation because * char * pointer may change during text drawing. */ label.DrawClip(UI.MapArea.X + 8, UI.MapArea.Y + 8 + z * (UI.MessageFont->Height() + 1) - MessagesScrollY, std::string(Messages[z])); if (z == 0) { PopClipping(); } } if (MessagesCount < 1) { MessagesSameCount = 0; } #ifdef DEBUG } #endif } } /** ** Adds message to the stack ** ** @param msg Message to add. */ void MessagesDisplay::AddMessage(const char *msg) { unsigned long ticks = GetTicks(); if (!MessagesCount) { MessagesFrameTimeout = ticks + UI.MessageScrollSpeed * 1000; } if (MessagesCount == MESSAGES_MAX) { // Out of space to store messages, can't scroll smoothly ShiftMessages(); MessagesFrameTimeout = ticks + UI.MessageScrollSpeed * 1000; MessagesScrollY = 0; } char *ptr; char *next; char *message = Messages[MessagesCount]; // Split long message into lines if (strlen(msg) >= sizeof(Messages[0])) { strncpy(message, msg, sizeof(Messages[0]) - 1); ptr = message + sizeof(Messages[0]) - 1; *ptr-- = '\0'; next = ptr + 1; while (ptr >= message) { if (*ptr == ' ') { *ptr = '\0'; next = ptr + 1; break; } --ptr; } if (ptr < message) { ptr = next - 1; } } else { strcpy_s(message, sizeof(Messages[MessagesCount]), msg); next = ptr = message + strlen(message); } while (UI.MessageFont->Width(message) + 8 >= UI.MapArea.EndX - UI.MapArea.X) { while (1) { --ptr; if (*ptr == ' ') { *ptr = '\0'; next = ptr + 1; break; } else if (ptr == message) { break; } } // No space found, wrap in the middle of a word if (ptr == message) { ptr = next - 1; while (UI.MessageFont->Width(message) + 8 >= UI.MapArea.EndX - UI.MapArea.X) { *--ptr = '\0'; } next = ptr + 1; break; } } ++MessagesCount; if (strlen(msg) != (size_t)(ptr - message)) { AddMessage(msg + (next - message)); } } /** ** Check if this message repeats ** ** @param msg Message to check. ** ** @return true to skip this message */ bool MessagesDisplay::CheckRepeatMessage(const char *msg) { if (MessagesCount < 1) { return false; } if (!strcmp(msg, Messages[MessagesCount - 1])) { ++MessagesSameCount; return true; } if (MessagesSameCount > 0) { char temp[256]; int n = MessagesSameCount; MessagesSameCount = 0; // NOTE: vladi: yep it's a tricky one, but should work fine prbably :) snprintf(temp, sizeof(temp), _("Last message repeated ~<%d~> times"), n + 1); AddMessage(temp); } return false; } /** ** Add a new message to display only if it differs from the preceding one. */ void MessagesDisplay::AddUniqueMessage(const char *s) { if (!CheckRepeatMessage(s)) { AddMessage(s); } } /** ** Clean up messages. */ void MessagesDisplay::CleanMessages() { MessagesCount = 0; MessagesSameCount = 0; MessagesScrollY = 0; MessagesFrameTimeout = 0; MessagesEventCount = 0; MessagesEventIndex = 0; } static MessagesDisplay allmessages; /** ** Update messages */ void UpdateMessages() { allmessages.UpdateMessages(); } /** ** Clean messages */ void CleanMessages() { allmessages.CleanMessages(); } /** ** Draw messages */ void DrawMessages() { allmessages.DrawMessages(); } /** ** Set message to display. ** ** @param fmt To be displayed in text overlay. */ void SetMessage(const char *fmt, ...) { char temp[512]; va_list va; va_start(va, fmt); vsnprintf(temp, sizeof(temp) - 1, fmt, va); temp[sizeof(temp) - 1] = '\0'; va_end(va); allmessages.AddUniqueMessage(temp); } /** ** Shift messages events array by one. */ void ShiftMessagesEvent() { if (MessagesEventCount) { --MessagesEventCount; for (int z = 0; z < MessagesEventCount; ++z) { MessagesEventPos[z] = MessagesEventPos[z + 1]; strcpy_s(MessagesEvent[z], sizeof(MessagesEvent[z]), MessagesEvent[z + 1]); } } } /** ** Set message to display. ** ** @param pos Message pos map origin. ** @param fmt To be displayed in text overlay. ** ** @note FIXME: vladi: I know this can be just separated func w/o msg but ** it is handy to stick all in one call, someone? */ void SetMessageEvent(const Vec2i &pos, const char *fmt, ...) { Assert(Map.Info.IsPointOnMap(pos)); char temp[256]; va_list va; va_start(va, fmt); vsnprintf(temp, sizeof(temp) - 1, fmt, va); temp[sizeof(temp) - 1] = '\0'; va_end(va); allmessages.AddUniqueMessage(temp); if (MessagesEventCount == MESSAGES_MAX) { ShiftMessagesEvent(); } strcpy_s(MessagesEvent[MessagesEventCount], sizeof(MessagesEvent[MessagesEventCount]), temp); MessagesEventPos[MessagesEventCount] = pos; MessagesEventIndex = MessagesEventCount; ++MessagesEventCount; } /** ** Goto message origin. */ void CenterOnMessage() { if (MessagesEventIndex >= MessagesEventCount) { MessagesEventIndex = 0; } if (MessagesEventCount == 0) { return; } const Vec2i &pos(MessagesEventPos[MessagesEventIndex]); UI.SelectedViewport->Center(Map.TilePosToMapPixelPos_Center(pos)); SetMessage(_("~<Event: %s~>"), MessagesEvent[MessagesEventIndex]); ++MessagesEventIndex; } void ToggleShowMessages() { allmessages.ToggleShowMessages(); } #ifdef DEBUG void ToggleShowBuilListMessages() { allmessages.ToggleShowBuilListMessages(); } #endif /*---------------------------------------------------------------------------- -- INFO PANEL ----------------------------------------------------------------------------*/ /** ** Draw info panel background. ** ** @param frame frame nr. of the info panel background. */ static void DrawInfoPanelBackground(unsigned frame) { if (UI.InfoPanel.G) { UI.InfoPanel.G->DrawFrame(frame, UI.InfoPanel.X, UI.InfoPanel.Y); } } static void InfoPanel_draw_no_selection() { DrawInfoPanelBackground(0); if (UnitUnderCursor && UnitUnderCursor->IsVisible(*ThisPlayer) && !UnitUnderCursor->Type->BoolFlag[ISNOTSELECTABLE_INDEX].value) { // FIXME: not correct for enemies units DrawUnitInfo(*UnitUnderCursor); } else { // FIXME: need some cool ideas for this. int x = UI.InfoPanel.X + 16; int y = UI.InfoPanel.Y + 8; CLabel label(GetGameFont()); label.Draw(x, y, "Stratagus"); y += 16; label.Draw(x, y, _("Cycle:")); label.Draw(x + 48, y, GameCycle); label.Draw(x + 110, y, CYCLES_PER_SECOND * VideoSyncSpeed / 100); y += 20; std::string nc; std::string rc; GetDefaultTextColors(nc, rc); for (int i = 0; i < PlayerMax - 1; ++i) { if (Players[i].Type != PlayerNobody) { if (ThisPlayer->IsAllied(Players[i])) { label.SetNormalColor(FontGreen); } else if (ThisPlayer->IsEnemy(Players[i])) { label.SetNormalColor(FontRed); } else { label.SetNormalColor(nc); } label.Draw(x + 15, y, i); Video.DrawRectangleClip(ColorWhite, x, y, 12, 12); Video.FillRectangleClip(PlayerColors[GameSettings.Presets[i].PlayerColor][0], x + 1, y + 1, 10, 10); label.Draw(x + 27, y, Players[i].Name); label.Draw(x + 117, y, Players[i].Score); y += 14; } } } } static void InfoPanel_draw_single_selection(CUnit *selUnit) { CUnit &unit = (selUnit ? *selUnit : *Selected[0]); int panelIndex; // FIXME: not correct for enemy's units if (unit.Player == ThisPlayer || ThisPlayer->IsTeamed(unit) || ThisPlayer->IsAllied(unit) || ReplayRevealMap) { if (unit.Orders[0]->Action == UnitActionBuilt || unit.Orders[0]->Action == UnitActionResearch || unit.Orders[0]->Action == UnitActionUpgradeTo || unit.Orders[0]->Action == UnitActionTrain) { panelIndex = 3; } else if (unit.Stats->Variables[MANA_INDEX].Max) { panelIndex = 2; } else { panelIndex = 1; } } else { panelIndex = 0; } DrawInfoPanelBackground(panelIndex); DrawUnitInfo(unit); if (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == 0) { UI.StatusLine.Set(unit.Type->Name); } } static void InfoPanel_draw_multiple_selection() { // If there are more units selected draw their pictures and a health bar DrawInfoPanelBackground(0); for (size_t i = 0; i != std::min(Selected.size(), UI.SelectedButtons.size()); ++i) { const CIcon &icon = *Selected[i]->Type->Icon.Icon; const PixelPos pos(UI.SelectedButtons[i].X, UI.SelectedButtons[i].Y); icon.DrawUnitIcon(*UI.SelectedButtons[i].Style, (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == (int)i) ? (IconActive | (MouseButtons & LeftButton)) : 0, pos, "", Selected[i]->RescuedFrom ? GameSettings.Presets[Selected[i]->RescuedFrom->Index].PlayerColor : GameSettings.Presets[Selected[i]->Player->Index].PlayerColor); UiDrawLifeBar(*Selected[i], UI.SelectedButtons[i].X, UI.SelectedButtons[i].Y); if (ButtonAreaUnderCursor == ButtonAreaSelected && ButtonUnderCursor == (int) i) { UI.StatusLine.Set(Selected[i]->Type->Name); } } if (Selected.size() > UI.SelectedButtons.size()) { char buf[5]; sprintf(buf, "+%lu", (long unsigned int)(Selected.size() - UI.SelectedButtons.size())); CLabel(*UI.MaxSelectedFont).Draw(UI.MaxSelectedTextX, UI.MaxSelectedTextY, buf); } } /** ** Draw info panel. ** ** Panel: ** neutral - neutral or opponent ** normal - not 1,3,4 ** magic unit - magic units ** construction - under construction */ void CInfoPanel::Draw() { if (UnitUnderCursor && Selected.empty() && !UnitUnderCursor->Type->IsNotSelectable && (ReplayRevealMap || UnitUnderCursor->IsVisible(*ThisPlayer))) { InfoPanel_draw_single_selection(UnitUnderCursor); } else { switch (Selected.size()) { case 0: { InfoPanel_draw_no_selection(); break; } case 1: { InfoPanel_draw_single_selection(NULL); break; } default: { InfoPanel_draw_multiple_selection(); break; } } } } /*---------------------------------------------------------------------------- -- TIMER ----------------------------------------------------------------------------*/ /** ** Draw the timer ** ** @todo FIXME : make DrawTimer more configurable (Pos, format). */ void DrawTimer() { if (!GameTimer.Init) { return; } int sec = GameTimer.Cycles / CYCLES_PER_SECOND; UI.Timer.Draw(sec); } /** ** Update the timer */ void UpdateTimer() { if (GameTimer.Running) { if (GameTimer.Increasing) { GameTimer.Cycles += GameCycle - GameTimer.LastUpdate; } else { GameTimer.Cycles -= GameCycle - GameTimer.LastUpdate; GameTimer.Cycles = std::max(GameTimer.Cycles, 0l); } GameTimer.LastUpdate = GameCycle; } } //@}
Java
function isPrime(n) { if (n === 2) { return true; } if (n % 2 === 0 || n === 1) { return false; } for (var i = 3; i <= Math.sqrt(n); i += 2) { if (n % i === 0) { return false; } } return true; } function nthPrimeNumber(n) { if (n <= 0) { throw new Error('Must be an integer >= 1'); } var numPrime = 1; var i = 1; if (n === 1) { return 2; } while (numPrime < n) { i += 2; if (isPrime(i)) { numPrime++; } } return i; } console.log(nthPrimeNumber(10001));
Java
<?php /** * glFusion CMS * * UTF-8 Language File for Calendar Plugin * * @license GNU General Public License version 2 or later * http://www.opensource.org/licenses/gpl-license.php * * Copyright (C) 2008-2018 by the following authors: * Mark R. Evans mark AT glfusion DOT org * * Based on prior work Copyright (C) 2001-2005 by the following authors: * Tony Bibbs - tony AT tonybibbs DOT com * Trinity Bays - trinity93 AT gmail DOT com * */ if (!defined ('GVERSION')) { die ('This file cannot be used on its own.'); } global $LANG32; ############################################################################### # Array Format: # $LANGXX[YY]: $LANG - variable name # XX - file id number # YY - phrase id number ############################################################################### # index.php $LANG_CAL_1 = array( 1 => 'Tapahtumakalenteri', 2 => 'Ei tapahtumia.', 3 => 'Milloin', 4 => 'Juuri', 5 => 'Kuvaus', 6 => 'Lisää tapahtuma', 7 => 'Tulevat tapahtumat', 8 => 'Lisäämällä tämän taphtuman kalenteriisi, näet nopeasti ne tapahtumat jotka sinua kiinnostaa klikkaamalla "Oma Kalenteri" käyttäjän toiminnot alueella.', 9 => 'Lisää minun jalenteriin', 10 => 'Poista minun kalenterista', 11 => 'Lisätään tapahtuma %s\'s Kalenteriin', 12 => 'Tapahtuma', 13 => 'Alkaa', 14 => 'Loppuu', 15 => 'Takaisin kalenteriin', 16 => 'Kalenteri', 17 => 'Aloitusp&auml;iv&auml;', 18 => 'Lopetusp&auml;iv&auml;', 19 => 'kalenteriin lähetetyt', 20 => 'Otsikko', 21 => 'Alkamis päivä', 22 => 'URL', 23 => 'Sinun tapahtumat', 24 => 'Sivuston tapahtumat', 25 => 'Ei tulevia tapahtumia', 26 => 'Lähetä tapahtuma', 27 => "Lähetetään tapahtuma {$_CONF['site_name']} laitaa tapahtuman pääkalenteriin josta käyttäjät voi lisätä heidän omaan kalenteriin. Tämä toiminto <b>EI</b> ole tarkoitettu henkilökohtaisiin tapahtumiin kuten syntymäpäivät yms tapahtumat.<br><br>Kun olet lähettänyt tapahtumasi, se lähetetään ylläpitoon ja jos se hyväksytään, tapahtumasai ilmestyy pääkalenteriin.", 28 => 'Otsikko', 29 => 'Päättymis aika', 30 => 'Alamis aika', 31 => 'Kokopäivän tapahtuma', 32 => 'Osoiterivi 1', 33 => 'Osoiterivi 2', 34 => 'Kaupunki', 35 => 'Osavaltio', 36 => 'Postinumero', 37 => 'Tapahtuman tyyppi', 38 => 'Muokkaa tapahtuma tyyppejä', 39 => 'Sijainti', 40 => 'Lisää tapahtuma kohteeseen', 41 => 'Pääkalenteri', 42 => 'Henkilökohtainen kalenteri', 43 => 'Linkki', 44 => 'HTML koodit eiv&auml;t ole sallittu', 45 => 'Lähetä', 46 => 'Tapahtumat systeemissä', 47 => 'Top kymmenen tapahtumat', 48 => 'Lukukertoja', 49 => 'Näyttää siltä että tällä sivustolla ei ole tapahtumia, tai kukaan ei ole klikannut niitä.', 50 => 'Tapahtumat', 51 => 'Poista', 52 => 'L&auml;hetti', 53 => 'Calendar View', ); $_LANG_CAL_SEARCH = array( 'results' => 'Kalenteri tulokset', 'title' => 'Otsikko', 'date_time' => 'Päivä & Aika', 'location' => 'Sijainti', 'description' => 'Kuvaus' ); ############################################################################### # calendar.php ($LANG30) $LANG_CAL_2 = array( 8 => 'Lisää oma tapahtuma', 9 => '%s Tapahtuma', 10 => 'Tapahtumat ', 11 => 'Pääkalenteri', 12 => 'Oma kalenteri', 25 => 'Takaisin ', 26 => 'Koko p&auml;iv&auml;n', 27 => 'Viikko', 28 => 'Oma kalenteri kohteelle', 29 => ' Julkinen kalenteri', 30 => 'poista tapahtuma', 31 => 'Lis&auml;&auml;', 32 => 'Tapahtuma', 33 => 'Päivä', 34 => 'Aika', 35 => 'Nopea lisäys', 36 => 'Lähetä', 37 => 'Oma kalenteri toiminto ei ole käytössä', 38 => 'Oma tapahtuma muokkaus', 39 => 'Päivä', 40 => 'Viikko', 41 => 'Kuukausi', 42 => 'Lisää päätapahtuma', 43 => 'Lähetetyt tapahtumat' ); ############################################################################### # admin/plugins/calendar/index.php, formerly admin/event.php ($LANG22) $LANG_CAL_ADMIN = array( 1 => 'Tapahtuma Muokkaus', 2 => 'Virhe', 3 => 'Viestin muoto', 4 => 'Tapahtuman URL', 5 => 'Tapahtuman alkamispäivä', 6 => 'Tapahtuman päättymispäivä', 7 => 'Tapahtuman sijainti', 8 => 'Kuvaus tapahtumasta', 9 => '(mukaanlukien http://)', 10 => 'Sinun täytyy antaa päivä/aika, tapahtuman otsikko, ja kuvaus tapahtumasta', 11 => 'Kalenteri hallinta', 12 => 'Muokataksesi tai poistaaksesi tapahtuman, klikkaa tapahtuman edit ikonia alhaalla. Uuden tapahtuman luodaksesi klikkaa "Luo uusi" ylhäältä. Klikkaa kopioi ikonia kopioidaksesi olemassaolevan tapahtuman.', 13 => 'Omistaja', 14 => 'Alkamispäivä', 15 => 'Päättymispäivä', 16 => '', 17 => "Yrität päästä tapahtumaan johon sinulla ei ole pääsy oikeutta. Tämä yrtitys kirjattiin. <a href=\"{$_CONF['site_admin_url']}/plugins/calendar/index.php\">mene takaisin tapahtuman hallintaan</a>.", 18 => '', 19 => '', 20 => 'tallenna', 21 => 'peruuta', 22 => 'poista', 23 => 'Epäkelpo Alkamis Päivä.', 24 => 'Epäkelpo päättymis Päivä.', 25 => 'Päättymispäivä On Aikaisemmin Kuin Alkamispäivä.', 26 => 'Batch Event Manager', 27 => 'Tässä ovat kaikki tapahtumat jotka ovat vanhempia kuin ', 28 => ' kuukautta. Päivitä aikaväli halutuksi, ja klikkaa Päivitä Lista. valitse yksi tai useampia tapahtumia tuloksista, ja klikkaa poista Ikonia alla poistaaksesi nämä tapahtumat. Vain tapahtumat jotka näkyy tällä sivulla ja on listattu, poistetaan.', 29 => '', 30 => 'P&auml;ivit&auml; Lista', 31 => 'Oletko varma että haluat poistaa kaikki valitut käyttäjät?', 32 => 'Listaa kaikki', 33 => 'Yhtään tapahtumaa ei valittu poistettavaksi', 34 => 'Tapahtuman ID', 35 => 'ei voitu poistaa', 36 => 'Poistettu', 37 => 'Moderoi Tapahtumaa', 38 => 'Batch tapahtuma Admin', 39 => 'Tapahtuman Admin', 40 => 'Event List', 41 => 'This screen allows you to edit / create events. Edit the fields below and save.', ); $LANG_CAL_AUTOTAG = array( 'desc_calendar' => 'Link: to a Calendar event on this site; link_text defaults to event title: [calendar:<i>event_id</i> {link_text}]', ); $LANG_CAL_MESSAGE = array( 'save' => 'tapahtuma Tallennettu.', 'delete' => 'Tapahtuma Poistettu.', 'private' => 'Tapahtuma Tallennettu Kalenteriisi', 'login' => 'Kalenteriasi ei voi avata ennenkuin olet kirjautunut', 'removed' => 'tapahtuma poistettu kalenteristasi', 'noprivate' => 'Valitamme, mutta henkilökohtaiset kalenterit ei ole sallittu tällä hetkellä', 'unauth' => 'Sinulla ei ole oikeuksia tapahtuman ylläpito sivulle. Kaikki yritykset kirjataan', 'delete_confirm' => 'Oletko varma että haluat poistaa tämän tapahtuman?' ); $PLG_calendar_MESSAGE4 = "Kiitos lähettämistä tapahtuman {$_CONF['site_name']}. On toimitettu henkilökuntamme hyväksyttäväksi. Jos hyväksytään, tapahtuma nähdään täällä, meidän <a href=\"{$_CONF['site_url']}/calendar/index.php\">kalenteri</a> jaksossa."; $PLG_calendar_MESSAGE17 = 'Tapahtuma Tallennettu.'; $PLG_calendar_MESSAGE18 = 'Tapahtuma Poistettu.'; $PLG_calendar_MESSAGE24 = 'Tapahtuma Tallennettu Kalenteriisi.'; $PLG_calendar_MESSAGE26 = 'Tapahtuma Poistettu.'; // Messages for the plugin upgrade $PLG_calendar_MESSAGE3001 = 'Plugin päivitys ei tueta.'; $PLG_calendar_MESSAGE3002 = $LANG32[9]; // Localization of the Admin Configuration UI $LANG_configsections['calendar'] = array( 'label' => 'Kalenteri', 'title' => 'Kalenteri Asetukset' ); $LANG_confignames['calendar'] = array( 'calendarloginrequired' => 'Kalenteri Kirjautuminen Vaaditaan', 'hidecalendarmenu' => 'Piiloita Kalenteri Valikossa', 'personalcalendars' => 'Salli Henkilökohtaiset Kalenterit', 'eventsubmission' => 'Ota Käyttöön Lähetys Jono', 'showupcomingevents' => 'Näytä Tulevat Tapahtumat', 'upcomingeventsrange' => 'Tulevien Tapahtumien Aikaväli', 'event_types' => 'Tapahtuma Tyypit', 'hour_mode' => 'Tunti Moodi', 'notification' => 'Sähköposti Ilmoitus', 'delete_event' => 'Poista Tapahtumalta Omistaja', 'aftersave' => 'Tapahtuman Tallennuksen Jälkeen', 'default_permissions' => 'Tapahtuman Oletus Oikeudet', 'only_admin_submit' => 'Salli Vain Admineitten Lähettää', 'displayblocks' => 'Näytä glFusion Lohkot', ); $LANG_configsubgroups['calendar'] = array( 'sg_main' => 'Pää Asetukset' ); $LANG_fs['calendar'] = array( 'fs_main' => 'Yleiset Kalenteri Asetukset', 'fs_permissions' => 'Oletus Oikeudet' ); $LANG_configSelect['calendar'] = array( 0 => array(1=> 'True', 0 => 'False'), 1 => array(true => 'True', false => 'False'), 6 => array(12 => '12', 24 => '24'), 9 => array('item'=>'Forward to Event', 'list'=>'Display Admin List', 'plugin'=>'Display Calendar', 'home'=>'Display Home', 'admin'=>'Display Admin'), 12 => array(0=>'No access', 2=>'Vain luku', 3=>'Read-Write'), 13 => array(0=>'Left Blocks', 1=>'Right Blocks', 2=>'Left & Right Blocks', 3=>'Ei yht&auml;&auml;n') ); ?>
Java
/***************************************************************************** * xa.c : xa file demux module for vlc ***************************************************************************** * Copyright (C) 2005 Rémi Denis-Courmont * $Id$ * * Authors: Rémi Denis-Courmont <rem # videolan.org> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser 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. *****************************************************************************/ /***************************************************************************** * Preamble *****************************************************************************/ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <assert.h> #include <vlc_common.h> #include <vlc_plugin.h> #include <vlc_demux.h> /***************************************************************************** * Module descriptor *****************************************************************************/ static int Open ( vlc_object_t * ); static void Close( vlc_object_t * ); vlc_module_begin () set_description( N_("XA demuxer") ) set_category( CAT_INPUT ) set_subcategory( SUBCAT_INPUT_DEMUX ) set_capability( "demux", 10 ) set_callbacks( Open, Close ) vlc_module_end () /***************************************************************************** * Local prototypes *****************************************************************************/ static int Demux ( demux_t * ); static int Control( demux_t *, int i_query, va_list args ); struct demux_sys_t { es_out_id_t *p_es; int64_t i_data_offset; unsigned int i_data_size; unsigned int i_block_frames; unsigned int i_frame_size; unsigned int i_bitrate; date_t pts; }; typedef struct xa_header_t { char xa_id[4]; uint32_t iSize; uint16_t wFormatTag; uint16_t nChannels; uint32_t nSamplesPerSec; uint32_t nAvgBytesPerSec; uint16_t nBlockAlign; uint16_t wBitsPerSample; } xa_header_t; static_assert(offsetof(xa_header_t, wBitsPerSample) == 22, "Bad padding"); #define FRAME_LENGTH 28 /* samples per frame */ /***************************************************************************** * Open: check file and initializes structures *****************************************************************************/ static int Open( vlc_object_t * p_this ) { demux_t *p_demux = (demux_t*)p_this; const uint8_t *peek; /* XA file heuristic */ if( vlc_stream_Peek( p_demux->s, &peek, 10 ) < 10 ) return VLC_EGENERIC; if( memcmp( peek, "XAI", 4 ) && memcmp( peek, "XAJ", 4 ) ) return VLC_EGENERIC; if( GetWLE( peek + 8 ) != 1 ) /* format tag */ return VLC_EGENERIC; demux_sys_t *p_sys = malloc( sizeof( demux_sys_t ) ); if( unlikely( p_sys == NULL ) ) return VLC_ENOMEM; /* read XA header*/ xa_header_t xa; if( vlc_stream_Read( p_demux->s, &xa, 24 ) < 24 ) { free( p_sys ); return VLC_EGENERIC; } es_format_t fmt; es_format_Init( &fmt, AUDIO_ES, VLC_FOURCC('X','A','J',0) ); msg_Dbg( p_demux, "assuming EA ADPCM audio codec" ); fmt.audio.i_rate = GetDWLE( &xa.nSamplesPerSec ); fmt.audio.i_bytes_per_frame = 15 * GetWLE( &xa.nChannels ); fmt.audio.i_frame_length = FRAME_LENGTH; fmt.audio.i_channels = GetWLE ( &xa.nChannels ); fmt.audio.i_blockalign = fmt.audio.i_bytes_per_frame; fmt.audio.i_bitspersample = GetWLE( &xa.wBitsPerSample ); fmt.i_bitrate = (fmt.audio.i_rate * fmt.audio.i_bytes_per_frame * 8) / fmt.audio.i_frame_length; p_sys->i_data_offset = vlc_stream_Tell( p_demux->s ); /* FIXME: better computation */ p_sys->i_data_size = xa.iSize * 15 / 56; /* How many frames per block (1:1 is too CPU intensive) */ p_sys->i_block_frames = fmt.audio.i_rate / (FRAME_LENGTH * 20) + 1; p_sys->i_frame_size = fmt.audio.i_bytes_per_frame; p_sys->i_bitrate = fmt.i_bitrate; msg_Dbg( p_demux, "fourcc: %4.4s, channels: %d, " "freq: %d Hz, bitrate: %dKo/s, blockalign: %d", (char *)&fmt.i_codec, fmt.audio.i_channels, fmt.audio.i_rate, fmt.i_bitrate / 8192, fmt.audio.i_blockalign ); if( fmt.audio.i_rate == 0 || fmt.audio.i_channels == 0 || fmt.audio.i_bitspersample != 16 ) { free( p_sys ); return VLC_EGENERIC; } p_sys->p_es = es_out_Add( p_demux->out, &fmt ); date_Init( &p_sys->pts, fmt.audio.i_rate, 1 ); date_Set( &p_sys->pts, VLC_TS_0 ); p_demux->pf_demux = Demux; p_demux->pf_control = Control; p_demux->p_sys = p_sys; return VLC_SUCCESS; } /***************************************************************************** * Demux: read packet and send them to decoders ***************************************************************************** * Returns -1 in case of error, 0 in case of EOF, 1 otherwise *****************************************************************************/ static int Demux( demux_t *p_demux ) { demux_sys_t *p_sys = p_demux->p_sys; block_t *p_block; int64_t i_offset; unsigned i_frames = p_sys->i_block_frames; i_offset = vlc_stream_Tell( p_demux->s ); if( p_sys->i_data_size > 0 && i_offset >= p_sys->i_data_offset + p_sys->i_data_size ) { /* EOF */ return 0; } p_block = vlc_stream_Block( p_demux->s, p_sys->i_frame_size * i_frames ); if( p_block == NULL ) { msg_Warn( p_demux, "cannot read data" ); return 0; } i_frames = p_block->i_buffer / p_sys->i_frame_size; p_block->i_dts = p_block->i_pts = date_Get( &p_sys->pts ); es_out_Control( p_demux->out, ES_OUT_SET_PCR, p_block->i_pts ); es_out_Send( p_demux->out, p_sys->p_es, p_block ); date_Increment( &p_sys->pts, i_frames * FRAME_LENGTH ); return 1; } /***************************************************************************** * Close: frees unused data *****************************************************************************/ static void Close ( vlc_object_t * p_this ) { demux_sys_t *p_sys = ((demux_t *)p_this)->p_sys; free( p_sys ); } /***************************************************************************** * Control: *****************************************************************************/ static int Control( demux_t *p_demux, int i_query, va_list args ) { demux_sys_t *p_sys = p_demux->p_sys; return demux_vaControlHelper( p_demux->s, p_sys->i_data_offset, p_sys->i_data_size ? p_sys->i_data_offset + p_sys->i_data_size : -1, p_sys->i_bitrate, p_sys->i_frame_size, i_query, args ); }
Java
body{ font-size:12px; font-family:tahoma; color:#6d6d6d; padding:0px; margin:0px; } table,td,tr,th,input,select,div,span,textarea{ font-family:tahoma; font-size:12px; } input{ text-align:center; } input[type=text],input[type=password]{ width:200px; } form{ padding:0px; margin:0px; } a:link{ font-size:11px; font-family:tahoma; color:#744; text-decoration:none; } a:visited{ font-size:11px; font-family:tahoma; color:#744; text-decoration:none; } a:hover{ font-size:11px; font-family:tahoma; color:orange; text-decoration:none; } .tx0{ font-family: tahoma; font-size:10px; } .tx1{ font-family: tahoma; font-size:11px; } .tx2{ font-family: tahoma; font-size:12px; } .er0{ font-family: tahoma; font-size:10px; color:red; } .er1{ font-family: tahoma; font-size:11px; color:red; } .er2{ font-family: tahoma; font-size:12px; color:red; } .submit0{ background-image:url('../templates/Default/admin/bg1.jpg'); font-size:10px; font-family:tahoma; border-color:#cccccc; border-width:1px; background-color:white; color:#555555; } .submit1{ background-image:url('../templates/Default/admin/bg1.jpg'); font-size:11px; font-family:tahoma; border-color:#cccccc; border-width:1px; background-color:white; color:#555555; } .submit2{ background-image:url('../templates/Default/admin/bg1.jpg'); font-size:12px; font-family:tahoma; border-color:#cccccc; border-width:1px; background-color:white; color:#555555; } .input0{ text-align:justify; font-family: tahoma; font-size:10px; } .input1{ text-align:; font-family: tahoma; font-size:11px; } .input2{ text-align:; font-family: tahoma; font-size:12px; } .select0{ text-align:justify; font-family: tahoma; font-size:10px; } .select1{ text-align:; font-family: tahoma; font-size:11px; } .select2{ text-align:; font-family: tahoma; font-size:12px; } #dhtmltooltip{ position: absolute; left: -300px; width: 150px; border: 1px solid black; padding: 2px; background-color: lightyellow; visibility: hidden; z-index: 100; /*Remove below line to remove shadow. Below line should always appear last within this CSS*/ filter: progid:DXImageTransform.Microsoft.Shadow(color=gray,direction=135); } #dhtmlpointer{ position:absolute; left: -300px; z-index: 101; visibility: hidden; }
Java
/* * Copyright (C) 2008-2010 Surevine Limited. * * Although intended for deployment and use alongside Alfresco this module should * be considered 'Not a Contribution' as defined in Alfresco'sstandard contribution agreement, see * http://www.alfresco.org/resource/AlfrescoContributionAgreementv2.pdf * * 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. */ // Get the change password url model.changePasswordUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_change_password.txt'); //Get the security label header model.securityLabelHeaderNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/security_label.txt'); //Get the help url model.helpLinkNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/url_help.txt'); model.launchChatUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Chat Dashlet/url_launch_chat.txt'); //Get the logo node model.appLogoNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Header/app_logo'); model.surevineLinkUrlNode = companyhome.childByNamePath('Data Dictionary/SV Theme/Configuration/Footer/url_surevine_link.txt'); cache.neverCache=false; cache.isPublic=false; cache.maxAge=36000; //10 hours cache.mustRevalidate=false; cache.ETag = 100;
Java
/* * Copyright 2001-2009 Sun Microsystems, Inc. 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 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. * */ // Sparse remembered set for a heap region (the "owning" region). Maps // indices of other regions to short sequences of cards in the other region // that might contain pointers into the owner region. // These tables only expand while they are accessed in parallel -- // deletions may be done in single-threaded code. This allows us to allow // unsynchronized reads/iterations, as long as expansions caused by // insertions only enqueue old versions for deletions, but do not delete // old versions synchronously. class SparsePRTEntry: public CHeapObj { public: enum SomePublicConstants { CardsPerEntry = 4, NullEntry = -1 }; private: RegionIdx_t _region_ind; int _next_index; CardIdx_t _cards[CardsPerEntry]; public: // Set the region_ind to the given value, and delete all cards. inline void init(RegionIdx_t region_ind); RegionIdx_t r_ind() const { return _region_ind; } bool valid_entry() const { return r_ind() >= 0; } void set_r_ind(RegionIdx_t rind) { _region_ind = rind; } int next_index() const { return _next_index; } int* next_index_addr() { return &_next_index; } void set_next_index(int ni) { _next_index = ni; } // Returns "true" iff the entry contains the given card index. inline bool contains_card(CardIdx_t card_index) const; // Returns the number of non-NULL card entries. inline int num_valid_cards() const; // Requires that the entry not contain the given card index. If there is // space available, add the given card index to the entry and return // "true"; otherwise, return "false" to indicate that the entry is full. enum AddCardResult { overflow, found, added }; inline AddCardResult add_card(CardIdx_t card_index); // Copy the current entry's cards into "cards". inline void copy_cards(CardIdx_t* cards) const; // Copy the current entry's cards into the "_card" array of "e." inline void copy_cards(SparsePRTEntry* e) const; inline CardIdx_t card(int i) const { return _cards[i]; } }; class RSHashTable : public CHeapObj { friend class RSHashTableIter; enum SomePrivateConstants { NullEntry = -1 }; size_t _capacity; size_t _capacity_mask; size_t _occupied_entries; size_t _occupied_cards; SparsePRTEntry* _entries; int* _buckets; int _free_region; int _free_list; // Requires that the caller hold a lock preventing parallel modifying // operations, and that the the table be less than completely full. If // an entry for "region_ind" is already in the table, finds it and // returns its address; otherwise returns "NULL." SparsePRTEntry* entry_for_region_ind(RegionIdx_t region_ind) const; // Requires that the caller hold a lock preventing parallel modifying // operations, and that the the table be less than completely full. If // an entry for "region_ind" is already in the table, finds it and // returns its address; otherwise allocates, initializes, inserts and // returns a new entry for "region_ind". SparsePRTEntry* entry_for_region_ind_create(RegionIdx_t region_ind); // Returns the index of the next free entry in "_entries". int alloc_entry(); // Declares the entry "fi" to be free. (It must have already been // deleted from any bucket lists. void free_entry(int fi); public: RSHashTable(size_t capacity); ~RSHashTable(); // Attempts to ensure that the given card_index in the given region is in // the sparse table. If successful (because the card was already // present, or because it was successfullly added) returns "true". // Otherwise, returns "false" to indicate that the addition would // overflow the entry for the region. The caller must transfer these // entries to a larger-capacity representation. bool add_card(RegionIdx_t region_id, CardIdx_t card_index); bool get_cards(RegionIdx_t region_id, CardIdx_t* cards); bool delete_entry(RegionIdx_t region_id); bool contains_card(RegionIdx_t region_id, CardIdx_t card_index) const; void add_entry(SparsePRTEntry* e); void clear(); size_t capacity() const { return _capacity; } size_t capacity_mask() const { return _capacity_mask; } size_t occupied_entries() const { return _occupied_entries; } size_t occupied_cards() const { return _occupied_cards; } size_t mem_size() const; SparsePRTEntry* entry(int i) const { return &_entries[i]; } void print(); }; // ValueObj because will be embedded in HRRS iterator. class RSHashTableIter VALUE_OBJ_CLASS_SPEC { int _tbl_ind; // [-1, 0.._rsht->_capacity) int _bl_ind; // [-1, 0.._rsht->_capacity) short _card_ind; // [0..CardsPerEntry) RSHashTable* _rsht; size_t _heap_bot_card_ind; // If the bucket list pointed to by _bl_ind contains a card, sets // _bl_ind to the index of that entry, and returns the card. // Otherwise, returns SparseEntry::NullEntry. CardIdx_t find_first_card_in_list(); // Computes the proper card index for the card whose offset in the // current region (as indicated by _bl_ind) is "ci". // This is subject to errors when there is iteration concurrent with // modification, but these errors should be benign. size_t compute_card_ind(CardIdx_t ci); public: RSHashTableIter(size_t heap_bot_card_ind) : _tbl_ind(RSHashTable::NullEntry), _bl_ind(RSHashTable::NullEntry), _card_ind((SparsePRTEntry::CardsPerEntry-1)), _rsht(NULL), _heap_bot_card_ind(heap_bot_card_ind) {} void init(RSHashTable* rsht) { _rsht = rsht; _tbl_ind = -1; // So that first increment gets to 0. _bl_ind = RSHashTable::NullEntry; _card_ind = (SparsePRTEntry::CardsPerEntry-1); } bool has_next(size_t& card_index); }; // Concurrent accesss to a SparsePRT must be serialized by some external // mutex. class SparsePRTIter; class SparsePRT VALUE_OBJ_CLASS_SPEC { // Iterations are done on the _cur hash table, since they only need to // see entries visible at the start of a collection pause. // All other operations are done using the _next hash table. RSHashTable* _cur; RSHashTable* _next; HeapRegion* _hr; enum SomeAdditionalPrivateConstants { InitialCapacity = 16 }; void expand(); bool _expanded; bool expanded() { return _expanded; } void set_expanded(bool b) { _expanded = b; } SparsePRT* _next_expanded; SparsePRT* next_expanded() { return _next_expanded; } void set_next_expanded(SparsePRT* nxt) { _next_expanded = nxt; } static SparsePRT* _head_expanded_list; public: SparsePRT(HeapRegion* hr); ~SparsePRT(); size_t occupied() const { return _next->occupied_cards(); } size_t mem_size() const; // Attempts to ensure that the given card_index in the given region is in // the sparse table. If successful (because the card was already // present, or because it was successfullly added) returns "true". // Otherwise, returns "false" to indicate that the addition would // overflow the entry for the region. The caller must transfer these // entries to a larger-capacity representation. bool add_card(RegionIdx_t region_id, CardIdx_t card_index); // If the table hold an entry for "region_ind", Copies its // cards into "cards", which must be an array of length at least // "CardsPerEntry", and returns "true"; otherwise, returns "false". bool get_cards(RegionIdx_t region_ind, CardIdx_t* cards); // If there is an entry for "region_ind", removes it and return "true"; // otherwise returns "false." bool delete_entry(RegionIdx_t region_ind); // Clear the table, and reinitialize to initial capacity. void clear(); // Ensure that "_cur" and "_next" point to the same table. void cleanup(); // Clean up all tables on the expanded list. Called single threaded. static void cleanup_all(); RSHashTable* cur() const { return _cur; } void init_iterator(SparsePRTIter* sprt_iter); static void add_to_expanded_list(SparsePRT* sprt); static SparsePRT* get_from_expanded_list(); bool contains_card(RegionIdx_t region_id, CardIdx_t card_index) const { return _next->contains_card(region_id, card_index); } #if 0 void verify_is_cleared(); void print(); #endif }; class SparsePRTIter: public /* RSHashTable:: */RSHashTableIter { public: SparsePRTIter(size_t heap_bot_card_ind) : /* RSHashTable:: */RSHashTableIter(heap_bot_card_ind) {} void init(const SparsePRT* sprt) { RSHashTableIter::init(sprt->cur()); } bool has_next(size_t& card_index) { return RSHashTableIter::has_next(card_index); } };
Java
<?php $widget = $vars["entity"]; // get widget settings $count = (int) $widget->wire_count; $filter = $widget->filter; if ($count < 1) { $count = 8; } $options = array( "type" => "object", "subtype" => "thewire", "limit" => $count, "full_view" => false, "pagination" => false, "view_type_toggle" => false ); if (!empty($filter)) { $filters = string_to_tag_array($filter); $filters = array_map("sanitise_string", $filters); $options["joins"] = array("JOIN " . elgg_get_config("dbprefix") . "objects_entity oe ON oe.guid = e.guid"); $options["wheres"] = array("(oe.description LIKE '%" . implode("%' OR oe.description LIKE '%", $filters) . "%')"); } $content = elgg_list_entities($options); if (!empty($content)) { echo $content; echo "<span class='elgg-widget-more'>" . elgg_view("output/url", array("href" => "thewire/all","text" => elgg_echo("thewire:moreposts"))) . "</span>"; } else { echo elgg_echo("thewire_tools:no_result"); }
Java
<?php /* * Template Name: Blog */ get_header(); ?> <?php while ( have_posts() ) : the_post(); ?> <div id="blog"> <?php get_template_part( 'content', 'introtext' ); ?> <section class="features"> <div class="container" role="main"> <div class="row"> <div class="span9"> <?php get_template_part( 'content', get_post_format() ); ?> </div> <div class="span3 sidebar"> <div class="blognav"> <?php get_sidebar(); ?> </div> </div> </div> </div> </section> </div> <?php endwhile; // end of the loop. ?> <?php get_footer(); ?>
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_04) on Wed Jul 02 15:54:03 IDT 2014 --> <title>com.codename1.payment Class Hierarchy (Codename One API)</title> <meta name="date" content="2014-07-02"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="com.codename1.payment Class Hierarchy (Codename One API)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/codename1/messaging/package-tree.html">Prev</a></li> <li><a href="../../../com/codename1/processing/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/codename1/payment/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h1 class="title">Hierarchy For Package com.codename1.payment</h1> <span class="strong">Package Hierarchies:</span> <ul class="horizontal"> <li><a href="../../../overview-tree.html">All Packages</a></li> </ul> </div> <div class="contentContainer"> <h2 title="Class Hierarchy">Class Hierarchy</h2> <ul> <li type="circle">java.lang.<a href="../../../java/lang/Object.html" title="class in java.lang"><span class="strong">Object</span></a> <ul> <li type="circle">com.codename1.payment.<a href="../../../com/codename1/payment/Product.html" title="class in com.codename1.payment"><span class="strong">Product</span></a></li> <li type="circle">com.codename1.payment.<a href="../../../com/codename1/payment/Purchase.html" title="class in com.codename1.payment"><span class="strong">Purchase</span></a></li> </ul> </li> </ul> <h2 title="Interface Hierarchy">Interface Hierarchy</h2> <ul> <li type="circle">com.codename1.payment.<a href="../../../com/codename1/payment/PurchaseCallback.html" title="interface in com.codename1.payment"><span class="strong">PurchaseCallback</span></a></li> </ul> </div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="package-summary.html">Package</a></li> <li>Class</li> <li class="navBarCell1Rev">Tree</li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-all.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li><a href="../../../com/codename1/messaging/package-tree.html">Prev</a></li> <li><a href="../../../com/codename1/processing/package-tree.html">Next</a></li> </ul> <ul class="navList"> <li><a href="../../../index.html?com/codename1/payment/package-tree.html" target="_top">Frames</a></li> <li><a href="package-tree.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
<?php function uwpf_delete_plugin() { delete_option('uwpf_options'); } function uwpf_init(){ register_setting( 'uwpf_plugin_options', 'uwpf_options', 'uwpf_validate' ); } function requires_wordpress_version() { global $wp_version; $plugin = plugin_basename( __FILE__ ); $plugin_data = get_plugin_data( __FILE__, false ); if ( version_compare($wp_version, "2.9", "<" ) ) { if( is_plugin_active($plugin) ) { deactivate_plugins( $plugin ); wp_die( "'".$plugin_data['Name']."' requires WordPress 2.9 or higher, and has been deactivated! Please upgrade WordPress and try again.<br /><br />Back to <a href='".admin_url()."'>WordPress admin</a>." ); } } } ?>
Java
<?php if ( !class_exists( 'RWMB_Field ' ) ) { class RWMB_Field { /** * Add actions * * @return void */ static function add_actions() {} /** * Enqueue scripts and styles * * @return void */ static function admin_enqueue_scripts() {} /** * Show field HTML * * @param array $field * @param bool $saved * * @return string */ static function show( $field, $saved ) { global $post; $field_class = RW_Meta_Box::get_class_name( $field ); $meta = call_user_func( array( $field_class, 'meta' ), $post->ID, $saved, $field ); $group = ''; // Empty the clone-group field $type = $field['type']; $id = $field['id']; $begin = call_user_func( array( $field_class, 'begin_html' ), $meta, $field ); // Apply filter to field begin HTML // 1st filter applies to all fields // 2nd filter applies to all fields with the same type // 3rd filter applies to current field only $begin = apply_filters( 'rwmb_begin_html', $begin, $field, $meta ); $begin = apply_filters( "rwmb_{$type}_begin_html", $begin, $field, $meta ); $begin = apply_filters( "rwmb_{$id}_begin_html", $begin, $field, $meta ); // Separate code for cloneable and non-cloneable fields to make easy to maintain // Cloneable fields if ( $field['clone'] ) { if ( isset( $field['clone-group'] ) ) $group = " clone-group='{$field['clone-group']}'"; $meta = (array) $meta; $field_html = ''; foreach ( $meta as $index => $sub_meta ) { $sub_field = $field; $sub_field['field_name'] = $field['field_name'] . "[{$index}]"; if ($index>0) { if (isset( $sub_field['address_field'] )) $sub_field['address_field'] = $field['address_field'] . "_{$index}"; $sub_field['id'] = $field['id'] . "_{$index}"; } if ( $field['multiple'] ) $sub_field['field_name'] .= '[]'; // Wrap field HTML in a div with class="rwmb-clone" if needed $input_html = '<div class="rwmb-clone">'; // Call separated methods for displaying each type of field //$input_html .= call_user_func( array( $field_class, 'html' ), $sub_meta, $sub_field ); // Apply filter to field HTML // 1st filter applies to all fields with the same type // 2nd filter applies to current field only $input_html = apply_filters( "rwmb_{$type}_html", $input_html, $field, $sub_meta ); $input_html = apply_filters( "rwmb_{$id}_html", $input_html, $field, $sub_meta ); // Add clone button $input_html .= self::clone_button(); $input_html .= '</div>'; $field_html .= $input_html; } } // Non-cloneable fields else { // Call separated methods for displaying each type of field $field_html = call_user_func( array( $field_class, 'html' ), $meta, $field ); // Apply filter to field HTML // 1st filter applies to all fields with the same type // 2nd filter applies to current field only $field_html = apply_filters( "rwmb_{$type}_html", $field_html, $field, $meta ); $field_html = apply_filters( "rwmb_{$id}_html", $field_html, $field, $meta ); } $end = call_user_func( array( $field_class, 'end_html' ), $meta, $field ); // Apply filter to field end HTML // 1st filter applies to all fields // 2nd filter applies to all fields with the same type // 3rd filter applies to current field only $end = apply_filters( 'rwmb_end_html', $end, $field, $meta ); $end = apply_filters( "rwmb_{$type}_end_html", $end, $field, $meta ); $end = apply_filters( "rwmb_{$id}_end_html", $end, $field, $meta ); // Apply filter to field wrapper // This allow users to change whole HTML markup of the field wrapper (i.e. table row) // 1st filter applies to all fields with the same type // 2nd filter applies to current field only //$html = apply_filters( "rwmb_{$type}_wrapper_html", "{$begin}{$field_html}{$end}", $field, $meta ); $html = apply_filters( "rwmb_{$type}_wrapper_html", "{$field_html}", $field, $meta ); $html = apply_filters( "rwmb_{$id}_wrapper_html", $html, $field, $meta ); // Display label and input in DIV and allow user-defined classes to be appended $classes = array( 'rwmb-field', "rwmb-{$type}-wrapper" ); if ( 'hidden' === $field['type'] ) $classes[] = 'hidden'; if ( !empty( $field['required'] ) ) $classes[] = 'required'; if ( !empty( $field['class'] ) ) $classes[] = $field['class']; printf( $field['before'] . '<div class="%s"%s>%s</div>' . $field['after'], implode( ' ', $classes ), $group, $html ); } /** * Get field HTML * * @param mixed $meta * @param array $field * * @return string */ static function html( $meta, $field ) { return ''; } /** * Show begin HTML markup for fields * * @param mixed $meta * @param array $field * * @return string */ static function begin_html( $meta, $field ) { if ( empty( $field['name'] ) ) return '<div class="rwmb-input">'; return sprintf( '<div class="rwmb-label"> <label for="%s">%s</label> </div> <div class="rwmb-input">', $field['id'], $field['name'] ); } /** * Show end HTML markup for fields * * @param mixed $meta * @param array $field * * @return string */ static function end_html( $meta, $field ) { $id = $field['id']; $button = ''; if ( $field['clone'] ) $button = '<a href="#" class="rwmb-button button-primary add-clone">' . __( '+', 'rwmb' ) . '</a>'; $desc = !empty( $field['desc'] ) ? "<p id='{$id}_description' class='description'>{$field['desc']}</p>" : ''; // Closes the container $html = "{$button}{$desc}</div>"; return $html; } /** * Add clone button * * @return string $html */ static function clone_button() { return '<a href="#" class="rwmb-button button remove-clone">' . __( '&#8211;', 'rwmb' ) . '</a>'; } /** * Get meta value * * @param int $post_id * @param bool $saved * @param array $field * * @return mixed */ static function meta( $post_id, $saved, $field ) { $meta = get_post_meta( $post_id, $field['id'], !$field['multiple'] ); // Use $field['std'] only when the meta box hasn't been saved (i.e. the first time we run) $meta = ( !$saved && '' === $meta || array() === $meta ) ? $field['std'] : $meta; // Escape attributes for non-wysiwyg fields if ( 'wysiwyg' !== $field['type'] ) $meta = is_array( $meta ) ? array_map( 'esc_attr', $meta ) : esc_attr( $meta ); $meta = apply_filters( "rwmb_{$field['type']}_meta", $meta ); $meta = apply_filters( "rwmb_{$field['id']}_meta", $meta ); return $meta; } /** * Set value of meta before saving into database * * @param mixed $new * @param mixed $old * @param int $post_id * @param array $field * * @return int */ static function value( $new, $old, $post_id, $field ) { return $new; } /** * Save meta value * * @param $new * @param $old * @param $post_id * @param $field */ static function save( $new, $old, $post_id, $field ) { $name = $field['id']; if ( '' === $new || array() === $new ) { delete_post_meta( $post_id, $name ); return; } if ( $field['multiple'] ) { foreach ( $new as $new_value ) { if ( !in_array( $new_value, $old ) ) add_post_meta( $post_id, $name, $new_value, false ); } foreach ( $old as $old_value ) { if ( !in_array( $old_value, $new ) ) delete_post_meta( $post_id, $name, $old_value ); } } else { if ( $field['clone'] ) { $new = (array) $new; foreach ( $new as $k => $v ) { if ( '' === $v ) unset( $new[$k] ); } } update_post_meta( $post_id, $name, $new ); } } /** * Normalize parameters for field * * @param array $field * * @return array */ static function normalize_field( $field ) { return $field; } } }
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_45) on Wed Jan 07 20:17:28 CST 2015 --> <title>Uses of Class gnu.getopt.Getopt</title> <meta name="date" content="2015-01-07"> <link rel="stylesheet" type="text/css" href="../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class gnu.getopt.Getopt"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../gnu/getopt/Getopt.html" title="class in gnu.getopt">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?gnu/getopt/class-use/Getopt.html" target="_top">Frames</a></li> <li><a href="Getopt.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class gnu.getopt.Getopt" class="title">Uses of Class<br>gnu.getopt.Getopt</h2> </div> <div class="classUseContainer">No usage of gnu.getopt.Getopt</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../gnu/getopt/Getopt.html" title="class in gnu.getopt">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../index-files/index-1.html">Index</a></li> <li><a href="../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../index.html?gnu/getopt/class-use/Getopt.html" target="_top">Frames</a></li> <li><a href="Getopt.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
Java
<!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>Taobao Cpp/Qt SDK: InventoryQueryResponse Class 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="search/search.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="search/search.js"></script> <script type="text/javascript"> $(document).ready(function() { searchBox.OnSelectItem(0); }); </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">Taobao Cpp/Qt SDK </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.3.1 --> <script type="text/javascript"> var searchBox = new SearchBox("searchBox", "search",false,'Search'); </script> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li class="current"><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li> <div id="MSearchBox" class="MSearchBoxInactive"> <span class="left"> <img id="MSearchSelect" src="search/mag_sel.png" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" alt=""/> <input type="text" id="MSearchField" value="Search" accesskey="S" onfocus="searchBox.OnSearchFieldFocus(true)" onblur="searchBox.OnSearchFieldFocus(false)" onkeyup="searchBox.OnSearchFieldChange(event)"/> </span><span class="right"> <a id="MSearchClose" href="javascript:searchBox.CloseResultsWindow()"><img id="MSearchCloseImg" border="0" src="search/close.png" alt=""/></a> </span> </div> </li> </ul> </div> <div id="navrow2" class="tabs2"> <ul class="tablist"> <li><a href="annotated.html"><span>Class&#160;List</span></a></li> <li><a href="classes.html"><span>Class&#160;Index</span></a></li> <li><a href="inherits.html"><span>Class&#160;Hierarchy</span></a></li> <li><a href="functions.html"><span>Class&#160;Members</span></a></li> </ul> </div> <!-- window showing the filter options --> <div id="MSearchSelectWindow" onmouseover="return searchBox.OnSearchSelectShow()" onmouseout="return searchBox.OnSearchSelectHide()" onkeydown="return searchBox.OnSearchSelectKey(event)"> <a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(0)"><span class="SelectionMark">&#160;</span>All</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(1)"><span class="SelectionMark">&#160;</span>Classes</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(2)"><span class="SelectionMark">&#160;</span>Files</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(3)"><span class="SelectionMark">&#160;</span>Functions</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(4)"><span class="SelectionMark">&#160;</span>Variables</a><a class="SelectItem" href="javascript:void(0)" onclick="searchBox.OnSelectItem(5)"><span class="SelectionMark">&#160;</span>Pages</a></div> <!-- iframe showing the search results (closed by default) --> <div id="MSearchResultsWindow"> <iframe src="javascript:void(0)" frameborder="0" name="MSearchResults" id="MSearchResults"> </iframe> </div> </div><!-- top --> <div class="header"> <div class="summary"> <a href="#pub-methods">Public Member Functions</a> &#124; <a href="#pri-attribs">Private Attributes</a> &#124; <a href="classInventoryQueryResponse-members.html">List of all members</a> </div> <div class="headertitle"> <div class="title">InventoryQueryResponse Class Reference</div> </div> </div><!--header--> <div class="contents"> <p>TOP RESPONSE API: 商家查询商品总体库存信息 <a href="classInventoryQueryResponse.html#details">More...</a></p> <p><code>#include &lt;<a class="el" href="InventoryQueryResponse_8h_source.html">InventoryQueryResponse.h</a>&gt;</code></p> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pub-methods"></a> Public Member Functions</h2></td></tr> <tr class="memitem:a48bce1584e6a9faf79f459247ea947d1"><td class="memItemLeft" align="right" valign="top">virtual&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#a48bce1584e6a9faf79f459247ea947d1">~InventoryQueryResponse</a> ()</td></tr> <tr class="separator:a48bce1584e6a9faf79f459247ea947d1"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aace94d1c58f6b1047ce81e4dd3dac523"><td class="memItemLeft" align="right" valign="top">QList&lt; <a class="el" href="classInventorySum.html">InventorySum</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#aace94d1c58f6b1047ce81e4dd3dac523">getItemInventorys</a> () const </td></tr> <tr class="separator:aace94d1c58f6b1047ce81e4dd3dac523"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a206abc6dfdd8d92dbe29a49f56cb9c6b"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#a206abc6dfdd8d92dbe29a49f56cb9c6b">setItemInventorys</a> (QList&lt; <a class="el" href="classInventorySum.html">InventorySum</a> &gt; <a class="el" href="classInventoryQueryResponse.html#ac0b78a3b2865cdc867d838fc5e334743">itemInventorys</a>)</td></tr> <tr class="separator:a206abc6dfdd8d92dbe29a49f56cb9c6b"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a518f3cb5830e479c2d3e900ab81b930e"><td class="memItemLeft" align="right" valign="top">QList&lt; <a class="el" href="classTipInfo.html">TipInfo</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#a518f3cb5830e479c2d3e900ab81b930e">getTipInfos</a> () const </td></tr> <tr class="separator:a518f3cb5830e479c2d3e900ab81b930e"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a20f666a61155f6c7fbfcf0099302d954"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#a20f666a61155f6c7fbfcf0099302d954">setTipInfos</a> (QList&lt; <a class="el" href="classTipInfo.html">TipInfo</a> &gt; <a class="el" href="classInventoryQueryResponse.html#ad148f3a3b176267ccf705e8440390c38">tipInfos</a>)</td></tr> <tr class="separator:a20f666a61155f6c7fbfcf0099302d954"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a617055db438ee63849d2ede92b906f32"><td class="memItemLeft" align="right" valign="top">virtual void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#a617055db438ee63849d2ede92b906f32">parseNormalResponse</a> ()</td></tr> <tr class="separator:a617055db438ee63849d2ede92b906f32"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="inherit_header pub_methods_classTaoResponse"><td colspan="2" onclick="javascript:toggleInherit('pub_methods_classTaoResponse')"><img src="closed.png" alt="-"/>&#160;Public Member Functions inherited from <a class="el" href="classTaoResponse.html">TaoResponse</a></td></tr> <tr class="memitem:a2e4420f5671664de8a1360866977d28b inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a2e4420f5671664de8a1360866977d28b">TaoResponse</a> ()</td></tr> <tr class="separator:a2e4420f5671664de8a1360866977d28b inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a32ef9c53545a593316521cb1daab3e1a inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">virtual&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a32ef9c53545a593316521cb1daab3e1a">~TaoResponse</a> ()</td></tr> <tr class="separator:a32ef9c53545a593316521cb1daab3e1a inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:af5a077aab153edf6247200587ee855ee inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#af5a077aab153edf6247200587ee855ee">parseResponse</a> ()</td></tr> <tr class="separator:af5a077aab153edf6247200587ee855ee inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a174dc083a44795514cfe7a9f14a3731a inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a174dc083a44795514cfe7a9f14a3731a">setParser</a> (<a class="el" href="classParser.html">Parser</a> *parser)</td></tr> <tr class="separator:a174dc083a44795514cfe7a9f14a3731a inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a854c6fdaef0abbeab21b5a43f65233ea inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a854c6fdaef0abbeab21b5a43f65233ea">parseError</a> ()</td></tr> <tr class="separator:a854c6fdaef0abbeab21b5a43f65233ea inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ae8f183ea55d76bf813f038aae7022db4 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#ae8f183ea55d76bf813f038aae7022db4">getErrorCode</a> () const </td></tr> <tr class="separator:ae8f183ea55d76bf813f038aae7022db4 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a2468d6e3ad0939ba2f4b12efd1b00413 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a2468d6e3ad0939ba2f4b12efd1b00413">setErrorCode</a> (const QString &amp;<a class="el" href="classTaoResponse.html#ac54f11b3b22a4f93c8587c1f4c3899d7">errorCode</a>)</td></tr> <tr class="separator:a2468d6e3ad0939ba2f4b12efd1b00413 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:adf75dc6bcbb550c8edb64d33939345ed inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#adf75dc6bcbb550c8edb64d33939345ed">getMsg</a> () const </td></tr> <tr class="separator:adf75dc6bcbb550c8edb64d33939345ed inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a76b9304897ecfc563d8f706d32c01b59 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a76b9304897ecfc563d8f706d32c01b59">setMsg</a> (const QString &amp;<a class="el" href="classTaoResponse.html#adc5e9252ac61126ac2936ab2f6b9a0c6">msg</a>)</td></tr> <tr class="separator:a76b9304897ecfc563d8f706d32c01b59 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a35fd73600c578a0d5fe9cbe1e1750689 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a35fd73600c578a0d5fe9cbe1e1750689">getSubCode</a> () const </td></tr> <tr class="separator:a35fd73600c578a0d5fe9cbe1e1750689 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a3c6346680f5209b3b9cd7fa0277222e6 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a3c6346680f5209b3b9cd7fa0277222e6">setSubCode</a> (const QString &amp;<a class="el" href="classTaoResponse.html#a5c6f8d740932e6453e7e3a2590fd3e6f">subCode</a>)</td></tr> <tr class="separator:a3c6346680f5209b3b9cd7fa0277222e6 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a7a0c8be833060f35437f741af784dd69 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a7a0c8be833060f35437f741af784dd69">getSubMsg</a> () const </td></tr> <tr class="separator:a7a0c8be833060f35437f741af784dd69 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a4eac44413ea5445d5cee1e8aac077194 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a4eac44413ea5445d5cee1e8aac077194">setSubMsg</a> (const QString &amp;<a class="el" href="classTaoResponse.html#a13f08fbbfd176df1e06c9dbf579d06f4">subMsg</a>)</td></tr> <tr class="separator:a4eac44413ea5445d5cee1e8aac077194 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:aff41254c8d0cf4454d663876569379d2 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">bool&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#aff41254c8d0cf4454d663876569379d2">isSuccess</a> ()</td></tr> <tr class="separator:aff41254c8d0cf4454d663876569379d2 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a92f81ae42b484c9b2258b508e4023068 inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">QString&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a92f81ae42b484c9b2258b508e4023068">getTopForbiddenFields</a> () const </td></tr> <tr class="separator:a92f81ae42b484c9b2258b508e4023068 inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:a475fb70a1c5657f8a947c3d1e3f5262d inherit pub_methods_classTaoResponse"><td class="memItemLeft" align="right" valign="top">void&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a475fb70a1c5657f8a947c3d1e3f5262d">setTopForbiddenFields</a> (const QString &amp;<a class="el" href="classTaoResponse.html#a4ff01826fe5b531e2427c7df23d4cc18">topForbiddenFields</a>)</td></tr> <tr class="separator:a475fb70a1c5657f8a947c3d1e3f5262d inherit pub_methods_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="pri-attribs"></a> Private Attributes</h2></td></tr> <tr class="memitem:ac0b78a3b2865cdc867d838fc5e334743"><td class="memItemLeft" align="right" valign="top">QList&lt; <a class="el" href="classInventorySum.html">InventorySum</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#ac0b78a3b2865cdc867d838fc5e334743">itemInventorys</a></td></tr> <tr class="memdesc:ac0b78a3b2865cdc867d838fc5e334743"><td class="mdescLeft">&#160;</td><td class="mdescRight">商品总体库存信息 <a href="#ac0b78a3b2865cdc867d838fc5e334743">More...</a><br/></td></tr> <tr class="separator:ac0b78a3b2865cdc867d838fc5e334743"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ad148f3a3b176267ccf705e8440390c38"><td class="memItemLeft" align="right" valign="top">QList&lt; <a class="el" href="classTipInfo.html">TipInfo</a> &gt;&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classInventoryQueryResponse.html#ad148f3a3b176267ccf705e8440390c38">tipInfos</a></td></tr> <tr class="memdesc:ad148f3a3b176267ccf705e8440390c38"><td class="mdescLeft">&#160;</td><td class="mdescRight">提示信息,提示不存在的后端商品 <a href="#ad148f3a3b176267ccf705e8440390c38">More...</a><br/></td></tr> <tr class="separator:ad148f3a3b176267ccf705e8440390c38"><td class="memSeparator" colspan="2">&#160;</td></tr> </table><table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="inherited"></a> Additional Inherited Members</h2></td></tr> <tr class="inherit_header pub_attribs_classTaoResponse"><td colspan="2" onclick="javascript:toggleInherit('pub_attribs_classTaoResponse')"><img src="closed.png" alt="-"/>&#160;Public Attributes inherited from <a class="el" href="classTaoResponse.html">TaoResponse</a></td></tr> <tr class="memitem:a49272f40b67d4bbb9c63f3f7b1ae7386 inherit pub_attribs_classTaoResponse"><td class="memItemLeft" align="right" valign="top"><a class="el" href="classParser.html">Parser</a> *&#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="classTaoResponse.html#a49272f40b67d4bbb9c63f3f7b1ae7386">responseParser</a></td></tr> <tr class="separator:a49272f40b67d4bbb9c63f3f7b1ae7386 inherit pub_attribs_classTaoResponse"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> <a name="details" id="details"></a><h2 class="groupheader">Detailed Description</h2> <div class="textblock"><p>TOP RESPONSE API: 商家查询商品总体库存信息 </p> <dl class="section author"><dt>Author</dt><dd>sd44 <a href="#" onclick="location.href='mai'+'lto:'+'sd4'+'4s'+'dd4'+'4@'+'yea'+'h.'+'net'; return false;">sd44s<span style="display: none;">.nosp@m.</span>dd44<span style="display: none;">.nosp@m.</span>@yeah<span style="display: none;">.nosp@m.</span>.net</a> </dd></dl> </div><h2 class="groupheader">Constructor &amp; Destructor Documentation</h2> <a class="anchor" id="a48bce1584e6a9faf79f459247ea947d1"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">virtual InventoryQueryResponse::~InventoryQueryResponse </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">inline</span><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Function Documentation</h2> <a class="anchor" id="aace94d1c58f6b1047ce81e4dd3dac523"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">QList&lt; <a class="el" href="classInventorySum.html">InventorySum</a> &gt; InventoryQueryResponse::getItemInventorys </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a518f3cb5830e479c2d3e900ab81b930e"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">QList&lt; <a class="el" href="classTipInfo.html">TipInfo</a> &gt; InventoryQueryResponse::getTipInfos </td> <td>(</td> <td class="paramname"></td><td>)</td> <td> const</td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a617055db438ee63849d2ede92b906f32"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">void InventoryQueryResponse::parseNormalResponse </td> <td>(</td> <td class="paramname"></td><td>)</td> <td></td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">virtual</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>Implements <a class="el" href="classTaoResponse.html#a726f09ea73fc5f7e1560c097d03b9838">TaoResponse</a>.</p> </div> </div> <a class="anchor" id="a206abc6dfdd8d92dbe29a49f56cb9c6b"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void InventoryQueryResponse::setItemInventorys </td> <td>(</td> <td class="paramtype">QList&lt; <a class="el" href="classInventorySum.html">InventorySum</a> &gt;&#160;</td> <td class="paramname"><em>itemInventorys</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <a class="anchor" id="a20f666a61155f6c7fbfcf0099302d954"></a> <div class="memitem"> <div class="memproto"> <table class="memname"> <tr> <td class="memname">void InventoryQueryResponse::setTipInfos </td> <td>(</td> <td class="paramtype">QList&lt; <a class="el" href="classTipInfo.html">TipInfo</a> &gt;&#160;</td> <td class="paramname"><em>tipInfos</em></td><td>)</td> <td></td> </tr> </table> </div><div class="memdoc"> </div> </div> <h2 class="groupheader">Member Data Documentation</h2> <a class="anchor" id="ac0b78a3b2865cdc867d838fc5e334743"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">QList&lt;<a class="el" href="classInventorySum.html">InventorySum</a>&gt; InventoryQueryResponse::itemInventorys</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">private</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>商品总体库存信息 </p> </div> </div> <a class="anchor" id="ad148f3a3b176267ccf705e8440390c38"></a> <div class="memitem"> <div class="memproto"> <table class="mlabels"> <tr> <td class="mlabels-left"> <table class="memname"> <tr> <td class="memname">QList&lt;<a class="el" href="classTipInfo.html">TipInfo</a>&gt; InventoryQueryResponse::tipInfos</td> </tr> </table> </td> <td class="mlabels-right"> <span class="mlabels"><span class="mlabel">private</span></span> </td> </tr> </table> </div><div class="memdoc"> <p>提示信息,提示不存在的后端商品 </p> </div> </div> <hr/>The documentation for this class was generated from the following files:<ul> <li>TaoApiCpp/response/<a class="el" href="InventoryQueryResponse_8h_source.html">InventoryQueryResponse.h</a></li> <li>TaoApiCpp/response/<a class="el" href="InventoryQueryResponse_8cpp.html">InventoryQueryResponse.cpp</a></li> </ul> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Sun Apr 14 2013 16:25:39 for Taobao Cpp/Qt SDK 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>
Java
/*************************************************************************** ofxdump.cpp ------------------- copyright : (C) 2002 by Benoit Grégoire email : bock@step.polymtl.ca ***************************************************************************/ /**@file * \brief Code for ofxdump utility. C++ example code * * ofxdump prints to stdout, in human readable form, everything the library understands about a particular ofx response file, and sends errors to stderr. To know exactly what the library understands about of a particular ofx response file, just call ofxdump on that file. * * ofxdump is meant as both a C++ code example and a developper/debuging tool. It uses every function and every structure of the LibOFX API. By default, WARNING, INFO, ERROR and STATUS messages are enabled. You can change these defaults at the top of ofxdump.cpp * * usage: ofxdump path_to_ofx_file/ofx_filename */ /*************************************************************************** * * * 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 <iostream> #include <iomanip> #include <string> #include "libofx.h" #include <stdio.h> /* for printf() */ #include <config.h> /* Include config constants, e.g., VERSION TF */ #include <errno.h> #include "cmdline.h" /* Gengetopt generated parser */ using namespace std; int ofx_proc_security_cb(struct OfxSecurityData data, void * security_data) { char dest_string[255]; cout<<"ofx_proc_security():\n"; if(data.unique_id_valid==true){ cout<<" Unique ID of the security being traded: "<<data.unique_id<<"\n"; } if(data.unique_id_type_valid==true){ cout<<" Format of the Unique ID: "<<data.unique_id_type<<"\n"; } if(data.secname_valid==true){ cout<<" Name of the security: "<<data.secname<<"\n"; } if(data.ticker_valid==true){ cout<<" Ticker symbol: "<<data.ticker<<"\n"; } if(data.unitprice_valid==true){ cout<<" Price of each unit of the security: "<<data.unitprice<<"\n"; } if(data.date_unitprice_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_unitprice))); cout<<" Date as of which the unitprice is valid: "<<dest_string<<"\n"; } if(data.currency_valid==true){ cout<<" Currency of the unitprice: "<<data.currency<<"\n"; } if(data.memo_valid==true){ cout<<" Extra transaction information (memo): "<<data.memo<<"\n"; } cout<<"\n"; return 0; } int ofx_proc_transaction_cb(struct OfxTransactionData data, void * transaction_data) { char dest_string[255]; cout<<"ofx_proc_transaction():\n"; if(data.account_id_valid==true){ cout<<" Account ID : "<<data.account_id<<"\n"; } if(data.transactiontype_valid==true) { if(data.transactiontype==OFX_CREDIT) strncpy(dest_string, "CREDIT: Generic credit", sizeof(dest_string)); else if (data.transactiontype==OFX_DEBIT) strncpy(dest_string, "DEBIT: Generic debit", sizeof(dest_string)); else if (data.transactiontype==OFX_INT) strncpy(dest_string, "INT: Interest earned or paid (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_DIV) strncpy(dest_string, "DIV: Dividend", sizeof(dest_string)); else if (data.transactiontype==OFX_FEE) strncpy(dest_string, "FEE: FI fee", sizeof(dest_string)); else if (data.transactiontype==OFX_SRVCHG) strncpy(dest_string, "SRVCHG: Service charge", sizeof(dest_string)); else if (data.transactiontype==OFX_DEP) strncpy(dest_string, "DEP: Deposit", sizeof(dest_string)); else if (data.transactiontype==OFX_ATM) strncpy(dest_string, "ATM: ATM debit or credit (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_POS) strncpy(dest_string, "POS: Point of sale debit or credit (Note: Depends on signage of amount)", sizeof(dest_string)); else if (data.transactiontype==OFX_XFER) strncpy(dest_string, "XFER: Transfer", sizeof(dest_string)); else if (data.transactiontype==OFX_CHECK) strncpy(dest_string, "CHECK: Check", sizeof(dest_string)); else if (data.transactiontype==OFX_PAYMENT) strncpy(dest_string, "PAYMENT: Electronic payment", sizeof(dest_string)); else if (data.transactiontype==OFX_CASH) strncpy(dest_string, "CASH: Cash withdrawal", sizeof(dest_string)); else if (data.transactiontype==OFX_DIRECTDEP) strncpy(dest_string, "DIRECTDEP: Direct deposit", sizeof(dest_string)); else if (data.transactiontype==OFX_DIRECTDEBIT) strncpy(dest_string, "DIRECTDEBIT: Merchant initiated debit", sizeof(dest_string)); else if (data.transactiontype==OFX_REPEATPMT) strncpy(dest_string, "REPEATPMT: Repeating payment/standing order", sizeof(dest_string)); else if (data.transactiontype==OFX_OTHER) strncpy(dest_string, "OTHER: Other", sizeof(dest_string)); else strncpy(dest_string, "Unknown transaction type", sizeof(dest_string)); cout<<" Transaction type: "<<dest_string<<"\n"; } if(data.date_initiated_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_initiated))); cout<<" Date initiated: "<<dest_string<<"\n"; } if(data.date_posted_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_posted))); cout<<" Date posted: "<<dest_string<<"\n"; } if(data.date_funds_available_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_funds_available))); cout<<" Date funds are available: "<<dest_string<<"\n"; } if(data.amount_valid==true){ cout<<" Total money amount: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.amount<<"\n"; } if(data.units_valid==true){ cout<<" # of units: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.units<<"\n"; } if(data.oldunits_valid==true){ cout<<" # of units before split: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.oldunits<<"\n"; } if(data.newunits_valid==true){ cout<<" # of units after split: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.newunits<<"\n"; } if(data.unitprice_valid==true){ cout<<" Unit price: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.unitprice<<"\n"; } if(data.fees_valid==true){ cout<<" Fees: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.fees<<"\n"; } if(data.commission_valid==true){ cout<<" Commission: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.commission<<"\n"; } if(data.fi_id_valid==true){ cout<<" Financial institution's ID for this transaction: "<<data.fi_id<<"\n"; } if(data.fi_id_corrected_valid==true){ cout<<" Financial institution ID replaced or corrected by this transaction: "<<data.fi_id_corrected<<"\n"; } if(data.fi_id_correction_action_valid==true){ cout<<" Action to take on the corrected transaction: "; if (data.fi_id_correction_action==DELETE) cout<<"DELETE\n"; else if (data.fi_id_correction_action==REPLACE) cout<<"REPLACE\n"; else cout<<"ofx_proc_transaction(): This should not happen!\n"; } if(data.invtransactiontype_valid==true){ cout<<" Investment transaction type: "; if (data.invtransactiontype==OFX_BUYDEBT) strncpy(dest_string, "BUYDEBT (Buy debt security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYMF) strncpy(dest_string, "BUYMF (Buy mutual fund)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYOPT) strncpy(dest_string, "BUYOPT (Buy option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYOTHER) strncpy(dest_string, "BUYOTHER (Buy other security type)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_BUYSTOCK) strncpy(dest_string, "BUYSTOCK (Buy stock))", sizeof(dest_string)); else if (data.invtransactiontype==OFX_CLOSUREOPT) strncpy(dest_string, "CLOSUREOPT (Close a position for an option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_INCOME) strncpy(dest_string, "INCOME (Investment income is realized as cash into the investment account)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_INVEXPENSE) strncpy(dest_string, "INVEXPENSE (Misc investment expense that is associated with a specific security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_JRNLFUND) strncpy(dest_string, "JRNLFUND (Journaling cash holdings between subaccounts within the same investment account)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_MARGININTEREST) strncpy(dest_string, "MARGININTEREST (Margin interest expense)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_REINVEST) strncpy(dest_string, "REINVEST (Reinvestment of income)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_RETOFCAP) strncpy(dest_string, "RETOFCAP (Return of capital)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLDEBT) strncpy(dest_string, "SELLDEBT (Sell debt security. Used when debt is sold, called, or reached maturity)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLMF) strncpy(dest_string, "SELLMF (Sell mutual fund)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLOPT) strncpy(dest_string, "SELLOPT (Sell option)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLOTHER) strncpy(dest_string, "SELLOTHER (Sell other type of security)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SELLSTOCK) strncpy(dest_string, "SELLSTOCK (Sell stock)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_SPLIT) strncpy(dest_string, "SPLIT (Stock or mutial fund split)", sizeof(dest_string)); else if (data.invtransactiontype==OFX_TRANSFER) strncpy(dest_string, "TRANSFER (Transfer holdings in and out of the investment account)", sizeof(dest_string)); else strncpy(dest_string, "ERROR, this investment transaction type is unknown. This is a bug in ofxdump", sizeof(dest_string)); cout<<dest_string<<"\n"; } if(data.unique_id_valid==true){ cout<<" Unique ID of the security being traded: "<<data.unique_id<<"\n"; } if(data.unique_id_type_valid==true){ cout<<" Format of the Unique ID: "<<data.unique_id_type<<"\n"; } if(data.security_data_valid==true){ ofx_proc_security_cb(*(data.security_data_ptr), NULL ); } if(data.server_transaction_id_valid==true){ cout<<" Server's transaction ID (confirmation number): "<<data.server_transaction_id<<"\n"; } if(data.check_number_valid==true){ cout<<" Check number: "<<data.check_number<<"\n"; } if(data.reference_number_valid==true){ cout<<" Reference number: "<<data.reference_number<<"\n"; } if(data.standard_industrial_code_valid==true){ cout<<" Standard Industrial Code: "<<data.standard_industrial_code<<"\n"; } if(data.payee_id_valid==true){ cout<<" Payee_id: "<<data.payee_id<<"\n"; } if(data.name_valid==true){ cout<<" Name of payee or transaction description: "<<data.name<<"\n"; } if(data.memo_valid==true){ cout<<" Extra transaction information (memo): "<<data.memo<<"\n"; } cout<<"\n"; return 0; }//end ofx_proc_transaction() int ofx_proc_statement_cb(struct OfxStatementData data, void * statement_data) { char dest_string[255]; cout<<"ofx_proc_statement():\n"; if(data.currency_valid==true){ cout<<" Currency: "<<data.currency<<"\n"; } if(data.account_id_valid==true){ cout<<" Account ID: "<<data.account_id<<"\n"; } if(data.date_start_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_start))); cout<<" Start date of this statement: "<<dest_string<<"\n"; } if(data.date_end_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.date_end))); cout<<" End date of this statement: "<<dest_string<<"\n"; } if(data.ledger_balance_valid==true){ cout<<" Ledger balance: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.ledger_balance<<"\n"; } if(data.ledger_balance_date_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.ledger_balance_date))); cout<<" Ledger balance date: "<<dest_string<<"\n"; } if(data.available_balance_valid==true){ cout<<" Available balance: "<<setiosflags(ios::fixed)<<setiosflags(ios::showpoint)<<setprecision(2)<<data.available_balance<<"\n"; } if(data.available_balance_date_valid==true){ strftime(dest_string,sizeof(dest_string),"%c %Z",localtime(&(data.available_balance_date))); cout<<" Ledger balance date: "<<dest_string<<"\n"; } if(data.marketing_info_valid==true){ cout<<" Marketing information: "<<data.marketing_info<<"\n"; } cout<<"\n"; return 0; }//end ofx_proc_statement() int ofx_proc_account_cb(struct OfxAccountData data, void * account_data) { cout<<"ofx_proc_account():\n"; if(data.account_id_valid==true){ cout<<" Account ID: "<<data.account_id<<"\n"; cout<<" Account name: "<<data.account_name<<"\n"; } if(data.account_type_valid==true){ cout<<" Account type: "; switch(data.account_type){ case OfxAccountData::OFX_CHECKING : cout<<"CHECKING\n"; break; case OfxAccountData::OFX_SAVINGS : cout<<"SAVINGS\n"; break; case OfxAccountData::OFX_MONEYMRKT : cout<<"MONEYMRKT\n"; break; case OfxAccountData::OFX_CREDITLINE : cout<<"CREDITLINE\n"; break; case OfxAccountData::OFX_CMA : cout<<"CMA\n"; break; case OfxAccountData::OFX_CREDITCARD : cout<<"CREDITCARD\n"; break; case OfxAccountData::OFX_INVESTMENT : cout<<"INVESTMENT\n"; break; default: cout<<"ofx_proc_account() WRITEME: This is an unknown account type!"; } } if(data.currency_valid==true){ cout<<" Currency: "<<data.currency<<"\n"; } if (data.bank_id_valid) cout<<" Bank ID: "<<data.bank_id << endl;; if (data.branch_id_valid) cout<<" Branch ID: "<<data.branch_id << endl; if (data.account_number_valid) cout<<" Account #: "<<data.account_number << endl; cout<<"\n"; return 0; }//end ofx_proc_account() int ofx_proc_status_cb(struct OfxStatusData data, void * status_data) { cout<<"ofx_proc_status():\n"; if(data.ofx_element_name_valid==true){ cout<<" Ofx entity this status is relevent to: "<< data.ofx_element_name<<" \n"; } if(data.severity_valid==true){ cout<<" Severity: "; switch(data.severity){ case OfxStatusData::INFO : cout<<"INFO\n"; break; case OfxStatusData::WARN : cout<<"WARN\n"; break; case OfxStatusData::ERROR : cout<<"ERROR\n"; break; default: cout<<"WRITEME: Unknown status severity!\n"; } } if(data.code_valid==true){ cout<<" Code: "<<data.code<<", name: "<<data.name<<"\n Description: "<<data.description<<"\n"; } if(data.server_message_valid==true){ cout<<" Server Message: "<<data.server_message<<"\n"; } cout<<"\n"; return 0; } int main (int argc, char *argv[]) { /** Tell ofxdump what you want it to send to stderr. See messages.cpp for more details */ extern int ofx_PARSER_msg; extern int ofx_DEBUG_msg; extern int ofx_WARNING_msg; extern int ofx_ERROR_msg; extern int ofx_INFO_msg; extern int ofx_STATUS_msg; gengetopt_args_info args_info; /* let's call our cmdline parser */ if (cmdline_parser (argc, argv, &args_info) != 0) exit(1) ; // if (args_info.msg_parser_given) // cout << "The msg_parser option was given!" << endl; // cout << "The flag is " << ( args_info.msg_parser_flag ? "on" : "off" ) << // "." << endl ; args_info.msg_parser_flag ? ofx_PARSER_msg = true : ofx_PARSER_msg = false; args_info.msg_debug_flag ? ofx_DEBUG_msg = true : ofx_DEBUG_msg = false; args_info.msg_warning_flag ? ofx_WARNING_msg = true : ofx_WARNING_msg = false; args_info.msg_error_flag ? ofx_ERROR_msg = true : ofx_ERROR_msg = false; args_info.msg_info_flag ? ofx_INFO_msg = true : ofx_INFO_msg = false; args_info.msg_status_flag ? ofx_STATUS_msg = true : ofx_STATUS_msg; bool skiphelp = false; if(args_info.list_import_formats_given) { skiphelp = true; cout <<"The supported file formats for the 'input-file-format' argument are:"<<endl; for(int i=0; LibofxImportFormatList[i].format!=LAST; i++) { cout <<" "<<LibofxImportFormatList[i].description<<endl; } } LibofxContextPtr libofx_context = libofx_get_new_context(); //char **inputs ; /* unamed options */ //unsigned inputs_num ; /* unamed options number */ if (args_info.inputs_num > 0) { const char* filename = args_info.inputs[0]; ofx_set_statement_cb(libofx_context, ofx_proc_statement_cb, 0); ofx_set_account_cb(libofx_context, ofx_proc_account_cb, 0); ofx_set_transaction_cb(libofx_context, ofx_proc_transaction_cb, 0); ofx_set_security_cb(libofx_context, ofx_proc_security_cb, 0); ofx_set_status_cb(libofx_context, ofx_proc_status_cb, 0); enum LibofxFileFormat file_format = libofx_get_file_format_from_str(LibofxImportFormatList, args_info.import_format_arg); /** @todo currently, only the first file is processed as the library can't deal with more right now.*/ if(args_info.inputs_num > 1) { cout << "Sorry, currently, only the first file is processed as the library can't deal with more right now. The following files were ignored:"<<endl; for ( unsigned i = 1 ; i < args_info.inputs_num ; ++i ) { cout << "file: " << args_info.inputs[i] << endl ; } } libofx_proc_file(libofx_context, args_info.inputs[0], file_format); } else { if ( !skiphelp ) cmdline_parser_print_help(); } return 0; }
Java
// // DO NOT EDIT - generated by simspec! // #ifndef ___ARHOST1X_UCLASS_H_INC_ #define ___ARHOST1X_UCLASS_H_INC_ // -------------------------------------------------------------------------- // // Copyright (c) 2004-2012, NVIDIA Corp. // All Rights Reserved. // // This is UNPUBLISHED PROPRIETARY SOURCE CODE of NVIDIA Corp.; // the contents of this file may not be disclosed to third parties, copied or // duplicated in any form, in whole or in part, without the prior written // permission of NVIDIA Corp. // // RESTRICTED RIGHTS LEGEND: // Use, duplication or disclosure by the Government is subject to restrictions // as set forth in subdivision (c)(1)(ii) of the Rights in Technical Data // and Computer Software clause at DFARS 252.227-7013, and/or in similar or // successor clauses in the FAR, DOD or NASA FAR Supplement. Unpublished - // rights reserved under the Copyright Laws of the United States. // // -------------------------------------------------------------------------- // // -------------------------------------------------------------------------- // // Copyright (c) 2004, NVIDIA Corp. // All Rights Reserved. // // This is UNPUBLISHED PROPRIETARY SOURCE CODE of NVIDIA Corp.; // the contents of this file may not be disclosed to third parties, copied or // duplicated in any form, in whole or in part, without the prior written // permission of NVIDIA Corp. // // RESTRICTED RIGHTS LEGEND: // Use, duplication or disclosure by the Government is subject to restrictions // as set forth in subdivision (c)(1)(ii) of the Rights in Technical Data // and Computer Software clause at DFARS 252.227-7013, and/or in similar or // successor clauses in the FAR, DOD or NASA FAR Supplement. Unpublished - // rights reserved under the Copyright Laws of the United States. // // -------------------------------------------------------------------------- // // Channel IDs // class offsets are always relative to the class (based at 0) // All Classes have the INCR_SYNCPT method // For host, this method, immediately increments // SYNCPT[indx], irrespective of the cond. // Note that INCR_SYNCPT_CNTRL and INCR_SYNCPT_ERROR // are included for consistency with host clients, // but writes to INCR_SYNCPT_CNTRL have no effect // on the operation of host1x, and because there // are no condition fifos to overflow, // INCR_SYNCPT_ERROR will never be set. // -------------------------------------------------------------------------- // // Copyright (c) 2004, NVIDIA Corp. // All Rights Reserved. // // This is UNPUBLISHED PROPRIETARY SOURCE CODE of NVIDIA Corp.; // the contents of this file may not be disclosed to third parties, copied or // duplicated in any form, in whole or in part, without the prior written // permission of NVIDIA Corp. // // RESTRICTED RIGHTS LEGEND: // Use, duplication or disclosure by the Government is subject to restrictions // as set forth in subdivision (c)(1)(ii) of the Rights in Technical Data // and Computer Software clause at DFARS 252.227-7013, and/or in similar or // successor clauses in the FAR, DOD or NASA FAR Supplement. Unpublished - // rights reserved under the Copyright Laws of the United States. // // -------------------------------------------------------------------------- // // Register NV_CLASS_HOST_INCR_SYNCPT_0 #define NV_CLASS_HOST_INCR_SYNCPT_0 _MK_ADDR_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_SECURE 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INCR_SYNCPT_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_RESET_MASK _MK_MASK_CONST(0xffff) #define NV_CLASS_HOST_INCR_SYNCPT_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_READ_MASK _MK_MASK_CONST(0xffff) #define NV_CLASS_HOST_INCR_SYNCPT_0_WRITE_MASK _MK_MASK_CONST(0xffff) // Condition mapped from raise/wait #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_SHIFT _MK_SHIFT_CONST(8) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_INCR_SYNCPT_0_COND_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_RANGE 15:8 #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_DEFAULT_MASK _MK_MASK_CONST(0xff) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_IMMEDIATE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_OP_DONE _MK_ENUM_CONST(1) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_RD_DONE _MK_ENUM_CONST(2) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_REG_WR_SAFE _MK_ENUM_CONST(3) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_4 _MK_ENUM_CONST(4) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_5 _MK_ENUM_CONST(5) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_6 _MK_ENUM_CONST(6) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_7 _MK_ENUM_CONST(7) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_8 _MK_ENUM_CONST(8) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_9 _MK_ENUM_CONST(9) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_10 _MK_ENUM_CONST(10) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_11 _MK_ENUM_CONST(11) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_12 _MK_ENUM_CONST(12) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_13 _MK_ENUM_CONST(13) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_14 _MK_ENUM_CONST(14) #define NV_CLASS_HOST_INCR_SYNCPT_0_COND_COND_15 _MK_ENUM_CONST(15) // syncpt index value #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_INCR_SYNCPT_0_INDX_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_RANGE 7:0 #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_DEFAULT_MASK _MK_MASK_CONST(0xff) #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_0_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0 _MK_ADDR_CONST(0x1) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_SECURE 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_RESET_MASK _MK_MASK_CONST(0x101) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_READ_MASK _MK_MASK_CONST(0x101) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_WRITE_MASK _MK_MASK_CONST(0x101) // If NO_STALL is 1, then when fifos are full, // INCR_SYNCPT methods will be dropped and the // INCR_SYNCPT_ERROR[COND] bit will be set. // If NO_STALL is 0, then when fifos are full, // the client host interface will be stalled. #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_SHIFT _MK_SHIFT_CONST(8) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_RANGE 8:8 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_DEFAULT_MASK _MK_MASK_CONST(0x1) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_NO_STALL_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // If SOFT_RESET is set, then all internal state // of the client syncpt block will be reset. // To do soft reset, first set SOFT_RESET of // all host1x clients affected, then clear all // SOFT_RESETs. #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_RANGE 0:0 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_DEFAULT_MASK _MK_MASK_CONST(0x1) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0_INCR_SYNCPT_SOFT_RESET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INCR_SYNCPT_ERROR_0 #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0 _MK_ADDR_CONST(0x2) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_SECURE 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) // COND_STATUS[COND] is set if the fifo for COND overflows. // This bit is sticky and will remain set until cleared. // Cleared by writing 1. #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_RANGE 31:0 #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_ERROR_0_COND_STATUS_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // reserve locations for future expansion // Reserved address 3 [0x3] // Reserved address 4 [0x4] // Reserved address 5 [0x5] // Reserved address 6 [0x6] // Reserved address 7 [0x7] // just in case names were redefined using macros // Wait on syncpt method // Command dispatch will stall until // SYNCPT[indx][NV_HOST1X_SYNCPT_THRESH_WIDTH-1:0] >= threshold[NV_HOST1X_SYNCPT_THRESH_WIDTH-1:0] // The comparison takes into account the possibility of wrapping. // Note that more bits are allocated for indx and threshold than may be used in an implementation // Use NV_HOST1X_SYNCPT_NB_PTS for the number of syncpts, and // NV_HOST1X_SYNCPT_THESH_WIDTH for the number of bits used by the comparison // Register NV_CLASS_HOST_WAIT_SYNCPT_0 #define NV_CLASS_HOST_WAIT_SYNCPT_0 _MK_ADDR_CONST(0x8) #define NV_CLASS_HOST_WAIT_SYNCPT_0_SECURE 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_WAIT_SYNCPT_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_SYNCPT_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_SHIFT _MK_SHIFT_CONST(24) #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_SHIFT) #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_RANGE 31:24 #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_FIELD (_MK_MASK_CONST(0xffffff) << NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_SHIFT) #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_RANGE 23:0 #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_0_THRESH_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Wait on syncpt method using base register // Command dispatch will stall until // SYNCPT[indx][NV_HOST1X_SYNCPT_THRESH_WIDTH-1:0] >= (SYNCPT_BASE[base_indx]+offset) // The comparison takes into account the possibility of wrapping. // Note that more bits are allocated for indx and base_indx than may be used in an implementation. // Use NV_HOST1X_SYNCPT_NB_PTS for the number of syncpts, // Use NV_HOST1X_SYNCPT_NB_BASES for the number of syncpt_bases, and // NV_HOST1X_SYNCPT_THESH_WIDTH for the number of bits used by the comparison // If NV_HOST1X_SYNCPT_THESH_WIDTH is greater than 16, offset is sign-extended before it is added to SYNCPT_BASE. // Register NV_CLASS_HOST_WAIT_SYNCPT_BASE_0 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0 _MK_ADDR_CONST(0x9) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_SECURE 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_SHIFT _MK_SHIFT_CONST(24) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_SHIFT) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_RANGE 31:24 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_SHIFT _MK_SHIFT_CONST(16) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_SHIFT) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_RANGE 23:16 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_BASE_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_FIELD (_MK_MASK_CONST(0xffff) << NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_SHIFT) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_RANGE 15:0 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_BASE_0_OFFSET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Wait on syncpt increment method // Command dispatch will stall until the next time that SYNCPT[indx] is incremented. // Note that more bits are allocated for indx than may be used in an implementation. // Use NV_HOST1X_SYNCPT_NB_PTS for the number of syncpts. // Register NV_CLASS_HOST_WAIT_SYNCPT_INCR_0 #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0 _MK_ADDR_CONST(0xa) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_SECURE 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_READ_MASK _MK_MASK_CONST(0xff000000) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_WRITE_MASK _MK_MASK_CONST(0xff000000) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_SHIFT _MK_SHIFT_CONST(24) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_SHIFT) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_RANGE 31:24 #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_SYNCPT_INCR_0_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Load syncpt base method // SYNCPT_BASE[indx] = value // Register NV_CLASS_HOST_LOAD_SYNCPT_BASE_0 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0 _MK_ADDR_CONST(0xb) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_SECURE 0x0 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_SHIFT _MK_SHIFT_CONST(24) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_SHIFT) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_RANGE 31:24 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_BASE_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_FIELD (_MK_MASK_CONST(0xffffff) << NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_SHIFT) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_RANGE 23:0 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_WOFFSET 0x0 #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_LOAD_SYNCPT_BASE_0_VALUE_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Increment syncpt base method // SYNCPT_BASE[indx] += offset // Register NV_CLASS_HOST_INCR_SYNCPT_BASE_0 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0 _MK_ADDR_CONST(0xc) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_SECURE 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_SHIFT _MK_SHIFT_CONST(24) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_RANGE 31:24 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_BASE_INDX_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_FIELD (_MK_MASK_CONST(0xffffff) << NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_SHIFT) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_RANGE 23:0 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_WOFFSET 0x0 #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INCR_SYNCPT_BASE_0_OFFSET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Clear method. Any bits set in VECTOR will be cleared in the channel's RAISE // vector. // Register NV_CLASS_HOST_CLEAR_0 #define NV_CLASS_HOST_CLEAR_0 _MK_ADDR_CONST(0xd) #define NV_CLASS_HOST_CLEAR_0_SECURE 0x0 #define NV_CLASS_HOST_CLEAR_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_CLEAR_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_CLEAR_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_CLEAR_0_VECTOR_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_CLEAR_0_VECTOR_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_CLEAR_0_VECTOR_SHIFT) #define NV_CLASS_HOST_CLEAR_0_VECTOR_RANGE 31:0 #define NV_CLASS_HOST_CLEAR_0_VECTOR_WOFFSET 0x0 #define NV_CLASS_HOST_CLEAR_0_VECTOR_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_VECTOR_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_VECTOR_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_CLEAR_0_VECTOR_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Wait method. Command dispatch will stall until any of the bits set in // VECTOR become set in the channel's RAISE vector. // Register NV_CLASS_HOST_WAIT_0 #define NV_CLASS_HOST_WAIT_0 _MK_ADDR_CONST(0xe) #define NV_CLASS_HOST_WAIT_0_SECURE 0x0 #define NV_CLASS_HOST_WAIT_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_WAIT_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_0_VECTOR_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_WAIT_0_VECTOR_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_WAIT_0_VECTOR_SHIFT) #define NV_CLASS_HOST_WAIT_0_VECTOR_RANGE 31:0 #define NV_CLASS_HOST_WAIT_0_VECTOR_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_0_VECTOR_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_VECTOR_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_VECTOR_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_0_VECTOR_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Wait w/ interrupt method. Identical to the WAIT method except an interrupt // will be triggered when the WAIT requirement is satisfied. // Register NV_CLASS_HOST_WAIT_WITH_INTR_0 #define NV_CLASS_HOST_WAIT_WITH_INTR_0 _MK_ADDR_CONST(0xf) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_SECURE 0x0 #define NV_CLASS_HOST_WAIT_WITH_INTR_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_WAIT_WITH_INTR_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_SHIFT) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_RANGE 31:0 #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_WOFFSET 0x0 #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_WAIT_WITH_INTR_0_VECTOR_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Delay number of microseconds. Command dispatch will stall until the number // of microseconds indicated in NUSEC has passed. The timing of microseconds // is controlled by the USEC_CLK register. // Register NV_CLASS_HOST_DELAY_USEC_0 #define NV_CLASS_HOST_DELAY_USEC_0 _MK_ADDR_CONST(0x10) #define NV_CLASS_HOST_DELAY_USEC_0_SECURE 0x0 #define NV_CLASS_HOST_DELAY_USEC_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_DELAY_USEC_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_READ_MASK _MK_MASK_CONST(0xfffff) #define NV_CLASS_HOST_DELAY_USEC_0_WRITE_MASK _MK_MASK_CONST(0xfffff) // Enough for 1.05 seconds #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_FIELD (_MK_MASK_CONST(0xfffff) << NV_CLASS_HOST_DELAY_USEC_0_NUSEC_SHIFT) #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_RANGE 19:0 #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_WOFFSET 0x0 #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_DELAY_USEC_0_NUSEC_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // This register value will initialize the high 32 bits of // tick count value in the host clock counter // Register NV_CLASS_HOST_TICKCOUNT_HI_0 #define NV_CLASS_HOST_TICKCOUNT_HI_0 _MK_ADDR_CONST(0x11) #define NV_CLASS_HOST_TICKCOUNT_HI_0_SECURE 0x0 #define NV_CLASS_HOST_TICKCOUNT_HI_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_TICKCOUNT_HI_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_TICKCOUNT_HI_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write tick count #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_SHIFT) #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_RANGE 31:0 #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_WOFFSET 0x0 #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_HI_0_TICKS_HI_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // This register value will initialize the low 32 bits of // tick count value in the host clock counter // Register NV_CLASS_HOST_TICKCOUNT_LO_0 #define NV_CLASS_HOST_TICKCOUNT_LO_0 _MK_ADDR_CONST(0x12) #define NV_CLASS_HOST_TICKCOUNT_LO_0_SECURE 0x0 #define NV_CLASS_HOST_TICKCOUNT_LO_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_TICKCOUNT_LO_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_TICKCOUNT_LO_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write tick count #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_SHIFT) #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_RANGE 31:0 #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_WOFFSET 0x0 #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCOUNT_LO_0_TICKS_LO_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // This register write enables the tick counter on the host clock to start counting // Register NV_CLASS_HOST_TICKCTRL_0 #define NV_CLASS_HOST_TICKCTRL_0 _MK_ADDR_CONST(0x13) #define NV_CLASS_HOST_TICKCTRL_0_SECURE 0x0 #define NV_CLASS_HOST_TICKCTRL_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_TICKCTRL_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_READ_MASK _MK_MASK_CONST(0x1) #define NV_CLASS_HOST_TICKCTRL_0_WRITE_MASK _MK_MASK_CONST(0x1) // Enable or Disable tick counter #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_SHIFT) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_RANGE 0:0 #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_WOFFSET 0x0 #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_DISABLE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_TICKCTRL_0_TICKCNT_ENABLE_ENABLE _MK_ENUM_CONST(1) // Reserved address 20 [0x14] // Reserved address 21 [0x15] // Reserved address 22 [0x16] // Reserved address 23 [0x17] // Reserved address 24 [0x18] // Reserved address 25 [0x19] // Reserved address 26 [0x1a] // Reserved address 27 [0x1b] // Reserved address 28 [0x1c] // Reserved address 29 [0x1d] // Reserved address 30 [0x1e] // Reserved address 31 [0x1f] // Reserved address 32 [0x20] // Reserved address 33 [0x21] // Reserved address 34 [0x22] // Reserved address 35 [0x23] // Reserved address 36 [0x24] // Reserved address 37 [0x25] // Reserved address 38 [0x26] // Reserved address 39 [0x27] // Reserved address 40 [0x28] // Reserved address 41 [0x29] // Reserved address 42 [0x2a] // Indirect addressing // These registers (along with INDDATA) are used to indirectly read/write either // register or memory. Host registers are not accessible using this interface. // If AUTOINC is set, INDOFFSET increments by 4 on every access of INDDATA. // // Either INDCTRL/INDOFF2 or INDOFF can be used, but INDOFF may not be able to // address all memory in chips with large memory maps. The rundundant bits in // INDCTRL and INDOFF are shared, so writing either offset sets those bits. // // NOTE: due to a HW bug (bug #343175) the following restrictions apply to the // use of indirect memory writes: // (1) at initialization time, do a dummy indirect write (with all byte enables set to zero), and // (2) dedicate an MLOCK for indirect memory writes, then before a channel issues // a set of indirect memory writes it must acquire this MLOCK; after the writes // have been issued, the MLOCK is released -- this will restrict the use of // indirect memory writes to a single channel at a time. // Register NV_CLASS_HOST_INDCTRL_0 #define NV_CLASS_HOST_INDCTRL_0 _MK_ADDR_CONST(0x2b) #define NV_CLASS_HOST_INDCTRL_0_SECURE 0x0 #define NV_CLASS_HOST_INDCTRL_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDCTRL_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_READ_MASK _MK_MASK_CONST(0xfc000003) #define NV_CLASS_HOST_INDCTRL_0_WRITE_MASK _MK_MASK_CONST(0xfc000003) // Byte enables. Will apply to all subsequent data transactions. Not applicable for reads. #define NV_CLASS_HOST_INDCTRL_0_INDBE_SHIFT _MK_SHIFT_CONST(28) #define NV_CLASS_HOST_INDCTRL_0_INDBE_FIELD (_MK_MASK_CONST(0xf) << NV_CLASS_HOST_INDCTRL_0_INDBE_SHIFT) #define NV_CLASS_HOST_INDCTRL_0_INDBE_RANGE 31:28 #define NV_CLASS_HOST_INDCTRL_0_INDBE_WOFFSET 0x0 #define NV_CLASS_HOST_INDCTRL_0_INDBE_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_INDBE_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_INDBE_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_INDBE_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Auto increment of read/write address #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_SHIFT _MK_SHIFT_CONST(27) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDCTRL_0_AUTOINC_SHIFT) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_RANGE 27:27 #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_WOFFSET 0x0 #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_DISABLE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDCTRL_0_AUTOINC_ENABLE _MK_ENUM_CONST(1) // Route return data to spool FIFO, only applicable to reads #define NV_CLASS_HOST_INDCTRL_0_SPOOL_SHIFT _MK_SHIFT_CONST(26) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDCTRL_0_SPOOL_SHIFT) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_RANGE 26:26 #define NV_CLASS_HOST_INDCTRL_0_SPOOL_WOFFSET 0x0 #define NV_CLASS_HOST_INDCTRL_0_SPOOL_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_DISABLE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDCTRL_0_SPOOL_ENABLE _MK_ENUM_CONST(1) // Access type: indirect register or indirect framebuffer #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_SHIFT _MK_SHIFT_CONST(1) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDCTRL_0_ACCTYPE_SHIFT) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_RANGE 1:1 #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_WOFFSET 0x0 #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_REG _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDCTRL_0_ACCTYPE_FB _MK_ENUM_CONST(1) // Read/write #define NV_CLASS_HOST_INDCTRL_0_RWN_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDCTRL_0_RWN_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDCTRL_0_RWN_SHIFT) #define NV_CLASS_HOST_INDCTRL_0_RWN_RANGE 0:0 #define NV_CLASS_HOST_INDCTRL_0_RWN_WOFFSET 0x0 #define NV_CLASS_HOST_INDCTRL_0_RWN_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_RWN_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_RWN_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_RWN_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDCTRL_0_RWN_WRITE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDCTRL_0_RWN_READ _MK_ENUM_CONST(1) // Register NV_CLASS_HOST_INDOFF2_0 #define NV_CLASS_HOST_INDOFF2_0 _MK_ADDR_CONST(0x2c) #define NV_CLASS_HOST_INDOFF2_0_SECURE 0x0 #define NV_CLASS_HOST_INDOFF2_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDOFF2_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_READ_MASK _MK_MASK_CONST(0xfffffffc) #define NV_CLASS_HOST_INDOFF2_0_WRITE_MASK _MK_MASK_CONST(0xfffffffc) // ACCTYPE=FB: framebuffer address #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_SHIFT _MK_SHIFT_CONST(2) #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_FIELD (_MK_MASK_CONST(0x3fffffff) << NV_CLASS_HOST_INDOFF2_0_INDOFFSET_SHIFT) #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_RANGE 31:2 #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDOFFSET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // ACCTYPE=REG: register module ID #define NV_CLASS_HOST_INDOFF2_0_INDMODID_SHIFT _MK_SHIFT_CONST(18) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_INDOFF2_0_INDMODID_SHIFT) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_RANGE 25:18 #define NV_CLASS_HOST_INDOFF2_0_INDMODID_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF2_0_INDMODID_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_HOST1X _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_MPE _MK_ENUM_CONST(1) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_VI _MK_ENUM_CONST(2) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_EPP _MK_ENUM_CONST(3) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_ISP _MK_ENUM_CONST(4) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_GR2D _MK_ENUM_CONST(5) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_GR3D _MK_ENUM_CONST(6) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_DISPLAY _MK_ENUM_CONST(8) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_TVO _MK_ENUM_CONST(11) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_DISPLAYB _MK_ENUM_CONST(9) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_DSI _MK_ENUM_CONST(12) #define NV_CLASS_HOST_INDOFF2_0_INDMODID_HDMI _MK_ENUM_CONST(10) // ACCTYPE=REG: register offset ([15:0]) #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_SHIFT _MK_SHIFT_CONST(2) #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_FIELD (_MK_MASK_CONST(0xffff) << NV_CLASS_HOST_INDOFF2_0_INDROFFSET_SHIFT) #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_RANGE 17:2 #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF2_0_INDROFFSET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDOFF_0 #define NV_CLASS_HOST_INDOFF_0 _MK_ADDR_CONST(0x2d) #define NV_CLASS_HOST_INDOFF_0_SECURE 0x0 #define NV_CLASS_HOST_INDOFF_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDOFF_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDOFF_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) // Byte enables. Will apply to all subsequent data transactions. Not applicable for reads. #define NV_CLASS_HOST_INDOFF_0_INDBE_SHIFT _MK_SHIFT_CONST(28) #define NV_CLASS_HOST_INDOFF_0_INDBE_FIELD (_MK_MASK_CONST(0xf) << NV_CLASS_HOST_INDOFF_0_INDBE_SHIFT) #define NV_CLASS_HOST_INDOFF_0_INDBE_RANGE 31:28 #define NV_CLASS_HOST_INDOFF_0_INDBE_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_INDBE_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDBE_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDBE_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDBE_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Auto increment of read/write address #define NV_CLASS_HOST_INDOFF_0_AUTOINC_SHIFT _MK_SHIFT_CONST(27) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDOFF_0_AUTOINC_SHIFT) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_RANGE 27:27 #define NV_CLASS_HOST_INDOFF_0_AUTOINC_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_AUTOINC_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_DISABLE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDOFF_0_AUTOINC_ENABLE _MK_ENUM_CONST(1) // Route return data to spool FIFO, only applicable to reads #define NV_CLASS_HOST_INDOFF_0_SPOOL_SHIFT _MK_SHIFT_CONST(26) #define NV_CLASS_HOST_INDOFF_0_SPOOL_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDOFF_0_SPOOL_SHIFT) #define NV_CLASS_HOST_INDOFF_0_SPOOL_RANGE 26:26 #define NV_CLASS_HOST_INDOFF_0_SPOOL_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_SPOOL_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_SPOOL_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_SPOOL_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_SPOOL_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_SPOOL_DISABLE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDOFF_0_SPOOL_ENABLE _MK_ENUM_CONST(1) // ACCTYPE=FB: framebuffer address #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_SHIFT _MK_SHIFT_CONST(2) #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_FIELD (_MK_MASK_CONST(0xffffff) << NV_CLASS_HOST_INDOFF_0_INDOFFSET_SHIFT) #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_RANGE 25:2 #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDOFFSET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // ACCTYPE=REG: register module ID #define NV_CLASS_HOST_INDOFF_0_INDMODID_SHIFT _MK_SHIFT_CONST(18) #define NV_CLASS_HOST_INDOFF_0_INDMODID_FIELD (_MK_MASK_CONST(0xff) << NV_CLASS_HOST_INDOFF_0_INDMODID_SHIFT) #define NV_CLASS_HOST_INDOFF_0_INDMODID_RANGE 25:18 #define NV_CLASS_HOST_INDOFF_0_INDMODID_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_INDMODID_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDMODID_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDMODID_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDMODID_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDMODID_HOST1X _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDOFF_0_INDMODID_MPE _MK_ENUM_CONST(1) #define NV_CLASS_HOST_INDOFF_0_INDMODID_VI _MK_ENUM_CONST(2) #define NV_CLASS_HOST_INDOFF_0_INDMODID_EPP _MK_ENUM_CONST(3) #define NV_CLASS_HOST_INDOFF_0_INDMODID_ISP _MK_ENUM_CONST(4) #define NV_CLASS_HOST_INDOFF_0_INDMODID_GR2D _MK_ENUM_CONST(5) #define NV_CLASS_HOST_INDOFF_0_INDMODID_GR3D _MK_ENUM_CONST(6) #define NV_CLASS_HOST_INDOFF_0_INDMODID_DISPLAY _MK_ENUM_CONST(8) #define NV_CLASS_HOST_INDOFF_0_INDMODID_TVO _MK_ENUM_CONST(11) #define NV_CLASS_HOST_INDOFF_0_INDMODID_DISPLAYB _MK_ENUM_CONST(9) #define NV_CLASS_HOST_INDOFF_0_INDMODID_DSI _MK_ENUM_CONST(12) #define NV_CLASS_HOST_INDOFF_0_INDMODID_HDMI _MK_ENUM_CONST(10) // ACCTYPE=REG: register offset ([15:0]) #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_SHIFT _MK_SHIFT_CONST(2) #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_FIELD (_MK_MASK_CONST(0xffff) << NV_CLASS_HOST_INDOFF_0_INDROFFSET_SHIFT) #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_RANGE 17:2 #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_INDROFFSET_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Access type: indirect register or indirect framebuffer #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_SHIFT _MK_SHIFT_CONST(1) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDOFF_0_ACCTYPE_SHIFT) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_RANGE 1:1 #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_REG _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDOFF_0_ACCTYPE_FB _MK_ENUM_CONST(1) // Read/write #define NV_CLASS_HOST_INDOFF_0_RWN_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDOFF_0_RWN_FIELD (_MK_MASK_CONST(0x1) << NV_CLASS_HOST_INDOFF_0_RWN_SHIFT) #define NV_CLASS_HOST_INDOFF_0_RWN_RANGE 0:0 #define NV_CLASS_HOST_INDOFF_0_RWN_WOFFSET 0x0 #define NV_CLASS_HOST_INDOFF_0_RWN_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_RWN_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_RWN_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_RWN_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDOFF_0_RWN_WRITE _MK_ENUM_CONST(0) #define NV_CLASS_HOST_INDOFF_0_RWN_READ _MK_ENUM_CONST(1) // These registers, when written, either writes to the data to the INDOFFSET in // INDOFF or triggers a read of the offset at INDOFFSET. // Register NV_CLASS_HOST_INDDATA_0 #define NV_CLASS_HOST_INDDATA_0 _MK_ADDR_CONST(0x2e) #define NV_CLASS_HOST_INDDATA_0_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_0_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_0_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_0_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_0_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_0_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_0_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_0_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_0_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_0_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_0_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA #define NV_CLASS_HOST_INDDATA _MK_ADDR_CONST(0x2e) #define NV_CLASS_HOST_INDDATA_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_1 #define NV_CLASS_HOST_INDDATA_1 _MK_ADDR_CONST(0x2f) #define NV_CLASS_HOST_INDDATA_1_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_1_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_1_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_1_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_1_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_1_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_1_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_1_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_1_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_1_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_1_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_2 #define NV_CLASS_HOST_INDDATA_2 _MK_ADDR_CONST(0x30) #define NV_CLASS_HOST_INDDATA_2_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_2_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_2_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_2_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_2_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_2_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_2_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_2_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_2_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_2_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_2_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_3 #define NV_CLASS_HOST_INDDATA_3 _MK_ADDR_CONST(0x31) #define NV_CLASS_HOST_INDDATA_3_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_3_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_3_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_3_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_3_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_3_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_3_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_3_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_3_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_3_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_3_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_4 #define NV_CLASS_HOST_INDDATA_4 _MK_ADDR_CONST(0x32) #define NV_CLASS_HOST_INDDATA_4_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_4_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_4_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_4_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_4_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_4_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_4_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_4_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_4_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_4_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_4_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_5 #define NV_CLASS_HOST_INDDATA_5 _MK_ADDR_CONST(0x33) #define NV_CLASS_HOST_INDDATA_5_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_5_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_5_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_5_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_5_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_5_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_5_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_5_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_5_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_5_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_5_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_6 #define NV_CLASS_HOST_INDDATA_6 _MK_ADDR_CONST(0x34) #define NV_CLASS_HOST_INDDATA_6_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_6_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_6_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_6_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_6_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_6_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_6_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_6_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_6_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_6_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_6_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_7 #define NV_CLASS_HOST_INDDATA_7 _MK_ADDR_CONST(0x35) #define NV_CLASS_HOST_INDDATA_7_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_7_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_7_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_7_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_7_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_7_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_7_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_7_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_7_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_7_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_7_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_8 #define NV_CLASS_HOST_INDDATA_8 _MK_ADDR_CONST(0x36) #define NV_CLASS_HOST_INDDATA_8_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_8_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_8_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_8_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_8_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_8_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_8_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_8_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_8_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_8_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_8_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_9 #define NV_CLASS_HOST_INDDATA_9 _MK_ADDR_CONST(0x37) #define NV_CLASS_HOST_INDDATA_9_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_9_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_9_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_9_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_9_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_9_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_9_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_9_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_9_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_9_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_9_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_10 #define NV_CLASS_HOST_INDDATA_10 _MK_ADDR_CONST(0x38) #define NV_CLASS_HOST_INDDATA_10_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_10_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_10_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_10_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_10_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_10_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_10_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_10_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_10_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_10_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_10_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_11 #define NV_CLASS_HOST_INDDATA_11 _MK_ADDR_CONST(0x39) #define NV_CLASS_HOST_INDDATA_11_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_11_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_11_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_11_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_11_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_11_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_11_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_11_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_11_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_11_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_11_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_12 #define NV_CLASS_HOST_INDDATA_12 _MK_ADDR_CONST(0x3a) #define NV_CLASS_HOST_INDDATA_12_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_12_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_12_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_12_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_12_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_12_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_12_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_12_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_12_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_12_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_12_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_13 #define NV_CLASS_HOST_INDDATA_13 _MK_ADDR_CONST(0x3b) #define NV_CLASS_HOST_INDDATA_13_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_13_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_13_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_13_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_13_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_13_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_13_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_13_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_13_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_13_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_13_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_14 #define NV_CLASS_HOST_INDDATA_14 _MK_ADDR_CONST(0x3c) #define NV_CLASS_HOST_INDDATA_14_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_14_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_14_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_14_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_14_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_14_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_14_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_14_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_14_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_14_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_14_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_15 #define NV_CLASS_HOST_INDDATA_15 _MK_ADDR_CONST(0x3d) #define NV_CLASS_HOST_INDDATA_15_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_15_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_15_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_15_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_15_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_15_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_15_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_15_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_15_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_15_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_15_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_16 #define NV_CLASS_HOST_INDDATA_16 _MK_ADDR_CONST(0x3e) #define NV_CLASS_HOST_INDDATA_16_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_16_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_16_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_16_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_16_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_16_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_16_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_16_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_16_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_16_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_16_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_17 #define NV_CLASS_HOST_INDDATA_17 _MK_ADDR_CONST(0x3f) #define NV_CLASS_HOST_INDDATA_17_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_17_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_17_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_17_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_17_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_17_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_17_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_17_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_17_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_17_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_17_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_18 #define NV_CLASS_HOST_INDDATA_18 _MK_ADDR_CONST(0x40) #define NV_CLASS_HOST_INDDATA_18_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_18_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_18_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_18_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_18_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_18_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_18_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_18_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_18_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_18_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_18_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_19 #define NV_CLASS_HOST_INDDATA_19 _MK_ADDR_CONST(0x41) #define NV_CLASS_HOST_INDDATA_19_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_19_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_19_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_19_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_19_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_19_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_19_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_19_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_19_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_19_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_19_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_20 #define NV_CLASS_HOST_INDDATA_20 _MK_ADDR_CONST(0x42) #define NV_CLASS_HOST_INDDATA_20_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_20_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_20_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_20_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_20_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_20_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_20_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_20_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_20_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_20_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_20_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_21 #define NV_CLASS_HOST_INDDATA_21 _MK_ADDR_CONST(0x43) #define NV_CLASS_HOST_INDDATA_21_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_21_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_21_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_21_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_21_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_21_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_21_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_21_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_21_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_21_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_21_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_22 #define NV_CLASS_HOST_INDDATA_22 _MK_ADDR_CONST(0x44) #define NV_CLASS_HOST_INDDATA_22_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_22_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_22_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_22_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_22_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_22_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_22_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_22_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_22_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_22_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_22_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_23 #define NV_CLASS_HOST_INDDATA_23 _MK_ADDR_CONST(0x45) #define NV_CLASS_HOST_INDDATA_23_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_23_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_23_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_23_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_23_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_23_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_23_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_23_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_23_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_23_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_23_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_24 #define NV_CLASS_HOST_INDDATA_24 _MK_ADDR_CONST(0x46) #define NV_CLASS_HOST_INDDATA_24_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_24_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_24_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_24_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_24_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_24_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_24_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_24_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_24_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_24_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_24_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_25 #define NV_CLASS_HOST_INDDATA_25 _MK_ADDR_CONST(0x47) #define NV_CLASS_HOST_INDDATA_25_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_25_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_25_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_25_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_25_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_25_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_25_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_25_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_25_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_25_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_25_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_26 #define NV_CLASS_HOST_INDDATA_26 _MK_ADDR_CONST(0x48) #define NV_CLASS_HOST_INDDATA_26_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_26_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_26_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_26_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_26_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_26_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_26_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_26_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_26_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_26_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_26_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_27 #define NV_CLASS_HOST_INDDATA_27 _MK_ADDR_CONST(0x49) #define NV_CLASS_HOST_INDDATA_27_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_27_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_27_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_27_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_27_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_27_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_27_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_27_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_27_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_27_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_27_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_28 #define NV_CLASS_HOST_INDDATA_28 _MK_ADDR_CONST(0x4a) #define NV_CLASS_HOST_INDDATA_28_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_28_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_28_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_28_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_28_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_28_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_28_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_28_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_28_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_28_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_28_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_29 #define NV_CLASS_HOST_INDDATA_29 _MK_ADDR_CONST(0x4b) #define NV_CLASS_HOST_INDDATA_29_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_29_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_29_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_29_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_29_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_29_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_29_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_29_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_29_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_29_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_29_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Register NV_CLASS_HOST_INDDATA_30 #define NV_CLASS_HOST_INDDATA_30 _MK_ADDR_CONST(0x4c) #define NV_CLASS_HOST_INDDATA_30_SECURE 0x0 #define NV_CLASS_HOST_INDDATA_30_WORD_COUNT 0x1 #define NV_CLASS_HOST_INDDATA_30_RESET_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_RESET_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_SW_DEFAULT_VAL _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_READ_MASK _MK_MASK_CONST(0xffffffff) #define NV_CLASS_HOST_INDDATA_30_WRITE_MASK _MK_MASK_CONST(0xffffffff) // read or write data #define NV_CLASS_HOST_INDDATA_30_INDDATA_SHIFT _MK_SHIFT_CONST(0) #define NV_CLASS_HOST_INDDATA_30_INDDATA_FIELD (_MK_MASK_CONST(0xffffffff) << NV_CLASS_HOST_INDDATA_30_INDDATA_SHIFT) #define NV_CLASS_HOST_INDDATA_30_INDDATA_RANGE 31:0 #define NV_CLASS_HOST_INDDATA_30_INDDATA_WOFFSET 0x0 #define NV_CLASS_HOST_INDDATA_30_INDDATA_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_INDDATA_DEFAULT_MASK _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_INDDATA_SW_DEFAULT _MK_MASK_CONST(0x0) #define NV_CLASS_HOST_INDDATA_30_INDDATA_SW_DEFAULT_MASK _MK_MASK_CONST(0x0) // Reserved address 77 [0x4d] // // REGISTER LIST // #define LIST_ARHOST1X_UCLASS_REGS(_op_) \ _op_(NV_CLASS_HOST_INCR_SYNCPT_0) \ _op_(NV_CLASS_HOST_INCR_SYNCPT_CNTRL_0) \ _op_(NV_CLASS_HOST_INCR_SYNCPT_ERROR_0) \ _op_(NV_CLASS_HOST_WAIT_SYNCPT_0) \ _op_(NV_CLASS_HOST_WAIT_SYNCPT_BASE_0) \ _op_(NV_CLASS_HOST_WAIT_SYNCPT_INCR_0) \ _op_(NV_CLASS_HOST_LOAD_SYNCPT_BASE_0) \ _op_(NV_CLASS_HOST_INCR_SYNCPT_BASE_0) \ _op_(NV_CLASS_HOST_CLEAR_0) \ _op_(NV_CLASS_HOST_WAIT_0) \ _op_(NV_CLASS_HOST_WAIT_WITH_INTR_0) \ _op_(NV_CLASS_HOST_DELAY_USEC_0) \ _op_(NV_CLASS_HOST_TICKCOUNT_HI_0) \ _op_(NV_CLASS_HOST_TICKCOUNT_LO_0) \ _op_(NV_CLASS_HOST_TICKCTRL_0) \ _op_(NV_CLASS_HOST_INDCTRL_0) \ _op_(NV_CLASS_HOST_INDOFF2_0) \ _op_(NV_CLASS_HOST_INDOFF_0) \ _op_(NV_CLASS_HOST_INDDATA_0) \ _op_(NV_CLASS_HOST_INDDATA) \ _op_(NV_CLASS_HOST_INDDATA_1) \ _op_(NV_CLASS_HOST_INDDATA_2) \ _op_(NV_CLASS_HOST_INDDATA_3) \ _op_(NV_CLASS_HOST_INDDATA_4) \ _op_(NV_CLASS_HOST_INDDATA_5) \ _op_(NV_CLASS_HOST_INDDATA_6) \ _op_(NV_CLASS_HOST_INDDATA_7) \ _op_(NV_CLASS_HOST_INDDATA_8) \ _op_(NV_CLASS_HOST_INDDATA_9) \ _op_(NV_CLASS_HOST_INDDATA_10) \ _op_(NV_CLASS_HOST_INDDATA_11) \ _op_(NV_CLASS_HOST_INDDATA_12) \ _op_(NV_CLASS_HOST_INDDATA_13) \ _op_(NV_CLASS_HOST_INDDATA_14) \ _op_(NV_CLASS_HOST_INDDATA_15) \ _op_(NV_CLASS_HOST_INDDATA_16) \ _op_(NV_CLASS_HOST_INDDATA_17) \ _op_(NV_CLASS_HOST_INDDATA_18) \ _op_(NV_CLASS_HOST_INDDATA_19) \ _op_(NV_CLASS_HOST_INDDATA_20) \ _op_(NV_CLASS_HOST_INDDATA_21) \ _op_(NV_CLASS_HOST_INDDATA_22) \ _op_(NV_CLASS_HOST_INDDATA_23) \ _op_(NV_CLASS_HOST_INDDATA_24) \ _op_(NV_CLASS_HOST_INDDATA_25) \ _op_(NV_CLASS_HOST_INDDATA_26) \ _op_(NV_CLASS_HOST_INDDATA_27) \ _op_(NV_CLASS_HOST_INDDATA_28) \ _op_(NV_CLASS_HOST_INDDATA_29) \ _op_(NV_CLASS_HOST_INDDATA_30) // // ADDRESS SPACES // #define BASE_ADDRESS_NV_CLASS_HOST 0x00000000 // // ARHOST1X_UCLASS REGISTER BANKS // #define NV_CLASS_HOST0_FIRST_REG 0x0000 // NV_CLASS_HOST_INCR_SYNCPT_0 #define NV_CLASS_HOST0_LAST_REG 0x0002 // NV_CLASS_HOST_INCR_SYNCPT_ERROR_0 #define NV_CLASS_HOST1_FIRST_REG 0x0008 // NV_CLASS_HOST_WAIT_SYNCPT_0 #define NV_CLASS_HOST1_LAST_REG 0x0013 // NV_CLASS_HOST_TICKCTRL_0 #define NV_CLASS_HOST2_FIRST_REG 0x002b // NV_CLASS_HOST_INDCTRL_0 #define NV_CLASS_HOST2_LAST_REG 0x004c // NV_CLASS_HOST_INDDATA_30 #ifndef _MK_SHIFT_CONST #define _MK_SHIFT_CONST(_constant_) _constant_ #endif #ifndef _MK_MASK_CONST #define _MK_MASK_CONST(_constant_) _constant_ #endif #ifndef _MK_ENUM_CONST #define _MK_ENUM_CONST(_constant_) (_constant_ ## UL) #endif #ifndef _MK_ADDR_CONST #define _MK_ADDR_CONST(_constant_) _constant_ #endif #endif // ifndef ___ARHOST1X_UCLASS_H_INC_
Java
<?php namespace Drupal\dct_user\EventSubscriber; use Drupal\Core\Routing\RouteMatchInterface; use Drupal\Core\Session\AccountInterface; use Drupal\Core\Url; use Symfony\Component\EventDispatcher\EventSubscriberInterface; use Symfony\Component\HttpFoundation\RedirectResponse; use Symfony\Component\HttpFoundation\RequestStack; use Symfony\Component\HttpKernel\Event\GetResponseEvent; use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException; use Symfony\Component\HttpKernel\KernelEvents; /** * Class NotAuthenticatedEventSubscriber. * * @package Drupal\dct_user\EventSubscriber */ class NotAuthenticatedEventSubscriber implements EventSubscriberInterface { /** * The current user. * * @var \Drupal\Core\Session\AccountInterface */ protected $currentUser; /** * The current request. * * @var \Symfony\Component\HttpFoundation\Request */ protected $request; /** * The current route match. * * @var \Drupal\Core\Routing\RouteMatchInterface */ protected $routeMatch; /** * The routes this subscriber should act on. */ const ROUTES = [ 'dct_commerce.ticket_redemption_code', 'entity.commerce_product.canonical', ]; /** * Constructs a new event subscriber. * * @param \Drupal\Core\Session\AccountInterface $current_user * The current user. * @param \Symfony\Component\HttpFoundation\RequestStack $requestStack * The current request stack. * @param \Drupal\Core\Routing\RouteMatchInterface $routeMatch * The current routeMatch. */ public function __construct(AccountInterface $current_user, RequestStack $requestStack, RouteMatchInterface $routeMatch) { $this->request = $requestStack->getCurrentRequest(); $this->currentUser = $current_user; $this->routeMatch = $routeMatch; } /** * {@inheritdoc} */ public static function getSubscribedEvents() { $events[KernelEvents::EXCEPTION][] = ['onKernelException']; return $events; } /** * Redirects on 403 Access Denied kernel exceptions. * * @param \Symfony\Component\HttpKernel\Event\GetResponseEvent $event * The Event to process. */ public function onKernelException(GetResponseEvent $event) { $exception = $event->getException(); if ($exception instanceof AccessDeniedHttpException && $this->currentUser->isAnonymous() && in_array($this->routeMatch->getRouteName(), static::ROUTES)) { $destination = []; if (!empty($this->request->getRequestUri())) { $destination = ['destination' => $this->request->getRequestUri()]; } $url = Url::fromRoute('dct_user.error_page', $destination); $response = new RedirectResponse($url->toString(TRUE)->getGeneratedUrl()); $event->setResponse($response); } } }
Java
using System; using Server.Engines.Craft; namespace Server.Items { [Alterable(typeof(DefBlacksmithy), typeof(DualShortAxes))] [FlipableAttribute(0x1443, 0x1442)] public class TwoHandedAxe : BaseAxe { [Constructable] public TwoHandedAxe() : base(0x1443) { this.Weight = 8.0; } public TwoHandedAxe(Serial serial) : base(serial) { } public override WeaponAbility PrimaryAbility { get { return WeaponAbility.DoubleStrike; } } public override WeaponAbility SecondaryAbility { get { return WeaponAbility.ShadowStrike; } } public override int AosStrengthReq { get { return 40; } } public override int AosMinDamage { get { return 16; } } public override int AosMaxDamage { get { return 19; } } public override int AosSpeed { get { return 31; } } public override float MlSpeed { get { return 3.50f; } } public override int InitMinHits { get { return 31; } } public override int InitMaxHits { get { return 90; } } public override void Serialize(GenericWriter writer) { base.Serialize(writer); writer.Write((int)0); // version } public override void Deserialize(GenericReader reader) { base.Deserialize(reader); int version = reader.ReadInt(); } } }
Java
class ChangeRoleForUsers < ActiveRecord::Migration def change remove_column :users, :role, :string add_column :users, :role, :string, :default=>'user' end end
Java
#include <string.h> #include <stdlib.h> #include "libterm.h" #include "cursor.h" #include "screen.h" #include "bitarr.h" int cursor_visibility(int tid, int sid, char visibility) { if(SCR(tid, sid).curs_invisible != !visibility) { SCR(tid, sid).curs_invisible = !visibility; if(!record_update(tid, sid, visibility ? UPD_CURS : UPD_CURS_INVIS)) { if(ltm_curerr.err_no == ESRCH) return 0; else return -1; } } return 0; } int cursor_abs_move(int tid, int sid, enum axis axis, ushort num) { int ret = 0; uint old; SCR(tid, sid).curs_prev_not_set = 0; switch(axis) { case X: old = SCR(tid, sid).cursor.x; if(num < SCR(tid, sid).cols) SCR(tid, sid).cursor.x = num; else SCR(tid, sid).cursor.x = SCR(tid, sid).cols-1; if(old == SCR(tid, sid).cursor.x) return 0; break; case Y: old = SCR(tid, sid).cursor.y; if(num < SCR(tid, sid).lines) SCR(tid, sid).cursor.y = num; else SCR(tid, sid).cursor.y = SCR(tid, sid).lines-1; if(old == SCR(tid, sid).cursor.y) return 0; break; default: LTM_ERR(EINVAL, "Invalid axis", error); } if(!record_update(tid, sid, UPD_CURS)) { if(ltm_curerr.err_no == ESRCH) return 0; else return -1; } error: return ret; } int cursor_rel_move(int tid, int sid, enum direction direction, ushort num) { int ret = 0; if(!num) return 0; switch(direction) { case UP: return cursor_abs_move(tid, sid, Y, num <= SCR(tid, sid).cursor.y ? SCR(tid, sid).cursor.y - num : 0); case DOWN: return cursor_abs_move(tid, sid, Y, SCR(tid, sid).cursor.y + num); case LEFT: return cursor_abs_move(tid, sid, X, num <= SCR(tid, sid).cursor.x ? SCR(tid, sid).cursor.x - num : 0); case RIGHT: return cursor_abs_move(tid, sid, X, SCR(tid, sid).cursor.x + num); default: LTM_ERR(EINVAL, "Invalid direction", error); } error: return ret; } int cursor_horiz_tab(int tid, int sid) { /* don't hardcode 8 here in the future? */ char dist = 8 - (SCR(tid, sid).cursor.x % 8); return cursor_rel_move(tid, sid, RIGHT, dist); } int cursor_down(int tid, int sid) { if(SCR(tid, sid).cursor.y == SCR(tid, sid).lines-1 && SCR(tid, sid).autoscroll) return screen_scroll(tid, sid); else return cursor_rel_move(tid, sid, DOWN, 1); } int cursor_vertical_tab(int tid, int sid) { if(cursor_down(tid, sid) == -1) return -1; bitarr_unset_index(SCR(tid, sid).wrapped, SCR(tid, sid).cursor.y); return 0; } int cursor_line_break(int tid, int sid) { if(cursor_vertical_tab(tid, sid) == -1) return -1; if(cursor_abs_move(tid, sid, X, 0) == -1) return -1; return 0; } int cursor_wrap(int tid, int sid) { if(cursor_down(tid, sid) == -1) return -1; bitarr_set_index(SCR(tid, sid).wrapped, SCR(tid, sid).cursor.y); if(cursor_abs_move(tid, sid, X, 0) == -1) return -1; return 0; } int cursor_advance(int tid, int sid) { if(SCR(tid, sid).cursor.x == SCR(tid, sid).cols-1) { if(!SCR(tid, sid).curs_prev_not_set) { SCR(tid, sid).curs_prev_not_set = 1; return 0; } return cursor_wrap(tid, sid); } else return cursor_rel_move(tid, sid, RIGHT, 1); }
Java
# Find the native LLVM includes and libraries # # Defines the following variables # LLVM_INCLUDE_DIR - where to find llvm include files # LLVM_LIBRARY_DIR - where to find llvm libs # LLVM_CFLAGS - llvm compiler flags # LLVM_LFLAGS - llvm linker flags # LLVM_MODULE_LIBS - list of llvm libs for working with modules. # LLVM_FOUND - True if llvm found. # LLVM_VERSION - Version string ("llvm-config --version") # # This module reads hints about search locations from variables # LLVM_ROOT - Preferred LLVM installation prefix (containing bin/, lib/, ...) # # Note: One may specify these as environment variables if they are not specified as # CMake variables or cache entries. #============================================================================= # Copyright 2014 Kevin Funk <kfunk@kde.org> # # Distributed under the OSI-approved BSD License (the "License"); # see accompanying file Copyright.txt for details. # # This software is distributed WITHOUT ANY WARRANTY; without even the # implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. # See the License for more information. #============================================================================= if (NOT LLVM_ROOT AND DEFINED ENV{LLVM_ROOT}) file(TO_CMAKE_PATH "$ENV{LLVM_ROOT}" LLVM_ROOT) endif() # if the user specified LLVM_ROOT, use that and fail otherwise if (LLVM_ROOT) find_program(LLVM_CONFIG_EXECUTABLE NAMES llvm-config HINTS ${LLVM_ROOT}/bin DOC "llvm-config executable" NO_DEFAULT_PATH) else() # find llvm-config, prefer the one with a version suffix, e.g. llvm-config-3.3 # note: on some distributions, only 'llvm-config' is shipped, so let's always try to fallback on that find_program(LLVM_CONFIG_EXECUTABLE NAMES llvm-config-${LLVM_FIND_VERSION} llvm-config DOC "llvm-config executable") # other distributions don't ship llvm-config, but only some llvm-config-VERSION binary # try to deduce installed LLVM version by looking up llvm-nm in PATH and *then* find llvm-config-VERSION via that if (NOT LLVM_CONFIG_EXECUTABLE) find_program(_llvmNmExecutable llvm-nm) if (_llvmNmExecutable) execute_process(COMMAND ${_llvmNmExecutable} --version OUTPUT_VARIABLE _out) string(REGEX REPLACE ".*LLVM version ([^ \n]+).*" "\\1" _versionString "${_out}") find_program(LLVM_CONFIG_EXECUTABLE NAMES llvm-config-${_versionString} DOC "llvm-config executable") endif() endif() endif() set(LLVM_FOUND FALSE) if (LLVM_CONFIG_EXECUTABLE) # verify that we've found the correct version of llvm-config execute_process(COMMAND ${LLVM_CONFIG_EXECUTABLE} --version OUTPUT_VARIABLE LLVM_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE) if (NOT LLVM_VERSION) set(_LLVM_ERROR_MESSAGE "Failed to parse version from llvm-config") elseif (LLVM_FIND_VERSION VERSION_GREATER LLVM_VERSION) set(_LLVM_ERROR_MESSAGE "LLVM version too old: ${LLVM_VERSION}") else() message(STATUS "Found LLVM (version: ${LLVM_VERSION}): (using ${LLVM_CONFIG_EXECUTABLE})") set(LLVM_FOUND TRUE) endif() else() set(_LLVM_ERROR_MESSAGE "Could NOT find 'llvm-config' executable") endif() if (LLVM_FOUND) execute_process( COMMAND ${LLVM_CONFIG_EXECUTABLE} --includedir OUTPUT_VARIABLE LLVM_INCLUDE_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND ${LLVM_CONFIG_EXECUTABLE} --libdir OUTPUT_VARIABLE LLVM_LIBRARY_DIR OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND ${LLVM_CONFIG_EXECUTABLE} --cppflags OUTPUT_VARIABLE LLVM_CFLAGS OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND ${LLVM_CONFIG_EXECUTABLE} --ldflags OUTPUT_VARIABLE LLVM_LFLAGS OUTPUT_STRIP_TRAILING_WHITESPACE ) execute_process( COMMAND ${LLVM_CONFIG_EXECUTABLE} --libs core bitreader asmparser analysis OUTPUT_VARIABLE LLVM_MODULE_LIBS OUTPUT_STRIP_TRAILING_WHITESPACE ) endif() if (LLVM_FIND_REQUIRED AND NOT LLVM_FOUND) message(FATAL_ERROR "Could not find LLVM: ${_LLVM_ERROR_MESSAGE}") elseif(_LLVM_ERROR_MESSAGE) message(STATUS "Could not find LLVM: ${_LLVM_ERROR_MESSAGE}") endif()
Java
<?php /* Template Name: Full Width */ ?> <?php get_header(); ?> <div class="row"> <div class="sixteen columns"> <div class="single-page" role="main"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <article <?php post_class(); ?>> <?php /*if(!is_front_page()) { WE DONT WANT THIS ?> <h1 id="post-<?php the_ID(); ?>" class="article-title"> <?php the_title(); ?> </h1> <?php } */?> <section class="post-content"> <?php the_content(); ?> </section><!-- .post-content --> </article> <?php endwhile; ?> <?php comments_template(); ?> <?php else : ?> <h2 class="center"><?php esc_attr_e('Nothing is Here - Page Not Found', ''); ?></h2> <div class="entry-content"> <p><?php esc_attr_e( 'Sorry, but we couldn\'t find what you we\'re looking for.', '' ); ?></p> </div><!-- .entry-content --> <?php endif; ?> </div><!--End Single Article--> </div> </div> <?php get_footer(); ?>
Java
/* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Implementation of the Transmission Control Protocol(TCP). * * Authors: Ross Biro * Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG> * Mark Evans, <evansmp@uhura.aston.ac.uk> * Corey Minyard <wf-rch!minyard@relay.EU.net> * Florian La Roche, <flla@stud.uni-sb.de> * Charles Hedrick, <hedrick@klinzhai.rutgers.edu> * Linus Torvalds, <torvalds@cs.helsinki.fi> * Alan Cox, <gw4pts@gw4pts.ampr.org> * Matthew Dillon, <dillon@apollo.west.oic.com> * Arnt Gulbrandsen, <agulbra@nvg.unit.no> * Jorge Cwik, <jorge@laser.satlink.net> */ /* * Changes: Pedro Roque : Retransmit queue handled by TCP. * : Fragmentation on mtu decrease * : Segment collapse on retransmit * : AF independence * * Linus Torvalds : send_delayed_ack * David S. Miller : Charge memory using the right skb * during syn/ack processing. * David S. Miller : Output engine completely rewritten. * Andrea Arcangeli: SYNACK carry ts_recent in tsecr. * Cacophonix Gaul : draft-minshall-nagle-01 * J Hadi Salim : ECN support * */ #define pr_fmt(fmt) "TCP: " fmt #include <net/mptcp.h> #include <net/ipv6.h> #include <net/tcp.h> #include <linux/compiler.h> #include <linux/gfp.h> #include <linux/module.h> /* People can turn this off for buggy TCP's found in printers etc. */ int sysctl_tcp_retrans_collapse __read_mostly = 1; /* People can turn this on to work with those rare, broken TCPs that * interpret the window field as a signed quantity. */ int sysctl_tcp_workaround_signed_windows __read_mostly = 0; /* Default TSQ limit of two TSO segments */ int sysctl_tcp_limit_output_bytes __read_mostly = 131072; /* This limits the percentage of the congestion window which we * will allow a single TSO frame to consume. Building TSO frames * which are too large can cause TCP streams to be bursty. */ int sysctl_tcp_tso_win_divisor __read_mostly = 3; int sysctl_tcp_mtu_probing __read_mostly = 0; int sysctl_tcp_base_mss __read_mostly = TCP_BASE_MSS; int cnt = 0; /* By default, RFC2861 behavior. */ int sysctl_tcp_slow_start_after_idle __read_mostly = 1; static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, int push_one, gfp_t gfp); /* Account for new data that has been sent to the network. */ void tcp_event_new_data_sent(struct sock *sk, const struct sk_buff *skb) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); unsigned int prior_packets = tp->packets_out; tcp_advance_send_head(sk, skb); tp->snd_nxt = TCP_SKB_CB(skb)->end_seq; tp->packets_out += tcp_skb_pcount(skb); if (!prior_packets || icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS || icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) { tcp_rearm_rto(sk); } } /* SND.NXT, if window was not shrunk. * If window has been shrunk, what should we make? It is not clear at all. * Using SND.UNA we will fail to open window, SND.NXT is out of window. :-( * Anything in between SND.UNA...SND.UNA+SND.WND also can be already * invalid. OK, let's make this for now: */ static inline __u32 tcp_acceptable_seq(const struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); if (!before(tcp_wnd_end(tp), tp->snd_nxt)) return tp->snd_nxt; else return tcp_wnd_end(tp); } /* Calculate mss to advertise in SYN segment. * RFC1122, RFC1063, draft-ietf-tcpimpl-pmtud-01 state that: * * 1. It is independent of path mtu. * 2. Ideally, it is maximal possible segment size i.e. 65535-40. * 3. For IPv4 it is reasonable to calculate it from maximal MTU of * attached devices, because some buggy hosts are confused by * large MSS. * 4. We do not make 3, we advertise MSS, calculated from first * hop device mtu, but allow to raise it to ip_rt_min_advmss. * This may be overridden via information stored in routing table. * 5. Value 65535 for MSS is valid in IPv6 and means "as large as possible, * probably even Jumbo". */ static __u16 tcp_advertise_mss(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); const struct dst_entry *dst = __sk_dst_get(sk); int mss = tp->advmss; if (dst) { unsigned int metric = dst_metric_advmss(dst); if (metric < mss) { mss = metric; tp->advmss = mss; } } return (__u16)mss; } /* RFC2861. Reset CWND after idle period longer RTO to "restart window". * This is the first part of cwnd validation mechanism. */ static void tcp_cwnd_restart(struct sock *sk, const struct dst_entry *dst) { struct tcp_sock *tp = tcp_sk(sk); s32 delta = tcp_time_stamp - tp->lsndtime; u32 restart_cwnd = tcp_init_cwnd(tp, dst); u32 cwnd = tp->snd_cwnd; tcp_ca_event(sk, CA_EVENT_CWND_RESTART); tp->snd_ssthresh = tcp_current_ssthresh(sk); restart_cwnd = min(restart_cwnd, cwnd); while ((delta -= inet_csk(sk)->icsk_rto) > 0 && cwnd > restart_cwnd) cwnd >>= 1; tp->snd_cwnd = max(cwnd, restart_cwnd); tp->snd_cwnd_stamp = tcp_time_stamp; tp->snd_cwnd_used = 0; } /* Congestion state accounting after a packet has been sent. */ static void tcp_event_data_sent(struct tcp_sock *tp, struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); const u32 now = tcp_time_stamp; const struct dst_entry *dst = __sk_dst_get(sk); if (sysctl_tcp_slow_start_after_idle && (!tp->packets_out && (s32)(now - tp->lsndtime) > icsk->icsk_rto)) tcp_cwnd_restart(sk, __sk_dst_get(sk)); tp->lsndtime = now; /* If it is a reply for ato after last received * packet, enter pingpong mode. */ if ((u32)(now - icsk->icsk_ack.lrcvtime) < icsk->icsk_ack.ato && (!dst || !dst_metric(dst, RTAX_QUICKACK))) icsk->icsk_ack.pingpong = 1; } /* Account for an ACK we sent. */ static inline void tcp_event_ack_sent(struct sock *sk, unsigned int pkts) { tcp_dec_quickack_mode(sk, pkts); inet_csk_clear_xmit_timer(sk, ICSK_TIME_DACK); } u32 tcp_default_init_rwnd(u32 mss) { /* Initial receive window should be twice of TCP_INIT_CWND to * enable proper sending of new unsent data during fast recovery * (RFC 3517, Section 4, NextSeg() rule (2)). Further place a * limit when mss is larger than 1460. */ u32 init_rwnd = TCP_INIT_CWND * 2; if (mss > 1460) init_rwnd = max((1460 * init_rwnd) / mss, 2U); return init_rwnd; } /* Determine a window scaling and initial window to offer. * Based on the assumption that the given amount of space * will be offered. Store the results in the tp structure. * NOTE: for smooth operation initial space offering should * be a multiple of mss if possible. We assume here that mss >= 1. * This MUST be enforced by all callers. */ void tcp_select_initial_window(int __space, __u32 mss, __u32 *rcv_wnd, __u32 *window_clamp, int wscale_ok, __u8 *rcv_wscale, __u32 init_rcv_wnd, const struct sock *sk) { unsigned int space; if (tcp_sk(sk)->mpc) mptcp_select_initial_window(&__space, window_clamp, sk); space = (__space < 0 ? 0 : __space); /* If no clamp set the clamp to the max possible scaled window */ if (*window_clamp == 0) (*window_clamp) = (65535 << 14); space = min(*window_clamp, space); /* Quantize space offering to a multiple of mss if possible. */ if (space > mss) space = (space / mss) * mss; /* NOTE: offering an initial window larger than 32767 * will break some buggy TCP stacks. If the admin tells us * it is likely we could be speaking with such a buggy stack * we will truncate our initial window offering to 32K-1 * unless the remote has sent us a window scaling option, * which we interpret as a sign the remote TCP is not * misinterpreting the window field as a signed quantity. */ if (sysctl_tcp_workaround_signed_windows) (*rcv_wnd) = min(space, MAX_TCP_WINDOW); else (*rcv_wnd) = space; (*rcv_wscale) = 0; if (wscale_ok) { /* Set window scaling on max possible window * See RFC1323 for an explanation of the limit to 14 */ space = max_t(u32, sysctl_tcp_rmem[2], sysctl_rmem_max); space = min_t(u32, space, *window_clamp); while (space > 65535 && (*rcv_wscale) < 14) { space >>= 1; (*rcv_wscale)++; } } if (mss > (1 << *rcv_wscale)) { if (!init_rcv_wnd) /* Use default unless specified otherwise */ init_rcv_wnd = tcp_default_init_rwnd(mss); *rcv_wnd = min(*rcv_wnd, init_rcv_wnd * mss); } /* Set the clamp no higher than max representable value */ (*window_clamp) = min(65535U << (*rcv_wscale), *window_clamp); } EXPORT_SYMBOL(tcp_select_initial_window); /* Chose a new window to advertise, update state in tcp_sock for the * socket, and return result with RFC1323 scaling applied. The return * value can be stuffed directly into th->window for an outgoing * frame. */ static u16 tcp_select_window(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); /* The window must never shrink at the meta-level. At the subflow we * have to allow this. Otherwise we may announce a window too large * for the current meta-level sk_rcvbuf. */ u32 cur_win = tcp_receive_window(tp->mpc ? tcp_sk(mptcp_meta_sk(sk)) : tp); u32 new_win = __tcp_select_window(sk); /* Never shrink the offered window */ if (new_win < cur_win) { /* Danger Will Robinson! * Don't update rcv_wup/rcv_wnd here or else * we will not be able to advertise a zero * window in time. --DaveM * * Relax Will Robinson. */ new_win = ALIGN(cur_win, 1 << tp->rx_opt.rcv_wscale); } if (tp->mpc) { mptcp_meta_tp(tp)->rcv_wnd = new_win; mptcp_meta_tp(tp)->rcv_wup = mptcp_meta_tp(tp)->rcv_nxt; } tp->rcv_wnd = new_win; tp->rcv_wup = tp->rcv_nxt; /* Make sure we do not exceed the maximum possible * scaled window. */ if (!tp->rx_opt.rcv_wscale && sysctl_tcp_workaround_signed_windows) new_win = min(new_win, MAX_TCP_WINDOW); else new_win = min(new_win, (65535U << tp->rx_opt.rcv_wscale)); /* RFC1323 scaling applied */ new_win >>= tp->rx_opt.rcv_wscale; /* If we advertise zero window, disable fast path. */ if (new_win == 0) tp->pred_flags = 0; return new_win; } /* Packet ECN state for a SYN-ACK */ static inline void TCP_ECN_send_synack(const struct tcp_sock *tp, struct sk_buff *skb) { TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_CWR; if (!(tp->ecn_flags & TCP_ECN_OK)) TCP_SKB_CB(skb)->tcp_flags &= ~TCPHDR_ECE; } /* Packet ECN state for a SYN. */ static inline void TCP_ECN_send_syn(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); tp->ecn_flags = 0; if (sock_net(sk)->ipv4.sysctl_tcp_ecn == 1) { TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ECE | TCPHDR_CWR; tp->ecn_flags = TCP_ECN_OK; } } static __inline__ void TCP_ECN_make_synack(const struct request_sock *req, struct tcphdr *th) { if (inet_rsk(req)->ecn_ok) th->ece = 1; } /* Set up ECN state for a packet on a ESTABLISHED socket that is about to * be sent. */ static inline void TCP_ECN_send(struct sock *sk, struct sk_buff *skb, int tcp_header_len) { struct tcp_sock *tp = tcp_sk(sk); if (tp->ecn_flags & TCP_ECN_OK) { /* Not-retransmitted data segment: set ECT and inject CWR. */ if (skb->len != tcp_header_len && !before(TCP_SKB_CB(skb)->seq, tp->snd_nxt)) { INET_ECN_xmit(sk); if (tp->ecn_flags & TCP_ECN_QUEUE_CWR) { tp->ecn_flags &= ~TCP_ECN_QUEUE_CWR; tcp_hdr(skb)->cwr = 1; skb_shinfo(skb)->gso_type |= SKB_GSO_TCP_ECN; } } else { /* ACK or retransmitted segment: clear ECT|CE */ INET_ECN_dontxmit(sk); } if (tp->ecn_flags & TCP_ECN_DEMAND_CWR) tcp_hdr(skb)->ece = 1; } } /* Constructs common control bits of non-data skb. If SYN/FIN is present, * auto increment end seqno. */ void tcp_init_nondata_skb(struct sk_buff *skb, u32 seq, u8 flags) { skb->ip_summed = CHECKSUM_PARTIAL; skb->csum = 0; TCP_SKB_CB(skb)->tcp_flags = flags; TCP_SKB_CB(skb)->sacked = 0; skb_shinfo(skb)->gso_segs = 1; skb_shinfo(skb)->gso_size = 0; skb_shinfo(skb)->gso_type = 0; TCP_SKB_CB(skb)->seq = seq; if (flags & (TCPHDR_SYN | TCPHDR_FIN)) seq++; TCP_SKB_CB(skb)->end_seq = seq; } bool tcp_urg_mode(const struct tcp_sock *tp) { return tp->snd_una != tp->snd_up; } #define OPTION_SACK_ADVERTISE (1 << 0) #define OPTION_TS (1 << 1) #define OPTION_MD5 (1 << 2) #define OPTION_WSCALE (1 << 3) #define OPTION_FAST_OPEN_COOKIE (1 << 8) /* Before adding here - take a look at OPTION_MPTCP in include/net/mptcp.h */ /* Write previously computed TCP options to the packet. * * Beware: Something in the Internet is very sensitive to the ordering of * TCP options, we learned this through the hard way, so be careful here. * Luckily we can at least blame others for their non-compliance but from * inter-operatibility perspective it seems that we're somewhat stuck with * the ordering which we have been using if we want to keep working with * those broken things (not that it currently hurts anybody as there isn't * particular reason why the ordering would need to be changed). * * At least SACK_PERM as the first option is known to lead to a disaster * (but it may well be that other scenarios fail similarly). */ static void tcp_options_write(__be32 *ptr, struct tcp_sock *tp, struct tcp_out_options *opts, struct sk_buff *skb) { u16 options = opts->options; /* mungable copy */ if (unlikely(OPTION_MD5 & options)) { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_MD5SIG << 8) | TCPOLEN_MD5SIG); /* overload cookie hash location */ opts->hash_location = (__u8 *)ptr; ptr += 4; } if (unlikely(opts->mss)) { *ptr++ = htonl((TCPOPT_MSS << 24) | (TCPOLEN_MSS << 16) | opts->mss); } if (likely(OPTION_TS & options)) { if (unlikely(OPTION_SACK_ADVERTISE & options)) { *ptr++ = htonl((TCPOPT_SACK_PERM << 24) | (TCPOLEN_SACK_PERM << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); options &= ~OPTION_SACK_ADVERTISE; } else { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_TIMESTAMP << 8) | TCPOLEN_TIMESTAMP); } *ptr++ = htonl(opts->tsval); *ptr++ = htonl(opts->tsecr); } if (unlikely(OPTION_SACK_ADVERTISE & options)) { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_SACK_PERM << 8) | TCPOLEN_SACK_PERM); } if (unlikely(OPTION_WSCALE & options)) { *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_WINDOW << 16) | (TCPOLEN_WINDOW << 8) | opts->ws); } if (unlikely(opts->num_sack_blocks)) { struct tcp_sack_block *sp = tp->rx_opt.dsack ? tp->duplicate_sack : tp->selective_acks; int this_sack; *ptr++ = htonl((TCPOPT_NOP << 24) | (TCPOPT_NOP << 16) | (TCPOPT_SACK << 8) | (TCPOLEN_SACK_BASE + (opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK))); for (this_sack = 0; this_sack < opts->num_sack_blocks; ++this_sack) { *ptr++ = htonl(sp[this_sack].start_seq); *ptr++ = htonl(sp[this_sack].end_seq); } tp->rx_opt.dsack = 0; } if (unlikely(OPTION_FAST_OPEN_COOKIE & options)) { struct tcp_fastopen_cookie *foc = opts->fastopen_cookie; *ptr++ = htonl((TCPOPT_EXP << 24) | ((TCPOLEN_EXP_FASTOPEN_BASE + foc->len) << 16) | TCPOPT_FASTOPEN_MAGIC); memcpy(ptr, foc->val, foc->len); if ((foc->len & 3) == 2) { u8 *align = ((u8 *)ptr) + foc->len; align[0] = align[1] = TCPOPT_NOP; } ptr += (foc->len + 3) >> 2; } if (unlikely(OPTION_MPTCP & opts->options)) mptcp_options_write(ptr, tp, opts, skb); } /* Compute TCP options for SYN packets. This is not the final * network wire format yet. */ static unsigned int tcp_syn_options(struct sock *sk, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_md5sig_key **md5) { struct tcp_sock *tp = tcp_sk(sk); unsigned int remaining = MAX_TCP_OPTION_SPACE; struct tcp_fastopen_request *fastopen = tp->fastopen_req; #ifdef CONFIG_TCP_MD5SIG *md5 = tp->af_specific->md5_lookup(sk, sk); if (*md5) { opts->options |= OPTION_MD5; remaining -= TCPOLEN_MD5SIG_ALIGNED; } #else *md5 = NULL; #endif /* We always get an MSS option. The option bytes which will be seen in * normal data packets should timestamps be used, must be in the MSS * advertised. But we subtract them from tp->mss_cache so that * calculations in tcp_sendmsg are simpler etc. So account for this * fact here if necessary. If we don't do this correctly, as a * receiver we won't recognize data packets as being full sized when we * should, and thus we won't abide by the delayed ACK rules correctly. * SACKs don't matter, we never delay an ACK when we have any of those * going out. */ opts->mss = tcp_advertise_mss(sk); remaining -= TCPOLEN_MSS_ALIGNED; if (likely(sysctl_tcp_timestamps && *md5 == NULL)) { opts->options |= OPTION_TS; opts->tsval = TCP_SKB_CB(skb)->when + tp->tsoffset; opts->tsecr = tp->rx_opt.ts_recent; remaining -= TCPOLEN_TSTAMP_ALIGNED; } if (likely(sysctl_tcp_window_scaling)) { opts->ws = tp->rx_opt.rcv_wscale; opts->options |= OPTION_WSCALE; remaining -= TCPOLEN_WSCALE_ALIGNED; } if (likely(sysctl_tcp_sack)) { opts->options |= OPTION_SACK_ADVERTISE; if (unlikely(!(OPTION_TS & opts->options))) remaining -= TCPOLEN_SACKPERM_ALIGNED; } if (tp->request_mptcp || tp->mpc) mptcp_syn_options(sk, opts, &remaining); if (fastopen && fastopen->cookie.len >= 0) { u32 need = TCPOLEN_EXP_FASTOPEN_BASE + fastopen->cookie.len; need = (need + 3) & ~3U; /* Align to 32 bits */ if (remaining >= need) { opts->options |= OPTION_FAST_OPEN_COOKIE; opts->fastopen_cookie = &fastopen->cookie; remaining -= need; tp->syn_fastopen = 1; } } return MAX_TCP_OPTION_SPACE - remaining; } /* Set up TCP options for SYN-ACKs. */ static unsigned int tcp_synack_options(struct sock *sk, struct request_sock *req, unsigned int mss, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_md5sig_key **md5, struct tcp_fastopen_cookie *foc) { struct inet_request_sock *ireq = inet_rsk(req); unsigned int remaining = MAX_TCP_OPTION_SPACE; #ifdef CONFIG_TCP_MD5SIG *md5 = tcp_rsk(req)->af_specific->md5_lookup(sk, req); if (*md5) { opts->options |= OPTION_MD5; remaining -= TCPOLEN_MD5SIG_ALIGNED; /* We can't fit any SACK blocks in a packet with MD5 + TS * options. There was discussion about disabling SACK * rather than TS in order to fit in better with old, * buggy kernels, but that was deemed to be unnecessary. */ ireq->tstamp_ok &= !ireq->sack_ok; } #else *md5 = NULL; #endif /* We always send an MSS option. */ opts->mss = mss; remaining -= TCPOLEN_MSS_ALIGNED; if (likely(ireq->wscale_ok)) { opts->ws = ireq->rcv_wscale; opts->options |= OPTION_WSCALE; remaining -= TCPOLEN_WSCALE_ALIGNED; } if (likely(ireq->tstamp_ok)) { opts->options |= OPTION_TS; opts->tsval = TCP_SKB_CB(skb)->when; opts->tsecr = req->ts_recent; remaining -= TCPOLEN_TSTAMP_ALIGNED; } if (likely(ireq->sack_ok)) { opts->options |= OPTION_SACK_ADVERTISE; if (unlikely(!ireq->tstamp_ok)) remaining -= TCPOLEN_SACKPERM_ALIGNED; } if (foc != NULL) { u32 need = TCPOLEN_EXP_FASTOPEN_BASE + foc->len; need = (need + 3) & ~3U; /* Align to 32 bits */ if (remaining >= need) { opts->options |= OPTION_FAST_OPEN_COOKIE; opts->fastopen_cookie = foc; remaining -= need; } } if (tcp_rsk(req)->saw_mpc) mptcp_synack_options(req, opts, &remaining); return MAX_TCP_OPTION_SPACE - remaining; } /* Compute TCP options for ESTABLISHED sockets. This is not the * final wire format yet. */ static unsigned int tcp_established_options(struct sock *sk, struct sk_buff *skb, struct tcp_out_options *opts, struct tcp_md5sig_key **md5) { struct tcp_skb_cb *tcb = skb ? TCP_SKB_CB(skb) : NULL; struct tcp_sock *tp = tcp_sk(sk); unsigned int size = 0; unsigned int eff_sacks; #ifdef CONFIG_TCP_MD5SIG *md5 = tp->af_specific->md5_lookup(sk, sk); if (unlikely(*md5)) { opts->options |= OPTION_MD5; size += TCPOLEN_MD5SIG_ALIGNED; } #else *md5 = NULL; #endif if (likely(tp->rx_opt.tstamp_ok)) { opts->options |= OPTION_TS; opts->tsval = tcb ? tcb->when + tp->tsoffset : 0; opts->tsecr = tp->rx_opt.ts_recent; size += TCPOLEN_TSTAMP_ALIGNED; } if (tp->mpc) mptcp_established_options(sk, skb, opts, &size); eff_sacks = tp->rx_opt.num_sacks + tp->rx_opt.dsack; if (unlikely(eff_sacks)) { const unsigned remaining = MAX_TCP_OPTION_SPACE - size; if (remaining < TCPOLEN_SACK_BASE_ALIGNED) opts->num_sack_blocks = 0; else opts->num_sack_blocks = min_t(unsigned int, eff_sacks, (remaining - TCPOLEN_SACK_BASE_ALIGNED) / TCPOLEN_SACK_PERBLOCK); if (opts->num_sack_blocks) size += TCPOLEN_SACK_BASE_ALIGNED + opts->num_sack_blocks * TCPOLEN_SACK_PERBLOCK; } return size; } /* TCP SMALL QUEUES (TSQ) * * TSQ goal is to keep small amount of skbs per tcp flow in tx queues (qdisc+dev) * to reduce RTT and bufferbloat. * We do this using a special skb destructor (tcp_wfree). * * Its important tcp_wfree() can be replaced by sock_wfree() in the event skb * needs to be reallocated in a driver. * The invariant being skb->truesize substracted from sk->sk_wmem_alloc * * Since transmit from skb destructor is forbidden, we use a tasklet * to process all sockets that eventually need to send more skbs. * We use one tasklet per cpu, with its own queue of sockets. */ struct tsq_tasklet { struct tasklet_struct tasklet; struct list_head head; /* queue of tcp sockets */ }; static DEFINE_PER_CPU(struct tsq_tasklet, tsq_tasklet); static void tcp_tsq_handler(struct sock *sk) { if ((1 << sk->sk_state) & (TCPF_ESTABLISHED | TCPF_FIN_WAIT1 | TCPF_CLOSING | TCPF_CLOSE_WAIT | TCPF_LAST_ACK)) tcp_write_xmit(sk, tcp_current_mss(sk), 0, 0, GFP_ATOMIC); } /* * One tasklest per cpu tries to send more skbs. * We run in tasklet context but need to disable irqs when * transfering tsq->head because tcp_wfree() might * interrupt us (non NAPI drivers) */ static void tcp_tasklet_func(unsigned long data) { struct tsq_tasklet *tsq = (struct tsq_tasklet *)data; LIST_HEAD(list); unsigned long flags; struct list_head *q, *n; struct tcp_sock *tp; struct sock *sk, *meta_sk; local_irq_save(flags); list_splice_init(&tsq->head, &list); local_irq_restore(flags); list_for_each_safe(q, n, &list) { tp = list_entry(q, struct tcp_sock, tsq_node); list_del(&tp->tsq_node); sk = (struct sock *)tp; meta_sk = tp->mpc ? mptcp_meta_sk(sk) : sk; bh_lock_sock(meta_sk); if (!sock_owned_by_user(meta_sk)) { tcp_tsq_handler(sk); if (tp->mpc) tcp_tsq_handler(meta_sk); } else { /* defer the work to tcp_release_cb() */ set_bit(TCP_TSQ_DEFERRED, &tp->tsq_flags); /* For MPTCP, we set the tsq-bit on the meta, and the * subflow as we don't know if the limitation happened * while inside mptcp_write_xmit or during tcp_write_xmit. */ if (tp->mpc) { set_bit(TCP_TSQ_DEFERRED, &tcp_sk(meta_sk)->tsq_flags); mptcp_tsq_flags(sk); } } bh_unlock_sock(meta_sk); clear_bit(TSQ_QUEUED, &tp->tsq_flags); sk_free(sk); } } #define TCP_DEFERRED_ALL ((1UL << TCP_TSQ_DEFERRED) | \ (1UL << TCP_WRITE_TIMER_DEFERRED) | \ (1UL << TCP_DELACK_TIMER_DEFERRED) | \ (1UL << TCP_MTU_REDUCED_DEFERRED) | \ (1UL << MPTCP_PATH_MANAGER) | \ (1UL << MPTCP_SUB_DEFERRED)) /** * tcp_release_cb - tcp release_sock() callback * @sk: socket * * called from release_sock() to perform protocol dependent * actions before socket release. */ void tcp_release_cb(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); unsigned long flags, nflags; /* perform an atomic operation only if at least one flag is set */ do { flags = tp->tsq_flags; if (!(flags & TCP_DEFERRED_ALL)) return; nflags = flags & ~TCP_DEFERRED_ALL; } while (cmpxchg(&tp->tsq_flags, flags, nflags) != flags); if (flags & (1UL << TCP_TSQ_DEFERRED)) tcp_tsq_handler(sk); if (flags & (1UL << TCP_WRITE_TIMER_DEFERRED)) { tcp_write_timer_handler(sk); __sock_put(sk); } if (flags & (1UL << TCP_DELACK_TIMER_DEFERRED)) { tcp_delack_timer_handler(sk); __sock_put(sk); } if (flags & (1UL << TCP_MTU_REDUCED_DEFERRED)) { sk->sk_prot->mtu_reduced(sk); __sock_put(sk); } if (flags & (1UL << MPTCP_PATH_MANAGER)) { if (tcp_sk(sk)->mpcb->pm_ops->release_sock) tcp_sk(sk)->mpcb->pm_ops->release_sock(sk); __sock_put(sk); } if (flags & (1UL << MPTCP_SUB_DEFERRED)) mptcp_tsq_sub_deferred(sk); } EXPORT_SYMBOL(tcp_release_cb); void __init tcp_tasklet_init(void) { int i; for_each_possible_cpu(i) { struct tsq_tasklet *tsq = &per_cpu(tsq_tasklet, i); INIT_LIST_HEAD(&tsq->head); tasklet_init(&tsq->tasklet, tcp_tasklet_func, (unsigned long)tsq); } } /* * Write buffer destructor automatically called from kfree_skb. * We cant xmit new skbs from this context, as we might already * hold qdisc lock. */ void tcp_wfree(struct sk_buff *skb) { struct sock *sk = skb->sk; struct tcp_sock *tp = tcp_sk(sk); if (test_and_clear_bit(TSQ_THROTTLED, &tp->tsq_flags) && !test_and_set_bit(TSQ_QUEUED, &tp->tsq_flags)) { unsigned long flags; struct tsq_tasklet *tsq; /* Keep a ref on socket. * This last ref will be released in tcp_tasklet_func() */ atomic_sub(skb->truesize - 1, &sk->sk_wmem_alloc); /* queue this socket to tasklet queue */ local_irq_save(flags); tsq = &__get_cpu_var(tsq_tasklet); list_add(&tp->tsq_node, &tsq->head); tasklet_schedule(&tsq->tasklet); local_irq_restore(flags); } else { sock_wfree(skb); } } /* This routine actually transmits TCP packets queued in by * tcp_do_sendmsg(). This is used by both the initial * transmission and possible later retransmissions. * All SKB's seen here are completely headerless. It is our * job to build the TCP header, and pass the packet down to * IP so it can do the same plus pass the packet off to the * device. * * We are working here with either a clone of the original * SKB, or a fresh unique copy made by the retransmit engine. */ int tcp_transmit_skb(struct sock *sk, struct sk_buff *skb, int clone_it, gfp_t gfp_mask) { const struct inet_connection_sock *icsk = inet_csk(sk); struct inet_sock *inet; struct tcp_sock *tp; struct tcp_skb_cb *tcb; struct tcp_out_options opts; unsigned int tcp_options_size, tcp_header_size; struct tcp_md5sig_key *md5; struct tcphdr *th; int err; BUG_ON(!skb || !tcp_skb_pcount(skb)); /* If congestion control is doing timestamping, we must * take such a timestamp before we potentially clone/copy. */ if (icsk->icsk_ca_ops->flags & TCP_CONG_RTT_STAMP) __net_timestamp(skb); if (likely(clone_it)) { const struct sk_buff *fclone = skb + 1; if (unlikely(skb->fclone == SKB_FCLONE_ORIG && fclone->fclone == SKB_FCLONE_CLONE)) NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPSPURIOUS_RTX_HOSTQUEUES); if (unlikely(skb_cloned(skb))) { struct sk_buff *newskb; if (mptcp_is_data_seq(skb)) skb_push(skb, MPTCP_SUB_LEN_DSS_ALIGN + MPTCP_SUB_LEN_ACK_ALIGN + MPTCP_SUB_LEN_SEQ_ALIGN); newskb = pskb_copy(skb, gfp_mask); if (mptcp_is_data_seq(skb)) { skb_pull(skb, MPTCP_SUB_LEN_DSS_ALIGN + MPTCP_SUB_LEN_ACK_ALIGN + MPTCP_SUB_LEN_SEQ_ALIGN); if (newskb) skb_pull(newskb, MPTCP_SUB_LEN_DSS_ALIGN + MPTCP_SUB_LEN_ACK_ALIGN + MPTCP_SUB_LEN_SEQ_ALIGN); } skb = newskb; } else { skb = skb_clone(skb, gfp_mask); } if (unlikely(!skb)) return -ENOBUFS; } inet = inet_sk(sk); tp = tcp_sk(sk); tcb = TCP_SKB_CB(skb); memset(&opts, 0, sizeof(opts)); if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) tcp_options_size = tcp_syn_options(sk, skb, &opts, &md5); else tcp_options_size = tcp_established_options(sk, skb, &opts, &md5); tcp_header_size = tcp_options_size + sizeof(struct tcphdr); if (tcp_packets_in_flight(tp) == 0) tcp_ca_event(sk, CA_EVENT_TX_START); /* if no packet is in qdisc/device queue, then allow XPS to select * another queue. */ skb->ooo_okay = sk_wmem_alloc_get(sk) == 0; skb_push(skb, tcp_header_size); skb_reset_transport_header(skb); skb_orphan(skb); skb->sk = sk; skb->destructor = (sysctl_tcp_limit_output_bytes > 0) ? tcp_wfree : sock_wfree; atomic_add(skb->truesize, &sk->sk_wmem_alloc); /* Build TCP header and checksum it. */ th = tcp_hdr(skb); th->source = inet->inet_sport; th->dest = inet->inet_dport; //printf("[transmit:]%5u, %5u\n", ntohs(inet->inet_sport), ntohs(inet->inet_dport)); th->seq = htonl(tcb->seq); th->ack_seq = htonl(tp->rcv_nxt); *(((__be16 *)th) + 6) = htons(((tcp_header_size >> 2) << 12) | tcb->tcp_flags); if (unlikely(tcb->tcp_flags & TCPHDR_SYN)) { /* RFC1323: The window in SYN & SYN/ACK segments * is never scaled. */ th->window = htons(min(tp->rcv_wnd, 65535U)); } else { th->window = htons(tcp_select_window(sk)); } th->check = 0; th->urg_ptr = 0; /* The urg_mode check is necessary during a below snd_una win probe */ if (unlikely(tcp_urg_mode(tp) && before(tcb->seq, tp->snd_up))) { if (before(tp->snd_up, tcb->seq + 0x10000)) { th->urg_ptr = htons(tp->snd_up - tcb->seq); th->urg = 1; } else if (after(tcb->seq + 0xFFFF, tp->snd_nxt)) { th->urg_ptr = htons(0xFFFF); th->urg = 1; } } tcp_options_write((__be32 *)(th + 1), tp, &opts, skb); if (likely((tcb->tcp_flags & TCPHDR_SYN) == 0)) TCP_ECN_send(sk, skb, tcp_header_size); #ifdef CONFIG_TCP_MD5SIG /* Calculate the MD5 hash, as we have all we need now */ if (md5) { sk_nocaps_add(sk, NETIF_F_GSO_MASK); tp->af_specific->calc_md5_hash(opts.hash_location, md5, sk, NULL, skb); } #endif icsk->icsk_af_ops->send_check(sk, skb); if (likely(tcb->tcp_flags & TCPHDR_ACK)) tcp_event_ack_sent(sk, tcp_skb_pcount(skb)); if (skb->len != tcp_header_size) tcp_event_data_sent(tp, sk); if (after(tcb->end_seq, tp->snd_nxt) || tcb->seq == tcb->end_seq) TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS, tcp_skb_pcount(skb)); /* if(sk->__sk_common.lane_info == 0) printf("[transmit_skb]lane:%d, is_path:%d, %d, %d\n", sk->__sk_common.lane_info, sk->__sk_common.is_path, sk->__sk_common.skc_daddr, sk->__sk_common.skc_rcv_saddr); */ if(sk->__sk_common.is_path == 1){ //printf("[transmit_skb]lane:%d, is_path:%d, %d, %d\n", sk->__sk_common.lane_info, sk->__sk_common.is_path, sk->__sk_common.skc_daddr, sk->__sk_common.skc_rcv_saddr); if(sk->__sk_common.lane_info == 0){ tcp_sk(sk)->snd_cwnd = 0; } //printf("hit!:%d\n", tcp_sk(sk)->snd_cwnd); } else{ if(sk->__sk_common.lane_info == 1){ tcp_sk(sk)->snd_cwnd = 2; } } err = icsk->icsk_af_ops->queue_xmit(skb, &inet->cork.fl); if (likely(err <= 0)) return err; tcp_enter_cwr(sk, 1); return net_xmit_eval(err); } /* This routine just queues the buffer for sending. * * NOTE: probe0 timer is not checked, do not forget tcp_push_pending_frames, * otherwise socket can stall. */ void tcp_queue_skb(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); /* Advance write_seq and place onto the write_queue. */ tp->write_seq = TCP_SKB_CB(skb)->end_seq; skb_header_release(skb); tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); } /* Initialize TSO segments for a packet. */ void tcp_set_skb_tso_segs(const struct sock *sk, struct sk_buff *skb, unsigned int mss_now) { if (skb->len <= mss_now || (is_meta_sk(sk) && !mptcp_sk_can_gso(sk)) || (!is_meta_sk(sk) && !sk_can_gso(sk)) || skb->ip_summed == CHECKSUM_NONE) { /* Avoid the costly divide in the normal * non-TSO case. */ skb_shinfo(skb)->gso_segs = 1; skb_shinfo(skb)->gso_size = 0; skb_shinfo(skb)->gso_type = 0; } else { skb_shinfo(skb)->gso_segs = DIV_ROUND_UP(skb->len, mss_now); skb_shinfo(skb)->gso_size = mss_now; skb_shinfo(skb)->gso_type = sk->sk_gso_type; } } /* When a modification to fackets out becomes necessary, we need to check * skb is counted to fackets_out or not. */ static void tcp_adjust_fackets_out(struct sock *sk, const struct sk_buff *skb, int decr) { struct tcp_sock *tp = tcp_sk(sk); if (!tp->sacked_out || tcp_is_reno(tp)) return; if (after(tcp_highest_sack_seq(tp), TCP_SKB_CB(skb)->seq)) tp->fackets_out -= decr; } /* Pcount in the middle of the write queue got changed, we need to do various * tweaks to fix counters */ void tcp_adjust_pcount(struct sock *sk, const struct sk_buff *skb, int decr) { struct tcp_sock *tp = tcp_sk(sk); tp->packets_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) tp->sacked_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) tp->retrans_out -= decr; if (TCP_SKB_CB(skb)->sacked & TCPCB_LOST) tp->lost_out -= decr; /* Reno case is special. Sigh... */ if (tcp_is_reno(tp) && decr > 0) tp->sacked_out -= min_t(u32, tp->sacked_out, decr); tcp_adjust_fackets_out(sk, skb, decr); if (tp->lost_skb_hint && before(TCP_SKB_CB(skb)->seq, TCP_SKB_CB(tp->lost_skb_hint)->seq) && (tcp_is_fack(tp) || (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED))) tp->lost_cnt_hint -= decr; tcp_verify_left_out(tp); } /* Function to create two new TCP segments. Shrinks the given segment * to the specified size and appends a new segment with the rest of the * packet to the list. This won't be called frequently, I hope. * Remember, these are still headerless SKBs at this point. */ int tcp_fragment(struct sock *sk, struct sk_buff *skb, u32 len, unsigned int mss_now) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int nsize, old_factor; int nlen; u8 flags; if (tcp_sk(sk)->mpc && mptcp_is_data_seq(skb)) mptcp_fragment(sk, skb, len, mss_now, 0); if (WARN_ON(len > skb->len)) return -EINVAL; nsize = skb_headlen(skb) - len; if (nsize < 0) nsize = 0; if (skb_cloned(skb) && skb_is_nonlinear(skb) && pskb_expand_head(skb, 0, 0, GFP_ATOMIC)) return -ENOMEM; /* Get a new skb... force flag on. */ buff = sk_stream_alloc_skb(sk, nsize, GFP_ATOMIC); if (buff == NULL) return -ENOMEM; /* We'll just try again later. */ sk->sk_wmem_queued += buff->truesize; sk_mem_charge(sk, buff->truesize); nlen = skb->len - len - nsize; buff->truesize += nlen; skb->truesize -= nlen; /* Correct the sequence numbers. */ TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; /* PSH and FIN should only be set in the second packet. */ flags = TCP_SKB_CB(skb)->tcp_flags; TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); TCP_SKB_CB(buff)->tcp_flags = flags; TCP_SKB_CB(buff)->sacked = TCP_SKB_CB(skb)->sacked; if (!skb_shinfo(skb)->nr_frags && skb->ip_summed != CHECKSUM_PARTIAL) { /* Copy and checksum data tail into the new buffer. */ buff->csum = csum_partial_copy_nocheck(skb->data + len, skb_put(buff, nsize), nsize, 0); skb_trim(skb, len); skb->csum = csum_block_sub(skb->csum, buff->csum, len); } else { skb->ip_summed = CHECKSUM_PARTIAL; skb_split(skb, buff, len); } buff->ip_summed = skb->ip_summed; /* Looks stupid, but our code really uses when of * skbs, which it never sent before. --ANK */ TCP_SKB_CB(buff)->when = TCP_SKB_CB(skb)->when; buff->tstamp = skb->tstamp; old_factor = tcp_skb_pcount(skb); /* Fix up tso_factor for both original and new SKB. */ tcp_set_skb_tso_segs(sk, skb, mss_now); tcp_set_skb_tso_segs(sk, buff, mss_now); /* If this packet has been sent out already, we must * adjust the various packet counters. */ if (!before(tp->snd_nxt, TCP_SKB_CB(buff)->end_seq)) { int diff = old_factor - tcp_skb_pcount(skb) - tcp_skb_pcount(buff); if (diff) tcp_adjust_pcount(sk, skb, diff); } /* Link BUFF into the send queue. */ skb_header_release(buff); tcp_insert_write_queue_after(skb, buff, sk); return 0; } /* This is similar to __pskb_pull_head() (it will go to core/skbuff.c * eventually). The difference is that pulled data not copied, but * immediately discarded. */ void __pskb_trim_head(struct sk_buff *skb, int len) { int i, k, eat; eat = min_t(int, len, skb_headlen(skb)); if (eat) { __skb_pull(skb, eat); len -= eat; if (!len) return; } eat = len; k = 0; for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) { int size = skb_frag_size(&skb_shinfo(skb)->frags[i]); if (size <= eat) { skb_frag_unref(skb, i); eat -= size; } else { skb_shinfo(skb)->frags[k] = skb_shinfo(skb)->frags[i]; if (eat) { skb_shinfo(skb)->frags[k].page_offset += eat; skb_frag_size_sub(&skb_shinfo(skb)->frags[k], eat); eat = 0; } k++; } } skb_shinfo(skb)->nr_frags = k; skb_reset_tail_pointer(skb); skb->data_len -= len; skb->len = skb->data_len; } /* Remove acked data from a packet in the transmit queue. */ int tcp_trim_head(struct sock *sk, struct sk_buff *skb, u32 len) { if (tcp_sk(sk)->mpc && !is_meta_sk(sk) && mptcp_is_data_seq(skb)) return mptcp_trim_head(sk, skb, len); if (skb_unclone(skb, GFP_ATOMIC)) return -ENOMEM; __pskb_trim_head(skb, len); TCP_SKB_CB(skb)->seq += len; skb->ip_summed = CHECKSUM_PARTIAL; skb->truesize -= len; sk->sk_wmem_queued -= len; sk_mem_uncharge(sk, len); sock_set_flag(sk, SOCK_QUEUE_SHRUNK); /* Any change of skb->len requires recalculation of tso factor. */ if (tcp_skb_pcount(skb) > 1) tcp_set_skb_tso_segs(sk, skb, tcp_skb_mss(skb)); #ifdef CONFIG_MPTCP /* Some data got acked - we assume that the seq-number reached the dest. * Anyway, our MPTCP-option has been trimmed above - we lost it here. * Only remove the SEQ if the call does not come from a meta retransmit. */ if (tcp_sk(sk)->mpc && !is_meta_sk(sk)) TCP_SKB_CB(skb)->mptcp_flags &= ~MPTCPHDR_SEQ; #endif return 0; } /* Calculate MSS not accounting any TCP options. */ static inline int __tcp_mtu_to_mss(struct sock *sk, int pmtu) { const struct tcp_sock *tp = tcp_sk(sk); const struct inet_connection_sock *icsk = inet_csk(sk); int mss_now; /* Calculate base mss without TCP options: It is MMS_S - sizeof(tcphdr) of rfc1122 */ mss_now = pmtu - icsk->icsk_af_ops->net_header_len - sizeof(struct tcphdr); /* IPv6 adds a frag_hdr in case RTAX_FEATURE_ALLFRAG is set */ if (icsk->icsk_af_ops->net_frag_header_len) { const struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst_allfrag(dst)) mss_now -= icsk->icsk_af_ops->net_frag_header_len; } /* Clamp it (mss_clamp does not include tcp options) */ if (mss_now > tp->rx_opt.mss_clamp) mss_now = tp->rx_opt.mss_clamp; /* Now subtract optional transport overhead */ mss_now -= icsk->icsk_ext_hdr_len; /* Then reserve room for full set of TCP options and 8 bytes of data */ if (mss_now < 48) mss_now = 48; return mss_now; } /* Calculate MSS. Not accounting for SACKs here. */ int tcp_mtu_to_mss(struct sock *sk, int pmtu) { /* Subtract TCP options size, not including SACKs */ return __tcp_mtu_to_mss(sk, pmtu) - (tcp_sk(sk)->tcp_header_len - sizeof(struct tcphdr)); } /* Inverse of above */ int tcp_mss_to_mtu(struct sock *sk, int mss) { const struct tcp_sock *tp = tcp_sk(sk); const struct inet_connection_sock *icsk = inet_csk(sk); int mtu; mtu = mss + tp->tcp_header_len + icsk->icsk_ext_hdr_len + icsk->icsk_af_ops->net_header_len; /* IPv6 adds a frag_hdr in case RTAX_FEATURE_ALLFRAG is set */ if (icsk->icsk_af_ops->net_frag_header_len) { const struct dst_entry *dst = __sk_dst_get(sk); if (dst && dst_allfrag(dst)) mtu += icsk->icsk_af_ops->net_frag_header_len; } return mtu; } /* MTU probing init per socket */ void tcp_mtup_init(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); icsk->icsk_mtup.enabled = sysctl_tcp_mtu_probing > 1; icsk->icsk_mtup.search_high = tp->rx_opt.mss_clamp + sizeof(struct tcphdr) + icsk->icsk_af_ops->net_header_len; icsk->icsk_mtup.search_low = tcp_mss_to_mtu(sk, sysctl_tcp_base_mss); icsk->icsk_mtup.probe_size = 0; } EXPORT_SYMBOL(tcp_mtup_init); /* This function synchronize snd mss to current pmtu/exthdr set. tp->rx_opt.user_mss is mss set by user by TCP_MAXSEG. It does NOT counts for TCP options, but includes only bare TCP header. tp->rx_opt.mss_clamp is mss negotiated at connection setup. It is minimum of user_mss and mss received with SYN. It also does not include TCP options. inet_csk(sk)->icsk_pmtu_cookie is last pmtu, seen by this function. tp->mss_cache is current effective sending mss, including all tcp options except for SACKs. It is evaluated, taking into account current pmtu, but never exceeds tp->rx_opt.mss_clamp. NOTE1. rfc1122 clearly states that advertised MSS DOES NOT include either tcp or ip options. NOTE2. inet_csk(sk)->icsk_pmtu_cookie and tp->mss_cache are READ ONLY outside this function. --ANK (980731) */ unsigned int tcp_sync_mss(struct sock *sk, u32 pmtu) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); int mss_now; if (icsk->icsk_mtup.search_high > pmtu) icsk->icsk_mtup.search_high = pmtu; mss_now = tcp_mtu_to_mss(sk, pmtu); mss_now = tcp_bound_to_half_wnd(tp, mss_now); /* And store cached results */ icsk->icsk_pmtu_cookie = pmtu; if (icsk->icsk_mtup.enabled) mss_now = min(mss_now, tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_low)); tp->mss_cache = mss_now; return mss_now; } EXPORT_SYMBOL(tcp_sync_mss); /* Compute the current effective MSS, taking SACKs and IP options, * and even PMTU discovery events into account. */ unsigned int tcp_current_mss(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); const struct dst_entry *dst = __sk_dst_get(sk); u32 mss_now; unsigned int header_len; struct tcp_out_options opts; struct tcp_md5sig_key *md5; mss_now = tp->mss_cache; if (dst) { u32 mtu = dst_mtu(dst); if (mtu != inet_csk(sk)->icsk_pmtu_cookie) mss_now = tcp_sync_mss(sk, mtu); } header_len = tcp_established_options(sk, NULL, &opts, &md5) + sizeof(struct tcphdr); /* The mss_cache is sized based on tp->tcp_header_len, which assumes * some common options. If this is an odd packet (because we have SACK * blocks etc) then our calculated header_len will be different, and * we have to adjust mss_now correspondingly */ if (header_len != tp->tcp_header_len) { int delta = (int) header_len - tp->tcp_header_len; mss_now -= delta; } return mss_now; } /* Congestion window validation. (RFC2861) */ void tcp_cwnd_validate(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); if (tp->packets_out >= tp->snd_cwnd) { /* Network is feed fully. */ tp->snd_cwnd_used = 0; tp->snd_cwnd_stamp = tcp_time_stamp; } else { /* Network starves. */ if (tp->packets_out > tp->snd_cwnd_used) tp->snd_cwnd_used = tp->packets_out; if (sysctl_tcp_slow_start_after_idle && (s32)(tcp_time_stamp - tp->snd_cwnd_stamp) >= inet_csk(sk)->icsk_rto) tcp_cwnd_application_limited(sk); } } /* Returns the portion of skb which can be sent right away without * introducing MSS oddities to segment boundaries. In rare cases where * mss_now != mss_cache, we will request caller to create a small skb * per input skb which could be mostly avoided here (if desired). * * We explicitly want to create a request for splitting write queue tail * to a small skb for Nagle purposes while avoiding unnecessary modulos, * thus all the complexity (cwnd_len is always MSS multiple which we * return whenever allowed by the other factors). Basically we need the * modulo only when the receiver window alone is the limiting factor or * when we would be allowed to send the split-due-to-Nagle skb fully. */ unsigned int tcp_mss_split_point(const struct sock *sk, const struct sk_buff *skb, unsigned int mss_now, unsigned int max_segs) { const struct tcp_sock *tp = tcp_sk(sk); const struct sock *meta_sk = tp->mpc ? mptcp_meta_sk(sk) : sk; u32 needed, window, max_len; if (!tp->mpc) window = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; else /* We need to evaluate the available space in the sending window * at the subflow level. However, the subflow seq has not yet * been set. Nevertheless we know that the caller will set it to * write_seq. */ window = tcp_wnd_end(tp) - tp->write_seq; max_len = mss_now * max_segs; if (likely(max_len <= window && skb != tcp_write_queue_tail(meta_sk))) return max_len; needed = min(skb->len, window); if (max_len <= needed) return max_len; return needed - needed % mss_now; } /* Can at least one segment of SKB be sent right now, according to the * congestion window rules? If so, return how many segments are allowed. */ unsigned int tcp_cwnd_test(const struct tcp_sock *tp, const struct sk_buff *skb) { u32 in_flight, cwnd; /* Don't be strict about the congestion window for the final FIN. */ if (skb && ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) || mptcp_is_data_fin(skb)) && tcp_skb_pcount(skb) == 1) return 1; in_flight = tcp_packets_in_flight(tp); cwnd = tp->snd_cwnd; if (in_flight < cwnd) return (cwnd - in_flight); return 0; } /* Initialize TSO state of a skb. * This must be invoked the first time we consider transmitting * SKB onto the wire. */ int tcp_init_tso_segs(const struct sock *sk, struct sk_buff *skb, unsigned int mss_now) { int tso_segs = tcp_skb_pcount(skb); if (!tso_segs || (tso_segs > 1 && tcp_skb_mss(skb) != mss_now)) { tcp_set_skb_tso_segs(sk, skb, mss_now); tso_segs = tcp_skb_pcount(skb); } return tso_segs; } /* Minshall's variant of the Nagle send check. */ static inline bool tcp_minshall_check(const struct tcp_sock *tp) { return after(tp->snd_sml, tp->snd_una) && !after(tp->snd_sml, tp->snd_nxt); } /* Return false, if packet can be sent now without violation Nagle's rules: * 1. It is full sized. * 2. Or it contains FIN. (already checked by caller) * 3. Or TCP_CORK is not set, and TCP_NODELAY is set. * 4. Or TCP_CORK is not set, and all sent packets are ACKed. * With Minshall's modification: all sent small packets are ACKed. */ static inline bool tcp_nagle_check(const struct tcp_sock *tp, const struct sk_buff *skb, unsigned int mss_now, int nonagle) { return skb->len < mss_now && ((nonagle & TCP_NAGLE_CORK) || (!nonagle && tp->packets_out && tcp_minshall_check(tp))); } /* Return true if the Nagle test allows this packet to be * sent now. */ bool tcp_nagle_test(const struct tcp_sock *tp, const struct sk_buff *skb, unsigned int cur_mss, int nonagle) { /* Nagle rule does not apply to frames, which sit in the middle of the * write_queue (they have no chances to get new data). * * This is implemented in the callers, where they modify the 'nonagle' * argument based upon the location of SKB in the send queue. */ if (nonagle & TCP_NAGLE_PUSH) return true; /* Don't use the nagle rule for urgent data (or for the final FIN). */ if (tcp_urg_mode(tp) || (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) || mptcp_is_data_fin(skb)) return true; if (!tcp_nagle_check(tp, skb, cur_mss, nonagle)) return true; return false; } /* Does at least the first segment of SKB fit into the send window? */ bool tcp_snd_wnd_test(const struct tcp_sock *tp, const struct sk_buff *skb, unsigned int cur_mss) { u32 end_seq = TCP_SKB_CB(skb)->end_seq; if (skb->len > cur_mss) end_seq = TCP_SKB_CB(skb)->seq + cur_mss; return !after(end_seq, tcp_wnd_end(tp)); } /* This checks if the data bearing packet SKB (usually tcp_send_head(sk)) * should be put on the wire right now. If so, it returns the number of * packets allowed by the congestion window. */ static unsigned int tcp_snd_test(const struct sock *sk, struct sk_buff *skb, unsigned int cur_mss, int nonagle) { const struct tcp_sock *tp = tcp_sk(sk); unsigned int cwnd_quota; tcp_init_tso_segs(sk, skb, cur_mss); if (!tcp_nagle_test(tp, skb, cur_mss, nonagle)) return 0; cwnd_quota = tcp_cwnd_test(tp, skb); if (cwnd_quota && !tcp_snd_wnd_test(tp, skb, cur_mss)) cwnd_quota = 0; return cwnd_quota; } /* Test if sending is allowed right now. */ bool tcp_may_send_now(struct sock *sk) { const struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = tcp_send_head(sk); return skb && tcp_snd_test(sk, skb, tcp_current_mss(sk), (tcp_skb_is_last(sk, skb) ? tp->nonagle : TCP_NAGLE_PUSH)); } /* Trim TSO SKB to LEN bytes, put the remaining data into a new packet * which is put after SKB on the list. It is very much like * tcp_fragment() except that it may make several kinds of assumptions * in order to speed up the splitting operation. In particular, we * know that all the data is in scatter-gather pages, and that the * packet has never been sent out before (and thus is not cloned). */ static int tso_fragment(struct sock *sk, struct sk_buff *skb, unsigned int len, unsigned int mss_now, gfp_t gfp) { struct sk_buff *buff; int nlen = skb->len - len; u8 flags; if (tcp_sk(sk)->mpc && mptcp_is_data_seq(skb)) mptso_fragment(sk, skb, len, mss_now, gfp, 0); /* All of a TSO frame must be composed of paged data. */ if (skb->len != skb->data_len) return tcp_fragment(sk, skb, len, mss_now); buff = sk_stream_alloc_skb(sk, 0, gfp); if (unlikely(buff == NULL)) return -ENOMEM; sk->sk_wmem_queued += buff->truesize; sk_mem_charge(sk, buff->truesize); buff->truesize += nlen; skb->truesize -= nlen; /* Correct the sequence numbers. */ TCP_SKB_CB(buff)->seq = TCP_SKB_CB(skb)->seq + len; TCP_SKB_CB(buff)->end_seq = TCP_SKB_CB(skb)->end_seq; TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(buff)->seq; /* PSH and FIN should only be set in the second packet. */ flags = TCP_SKB_CB(skb)->tcp_flags; TCP_SKB_CB(skb)->tcp_flags = flags & ~(TCPHDR_FIN | TCPHDR_PSH); TCP_SKB_CB(buff)->tcp_flags = flags; /* This packet was never sent out yet, so no SACK bits. */ TCP_SKB_CB(buff)->sacked = 0; buff->ip_summed = skb->ip_summed = CHECKSUM_PARTIAL; skb_split(skb, buff, len); /* Fix up tso_factor for both original and new SKB. */ tcp_set_skb_tso_segs(sk, skb, mss_now); tcp_set_skb_tso_segs(sk, buff, mss_now); /* Link BUFF into the send queue. */ skb_header_release(buff); tcp_insert_write_queue_after(skb, buff, sk); return 0; } /* Try to defer sending, if possible, in order to minimize the amount * of TSO splitting we do. View it as a kind of TSO Nagle test. * * This algorithm is from John Heffner. */ bool tcp_tso_should_defer(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sock *meta_sk = tp->mpc ? mptcp_meta_sk(sk) : sk; struct tcp_sock *meta_tp = tcp_sk(meta_sk); const struct inet_connection_sock *icsk = inet_csk(sk); u32 send_win, cong_win, limit, in_flight; int win_divisor; if ((TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) || mptcp_is_data_fin(skb)) goto send_now; if (icsk->icsk_ca_state != TCP_CA_Open) goto send_now; /* Defer for less than two clock ticks. */ if (meta_tp->tso_deferred && (((u32)jiffies << 1) >> 1) - (meta_tp->tso_deferred >> 1) > 1) goto send_now; in_flight = tcp_packets_in_flight(tp); BUG_ON(tcp_skb_pcount(skb) <= 1 || (tp->snd_cwnd <= in_flight)); if (!tp->mpc) send_win = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; else /* We need to evaluate the available space in the sending window * at the subflow level. However, the subflow seq has not yet * been set. Nevertheless we know that the caller will set it to * write_seq. */ send_win = tcp_wnd_end(tp) - tp->write_seq; /* From in_flight test above, we know that cwnd > in_flight. */ cong_win = (tp->snd_cwnd - in_flight) * tp->mss_cache; limit = min(send_win, cong_win); /* If a full-sized TSO skb can be sent, do it. */ if (limit >= min_t(unsigned int, sk->sk_gso_max_size, sk->sk_gso_max_segs * tp->mss_cache)) goto send_now; /* Middle in queue won't get any more data, full sendable already? */ if ((skb != tcp_write_queue_tail(meta_sk)) && (limit >= skb->len)) goto send_now; win_divisor = ACCESS_ONCE(sysctl_tcp_tso_win_divisor); if (win_divisor) { u32 chunk = min(tp->snd_wnd, tp->snd_cwnd * tp->mss_cache); /* If at least some fraction of a window is available, * just use it. */ chunk /= win_divisor; if (limit >= chunk) goto send_now; } else { /* Different approach, try not to defer past a single * ACK. Receiver should ACK every other full sized * frame, so if we have space for more than 3 frames * then send now. */ if (limit > tcp_max_tso_deferred_mss(tp) * tp->mss_cache) goto send_now; } /* Ok, it looks like it is advisable to defer. * Do not rearm the timer if already set to not break TCP ACK clocking. */ if (!meta_tp->tso_deferred) meta_tp->tso_deferred = 1 | (jiffies << 1); return true; send_now: meta_tp->tso_deferred = 0; return false; } /* Create a new MTU probe if we are ready. * MTU probe is regularly attempting to increase the path MTU by * deliberately sending larger packets. This discovers routing * changes resulting in larger path MTUs. * * Returns 0 if we should wait to probe (no cwnd available), * 1 if a probe was sent, * -1 otherwise */ int tcp_mtu_probe(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); struct sk_buff *skb, *nskb, *next; int len; int probe_size; int size_needed; int copy; int mss_now; /* Not currently probing/verifying, * not in recovery, * have enough cwnd, and * not SACKing (the variable headers throw things off) */ if (!icsk->icsk_mtup.enabled || icsk->icsk_mtup.probe_size || inet_csk(sk)->icsk_ca_state != TCP_CA_Open || tp->snd_cwnd < 11 || tp->rx_opt.num_sacks || tp->rx_opt.dsack) return -1; /* Very simple search strategy: just double the MSS. */ mss_now = tcp_current_mss(sk); probe_size = 2 * tp->mss_cache; size_needed = probe_size + (tp->reordering + 1) * tp->mss_cache; if (probe_size > tcp_mtu_to_mss(sk, icsk->icsk_mtup.search_high)) { /* TODO: set timer for probe_converge_event */ return -1; } /* Have enough data in the send queue to probe? */ if (tp->write_seq - tp->snd_nxt < size_needed) return -1; if (tp->snd_wnd < size_needed) return -1; if (after(tp->snd_nxt + size_needed, tcp_wnd_end(tp))) return 0; /* Do we need to wait to drain cwnd? With none in flight, don't stall */ if (tcp_packets_in_flight(tp) + 2 > tp->snd_cwnd) { if (!tcp_packets_in_flight(tp)) return -1; else return 0; } /* We're allowed to probe. Build it now. */ if ((nskb = sk_stream_alloc_skb(sk, probe_size, GFP_ATOMIC)) == NULL) return -1; sk->sk_wmem_queued += nskb->truesize; sk_mem_charge(sk, nskb->truesize); skb = tcp_send_head(sk); TCP_SKB_CB(nskb)->seq = TCP_SKB_CB(skb)->seq; TCP_SKB_CB(nskb)->end_seq = TCP_SKB_CB(skb)->seq + probe_size; TCP_SKB_CB(nskb)->tcp_flags = TCPHDR_ACK; TCP_SKB_CB(nskb)->sacked = 0; nskb->csum = 0; nskb->ip_summed = skb->ip_summed; tcp_insert_write_queue_before(nskb, skb, sk); len = 0; tcp_for_write_queue_from_safe(skb, next, sk) { copy = min_t(int, skb->len, probe_size - len); if (nskb->ip_summed) skb_copy_bits(skb, 0, skb_put(nskb, copy), copy); else nskb->csum = skb_copy_and_csum_bits(skb, 0, skb_put(nskb, copy), copy, nskb->csum); if (skb->len <= copy) { /* We've eaten all the data from this skb. * Throw it away. */ TCP_SKB_CB(nskb)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags; tcp_unlink_write_queue(skb, sk); sk_wmem_free_skb(sk, skb); } else { TCP_SKB_CB(nskb)->tcp_flags |= TCP_SKB_CB(skb)->tcp_flags & ~(TCPHDR_FIN|TCPHDR_PSH); if (!skb_shinfo(skb)->nr_frags) { skb_pull(skb, copy); if (skb->ip_summed != CHECKSUM_PARTIAL) skb->csum = csum_partial(skb->data, skb->len, 0); } else { __pskb_trim_head(skb, copy); tcp_set_skb_tso_segs(sk, skb, mss_now); } TCP_SKB_CB(skb)->seq += copy; } len += copy; if (len >= probe_size) break; } tcp_init_tso_segs(sk, nskb, nskb->len); /* We're ready to send. If this fails, the probe will * be resegmented into mss-sized pieces by tcp_write_xmit(). */ TCP_SKB_CB(nskb)->when = tcp_time_stamp; if (!tcp_transmit_skb(sk, nskb, 1, GFP_ATOMIC)) { /* Decrement cwnd here because we are sending * effectively two packets. */ tp->snd_cwnd--; tcp_event_new_data_sent(sk, nskb); icsk->icsk_mtup.probe_size = tcp_mss_to_mtu(sk, nskb->len); tp->mtu_probe.probe_seq_start = TCP_SKB_CB(nskb)->seq; tp->mtu_probe.probe_seq_end = TCP_SKB_CB(nskb)->end_seq; return 1; } return -1; } /* This routine writes packets to the network. It advances the * send_head. This happens as incoming acks open up the remote * window for us. * * LARGESEND note: !tcp_urg_mode is overkill, only frames between * snd_up-64k-mss .. snd_up cannot be large. However, taking into * account rare use of URG, this is not a big flaw. * * Send at most one packet when push_one > 0. Temporarily ignore * cwnd limit to force at most one packet out when push_one == 2. * Returns true, if no segments are in flight and we have queued segments, * but cannot send anything now because of SWS or another problem. */ static bool tcp_write_xmit(struct sock *sk, unsigned int mss_now, int nonagle, int push_one, gfp_t gfp) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; unsigned int tso_segs, sent_pkts; int cwnd_quota; int result; //printf("mptcp?::%d, %d\n", sk->__sk_common.skc_daddr, sk->__sk_common.skc_rcv_saddr); if (is_meta_sk(sk)) return mptcp_write_xmit(sk, mss_now, nonagle, push_one, gfp); sent_pkts = 0; if (!push_one) { /* Do MTU probing. */ result = tcp_mtu_probe(sk); if (!result) { return false; } else if (result > 0) { sent_pkts = 1; } } while ((skb = tcp_send_head(sk))) { unsigned int limit; tso_segs = tcp_init_tso_segs(sk, skb, mss_now); BUG_ON(!tso_segs); if (unlikely(tp->repair) && tp->repair_queue == TCP_SEND_QUEUE) goto repair; /* Skip network transmission */ cwnd_quota = tcp_cwnd_test(tp, skb); if (!cwnd_quota) { if (push_one == 2) /* Force out a loss probe pkt. */ cwnd_quota = 1; else break; } if (unlikely(!tcp_snd_wnd_test(tp, skb, mss_now))) break; if (tso_segs == 1) { if (unlikely(!tcp_nagle_test(tp, skb, mss_now, (tcp_skb_is_last(sk, skb) ? nonagle : TCP_NAGLE_PUSH)))) break; } else { if (!push_one && tcp_tso_should_defer(sk, skb)) break; } /* TSQ : sk_wmem_alloc accounts skb truesize, * including skb overhead. But thats OK. */ if (atomic_read(&sk->sk_wmem_alloc) >= sysctl_tcp_limit_output_bytes) { set_bit(TSQ_THROTTLED, &tp->tsq_flags); break; } limit = mss_now; if (tso_segs > 1 && !tcp_urg_mode(tp)) limit = tcp_mss_split_point(sk, skb, mss_now, min_t(unsigned int, cwnd_quota, sk->sk_gso_max_segs)); if (skb->len > limit && unlikely(tso_fragment(sk, skb, limit, mss_now, gfp))) break; TCP_SKB_CB(skb)->when = tcp_time_stamp; if (unlikely(tcp_transmit_skb(sk, skb, 1, gfp))) break; repair: /* Advance the send_head. This one is sent out. * This call will increment packets_out. */ tcp_event_new_data_sent(sk, skb); tcp_minshall_update(tp, mss_now, skb); sent_pkts += tcp_skb_pcount(skb); if (push_one) break; } if (likely(sent_pkts)) { if (tcp_in_cwnd_reduction(sk)) tp->prr_out += sent_pkts; /* Send one loss probe per tail loss episode. */ if (push_one != 2) tcp_schedule_loss_probe(sk); tcp_cwnd_validate(sk); return false; } return (push_one == 2) || (!tp->packets_out && tcp_send_head(sk)); } bool tcp_schedule_loss_probe(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); u32 timeout, tlp_time_stamp, rto_time_stamp; u32 rtt = tp->srtt >> 3; if (WARN_ON(icsk->icsk_pending == ICSK_TIME_EARLY_RETRANS)) return false; /* No consecutive loss probes. */ if (WARN_ON(icsk->icsk_pending == ICSK_TIME_LOSS_PROBE)) { tcp_rearm_rto(sk); return false; } /* Don't do any loss probe on a Fast Open connection before 3WHS * finishes. */ if (sk->sk_state == TCP_SYN_RECV) return false; /* TLP is only scheduled when next timer event is RTO. */ if (icsk->icsk_pending != ICSK_TIME_RETRANS) return false; /* Schedule a loss probe in 2*RTT for SACK capable connections * in Open state, that are either limited by cwnd or application. */ if (sysctl_tcp_early_retrans < 3 || !rtt || !tp->packets_out || !tcp_is_sack(tp) || inet_csk(sk)->icsk_ca_state != TCP_CA_Open) return false; if ((tp->snd_cwnd > tcp_packets_in_flight(tp)) && tcp_send_head(sk)) return false; /* Probe timeout is at least 1.5*rtt + TCP_DELACK_MAX to account * for delayed ack when there's one outstanding packet. */ timeout = rtt << 1; if (tp->packets_out == 1) timeout = max_t(u32, timeout, (rtt + (rtt >> 1) + TCP_DELACK_MAX)); timeout = max_t(u32, timeout, msecs_to_jiffies(10)); /* If RTO is shorter, just schedule TLP in its place. */ tlp_time_stamp = tcp_time_stamp + timeout; rto_time_stamp = (u32)inet_csk(sk)->icsk_timeout; if ((s32)(tlp_time_stamp - rto_time_stamp) > 0) { s32 delta = rto_time_stamp - tcp_time_stamp; if (delta > 0) timeout = delta; } inet_csk_reset_xmit_timer(sk, ICSK_TIME_LOSS_PROBE, timeout, TCP_RTO_MAX); return true; } /* When probe timeout (PTO) fires, send a new segment if one exists, else * retransmit the last segment. */ void tcp_send_loss_probe(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; int pcount; int mss = tcp_current_mss(sk); int err = -1; if (tcp_send_head(sk) != NULL) { err = tcp_write_xmit(sk, mss, TCP_NAGLE_OFF, 2, GFP_ATOMIC); goto rearm_timer; } /* At most one outstanding TLP retransmission. */ if (tp->tlp_high_seq) goto rearm_timer; /* Retransmit last segment. */ skb = tcp_write_queue_tail(sk); if (WARN_ON(!skb)) goto rearm_timer; pcount = tcp_skb_pcount(skb); if (WARN_ON(!pcount)) goto rearm_timer; if ((pcount > 1) && (skb->len > (pcount - 1) * mss)) { if (unlikely(tcp_fragment(sk, skb, (pcount - 1) * mss, mss))) goto rearm_timer; skb = tcp_write_queue_tail(sk); } if (WARN_ON(!skb || !tcp_skb_pcount(skb))) goto rearm_timer; /* Probe with zero data doesn't trigger fast recovery. */ if (skb->len > 0) err = __tcp_retransmit_skb(sk, skb); /* Record snd_nxt for loss detection. */ if (likely(!err)) tp->tlp_high_seq = tp->snd_nxt; rearm_timer: inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, inet_csk(sk)->icsk_rto, TCP_RTO_MAX); if (likely(!err)) NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPLOSSPROBES); return; } /* Push out any pending frames which were held back due to * TCP_CORK or attempt at coalescing tiny packets. * The socket must be locked by the caller. */ void __tcp_push_pending_frames(struct sock *sk, unsigned int cur_mss, int nonagle) { /* If we are closed, the bytes will have to remain here. * In time closedown will finish, we empty the write queue and * all will be happy. */ if (unlikely(sk->sk_state == TCP_CLOSE)) return; if (tcp_write_xmit(sk, cur_mss, nonagle, 0, sk_gfp_atomic(sk, GFP_ATOMIC))) tcp_check_probe_timer(sk); } /* Send _single_ skb sitting at the send head. This function requires * true push pending frames to setup probe timer etc. */ void tcp_push_one(struct sock *sk, unsigned int mss_now) { struct sk_buff *skb = tcp_send_head(sk); BUG_ON(!skb || skb->len < mss_now); tcp_write_xmit(sk, mss_now, TCP_NAGLE_PUSH, 1, sk->sk_allocation); } /* This function returns the amount that we can raise the * usable window based on the following constraints * * 1. The window can never be shrunk once it is offered (RFC 793) * 2. We limit memory per socket * * RFC 1122: * "the suggested [SWS] avoidance algorithm for the receiver is to keep * RECV.NEXT + RCV.WIN fixed until: * RCV.BUFF - RCV.USER - RCV.WINDOW >= min(1/2 RCV.BUFF, MSS)" * * i.e. don't raise the right edge of the window until you can raise * it at least MSS bytes. * * Unfortunately, the recommended algorithm breaks header prediction, * since header prediction assumes th->window stays fixed. * * Strictly speaking, keeping th->window fixed violates the receiver * side SWS prevention criteria. The problem is that under this rule * a stream of single byte packets will cause the right side of the * window to always advance by a single byte. * * Of course, if the sender implements sender side SWS prevention * then this will not be a problem. * * BSD seems to make the following compromise: * * If the free space is less than the 1/4 of the maximum * space available and the free space is less than 1/2 mss, * then set the window to 0. * [ Actually, bsd uses MSS and 1/4 of maximal _window_ ] * Otherwise, just prevent the window from shrinking * and from being larger than the largest representable value. * * This prevents incremental opening of the window in the regime * where TCP is limited by the speed of the reader side taking * data out of the TCP receive queue. It does nothing about * those cases where the window is constrained on the sender side * because the pipeline is full. * * BSD also seems to "accidentally" limit itself to windows that are a * multiple of MSS, at least until the free space gets quite small. * This would appear to be a side effect of the mbuf implementation. * Combining these two algorithms results in the observed behavior * of having a fixed window size at almost all times. * * Below we obtain similar behavior by forcing the offered window to * a multiple of the mss when it is feasible to do so. * * Note, we don't "adjust" for TIMESTAMP or SACK option bytes. * Regular options like TIMESTAMP are taken into account. */ u32 __tcp_select_window(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); /* MSS for the peer's data. Previous versions used mss_clamp * here. I don't know if the value based on our guesses * of peer's MSS is better for the performance. It's more correct * but may be worse for the performance because of rcv_mss * fluctuations. --SAW 1998/11/1 */ int mss = icsk->icsk_ack.rcv_mss; int free_space = tcp_space(sk); int full_space = min_t(int, tp->window_clamp, tcp_full_space(sk)); int window; if (tp->mpc) return __mptcp_select_window(sk); if (mss > full_space) mss = full_space; if (free_space < (full_space >> 1)) { icsk->icsk_ack.quick = 0; if (sk_under_memory_pressure(sk)) tp->rcv_ssthresh = min(tp->rcv_ssthresh, 4U * tp->advmss); if (free_space < mss) return 0; } if (free_space > tp->rcv_ssthresh) free_space = tp->rcv_ssthresh; /* Don't do rounding if we are using window scaling, since the * scaled window will not line up with the MSS boundary anyway. */ window = tp->rcv_wnd; if (tp->rx_opt.rcv_wscale) { window = free_space; /* Advertise enough space so that it won't get scaled away. * Import case: prevent zero window announcement if * 1<<rcv_wscale > mss. */ if (((window >> tp->rx_opt.rcv_wscale) << tp->rx_opt.rcv_wscale) != window) window = (((window >> tp->rx_opt.rcv_wscale) + 1) << tp->rx_opt.rcv_wscale); } else { /* Get the largest window that is a nice multiple of mss. * Window clamp already applied above. * If our current window offering is within 1 mss of the * free space we just keep it. This prevents the divide * and multiply from happening most of the time. * We also don't do any window rounding when the free space * is too small. */ if (window <= free_space - mss || window > free_space) window = (free_space / mss) * mss; else if (mss == full_space && free_space > window + (full_space >> 1)) window = free_space; } return window; } /* Collapses two adjacent SKB's during retransmission. */ static void tcp_collapse_retrans(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *next_skb = tcp_write_queue_next(sk, skb); int skb_size, next_skb_size; skb_size = skb->len; next_skb_size = next_skb->len; BUG_ON(tcp_skb_pcount(skb) != 1 || tcp_skb_pcount(next_skb) != 1); tcp_highest_sack_combine(sk, next_skb, skb); tcp_unlink_write_queue(next_skb, sk); skb_copy_from_linear_data(next_skb, skb_put(skb, next_skb_size), next_skb_size); if (next_skb->ip_summed == CHECKSUM_PARTIAL) skb->ip_summed = CHECKSUM_PARTIAL; if (skb->ip_summed != CHECKSUM_PARTIAL) skb->csum = csum_block_add(skb->csum, next_skb->csum, skb_size); /* Update sequence range on original skb. */ TCP_SKB_CB(skb)->end_seq = TCP_SKB_CB(next_skb)->end_seq; /* Merge over control information. This moves PSH/FIN etc. over */ TCP_SKB_CB(skb)->tcp_flags |= TCP_SKB_CB(next_skb)->tcp_flags; /* All done, get rid of second SKB and account for it so * packet counting does not break. */ TCP_SKB_CB(skb)->sacked |= TCP_SKB_CB(next_skb)->sacked & TCPCB_EVER_RETRANS; /* changed transmit queue under us so clear hints */ tcp_clear_retrans_hints_partial(tp); if (next_skb == tp->retransmit_skb_hint) tp->retransmit_skb_hint = skb; tcp_adjust_pcount(sk, next_skb, tcp_skb_pcount(next_skb)); sk_wmem_free_skb(sk, next_skb); } /* Check if coalescing SKBs is legal. */ static bool tcp_can_collapse(const struct sock *sk, const struct sk_buff *skb) { if (tcp_skb_pcount(skb) > 1) return false; /* TODO: SACK collapsing could be used to remove this condition */ if (skb_shinfo(skb)->nr_frags != 0) return false; if (skb_cloned(skb)) return false; if (skb == tcp_send_head(sk)) return false; /* Some heurestics for collapsing over SACK'd could be invented */ if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_ACKED) return false; return true; } /* Collapse packets in the retransmit queue to make to create * less packets on the wire. This is only done on retransmission. */ static void tcp_retrans_try_collapse(struct sock *sk, struct sk_buff *to, int space) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = to, *tmp; bool first = true; if (!sysctl_tcp_retrans_collapse) return; if (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN) return; /* Currently not supported for MPTCP - but it should be possible */ if (tp->mpc) return; tcp_for_write_queue_from_safe(skb, tmp, sk) { if (!tcp_can_collapse(sk, skb)) break; space -= skb->len; if (first) { first = false; continue; } if (space < 0) break; /* Punt if not enough space exists in the first SKB for * the data in the second */ if (skb->len > skb_availroom(to)) break; if (after(TCP_SKB_CB(skb)->end_seq, tcp_wnd_end(tp))) break; tcp_collapse_retrans(sk, to); } } /* This retransmits one SKB. Policy decisions and retransmit queue * state updates are done by the caller. Returns non-zero if an * error occurred which prevented the send. */ int __tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct inet_connection_sock *icsk = inet_csk(sk); unsigned int cur_mss; /* Inconslusive MTU probe */ if (icsk->icsk_mtup.probe_size) { icsk->icsk_mtup.probe_size = 0; } /* Do not sent more than we queued. 1/4 is reserved for possible * copying overhead: fragmentation, tunneling, mangling etc. */ if (atomic_read(&sk->sk_wmem_alloc) > min(sk->sk_wmem_queued + (sk->sk_wmem_queued >> 2), sk->sk_sndbuf)) return -EAGAIN; if (before(TCP_SKB_CB(skb)->seq, tp->snd_una)) { if (before(TCP_SKB_CB(skb)->end_seq, tp->snd_una)) BUG(); if (tcp_trim_head(sk, skb, tp->snd_una - TCP_SKB_CB(skb)->seq)) return -ENOMEM; } if (inet_csk(sk)->icsk_af_ops->rebuild_header(sk)) return -EHOSTUNREACH; /* Routing failure or similar. */ cur_mss = tcp_current_mss(sk); /* If receiver has shrunk his window, and skb is out of * new window, do not retransmit it. The exception is the * case, when window is shrunk to zero. In this case * our retransmit serves as a zero window probe. */ if (!before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp)) && TCP_SKB_CB(skb)->seq != tp->snd_una) return -EAGAIN; if (skb->len > cur_mss) { if (tcp_fragment(sk, skb, cur_mss, cur_mss)) return -ENOMEM; /* We'll try again later. */ } else { int oldpcount = tcp_skb_pcount(skb); if (unlikely(oldpcount > 1)) { tcp_init_tso_segs(sk, skb, cur_mss); tcp_adjust_pcount(sk, skb, oldpcount - tcp_skb_pcount(skb)); } } tcp_retrans_try_collapse(sk, skb, cur_mss); /* Some Solaris stacks overoptimize and ignore the FIN on a * retransmit when old data is attached. So strip it off * since it is cheap to do so and saves bytes on the network. */ if (skb->len > 0 && (TCP_SKB_CB(skb)->tcp_flags & TCPHDR_FIN) && tp->snd_una == (TCP_SKB_CB(skb)->end_seq - 1)) { if (!pskb_trim(skb, 0)) { /* Reuse, even though it does some unnecessary work */ tcp_init_nondata_skb(skb, TCP_SKB_CB(skb)->end_seq - 1, TCP_SKB_CB(skb)->tcp_flags); skb->ip_summed = CHECKSUM_NONE; } } /* Make a copy, if the first transmission SKB clone we made * is still in somebody's hands, else make a clone. */ TCP_SKB_CB(skb)->when = tcp_time_stamp; /* make sure skb->data is aligned on arches that require it * and check if ack-trimming & collapsing extended the headroom * beyond what csum_start can cover. */ if (unlikely((NET_IP_ALIGN && ((unsigned long)skb->data & 3)) || skb_headroom(skb) >= 0xFFFF)) { struct sk_buff *nskb; if (mptcp_is_data_seq(skb)) skb_push(skb, MPTCP_SUB_LEN_DSS_ALIGN + MPTCP_SUB_LEN_ACK_ALIGN + MPTCP_SUB_LEN_SEQ_ALIGN); nskb = __pskb_copy(skb, MAX_TCP_HEADER, GFP_ATOMIC); if (mptcp_is_data_seq(skb)) { skb_pull(skb, MPTCP_SUB_LEN_DSS_ALIGN + MPTCP_SUB_LEN_ACK_ALIGN + MPTCP_SUB_LEN_SEQ_ALIGN); if (nskb) skb_pull(nskb, MPTCP_SUB_LEN_DSS_ALIGN + MPTCP_SUB_LEN_ACK_ALIGN + MPTCP_SUB_LEN_SEQ_ALIGN); } return nskb ? tcp_transmit_skb(sk, nskb, 0, GFP_ATOMIC) : -ENOBUFS; } else { return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); } } int tcp_retransmit_skb(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); int err = __tcp_retransmit_skb(sk, skb); if (err == 0) { /* Update global TCP statistics. */ TCP_INC_STATS(sock_net(sk), TCP_MIB_RETRANSSEGS); tp->total_retrans++; #if FASTRETRANS_DEBUG > 0 if (TCP_SKB_CB(skb)->sacked & TCPCB_SACKED_RETRANS) { net_dbg_ratelimited("retrans_out leaked\n"); } #endif if (!tp->retrans_out) tp->lost_retrans_low = tp->snd_nxt; TCP_SKB_CB(skb)->sacked |= TCPCB_RETRANS; tp->retrans_out += tcp_skb_pcount(skb); /* Save stamp of the first retransmit. */ if (!tp->retrans_stamp) tp->retrans_stamp = TCP_SKB_CB(skb)->when; tp->undo_retrans += tcp_skb_pcount(skb); /* snd_nxt is stored to detect loss of retransmitted segment, * see tcp_input.c tcp_sacktag_write_queue(). */ TCP_SKB_CB(skb)->ack_seq = tp->snd_nxt; } else { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_TCPRETRANSFAIL); } return err; } /* Check if we forward retransmits are possible in the current * window/congestion state. */ static bool tcp_can_forward_retransmit(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); const struct tcp_sock *tp = tcp_sk(sk); /* Forward retransmissions are possible only during Recovery. */ if (icsk->icsk_ca_state != TCP_CA_Recovery) return false; /* No forward retransmissions in Reno are possible. */ if (tcp_is_reno(tp)) return false; /* Yeah, we have to make difficult choice between forward transmission * and retransmission... Both ways have their merits... * * For now we do not retransmit anything, while we have some new * segments to send. In the other cases, follow rule 3 for * NextSeg() specified in RFC3517. */ if (tcp_may_send_now(sk)) return false; return true; } /* This gets called after a retransmit timeout, and the initially * retransmitted data is acknowledged. It tries to continue * resending the rest of the retransmit queue, until either * we've sent it all or the congestion window limit is reached. * If doing SACK, the first ACK which comes back for a timeout * based retransmit packet might feed us FACK information again. * If so, we use it to avoid unnecessarily retransmissions. */ void tcp_xmit_retransmit_queue(struct sock *sk) { const struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; struct sk_buff *hole = NULL; u32 last_lost; int mib_idx; int fwd_rexmitting = 0; if (!tp->packets_out) return; if (!tp->lost_out) tp->retransmit_high = tp->snd_una; if (tp->retransmit_skb_hint) { skb = tp->retransmit_skb_hint; last_lost = TCP_SKB_CB(skb)->end_seq; if (after(last_lost, tp->retransmit_high)) last_lost = tp->retransmit_high; } else { skb = tcp_write_queue_head(sk); last_lost = tp->snd_una; } tcp_for_write_queue_from(skb, sk) { __u8 sacked = TCP_SKB_CB(skb)->sacked; if (skb == tcp_send_head(sk)) break; /* we could do better than to assign each time */ if (hole == NULL) tp->retransmit_skb_hint = skb; /* Assume this retransmit will generate * only one packet for congestion window * calculation purposes. This works because * tcp_retransmit_skb() will chop up the * packet to be MSS sized and all the * packet counting works out. */ if (tcp_packets_in_flight(tp) >= tp->snd_cwnd) return; if (fwd_rexmitting) { begin_fwd: if (!before(TCP_SKB_CB(skb)->seq, tcp_highest_sack_seq(tp))) break; mib_idx = LINUX_MIB_TCPFORWARDRETRANS; } else if (!before(TCP_SKB_CB(skb)->seq, tp->retransmit_high)) { tp->retransmit_high = last_lost; if (!tcp_can_forward_retransmit(sk)) break; /* Backtrack if necessary to non-L'ed skb */ if (hole != NULL) { skb = hole; hole = NULL; } fwd_rexmitting = 1; goto begin_fwd; } else if (!(sacked & TCPCB_LOST)) { if (hole == NULL && !(sacked & (TCPCB_SACKED_RETRANS|TCPCB_SACKED_ACKED))) hole = skb; continue; } else { last_lost = TCP_SKB_CB(skb)->end_seq; if (icsk->icsk_ca_state != TCP_CA_Loss) mib_idx = LINUX_MIB_TCPFASTRETRANS; else mib_idx = LINUX_MIB_TCPSLOWSTARTRETRANS; } if (sacked & (TCPCB_SACKED_ACKED|TCPCB_SACKED_RETRANS)) continue; if (tcp_retransmit_skb(sk, skb)) return; NET_INC_STATS_BH(sock_net(sk), mib_idx); if (tcp_in_cwnd_reduction(sk)) tp->prr_out += tcp_skb_pcount(skb); if (skb == tcp_write_queue_head(sk)) inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, inet_csk(sk)->icsk_rto, TCP_RTO_MAX); } } /* Send a fin. The caller locks the socket for us. This cannot be * allowed to fail queueing a FIN frame under any circumstances. */ void tcp_send_fin(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb = tcp_write_queue_tail(sk); int mss_now; /* Optimization, tack on the FIN if we have a queue of * unsent frames. But be careful about outgoing SACKS * and IP options. */ mss_now = tcp_current_mss(sk); if (tcp_send_head(sk) != NULL) { TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_FIN; TCP_SKB_CB(skb)->end_seq++; tp->write_seq++; } else { /* Socket is locked, keep trying until memory is available. */ for (;;) { skb = alloc_skb_fclone(MAX_TCP_HEADER, sk->sk_allocation); if (skb) break; yield(); } /* Reserve space for headers and prepare control bits. */ skb_reserve(skb, MAX_TCP_HEADER); /* FIN eats a sequence byte, write_seq advanced by tcp_queue_skb(). */ tcp_init_nondata_skb(skb, tp->write_seq, TCPHDR_ACK | TCPHDR_FIN); tcp_queue_skb(sk, skb); } __tcp_push_pending_frames(sk, mss_now, TCP_NAGLE_OFF); } /* We get here when a process closes a file descriptor (either due to * an explicit close() or as a byproduct of exit()'ing) and there * was unread data in the receive queue. This behavior is recommended * by RFC 2525, section 2.17. -DaveM */ void tcp_send_active_reset(struct sock *sk, gfp_t priority) { struct sk_buff *skb; if (is_meta_sk(sk)) { mptcp_send_active_reset(sk, priority); return; } /* NOTE: No TCP options attached and we never retransmit this. */ skb = alloc_skb(MAX_TCP_HEADER, priority); if (!skb) { NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); return; } /* Reserve space for headers and prepare control bits. */ skb_reserve(skb, MAX_TCP_HEADER); tcp_init_nondata_skb(skb, tcp_acceptable_seq(sk), TCPHDR_ACK | TCPHDR_RST); /* Send it off. */ TCP_SKB_CB(skb)->when = tcp_time_stamp; if (tcp_transmit_skb(sk, skb, 0, priority)) NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPABORTFAILED); TCP_INC_STATS(sock_net(sk), TCP_MIB_OUTRSTS); } /* Send a crossed SYN-ACK during socket establishment. * WARNING: This routine must only be called when we have already sent * a SYN packet that crossed the incoming SYN that caused this routine * to get called. If this assumption fails then the initial rcv_wnd * and rcv_wscale values will not be correct. */ int tcp_send_synack(struct sock *sk) { struct sk_buff *skb; skb = tcp_write_queue_head(sk); if (skb == NULL || !(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_SYN)) { pr_debug("%s: wrong queue state\n", __func__); return -EFAULT; } if (!(TCP_SKB_CB(skb)->tcp_flags & TCPHDR_ACK)) { if (skb_cloned(skb)) { struct sk_buff *nskb = skb_copy(skb, GFP_ATOMIC); if (nskb == NULL) return -ENOMEM; tcp_unlink_write_queue(skb, sk); skb_header_release(nskb); __tcp_add_write_queue_head(sk, nskb); sk_wmem_free_skb(sk, skb); sk->sk_wmem_queued += nskb->truesize; sk_mem_charge(sk, nskb->truesize); skb = nskb; } TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_ACK; TCP_ECN_send_synack(tcp_sk(sk), skb); } TCP_SKB_CB(skb)->when = tcp_time_stamp; return tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); } /** * tcp_make_synack - Prepare a SYN-ACK. * sk: listener socket * dst: dst entry attached to the SYNACK * req: request_sock pointer * * Allocate one skb and build a SYNACK packet. * @dst is consumed : Caller should not use it again. */ struct sk_buff *tcp_make_synack(struct sock *sk, struct dst_entry *dst, struct request_sock *req, struct tcp_fastopen_cookie *foc) { struct tcp_out_options opts; struct inet_request_sock *ireq = inet_rsk(req); struct tcp_sock *tp = tcp_sk(sk); struct tcphdr *th; struct sk_buff *skb; struct tcp_md5sig_key *md5; int tcp_header_size; int mss; skb = sock_wmalloc(sk, MAX_TCP_HEADER + 15, 1, GFP_ATOMIC); if (unlikely(!skb)) { dst_release(dst); return NULL; } /* Reserve space for headers. */ skb_reserve(skb, MAX_TCP_HEADER); skb_dst_set(skb, dst); security_skb_owned_by(skb, sk); mss = dst_metric_advmss(dst); if (tp->rx_opt.user_mss && tp->rx_opt.user_mss < mss) mss = tp->rx_opt.user_mss; if (req->rcv_wnd == 0) { /* ignored for retransmitted syns */ __u8 rcv_wscale; /* Set this up on the first call only */ req->window_clamp = tp->window_clamp ? : dst_metric(dst, RTAX_WINDOW); /* limit the window selection if the user enforce a smaller rx buffer */ if (sk->sk_userlocks & SOCK_RCVBUF_LOCK && (req->window_clamp > tcp_full_space(sk) || req->window_clamp == 0)) req->window_clamp = tcp_full_space(sk); tcp_select_initial_window(tcp_full_space(sk), mss - (ireq->tstamp_ok ? TCPOLEN_TSTAMP_ALIGNED : 0) - (tcp_rsk(req)->saw_mpc ? MPTCP_SUB_LEN_DSM_ALIGN : 0), &req->rcv_wnd, &req->window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND), sk); ireq->rcv_wscale = rcv_wscale; } memset(&opts, 0, sizeof(opts)); #ifdef CONFIG_SYN_COOKIES if (unlikely(req->cookie_ts)) TCP_SKB_CB(skb)->when = cookie_init_timestamp(req); else #endif TCP_SKB_CB(skb)->when = tcp_time_stamp; tcp_header_size = tcp_synack_options(sk, req, mss, skb, &opts, &md5, foc) + sizeof(*th); skb_push(skb, tcp_header_size); skb_reset_transport_header(skb); th = tcp_hdr(skb); memset(th, 0, sizeof(struct tcphdr)); th->syn = 1; th->ack = 1; TCP_ECN_make_synack(req, th); th->source = ireq->loc_port; th->dest = ireq->rmt_port; /* Setting of flags are superfluous here for callers (and ECE is * not even correctly set) */ tcp_init_nondata_skb(skb, tcp_rsk(req)->snt_isn, TCPHDR_SYN | TCPHDR_ACK); th->seq = htonl(TCP_SKB_CB(skb)->seq); /* XXX data is queued and acked as is. No buffer/window check */ th->ack_seq = htonl(tcp_rsk(req)->rcv_nxt); /* RFC1323: The window in SYN & SYN/ACK segments is never scaled. */ th->window = htons(min(req->rcv_wnd, 65535U)); tcp_options_write((__be32 *)(th + 1), tp, &opts, skb); th->doff = (tcp_header_size >> 2); TCP_ADD_STATS(sock_net(sk), TCP_MIB_OUTSEGS, tcp_skb_pcount(skb)); #ifdef CONFIG_TCP_MD5SIG /* Okay, we have all we need - do the md5 hash if needed */ if (md5) { tcp_rsk(req)->af_specific->calc_md5_hash(opts.hash_location, md5, NULL, req, skb); } #endif return skb; } EXPORT_SYMBOL(tcp_make_synack); /* Do all connect socket setups that can be done AF independent. */ void tcp_connect_init(struct sock *sk) { const struct dst_entry *dst = __sk_dst_get(sk); struct tcp_sock *tp = tcp_sk(sk); __u8 rcv_wscale; /* We'll fix this up when we get a response from the other end. * See tcp_input.c:tcp_rcv_state_process case TCP_SYN_SENT. */ tp->tcp_header_len = sizeof(struct tcphdr) + (sysctl_tcp_timestamps ? TCPOLEN_TSTAMP_ALIGNED : 0); #ifdef CONFIG_TCP_MD5SIG if (tp->af_specific->md5_lookup(sk, sk) != NULL) tp->tcp_header_len += TCPOLEN_MD5SIG_ALIGNED; #endif /* If user gave his TCP_MAXSEG, record it to clamp */ if (tp->rx_opt.user_mss) tp->rx_opt.mss_clamp = tp->rx_opt.user_mss; tp->max_window = 0; tcp_mtup_init(sk); tcp_sync_mss(sk, dst_mtu(dst)); if (!tp->window_clamp) tp->window_clamp = dst_metric(dst, RTAX_WINDOW); tp->advmss = dst_metric_advmss(dst); if (tp->rx_opt.user_mss && tp->rx_opt.user_mss < tp->advmss) tp->advmss = tp->rx_opt.user_mss; tcp_initialize_rcv_mss(sk); /* limit the window selection if the user enforce a smaller rx buffer */ if (sk->sk_userlocks & SOCK_RCVBUF_LOCK && (tp->window_clamp > tcp_full_space(sk) || tp->window_clamp == 0)) tp->window_clamp = tcp_full_space(sk); tcp_select_initial_window(tcp_full_space(sk), tp->advmss - (tp->rx_opt.ts_recent_stamp ? tp->tcp_header_len - sizeof(struct tcphdr) : 0), &tp->rcv_wnd, &tp->window_clamp, sysctl_tcp_window_scaling, &rcv_wscale, dst_metric(dst, RTAX_INITRWND), sk); tp->rx_opt.rcv_wscale = rcv_wscale; tp->rcv_ssthresh = tp->rcv_wnd; sk->sk_err = 0; sock_reset_flag(sk, SOCK_DONE); tp->snd_wnd = 0; tcp_init_wl(tp, 0); tp->snd_una = tp->write_seq; tp->snd_sml = tp->write_seq; tp->snd_up = tp->write_seq; tp->snd_nxt = tp->write_seq; if (likely(!tp->repair)) tp->rcv_nxt = 0; else tp->rcv_tstamp = tcp_time_stamp; tp->rcv_wup = tp->rcv_nxt; tp->copied_seq = tp->rcv_nxt; inet_csk(sk)->icsk_rto = TCP_TIMEOUT_INIT; inet_csk(sk)->icsk_retransmits = 0; tcp_clear_retrans(tp); #ifdef CONFIG_MPTCP if (sysctl_mptcp_enabled && mptcp_doit(sk)) { if (is_master_tp(tp)) { tp->request_mptcp = 1; mptcp_connect_init(sk); } else if (tp->mptcp) { tp->mptcp->snt_isn = tp->write_seq; tp->mptcp->init_rcv_wnd = tp->rcv_wnd; } } #endif } static void tcp_connect_queue_skb(struct sock *sk, struct sk_buff *skb) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_skb_cb *tcb = TCP_SKB_CB(skb); tcb->end_seq += skb->len; skb_header_release(skb); __tcp_add_write_queue_tail(sk, skb); sk->sk_wmem_queued += skb->truesize; sk_mem_charge(sk, skb->truesize); tp->write_seq = tcb->end_seq; tp->packets_out += tcp_skb_pcount(skb); } /* Build and send a SYN with data and (cached) Fast Open cookie. However, * queue a data-only packet after the regular SYN, such that regular SYNs * are retransmitted on timeouts. Also if the remote SYN-ACK acknowledges * only the SYN sequence, the data are retransmitted in the first ACK. * If cookie is not cached or other error occurs, falls back to send a * regular SYN with Fast Open cookie request option. */ static int tcp_send_syn_data(struct sock *sk, struct sk_buff *syn) { struct tcp_sock *tp = tcp_sk(sk); struct tcp_fastopen_request *fo = tp->fastopen_req; int syn_loss = 0, space, i, err = 0, iovlen = fo->data->msg_iovlen; struct sk_buff *syn_data = NULL, *data; unsigned long last_syn_loss = 0; tp->rx_opt.mss_clamp = tp->advmss; /* If MSS is not cached */ tcp_fastopen_cache_get(sk, &tp->rx_opt.mss_clamp, &fo->cookie, &syn_loss, &last_syn_loss); /* Recurring FO SYN losses: revert to regular handshake temporarily */ if (syn_loss > 1 && time_before(jiffies, last_syn_loss + (60*HZ << syn_loss))) { fo->cookie.len = -1; goto fallback; } if (sysctl_tcp_fastopen & TFO_CLIENT_NO_COOKIE) fo->cookie.len = -1; else if (fo->cookie.len <= 0) goto fallback; /* MSS for SYN-data is based on cached MSS and bounded by PMTU and * user-MSS. Reserve maximum option space for middleboxes that add * private TCP options. The cost is reduced data space in SYN :( */ if (tp->rx_opt.user_mss && tp->rx_opt.user_mss < tp->rx_opt.mss_clamp) tp->rx_opt.mss_clamp = tp->rx_opt.user_mss; space = __tcp_mtu_to_mss(sk, inet_csk(sk)->icsk_pmtu_cookie) - MAX_TCP_OPTION_SPACE; syn_data = skb_copy_expand(syn, skb_headroom(syn), space, sk->sk_allocation); if (syn_data == NULL) goto fallback; for (i = 0; i < iovlen && syn_data->len < space; ++i) { struct iovec *iov = &fo->data->msg_iov[i]; unsigned char __user *from = iov->iov_base; int len = iov->iov_len; if (syn_data->len + len > space) len = space - syn_data->len; else if (i + 1 == iovlen) /* No more data pending in inet_wait_for_connect() */ fo->data = NULL; if (skb_add_data(syn_data, from, len)) goto fallback; } /* Queue a data-only packet after the regular SYN for retransmission */ data = pskb_copy(syn_data, sk->sk_allocation); if (data == NULL) goto fallback; TCP_SKB_CB(data)->seq++; TCP_SKB_CB(data)->tcp_flags &= ~TCPHDR_SYN; TCP_SKB_CB(data)->tcp_flags = (TCPHDR_ACK|TCPHDR_PSH); tcp_connect_queue_skb(sk, data); fo->copied = data->len; if (tcp_transmit_skb(sk, syn_data, 0, sk->sk_allocation) == 0) { tp->syn_data = (fo->copied > 0); NET_INC_STATS(sock_net(sk), LINUX_MIB_TCPFASTOPENACTIVE); goto done; } syn_data = NULL; fallback: /* Send a regular SYN with Fast Open cookie request option */ if (fo->cookie.len > 0) fo->cookie.len = 0; err = tcp_transmit_skb(sk, syn, 1, sk->sk_allocation); if (err) tp->syn_fastopen = 0; kfree_skb(syn_data); done: fo->cookie.len = -1; /* Exclude Fast Open option for SYN retries */ return err; } /* Build a SYN and send it off. */ int tcp_connect(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *buff; int err; //printf("cwnd_init:%d\n", tcp_sk(sk)->snd_cwnd); tcp_connect_init(sk); if (unlikely(tp->repair)) { tcp_finish_connect(sk, NULL); return 0; } buff = alloc_skb_fclone(MAX_TCP_HEADER + 15, sk->sk_allocation); if (unlikely(buff == NULL)) return -ENOBUFS; /* Reserve space for headers. */ skb_reserve(buff, MAX_TCP_HEADER); tcp_init_nondata_skb(buff, tp->write_seq++, TCPHDR_SYN); tp->retrans_stamp = TCP_SKB_CB(buff)->when = tcp_time_stamp; tcp_connect_queue_skb(sk, buff); TCP_ECN_send_syn(sk, buff); //tcp_sk(sk)->snd_cwnd = 0; //printf("cwnd_init:%d\n", tcp_sk(sk)->snd_cwnd); /* Send off SYN; include data in Fast Open. */ err = tp->fastopen_req ? tcp_send_syn_data(sk, buff) : tcp_transmit_skb(sk, buff, 1, sk->sk_allocation); if (err == -ECONNREFUSED) return err; /* We change tp->snd_nxt after the tcp_transmit_skb() call * in order to make this packet get counted in tcpOutSegs. */ tp->snd_nxt = tp->write_seq; tp->pushed_seq = tp->write_seq; TCP_INC_STATS(sock_net(sk), TCP_MIB_ACTIVEOPENS); /* Timer for repeating the SYN until an answer. */ inet_csk_reset_xmit_timer(sk, ICSK_TIME_RETRANS, inet_csk(sk)->icsk_rto, TCP_RTO_MAX); return 0; } EXPORT_SYMBOL(tcp_connect); /* Send out a delayed ack, the caller does the policy checking * to see if we should even be here. See tcp_input.c:tcp_ack_snd_check() * for details. */ void tcp_send_delayed_ack(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); int ato = icsk->icsk_ack.ato; unsigned long timeout; if (ato > TCP_DELACK_MIN) { const struct tcp_sock *tp = tcp_sk(sk); int max_ato = HZ / 2; if (icsk->icsk_ack.pingpong || (icsk->icsk_ack.pending & ICSK_ACK_PUSHED)) max_ato = TCP_DELACK_MAX; /* Slow path, intersegment interval is "high". */ /* If some rtt estimate is known, use it to bound delayed ack. * Do not use inet_csk(sk)->icsk_rto here, use results of rtt measurements * directly. */ if (tp->srtt) { int rtt = max(tp->srtt >> 3, TCP_DELACK_MIN); if (rtt < max_ato) max_ato = rtt; } ato = min(ato, max_ato); } /* Stay within the limit we were given */ timeout = jiffies + ato; /* Use new timeout only if there wasn't a older one earlier. */ if (icsk->icsk_ack.pending & ICSK_ACK_TIMER) { /* If delack timer was blocked or is about to expire, * send ACK now. */ if (icsk->icsk_ack.blocked || time_before_eq(icsk->icsk_ack.timeout, jiffies + (ato >> 2))) { tcp_send_ack(sk); return; } if (!time_before(timeout, icsk->icsk_ack.timeout)) timeout = icsk->icsk_ack.timeout; } icsk->icsk_ack.pending |= ICSK_ACK_SCHED | ICSK_ACK_TIMER; icsk->icsk_ack.timeout = timeout; sk_reset_timer(sk, &icsk->icsk_delack_timer, timeout); } /* This routine sends an ack and also updates the window. */ void tcp_send_ack(struct sock *sk) { struct sk_buff *buff; /* If we have been reset, we may not send again. */ if (sk->sk_state == TCP_CLOSE) return; /* We are not putting this on the write queue, so * tcp_transmit_skb() will set the ownership to this * sock. */ buff = alloc_skb(MAX_TCP_HEADER, sk_gfp_atomic(sk, GFP_ATOMIC)); if (buff == NULL) { inet_csk_schedule_ack(sk); inet_csk(sk)->icsk_ack.ato = TCP_ATO_MIN; inet_csk_reset_xmit_timer(sk, ICSK_TIME_DACK, TCP_DELACK_MAX, TCP_RTO_MAX); return; } /* Reserve space for headers and prepare control bits. */ skb_reserve(buff, MAX_TCP_HEADER); tcp_init_nondata_skb(buff, tcp_acceptable_seq(sk), TCPHDR_ACK); /* Send it off, this clears delayed acks for us. */ TCP_SKB_CB(buff)->when = tcp_time_stamp; tcp_transmit_skb(sk, buff, 0, sk_gfp_atomic(sk, GFP_ATOMIC)); } EXPORT_SYMBOL(tcp_send_ack); /* This routine sends a packet with an out of date sequence * number. It assumes the other end will try to ack it. * * Question: what should we make while urgent mode? * 4.4BSD forces sending single byte of data. We cannot send * out of window data, because we have SND.NXT==SND.MAX... * * Current solution: to send TWO zero-length segments in urgent mode: * one is with SEG.SEQ=SND.UNA to deliver urgent pointer, another is * out-of-date with SND.UNA-1 to probe window. */ int tcp_xmit_probe_skb(struct sock *sk, int urgent) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; /* We don't queue it, tcp_transmit_skb() sets ownership. */ skb = alloc_skb(MAX_TCP_HEADER, sk_gfp_atomic(sk, GFP_ATOMIC)); if (skb == NULL) return -1; /* Reserve space for headers and set control bits. */ skb_reserve(skb, MAX_TCP_HEADER); /* Use a previous sequence. This should cause the other * end to send an ack. Don't queue or clone SKB, just * send it. */ tcp_init_nondata_skb(skb, tp->snd_una - !urgent, TCPHDR_ACK); TCP_SKB_CB(skb)->when = tcp_time_stamp; return tcp_transmit_skb(sk, skb, 0, GFP_ATOMIC); } void tcp_send_window_probe(struct sock *sk) { if (sk->sk_state == TCP_ESTABLISHED) { tcp_sk(sk)->snd_wl1 = tcp_sk(sk)->rcv_nxt - 1; tcp_sk(sk)->snd_nxt = tcp_sk(sk)->write_seq; tcp_xmit_probe_skb(sk, 0); } } /* Initiate keepalive or window probe from timer. */ int tcp_write_wakeup(struct sock *sk) { struct tcp_sock *tp = tcp_sk(sk); struct sk_buff *skb; if (sk->sk_state == TCP_CLOSE) return -1; if (is_meta_sk(sk)) return mptcp_write_wakeup(sk); if ((skb = tcp_send_head(sk)) != NULL && before(TCP_SKB_CB(skb)->seq, tcp_wnd_end(tp))) { int err; unsigned int mss = tcp_current_mss(sk); unsigned int seg_size = tcp_wnd_end(tp) - TCP_SKB_CB(skb)->seq; if (before(tp->pushed_seq, TCP_SKB_CB(skb)->end_seq)) tp->pushed_seq = TCP_SKB_CB(skb)->end_seq; /* We are probing the opening of a window * but the window size is != 0 * must have been a result SWS avoidance ( sender ) */ if (seg_size < TCP_SKB_CB(skb)->end_seq - TCP_SKB_CB(skb)->seq || skb->len > mss) { seg_size = min(seg_size, mss); TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; if (tcp_fragment(sk, skb, seg_size, mss)) return -1; } else if (!tcp_skb_pcount(skb)) tcp_set_skb_tso_segs(sk, skb, mss); TCP_SKB_CB(skb)->tcp_flags |= TCPHDR_PSH; TCP_SKB_CB(skb)->when = tcp_time_stamp; err = tcp_transmit_skb(sk, skb, 1, GFP_ATOMIC); if (!err) tcp_event_new_data_sent(sk, skb); return err; } else { if (between(tp->snd_up, tp->snd_una + 1, tp->snd_una + 0xFFFF)) tcp_xmit_probe_skb(sk, 1); return tcp_xmit_probe_skb(sk, 0); } } /* A window probe timeout has occurred. If window is not closed send * a partial packet else a zero probe. */ void tcp_send_probe0(struct sock *sk) { struct inet_connection_sock *icsk = inet_csk(sk); struct tcp_sock *tp = tcp_sk(sk); int err; err = tcp_write_wakeup(sk); if (tp->packets_out || !tcp_send_head(sk)) { /* Cancel probe timer, if it is not required. */ icsk->icsk_probes_out = 0; icsk->icsk_backoff = 0; return; } if (err <= 0) { if (icsk->icsk_backoff < sysctl_tcp_retries2) icsk->icsk_backoff++; icsk->icsk_probes_out++; inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0, min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RTO_MAX), TCP_RTO_MAX); } else { /* If packet was not sent due to local congestion, * do not backoff and do not remember icsk_probes_out. * Let local senders to fight for local resources. * * Use accumulated backoff yet. */ if (!icsk->icsk_probes_out) icsk->icsk_probes_out = 1; inet_csk_reset_xmit_timer(sk, ICSK_TIME_PROBE0, min(icsk->icsk_rto << icsk->icsk_backoff, TCP_RESOURCE_PROBE_INTERVAL), TCP_RTO_MAX); } }
Java
/* Copyright (C) 2005-2006 Jean-Marc Valin File: fftwrap.c Wrapper for various FFTs 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 Xiph.org 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 FOUNDATION OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif /*#define USE_SMALLFT*/ #define USE_KISS_FFT #include "misc.h" #define MAX_FFT_SIZE 2048 #ifdef FIXED_POINT static int maximize_range(spx_word16_t *in, spx_word16_t *out, spx_word16_t bound, int len) { int i, shift; spx_word16_t max_val = 0; for (i=0;i<len;i++) { if (in[i]>max_val) max_val = in[i]; if (-in[i]>max_val) max_val = -in[i]; } shift=0; while (max_val <= (bound>>1) && max_val != 0) { max_val <<= 1; shift++; } for (i=0;i<len;i++) { out[i] = in[i] << shift; } return shift; } static void renorm_range(spx_word16_t *in, spx_word16_t *out, int shift, int len) { int i; for (i=0;i<len;i++) { out[i] = (in[i] + (1<<(shift-1))) >> shift; } } #endif #ifdef USE_SMALLFT #include "smallft.h" #include <math.h> void *spx_fft_init(int size) { struct drft_lookup *table; table = speex_alloc(sizeof(struct drft_lookup)); spx_drft_init((struct drft_lookup *)table, size); return (void*)table; } void spx_fft_destroy(void *table) { spx_drft_clear(table); speex_free(table); } void spx_fft(void *table, float *in, float *out) { if (in==out) { int i; speex_warning("FFT should not be done in-place"); float scale = 1./((struct drft_lookup *)table)->n; for (i=0;i<((struct drft_lookup *)table)->n;i++) out[i] = scale*in[i]; } else { int i; float scale = 1./((struct drft_lookup *)table)->n; for (i=0;i<((struct drft_lookup *)table)->n;i++) out[i] = scale*in[i]; } spx_drft_forward((struct drft_lookup *)table, out); } void spx_ifft(void *table, float *in, float *out) { if (in==out) { int i; speex_warning("FFT should not be done in-place"); } else { int i; for (i=0;i<((struct drft_lookup *)table)->n;i++) out[i] = in[i]; } spx_drft_backward((struct drft_lookup *)table, out); } #elif defined(USE_KISS_FFT) #include "kiss_fftr.h" #include "kiss_fft.h" struct kiss_config { kiss_fftr_cfg forward; kiss_fftr_cfg backward; kiss_fft_cpx *freq_data; int N; }; void *spx_fft_init(int size) { struct kiss_config *table; table = (struct kiss_config*)speex_alloc(sizeof(struct kiss_config)); table->freq_data = (kiss_fft_cpx*)speex_alloc(sizeof(kiss_fft_cpx)*((size>>1)+1)); table->forward = kiss_fftr_alloc(size,0,NULL,NULL); table->backward = kiss_fftr_alloc(size,1,NULL,NULL); table->N = size; return table; } void spx_fft_destroy(void *table) { struct kiss_config *t = (struct kiss_config *)table; kiss_fftr_free(t->forward); kiss_fftr_free(t->backward); speex_free(t->freq_data); speex_free(table); } #ifdef FIXED_POINT void spx_fft(void *table, spx_word16_t *in, spx_word16_t *out) { int i; int shift; struct kiss_config *t = (struct kiss_config *)table; shift = maximize_range(in, in, 32000, t->N); kiss_fftr(t->forward, in, t->freq_data); out[0] = t->freq_data[0].r; for (i=1;i<t->N>>1;i++) { out[(i<<1)-1] = t->freq_data[i].r; out[(i<<1)] = t->freq_data[i].i; } out[(i<<1)-1] = t->freq_data[i].r; renorm_range(in, in, shift, t->N); renorm_range(out, out, shift, t->N); } #else void spx_fft(void *table, spx_word16_t *in, spx_word16_t *out) { int i; float scale; struct kiss_config *t = (struct kiss_config *)table; scale = 1./t->N; kiss_fftr(t->forward, in, t->freq_data); out[0] = scale*t->freq_data[0].r; for (i=1;i<t->N>>1;i++) { out[(i<<1)-1] = scale*t->freq_data[i].r; out[(i<<1)] = scale*t->freq_data[i].i; } out[(i<<1)-1] = scale*t->freq_data[i].r; } #endif void spx_ifft(void *table, spx_word16_t *in, spx_word16_t *out) { int i; struct kiss_config *t = (struct kiss_config *)table; t->freq_data[0].r = in[0]; t->freq_data[0].i = 0; for (i=1;i<t->N>>1;i++) { t->freq_data[i].r = in[(i<<1)-1]; t->freq_data[i].i = in[(i<<1)]; } t->freq_data[i].r = in[(i<<1)-1]; t->freq_data[i].i = 0; kiss_fftri(t->backward, t->freq_data, out); } #else #error No other FFT implemented #endif #ifdef FIXED_POINT /*#include "smallft.h"*/ void spx_fft_float(void *table, float *in, float *out) { int i; #ifdef USE_SMALLFT int N = ((struct drft_lookup *)table)->n; #elif defined(USE_KISS_FFT) int N = ((struct kiss_config *)table)->N; #else #endif #ifdef VAR_ARRAYS spx_word16_t _in[N]; spx_word16_t _out[N]; #else spx_word16_t _in[MAX_FFT_SIZE]; spx_word16_t _out[MAX_FFT_SIZE]; #endif for (i=0;i<N;i++) _in[i] = (int)floor(.5+in[i]); spx_fft(table, _in, _out); for (i=0;i<N;i++) out[i] = _out[i]; #if 0 if (!fixed_point) { float scale; struct drft_lookup t; spx_drft_init(&t, ((struct kiss_config *)table)->N); scale = 1./((struct kiss_config *)table)->N; for (i=0;i<((struct kiss_config *)table)->N;i++) out[i] = scale*in[i]; spx_drft_forward(&t, out); spx_drft_clear(&t); } #endif } void spx_ifft_float(void *table, float *in, float *out) { int i; #ifdef USE_SMALLFT int N = ((struct drft_lookup *)table)->n; #elif defined(USE_KISS_FFT) int N = ((struct kiss_config *)table)->N; #else #endif #ifdef VAR_ARRAYS spx_word16_t _in[N]; spx_word16_t _out[N]; #else spx_word16_t _in[MAX_FFT_SIZE]; spx_word16_t _out[MAX_FFT_SIZE]; #endif for (i=0;i<N;i++) _in[i] = (int)floor(.5+in[i]); spx_ifft(table, _in, _out); for (i=0;i<N;i++) out[i] = _out[i]; #if 0 if (!fixed_point) { int i; struct drft_lookup t; spx_drft_init(&t, ((struct kiss_config *)table)->N); for (i=0;i<((struct kiss_config *)table)->N;i++) out[i] = in[i]; spx_drft_backward(&t, out); spx_drft_clear(&t); } #endif } #else void spx_fft_float(void *table, float *in, float *out) { spx_fft(table, in, out); } void spx_ifft_float(void *table, float *in, float *out) { spx_ifft(table, in, out); } #endif
Java
#!/usr/bin/python2.3 # This is the short name of the plugin, used as the menu item # for the plugin. # If not specified, the name of the file will be used. shortname = "Moment Curve layout (Cohen et al. 1995)" # This is the long name of the plugin, used as the menu note # for the plugin. # If not specified, the short name will be used. name = "Moment Curve layout, O(n^3)" DEBUG = False def run(context, UI): """ Run this plugin. """ if len(context.graph.vertices) < 1: generate = True else: res = UI.prYesNo("Use current graph?", "Would you like to apply the layout to the current graph? If not, a complete graph will be generated and the current graph cleared.") if res: generate = False # Go through and eliminate any existing bend points from graph import DummyVertex for v in [x for x in context.graph.vertices if isinstance(x, DummyVertex)]: context.graph.removeVertex(v) else: generate = True if generate: N = UI.prType("Number of Vertices", "Input number of vertices to generate complete graph:", int, 4) if N == None: return True while N < 0: N = UI.prType("Number of Vertices", "Please input positive value.\n\nInput number of vertices to generate complete graph:", int, N) if N == None: return True context.graph.clear() # Generate a complete graph k_n(context, N) res = UI.prYesNo("Use mod-p layout?", "Would you like to use the mod-p compact layout (O(n^3) volume)? If not, the O(n^6) uncompacted layout will be used.") # Lay it out according to the 1bend layout moment(context, compact=res) context.camera.lookAtGraph(context.graph, context.graph.centerOfMass(), offset=context.graph.viewpoint()) return True def k_n(C, n): """ k_n (C, n) -> void Create a complete graph on n vertices in context C. """ from graph import Vertex, DummyVertex G = C.graph G.clear() # Add n vertices for i in range(n): G.addVertex(Vertex(id='%d' % i, name='v%d' % i)) # For every pair of vertices (u, v): for u in G.vertices: for v in G.vertices: # ignoring duplicates and u==v if (u, v) not in G.edges and (v, u) not in G.edges and u != v: # add an edge between u and v G.addEdge((u, v)) def moment(C, compact=False): """ Run moment curve layout (Cohen, Eades, Lin, Ruskey 1995). """ G = C.graph from math import sqrt, ceil, floor from graph import DummyVertex, GraphError import colorsys vertices = [x for x in G.vertices if not isinstance(x, DummyVertex)] n = len(vertices) # Choose a prime p with n < p <= 2n for p in range(n + 1, 2 * n + 1): for div in range(2, p / 2): if p % div == 0: # print "%d is not a prime (div by %d)" % (p, div) break else: # We did not find a divisor # print "%d is a prime!" % p break else: # Can't happen! raise Exception, "Can't find a prime between %d and %d!" % (n + 1, 2 * n) # Position each vertex if compact: for i in range(n): G.modVertex(vertices[i]).pos = (i * 10, ((i * i) % p) * 10, ((i * i * i) % p) * 10) else: for i in range(n): G.modVertex(vertices[i]).pos = (i, (i * i), (i * i * i)) return
Java
/* * IPv6 Address [auto]configuration * Linux INET6 implementation * * Authors: * Pedro Roque <roque@di.fc.ul.pt> * Alexey Kuznetsov <kuznet@ms2.inr.ac.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. */ /* * Changes: * * Janos Farkas : delete timer on ifdown * <chexum@bankinf.banki.hu> * Andi Kleen : kill double kfree on module * unload. * Maciej W. Rozycki : FDDI support * sekiya@USAGI : Don't send too many RS * packets. * yoshfuji@USAGI : Fixed interval between DAD * packets. * YOSHIFUJI Hideaki @USAGI : improved accuracy of * address validation timer. * YOSHIFUJI Hideaki @USAGI : Privacy Extensions (RFC3041) * support. * Yuji SEKIYA @USAGI : Don't assign a same IPv6 * address on a same interface. * YOSHIFUJI Hideaki @USAGI : ARCnet support * YOSHIFUJI Hideaki @USAGI : convert /proc/net/if_inet6 to * seq_file. * YOSHIFUJI Hideaki @USAGI : improved source address * selection; consider scope, * status etc. * Harout S. Hedeshian : procfs flag to toggle automatic * addition of prefix route */ #include <linux/errno.h> #include <linux/types.h> #include <linux/kernel.h> #include <linux/socket.h> #include <linux/sockios.h> #include <linux/net.h> #include <linux/in6.h> #include <linux/netdevice.h> #include <linux/if_addr.h> #include <linux/if_arp.h> #include <linux/if_arcnet.h> #include <linux/if_infiniband.h> #include <linux/route.h> #include <linux/inetdevice.h> #include <linux/init.h> #include <linux/slab.h> #ifdef CONFIG_SYSCTL #include <linux/sysctl.h> #endif #include <linux/capability.h> #include <linux/delay.h> #include <linux/notifier.h> #include <linux/string.h> #include <net/net_namespace.h> #include <net/sock.h> #include <net/snmp.h> #include <net/ipv6.h> #include <net/protocol.h> #include <net/ndisc.h> #include <net/ip6_route.h> #include <net/addrconf.h> #include <net/tcp.h> #include <net/ip.h> #include <net/netlink.h> #include <net/pkt_sched.h> #include <linux/if_tunnel.h> #include <linux/rtnetlink.h> #ifdef CONFIG_IPV6_PRIVACY #include <linux/random.h> #endif #include <linux/uaccess.h> #include <asm/unaligned.h> #include <linux/proc_fs.h> #include <linux/seq_file.h> #include <linux/export.h> /* Set to 3 to get tracing... */ // //#define ACONF_DEBUG 2 // The original value. #define ACONF_DEBUG 2 // To debug... // LGE_CHANGE_E, [LGE_DATA][LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER], heeyeon.nah@lge.com, 2013-05-21 #if ACONF_DEBUG >= 3 #define ADBG(x) printk x #else #define ADBG(x) #endif #define INFINITY_LIFE_TIME 0xFFFFFFFF // //The value of global scope is 1. //The value of link-local scope is 33. #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER #define LGE_DATA_GLOBAL_SCOPE 1 #define LGE_DATA_LINK_LOCAL_SCOPE 33 //The value which is 100 equals 1 second. //So value which is 5 equals 50 milli-seconds. //The 50 milli-seconds is requirements of LGU+. #define LGE_DATA_WAITING_TIME_FOR_DAD_OF_LGU 5 #endif // static inline u32 cstamp_delta(unsigned long cstamp) { return (cstamp - INITIAL_JIFFIES) * 100UL / HZ; } #define ADDRCONF_TIMER_FUZZ_MINUS (HZ > 50 ? HZ/50 : 1) #define ADDRCONF_TIMER_FUZZ (HZ / 4) #define ADDRCONF_TIMER_FUZZ_MAX (HZ) #ifdef CONFIG_SYSCTL static void addrconf_sysctl_register(struct inet6_dev *idev); static void addrconf_sysctl_unregister(struct inet6_dev *idev); #else static inline void addrconf_sysctl_register(struct inet6_dev *idev) { } static inline void addrconf_sysctl_unregister(struct inet6_dev *idev) { } #endif #ifdef CONFIG_IPV6_PRIVACY static int __ipv6_regen_rndid(struct inet6_dev *idev); static int __ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr); static void ipv6_regen_rndid(unsigned long data); #endif static int ipv6_generate_eui64(u8 *eui, struct net_device *dev); static int ipv6_count_addresses(struct inet6_dev *idev); /* * Configured unicast address hash table */ static struct hlist_head inet6_addr_lst[IN6_ADDR_HSIZE]; static DEFINE_SPINLOCK(addrconf_hash_lock); static void addrconf_verify(unsigned long); static DEFINE_TIMER(addr_chk_timer, addrconf_verify, 0, 0); static DEFINE_SPINLOCK(addrconf_verify_lock); static void addrconf_join_anycast(struct inet6_ifaddr *ifp); static void addrconf_leave_anycast(struct inet6_ifaddr *ifp); static void addrconf_type_change(struct net_device *dev, unsigned long event); static int addrconf_ifdown(struct net_device *dev, int how); static void addrconf_dad_start(struct inet6_ifaddr *ifp, u32 flags); static void addrconf_dad_timer(unsigned long data); static void addrconf_dad_completed(struct inet6_ifaddr *ifp); static void addrconf_dad_run(struct inet6_dev *idev); static void addrconf_rs_timer(unsigned long data); static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa); static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifa); static void inet6_prefix_notify(int event, struct inet6_dev *idev, struct prefix_info *pinfo); static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr, struct net_device *dev); static ATOMIC_NOTIFIER_HEAD(inet6addr_chain); static struct ipv6_devconf ipv6_devconf __read_mostly = { .forwarding = 0, .hop_limit = IPV6_DEFAULT_HOPLIMIT, .mtu6 = IPV6_MIN_MTU, .accept_ra = 1, .accept_redirects = 1, .autoconf = 1, .force_mld_version = 0, .dad_transmits = 1, .rtr_solicits = MAX_RTR_SOLICITATIONS, .rtr_solicit_interval = RTR_SOLICITATION_INTERVAL, .rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY, #ifdef CONFIG_IPV6_PRIVACY .use_tempaddr = 0, .temp_valid_lft = TEMP_VALID_LIFETIME, .temp_prefered_lft = TEMP_PREFERRED_LIFETIME, .regen_max_retry = REGEN_MAX_RETRY, .max_desync_factor = MAX_DESYNC_FACTOR, #endif .max_addresses = IPV6_MAX_ADDRESSES, .accept_ra_defrtr = 1, .accept_ra_pinfo = 1, #ifdef CONFIG_LGE_DHCPV6_WIFI .ra_info_flag = 0, #endif #ifdef CONFIG_IPV6_ROUTER_PREF .accept_ra_rtr_pref = 1, .rtr_probe_interval = 60 * HZ, #ifdef CONFIG_IPV6_ROUTE_INFO .accept_ra_rt_info_max_plen = 0, #endif #endif .accept_ra_rt_table = 0, .proxy_ndp = 0, .accept_source_route = 0, /* we do not accept RH0 by default. */ .disable_ipv6 = 0, .accept_dad = 1, .accept_ra_prefix_route = 1, }; static struct ipv6_devconf ipv6_devconf_dflt __read_mostly = { .forwarding = 0, .hop_limit = IPV6_DEFAULT_HOPLIMIT, .mtu6 = IPV6_MIN_MTU, .accept_ra = 1, .accept_redirects = 1, .autoconf = 1, .dad_transmits = 1, .rtr_solicits = MAX_RTR_SOLICITATIONS, .rtr_solicit_interval = RTR_SOLICITATION_INTERVAL, .rtr_solicit_delay = MAX_RTR_SOLICITATION_DELAY, #ifdef CONFIG_IPV6_PRIVACY .use_tempaddr = 0, .temp_valid_lft = TEMP_VALID_LIFETIME, .temp_prefered_lft = TEMP_PREFERRED_LIFETIME, .regen_max_retry = REGEN_MAX_RETRY, .max_desync_factor = MAX_DESYNC_FACTOR, #endif .max_addresses = IPV6_MAX_ADDRESSES, .accept_ra_defrtr = 1, .accept_ra_pinfo = 1, #ifdef CONFIG_LGE_DHCPV6_WIFI .ra_info_flag = 0, #endif #ifdef CONFIG_IPV6_ROUTER_PREF .accept_ra_rtr_pref = 1, .rtr_probe_interval = 60 * HZ, #ifdef CONFIG_IPV6_ROUTE_INFO .accept_ra_rt_info_max_plen = 0, #endif #endif .accept_ra_rt_table = 0, .proxy_ndp = 0, .accept_source_route = 0, /* we do not accept RH0 by default. */ .disable_ipv6 = 0, .accept_dad = 1, .accept_ra_prefix_route = 1, }; /* IPv6 Wildcard Address and Loopback Address defined by RFC2553 */ const struct in6_addr in6addr_any = IN6ADDR_ANY_INIT; const struct in6_addr in6addr_loopback = IN6ADDR_LOOPBACK_INIT; const struct in6_addr in6addr_linklocal_allnodes = IN6ADDR_LINKLOCAL_ALLNODES_INIT; const struct in6_addr in6addr_linklocal_allrouters = IN6ADDR_LINKLOCAL_ALLROUTERS_INIT; /* Check if a valid qdisc is available */ static inline bool addrconf_qdisc_ok(const struct net_device *dev) { return !qdisc_tx_is_noop(dev); } /* Check if a route is valid prefix route */ static inline int addrconf_is_prefix_route(const struct rt6_info *rt) { return (rt->rt6i_flags & (RTF_GATEWAY | RTF_DEFAULT)) == 0; } static void addrconf_del_timer(struct inet6_ifaddr *ifp) { if (del_timer(&ifp->timer)) __in6_ifa_put(ifp); } enum addrconf_timer_t { AC_NONE, AC_DAD, AC_RS, }; static void addrconf_mod_timer(struct inet6_ifaddr *ifp, enum addrconf_timer_t what, unsigned long when) { if (!del_timer(&ifp->timer)) in6_ifa_hold(ifp); switch (what) { case AC_DAD: ifp->timer.function = addrconf_dad_timer; break; case AC_RS: ifp->timer.function = addrconf_rs_timer; break; default: break; } ifp->timer.expires = jiffies + when; add_timer(&ifp->timer); } static int snmp6_alloc_dev(struct inet6_dev *idev) { if (snmp_mib_init((void __percpu **)idev->stats.ipv6, sizeof(struct ipstats_mib), __alignof__(struct ipstats_mib)) < 0) goto err_ip; idev->stats.icmpv6dev = kzalloc(sizeof(struct icmpv6_mib_device), GFP_KERNEL); if (!idev->stats.icmpv6dev) goto err_icmp; idev->stats.icmpv6msgdev = kzalloc(sizeof(struct icmpv6msg_mib_device), GFP_KERNEL); if (!idev->stats.icmpv6msgdev) goto err_icmpmsg; return 0; err_icmpmsg: kfree(idev->stats.icmpv6dev); err_icmp: snmp_mib_free((void __percpu **)idev->stats.ipv6); err_ip: return -ENOMEM; } static void snmp6_free_dev(struct inet6_dev *idev) { kfree(idev->stats.icmpv6msgdev); kfree(idev->stats.icmpv6dev); snmp_mib_free((void __percpu **)idev->stats.ipv6); } /* Nobody refers to this device, we may destroy it. */ void in6_dev_finish_destroy(struct inet6_dev *idev) { struct net_device *dev = idev->dev; WARN_ON(!list_empty(&idev->addr_list)); WARN_ON(idev->mc_list != NULL); #ifdef NET_REFCNT_DEBUG printk(KERN_DEBUG "in6_dev_finish_destroy: %s\n", dev ? dev->name : "NIL"); #endif dev_put(dev); if (!idev->dead) { pr_warning("Freeing alive inet6 device %p\n", idev); return; } snmp6_free_dev(idev); kfree_rcu(idev, rcu); } EXPORT_SYMBOL(in6_dev_finish_destroy); static struct inet6_dev * ipv6_add_dev(struct net_device *dev) { struct inet6_dev *ndev; ASSERT_RTNL(); if (dev->mtu < IPV6_MIN_MTU) return NULL; ndev = kzalloc(sizeof(struct inet6_dev), GFP_KERNEL); if (ndev == NULL) return NULL; rwlock_init(&ndev->lock); ndev->dev = dev; INIT_LIST_HEAD(&ndev->addr_list); memcpy(&ndev->cnf, dev_net(dev)->ipv6.devconf_dflt, sizeof(ndev->cnf)); ndev->cnf.mtu6 = dev->mtu; ndev->cnf.sysctl = NULL; ndev->nd_parms = neigh_parms_alloc(dev, &nd_tbl); if (ndev->nd_parms == NULL) { kfree(ndev); return NULL; } if (ndev->cnf.forwarding) dev_disable_lro(dev); /* We refer to the device */ dev_hold(dev); if (snmp6_alloc_dev(ndev) < 0) { ADBG((KERN_WARNING "%s(): cannot allocate memory for statistics; dev=%s.\n", __func__, dev->name)); neigh_parms_release(&nd_tbl, ndev->nd_parms); dev_put(dev); kfree(ndev); return NULL; } if (snmp6_register_dev(ndev) < 0) { ADBG((KERN_WARNING "%s(): cannot create /proc/net/dev_snmp6/%s\n", __func__, dev->name)); neigh_parms_release(&nd_tbl, ndev->nd_parms); ndev->dead = 1; in6_dev_finish_destroy(ndev); return NULL; } /* One reference from device. We must do this before * we invoke __ipv6_regen_rndid(). */ in6_dev_hold(ndev); if (dev->flags & (IFF_NOARP | IFF_LOOPBACK)) ndev->cnf.accept_dad = -1; #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) if (dev->type == ARPHRD_SIT && (dev->priv_flags & IFF_ISATAP)) { printk(KERN_INFO "%s: Disabled Multicast RS\n", dev->name); ndev->cnf.rtr_solicits = 0; } #endif #ifdef CONFIG_IPV6_PRIVACY INIT_LIST_HEAD(&ndev->tempaddr_list); setup_timer(&ndev->regen_timer, ipv6_regen_rndid, (unsigned long)ndev); if ((dev->flags&IFF_LOOPBACK) || dev->type == ARPHRD_TUNNEL || dev->type == ARPHRD_TUNNEL6 || dev->type == ARPHRD_SIT || dev->type == ARPHRD_NONE) { ndev->cnf.use_tempaddr = -1; } else { in6_dev_hold(ndev); ipv6_regen_rndid((unsigned long) ndev); } #endif if (netif_running(dev) && addrconf_qdisc_ok(dev)) ndev->if_flags |= IF_READY; ipv6_mc_init_dev(ndev); ndev->tstamp = jiffies; addrconf_sysctl_register(ndev); /* protected by rtnl_lock */ rcu_assign_pointer(dev->ip6_ptr, ndev); /* Join all-node multicast group */ ipv6_dev_mc_inc(dev, &in6addr_linklocal_allnodes); /* Join all-router multicast group if forwarding is set */ if (ndev->cnf.forwarding && (dev->flags & IFF_MULTICAST)) ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters); return ndev; } static struct inet6_dev * ipv6_find_idev(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); idev = __in6_dev_get(dev); if (!idev) { idev = ipv6_add_dev(dev); if (!idev) return NULL; } if (dev->flags&IFF_UP) ipv6_mc_up(idev); return idev; } #ifdef CONFIG_SYSCTL static void dev_forward_change(struct inet6_dev *idev) { struct net_device *dev; struct inet6_ifaddr *ifa; if (!idev) return; dev = idev->dev; if (idev->cnf.forwarding) dev_disable_lro(dev); if (dev && (dev->flags & IFF_MULTICAST)) { if (idev->cnf.forwarding) ipv6_dev_mc_inc(dev, &in6addr_linklocal_allrouters); else ipv6_dev_mc_dec(dev, &in6addr_linklocal_allrouters); } list_for_each_entry(ifa, &idev->addr_list, if_list) { if (ifa->flags&IFA_F_TENTATIVE) continue; if (idev->cnf.forwarding) addrconf_join_anycast(ifa); else addrconf_leave_anycast(ifa); } } static void addrconf_forward_change(struct net *net, __s32 newf) { struct net_device *dev; struct inet6_dev *idev; for_each_netdev(net, dev) { idev = __in6_dev_get(dev); if (idev) { int changed = (!idev->cnf.forwarding) ^ (!newf); idev->cnf.forwarding = newf; if (changed) dev_forward_change(idev); } } } static int addrconf_fixup_forwarding(struct ctl_table *table, int *p, int newf) { struct net *net; int old; if (!rtnl_trylock()) return restart_syscall(); net = (struct net *)table->extra2; old = *p; *p = newf; if (p == &net->ipv6.devconf_dflt->forwarding) { rtnl_unlock(); return 0; } if (p == &net->ipv6.devconf_all->forwarding) { net->ipv6.devconf_dflt->forwarding = newf; addrconf_forward_change(net, newf); } else if ((!newf) ^ (!old)) dev_forward_change((struct inet6_dev *)table->extra1); rtnl_unlock(); if (newf) rt6_purge_dflt_routers(net); return 1; } #endif /* Nobody refers to this ifaddr, destroy it */ void inet6_ifa_finish_destroy(struct inet6_ifaddr *ifp) { WARN_ON(!hlist_unhashed(&ifp->addr_lst)); #ifdef NET_REFCNT_DEBUG printk(KERN_DEBUG "inet6_ifa_finish_destroy\n"); #endif in6_dev_put(ifp->idev); if (del_timer(&ifp->timer)) pr_notice("Timer is still running, when freeing ifa=%p\n", ifp); if (ifp->state != INET6_IFADDR_STATE_DEAD) { pr_warning("Freeing alive inet6 address %p\n", ifp); return; } dst_release(&ifp->rt->dst); kfree_rcu(ifp, rcu); } static void ipv6_link_dev_addr(struct inet6_dev *idev, struct inet6_ifaddr *ifp) { struct list_head *p; int ifp_scope = ipv6_addr_src_scope(&ifp->addr); /* * Each device address list is sorted in order of scope - * global before linklocal. */ list_for_each(p, &idev->addr_list) { struct inet6_ifaddr *ifa = list_entry(p, struct inet6_ifaddr, if_list); if (ifp_scope >= ipv6_addr_src_scope(&ifa->addr)) break; } list_add_tail(&ifp->if_list, p); } static u32 ipv6_addr_hash(const struct in6_addr *addr) { /* * We perform the hash function over the last 64 bits of the address * This will include the IEEE address token on links that support it. */ return jhash_2words((__force u32)addr->s6_addr32[2], (__force u32)addr->s6_addr32[3], 0) & (IN6_ADDR_HSIZE - 1); } /* On success it returns ifp with increased reference count */ static struct inet6_ifaddr * ipv6_add_addr(struct inet6_dev *idev, const struct in6_addr *addr, int pfxlen, int scope, u32 flags) { struct inet6_ifaddr *ifa = NULL; struct rt6_info *rt; unsigned int hash; int err = 0; int addr_type = ipv6_addr_type(addr); if (addr_type == IPV6_ADDR_ANY || addr_type & IPV6_ADDR_MULTICAST || (!(idev->dev->flags & IFF_LOOPBACK) && addr_type & IPV6_ADDR_LOOPBACK)) return ERR_PTR(-EADDRNOTAVAIL); rcu_read_lock_bh(); if (idev->dead) { err = -ENODEV; /*XXX*/ goto out2; } if (idev->cnf.disable_ipv6) { err = -EACCES; goto out2; } spin_lock(&addrconf_hash_lock); /* Ignore adding duplicate addresses on an interface */ if (ipv6_chk_same_addr(dev_net(idev->dev), addr, idev->dev)) { ADBG(("ipv6_add_addr: already assigned\n")); err = -EEXIST; goto out; } ifa = kzalloc(sizeof(struct inet6_ifaddr), GFP_ATOMIC); if (ifa == NULL) { ADBG(("ipv6_add_addr: malloc failed\n")); err = -ENOBUFS; goto out; } rt = addrconf_dst_alloc(idev, addr, false); if (IS_ERR(rt)) { err = PTR_ERR(rt); goto out; } ifa->addr = *addr; spin_lock_init(&ifa->lock); spin_lock_init(&ifa->state_lock); init_timer(&ifa->timer); INIT_HLIST_NODE(&ifa->addr_lst); ifa->timer.data = (unsigned long) ifa; ifa->scope = scope; ifa->prefix_len = pfxlen; ifa->flags = flags | IFA_F_TENTATIVE; ifa->cstamp = ifa->tstamp = jiffies; ifa->rt = rt; ifa->idev = idev; in6_dev_hold(idev); /* For caller */ in6_ifa_hold(ifa); /* Add to big hash table */ hash = ipv6_addr_hash(addr); hlist_add_head_rcu(&ifa->addr_lst, &inet6_addr_lst[hash]); write_lock(&idev->lock); /* Add to inet6_dev unicast addr list. */ ipv6_link_dev_addr(idev, ifa); #ifdef CONFIG_IPV6_PRIVACY if (ifa->flags&IFA_F_TEMPORARY) { list_add(&ifa->tmp_list, &idev->tempaddr_list); in6_ifa_hold(ifa); } #endif in6_ifa_hold(ifa); write_unlock(&idev->lock); spin_unlock(&addrconf_hash_lock); out2: rcu_read_unlock_bh(); if (likely(err == 0)) atomic_notifier_call_chain(&inet6addr_chain, NETDEV_UP, ifa); else { kfree(ifa); ifa = ERR_PTR(err); } return ifa; out: spin_unlock(&addrconf_hash_lock); goto out2; } /* This function wants to get referenced ifp and releases it before return */ static void ipv6_del_addr(struct inet6_ifaddr *ifp) { struct inet6_ifaddr *ifa, *ifn; struct inet6_dev *idev = ifp->idev; int state; int deleted = 0, onlink = 0; unsigned long expires = jiffies; spin_lock_bh(&ifp->state_lock); state = ifp->state; ifp->state = INET6_IFADDR_STATE_DEAD; spin_unlock_bh(&ifp->state_lock); if (state == INET6_IFADDR_STATE_DEAD) goto out; spin_lock_bh(&addrconf_hash_lock); hlist_del_init_rcu(&ifp->addr_lst); write_lock_bh(&idev->lock); #ifdef CONFIG_IPV6_PRIVACY if (ifp->flags&IFA_F_TEMPORARY) { list_del(&ifp->tmp_list); if (ifp->ifpub) { in6_ifa_put(ifp->ifpub); ifp->ifpub = NULL; } __in6_ifa_put(ifp); } #endif list_for_each_entry_safe(ifa, ifn, &idev->addr_list, if_list) { if (ifa == ifp) { list_del_init(&ifp->if_list); __in6_ifa_put(ifp); if (!(ifp->flags & IFA_F_PERMANENT) || onlink > 0) break; deleted = 1; continue; } else if (ifp->flags & IFA_F_PERMANENT) { if (ipv6_prefix_equal(&ifa->addr, &ifp->addr, ifp->prefix_len)) { if (ifa->flags & IFA_F_PERMANENT) { onlink = 1; if (deleted) break; } else { unsigned long lifetime; if (!onlink) onlink = -1; spin_lock(&ifa->lock); lifetime = addrconf_timeout_fixup(ifa->valid_lft, HZ); /* * Note: Because this address is * not permanent, lifetime < * LONG_MAX / HZ here. */ if (time_before(expires, ifa->tstamp + lifetime * HZ)) expires = ifa->tstamp + lifetime * HZ; spin_unlock(&ifa->lock); } } } } write_unlock_bh(&idev->lock); spin_unlock_bh(&addrconf_hash_lock); addrconf_del_timer(ifp); ipv6_ifa_notify(RTM_DELADDR, ifp); atomic_notifier_call_chain(&inet6addr_chain, NETDEV_DOWN, ifp); /* * Purge or update corresponding prefix * * 1) we don't purge prefix here if address was not permanent. * prefix is managed by its own lifetime. * 2) if there're no addresses, delete prefix. * 3) if there're still other permanent address(es), * corresponding prefix is still permanent. * 4) otherwise, update prefix lifetime to the * longest valid lifetime among the corresponding * addresses on the device. * Note: subsequent RA will update lifetime. * * --yoshfuji */ if ((ifp->flags & IFA_F_PERMANENT) && onlink < 1) { struct in6_addr prefix; struct rt6_info *rt; struct net *net = dev_net(ifp->idev->dev); struct flowi6 fl6 = {}; ipv6_addr_prefix(&prefix, &ifp->addr, ifp->prefix_len); fl6.flowi6_oif = ifp->idev->dev->ifindex; fl6.daddr = prefix; rt = (struct rt6_info *)ip6_route_lookup(net, &fl6, RT6_LOOKUP_F_IFACE); if (rt != net->ipv6.ip6_null_entry && addrconf_is_prefix_route(rt)) { if (onlink == 0) { ip6_del_rt(rt); rt = NULL; } else if (!(rt->rt6i_flags & RTF_EXPIRES)) { rt6_set_expires(rt, expires); } } dst_release(&rt->dst); } /* clean up prefsrc entries */ rt6_remove_prefsrc(ifp); out: in6_ifa_put(ifp); } #ifdef CONFIG_IPV6_PRIVACY static int ipv6_create_tempaddr(struct inet6_ifaddr *ifp, struct inet6_ifaddr *ift) { struct inet6_dev *idev = ifp->idev; struct in6_addr addr, *tmpaddr; unsigned long tmp_prefered_lft, tmp_valid_lft, tmp_tstamp, age; unsigned long regen_advance; int tmp_plen; int ret = 0; int max_addresses; u32 addr_flags; unsigned long now = jiffies; write_lock(&idev->lock); if (ift) { spin_lock_bh(&ift->lock); memcpy(&addr.s6_addr[8], &ift->addr.s6_addr[8], 8); spin_unlock_bh(&ift->lock); tmpaddr = &addr; } else { tmpaddr = NULL; } retry: in6_dev_hold(idev); if (idev->cnf.use_tempaddr <= 0) { write_unlock(&idev->lock); printk(KERN_INFO "ipv6_create_tempaddr(): use_tempaddr is disabled.\n"); in6_dev_put(idev); ret = -1; goto out; } spin_lock_bh(&ifp->lock); if (ifp->regen_count++ >= idev->cnf.regen_max_retry) { idev->cnf.use_tempaddr = -1; /*XXX*/ spin_unlock_bh(&ifp->lock); write_unlock(&idev->lock); printk(KERN_WARNING "ipv6_create_tempaddr(): regeneration time exceeded. disabled temporary address support.\n"); in6_dev_put(idev); ret = -1; goto out; } in6_ifa_hold(ifp); memcpy(addr.s6_addr, ifp->addr.s6_addr, 8); if (__ipv6_try_regen_rndid(idev, tmpaddr) < 0) { spin_unlock_bh(&ifp->lock); write_unlock(&idev->lock); printk(KERN_WARNING "ipv6_create_tempaddr(): regeneration of randomized interface id failed.\n"); in6_ifa_put(ifp); in6_dev_put(idev); ret = -1; goto out; } memcpy(&addr.s6_addr[8], idev->rndid, 8); age = (now - ifp->tstamp) / HZ; tmp_valid_lft = min_t(__u32, ifp->valid_lft, idev->cnf.temp_valid_lft + age); tmp_prefered_lft = min_t(__u32, ifp->prefered_lft, idev->cnf.temp_prefered_lft + age - idev->cnf.max_desync_factor); tmp_plen = ifp->prefix_len; max_addresses = idev->cnf.max_addresses; tmp_tstamp = ifp->tstamp; spin_unlock_bh(&ifp->lock); regen_advance = idev->cnf.regen_max_retry * idev->cnf.dad_transmits * idev->nd_parms->retrans_time / HZ; write_unlock(&idev->lock); /* A temporary address is created only if this calculated Preferred * Lifetime is greater than REGEN_ADVANCE time units. In particular, * an implementation must not create a temporary address with a zero * Preferred Lifetime. * Use age calculation as in addrconf_verify to avoid unnecessary * temporary addresses being generated. */ age = (now - tmp_tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ; if (tmp_prefered_lft <= regen_advance + age) { in6_ifa_put(ifp); in6_dev_put(idev); ret = -1; goto out; } addr_flags = IFA_F_TEMPORARY; /* set in addrconf_prefix_rcv() */ if (ifp->flags & IFA_F_OPTIMISTIC) addr_flags |= IFA_F_OPTIMISTIC; ift = ipv6_add_addr(idev, &addr, tmp_plen, ipv6_addr_type(&addr)&IPV6_ADDR_SCOPE_MASK, addr_flags); if (IS_ERR(ift)) { in6_ifa_put(ifp); in6_dev_put(idev); printk(KERN_INFO "ipv6_create_tempaddr(): retry temporary address regeneration.\n"); tmpaddr = &addr; write_lock(&idev->lock); goto retry; } spin_lock_bh(&ift->lock); ift->ifpub = ifp; ift->valid_lft = tmp_valid_lft; ift->prefered_lft = tmp_prefered_lft; ift->cstamp = now; ift->tstamp = tmp_tstamp; spin_unlock_bh(&ift->lock); addrconf_dad_start(ift, 0); in6_ifa_put(ift); in6_dev_put(idev); out: return ret; } #endif /* * Choose an appropriate source address (RFC3484) */ enum { IPV6_SADDR_RULE_INIT = 0, IPV6_SADDR_RULE_LOCAL, IPV6_SADDR_RULE_SCOPE, IPV6_SADDR_RULE_PREFERRED, #ifdef CONFIG_IPV6_MIP6 IPV6_SADDR_RULE_HOA, #endif IPV6_SADDR_RULE_OIF, IPV6_SADDR_RULE_LABEL, #ifdef CONFIG_IPV6_PRIVACY IPV6_SADDR_RULE_PRIVACY, #endif IPV6_SADDR_RULE_ORCHID, IPV6_SADDR_RULE_PREFIX, #ifdef CONFIG_IPV6_OPTIMISTIC_DAD IPV6_SADDR_RULE_NOT_OPTIMISTIC, #endif IPV6_SADDR_RULE_MAX }; struct ipv6_saddr_score { int rule; int addr_type; struct inet6_ifaddr *ifa; DECLARE_BITMAP(scorebits, IPV6_SADDR_RULE_MAX); int scopedist; int matchlen; }; struct ipv6_saddr_dst { const struct in6_addr *addr; int ifindex; int scope; int label; unsigned int prefs; }; static inline int ipv6_saddr_preferred(int type) { if (type & (IPV6_ADDR_MAPPED|IPV6_ADDR_COMPATv4|IPV6_ADDR_LOOPBACK)) return 1; return 0; } static inline bool ipv6_use_optimistic_addr(struct inet6_dev *idev) { #ifdef CONFIG_IPV6_OPTIMISTIC_DAD return idev && idev->cnf.optimistic_dad && idev->cnf.use_optimistic; #else return false; #endif } static int ipv6_get_saddr_eval(struct net *net, struct ipv6_saddr_score *score, struct ipv6_saddr_dst *dst, int i) { int ret; if (i <= score->rule) { switch (i) { case IPV6_SADDR_RULE_SCOPE: ret = score->scopedist; break; case IPV6_SADDR_RULE_PREFIX: ret = score->matchlen; break; default: ret = !!test_bit(i, score->scorebits); } goto out; } switch (i) { case IPV6_SADDR_RULE_INIT: /* Rule 0: remember if hiscore is not ready yet */ ret = !!score->ifa; break; case IPV6_SADDR_RULE_LOCAL: /* Rule 1: Prefer same address */ ret = ipv6_addr_equal(&score->ifa->addr, dst->addr); break; case IPV6_SADDR_RULE_SCOPE: /* Rule 2: Prefer appropriate scope * * ret * ^ * -1 | d 15 * ---+--+-+---> scope * | * | d is scope of the destination. * B-d | \ * | \ <- smaller scope is better if * B-15 | \ if scope is enough for destinaion. * | ret = B - scope (-1 <= scope >= d <= 15). * d-C-1 | / * |/ <- greater is better * -C / if scope is not enough for destination. * /| ret = scope - C (-1 <= d < scope <= 15). * * d - C - 1 < B -15 (for all -1 <= d <= 15). * C > d + 14 - B >= 15 + 14 - B = 29 - B. * Assume B = 0 and we get C > 29. */ ret = __ipv6_addr_src_scope(score->addr_type); if (ret >= dst->scope) ret = -ret; else ret -= 128; /* 30 is enough */ score->scopedist = ret; break; case IPV6_SADDR_RULE_PREFERRED: { /* Rule 3: Avoid deprecated and optimistic addresses */ u8 avoid = IFA_F_DEPRECATED; if (!ipv6_use_optimistic_addr(score->ifa->idev)) avoid |= IFA_F_OPTIMISTIC; ret = ipv6_saddr_preferred(score->addr_type) || !(score->ifa->flags & avoid); break; } #ifdef CONFIG_IPV6_MIP6 case IPV6_SADDR_RULE_HOA: { /* Rule 4: Prefer home address */ int prefhome = !(dst->prefs & IPV6_PREFER_SRC_COA); ret = !(score->ifa->flags & IFA_F_HOMEADDRESS) ^ prefhome; break; } #endif case IPV6_SADDR_RULE_OIF: /* Rule 5: Prefer outgoing interface */ ret = (!dst->ifindex || dst->ifindex == score->ifa->idev->dev->ifindex); break; case IPV6_SADDR_RULE_LABEL: /* Rule 6: Prefer matching label */ ret = ipv6_addr_label(net, &score->ifa->addr, score->addr_type, score->ifa->idev->dev->ifindex) == dst->label; break; #ifdef CONFIG_IPV6_PRIVACY case IPV6_SADDR_RULE_PRIVACY: { /* Rule 7: Prefer public address * Note: prefer temporary address if use_tempaddr >= 2 */ int preftmp = dst->prefs & (IPV6_PREFER_SRC_PUBLIC|IPV6_PREFER_SRC_TMP) ? !!(dst->prefs & IPV6_PREFER_SRC_TMP) : score->ifa->idev->cnf.use_tempaddr >= 2; ret = (!(score->ifa->flags & IFA_F_TEMPORARY)) ^ preftmp; break; } #endif case IPV6_SADDR_RULE_ORCHID: /* Rule 8-: Prefer ORCHID vs ORCHID or * non-ORCHID vs non-ORCHID */ ret = !(ipv6_addr_orchid(&score->ifa->addr) ^ ipv6_addr_orchid(dst->addr)); break; case IPV6_SADDR_RULE_PREFIX: /* Rule 8: Use longest matching prefix */ score->matchlen = ret = ipv6_addr_diff(&score->ifa->addr, dst->addr); break; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD case IPV6_SADDR_RULE_NOT_OPTIMISTIC: /* Optimistic addresses still have lower precedence than other * preferred addresses. */ ret = !(score->ifa->flags & IFA_F_OPTIMISTIC); break; #endif default: ret = 0; } if (ret) __set_bit(i, score->scorebits); score->rule = i; out: return ret; } int ipv6_dev_get_saddr(struct net *net, struct net_device *dst_dev, const struct in6_addr *daddr, unsigned int prefs, struct in6_addr *saddr) { struct ipv6_saddr_score scores[2], *score = &scores[0], *hiscore = &scores[1]; struct ipv6_saddr_dst dst; struct net_device *dev; int dst_type; dst_type = __ipv6_addr_type(daddr); dst.addr = daddr; dst.ifindex = dst_dev ? dst_dev->ifindex : 0; dst.scope = __ipv6_addr_src_scope(dst_type); dst.label = ipv6_addr_label(net, daddr, dst_type, dst.ifindex); dst.prefs = prefs; hiscore->rule = -1; hiscore->ifa = NULL; rcu_read_lock(); for_each_netdev_rcu(net, dev) { struct inet6_dev *idev; /* Candidate Source Address (section 4) * - multicast and link-local destination address, * the set of candidate source address MUST only * include addresses assigned to interfaces * belonging to the same link as the outgoing * interface. * (- For site-local destination addresses, the * set of candidate source addresses MUST only * include addresses assigned to interfaces * belonging to the same site as the outgoing * interface.) */ if (((dst_type & IPV6_ADDR_MULTICAST) || dst.scope <= IPV6_ADDR_SCOPE_LINKLOCAL) && dst.ifindex && dev->ifindex != dst.ifindex) continue; idev = __in6_dev_get(dev); if (!idev) continue; read_lock_bh(&idev->lock); list_for_each_entry(score->ifa, &idev->addr_list, if_list) { int i; /* * - Tentative Address (RFC2462 section 5.4) * - A tentative address is not considered * "assigned to an interface" in the traditional * sense, unless it is also flagged as optimistic. * - Candidate Source Address (section 4) * - In any case, anycast addresses, multicast * addresses, and the unspecified address MUST * NOT be included in a candidate set. */ if ((score->ifa->flags & IFA_F_TENTATIVE) && (!(score->ifa->flags & IFA_F_OPTIMISTIC))) continue; score->addr_type = __ipv6_addr_type(&score->ifa->addr); if (unlikely(score->addr_type == IPV6_ADDR_ANY || score->addr_type & IPV6_ADDR_MULTICAST)) { LIMIT_NETDEBUG(KERN_DEBUG "ADDRCONF: unspecified / multicast address " "assigned as unicast address on %s", dev->name); continue; } score->rule = -1; bitmap_zero(score->scorebits, IPV6_SADDR_RULE_MAX); for (i = 0; i < IPV6_SADDR_RULE_MAX; i++) { int minihiscore, miniscore; minihiscore = ipv6_get_saddr_eval(net, hiscore, &dst, i); miniscore = ipv6_get_saddr_eval(net, score, &dst, i); if (minihiscore > miniscore) { if (i == IPV6_SADDR_RULE_SCOPE && score->scopedist > 0) { /* * special case: * each remaining entry * has too small (not enough) * scope, because ifa entries * are sorted by their scope * values. */ goto try_nextdev; } break; } else if (minihiscore < miniscore) { if (hiscore->ifa) in6_ifa_put(hiscore->ifa); in6_ifa_hold(score->ifa); swap(hiscore, score); /* restore our iterator */ score->ifa = hiscore->ifa; break; } } } try_nextdev: read_unlock_bh(&idev->lock); } rcu_read_unlock(); if (!hiscore->ifa) return -EADDRNOTAVAIL; *saddr = hiscore->ifa->addr; in6_ifa_put(hiscore->ifa); return 0; } EXPORT_SYMBOL(ipv6_dev_get_saddr); int __ipv6_get_lladdr(struct inet6_dev *idev, struct in6_addr *addr, unsigned char banned_flags) { struct inet6_ifaddr *ifp; int err = -EADDRNOTAVAIL; list_for_each_entry(ifp, &idev->addr_list, if_list) { if (ifp->scope == IFA_LINK && !(ifp->flags & banned_flags)) { *addr = ifp->addr; err = 0; break; } } return err; } int ipv6_get_lladdr(struct net_device *dev, struct in6_addr *addr, unsigned char banned_flags) { struct inet6_dev *idev; int err = -EADDRNOTAVAIL; rcu_read_lock(); idev = __in6_dev_get(dev); if (idev) { read_lock_bh(&idev->lock); err = __ipv6_get_lladdr(idev, addr, banned_flags); read_unlock_bh(&idev->lock); } rcu_read_unlock(); return err; } static int ipv6_count_addresses(struct inet6_dev *idev) { int cnt = 0; struct inet6_ifaddr *ifp; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) cnt++; read_unlock_bh(&idev->lock); return cnt; } int ipv6_chk_addr(struct net *net, const struct in6_addr *addr, const struct net_device *dev, int strict) { struct inet6_ifaddr *ifp; struct hlist_node *node; unsigned int hash = ipv6_addr_hash(addr); rcu_read_lock_bh(); hlist_for_each_entry_rcu(ifp, node, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr) && (!(ifp->flags&IFA_F_TENTATIVE) || (ipv6_use_optimistic_addr(ifp->idev) && ifp->flags&IFA_F_OPTIMISTIC)) && (dev == NULL || ifp->idev->dev == dev || !(ifp->scope&(IFA_LINK|IFA_HOST) || strict))) { rcu_read_unlock_bh(); return 1; } } rcu_read_unlock_bh(); return 0; } EXPORT_SYMBOL(ipv6_chk_addr); static bool ipv6_chk_same_addr(struct net *net, const struct in6_addr *addr, struct net_device *dev) { unsigned int hash = ipv6_addr_hash(addr); struct inet6_ifaddr *ifp; struct hlist_node *node; hlist_for_each_entry(ifp, node, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr)) { if (dev == NULL || ifp->idev->dev == dev) return true; } } return false; } int ipv6_chk_prefix(const struct in6_addr *addr, struct net_device *dev) { struct inet6_dev *idev; struct inet6_ifaddr *ifa; int onlink; onlink = 0; rcu_read_lock(); idev = __in6_dev_get(dev); if (idev) { read_lock_bh(&idev->lock); list_for_each_entry(ifa, &idev->addr_list, if_list) { onlink = ipv6_prefix_equal(addr, &ifa->addr, ifa->prefix_len); if (onlink) break; } read_unlock_bh(&idev->lock); } rcu_read_unlock(); return onlink; } EXPORT_SYMBOL(ipv6_chk_prefix); struct inet6_ifaddr *ipv6_get_ifaddr(struct net *net, const struct in6_addr *addr, struct net_device *dev, int strict) { struct inet6_ifaddr *ifp, *result = NULL; unsigned int hash = ipv6_addr_hash(addr); struct hlist_node *node; rcu_read_lock_bh(); hlist_for_each_entry_rcu_bh(ifp, node, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr)) { if (dev == NULL || ifp->idev->dev == dev || !(ifp->scope&(IFA_LINK|IFA_HOST) || strict)) { result = ifp; in6_ifa_hold(ifp); break; } } } rcu_read_unlock_bh(); return result; } /* Gets referenced address, destroys ifaddr */ static void addrconf_dad_stop(struct inet6_ifaddr *ifp, int dad_failed) { if (ifp->flags&IFA_F_PERMANENT) { spin_lock_bh(&ifp->lock); addrconf_del_timer(ifp); ifp->flags |= IFA_F_TENTATIVE; if (dad_failed) ifp->flags |= IFA_F_DADFAILED; spin_unlock_bh(&ifp->lock); if (dad_failed) ipv6_ifa_notify(0, ifp); in6_ifa_put(ifp); #ifdef CONFIG_IPV6_PRIVACY } else if (ifp->flags&IFA_F_TEMPORARY) { struct inet6_ifaddr *ifpub; spin_lock_bh(&ifp->lock); ifpub = ifp->ifpub; if (ifpub) { in6_ifa_hold(ifpub); spin_unlock_bh(&ifp->lock); ipv6_create_tempaddr(ifpub, ifp); in6_ifa_put(ifpub); } else { spin_unlock_bh(&ifp->lock); } ipv6_del_addr(ifp); #endif } else ipv6_del_addr(ifp); } static int addrconf_dad_end(struct inet6_ifaddr *ifp) { int err = -ENOENT; spin_lock(&ifp->state_lock); if (ifp->state == INET6_IFADDR_STATE_DAD) { ifp->state = INET6_IFADDR_STATE_POSTDAD; err = 0; } spin_unlock(&ifp->state_lock); return err; } void addrconf_dad_failure(struct inet6_ifaddr *ifp) { struct inet6_dev *idev = ifp->idev; if (addrconf_dad_end(ifp)) { in6_ifa_put(ifp); return; } if (net_ratelimit()) printk(KERN_INFO "%s: IPv6 duplicate address %pI6c detected!\n", ifp->idev->dev->name, &ifp->addr); if (idev->cnf.accept_dad > 1 && !idev->cnf.disable_ipv6) { struct in6_addr addr; addr.s6_addr32[0] = htonl(0xfe800000); addr.s6_addr32[1] = 0; if (!ipv6_generate_eui64(addr.s6_addr + 8, idev->dev) && ipv6_addr_equal(&ifp->addr, &addr)) { /* DAD failed for link-local based on MAC address */ idev->cnf.disable_ipv6 = 1; printk(KERN_INFO "%s: IPv6 being disabled!\n", ifp->idev->dev->name); } } addrconf_dad_stop(ifp, 1); } /* Join to solicited addr multicast group. */ void addrconf_join_solict(struct net_device *dev, const struct in6_addr *addr) { struct in6_addr maddr; if (dev->flags&(IFF_LOOPBACK|IFF_NOARP)) return; addrconf_addr_solict_mult(addr, &maddr); ipv6_dev_mc_inc(dev, &maddr); } void addrconf_leave_solict(struct inet6_dev *idev, const struct in6_addr *addr) { struct in6_addr maddr; if (idev->dev->flags&(IFF_LOOPBACK|IFF_NOARP)) return; addrconf_addr_solict_mult(addr, &maddr); __ipv6_dev_mc_dec(idev, &maddr); } static void addrconf_join_anycast(struct inet6_ifaddr *ifp) { struct in6_addr addr; if (ifp->prefix_len == 127) /* RFC 6164 */ return; ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len); if (ipv6_addr_any(&addr)) return; ipv6_dev_ac_inc(ifp->idev->dev, &addr); } static void addrconf_leave_anycast(struct inet6_ifaddr *ifp) { struct in6_addr addr; if (ifp->prefix_len == 127) /* RFC 6164 */ return; ipv6_addr_prefix(&addr, &ifp->addr, ifp->prefix_len); if (ipv6_addr_any(&addr)) return; __ipv6_dev_ac_dec(ifp->idev, &addr); } static int addrconf_ifid_eui48(u8 *eui, struct net_device *dev) { if (dev->addr_len != ETH_ALEN) return -1; memcpy(eui, dev->dev_addr, 3); memcpy(eui + 5, dev->dev_addr + 3, 3); /* * The zSeries OSA network cards can be shared among various * OS instances, but the OSA cards have only one MAC address. * This leads to duplicate address conflicts in conjunction * with IPv6 if more than one instance uses the same card. * * The driver for these cards can deliver a unique 16-bit * identifier for each instance sharing the same card. It is * placed instead of 0xFFFE in the interface identifier. The * "u" bit of the interface identifier is not inverted in this * case. Hence the resulting interface identifier has local * scope according to RFC2373. */ if (dev->dev_id) { eui[3] = (dev->dev_id >> 8) & 0xFF; eui[4] = dev->dev_id & 0xFF; } else { eui[3] = 0xFF; eui[4] = 0xFE; eui[0] ^= 2; } return 0; } static int addrconf_ifid_arcnet(u8 *eui, struct net_device *dev) { /* XXX: inherit EUI-64 from other interface -- yoshfuji */ if (dev->addr_len != ARCNET_ALEN) return -1; memset(eui, 0, 7); eui[7] = *(u8*)dev->dev_addr; return 0; } static int addrconf_ifid_infiniband(u8 *eui, struct net_device *dev) { if (dev->addr_len != INFINIBAND_ALEN) return -1; memcpy(eui, dev->dev_addr + 12, 8); eui[0] |= 2; return 0; } static int __ipv6_isatap_ifid(u8 *eui, __be32 addr) { if (addr == 0) return -1; eui[0] = (ipv4_is_zeronet(addr) || ipv4_is_private_10(addr) || ipv4_is_loopback(addr) || ipv4_is_linklocal_169(addr) || ipv4_is_private_172(addr) || ipv4_is_test_192(addr) || ipv4_is_anycast_6to4(addr) || ipv4_is_private_192(addr) || ipv4_is_test_198(addr) || ipv4_is_multicast(addr) || ipv4_is_lbcast(addr)) ? 0x00 : 0x02; eui[1] = 0; eui[2] = 0x5E; eui[3] = 0xFE; memcpy(eui + 4, &addr, 4); return 0; } static int addrconf_ifid_sit(u8 *eui, struct net_device *dev) { if (dev->priv_flags & IFF_ISATAP) return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr); return -1; } static int addrconf_ifid_gre(u8 *eui, struct net_device *dev) { return __ipv6_isatap_ifid(eui, *(__be32 *)dev->dev_addr); } static int ipv6_generate_eui64(u8 *eui, struct net_device *dev) { switch (dev->type) { case ARPHRD_ETHER: case ARPHRD_FDDI: case ARPHRD_IEEE802_TR: return addrconf_ifid_eui48(eui, dev); case ARPHRD_ARCNET: return addrconf_ifid_arcnet(eui, dev); case ARPHRD_INFINIBAND: return addrconf_ifid_infiniband(eui, dev); case ARPHRD_SIT: return addrconf_ifid_sit(eui, dev); case ARPHRD_IPGRE: return addrconf_ifid_gre(eui, dev); case ARPHRD_RAWIP: { struct in6_addr lladdr; if (ipv6_get_lladdr(dev, &lladdr, IFA_F_TENTATIVE)) get_random_bytes(eui, 8); else memcpy(eui, lladdr.s6_addr + 8, 8); return 0; } } return -1; } static int ipv6_inherit_eui64(u8 *eui, struct inet6_dev *idev) { int err = -1; struct inet6_ifaddr *ifp; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) { if (ifp->scope == IFA_LINK && !(ifp->flags&IFA_F_TENTATIVE)) { memcpy(eui, ifp->addr.s6_addr+8, 8); err = 0; break; } } read_unlock_bh(&idev->lock); return err; } #ifdef CONFIG_IPV6_PRIVACY /* (re)generation of randomized interface identifier (RFC 3041 3.2, 3.5) */ static int __ipv6_regen_rndid(struct inet6_dev *idev) { regen: get_random_bytes(idev->rndid, sizeof(idev->rndid)); idev->rndid[0] &= ~0x02; /* * <draft-ietf-ipngwg-temp-addresses-v2-00.txt>: * check if generated address is not inappropriate * * - Reserved subnet anycast (RFC 2526) * 11111101 11....11 1xxxxxxx * - ISATAP (RFC4214) 6.1 * 00-00-5E-FE-xx-xx-xx-xx * - value 0 * - XXX: already assigned to an address on the device */ if (idev->rndid[0] == 0xfd && (idev->rndid[1]&idev->rndid[2]&idev->rndid[3]&idev->rndid[4]&idev->rndid[5]&idev->rndid[6]) == 0xff && (idev->rndid[7]&0x80)) goto regen; if ((idev->rndid[0]|idev->rndid[1]) == 0) { if (idev->rndid[2] == 0x5e && idev->rndid[3] == 0xfe) goto regen; if ((idev->rndid[2]|idev->rndid[3]|idev->rndid[4]|idev->rndid[5]|idev->rndid[6]|idev->rndid[7]) == 0x00) goto regen; } return 0; } static void ipv6_regen_rndid(unsigned long data) { struct inet6_dev *idev = (struct inet6_dev *) data; unsigned long expires; rcu_read_lock_bh(); write_lock_bh(&idev->lock); if (idev->dead) goto out; if (__ipv6_regen_rndid(idev) < 0) goto out; expires = jiffies + idev->cnf.temp_prefered_lft * HZ - idev->cnf.regen_max_retry * idev->cnf.dad_transmits * idev->nd_parms->retrans_time - idev->cnf.max_desync_factor * HZ; if (time_before(expires, jiffies)) { printk(KERN_WARNING "ipv6_regen_rndid(): too short regeneration interval; timer disabled for %s.\n", idev->dev->name); goto out; } if (!mod_timer(&idev->regen_timer, expires)) in6_dev_hold(idev); out: write_unlock_bh(&idev->lock); rcu_read_unlock_bh(); in6_dev_put(idev); } static int __ipv6_try_regen_rndid(struct inet6_dev *idev, struct in6_addr *tmpaddr) { int ret = 0; if (tmpaddr && memcmp(idev->rndid, &tmpaddr->s6_addr[8], 8) == 0) ret = __ipv6_regen_rndid(idev); return ret; } #endif u32 addrconf_rt_table(const struct net_device *dev, u32 default_table) { /* Determines into what table to put autoconf PIO/RIO/default routes * learned on this device. * * - If 0, use the same table for every device. This puts routes into * one of RT_TABLE_{PREFIX,INFO,DFLT} depending on the type of route * (but note that these three are currently all equal to * RT6_TABLE_MAIN). * - If > 0, use the specified table. * - If < 0, put routes into table dev->ifindex + (-rt_table). */ struct inet6_dev *idev = in6_dev_get(dev); u32 table; int sysctl = idev->cnf.accept_ra_rt_table; if (sysctl == 0) { table = default_table; } else if (sysctl > 0) { table = (u32) sysctl; } else { table = (unsigned) dev->ifindex + (-sysctl); } in6_dev_put(idev); return table; } /* * Add prefix route. */ static void addrconf_prefix_route(struct in6_addr *pfx, int plen, struct net_device *dev, unsigned long expires, u32 flags) { struct fib6_config cfg = { .fc_table = addrconf_rt_table(dev, RT6_TABLE_PREFIX), .fc_metric = IP6_RT_PRIO_ADDRCONF, .fc_ifindex = dev->ifindex, .fc_expires = expires, .fc_dst_len = plen, .fc_flags = RTF_UP | flags, .fc_nlinfo.nl_net = dev_net(dev), .fc_protocol = RTPROT_KERNEL, }; cfg.fc_dst = *pfx; /* Prevent useless cloning on PtP SIT. This thing is done here expecting that the whole class of non-broadcast devices need not cloning. */ #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) if (dev->type == ARPHRD_SIT && (dev->flags & IFF_POINTOPOINT)) cfg.fc_flags |= RTF_NONEXTHOP; #endif ip6_route_add(&cfg); } static struct rt6_info *addrconf_get_prefix_route(const struct in6_addr *pfx, int plen, const struct net_device *dev, u32 flags, u32 noflags) { struct fib6_node *fn; struct rt6_info *rt = NULL; struct fib6_table *table; table = fib6_get_table(dev_net(dev), addrconf_rt_table(dev, RT6_TABLE_PREFIX)); if (table == NULL) return NULL; write_lock_bh(&table->tb6_lock); fn = fib6_locate(&table->tb6_root, pfx, plen, NULL, 0); if (!fn) goto out; for (rt = fn->leaf; rt; rt = rt->dst.rt6_next) { if (rt->dst.dev->ifindex != dev->ifindex) continue; if ((rt->rt6i_flags & flags) != flags) continue; if ((rt->rt6i_flags & noflags) != 0) continue; dst_hold(&rt->dst); break; } out: write_unlock_bh(&table->tb6_lock); return rt; } /* Create "default" multicast route to the interface */ static void addrconf_add_mroute(struct net_device *dev) { struct fib6_config cfg = { .fc_table = RT6_TABLE_LOCAL, .fc_metric = IP6_RT_PRIO_ADDRCONF, .fc_ifindex = dev->ifindex, .fc_dst_len = 8, .fc_flags = RTF_UP, .fc_nlinfo.nl_net = dev_net(dev), }; ipv6_addr_set(&cfg.fc_dst, htonl(0xFF000000), 0, 0, 0); ip6_route_add(&cfg); } #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) static void sit_route_add(struct net_device *dev) { struct fib6_config cfg = { .fc_table = RT6_TABLE_MAIN, .fc_metric = IP6_RT_PRIO_ADDRCONF, .fc_ifindex = dev->ifindex, .fc_dst_len = 96, .fc_flags = RTF_UP | RTF_NONEXTHOP, .fc_nlinfo.nl_net = dev_net(dev), }; /* prefix length - 96 bits "::d.d.d.d" */ ip6_route_add(&cfg); } #endif static void addrconf_add_lroute(struct net_device *dev) { struct in6_addr addr; ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0); addrconf_prefix_route(&addr, 64, dev, 0, 0); } static struct inet6_dev *addrconf_add_dev(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); idev = ipv6_find_idev(dev); if (!idev) return ERR_PTR(-ENOBUFS); if (idev->cnf.disable_ipv6) return ERR_PTR(-EACCES); /* Add default multicast route */ if (!(dev->flags & IFF_LOOPBACK)) addrconf_add_mroute(dev); /* Add link local route */ addrconf_add_lroute(dev); return idev; } void addrconf_prefix_rcv(struct net_device *dev, u8 *opt, int len, bool sllao) { struct prefix_info *pinfo; __u32 valid_lft; __u32 prefered_lft; int addr_type; struct inet6_dev *in6_dev; struct net *net = dev_net(dev); // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] The prefix is received now !", __func__); #endif // pinfo = (struct prefix_info *) opt; if (len < sizeof(struct prefix_info)) { ADBG(("addrconf: prefix option too short\n")); return; } /* * Validation checks ([ADDRCONF], page 19) */ addr_type = ipv6_addr_type(&pinfo->prefix); if (addr_type & (IPV6_ADDR_MULTICAST|IPV6_ADDR_LINKLOCAL)) return; valid_lft = ntohl(pinfo->valid); prefered_lft = ntohl(pinfo->prefered); if (prefered_lft > valid_lft) { if (net_ratelimit()) printk(KERN_WARNING "addrconf: prefix option has invalid lifetime\n"); return; } in6_dev = in6_dev_get(dev); if (in6_dev == NULL) { if (net_ratelimit()) printk(KERN_DEBUG "addrconf: device %s not configured\n", dev->name); return; } /* * Two things going on here: * 1) Add routes for on-link prefixes * 2) Configure prefixes with the auto flag set */ if (pinfo->onlink) { struct rt6_info *rt; unsigned long rt_expires; /* Avoid arithmetic overflow. Really, we could * save rt_expires in seconds, likely valid_lft, * but it would require division in fib gc, that it * not good. */ if (HZ > USER_HZ) rt_expires = addrconf_timeout_fixup(valid_lft, HZ); else rt_expires = addrconf_timeout_fixup(valid_lft, USER_HZ); if (addrconf_finite_timeout(rt_expires)) rt_expires *= HZ; rt = addrconf_get_prefix_route(&pinfo->prefix, pinfo->prefix_len, dev, RTF_ADDRCONF | RTF_PREFIX_RT, RTF_GATEWAY | RTF_DEFAULT); if (rt) { /* Autoconf prefix route */ if (valid_lft == 0) { ip6_del_rt(rt); rt = NULL; } else if (addrconf_finite_timeout(rt_expires)) { /* not infinity */ rt6_set_expires(rt, jiffies + rt_expires); } else { rt6_clean_expires(rt); } } else if (valid_lft) { clock_t expires = 0; int flags = RTF_ADDRCONF | RTF_PREFIX_RT; if (addrconf_finite_timeout(rt_expires)) { /* not infinity */ flags |= RTF_EXPIRES; expires = jiffies_to_clock_t(rt_expires); } if (dev->ip6_ptr->cnf.accept_ra_prefix_route) { addrconf_prefix_route(&pinfo->prefix, pinfo->prefix_len, dev, expires, flags); } } if (rt) dst_release(&rt->dst); } /* Try to figure out our local address for this prefix */ if (pinfo->autoconf && in6_dev->cnf.autoconf) { struct inet6_ifaddr * ifp; struct in6_addr addr; int create = 0, update_lft = 0; if (pinfo->prefix_len == 64) { memcpy(&addr, &pinfo->prefix, 8); if (ipv6_generate_eui64(addr.s6_addr + 8, dev) && ipv6_inherit_eui64(addr.s6_addr + 8, in6_dev)) { in6_dev_put(in6_dev); return; } goto ok; } if (net_ratelimit()) printk(KERN_DEBUG "IPv6 addrconf: prefix with wrong length %d\n", pinfo->prefix_len); in6_dev_put(in6_dev); return; ok: ifp = ipv6_get_ifaddr(net, &addr, dev, 1); if (ifp == NULL && valid_lft) { int max_addresses = in6_dev->cnf.max_addresses; u32 addr_flags = 0; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD if (in6_dev->cnf.optimistic_dad && !net->ipv6.devconf_all->forwarding && sllao) addr_flags = IFA_F_OPTIMISTIC; #endif /* Do not allow to create too much of autoconfigured * addresses; this would be too easy way to crash kernel. */ if (!max_addresses || ipv6_count_addresses(in6_dev) < max_addresses) ifp = ipv6_add_addr(in6_dev, &addr, pinfo->prefix_len, addr_type&IPV6_ADDR_SCOPE_MASK, addr_flags); if (!ifp || IS_ERR(ifp)) { in6_dev_put(in6_dev); return; } update_lft = create = 1; ifp->cstamp = jiffies; addrconf_dad_start(ifp, RTF_ADDRCONF|RTF_PREFIX_RT); } if (ifp) { int flags; unsigned long now; #ifdef CONFIG_IPV6_PRIVACY struct inet6_ifaddr *ift; #endif u32 stored_lft; /* update lifetime (RFC2462 5.5.3 e) */ spin_lock(&ifp->lock); now = jiffies; if (ifp->valid_lft > (now - ifp->tstamp) / HZ) stored_lft = ifp->valid_lft - (now - ifp->tstamp) / HZ; else stored_lft = 0; if (!update_lft && stored_lft) { if (valid_lft > MIN_VALID_LIFETIME || valid_lft > stored_lft) update_lft = 1; else if (stored_lft <= MIN_VALID_LIFETIME) { /* valid_lft <= stored_lft is always true */ /* * RFC 4862 Section 5.5.3e: * "Note that the preferred lifetime of * the corresponding address is always * reset to the Preferred Lifetime in * the received Prefix Information * option, regardless of whether the * valid lifetime is also reset or * ignored." * * So if the preferred lifetime in * this advertisement is different * than what we have stored, but the * valid lifetime is invalid, just * reset prefered_lft. * * We must set the valid lifetime * to the stored lifetime since we'll * be updating the timestamp below, * else we'll set it back to the * minimum. */ if (prefered_lft != ifp->prefered_lft) { valid_lft = stored_lft; update_lft = 1; } } else { valid_lft = MIN_VALID_LIFETIME; if (valid_lft < prefered_lft) prefered_lft = valid_lft; update_lft = 1; } } if (update_lft) { ifp->valid_lft = valid_lft; ifp->prefered_lft = prefered_lft; ifp->tstamp = now; flags = ifp->flags; ifp->flags &= ~IFA_F_DEPRECATED; spin_unlock(&ifp->lock); if (!(flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ifp); } else spin_unlock(&ifp->lock); #ifdef CONFIG_IPV6_PRIVACY read_lock_bh(&in6_dev->lock); /* update all temporary addresses in the list */ list_for_each_entry(ift, &in6_dev->tempaddr_list, tmp_list) { int age, max_valid, max_prefered; if (ifp != ift->ifpub) continue; /* * RFC 4941 section 3.3: * If a received option will extend the lifetime * of a public address, the lifetimes of * temporary addresses should be extended, * subject to the overall constraint that no * temporary addresses should ever remain * "valid" or "preferred" for a time longer than * (TEMP_VALID_LIFETIME) or * (TEMP_PREFERRED_LIFETIME - DESYNC_FACTOR), * respectively. */ age = (now - ift->cstamp) / HZ; max_valid = in6_dev->cnf.temp_valid_lft - age; if (max_valid < 0) max_valid = 0; max_prefered = in6_dev->cnf.temp_prefered_lft - in6_dev->cnf.max_desync_factor - age; if (max_prefered < 0) max_prefered = 0; if (valid_lft > max_valid) valid_lft = max_valid; if (prefered_lft > max_prefered) prefered_lft = max_prefered; spin_lock(&ift->lock); flags = ift->flags; ift->valid_lft = valid_lft; ift->prefered_lft = prefered_lft; ift->tstamp = now; if (prefered_lft > 0) ift->flags &= ~IFA_F_DEPRECATED; spin_unlock(&ift->lock); if (!(flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ift); } if ((create || list_empty(&in6_dev->tempaddr_list)) && in6_dev->cnf.use_tempaddr > 0) { /* * When a new public address is created as * described in [ADDRCONF], also create a new * temporary address. Also create a temporary * address if it's enabled but no temporary * address currently exists. */ read_unlock_bh(&in6_dev->lock); ipv6_create_tempaddr(ifp, NULL); } else { read_unlock_bh(&in6_dev->lock); } #endif in6_ifa_put(ifp); addrconf_verify(0); } } inet6_prefix_notify(RTM_NEWPREFIX, in6_dev, pinfo); in6_dev_put(in6_dev); } /* * Set destination address. * Special case for SIT interfaces where we create a new "virtual" * device. */ int addrconf_set_dstaddr(struct net *net, void __user *arg) { struct in6_ifreq ireq; struct net_device *dev; int err = -EINVAL; rtnl_lock(); err = -EFAULT; if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq))) goto err_exit; dev = __dev_get_by_index(net, ireq.ifr6_ifindex); err = -ENODEV; if (dev == NULL) goto err_exit; #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) if (dev->type == ARPHRD_SIT) { const struct net_device_ops *ops = dev->netdev_ops; struct ifreq ifr; struct ip_tunnel_parm p; err = -EADDRNOTAVAIL; if (!(ipv6_addr_type(&ireq.ifr6_addr) & IPV6_ADDR_COMPATv4)) goto err_exit; memset(&p, 0, sizeof(p)); p.iph.daddr = ireq.ifr6_addr.s6_addr32[3]; p.iph.saddr = 0; p.iph.version = 4; p.iph.ihl = 5; p.iph.protocol = IPPROTO_IPV6; p.iph.ttl = 64; ifr.ifr_ifru.ifru_data = (__force void __user *)&p; if (ops->ndo_do_ioctl) { mm_segment_t oldfs = get_fs(); set_fs(KERNEL_DS); err = ops->ndo_do_ioctl(dev, &ifr, SIOCADDTUNNEL); set_fs(oldfs); } else err = -EOPNOTSUPP; if (err == 0) { err = -ENOBUFS; dev = __dev_get_by_name(net, p.name); if (!dev) goto err_exit; err = dev_open(dev); } } #endif err_exit: rtnl_unlock(); return err; } /* * Manual configuration of address on an interface */ static int inet6_addr_add(struct net *net, int ifindex, const struct in6_addr *pfx, unsigned int plen, __u8 ifa_flags, __u32 prefered_lft, __u32 valid_lft) { struct inet6_ifaddr *ifp; struct inet6_dev *idev; struct net_device *dev; int scope; u32 flags; clock_t expires; unsigned long timeout; ASSERT_RTNL(); if (plen > 128) return -EINVAL; /* check the lifetime */ if (!valid_lft || prefered_lft > valid_lft) return -EINVAL; dev = __dev_get_by_index(net, ifindex); if (!dev) return -ENODEV; idev = addrconf_add_dev(dev); if (IS_ERR(idev)) return PTR_ERR(idev); scope = ipv6_addr_scope(pfx); timeout = addrconf_timeout_fixup(valid_lft, HZ); if (addrconf_finite_timeout(timeout)) { expires = jiffies_to_clock_t(timeout * HZ); valid_lft = timeout; flags = RTF_EXPIRES; } else { expires = 0; flags = 0; ifa_flags |= IFA_F_PERMANENT; } timeout = addrconf_timeout_fixup(prefered_lft, HZ); if (addrconf_finite_timeout(timeout)) { if (timeout == 0) ifa_flags |= IFA_F_DEPRECATED; prefered_lft = timeout; } ifp = ipv6_add_addr(idev, pfx, plen, scope, ifa_flags); if (!IS_ERR(ifp)) { spin_lock_bh(&ifp->lock); ifp->valid_lft = valid_lft; ifp->prefered_lft = prefered_lft; ifp->tstamp = jiffies; spin_unlock_bh(&ifp->lock); addrconf_prefix_route(&ifp->addr, ifp->prefix_len, dev, expires, flags); /* * Note that section 3.1 of RFC 4429 indicates * that the Optimistic flag should not be set for * manually configured addresses */ addrconf_dad_start(ifp, 0); in6_ifa_put(ifp); addrconf_verify(0); return 0; } return PTR_ERR(ifp); } static int inet6_addr_del(struct net *net, int ifindex, const struct in6_addr *pfx, unsigned int plen) { struct inet6_ifaddr *ifp; struct inet6_dev *idev; struct net_device *dev; if (plen > 128) return -EINVAL; dev = __dev_get_by_index(net, ifindex); if (!dev) return -ENODEV; if ((idev = __in6_dev_get(dev)) == NULL) return -ENXIO; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) { if (ifp->prefix_len == plen && ipv6_addr_equal(pfx, &ifp->addr)) { in6_ifa_hold(ifp); read_unlock_bh(&idev->lock); ipv6_del_addr(ifp); /* If the last address is deleted administratively, disable IPv6 on this interface. */ if (list_empty(&idev->addr_list)) addrconf_ifdown(idev->dev, 1); return 0; } } read_unlock_bh(&idev->lock); return -EADDRNOTAVAIL; } int addrconf_add_ifaddr(struct net *net, void __user *arg) { struct in6_ifreq ireq; int err; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq))) return -EFAULT; rtnl_lock(); err = inet6_addr_add(net, ireq.ifr6_ifindex, &ireq.ifr6_addr, ireq.ifr6_prefixlen, IFA_F_PERMANENT, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME); rtnl_unlock(); return err; } int addrconf_del_ifaddr(struct net *net, void __user *arg) { struct in6_ifreq ireq; int err; if (!capable(CAP_NET_ADMIN)) return -EPERM; if (copy_from_user(&ireq, arg, sizeof(struct in6_ifreq))) return -EFAULT; rtnl_lock(); err = inet6_addr_del(net, ireq.ifr6_ifindex, &ireq.ifr6_addr, ireq.ifr6_prefixlen); rtnl_unlock(); return err; } static void add_addr(struct inet6_dev *idev, const struct in6_addr *addr, int plen, int scope) { struct inet6_ifaddr *ifp; ifp = ipv6_add_addr(idev, addr, plen, scope, IFA_F_PERMANENT); if (!IS_ERR(ifp)) { spin_lock_bh(&ifp->lock); ifp->flags &= ~IFA_F_TENTATIVE; spin_unlock_bh(&ifp->lock); ipv6_ifa_notify(RTM_NEWADDR, ifp); in6_ifa_put(ifp); } } #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) static void sit_add_v4_addrs(struct inet6_dev *idev) { struct in6_addr addr; struct net_device *dev; struct net *net = dev_net(idev->dev); int scope; ASSERT_RTNL(); memset(&addr, 0, sizeof(struct in6_addr)); memcpy(&addr.s6_addr32[3], idev->dev->dev_addr, 4); if (idev->dev->flags&IFF_POINTOPOINT) { addr.s6_addr32[0] = htonl(0xfe800000); scope = IFA_LINK; } else { scope = IPV6_ADDR_COMPATv4; } if (addr.s6_addr32[3]) { add_addr(idev, &addr, 128, scope); return; } for_each_netdev(net, dev) { struct in_device * in_dev = __in_dev_get_rtnl(dev); if (in_dev && (dev->flags & IFF_UP)) { struct in_ifaddr * ifa; int flag = scope; for (ifa = in_dev->ifa_list; ifa; ifa = ifa->ifa_next) { int plen; addr.s6_addr32[3] = ifa->ifa_local; if (ifa->ifa_scope == RT_SCOPE_LINK) continue; if (ifa->ifa_scope >= RT_SCOPE_HOST) { if (idev->dev->flags&IFF_POINTOPOINT) continue; flag |= IFA_HOST; } if (idev->dev->flags&IFF_POINTOPOINT) plen = 64; else plen = 96; add_addr(idev, &addr, plen, flag); } } } } #endif static void init_loopback(struct net_device *dev) { struct inet6_dev *idev; struct net_device *sp_dev; struct inet6_ifaddr *sp_ifa; struct rt6_info *sp_rt; /* ::1 */ ASSERT_RTNL(); if ((idev = ipv6_find_idev(dev)) == NULL) { printk(KERN_DEBUG "init loopback: add_dev failed\n"); return; } add_addr(idev, &in6addr_loopback, 128, IFA_HOST); /* Add routes to other interface's IPv6 addresses */ for_each_netdev(dev_net(dev), sp_dev) { if (!strcmp(sp_dev->name, dev->name)) continue; idev = __in6_dev_get(sp_dev); if (!idev) continue; read_lock_bh(&idev->lock); list_for_each_entry(sp_ifa, &idev->addr_list, if_list) { if (sp_ifa->flags & (IFA_F_DADFAILED | IFA_F_TENTATIVE)) continue; if (sp_ifa->rt) { /* This dst has been added to garbage list when * lo device down, release this obsolete dst and * reallocate a new router for ifa. */ if (sp_ifa->rt->dst.obsolete > 0) { dst_release(&sp_ifa->rt->dst); sp_ifa->rt = NULL; } else { continue; } } sp_rt = addrconf_dst_alloc(idev, &sp_ifa->addr, 0); /* Failure cases are ignored */ if (!IS_ERR(sp_rt)) { sp_ifa->rt = sp_rt; ip6_ins_rt(sp_rt); } } read_unlock_bh(&idev->lock); } } static void addrconf_add_linklocal(struct inet6_dev *idev, const struct in6_addr *addr) { struct inet6_ifaddr * ifp; u32 addr_flags = IFA_F_PERMANENT; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD if (idev->cnf.optimistic_dad && !dev_net(idev->dev)->ipv6.devconf_all->forwarding) addr_flags |= IFA_F_OPTIMISTIC; #endif ifp = ipv6_add_addr(idev, addr, 64, IFA_LINK, addr_flags); if (!IS_ERR(ifp)) { addrconf_prefix_route(&ifp->addr, ifp->prefix_len, idev->dev, 0, 0); addrconf_dad_start(ifp, 0); in6_ifa_put(ifp); } } static void addrconf_dev_config(struct net_device *dev) { struct in6_addr addr; struct inet6_dev * idev; ASSERT_RTNL(); if ((dev->type != ARPHRD_ETHER) && (dev->type != ARPHRD_FDDI) && (dev->type != ARPHRD_IEEE802_TR) && (dev->type != ARPHRD_ARCNET) && (dev->type != ARPHRD_RAWIP) && (dev->type != ARPHRD_INFINIBAND)) { /* Alas, we support only Ethernet autoconfiguration. */ return; } idev = addrconf_add_dev(dev); if (IS_ERR(idev)) return; memset(&addr, 0, sizeof(struct in6_addr)); addr.s6_addr32[0] = htonl(0xFE800000); if (ipv6_generate_eui64(addr.s6_addr + 8, dev) == 0) addrconf_add_linklocal(idev, &addr); } #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) static void addrconf_sit_config(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); /* * Configure the tunnel with one of our IPv4 * addresses... we should configure all of * our v4 addrs in the tunnel */ if ((idev = ipv6_find_idev(dev)) == NULL) { printk(KERN_DEBUG "init sit: add_dev failed\n"); return; } if (dev->priv_flags & IFF_ISATAP) { struct in6_addr addr; ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0); addrconf_prefix_route(&addr, 64, dev, 0, 0); if (!ipv6_generate_eui64(addr.s6_addr + 8, dev)) addrconf_add_linklocal(idev, &addr); return; } sit_add_v4_addrs(idev); if (dev->flags&IFF_POINTOPOINT) { addrconf_add_mroute(dev); addrconf_add_lroute(dev); } else sit_route_add(dev); } #endif #if defined(CONFIG_NET_IPGRE) || defined(CONFIG_NET_IPGRE_MODULE) static void addrconf_gre_config(struct net_device *dev) { struct inet6_dev *idev; struct in6_addr addr; pr_info("ipv6: addrconf_gre_config(%s)\n", dev->name); ASSERT_RTNL(); if ((idev = ipv6_find_idev(dev)) == NULL) { printk(KERN_DEBUG "init gre: add_dev failed\n"); return; } ipv6_addr_set(&addr, htonl(0xFE800000), 0, 0, 0); addrconf_prefix_route(&addr, 64, dev, 0, 0); if (!ipv6_generate_eui64(addr.s6_addr + 8, dev)) addrconf_add_linklocal(idev, &addr); } #endif static inline int ipv6_inherit_linklocal(struct inet6_dev *idev, struct net_device *link_dev) { struct in6_addr lladdr; if (!ipv6_get_lladdr(link_dev, &lladdr, IFA_F_TENTATIVE)) { addrconf_add_linklocal(idev, &lladdr); return 0; } return -1; } static void ip6_tnl_add_linklocal(struct inet6_dev *idev) { struct net_device *link_dev; struct net *net = dev_net(idev->dev); /* first try to inherit the link-local address from the link device */ if (idev->dev->iflink && (link_dev = __dev_get_by_index(net, idev->dev->iflink))) { if (!ipv6_inherit_linklocal(idev, link_dev)) return; } /* then try to inherit it from any device */ for_each_netdev(net, link_dev) { if (!ipv6_inherit_linklocal(idev, link_dev)) return; } printk(KERN_DEBUG "init ip6-ip6: add_linklocal failed\n"); } /* * Autoconfigure tunnel with a link-local address so routing protocols, * DHCPv6, MLD etc. can be run over the virtual link */ static void addrconf_ip6_tnl_config(struct net_device *dev) { struct inet6_dev *idev; ASSERT_RTNL(); idev = addrconf_add_dev(dev); if (IS_ERR(idev)) { printk(KERN_DEBUG "init ip6-ip6: add_dev failed\n"); return; } ip6_tnl_add_linklocal(idev); } static int addrconf_notify(struct notifier_block *this, unsigned long event, void * data) { struct net_device *dev = (struct net_device *) data; struct inet6_dev *idev = __in6_dev_get(dev); int run_pending = 0; int err; switch (event) { case NETDEV_REGISTER: if (!idev && dev->mtu >= IPV6_MIN_MTU) { idev = ipv6_add_dev(dev); if (!idev) return notifier_from_errno(-ENOMEM); } break; case NETDEV_UP: case NETDEV_CHANGE: if (dev->flags & IFF_SLAVE) break; if (event == NETDEV_UP) { if (!addrconf_qdisc_ok(dev)) { /* device is not ready yet. */ printk(KERN_INFO "ADDRCONF(NETDEV_UP): %s: " "link is not ready\n", dev->name); break; } if (!idev && dev->mtu >= IPV6_MIN_MTU) idev = ipv6_add_dev(dev); if (idev) { idev->if_flags |= IF_READY; run_pending = 1; } } else { if (!addrconf_qdisc_ok(dev)) { /* device is still not ready. */ break; } if (idev) { if (idev->if_flags & IF_READY) /* device is already configured. */ break; idev->if_flags |= IF_READY; } printk(KERN_INFO "ADDRCONF(NETDEV_CHANGE): %s: " "link becomes ready\n", dev->name); run_pending = 1; } switch (dev->type) { #if defined(CONFIG_IPV6_SIT) || defined(CONFIG_IPV6_SIT_MODULE) case ARPHRD_SIT: addrconf_sit_config(dev); break; #endif #if defined(CONFIG_NET_IPGRE) || defined(CONFIG_NET_IPGRE_MODULE) case ARPHRD_IPGRE: addrconf_gre_config(dev); break; #endif case ARPHRD_TUNNEL6: addrconf_ip6_tnl_config(dev); break; case ARPHRD_LOOPBACK: init_loopback(dev); break; default: addrconf_dev_config(dev); break; } if (idev) { if (run_pending) addrconf_dad_run(idev); /* * If the MTU changed during the interface down, * when the interface up, the changed MTU must be * reflected in the idev as well as routers. */ if (idev->cnf.mtu6 != dev->mtu && dev->mtu >= IPV6_MIN_MTU) { rt6_mtu_change(dev, dev->mtu); idev->cnf.mtu6 = dev->mtu; } idev->tstamp = jiffies; inet6_ifinfo_notify(RTM_NEWLINK, idev); /* * If the changed mtu during down is lower than * IPV6_MIN_MTU stop IPv6 on this interface. */ if (dev->mtu < IPV6_MIN_MTU) addrconf_ifdown(dev, 1); } break; case NETDEV_CHANGEMTU: if (idev && dev->mtu >= IPV6_MIN_MTU) { rt6_mtu_change(dev, dev->mtu); idev->cnf.mtu6 = dev->mtu; break; } if (!idev && dev->mtu >= IPV6_MIN_MTU) { idev = ipv6_add_dev(dev); if (idev) break; } /* * MTU falled under IPV6_MIN_MTU. * Stop IPv6 on this interface. */ case NETDEV_DOWN: case NETDEV_UNREGISTER: /* * Remove all addresses from this interface. */ addrconf_ifdown(dev, event != NETDEV_DOWN); break; case NETDEV_CHANGENAME: if (idev) { snmp6_unregister_dev(idev); addrconf_sysctl_unregister(idev); addrconf_sysctl_register(idev); err = snmp6_register_dev(idev); if (err) return notifier_from_errno(err); } break; case NETDEV_PRE_TYPE_CHANGE: case NETDEV_POST_TYPE_CHANGE: addrconf_type_change(dev, event); break; } return NOTIFY_OK; } /* * addrconf module should be notified of a device going up */ static struct notifier_block ipv6_dev_notf = { .notifier_call = addrconf_notify, }; static void addrconf_type_change(struct net_device *dev, unsigned long event) { struct inet6_dev *idev; ASSERT_RTNL(); idev = __in6_dev_get(dev); if (event == NETDEV_POST_TYPE_CHANGE) ipv6_mc_remap(idev); else if (event == NETDEV_PRE_TYPE_CHANGE) ipv6_mc_unmap(idev); } static int addrconf_ifdown(struct net_device *dev, int how) { struct net *net = dev_net(dev); struct inet6_dev *idev; struct inet6_ifaddr *ifa; int state, i; ASSERT_RTNL(); rt6_ifdown(net, dev); neigh_ifdown(&nd_tbl, dev); idev = __in6_dev_get(dev); if (idev == NULL) return -ENODEV; /* * Step 1: remove reference to ipv6 device from parent device. * Do not dev_put! */ if (how) { idev->dead = 1; /* protected by rtnl_lock */ RCU_INIT_POINTER(dev->ip6_ptr, NULL); /* Step 1.5: remove snmp6 entry */ snmp6_unregister_dev(idev); } /* Step 2: clear hash table */ spin_lock_bh(&addrconf_hash_lock); for (i = 0; i < IN6_ADDR_HSIZE; i++) { struct hlist_head *h = &inet6_addr_lst[i]; struct hlist_node *n; restart: hlist_for_each_entry_rcu(ifa, n, h, addr_lst) { if (ifa->idev == idev) { hlist_del_init_rcu(&ifa->addr_lst); addrconf_del_timer(ifa); goto restart; } } } write_lock_bh(&idev->lock); /* Step 2: clear flags for stateless addrconf */ if (!how) idev->if_flags &= ~(IF_RS_SENT|IF_RA_RCVD|IF_READY); #ifdef CONFIG_IPV6_PRIVACY if (how && del_timer(&idev->regen_timer)) in6_dev_put(idev); /* Step 3: clear tempaddr list */ while (!list_empty(&idev->tempaddr_list)) { ifa = list_first_entry(&idev->tempaddr_list, struct inet6_ifaddr, tmp_list); list_del(&ifa->tmp_list); write_unlock_bh(&idev->lock); spin_lock_bh(&ifa->lock); if (ifa->ifpub) { in6_ifa_put(ifa->ifpub); ifa->ifpub = NULL; } spin_unlock_bh(&ifa->lock); in6_ifa_put(ifa); write_lock_bh(&idev->lock); } #endif while (!list_empty(&idev->addr_list)) { ifa = list_first_entry(&idev->addr_list, struct inet6_ifaddr, if_list); addrconf_del_timer(ifa); list_del(&ifa->if_list); write_unlock_bh(&idev->lock); spin_lock_bh(&ifa->state_lock); state = ifa->state; ifa->state = INET6_IFADDR_STATE_DEAD; spin_unlock_bh(&ifa->state_lock); if (state != INET6_IFADDR_STATE_DEAD) { __ipv6_ifa_notify(RTM_DELADDR, ifa); atomic_notifier_call_chain(&inet6addr_chain, NETDEV_DOWN, ifa); } in6_ifa_put(ifa); write_lock_bh(&idev->lock); } write_unlock_bh(&idev->lock); spin_unlock_bh(&addrconf_hash_lock); /* Step 5: Discard anycast and multicast list */ if (how) { ipv6_ac_destroy_dev(idev); ipv6_mc_destroy_dev(idev); } else { ipv6_mc_down(idev); } idev->tstamp = jiffies; /* Last: Shot the device (if unregistered) */ if (how) { addrconf_sysctl_unregister(idev); neigh_parms_release(&nd_tbl, idev->nd_parms); neigh_ifdown(&nd_tbl, dev); in6_dev_put(idev); } return 0; } static void addrconf_rs_timer(unsigned long data) { struct inet6_ifaddr *ifp = (struct inet6_ifaddr *) data; struct inet6_dev *idev = ifp->idev; read_lock(&idev->lock); if (idev->dead || !(idev->if_flags & IF_READY)) goto out; if (idev->cnf.forwarding) goto out; /* Announcement received after solicitation was sent */ // if (idev->if_flags & IF_RA_RCVD){ #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] The RA msg had been received!", __func__); #endif goto out; } // spin_lock(&ifp->lock); if (ifp->probes++ < idev->cnf.rtr_solicits) { /* The wait after the last probe can be shorter */ addrconf_mod_timer(ifp, AC_RS, (ifp->probes == idev->cnf.rtr_solicits) ? idev->cnf.rtr_solicit_delay : idev->cnf.rtr_solicit_interval); spin_unlock(&ifp->lock); // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()][stage 2] rs is sent now!", __func__); #endif // ndisc_send_rs(idev->dev, &ifp->addr, &in6addr_linklocal_allrouters); } else { spin_unlock(&ifp->lock); /* * Note: we do not support deprecated "all on-link" * assumption any longer. */ printk(KERN_DEBUG "%s: no IPv6 routers present\n", idev->dev->name); } out: read_unlock(&idev->lock); in6_ifa_put(ifp); } /* * Duplicate Address Detection */ static void addrconf_dad_kick(struct inet6_ifaddr *ifp) { unsigned long rand_num; struct inet6_dev *idev = ifp->idev; if (ifp->flags & IFA_F_OPTIMISTIC) rand_num = 0; else rand_num = net_random() % (idev->cnf.rtr_solicit_delay ? : 1); ifp->probes = idev->cnf.dad_transmits; // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] dad_transmits == %d, ramd_num == %lu", __func__, idev->cnf.dad_transmits, rand_num); #endif // addrconf_mod_timer(ifp, AC_DAD, rand_num); } static void addrconf_dad_start(struct inet6_ifaddr *ifp, u32 flags) { struct inet6_dev *idev = ifp->idev; struct net_device *dev = idev->dev; // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER int ipv6AddrType = 0; //initializing const char InterfaceNameToApply[6]="rmnet"; char CurrentInterfaceName[6]={0};//initializing ipv6AddrType = ipv6_addr_type(&ifp->addr); printk(KERN_DEBUG "[LGE_DATA][%s()] dad_start! dev_name == %s", __func__, dev->name); printk(KERN_DEBUG "[LGE_DATA][%s()] ipv6_addr_type == %d", __func__, ipv6AddrType); strncpy(CurrentInterfaceName,dev->name,5); if(CurrentInterfaceName == NULL){ printk(KERN_DEBUG "[LGE_DATA] CurrentInterfaceName is NULL !\n"); return; } #endif // addrconf_join_solict(dev, &ifp->addr); net_srandom(ifp->addr.s6_addr32[3]); read_lock_bh(&idev->lock); spin_lock(&ifp->lock); if (ifp->state == INET6_IFADDR_STATE_DEAD) goto out; // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER if (((strcmp(InterfaceNameToApply, CurrentInterfaceName) == 0) && (ipv6AddrType == LGE_DATA_GLOBAL_SCOPE)) || (dev->flags&(IFF_NOARP|IFF_LOOPBACK) || idev->cnf.accept_dad < 1 || !(ifp->flags&IFA_F_TENTATIVE) || ifp->flags & IFA_F_NODAD)) #else // Kernel Original implemenatation START if (dev->flags&(IFF_NOARP|IFF_LOOPBACK) || idev->cnf.accept_dad < 1 || !(ifp->flags&IFA_F_TENTATIVE) || ifp->flags & IFA_F_NODAD) // Kernel Original implemenatation END #endif // { ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED); spin_unlock(&ifp->lock); read_unlock_bh(&idev->lock); // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] ipv6_addr_type == %d, Because the IPv6 type is Global Scope, we will immediately finish the DAD process for Global Scope.", __func__, ipv6AddrType); #endif // addrconf_dad_completed(ifp); return; } if (!(idev->if_flags & IF_READY)) { spin_unlock(&ifp->lock); read_unlock_bh(&idev->lock); /* * If the device is not ready: * - keep it tentative if it is a permanent address. * - otherwise, kill it. */ in6_ifa_hold(ifp); addrconf_dad_stop(ifp, 0); return; } /* * Optimistic nodes can start receiving * Frames right away */ if (ifp->flags & IFA_F_OPTIMISTIC) { ip6_ins_rt(ifp->rt); if (ipv6_use_optimistic_addr(idev)) { /* Because optimistic nodes can use this address, * notify listeners. If DAD fails, RTM_DELADDR is sent. */ ipv6_ifa_notify(RTM_NEWADDR, ifp); } } addrconf_dad_kick(ifp); out: spin_unlock(&ifp->lock); read_unlock_bh(&idev->lock); } static void addrconf_dad_timer(unsigned long data) { struct inet6_ifaddr *ifp = (struct inet6_ifaddr *) data; struct inet6_dev *idev = ifp->idev; struct in6_addr mcaddr; // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER struct net_device *dev = idev->dev; const char InterfaceNameToApply[6]="rmnet"; char CurrentInterfaceName[6]={0};//initializing #endif // if (!ifp->probes && addrconf_dad_end(ifp)) goto out; read_lock(&idev->lock); if (idev->dead || !(idev->if_flags & IF_READY)) { read_unlock(&idev->lock); goto out; } spin_lock(&ifp->lock); if (ifp->state == INET6_IFADDR_STATE_DEAD) { spin_unlock(&ifp->lock); read_unlock(&idev->lock); goto out; } if (ifp->probes == 0) { /* * DAD was successful */ // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] DAD was successful!", __func__); #endif // ifp->flags &= ~(IFA_F_TENTATIVE|IFA_F_OPTIMISTIC|IFA_F_DADFAILED); spin_unlock(&ifp->lock); read_unlock(&idev->lock); addrconf_dad_completed(ifp); goto out; } ifp->probes--; // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()], ifp->idev->nd_parms->retrans_time == %d", __func__, ifp->idev->nd_parms->retrans_time); printk(KERN_DEBUG "[LGE_DATA][%s()] dev_name == %s", __func__, dev->name); strncpy(CurrentInterfaceName,dev->name,5); if(CurrentInterfaceName == NULL){ spin_unlock(&ifp->lock); read_unlock(&idev->lock); printk(KERN_DEBUG "[LGE_DATA] CurrentInterfaceName is NULL !\n"); goto out; } printk(KERN_DEBUG "[LGE_DATA][%s()] CopyInterfaceName == %s, CurrentInterfaceName == %s", __func__, InterfaceNameToApply, CurrentInterfaceName); if(strcmp(InterfaceNameToApply, CurrentInterfaceName) == 0){//In case of rmnet, this patch will be applied bacause We should not impact to the Wi-Fi and so on. addrconf_mod_timer(ifp, AC_DAD, LGE_DATA_WAITING_TIME_FOR_DAD_OF_LGU); printk(KERN_DEBUG "[LGE_DATA][%s()] The waiting time for link-local DAD is set as [%d] milli-seconds in case of only rmnet interface !", __func__, LGE_DATA_WAITING_TIME_FOR_DAD_OF_LGU*10); }else{ //kernel original code -- START addrconf_mod_timer(ifp, AC_DAD, ifp->idev->nd_parms->retrans_time); //kernel original code -- END } #else addrconf_mod_timer(ifp, AC_DAD, ifp->idev->nd_parms->retrans_time); #endif // spin_unlock(&ifp->lock); read_unlock(&idev->lock); /* send a neighbour solicitation for our addr */ // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] send a neighbour solicitation for our addr !", __func__); #endif // addrconf_addr_solict_mult(&ifp->addr, &mcaddr); ndisc_send_ns(ifp->idev->dev, NULL, &ifp->addr, &mcaddr, &in6addr_any); out: in6_ifa_put(ifp); } static void addrconf_dad_completed(struct inet6_ifaddr *ifp) { struct net_device *dev = ifp->idev->dev; /* * Configure the address for reception. Now it is valid. */ ipv6_ifa_notify(RTM_NEWADDR, ifp); // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()] dad_is_completed!", __func__); #endif // /* If added prefix is link local and we are prepared to process router advertisements, start sending router solicitations. */ if (((ifp->idev->cnf.accept_ra == 1 && !ifp->idev->cnf.forwarding) || ifp->idev->cnf.accept_ra == 2) && ifp->idev->cnf.rtr_solicits > 0 && (dev->flags&IFF_LOOPBACK) == 0 && (ipv6_addr_type(&ifp->addr) & IPV6_ADDR_LINKLOCAL)) { /* * If a host as already performed a random delay * [...] as part of DAD [...] there is no need * to delay again before sending the first RS */ // #ifdef CONFIG_LGP_DATA_TCPIP_SLAAC_IPV6_ALLOCATION_BOOSTER printk(KERN_DEBUG "[LGE_DATA][%s()][stage 1] rs is sent now!", __func__); #endif // ndisc_send_rs(ifp->idev->dev, &ifp->addr, &in6addr_linklocal_allrouters); spin_lock_bh(&ifp->lock); ifp->probes = 1; ifp->idev->if_flags |= IF_RS_SENT; addrconf_mod_timer(ifp, AC_RS, ifp->idev->cnf.rtr_solicit_interval); spin_unlock_bh(&ifp->lock); } } static void addrconf_dad_run(struct inet6_dev *idev) { struct inet6_ifaddr *ifp; read_lock_bh(&idev->lock); list_for_each_entry(ifp, &idev->addr_list, if_list) { spin_lock(&ifp->lock); if (ifp->flags & IFA_F_TENTATIVE && ifp->state == INET6_IFADDR_STATE_DAD) addrconf_dad_kick(ifp); spin_unlock(&ifp->lock); } read_unlock_bh(&idev->lock); } #ifdef CONFIG_PROC_FS struct if6_iter_state { struct seq_net_private p; int bucket; int offset; }; static struct inet6_ifaddr *if6_get_first(struct seq_file *seq, loff_t pos) { struct inet6_ifaddr *ifa = NULL; struct if6_iter_state *state = seq->private; struct net *net = seq_file_net(seq); int p = 0; /* initial bucket if pos is 0 */ if (pos == 0) { state->bucket = 0; state->offset = 0; } for (; state->bucket < IN6_ADDR_HSIZE; ++state->bucket) { struct hlist_node *n; hlist_for_each_entry_rcu_bh(ifa, n, &inet6_addr_lst[state->bucket], addr_lst) { if (!net_eq(dev_net(ifa->idev->dev), net)) continue; /* sync with offset */ if (p < state->offset) { p++; continue; } state->offset++; return ifa; } /* prepare for next bucket */ state->offset = 0; p = 0; } return NULL; } static struct inet6_ifaddr *if6_get_next(struct seq_file *seq, struct inet6_ifaddr *ifa) { struct if6_iter_state *state = seq->private; struct net *net = seq_file_net(seq); struct hlist_node *n = &ifa->addr_lst; hlist_for_each_entry_continue_rcu_bh(ifa, n, addr_lst) { if (!net_eq(dev_net(ifa->idev->dev), net)) continue; state->offset++; return ifa; } while (++state->bucket < IN6_ADDR_HSIZE) { state->offset = 0; hlist_for_each_entry_rcu_bh(ifa, n, &inet6_addr_lst[state->bucket], addr_lst) { if (!net_eq(dev_net(ifa->idev->dev), net)) continue; state->offset++; return ifa; } } return NULL; } static void *if6_seq_start(struct seq_file *seq, loff_t *pos) __acquires(rcu_bh) { rcu_read_lock_bh(); return if6_get_first(seq, *pos); } static void *if6_seq_next(struct seq_file *seq, void *v, loff_t *pos) { struct inet6_ifaddr *ifa; ifa = if6_get_next(seq, v); ++*pos; return ifa; } static void if6_seq_stop(struct seq_file *seq, void *v) __releases(rcu_bh) { rcu_read_unlock_bh(); } static int if6_seq_show(struct seq_file *seq, void *v) { struct inet6_ifaddr *ifp = (struct inet6_ifaddr *)v; seq_printf(seq, "%pi6 %02x %02x %02x %02x %8s\n", &ifp->addr, ifp->idev->dev->ifindex, ifp->prefix_len, ifp->scope, ifp->flags, ifp->idev->dev->name); return 0; } static const struct seq_operations if6_seq_ops = { .start = if6_seq_start, .next = if6_seq_next, .show = if6_seq_show, .stop = if6_seq_stop, }; static int if6_seq_open(struct inode *inode, struct file *file) { return seq_open_net(inode, file, &if6_seq_ops, sizeof(struct if6_iter_state)); } static const struct file_operations if6_fops = { .owner = THIS_MODULE, .open = if6_seq_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release_net, }; static int __net_init if6_proc_net_init(struct net *net) { if (!proc_net_fops_create(net, "if_inet6", S_IRUGO, &if6_fops)) return -ENOMEM; return 0; } static void __net_exit if6_proc_net_exit(struct net *net) { proc_net_remove(net, "if_inet6"); } static struct pernet_operations if6_proc_net_ops = { .init = if6_proc_net_init, .exit = if6_proc_net_exit, }; int __init if6_proc_init(void) { return register_pernet_subsys(&if6_proc_net_ops); } void if6_proc_exit(void) { unregister_pernet_subsys(&if6_proc_net_ops); } #endif /* CONFIG_PROC_FS */ #if defined(CONFIG_IPV6_MIP6) || defined(CONFIG_IPV6_MIP6_MODULE) /* Check if address is a home address configured on any interface. */ int ipv6_chk_home_addr(struct net *net, const struct in6_addr *addr) { int ret = 0; struct inet6_ifaddr *ifp = NULL; struct hlist_node *n; unsigned int hash = ipv6_addr_hash(addr); rcu_read_lock_bh(); hlist_for_each_entry_rcu_bh(ifp, n, &inet6_addr_lst[hash], addr_lst) { if (!net_eq(dev_net(ifp->idev->dev), net)) continue; if (ipv6_addr_equal(&ifp->addr, addr) && (ifp->flags & IFA_F_HOMEADDRESS)) { ret = 1; break; } } rcu_read_unlock_bh(); return ret; } #endif /* * Periodic address status verification */ static void addrconf_verify(unsigned long foo) { unsigned long now, next, next_sec, next_sched; struct inet6_ifaddr *ifp; struct hlist_node *node; int i; rcu_read_lock_bh(); spin_lock(&addrconf_verify_lock); now = jiffies; next = round_jiffies_up(now + ADDR_CHECK_FREQUENCY); del_timer(&addr_chk_timer); for (i = 0; i < IN6_ADDR_HSIZE; i++) { restart: hlist_for_each_entry_rcu_bh(ifp, node, &inet6_addr_lst[i], addr_lst) { unsigned long age; if (ifp->flags & IFA_F_PERMANENT) continue; spin_lock(&ifp->lock); /* We try to batch several events at once. */ age = (now - ifp->tstamp + ADDRCONF_TIMER_FUZZ_MINUS) / HZ; if (ifp->valid_lft != INFINITY_LIFE_TIME && age >= ifp->valid_lft) { spin_unlock(&ifp->lock); in6_ifa_hold(ifp); ipv6_del_addr(ifp); goto restart; } else if (ifp->prefered_lft == INFINITY_LIFE_TIME) { spin_unlock(&ifp->lock); continue; } else if (age >= ifp->prefered_lft) { /* jiffies - ifp->tstamp > age >= ifp->prefered_lft */ int deprecate = 0; if (!(ifp->flags&IFA_F_DEPRECATED)) { deprecate = 1; ifp->flags |= IFA_F_DEPRECATED; } if (time_before(ifp->tstamp + ifp->valid_lft * HZ, next)) next = ifp->tstamp + ifp->valid_lft * HZ; spin_unlock(&ifp->lock); if (deprecate) { in6_ifa_hold(ifp); ipv6_ifa_notify(0, ifp); in6_ifa_put(ifp); goto restart; } #ifdef CONFIG_IPV6_PRIVACY } else if ((ifp->flags&IFA_F_TEMPORARY) && !(ifp->flags&IFA_F_TENTATIVE)) { unsigned long regen_advance = ifp->idev->cnf.regen_max_retry * ifp->idev->cnf.dad_transmits * ifp->idev->nd_parms->retrans_time / HZ; if (age >= ifp->prefered_lft - regen_advance) { struct inet6_ifaddr *ifpub = ifp->ifpub; if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ; if (!ifp->regen_count && ifpub) { ifp->regen_count++; in6_ifa_hold(ifp); in6_ifa_hold(ifpub); spin_unlock(&ifp->lock); spin_lock(&ifpub->lock); ifpub->regen_count = 0; spin_unlock(&ifpub->lock); ipv6_create_tempaddr(ifpub, ifp); in6_ifa_put(ifpub); in6_ifa_put(ifp); goto restart; } } else if (time_before(ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ - regen_advance * HZ; spin_unlock(&ifp->lock); #endif } else { /* ifp->prefered_lft <= ifp->valid_lft */ if (time_before(ifp->tstamp + ifp->prefered_lft * HZ, next)) next = ifp->tstamp + ifp->prefered_lft * HZ; spin_unlock(&ifp->lock); } } } next_sec = round_jiffies_up(next); next_sched = next; /* If rounded timeout is accurate enough, accept it. */ if (time_before(next_sec, next + ADDRCONF_TIMER_FUZZ)) next_sched = next_sec; /* And minimum interval is ADDRCONF_TIMER_FUZZ_MAX. */ if (time_before(next_sched, jiffies + ADDRCONF_TIMER_FUZZ_MAX)) next_sched = jiffies + ADDRCONF_TIMER_FUZZ_MAX; pr_debug("now = %lu, schedule = %lu, rounded schedule = %lu => %lu\n", now, next, next_sec, next_sched); addr_chk_timer.expires = next_sched; add_timer(&addr_chk_timer); spin_unlock(&addrconf_verify_lock); rcu_read_unlock_bh(); } static struct in6_addr *extract_addr(struct nlattr *addr, struct nlattr *local) { struct in6_addr *pfx = NULL; if (addr) pfx = nla_data(addr); if (local) { if (pfx && nla_memcmp(local, pfx, sizeof(*pfx))) pfx = NULL; else pfx = nla_data(local); } return pfx; } static const struct nla_policy ifa_ipv6_policy[IFA_MAX+1] = { [IFA_ADDRESS] = { .len = sizeof(struct in6_addr) }, [IFA_LOCAL] = { .len = sizeof(struct in6_addr) }, [IFA_CACHEINFO] = { .len = sizeof(struct ifa_cacheinfo) }, }; static int inet6_rtm_deladdr(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg) { struct net *net = sock_net(skb->sk); struct ifaddrmsg *ifm; struct nlattr *tb[IFA_MAX+1]; struct in6_addr *pfx; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy); if (err < 0) return err; ifm = nlmsg_data(nlh); pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL]); if (pfx == NULL) return -EINVAL; return inet6_addr_del(net, ifm->ifa_index, pfx, ifm->ifa_prefixlen); } static int inet6_addr_modify(struct inet6_ifaddr *ifp, u8 ifa_flags, u32 prefered_lft, u32 valid_lft) { u32 flags; clock_t expires; unsigned long timeout; if (!valid_lft || (prefered_lft > valid_lft)) return -EINVAL; timeout = addrconf_timeout_fixup(valid_lft, HZ); if (addrconf_finite_timeout(timeout)) { expires = jiffies_to_clock_t(timeout * HZ); valid_lft = timeout; flags = RTF_EXPIRES; } else { expires = 0; flags = 0; ifa_flags |= IFA_F_PERMANENT; } timeout = addrconf_timeout_fixup(prefered_lft, HZ); if (addrconf_finite_timeout(timeout)) { if (timeout == 0) ifa_flags |= IFA_F_DEPRECATED; prefered_lft = timeout; } spin_lock_bh(&ifp->lock); ifp->flags = (ifp->flags & ~(IFA_F_DEPRECATED | IFA_F_PERMANENT | IFA_F_NODAD | IFA_F_HOMEADDRESS)) | ifa_flags; ifp->tstamp = jiffies; ifp->valid_lft = valid_lft; ifp->prefered_lft = prefered_lft; spin_unlock_bh(&ifp->lock); if (!(ifp->flags&IFA_F_TENTATIVE)) ipv6_ifa_notify(0, ifp); addrconf_prefix_route(&ifp->addr, ifp->prefix_len, ifp->idev->dev, expires, flags); addrconf_verify(0); return 0; } static int inet6_rtm_newaddr(struct sk_buff *skb, struct nlmsghdr *nlh, void *arg) { struct net *net = sock_net(skb->sk); struct ifaddrmsg *ifm; struct nlattr *tb[IFA_MAX+1]; struct in6_addr *pfx; struct inet6_ifaddr *ifa; struct net_device *dev; u32 valid_lft = INFINITY_LIFE_TIME, preferred_lft = INFINITY_LIFE_TIME; u8 ifa_flags; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy); if (err < 0) return err; ifm = nlmsg_data(nlh); pfx = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL]); if (pfx == NULL) return -EINVAL; if (tb[IFA_CACHEINFO]) { struct ifa_cacheinfo *ci; ci = nla_data(tb[IFA_CACHEINFO]); valid_lft = ci->ifa_valid; preferred_lft = ci->ifa_prefered; } else { preferred_lft = INFINITY_LIFE_TIME; valid_lft = INFINITY_LIFE_TIME; } dev = __dev_get_by_index(net, ifm->ifa_index); if (dev == NULL) return -ENODEV; /* We ignore other flags so far. */ ifa_flags = ifm->ifa_flags & (IFA_F_NODAD | IFA_F_HOMEADDRESS); ifa = ipv6_get_ifaddr(net, pfx, dev, 1); if (ifa == NULL) { /* * It would be best to check for !NLM_F_CREATE here but * userspace alreay relies on not having to provide this. */ return inet6_addr_add(net, ifm->ifa_index, pfx, ifm->ifa_prefixlen, ifa_flags, preferred_lft, valid_lft); } if (nlh->nlmsg_flags & NLM_F_EXCL || !(nlh->nlmsg_flags & NLM_F_REPLACE)) err = -EEXIST; else err = inet6_addr_modify(ifa, ifa_flags, preferred_lft, valid_lft); in6_ifa_put(ifa); return err; } static void put_ifaddrmsg(struct nlmsghdr *nlh, u8 prefixlen, u8 flags, u8 scope, int ifindex) { struct ifaddrmsg *ifm; ifm = nlmsg_data(nlh); ifm->ifa_family = AF_INET6; ifm->ifa_prefixlen = prefixlen; ifm->ifa_flags = flags; ifm->ifa_scope = scope; ifm->ifa_index = ifindex; } static int put_cacheinfo(struct sk_buff *skb, unsigned long cstamp, unsigned long tstamp, u32 preferred, u32 valid) { struct ifa_cacheinfo ci; ci.cstamp = cstamp_delta(cstamp); ci.tstamp = cstamp_delta(tstamp); ci.ifa_prefered = preferred; ci.ifa_valid = valid; return nla_put(skb, IFA_CACHEINFO, sizeof(ci), &ci); } static inline int rt_scope(int ifa_scope) { if (ifa_scope & IFA_HOST) return RT_SCOPE_HOST; else if (ifa_scope & IFA_LINK) return RT_SCOPE_LINK; else if (ifa_scope & IFA_SITE) return RT_SCOPE_SITE; else return RT_SCOPE_UNIVERSE; } static inline int inet6_ifaddr_msgsize(void) { return NLMSG_ALIGN(sizeof(struct ifaddrmsg)) + nla_total_size(16) /* IFA_ADDRESS */ + nla_total_size(sizeof(struct ifa_cacheinfo)); } static int inet6_fill_ifaddr(struct sk_buff *skb, struct inet6_ifaddr *ifa, u32 pid, u32 seq, int event, unsigned int flags) { struct nlmsghdr *nlh; u32 preferred, valid; nlh = nlmsg_put(skb, pid, seq, event, sizeof(struct ifaddrmsg), flags); if (nlh == NULL) return -EMSGSIZE; put_ifaddrmsg(nlh, ifa->prefix_len, ifa->flags, rt_scope(ifa->scope), ifa->idev->dev->ifindex); if (!(ifa->flags&IFA_F_PERMANENT)) { preferred = ifa->prefered_lft; valid = ifa->valid_lft; if (preferred != INFINITY_LIFE_TIME) { long tval = (jiffies - ifa->tstamp)/HZ; if (preferred > tval) preferred -= tval; else preferred = 0; if (valid != INFINITY_LIFE_TIME) { if (valid > tval) valid -= tval; else valid = 0; } } } else { preferred = INFINITY_LIFE_TIME; valid = INFINITY_LIFE_TIME; } if (nla_put(skb, IFA_ADDRESS, 16, &ifa->addr) < 0 || put_cacheinfo(skb, ifa->cstamp, ifa->tstamp, preferred, valid) < 0) { nlmsg_cancel(skb, nlh); return -EMSGSIZE; } return nlmsg_end(skb, nlh); } static int inet6_fill_ifmcaddr(struct sk_buff *skb, struct ifmcaddr6 *ifmca, u32 pid, u32 seq, int event, u16 flags) { struct nlmsghdr *nlh; u8 scope = RT_SCOPE_UNIVERSE; int ifindex = ifmca->idev->dev->ifindex; if (ipv6_addr_scope(&ifmca->mca_addr) & IFA_SITE) scope = RT_SCOPE_SITE; nlh = nlmsg_put(skb, pid, seq, event, sizeof(struct ifaddrmsg), flags); if (nlh == NULL) return -EMSGSIZE; put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex); if (nla_put(skb, IFA_MULTICAST, 16, &ifmca->mca_addr) < 0 || put_cacheinfo(skb, ifmca->mca_cstamp, ifmca->mca_tstamp, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) { nlmsg_cancel(skb, nlh); return -EMSGSIZE; } return nlmsg_end(skb, nlh); } static int inet6_fill_ifacaddr(struct sk_buff *skb, struct ifacaddr6 *ifaca, u32 pid, u32 seq, int event, unsigned int flags) { struct nlmsghdr *nlh; u8 scope = RT_SCOPE_UNIVERSE; int ifindex = ifaca->aca_idev->dev->ifindex; if (ipv6_addr_scope(&ifaca->aca_addr) & IFA_SITE) scope = RT_SCOPE_SITE; nlh = nlmsg_put(skb, pid, seq, event, sizeof(struct ifaddrmsg), flags); if (nlh == NULL) return -EMSGSIZE; put_ifaddrmsg(nlh, 128, IFA_F_PERMANENT, scope, ifindex); if (nla_put(skb, IFA_ANYCAST, 16, &ifaca->aca_addr) < 0 || put_cacheinfo(skb, ifaca->aca_cstamp, ifaca->aca_tstamp, INFINITY_LIFE_TIME, INFINITY_LIFE_TIME) < 0) { nlmsg_cancel(skb, nlh); return -EMSGSIZE; } return nlmsg_end(skb, nlh); } enum addr_type_t { UNICAST_ADDR, MULTICAST_ADDR, ANYCAST_ADDR, }; /* called with rcu_read_lock() */ static int in6_dump_addrs(struct inet6_dev *idev, struct sk_buff *skb, struct netlink_callback *cb, enum addr_type_t type, int s_ip_idx, int *p_ip_idx) { struct ifmcaddr6 *ifmca; struct ifacaddr6 *ifaca; int err = 1; int ip_idx = *p_ip_idx; read_lock_bh(&idev->lock); switch (type) { case UNICAST_ADDR: { struct inet6_ifaddr *ifa; /* unicast address incl. temp addr */ list_for_each_entry(ifa, &idev->addr_list, if_list) { if (++ip_idx < s_ip_idx) continue; err = inet6_fill_ifaddr(skb, ifa, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, RTM_NEWADDR, NLM_F_MULTI); if (err <= 0) break; } break; } case MULTICAST_ADDR: /* multicast address */ for (ifmca = idev->mc_list; ifmca; ifmca = ifmca->next, ip_idx++) { if (ip_idx < s_ip_idx) continue; err = inet6_fill_ifmcaddr(skb, ifmca, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, RTM_GETMULTICAST, NLM_F_MULTI); if (err <= 0) break; } break; case ANYCAST_ADDR: /* anycast address */ for (ifaca = idev->ac_list; ifaca; ifaca = ifaca->aca_next, ip_idx++) { if (ip_idx < s_ip_idx) continue; err = inet6_fill_ifacaddr(skb, ifaca, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, RTM_GETANYCAST, NLM_F_MULTI); if (err <= 0) break; } break; default: break; } read_unlock_bh(&idev->lock); *p_ip_idx = ip_idx; return err; } static int inet6_dump_addr(struct sk_buff *skb, struct netlink_callback *cb, enum addr_type_t type) { struct net *net = sock_net(skb->sk); int h, s_h; int idx, ip_idx; int s_idx, s_ip_idx; struct net_device *dev; struct inet6_dev *idev; struct hlist_head *head; struct hlist_node *node; s_h = cb->args[0]; s_idx = idx = cb->args[1]; s_ip_idx = ip_idx = cb->args[2]; rcu_read_lock(); for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) { idx = 0; head = &net->dev_index_head[h]; hlist_for_each_entry_rcu(dev, node, head, index_hlist) { if (idx < s_idx) goto cont; if (h > s_h || idx > s_idx) s_ip_idx = 0; ip_idx = 0; idev = __in6_dev_get(dev); if (!idev) goto cont; if (in6_dump_addrs(idev, skb, cb, type, s_ip_idx, &ip_idx) <= 0) goto done; cont: idx++; } } done: rcu_read_unlock(); cb->args[0] = h; cb->args[1] = idx; cb->args[2] = ip_idx; return skb->len; } static int inet6_dump_ifaddr(struct sk_buff *skb, struct netlink_callback *cb) { enum addr_type_t type = UNICAST_ADDR; return inet6_dump_addr(skb, cb, type); } static int inet6_dump_ifmcaddr(struct sk_buff *skb, struct netlink_callback *cb) { enum addr_type_t type = MULTICAST_ADDR; return inet6_dump_addr(skb, cb, type); } static int inet6_dump_ifacaddr(struct sk_buff *skb, struct netlink_callback *cb) { enum addr_type_t type = ANYCAST_ADDR; return inet6_dump_addr(skb, cb, type); } static int inet6_rtm_getaddr(struct sk_buff *in_skb, struct nlmsghdr* nlh, void *arg) { struct net *net = sock_net(in_skb->sk); struct ifaddrmsg *ifm; struct nlattr *tb[IFA_MAX+1]; struct in6_addr *addr = NULL; struct net_device *dev = NULL; struct inet6_ifaddr *ifa; struct sk_buff *skb; int err; err = nlmsg_parse(nlh, sizeof(*ifm), tb, IFA_MAX, ifa_ipv6_policy); if (err < 0) goto errout; addr = extract_addr(tb[IFA_ADDRESS], tb[IFA_LOCAL]); if (addr == NULL) { err = -EINVAL; goto errout; } ifm = nlmsg_data(nlh); if (ifm->ifa_index) dev = __dev_get_by_index(net, ifm->ifa_index); ifa = ipv6_get_ifaddr(net, addr, dev, 1); if (!ifa) { err = -EADDRNOTAVAIL; goto errout; } skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_KERNEL); if (!skb) { err = -ENOBUFS; goto errout_ifa; } err = inet6_fill_ifaddr(skb, ifa, NETLINK_CB(in_skb).pid, nlh->nlmsg_seq, RTM_NEWADDR, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout_ifa; } err = rtnl_unicast(skb, net, NETLINK_CB(in_skb).pid); errout_ifa: in6_ifa_put(ifa); errout: return err; } static void inet6_ifa_notify(int event, struct inet6_ifaddr *ifa) { struct sk_buff *skb; struct net *net = dev_net(ifa->idev->dev); int err = -ENOBUFS; skb = nlmsg_new(inet6_ifaddr_msgsize(), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_fill_ifaddr(skb, ifa, 0, 0, event, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_ifaddr_msgsize() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFADDR, NULL, GFP_ATOMIC); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_IFADDR, err); } static inline void ipv6_store_devconf(struct ipv6_devconf *cnf, __s32 *array, int bytes) { BUG_ON(bytes < (DEVCONF_MAX * 4)); memset(array, 0, bytes); array[DEVCONF_FORWARDING] = cnf->forwarding; array[DEVCONF_HOPLIMIT] = cnf->hop_limit; array[DEVCONF_MTU6] = cnf->mtu6; array[DEVCONF_ACCEPT_RA] = cnf->accept_ra; array[DEVCONF_ACCEPT_REDIRECTS] = cnf->accept_redirects; array[DEVCONF_AUTOCONF] = cnf->autoconf; array[DEVCONF_DAD_TRANSMITS] = cnf->dad_transmits; array[DEVCONF_RTR_SOLICITS] = cnf->rtr_solicits; array[DEVCONF_RTR_SOLICIT_INTERVAL] = jiffies_to_msecs(cnf->rtr_solicit_interval); array[DEVCONF_RTR_SOLICIT_DELAY] = jiffies_to_msecs(cnf->rtr_solicit_delay); array[DEVCONF_FORCE_MLD_VERSION] = cnf->force_mld_version; #ifdef CONFIG_IPV6_PRIVACY array[DEVCONF_USE_TEMPADDR] = cnf->use_tempaddr; array[DEVCONF_TEMP_VALID_LFT] = cnf->temp_valid_lft; array[DEVCONF_TEMP_PREFERED_LFT] = cnf->temp_prefered_lft; array[DEVCONF_REGEN_MAX_RETRY] = cnf->regen_max_retry; array[DEVCONF_MAX_DESYNC_FACTOR] = cnf->max_desync_factor; #endif array[DEVCONF_MAX_ADDRESSES] = cnf->max_addresses; array[DEVCONF_ACCEPT_RA_DEFRTR] = cnf->accept_ra_defrtr; array[DEVCONF_ACCEPT_RA_PINFO] = cnf->accept_ra_pinfo; #ifdef CONFIG_IPV6_ROUTER_PREF array[DEVCONF_ACCEPT_RA_RTR_PREF] = cnf->accept_ra_rtr_pref; array[DEVCONF_RTR_PROBE_INTERVAL] = jiffies_to_msecs(cnf->rtr_probe_interval); #ifdef CONFIG_IPV6_ROUTE_INFO array[DEVCONF_ACCEPT_RA_RT_INFO_MAX_PLEN] = cnf->accept_ra_rt_info_max_plen; #endif #endif array[DEVCONF_ACCEPT_RA_RT_TABLE] = cnf->accept_ra_rt_table; array[DEVCONF_PROXY_NDP] = cnf->proxy_ndp; array[DEVCONF_ACCEPT_SOURCE_ROUTE] = cnf->accept_source_route; #ifdef CONFIG_IPV6_OPTIMISTIC_DAD array[DEVCONF_OPTIMISTIC_DAD] = cnf->optimistic_dad; array[DEVCONF_USE_OPTIMISTIC] = cnf->use_optimistic; #endif #ifdef CONFIG_IPV6_MROUTE array[DEVCONF_MC_FORWARDING] = cnf->mc_forwarding; #endif array[DEVCONF_DISABLE_IPV6] = cnf->disable_ipv6; array[DEVCONF_ACCEPT_DAD] = cnf->accept_dad; array[DEVCONF_FORCE_TLLAO] = cnf->force_tllao; #ifdef CONFIG_LGE_DHCPV6_WIFI array[DEVCONF_RA_INFO_FLAG] = cnf->ra_info_flag; #endif } static inline size_t inet6_ifla6_size(void) { return nla_total_size(4) /* IFLA_INET6_FLAGS */ + nla_total_size(sizeof(struct ifla_cacheinfo)) + nla_total_size(DEVCONF_MAX * 4) /* IFLA_INET6_CONF */ + nla_total_size(IPSTATS_MIB_MAX * 8) /* IFLA_INET6_STATS */ + nla_total_size(ICMP6_MIB_MAX * 8); /* IFLA_INET6_ICMP6STATS */ } static inline size_t inet6_if_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct ifinfomsg)) + nla_total_size(IFNAMSIZ) /* IFLA_IFNAME */ + nla_total_size(MAX_ADDR_LEN) /* IFLA_ADDRESS */ + nla_total_size(4) /* IFLA_MTU */ + nla_total_size(4) /* IFLA_LINK */ + nla_total_size(inet6_ifla6_size()); /* IFLA_PROTINFO */ } static inline void __snmp6_fill_statsdev(u64 *stats, atomic_long_t *mib, int items, int bytes) { int i; int pad = bytes - sizeof(u64) * items; BUG_ON(pad < 0); /* Use put_unaligned() because stats may not be aligned for u64. */ put_unaligned(items, &stats[0]); for (i = 1; i < items; i++) put_unaligned(atomic_long_read(&mib[i]), &stats[i]); memset(&stats[items], 0, pad); } static inline void __snmp6_fill_stats64(u64 *stats, void __percpu **mib, int items, int bytes, size_t syncpoff) { int i; int pad = bytes - sizeof(u64) * items; BUG_ON(pad < 0); /* Use put_unaligned() because stats may not be aligned for u64. */ put_unaligned(items, &stats[0]); for (i = 1; i < items; i++) put_unaligned(snmp_fold_field64(mib, i, syncpoff), &stats[i]); memset(&stats[items], 0, pad); } static void snmp6_fill_stats(u64 *stats, struct inet6_dev *idev, int attrtype, int bytes) { switch (attrtype) { case IFLA_INET6_STATS: __snmp6_fill_stats64(stats, (void __percpu **)idev->stats.ipv6, IPSTATS_MIB_MAX, bytes, offsetof(struct ipstats_mib, syncp)); break; case IFLA_INET6_ICMP6STATS: __snmp6_fill_statsdev(stats, idev->stats.icmpv6dev->mibs, ICMP6_MIB_MAX, bytes); break; } } static int inet6_fill_ifla6_attrs(struct sk_buff *skb, struct inet6_dev *idev) { struct nlattr *nla; struct ifla_cacheinfo ci; NLA_PUT_U32(skb, IFLA_INET6_FLAGS, idev->if_flags); ci.max_reasm_len = IPV6_MAXPLEN; ci.tstamp = cstamp_delta(idev->tstamp); ci.reachable_time = jiffies_to_msecs(idev->nd_parms->reachable_time); ci.retrans_time = jiffies_to_msecs(idev->nd_parms->retrans_time); NLA_PUT(skb, IFLA_INET6_CACHEINFO, sizeof(ci), &ci); nla = nla_reserve(skb, IFLA_INET6_CONF, DEVCONF_MAX * sizeof(s32)); if (nla == NULL) goto nla_put_failure; ipv6_store_devconf(&idev->cnf, nla_data(nla), nla_len(nla)); /* XXX - MC not implemented */ nla = nla_reserve(skb, IFLA_INET6_STATS, IPSTATS_MIB_MAX * sizeof(u64)); if (nla == NULL) goto nla_put_failure; snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_STATS, nla_len(nla)); nla = nla_reserve(skb, IFLA_INET6_ICMP6STATS, ICMP6_MIB_MAX * sizeof(u64)); if (nla == NULL) goto nla_put_failure; snmp6_fill_stats(nla_data(nla), idev, IFLA_INET6_ICMP6STATS, nla_len(nla)); return 0; nla_put_failure: return -EMSGSIZE; } static size_t inet6_get_link_af_size(const struct net_device *dev) { if (!__in6_dev_get(dev)) return 0; return inet6_ifla6_size(); } static int inet6_fill_link_af(struct sk_buff *skb, const struct net_device *dev) { struct inet6_dev *idev = __in6_dev_get(dev); if (!idev) return -ENODATA; if (inet6_fill_ifla6_attrs(skb, idev) < 0) return -EMSGSIZE; return 0; } static int inet6_fill_ifinfo(struct sk_buff *skb, struct inet6_dev *idev, u32 pid, u32 seq, int event, unsigned int flags) { struct net_device *dev = idev->dev; struct ifinfomsg *hdr; struct nlmsghdr *nlh; void *protoinfo; nlh = nlmsg_put(skb, pid, seq, event, sizeof(*hdr), flags); if (nlh == NULL) return -EMSGSIZE; hdr = nlmsg_data(nlh); hdr->ifi_family = AF_INET6; hdr->__ifi_pad = 0; hdr->ifi_type = dev->type; hdr->ifi_index = dev->ifindex; hdr->ifi_flags = dev_get_flags(dev); hdr->ifi_change = 0; NLA_PUT_STRING(skb, IFLA_IFNAME, dev->name); if (dev->addr_len) NLA_PUT(skb, IFLA_ADDRESS, dev->addr_len, dev->dev_addr); NLA_PUT_U32(skb, IFLA_MTU, dev->mtu); if (dev->ifindex != dev->iflink) NLA_PUT_U32(skb, IFLA_LINK, dev->iflink); protoinfo = nla_nest_start(skb, IFLA_PROTINFO); if (protoinfo == NULL) goto nla_put_failure; if (inet6_fill_ifla6_attrs(skb, idev) < 0) goto nla_put_failure; nla_nest_end(skb, protoinfo); return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static int inet6_dump_ifinfo(struct sk_buff *skb, struct netlink_callback *cb) { struct net *net = sock_net(skb->sk); int h, s_h; int idx = 0, s_idx; struct net_device *dev; struct inet6_dev *idev; struct hlist_head *head; struct hlist_node *node; s_h = cb->args[0]; s_idx = cb->args[1]; rcu_read_lock(); for (h = s_h; h < NETDEV_HASHENTRIES; h++, s_idx = 0) { idx = 0; head = &net->dev_index_head[h]; hlist_for_each_entry_rcu(dev, node, head, index_hlist) { if (idx < s_idx) goto cont; idev = __in6_dev_get(dev); if (!idev) goto cont; if (inet6_fill_ifinfo(skb, idev, NETLINK_CB(cb->skb).pid, cb->nlh->nlmsg_seq, RTM_NEWLINK, NLM_F_MULTI) <= 0) goto out; cont: idx++; } } out: rcu_read_unlock(); cb->args[1] = idx; cb->args[0] = h; return skb->len; } void inet6_ifinfo_notify(int event, struct inet6_dev *idev) { struct sk_buff *skb; struct net *net = dev_net(idev->dev); int err = -ENOBUFS; skb = nlmsg_new(inet6_if_nlmsg_size(), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_fill_ifinfo(skb, idev, 0, 0, event, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_if_nlmsg_size() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_IFINFO, NULL, GFP_ATOMIC); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_IFINFO, err); } static inline size_t inet6_prefix_nlmsg_size(void) { return NLMSG_ALIGN(sizeof(struct prefixmsg)) + nla_total_size(sizeof(struct in6_addr)) + nla_total_size(sizeof(struct prefix_cacheinfo)); } static int inet6_fill_prefix(struct sk_buff *skb, struct inet6_dev *idev, struct prefix_info *pinfo, u32 pid, u32 seq, int event, unsigned int flags) { struct prefixmsg *pmsg; struct nlmsghdr *nlh; struct prefix_cacheinfo ci; nlh = nlmsg_put(skb, pid, seq, event, sizeof(*pmsg), flags); if (nlh == NULL) return -EMSGSIZE; pmsg = nlmsg_data(nlh); pmsg->prefix_family = AF_INET6; pmsg->prefix_pad1 = 0; pmsg->prefix_pad2 = 0; pmsg->prefix_ifindex = idev->dev->ifindex; pmsg->prefix_len = pinfo->prefix_len; pmsg->prefix_type = pinfo->type; pmsg->prefix_pad3 = 0; pmsg->prefix_flags = 0; if (pinfo->onlink) pmsg->prefix_flags |= IF_PREFIX_ONLINK; if (pinfo->autoconf) pmsg->prefix_flags |= IF_PREFIX_AUTOCONF; NLA_PUT(skb, PREFIX_ADDRESS, sizeof(pinfo->prefix), &pinfo->prefix); ci.preferred_time = ntohl(pinfo->prefered); ci.valid_time = ntohl(pinfo->valid); NLA_PUT(skb, PREFIX_CACHEINFO, sizeof(ci), &ci); return nlmsg_end(skb, nlh); nla_put_failure: nlmsg_cancel(skb, nlh); return -EMSGSIZE; } static void inet6_prefix_notify(int event, struct inet6_dev *idev, struct prefix_info *pinfo) { struct sk_buff *skb; struct net *net = dev_net(idev->dev); int err = -ENOBUFS; skb = nlmsg_new(inet6_prefix_nlmsg_size(), GFP_ATOMIC); if (skb == NULL) goto errout; err = inet6_fill_prefix(skb, idev, pinfo, 0, 0, event, 0); if (err < 0) { /* -EMSGSIZE implies BUG in inet6_prefix_nlmsg_size() */ WARN_ON(err == -EMSGSIZE); kfree_skb(skb); goto errout; } rtnl_notify(skb, net, 0, RTNLGRP_IPV6_PREFIX, NULL, GFP_ATOMIC); return; errout: if (err < 0) rtnl_set_sk_err(net, RTNLGRP_IPV6_PREFIX, err); } static void __ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp) { inet6_ifa_notify(event ? : RTM_NEWADDR, ifp); switch (event) { case RTM_NEWADDR: /* * If the address was optimistic * we inserted the route at the start of * our DAD process, so we don't need * to do it again */ if (!(ifp->rt->rt6i_node)) ip6_ins_rt(ifp->rt); if (ifp->idev->cnf.forwarding) addrconf_join_anycast(ifp); break; case RTM_DELADDR: if (ifp->idev->cnf.forwarding) addrconf_leave_anycast(ifp); addrconf_leave_solict(ifp->idev, &ifp->addr); dst_hold(&ifp->rt->dst); if (ip6_del_rt(ifp->rt)) dst_free(&ifp->rt->dst); break; } } static void ipv6_ifa_notify(int event, struct inet6_ifaddr *ifp) { rcu_read_lock_bh(); if (likely(ifp->idev->dead == 0)) __ipv6_ifa_notify(event, ifp); rcu_read_unlock_bh(); } #ifdef CONFIG_SYSCTL static int addrconf_sysctl_forward(ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = ctl->data; int val = *valp; loff_t pos = *ppos; ctl_table lctl; int ret; /* * ctl->data points to idev->cnf.forwarding, we should * not modify it until we get the rtnl lock. */ lctl = *ctl; lctl.data = &val; ret = proc_dointvec(&lctl, write, buffer, lenp, ppos); if (write) ret = addrconf_fixup_forwarding(ctl, valp, val); if (ret) *ppos = pos; return ret; } static void dev_disable_change(struct inet6_dev *idev) { if (!idev || !idev->dev) return; if (idev->cnf.disable_ipv6) addrconf_notify(NULL, NETDEV_DOWN, idev->dev); else addrconf_notify(NULL, NETDEV_UP, idev->dev); } static void addrconf_disable_change(struct net *net, __s32 newf) { struct net_device *dev; struct inet6_dev *idev; rcu_read_lock(); for_each_netdev_rcu(net, dev) { idev = __in6_dev_get(dev); if (idev) { int changed = (!idev->cnf.disable_ipv6) ^ (!newf); idev->cnf.disable_ipv6 = newf; if (changed) dev_disable_change(idev); } } rcu_read_unlock(); } static int addrconf_disable_ipv6(struct ctl_table *table, int *p, int newf) { struct net *net; int old; if (!rtnl_trylock()) return restart_syscall(); net = (struct net *)table->extra2; old = *p; *p = newf; if (p == &net->ipv6.devconf_dflt->disable_ipv6) { rtnl_unlock(); return 0; } if (p == &net->ipv6.devconf_all->disable_ipv6) { net->ipv6.devconf_dflt->disable_ipv6 = newf; addrconf_disable_change(net, newf); } else if ((!newf) ^ (!old)) dev_disable_change((struct inet6_dev *)table->extra1); rtnl_unlock(); return 0; } static int addrconf_sysctl_disable(ctl_table *ctl, int write, void __user *buffer, size_t *lenp, loff_t *ppos) { int *valp = ctl->data; int val = *valp; loff_t pos = *ppos; ctl_table lctl; int ret; /* * ctl->data points to idev->cnf.disable_ipv6, we should * not modify it until we get the rtnl lock. */ lctl = *ctl; lctl.data = &val; ret = proc_dointvec(&lctl, write, buffer, lenp, ppos); if (write) ret = addrconf_disable_ipv6(ctl, valp, val); if (ret) *ppos = pos; return ret; } static struct addrconf_sysctl_table { struct ctl_table_header *sysctl_header; ctl_table addrconf_vars[DEVCONF_MAX+1]; char *dev_name; } addrconf_sysctl __read_mostly = { .sysctl_header = NULL, .addrconf_vars = { { .procname = "forwarding", .data = &ipv6_devconf.forwarding, .maxlen = sizeof(int), .mode = 0644, .proc_handler = addrconf_sysctl_forward, }, { .procname = "hop_limit", .data = &ipv6_devconf.hop_limit, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "mtu", .data = &ipv6_devconf.mtu6, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_ra", .data = &ipv6_devconf.accept_ra, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_redirects", .data = &ipv6_devconf.accept_redirects, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "autoconf", .data = &ipv6_devconf.autoconf, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "dad_transmits", .data = &ipv6_devconf.dad_transmits, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "router_solicitations", .data = &ipv6_devconf.rtr_solicits, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "router_solicitation_interval", .data = &ipv6_devconf.rtr_solicit_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "router_solicitation_delay", .data = &ipv6_devconf.rtr_solicit_delay, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, { .procname = "force_mld_version", .data = &ipv6_devconf.force_mld_version, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IPV6_PRIVACY { .procname = "use_tempaddr", .data = &ipv6_devconf.use_tempaddr, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "temp_valid_lft", .data = &ipv6_devconf.temp_valid_lft, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "temp_prefered_lft", .data = &ipv6_devconf.temp_prefered_lft, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "regen_max_retry", .data = &ipv6_devconf.regen_max_retry, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "max_desync_factor", .data = &ipv6_devconf.max_desync_factor, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif { .procname = "max_addresses", .data = &ipv6_devconf.max_addresses, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_ra_defrtr", .data = &ipv6_devconf.accept_ra_defrtr, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_ra_pinfo", .data = &ipv6_devconf.accept_ra_pinfo, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IPV6_ROUTER_PREF { .procname = "accept_ra_rtr_pref", .data = &ipv6_devconf.accept_ra_rtr_pref, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "router_probe_interval", .data = &ipv6_devconf.rtr_probe_interval, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec_jiffies, }, #ifdef CONFIG_IPV6_ROUTE_INFO { .procname = "accept_ra_rt_info_max_plen", .data = &ipv6_devconf.accept_ra_rt_info_max_plen, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif #endif { .procname = "accept_ra_rt_table", .data = &ipv6_devconf.accept_ra_rt_table, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "proxy_ndp", .data = &ipv6_devconf.proxy_ndp, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "accept_source_route", .data = &ipv6_devconf.accept_source_route, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_IPV6_OPTIMISTIC_DAD { .procname = "optimistic_dad", .data = &ipv6_devconf.optimistic_dad, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "use_optimistic", .data = &ipv6_devconf.use_optimistic, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #endif #ifdef CONFIG_IPV6_MROUTE { .procname = "mc_forwarding", .data = &ipv6_devconf.mc_forwarding, .maxlen = sizeof(int), .mode = 0444, .proc_handler = proc_dointvec, }, #endif { .procname = "disable_ipv6", .data = &ipv6_devconf.disable_ipv6, .maxlen = sizeof(int), .mode = 0644, .proc_handler = addrconf_sysctl_disable, }, { .procname = "accept_dad", .data = &ipv6_devconf.accept_dad, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, { .procname = "force_tllao", .data = &ipv6_devconf.force_tllao, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, { .procname = "accept_ra_prefix_route", .data = &ipv6_devconf.accept_ra_prefix_route, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec, }, #ifdef CONFIG_LGE_DHCPV6_WIFI { .procname = "ra_info_flag", .data = &ipv6_devconf.ra_info_flag, .maxlen = sizeof(int), .mode = 0644, .proc_handler = proc_dointvec }, #endif { /* sentinel */ } }, }; static int __addrconf_sysctl_register(struct net *net, char *dev_name, struct inet6_dev *idev, struct ipv6_devconf *p) { int i; struct addrconf_sysctl_table *t; #define ADDRCONF_CTL_PATH_DEV 3 struct ctl_path addrconf_ctl_path[] = { { .procname = "net", }, { .procname = "ipv6", }, { .procname = "conf", }, { /* to be set */ }, { }, }; t = kmemdup(&addrconf_sysctl, sizeof(*t), GFP_KERNEL); if (t == NULL) goto out; for (i = 0; t->addrconf_vars[i].data; i++) { t->addrconf_vars[i].data += (char *)p - (char *)&ipv6_devconf; t->addrconf_vars[i].extra1 = idev; /* embedded; no ref */ t->addrconf_vars[i].extra2 = net; } /* * Make a copy of dev_name, because '.procname' is regarded as const * by sysctl and we wouldn't want anyone to change it under our feet * (see SIOCSIFNAME). */ t->dev_name = kstrdup(dev_name, GFP_KERNEL); if (!t->dev_name) goto free; addrconf_ctl_path[ADDRCONF_CTL_PATH_DEV].procname = t->dev_name; t->sysctl_header = register_net_sysctl_table(net, addrconf_ctl_path, t->addrconf_vars); if (t->sysctl_header == NULL) goto free_procname; p->sysctl = t; return 0; free_procname: kfree(t->dev_name); free: kfree(t); out: return -ENOBUFS; } static void __addrconf_sysctl_unregister(struct ipv6_devconf *p) { struct addrconf_sysctl_table *t; if (p->sysctl == NULL) return; t = p->sysctl; p->sysctl = NULL; unregister_net_sysctl_table(t->sysctl_header); kfree(t->dev_name); kfree(t); } static void addrconf_sysctl_register(struct inet6_dev *idev) { neigh_sysctl_register(idev->dev, idev->nd_parms, "ipv6", &ndisc_ifinfo_sysctl_change); __addrconf_sysctl_register(dev_net(idev->dev), idev->dev->name, idev, &idev->cnf); } static void addrconf_sysctl_unregister(struct inet6_dev *idev) { __addrconf_sysctl_unregister(&idev->cnf); neigh_sysctl_unregister(idev->nd_parms); } #endif static int __net_init addrconf_init_net(struct net *net) { int err = -ENOMEM; struct ipv6_devconf *all, *dflt; all = kmemdup(&ipv6_devconf, sizeof(ipv6_devconf), GFP_KERNEL); if (all == NULL) goto err_alloc_all; dflt = kmemdup(&ipv6_devconf_dflt, sizeof(ipv6_devconf_dflt), GFP_KERNEL); if (dflt == NULL) goto err_alloc_dflt; /* these will be inherited by all namespaces */ dflt->autoconf = ipv6_defaults.autoconf; dflt->disable_ipv6 = ipv6_defaults.disable_ipv6; net->ipv6.devconf_all = all; net->ipv6.devconf_dflt = dflt; #ifdef CONFIG_SYSCTL err = __addrconf_sysctl_register(net, "all", NULL, all); if (err < 0) goto err_reg_all; err = __addrconf_sysctl_register(net, "default", NULL, dflt); if (err < 0) goto err_reg_dflt; #endif return 0; #ifdef CONFIG_SYSCTL err_reg_dflt: __addrconf_sysctl_unregister(all); err_reg_all: kfree(dflt); #endif err_alloc_dflt: kfree(all); err_alloc_all: return err; } static void __net_exit addrconf_exit_net(struct net *net) { #ifdef CONFIG_SYSCTL __addrconf_sysctl_unregister(net->ipv6.devconf_dflt); __addrconf_sysctl_unregister(net->ipv6.devconf_all); #endif if (!net_eq(net, &init_net)) { kfree(net->ipv6.devconf_dflt); kfree(net->ipv6.devconf_all); } } static struct pernet_operations addrconf_ops = { .init = addrconf_init_net, .exit = addrconf_exit_net, }; /* * Device notifier */ int register_inet6addr_notifier(struct notifier_block *nb) { return atomic_notifier_chain_register(&inet6addr_chain, nb); } EXPORT_SYMBOL(register_inet6addr_notifier); int unregister_inet6addr_notifier(struct notifier_block *nb) { return atomic_notifier_chain_unregister(&inet6addr_chain, nb); } EXPORT_SYMBOL(unregister_inet6addr_notifier); static struct rtnl_af_ops inet6_ops = { .family = AF_INET6, .fill_link_af = inet6_fill_link_af, .get_link_af_size = inet6_get_link_af_size, }; /* * Init / cleanup code */ int __init addrconf_init(void) { int i, err; err = ipv6_addr_label_init(); if (err < 0) { printk(KERN_CRIT "IPv6 Addrconf:" " cannot initialize default policy table: %d.\n", err); goto out; } err = register_pernet_subsys(&addrconf_ops); if (err < 0) goto out_addrlabel; /* The addrconf netdev notifier requires that loopback_dev * has it's ipv6 private information allocated and setup * before it can bring up and give link-local addresses * to other devices which are up. * * Unfortunately, loopback_dev is not necessarily the first * entry in the global dev_base list of net devices. In fact, * it is likely to be the very last entry on that list. * So this causes the notifier registry below to try and * give link-local addresses to all devices besides loopback_dev * first, then loopback_dev, which cases all the non-loopback_dev * devices to fail to get a link-local address. * * So, as a temporary fix, allocate the ipv6 structure for * loopback_dev first by hand. * Longer term, all of the dependencies ipv6 has upon the loopback * device and it being up should be removed. */ rtnl_lock(); if (!ipv6_add_dev(init_net.loopback_dev)) err = -ENOMEM; rtnl_unlock(); if (err) goto errlo; for (i = 0; i < IN6_ADDR_HSIZE; i++) INIT_HLIST_HEAD(&inet6_addr_lst[i]); register_netdevice_notifier(&ipv6_dev_notf); addrconf_verify(0); err = rtnl_af_register(&inet6_ops); if (err < 0) goto errout_af; err = __rtnl_register(PF_INET6, RTM_GETLINK, NULL, inet6_dump_ifinfo, NULL); if (err < 0) goto errout; /* Only the first call to __rtnl_register can fail */ __rtnl_register(PF_INET6, RTM_NEWADDR, inet6_rtm_newaddr, NULL, NULL); __rtnl_register(PF_INET6, RTM_DELADDR, inet6_rtm_deladdr, NULL, NULL); __rtnl_register(PF_INET6, RTM_GETADDR, inet6_rtm_getaddr, inet6_dump_ifaddr, NULL); __rtnl_register(PF_INET6, RTM_GETMULTICAST, NULL, inet6_dump_ifmcaddr, NULL); __rtnl_register(PF_INET6, RTM_GETANYCAST, NULL, inet6_dump_ifacaddr, NULL); ipv6_addr_label_rtnl_register(); return 0; errout: rtnl_af_unregister(&inet6_ops); errout_af: unregister_netdevice_notifier(&ipv6_dev_notf); errlo: unregister_pernet_subsys(&addrconf_ops); out_addrlabel: ipv6_addr_label_cleanup(); out: return err; } void addrconf_cleanup(void) { struct net_device *dev; int i; unregister_netdevice_notifier(&ipv6_dev_notf); unregister_pernet_subsys(&addrconf_ops); ipv6_addr_label_cleanup(); rtnl_lock(); __rtnl_af_unregister(&inet6_ops); /* clean dev list */ for_each_netdev(&init_net, dev) { if (__in6_dev_get(dev) == NULL) continue; addrconf_ifdown(dev, 1); } addrconf_ifdown(init_net.loopback_dev, 2); /* * Check hash table. */ spin_lock_bh(&addrconf_hash_lock); for (i = 0; i < IN6_ADDR_HSIZE; i++) WARN_ON(!hlist_empty(&inet6_addr_lst[i])); spin_unlock_bh(&addrconf_hash_lock); del_timer(&addr_chk_timer); rtnl_unlock(); }
Java
<?php namespace Thru\ActiveRecord\Test\Models; use Thru\ActiveRecord\ActiveRecord; /** * Class TestModel * @var $test_model_id integer * @var $integer_field integer * @var $text_field text * @var $date_field date */ class TestModel extends ActiveRecord { protected $_table = "test_models"; public $test_model_id; public $integer_field; public $text_field; public $date_field; }
Java
java -Djava.ext.dirs=reggie-libs -Djava.util.logging.config.file=config/logging.properties -jar reggie-libs/start.jar config/start-reggie.config
Java
// // This file is part of Gambit // Copyright (c) 1994-2016, The Gambit Project (http://www.gambit-project.org) // // FILE: src/libgambit/dvector.h // Doubly-partitioned vector class // // 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. // #ifndef LIBGAMBIT_DVECTOR_H #define LIBGAMBIT_DVECTOR_H #include "pvector.h" namespace Gambit { template <class T> class DVector : public PVector<T> { private: int sum(int part, const PVector<int> &v) const; void setindex(void); bool Check(const DVector<T> &) const; protected: T ***dvptr; Array<int> dvlen, dvidx; public: DVector(void); DVector(const PVector<int> &sig); DVector(const Vector<T> &val, const PVector<int> &sig); DVector(const DVector<T> &v); virtual ~DVector(); T &operator()(int a, int b, int c); const T &operator()(int a, int b, int c) const; // extract a subvector void CopySubRow(int row, int col, const DVector<T> &v); DVector<T> &operator=(const DVector<T> &v); DVector<T> &operator=(const PVector<T> &v); DVector<T> &operator=(const Vector<T> &v); DVector<T> &operator=(T c); DVector<T> operator+(const DVector<T> &v) const; DVector<T> &operator+=(const DVector<T> &v); DVector<T> operator-(void) const; DVector<T> operator-(const DVector<T> &v) const; DVector<T> &operator-=(const DVector<T> &v); T operator*(const DVector<T> &v) const; DVector<T> &operator*=(const T &c); DVector<T> operator/(const T &c) const; bool operator==(const DVector<T> &v) const; bool operator!=(const DVector<T> &v) const; const Array<int> &DPLengths(void) const; }; } // end namespace Gambit #endif // LIBGAMBIT_DVECTOR_H
Java
/* Copyright (c) 2010-2012, Code Aurora Forum. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 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. * */ /* #define DEBUG */ #define DEV_DBG_PREFIX "HDMI: " /* #define REG_DUMP */ #define CEC_MSG_PRINT #define TOGGLE_CEC_HARDWARE_FSM #include <linux/types.h> #include <linux/bitops.h> #include <linux/clk.h> #include <linux/mutex.h> #include <mach/msm_hdmi_audio.h> #include <mach/clk.h> #include <mach/msm_iomap.h> #include <mach/socinfo.h> #include "msm_fb.h" #include "hdmi_msm.h" /* Supported HDMI Audio channels */ #define MSM_HDMI_AUDIO_CHANNEL_2 0 #define MSM_HDMI_AUDIO_CHANNEL_4 1 #define MSM_HDMI_AUDIO_CHANNEL_6 2 #define MSM_HDMI_AUDIO_CHANNEL_8 3 #define MSM_HDMI_AUDIO_CHANNEL_MAX 4 #define MSM_HDMI_AUDIO_CHANNEL_FORCE_32BIT 0x7FFFFFFF /* Supported HDMI Audio sample rates */ #define MSM_HDMI_SAMPLE_RATE_32KHZ 0 #define MSM_HDMI_SAMPLE_RATE_44_1KHZ 1 #define MSM_HDMI_SAMPLE_RATE_48KHZ 2 #define MSM_HDMI_SAMPLE_RATE_88_2KHZ 3 #define MSM_HDMI_SAMPLE_RATE_96KHZ 4 #define MSM_HDMI_SAMPLE_RATE_176_4KHZ 5 #define MSM_HDMI_SAMPLE_RATE_192KHZ 6 #define MSM_HDMI_SAMPLE_RATE_MAX 7 #define MSM_HDMI_SAMPLE_RATE_FORCE_32BIT 0x7FFFFFFF static int msm_hdmi_sample_rate = MSM_HDMI_SAMPLE_RATE_48KHZ; /* HDMI/HDCP Registers */ #define HDCP_DDC_STATUS 0x0128 #define HDCP_DDC_CTRL_0 0x0120 #define HDCP_DDC_CTRL_1 0x0124 #define HDMI_DDC_CTRL 0x020C #define HPD_EVENT_OFFLINE 0 #define HPD_EVENT_ONLINE 1 #define SWITCH_SET_HDMI_AUDIO(d, force) \ do {\ if (!hdmi_msm_is_dvi_mode() &&\ ((force) ||\ (external_common_state->audio_sdev.state != (d)))) {\ switch_set_state(&external_common_state->audio_sdev,\ (d));\ DEV_INFO("%s: hdmi_audio state switched to %d\n",\ __func__,\ external_common_state->audio_sdev.state);\ } \ } while (0) struct workqueue_struct *hdmi_work_queue; struct hdmi_msm_state_type *hdmi_msm_state; /* Enable HDCP by default */ static bool hdcp_feature_on = true; DEFINE_MUTEX(hdmi_msm_state_mutex); EXPORT_SYMBOL(hdmi_msm_state_mutex); static DEFINE_MUTEX(hdcp_auth_state_mutex); static void hdmi_msm_dump_regs(const char *prefix); static void hdmi_msm_hdcp_enable(void); static void hdmi_msm_turn_on(void); static int hdmi_msm_audio_off(void); static int hdmi_msm_read_edid(void); static void hdmi_msm_hpd_off(void); static boolean hdmi_msm_is_dvi_mode(void); #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT static void hdmi_msm_cec_line_latch_detect(void); #ifdef TOGGLE_CEC_HARDWARE_FSM static boolean msg_send_complete = TRUE; static boolean msg_recv_complete = TRUE; #endif #define HDMI_MSM_CEC_REFTIMER_REFTIMER_ENABLE BIT(16) #define HDMI_MSM_CEC_REFTIMER_REFTIMER(___t) (((___t)&0xFFFF) << 0) #define HDMI_MSM_CEC_TIME_SIGNAL_FREE_TIME(___t) (((___t)&0x1FF) << 7) #define HDMI_MSM_CEC_TIME_ENABLE BIT(0) #define HDMI_MSM_CEC_ADDR_LOGICAL_ADDR(___la) (((___la)&0xFF) << 0) #define HDMI_MSM_CEC_CTRL_LINE_OE BIT(9) #define HDMI_MSM_CEC_CTRL_FRAME_SIZE(___sz) (((___sz)&0x1F) << 4) #define HDMI_MSM_CEC_CTRL_SOFT_RESET BIT(2) #define HDMI_MSM_CEC_CTRL_SEND_TRIG BIT(1) #define HDMI_MSM_CEC_CTRL_ENABLE BIT(0) #define HDMI_MSM_CEC_INT_FRAME_RD_DONE_MASK BIT(7) #define HDMI_MSM_CEC_INT_FRAME_RD_DONE_ACK BIT(6) #define HDMI_MSM_CEC_INT_FRAME_RD_DONE_INT BIT(6) #define HDMI_MSM_CEC_INT_MONITOR_MASK BIT(5) #define HDMI_MSM_CEC_INT_MONITOR_ACK BIT(4) #define HDMI_MSM_CEC_INT_MONITOR_INT BIT(4) #define HDMI_MSM_CEC_INT_FRAME_ERROR_MASK BIT(3) #define HDMI_MSM_CEC_INT_FRAME_ERROR_ACK BIT(2) #define HDMI_MSM_CEC_INT_FRAME_ERROR_INT BIT(2) #define HDMI_MSM_CEC_INT_FRAME_WR_DONE_MASK BIT(1) #define HDMI_MSM_CEC_INT_FRAME_WR_DONE_ACK BIT(0) #define HDMI_MSM_CEC_INT_FRAME_WR_DONE_INT BIT(0) #define HDMI_MSM_CEC_FRAME_WR_SUCCESS(___st) (((___st)&0xB) ==\ (HDMI_MSM_CEC_INT_FRAME_WR_DONE_INT |\ HDMI_MSM_CEC_INT_FRAME_WR_DONE_MASK |\ HDMI_MSM_CEC_INT_FRAME_ERROR_MASK)) #define HDMI_MSM_CEC_RETRANSMIT_NUM(___num) (((___num)&0xF) << 4) #define HDMI_MSM_CEC_RETRANSMIT_ENABLE BIT(0) #define HDMI_MSM_CEC_WR_DATA_DATA(___d) (((___d)&0xFF) << 8) void hdmi_msm_cec_init(void) { /* 0x02A8 CEC_REFTIMER */ HDMI_OUTP(0x02A8, HDMI_MSM_CEC_REFTIMER_REFTIMER_ENABLE | HDMI_MSM_CEC_REFTIMER_REFTIMER(27 * 50) ); /* * 0x02A0 CEC_ADDR * Starting with a default address of 4 */ HDMI_OUTP(0x02A0, HDMI_MSM_CEC_ADDR_LOGICAL_ADDR(4)); hdmi_msm_state->first_monitor = 0; hdmi_msm_state->fsm_reset_done = false; /* 0x029C CEC_INT */ /* Enable CEC interrupts */ HDMI_OUTP(0x029C, \ HDMI_MSM_CEC_INT_FRAME_WR_DONE_MASK \ | HDMI_MSM_CEC_INT_FRAME_ERROR_MASK \ | HDMI_MSM_CEC_INT_MONITOR_MASK \ | HDMI_MSM_CEC_INT_FRAME_RD_DONE_MASK); HDMI_OUTP(0x02B0, 0x7FF << 4 | 1); /* * Slight adjustment to logic 1 low periods on read, * CEC Test 8.2-3 was failing, 8 for the * BIT_1_ERR_RANGE_HI = 8 => 750us, the test used 775us, * so increased this to 9 which => 800us. */ /* * CEC latch up issue - To fire monitor interrupt * for every start of message */ HDMI_OUTP(0x02E0, 0x880000); /* * Slight adjustment to logic 0 low period on write */ HDMI_OUTP(0x02DC, 0x8888A888); /* * Enable Signal Free Time counter and set to 7 bit periods */ HDMI_OUTP(0x02A4, 0x1 | (7 * 0x30) << 7); /* 0x028C CEC_CTRL */ HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); } void hdmi_msm_cec_write_logical_addr(int addr) { /* 0x02A0 CEC_ADDR * LOGICAL_ADDR 7:0 NUM */ HDMI_OUTP(0x02A0, addr & 0xFF); } void hdmi_msm_dump_cec_msg(struct hdmi_msm_cec_msg *msg) { #ifdef CEC_MSG_PRINT int i; DEV_DBG("sender_id : %d", msg->sender_id); DEV_DBG("recvr_id : %d", msg->recvr_id); if (msg->frame_size < 2) { DEV_DBG("polling message"); return; } DEV_DBG("opcode : %02x", msg->opcode); for (i = 0; i < msg->frame_size - 2; i++) DEV_DBG("operand(%2d) : %02x", i + 1, msg->operand[i]); #endif /* CEC_MSG_PRINT */ } void hdmi_msm_cec_msg_send(struct hdmi_msm_cec_msg *msg) { int i; uint32 timeout_count = 1; int retry = 10; boolean frameType = (msg->recvr_id == 15 ? BIT(0) : 0); mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->fsm_reset_done = false; mutex_unlock(&hdmi_msm_state_mutex); #ifdef TOGGLE_CEC_HARDWARE_FSM msg_send_complete = FALSE; #endif INIT_COMPLETION(hdmi_msm_state->cec_frame_wr_done); hdmi_msm_state->cec_frame_wr_status = 0; /* 0x0294 HDMI_MSM_CEC_RETRANSMIT */ HDMI_OUTP(0x0294, #ifdef DRVR_ONLY_CECT_NO_DAEMON HDMI_MSM_CEC_RETRANSMIT_NUM(msg->retransmit) | (msg->retransmit > 0) ? HDMI_MSM_CEC_RETRANSMIT_ENABLE : 0); #else HDMI_MSM_CEC_RETRANSMIT_NUM(0) | HDMI_MSM_CEC_RETRANSMIT_ENABLE); #endif /* 0x028C CEC_CTRL */ HDMI_OUTP(0x028C, 0x1 | msg->frame_size << 4); /* 0x0290 CEC_WR_DATA */ /* header block */ HDMI_OUTP(0x0290, HDMI_MSM_CEC_WR_DATA_DATA(msg->sender_id << 4 | msg->recvr_id) | frameType); /* data block 0 : opcode */ HDMI_OUTP(0x0290, HDMI_MSM_CEC_WR_DATA_DATA(msg->frame_size < 2 ? 0 : msg->opcode) | frameType); /* data block 1-14 : operand 0-13 */ for (i = 0; i < msg->frame_size - 1; i++) HDMI_OUTP(0x0290, HDMI_MSM_CEC_WR_DATA_DATA(msg->operand[i]) | (msg->recvr_id == 15 ? BIT(0) : 0)); for (; i < 14; i++) HDMI_OUTP(0x0290, HDMI_MSM_CEC_WR_DATA_DATA(0) | (msg->recvr_id == 15 ? BIT(0) : 0)); while ((HDMI_INP(0x0298) & 1) && retry--) { DEV_DBG("CEC line is busy(%d)\n", retry); schedule(); } /* 0x028C CEC_CTRL */ HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_LINE_OE | HDMI_MSM_CEC_CTRL_FRAME_SIZE(msg->frame_size) | HDMI_MSM_CEC_CTRL_SEND_TRIG | HDMI_MSM_CEC_CTRL_ENABLE); timeout_count = wait_for_completion_interruptible_timeout( &hdmi_msm_state->cec_frame_wr_done, HZ); if (!timeout_count) { hdmi_msm_state->cec_frame_wr_status |= CEC_STATUS_WR_TMOUT; DEV_ERR("%s: timedout", __func__); hdmi_msm_dump_cec_msg(msg); } else { DEV_DBG("CEC write frame done (frame len=%d)", msg->frame_size); hdmi_msm_dump_cec_msg(msg); } #ifdef TOGGLE_CEC_HARDWARE_FSM if (!msg_recv_complete) { /* Toggle CEC hardware FSM */ HDMI_OUTP(0x028C, 0x0); HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); msg_recv_complete = TRUE; } msg_send_complete = TRUE; #else HDMI_OUTP(0x028C, 0x0); HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); #endif } void hdmi_msm_cec_line_latch_detect(void) { /* * CECT 9-5-1 * The timer period needs to be changed to appropriate value */ /* * Timedout without RD_DONE, WR_DONE or ERR_INT * Toggle CEC hardware FSM */ mutex_lock(&hdmi_msm_state_mutex); if (hdmi_msm_state->first_monitor == 1) { DEV_WARN("CEC line is probably latched up - CECT 9-5-1"); if (!msg_recv_complete) hdmi_msm_state->fsm_reset_done = true; HDMI_OUTP(0x028C, 0x0); HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); hdmi_msm_state->first_monitor = 0; } mutex_unlock(&hdmi_msm_state_mutex); } void hdmi_msm_cec_msg_recv(void) { uint32 data; int i; #ifdef DRVR_ONLY_CECT_NO_DAEMON struct hdmi_msm_cec_msg temp_msg; #endif mutex_lock(&hdmi_msm_state_mutex); if (hdmi_msm_state->cec_queue_wr == hdmi_msm_state->cec_queue_rd && hdmi_msm_state->cec_queue_full) { mutex_unlock(&hdmi_msm_state_mutex); DEV_ERR("CEC message queue is overflowing\n"); #ifdef DRVR_ONLY_CECT_NO_DAEMON /* * Without CEC daemon: * Compliance tests fail once the queue gets filled up. * so reset the pointers to the start of the queue. */ hdmi_msm_state->cec_queue_wr = hdmi_msm_state->cec_queue_start; hdmi_msm_state->cec_queue_rd = hdmi_msm_state->cec_queue_start; hdmi_msm_state->cec_queue_full = false; #else return; #endif } if (hdmi_msm_state->cec_queue_wr == NULL) { DEV_ERR("%s: wp is NULL\n", __func__); return; } mutex_unlock(&hdmi_msm_state_mutex); /* 0x02AC CEC_RD_DATA */ data = HDMI_INP(0x02AC); hdmi_msm_state->cec_queue_wr->sender_id = (data & 0xF0) >> 4; hdmi_msm_state->cec_queue_wr->recvr_id = (data & 0x0F); hdmi_msm_state->cec_queue_wr->frame_size = (data & 0x1F00) >> 8; DEV_DBG("Recvd init=[%u] dest=[%u] size=[%u]\n", hdmi_msm_state->cec_queue_wr->sender_id, hdmi_msm_state->cec_queue_wr->recvr_id, hdmi_msm_state->cec_queue_wr->frame_size); if (hdmi_msm_state->cec_queue_wr->frame_size < 1) { DEV_ERR("%s: invalid message (frame length = %d)", __func__, hdmi_msm_state->cec_queue_wr->frame_size); return; } else if (hdmi_msm_state->cec_queue_wr->frame_size == 1) { DEV_DBG("%s: polling message (dest[%x] <- init[%x])", __func__, hdmi_msm_state->cec_queue_wr->recvr_id, hdmi_msm_state->cec_queue_wr->sender_id); return; } /* data block 0 : opcode */ data = HDMI_INP(0x02AC); hdmi_msm_state->cec_queue_wr->opcode = data & 0xFF; /* data block 1-14 : operand 0-13 */ for (i = 0; i < hdmi_msm_state->cec_queue_wr->frame_size - 2; i++) { data = HDMI_INP(0x02AC); hdmi_msm_state->cec_queue_wr->operand[i] = data & 0xFF; } for (; i < 14; i++) hdmi_msm_state->cec_queue_wr->operand[i] = 0; DEV_DBG("CEC read frame done\n"); DEV_DBG("=======================================\n"); hdmi_msm_dump_cec_msg(hdmi_msm_state->cec_queue_wr); DEV_DBG("=======================================\n"); #ifdef DRVR_ONLY_CECT_NO_DAEMON switch (hdmi_msm_state->cec_queue_wr->opcode) { case 0x64: /* Set OSD String */ DEV_INFO("Recvd OSD Str=[%x]\n",\ hdmi_msm_state->cec_queue_wr->operand[3]); break; case 0x83: /* Give Phy Addr */ DEV_INFO("Recvd a Give Phy Addr cmd\n"); memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); /* Setup a frame for sending out phy addr */ temp_msg.sender_id = 0x4; /* Broadcast */ temp_msg.recvr_id = 0xf; temp_msg.opcode = 0x84; i = 0; temp_msg.operand[i++] = 0x10; temp_msg.operand[i++] = 0x00; temp_msg.operand[i++] = 0x04; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); break; case 0xFF: /* Abort */ DEV_INFO("Recvd an abort cmd 0xFF\n"); memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /*feature abort */ temp_msg.opcode = 0x00; temp_msg.operand[i++] = hdmi_msm_state->cec_queue_wr->opcode; /*reason for abort = "Refused" */ temp_msg.operand[i++] = 0x04; temp_msg.frame_size = i + 2; hdmi_msm_dump_cec_msg(&temp_msg); hdmi_msm_cec_msg_send(&temp_msg); break; case 0x046: /* Give OSD name */ DEV_INFO("Recvd cmd 0x046\n"); memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /* OSD Name */ temp_msg.opcode = 0x47; /* Display control byte */ temp_msg.operand[i++] = 0x00; temp_msg.operand[i++] = 'H'; temp_msg.operand[i++] = 'e'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'o'; temp_msg.operand[i++] = ' '; temp_msg.operand[i++] = 'W'; temp_msg.operand[i++] = 'o'; temp_msg.operand[i++] = 'r'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'd'; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); break; case 0x08F: /* Give Device Power status */ DEV_INFO("Recvd a Power status message\n"); memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /* OSD String */ temp_msg.opcode = 0x90; temp_msg.operand[i++] = 'H'; temp_msg.operand[i++] = 'e'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'o'; temp_msg.operand[i++] = ' '; temp_msg.operand[i++] = 'W'; temp_msg.operand[i++] = 'o'; temp_msg.operand[i++] = 'r'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'd'; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); break; case 0x080: /* Routing Change cmd */ case 0x086: /* Set Stream Path */ DEV_INFO("Recvd Set Stream\n"); memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; /*Broadcast this message*/ temp_msg.recvr_id = 0xf; i = 0; temp_msg.opcode = 0x82; /* Active Source */ temp_msg.operand[i++] = 0x10; temp_msg.operand[i++] = 0x00; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); /* * sending <Image View On> message */ memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /* opcode for Image View On */ temp_msg.opcode = 0x04; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); break; case 0x44: /* User Control Pressed */ DEV_INFO("User Control Pressed\n"); break; case 0x45: /* User Control Released */ DEV_INFO("User Control Released\n"); break; default: DEV_INFO("Recvd an unknown cmd = [%u]\n", hdmi_msm_state->cec_queue_wr->opcode); #ifdef __SEND_ABORT__ memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /* opcode for feature abort */ temp_msg.opcode = 0x00; temp_msg.operand[i++] = hdmi_msm_state->cec_queue_wr->opcode; /*reason for abort = "Unrecognized opcode" */ temp_msg.operand[i++] = 0x00; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); break; #else memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /* OSD String */ temp_msg.opcode = 0x64; temp_msg.operand[i++] = 0x0; temp_msg.operand[i++] = 'H'; temp_msg.operand[i++] = 'e'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'o'; temp_msg.operand[i++] = ' '; temp_msg.operand[i++] = 'W'; temp_msg.operand[i++] = 'o'; temp_msg.operand[i++] = 'r'; temp_msg.operand[i++] = 'l'; temp_msg.operand[i++] = 'd'; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); break; #endif /* __SEND_ABORT__ */ } #endif /* DRVR_ONLY_CECT_NO_DAEMON */ mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->cec_queue_wr++; if (hdmi_msm_state->cec_queue_wr == CEC_QUEUE_END) hdmi_msm_state->cec_queue_wr = hdmi_msm_state->cec_queue_start; if (hdmi_msm_state->cec_queue_wr == hdmi_msm_state->cec_queue_rd) hdmi_msm_state->cec_queue_full = true; mutex_unlock(&hdmi_msm_state_mutex); DEV_DBG("Exiting %s()\n", __func__); } void hdmi_msm_cec_one_touch_play(void) { struct hdmi_msm_cec_msg temp_msg; uint32 i = 0; memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; /* * Broadcast this message */ temp_msg.recvr_id = 0xf; i = 0; /* Active Source */ temp_msg.opcode = 0x82; temp_msg.operand[i++] = 0x10; temp_msg.operand[i++] = 0x00; /*temp_msg.operand[i++] = 0x04;*/ temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); /* * sending <Image View On> message */ memset(&temp_msg, 0x00, sizeof(struct hdmi_msm_cec_msg)); temp_msg.sender_id = 0x4; temp_msg.recvr_id = hdmi_msm_state->cec_queue_wr->sender_id; i = 0; /* Image View On */ temp_msg.opcode = 0x04; temp_msg.frame_size = i + 2; hdmi_msm_cec_msg_send(&temp_msg); } #endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT */ uint32 hdmi_msm_get_io_base(void) { return (uint32)MSM_HDMI_BASE; } EXPORT_SYMBOL(hdmi_msm_get_io_base); /* Table indicating the video format supported by the HDMI TX Core v1.0 */ /* Valid Pixel-Clock rates: 25.2MHz, 27MHz, 27.03MHz, 74.25MHz, 148.5MHz */ static void hdmi_msm_setup_video_mode_lut(void) { HDMI_SETUP_LUT(640x480p60_4_3); HDMI_SETUP_LUT(720x480p60_4_3); HDMI_SETUP_LUT(720x480p60_16_9); HDMI_SETUP_LUT(1280x720p60_16_9); HDMI_SETUP_LUT(1920x1080i60_16_9); HDMI_SETUP_LUT(1440x480i60_4_3); HDMI_SETUP_LUT(1440x480i60_16_9); HDMI_SETUP_LUT(1920x1080p60_16_9); HDMI_SETUP_LUT(720x576p50_4_3); HDMI_SETUP_LUT(720x576p50_16_9); HDMI_SETUP_LUT(1280x720p50_16_9); HDMI_SETUP_LUT(1440x576i50_4_3); HDMI_SETUP_LUT(1440x576i50_16_9); HDMI_SETUP_LUT(1920x1080p50_16_9); HDMI_SETUP_LUT(1920x1080p24_16_9); HDMI_SETUP_LUT(1920x1080p25_16_9); HDMI_SETUP_LUT(1920x1080p30_16_9); } #ifdef PORT_DEBUG const char *hdmi_msm_name(uint32 offset) { switch (offset) { case 0x0000: return "CTRL"; case 0x0020: return "AUDIO_PKT_CTRL1"; case 0x0024: return "ACR_PKT_CTRL"; case 0x0028: return "VBI_PKT_CTRL"; case 0x002C: return "INFOFRAME_CTRL0"; #ifdef CONFIG_FB_MSM_HDMI_3D case 0x0034: return "GEN_PKT_CTRL"; #endif case 0x003C: return "ACP"; case 0x0040: return "GC"; case 0x0044: return "AUDIO_PKT_CTRL2"; case 0x0048: return "ISRC1_0"; case 0x004C: return "ISRC1_1"; case 0x0050: return "ISRC1_2"; case 0x0054: return "ISRC1_3"; case 0x0058: return "ISRC1_4"; case 0x005C: return "ISRC2_0"; case 0x0060: return "ISRC2_1"; case 0x0064: return "ISRC2_2"; case 0x0068: return "ISRC2_3"; case 0x006C: return "AVI_INFO0"; case 0x0070: return "AVI_INFO1"; case 0x0074: return "AVI_INFO2"; case 0x0078: return "AVI_INFO3"; #ifdef CONFIG_FB_MSM_HDMI_3D case 0x0084: return "GENERIC0_HDR"; case 0x0088: return "GENERIC0_0"; case 0x008C: return "GENERIC0_1"; #endif case 0x00C4: return "ACR_32_0"; case 0x00C8: return "ACR_32_1"; case 0x00CC: return "ACR_44_0"; case 0x00D0: return "ACR_44_1"; case 0x00D4: return "ACR_48_0"; case 0x00D8: return "ACR_48_1"; case 0x00E4: return "AUDIO_INFO0"; case 0x00E8: return "AUDIO_INFO1"; case 0x0110: return "HDCP_CTRL"; case 0x0114: return "HDCP_DEBUG_CTRL"; case 0x0118: return "HDCP_INT_CTRL"; case 0x011C: return "HDCP_LINK0_STATUS"; case 0x012C: return "HDCP_ENTROPY_CTRL0"; case 0x0130: return "HDCP_RESET"; case 0x0134: return "HDCP_RCVPORT_DATA0"; case 0x0138: return "HDCP_RCVPORT_DATA1"; case 0x013C: return "HDCP_RCVPORT_DATA2"; case 0x0144: return "HDCP_RCVPORT_DATA3"; case 0x0148: return "HDCP_RCVPORT_DATA4"; case 0x014C: return "HDCP_RCVPORT_DATA5"; case 0x0150: return "HDCP_RCVPORT_DATA6"; case 0x0168: return "HDCP_RCVPORT_DATA12"; case 0x01D0: return "AUDIO_CFG"; case 0x0208: return "USEC_REFTIMER"; case 0x020C: return "DDC_CTRL"; case 0x0214: return "DDC_INT_CTRL"; case 0x0218: return "DDC_SW_STATUS"; case 0x021C: return "DDC_HW_STATUS"; case 0x0220: return "DDC_SPEED"; case 0x0224: return "DDC_SETUP"; case 0x0228: return "DDC_TRANS0"; case 0x022C: return "DDC_TRANS1"; case 0x0238: return "DDC_DATA"; case 0x0250: return "HPD_INT_STATUS"; case 0x0254: return "HPD_INT_CTRL"; case 0x0258: return "HPD_CTRL"; case 0x025C: return "HDCP_ENTROPY_CTRL1"; case 0x027C: return "DDC_REF"; case 0x0284: return "HDCP_SW_UPPER_AKSV"; case 0x0288: return "HDCP_SW_LOWER_AKSV"; case 0x02B4: return "ACTIVE_H"; case 0x02B8: return "ACTIVE_V"; case 0x02BC: return "ACTIVE_V_F2"; case 0x02C0: return "TOTAL"; case 0x02C4: return "V_TOTAL_F2"; case 0x02C8: return "FRAME_CTRL"; case 0x02CC: return "AUD_INT"; case 0x0300: return "PHY_REG0"; case 0x0304: return "PHY_REG1"; case 0x0308: return "PHY_REG2"; case 0x030C: return "PHY_REG3"; case 0x0310: return "PHY_REG4"; case 0x0314: return "PHY_REG5"; case 0x0318: return "PHY_REG6"; case 0x031C: return "PHY_REG7"; case 0x0320: return "PHY_REG8"; case 0x0324: return "PHY_REG9"; case 0x0328: return "PHY_REG10"; case 0x032C: return "PHY_REG11"; case 0x0330: return "PHY_REG12"; default: return "???"; } } void hdmi_outp(uint32 offset, uint32 value) { uint32 in_val; outpdw(MSM_HDMI_BASE+offset, value); in_val = inpdw(MSM_HDMI_BASE+offset); DEV_DBG("HDMI[%04x] => %08x [%08x] %s\n", offset, value, in_val, hdmi_msm_name(offset)); } uint32 hdmi_inp(uint32 offset) { uint32 value = inpdw(MSM_HDMI_BASE+offset); DEV_DBG("HDMI[%04x] <= %08x %s\n", offset, value, hdmi_msm_name(offset)); return value; } #endif /* DEBUG */ static void hdmi_msm_turn_on(void); static int hdmi_msm_audio_off(void); static int hdmi_msm_read_edid(void); static void hdmi_msm_hpd_off(void); static bool hdmi_ready(void) { return MSM_HDMI_BASE && hdmi_msm_state && hdmi_msm_state->hdmi_app_clk && hdmi_msm_state->hpd_initialized; } static void hdmi_msm_send_event(boolean on) { char *envp[2]; /* QDSP OFF preceding the HPD event notification */ envp[0] = "HDCP_STATE=FAIL"; envp[1] = NULL; DEV_ERR("hdmi: HDMI HPD: QDSP OFF\n"); kobject_uevent_env(external_common_state->uevent_kobj, KOBJ_CHANGE, envp); if (on) { /* Build EDID table */ hdmi_msm_read_edid(); switch_set_state(&external_common_state->sdev, 1); DEV_INFO("%s: hdmi state switched to %d\n", __func__, external_common_state->sdev.state); DEV_INFO("HDMI HPD: CONNECTED: send ONLINE\n"); kobject_uevent(external_common_state->uevent_kobj, KOBJ_ONLINE); if (!hdmi_msm_state->hdcp_enable) { /* Send Audio for HDMI Compliance Cases*/ envp[0] = "HDCP_STATE=PASS"; envp[1] = NULL; DEV_INFO("HDMI HPD: sense : send HDCP_PASS\n"); kobject_uevent_env(external_common_state->uevent_kobj, KOBJ_CHANGE, envp); } } else { switch_set_state(&external_common_state->sdev, 0); DEV_INFO("%s: hdmi state switch to %d\n", __func__, external_common_state->sdev.state); DEV_INFO("hdmi: HDMI HPD: sense DISCONNECTED: send OFFLINE\n"); kobject_uevent(external_common_state->uevent_kobj, KOBJ_OFFLINE); } /*[ECID:000000] ZTEBSP wanghaifei start 20130221, add qcom new patch for HDP resume wait*/ // if (!completion_done(&hdmi_msm_state->hpd_event_processed)) // complete(&hdmi_msm_state->hpd_event_processed); /*[ECID:000000] ZTEBSP wanghaifei end 20130221, add qcom new patch for HDP resume wait*/ } static void hdmi_msm_hpd_state_work(struct work_struct *work) { if (!hdmi_ready()) { DEV_ERR("hdmi: %s: ignored, probe failed\n", __func__); return; } hdmi_msm_send_event(external_common_state->hpd_state); } #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT static void hdmi_msm_cec_latch_work(struct work_struct *work) { hdmi_msm_cec_line_latch_detect(); } #endif static void hdcp_deauthenticate(void); static void hdmi_msm_hdcp_reauth_work(struct work_struct *work) { if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } /* Don't process recursive actions */ mutex_lock(&hdmi_msm_state_mutex); if (hdmi_msm_state->hdcp_activating) { mutex_unlock(&hdmi_msm_state_mutex); return; } mutex_unlock(&hdmi_msm_state_mutex); /* * Reauth=>deauth, hdcp_auth * hdcp_auth=>turn_on() which calls * HDMI Core reset without informing the Audio QDSP * this can do bad things to video playback on the HDTV * Therefore, as surprising as it may sound do reauth * only if the device is HDCP-capable */ hdcp_deauthenticate(); mutex_lock(&hdcp_auth_state_mutex); hdmi_msm_state->reauth = TRUE; mutex_unlock(&hdcp_auth_state_mutex); mod_timer(&hdmi_msm_state->hdcp_timer, jiffies + HZ/2); } static void hdmi_msm_hdcp_work(struct work_struct *work) { if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } /* Only re-enable if cable still connected */ mutex_lock(&external_common_state_hpd_mutex); if (external_common_state->hpd_state && !(hdmi_msm_state->full_auth_done)) { mutex_unlock(&external_common_state_hpd_mutex); if (hdmi_msm_state->reauth == TRUE) { DEV_DBG("%s: Starting HDCP re-authentication\n", __func__); hdmi_msm_turn_on(); } else { DEV_DBG("%s: Starting HDCP authentication\n", __func__); hdmi_msm_hdcp_enable(); } } else { mutex_unlock(&external_common_state_hpd_mutex); DEV_DBG("%s: HDMI not connected or HDCP already active\n", __func__); hdmi_msm_state->reauth = FALSE; } } int hdmi_msm_process_hdcp_interrupts(void) { int rc = -1; uint32 hdcp_int_val; char *envp[2]; if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return -EINVAL; } /* HDCP_INT_CTRL[0x0118] * [0] AUTH_SUCCESS_INT [R] HDCP Authentication Success * interrupt status * [1] AUTH_SUCCESS_ACK [W] Acknowledge bit for HDCP * Authentication Success bit - write 1 to clear * [2] AUTH_SUCCESS_MASK [R/W] Mask bit for HDCP Authentication * Success interrupt - set to 1 to enable interrupt */ hdcp_int_val = HDMI_INP_ND(0x0118); if ((hdcp_int_val & (1 << 2)) && (hdcp_int_val & (1 << 0))) { /* AUTH_SUCCESS_INT */ HDMI_OUTP(0x0118, (hdcp_int_val | (1 << 1)) & ~(1 << 0)); DEV_INFO("HDCP: AUTH_SUCCESS_INT received\n"); complete_all(&hdmi_msm_state->hdcp_success_done); return 0; } /* [4] AUTH_FAIL_INT [R] HDCP Authentication Lost * interrupt Status * [5] AUTH_FAIL_ACK [W] Acknowledge bit for HDCP * Authentication Lost bit - write 1 to clear * [6] AUTH_FAIL_MASK [R/W] Mask bit fo HDCP Authentication * Lost interrupt set to 1 to enable interrupt * [7] AUTH_FAIL_INFO_ACK [W] Acknowledge bit for HDCP * Authentication Failure Info field - write 1 to clear */ if ((hdcp_int_val & (1 << 6)) && (hdcp_int_val & (1 << 4))) { /* AUTH_FAIL_INT */ /* Clear and Disable */ uint32 link_status = HDMI_INP_ND(0x011C); HDMI_OUTP(0x0118, (hdcp_int_val | (1 << 5)) & ~((1 << 6) | (1 << 4))); DEV_INFO("HDCP: AUTH_FAIL_INT received, LINK0_STATUS=0x%08x\n", link_status); if (hdmi_msm_state->full_auth_done) { SWITCH_SET_HDMI_AUDIO(0, 0); envp[0] = "HDCP_STATE=FAIL"; envp[1] = NULL; DEV_INFO("HDMI HPD:QDSP OFF\n"); kobject_uevent_env(external_common_state->uevent_kobj, KOBJ_CHANGE, envp); mutex_lock(&hdcp_auth_state_mutex); hdmi_msm_state->full_auth_done = FALSE; mutex_unlock(&hdcp_auth_state_mutex); /* Calling reauth only when authentication * is sucessful or else we always go into * the reauth loop. Also, No need to reauthenticate * if authentication failed because of cable disconnect */ if (((link_status & 0xF0) >> 4) != 0x7) { DEV_DBG("Reauthenticate From %s HDCP FAIL INT ", __func__); queue_work(hdmi_work_queue, &hdmi_msm_state->hdcp_reauth_work); } else { DEV_INFO("HDCP: HDMI cable disconnected\n"); } } /* Clear AUTH_FAIL_INFO as well */ HDMI_OUTP(0x0118, (hdcp_int_val | (1 << 7))); return 0; } /* [8] DDC_XFER_REQ_INT [R] HDCP DDC Transfer Request * interrupt status * [9] DDC_XFER_REQ_ACK [W] Acknowledge bit for HDCP DDC * Transfer Request bit - write 1 to clear * [10] DDC_XFER_REQ_MASK [R/W] Mask bit for HDCP DDC Transfer * Request interrupt - set to 1 to enable interrupt */ if ((hdcp_int_val & (1 << 10)) && (hdcp_int_val & (1 << 8))) { /* DDC_XFER_REQ_INT */ HDMI_OUTP_ND(0x0118, (hdcp_int_val | (1 << 9)) & ~(1 << 8)); if (!(hdcp_int_val & (1 << 12))) return 0; } /* [12] DDC_XFER_DONE_INT [R] HDCP DDC Transfer done interrupt * status * [13] DDC_XFER_DONE_ACK [W] Acknowledge bit for HDCP DDC * Transfer done bit - write 1 to clear * [14] DDC_XFER_DONE_MASK [R/W] Mask bit for HDCP DDC Transfer * done interrupt - set to 1 to enable interrupt */ if ((hdcp_int_val & (1 << 14)) && (hdcp_int_val & (1 << 12))) { /* DDC_XFER_DONE_INT */ HDMI_OUTP_ND(0x0118, (hdcp_int_val | (1 << 13)) & ~(1 << 12)); DEV_INFO("HDCP: DDC_XFER_DONE received\n"); return 0; } return rc; } static irqreturn_t hdmi_msm_isr(int irq, void *dev_id) { uint32 hpd_int_status; uint32 hpd_int_ctrl; #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT uint32 cec_intr_status; #endif uint32 ddc_int_ctrl; uint32 audio_int_val; static uint32 fifo_urun_int_occurred; static uint32 sample_drop_int_occurred; const uint32 occurrence_limit = 5; if (!hdmi_ready()) { DEV_DBG("ISR ignored, probe failed\n"); return IRQ_HANDLED; } /* Process HPD Interrupt */ /* HDMI_HPD_INT_STATUS[0x0250] */ hpd_int_status = HDMI_INP_ND(0x0250); /* HDMI_HPD_INT_CTRL[0x0254] */ hpd_int_ctrl = HDMI_INP_ND(0x0254); if ((hpd_int_ctrl & (1 << 2)) && (hpd_int_status & (1 << 0))) { /* * Got HPD interrupt. Ack the interrupt and disable any * further HPD interrupts until we process this interrupt. */ HDMI_OUTP(0x0254, ((hpd_int_ctrl | (BIT(0))) & ~BIT(2))); external_common_state->hpd_state = (HDMI_INP(0x0250) & BIT(1)) >> 1; DEV_DBG("%s: Queuing work to handle HPD %s event\n", __func__, external_common_state->hpd_state ? "connect" : "disconnect"); queue_work(hdmi_work_queue, &hdmi_msm_state->hpd_state_work); return IRQ_HANDLED; } /* Process DDC Interrupts */ /* HDMI_DDC_INT_CTRL[0x0214] */ ddc_int_ctrl = HDMI_INP_ND(0x0214); if ((ddc_int_ctrl & (1 << 2)) && (ddc_int_ctrl & (1 << 0))) { /* SW_DONE INT occured, clr it */ HDMI_OUTP_ND(0x0214, ddc_int_ctrl | (1 << 1)); complete(&hdmi_msm_state->ddc_sw_done); return IRQ_HANDLED; } /* FIFO Underrun Int is enabled */ /* HDMI_AUD_INT[0x02CC] * [3] AUD_SAM_DROP_MASK [R/W] * [2] AUD_SAM_DROP_ACK [W], AUD_SAM_DROP_INT [R] * [1] AUD_FIFO_URUN_MASK [R/W] * [0] AUD_FIFO_URUN_ACK [W], AUD_FIFO_URUN_INT [R] */ audio_int_val = HDMI_INP_ND(0x02CC); if ((audio_int_val & (1 << 1)) && (audio_int_val & (1 << 0))) { /* FIFO Underrun occured, clr it */ HDMI_OUTP(0x02CC, audio_int_val | (1 << 0)); ++fifo_urun_int_occurred; DEV_INFO("HDMI AUD_FIFO_URUN: %d\n", fifo_urun_int_occurred); if (fifo_urun_int_occurred >= occurrence_limit) { HDMI_OUTP(0x02CC, HDMI_INP(0x02CC) & ~(1 << 1)); DEV_INFO("HDMI AUD_FIFO_URUN: INT has been disabled " "by the ISR after %d occurences...\n", fifo_urun_int_occurred); } return IRQ_HANDLED; } /* Audio Sample Drop int is enabled */ if ((audio_int_val & (1 << 3)) && (audio_int_val & (1 << 2))) { /* Audio Sample Drop occured, clr it */ HDMI_OUTP(0x02CC, audio_int_val | (1 << 2)); DEV_DBG("%s: AUD_SAM_DROP", __func__); ++sample_drop_int_occurred; if (sample_drop_int_occurred >= occurrence_limit) { HDMI_OUTP(0x02CC, HDMI_INP(0x02CC) & ~(1 << 3)); DEV_INFO("HDMI AUD_SAM_DROP: INT has been disabled " "by the ISR after %d occurences...\n", sample_drop_int_occurred); } return IRQ_HANDLED; } if (!hdmi_msm_process_hdcp_interrupts()) return IRQ_HANDLED; #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT /* Process CEC Interrupt */ /* HDMI_MSM_CEC_INT[0x029C] */ cec_intr_status = HDMI_INP_ND(0x029C); DEV_DBG("cec interrupt status is [%u]\n", cec_intr_status); if (HDMI_MSM_CEC_FRAME_WR_SUCCESS(cec_intr_status)) { DEV_DBG("CEC_IRQ_FRAME_WR_DONE\n"); HDMI_OUTP(0x029C, cec_intr_status | HDMI_MSM_CEC_INT_FRAME_WR_DONE_ACK); mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->cec_frame_wr_status |= CEC_STATUS_WR_DONE; hdmi_msm_state->first_monitor = 0; del_timer(&hdmi_msm_state->cec_read_timer); mutex_unlock(&hdmi_msm_state_mutex); complete(&hdmi_msm_state->cec_frame_wr_done); return IRQ_HANDLED; } if ((cec_intr_status & (1 << 2)) && (cec_intr_status & (1 << 3))) { DEV_DBG("CEC_IRQ_FRAME_ERROR\n"); #ifdef TOGGLE_CEC_HARDWARE_FSM /* Toggle CEC hardware FSM */ HDMI_OUTP(0x028C, 0x0); HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); #endif HDMI_OUTP(0x029C, cec_intr_status); mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->first_monitor = 0; del_timer(&hdmi_msm_state->cec_read_timer); hdmi_msm_state->cec_frame_wr_status |= CEC_STATUS_WR_ERROR; mutex_unlock(&hdmi_msm_state_mutex); complete(&hdmi_msm_state->cec_frame_wr_done); return IRQ_HANDLED; } if ((cec_intr_status & (1 << 4)) && (cec_intr_status & (1 << 5))) { DEV_DBG("CEC_IRQ_MONITOR\n"); HDMI_OUTP(0x029C, cec_intr_status | HDMI_MSM_CEC_INT_MONITOR_ACK); /* * CECT 9-5-1 * On the first occassion start a timer * for few hundred ms, if it expires then * reset the CEC block else go on with * frame transactions as usual. * Below adds hdmi_msm_cec_msg_recv() as an * item into the work queue instead of running in * interrupt context */ mutex_lock(&hdmi_msm_state_mutex); if (hdmi_msm_state->first_monitor == 0) { /* This timer might have to be changed * worst case theoritical = * 16 bytes * 8 * 2.7msec = 346 msec */ mod_timer(&hdmi_msm_state->cec_read_timer, jiffies + HZ/2); hdmi_msm_state->first_monitor = 1; } mutex_unlock(&hdmi_msm_state_mutex); return IRQ_HANDLED; } if ((cec_intr_status & (1 << 6)) && (cec_intr_status & (1 << 7))) { DEV_DBG("CEC_IRQ_FRAME_RD_DONE\n"); mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->first_monitor = 0; del_timer(&hdmi_msm_state->cec_read_timer); mutex_unlock(&hdmi_msm_state_mutex); HDMI_OUTP(0x029C, cec_intr_status | HDMI_MSM_CEC_INT_FRAME_RD_DONE_ACK); hdmi_msm_cec_msg_recv(); #ifdef TOGGLE_CEC_HARDWARE_FSM if (!msg_send_complete) msg_recv_complete = FALSE; else { /* Toggle CEC hardware FSM */ HDMI_OUTP(0x028C, 0x0); HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); } #else HDMI_OUTP(0x028C, 0x0); HDMI_OUTP(0x028C, HDMI_MSM_CEC_CTRL_ENABLE); #endif return IRQ_HANDLED; } #endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT */ DEV_DBG("%s: HPD<Ctrl=%04x, State=%04x>, ddc_int_ctrl=%04x, " "aud_int=%04x, cec_intr_status=%04x\n", __func__, hpd_int_ctrl, hpd_int_status, ddc_int_ctrl, audio_int_val, HDMI_INP_ND(0x029C)); return IRQ_HANDLED; } static int check_hdmi_features(void) { /* RAW_FEAT_CONFIG_ROW0_LSB */ uint32 val = inpdw(QFPROM_BASE + 0x0238); /* HDMI_DISABLE */ boolean hdmi_disabled = (val & 0x00200000) >> 21; /* HDCP_DISABLE */ boolean hdcp_disabled = (val & 0x00400000) >> 22; DEV_DBG("Features <val:0x%08x, HDMI:%s, HDCP:%s>\n", val, hdmi_disabled ? "OFF" : "ON", hdcp_disabled ? "OFF" : "ON"); if (hdmi_disabled) { DEV_ERR("ERROR: HDMI disabled\n"); return -ENODEV; } if (hdcp_disabled) DEV_WARN("WARNING: HDCP disabled\n"); return 0; } static boolean hdmi_msm_has_hdcp(void) { /* RAW_FEAT_CONFIG_ROW0_LSB, HDCP_DISABLE */ return (inpdw(QFPROM_BASE + 0x0238) & 0x00400000) ? FALSE : TRUE; } static boolean hdmi_msm_is_power_on(void) { /* HDMI_CTRL, ENABLE */ return (HDMI_INP_ND(0x0000) & 0x00000001) ? TRUE : FALSE; } /* 1.2.1.2.1 DVI Operation * HDMI compliance requires the HDMI core to support DVI as well. The * HDMI core also supports DVI. In DVI operation there are no preambles * and guardbands transmitted. THe TMDS encoding of video data remains * the same as HDMI. There are no VBI or audio packets transmitted. In * order to enable DVI mode in HDMI core, HDMI_DVI_SEL field of * HDMI_CTRL register needs to be programmed to 0. */ static boolean hdmi_msm_is_dvi_mode(void) { /* HDMI_CTRL, HDMI_DVI_SEL */ return (HDMI_INP_ND(0x0000) & 0x00000002) ? FALSE : TRUE; } void hdmi_msm_set_mode(boolean power_on) { uint32 reg_val = 0; if (power_on) { /* ENABLE */ reg_val |= 0x00000001; /* Enable the block */ if (external_common_state->hdmi_sink == 0) { /* HDMI_DVI_SEL */ reg_val |= 0x00000002; if (hdmi_msm_state->hdcp_enable) /* HDMI Encryption */ reg_val |= 0x00000004; /* HDMI_CTRL */ HDMI_OUTP(0x0000, reg_val); /* HDMI_DVI_SEL */ reg_val &= ~0x00000002; } else { if (hdmi_msm_state->hdcp_enable) /* HDMI_Encryption_ON */ reg_val |= 0x00000006; else reg_val |= 0x00000002; } } else reg_val = 0x00000002; /* HDMI_CTRL */ HDMI_OUTP(0x0000, reg_val); DEV_DBG("HDMI Core: %s, HDMI_CTRL=0x%08x\n", power_on ? "Enable" : "Disable", reg_val); } static void msm_hdmi_init_ddc(void) { /* 0x0220 HDMI_DDC_SPEED [31:16] PRESCALE prescale = (m * xtal_frequency) / (desired_i2c_speed), where m is multiply factor, default: m = 1 [1:0] THRESHOLD Select threshold to use to determine whether value sampled on SDA is a 1 or 0. Specified in terms of the ratio between the number of sampled ones and the total number of times SDA is sampled. * 0x0: >0 * 0x1: 1/4 of total samples * 0x2: 1/2 of total samples * 0x3: 3/4 of total samples */ /* Configure the Pre-Scale multiplier * Configure the Threshold */ HDMI_OUTP_ND(0x0220, (10 << 16) | (2 << 0)); /* * 0x0224 HDMI_DDC_SETUP * Setting 31:24 bits : Time units to wait before timeout * when clock is being stalled by external sink device */ HDMI_OUTP_ND(0x0224, 0xff000000); /* 0x027C HDMI_DDC_REF [6] REFTIMER_ENABLE Enable the timer * 0: Disable * 1: Enable [15:0] REFTIMER Value to set the register in order to generate DDC strobe. This register counts on HDCP application clock */ /* Enable reference timer * 27 micro-seconds */ HDMI_OUTP_ND(0x027C, (1 << 16) | (27 << 0)); } static int hdmi_msm_ddc_clear_irq(const char *what) { const uint32 time_out = 0xFFFF; uint32 time_out_count, reg_val; /* clear pending and enable interrupt */ time_out_count = time_out; do { --time_out_count; /* HDMI_DDC_INT_CTRL[0x0214] [2] SW_DONE_MK Mask bit for SW_DONE_INT. Set to 1 to enable interrupt. [1] SW_DONE_ACK WRITE ONLY. Acknowledge bit for SW_DONE_INT. Write 1 to clear interrupt. [0] SW_DONE_INT READ ONLY. SW_DONE interrupt status */ /* Clear and Enable DDC interrupt */ /* Write */ HDMI_OUTP_ND(0x0214, (1 << 2) | (1 << 1)); /* Read back */ reg_val = HDMI_INP_ND(0x0214); } while ((reg_val & 0x1) && time_out_count); if (!time_out_count) { DEV_ERR("%s[%s]: timedout\n", __func__, what); return -ETIMEDOUT; } return 0; } static int hdmi_msm_ddc_write(uint32 dev_addr, uint32 offset, const uint8 *data_buf, uint32 data_len, const char *what) { uint32 reg_val, ndx; int status = 0, retry = 10; uint32 time_out_count; if (NULL == data_buf) { status = -EINVAL; DEV_ERR("%s[%s]: invalid input paramter\n", __func__, what); goto error; } again: status = hdmi_msm_ddc_clear_irq(what); if (status) goto error; /* Ensure Device Address has LSB set to 0 to indicate Slave addr read */ dev_addr &= 0xFE; /* 0x0238 HDMI_DDC_DATA [31] INDEX_WRITE WRITE ONLY. To write index field, set this bit to 1 while writing HDMI_DDC_DATA. [23:16] INDEX Use to set index into DDC buffer for next read or current write, or to read index of current read or next write. Writable only when INDEX_WRITE=1. [15:8] DATA Use to fill or read the DDC buffer [0] DATA_RW Select whether buffer access will be a read or write. For writes, address auto-increments on write to HDMI_DDC_DATA. For reads, address autoincrements on reads to HDMI_DDC_DATA. * 0: Write * 1: Read */ /* 1. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #1 * DATA_RW = 0x1 (write) * DATA = linkAddress (primary link address and writing) * INDEX = 0x0 (initial offset into buffer) * INDEX_WRITE = 0x1 (setting initial offset) */ HDMI_OUTP_ND(0x0238, (0x1UL << 31) | (dev_addr << 8)); /* 2. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #2 * DATA_RW = 0x0 (write) * DATA = offsetAddress * INDEX = 0x0 * INDEX_WRITE = 0x0 (auto-increment by hardware) */ HDMI_OUTP_ND(0x0238, offset << 8); /* 3. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #3 * DATA_RW = 0x0 (write) * DATA = data_buf[ndx] * INDEX = 0x0 * INDEX_WRITE = 0x0 (auto-increment by hardware) */ for (ndx = 0; ndx < data_len; ++ndx) HDMI_OUTP_ND(0x0238, ((uint32)data_buf[ndx]) << 8); /* Data setup is complete, now setup the transaction characteristics */ /* 0x0228 HDMI_DDC_TRANS0 [23:16] CNT0 Byte count for first transaction (excluding the first byte, which is usually the address). [13] STOP0 Determines whether a stop bit will be sent after the first transaction * 0: NO STOP * 1: STOP [12] START0 Determines whether a start bit will be sent before the first transaction * 0: NO START * 1: START [8] STOP_ON_NACK0 Determines whether the current transfer will stop if a NACK is received during the first transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW0 Read/write indicator for first transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 4. Write to HDMI_I2C_TRANSACTION0 with the following fields set in order to handle characteristics of portion #1 and portion #2 * RW0 = 0x0 (write) * START0 = 0x1 (insert START bit) * STOP0 = 0x0 (do NOT insert STOP bit) * CNT0 = 0x1 (single byte transaction excluding address) */ HDMI_OUTP_ND(0x0228, (1 << 12) | (1 << 16)); /* 0x022C HDMI_DDC_TRANS1 [23:16] CNT1 Byte count for second transaction (excluding the first byte, which is usually the address). [13] STOP1 Determines whether a stop bit will be sent after the second transaction * 0: NO STOP * 1: STOP [12] START1 Determines whether a start bit will be sent before the second transaction * 0: NO START * 1: START [8] STOP_ON_NACK1 Determines whether the current transfer will stop if a NACK is received during the second transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW1 Read/write indicator for second transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 5. Write to HDMI_I2C_TRANSACTION1 with the following fields set in order to handle characteristics of portion #3 * RW1 = 0x1 (read) * START1 = 0x1 (insert START bit) * STOP1 = 0x1 (insert STOP bit) * CNT1 = data_len (0xN (write N bytes of data)) * Byte count for second transition (excluding the first * Byte which is usually the address) */ HDMI_OUTP_ND(0x022C, (1 << 13) | ((data_len-1) << 16)); /* Trigger the I2C transfer */ /* 0x020C HDMI_DDC_CTRL [21:20] TRANSACTION_CNT Number of transactions to be done in current transfer. * 0x0: transaction0 only * 0x1: transaction0, transaction1 * 0x2: transaction0, transaction1, transaction2 * 0x3: transaction0, transaction1, transaction2, transaction3 [3] SW_STATUS_RESET Write 1 to reset HDMI_DDC_SW_STATUS flags, will reset SW_DONE, ABORTED, TIMEOUT, SW_INTERRUPTED, BUFFER_OVERFLOW, STOPPED_ON_NACK, NACK0, NACK1, NACK2, NACK3 [2] SEND_RESET Set to 1 to send reset sequence (9 clocks with no data) at start of transfer. This sequence is sent after GO is written to 1, before the first transaction only. [1] SOFT_RESET Write 1 to reset DDC controller [0] GO WRITE ONLY. Write 1 to start DDC transfer. */ /* 6. Write to HDMI_I2C_CONTROL to kick off the hardware. * Note that NOTHING has been transmitted on the DDC lines up to this * point. * TRANSACTION_CNT = 0x1 (execute transaction0 followed by * transaction1) * GO = 0x1 (kicks off hardware) */ INIT_COMPLETION(hdmi_msm_state->ddc_sw_done); HDMI_OUTP_ND(0x020C, (1 << 0) | (1 << 20)); time_out_count = wait_for_completion_interruptible_timeout( &hdmi_msm_state->ddc_sw_done, HZ/2); HDMI_OUTP_ND(0x0214, 0x2); if (!time_out_count) { if (retry-- > 0) { DEV_INFO("%s[%s]: failed timout, retry=%d\n", __func__, what, retry); goto again; } status = -ETIMEDOUT; DEV_ERR("%s[%s]: timedout, DDC SW Status=%08x, HW " "Status=%08x, Int Ctrl=%08x\n", __func__, what, HDMI_INP_ND(0x0218), HDMI_INP_ND(0x021C), HDMI_INP_ND(0x0214)); goto error; } /* Read DDC status */ reg_val = HDMI_INP_ND(0x0218); reg_val &= 0x00001000 | 0x00002000 | 0x00004000 | 0x00008000; /* Check if any NACK occurred */ if (reg_val) { if (retry > 1) HDMI_OUTP_ND(0x020C, BIT(3)); /* SW_STATUS_RESET */ else HDMI_OUTP_ND(0x020C, BIT(1)); /* SOFT_RESET */ if (retry-- > 0) { DEV_DBG("%s[%s]: failed NACK=%08x, retry=%d\n", __func__, what, reg_val, retry); msleep(100); goto again; } status = -EIO; DEV_ERR("%s[%s]: failed NACK: %08x\n", __func__, what, reg_val); goto error; } DEV_DBG("%s[%s] success\n", __func__, what); error: return status; } static int hdmi_msm_ddc_read_retry(uint32 dev_addr, uint32 offset, uint8 *data_buf, uint32 data_len, uint32 request_len, int retry, const char *what) { uint32 reg_val, ndx; int status = 0; uint32 time_out_count; int log_retry_fail = retry != 1; if (NULL == data_buf) { status = -EINVAL; DEV_ERR("%s: invalid input paramter\n", __func__); goto error; } again: status = hdmi_msm_ddc_clear_irq(what); if (status) goto error; /* Ensure Device Address has LSB set to 0 to indicate Slave addr read */ dev_addr &= 0xFE; /* 0x0238 HDMI_DDC_DATA [31] INDEX_WRITE WRITE ONLY. To write index field, set this bit to 1 while writing HDMI_DDC_DATA. [23:16] INDEX Use to set index into DDC buffer for next read or current write, or to read index of current read or next write. Writable only when INDEX_WRITE=1. [15:8] DATA Use to fill or read the DDC buffer [0] DATA_RW Select whether buffer access will be a read or write. For writes, address auto-increments on write to HDMI_DDC_DATA. For reads, address autoincrements on reads to HDMI_DDC_DATA. * 0: Write * 1: Read */ /* 1. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #1 * DATA_RW = 0x0 (write) * DATA = linkAddress (primary link address and writing) * INDEX = 0x0 (initial offset into buffer) * INDEX_WRITE = 0x1 (setting initial offset) */ HDMI_OUTP_ND(0x0238, (0x1UL << 31) | (dev_addr << 8)); /* 2. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #2 * DATA_RW = 0x0 (write) * DATA = offsetAddress * INDEX = 0x0 * INDEX_WRITE = 0x0 (auto-increment by hardware) */ HDMI_OUTP_ND(0x0238, offset << 8); /* 3. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #3 * DATA_RW = 0x0 (write) * DATA = linkAddress + 1 (primary link address 0x74 and reading) * INDEX = 0x0 * INDEX_WRITE = 0x0 (auto-increment by hardware) */ HDMI_OUTP_ND(0x0238, (dev_addr | 1) << 8); /* Data setup is complete, now setup the transaction characteristics */ /* 0x0228 HDMI_DDC_TRANS0 [23:16] CNT0 Byte count for first transaction (excluding the first byte, which is usually the address). [13] STOP0 Determines whether a stop bit will be sent after the first transaction * 0: NO STOP * 1: STOP [12] START0 Determines whether a start bit will be sent before the first transaction * 0: NO START * 1: START [8] STOP_ON_NACK0 Determines whether the current transfer will stop if a NACK is received during the first transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW0 Read/write indicator for first transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 4. Write to HDMI_I2C_TRANSACTION0 with the following fields set in order to handle characteristics of portion #1 and portion #2 * RW0 = 0x0 (write) * START0 = 0x1 (insert START bit) * STOP0 = 0x0 (do NOT insert STOP bit) * CNT0 = 0x1 (single byte transaction excluding address) */ HDMI_OUTP_ND(0x0228, (1 << 12) | (1 << 16)); /* 0x022C HDMI_DDC_TRANS1 [23:16] CNT1 Byte count for second transaction (excluding the first byte, which is usually the address). [13] STOP1 Determines whether a stop bit will be sent after the second transaction * 0: NO STOP * 1: STOP [12] START1 Determines whether a start bit will be sent before the second transaction * 0: NO START * 1: START [8] STOP_ON_NACK1 Determines whether the current transfer will stop if a NACK is received during the second transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW1 Read/write indicator for second transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 5. Write to HDMI_I2C_TRANSACTION1 with the following fields set in order to handle characteristics of portion #3 * RW1 = 0x1 (read) * START1 = 0x1 (insert START bit) * STOP1 = 0x1 (insert STOP bit) * CNT1 = data_len (it's 128 (0x80) for a blk read) */ HDMI_OUTP_ND(0x022C, 1 | (1 << 12) | (1 << 13) | (request_len << 16)); /* Trigger the I2C transfer */ /* 0x020C HDMI_DDC_CTRL [21:20] TRANSACTION_CNT Number of transactions to be done in current transfer. * 0x0: transaction0 only * 0x1: transaction0, transaction1 * 0x2: transaction0, transaction1, transaction2 * 0x3: transaction0, transaction1, transaction2, transaction3 [3] SW_STATUS_RESET Write 1 to reset HDMI_DDC_SW_STATUS flags, will reset SW_DONE, ABORTED, TIMEOUT, SW_INTERRUPTED, BUFFER_OVERFLOW, STOPPED_ON_NACK, NACK0, NACK1, NACK2, NACK3 [2] SEND_RESET Set to 1 to send reset sequence (9 clocks with no data) at start of transfer. This sequence is sent after GO is written to 1, before the first transaction only. [1] SOFT_RESET Write 1 to reset DDC controller [0] GO WRITE ONLY. Write 1 to start DDC transfer. */ /* 6. Write to HDMI_I2C_CONTROL to kick off the hardware. * Note that NOTHING has been transmitted on the DDC lines up to this * point. * TRANSACTION_CNT = 0x1 (execute transaction0 followed by * transaction1) * SEND_RESET = Set to 1 to send reset sequence * GO = 0x1 (kicks off hardware) */ INIT_COMPLETION(hdmi_msm_state->ddc_sw_done); HDMI_OUTP_ND(0x020C, (1 << 0) | (1 << 20)); time_out_count = wait_for_completion_interruptible_timeout( &hdmi_msm_state->ddc_sw_done, HZ/2); HDMI_OUTP_ND(0x0214, 0x2); if (!time_out_count) { if (retry-- > 0) { DEV_INFO("%s: failed timout, retry=%d\n", __func__, retry); goto again; } status = -ETIMEDOUT; DEV_ERR("%s: timedout(7), DDC SW Status=%08x, HW " "Status=%08x, Int Ctrl=%08x\n", __func__, HDMI_INP(0x0218), HDMI_INP(0x021C), HDMI_INP(0x0214)); goto error; } /* Read DDC status */ reg_val = HDMI_INP_ND(0x0218); reg_val &= 0x00001000 | 0x00002000 | 0x00004000 | 0x00008000; /* Check if any NACK occurred */ if (reg_val) { HDMI_OUTP_ND(0x020C, BIT(3)); /* SW_STATUS_RESET */ if (retry == 1) HDMI_OUTP_ND(0x020C, BIT(1)); /* SOFT_RESET */ if (retry-- > 0) { DEV_DBG("%s(%s): failed NACK=0x%08x, retry=%d, " "dev-addr=0x%02x, offset=0x%02x, " "length=%d\n", __func__, what, reg_val, retry, dev_addr, offset, data_len); goto again; } status = -EIO; if (log_retry_fail) DEV_ERR("%s(%s): failed NACK=0x%08x, dev-addr=0x%02x, " "offset=0x%02x, length=%d\n", __func__, what, reg_val, dev_addr, offset, data_len); goto error; } /* 0x0238 HDMI_DDC_DATA [31] INDEX_WRITE WRITE ONLY. To write index field, set this bit to 1 while writing HDMI_DDC_DATA. [23:16] INDEX Use to set index into DDC buffer for next read or current write, or to read index of current read or next write. Writable only when INDEX_WRITE=1. [15:8] DATA Use to fill or read the DDC buffer [0] DATA_RW Select whether buffer access will be a read or write. For writes, address auto-increments on write to HDMI_DDC_DATA. For reads, address autoincrements on reads to HDMI_DDC_DATA. * 0: Write * 1: Read */ /* 8. ALL data is now available and waiting in the DDC buffer. * Read HDMI_I2C_DATA with the following fields set * RW = 0x1 (read) * DATA = BCAPS (this is field where data is pulled from) * INDEX = 0x3 (where the data has been placed in buffer by hardware) * INDEX_WRITE = 0x1 (explicitly define offset) */ /* Write this data to DDC buffer */ HDMI_OUTP_ND(0x0238, 0x1 | (3 << 16) | (1 << 31)); /* Discard first byte */ HDMI_INP_ND(0x0238); for (ndx = 0; ndx < data_len; ++ndx) { reg_val = HDMI_INP_ND(0x0238); data_buf[ndx] = (uint8) ((reg_val & 0x0000FF00) >> 8); } DEV_DBG("%s[%s] success\n", __func__, what); error: return status; } static int hdmi_msm_ddc_read_edid_seg(uint32 dev_addr, uint32 offset, uint8 *data_buf, uint32 data_len, uint32 request_len, int retry, const char *what) { uint32 reg_val, ndx; int status = 0; uint32 time_out_count; int log_retry_fail = retry != 1; int seg_addr = 0x60, seg_num = 0x01; if (NULL == data_buf) { status = -EINVAL; DEV_ERR("%s: invalid input paramter\n", __func__); goto error; } again: status = hdmi_msm_ddc_clear_irq(what); if (status) goto error; /* Ensure Device Address has LSB set to 0 to indicate Slave addr read */ dev_addr &= 0xFE; /* 0x0238 HDMI_DDC_DATA [31] INDEX_WRITE WRITE ONLY. To write index field, set this bit to 1 while writing HDMI_DDC_DATA. [23:16] INDEX Use to set index into DDC buffer for next read or current write, or to read index of current read or next write. Writable only when INDEX_WRITE=1. [15:8] DATA Use to fill or read the DDC buffer [0] DATA_RW Select whether buffer access will be a read or write. For writes, address auto-increments on write to HDMI_DDC_DATA. For reads, address autoincrements on reads to HDMI_DDC_DATA. * 0: Write * 1: Read */ /* 1. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #1 * DATA_RW = 0x0 (write) * DATA = linkAddress (primary link address and writing) * INDEX = 0x0 (initial offset into buffer) * INDEX_WRITE = 0x1 (setting initial offset) */ HDMI_OUTP_ND(0x0238, (0x1UL << 31) | (seg_addr << 8)); /* 2. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #2 * DATA_RW = 0x0 (write) * DATA = offsetAddress * INDEX = 0x0 * INDEX_WRITE = 0x0 (auto-increment by hardware) */ HDMI_OUTP_ND(0x0238, seg_num << 8); /* 3. Write to HDMI_I2C_DATA with the following fields set in order to * handle portion #3 * DATA_RW = 0x0 (write) * DATA = linkAddress + 1 (primary link address 0x74 and reading) * INDEX = 0x0 * INDEX_WRITE = 0x0 (auto-increment by hardware) */ HDMI_OUTP_ND(0x0238, dev_addr << 8); HDMI_OUTP_ND(0x0238, offset << 8); HDMI_OUTP_ND(0x0238, (dev_addr | 1) << 8); /* Data setup is complete, now setup the transaction characteristics */ /* 0x0228 HDMI_DDC_TRANS0 [23:16] CNT0 Byte count for first transaction (excluding the first byte, which is usually the address). [13] STOP0 Determines whether a stop bit will be sent after the first transaction * 0: NO STOP * 1: STOP [12] START0 Determines whether a start bit will be sent before the first transaction * 0: NO START * 1: START [8] STOP_ON_NACK0 Determines whether the current transfer will stop if a NACK is received during the first transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW0 Read/write indicator for first transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 4. Write to HDMI_I2C_TRANSACTION0 with the following fields set in order to handle characteristics of portion #1 and portion #2 * RW0 = 0x0 (write) * START0 = 0x1 (insert START bit) * STOP0 = 0x0 (do NOT insert STOP bit) * CNT0 = 0x1 (single byte transaction excluding address) */ HDMI_OUTP_ND(0x0228, (1 << 12) | (1 << 16)); /* 0x022C HDMI_DDC_TRANS1 [23:16] CNT1 Byte count for second transaction (excluding the first byte, which is usually the address). [13] STOP1 Determines whether a stop bit will be sent after the second transaction * 0: NO STOP * 1: STOP [12] START1 Determines whether a start bit will be sent before the second transaction * 0: NO START * 1: START [8] STOP_ON_NACK1 Determines whether the current transfer will stop if a NACK is received during the second transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW1 Read/write indicator for second transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 5. Write to HDMI_I2C_TRANSACTION1 with the following fields set in order to handle characteristics of portion #3 * RW1 = 0x1 (read) * START1 = 0x1 (insert START bit) * STOP1 = 0x1 (insert STOP bit) * CNT1 = data_len (it's 128 (0x80) for a blk read) */ HDMI_OUTP_ND(0x022C, (1 << 12) | (1 << 16)); /* 0x022C HDMI_DDC_TRANS2 [23:16] CNT1 Byte count for second transaction (excluding the first byte, which is usually the address). [13] STOP1 Determines whether a stop bit will be sent after the second transaction * 0: NO STOP * 1: STOP [12] START1 Determines whether a start bit will be sent before the second transaction * 0: NO START * 1: START [8] STOP_ON_NACK1 Determines whether the current transfer will stop if a NACK is received during the second transaction (current transaction always stops). * 0: STOP CURRENT TRANSACTION, GO TO NEXT TRANSACTION * 1: STOP ALL TRANSACTIONS, SEND STOP BIT [0] RW1 Read/write indicator for second transaction - set to 0 for write, 1 for read. This bit only controls HDMI_DDC behaviour - the R/W bit in the transaction is programmed into the DDC buffer as the LSB of the address byte. * 0: WRITE * 1: READ */ /* 5. Write to HDMI_I2C_TRANSACTION1 with the following fields set in order to handle characteristics of portion #3 * RW1 = 0x1 (read) * START1 = 0x1 (insert START bit) * STOP1 = 0x1 (insert STOP bit) * CNT1 = data_len (it's 128 (0x80) for a blk read) */ HDMI_OUTP_ND(0x0230, 1 | (1 << 12) | (1 << 13) | (request_len << 16)); /* Trigger the I2C transfer */ /* 0x020C HDMI_DDC_CTRL [21:20] TRANSACTION_CNT Number of transactions to be done in current transfer. * 0x0: transaction0 only * 0x1: transaction0, transaction1 * 0x2: transaction0, transaction1, transaction2 * 0x3: transaction0, transaction1, transaction2, transaction3 [3] SW_STATUS_RESET Write 1 to reset HDMI_DDC_SW_STATUS flags, will reset SW_DONE, ABORTED, TIMEOUT, SW_INTERRUPTED, BUFFER_OVERFLOW, STOPPED_ON_NACK, NACK0, NACK1, NACK2, NACK3 [2] SEND_RESET Set to 1 to send reset sequence (9 clocks with no data) at start of transfer. This sequence is sent after GO is written to 1, before the first transaction only. [1] SOFT_RESET Write 1 to reset DDC controller [0] GO WRITE ONLY. Write 1 to start DDC transfer. */ /* 6. Write to HDMI_I2C_CONTROL to kick off the hardware. * Note that NOTHING has been transmitted on the DDC lines up to this * point. * TRANSACTION_CNT = 0x2 (execute transaction0 followed by * transaction1) * GO = 0x1 (kicks off hardware) */ INIT_COMPLETION(hdmi_msm_state->ddc_sw_done); HDMI_OUTP_ND(0x020C, (1 << 0) | (2 << 20)); time_out_count = wait_for_completion_interruptible_timeout( &hdmi_msm_state->ddc_sw_done, HZ/2); HDMI_OUTP_ND(0x0214, 0x2); if (!time_out_count) { if (retry-- > 0) { DEV_INFO("%s: failed timout, retry=%d\n", __func__, retry); goto again; } status = -ETIMEDOUT; DEV_ERR("%s: timedout(7), DDC SW Status=%08x, HW " "Status=%08x, Int Ctrl=%08x\n", __func__, HDMI_INP(0x0218), HDMI_INP(0x021C), HDMI_INP(0x0214)); goto error; } /* Read DDC status */ reg_val = HDMI_INP_ND(0x0218); reg_val &= 0x00001000 | 0x00002000 | 0x00004000 | 0x00008000; /* Check if any NACK occurred */ if (reg_val) { HDMI_OUTP_ND(0x020C, BIT(3)); /* SW_STATUS_RESET */ if (retry == 1) HDMI_OUTP_ND(0x020C, BIT(1)); /* SOFT_RESET */ if (retry-- > 0) { DEV_DBG("%s(%s): failed NACK=0x%08x, retry=%d, " "dev-addr=0x%02x, offset=0x%02x, " "length=%d\n", __func__, what, reg_val, retry, dev_addr, offset, data_len); goto again; } status = -EIO; if (log_retry_fail) DEV_ERR("%s(%s): failed NACK=0x%08x, dev-addr=0x%02x, " "offset=0x%02x, length=%d\n", __func__, what, reg_val, dev_addr, offset, data_len); goto error; } /* 0x0238 HDMI_DDC_DATA [31] INDEX_WRITE WRITE ONLY. To write index field, set this bit to 1 while writing HDMI_DDC_DATA. [23:16] INDEX Use to set index into DDC buffer for next read or current write, or to read index of current read or next write. Writable only when INDEX_WRITE=1. [15:8] DATA Use to fill or read the DDC buffer [0] DATA_RW Select whether buffer access will be a read or write. For writes, address auto-increments on write to HDMI_DDC_DATA. For reads, address autoincrements on reads to HDMI_DDC_DATA. * 0: Write * 1: Read */ /* 8. ALL data is now available and waiting in the DDC buffer. * Read HDMI_I2C_DATA with the following fields set * RW = 0x1 (read) * DATA = BCAPS (this is field where data is pulled from) * INDEX = 0x5 (where the data has been placed in buffer by hardware) * INDEX_WRITE = 0x1 (explicitly define offset) */ /* Write this data to DDC buffer */ HDMI_OUTP_ND(0x0238, 0x1 | (5 << 16) | (1 << 31)); /* Discard first byte */ HDMI_INP_ND(0x0238); for (ndx = 0; ndx < data_len; ++ndx) { reg_val = HDMI_INP_ND(0x0238); data_buf[ndx] = (uint8) ((reg_val & 0x0000FF00) >> 8); } DEV_DBG("%s[%s] success\n", __func__, what); error: return status; } static int hdmi_msm_ddc_read(uint32 dev_addr, uint32 offset, uint8 *data_buf, uint32 data_len, int retry, const char *what, boolean no_align) { int ret = hdmi_msm_ddc_read_retry(dev_addr, offset, data_buf, data_len, data_len, retry, what); if (!ret) return 0; if (no_align) { return hdmi_msm_ddc_read_retry(dev_addr, offset, data_buf, data_len, data_len, retry, what); } else { return hdmi_msm_ddc_read_retry(dev_addr, offset, data_buf, data_len, 32 * ((data_len + 31) / 32), retry, what); } } static int hdmi_msm_read_edid_block(int block, uint8 *edid_buf) { int i, rc = 0; int block_size = 0x80; do { DEV_DBG("EDID: reading block(%d) with block-size=%d\n", block, block_size); for (i = 0; i < 0x80; i += block_size) { /*Read EDID twice with 32bit alighnment too */ if (block < 2) { rc = hdmi_msm_ddc_read(0xA0, block*0x80 + i, edid_buf+i, block_size, 1, "EDID", FALSE); } else { rc = hdmi_msm_ddc_read_edid_seg(0xA0, block*0x80 + i, edid_buf+i, block_size, block_size, 1, "EDID"); } if (rc) break; } block_size /= 2; } while (rc && (block_size >= 16)); return rc; } static int hdmi_msm_read_edid(void) { int status; msm_hdmi_init_ddc(); /* Looks like we need to turn on HDMI engine before any * DDC transaction */ if (!hdmi_msm_is_power_on()) { DEV_ERR("%s: failed: HDMI power is off", __func__); status = -ENXIO; goto error; } external_common_state->read_edid_block = hdmi_msm_read_edid_block; status = hdmi_common_read_edid(); if (!status) DEV_DBG("EDID: successfully read\n"); error: return status; } static void hdcp_auth_info(uint32 auth_info) { if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } switch (auth_info) { case 0: DEV_INFO("%s: None", __func__); break; case 1: DEV_INFO("%s: Software Disabled Authentication", __func__); break; case 2: DEV_INFO("%s: An Written", __func__); break; case 3: DEV_INFO("%s: Invalid Aksv", __func__); break; case 4: DEV_INFO("%s: Invalid Bksv", __func__); break; case 5: DEV_INFO("%s: RI Mismatch (including RO)", __func__); break; case 6: DEV_INFO("%s: consecutive Pj Mismatches", __func__); break; case 7: DEV_INFO("%s: HPD Disconnect", __func__); break; case 8: default: DEV_INFO("%s: Reserved", __func__); break; } } static void hdcp_key_state(uint32 key_state) { if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } switch (key_state) { case 0: DEV_WARN("%s: No HDCP Keys", __func__); break; case 1: DEV_WARN("%s: Not Checked", __func__); break; case 2: DEV_DBG("%s: Checking", __func__); break; case 3: DEV_DBG("%s: HDCP Keys Valid", __func__); break; case 4: DEV_WARN("%s: AKSV not valid", __func__); break; case 5: DEV_WARN("%s: Checksum Mismatch", __func__); break; case 6: DEV_DBG("%s: Production AKSV" "with ENABLE_USER_DEFINED_AN=1", __func__); break; case 7: default: DEV_INFO("%s: Reserved", __func__); break; } } static int hdmi_msm_count_one(uint8 *array, uint8 len) { int i, j, count = 0; for (i = 0; i < len; i++) for (j = 0; j < 8; j++) count += (((array[i] >> j) & 0x1) ? 1 : 0); return count; } static void hdcp_deauthenticate(void) { int hdcp_link_status = HDMI_INP(0x011C); if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } /* Disable HDCP interrupts */ HDMI_OUTP(0x0118, 0x0); mutex_lock(&hdcp_auth_state_mutex); external_common_state->hdcp_active = FALSE; mutex_unlock(&hdcp_auth_state_mutex); /* 0x0130 HDCP_RESET [0] LINK0_DEAUTHENTICATE */ HDMI_OUTP(0x0130, 0x1); /* 0x0110 HDCP_CTRL [8] ENCRYPTION_ENABLE [0] ENABLE */ /* encryption_enable = 0 | hdcp block enable = 1 */ HDMI_OUTP(0x0110, 0x0); if (hdcp_link_status & 0x00000004) hdcp_auth_info((hdcp_link_status & 0x000000F0) >> 4); } static void check_and_clear_HDCP_DDC_Failure(void) { int hdcp_ddc_ctrl1_reg; int hdcp_ddc_status; int failure; int nack0; if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } /* * Check for any DDC transfer failures * 0x0128 HDCP_DDC_STATUS * [16] FAILED Indicates that the last HDCP HW DDC transer * failed. This occurs when a transfer is * attempted with HDCP DDC disabled * (HDCP_DDC_DISABLE=1) or the number of retries * match HDCP_DDC_RETRY_CNT * * [14] NACK0 Indicates that the last HDCP HW DDC transfer * was aborted due to a NACK on the first * transaction - cleared by writing 0 to GO bit */ hdcp_ddc_status = HDMI_INP(HDCP_DDC_STATUS); failure = (hdcp_ddc_status >> 16) & 0x1; nack0 = (hdcp_ddc_status >> 14) & 0x1; DEV_DBG("%s: On Entry: HDCP_DDC_STATUS = 0x%x, FAILURE = %d," "NACK0 = %d\n", __func__ , hdcp_ddc_status, failure, nack0); if (failure == 0x1) { /* * Indicates that the last HDCP HW DDC transfer failed. * This occurs when a transfer is attempted with HDCP DDC * disabled (HDCP_DDC_DISABLE=1) or the number of retries * matches HDCP_DDC_RETRY_CNT. * Failure occured, let's clear it. */ DEV_INFO("%s: DDC failure detected. HDCP_DDC_STATUS=0x%08x\n", __func__, hdcp_ddc_status); /* * First, Disable DDC * 0x0120 HDCP_DDC_CTRL_0 * [0] DDC_DISABLE Determines whether HDCP Ri and Pj reads * are done unassisted by hardware or by * software via HDMI_DDC (HDCP provides * interrupts to request software * transfers) * 0 : Use Hardware DDC * 1 : Use Software DDC */ HDMI_OUTP(HDCP_DDC_CTRL_0, 0x1); /* * ACK the Failure to Clear it * 0x0124 HDCP_DDC_CTRL_1 * [0] DDC_FAILED_ACK Write 1 to clear * HDCP_STATUS.HDCP_DDC_FAILED */ hdcp_ddc_ctrl1_reg = HDMI_INP(HDCP_DDC_CTRL_1); HDMI_OUTP(HDCP_DDC_CTRL_1, hdcp_ddc_ctrl1_reg | 0x1); /* Check if the FAILURE got Cleared */ hdcp_ddc_status = HDMI_INP(HDCP_DDC_STATUS); hdcp_ddc_status = (hdcp_ddc_status >> 16) & 0x1; if (hdcp_ddc_status == 0x0) { DEV_INFO("%s: HDCP DDC Failure has been cleared\n", __func__); } else { DEV_WARN("%s: Error: HDCP DDC Failure DID NOT get" "cleared\n", __func__); } /* Re-Enable HDCP DDC */ HDMI_OUTP(HDCP_DDC_CTRL_0, 0x0); } if (nack0 == 0x1) { /* * 0x020C HDMI_DDC_CTRL * [3] SW_STATUS_RESET Write 1 to reset HDMI_DDC_SW_STATUS * flags, will reset SW_DONE, ABORTED, * TIMEOUT, SW_INTERRUPTED, * BUFFER_OVERFLOW, STOPPED_ON_NACK, NACK0, * NACK1, NACK2, NACK3 */ HDMI_OUTP_ND(HDMI_DDC_CTRL, HDMI_INP(HDMI_DDC_CTRL) | (0x1 << 3)); msleep(20); HDMI_OUTP_ND(HDMI_DDC_CTRL, HDMI_INP(HDMI_DDC_CTRL) & ~(0x1 << 3)); } hdcp_ddc_status = HDMI_INP(HDCP_DDC_STATUS); failure = (hdcp_ddc_status >> 16) & 0x1; nack0 = (hdcp_ddc_status >> 14) & 0x1; DEV_DBG("%s: On Exit: HDCP_DDC_STATUS = 0x%x, FAILURE = %d," "NACK0 = %d\n", __func__ , hdcp_ddc_status, failure, nack0); } static int hdcp_authentication_part1(void) { int ret = 0; boolean is_match; boolean is_part1_done = FALSE; uint32 timeout_count; uint8 bcaps; uint8 aksv[5]; uint32 qfprom_aksv_0, qfprom_aksv_1, link0_aksv_0, link0_aksv_1; uint8 bksv[5]; uint32 link0_bksv_0, link0_bksv_1; uint8 an[8]; uint32 link0_an_0, link0_an_1; uint32 hpd_int_status, hpd_int_ctrl; static uint8 buf[0xFF]; memset(buf, 0, sizeof(buf)); if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return 0; } if (!is_part1_done) { is_part1_done = TRUE; /* Fetch aksv from QFprom, this info should be public. */ qfprom_aksv_0 = inpdw(QFPROM_BASE + 0x000060D8); qfprom_aksv_1 = inpdw(QFPROM_BASE + 0x000060DC); /* copy an and aksv to byte arrays for transmission */ aksv[0] = qfprom_aksv_0 & 0xFF; aksv[1] = (qfprom_aksv_0 >> 8) & 0xFF; aksv[2] = (qfprom_aksv_0 >> 16) & 0xFF; aksv[3] = (qfprom_aksv_0 >> 24) & 0xFF; aksv[4] = qfprom_aksv_1 & 0xFF; /* check there are 20 ones in AKSV */ if (hdmi_msm_count_one(aksv, 5) != 20) { DEV_ERR("HDCP: AKSV read from QFPROM doesn't have " "20 1's and 20 0's, FAIL (AKSV=%02x%08x)\n", qfprom_aksv_1, qfprom_aksv_0); ret = -EINVAL; goto error; } DEV_DBG("HDCP: AKSV=%02x%08x\n", qfprom_aksv_1, qfprom_aksv_0); /* 0x0288 HDCP_SW_LOWER_AKSV [31:0] LOWER_AKSV */ /* 0x0284 HDCP_SW_UPPER_AKSV [7:0] UPPER_AKSV */ /* This is the lower 32 bits of the SW * injected AKSV value(AKSV[31:0]) read * from the EFUSE. It is needed for HDCP * authentication and must be written * before enabling HDCP. */ HDMI_OUTP(0x0288, qfprom_aksv_0); HDMI_OUTP(0x0284, qfprom_aksv_1); msm_hdmi_init_ddc(); /* read Bcaps at 0x40 in HDCP Port */ ret = hdmi_msm_ddc_read(0x74, 0x40, &bcaps, 1, 5, "Bcaps", TRUE); if (ret) { DEV_ERR("%s(%d): Read Bcaps failed", __func__, __LINE__); goto error; } DEV_DBG("HDCP: Bcaps=%02x\n", bcaps); /* HDCP setup prior to HDCP enabled */ /* 0x0148 HDCP_RCVPORT_DATA4 [15:8] LINK0_AINFO [7:0] LINK0_AKSV_1 */ /* LINK0_AINFO = 0x2 FEATURE 1.1 on. * = 0x0 FEATURE 1.1 off*/ HDMI_OUTP(0x0148, 0x0); /* 0x012C HDCP_ENTROPY_CTRL0 [31:0] BITS_OF_INFLUENCE_0 */ /* 0x025C HDCP_ENTROPY_CTRL1 [31:0] BITS_OF_INFLUENCE_1 */ HDMI_OUTP(0x012C, 0xB1FFB0FF); HDMI_OUTP(0x025C, 0xF00DFACE); /* 0x0114 HDCP_DEBUG_CTRL [2] DEBUG_RNG_CIPHER else default 0 */ HDMI_OUTP(0x0114, HDMI_INP(0x0114) & 0xFFFFFFFB); /* 0x0110 HDCP_CTRL [8] ENCRYPTION_ENABLE [0] ENABLE */ /* Enable HDCP. Encryption should be enabled after reading R0 */ HDMI_OUTP(0x0110, BIT(0)); /* * Check to see if a HDCP DDC Failure is indicated in * HDCP_DDC_STATUS. If yes, clear it. */ check_and_clear_HDCP_DDC_Failure(); /* 0x0118 HDCP_INT_CTRL * [2] AUTH_SUCCESS_MASK [R/W] Mask bit for\ * HDCP Authentication * Success interrupt - set to 1 to enable interrupt * * [6] AUTH_FAIL_MASK [R/W] Mask bit for HDCP * Authentication * Lost interrupt set to 1 to enable interrupt * * [7] AUTH_FAIL_INFO_ACK [W] Acknwledge bit for HDCP * Auth Failure Info field - write 1 to clear * * [10] DDC_XFER_REQ_MASK [R/W] Mask bit for HDCP\ * DDC Transfer * Request interrupt - set to 1 to enable interrupt * * [14] DDC_XFER_DONE_MASK [R/W] Mask bit for HDCP\ * DDC Transfer * done interrupt - set to 1 to enable interrupt */ /* enable all HDCP ints */ HDMI_OUTP(0x0118, (1 << 2) | (1 << 6) | (1 << 7)); /* 0x011C HDCP_LINK0_STATUS [8] AN_0_READY [9] AN_1_READY */ /* wait for an0 and an1 ready bits to be set in LINK0_STATUS */ mutex_lock(&hdcp_auth_state_mutex); timeout_count = 100; while (((HDMI_INP_ND(0x011C) & (0x3 << 8)) != (0x3 << 8)) && timeout_count--) msleep(20); if (!timeout_count) { ret = -ETIMEDOUT; DEV_ERR("%s(%d): timedout, An0=%d, An1=%d\n", __func__, __LINE__, (HDMI_INP_ND(0x011C) & BIT(8)) >> 8, (HDMI_INP_ND(0x011C) & BIT(9)) >> 9); mutex_unlock(&hdcp_auth_state_mutex); goto error; } /* 0x0168 HDCP_RCVPORT_DATA12 [23:8] BSTATUS [7:0] BCAPS */ HDMI_OUTP(0x0168, bcaps); /* 0x014C HDCP_RCVPORT_DATA5 [31:0] LINK0_AN_0 */ /* read an0 calculation */ link0_an_0 = HDMI_INP(0x014C); /* 0x0150 HDCP_RCVPORT_DATA6 [31:0] LINK0_AN_1 */ /* read an1 calculation */ link0_an_1 = HDMI_INP(0x0150); mutex_unlock(&hdcp_auth_state_mutex); /* three bits 28..30 */ hdcp_key_state((HDMI_INP(0x011C) >> 28) & 0x7); /* 0x0144 HDCP_RCVPORT_DATA3 [31:0] LINK0_AKSV_0 public key 0x0148 HDCP_RCVPORT_DATA4 [15:8] LINK0_AINFO [7:0] LINK0_AKSV_1 public key */ link0_aksv_0 = HDMI_INP(0x0144); link0_aksv_1 = HDMI_INP(0x0148); /* copy an and aksv to byte arrays for transmission */ aksv[0] = link0_aksv_0 & 0xFF; aksv[1] = (link0_aksv_0 >> 8) & 0xFF; aksv[2] = (link0_aksv_0 >> 16) & 0xFF; aksv[3] = (link0_aksv_0 >> 24) & 0xFF; aksv[4] = link0_aksv_1 & 0xFF; an[0] = link0_an_0 & 0xFF; an[1] = (link0_an_0 >> 8) & 0xFF; an[2] = (link0_an_0 >> 16) & 0xFF; an[3] = (link0_an_0 >> 24) & 0xFF; an[4] = link0_an_1 & 0xFF; an[5] = (link0_an_1 >> 8) & 0xFF; an[6] = (link0_an_1 >> 16) & 0xFF; an[7] = (link0_an_1 >> 24) & 0xFF; /* Write An 8 bytes to offset 0x18 */ ret = hdmi_msm_ddc_write(0x74, 0x18, an, 8, "An"); if (ret) { DEV_ERR("%s(%d): Write An failed", __func__, __LINE__); goto error; } /* Write Aksv 5 bytes to offset 0x10 */ ret = hdmi_msm_ddc_write(0x74, 0x10, aksv, 5, "Aksv"); if (ret) { DEV_ERR("%s(%d): Write Aksv failed", __func__, __LINE__); goto error; } DEV_DBG("HDCP: Link0-AKSV=%02x%08x\n", link0_aksv_1 & 0xFF, link0_aksv_0); /* Read Bksv 5 bytes at 0x00 in HDCP port */ ret = hdmi_msm_ddc_read(0x74, 0x00, bksv, 5, 5, "Bksv", TRUE); if (ret) { DEV_ERR("%s(%d): Read BKSV failed", __func__, __LINE__); goto error; } /* check there are 20 ones in BKSV */ if (hdmi_msm_count_one(bksv, 5) != 20) { DEV_ERR("HDCP: BKSV read from Sink doesn't have " "20 1's and 20 0's, FAIL (BKSV=" "%02x%02x%02x%02x%02x)\n", bksv[4], bksv[3], bksv[2], bksv[1], bksv[0]); ret = -EINVAL; goto error; } link0_bksv_0 = bksv[3]; link0_bksv_0 = (link0_bksv_0 << 8) | bksv[2]; link0_bksv_0 = (link0_bksv_0 << 8) | bksv[1]; link0_bksv_0 = (link0_bksv_0 << 8) | bksv[0]; link0_bksv_1 = bksv[4]; DEV_DBG("HDCP: BKSV=%02x%08x\n", link0_bksv_1, link0_bksv_0); /* 0x0134 HDCP_RCVPORT_DATA0 [31:0] LINK0_BKSV_0 */ HDMI_OUTP(0x0134, link0_bksv_0); /* 0x0138 HDCP_RCVPORT_DATA1 [31:0] LINK0_BKSV_1 */ HDMI_OUTP(0x0138, link0_bksv_1); DEV_DBG("HDCP: Link0-BKSV=%02x%08x\n", link0_bksv_1, link0_bksv_0); /* HDMI_HPD_INT_STATUS[0x0250] */ hpd_int_status = HDMI_INP_ND(0x0250); /* HDMI_HPD_INT_CTRL[0x0254] */ hpd_int_ctrl = HDMI_INP_ND(0x0254); DEV_DBG("[SR-DEUG]: HPD_INTR_CTRL=[%u] HPD_INTR_STATUS=[%u] " "before reading R0'\n", hpd_int_ctrl, hpd_int_status); /* * HDCP Compliace Test case 1B-01: * Wait here until all the ksv bytes have been * read from the KSV FIFO register. */ msleep(125); /* Reading R0' 2 bytes at offset 0x08 */ ret = hdmi_msm_ddc_read(0x74, 0x08, buf, 2, 5, "RO'", TRUE); if (ret) { DEV_ERR("%s(%d): Read RO's failed", __func__, __LINE__); goto error; } DEV_DBG("HDCP: R0'=%02x%02x\n", buf[1], buf[0]); INIT_COMPLETION(hdmi_msm_state->hdcp_success_done); /* 0x013C HDCP_RCVPORT_DATA2_0 [15:0] LINK0_RI */ HDMI_OUTP(0x013C, (((uint32)buf[1]) << 8) | buf[0]); timeout_count = wait_for_completion_interruptible_timeout( &hdmi_msm_state->hdcp_success_done, HZ*2); if (!timeout_count) { ret = -ETIMEDOUT; is_match = HDMI_INP(0x011C) & BIT(12); DEV_ERR("%s(%d): timedout, Link0=<%s>\n", __func__, __LINE__, is_match ? "RI_MATCH" : "No RI Match INTR in time"); if (!is_match) goto error; } /* 0x011C HDCP_LINK0_STATUS [12] RI_MATCHES [0] MISMATCH, [1] MATCH [0] AUTH_SUCCESS */ /* Checking for RI, R0 Match */ /* RI_MATCHES */ if ((HDMI_INP(0x011C) & BIT(12)) != BIT(12)) { ret = -EINVAL; DEV_ERR("%s: HDCP_LINK0_STATUS[RI_MATCHES]: MISMATCH\n", __func__); goto error; } /* Enable HDCP Encryption */ HDMI_OUTP(0x0110, BIT(0) | BIT(8)); DEV_INFO("HDCP: authentication part I, successful\n"); is_part1_done = FALSE; return 0; error: DEV_ERR("[%s]: HDCP Reauthentication\n", __func__); is_part1_done = FALSE; return ret; } else { return 1; } } static int hdmi_msm_transfer_v_h(void) { /* Read V'.HO 4 Byte at offset 0x20 */ char what[20]; int ret; uint8 buf[4]; if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return 0; } snprintf(what, sizeof(what), "V' H0"); ret = hdmi_msm_ddc_read(0x74, 0x20, buf, 4, 5, what, TRUE); if (ret) { DEV_ERR("%s: Read %s failed", __func__, what); return ret; } DEV_DBG("buf[0]= %x , buf[1] = %x , buf[2] = %x , buf[3] = %x\n ", buf[0] , buf[1] , buf[2] , buf[3]); /* 0x0154 HDCP_RCVPORT_DATA7 [31:0] V_HO */ HDMI_OUTP(0x0154 , (buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0])); snprintf(what, sizeof(what), "V' H1"); ret = hdmi_msm_ddc_read(0x74, 0x24, buf, 4, 5, what, TRUE); if (ret) { DEV_ERR("%s: Read %s failed", __func__, what); return ret; } DEV_DBG("buf[0]= %x , buf[1] = %x , buf[2] = %x , buf[3] = %x\n ", buf[0] , buf[1] , buf[2] , buf[3]); /* 0x0158 HDCP_RCVPORT_ DATA8 [31:0] V_H1 */ HDMI_OUTP(0x0158, (buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0])); snprintf(what, sizeof(what), "V' H2"); ret = hdmi_msm_ddc_read(0x74, 0x28, buf, 4, 5, what, TRUE); if (ret) { DEV_ERR("%s: Read %s failed", __func__, what); return ret; } DEV_DBG("buf[0]= %x , buf[1] = %x , buf[2] = %x , buf[3] = %x\n ", buf[0] , buf[1] , buf[2] , buf[3]); /* 0x015c HDCP_RCVPORT_DATA9 [31:0] V_H2 */ HDMI_OUTP(0x015c , (buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0])); snprintf(what, sizeof(what), "V' H3"); ret = hdmi_msm_ddc_read(0x74, 0x2c, buf, 4, 5, what, TRUE); if (ret) { DEV_ERR("%s: Read %s failed", __func__, what); return ret; } DEV_DBG("buf[0]= %x , buf[1] = %x , buf[2] = %x , buf[3] = %x\n ", buf[0] , buf[1] , buf[2] , buf[3]); /* 0x0160 HDCP_RCVPORT_DATA10 [31:0] V_H3 */ HDMI_OUTP(0x0160, (buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0])); snprintf(what, sizeof(what), "V' H4"); ret = hdmi_msm_ddc_read(0x74, 0x30, buf, 4, 5, what, TRUE); if (ret) { DEV_ERR("%s: Read %s failed", __func__, what); return ret; } DEV_DBG("buf[0]= %x , buf[1] = %x , buf[2] = %x , buf[3] = %x\n ", buf[0] , buf[1] , buf[2] , buf[3]); /* 0x0164 HDCP_RCVPORT_DATA11 [31:0] V_H4 */ HDMI_OUTP(0x0164, (buf[3] << 24 | buf[2] << 16 | buf[1] << 8 | buf[0])); return 0; } static int hdcp_authentication_part2(void) { int ret = 0; uint32 timeout_count; int i = 0; int cnt = 0; uint bstatus; uint8 bcaps; uint32 down_stream_devices; uint32 ksv_bytes; static uint8 buf[0xFF]; static uint8 kvs_fifo[5 * 127]; boolean max_devs_exceeded = 0; boolean max_cascade_exceeded = 0; boolean ksv_done = FALSE; if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return 0; } memset(buf, 0, sizeof(buf)); memset(kvs_fifo, 0, sizeof(kvs_fifo)); /* wait until READY bit is set in bcaps */ timeout_count = 50; do { timeout_count--; /* read bcaps 1 Byte at offset 0x40 */ ret = hdmi_msm_ddc_read(0x74, 0x40, &bcaps, 1, 1, "Bcaps", FALSE); if (ret) { DEV_ERR("%s(%d): Read Bcaps failed", __func__, __LINE__); goto error; } msleep(100); } while ((0 == (bcaps & 0x20)) && timeout_count); /* READY (Bit 5) */ if (!timeout_count) { ret = -ETIMEDOUT; DEV_ERR("%s:timedout(1)", __func__); goto error; } /* read bstatus 2 bytes at offset 0x41 */ ret = hdmi_msm_ddc_read(0x74, 0x41, buf, 2, 5, "Bstatus", FALSE); if (ret) { DEV_ERR("%s(%d): Read Bstatus failed", __func__, __LINE__); goto error; } bstatus = buf[1]; bstatus = (bstatus << 8) | buf[0]; /* 0x0168 DCP_RCVPORT_DATA12 [7:0] BCAPS [23:8 BSTATUS */ HDMI_OUTP(0x0168, bcaps | (bstatus << 8)); /* BSTATUS [6:0] DEVICE_COUNT Number of HDMI device attached to repeater * - see HDCP spec */ down_stream_devices = bstatus & 0x7F; if (down_stream_devices == 0x0) { /* There isn't any devices attaced to the Repeater */ DEV_ERR("%s: there isn't any devices attached to the " "Repeater\n", __func__); ret = -EINVAL; goto error; } /* * HDCP Compliance 1B-05: * Check if no. of devices connected to repeater * exceed max_devices_connected from bit 7 of Bstatus. */ max_devs_exceeded = (bstatus & 0x80) >> 7; if (max_devs_exceeded == 0x01) { DEV_ERR("%s: Number of devs connected to repeater " "exceeds max_devs\n", __func__); ret = -EINVAL; goto hdcp_error; } /* * HDCP Compliance 1B-06: * Check if no. of cascade connected to repeater * exceed max_cascade_connected from bit 11 of Bstatus. */ max_cascade_exceeded = (bstatus & 0x800) >> 11; if (max_cascade_exceeded == 0x01) { DEV_ERR("%s: Number of cascade connected to repeater " "exceeds max_cascade\n", __func__); ret = -EINVAL; goto hdcp_error; } /* Read KSV FIFO over DDC * Key Slection vector FIFO * Used to pull downstream KSVs from HDCP Repeaters. * All bytes (DEVICE_COUNT * 5) must be read in a single, * auto incrementing access. * All bytes read as 0x00 for HDCP Receivers that are not * HDCP Repeaters (REPEATER == 0). */ ksv_bytes = 5 * down_stream_devices; /* Reading KSV FIFO / KSV FIFO */ ksv_done = FALSE; ret = hdmi_msm_ddc_read(0x74, 0x43, kvs_fifo, ksv_bytes, 5, "KSV FIFO", TRUE); do { if (ret) { DEV_ERR("%s(%d): Read KSV FIFO failed", __func__, __LINE__); /* * HDCP Compliace Test case 1B-01: * Wait here until all the ksv bytes have been * read from the KSV FIFO register. */ msleep(25); } else { ksv_done = TRUE; } cnt++; } while (!ksv_done && cnt != 20); if (ksv_done == FALSE) goto error; ret = hdmi_msm_transfer_v_h(); if (ret) goto error; /* Next: Write KSV FIFO to HDCP_SHA_DATA. * This is done 1 byte at time starting with the LSB. * On the very last byte write, * the HDCP_SHA_DATA_DONE bit[0] */ /* 0x023C HDCP_SHA_CTRL [0] RESET [0] Enable, [1] Reset [4] SELECT [0] DIGA_HDCP, [1] DIGB_HDCP */ /* reset SHA engine */ HDMI_OUTP(0x023C, 1); /* enable SHA engine, SEL=DIGA_HDCP */ HDMI_OUTP(0x023C, 0); for (i = 0; i < ksv_bytes - 1; i++) { /* Write KSV byte and do not set DONE bit[0] */ HDMI_OUTP_ND(0x0244, kvs_fifo[i] << 16); /* Once 64 bytes have been written, we need to poll for * HDCP_SHA_BLOCK_DONE before writing any further */ if (i && !((i+1)%64)) { timeout_count = 100; while (!(HDMI_INP_ND(0x0240) & 0x1) && (--timeout_count)) { DEV_DBG("HDCP Auth Part II: Waiting for the " "computation of the current 64 byte to " "complete. HDCP_SHA_STATUS=%08x. " "timeout_count=%d\n", HDMI_INP_ND(0x0240), timeout_count); msleep(20); } if (!timeout_count) { ret = -ETIMEDOUT; DEV_ERR("%s(%d): timedout", __func__, __LINE__); goto error; } } } /* Write l to DONE bit[0] */ HDMI_OUTP_ND(0x0244, (kvs_fifo[ksv_bytes - 1] << 16) | 0x1); /* 0x0240 HDCP_SHA_STATUS [4] COMP_DONE */ /* Now wait for HDCP_SHA_COMP_DONE */ timeout_count = 100; while ((0x10 != (HDMI_INP_ND(0x0240) & 0xFFFFFF10)) && --timeout_count) msleep(20); if (!timeout_count) { ret = -ETIMEDOUT; DEV_ERR("%s(%d): timedout", __func__, __LINE__); goto error; } /* 0x011C HDCP_LINK0_STATUS [20] V_MATCHES */ timeout_count = 100; while (((HDMI_INP_ND(0x011C) & (1 << 20)) != (1 << 20)) && --timeout_count) { msleep(20); } if (!timeout_count) { ret = -ETIMEDOUT; DEV_ERR("%s(%d): timedout", __func__, __LINE__); goto error; } DEV_INFO("HDCP: authentication part II, successful\n"); hdcp_error: error: return ret; } static int hdcp_authentication_part3(uint32 found_repeater) { int ret = 0; int poll = 3000; if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return 0; } while (poll) { /* 0x011C HDCP_LINK0_STATUS [30:28] KEYS_STATE = 3 = "Valid" [24] RO_COMPUTATION_DONE [0] Not Done, [1] Done [20] V_MATCHES [0] Mismtach, [1] Match [12] RI_MATCHES [0] Mismatch, [1] Match [0] AUTH_SUCCESS */ if (HDMI_INP_ND(0x011C) != (0x31001001 | (found_repeater << 20))) { DEV_ERR("HDCP: autentication part III, FAILED, " "Link Status=%08x\n", HDMI_INP(0x011C)); ret = -EINVAL; goto error; } poll--; } DEV_INFO("HDCP: authentication part III, successful\n"); error: return ret; } static void hdmi_msm_hdcp_enable(void) { int ret = 0; uint8 bcaps; uint32 found_repeater = 0x0; char *envp[2]; if (!hdmi_msm_state->hdcp_enable) { DEV_INFO("%s: HDCP NOT ENABLED\n", __func__); return; } mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->hdcp_activating = TRUE; mutex_unlock(&hdmi_msm_state_mutex); fill_black_screen(); mutex_lock(&hdcp_auth_state_mutex); /* This flag prevents other threads from re-authenticating * after we've just authenticated (i.e., finished part3) * We probably need to protect this in a mutex lock */ hdmi_msm_state->full_auth_done = FALSE; mutex_unlock(&hdcp_auth_state_mutex); /* Disable HDCP before we start part1 */ HDMI_OUTP(0x0110, 0x0); /* PART I Authentication*/ ret = hdcp_authentication_part1(); if (ret) goto error; /* PART II Authentication*/ /* read Bcaps at 0x40 in HDCP Port */ ret = hdmi_msm_ddc_read(0x74, 0x40, &bcaps, 1, 5, "Bcaps", FALSE); if (ret) { DEV_ERR("%s(%d): Read Bcaps failed\n", __func__, __LINE__); goto error; } DEV_DBG("HDCP: Bcaps=0x%02x (%s)\n", bcaps, (bcaps & BIT(6)) ? "repeater" : "no repeater"); /* if REPEATER (Bit 6), perform Part2 Authentication */ if (bcaps & BIT(6)) { found_repeater = 0x1; ret = hdcp_authentication_part2(); if (ret) goto error; } else DEV_INFO("HDCP: authentication part II skipped, no repeater\n"); /* PART III Authentication*/ ret = hdcp_authentication_part3(found_repeater); if (ret) goto error; unfill_black_screen(); mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->hdcp_activating = FALSE; mutex_unlock(&hdmi_msm_state_mutex); mutex_lock(&hdcp_auth_state_mutex); /* * This flag prevents other threads from re-authenticating * after we've just authenticated (i.e., finished part3) */ hdmi_msm_state->full_auth_done = TRUE; external_common_state->hdcp_active = TRUE; mutex_unlock(&hdcp_auth_state_mutex); if (!hdmi_msm_is_dvi_mode()) { DEV_INFO("HDMI HPD: sense : send HDCP_PASS\n"); envp[0] = "HDCP_STATE=PASS"; envp[1] = NULL; kobject_uevent_env(external_common_state->uevent_kobj, KOBJ_CHANGE, envp); SWITCH_SET_HDMI_AUDIO(1, 0); } return; error: if (hdmi_msm_state->hpd_during_auth) { DEV_WARN("Calling Deauthentication: HPD occured during " "authentication from [%s]\n", __func__); hdcp_deauthenticate(); mutex_lock(&hdcp_auth_state_mutex); hdmi_msm_state->hpd_during_auth = FALSE; mutex_unlock(&hdcp_auth_state_mutex); } else { DEV_WARN("[DEV_DBG]: Calling reauth from [%s]\n", __func__); if (hdmi_msm_state->panel_power_on) queue_work(hdmi_work_queue, &hdmi_msm_state->hdcp_reauth_work); } mutex_lock(&hdmi_msm_state_mutex); hdmi_msm_state->hdcp_activating = FALSE; mutex_unlock(&hdmi_msm_state_mutex); } static void hdmi_msm_video_setup(int video_format) { uint32 total_v = 0; uint32 total_h = 0; uint32 start_h = 0; uint32 end_h = 0; uint32 start_v = 0; uint32 end_v = 0; const struct hdmi_disp_mode_timing_type *timing = hdmi_common_get_supported_mode(video_format); /* timing register setup */ if (timing == NULL) { DEV_ERR("video format not supported: %d\n", video_format); return; } /* Hsync Total and Vsync Total */ total_h = timing->active_h + timing->front_porch_h + timing->back_porch_h + timing->pulse_width_h - 1; total_v = timing->active_v + timing->front_porch_v + timing->back_porch_v + timing->pulse_width_v - 1; /* 0x02C0 HDMI_TOTAL [27:16] V_TOTAL Vertical Total [11:0] H_TOTAL Horizontal Total */ HDMI_OUTP(0x02C0, ((total_v << 16) & 0x0FFF0000) | ((total_h << 0) & 0x00000FFF)); /* Hsync Start and Hsync End */ start_h = timing->back_porch_h + timing->pulse_width_h; end_h = (total_h + 1) - timing->front_porch_h; /* 0x02B4 HDMI_ACTIVE_H [27:16] END Horizontal end [11:0] START Horizontal start */ HDMI_OUTP(0x02B4, ((end_h << 16) & 0x0FFF0000) | ((start_h << 0) & 0x00000FFF)); start_v = timing->back_porch_v + timing->pulse_width_v - 1; end_v = total_v - timing->front_porch_v; /* 0x02B8 HDMI_ACTIVE_V [27:16] END Vertical end [11:0] START Vertical start */ HDMI_OUTP(0x02B8, ((end_v << 16) & 0x0FFF0000) | ((start_v << 0) & 0x00000FFF)); if (timing->interlaced) { /* 0x02C4 HDMI_V_TOTAL_F2 [11:0] V_TOTAL_F2 Vertical total for field2 */ HDMI_OUTP(0x02C4, ((total_v + 1) << 0) & 0x00000FFF); /* 0x02BC HDMI_ACTIVE_V_F2 [27:16] END_F2 Vertical end for field2 [11:0] START_F2 Vertical start for Field2 */ HDMI_OUTP(0x02BC, (((start_v + 1) << 0) & 0x00000FFF) | (((end_v + 1) << 16) & 0x0FFF0000)); } else { /* HDMI_V_TOTAL_F2 */ HDMI_OUTP(0x02C4, 0); /* HDMI_ACTIVE_V_F2 */ HDMI_OUTP(0x02BC, 0); } hdmi_frame_ctrl_cfg(timing); } struct hdmi_msm_audio_acr { uint32 n; /* N parameter for clock regeneration */ uint32 cts; /* CTS parameter for clock regeneration */ }; struct hdmi_msm_audio_arcs { uint32 pclk; struct hdmi_msm_audio_acr lut[MSM_HDMI_SAMPLE_RATE_MAX]; }; #define HDMI_MSM_AUDIO_ARCS(pclk, ...) { pclk, __VA_ARGS__ } /* Audio constants lookup table for hdmi_msm_audio_acr_setup */ /* Valid Pixel-Clock rates: 25.2MHz, 27MHz, 27.03MHz, 74.25MHz, 148.5MHz */ static const struct hdmi_msm_audio_arcs hdmi_msm_audio_acr_lut[] = { /* 25.200MHz */ HDMI_MSM_AUDIO_ARCS(25200, { {4096, 25200}, {6272, 28000}, {6144, 25200}, {12544, 28000}, {12288, 25200}, {25088, 28000}, {24576, 25200} }), /* 27.000MHz */ HDMI_MSM_AUDIO_ARCS(27000, { {4096, 27000}, {6272, 30000}, {6144, 27000}, {12544, 30000}, {12288, 27000}, {25088, 30000}, {24576, 27000} }), /* 27.027MHz */ HDMI_MSM_AUDIO_ARCS(27030, { {4096, 27027}, {6272, 30030}, {6144, 27027}, {12544, 30030}, {12288, 27027}, {25088, 30030}, {24576, 27027} }), /* 74.250MHz */ HDMI_MSM_AUDIO_ARCS(74250, { {4096, 74250}, {6272, 82500}, {6144, 74250}, {12544, 82500}, {12288, 74250}, {25088, 82500}, {24576, 74250} }), /* 148.500MHz */ HDMI_MSM_AUDIO_ARCS(148500, { {4096, 148500}, {6272, 165000}, {6144, 148500}, {12544, 165000}, {12288, 148500}, {25088, 165000}, {24576, 148500} }), }; static void hdmi_msm_audio_acr_setup(boolean enabled, int video_format, int audio_sample_rate, int num_of_channels) { /* Read first before writing */ /* HDMI_ACR_PKT_CTRL[0x0024] */ uint32 acr_pck_ctrl_reg = HDMI_INP(0x0024); if (enabled) { const struct hdmi_disp_mode_timing_type *timing = hdmi_common_get_supported_mode(video_format); const struct hdmi_msm_audio_arcs *audio_arc = &hdmi_msm_audio_acr_lut[0]; const int lut_size = sizeof(hdmi_msm_audio_acr_lut) /sizeof(*hdmi_msm_audio_acr_lut); uint32 i, n, cts, layout, multiplier, aud_pck_ctrl_2_reg; if (timing == NULL) { DEV_WARN("%s: video format %d not supported\n", __func__, video_format); return; } for (i = 0; i < lut_size; audio_arc = &hdmi_msm_audio_acr_lut[++i]) { if (audio_arc->pclk == timing->pixel_freq) break; } if (i >= lut_size) { DEV_WARN("%s: pixel clock %d not supported\n", __func__, timing->pixel_freq); return; } n = audio_arc->lut[audio_sample_rate].n; cts = audio_arc->lut[audio_sample_rate].cts; layout = (MSM_HDMI_AUDIO_CHANNEL_2 == num_of_channels) ? 0 : 1; if ((MSM_HDMI_SAMPLE_RATE_192KHZ == audio_sample_rate) || (MSM_HDMI_SAMPLE_RATE_176_4KHZ == audio_sample_rate)) { multiplier = 4; n >>= 2; /* divide N by 4 and use multiplier */ } else if ((MSM_HDMI_SAMPLE_RATE_96KHZ == audio_sample_rate) || (MSM_HDMI_SAMPLE_RATE_88_2KHZ == audio_sample_rate)) { multiplier = 2; n >>= 1; /* divide N by 2 and use multiplier */ } else { multiplier = 1; } DEV_DBG("%s: n=%u, cts=%u, layout=%u\n", __func__, n, cts, layout); /* AUDIO_PRIORITY | SOURCE */ acr_pck_ctrl_reg |= 0x80000100; /* N_MULTIPLE(multiplier) */ acr_pck_ctrl_reg |= (multiplier & 7) << 16; if ((MSM_HDMI_SAMPLE_RATE_48KHZ == audio_sample_rate) || (MSM_HDMI_SAMPLE_RATE_96KHZ == audio_sample_rate) || (MSM_HDMI_SAMPLE_RATE_192KHZ == audio_sample_rate)) { /* SELECT(3) */ acr_pck_ctrl_reg |= 3 << 4; /* CTS_48 */ cts <<= 12; /* CTS: need to determine how many fractional bits */ /* HDMI_ACR_48_0 */ HDMI_OUTP(0x00D4, cts); /* N */ /* HDMI_ACR_48_1 */ HDMI_OUTP(0x00D8, n); } else if ((MSM_HDMI_SAMPLE_RATE_44_1KHZ == audio_sample_rate) || (MSM_HDMI_SAMPLE_RATE_88_2KHZ == audio_sample_rate) || (MSM_HDMI_SAMPLE_RATE_176_4KHZ == audio_sample_rate)) { /* SELECT(2) */ acr_pck_ctrl_reg |= 2 << 4; /* CTS_44 */ cts <<= 12; /* CTS: need to determine how many fractional bits */ /* HDMI_ACR_44_0 */ HDMI_OUTP(0x00CC, cts); /* N */ /* HDMI_ACR_44_1 */ HDMI_OUTP(0x00D0, n); } else { /* default to 32k */ /* SELECT(1) */ acr_pck_ctrl_reg |= 1 << 4; /* CTS_32 */ cts <<= 12; /* CTS: need to determine how many fractional bits */ /* HDMI_ACR_32_0 */ HDMI_OUTP(0x00C4, cts); /* N */ /* HDMI_ACR_32_1 */ HDMI_OUTP(0x00C8, n); } /* Payload layout depends on number of audio channels */ /* LAYOUT_SEL(layout) */ aud_pck_ctrl_2_reg = 1 | (layout << 1); /* override | layout */ /* HDMI_AUDIO_PKT_CTRL2[0x00044] */ HDMI_OUTP(0x00044, aud_pck_ctrl_2_reg); /* SEND | CONT */ acr_pck_ctrl_reg |= 0x00000003; } else { /* ~(SEND | CONT) */ acr_pck_ctrl_reg &= ~0x00000003; } /* HDMI_ACR_PKT_CTRL[0x0024] */ HDMI_OUTP(0x0024, acr_pck_ctrl_reg); } static void hdmi_msm_outpdw_chk(uint32 offset, uint32 data) { uint32 check, i = 0; #ifdef DEBUG HDMI_OUTP(offset, data); #endif do { outpdw(MSM_HDMI_BASE+offset, data); check = inpdw(MSM_HDMI_BASE+offset); } while (check != data && i++ < 10); if (check != data) DEV_ERR("%s: failed addr=%08x, data=%x, check=%x", __func__, offset, data, check); } static void hdmi_msm_rmw32or(uint32 offset, uint32 data) { uint32 reg_data; reg_data = inpdw(MSM_HDMI_BASE+offset); reg_data = inpdw(MSM_HDMI_BASE+offset); hdmi_msm_outpdw_chk(offset, reg_data | data); } #define HDMI_AUDIO_CFG 0x01D0 #define HDMI_AUDIO_ENGINE_ENABLE 1 #define HDMI_AUDIO_FIFO_MASK 0x000000F0 #define HDMI_AUDIO_FIFO_WATERMARK_SHIFT 4 #define HDMI_AUDIO_FIFO_MAX_WATER_MARK 8 int hdmi_audio_enable(bool on , u32 fifo_water_mark) { u32 hdmi_audio_config; hdmi_audio_config = HDMI_INP(HDMI_AUDIO_CFG); if (on) { if (fifo_water_mark > HDMI_AUDIO_FIFO_MAX_WATER_MARK) { pr_err("%s : HDMI audio fifo water mark can not be more" " than %u\n", __func__, HDMI_AUDIO_FIFO_MAX_WATER_MARK); return -EINVAL; } /* * Enable HDMI Audio engine. * MUST be enabled after Audio DMA is enabled. */ hdmi_audio_config &= ~(HDMI_AUDIO_FIFO_MASK); hdmi_audio_config |= (HDMI_AUDIO_ENGINE_ENABLE | (fifo_water_mark << HDMI_AUDIO_FIFO_WATERMARK_SHIFT)); } else hdmi_audio_config &= ~(HDMI_AUDIO_ENGINE_ENABLE); HDMI_OUTP(HDMI_AUDIO_CFG, hdmi_audio_config); mb(); pr_info("%s :HDMI_AUDIO_CFG 0x%08x\n", __func__, HDMI_INP(HDMI_AUDIO_CFG)); return 0; } EXPORT_SYMBOL(hdmi_audio_enable); #define HDMI_AUDIO_PKT_CTRL 0x0020 #define HDMI_AUDIO_SAMPLE_SEND_ENABLE 1 int hdmi_audio_packet_enable(bool on) { u32 hdmi_audio_pkt_ctrl; hdmi_audio_pkt_ctrl = HDMI_INP(HDMI_AUDIO_PKT_CTRL); if (on) hdmi_audio_pkt_ctrl |= HDMI_AUDIO_SAMPLE_SEND_ENABLE; else hdmi_audio_pkt_ctrl &= ~(HDMI_AUDIO_SAMPLE_SEND_ENABLE); HDMI_OUTP(HDMI_AUDIO_PKT_CTRL, hdmi_audio_pkt_ctrl); mb(); pr_info("%s : HDMI_AUDIO_PKT_CTRL 0x%08x\n", __func__, HDMI_INP(HDMI_AUDIO_PKT_CTRL)); return 0; } EXPORT_SYMBOL(hdmi_audio_packet_enable); /* TO-DO: return -EINVAL when num_of_channels and channel_allocation * does not match CEA 861-D spec. */ int hdmi_msm_audio_info_setup(bool enabled, u32 num_of_channels, u32 channel_allocation, u32 level_shift, bool down_mix) { uint32 channel_count = 1; /* Default to 2 channels -> See Table 17 in CEA-D spec */ uint32 check_sum, audio_info_0_reg, audio_info_1_reg; uint32 audio_info_ctrl_reg; u32 aud_pck_ctrl_2_reg; u32 layout; layout = (MSM_HDMI_AUDIO_CHANNEL_2 == num_of_channels) ? 0 : 1; aud_pck_ctrl_2_reg = 1 | (layout << 1); HDMI_OUTP(0x00044, aud_pck_ctrl_2_reg); /* Please see table 20 Audio InfoFrame in HDMI spec FL = front left FC = front Center FR = front right FLC = front left center FRC = front right center RL = rear left RC = rear center RR = rear right RLC = rear left center RRC = rear right center LFE = low frequency effect */ /* Read first then write because it is bundled with other controls */ /* HDMI_INFOFRAME_CTRL0[0x002C] */ audio_info_ctrl_reg = HDMI_INP(0x002C); if (enabled) { switch (num_of_channels) { case MSM_HDMI_AUDIO_CHANNEL_2: channel_allocation = 0; /* Default to FR,FL */ break; case MSM_HDMI_AUDIO_CHANNEL_4: channel_count = 3; /* FC,LFE,FR,FL */ channel_allocation = 0x3; break; case MSM_HDMI_AUDIO_CHANNEL_6: channel_count = 5; /* RR,RL,FC,LFE,FR,FL */ channel_allocation = 0xB; break; case MSM_HDMI_AUDIO_CHANNEL_8: channel_count = 7; /* FRC,FLC,RR,RL,FC,LFE,FR,FL */ channel_allocation = 0x1f; break; default: pr_err("%s(): Unsupported num_of_channels = %u\n", __func__, num_of_channels); return -EINVAL; break; } /* Program the Channel-Speaker allocation */ audio_info_1_reg = 0; /* CA(channel_allocation) */ audio_info_1_reg |= channel_allocation & 0xff; /* Program the Level shifter */ /* LSV(level_shift) */ audio_info_1_reg |= (level_shift << 11) & 0x00007800; /* Program the Down-mix Inhibit Flag */ /* DM_INH(down_mix) */ audio_info_1_reg |= (down_mix << 15) & 0x00008000; /* HDMI_AUDIO_INFO1[0x00E8] */ HDMI_OUTP(0x00E8, audio_info_1_reg); /* Calculate CheckSum Sum of all the bytes in the Audio Info Packet bytes (See table 8.4 in HDMI spec) */ check_sum = 0; /* HDMI_AUDIO_INFO_FRAME_PACKET_HEADER_TYPE[0x84] */ check_sum += 0x84; /* HDMI_AUDIO_INFO_FRAME_PACKET_HEADER_VERSION[0x01] */ check_sum += 1; /* HDMI_AUDIO_INFO_FRAME_PACKET_LENGTH[0x0A] */ check_sum += 0x0A; check_sum += channel_count; check_sum += channel_allocation; /* See Table 8.5 in HDMI spec */ check_sum += (level_shift & 0xF) << 3 | (down_mix & 0x1) << 7; check_sum &= 0xFF; check_sum = (uint8) (256 - check_sum); audio_info_0_reg = 0; /* CHECKSUM(check_sum) */ audio_info_0_reg |= check_sum & 0xff; /* CC(channel_count) */ audio_info_0_reg |= (channel_count << 8) & 0x00000700; /* HDMI_AUDIO_INFO0[0x00E4] */ HDMI_OUTP(0x00E4, audio_info_0_reg); /* Set these flags */ /* AUDIO_INFO_UPDATE | AUDIO_INFO_SOURCE | AUDIO_INFO_CONT | AUDIO_INFO_SEND */ audio_info_ctrl_reg |= 0x000000F0; } else { /* Clear these flags */ /* ~(AUDIO_INFO_UPDATE | AUDIO_INFO_SOURCE | AUDIO_INFO_CONT | AUDIO_INFO_SEND) */ audio_info_ctrl_reg &= ~0x000000F0; } /* HDMI_INFOFRAME_CTRL0[0x002C] */ HDMI_OUTP(0x002C, audio_info_ctrl_reg); hdmi_msm_dump_regs("HDMI-AUDIO-ON: "); return 0; } EXPORT_SYMBOL(hdmi_msm_audio_info_setup); static void hdmi_msm_en_gc_packet(boolean av_mute_is_requested) { /* HDMI_GC[0x0040] */ HDMI_OUTP(0x0040, av_mute_is_requested ? 1 : 0); /* GC packet enable (every frame) */ /* HDMI_VBI_PKT_CTRL[0x0028] */ hdmi_msm_rmw32or(0x0028, 3 << 4); } #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_ISRC_ACP_SUPPORT static void hdmi_msm_en_isrc_packet(boolean isrc_is_continued) { static const char isrc_psuedo_data[] = "ISRC1:0123456789isrc2=ABCDEFGHIJ"; const uint32 * isrc_data = (const uint32 *) isrc_psuedo_data; /* ISRC_STATUS =0b010 | ISRC_CONTINUE | ISRC_VALID */ /* HDMI_ISRC1_0[0x00048] */ HDMI_OUTP(0x00048, 2 | (isrc_is_continued ? 1 : 0) << 6 | 0 << 7); /* HDMI_ISRC1_1[0x004C] */ HDMI_OUTP(0x004C, *isrc_data++); /* HDMI_ISRC1_2[0x0050] */ HDMI_OUTP(0x0050, *isrc_data++); /* HDMI_ISRC1_3[0x0054] */ HDMI_OUTP(0x0054, *isrc_data++); /* HDMI_ISRC1_4[0x0058] */ HDMI_OUTP(0x0058, *isrc_data++); /* HDMI_ISRC2_0[0x005C] */ HDMI_OUTP(0x005C, *isrc_data++); /* HDMI_ISRC2_1[0x0060] */ HDMI_OUTP(0x0060, *isrc_data++); /* HDMI_ISRC2_2[0x0064] */ HDMI_OUTP(0x0064, *isrc_data++); /* HDMI_ISRC2_3[0x0068] */ HDMI_OUTP(0x0068, *isrc_data); /* HDMI_VBI_PKT_CTRL[0x0028] */ /* ISRC Send + Continuous */ hdmi_msm_rmw32or(0x0028, 3 << 8); } #else static void hdmi_msm_en_isrc_packet(boolean isrc_is_continued) { /* * Until end-to-end support for various audio packets */ } #endif #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_ISRC_ACP_SUPPORT static void hdmi_msm_en_acp_packet(uint32 byte1) { /* HDMI_ACP[0x003C] */ HDMI_OUTP(0x003C, 2 | 1 << 8 | byte1 << 16); /* HDMI_VBI_PKT_CTRL[0x0028] */ /* ACP send, s/w source */ hdmi_msm_rmw32or(0x0028, 3 << 12); } #else static void hdmi_msm_en_acp_packet(uint32 byte1) { /* * Until end-to-end support for various audio packets */ } #endif int hdmi_msm_audio_get_sample_rate(void) { return msm_hdmi_sample_rate; } EXPORT_SYMBOL(hdmi_msm_audio_get_sample_rate); void hdmi_msm_audio_sample_rate_reset(int rate) { msm_hdmi_sample_rate = rate; if (hdmi_msm_state->hdcp_enable) hdcp_deauthenticate(); else hdmi_msm_turn_on(); } EXPORT_SYMBOL(hdmi_msm_audio_sample_rate_reset); static void hdmi_msm_audio_setup(void) { const int channels = MSM_HDMI_AUDIO_CHANNEL_2; /* (0) for clr_avmute, (1) for set_avmute */ hdmi_msm_en_gc_packet(0); /* (0) for isrc1 only, (1) for isrc1 and isrc2 */ hdmi_msm_en_isrc_packet(1); /* arbitrary bit pattern for byte1 */ hdmi_msm_en_acp_packet(0x5a); DEV_DBG("Not setting ACP, ISRC1, ISRC2 packets\n"); hdmi_msm_audio_acr_setup(TRUE, external_common_state->video_resolution, msm_hdmi_sample_rate, channels); hdmi_msm_audio_info_setup(TRUE, channels, 0, 0, FALSE); /* Turn on Audio FIFO and SAM DROP ISR */ HDMI_OUTP(0x02CC, HDMI_INP(0x02CC) | BIT(1) | BIT(3)); DEV_INFO("HDMI Audio: Enabled\n"); } static int hdmi_msm_audio_off(void) { uint32 audio_cfg; int i, timeout_val = 50; for (i = 0; (i < timeout_val) && ((audio_cfg = HDMI_INP_ND(0x01D0)) & BIT(0)); i++) { DEV_DBG("%s: %d times: AUDIO CFG is %08xi\n", __func__, i+1, audio_cfg); if (!((i+1) % 10)) { DEV_ERR("%s: audio still on after %d sec. try again\n", __func__, (i+1)/10); SWITCH_SET_HDMI_AUDIO(0, 1); } msleep(100); } if (i == timeout_val) DEV_ERR("%s: Error: cannot turn off audio engine\n", __func__); hdmi_msm_audio_info_setup(FALSE, 0, 0, 0, FALSE); hdmi_msm_audio_acr_setup(FALSE, 0, 0, 0); DEV_INFO("HDMI Audio: Disabled\n"); return 0; } static uint8 hdmi_msm_avi_iframe_lut[][16] = { /* 480p60 480i60 576p50 576i50 720p60 720p50 1080p60 1080i60 1080p50 1080i50 1080p24 1080p30 1080p25 640x480p 480p60_16_9 576p50_4_3 */ {0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10, 0x10}, /*00*/ {0x18, 0x18, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x28, 0x18, 0x28, 0x18}, /*01*/ {0x00, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x88, 0x00, 0x04}, /*02*/ {0x02, 0x06, 0x11, 0x15, 0x04, 0x13, 0x10, 0x05, 0x1F, 0x14, 0x20, 0x22, 0x21, 0x01, 0x03, 0x11}, /*03*/ {0x00, 0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*04*/ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*05*/ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*06*/ {0xE1, 0xE1, 0x41, 0x41, 0xD1, 0xd1, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0x39, 0xe1, 0xE1, 0x41}, /*07*/ {0x01, 0x01, 0x02, 0x02, 0x02, 0x02, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x04, 0x01, 0x01, 0x02}, /*08*/ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*09*/ {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, /*10*/ {0xD1, 0xD1, 0xD1, 0xD1, 0x01, 0x01, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0x81, 0xD1, 0xD1}, /*11*/ {0x02, 0x02, 0x02, 0x02, 0x05, 0x05, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x02, 0x02, 0x02} /*12*/ }; static void hdmi_msm_avi_info_frame(void) { /* two header + length + 13 data */ uint8 aviInfoFrame[16]; uint8 checksum; uint32 sum; uint32 regVal; int i; int mode = 0; boolean use_ce_scan_info = TRUE; switch (external_common_state->video_resolution) { case HDMI_VFRMT_720x480p60_4_3: mode = 0; break; case HDMI_VFRMT_720x480i60_16_9: mode = 1; break; case HDMI_VFRMT_720x576p50_16_9: mode = 2; break; case HDMI_VFRMT_720x576i50_16_9: mode = 3; break; case HDMI_VFRMT_1280x720p60_16_9: mode = 4; break; case HDMI_VFRMT_1280x720p50_16_9: mode = 5; break; case HDMI_VFRMT_1920x1080p60_16_9: mode = 6; break; case HDMI_VFRMT_1920x1080i60_16_9: mode = 7; break; case HDMI_VFRMT_1920x1080p50_16_9: mode = 8; break; case HDMI_VFRMT_1920x1080i50_16_9: mode = 9; break; case HDMI_VFRMT_1920x1080p24_16_9: mode = 10; break; case HDMI_VFRMT_1920x1080p30_16_9: mode = 11; break; case HDMI_VFRMT_1920x1080p25_16_9: mode = 12; break; case HDMI_VFRMT_640x480p60_4_3: mode = 13; break; case HDMI_VFRMT_720x480p60_16_9: mode = 14; break; case HDMI_VFRMT_720x576p50_4_3: mode = 15; break; default: DEV_INFO("%s: mode %d not supported\n", __func__, external_common_state->video_resolution); return; } /* InfoFrame Type = 82 */ aviInfoFrame[0] = 0x82; /* Version = 2 */ aviInfoFrame[1] = 2; /* Length of AVI InfoFrame = 13 */ aviInfoFrame[2] = 13; /* Data Byte 01: 0 Y1 Y0 A0 B1 B0 S1 S0 */ aviInfoFrame[3] = hdmi_msm_avi_iframe_lut[0][mode]; /* * If the sink specified support for both underscan/overscan * then, by default, set the underscan bit. * Only checking underscan support for preferred format and cea formats */ if ((external_common_state->video_resolution == external_common_state->preferred_video_format)) { use_ce_scan_info = FALSE; switch (external_common_state->pt_scan_info) { case 0: /* * Need to use the info specified for the corresponding * IT or CE format */ DEV_DBG("%s: No underscan information specified for the" " preferred video format\n", __func__); use_ce_scan_info = TRUE; break; case 3: DEV_DBG("%s: Setting underscan bit for the preferred" " video format\n", __func__); aviInfoFrame[3] |= 0x02; break; default: DEV_DBG("%s: Underscan information not set for the" " preferred video format\n", __func__); break; } } if (use_ce_scan_info) { if (3 == external_common_state->ce_scan_info) { DEV_DBG("%s: Setting underscan bit for the CE video" " format\n", __func__); aviInfoFrame[3] |= 0x02; } else { DEV_DBG("%s: Not setting underscan bit for the CE video" " format\n", __func__); } } /* Data Byte 02: C1 C0 M1 M0 R3 R2 R1 R0 */ aviInfoFrame[4] = hdmi_msm_avi_iframe_lut[1][mode]; /* Data Byte 03: ITC EC2 EC1 EC0 Q1 Q0 SC1 SC0 */ aviInfoFrame[5] = hdmi_msm_avi_iframe_lut[2][mode]; /* Data Byte 04: 0 VIC6 VIC5 VIC4 VIC3 VIC2 VIC1 VIC0 */ aviInfoFrame[6] = hdmi_msm_avi_iframe_lut[3][mode]; /* Data Byte 05: 0 0 0 0 PR3 PR2 PR1 PR0 */ aviInfoFrame[7] = hdmi_msm_avi_iframe_lut[4][mode]; /* Data Byte 06: LSB Line No of End of Top Bar */ aviInfoFrame[8] = hdmi_msm_avi_iframe_lut[5][mode]; /* Data Byte 07: MSB Line No of End of Top Bar */ aviInfoFrame[9] = hdmi_msm_avi_iframe_lut[6][mode]; /* Data Byte 08: LSB Line No of Start of Bottom Bar */ aviInfoFrame[10] = hdmi_msm_avi_iframe_lut[7][mode]; /* Data Byte 09: MSB Line No of Start of Bottom Bar */ aviInfoFrame[11] = hdmi_msm_avi_iframe_lut[8][mode]; /* Data Byte 10: LSB Pixel Number of End of Left Bar */ aviInfoFrame[12] = hdmi_msm_avi_iframe_lut[9][mode]; /* Data Byte 11: MSB Pixel Number of End of Left Bar */ aviInfoFrame[13] = hdmi_msm_avi_iframe_lut[10][mode]; /* Data Byte 12: LSB Pixel Number of Start of Right Bar */ aviInfoFrame[14] = hdmi_msm_avi_iframe_lut[11][mode]; /* Data Byte 13: MSB Pixel Number of Start of Right Bar */ aviInfoFrame[15] = hdmi_msm_avi_iframe_lut[12][mode]; sum = 0; for (i = 0; i < 16; i++) sum += aviInfoFrame[i]; sum &= 0xFF; sum = 256 - sum; checksum = (uint8) sum; regVal = aviInfoFrame[5]; regVal = regVal << 8 | aviInfoFrame[4]; regVal = regVal << 8 | aviInfoFrame[3]; regVal = regVal << 8 | checksum; HDMI_OUTP(0x006C, regVal); regVal = aviInfoFrame[9]; regVal = regVal << 8 | aviInfoFrame[8]; regVal = regVal << 8 | aviInfoFrame[7]; regVal = regVal << 8 | aviInfoFrame[6]; HDMI_OUTP(0x0070, regVal); regVal = aviInfoFrame[13]; regVal = regVal << 8 | aviInfoFrame[12]; regVal = regVal << 8 | aviInfoFrame[11]; regVal = regVal << 8 | aviInfoFrame[10]; HDMI_OUTP(0x0074, regVal); regVal = aviInfoFrame[1]; regVal = regVal << 16 | aviInfoFrame[15]; regVal = regVal << 8 | aviInfoFrame[14]; HDMI_OUTP(0x0078, regVal); /* INFOFRAME_CTRL0[0x002C] */ /* 0x3 for AVI InfFrame enable (every frame) */ HDMI_OUTP(0x002C, HDMI_INP(0x002C) | 0x00000003L); } #ifdef CONFIG_FB_MSM_HDMI_3D static void hdmi_msm_vendor_infoframe_packetsetup(void) { uint32 packet_header = 0; uint32 check_sum = 0; uint32 packet_payload = 0; if (!external_common_state->format_3d) { HDMI_OUTP(0x0034, 0); return; } /* 0x0084 GENERIC0_HDR * HB0 7:0 NUM * HB1 15:8 NUM * HB2 23:16 NUM */ /* Setup Packet header and payload */ /* 0x81 VS_INFO_FRAME_ID 0x01 VS_INFO_FRAME_VERSION 0x1B VS_INFO_FRAME_PAYLOAD_LENGTH */ packet_header = 0x81 | (0x01 << 8) | (0x1B << 16); HDMI_OUTP(0x0084, packet_header); check_sum = packet_header & 0xff; check_sum += (packet_header >> 8) & 0xff; check_sum += (packet_header >> 16) & 0xff; /* 0x008C GENERIC0_1 * BYTE4 7:0 NUM * BYTE5 15:8 NUM * BYTE6 23:16 NUM * BYTE7 31:24 NUM */ /* 0x02 VS_INFO_FRAME_3D_PRESENT */ packet_payload = 0x02 << 5; switch (external_common_state->format_3d) { case 1: /* 0b1000 VIDEO_3D_FORMAT_SIDE_BY_SIDE_HALF */ packet_payload |= (0x08 << 8) << 4; break; case 2: /* 0b0110 VIDEO_3D_FORMAT_TOP_AND_BOTTOM_HALF */ packet_payload |= (0x06 << 8) << 4; break; } HDMI_OUTP(0x008C, packet_payload); check_sum += packet_payload & 0xff; check_sum += (packet_payload >> 8) & 0xff; #define IEEE_REGISTRATION_ID 0xC03 /* Next 3 bytes are IEEE Registration Identifcation */ /* 0x0088 GENERIC0_0 * BYTE0 7:0 NUM (checksum) * BYTE1 15:8 NUM * BYTE2 23:16 NUM * BYTE3 31:24 NUM */ check_sum += IEEE_REGISTRATION_ID & 0xff; check_sum += (IEEE_REGISTRATION_ID >> 8) & 0xff; check_sum += (IEEE_REGISTRATION_ID >> 16) & 0xff; HDMI_OUTP(0x0088, (0x100 - (0xff & check_sum)) | ((IEEE_REGISTRATION_ID & 0xff) << 8) | (((IEEE_REGISTRATION_ID >> 8) & 0xff) << 16) | (((IEEE_REGISTRATION_ID >> 16) & 0xff) << 24)); /* 0x0034 GEN_PKT_CTRL * GENERIC0_SEND 0 0 = Disable Generic0 Packet Transmission * 1 = Enable Generic0 Packet Transmission * GENERIC0_CONT 1 0 = Send Generic0 Packet on next frame only * 1 = Send Generic0 Packet on every frame * GENERIC0_UPDATE 2 NUM * GENERIC1_SEND 4 0 = Disable Generic1 Packet Transmission * 1 = Enable Generic1 Packet Transmission * GENERIC1_CONT 5 0 = Send Generic1 Packet on next frame only * 1 = Send Generic1 Packet on every frame * GENERIC0_LINE 21:16 NUM * GENERIC1_LINE 29:24 NUM */ /* GENERIC0_LINE | GENERIC0_UPDATE | GENERIC0_CONT | GENERIC0_SEND * Setup HDMI TX generic packet control * Enable this packet to transmit every frame * Enable this packet to transmit every frame * Enable HDMI TX engine to transmit Generic packet 0 */ HDMI_OUTP(0x0034, (1 << 16) | (1 << 2) | BIT(1) | BIT(0)); } static void hdmi_msm_switch_3d(boolean on) { mutex_lock(&external_common_state_hpd_mutex); if (external_common_state->hpd_state) hdmi_msm_vendor_infoframe_packetsetup(); mutex_unlock(&external_common_state_hpd_mutex); } #endif #define IFRAME_CHECKSUM_32(d) \ ((d & 0xff) + ((d >> 8) & 0xff) + \ ((d >> 16) & 0xff) + ((d >> 24) & 0xff)) static void hdmi_msm_spd_infoframe_packetsetup(void) { uint32 packet_header = 0; uint32 check_sum = 0; uint32 packet_payload = 0; uint32 packet_control = 0; uint8 *vendor_name = external_common_state->spd_vendor_name; uint8 *product_description = external_common_state->spd_product_description; /* 0x00A4 GENERIC1_HDR * HB0 7:0 NUM * HB1 15:8 NUM * HB2 23:16 NUM */ /* Setup Packet header and payload */ /* 0x83 InfoFrame Type Code 0x01 InfoFrame Version Number 0x19 Length of Source Product Description InfoFrame */ packet_header = 0x83 | (0x01 << 8) | (0x19 << 16); HDMI_OUTP(0x00A4, packet_header); check_sum += IFRAME_CHECKSUM_32(packet_header); /* 0x00AC GENERIC1_1 * BYTE4 7:0 VENDOR_NAME[3] * BYTE5 15:8 VENDOR_NAME[4] * BYTE6 23:16 VENDOR_NAME[5] * BYTE7 31:24 VENDOR_NAME[6] */ packet_payload = (vendor_name[3] & 0x7f) | ((vendor_name[4] & 0x7f) << 8) | ((vendor_name[5] & 0x7f) << 16) | ((vendor_name[6] & 0x7f) << 24); HDMI_OUTP(0x00AC, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* Product Description (7-bit ASCII code) */ /* 0x00B0 GENERIC1_2 * BYTE8 7:0 VENDOR_NAME[7] * BYTE9 15:8 PRODUCT_NAME[ 0] * BYTE10 23:16 PRODUCT_NAME[ 1] * BYTE11 31:24 PRODUCT_NAME[ 2] */ packet_payload = (vendor_name[7] & 0x7f) | ((product_description[0] & 0x7f) << 8) | ((product_description[1] & 0x7f) << 16) | ((product_description[2] & 0x7f) << 24); HDMI_OUTP(0x00B0, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* 0x00B4 GENERIC1_3 * BYTE12 7:0 PRODUCT_NAME[ 3] * BYTE13 15:8 PRODUCT_NAME[ 4] * BYTE14 23:16 PRODUCT_NAME[ 5] * BYTE15 31:24 PRODUCT_NAME[ 6] */ packet_payload = (product_description[3] & 0x7f) | ((product_description[4] & 0x7f) << 8) | ((product_description[5] & 0x7f) << 16) | ((product_description[6] & 0x7f) << 24); HDMI_OUTP(0x00B4, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* 0x00B8 GENERIC1_4 * BYTE16 7:0 PRODUCT_NAME[ 7] * BYTE17 15:8 PRODUCT_NAME[ 8] * BYTE18 23:16 PRODUCT_NAME[ 9] * BYTE19 31:24 PRODUCT_NAME[10] */ packet_payload = (product_description[7] & 0x7f) | ((product_description[8] & 0x7f) << 8) | ((product_description[9] & 0x7f) << 16) | ((product_description[10] & 0x7f) << 24); HDMI_OUTP(0x00B8, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* 0x00BC GENERIC1_5 * BYTE20 7:0 PRODUCT_NAME[11] * BYTE21 15:8 PRODUCT_NAME[12] * BYTE22 23:16 PRODUCT_NAME[13] * BYTE23 31:24 PRODUCT_NAME[14] */ packet_payload = (product_description[11] & 0x7f) | ((product_description[12] & 0x7f) << 8) | ((product_description[13] & 0x7f) << 16) | ((product_description[14] & 0x7f) << 24); HDMI_OUTP(0x00BC, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* 0x00C0 GENERIC1_6 * BYTE24 7:0 PRODUCT_NAME[15] * BYTE25 15:8 Source Device Information * BYTE26 23:16 NUM * BYTE27 31:24 NUM */ /* Source Device Information * 00h unknown * 01h Digital STB * 02h DVD * 03h D-VHS * 04h HDD Video * 05h DVC * 06h DSC * 07h Video CD * 08h Game * 09h PC general */ packet_payload = (product_description[15] & 0x7f) | 0x00 << 8; HDMI_OUTP(0x00C0, packet_payload); check_sum += IFRAME_CHECKSUM_32(packet_payload); /* Vendor Name (7bit ASCII code) */ /* 0x00A8 GENERIC1_0 * BYTE0 7:0 CheckSum * BYTE1 15:8 VENDOR_NAME[0] * BYTE2 23:16 VENDOR_NAME[1] * BYTE3 31:24 VENDOR_NAME[2] */ packet_payload = ((vendor_name[0] & 0x7f) << 8) | ((vendor_name[1] & 0x7f) << 16) | ((vendor_name[2] & 0x7f) << 24); check_sum += IFRAME_CHECKSUM_32(packet_payload); packet_payload |= ((0x100 - (0xff & check_sum)) & 0xff); HDMI_OUTP(0x00A8, packet_payload); /* GENERIC1_LINE | GENERIC1_CONT | GENERIC1_SEND * Setup HDMI TX generic packet control * Enable this packet to transmit every frame * Enable HDMI TX engine to transmit Generic packet 1 */ packet_control = HDMI_INP_ND(0x0034); packet_control |= ((0x1 << 24) | (1 << 5) | (1 << 4)); HDMI_OUTP(0x0034, packet_control); } int hdmi_msm_clk(int on) { int rc; DEV_DBG("HDMI Clk: %s\n", on ? "Enable" : "Disable"); if (on) { rc = clk_prepare_enable(hdmi_msm_state->hdmi_app_clk); if (rc) { DEV_ERR("'hdmi_app_clk' clock enable failed, rc=%d\n", rc); return rc; } rc = clk_prepare_enable(hdmi_msm_state->hdmi_m_pclk); if (rc) { DEV_ERR("'hdmi_m_pclk' clock enable failed, rc=%d\n", rc); return rc; } rc = clk_prepare_enable(hdmi_msm_state->hdmi_s_pclk); if (rc) { DEV_ERR("'hdmi_s_pclk' clock enable failed, rc=%d\n", rc); return rc; } } else { clk_disable_unprepare(hdmi_msm_state->hdmi_app_clk); clk_disable_unprepare(hdmi_msm_state->hdmi_m_pclk); clk_disable_unprepare(hdmi_msm_state->hdmi_s_pclk); } return 0; } static void hdmi_msm_turn_on(void) { uint32 audio_pkt_ctrl, audio_cfg; /* * Number of wait iterations for QDSP to disable Audio Engine * before resetting HDMI core */ int i = 10; audio_pkt_ctrl = HDMI_INP_ND(0x0020); audio_cfg = HDMI_INP_ND(0x01D0); /* * Checking BIT[0] of AUDIO PACKET CONTROL and * AUDIO CONFIGURATION register */ while (((audio_pkt_ctrl & 0x00000001) || (audio_cfg & 0x00000001)) && (i--)) { audio_pkt_ctrl = HDMI_INP_ND(0x0020); audio_cfg = HDMI_INP_ND(0x01D0); DEV_DBG("%d times :: HDMI AUDIO PACKET is %08x and " "AUDIO CFG is %08x", i, audio_pkt_ctrl, audio_cfg); msleep(20); } hdmi_msm_set_mode(FALSE); mutex_lock(&hdcp_auth_state_mutex); hdmi_msm_reset_core(); mutex_unlock(&hdcp_auth_state_mutex); hdmi_msm_init_phy(external_common_state->video_resolution); /* HDMI_USEC_REFTIMER[0x0208] */ HDMI_OUTP(0x0208, 0x0001001B); hdmi_msm_set_mode(TRUE); hdmi_msm_video_setup(external_common_state->video_resolution); if (!hdmi_msm_is_dvi_mode()) { hdmi_msm_audio_setup(); /* * Send the audio switch device notification if HDCP is * not enabled. Otherwise, the notification would be * sent after HDCP authentication is successful. */ if (!hdmi_msm_state->hdcp_enable) SWITCH_SET_HDMI_AUDIO(1, 0); } hdmi_msm_avi_info_frame(); #ifdef CONFIG_FB_MSM_HDMI_3D hdmi_msm_vendor_infoframe_packetsetup(); #endif hdmi_msm_spd_infoframe_packetsetup(); if (hdmi_msm_state->hdcp_enable && hdmi_msm_state->reauth) { hdmi_msm_hdcp_enable(); hdmi_msm_state->reauth = FALSE ; } #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT /* re-initialize CEC if enabled */ mutex_lock(&hdmi_msm_state_mutex); if (hdmi_msm_state->cec_enabled == true) { hdmi_msm_cec_init(); hdmi_msm_cec_write_logical_addr( hdmi_msm_state->cec_logical_addr); } mutex_unlock(&hdmi_msm_state_mutex); #endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT */ DEV_INFO("HDMI Core: Initialized\n"); } static void hdmi_msm_hdcp_timer(unsigned long data) { if (!hdmi_msm_state->hdcp_enable) { DEV_DBG("%s: HDCP not enabled\n", __func__); return; } queue_work(hdmi_work_queue, &hdmi_msm_state->hdcp_work); } #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT static void hdmi_msm_cec_read_timer_func(unsigned long data) { queue_work(hdmi_work_queue, &hdmi_msm_state->cec_latch_detect_work); } #endif static void hdmi_msm_hpd_polarity_setup(void) { u32 cable_sense; bool polarity = !external_common_state->hpd_state; bool trigger = false; if (polarity) HDMI_OUTP(0x0254, BIT(2) | BIT(1)); else HDMI_OUTP(0x0254, BIT(2)); cable_sense = (HDMI_INP(0x0250) & BIT(1)) >> 1; if (cable_sense == polarity) trigger = true; DEV_DBG("%s: listen=%s, sense=%s, trigger=%s\n", __func__, polarity ? "connect" : "disconnect", cable_sense ? "connect" : "disconnect", trigger ? "Yes" : "No"); if (trigger) { u32 reg_val = HDMI_INP(0x0258); /* Toggle HPD circuit to trigger HPD sense */ HDMI_OUTP(0x0258, reg_val & ~BIT(28)); HDMI_OUTP(0x0258, reg_val | BIT(28)); } } static void hdmi_msm_hpd_off(void) { int rc = 0; if (!hdmi_msm_state->hpd_initialized) { DEV_DBG("%s: HPD is already OFF, returning\n", __func__); return; } DEV_DBG("%s: (timer, 5V, IRQ off)\n", __func__); disable_irq(hdmi_msm_state->irq); /* Disable HPD interrupt */ HDMI_OUTP(0x0254, 0); DEV_DBG("%s: Disabling HPD_CTRLd\n", __func__); hdmi_msm_set_mode(FALSE); hdmi_msm_state->pd->enable_5v(0); hdmi_msm_clk(0); rc = hdmi_msm_state->pd->gpio_config(0); if (rc != 0) DEV_INFO("%s: Failed to disable GPIOs. Error=%d\n", __func__, rc); hdmi_msm_state->hpd_initialized = FALSE; } static void hdmi_msm_dump_regs(const char *prefix) { #ifdef REG_DUMP print_hex_dump(KERN_INFO, prefix, DUMP_PREFIX_OFFSET, 32, 4, (void *)MSM_HDMI_BASE, 0x0334, false); #endif } static int hdmi_msm_hpd_on(void) { static int phy_reset_done; uint32 hpd_ctrl; int rc = 0; if (hdmi_msm_state->hpd_initialized) { DEV_DBG("%s: HPD is already ON\n", __func__); } else { rc = hdmi_msm_state->pd->gpio_config(1); if (rc) { DEV_ERR("%s: Failed to enable GPIOs. Error=%d\n", __func__, rc); goto error1; } rc = hdmi_msm_clk(1); if (rc) { DEV_ERR("%s: Failed to enable clocks. Error=%d\n", __func__, rc); goto error2; } rc = hdmi_msm_state->pd->enable_5v(1); if (rc) { DEV_ERR("%s: Failed to enable 5V regulator. Error=%d\n", __func__, rc); goto error3; } hdmi_msm_dump_regs("HDMI-INIT: "); hdmi_msm_set_mode(FALSE); if (!phy_reset_done) { hdmi_phy_reset(); phy_reset_done = 1; } hdmi_msm_set_mode(TRUE); /* HDMI_USEC_REFTIMER[0x0208] */ HDMI_OUTP(0x0208, 0x0001001B); /* Set up HPD state variables */ mutex_lock(&external_common_state_hpd_mutex); external_common_state->hpd_state = 0; mutex_unlock(&external_common_state_hpd_mutex); mutex_lock(&hdmi_msm_state_mutex); mutex_unlock(&hdmi_msm_state_mutex); enable_irq(hdmi_msm_state->irq); hdmi_msm_state->hpd_initialized = TRUE; /* set timeout to 4.1ms (max) for hardware debounce */ hpd_ctrl = HDMI_INP(0x0258) | 0x1FFF; /* Turn on HPD HW circuit */ HDMI_OUTP(0x0258, hpd_ctrl | BIT(28)); /* Set HPD cable sense polarity */ hdmi_msm_hpd_polarity_setup(); } DEV_DBG("%s: (IRQ, 5V on)\n", __func__); return 0; error3: hdmi_msm_clk(0); error2: hdmi_msm_state->pd->gpio_config(0); error1: return rc; } static int hdmi_msm_power_ctrl(boolean enable) { int rc = 0; if (enable) { /* * Enable HPD only if the UI option is on or if * HDMI is configured as the primary display */ if (hdmi_prim_display || external_common_state->hpd_feature_on) { DEV_DBG("%s: Turning HPD ciruitry on\n", __func__); /*[ECID:000000] ZTEBSP wanghaifei start 20130221, add qcom new patch for HDP resume wait*/ if (external_common_state->pre_suspend_hpd_state) { external_common_state->pre_suspend_hpd_state = false; hdmi_msm_send_event(HPD_EVENT_OFFLINE); } /*[ECID:000000] ZTEBSP wanghaifei end 20130221, add qcom new patch for HDP resume wait*/ rc = hdmi_msm_hpd_on(); if (rc) { DEV_ERR("%s: HPD ON FAILED\n", __func__); return rc; } /*[ECID:000000] ZTEBSP wanghaifei start 20130221, add qcom new patch for HDP resume wait*/ #if 0 /* Wait for HPD initialization to complete */ INIT_COMPLETION(hdmi_msm_state->hpd_event_processed); time = wait_for_completion_interruptible_timeout( &hdmi_msm_state->hpd_event_processed, HZ); if (!time && !external_common_state->hpd_state) { DEV_DBG("%s: cable not detected\n", __func__); queue_work(hdmi_work_queue, &hdmi_msm_state->hpd_state_work); } #endif /*[ECID:000000] ZTEBSP wanghaifei end 20130221, add qcom new patch for HDP resume wait*/ } } else { DEV_DBG("%s: Turning HPD ciruitry off\n", __func__); /*[ECID:000000] ZTEBSP wanghaifei start 20130221, add qcom new patch for HDP resume wait*/ external_common_state->pre_suspend_hpd_state = external_common_state->hpd_state; /*[ECID:000000] ZTEBSP wanghaifei end 20130221, add qcom new patch for HDP resume wait*/ hdmi_msm_hpd_off(); } return rc; } static int hdmi_msm_power_on(struct platform_device *pdev) { struct msm_fb_data_type *mfd = platform_get_drvdata(pdev); int ret = 0; bool changed; if (!hdmi_ready()) { DEV_ERR("%s: HDMI/HPD not initialized\n", __func__); return ret; } if (!external_common_state->hpd_state) { DEV_DBG("%s:HDMI cable not connected\n", __func__); goto error; } /* Only start transmission with supported resolution */ changed = hdmi_common_get_video_format_from_drv_data(mfd); if (changed || external_common_state->default_res_supported) { mutex_lock(&external_common_state_hpd_mutex); if (external_common_state->hpd_state && hdmi_msm_is_power_on()) { mutex_unlock(&external_common_state_hpd_mutex); DEV_INFO("HDMI cable connected %s(%dx%d, %d)\n", __func__, mfd->var_xres, mfd->var_yres, mfd->var_pixclock); hdmi_msm_turn_on(); hdmi_msm_state->panel_power_on = TRUE; if (hdmi_msm_state->hdcp_enable) { /* Kick off HDCP Authentication */ mutex_lock(&hdcp_auth_state_mutex); hdmi_msm_state->reauth = FALSE; hdmi_msm_state->full_auth_done = FALSE; mutex_unlock(&hdcp_auth_state_mutex); mod_timer(&hdmi_msm_state->hdcp_timer, jiffies + HZ/2); } } else { mutex_unlock(&external_common_state_hpd_mutex); } hdmi_msm_dump_regs("HDMI-ON: "); DEV_INFO("power=%s DVI= %s\n", hdmi_msm_is_power_on() ? "ON" : "OFF" , hdmi_msm_is_dvi_mode() ? "ON" : "OFF"); } else { DEV_ERR("%s: Video fmt %d not supp. Returning\n", __func__, external_common_state->video_resolution); } error: /* Set HPD cable sense polarity */ hdmi_msm_hpd_polarity_setup(); return ret; } void mhl_connect_api(boolean on) { char *envp[2]; /* Simulating a HPD event based on MHL event */ if (on) { hdmi_msm_read_edid(); hdmi_msm_state->reauth = FALSE ; /* Build EDID table */ hdmi_msm_turn_on(); DEV_INFO("HDMI HPD: CONNECTED: send ONLINE\n"); kobject_uevent(external_common_state->uevent_kobj, KOBJ_ONLINE); envp[0] = 0; if (!hdmi_msm_state->hdcp_enable) { /* Send Audio for HDMI Compliance Cases*/ envp[0] = "HDCP_STATE=PASS"; envp[1] = NULL; DEV_INFO("HDMI HPD: sense : send HDCP_PASS\n"); kobject_uevent_env(external_common_state->uevent_kobj, KOBJ_CHANGE, envp); switch_set_state(&external_common_state->sdev, 1); DEV_INFO("%s: hdmi state switched to %d\n", __func__, external_common_state->sdev.state); } else { hdmi_msm_hdcp_enable(); } } else { DEV_INFO("HDMI HPD: DISCONNECTED: send OFFLINE\n"); kobject_uevent(external_common_state->uevent_kobj, KOBJ_OFFLINE); switch_set_state(&external_common_state->sdev, 0); DEV_INFO("%s: hdmi state switched to %d\n", __func__, external_common_state->sdev.state); } } EXPORT_SYMBOL(mhl_connect_api); /* Note that power-off will also be called when the cable-remove event is * processed on the user-space and as a result the framebuffer is powered * down. However, we are still required to be able to detect a cable-insert * event; so for now leave the HDMI engine running; so that the HPD IRQ is * still being processed. */ static int hdmi_msm_power_off(struct platform_device *pdev) { int ret = 0; if (!hdmi_ready()) { DEV_ERR("%s: HDMI/HPD not initialized\n", __func__); return ret; } if (!hdmi_msm_state->panel_power_on) { DEV_DBG("%s: panel not ON\n", __func__); goto error; } if (hdmi_msm_state->hdcp_enable) { if (hdmi_msm_state->hdcp_activating) { /* * Let the HDCP work know that we got an HPD * disconnect so that it can stop the * reauthentication loop. */ mutex_lock(&hdcp_auth_state_mutex); hdmi_msm_state->hpd_during_auth = TRUE; mutex_unlock(&hdcp_auth_state_mutex); } /* * Cancel any pending reauth attempts. * If one is ongoing, wait for it to finish */ cancel_work_sync(&hdmi_msm_state->hdcp_reauth_work); cancel_work_sync(&hdmi_msm_state->hdcp_work); del_timer_sync(&hdmi_msm_state->hdcp_timer); hdcp_deauthenticate(); } SWITCH_SET_HDMI_AUDIO(0, 0); if (!hdmi_msm_is_dvi_mode()) hdmi_msm_audio_off(); hdmi_msm_powerdown_phy(); hdmi_msm_state->panel_power_on = FALSE; DEV_INFO("power: OFF (audio off)\n"); if (!completion_done(&hdmi_msm_state->hpd_event_processed)) complete(&hdmi_msm_state->hpd_event_processed); error: /* Set HPD cable sense polarity */ hdmi_msm_hpd_polarity_setup(); return ret; } void hdmi_msm_config_hdcp_feature(void) { if (hdcp_feature_on && hdmi_msm_has_hdcp()) { init_timer(&hdmi_msm_state->hdcp_timer); hdmi_msm_state->hdcp_timer.function = hdmi_msm_hdcp_timer; hdmi_msm_state->hdcp_timer.data = (uint32)NULL; hdmi_msm_state->hdcp_timer.expires = 0xffffffffL; init_completion(&hdmi_msm_state->hdcp_success_done); INIT_WORK(&hdmi_msm_state->hdcp_reauth_work, hdmi_msm_hdcp_reauth_work); INIT_WORK(&hdmi_msm_state->hdcp_work, hdmi_msm_hdcp_work); hdmi_msm_state->hdcp_enable = TRUE; } else { del_timer(&hdmi_msm_state->hdcp_timer); hdmi_msm_state->hdcp_enable = FALSE; } external_common_state->present_hdcp = hdmi_msm_state->hdcp_enable; DEV_INFO("%s: HDCP Feature: %s\n", __func__, hdmi_msm_state->hdcp_enable ? "Enabled" : "Disabled"); } static int __devinit hdmi_msm_probe(struct platform_device *pdev) { int rc; struct platform_device *fb_dev; if (!hdmi_msm_state) { pr_err("%s: hdmi_msm_state is NULL\n", __func__); return -ENOMEM; } external_common_state->dev = &pdev->dev; DEV_DBG("probe\n"); if (pdev->id == 0) { struct resource *res; #define GET_RES(name, mode) do { \ res = platform_get_resource_byname(pdev, mode, name); \ if (!res) { \ DEV_ERR("'" name "' resource not found\n"); \ rc = -ENODEV; \ goto error; \ } \ } while (0) #define IO_REMAP(var, name) do { \ GET_RES(name, IORESOURCE_MEM); \ var = ioremap(res->start, resource_size(res)); \ if (!var) { \ DEV_ERR("'" name "' ioremap failed\n"); \ rc = -ENOMEM; \ goto error; \ } \ } while (0) #define GET_IRQ(var, name) do { \ GET_RES(name, IORESOURCE_IRQ); \ var = res->start; \ } while (0) IO_REMAP(hdmi_msm_state->qfprom_io, "hdmi_msm_qfprom_addr"); hdmi_msm_state->hdmi_io = MSM_HDMI_BASE; GET_IRQ(hdmi_msm_state->irq, "hdmi_msm_irq"); hdmi_msm_state->pd = pdev->dev.platform_data; #undef GET_RES #undef IO_REMAP #undef GET_IRQ return 0; } hdmi_msm_state->hdmi_app_clk = clk_get(&pdev->dev, "core_clk"); if (IS_ERR(hdmi_msm_state->hdmi_app_clk)) { DEV_ERR("'core_clk' clk not found\n"); rc = IS_ERR(hdmi_msm_state->hdmi_app_clk); goto error; } hdmi_msm_state->hdmi_m_pclk = clk_get(&pdev->dev, "master_iface_clk"); if (IS_ERR(hdmi_msm_state->hdmi_m_pclk)) { DEV_ERR("'master_iface_clk' clk not found\n"); rc = IS_ERR(hdmi_msm_state->hdmi_m_pclk); goto error; } hdmi_msm_state->hdmi_s_pclk = clk_get(&pdev->dev, "slave_iface_clk"); if (IS_ERR(hdmi_msm_state->hdmi_s_pclk)) { DEV_ERR("'slave_iface_clk' clk not found\n"); rc = IS_ERR(hdmi_msm_state->hdmi_s_pclk); goto error; } hdmi_msm_state->is_mhl_enabled = hdmi_msm_state->pd->is_mhl_enabled; rc = check_hdmi_features(); if (rc) { DEV_ERR("Init FAILED: check_hdmi_features rc=%d\n", rc); goto error; } if (!hdmi_msm_state->pd->core_power) { DEV_ERR("Init FAILED: core_power function missing\n"); rc = -ENODEV; goto error; } if (!hdmi_msm_state->pd->enable_5v) { DEV_ERR("Init FAILED: enable_5v function missing\n"); rc = -ENODEV; goto error; } if (!hdmi_msm_state->pd->cec_power) { DEV_ERR("Init FAILED: cec_power function missing\n"); rc = -ENODEV; goto error; } rc = request_threaded_irq(hdmi_msm_state->irq, NULL, &hdmi_msm_isr, IRQF_TRIGGER_HIGH | IRQF_ONESHOT, "hdmi_msm_isr", NULL); if (rc) { DEV_ERR("Init FAILED: IRQ request, rc=%d\n", rc); goto error; } disable_irq(hdmi_msm_state->irq); #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT init_timer(&hdmi_msm_state->cec_read_timer); hdmi_msm_state->cec_read_timer.function = hdmi_msm_cec_read_timer_func; hdmi_msm_state->cec_read_timer.data = (uint32)NULL; hdmi_msm_state->cec_read_timer.expires = 0xffffffffL; #endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT */ fb_dev = msm_fb_add_device(pdev); if (fb_dev) { rc = external_common_state_create(fb_dev); if (rc) { DEV_ERR("Init FAILED: hdmi_msm_state_create, rc=%d\n", rc); goto error; } } else DEV_ERR("Init FAILED: failed to add fb device\n"); if (hdmi_prim_display) { rc = hdmi_msm_hpd_on(); if (rc) goto error; } hdmi_msm_config_hdcp_feature(); /* Initialize hdmi node and register with switch driver */ if (hdmi_prim_display) external_common_state->sdev.name = "hdmi_as_primary"; else external_common_state->sdev.name = "hdmi"; if (switch_dev_register(&external_common_state->sdev) < 0) { DEV_ERR("Hdmi switch registration failed\n"); rc = -ENODEV; goto error; } external_common_state->audio_sdev.name = "hdmi_audio"; if (switch_dev_register(&external_common_state->audio_sdev) < 0) { DEV_ERR("Hdmi audio switch registration failed\n"); switch_dev_unregister(&external_common_state->sdev); rc = -ENODEV; goto error; } return 0; error: if (hdmi_msm_state->qfprom_io) iounmap(hdmi_msm_state->qfprom_io); hdmi_msm_state->qfprom_io = NULL; if (hdmi_msm_state->hdmi_io) iounmap(hdmi_msm_state->hdmi_io); hdmi_msm_state->hdmi_io = NULL; external_common_state_remove(); if (hdmi_msm_state->hdmi_app_clk) clk_put(hdmi_msm_state->hdmi_app_clk); if (hdmi_msm_state->hdmi_m_pclk) clk_put(hdmi_msm_state->hdmi_m_pclk); if (hdmi_msm_state->hdmi_s_pclk) clk_put(hdmi_msm_state->hdmi_s_pclk); hdmi_msm_state->hdmi_app_clk = NULL; hdmi_msm_state->hdmi_m_pclk = NULL; hdmi_msm_state->hdmi_s_pclk = NULL; return rc; } static int __devexit hdmi_msm_remove(struct platform_device *pdev) { DEV_INFO("HDMI device: remove\n"); DEV_INFO("HDMI HPD: OFF\n"); /* Unregister hdmi node from switch driver */ switch_dev_unregister(&external_common_state->sdev); switch_dev_unregister(&external_common_state->audio_sdev); hdmi_msm_hpd_off(); free_irq(hdmi_msm_state->irq, NULL); if (hdmi_msm_state->qfprom_io) iounmap(hdmi_msm_state->qfprom_io); hdmi_msm_state->qfprom_io = NULL; if (hdmi_msm_state->hdmi_io) iounmap(hdmi_msm_state->hdmi_io); hdmi_msm_state->hdmi_io = NULL; external_common_state_remove(); if (hdmi_msm_state->hdmi_app_clk) clk_put(hdmi_msm_state->hdmi_app_clk); if (hdmi_msm_state->hdmi_m_pclk) clk_put(hdmi_msm_state->hdmi_m_pclk); if (hdmi_msm_state->hdmi_s_pclk) clk_put(hdmi_msm_state->hdmi_s_pclk); hdmi_msm_state->hdmi_app_clk = NULL; hdmi_msm_state->hdmi_m_pclk = NULL; hdmi_msm_state->hdmi_s_pclk = NULL; kfree(hdmi_msm_state); hdmi_msm_state = NULL; return 0; } static int hdmi_msm_hpd_feature(int on) { int rc = 0; DEV_INFO("%s: %d\n", __func__, on); if (on) { rc = hdmi_msm_hpd_on(); } else { if (external_common_state->hpd_state) { external_common_state->hpd_state = 0; /* Send offline event to switch OFF HDMI and HAL FD */ hdmi_msm_send_event(HPD_EVENT_OFFLINE); /* Wait for HDMI and FD to close */ INIT_COMPLETION(hdmi_msm_state->hpd_event_processed); wait_for_completion_interruptible_timeout( &hdmi_msm_state->hpd_event_processed, HZ); } hdmi_msm_hpd_off(); /* Set HDMI switch node to 0 on HPD feature disable */ switch_set_state(&external_common_state->sdev, 0); DEV_INFO("%s: hdmi state switched to %d\n", __func__, external_common_state->sdev.state); } return rc; } static struct platform_driver this_driver = { .probe = hdmi_msm_probe, .remove = hdmi_msm_remove, .driver.name = "hdmi_msm", }; static struct msm_fb_panel_data hdmi_msm_panel_data = { .on = hdmi_msm_power_on, .off = hdmi_msm_power_off, .power_ctrl = hdmi_msm_power_ctrl, }; static struct platform_device this_device = { .name = "hdmi_msm", .id = 1, .dev.platform_data = &hdmi_msm_panel_data, }; static int __init hdmi_msm_init(void) { int rc; if (msm_fb_detect_client("hdmi_msm")) return 0; #ifdef CONFIG_FB_MSM_HDMI_AS_PRIMARY hdmi_prim_display = 1; #endif hdmi_msm_setup_video_mode_lut(); hdmi_msm_state = kzalloc(sizeof(*hdmi_msm_state), GFP_KERNEL); if (!hdmi_msm_state) { pr_err("hdmi_msm_init FAILED: out of memory\n"); rc = -ENOMEM; goto init_exit; } external_common_state = &hdmi_msm_state->common; if (hdmi_prim_display && hdmi_prim_resolution) external_common_state->video_resolution = hdmi_prim_resolution - 1; else external_common_state->video_resolution = HDMI_VFRMT_1920x1080p60_16_9; #ifdef CONFIG_FB_MSM_HDMI_3D external_common_state->switch_3d = hdmi_msm_switch_3d; #endif memset(external_common_state->spd_vendor_name, 0, sizeof(external_common_state->spd_vendor_name)); memset(external_common_state->spd_product_description, 0, sizeof(external_common_state->spd_product_description)); #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT hdmi_msm_state->cec_queue_start = kzalloc(sizeof(struct hdmi_msm_cec_msg)*CEC_QUEUE_SIZE, GFP_KERNEL); if (!hdmi_msm_state->cec_queue_start) { pr_err("hdmi_msm_init FAILED: CEC queue out of memory\n"); rc = -ENOMEM; goto init_exit; } hdmi_msm_state->cec_queue_wr = hdmi_msm_state->cec_queue_start; hdmi_msm_state->cec_queue_rd = hdmi_msm_state->cec_queue_start; hdmi_msm_state->cec_queue_full = false; #endif /* * Create your work queue * allocs and returns ptr */ hdmi_work_queue = create_workqueue("hdmi_hdcp"); external_common_state->hpd_feature = hdmi_msm_hpd_feature; rc = platform_driver_register(&this_driver); if (rc) { pr_err("hdmi_msm_init FAILED: platform_driver_register rc=%d\n", rc); goto init_exit; } hdmi_common_init_panel_info(&hdmi_msm_panel_data.panel_info); init_completion(&hdmi_msm_state->ddc_sw_done); init_completion(&hdmi_msm_state->hpd_event_processed); INIT_WORK(&hdmi_msm_state->hpd_state_work, hdmi_msm_hpd_state_work); #ifdef CONFIG_FB_MSM_HDMI_MSM_PANEL_CEC_SUPPORT INIT_WORK(&hdmi_msm_state->cec_latch_detect_work, hdmi_msm_cec_latch_work); init_completion(&hdmi_msm_state->cec_frame_wr_done); init_completion(&hdmi_msm_state->cec_line_latch_wait); #endif rc = platform_device_register(&this_device); if (rc) { pr_err("hdmi_msm_init FAILED: platform_device_register rc=%d\n", rc); platform_driver_unregister(&this_driver); goto init_exit; } pr_debug("%s: success:" #ifdef DEBUG " DEBUG" #else " RELEASE" #endif " AUDIO EDID HPD HDCP" " DVI" #ifndef CONFIG_FB_MSM_HDMI_MSM_PANEL_DVI_SUPPORT ":0" #endif /* CONFIG_FB_MSM_HDMI_MSM_PANEL_DVI_SUPPORT */ "\n", __func__); return 0; init_exit: kfree(hdmi_msm_state); hdmi_msm_state = NULL; return rc; } static void __exit hdmi_msm_exit(void) { platform_device_unregister(&this_device); platform_driver_unregister(&this_driver); } static int set_hdcp_feature_on(const char *val, const struct kernel_param *kp) { int rv = param_set_bool(val, kp); if (rv) return rv; pr_debug("%s: HDCP feature = %d\n", __func__, hdcp_feature_on); if (hdmi_msm_state) { if ((HDMI_INP(0x0250) & 0x2)) { pr_err("%s: Unable to set HDCP feature", __func__); pr_err("%s: HDMI panel is currently turned on", __func__); } else if (hdcp_feature_on != hdmi_msm_state->hdcp_enable) { hdmi_msm_config_hdcp_feature(); } } return 0; } static struct kernel_param_ops hdcp_feature_on_param_ops = { .set = set_hdcp_feature_on, .get = param_get_bool, }; module_param_cb(hdcp, &hdcp_feature_on_param_ops, &hdcp_feature_on, S_IRUGO | S_IWUSR); MODULE_PARM_DESC(hdcp, "Enable or Disable HDCP"); module_init(hdmi_msm_init); module_exit(hdmi_msm_exit); MODULE_LICENSE("GPL v2"); MODULE_VERSION("0.3"); MODULE_AUTHOR("Qualcomm Innovation Center, Inc."); MODULE_DESCRIPTION("HDMI MSM TX driver");
Java
package newpackage; public class DaneWejsciowe { float wartosc; String argument; public DaneWejsciowe( String argument,float wartosc) { this.wartosc = wartosc; this.argument = argument; } }
Java
/** ******************************************************************************** \file ctrlkcal.h \brief Definitions for kernel ctrl CAL module This file contains the definitions for the kernel ctrl CAL module. *******************************************************************************/ /*------------------------------------------------------------------------------ Copyright (c) 2014, Bernecker+Rainer Industrie-Elektronik Ges.m.b.H. (B&R) 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 copyright holders nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL COPYRIGHT HOLDERS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ------------------------------------------------------------------------------*/ #ifndef _INC_ctrlkcal_H_ #define _INC_ctrlkcal_H_ //------------------------------------------------------------------------------ // includes //------------------------------------------------------------------------------ #include <common/oplkinc.h> #include <common/ctrl.h> //------------------------------------------------------------------------------ // const defines //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // typedef //------------------------------------------------------------------------------ //------------------------------------------------------------------------------ // function prototypes //------------------------------------------------------------------------------ #ifdef __cplusplus extern "C" { #endif tOplkError ctrlkcal_init(void); void ctrlkcal_exit(void); tOplkError ctrlkcal_process(void); tOplkError ctrlkcal_getCmd(tCtrlCmdType* pCmd_p); void ctrlkcal_sendReturn(UINT16 retval_p); void ctrlkcal_setStatus(UINT16 status_p); UINT16 ctrlkcal_getStatus(void); void ctrlkcal_updateHeartbeat(UINT16 heartbeat_p); tOplkError ctrlkcal_readInitParam(tCtrlInitParam* pInitParam_p); void ctrlkcal_storeInitParam(tCtrlInitParam* pInitParam_p); #ifdef __cplusplus } #endif #endif /* _INC_ctrlkcal_H_ */
Java
<?php /** * Template to display the main page for the new forum * @access public */ $this->setLayoutTemplate('poll_layout_tpl.php'); echo $display.'<br />'; ?>
Java
/* * Copyright (C) 2005-2009 MaNGOS <http://getmangos.com/> * * Copyright (C) 2008-2010 Trinity <http://www.trinitycore.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, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "WorldPacket.h" #include "Opcodes.h" #include "Log.h" #include "ObjectMgr.h" #include "SpellMgr.h" #include "Player.h" #include "Unit.h" #include "Spell.h" #include "SpellAuraEffects.h" #include "DynamicObject.h" #include "ObjectAccessor.h" #include "Util.h" #include "GridNotifiers.h" #include "GridNotifiersImpl.h" #include "CellImpl.h" AuraApplication::AuraApplication(Unit * target, Unit * caster, Aura * aura, uint8 effMask) : m_target(target), m_base(aura), m_slot(MAX_AURAS), m_flags(AFLAG_NONE), m_needClientUpdate(false) , m_removeMode(AURA_REMOVE_NONE), m_effectsToApply(effMask) { assert(GetTarget() && GetBase()); if (GetBase()->IsVisible()) { // Try find slot for aura uint8 slot = MAX_AURAS; // Lookup for auras already applied from spell if (AuraApplication * foundAura = m_target->GetAuraApplication(m_base->GetId(), m_base->GetCasterGUID())) { // allow use single slot only by auras from same caster slot = foundAura->GetSlot(); } else { Unit::VisibleAuraMap const * visibleAuras = m_target->GetVisibleAuras(); // lookup for free slots in units visibleAuras Unit::VisibleAuraMap::const_iterator itr = visibleAuras->find(0); for (uint32 freeSlot = 0; freeSlot < MAX_AURAS; ++itr , ++freeSlot) { if (itr == visibleAuras->end() || itr->first != freeSlot) { slot = freeSlot; break; } } } // Register Visible Aura if (slot < MAX_AURAS) { m_slot = slot; m_target->SetVisibleAura(slot, this); SetNeedClientUpdate(); sLog.outDebug("Aura: %u Effect: %d put to unit visible auras slot: %u", GetBase()->GetId(), GetEffectMask(), slot); } else sLog.outDebug("Aura: %u Effect: %d could not find empty unit visible slot", GetBase()->GetId(), GetEffectMask()); } m_flags |= (_CheckPositive(caster) ? AFLAG_POSITIVE : AFLAG_NEGATIVE) | (GetBase()->GetCasterGUID() == GetTarget()->GetGUID() ? AFLAG_CASTER : AFLAG_NONE); m_isNeedManyNegativeEffects = false; if (GetBase()->GetCasterGUID() == GetTarget()->GetGUID()) // caster == target - 1 negative effect is enough for aura to be negative m_isNeedManyNegativeEffects = false; else if (caster) m_isNeedManyNegativeEffects = caster->IsFriendlyTo(m_target); } void AuraApplication::_Remove() { uint8 slot = GetSlot(); if (slot >= MAX_AURAS) return; if (AuraApplication * foundAura = m_target->GetAuraApplication(GetBase()->GetId(), GetBase()->GetCasterGUID())) { // Reuse visible aura slot by aura which is still applied - prevent storing dead pointers if (slot == foundAura->GetSlot()) { if (GetTarget()->GetVisibleAura(slot) == this) { GetTarget()->SetVisibleAura(slot, foundAura); foundAura->SetNeedClientUpdate(); } // set not valid slot for aura - prevent removing other visible aura slot = MAX_AURAS; } } // update for out of range group members if (slot < MAX_AURAS) { GetTarget()->RemoveVisibleAura(slot); ClientUpdate(true); } } bool AuraApplication::_CheckPositive(Unit * caster) const { // Aura is positive when it is casted by friend and at least one aura is positive // or when it is casted by enemy and at least one aura is negative for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if ((1<<i & GetEffectMask())) { if (m_isNeedManyNegativeEffects == IsPositiveEffect(GetBase()->GetId(), i)) return m_isNeedManyNegativeEffects; } } return !m_isNeedManyNegativeEffects; } void AuraApplication::_HandleEffect(uint8 effIndex, bool apply) { AuraEffect * aurEff = GetBase()->GetEffect(effIndex); assert(aurEff); assert(HasEffect(effIndex) == (!apply)); assert((1<<effIndex) & m_effectsToApply); sLog.outDebug("AuraApplication::_HandleEffect: %u, apply: %u: amount: %u", aurEff->GetAuraType(), apply, aurEff->GetAmount()); Unit * caster = GetBase()->GetCaster(); m_flags &= ~(AFLAG_POSITIVE | AFLAG_NEGATIVE); if (apply) { m_flags |= 1<<effIndex; m_flags |=_CheckPositive(caster) ? AFLAG_POSITIVE : AFLAG_NEGATIVE; GetTarget()->_HandleAuraEffect(aurEff, true); aurEff->HandleEffect(this, AURA_EFFECT_HANDLE_REAL, true); } else { m_flags &= ~(1<<effIndex); m_flags |=_CheckPositive(caster) ? AFLAG_POSITIVE : AFLAG_NEGATIVE; // remove from list before mods removing (prevent cyclic calls, mods added before including to aura list - use reverse order) GetTarget()->_HandleAuraEffect(aurEff, false); aurEff->HandleEffect(this, AURA_EFFECT_HANDLE_REAL, false); // Remove all triggered by aura spells vs unlimited duration aurEff->CleanupTriggeredSpells(GetTarget()); } SetNeedClientUpdate(); } void AuraApplication::ClientUpdate(bool remove) { m_needClientUpdate = false; WorldPacket data(SMSG_AURA_UPDATE); data.append(GetTarget()->GetPackGUID()); data << uint8(m_slot); if (remove) { assert(!m_target->GetVisibleAura(m_slot)); data << uint32(0); sLog.outDebug("Aura %u removed slot %u",GetBase()->GetId(), m_slot); m_target->SendMessageToSet(&data, true); return; } assert(m_target->GetVisibleAura(m_slot)); Aura const * aura = GetBase(); data << uint32(aura->GetId()); uint32 flags = m_flags; if (aura->GetMaxDuration() > 0) flags |= AFLAG_DURATION; data << uint8(flags); data << uint8(aura->GetCasterLevel()); data << uint8(aura->GetStackAmount() > 1 ? aura->GetStackAmount() : (aura->GetCharges()) ? aura->GetCharges() : 1); if (!(flags & AFLAG_CASTER)) data.appendPackGUID(aura->GetCasterGUID()); if (flags & AFLAG_DURATION) { data << uint32(aura->GetMaxDuration()); data << uint32(aura->GetDuration()); } m_target->SendMessageToSet(&data, true); } Aura * Aura::TryCreate(SpellEntry const* spellproto, uint8 tryEffMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) { assert(spellproto); assert(owner); assert(caster || casterGUID); assert(tryEffMask <= MAX_EFFECT_MASK); uint8 effMask = 0; switch(owner->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (IsUnitOwnedAuraEffect(spellproto->Effect[i])) effMask |= 1 << i; } break; case TYPEID_DYNAMICOBJECT: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (spellproto->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA) effMask |= 1 << i; } break; } if (uint8 realMask = effMask & tryEffMask) return Create(spellproto,realMask,owner,caster,baseAmount,castItem,casterGUID); return NULL; } Aura * Aura::TryCreate(SpellEntry const* spellproto, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) { assert(spellproto); assert(owner); assert(caster || casterGUID); uint8 effMask = 0; switch(owner->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (IsUnitOwnedAuraEffect(spellproto->Effect[i])) effMask |= 1 << i; } break; case TYPEID_DYNAMICOBJECT: for (uint8 i = 0; i< MAX_SPELL_EFFECTS; ++i) { if (spellproto->Effect[i] == SPELL_EFFECT_PERSISTENT_AREA_AURA) effMask |= 1 << i; } break; } if (effMask) return Create(spellproto,effMask,owner,caster,baseAmount,castItem,casterGUID); return NULL; } Aura * Aura::Create(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) { assert(effMask); assert(spellproto); assert(owner); assert(caster || casterGUID); assert(effMask <= MAX_EFFECT_MASK); // try to get caster of aura if (casterGUID) { if (owner->GetGUID() == casterGUID) caster = (Unit *)owner; else caster = ObjectAccessor::GetUnit(*owner, casterGUID); } Aura * aura = NULL; switch(owner->GetTypeId()) { case TYPEID_UNIT: case TYPEID_PLAYER: aura = new UnitAura(spellproto,effMask,owner,caster,baseAmount,castItem, casterGUID); break; case TYPEID_DYNAMICOBJECT: aura = new DynObjAura(spellproto,effMask,owner,caster,baseAmount,castItem, casterGUID); break; default: assert(false); return NULL; } // aura can be removed in Unit::_AddAura call if (aura->IsRemoved()) return NULL; return aura; } Aura::Aura(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) : m_spellProto(spellproto), m_owner(owner), m_casterGuid(casterGUID ? casterGUID : caster->GetGUID()), m_castItemGuid(castItem ? castItem->GetGUID() : 0), m_applyTime(time(NULL)), m_timeCla(0), m_isSingleTarget(false), m_updateTargetMapInterval(0), m_procCharges(0), m_stackAmount(1), m_isRemoved(false), m_casterLevel(caster ? caster->getLevel() : m_spellProto->spellLevel) { if (m_spellProto->manaPerSecond || m_spellProto->manaPerSecondPerLevel) m_timeCla = 1 * IN_MILISECONDS; Player* modOwner = NULL; if (caster) { modOwner = caster->GetSpellModOwner(); m_maxDuration = caster->CalcSpellDuration(m_spellProto); } else m_maxDuration = GetSpellDuration(m_spellProto); if (IsPassive() && m_spellProto->DurationIndex == 0) m_maxDuration = -1; if (!IsPermanent() && modOwner) modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, m_maxDuration); m_duration = m_maxDuration; m_procCharges = m_spellProto->procCharges; if (modOwner) modOwner->ApplySpellMod(GetId(), SPELLMOD_CHARGES, m_procCharges); for (uint8 i=0 ; i<MAX_SPELL_EFFECTS; ++i) { if (effMask & (uint8(1) << i)) m_effects[i] = new AuraEffect(this, i, baseAmount ? baseAmount + i : NULL, caster); else m_effects[i] = NULL; } } Aura::~Aura() { // free effects memory for (uint8 i = 0 ; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) delete m_effects[i]; assert(m_applications.empty()); _DeleteRemovedApplications(); } Unit* Aura::GetCaster() const { if (GetOwner()->GetGUID() == GetCasterGUID()) return GetUnitOwner(); if (AuraApplication const * aurApp = GetApplicationOfTarget(GetCasterGUID())) return aurApp->GetTarget(); return ObjectAccessor::GetUnit(*GetOwner(), GetCasterGUID()); } AuraObjectType Aura::GetType() const { return (m_owner->GetTypeId() == TYPEID_DYNAMICOBJECT) ? DYNOBJ_AURA_TYPE : UNIT_AURA_TYPE; } void Aura::_ApplyForTarget(Unit * target, Unit * caster, AuraApplication * auraApp) { assert(target); assert(auraApp); // aura mustn't be already applied assert (m_applications.find(target->GetGUID()) == m_applications.end()); m_applications[target->GetGUID()] = auraApp; // set infinity cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (m_spellProto->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) { Item* castItem = m_castItemGuid ? caster->ToPlayer()->GetItemByGuid(m_castItemGuid) : NULL; caster->ToPlayer()->AddSpellAndCategoryCooldowns(m_spellProto,castItem ? castItem->GetEntry() : 0, NULL,true); } } } void Aura::_UnapplyForTarget(Unit * target, Unit * caster, AuraApplication * auraApp) { assert(target); assert(auraApp->GetRemoveMode()); assert(auraApp); ApplicationMap::iterator itr = m_applications.find(target->GetGUID()); // aura has to be already applied assert(itr->second == auraApp); m_applications.erase(itr); m_removedApplications.push_back(auraApp); // reset cooldown state for spells if (caster && caster->GetTypeId() == TYPEID_PLAYER) { if (GetSpellProto()->Attributes & SPELL_ATTR_DISABLED_WHILE_ACTIVE) // note: item based cooldowns and cooldown spell mods with charges ignored (unknown existed cases) caster->ToPlayer()->SendCooldownEvent(GetSpellProto()); } } // removes aura from all targets // and marks aura as removed void Aura::_Remove(AuraRemoveMode removeMode) { assert (!m_isRemoved); m_isRemoved = true; ApplicationMap::iterator appItr = m_applications.begin(); while (!m_applications.empty()) { AuraApplication * aurApp = appItr->second; Unit * target = aurApp->GetTarget(); target->_UnapplyAura(aurApp, removeMode); appItr = m_applications.begin(); } } void Aura::UpdateTargetMap(Unit * caster, bool apply) { if (IsRemoved()) return; m_updateTargetMapInterval = UPDATE_TARGET_MAP_INTERVAL; // fill up to date target list // target, effMask std::map<Unit *, uint8> targets; FillTargetMap(targets, caster); UnitList targetsToRemove; // mark all auras as ready to remove for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end();++appIter) { std::map<Unit *, uint8>::iterator existing = targets.find(appIter->second->GetTarget()); // not found in current area - remove the aura if (existing == targets.end()) targetsToRemove.push_back(appIter->second->GetTarget()); else { // needs readding - remove now, will be applied in next update cycle // (dbcs do not have auras which apply on same type of targets but have different radius, so this is not really needed) if (appIter->second->GetEffectMask() != existing->second) targetsToRemove.push_back(appIter->second->GetTarget()); // nothing todo - aura already applied // remove from auras to register list targets.erase(existing); } } // register auras for units for (std::map<Unit *, uint8>::iterator itr = targets.begin(); itr!= targets.end();) { bool addUnit = true; // check target immunities if (itr->first->IsImmunedToSpell(GetSpellProto())) addUnit = false; if (addUnit) { // persistent area aura does not hit flying targets if (GetType() == DYNOBJ_AURA_TYPE) { if (itr->first->isInFlight()) addUnit = false; } // unit auras can not stack with each other else // (GetType() == UNIT_AURA_TYPE) { // Allow to remove by stack when aura is going to be applied on owner if (itr->first != GetOwner()) { // check if not stacking aura already on target // this one prevents unwanted usefull buff loss because of stacking and prevents overriding auras periodicaly by 2 near area aura owners for (Unit::AuraApplicationMap::iterator iter = itr->first->GetAppliedAuras().begin(); iter != itr->first->GetAppliedAuras().end(); ++iter) { Aura const * aura = iter->second->GetBase(); if (!spellmgr.CanAurasStack(GetSpellProto(), aura->GetSpellProto(), aura->GetCasterGUID() == GetCasterGUID())) { addUnit = false; break; } } } } } if (!addUnit) targets.erase(itr++); else { // owner has to be in world, or effect has to be applied to self assert((!GetOwner()->IsInWorld() && GetOwner() == itr->first) || GetOwner()->IsInMap(itr->first)); itr->first->_CreateAuraApplication(this, itr->second); ++itr; } } // remove auras from units no longer needing them for (UnitList::iterator itr = targetsToRemove.begin(); itr != targetsToRemove.end();++itr) { if (AuraApplication * aurApp = GetApplicationOfTarget((*itr)->GetGUID())) (*itr)->_UnapplyAura(aurApp, AURA_REMOVE_BY_DEFAULT); } if (!apply) return; // apply aura effects for units for (std::map<Unit *, uint8>::iterator itr = targets.begin(); itr!= targets.end();++itr) { if (AuraApplication * aurApp = GetApplicationOfTarget(itr->first->GetGUID())) { // owner has to be in world, or effect has to be applied to self assert((!GetOwner()->IsInWorld() && GetOwner() == itr->first) || GetOwner()->IsInMap(itr->first)); itr->first->_ApplyAura(aurApp, itr->second); } } } // targets have to be registered and not have effect applied yet to use this function void Aura::_ApplyEffectForTargets(uint8 effIndex) { Unit * caster = GetCaster(); // prepare list of aura targets UnitList targetList; for (ApplicationMap::iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) { if ((appIter->second->GetEffectsToApply() & (1<<effIndex)) && CheckTarget(appIter->second->GetTarget()) && !appIter->second->HasEffect(effIndex)) targetList.push_back(appIter->second->GetTarget()); } // apply effect to targets for (UnitList::iterator itr = targetList.begin(); itr != targetList.end(); ++itr) { if (GetApplicationOfTarget((*itr)->GetGUID())) { // owner has to be in world, or effect has to be applied to self assert((!GetOwner()->IsInWorld() && GetOwner() == *itr) || GetOwner()->IsInMap(*itr)); (*itr)->_ApplyAuraEffect(this, effIndex); } } } void Aura::UpdateOwner(uint32 diff, WorldObject * owner) { assert(owner == m_owner); Unit * caster = GetCaster(); // Apply spellmods for channeled auras // used for example when triggered spell of spell:10 is modded Spell * modSpell = NULL; Player * modOwner = NULL; if (caster) if ((modOwner = caster->GetSpellModOwner()) && (modSpell = modOwner->FindCurrentSpellBySpellId(GetId()))) modOwner->SetSpellModTakingSpell(modSpell, true); Update(diff, caster); if (m_updateTargetMapInterval <= diff) UpdateTargetMap(caster); else m_updateTargetMapInterval -= diff; // update aura effects for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) m_effects[i]->Update(diff, caster); // remove spellmods after effects update if (modSpell) modOwner->SetSpellModTakingSpell(modSpell, false); _DeleteRemovedApplications(); } void Aura::Update(uint32 diff, Unit * caster) { if (m_duration > 0) { m_duration -= diff; if (m_duration < 0) m_duration = 0; // handle manaPerSecond/manaPerSecondPerLevel if (m_timeCla) { if (m_timeCla > diff) m_timeCla -= diff; else if (caster) { if (int32 manaPerSecond = m_spellProto->manaPerSecond + m_spellProto->manaPerSecondPerLevel * caster->getLevel()) { m_timeCla += 1000 - diff; Powers powertype = Powers(m_spellProto->powerType); if (powertype == POWER_HEALTH) { if (caster->GetHealth() > manaPerSecond) caster->ModifyHealth(-manaPerSecond); else { Remove(); return; } } else { if (caster->GetPower(powertype) >= manaPerSecond) caster->ModifyPower(powertype, -manaPerSecond); else { Remove(); return; } } } } } } } bool Aura::CheckTarget(Unit *target) { // some special cases switch(GetId()) { case 45828: // AV Marshal's HP/DMG auras case 45829: case 45830: case 45821: case 45822: // AV Warmaster's HP/DMG auras case 45823: case 45824: case 45826: switch(target->GetEntry()) { // alliance case 14762: // Dun Baldar North Marshal case 14763: // Dun Baldar South Marshal case 14764: // Icewing Marshal case 14765: // Stonehearth Marshal case 11948: // Vandar Stormspike // horde case 14772: // East Frostwolf Warmaster case 14776: // Tower Point Warmaster case 14773: // Iceblood Warmaster case 14777: // West Frostwolf Warmaster case 11946: // Drek'thar return true; default: return false; break; } break; default: return true; break; } } void Aura::SetDuration(int32 duration, bool withMods) { if (withMods) { if (Unit * caster = GetCaster()) if (Player * modOwner = caster->GetSpellModOwner()) modOwner->ApplySpellMod(GetId(), SPELLMOD_DURATION, duration); } m_duration = duration; SetNeedClientUpdateForTargets(); } void Aura::RefreshDuration() { SetDuration(GetMaxDuration()); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) m_effects[i]->ResetPeriodic(); if (m_spellProto->manaPerSecond || m_spellProto->manaPerSecondPerLevel) m_timeCla = 1 * IN_MILISECONDS; } void Aura::SetCharges(uint8 charges) { if (m_procCharges == charges) return; m_procCharges = charges; SetNeedClientUpdateForTargets(); } bool Aura::DropCharge() { if (m_procCharges) //auras without charges always have charge = 0 { if (--m_procCharges) // Send charge change SetNeedClientUpdateForTargets(); else // Last charge dropped { Remove(AURA_REMOVE_BY_EXPIRE); return true; } } return false; } void Aura::SetStackAmount(uint8 stackAmount, bool applied) { if (stackAmount != m_stackAmount) { m_stackAmount = stackAmount; RecalculateAmountOfEffects(); } SetNeedClientUpdateForTargets(); } bool Aura::ModStackAmount(int32 num) { // Can`t mod if (!m_spellProto->StackAmount || !GetStackAmount()) return true; // Modify stack but limit it int32 stackAmount = m_stackAmount + num; if (stackAmount > m_spellProto->StackAmount) stackAmount = m_spellProto->StackAmount; else if (stackAmount <= 0) // Last aura from stack removed { m_stackAmount = 0; return true; // need remove aura } bool refresh = stackAmount >= GetStackAmount(); // Update stack amount SetStackAmount(stackAmount); if (refresh) RefreshDuration(); SetNeedClientUpdateForTargets(); return false; } bool Aura::IsPassive() const { return IsPassiveSpell(GetSpellProto()); } bool Aura::IsDeathPersistent() const { return IsDeathPersistentSpell(GetSpellProto()); } bool Aura::CanBeSaved() const { if (IsPassive()) return false; if (GetCasterGUID() != GetOwner()->GetGUID()) if (IsSingleTargetSpell(GetSpellProto())) return false; // Can't be saved - aura handler relies on calculated amount and changes it if (HasEffectType(SPELL_AURA_CONVERT_RUNE)) return false; return true; } bool Aura::HasEffectType(AuraType type) const { for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) { if (m_effects[i] && m_effects[i]->GetAuraType() == type) return true; } return false; } void Aura::RecalculateAmountOfEffects() { assert (!IsRemoved()); Unit * caster = GetCaster(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) m_effects[i]->RecalculateAmount(caster); } void Aura::HandleAllEffects(AuraApplication const * aurApp, uint8 mode, bool apply) { assert (!IsRemoved()); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i] && !IsRemoved()) m_effects[i]->HandleEffect(aurApp, mode, apply); } bool Aura::IsVisible() const { // Is this blizzlike? show totem passive auras if (GetOwner()->GetTypeId() == TYPEID_UNIT && m_owner->ToCreature()->isTotem() && IsPassive()) return true; return !IsPassive() || HasEffectType(SPELL_AURA_ABILITY_IGNORE_AURASTATE); } void Aura::UnregisterSingleTarget() { assert(m_isSingleTarget); Unit * caster = GetCaster(); caster->GetSingleCastAuras().remove(this); SetIsSingleTarget(false); } void Aura::SetLoadedState(int32 maxduration, int32 duration, int32 charges, uint8 stackamount, uint8 recalculateMask, int32 * amount) { m_maxDuration = maxduration; m_duration = duration; m_procCharges = charges; m_stackAmount = stackamount; Unit * caster = GetCaster(); for (uint8 i = 0; i < MAX_SPELL_EFFECTS; ++i) if (m_effects[i]) { m_effects[i]->SetAmount(amount[i]); m_effects[i]->SetCanBeRecalculated(recalculateMask & (1<<i)); m_effects[i]->CalculatePeriodic(caster); m_effects[i]->CalculateSpellMod(); m_effects[i]->RecalculateAmount(caster); } } // trigger effects on real aura apply/remove void Aura::HandleAuraSpecificMods(AuraApplication const * aurApp, Unit * caster, bool apply) { Unit * target = aurApp->GetTarget(); AuraRemoveMode removeMode = aurApp->GetRemoveMode(); // spell_area table SpellAreaForAreaMapBounds saBounds = spellmgr.GetSpellAreaForAuraMapBounds(GetId()); if (saBounds.first != saBounds.second) { uint32 zone, area; target->GetZoneAndAreaId(zone,area); for (SpellAreaForAreaMap::const_iterator itr = saBounds.first; itr != saBounds.second; ++itr) { // some auras remove at aura remove if (!itr->second->IsFitToRequirements((Player*)target,zone,area)) target->RemoveAurasDueToSpell(itr->second->spellId); // some auras applied at aura apply else if (itr->second->autocast) { if (!target->HasAura(itr->second->spellId)) target->CastSpell(target,itr->second->spellId,true); } } } // mods at aura apply if (apply) { // Apply linked auras (On first aura apply) if (spellmgr.GetSpellCustomAttr(GetId()) & SPELL_ATTR_CU_LINK_AURA) { if (const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(GetId() + SPELL_LINK_AURA)) for (std::vector<int32>::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) { if (*itr < 0) target->ApplySpellImmune(GetId(), IMMUNITY_ID, -(*itr), true); else if (caster) caster->AddAura(*itr, target); } } switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: switch(GetId()) { case 32474: // Buffeting Winds of Susurrus if (target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->ActivateTaxiPathTo(506, GetId()); break; case 33572: // Gronn Lord's Grasp, becomes stoned if (GetStackAmount() >= 5 && !target->HasAura(33652)) target->CastSpell(target, 33652, true); break; case 60970: // Heroic Fury (remove Intercept cooldown) if (target->GetTypeId() == TYPEID_PLAYER) target->ToPlayer()->RemoveSpellCooldown(20252, true); break; } break; case SPELLFAMILY_MAGE: if (!caster) break; if (GetSpellProto()->SpellFamilyFlags[0] & 0x00000001 && GetSpellProto()->SpellFamilyFlags[2] & 0x00000008) { // Glyph of Fireball if (caster->HasAura(56368)) SetDuration(0); } else if (GetSpellProto()->SpellFamilyFlags[0] & 0x00000020 && GetSpellProto()->SpellVisual[0] == 13) { // Glyph of Frostbolt if (caster->HasAura(56370)) SetDuration(0); } // Todo: This should be moved to similar function in spell::hit else if (GetSpellProto()->SpellFamilyFlags[0] & 0x01000000) { // Polymorph Sound - Sheep && Penguin if (GetSpellProto()->SpellIconID == 82 && GetSpellProto()->SpellVisual[0] == 12978) { // Glyph of the Penguin if (caster->HasAura(52648)) caster->CastSpell(target,61635,true); else caster->CastSpell(target,61634,true); } } switch(GetId()) { case 12536: // Clearcasting case 12043: // Presence of Mind // Arcane Potency if (AuraEffect const * aurEff = caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_MAGE, 2120, 0)) { if (roll_chance_i(aurEff->GetAmount())) { uint32 spellId = 0; switch (aurEff->GetId()) { case 31571: spellId = 57529; break; case 31572: spellId = 57531; break; default: sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Arcane Potency (%d) found", aurEff->GetId()); } if (spellId) caster->CastSpell(caster, spellId, true); } } break; } break; case SPELLFAMILY_WARLOCK: switch(GetId()) { case 48020: // Demonic Circle if (target->GetTypeId() == TYPEID_PLAYER) if (GameObject* obj = target->GetGameObject(48018)) { target->ToPlayer()->TeleportTo(obj->GetMapId(),obj->GetPositionX(),obj->GetPositionY(),obj->GetPositionZ(),obj->GetOrientation()); target->ToPlayer()->RemoveMovementImpairingAuras(); } break; } break; case SPELLFAMILY_PRIEST: if (!caster) break; // Devouring Plague if (GetSpellProto()->SpellFamilyFlags[0] & 0x02000000 && GetEffect(0)) { // Improved Devouring Plague if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 3790, 1)) { int32 basepoints0 = aurEff->GetAmount() * GetEffect(0)->GetTotalTicks() * GetEffect(0)->GetAmount() / 100; caster->CastCustomSpell(target, 63675, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); } } // Renew else if (GetSpellProto()->SpellFamilyFlags[0] & 0x00000040 && GetEffect(0)) { // Empowered Renew if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 3021, 1)) { int32 basepoints0 = aurEff->GetAmount() * GetEffect(0)->GetTotalTicks() * caster->SpellHealingBonus(target, GetSpellProto(), GetEffect(0)->GetAmount(), HEAL) / 100; caster->CastCustomSpell(target, 63544, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); } } // Power Word: Shield else if (m_spellProto->SpellFamilyFlags[0] & 0x1 && m_spellProto->SpellFamilyFlags[2] & 0x400 && GetEffect(0)) { // Glyph of Power Word: Shield if (AuraEffect* glyph = caster->GetAuraEffect(55672,0)) { // instantly heal m_amount% of the absorb-value int32 heal = glyph->GetAmount() * GetEffect(0)->GetAmount()/100; caster->CastCustomSpell(GetUnitOwner(), 56160, &heal, NULL, NULL, true, 0, GetEffect(0)); } } break; case SPELLFAMILY_ROGUE: // Sprint (skip non player casted spells by category) if (GetSpellProto()->SpellFamilyFlags[0] & 0x40 && GetSpellProto()->Category == 44) // in official maybe there is only one icon? if (target->HasAura(58039)) // Glyph of Blurred Speed target->CastSpell(target, 61922, true); // Sprint (waterwalk) break; case SPELLFAMILY_DEATHKNIGHT: if (!caster) break; // Frost Fever and Blood Plague if (GetSpellProto()->SpellFamilyFlags[2] & 0x2) { // Can't proc on self if (GetCasterGUID() == target->GetGUID()) break; AuraEffect * aurEff = NULL; // Ebon Plaguebringer / Crypt Fever Unit::AuraEffectList const& TalentAuras = caster->GetAuraEffectsByType(SPELL_AURA_OVERRIDE_CLASS_SCRIPTS); for (Unit::AuraEffectList::const_iterator itr = TalentAuras.begin(); itr != TalentAuras.end(); ++itr) { if ((*itr)->GetMiscValue() == 7282) { aurEff = *itr; // Ebon Plaguebringer - end search if found if ((*itr)->GetSpellProto()->SpellIconID == 1766) break; } } if (aurEff) { uint32 spellId = 0; switch (aurEff->GetId()) { // Ebon Plague case 51161: spellId = 51735; break; case 51160: spellId = 51734; break; case 51099: spellId = 51726; break; // Crypt Fever case 49632: spellId = 50510; break; case 49631: spellId = 50509; break; case 49032: spellId = 50508; break; default: sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Crypt Fever/Ebon Plague (%d) found", aurEff->GetId()); } caster->CastSpell(target, spellId, true, 0, GetEffect(0)); } } break; } } // mods at aura remove else { // Remove Linked Auras if (removeMode != AURA_REMOVE_BY_STACK && removeMode != AURA_REMOVE_BY_DEATH) { if (uint32 customAttr = spellmgr.GetSpellCustomAttr(GetId())) { if (customAttr & SPELL_ATTR_CU_LINK_REMOVE) { if (const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(-(int32)GetId())) for (std::vector<int32>::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) { if (*itr < 0) target->RemoveAurasDueToSpell(-(*itr)); else if (removeMode != AURA_REMOVE_BY_DEFAULT) target->CastSpell(target, *itr, true, 0, 0, GetCasterGUID()); } } if (customAttr & SPELL_ATTR_CU_LINK_AURA) { if (const std::vector<int32> *spell_triggered = spellmgr.GetSpellLinked(GetId() + SPELL_LINK_AURA)) for (std::vector<int32>::const_iterator itr = spell_triggered->begin(); itr != spell_triggered->end(); ++itr) { if (*itr < 0) target->ApplySpellImmune(GetId(), IMMUNITY_ID, -(*itr), false); else target->RemoveAurasDueToSpell(*itr); } } } } switch(GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_GENERIC: // Remove the immunity shield marker on Avenging Wrath removal if Forbearance is not present if (GetId() == 61987 && target->HasAura(61988) && !target->HasAura(25771)) target->RemoveAura(61988); break; case SPELLFAMILY_MAGE: switch(GetId()) { case 66: // Invisibility if (removeMode != AURA_REMOVE_BY_EXPIRE) break; target->CastSpell(target, 32612, true, NULL, GetEffect(1)); break; } if (!caster) break; // Ice barrier - dispel/absorb remove if (removeMode == AURA_REMOVE_BY_ENEMY_SPELL && GetSpellProto()->SpellFamilyFlags[1] & 0x1) { // Shattered Barrier if (caster->GetDummyAuraEffect(SPELLFAMILY_MAGE, 2945, 0)) caster->CastSpell(target, 55080, true, NULL, GetEffect(0)); } break; case SPELLFAMILY_WARRIOR: if (!caster) break; // Spell Reflection if (GetSpellProto()->SpellFamilyFlags[1] & 0x2) { if (removeMode != AURA_REMOVE_BY_DEFAULT) { // Improved Spell Reflection if (caster->GetDummyAuraEffect(SPELLFAMILY_WARRIOR,1935, 1)) { // aura remove - remove auras from all party members std::list<Unit*> PartyMembers; target->GetPartyMembers(PartyMembers); for (std::list<Unit*>::iterator itr = PartyMembers.begin(); itr != PartyMembers.end(); ++itr) { if ((*itr)!= target) (*itr)->RemoveAurasWithFamily(SPELLFAMILY_WARRIOR, 0, 0x2, 0, GetCasterGUID()); } } } } break; case SPELLFAMILY_WARLOCK: if (!caster) break; // Curse of Doom if (GetSpellProto()->SpellFamilyFlags[1] & 0x02) { if (removeMode == AURA_REMOVE_BY_DEATH) { if (caster->GetTypeId() == TYPEID_PLAYER && caster->ToPlayer()->isHonorOrXPTarget(target)) caster->CastSpell(target, 18662, true, NULL, GetEffect(0)); } } // Improved Fear else if (GetSpellProto()->SpellFamilyFlags[1] & 0x00000400) { if (AuraEffect* aurEff = caster->GetAuraEffect(SPELL_AURA_DUMMY, SPELLFAMILY_WARLOCK, 98, 0)) { uint32 spellId = 0; switch (aurEff->GetId()) { case 53759: spellId = 60947; break; case 53754: spellId = 60946; break; default: sLog.outError("Aura::HandleAuraSpecificMods: Unknown rank of Improved Fear (%d) found", aurEff->GetId()); } if (spellId) caster->CastSpell(target, spellId, true); } } switch(GetId()) { case 48018: // Demonic Circle // Do not remove GO when aura is removed by stack // to prevent remove GO added by new spell // old one is already removed if (removeMode != AURA_REMOVE_BY_STACK) target->RemoveGameObject(GetId(), true); target->RemoveAura(62388); break; } break; case SPELLFAMILY_PRIEST: if (!caster) break; // Shadow word: Pain // Vampiric Touch if (removeMode == AURA_REMOVE_BY_ENEMY_SPELL && (GetSpellProto()->SpellFamilyFlags[0] & 0x00008000 || GetSpellProto()->SpellFamilyFlags[1] & 0x00000400)) { // Shadow Affinity if (AuraEffect const * aurEff = caster->GetDummyAuraEffect(SPELLFAMILY_PRIEST, 178, 1)) { int32 basepoints0 = aurEff->GetAmount() * caster->GetCreateMana() / 100; caster->CastCustomSpell(caster, 64103, &basepoints0, NULL, NULL, true, NULL, GetEffect(0)); } } // Power word: shield else if (removeMode == AURA_REMOVE_BY_ENEMY_SPELL && GetSpellProto()->SpellFamilyFlags[0] & 0x00000001) { // Rapture if (Aura const * aura = caster->GetAuraOfRankedSpell(47535)) { // check cooldown if (caster->GetTypeId() == TYPEID_PLAYER) { if (caster->ToPlayer()->HasSpellCooldown(aura->GetId())) break; // and add if needed caster->ToPlayer()->AddSpellCooldown(aura->GetId(), 0, uint32(time(NULL) + 12)); } // effect on caster if (AuraEffect const * aurEff = aura->GetEffect(0)) { float multiplier = aurEff->GetAmount(); if (aurEff->GetId() == 47535) multiplier -= 0.5f; else if (aurEff->GetId() == 47537) multiplier += 0.5f; int32 basepoints0 = (multiplier * caster->GetMaxPower(POWER_MANA) / 100); caster->CastCustomSpell(caster, 47755, &basepoints0, NULL, NULL, true); } // effect on aura target if (AuraEffect const * aurEff = aura->GetEffect(1)) { if (!roll_chance_i(aurEff->GetAmount())) break; int32 triggeredSpellId = 0; switch(target->getPowerType()) { case POWER_MANA: { int32 basepoints0 = 2 * (target->GetMaxPower(POWER_MANA) / 100); caster->CastCustomSpell(target, 63654, &basepoints0, NULL, NULL, true); break; } case POWER_RAGE: triggeredSpellId = 63653; break; case POWER_ENERGY: triggeredSpellId = 63655; break; case POWER_RUNIC_POWER: triggeredSpellId = 63652; break; } if (triggeredSpellId) caster->CastSpell(target, triggeredSpellId, true); } } } switch(GetId()) { case 47788: // Guardian Spirit if (removeMode != AURA_REMOVE_BY_EXPIRE) break; if (caster->GetTypeId() != TYPEID_PLAYER) break; Player *player = caster->ToPlayer(); // Glyph of Guardian Spirit if (AuraEffect * aurEff = player->GetAuraEffect(63231, 0)) { if (!player->HasSpellCooldown(47788)) break; player->RemoveSpellCooldown(GetSpellProto()->Id, true); player->AddSpellCooldown(GetSpellProto()->Id, 0, uint32(time(NULL) + aurEff->GetAmount())); WorldPacket data(SMSG_SPELL_COOLDOWN, 8+1+4+4); data << uint64(player->GetGUID()); data << uint8(0x0); // flags (0x1, 0x2) data << uint32(GetSpellProto()->Id); data << uint32(aurEff->GetAmount()*IN_MILISECONDS); player->SendDirectMessage(&data); } break; } break; case SPELLFAMILY_PALADIN: // Remove the immunity shield marker on Forbearance removal if AW marker is not present if (GetId() == 25771 && target->HasAura(61988) && !target->HasAura(61987)) target->RemoveAura(61988); break; case SPELLFAMILY_DEATHKNIGHT: // Blood of the North // Reaping // Death Rune Mastery if (GetSpellProto()->SpellIconID == 3041 || GetSpellProto()->SpellIconID == 22 || GetSpellProto()->SpellIconID == 2622) { if (!GetEffect(0) || GetEffect(0)->GetAuraType() != SPELL_AURA_PERIODIC_DUMMY) break; if (target->GetTypeId() != TYPEID_PLAYER) break; if (target->ToPlayer()->getClass() != CLASS_DEATH_KNIGHT) break; // aura removed - remove death runes target->ToPlayer()->RemoveRunesByAuraEffect(GetEffect(0)); } switch(GetId()) { case 50514: // Summon Gargoyle if (removeMode != AURA_REMOVE_BY_EXPIRE) break; target->CastSpell(target, GetEffect(0)->GetAmount(), true, NULL, GetEffect(0)); break; } break; } } // mods at aura apply or remove switch (GetSpellProto()->SpellFamilyName) { case SPELLFAMILY_ROGUE: // Stealth if (GetSpellProto()->SpellFamilyFlags[0] & 0x00400000) { // Master of subtlety if (AuraEffect const * aurEff = target->GetAuraEffectOfRankedSpell(31221, 0)) { if (!apply) target->CastSpell(target,31666,true); else { int32 basepoints0 = aurEff->GetAmount(); target->CastCustomSpell(target,31665, &basepoints0, NULL, NULL ,true); } } // Overkill if (target->HasAura(58426)) { if (!apply) target->CastSpell(target,58428,true); else target->CastSpell(target,58427,true); } break; } break; case SPELLFAMILY_HUNTER: switch(GetId()) { case 19574: // Bestial Wrath // The Beast Within cast on owner if talent present if (Unit* owner = target->GetOwner()) { // Search talent if (owner->HasAura(34692)) { if (apply) owner->CastSpell(owner, 34471, true, 0, GetEffect(0)); else owner->RemoveAurasDueToSpell(34471); } } break; } break; case SPELLFAMILY_PALADIN: switch(GetId()) { case 19746: case 31821: // Aura Mastery Triggered Spell Handler // If apply Concentration Aura -> trigger -> apply Aura Mastery Immunity // If remove Concentration Aura -> trigger -> remove Aura Mastery Immunity // If remove Aura Mastery -> trigger -> remove Aura Mastery Immunity // Do effects only on aura owner if (GetCasterGUID() != target->GetGUID()) break; if (apply) { if ((GetSpellProto()->Id == 31821 && target->HasAura(19746, GetCasterGUID())) || (GetSpellProto()->Id == 19746 && target->HasAura(31821))) target->CastSpell(target,64364,true); } else target->RemoveAurasDueToSpell(64364, GetCasterGUID()); break; } break; case SPELLFAMILY_DEATHKNIGHT: if (GetSpellSpecific(GetSpellProto()) == SPELL_SPECIFIC_PRESENCE) { AuraEffect *bloodPresenceAura=0; // healing by damage done AuraEffect *frostPresenceAura=0; // increased health AuraEffect *unholyPresenceAura=0; // increased movement speed, faster rune recovery // Improved Presences Unit::AuraEffectList const& vDummyAuras = target->GetAuraEffectsByType(SPELL_AURA_DUMMY); for (Unit::AuraEffectList::const_iterator itr = vDummyAuras.begin(); itr != vDummyAuras.end(); ++itr) { switch((*itr)->GetId()) { // Improved Blood Presence case 50365: case 50371: { bloodPresenceAura = (*itr); break; } // Improved Frost Presence case 50384: case 50385: { frostPresenceAura = (*itr); break; } // Improved Unholy Presence case 50391: case 50392: { unholyPresenceAura = (*itr); break; } } } uint32 presence=GetId(); if (apply) { // Blood Presence bonus if (presence == 48266) target->CastSpell(target, 63611, true); else if (bloodPresenceAura) { int32 basePoints1=bloodPresenceAura->GetAmount(); target->CastCustomSpell(target,63611,NULL,&basePoints1,NULL,true,0,bloodPresenceAura); } // Frost Presence bonus if (presence == 48263) target->CastSpell(target, 61261, true); else if (frostPresenceAura) { int32 basePoints0=frostPresenceAura->GetAmount(); target->CastCustomSpell(target,61261,&basePoints0,NULL,NULL,true,0,frostPresenceAura); } // Unholy Presence bonus if (presence == 48265) { if (unholyPresenceAura) { // Not listed as any effect, only base points set int32 basePoints0 = unholyPresenceAura->GetSpellProto()->EffectBasePoints[1]; target->CastCustomSpell(target,63622,&basePoints0 ,&basePoints0,&basePoints0,true,0,unholyPresenceAura); target->CastCustomSpell(target,65095,&basePoints0 ,NULL,NULL,true,0,unholyPresenceAura); } target->CastSpell(target,49772, true); } else if (unholyPresenceAura) { int32 basePoints0=unholyPresenceAura->GetAmount(); target->CastCustomSpell(target,49772,&basePoints0,NULL,NULL,true,0,unholyPresenceAura); } } else { // Remove passive auras if (presence == 48266 || bloodPresenceAura) target->RemoveAurasDueToSpell(63611); if (presence == 48263 || frostPresenceAura) target->RemoveAurasDueToSpell(61261); if (presence == 48265 || unholyPresenceAura) { if (presence == 48265 && unholyPresenceAura) { target->RemoveAurasDueToSpell(63622); target->RemoveAurasDueToSpell(65095); } target->RemoveAurasDueToSpell(49772); } } } break; case SPELLFAMILY_WARLOCK: // Drain Soul - If the target is at or below 25% health, Drain Soul causes four times the normal damage if (GetSpellProto()->SpellFamilyFlags[0] & 0x00004000) { if (!caster) break; if (apply) { if (target != caster && target->GetHealth() <= target->GetMaxHealth() / 4) caster->CastSpell(caster, 200000, true); } else { if (target != caster) caster->RemoveAurasDueToSpell(GetId()); else caster->RemoveAurasDueToSpell(200000); } } break; } } void Aura::SetNeedClientUpdateForTargets() const { for (ApplicationMap::const_iterator appIter = m_applications.begin(); appIter != m_applications.end(); ++appIter) appIter->second->SetNeedClientUpdate(); } void Aura::_DeleteRemovedApplications() { while (!m_removedApplications.empty()) { delete m_removedApplications.front(); m_removedApplications.pop_front(); } } UnitAura::UnitAura(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) : Aura(spellproto, effMask, owner, caster, baseAmount, castItem, casterGUID) { m_AuraDRGroup = DIMINISHING_NONE; GetUnitOwner()->_AddAura(this, caster); }; void UnitAura::_ApplyForTarget(Unit * target, Unit * caster, AuraApplication * aurApp) { Aura::_ApplyForTarget(target, caster, aurApp); // register aura diminishing on apply if (DiminishingGroup group = GetDiminishGroup()) target->ApplyDiminishingAura(group,true); } void UnitAura::_UnapplyForTarget(Unit * target, Unit * caster, AuraApplication * aurApp) { Aura::_UnapplyForTarget(target, caster, aurApp); // unregister aura diminishing (and store last time) if (DiminishingGroup group = GetDiminishGroup()) target->ApplyDiminishingAura(group,false); } void UnitAura::Remove(AuraRemoveMode removeMode) { if (IsRemoved()) return; GetUnitOwner()->RemoveOwnedAura(this, removeMode); } void UnitAura::FillTargetMap(std::map<Unit *, uint8> & targets, Unit * caster) { Player * modOwner = NULL; if (caster) modOwner = caster->GetSpellModOwner(); for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS ; ++effIndex) { if (!HasEffect(effIndex)) continue; UnitList targetList; // non-area aura if (GetSpellProto()->Effect[effIndex] == SPELL_EFFECT_APPLY_AURA) { targetList.push_back(GetUnitOwner()); } else { float radius; if (GetSpellProto()->Effect[effIndex] == SPELL_EFFECT_APPLY_AREA_AURA_ENEMY) radius = GetSpellRadiusForHostile(sSpellRadiusStore.LookupEntry(GetSpellProto()->EffectRadiusIndex[effIndex])); else radius = GetSpellRadiusForFriend(sSpellRadiusStore.LookupEntry(GetSpellProto()->EffectRadiusIndex[effIndex])); if (modOwner) modOwner->ApplySpellMod(GetId(), SPELLMOD_RADIUS, radius); if (!GetUnitOwner()->hasUnitState(UNIT_STAT_ISOLATED)) { switch(GetSpellProto()->Effect[effIndex]) { case SPELL_EFFECT_APPLY_AREA_AURA_PARTY: targetList.push_back(GetUnitOwner()); GetUnitOwner()->GetPartyMemberInDist(targetList, radius); break; case SPELL_EFFECT_APPLY_AREA_AURA_RAID: targetList.push_back(GetUnitOwner()); GetUnitOwner()->GetRaidMember(targetList, radius); break; case SPELL_EFFECT_APPLY_AREA_AURA_FRIEND: { targetList.push_back(GetUnitOwner()); Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); Trinity::UnitListSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(GetUnitOwner(), targetList, u_check); GetUnitOwner()->VisitNearbyObject(radius, searcher); break; } case SPELL_EFFECT_APPLY_AREA_AURA_ENEMY: { Trinity::AnyAoETargetUnitInObjectRangeCheck u_check(GetUnitOwner(), GetUnitOwner(), radius); // No GetCharmer in searcher Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck> searcher(GetUnitOwner(), targetList, u_check); GetUnitOwner()->VisitNearbyObject(radius, searcher); break; } case SPELL_EFFECT_APPLY_AREA_AURA_PET: targetList.push_back(GetUnitOwner()); case SPELL_EFFECT_APPLY_AREA_AURA_OWNER: { if (Unit *owner = GetUnitOwner()->GetCharmerOrOwner()) if (GetUnitOwner()->IsWithinDistInMap(owner, radius)) targetList.push_back(owner); break; } } } } for (UnitList::iterator itr = targetList.begin(); itr!= targetList.end();++itr) { std::map<Unit *, uint8>::iterator existing = targets.find(*itr); if (existing != targets.end()) existing->second |= 1<<effIndex; else targets[*itr] = 1<<effIndex; } } } DynObjAura::DynObjAura(SpellEntry const* spellproto, uint8 effMask, WorldObject * owner, Unit * caster, int32 *baseAmount, Item * castItem, uint64 casterGUID) : Aura(spellproto, effMask, owner, caster, baseAmount, castItem, casterGUID) { GetDynobjOwner()->SetAura(this); } void DynObjAura::Remove(AuraRemoveMode removeMode) { if (IsRemoved()) return; _Remove(removeMode); } void DynObjAura::FillTargetMap(std::map<Unit *, uint8> & targets, Unit * caster) { Unit * dynObjOwnerCaster = GetDynobjOwner()->GetCaster(); float radius = GetDynobjOwner()->GetRadius(); for (uint8 effIndex = 0; effIndex < MAX_SPELL_EFFECTS; ++effIndex) { if (!HasEffect(effIndex)) continue; UnitList targetList; if (GetSpellProto()->EffectImplicitTargetB[effIndex] == TARGET_DEST_DYNOBJ_ALLY || GetSpellProto()->EffectImplicitTargetB[effIndex] == TARGET_UNIT_AREA_ALLY_DST) { Trinity::AnyFriendlyUnitInObjectRangeCheck u_check(GetDynobjOwner(), dynObjOwnerCaster, radius); Trinity::UnitListSearcher<Trinity::AnyFriendlyUnitInObjectRangeCheck> searcher(GetDynobjOwner(), targetList, u_check); GetDynobjOwner()->VisitNearbyObject(radius, searcher); } else { Trinity::AnyAoETargetUnitInObjectRangeCheck u_check(GetDynobjOwner(), dynObjOwnerCaster, radius); Trinity::UnitListSearcher<Trinity::AnyAoETargetUnitInObjectRangeCheck> searcher(GetDynobjOwner(), targetList, u_check); GetDynobjOwner()->VisitNearbyObject(radius, searcher); } for (UnitList::iterator itr = targetList.begin(); itr!= targetList.end();++itr) { std::map<Unit *, uint8>::iterator existing = targets.find(*itr); if (existing != targets.end()) existing->second |= 1<<effIndex; else targets[*itr] = 1<<effIndex; } } }
Java
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "errno-util.h" #include "format-table.h" #include "hexdecoct.h" #include "homectl-pkcs11.h" #include "libcrypt-util.h" #include "memory-util.h" #include "openssl-util.h" #include "pkcs11-util.h" #include "random-util.h" #include "strv.h" struct pkcs11_callback_data { char *pin_used; X509 *cert; }; #if HAVE_P11KIT static void pkcs11_callback_data_release(struct pkcs11_callback_data *data) { erase_and_free(data->pin_used); X509_free(data->cert); } static int pkcs11_callback( CK_FUNCTION_LIST *m, CK_SESSION_HANDLE session, CK_SLOT_ID slot_id, const CK_SLOT_INFO *slot_info, const CK_TOKEN_INFO *token_info, P11KitUri *uri, void *userdata) { _cleanup_(erase_and_freep) char *pin_used = NULL; struct pkcs11_callback_data *data = userdata; CK_OBJECT_HANDLE object; int r; assert(m); assert(slot_info); assert(token_info); assert(uri); assert(data); /* Called for every token matching our URI */ r = pkcs11_token_login(m, session, slot_id, token_info, "home directory operation", "user-home", "pkcs11-pin", UINT64_MAX, &pin_used); if (r < 0) return r; r = pkcs11_token_find_x509_certificate(m, session, uri, &object); if (r < 0) return r; r = pkcs11_token_read_x509_certificate(m, session, object, &data->cert); if (r < 0) return r; /* Let's read some random data off the token and write it to the kernel pool before we generate our * random key from it. This way we can claim the quality of the RNG is at least as good as the * kernel's and the token's pool */ (void) pkcs11_token_acquire_rng(m, session); data->pin_used = TAKE_PTR(pin_used); return 1; } #endif static int acquire_pkcs11_certificate( const char *uri, X509 **ret_cert, char **ret_pin_used) { #if HAVE_P11KIT _cleanup_(pkcs11_callback_data_release) struct pkcs11_callback_data data = {}; int r; r = pkcs11_find_token(uri, pkcs11_callback, &data); if (r == -EAGAIN) /* pkcs11_find_token() doesn't log about this error, but all others */ return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "Specified PKCS#11 token with URI '%s' not found.", uri); if (r < 0) return r; *ret_cert = TAKE_PTR(data.cert); *ret_pin_used = TAKE_PTR(data.pin_used); return 0; #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PKCS#11 tokens not supported on this build."); #endif } static int encrypt_bytes( EVP_PKEY *pkey, const void *decrypted_key, size_t decrypted_key_size, void **ret_encrypt_key, size_t *ret_encrypt_key_size) { _cleanup_(EVP_PKEY_CTX_freep) EVP_PKEY_CTX *ctx = NULL; _cleanup_free_ void *b = NULL; size_t l; ctx = EVP_PKEY_CTX_new(pkey, NULL); if (!ctx) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to allocate public key context"); if (EVP_PKEY_encrypt_init(ctx) <= 0) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to initialize public key context"); if (EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_PADDING) <= 0) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to configure PKCS#1 padding"); if (EVP_PKEY_encrypt(ctx, NULL, &l, decrypted_key, decrypted_key_size) <= 0) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine encrypted key size"); b = malloc(l); if (!b) return log_oom(); if (EVP_PKEY_encrypt(ctx, b, &l, decrypted_key, decrypted_key_size) <= 0) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to determine encrypted key size"); *ret_encrypt_key = TAKE_PTR(b); *ret_encrypt_key_size = l; return 0; } static int add_pkcs11_encrypted_key( JsonVariant **v, const char *uri, const void *encrypted_key, size_t encrypted_key_size, const void *decrypted_key, size_t decrypted_key_size) { _cleanup_(json_variant_unrefp) JsonVariant *l = NULL, *w = NULL, *e = NULL; _cleanup_(erase_and_freep) char *base64_encoded = NULL, *hashed = NULL; int r; assert(v); assert(uri); assert(encrypted_key); assert(encrypted_key_size > 0); assert(decrypted_key); assert(decrypted_key_size > 0); /* Before using UNIX hashing on the supplied key we base64 encode it, since crypt_r() and friends * expect a NUL terminated string, and we use a binary key */ r = base64mem(decrypted_key, decrypted_key_size, &base64_encoded); if (r < 0) return log_error_errno(r, "Failed to base64 encode secret key: %m"); r = hash_password(base64_encoded, &hashed); if (r < 0) return log_error_errno(errno_or_else(EINVAL), "Failed to UNIX hash secret key: %m"); r = json_build(&e, JSON_BUILD_OBJECT( JSON_BUILD_PAIR("uri", JSON_BUILD_STRING(uri)), JSON_BUILD_PAIR("data", JSON_BUILD_BASE64(encrypted_key, encrypted_key_size)), JSON_BUILD_PAIR("hashedPassword", JSON_BUILD_STRING(hashed)))); if (r < 0) return log_error_errno(r, "Failed to build encrypted JSON key object: %m"); w = json_variant_ref(json_variant_by_key(*v, "privileged")); l = json_variant_ref(json_variant_by_key(w, "pkcs11EncryptedKey")); r = json_variant_append_array(&l, e); if (r < 0) return log_error_errno(r, "Failed append PKCS#11 encrypted key: %m"); r = json_variant_set_field(&w, "pkcs11EncryptedKey", l); if (r < 0) return log_error_errno(r, "Failed to set PKCS#11 encrypted key: %m"); r = json_variant_set_field(v, "privileged", w); if (r < 0) return log_error_errno(r, "Failed to update privileged field: %m"); return 0; } static int add_pkcs11_token_uri(JsonVariant **v, const char *uri) { _cleanup_(json_variant_unrefp) JsonVariant *w = NULL; _cleanup_strv_free_ char **l = NULL; int r; assert(v); assert(uri); w = json_variant_ref(json_variant_by_key(*v, "pkcs11TokenUri")); if (w) { r = json_variant_strv(w, &l); if (r < 0) return log_error_errno(r, "Failed to parse PKCS#11 token list: %m"); if (strv_contains(l, uri)) return 0; } r = strv_extend(&l, uri); if (r < 0) return log_oom(); w = json_variant_unref(w); r = json_variant_new_array_strv(&w, l); if (r < 0) return log_error_errno(r, "Failed to create PKCS#11 token URI JSON: %m"); r = json_variant_set_field(v, "pkcs11TokenUri", w); if (r < 0) return log_error_errno(r, "Failed to update PKCS#11 token URI list: %m"); return 0; } int identity_add_token_pin(JsonVariant **v, const char *pin) { _cleanup_(json_variant_unrefp) JsonVariant *w = NULL, *l = NULL; _cleanup_(strv_free_erasep) char **pins = NULL; int r; assert(v); if (isempty(pin)) return 0; w = json_variant_ref(json_variant_by_key(*v, "secret")); l = json_variant_ref(json_variant_by_key(w, "tokenPin")); r = json_variant_strv(l, &pins); if (r < 0) return log_error_errno(r, "Failed to convert PIN array: %m"); if (strv_find(pins, pin)) return 0; r = strv_extend(&pins, pin); if (r < 0) return log_oom(); strv_uniq(pins); l = json_variant_unref(l); r = json_variant_new_array_strv(&l, pins); if (r < 0) return log_error_errno(r, "Failed to allocate new PIN array JSON: %m"); json_variant_sensitive(l); r = json_variant_set_field(&w, "tokenPin", l); if (r < 0) return log_error_errno(r, "Failed to update PIN field: %m"); r = json_variant_set_field(v, "secret", w); if (r < 0) return log_error_errno(r, "Failed to update secret object: %m"); return 1; } int identity_add_pkcs11_key_data(JsonVariant **v, const char *uri) { _cleanup_(erase_and_freep) void *decrypted_key = NULL, *encrypted_key = NULL; _cleanup_(erase_and_freep) char *pin = NULL; size_t decrypted_key_size, encrypted_key_size; _cleanup_(X509_freep) X509 *cert = NULL; EVP_PKEY *pkey; RSA *rsa; int bits; int r; assert(v); r = acquire_pkcs11_certificate(uri, &cert, &pin); if (r < 0) return r; pkey = X509_get0_pubkey(cert); if (!pkey) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract public key from X.509 certificate."); if (EVP_PKEY_base_id(pkey) != EVP_PKEY_RSA) return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "X.509 certificate does not refer to RSA key."); rsa = EVP_PKEY_get0_RSA(pkey); if (!rsa) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to acquire RSA public key from X.509 certificate."); bits = RSA_bits(rsa); log_debug("Bits in RSA key: %i", bits); /* We use PKCS#1 padding for the RSA cleartext, hence let's leave some extra space for it, hence only * generate a random key half the size of the RSA length */ decrypted_key_size = bits / 8 / 2; if (decrypted_key_size < 1) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Uh, RSA key size too short?"); log_debug("Generating %zu bytes random key.", decrypted_key_size); decrypted_key = malloc(decrypted_key_size); if (!decrypted_key) return log_oom(); r = genuine_random_bytes(decrypted_key, decrypted_key_size, RANDOM_BLOCK); if (r < 0) return log_error_errno(r, "Failed to generate random key: %m"); r = encrypt_bytes(pkey, decrypted_key, decrypted_key_size, &encrypted_key, &encrypted_key_size); if (r < 0) return log_error_errno(r, "Failed to encrypt key: %m"); /* Add the token URI to the public part of the record. */ r = add_pkcs11_token_uri(v, uri); if (r < 0) return r; /* Include the encrypted version of the random key we just generated in the privileged part of the record */ r = add_pkcs11_encrypted_key( v, uri, encrypted_key, encrypted_key_size, decrypted_key, decrypted_key_size); if (r < 0) return r; /* If we acquired the PIN also include it in the secret section of the record, so that systemd-homed * can use it if it needs to, given that it likely needs to decrypt the key again to pass to LUKS or * fscrypt. */ r = identity_add_token_pin(v, pin); if (r < 0) return r; return 0; } #if HAVE_P11KIT static int list_callback( CK_FUNCTION_LIST *m, CK_SESSION_HANDLE session, CK_SLOT_ID slot_id, const CK_SLOT_INFO *slot_info, const CK_TOKEN_INFO *token_info, P11KitUri *uri, void *userdata) { _cleanup_free_ char *token_uri_string = NULL, *token_label = NULL, *token_manufacturer_id = NULL, *token_model = NULL; _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL; Table *t = userdata; int uri_result, r; assert(slot_info); assert(token_info); /* We only care about hardware devices here with a token inserted. Let's filter everything else * out. (Note that the user can explicitly specify non-hardware tokens if they like, but during * enumeration we'll filter those, since software tokens are typically the system certificate store * and such, and it's typically not what people want to bind their home directories to.) */ if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT)) return -EAGAIN; token_label = pkcs11_token_label(token_info); if (!token_label) return log_oom(); token_manufacturer_id = pkcs11_token_manufacturer_id(token_info); if (!token_manufacturer_id) return log_oom(); token_model = pkcs11_token_model(token_info); if (!token_model) return log_oom(); token_uri = uri_from_token_info(token_info); if (!token_uri) return log_oom(); uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, &token_uri_string); if (uri_result != P11_KIT_URI_OK) return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result)); r = table_add_many( t, TABLE_STRING, token_uri_string, TABLE_STRING, token_label, TABLE_STRING, token_manufacturer_id, TABLE_STRING, token_model); if (r < 0) return table_log_add_error(r); return -EAGAIN; /* keep scanning */ } #endif int list_pkcs11_tokens(void) { #if HAVE_P11KIT _cleanup_(table_unrefp) Table *t = NULL; int r; t = table_new("uri", "label", "manufacturer", "model"); if (!t) return log_oom(); r = pkcs11_find_token(NULL, list_callback, t); if (r < 0 && r != -EAGAIN) return r; if (table_get_rows(t) <= 1) { log_info("No suitable PKCS#11 tokens found."); return 0; } r = table_print(t, stdout); if (r < 0) return log_error_errno(r, "Failed to show device table: %m"); return 0; #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PKCS#11 tokens not supported on this build."); #endif } #if HAVE_P11KIT static int auto_callback( CK_FUNCTION_LIST *m, CK_SESSION_HANDLE session, CK_SLOT_ID slot_id, const CK_SLOT_INFO *slot_info, const CK_TOKEN_INFO *token_info, P11KitUri *uri, void *userdata) { _cleanup_(p11_kit_uri_freep) P11KitUri *token_uri = NULL; char **t = userdata; int uri_result; assert(slot_info); assert(token_info); if (!FLAGS_SET(token_info->flags, CKF_HW_SLOT|CKF_TOKEN_PRESENT)) return -EAGAIN; if (*t) return log_error_errno(SYNTHETIC_ERRNO(ENOTUNIQ), "More than one suitable PKCS#11 token found."); token_uri = uri_from_token_info(token_info); if (!token_uri) return log_oom(); uri_result = p11_kit_uri_format(token_uri, P11_KIT_URI_FOR_ANY, t); if (uri_result != P11_KIT_URI_OK) return log_warning_errno(SYNTHETIC_ERRNO(EAGAIN), "Failed to format slot URI: %s", p11_kit_uri_message(uri_result)); return 0; } #endif int find_pkcs11_token_auto(char **ret) { #if HAVE_P11KIT int r; r = pkcs11_find_token(NULL, auto_callback, ret); if (r == -EAGAIN) return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "No suitable PKCS#11 tokens found."); if (r < 0) return r; return 0; #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PKCS#11 tokens not supported on this build."); #endif }
Java
using OpenDBDiff.Abstractions.Schema; using OpenDBDiff.Abstractions.Schema.Model; using System; using System.Linq; namespace OpenDBDiff.SqlServer.Schema.Model { public class Columns<T> : SchemaList<Column, T> where T : ISchemaBase { public Columns(T parent) : base(parent) { } /// <summary> /// Clona el objeto Columns en una nueva instancia. /// </summary> public new Columns<T> Clone(T parentObject) { Columns<T> columns = new Columns<T>(parentObject); for (int index = 0; index < this.Count; index++) { columns.Add(this[index].Clone(parentObject)); } return columns; } public override string ToSql() { return string.Join ( ",\r\n", this .Where(c => !c.HasState(ObjectStatus.Drop)) .Select(c => "\t" + c.ToSql(true)) ); } public override SQLScriptList ToSqlDiff(System.Collections.Generic.ICollection<ISchemaBase> schemas) { string sqlDrop = ""; string sqlAdd = ""; string sqlCons = ""; string sqlBinds = ""; SQLScriptList list = new SQLScriptList(); if (Parent.Status != ObjectStatus.Rebuild) { this.ForEach(item => { bool isIncluded = schemas.Count == 0; if (!isIncluded) { foreach (var selectedSchema in schemas) { if (selectedSchema.Id == item.Id) { isIncluded = true; break; } } } if (isIncluded) { if (item.HasState(ObjectStatus.Drop)) { if (item.DefaultConstraint != null) list.Add(item.DefaultConstraint.Drop()); /*Si la columna formula debe ser eliminada y ya fue efectuada la operacion en otro momento, no * se borra nuevamente*/ if (!item.GetWasInsertInDiffList(ScriptAction.AlterColumnFormula)) sqlDrop += "[" + item.Name + "],"; } if (item.HasState(ObjectStatus.Create)) sqlAdd += "\r\n" + item.ToSql(true) + ","; if ((item.HasState(ObjectStatus.Alter) || (item.HasState(ObjectStatus.RebuildDependencies)))) { if ((!item.Parent.HasState(ObjectStatus.RebuildDependencies) || (!item.Parent.HasState(ObjectStatus.Rebuild)))) list.AddRange(item.RebuildSchemaBindingDependencies()); list.AddRange(item.RebuildConstraint(false)); list.AddRange(item.RebuildDependencies()); list.AddRange(item.Alter(ScriptAction.AlterTable)); } if (item.HasState(ObjectStatus.Update)) list.Add("UPDATE " + Parent.FullName + " SET [" + item.Name + "] = " + item.DefaultForceValue + " WHERE [" + item.Name + "] IS NULL\r\nGO\r\n", 0, ScriptAction.UpdateTable); if (item.HasState(ObjectStatus.Bind)) { if (item.Rule.Id != 0) sqlBinds += item.Rule.ToSQLAddBind(); if (item.Rule.Id == 0) sqlBinds += item.Rule.ToSQLAddUnBind(); } if (item.DefaultConstraint != null) list.AddRange(item.DefaultConstraint.ToSqlDiff(schemas)); } }); if (!String.IsNullOrEmpty(sqlDrop)) sqlDrop = "ALTER TABLE " + Parent.FullName + " DROP COLUMN " + sqlDrop.Substring(0, sqlDrop.Length - 1) + "\r\nGO\r\n"; if (!String.IsNullOrEmpty(sqlAdd)) sqlAdd = "ALTER TABLE " + Parent.FullName + " ADD " + sqlAdd.Substring(0, sqlAdd.Length - 1) + "\r\nGO\r\n"; if (!String.IsNullOrEmpty(sqlDrop + sqlAdd + sqlCons + sqlBinds)) list.Add(sqlDrop + sqlAdd + sqlBinds, 0, ScriptAction.AlterTable); } else { this.ForEach(item => { if (item.Status != ObjectStatus.Original) item.RootParent.ActionMessage[item.Parent.FullName].Add(item); }); } return list; } } }
Java
#pragma once #include <obs.hpp> #include <map> const std::map<int, const char*> &GetAACEncoderBitrateMap(); const char *GetAACEncoderForBitrate(int bitrate); int FindClosestAvailableAACBitrate(int bitrate);
Java
<?php /** * @package snow-monkey * @author inc2734 * @license GPL-2.0+ * @version 15.13.0 */ use Inc2734\WP_Customizer_Framework\Framework; use Framework\Helper; Framework::control( 'select', 'footer-widget-area-column-size', [ 'label' => __( 'Number of columns in the footer widget area on PC', 'snow-monkey' ), 'priority' => 110, 'default' => '1-4', 'choices' => [ '1-1' => __( '1 column', 'snow-monkey' ), '1-2' => __( '2 columns', 'snow-monkey' ), '1-3' => __( '3 columns', 'snow-monkey' ), '1-4' => __( '4 columns', 'snow-monkey' ), ], 'active_callback' => function() { return Helper::is_active_sidebar( 'footer-widget-area' ); }, ] ); if ( ! is_customize_preview() ) { return; } $panel = Framework::get_panel( 'design' ); $section = Framework::get_section( 'footer' ); $control = Framework::get_control( 'footer-widget-area-column-size' ); $control->join( $section )->join( $panel );
Java
// license:BSD-3-Clause // copyright-holders:Curt Coder /********************************************************************** Kempston Disk Interface emulation **********************************************************************/ #include "kempston_di.h" //************************************************************************** // DEVICE DEFINITIONS //************************************************************************** const device_type KEMPSTON_DISK_INTERFACE = &device_creator<kempston_disk_interface_t>; //------------------------------------------------- // ROM( kempston_disk_system ) //------------------------------------------------- ROM_START( kempston_disk_system ) ROM_REGION( 0x2000, "rom", 0 ) ROM_DEFAULT_BIOS("v114") ROM_SYSTEM_BIOS( 0, "v114", "v1.14" ) ROMX_LOAD( "kempston_disk_system_v1.14_1984.rom", 0x0000, 0x2000, CRC(0b70ad2e) SHA1(ff8158d25864d920f3f6df259167e91c2784692c), ROM_BIOS(1) ) ROM_END //------------------------------------------------- // rom_region - device-specific ROM region //------------------------------------------------- const tiny_rom_entry *kempston_disk_interface_t::device_rom_region() const { return ROM_NAME( kempston_disk_system ); } //************************************************************************** // LIVE DEVICE //************************************************************************** //------------------------------------------------- // kempston_disk_interface_t - constructor //------------------------------------------------- kempston_disk_interface_t::kempston_disk_interface_t(const machine_config &mconfig, const char *tag, device_t *owner, UINT32 clock) : device_t(mconfig, KEMPSTON_DISK_INTERFACE, "Kempston Disk Interface", tag, owner, clock, "ql_kdi", __FILE__), device_ql_expansion_card_interface(mconfig, *this) { } //------------------------------------------------- // device_start - device-specific startup //------------------------------------------------- void kempston_disk_interface_t::device_start() { } //------------------------------------------------- // read - //------------------------------------------------- UINT8 kempston_disk_interface_t::read(address_space &space, offs_t offset, UINT8 data) { return data; } //------------------------------------------------- // write - //------------------------------------------------- void kempston_disk_interface_t::write(address_space &space, offs_t offset, UINT8 data) { }
Java
extern sf::Time deltaTime;
Java
//////////////////////////////////////////////////////////////////////////////// // // Copyright 2016 RWS Inc, All Rights Reserved // // This program is free software; you can redistribute it and/or modify // it under the terms of version 2 of the GNU General Public License as published by // the Free Software Foundation // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program; if not, write to the Free Software Foundation, Inc., // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA // // fire.cpp // Project: Postal // // This module implements the CFire weapon class which is a burning flame // for several different effects and weapons. // // // History: // 01/17/97 BRH Started this weapon object. // // 01/23/97 BRH Updated the time to GetGameTime rather than using // real time.. // // 02/04/97 JMI Changed LoadDib() call to Load() (which now supports // loading of DIBs). // // 02/06/97 BRH Added RAnimSprite animation of the explosion for now. // We are going to do an Alpha effect on the explosion, so // there are two animations, one of the image and one of // the Alpha information stored as a BMP8 animation. When // the Alpha effect is ready, we will pass a frame from // each animation to a function to draw it. // // 02/06/97 BRH Fixed problem with timer. Since all Explosion objects // are using the same resource managed animation, they cannot // use the animation timer, they have to do the timing // themselves. // // 02/07/97 BRH Changed the sprite from CSprite2 to CSpriteAlpha2 for // the Alpha Blit effect. // // 02/09/97 BRH Started the Fire from Explode file since they are // similar. // // 02/10/97 JMI rspReleaseResource() now takes a ptr to a ptr. // // 02/11/97 BRH Changed the fire to start on a random frame number // so if you have many fires, they don't pulsate or all // burn in sync with each other. // // 02/14/97 BRH Changed from using the RAnimSprite to channel data. // // 02/17/97 BRH Now uses the resource manager to get the assets and starts // at a random time interval so the fire will be random again. // // 02/17/97 BRH Changed the lifetime to be time based rather than frame // based which was causing the fire to live on forever // since being switched from RAnimSprite to RChannel1. // // 02/18/97 BRH Now the fire changes to different Alpha channels as it // burns out during its time to live. // // 02/19/97 BRH Checks for collisions and sends messages. // // 02/19/97 BRH Added the ability to run both small and large fire // animations. Change the duration on the alpha layers // so that the initial alpha channel gets played for 80% // of the burning time. Also added bThick parameter to startup // which will start using the 0th Alpha channel which is // more opaque. If you want more Alpha, set to false which // will start on the next Alpha level down. // // 02/23/97 BRH Added static Preload() funciton which will be called // before play begins to cache a resource for this object. // // 02/24/97 JMI No longer sets the m_type member of the m_sprite b/c it // is set by m_sprite's constructor. // // 02/24/97 BRH Set the default state in ProcessMessages // // 02/24/97 BRH Added a timer for checkin collisions so it doesn't have // to check each time, but it was checking only when changing // alpha levels which was too long. // // 03/05/97 JMI Render()'s mapping from 3D to 2D had a typo (was adding m_dY // instead of subtracting). Now uses Map3Dto2D(). // // 03/13/97 JMI Load now takes a version number. // // 04/10/97 BRH Updated this to work with the new multi layer attribute // maps. // // 04/14/97 BRH Added CSmash::Item to the collide bits so that the fire // will send messages to barrels and other items. // // 04/21/97 BRH Added Smoke animation to the fire and the ability of the // fire to change to smoke. // // 02/22/97 BRH Adjusted the timer for the smoke effect to eliminate some // of the final frames so that the smoke wouldn't pulsate // like it did. // // 04/23/97 JMI Changed this item's m_smash bits from CSmash::Item to // CSmash::Fire. // Now affects Characters, Miscs, Mines, and Barrels. // // 04/24/97 BRH Added static wind direction variable that will get // adjusted slightly by each new creation of smoke which // calls WindDirectionUpdate() to randomly vary the wind // direction. // // 04/25/97 BRH Fixed problem with smoke that was created as smoke, // setting people on fire. Also fixed wall detection // and added an individual direction variable to each // instance of smoke that initially copies the wind // direction and uses it until it hits a wall, then it // rotates in one direction or the other until it is // free to move again. // // 05/09/97 JMI Update() now moves the smashatorium object when the CFire // is not Smoke. // // 05/29/97 JMI Removed ASSERT on m_pRealm->m_pAttribMap which no longer // exists. // // 06/11/97 BRH Pass along the m_u16ShooterID value in the Burn message. // // 06/15/97 BRH Fixed Smoke going past animation by 1 frame. // // 06/16/97 BRH Fixed smoke init of static wind direction. Now it // inits the wind direction on class load so that it doesn't // cause problems for the demo mode. // // 06/17/97 MJR Same as previous one for wind velocity. // // MJR Moved resetting of statics to Preload(), since in most // cases, fire or smoke are not Load()'ed. // // 06/18/97 BRH Changed over to using GetRandom() // // 06/26/97 BRH Added CSmash::AlmostDead to the include bits for fire so // that writhing guys can be killed by fire. // // 07/01/97 BRH Added small smoke animation. // // 07/04/97 BRH Added an auto alpha blend on the small smoke for the // rocket trails so they can blend into alpha based on // their time to live. May need to disable the // alpha channel for it to work correctly. // // 07/08/97 JMI Fixed Render() to distribute the homogeneous alpha level // better. Still needs tuning. // // 07/09/97 JMI Now uses m_pRealm->Make2dResPath() to get the fullpath // for 2D image components. // // 07/09/97 JMI Changed Preload() to take a pointer to the calling realm // as a parameter. // // 07/10/97 JMI Now uses alpha mask and level for animation. // // 07/13/97 BRH Changed the animations to use only 1 alpha mask and change // the alpha level based on time. // // 07/20/97 JMI Added some ASSERTs. // // 07/23/97 BRH Changed small fires to create small smokes rather than // large which slows down the game quite a bit. // // 07/27/97 JMI Changed to use Z position (i.e., X/Z plane) instead of // Y2 position (i.e., viewing plane) position for draw // priority. // // 08/11/97 BRH If alpha blending is turned off, as a performance option, // then don't even blit the smoke since without the alpha // effect, you can't see through it at all. // // 08/20/97 JMI Now does a range check on m_sCurrentAlphaLevel after // decrementing. // // 09/02/97 JMI Added m_u16FireStarterID. This is used for a special case // when the starter of the fire is not the thing using the // fire as a weapon (e.g., when a guy catches fire he can // use the fire on other people by running into them causing // them to catch on fire; however, if his own fire kills him // it is to the creator of the fire's credit that he dies). // //////////////////////////////////////////////////////////////////////////////// #define FIRE_CPP #include "RSPiX.h" #include <math.h> #include "fire.h" #include "dude.h" #include "game.h" #include "reality.h" //////////////////////////////////////////////////////////////////////////////// // Macros/types/etc. //////////////////////////////////////////////////////////////////////////////// #define AA_FILE "fire.aan" #define LARGE_FILE "fire.aan" #define SMALL_FILE "smallfire.aan" #define SMOKE_FILE "smoke.aan" #define SMALL_SMOKE_FILE "tinysmoke.aan" #define INIT_WIND_DIR 30 #define INIT_WIND_VEL 30 #define MAX_ALPHA 200 // Used for smoke trails #define THICK_ALPHA 255 // Start alpha level for thick fire #define THIN_ALPHA 200 // Start alpha level for thin fire #define DIEDOWN_ALPHA 100 // Point at which it looks like its dying down #define SMOLDER_ALPHA 30 // Point at which it is too weak to burn anyone #define BRIGHT_PERCENT 0.80 // Amount of the time it should be more opaque //////////////////////////////////////////////////////////////////////////////// // Variables/data //////////////////////////////////////////////////////////////////////////////// // Let this auto-init to 0 int16_t CFire::ms_sFileCount; int16_t CFire::ms_sLargeRadius = 20; int16_t CFire::ms_sSmallRadius = 8; int16_t CFire::ms_sWindDirection = INIT_WIND_DIR; // Start wind in this direction int32_t CFire::ms_lCollisionTime = 250; // Check for collisions this often int32_t CFire::ms_lSmokeTime = 10000; // Time to let smoke run double CFire::ms_dWindVelocity = INIT_WIND_VEL; // Pixels per second drift due to wind //////////////////////////////////////////////////////////////////////////////// // Load object (should call base class version!) //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Load( // Returns 0 if successfull, non-zero otherwise RFile* pFile, // In: File to load from bool bEditMode, // In: True for edit mode, false otherwise int16_t sFileCount, // In: File count (unique per file, never 0) uint32_t ulFileVersion) // In: Version of file format to load. { int16_t sResult = CThing::Load(pFile, bEditMode, sFileCount, ulFileVersion); if (sResult == 0) { // Load common data just once per file (not with each object) if (ms_sFileCount != sFileCount) { ms_sFileCount = sFileCount; // Init the static wind direction and velocity when the class loads. ms_sWindDirection = INIT_WIND_DIR; ms_dWindVelocity = INIT_WIND_VEL; // Load static data. switch (ulFileVersion) { default: case 1: break; } } // Load instance data. switch (ulFileVersion) { default: case 1: pFile->Read(&m_eFireAnim); break; } // Make sure there were no file errors or format errors . . . if (!pFile->Error() && sResult == 0) { // Get resources sResult = GetResources(); } else { sResult = -1; TRACE("CFire::Load(): Error reading from file!\n"); } } else { TRACE("CFire::Load(): CThing::Load() failed.\n"); } return sResult; } //////////////////////////////////////////////////////////////////////////////// // Save object (should call base class version!) //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Save( // Returns 0 if successfull, non-zero otherwise RFile* pFile, // In: File to save to int16_t sFileCount) // In: File count (unique per file, never 0) { int16_t sResult = CThing::Save(pFile, sFileCount); if (sResult == 0) { // Save common data just once per file (not with each object) if (ms_sFileCount != sFileCount) { ms_sFileCount = sFileCount; // Save static data } pFile->Write(&m_eFireAnim); } else { TRACE("CFire::Save(): CThing::Save() failed.\n"); } return sResult; } //////////////////////////////////////////////////////////////////////////////// // Startup object //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Startup(void) // Returns 0 if successfull, non-zero otherwise { return Init(); } //////////////////////////////////////////////////////////////////////////////// // Shutdown object //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Shutdown(void) // Returns 0 if successfull, non-zero otherwise { return 0; } //////////////////////////////////////////////////////////////////////////////// // Suspend object //////////////////////////////////////////////////////////////////////////////// void CFire::Suspend(void) { m_sSuspend++; } //////////////////////////////////////////////////////////////////////////////// // Resume object //////////////////////////////////////////////////////////////////////////////// void CFire::Resume(void) { m_sSuspend--; // If we're actually going to start updating again, we need to reset // the time so as to ignore any time that passed while we were suspended. // This method is far from precise, but I'm hoping it's good enough. if (m_sSuspend == 0) m_lPrevTime = m_pRealm->m_time.GetGameTime(); } //////////////////////////////////////////////////////////////////////////////// // Update object //////////////////////////////////////////////////////////////////////////////// void CFire::Update(void) { int32_t lThisTime; double dSeconds; double dDistance; double dNewX; double dNewZ; if (!m_sSuspend) { // See if we killed ourselves if (ProcessMessages() == State_Deleted) return; if (m_lTimer < m_lBurnUntil) { lThisTime = m_pRealm->m_time.GetGameTime(); m_lTimer += lThisTime - m_lPrevTime; // See if its time to change to the next alpha channel if (m_lTimer > m_lCurrentAlphaTimeout) { m_sCurrentAlphaLevel--; // Range check. if (m_sCurrentAlphaLevel < 0) m_sCurrentAlphaLevel = 0; else if (m_sCurrentAlphaLevel > 255) m_sCurrentAlphaLevel = 255; if (m_lTimer < m_lAlphaBreakPoint) m_lCurrentAlphaTimeout += m_lBrightAlphaInterval; else m_lCurrentAlphaTimeout += m_lDimAlphaInterval; } if (lThisTime > m_lCollisionTimer) { // If the fire is not smoldering out, then it has the ability // to set other things on fire and should check collisions // to see which things it should tell to burn. if (m_bSendMessages && m_sCurrentAlphaLevel > SMOLDER_ALPHA && m_eFireAnim != Smoke && m_eFireAnim != SmallSmoke) { CSmash* pSmashed = NULL; GameMessage msg; msg.msg_Burn.eType = typeBurn; msg.msg_Burn.sPriority = 0; msg.msg_Burn.sDamage = 10; msg.msg_Burn.u16ShooterID = m_u16ShooterID; m_pRealm->m_smashatorium.QuickCheckReset(&m_smash, m_u32CollideIncludeBits, m_u32CollideDontcareBits, m_u32CollideExcludeBits); while (m_pRealm->m_smashatorium.QuickCheckNext(&pSmashed)) { // Default to the standard case where credit is given to the // shooter. msg.msg_Burn.u16ShooterID = m_u16ShooterID; if ((m_bIsBurningDude) && (pSmashed->m_pThing->GetClassID() != CDudeID)) UnlockAchievement(ACHIEVEMENT_TOUCH_SOMEONE_WHILE_BURNING); // If the fire starter ID is set . . . if (m_u16FireStarterID != CIdBank::IdNil) { // If this is the shooter . . . if (pSmashed->m_pThing->GetInstanceID() == m_u16ShooterID) { // The shooter is damaged by his own fire with credit // given to the fire starter. msg.msg_Burn.u16ShooterID = m_u16FireStarterID; } } // Burn. SendThingMessage(&msg, pSmashed->m_pThing); } } // Reset collision timer for next time m_lCollisionTimer = lThisTime + ms_lCollisionTime; } // If this is smoke, make it drift in the wind direction if (m_eFireAnim == Smoke || m_eFireAnim == SmallSmoke) { // Update position using wind direction and velocity dSeconds = ((double) lThisTime - (double) m_lPrevTime) / 1000.0; // Apply internal velocity. dDistance = ms_dWindVelocity * dSeconds; dNewX = m_dX + COSQ[(int16_t) m_sRot] * dDistance; dNewZ = m_dZ - SINQ[(int16_t) m_sRot] * dDistance; // Check attribute map for walls, and if you hit a wall, // set the timer so you will die off next time around. int16_t sHeight = m_pRealm->GetHeight((int16_t) dNewX, (int16_t) dNewZ); // If it hits a wall taller than itself, then it will rotate in the // predetermined direction until it is free to move. if ((int16_t) m_dY < sHeight) { if (m_bTurnRight) m_sRot = rspMod360(m_sRot - 20); else m_sRot = rspMod360(m_sRot + 20); } else // else it is ok, so update its new position { m_dX = dNewX; m_dZ = dNewZ; } } else { // Update our smashatorium location. m_smash.m_sphere.sphere.X = m_dX; m_smash.m_sphere.sphere.Y = m_dY; m_smash.m_sphere.sphere.Z = m_dZ; // Update the smash. m_pRealm->m_smashatorium.Update(&m_smash); } m_lPrevTime = lThisTime; } else { // If its done smoking, then delete it if (m_eFireAnim == Smoke || m_eFireAnim == SmallSmoke) { delete this; } // Else change the fire to smoke else { if (Smokeout() != SUCCESS) delete this; } } } } //////////////////////////////////////////////////////////////////////////////// // Render object //////////////////////////////////////////////////////////////////////////////// void CFire::Render(void) { CAlphaAnim* pAnim; if (m_eFireAnim == Smoke || m_eFireAnim == SmallSmoke) { pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(m_lTimer); // For a performance gain, don't blit the smoke at all if alpha // blending is turned off - its impossible to see through when // alpha blending is off anyway. if (g_GameSettings.m_sAlphaBlend) m_sprite.m_sInFlags = 0; else m_sprite.m_sInFlags = CSprite::InHidden; } else { pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(m_lTimer % m_pAnimChannel->TotalTime()); } if (pAnim) { // Map from 3d to 2d coords Map3Dto2D(m_dX, m_dY, m_dZ, &(m_sprite.m_sX2), &(m_sprite.m_sY2) ); // Offset by animations 2D offsets. m_sprite.m_sX2 += pAnim->m_sX; m_sprite.m_sY2 += pAnim->m_sY; // Priority is based on our Z position. m_sprite.m_sPriority = m_dZ; // Layer should be based on info we get from attribute map. m_sprite.m_sLayer = CRealm::GetLayerViaAttrib(m_pRealm->GetLayer((int16_t) m_dX, (int16_t) m_dZ)); // Copy the color info and the alpha channel to the Alpha Sprite m_sprite.m_pImage = &(pAnim->m_imColor); // If its the tiny smoke (for trails) // Do the alpha based on the time to live. if (m_eFireAnim == SmallSmoke) { // Set the alpha level so it gets more translucent over time. m_sprite.m_sAlphaLevel = MAX_ALPHA - (MAX_ALPHA * (m_lTimer - m_lStartTime) ) / m_lTimeToLive ; // Do a range check. if (m_sprite.m_sAlphaLevel < 0) m_sprite.m_sAlphaLevel = 0; else if (m_sprite.m_sAlphaLevel > MAX_ALPHA) m_sprite.m_sAlphaLevel = MAX_ALPHA; } else { m_sprite.m_sAlphaLevel = m_sCurrentAlphaLevel; } // Now there is only one alpha mask m_sprite.m_pimAlpha = &(pAnim->m_pimAlphaArray[0]); ASSERT(m_sprite.m_sAlphaLevel <= 255); ASSERT(m_sprite.m_sAlphaLevel >= 0); // Update sprite in scene m_pRealm->m_scene.UpdateSprite(&m_sprite); } } //////////////////////////////////////////////////////////////////////////////// // Setup //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Setup( // Returns 0 if successfull, non-zero otherwise int16_t sX, // In: New x coord int16_t sY, // In: New y coord int16_t sZ, // In: New z coord int32_t lTimeToLive, // In: Number of milliseconds to burn, default 1sec bool bThick, // In: Use thick fire (more opaque) default = true FireAnim eAnimType) // In: Animation type to use default = LargeFire { int16_t sResult = 0; // Use specified position m_dX = (double)sX; m_dY = (double)sY; m_dZ = (double)sZ; m_lPrevTime = m_pRealm->m_time.GetGameTime(); m_lCollisionTimer = m_lPrevTime + ms_lCollisionTime; m_eFireAnim = eAnimType; m_lTimeToLive = lTimeToLive; if (bThick) m_sCurrentAlphaLevel = THICK_ALPHA; else m_sCurrentAlphaLevel = THIN_ALPHA; // Load resources sResult = GetResources(); if (sResult == SUCCESS) sResult = Init(); m_sRot = ms_sWindDirection; m_bTurnRight = (GetRandom() & 0x01); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Init //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Init(void) { int16_t sResult = SUCCESS; CAlphaAnim* pAnim = NULL; if (m_pAnimChannel != NULL) { m_lTimer = GetRandom() % m_pAnimChannel->TotalTime(); m_lStartTime = m_lTimer; m_lBurnUntil = m_lTimer + m_lTimeToLive; m_lAlphaBreakPoint = m_lTimer + (m_lTimeToLive * BRIGHT_PERCENT); pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(0); ASSERT(pAnim != NULL); m_lBrightAlphaInterval = (m_lTimeToLive * BRIGHT_PERCENT) / MAX(1, m_sCurrentAlphaLevel - DIEDOWN_ALPHA); m_lDimAlphaInterval = (m_lTimeToLive * (100.0 - BRIGHT_PERCENT)) / MAX(1, DIEDOWN_ALPHA); m_lCurrentAlphaTimeout = m_lTimer + m_lBrightAlphaInterval; m_sTotalAlphaChannels = 1; } switch (m_eFireAnim) { case LargeFire: // Update sphere m_smash.m_sphere.sphere.X = m_dX; m_smash.m_sphere.sphere.Y = m_dY; m_smash.m_sphere.sphere.Z = m_dZ; m_smash.m_sphere.sphere.lRadius = ms_sLargeRadius; m_smash.m_bits = CSmash::Fire; m_smash.m_pThing = this; // Update the smash m_pRealm->m_smashatorium.Update(&m_smash); break; case SmallFire: // Update sphere m_smash.m_sphere.sphere.X = m_dX; m_smash.m_sphere.sphere.Y = m_dY; m_smash.m_sphere.sphere.Z = m_dZ; m_smash.m_sphere.sphere.lRadius = ms_sSmallRadius; m_smash.m_bits = CSmash::Fire; m_smash.m_pThing = this; // Update the smash m_pRealm->m_smashatorium.Update(&m_smash); break; case Smoke: m_smash.m_pThing = NULL; m_bSendMessages = false; break; case SmallSmoke: m_smash.m_pThing = NULL; m_bSendMessages = false; m_lStartTime = m_lTimer = GetRandom() % m_pAnimChannel->TotalTime() / 3; m_lBurnUntil = m_lTimer + m_lTimeToLive; break; } // Set the collision bits m_u32CollideIncludeBits = CSmash::Character | CSmash::Barrel | CSmash::Mine | CSmash::Misc | CSmash::AlmostDead; m_u32CollideDontcareBits = CSmash::Good | CSmash::Bad; m_u32CollideExcludeBits = 0; return sResult; } //////////////////////////////////////////////////////////////////////////////// // Smokeout - Change from fire to smoke //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Smokeout(void) { int16_t sResult = SUCCESS; // Modify the wind direction slightly WindDirectionUpdate(); // Remove smash from the smashatorium if it was being used if (m_smash.m_pThing) m_pRealm->m_smashatorium.Remove(&m_smash); m_bSendMessages = false; // Release the fire animation and get the smoke animation FreeResources(); if (m_eFireAnim == SmallFire) m_eFireAnim = SmallSmoke; else m_eFireAnim = Smoke; sResult = GetResources(); // Reset timers CAlphaAnim* pAnim = NULL; if (m_pAnimChannel != NULL) { // Reset alpha level m_sCurrentAlphaLevel = THICK_ALPHA; pAnim = (CAlphaAnim*) m_pAnimChannel->GetAtTime(0); ASSERT(pAnim != NULL); // m_lTimeToLive = m_pAnimChannel->TotalTime(); // use same time to live as the original m_lStartTime = m_lTimer = 0; m_lBurnUntil = m_lTimer + m_lTimeToLive; m_lAlphaBreakPoint = m_lTimer + (m_lTimeToLive * BRIGHT_PERCENT); m_lBrightAlphaInterval = (m_lTimeToLive * BRIGHT_PERCENT) / MAX(1, m_sCurrentAlphaLevel - DIEDOWN_ALPHA); m_lDimAlphaInterval = (m_lTimeToLive * (1.0 - BRIGHT_PERCENT)) / MAX(1, DIEDOWN_ALPHA); m_lCurrentAlphaTimeout = m_lTimer + m_lBrightAlphaInterval; m_sTotalAlphaChannels = 1; } return sResult; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to init new object at specified position //////////////////////////////////////////////////////////////////////////////// int16_t CFire::EditNew( // Returns 0 if successfull, non-zero otherwise int16_t sX, // In: New x coord int16_t sY, // In: New y coord int16_t sZ) // In: New z coord { int16_t sResult = 0; // Use specified position m_dX = (double)sX; m_dY = (double)sY; m_dZ = (double)sZ; m_lTimer = GetRandom(); //m_pRealm->m_time.GetGameTime() + 1000; m_lPrevTime = m_pRealm->m_time.GetGameTime(); // Load resources sResult = GetResources(); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to modify object //////////////////////////////////////////////////////////////////////////////// int16_t CFire::EditModify(void) { return 0; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to move object to specified position //////////////////////////////////////////////////////////////////////////////// int16_t CFire::EditMove( // Returns 0 if successfull, non-zero otherwise int16_t sX, // In: New x coord int16_t sY, // In: New y coord int16_t sZ) // In: New z coord { m_dX = (double)sX; m_dY = (double)sY; m_dZ = (double)sZ; return 0; } //////////////////////////////////////////////////////////////////////////////// // Called by editor to update object //////////////////////////////////////////////////////////////////////////////// void CFire::EditUpdate(void) { } //////////////////////////////////////////////////////////////////////////////// // Called by editor to render object //////////////////////////////////////////////////////////////////////////////// void CFire::EditRender(void) { // In some cases, object's might need to do a special-case render in edit // mode because Startup() isn't called. In this case it doesn't matter, so // we can call the normal Render(). Render(); } //////////////////////////////////////////////////////////////////////////////// // Get all required resources //////////////////////////////////////////////////////////////////////////////// int16_t CFire::GetResources(void) // Returns 0 if successfull, non-zero otherwise { int16_t sResult = SUCCESS; switch (m_eFireAnim) { case LargeFire: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(LARGE_FILE), &m_pAnimChannel, RFile::LittleEndian); break; case SmallFire: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(SMALL_FILE), &m_pAnimChannel, RFile::LittleEndian); break; case Smoke: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(SMOKE_FILE), &m_pAnimChannel, RFile::LittleEndian); break; case SmallSmoke: sResult = rspGetResource(&g_resmgrGame, m_pRealm->Make2dResPath(SMALL_SMOKE_FILE), &m_pAnimChannel, RFile::LittleEndian); break; } if (sResult != 0) TRACE("CFire::GetResources - Error getting fire animation resource\n"); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Free all resources //////////////////////////////////////////////////////////////////////////////// int16_t CFire::FreeResources(void) // Returns 0 if successfull, non-zero otherwise { int16_t sResult = 0; rspReleaseResource(&g_resmgrGame, &m_pAnimChannel); return sResult; } //////////////////////////////////////////////////////////////////////////////// // Preload - basically trick the resource manager into caching resources for fire // animations before play begins so that when a fire is set for // the first time, there won't be a delay while it loads. //////////////////////////////////////////////////////////////////////////////// int16_t CFire::Preload( CRealm* prealm) // In: Calling realm. { // Init the static wind direction and velocity when the class loads. ms_sWindDirection = INIT_WIND_DIR; ms_dWindVelocity = INIT_WIND_VEL; ChannelAA* pRes; int16_t sResult = rspGetResource(&g_resmgrGame, prealm->Make2dResPath(LARGE_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); sResult |= rspGetResource(&g_resmgrGame, prealm->Make2dResPath(SMALL_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); sResult |= rspGetResource(&g_resmgrGame, prealm->Make2dResPath(SMOKE_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); sResult |= rspGetResource(&g_resmgrGame, prealm->Make2dResPath(SMALL_SMOKE_FILE), &pRes, RFile::LittleEndian); rspReleaseResource(&g_resmgrGame, &pRes); return sResult; } //////////////////////////////////////////////////////////////////////////////// // ProcessMessages //////////////////////////////////////////////////////////////////////////////// CFire::CFireState CFire::ProcessMessages(void) { CFireState eNewState = State_Idle; GameMessage msg; if (m_MessageQueue.DeQ(&msg) == true) { switch(msg.msg_Generic.eType) { case typeObjectDelete: m_MessageQueue.Empty(); delete this; return CFire::State_Deleted; break; } } // Dump the rest of the messages m_MessageQueue.Empty(); return eNewState; } //////////////////////////////////////////////////////////////////////////////// // EOF ////////////////////////////////////////////////////////////////////////////////
Java
/* $Id: elsa_ser.c,v 1.1.1.1 2011/08/19 02:08:59 ronald Exp $ * * stuff for the serial modem on ELSA cards * * This software may be used and distributed according to the terms * of the GNU General Public License, incorporated herein by reference. * */ #include <linux/serial.h> #include <linux/serial_reg.h> #include <linux/slab.h> #define MAX_MODEM_BUF 256 #define WAKEUP_CHARS (MAX_MODEM_BUF/2) #define RS_ISR_PASS_LIMIT 256 #define BASE_BAUD ( 1843200 / 16 ) //#define SERIAL_DEBUG_OPEN 1 //#define SERIAL_DEBUG_INTR 1 //#define SERIAL_DEBUG_FLOW 1 #undef SERIAL_DEBUG_OPEN #undef SERIAL_DEBUG_INTR #undef SERIAL_DEBUG_FLOW #undef SERIAL_DEBUG_REG //#define SERIAL_DEBUG_REG 1 #ifdef SERIAL_DEBUG_REG static u_char deb[32]; const char *ModemIn[] = {"RBR","IER","IIR","LCR","MCR","LSR","MSR","SCR"}; const char *ModemOut[] = {"THR","IER","FCR","LCR","MCR","LSR","MSR","SCR"}; #endif static char *MInit_1 = "AT&F&C1E0&D2\r\0"; static char *MInit_2 = "ATL2M1S64=13\r\0"; static char *MInit_3 = "AT+FCLASS=0\r\0"; static char *MInit_4 = "ATV1S2=128X1\r\0"; static char *MInit_5 = "AT\\V8\\N3\r\0"; static char *MInit_6 = "ATL0M0&G0%E1\r\0"; static char *MInit_7 = "AT%L1%M0%C3\r\0"; static char *MInit_speed28800 = "AT%G0%B28800\r\0"; static char *MInit_dialout = "ATs7=60 x1 d\r\0"; static char *MInit_dialin = "ATs7=60 x1 a\r\0"; static inline unsigned int serial_in(struct IsdnCardState *cs, int offset) { #ifdef SERIAL_DEBUG_REG u_int val = inb(cs->hw.elsa.base + 8 + offset); debugl1(cs,"in %s %02x",ModemIn[offset], val); return(val); #else return inb(cs->hw.elsa.base + 8 + offset); #endif } static inline unsigned int serial_inp(struct IsdnCardState *cs, int offset) { #ifdef SERIAL_DEBUG_REG #ifdef ELSA_SERIAL_NOPAUSE_IO u_int val = inb(cs->hw.elsa.base + 8 + offset); debugl1(cs,"inp %s %02x",ModemIn[offset], val); #else u_int val = inb_p(cs->hw.elsa.base + 8 + offset); debugl1(cs,"inP %s %02x",ModemIn[offset], val); #endif return(val); #else #ifdef ELSA_SERIAL_NOPAUSE_IO return inb(cs->hw.elsa.base + 8 + offset); #else return inb_p(cs->hw.elsa.base + 8 + offset); #endif #endif } static inline void serial_out(struct IsdnCardState *cs, int offset, int value) { #ifdef SERIAL_DEBUG_REG debugl1(cs,"out %s %02x",ModemOut[offset], value); #endif outb(value, cs->hw.elsa.base + 8 + offset); } static inline void serial_outp(struct IsdnCardState *cs, int offset, int value) { #ifdef SERIAL_DEBUG_REG #ifdef ELSA_SERIAL_NOPAUSE_IO debugl1(cs,"outp %s %02x",ModemOut[offset], value); #else debugl1(cs,"outP %s %02x",ModemOut[offset], value); #endif #endif #ifdef ELSA_SERIAL_NOPAUSE_IO outb(value, cs->hw.elsa.base + 8 + offset); #else outb_p(value, cs->hw.elsa.base + 8 + offset); #endif } /* * This routine is called to set the UART divisor registers to match * the specified baud rate for a serial port. */ static void change_speed(struct IsdnCardState *cs, int baud) { int quot = 0, baud_base; unsigned cval, fcr = 0; int bits; /* byte size and parity */ cval = 0x03; bits = 10; /* Determine divisor based on baud rate */ baud_base = BASE_BAUD; quot = baud_base / baud; /* If the quotient is ever zero, default to 9600 bps */ if (!quot) quot = baud_base / 9600; /* Set up FIFO's */ if ((baud_base / quot) < 2400) fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_1; else fcr = UART_FCR_ENABLE_FIFO | UART_FCR_TRIGGER_8; serial_outp(cs, UART_FCR, fcr); /* CTS flow control flag and modem status interrupts */ cs->hw.elsa.IER &= ~UART_IER_MSI; cs->hw.elsa.IER |= UART_IER_MSI; serial_outp(cs, UART_IER, cs->hw.elsa.IER); debugl1(cs,"modem quot=0x%x", quot); serial_outp(cs, UART_LCR, cval | UART_LCR_DLAB);/* set DLAB */ serial_outp(cs, UART_DLL, quot & 0xff); /* LS of divisor */ serial_outp(cs, UART_DLM, quot >> 8); /* MS of divisor */ serial_outp(cs, UART_LCR, cval); /* reset DLAB */ serial_inp(cs, UART_RX); } static int mstartup(struct IsdnCardState *cs) { int retval=0; /* * Clear the FIFO buffers and disable them * (they will be reenabled in change_speed()) */ serial_outp(cs, UART_FCR, (UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT)); /* * At this point there's no way the LSR could still be 0xFF; * if it is, then bail out, because there's likely no UART * here. */ if (serial_inp(cs, UART_LSR) == 0xff) { retval = -ENODEV; goto errout; } /* * Clear the interrupt registers. */ (void) serial_inp(cs, UART_RX); (void) serial_inp(cs, UART_IIR); (void) serial_inp(cs, UART_MSR); /* * Now, initialize the UART */ serial_outp(cs, UART_LCR, UART_LCR_WLEN8); /* reset DLAB */ cs->hw.elsa.MCR = 0; cs->hw.elsa.MCR = UART_MCR_DTR | UART_MCR_RTS | UART_MCR_OUT2; serial_outp(cs, UART_MCR, cs->hw.elsa.MCR); /* * Finally, enable interrupts */ cs->hw.elsa.IER = UART_IER_MSI | UART_IER_RLSI | UART_IER_RDI; serial_outp(cs, UART_IER, cs->hw.elsa.IER); /* enable interrupts */ /* * And clear the interrupt registers again for luck. */ (void)serial_inp(cs, UART_LSR); (void)serial_inp(cs, UART_RX); (void)serial_inp(cs, UART_IIR); (void)serial_inp(cs, UART_MSR); cs->hw.elsa.transcnt = cs->hw.elsa.transp = 0; cs->hw.elsa.rcvcnt = cs->hw.elsa.rcvp =0; /* * and set the speed of the serial port */ change_speed(cs, BASE_BAUD); cs->hw.elsa.MFlag = 1; errout: return retval; } /* * This routine will shutdown a serial port; interrupts are disabled, and * DTR is dropped if the hangup on close termio flag is on. */ static void mshutdown(struct IsdnCardState *cs) { #ifdef SERIAL_DEBUG_OPEN printk(KERN_DEBUG"Shutting down serial ...."); #endif /* * clear delta_msr_wait queue to avoid mem leaks: we may free the irq * here so the queue might never be waken up */ cs->hw.elsa.IER = 0; serial_outp(cs, UART_IER, 0x00); /* disable all intrs */ cs->hw.elsa.MCR &= ~UART_MCR_OUT2; /* disable break condition */ serial_outp(cs, UART_LCR, serial_inp(cs, UART_LCR) & ~UART_LCR_SBC); cs->hw.elsa.MCR &= ~(UART_MCR_DTR|UART_MCR_RTS); serial_outp(cs, UART_MCR, cs->hw.elsa.MCR); /* disable FIFO's */ serial_outp(cs, UART_FCR, (UART_FCR_CLEAR_RCVR | UART_FCR_CLEAR_XMIT)); serial_inp(cs, UART_RX); /* read data port to reset things */ #ifdef SERIAL_DEBUG_OPEN printk(" done\n"); #endif } static inline int write_modem(struct BCState *bcs) { int ret=0; struct IsdnCardState *cs = bcs->cs; int count, len, fp; if (!bcs->tx_skb) return 0; if (bcs->tx_skb->len <= 0) return 0; len = bcs->tx_skb->len; if (len > MAX_MODEM_BUF - cs->hw.elsa.transcnt) len = MAX_MODEM_BUF - cs->hw.elsa.transcnt; fp = cs->hw.elsa.transcnt + cs->hw.elsa.transp; fp &= (MAX_MODEM_BUF -1); count = len; if (count > MAX_MODEM_BUF - fp) { count = MAX_MODEM_BUF - fp; skb_copy_from_linear_data(bcs->tx_skb, cs->hw.elsa.transbuf + fp, count); skb_pull(bcs->tx_skb, count); cs->hw.elsa.transcnt += count; ret = count; count = len - count; fp = 0; } skb_copy_from_linear_data(bcs->tx_skb, cs->hw.elsa.transbuf + fp, count); skb_pull(bcs->tx_skb, count); cs->hw.elsa.transcnt += count; ret += count; if (cs->hw.elsa.transcnt && !(cs->hw.elsa.IER & UART_IER_THRI)) { cs->hw.elsa.IER |= UART_IER_THRI; serial_outp(cs, UART_IER, cs->hw.elsa.IER); } return(ret); } static inline void modem_fill(struct BCState *bcs) { if (bcs->tx_skb) { if (bcs->tx_skb->len) { write_modem(bcs); return; } else { if (test_bit(FLG_LLI_L1WAKEUP,&bcs->st->lli.flag) && (PACKET_NOACK != bcs->tx_skb->pkt_type)) { u_long flags; spin_lock_irqsave(&bcs->aclock, flags); bcs->ackcnt += bcs->hw.hscx.count; spin_unlock_irqrestore(&bcs->aclock, flags); schedule_event(bcs, B_ACKPENDING); } dev_kfree_skb_any(bcs->tx_skb); bcs->tx_skb = NULL; } } if ((bcs->tx_skb = skb_dequeue(&bcs->squeue))) { bcs->hw.hscx.count = 0; test_and_set_bit(BC_FLG_BUSY, &bcs->Flag); write_modem(bcs); } else { test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag); schedule_event(bcs, B_XMTBUFREADY); } } static inline void receive_chars(struct IsdnCardState *cs, int *status) { unsigned char ch; struct sk_buff *skb; do { ch = serial_in(cs, UART_RX); if (cs->hw.elsa.rcvcnt >= MAX_MODEM_BUF) break; cs->hw.elsa.rcvbuf[cs->hw.elsa.rcvcnt++] = ch; #ifdef SERIAL_DEBUG_INTR printk("DR%02x:%02x...", ch, *status); #endif if (*status & (UART_LSR_BI | UART_LSR_PE | UART_LSR_FE | UART_LSR_OE)) { #ifdef SERIAL_DEBUG_INTR printk("handling exept...."); #endif } *status = serial_inp(cs, UART_LSR); } while (*status & UART_LSR_DR); if (cs->hw.elsa.MFlag == 2) { if (!(skb = dev_alloc_skb(cs->hw.elsa.rcvcnt))) printk(KERN_WARNING "ElsaSER: receive out of memory\n"); else { memcpy(skb_put(skb, cs->hw.elsa.rcvcnt), cs->hw.elsa.rcvbuf, cs->hw.elsa.rcvcnt); skb_queue_tail(& cs->hw.elsa.bcs->rqueue, skb); } schedule_event(cs->hw.elsa.bcs, B_RCVBUFREADY); } else { char tmp[128]; char *t = tmp; t += sprintf(t, "modem read cnt %d", cs->hw.elsa.rcvcnt); QuickHex(t, cs->hw.elsa.rcvbuf, cs->hw.elsa.rcvcnt); debugl1(cs, tmp); } cs->hw.elsa.rcvcnt = 0; } static inline void transmit_chars(struct IsdnCardState *cs, int *intr_done) { int count; debugl1(cs, "transmit_chars: p(%x) cnt(%x)", cs->hw.elsa.transp, cs->hw.elsa.transcnt); if (cs->hw.elsa.transcnt <= 0) { cs->hw.elsa.IER &= ~UART_IER_THRI; serial_out(cs, UART_IER, cs->hw.elsa.IER); return; } count = 16; do { serial_outp(cs, UART_TX, cs->hw.elsa.transbuf[cs->hw.elsa.transp++]); if (cs->hw.elsa.transp >= MAX_MODEM_BUF) cs->hw.elsa.transp=0; if (--cs->hw.elsa.transcnt <= 0) break; } while (--count > 0); if ((cs->hw.elsa.transcnt < WAKEUP_CHARS) && (cs->hw.elsa.MFlag==2)) modem_fill(cs->hw.elsa.bcs); #ifdef SERIAL_DEBUG_INTR printk("THRE..."); #endif if (intr_done) *intr_done = 0; if (cs->hw.elsa.transcnt <= 0) { cs->hw.elsa.IER &= ~UART_IER_THRI; serial_outp(cs, UART_IER, cs->hw.elsa.IER); } } static void rs_interrupt_elsa(struct IsdnCardState *cs) { int status, iir, msr; int pass_counter = 0; #ifdef SERIAL_DEBUG_INTR printk(KERN_DEBUG "rs_interrupt_single(%d)...", cs->irq); #endif do { status = serial_inp(cs, UART_LSR); debugl1(cs,"rs LSR %02x", status); #ifdef SERIAL_DEBUG_INTR printk("status = %x...", status); #endif if (status & UART_LSR_DR) receive_chars(cs, &status); if (status & UART_LSR_THRE) transmit_chars(cs, NULL); if (pass_counter++ > RS_ISR_PASS_LIMIT) { printk("rs_single loop break.\n"); break; } iir = serial_inp(cs, UART_IIR); debugl1(cs,"rs IIR %02x", iir); if ((iir & 0xf) == 0) { msr = serial_inp(cs, UART_MSR); debugl1(cs,"rs MSR %02x", msr); } } while (!(iir & UART_IIR_NO_INT)); #ifdef SERIAL_DEBUG_INTR printk("end.\n"); #endif } extern int open_hscxstate(struct IsdnCardState *cs, struct BCState *bcs); extern void modehscx(struct BCState *bcs, int mode, int bc); extern void hscx_l2l1(struct PStack *st, int pr, void *arg); static void close_elsastate(struct BCState *bcs) { modehscx(bcs, 0, bcs->channel); if (test_and_clear_bit(BC_FLG_INIT, &bcs->Flag)) { if (bcs->hw.hscx.rcvbuf) { if (bcs->mode != L1_MODE_MODEM) kfree(bcs->hw.hscx.rcvbuf); bcs->hw.hscx.rcvbuf = NULL; } skb_queue_purge(&bcs->rqueue); skb_queue_purge(&bcs->squeue); if (bcs->tx_skb) { dev_kfree_skb_any(bcs->tx_skb); bcs->tx_skb = NULL; test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag); } } } static void modem_write_cmd(struct IsdnCardState *cs, u_char *buf, int len) { int count, fp; u_char *msg = buf; if (!len) return; if (len > (MAX_MODEM_BUF - cs->hw.elsa.transcnt)) { return; } fp = cs->hw.elsa.transcnt + cs->hw.elsa.transp; fp &= (MAX_MODEM_BUF -1); count = len; if (count > MAX_MODEM_BUF - fp) { count = MAX_MODEM_BUF - fp; memcpy(cs->hw.elsa.transbuf + fp, msg, count); cs->hw.elsa.transcnt += count; msg += count; count = len - count; fp = 0; } memcpy(cs->hw.elsa.transbuf + fp, msg, count); cs->hw.elsa.transcnt += count; if (cs->hw.elsa.transcnt && !(cs->hw.elsa.IER & UART_IER_THRI)) { cs->hw.elsa.IER |= UART_IER_THRI; serial_outp(cs, UART_IER, cs->hw.elsa.IER); } } static void modem_set_init(struct IsdnCardState *cs) { int timeout; #define RCV_DELAY 20 modem_write_cmd(cs, MInit_1, strlen(MInit_1)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); modem_write_cmd(cs, MInit_2, strlen(MInit_2)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); modem_write_cmd(cs, MInit_3, strlen(MInit_3)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); modem_write_cmd(cs, MInit_4, strlen(MInit_4)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); modem_write_cmd(cs, MInit_5, strlen(MInit_5)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); modem_write_cmd(cs, MInit_6, strlen(MInit_6)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); modem_write_cmd(cs, MInit_7, strlen(MInit_7)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); } static void modem_set_dial(struct IsdnCardState *cs, int outgoing) { int timeout; #define RCV_DELAY 20 modem_write_cmd(cs, MInit_speed28800, strlen(MInit_speed28800)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); if (outgoing) modem_write_cmd(cs, MInit_dialout, strlen(MInit_dialout)); else modem_write_cmd(cs, MInit_dialin, strlen(MInit_dialin)); timeout = 1000; while(timeout-- && cs->hw.elsa.transcnt) udelay(1000); debugl1(cs, "msi tout=%d", timeout); mdelay(RCV_DELAY); } static void modem_l2l1(struct PStack *st, int pr, void *arg) { struct BCState *bcs = st->l1.bcs; struct sk_buff *skb = arg; u_long flags; if (pr == (PH_DATA | REQUEST)) { spin_lock_irqsave(&bcs->cs->lock, flags); if (bcs->tx_skb) { skb_queue_tail(&bcs->squeue, skb); } else { bcs->tx_skb = skb; test_and_set_bit(BC_FLG_BUSY, &bcs->Flag); bcs->hw.hscx.count = 0; write_modem(bcs); } spin_unlock_irqrestore(&bcs->cs->lock, flags); } else if (pr == (PH_ACTIVATE | REQUEST)) { test_and_set_bit(BC_FLG_ACTIV, &bcs->Flag); st->l1.l1l2(st, PH_ACTIVATE | CONFIRM, NULL); set_arcofi(bcs->cs, st->l1.bc); mstartup(bcs->cs); modem_set_dial(bcs->cs, test_bit(FLG_ORIG, &st->l2.flag)); bcs->cs->hw.elsa.MFlag=2; } else if (pr == (PH_DEACTIVATE | REQUEST)) { test_and_clear_bit(BC_FLG_ACTIV, &bcs->Flag); bcs->cs->dc.isac.arcofi_bc = st->l1.bc; arcofi_fsm(bcs->cs, ARCOFI_START, &ARCOFI_XOP_0); interruptible_sleep_on(&bcs->cs->dc.isac.arcofi_wait); bcs->cs->hw.elsa.MFlag=1; } else { printk(KERN_WARNING"ElsaSer: unknown pr %x\n", pr); } } static int setstack_elsa(struct PStack *st, struct BCState *bcs) { bcs->channel = st->l1.bc; switch (st->l1.mode) { case L1_MODE_HDLC: case L1_MODE_TRANS: if (open_hscxstate(st->l1.hardware, bcs)) return (-1); st->l2.l2l1 = hscx_l2l1; break; case L1_MODE_MODEM: bcs->mode = L1_MODE_MODEM; if (!test_and_set_bit(BC_FLG_INIT, &bcs->Flag)) { bcs->hw.hscx.rcvbuf = bcs->cs->hw.elsa.rcvbuf; skb_queue_head_init(&bcs->rqueue); skb_queue_head_init(&bcs->squeue); } bcs->tx_skb = NULL; test_and_clear_bit(BC_FLG_BUSY, &bcs->Flag); bcs->event = 0; bcs->hw.hscx.rcvidx = 0; bcs->tx_cnt = 0; bcs->cs->hw.elsa.bcs = bcs; st->l2.l2l1 = modem_l2l1; break; } st->l1.bcs = bcs; setstack_manager(st); bcs->st = st; setstack_l1_B(st); return (0); } static void init_modem(struct IsdnCardState *cs) { cs->bcs[0].BC_SetStack = setstack_elsa; cs->bcs[1].BC_SetStack = setstack_elsa; cs->bcs[0].BC_Close = close_elsastate; cs->bcs[1].BC_Close = close_elsastate; if (!(cs->hw.elsa.rcvbuf = kmalloc(MAX_MODEM_BUF, GFP_ATOMIC))) { printk(KERN_WARNING "Elsa: No modem mem hw.elsa.rcvbuf\n"); return; } if (!(cs->hw.elsa.transbuf = kmalloc(MAX_MODEM_BUF, GFP_ATOMIC))) { printk(KERN_WARNING "Elsa: No modem mem hw.elsa.transbuf\n"); kfree(cs->hw.elsa.rcvbuf); cs->hw.elsa.rcvbuf = NULL; return; } if (mstartup(cs)) { printk(KERN_WARNING "Elsa: problem startup modem\n"); } modem_set_init(cs); } static void release_modem(struct IsdnCardState *cs) { cs->hw.elsa.MFlag = 0; if (cs->hw.elsa.transbuf) { if (cs->hw.elsa.rcvbuf) { mshutdown(cs); kfree(cs->hw.elsa.rcvbuf); cs->hw.elsa.rcvbuf = NULL; } kfree(cs->hw.elsa.transbuf); cs->hw.elsa.transbuf = NULL; } }
Java
<?php namespace Themosis\Core\Console; use Illuminate\Console\Command; use Illuminate\Console\ConfirmableTrait; use Illuminate\Encryption\Encrypter; class KeyGenerateCommand extends Command { use ConfirmableTrait; /** * Name and signature of the console command. * * @var string */ protected $signature = 'key:generate {--show : Display the key instead of modifying files} {--force : Force the operation to run when in production}'; /** * Console command description. * * @var string */ protected $description = 'Set the application key'; /** * Execute the console command. */ public function handle() { $key = $this->generateRandomKey(); if ($this->option('show')) { $this->line('<comment>'.$key.'</comment>'); return; } // Next, we will replace the application key in the environment file so it is // automatically setup for this developer. This key gets generated using a // secure random byte generator and is later base64 encoded for storage. if (! $this->setKeyInEnvironmentFile($key)) { return; } $this->laravel['config']['app.key'] = $key; $this->info("Application key [$key] set successfully."); } /** * Generate a random key for the application. * * @return string */ protected function generateRandomKey() { return 'base64:'.base64_encode(Encrypter::generateKey($this->laravel['config']['app.cipher'])); } /** * Set the application key in the environment file. * * @param string $key * * @return bool */ protected function setKeyInEnvironmentFile(string $key) { $currentKey = $this->laravel['config']['app.key']; if (0 !== strlen($currentKey) && (! $this->confirmToProceed())) { return false; } $this->writeNewEnvironmentFileWith($key); return true; } /** * Write new environment file with the given key. * * @param string $key */ protected function writeNewEnvironmentFileWith(string $key) { file_put_contents( $this->laravel->environmentFilePath(), preg_replace( $this->keyReplacementPattern(), 'APP_KEY='.$key, file_get_contents($this->laravel->environmentFilePath()) ) ); } /** * Get a regex pattern that will match env APP_KEY with any random key. * * @return string */ protected function keyReplacementPattern() { $escaped = preg_quote('='.$this->laravel['config']['app.key'], '/'); return "/^APP_KEY{$escaped}/m"; } }
Java
#!/bin/sh -e # Glen Pitt-Pladdy (ISC) . ./functions.sh depends_SLES() { echo >/dev/null } depends_RHEL() { [ -x /usr/bin/expect ] || yum install -y expect } trakapacheconf_SLES() { CONFDIR=/etc/apache2/conf.d CONF=$CONFDIR/t2016-$TRAKNS.conf echo $CONF } trakapacheconf_RHEL() { CONFDIR=/etc/httpd/conf.d CONF=$CONFDIR/t2016-$TRAKNS.conf echo $CONF } apacherestart_SLES() { [ -x /usr/sbin/httpd2 ] && service apache2 restart return 0 } apacherestart_RHEL() { [ -x /usr/sbin/httpd ] && service httpd restart return 0 } echo "########################################" INST=`instname $SITE $ENV DB$VER` TRAKNS=`traknamespace $SITE $ENV` TRAKPATH=`trakpath $SITE $ENV DB$VER` echo "Vanilla Trak $VER Install for $SITE : $ENV ($INST: $TRAKNS)" # check if we need to do this if [ -f ${TRAKPATH}/web/default.htm -a -f ${TRAKPATH}/db/data/CACHE.DAT ]; then echo "Already appears to be web and databases installed" exit 0 fi # get cache password if needed if [ -z "$CACHEPASS" ]; then getpass "Caché Password" CACHEPASS 1 fi # get Trak zip password if needed if [ -z "$TRAKZIPPASS" ]; then getpass "TrakCare .zip Password" TRAKZIPPASS 1 fi # find installer #installer=`locatefilestd $VER_*_R*_B*.zip` installer=/trak/iscbuild/installers/T2015_20150331_1957_ENXX_R0_FULL_B10.zip #installer=/trak/iscbuild/installers/2014_20140902_1034_R4ENXX_B32.zip #installer=/trak/iscbuild/installers/T2015_20150527_1736_DEV_ENXX_FULL_B231.zip echo $installer # check for target web/ directory if [ ! -d ${TRAKPATH}/web ]; then echo "FATAL - expecting \"${TRAKPATH}/web/\" to be created with appropriate permissions in advance" >&2 exit 1 fi # install dependancies osspecific depends # check that expect is available if [ ! -x /usr/bin/expect ]; then echo "FATAL - can't find executable /usr/bin/expect" >&2 exit 1 fi # check it's already installed if [ -f ${TRAKPATH}/web/default.htm ]; then echo "Install (web/default.htm) already exists - skipping" exit 0 fi # check we are root if [ `whoami` != 'root' ]; then echo "Being run as user `whoami` - should be run as root" exit 1 fi # install T2014 mkdir $TMPDIR/trakextract cp expect/TrakVanillaT2015_Install_install.expect $TMPDIR/trakextract chmod 755 $TMPDIR/trakextract/TrakVanillaT2015_Install_install.expect olddir=`pwd` cd $TMPDIR/trakextract ${olddir}/expect/TrakVanillaT2014_Install_unzip.expect $installer chown $CACHEUSR.$CACHEGRP $TMPDIR/trakextract -R $TMPDIR/trakextract/TrakVanillaT2015_Install_install.expect $INST $TMPDIR/trakextract $ENV $TRAKNS ${TRAKPATH} /trakcare cd ${olddir} rm -r $TMPDIR/trakextract # fix up database naming to UK convention ccontrol stop $INST nouser UCSITE=`echo $SITE | tr '[:lower:]' '[:upper:]'` sed -i "s/^$TRAKNS=$ENV-DATA,$ENV-APPSYS/$TRAKNS=$TRAKNS-DATA,$TRAKNS-APPSYS/" ${TRAKPATH}/hs/cache.cpf sed -i "s/^$ENV-/$TRAKNS-/" ${TRAKPATH}/hs/cache.cpf sed -i "s/\(Global_.*\|Routine_.*\|Package_.*\)=$ENV-/\1=$TRAKNS-/" ${TRAKPATH}/hs/cache.cpf ./expect/TrakVanillaT2014_Install_start.expect $INST # change web/ directory to use site code (and possibly create lc symlink) cd ${TRAKPATH}/web/custom/ mv $TRAKNS/ $SITE_UC #ln -s $SITE_UC $SITE_LC cd ${olddir} # change config in Configuration Manager ./expect/TrakVanillaT2014_Install_cleanup.expect $INST $TRAKNS $SITE_UC ${TRAKPATH}/web/custom/$SITE_UC/cdl # fix web/ permissions chown $CACHEUSR.$CACHEGRP ${TRAKPATH}/web -R find ${TRAKPATH}/web -type d -exec chmod 2770 {} \; find ${TRAKPATH}/web -type f -exec chmod 660 {} \; ## install the apache config #osspecific trakapacheconf ##apacheconf=`osspecific trakapacheconf` #if [ -d $CONFDIR -a -f /opt/cspgateway/bin/CSP.ini ]; then # apacheconf=$CONF # cp conffiles/apache-t2016.conf $apacheconf # chmod 644 $apacheconf # # apply custom settings # sed -i 's/TRAKWEBAPP/\/trakcare/g' $apacheconf # sed -i "s/TRAKWEBDIR/`path2regexp ${TRAKPATH}/web`/g" $apacheconf # # add in CSP config # ini_update.pl /opt/cspgateway/bin/CSP.ini \ # '[APP_PATH:/trakcare]GZIP_Compression=Enabled' \ # '[APP_PATH:/trakcare]GZIP_Exclude_File_Types=jpeg gif ico png' \ # '[APP_PATH:/trakcare]Response_Size_Notification=Chunked Transfer Encoding and Content Length' \ # '[APP_PATH:/trakcare]KeepAlive=No Action' \ # '[APP_PATH:/trakcare]Non_Parsed_Headers=Enabled' \ # '[APP_PATH:/trakcare]Alternative_Servers=Disabled' \ # "[APP_PATH:/trakcare]Alternative_Server_0=1~~~~~~$INST" \ # "[APP_PATH:/trakcare]Default_Server=$INST" \ # '[APP_PATH_INDEX]/trakcare=Enabled' #else # echo "Skipping Trak Config (no Apache and/or CSP)" #fi #osspecific apacherestart
Java
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <link rel="stylesheet" type="text/css" href="style/style.css"> <link rel="stylesheet" type="text/css" media="only screen and (min-device-width: 360px)" href="style-compact.css"> <script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','//www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-74917613-1', 'auto'); ga('send', 'pageview'); </script> </head> <body> <div class="dungeonBackgroundContainer"> <img class="dungeonFrame" src="../../BFStoryArchive/BFStoryArchive/dungeon_battle_collection/baseDungeonFrame.png" /> <img class="dungeonImage" src="../../BFStoryArchive/BFStoryArchive/dungeon_battle_collection/dungeon_battle_40700.jpg" /> </div> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_0.png" /> </div> <div class="speakerName"><a href="http://i.imgur.com/PZWh1tF.png">パリス</a></div> <div class="speakerMessage">…はい。グラントスは半覚醒状態ながらも すでに目覚めています。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_0.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">いえ、その件については 問題ありません。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_0.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">はい、わかりました。 任務を継続します。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName"><a href="http://i.imgur.com/OVgKa0l.png">ルジーナ</a></div> <div class="speakerMessage">おい、そこのクソ女!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">何をボソボソと しゃべってやがる!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_3.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">俺様を皇国のお偉いさんにでも 報告してるんでありますか?</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">フフッ、よくわかったわね。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">優秀な召喚師の情報は皇国にとって、 とても有益なのよ。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_4.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">ケッ! 胸クソ悪いー!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">……!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_1.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">おせーぞ! Shou-chan!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_1.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">こんなヤベー時に チンタラしてんじゃねーよ!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">あら、それなら 待たずに先に行けばよかったのに。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">雑魚には雑魚の使い道ってもんが あんだろうが!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">まぁいい。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_3.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">いいか、 俺様はこれから何百年も眠り続けてる</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_3.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">巨人どもの神、 『グラントス』をぶっ潰しに行く。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">まあ、俺様が戦うからは ただのデクノボーにはちげーねーが、</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">さすがにヤツとの戦闘中に 他の魔物に邪魔されたら面倒だ。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_3.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">そこで、俺が神を倒している間 お前らが魔物どもを引きつけておけ!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">あら、随分と優しいのね。 自分から強敵に挑むなんて。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_2.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">あぁ!?</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">テメーらじゃ、まともに やりあうことなんざできねーだろーが。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">グズどもが失敗した後始末するよか、 最初から俺様がやっちまった方がマシだ。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_3.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">俺様の本当の力、見せてやるよ。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_5.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">いいか、お前らはしっかり オトリとして魔物どもと戦ってろよ!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara4_1.png" /> </div> <div class="speakerName">ルジーナ</div> <div class="speakerMessage">この程度の任務をしくじるようなら、 俺様が直接ぶっ殺してやるからな!</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">フフッ、一応、名の通った 魔討隊のリーダーなだけはあるわね。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">言動は残念な感じだけど、</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">知識と実力は それなりにあるということかしら。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">私の想像以上の情報を 集めていたようだしね…。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_0.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">とはいえ、私の調査だと</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_0.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">グラントスは彼の手に負えるような 相手じゃなさそうだけど…。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_0.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">私も力を貸す必要がありそうね。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">もちろん、 あなたの力も貸してもらうわよ。</div> </div> <br> <div class="dialogueContainer"> <div class="facePortrait"> <img class="facePortraitFrame" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/characterFrame.png" /> <img class="facePortraitImg" src="../../BFStoryArchive/BFStoryArchive/navi_chara_collection/navi_chara5_1.png" /> </div> <div class="speakerName">パリス</div> <div class="speakerMessage">あなたの実力、 しっかりと見せてもらうわ。</div> </div> <br> </body> </html> <!-- contact me at reddit /u/blackrobe199 -->
Java
<?php require_once './includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); global $base_url; require_once ('tcpdf/pdfcss.php'); require_once('tcpdf/config/lang/eng.php'); require_once('tcpdf/tcpdf.php'); // create new PDF document $pdf = new TCPDF(L, PDF_UNIT, B4, true, 'UTF-8', false); // set document information $pdf->SetCreator(PDF_CREATOR); $pdf->SetAuthor('SC and ST'); $pdf->SetTitle('SC and ST'); $pdf->SetSubject('SC and ST'); $pdf->SetKeywords('SC and ST'); //$pdf->SetHeaderData('tcpdf/images/hpsc.png', PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); $pdf->SetHeaderData('tcpdf/images/hpsc.png', PDF_HEADER_LOGO_WIDTH, '',''); // set default header data //$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING); // set header and footer fonts $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN)); $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA)); // set default monospaced font $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED); //set margins $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT); $pdf->SetHeaderMargin(PDF_MARGIN_HEADER); $pdf->SetFooterMargin(PDF_MARGIN_FOOTER); //set auto page breaks $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM); //set image scale factor $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO); //set some language-dependent strings $pdf->setLanguageArray($l); // set font $pdf->SetFont('helvetica', '', 10); // add a page $pdf->AddPage(); if($_REQUEST['op'] == 'assetRegister_report'){ global $user, $base_url; $rid = $_REQUEST['rid']; $fromtime = $_REQUEST['fromtime']; $totime = $_REQUEST['totime']; $from = $fromtime; $to = $totime; //echo $fromtime.'jj';exit; $output =''; // define some HTML content with style $output .= <<<EOF <style> td.header_first{ color:111111; font-family:Verdana; font-size: 12pt; text-align:center; background-color:#ffffff; } td.header_report{ color:111111; font-family:Verdana; font-size: 16pt; text-align:center; font-weight:bold; background-color:#ffffff; } table{ width:1200px; } table.tbl_border{border:1px solid #a7c942; background-color:#a7c942; } td.header1 { color:#3b3c3c; background-color:#ffffff; font-family:Verdana; font-size: 11pt; font-weight: normal; } td.header2 { border-bottom-color:#FFFFFF; color: #ffffff; background-color:#a7c942; font-family:Verdana; font-size: 10pt; font-weight: bold; } td.header3 { color: #222222; background-color:#dddddd; font-family:Verdana; font-size: 11pt; font-weight: bold; } td.header4 { color: #222222; font-family:Verdana; font-size: 11pt; font-weight: bold; background-color:#eeeeee; } td.header4_1 { color:#222222; background-color:#ffffff; font-family:Verdana; font-size: 11pt; font-weight: normal; } td.header4_2 { color:#222222; background-color:#eaf2d3; font-family:Verdana; font-size: 11pt; font-weight: normal; } td.msg{ color:#FF0000; text-align:left; } </style> EOF; // Header Title $output .='<table cellpadding="0" cellspacing="0" border="0"> <tr><td class="header_report" colspan="5" align="center"> Asset Register</td></tr> <tr><td>&nbsp;</td></tr> </table>'; $append=''; if($fromtime){ if($fromtime !='1970-01-01' && $totime !='1970-01-01' ){ $append .= " date_amc BETWEEN '".$fromtime."' AND '".$totime."' AND "; } } $append .= " 1=1 "; $sql="select * from tbl_itassets where $append"; $output .='<table cellpadding="3" cellspacing="2" border="0">'; if($fromtime){ $output .='<tr><td class="header_first" align="left"> <b>From Date: </b>'.date('d-m-Y',strtotime($fromtime)).'&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<b>To Date: </b>'.date('d-m-Y',strtotime($totime)).'</td></tr>'; } $output .='</table>'; $output .='<table cellpadding="2" cellspacing="2" border="0" class="tbl_border" style="width:1095px;"><tr> <td width="5%" colspan="1" class="header2">S. No.</td> <td width="6%" colspan="1" class="header2">Section</td> <td width="6%" colspan="1" class="header2">Asset Type</td> <td width="8%" colspan="1" class="header2">Quantity</td> <td width="5%" colspan="1" class="header2">Amount</td> <td width="5%" colspan="1" class="header2">Procurement Cost</td> <td width="9%" colspan="1" class="header2">Asset Details</td> <td width="9%" colspan="1" class="header2">Insurance Company</td> <td width="9%" colspan="1" class="header2">Sum Insured</td> <td width="9%" colspan="1" class="header2">Date of Renewal</td> <td width="5%" colspan="1" class="header2">Claim Details</td> <td width="9%" colspan="1" class="header2">AMC Vendor Name</td> <td width="9%" colspan="1" class="header2">AMC Date</td> <td width="5%" colspan="1" class="header2">AMC Amount</td> <td width="9%" colspan="1" class="header2">Contract Details</td> </tr>'; $res = db_query($sql); $counter=1; while($rs = db_fetch_object($res)){ $comp_name=ucwords($rs->company_name); if($comp_name==''){$comp_name='N/A';} $sum_insured=($rs->sum_insured); if($sum_insured==''){$sum_insured='N/A';} $date_renewal=date('d-m-Y',strtotime($rs->date_renewal)); if($date_renewal==''){$date_renewal='N/A';} $claim_det=ucwords($rs->claim_details); if($claim_det==''){$claim_det='N/A';} $vendor_name=ucwords($rs->vendor_name);if($vendor_name==''){$vendor_name='N/A';} $date_amc=date('d-m-Y',strtotime($rs->date_amc)); if($date_amc==''){$date_amc='N/A';} $amt_amc=$rs->amount_amc; if($amt_amc==''){$amt_amc='N/A';} $contract_det=ucwords($rs->contract_details);if($contract_det==''){$contract_det='N/A';} if($counter%2==0){ $class='header4_1';}else{$class='header4_2';} $output .='<tr> <td width="5%" class="'.$class.'" align="center">'.$counter.'</td> <td width="6%" class="'.$class.'" align="left">'.ucwords(getLookupName($rs->section)).'</td> <td width="6%" class="'.$class.'" align="left">'.ucwords(getLookupName($rs->asset_type)).'</td> <td width="8%" class="'.$class.'" align="left">'.ucwords($rs->quantity).'</td> <td width="5%" class="'.$class.'" align="right">'.round($rs->amount).'</td> <td width="5%" class="'.$class.'" align="right">'.round($rs->proc_cost).'</td> <td width="9%" class="'.$class.'" align="left">'.ucwords($rs->asset_details).'</td> <td width="9%" class="'.$class.'" align="left">'.$comp_name.'</td> <td width="9%" class="'.$class.'" align="right">'.round($sum_insured).'</td> <td width="9%" class="'.$class.'" align="center">'.$date_renewal.'</td> <td width="5%" class="'.$class.'" align="left">'.$claim_det.'</td> <td width="9%" class="'.$class.'" align="left">'.$vendor_name.'</td> <td width="9%" class="'.$class.'" align="center">'.$date_amc.'</td> <td width="5%" class="'.$class.'" align="right">'.round($amt_amc).'</td> <td width="9%" class="'.$class.'" align="left">'.$contract_det.'</td> </tr>'; $counter++; } $output .='</table>'; ob_end_clean(); // print a block of text using Write() $pdf->writeHTML($output, true,1, false, false); $pdf->Output('assetRegister_'.time().'.pdf', 'I'); }
Java
/** * AshtavargaChartData.java * Created On 2006, Mar 31, 2006 5:12:23 PM * @author E. Rajasekar */ package app.astrosoft.beans; import java.util.EnumMap; import app.astrosoft.consts.AshtavargaName; import app.astrosoft.consts.AstrosoftTableColumn; import app.astrosoft.consts.Rasi; import app.astrosoft.core.Ashtavarga; import app.astrosoft.export.Exportable; import app.astrosoft.export.Exporter; import app.astrosoft.ui.table.ColumnMetaData; import app.astrosoft.ui.table.DefaultColumnMetaData; import app.astrosoft.ui.table.Table; import app.astrosoft.ui.table.TableData; import app.astrosoft.ui.table.TableRowData; public class AshtaVargaChartData extends AbstractChartData implements Exportable{ private EnumMap<Rasi, Integer> varga; public AshtaVargaChartData(AshtavargaName name, EnumMap<Rasi, Integer> varga) { super(); this.varga = varga; chartName = name.toString(); int count = Ashtavarga.getCount(name); if ( count != -1){ chartName = chartName + " ( " +String.valueOf(count) + " ) "; } } public Table getChartHouseTable(final Rasi rasi) { Table ashtavargaTable = new Table(){ public TableData<TableRowData> getTableData() { return new TableData<TableRowData>(){ public TableRowData getRow(final int index){ return new TableRowData(){ public Object getColumnData(AstrosoftTableColumn col) { return (index == 1) ? varga.get(rasi) : null; } }; } public int getRowCount() { return 2; } }; } public ColumnMetaData getColumnMetaData() { return colMetaData; } }; return ashtavargaTable; } @Override public DefaultColumnMetaData getHouseTableColMetaData() { return new DefaultColumnMetaData(AstrosoftTableColumn.C1){ @Override public Class getColumnClass(AstrosoftTableColumn col) { return Integer.class; } }; } public EnumMap<Rasi, Integer> getVarga() { return varga; } public void doExport(Exporter e) { e.export(this); } }
Java
package mcmod.nxs.animalwarriors.lib; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.item.ItemArmor; public class ArmorHelper extends ItemArmor { public ArmorHelper(ArmorMaterial material, int type, int layer) { super(material, type, layer); } public ItemArmor setNameAndTab(String name, CreativeTabs tab) { this.setTextureName(ResourcePathHelper.getResourcesPath() + name); this.setUnlocalizedName(name); this.setCreativeTab(tab); return this; } }
Java
<!DOCTYPE html> <html lang="es"> <head> <meta charset="UTF-8"> <title> </title> <style> .municipios{ font-size:12px; font-family: 'helvetica','raleway'; padding:1em 1em; background-color:#2C85AF; color:#FFFFFF; } .direccion{ font-size:12px; font-family: 'helvetica','raleway'; padding:1em 4em; background-color:#2C85AF; color:#FFFFFF; } .rellenotabla{ font-size: 10px; padding:1em 1em; font-family: 'helvetica','raleway'; } .rellenotabla2{ font-size: 10px; padding:1em 3em; font-family: 'helvetica','raleway'; } .textocolspan{ font-size:10px; font-family: 'helvetica','raleway'; background-color:#5AAED0; color:#FFFFFF; text-align:left; padding: 0.5em 1em; text-shadow: 1px 1px #000000; } @font-face { font-family: 'helvetica'; src: url('fonts/helvetica-b.eot'); /* IE9 Compat Modes */ src: url('fonts/helvetica-b.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */ url('fonts/helveticaneue-webfont.woff') format('woff'), /* Modern Browsers */ url('fonts/HELVE6.ttf') format('truetype'), /* Safari, Android, iOS */ url('fonts/Helvetica_Neue_typeface_weights.svg#svgFontName') format('svg'); /* Legacy iOS */ } div.boton_ubicacion{ background-color: #035A9F; color: #FFFFFF; } div.boton_ubicacion:hover{ background-color: #E4E5E6; color: #035A9F; } div#terminales{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px;padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#terminales:hover{ background-color: #E4E5E6; color: #035A9F; } div#centros{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px; padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#centros:hover{ background-color: #E4E5E6; color: #035A9F; } div#agencias{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px; padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#agencias:hover{ background-color: #E4E5E6; color: #035A9F; } div#oxxo{ display:inline-block; background-color:#2C85AF; color:#FFFFFF; font-family: 'raleway'; font-size:14px; padding:5px 15px; cursor:pointer; cursor: hand; margin-right:-4px; } div#oxxo:hover{ background-color: #E4E5E6; color: #035A9F; } </style> </head> <body> <div style="width:100%;border:1px solid #BDBDBD;text-align:center;overflow:hidden;float:right"> <div id="terminales" >Terminales y Centrales</div> <div id="centros" >Centros Comerciales</div> <div id="agencias" >Agencias de Viajes</div> <div id="oxxo" >Oxxo</div> <!-- ============================TERMINALES Y CENTRALES================================================================= --> <div id="mostrartermi" style="display:block"> <div style="display:inline-block;text-align:left;font-family: 'helvetica','raleway'"> <div style="display:inline-block"><img src="img/terminales.jpg" alt=""> </div> <div style="display:inline-block"><p style="font-size:12px">TERMINALES Y CENTRALES</p> <p style="color:#1959A0;font-weight:bold">SINALOA</p></div> </div> <div style="display:inline-block;width:100%;font-family: 'helvetica','raleway';"> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Mazatlán</p> <p>Calle Ferrusquilla s/n Interior <br> Edificio central de Autobuses <br> Colonia Palos Prietos <br> Tel: 01 (669) 981 46 59</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Plaza San Ignacio</p> <p>Carretera Internacional Km. 1205 <br> Col. Fovisste en Playa Azul <br> Tel. 01 (669) 135 12 34</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Culiacán</p> <p style="font-size:12px"><strong>CENTRAL DE AUTOBUSES CULIACÁN</strong> <br> en sala de primera y sala de segunda. <br> Blvd. Rolando Arjona # 2571 Norte y Blvd. <br> Culiacan Colonia Desarrollo Urbano 3 Rios. <br> Tel. 01 (667) 761 27 61</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Guamuchil</p> <p>Nicolas Bravo y Adolfo Lopez Mateos # 479 <br> Colonia Morelos <br> Tel: 01 (673) 732 67 50</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Guasave</p> <p >Blvd. 16 de Septiembre y 5 de Febrero S/n <br> Colonia <Centrobr></Centrobr> Tel. 01 (687) 872 98 45</p> </div> <div style="display:inline-block;padding:10px;text-align:left"> <p style="font-weight:bold">•Los Mochis</p> <p style="font-size:12px"><strong>TERMINAL</strong> <br> Blvd. Rosendo G. Castro y <br> Belisario Dominguez # 620 Sur <br> Colonia Bienestar <br> Tel: 01 (668) 817 59 07 <br> <strong>CENTRAL DE AUTOBUSES</strong> <br> Blvd. Rosendo G. Castro y Constitucion # 302 Oriente Col. Bienestar <br> Tel: 01 (668) 815 67 84</p> </div> </div> </div> <!-- ====================================CENTROS COMERCIALES============================================================ --> <div id="mostrarcentros" style="display:none"> <div style="display:block;text-align:center;font-family: 'helvetica','raleway'"> <div style="display:inline-block"><img src="img/comerciales.jpg" alt=""> </div> <div style="display:inline-block"><p style="font-size:12px">CENTROS COMERCIALES</p> <p style="color:#1959A0;font-weight:bold">SINALOA</p></div> </div> <div style="display:inline-block;font-family: 'helvetica',raleway';width:100%;text-align:center"> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/bodega_aurrera.png" alt=""> <p style="font-weight:bold;">•Estadio, Culiacán</p> <p>Blvd. Enrique Sáncez Alonso 2402 Nte. <br> Col. Desarrollo Urbano Tres Rios <br> C.P. 80030 <br> Tel. 01 (667) 146 61 60</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;"> •Los Mochis</p> <p>Blvd. Jiquilpan 1112 <br> Pte Local B <br> Col. Jiquilpan Ahome C.P. 81220 <br> Tel. 01 (668) 818 28 35</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•Culiacán</p> <p>Av. Regional 1330 Norte <br> Col. Sector V de la Primera del <br> Plan Parcial <br> (Tres Tios) C.P. 80000 <br> Tel. 01 (667) 750 95 42</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•Walmart 68, Culiacán</p> <p>Carretera Internacional 2017 <br> Col. Hacienda del Mar C.P. 82128 <br> Tel. 01 (669) 940 81 66</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•El Cochi, Mazatlán</p> <p>Av. Manuel J. Clouthier 4459 <br> Col. El Cochi C.P. 82139</p> </div> <div style="display:inline-block;font-size:15px;text-align:left;padding:10px"> <img style="width:100px" src="img/walmart.png" alt=""> <p style="font-weight:bold;">•Soriana Santa Rosa, Mazatlán</p> <p>Av. Luis Donaldo Colosio 17301 <br> Col. Fracc. Valle Dorado C.P. 82165 <br> Tel. 01 (669) 940 58 34</p> </div> </div> </div> <!-- ======================================AGENCIAS DE VIAJES==================================================== --> <div id="mostraragencias" style="display:none"> <div style="display:inline-block;text-align:left;font-family: 'helvetica','raleway'"> <div style="display:inline-block"><img src="img/agencias.jpg" alt=""> </div> <div style="display:inline-block"><p style="font-size:12px">AGENCIAS DE VIAJES</p> <p style="color:#1959A0;font-weight:bold">SINALOA</p></div> </div> <center><table> <tr> <td class="municipios">MUNICIPIO</td> <td class="municipios">COLONIA</td> <td class="direccion">DIRECCIÓN</td> <td class="municipios">TELÉFONO 1</td> <td class="municipios">TELÉFONO 2</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SERVICIOS Y VIAJES MICHEL</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">ALMADA</td> <td class="rellenotabla2">LAZARO CARDENAS N198-G</td> <td class="rellenotabla">6677128033</td> <td class="rellenotabla">6677128711</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: ROSEF & TURISMO</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">CHAPULTEPEC</td> <td class="rellenotabla2">ALVARO OBREGON 1330 NTE</td> <td class="rellenotabla">6677127700</td> <td class="rellenotabla">6677127701</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: AGENCIA DE VIAJES NERY TOURS</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">FEDERALISMO</td> <td class="rellenotabla2">BLVD CULIACAN 450-10</td> <td class="rellenotabla">6677612992</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: CULHUACAN TOURS</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">LAS QUINTAS</td> <td class="rellenotabla2">PRESA BALSEQUILLOS N 13</td> <td class="rellenotabla">6677152606</td> <td class="rellenotabla">6677152603</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SULLIVAN TURISMO</td> </tr> <tr> <td class="rellenotabla">CULIACAN</td> <td class="rellenotabla">VALLADO</td> <td class="rellenotabla2">BLVD EMILIANO ZAPATA N 2151</td> <td class="rellenotabla">6677178364</td> <td class="rellenotabla">6677176350</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: AGENCIA MORAGA</td> </tr> <tr> <td class="rellenotabla">GUAMUCHIL</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">AGUSTINA RAMIREZ SUR NO. 671-A</td> <td class="rellenotabla">673 7322401</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES LUDACAR</td> </tr> <tr> <td class="rellenotabla">GUASAVE</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">EMILIANO ZAPATA N 45</td> <td class="rellenotabla">6878714677</td> <td class="rellenotabla">6878714657</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SOLEITOURS</td> </tr> <tr> <td class="rellenotabla">LOS MOCHIS</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">CARDENAS PONIENTE N.- 509</td> <td class="rellenotabla">6688123030</td> <td class="rellenotabla">018009676534</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES TRANVIA</td> </tr> <tr> <td class="rellenotabla">LOS MOCHIS</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">CALLEJON TENOCHTITLAN PTE N.- 399</td> <td class="rellenotabla">6688123864</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: SERVICIOS TURISTICOS CONELVA</td> </tr> <tr> <td class="rellenotabla">LOS MOCHIS</td> <td class="rellenotabla">CENTRO AHOME</td> <td class="rellenotabla2">GABRIEL LEYVA SOLANO 357 NTE</td> <td class="rellenotabla">6688152484</td> <td class="rellenotabla">6688158090</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES COPALA</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">C.C LA GRAN PLAZA</td> <td class="rellenotabla2">APOLO Y REFORMA L -F-4</td> <td class="rellenotabla">6699862120</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VIAJES MARLOPOS</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">AV OLAS ALTAS N 11</td> <td class="rellenotabla">6699811993</td> <td class="rellenotabla">6699811994</td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: VISTA TOURS MAZATLAN S.A DE C.V</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">LOMAS DE MAZATLAN</td> <td class="rellenotabla2">AV. CAMARON SABALO NO. 51 LOC. 2 Y 3</td> <td class="rellenotabla">(669) 9868610</td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: PROMOTOURS EL CID</td> </tr> <tr> <td class="rellenotabla">MAZATLAN</td> <td class="rellenotabla">ZONA DORADA</td> <td class="rellenotabla2">AV CAMARON SABALO S/N LOC. 18</td> <td class="rellenotabla"></td> <td class="rellenotabla"></td> </tr> <tr> <td class="textocolspan" colspan="5">Agencia: AGENCIA DE VIAJES NERY TOURS SUC NOVOLATO</td> </tr> <tr> <td class="rellenotabla">NAVOLATO</td> <td class="rellenotabla">CENTRO</td> <td class="rellenotabla2">AV NIÑOS HEROES 484-A</td> <td class="rellenotabla">6727271850</td> <td class="rellenotabla"></td> </tr> </table></center> </div> <!-- =================================================OXXO======================================================================== --> <div id="mostraroxxo" style="display:none"> <p style="font-family:'helvetica','raleway'">Adquiere tus boletos de autobus TAP en las tiendas Oxxo.</p> </div> </div> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script> $(function(){ $('#oxxo').on('click', mostraroxo); function mostraroxo(){ $('#mostraroxxo').css('display', 'block'); $('#mostrartermi').css('display', 'none'); $('#mostraragencias').css('display', 'none'); $('#mostrarcentros').css('display', 'none'); } ; $('#agencias').on('click',mostraragen); function mostraragen(){ $('#mostraragencias').css('display', 'block'); $('#mostraroxxo').css('display', 'none'); $('#mostrartermi').css('display', 'none'); $('#mostrarcentros').css('display', 'none'); } ; $('#centros').on('click',mostrarcen); function mostrarcen(){ $('#mostrarcentros').css('display', 'block'); $('#mostraroxxo').css('display', 'none'); $('#mostrartermi').css('display', 'none'); $('#mostraragencias').css('display', 'none'); } ; $('#terminales').on('click',mostrarter); function mostrarter (){ $('#mostrartermi').css('display', 'block'); $('#mostraroxxo').css('display', 'none'); $('#mostraragencias').css('display', 'none'); $('#mostrarcentros').css('display', 'none'); } }); </script> </body> </html>
Java
// float_digits(). // General includes. #include "base/cl_sysdep.h" // Specification. #include "cln/dfloat.h" // Implementation. #include "float/dfloat/cl_DF.h" namespace cln { CL_INLINE uintC CL_INLINE_DECL(float_digits) (const cl_DF& x) { unused x; return DF_mant_len+1; // 53 } } // namespace cln
Java
package org.scada_lts.dao.model.multichangehistory; import java.util.Objects; /** * @author grzegorz.bylica@abilit.eu on 16.10.2019 */ public class MultiChangeHistoryValues { private int id; private int userId; private String userName; private String viewAndCmpIdentyfication; private String interpretedState; private long timeStamp; private int valueId; private String value; private int dataPointId; private String xidPoint; public MultiChangeHistoryValues() {} public int getId() { return id; } public void setId(int id) { this.id = id; } public int getUserId() { return userId; } public void setUserId(int userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getViewAndCmpIdentyfication() { return viewAndCmpIdentyfication; } public void setViewAndCmpIdentyfication(String viewAndCmpIdentyfication) { this.viewAndCmpIdentyfication = viewAndCmpIdentyfication; } public String getInterpretedState() { return interpretedState; } public void setInterpretedState(String interpretedState) { this.interpretedState = interpretedState; } public long getTimeStamp() { return timeStamp; } public void setTimeStamp(long timeStamp) { this.timeStamp = timeStamp; } public int getValueId() { return valueId; } public void setValueId(int valueId) { this.valueId = valueId; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public int getDataPointId() { return dataPointId; } public void setDataPointId(int dataPointId) { this.dataPointId = dataPointId; } public String getXidPoint() { return xidPoint; } public void setXidPoint(String xidPoint) { this.xidPoint = xidPoint; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; MultiChangeHistoryValues that = (MultiChangeHistoryValues) o; return id == that.id && userId == that.userId && valueId == that.valueId && dataPointId == that.dataPointId && Objects.equals(userName, that.userName) && Objects.equals(viewAndCmpIdentyfication, that.viewAndCmpIdentyfication) && Objects.equals(interpretedState, that.interpretedState) && Objects.equals(timeStamp, that.timeStamp) && Objects.equals(value, that.value) && Objects.equals(xidPoint, that.xidPoint); } @Override public int hashCode() { return Objects.hash(id, userId, userName, viewAndCmpIdentyfication, interpretedState, timeStamp, valueId, value, dataPointId, xidPoint); } @Override public String toString() { return "MultiChangeHistoryValues{" + "id=" + id + ", userId=" + userId + ", userName='" + userName + '\'' + ", viewAndCmpIdentyfication='" + viewAndCmpIdentyfication + '\'' + ", interpretedState='" + interpretedState + '\'' + ", ts=" + timeStamp + ", valueId=" + valueId + ", value='" + value + '\'' + ", dataPointId=" + dataPointId + ", xidPoint='" + xidPoint + '\'' + '}'; } }
Java
<?php /** V4.50 6 July 2004 (c) 2000-2004 John Lim (jlim@natsoft.com.my). All rights reserved. Released under both BSD license and Lesser GPL library license. Whenever there is any discrepancy between the two licenses, the BSD license will take precedence. Set tabs to 4 for best viewing. */ // security - hide paths if (!defined('ADODB_DIR')) die(); class ADODB2_ibase extends ADODB_DataDict { var $databaseType = 'ibase'; var $seqField = false; function ActualType($meta) { switch($meta) { case 'C': return 'VARCHAR'; case 'XL': case 'X': return 'VARCHAR(4000)'; case 'C2': return 'VARCHAR'; // up to 32K case 'X2': return 'VARCHAR(4000)'; case 'B': return 'BLOB'; case 'D': return 'DATE'; case 'T': return 'TIMESTAMP'; case 'L': return 'SMALLINT'; case 'I': return 'INTEGER'; case 'I1': return 'SMALLINT'; case 'I2': return 'SMALLINT'; case 'I4': return 'INTEGER'; case 'I8': return 'INTEGER'; case 'F': return 'DOUBLE PRECISION'; case 'N': return 'DECIMAL'; default: return $meta; } } function AlterColumnSQL($tabname, $flds) { if ($this->debug) ADOConnection::outp("AlterColumnSQL not supported"); return array(); } function DropColumnSQL($tabname, $flds) { if ($this->debug) ADOConnection::outp("DropColumnSQL not supported"); return array(); } } ?>
Java
# -*- coding: utf-8 -*- # ..#######.########.#######.##....#..######..######.########....###...########.#######.########..######. # .##.....#.##.....#.##......###...#.##....#.##....#.##.....#...##.##..##.....#.##......##.....#.##....## # .##.....#.##.....#.##......####..#.##......##......##.....#..##...##.##.....#.##......##.....#.##...... # .##.....#.########.######..##.##.#..######.##......########.##.....#.########.######..########..######. # .##.....#.##.......##......##..###.......#.##......##...##..########.##.......##......##...##........## # .##.....#.##.......##......##...##.##....#.##....#.##....##.##.....#.##.......##......##....##.##....## # ..#######.##.......#######.##....#..######..######.##.....#.##.....#.##.......#######.##.....#..######. ''' OpenScrapers 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 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. ''' import re from openscrapers.modules import cleantitle, source_utils, cfscrape class source: def __init__(self): self.priority = 1 self.language = ['en'] self.domains = ['coolmoviezone.online'] self.base_link = 'https://coolmoviezone.online' self.scraper = cfscrape.create_scraper() def movie(self, imdb, title, localtitle, aliases, year): try: title = cleantitle.geturl(title) url = self.base_link + '/%s-%s' % (title, year) return url except: return def sources(self, url, hostDict, hostprDict): try: sources = [] r = self.scraper.get(url).content match = re.compile('<td align="center"><strong><a href="(.+?)"').findall(r) for url in match: host = url.split('//')[1].replace('www.', '') host = host.split('/')[0].split('.')[0].title() quality = source_utils.check_sd_url(url) sources.append({'source': host, 'quality': quality, 'language': 'en', 'url': url, 'direct': False, 'debridonly': False}) except Exception: return return sources def resolve(self, url): return url
Java
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations * under the License. */ package org.apache.fontbox.cff.charset; /** * This is specialized CFFCharset. It's used if the CharsetId of a font is set to 1. * * @author Villu Ruusmann * @version $Revision$ */ public class CFFExpertCharset extends CFFCharset { private CFFExpertCharset() { } /** * Returns an instance of the CFFExpertCharset class. * * @return an instance of CFFExpertCharset */ public static CFFExpertCharset getInstance() { return CFFExpertCharset.INSTANCE; } private static final CFFExpertCharset INSTANCE = new CFFExpertCharset(); static { INSTANCE.register(1, "space"); INSTANCE.register(13, "comma"); INSTANCE.register(14, "hyphen"); INSTANCE.register(15, "period"); INSTANCE.register(27, "colon"); INSTANCE.register(28, "semicolon"); INSTANCE.register(99, "fraction"); INSTANCE.register(109, "fi"); INSTANCE.register(110, "fl"); INSTANCE.register(150, "onesuperior"); INSTANCE.register(155, "onehalf"); INSTANCE.register(158, "onequarter"); INSTANCE.register(163, "threequarters"); INSTANCE.register(164, "twosuperior"); INSTANCE.register(169, "threesuperior"); INSTANCE.register(229, "exclamsmall"); INSTANCE.register(230, "Hungarumlautsmall"); INSTANCE.register(231, "dollaroldstyle"); INSTANCE.register(232, "dollarsuperior"); INSTANCE.register(233, "ampersandsmall"); INSTANCE.register(234, "Acutesmall"); INSTANCE.register(235, "parenleftsuperior"); INSTANCE.register(236, "parenrightsuperior"); INSTANCE.register(237, "twodotenleader"); INSTANCE.register(238, "onedotenleader"); INSTANCE.register(239, "zerooldstyle"); INSTANCE.register(240, "oneoldstyle"); INSTANCE.register(241, "twooldstyle"); INSTANCE.register(242, "threeoldstyle"); INSTANCE.register(243, "fouroldstyle"); INSTANCE.register(244, "fiveoldstyle"); INSTANCE.register(245, "sixoldstyle"); INSTANCE.register(246, "sevenoldstyle"); INSTANCE.register(247, "eightoldstyle"); INSTANCE.register(248, "nineoldstyle"); INSTANCE.register(249, "commasuperior"); INSTANCE.register(250, "threequartersemdash"); INSTANCE.register(251, "periodsuperior"); INSTANCE.register(252, "questionsmall"); INSTANCE.register(253, "asuperior"); INSTANCE.register(254, "bsuperior"); INSTANCE.register(255, "centsuperior"); INSTANCE.register(256, "dsuperior"); INSTANCE.register(257, "esuperior"); INSTANCE.register(258, "isuperior"); INSTANCE.register(259, "lsuperior"); INSTANCE.register(260, "msuperior"); INSTANCE.register(261, "nsuperior"); INSTANCE.register(262, "osuperior"); INSTANCE.register(263, "rsuperior"); INSTANCE.register(264, "ssuperior"); INSTANCE.register(265, "tsuperior"); INSTANCE.register(266, "ff"); INSTANCE.register(267, "ffi"); INSTANCE.register(268, "ffl"); INSTANCE.register(269, "parenleftinferior"); INSTANCE.register(270, "parenrightinferior"); INSTANCE.register(271, "Circumflexsmall"); INSTANCE.register(272, "hyphensuperior"); INSTANCE.register(273, "Gravesmall"); INSTANCE.register(274, "Asmall"); INSTANCE.register(275, "Bsmall"); INSTANCE.register(276, "Csmall"); INSTANCE.register(277, "Dsmall"); INSTANCE.register(278, "Esmall"); INSTANCE.register(279, "Fsmall"); INSTANCE.register(280, "Gsmall"); INSTANCE.register(281, "Hsmall"); INSTANCE.register(282, "Ismall"); INSTANCE.register(283, "Jsmall"); INSTANCE.register(284, "Ksmall"); INSTANCE.register(285, "Lsmall"); INSTANCE.register(286, "Msmall"); INSTANCE.register(287, "Nsmall"); INSTANCE.register(288, "Osmall"); INSTANCE.register(289, "Psmall"); INSTANCE.register(290, "Qsmall"); INSTANCE.register(291, "Rsmall"); INSTANCE.register(292, "Ssmall"); INSTANCE.register(293, "Tsmall"); INSTANCE.register(294, "Usmall"); INSTANCE.register(295, "Vsmall"); INSTANCE.register(296, "Wsmall"); INSTANCE.register(297, "Xsmall"); INSTANCE.register(298, "Ysmall"); INSTANCE.register(299, "Zsmall"); INSTANCE.register(300, "colonmonetary"); INSTANCE.register(301, "onefitted"); INSTANCE.register(302, "rupiah"); INSTANCE.register(303, "Tildesmall"); INSTANCE.register(304, "exclamdownsmall"); INSTANCE.register(305, "centoldstyle"); INSTANCE.register(306, "Lslashsmall"); INSTANCE.register(307, "Scaronsmall"); INSTANCE.register(308, "Zcaronsmall"); INSTANCE.register(309, "Dieresissmall"); INSTANCE.register(310, "Brevesmall"); INSTANCE.register(311, "Caronsmall"); INSTANCE.register(312, "Dotaccentsmall"); INSTANCE.register(313, "Macronsmall"); INSTANCE.register(314, "figuredash"); INSTANCE.register(315, "hypheninferior"); INSTANCE.register(316, "Ogoneksmall"); INSTANCE.register(317, "Ringsmall"); INSTANCE.register(318, "Cedillasmall"); INSTANCE.register(319, "questiondownsmall"); INSTANCE.register(320, "oneeighth"); INSTANCE.register(321, "threeeighths"); INSTANCE.register(322, "fiveeighths"); INSTANCE.register(323, "seveneighths"); INSTANCE.register(324, "onethird"); INSTANCE.register(325, "twothirds"); INSTANCE.register(326, "zerosuperior"); INSTANCE.register(327, "foursuperior"); INSTANCE.register(328, "fivesuperior"); INSTANCE.register(329, "sixsuperior"); INSTANCE.register(330, "sevensuperior"); INSTANCE.register(331, "eightsuperior"); INSTANCE.register(332, "ninesuperior"); INSTANCE.register(333, "zeroinferior"); INSTANCE.register(334, "oneinferior"); INSTANCE.register(335, "twoinferior"); INSTANCE.register(336, "threeinferior"); INSTANCE.register(337, "fourinferior"); INSTANCE.register(338, "fiveinferior"); INSTANCE.register(339, "sixinferior"); INSTANCE.register(340, "seveninferior"); INSTANCE.register(341, "eightinferior"); INSTANCE.register(342, "nineinferior"); INSTANCE.register(343, "centinferior"); INSTANCE.register(344, "dollarinferior"); INSTANCE.register(345, "periodinferior"); INSTANCE.register(346, "commainferior"); INSTANCE.register(347, "Agravesmall"); INSTANCE.register(348, "Aacutesmall"); INSTANCE.register(349, "Acircumflexsmall"); INSTANCE.register(350, "Atildesmall"); INSTANCE.register(351, "Adieresissmall"); INSTANCE.register(352, "Aringsmall"); INSTANCE.register(353, "AEsmall"); INSTANCE.register(354, "Ccedillasmall"); INSTANCE.register(355, "Egravesmall"); INSTANCE.register(356, "Eacutesmall"); INSTANCE.register(357, "Ecircumflexsmall"); INSTANCE.register(358, "Edieresissmall"); INSTANCE.register(359, "Igravesmall"); INSTANCE.register(360, "Iacutesmall"); INSTANCE.register(361, "Icircumflexsmall"); INSTANCE.register(362, "Idieresissmall"); INSTANCE.register(363, "Ethsmall"); INSTANCE.register(364, "Ntildesmall"); INSTANCE.register(365, "Ogravesmall"); INSTANCE.register(366, "Oacutesmall"); INSTANCE.register(367, "Ocircumflexsmall"); INSTANCE.register(368, "Otildesmall"); INSTANCE.register(369, "Odieresissmall"); INSTANCE.register(370, "OEsmall"); INSTANCE.register(371, "Oslashsmall"); INSTANCE.register(372, "Ugravesmall"); INSTANCE.register(373, "Uacutesmall"); INSTANCE.register(374, "Ucircumflexsmall"); INSTANCE.register(375, "Udieresissmall"); INSTANCE.register(376, "Yacutesmall"); INSTANCE.register(377, "Thornsmall"); INSTANCE.register(378, "Ydieresissmall"); } }
Java
</main> <div class="footer__break"></div> <footer id="footer" class="footer" role="contentinfo"> <div class="content__wrapper"> <?php get_template_part( 'template-parts/footer/newsletter' ); get_template_part( 'template-parts/footer/social' ); ?> </div> <?php get_template_part( 'template-parts/footer/copyright' ); ?> </footer> <?php get_template_part( 'template-parts/footer/bottom' ); ?> <?php wp_footer(); ?> </body> </html>
Java
package com.starfarers.dao; import java.util.List; public interface BaseDao<T> { public void create(T entity); public T save(T entity); public void save(List<T> entities); public void remove(T entity); public T find(Integer id); public List<T> findAll(); public <P> T findBy(String attribute, P parameter); }
Java
/* * YAFFS: Yet another Flash File System . A NAND-flash specific file system. * * Copyright (C) 2002-2007 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 Lesser General Public License version 2.1 as * published by the Free Software Foundation. * * Note: Only YAFFS headers are LGPL, YAFFS C code is covered by GPL. */ /* This is used to pack YAFFS2 tags, not YAFFS1tags. */ #ifndef __YAFFS_PACKEDTAGS2_H__ #define __YAFFS_PACKEDTAGS2_H__ #include "yaffs_guts.h" #include "yaffs_ecc.h" typedef struct { unsigned sequenceNumber; unsigned objectId; unsigned chunkId; unsigned byteCount; } yaffs_PackedTags2TagsPart; typedef struct{ yaffs_PackedTags2TagsPart t; yaffs_ECCOther ecc; } yaffs_PackedTags2; /* Full packed tags with ECC, used for oob tags */ void yaffs_PackTags2(yaffs_PackedTags2 * pt, const yaffs_ExtendedTags * t); void yaffs_UnpackTags2(yaffs_ExtendedTags * t, yaffs_PackedTags2 * pt); /* Only the tags part (no ECC for use with inband tags */ void yaffs_PackTags2TagsPart(yaffs_PackedTags2TagsPart * pt, const yaffs_ExtendedTags * t); void yaffs_UnpackTags2TagsPart(yaffs_ExtendedTags * t, yaffs_PackedTags2TagsPart * pt); #endif
Java
/* * Multiple format streaming server * Copyright (c) 2000, 2001, 2002 Fabrice Bellard * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #define HAVE_AV_CONFIG_H #include "avformat.h" #include <stdarg.h> #include <unistd.h> #include <fcntl.h> #include <sys/ioctl.h> #include <sys/poll.h> #include <errno.h> #include <sys/time.h> #undef time //needed because HAVE_AV_CONFIG_H is defined on top #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <sys/wait.h> #include <netinet/in.h> #include <arpa/inet.h> #include <netdb.h> #include <signal.h> #ifdef CONFIG_HAVE_DLFCN #include <dlfcn.h> #endif #include "ffserver.h" /* maximum number of simultaneous HTTP connections */ #define HTTP_MAX_CONNECTIONS 2000 enum HTTPState { HTTPSTATE_WAIT_REQUEST, HTTPSTATE_SEND_HEADER, HTTPSTATE_SEND_DATA_HEADER, HTTPSTATE_SEND_DATA, /* sending TCP or UDP data */ HTTPSTATE_SEND_DATA_TRAILER, HTTPSTATE_RECEIVE_DATA, HTTPSTATE_WAIT_FEED, /* wait for data from the feed */ HTTPSTATE_READY, RTSPSTATE_WAIT_REQUEST, RTSPSTATE_SEND_REPLY, RTSPSTATE_SEND_PACKET, }; const char *http_state[] = { "HTTP_WAIT_REQUEST", "HTTP_SEND_HEADER", "SEND_DATA_HEADER", "SEND_DATA", "SEND_DATA_TRAILER", "RECEIVE_DATA", "WAIT_FEED", "READY", "RTSP_WAIT_REQUEST", "RTSP_SEND_REPLY", "RTSP_SEND_PACKET", }; #define IOBUFFER_INIT_SIZE 8192 /* coef for exponential mean for bitrate estimation in statistics */ #define AVG_COEF 0.9 /* timeouts are in ms */ #define HTTP_REQUEST_TIMEOUT (15 * 1000) #define RTSP_REQUEST_TIMEOUT (3600 * 24 * 1000) #define SYNC_TIMEOUT (10 * 1000) typedef struct { int64_t count1, count2; long time1, time2; } DataRateData; /* context associated with one connection */ typedef struct HTTPContext { enum HTTPState state; int fd; /* socket file descriptor */ struct sockaddr_in from_addr; /* origin */ struct pollfd *poll_entry; /* used when polling */ long timeout; uint8_t *buffer_ptr, *buffer_end; int http_error; struct HTTPContext *next; int got_key_frame; /* stream 0 => 1, stream 1 => 2, stream 2=> 4 */ int64_t data_count; /* feed input */ int feed_fd; /* input format handling */ AVFormatContext *fmt_in; long start_time; /* In milliseconds - this wraps fairly often */ int64_t first_pts; /* initial pts value */ int64_t cur_pts; /* current pts value from the stream in us */ int64_t cur_frame_duration; /* duration of the current frame in us */ int cur_frame_bytes; /* output frame size, needed to compute the time at which we send each packet */ int pts_stream_index; /* stream we choose as clock reference */ int64_t cur_clock; /* current clock reference value in us */ /* output format handling */ struct FFStream *stream; /* -1 is invalid stream */ int feed_streams[MAX_STREAMS]; /* index of streams in the feed */ int switch_feed_streams[MAX_STREAMS]; /* index of streams in the feed */ int switch_pending; AVFormatContext fmt_ctx; /* instance of FFStream for one user */ int last_packet_sent; /* true if last data packet was sent */ int suppress_log; DataRateData datarate; int wmp_client_id; char protocol[16]; char method[16]; char url[128]; int buffer_size; uint8_t *buffer; int is_packetized; /* if true, the stream is packetized */ int packet_stream_index; /* current stream for output in state machine */ /* RTSP state specific */ uint8_t *pb_buffer; /* XXX: use that in all the code */ ByteIOContext *pb; int seq; /* RTSP sequence number */ /* RTP state specific */ enum RTSPProtocol rtp_protocol; char session_id[32]; /* session id */ AVFormatContext *rtp_ctx[MAX_STREAMS]; /* RTP/UDP specific */ URLContext *rtp_handles[MAX_STREAMS]; /* RTP/TCP specific */ struct HTTPContext *rtsp_c; uint8_t *packet_buffer, *packet_buffer_ptr, *packet_buffer_end; } HTTPContext; static AVFrame dummy_frame; /* each generated stream is described here */ enum StreamType { STREAM_TYPE_LIVE, STREAM_TYPE_STATUS, STREAM_TYPE_REDIRECT, }; enum IPAddressAction { IP_ALLOW = 1, IP_DENY, }; typedef struct IPAddressACL { struct IPAddressACL *next; enum IPAddressAction action; /* These are in host order */ struct in_addr first; struct in_addr last; } IPAddressACL; /* description of each stream of the ffserver.conf file */ typedef struct FFStream { enum StreamType stream_type; char filename[1024]; /* stream filename */ struct FFStream *feed; /* feed we are using (can be null if coming from file) */ AVFormatParameters *ap_in; /* input parameters */ AVInputFormat *ifmt; /* if non NULL, force input format */ AVOutputFormat *fmt; IPAddressACL *acl; int nb_streams; int prebuffer; /* Number of millseconds early to start */ long max_time; /* Number of milliseconds to run */ int send_on_key; AVStream *streams[MAX_STREAMS]; int feed_streams[MAX_STREAMS]; /* index of streams in the feed */ char feed_filename[1024]; /* file name of the feed storage, or input file name for a stream */ char author[512]; char title[512]; char copyright[512]; char comment[512]; pid_t pid; /* Of ffmpeg process */ time_t pid_start; /* Of ffmpeg process */ char **child_argv; struct FFStream *next; int bandwidth; /* bandwidth, in kbits/s */ /* RTSP options */ char *rtsp_option; /* multicast specific */ int is_multicast; struct in_addr multicast_ip; int multicast_port; /* first port used for multicast */ int multicast_ttl; int loop; /* if true, send the stream in loops (only meaningful if file) */ /* feed specific */ int feed_opened; /* true if someone is writing to the feed */ int is_feed; /* true if it is a feed */ int readonly; /* True if writing is prohibited to the file */ int conns_served; int64_t bytes_served; int64_t feed_max_size; /* maximum storage size */ int64_t feed_write_index; /* current write position in feed (it wraps round) */ int64_t feed_size; /* current size of feed */ struct FFStream *next_feed; } FFStream; typedef struct FeedData { long long data_count; float avg_frame_size; /* frame size averraged over last frames with exponential mean */ } FeedData; struct sockaddr_in my_http_addr; struct sockaddr_in my_rtsp_addr; char logfilename[1024]; HTTPContext *first_http_ctx; FFStream *first_feed; /* contains only feeds */ FFStream *first_stream; /* contains all streams, including feeds */ static void new_connection(int server_fd, int is_rtsp); static void close_connection(HTTPContext *c); /* HTTP handling */ static int handle_connection(HTTPContext *c); static int http_parse_request(HTTPContext *c); static int http_send_data(HTTPContext *c); static void compute_stats(HTTPContext *c); static int open_input_stream(HTTPContext *c, const char *info); static int http_start_receive_data(HTTPContext *c); static int http_receive_data(HTTPContext *c); /* RTSP handling */ static int rtsp_parse_request(HTTPContext *c); static void rtsp_cmd_describe(HTTPContext *c, const char *url); static void rtsp_cmd_options(HTTPContext *c, const char *url); static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPHeader *h); static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h); static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h); static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h); /* SDP handling */ static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer, struct in_addr my_ip); /* RTP handling */ static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr, FFStream *stream, const char *session_id, enum RTSPProtocol rtp_protocol); static int rtp_new_av_stream(HTTPContext *c, int stream_index, struct sockaddr_in *dest_addr, HTTPContext *rtsp_c); static const char *my_program_name; static const char *my_program_dir; static int ffserver_debug; static int ffserver_daemon; static int no_launch; static int need_to_start_children; int nb_max_connections; int nb_connections; int max_bandwidth; int current_bandwidth; static long cur_time; // Making this global saves on passing it around everywhere static long gettime_ms(void) { struct timeval tv; gettimeofday(&tv,NULL); return (long long)tv.tv_sec * 1000 + (tv.tv_usec / 1000); } static FILE *logfile = NULL; static void __attribute__ ((format (printf, 1, 2))) http_log(const char *fmt, ...) { va_list ap; va_start(ap, fmt); if (logfile) { vfprintf(logfile, fmt, ap); fflush(logfile); } va_end(ap); } static char *ctime1(char *buf2) { time_t ti; char *p; ti = time(NULL); p = ctime(&ti); strcpy(buf2, p); p = buf2 + strlen(p) - 1; if (*p == '\n') *p = '\0'; return buf2; } static void log_connection(HTTPContext *c) { char buf2[32]; if (c->suppress_log) return; http_log("%s - - [%s] \"%s %s %s\" %d %lld\n", inet_ntoa(c->from_addr.sin_addr), ctime1(buf2), c->method, c->url, c->protocol, (c->http_error ? c->http_error : 200), c->data_count); } static void update_datarate(DataRateData *drd, int64_t count) { if (!drd->time1 && !drd->count1) { drd->time1 = drd->time2 = cur_time; drd->count1 = drd->count2 = count; } else { if (cur_time - drd->time2 > 5000) { drd->time1 = drd->time2; drd->count1 = drd->count2; drd->time2 = cur_time; drd->count2 = count; } } } /* In bytes per second */ static int compute_datarate(DataRateData *drd, int64_t count) { if (cur_time == drd->time1) return 0; return ((count - drd->count1) * 1000) / (cur_time - drd->time1); } static int get_longterm_datarate(DataRateData *drd, int64_t count) { /* You get the first 3 seconds flat out */ if (cur_time - drd->time1 < 3000) return 0; return compute_datarate(drd, count); } static void start_children(FFStream *feed) { if (no_launch) return; for (; feed; feed = feed->next) { if (feed->child_argv && !feed->pid) { feed->pid_start = time(0); feed->pid = fork(); if (feed->pid < 0) { fprintf(stderr, "Unable to create children\n"); exit(1); } if (!feed->pid) { /* In child */ char pathname[1024]; char *slash; int i; for (i = 3; i < 256; i++) { close(i); } if (!ffserver_debug) { i = open("/dev/null", O_RDWR); if (i) dup2(i, 0); dup2(i, 1); dup2(i, 2); if (i) close(i); } pstrcpy(pathname, sizeof(pathname), my_program_name); slash = strrchr(pathname, '/'); if (!slash) { slash = pathname; } else { slash++; } strcpy(slash, "ffmpeg"); /* This is needed to make relative pathnames work */ chdir(my_program_dir); signal(SIGPIPE, SIG_DFL); execvp(pathname, feed->child_argv); _exit(1); } } } } /* open a listening socket */ static int socket_open_listen(struct sockaddr_in *my_addr) { int server_fd, tmp; server_fd = socket(AF_INET,SOCK_STREAM,0); if (server_fd < 0) { perror ("socket"); return -1; } tmp = 1; setsockopt(server_fd, SOL_SOCKET, SO_REUSEADDR, &tmp, sizeof(tmp)); if (bind (server_fd, (struct sockaddr *) my_addr, sizeof (*my_addr)) < 0) { char bindmsg[32]; snprintf(bindmsg, sizeof(bindmsg), "bind(port %d)", ntohs(my_addr->sin_port)); perror (bindmsg); close(server_fd); return -1; } if (listen (server_fd, 5) < 0) { perror ("listen"); close(server_fd); return -1; } fcntl(server_fd, F_SETFL, O_NONBLOCK); return server_fd; } /* start all multicast streams */ static void start_multicast(void) { FFStream *stream; char session_id[32]; HTTPContext *rtp_c; struct sockaddr_in dest_addr; int default_port, stream_index; default_port = 6000; for(stream = first_stream; stream != NULL; stream = stream->next) { if (stream->is_multicast) { /* open the RTP connection */ snprintf(session_id, sizeof(session_id), "%08x%08x", (int)random(), (int)random()); /* choose a port if none given */ if (stream->multicast_port == 0) { stream->multicast_port = default_port; default_port += 100; } dest_addr.sin_family = AF_INET; dest_addr.sin_addr = stream->multicast_ip; dest_addr.sin_port = htons(stream->multicast_port); rtp_c = rtp_new_connection(&dest_addr, stream, session_id, RTSP_PROTOCOL_RTP_UDP_MULTICAST); if (!rtp_c) { continue; } if (open_input_stream(rtp_c, "") < 0) { fprintf(stderr, "Could not open input stream for stream '%s'\n", stream->filename); continue; } /* open each RTP stream */ for(stream_index = 0; stream_index < stream->nb_streams; stream_index++) { dest_addr.sin_port = htons(stream->multicast_port + 2 * stream_index); if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, NULL) < 0) { fprintf(stderr, "Could not open output stream '%s/streamid=%d'\n", stream->filename, stream_index); exit(1); } } /* change state to send data */ rtp_c->state = HTTPSTATE_SEND_DATA; } } } /* main loop of the http server */ static int http_server(void) { int server_fd, ret, rtsp_server_fd, delay, delay1; struct pollfd poll_table[HTTP_MAX_CONNECTIONS + 2], *poll_entry; HTTPContext *c, *c_next; server_fd = socket_open_listen(&my_http_addr); if (server_fd < 0) return -1; rtsp_server_fd = socket_open_listen(&my_rtsp_addr); if (rtsp_server_fd < 0) return -1; http_log("ffserver started.\n"); start_children(first_feed); first_http_ctx = NULL; nb_connections = 0; start_multicast(); for(;;) { poll_entry = poll_table; poll_entry->fd = server_fd; poll_entry->events = POLLIN; poll_entry++; poll_entry->fd = rtsp_server_fd; poll_entry->events = POLLIN; poll_entry++; /* wait for events on each HTTP handle */ c = first_http_ctx; delay = 1000; while (c != NULL) { int fd; fd = c->fd; switch(c->state) { case HTTPSTATE_SEND_HEADER: case RTSPSTATE_SEND_REPLY: case RTSPSTATE_SEND_PACKET: c->poll_entry = poll_entry; poll_entry->fd = fd; poll_entry->events = POLLOUT; poll_entry++; break; case HTTPSTATE_SEND_DATA_HEADER: case HTTPSTATE_SEND_DATA: case HTTPSTATE_SEND_DATA_TRAILER: if (!c->is_packetized) { /* for TCP, we output as much as we can (may need to put a limit) */ c->poll_entry = poll_entry; poll_entry->fd = fd; poll_entry->events = POLLOUT; poll_entry++; } else { /* when ffserver is doing the timing, we work by looking at which packet need to be sent every 10 ms */ delay1 = 10; /* one tick wait XXX: 10 ms assumed */ if (delay1 < delay) delay = delay1; } break; case HTTPSTATE_WAIT_REQUEST: case HTTPSTATE_RECEIVE_DATA: case HTTPSTATE_WAIT_FEED: case RTSPSTATE_WAIT_REQUEST: /* need to catch errors */ c->poll_entry = poll_entry; poll_entry->fd = fd; poll_entry->events = POLLIN;/* Maybe this will work */ poll_entry++; break; default: c->poll_entry = NULL; break; } c = c->next; } /* wait for an event on one connection. We poll at least every second to handle timeouts */ do { ret = poll(poll_table, poll_entry - poll_table, delay); if (ret < 0 && errno != EAGAIN && errno != EINTR) return -1; } while (ret <= 0); cur_time = gettime_ms(); if (need_to_start_children) { need_to_start_children = 0; start_children(first_feed); } /* now handle the events */ for(c = first_http_ctx; c != NULL; c = c_next) { c_next = c->next; if (handle_connection(c) < 0) { /* close and free the connection */ log_connection(c); close_connection(c); } } poll_entry = poll_table; /* new HTTP connection request ? */ if (poll_entry->revents & POLLIN) { new_connection(server_fd, 0); } poll_entry++; /* new RTSP connection request ? */ if (poll_entry->revents & POLLIN) { new_connection(rtsp_server_fd, 1); } } } /* start waiting for a new HTTP/RTSP request */ static void start_wait_request(HTTPContext *c, int is_rtsp) { c->buffer_ptr = c->buffer; c->buffer_end = c->buffer + c->buffer_size - 1; /* leave room for '\0' */ if (is_rtsp) { c->timeout = cur_time + RTSP_REQUEST_TIMEOUT; c->state = RTSPSTATE_WAIT_REQUEST; } else { c->timeout = cur_time + HTTP_REQUEST_TIMEOUT; c->state = HTTPSTATE_WAIT_REQUEST; } } static void new_connection(int server_fd, int is_rtsp) { struct sockaddr_in from_addr; int fd, len; HTTPContext *c = NULL; len = sizeof(from_addr); fd = accept(server_fd, (struct sockaddr *)&from_addr, &len); if (fd < 0) return; fcntl(fd, F_SETFL, O_NONBLOCK); /* XXX: should output a warning page when coming close to the connection limit */ if (nb_connections >= nb_max_connections) goto fail; /* add a new connection */ c = av_mallocz(sizeof(HTTPContext)); if (!c) goto fail; c->fd = fd; c->poll_entry = NULL; c->from_addr = from_addr; c->buffer_size = IOBUFFER_INIT_SIZE; c->buffer = av_malloc(c->buffer_size); if (!c->buffer) goto fail; c->next = first_http_ctx; first_http_ctx = c; nb_connections++; start_wait_request(c, is_rtsp); return; fail: if (c) { av_free(c->buffer); av_free(c); } close(fd); } static void close_connection(HTTPContext *c) { HTTPContext **cp, *c1; int i, nb_streams; AVFormatContext *ctx; URLContext *h; AVStream *st; /* remove connection from list */ cp = &first_http_ctx; while ((*cp) != NULL) { c1 = *cp; if (c1 == c) { *cp = c->next; } else { cp = &c1->next; } } /* remove references, if any (XXX: do it faster) */ for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) { if (c1->rtsp_c == c) c1->rtsp_c = NULL; } /* remove connection associated resources */ if (c->fd >= 0) close(c->fd); if (c->fmt_in) { /* close each frame parser */ for(i=0;i<c->fmt_in->nb_streams;i++) { st = c->fmt_in->streams[i]; if (st->codec.codec) { avcodec_close(&st->codec); } } av_close_input_file(c->fmt_in); } /* free RTP output streams if any */ nb_streams = 0; if (c->stream) nb_streams = c->stream->nb_streams; for(i=0;i<nb_streams;i++) { ctx = c->rtp_ctx[i]; if (ctx) { av_write_trailer(ctx); av_free(ctx); } h = c->rtp_handles[i]; if (h) { url_close(h); } } ctx = &c->fmt_ctx; if (!c->last_packet_sent) { if (ctx->oformat) { /* prepare header */ if (url_open_dyn_buf(&ctx->pb) >= 0) { av_write_trailer(ctx); url_close_dyn_buf(&ctx->pb, &c->pb_buffer); } } } for(i=0; i<ctx->nb_streams; i++) av_free(ctx->streams[i]) ; if (c->stream) current_bandwidth -= c->stream->bandwidth; av_freep(&c->pb_buffer); av_freep(&c->packet_buffer); av_free(c->buffer); av_free(c); nb_connections--; } static int handle_connection(HTTPContext *c) { int len, ret; switch(c->state) { case HTTPSTATE_WAIT_REQUEST: case RTSPSTATE_WAIT_REQUEST: /* timeout ? */ if ((c->timeout - cur_time) < 0) return -1; if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; /* no need to read if no events */ if (!(c->poll_entry->revents & POLLIN)) return 0; /* read the data */ read_loop: len = read(c->fd, c->buffer_ptr, 1); if (len < 0) { if (errno != EAGAIN && errno != EINTR) return -1; } else if (len == 0) { return -1; } else { /* search for end of request. */ uint8_t *ptr; c->buffer_ptr += len; ptr = c->buffer_ptr; if ((ptr >= c->buffer + 2 && !memcmp(ptr-2, "\n\n", 2)) || (ptr >= c->buffer + 4 && !memcmp(ptr-4, "\r\n\r\n", 4))) { /* request found : parse it and reply */ if (c->state == HTTPSTATE_WAIT_REQUEST) { ret = http_parse_request(c); } else { ret = rtsp_parse_request(c); } if (ret < 0) return -1; } else if (ptr >= c->buffer_end) { /* request too long: cannot do anything */ return -1; } else goto read_loop; } break; case HTTPSTATE_SEND_HEADER: if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; /* no need to write if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr); if (len < 0) { if (errno != EAGAIN && errno != EINTR) { /* error : close connection */ av_freep(&c->pb_buffer); return -1; } } else { c->buffer_ptr += len; if (c->stream) c->stream->bytes_served += len; c->data_count += len; if (c->buffer_ptr >= c->buffer_end) { av_freep(&c->pb_buffer); /* if error, exit */ if (c->http_error) { return -1; } /* all the buffer was sent : synchronize to the incoming stream */ c->state = HTTPSTATE_SEND_DATA_HEADER; c->buffer_ptr = c->buffer_end = c->buffer; } } break; case HTTPSTATE_SEND_DATA: case HTTPSTATE_SEND_DATA_HEADER: case HTTPSTATE_SEND_DATA_TRAILER: /* for packetized output, we consider we can always write (the input streams sets the speed). It may be better to verify that we do not rely too much on the kernel queues */ if (!c->is_packetized) { if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; /* no need to read if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; } if (http_send_data(c) < 0) return -1; break; case HTTPSTATE_RECEIVE_DATA: /* no need to read if no events */ if (c->poll_entry->revents & (POLLERR | POLLHUP)) return -1; if (!(c->poll_entry->revents & POLLIN)) return 0; if (http_receive_data(c) < 0) return -1; break; case HTTPSTATE_WAIT_FEED: /* no need to read if no events */ if (c->poll_entry->revents & (POLLIN | POLLERR | POLLHUP)) return -1; /* nothing to do, we'll be waken up by incoming feed packets */ break; case RTSPSTATE_SEND_REPLY: if (c->poll_entry->revents & (POLLERR | POLLHUP)) { av_freep(&c->pb_buffer); return -1; } /* no need to write if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr); if (len < 0) { if (errno != EAGAIN && errno != EINTR) { /* error : close connection */ av_freep(&c->pb_buffer); return -1; } } else { c->buffer_ptr += len; c->data_count += len; if (c->buffer_ptr >= c->buffer_end) { /* all the buffer was sent : wait for a new request */ av_freep(&c->pb_buffer); start_wait_request(c, 1); } } break; case RTSPSTATE_SEND_PACKET: if (c->poll_entry->revents & (POLLERR | POLLHUP)) { av_freep(&c->packet_buffer); return -1; } /* no need to write if no events */ if (!(c->poll_entry->revents & POLLOUT)) return 0; len = write(c->fd, c->packet_buffer_ptr, c->packet_buffer_end - c->packet_buffer_ptr); if (len < 0) { if (errno != EAGAIN && errno != EINTR) { /* error : close connection */ av_freep(&c->packet_buffer); return -1; } } else { c->packet_buffer_ptr += len; if (c->packet_buffer_ptr >= c->packet_buffer_end) { /* all the buffer was sent : wait for a new request */ av_freep(&c->packet_buffer); c->state = RTSPSTATE_WAIT_REQUEST; } } break; case HTTPSTATE_READY: /* nothing to do */ break; default: return -1; } return 0; } static int extract_rates(char *rates, int ratelen, const char *request) { const char *p; for (p = request; *p && *p != '\r' && *p != '\n'; ) { if (strncasecmp(p, "Pragma:", 7) == 0) { const char *q = p + 7; while (*q && *q != '\n' && isspace(*q)) q++; if (strncasecmp(q, "stream-switch-entry=", 20) == 0) { int stream_no; int rate_no; q += 20; memset(rates, 0xff, ratelen); while (1) { while (*q && *q != '\n' && *q != ':') q++; if (sscanf(q, ":%d:%d", &stream_no, &rate_no) != 2) { break; } stream_no--; if (stream_no < ratelen && stream_no >= 0) { rates[stream_no] = rate_no; } while (*q && *q != '\n' && !isspace(*q)) q++; } return 1; } } p = strchr(p, '\n'); if (!p) break; p++; } return 0; } static int find_stream_in_feed(FFStream *feed, AVCodecContext *codec, int bit_rate) { int i; int best_bitrate = 100000000; int best = -1; for (i = 0; i < feed->nb_streams; i++) { AVCodecContext *feed_codec = &feed->streams[i]->codec; if (feed_codec->codec_id != codec->codec_id || feed_codec->sample_rate != codec->sample_rate || feed_codec->width != codec->width || feed_codec->height != codec->height) { continue; } /* Potential stream */ /* We want the fastest stream less than bit_rate, or the slowest * faster than bit_rate */ if (feed_codec->bit_rate <= bit_rate) { if (best_bitrate > bit_rate || feed_codec->bit_rate > best_bitrate) { best_bitrate = feed_codec->bit_rate; best = i; } } else { if (feed_codec->bit_rate < best_bitrate) { best_bitrate = feed_codec->bit_rate; best = i; } } } return best; } static int modify_current_stream(HTTPContext *c, char *rates) { int i; FFStream *req = c->stream; int action_required = 0; /* Not much we can do for a feed */ if (!req->feed) return 0; for (i = 0; i < req->nb_streams; i++) { AVCodecContext *codec = &req->streams[i]->codec; switch(rates[i]) { case 0: c->switch_feed_streams[i] = req->feed_streams[i]; break; case 1: c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 2); break; case 2: /* Wants off or slow */ c->switch_feed_streams[i] = find_stream_in_feed(req->feed, codec, codec->bit_rate / 4); #ifdef WANTS_OFF /* This doesn't work well when it turns off the only stream! */ c->switch_feed_streams[i] = -2; c->feed_streams[i] = -2; #endif break; } if (c->switch_feed_streams[i] >= 0 && c->switch_feed_streams[i] != c->feed_streams[i]) action_required = 1; } return action_required; } static void do_switch_stream(HTTPContext *c, int i) { if (c->switch_feed_streams[i] >= 0) { #ifdef PHILIP c->feed_streams[i] = c->switch_feed_streams[i]; #endif /* Now update the stream */ } c->switch_feed_streams[i] = -1; } /* XXX: factorize in utils.c ? */ /* XXX: take care with different space meaning */ static void skip_spaces(const char **pp) { const char *p; p = *pp; while (*p == ' ' || *p == '\t') p++; *pp = p; } static void get_word(char *buf, int buf_size, const char **pp) { const char *p; char *q; p = *pp; skip_spaces(&p); q = buf; while (!isspace(*p) && *p != '\0') { if ((q - buf) < buf_size - 1) *q++ = *p; p++; } if (buf_size > 0) *q = '\0'; *pp = p; } static int validate_acl(FFStream *stream, HTTPContext *c) { enum IPAddressAction last_action = IP_DENY; IPAddressACL *acl; struct in_addr *src = &c->from_addr.sin_addr; unsigned long src_addr = ntohl(src->s_addr); for (acl = stream->acl; acl; acl = acl->next) { if (src_addr >= acl->first.s_addr && src_addr <= acl->last.s_addr) { return (acl->action == IP_ALLOW) ? 1 : 0; } last_action = acl->action; } /* Nothing matched, so return not the last action */ return (last_action == IP_DENY) ? 1 : 0; } /* compute the real filename of a file by matching it without its extensions to all the stream filenames */ static void compute_real_filename(char *filename, int max_size) { char file1[1024]; char file2[1024]; char *p; FFStream *stream; /* compute filename by matching without the file extensions */ pstrcpy(file1, sizeof(file1), filename); p = strrchr(file1, '.'); if (p) *p = '\0'; for(stream = first_stream; stream != NULL; stream = stream->next) { pstrcpy(file2, sizeof(file2), stream->filename); p = strrchr(file2, '.'); if (p) *p = '\0'; if (!strcmp(file1, file2)) { pstrcpy(filename, max_size, stream->filename); break; } } } enum RedirType { REDIR_NONE, REDIR_ASX, REDIR_RAM, REDIR_ASF, REDIR_RTSP, REDIR_SDP, }; /* parse http request and prepare header */ static int http_parse_request(HTTPContext *c) { char *p; int post; enum RedirType redir_type; char cmd[32]; char info[1024], *filename; char url[1024], *q; char protocol[32]; char msg[1024]; const char *mime_type; FFStream *stream; int i; char ratebuf[32]; char *useragent = 0; p = c->buffer; get_word(cmd, sizeof(cmd), (const char **)&p); pstrcpy(c->method, sizeof(c->method), cmd); if (!strcmp(cmd, "GET")) post = 0; else if (!strcmp(cmd, "POST")) post = 1; else return -1; get_word(url, sizeof(url), (const char **)&p); pstrcpy(c->url, sizeof(c->url), url); get_word(protocol, sizeof(protocol), (const char **)&p); if (strcmp(protocol, "HTTP/1.0") && strcmp(protocol, "HTTP/1.1")) return -1; pstrcpy(c->protocol, sizeof(c->protocol), protocol); /* find the filename and the optional info string in the request */ p = url; if (*p == '/') p++; filename = p; p = strchr(p, '?'); if (p) { pstrcpy(info, sizeof(info), p); *p = '\0'; } else { info[0] = '\0'; } for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) { if (strncasecmp(p, "User-Agent:", 11) == 0) { useragent = p + 11; if (*useragent && *useragent != '\n' && isspace(*useragent)) useragent++; break; } p = strchr(p, '\n'); if (!p) break; p++; } redir_type = REDIR_NONE; if (match_ext(filename, "asx")) { redir_type = REDIR_ASX; filename[strlen(filename)-1] = 'f'; } else if (match_ext(filename, "asf") && (!useragent || strncasecmp(useragent, "NSPlayer", 8) != 0)) { /* if this isn't WMP or lookalike, return the redirector file */ redir_type = REDIR_ASF; } else if (match_ext(filename, "rpm,ram")) { redir_type = REDIR_RAM; strcpy(filename + strlen(filename)-2, "m"); } else if (match_ext(filename, "rtsp")) { redir_type = REDIR_RTSP; compute_real_filename(filename, sizeof(url) - 1); } else if (match_ext(filename, "sdp")) { redir_type = REDIR_SDP; compute_real_filename(filename, sizeof(url) - 1); } stream = first_stream; while (stream != NULL) { if (!strcmp(stream->filename, filename) && validate_acl(stream, c)) break; stream = stream->next; } if (stream == NULL) { snprintf(msg, sizeof(msg), "File '%s' not found", url); goto send_error; } c->stream = stream; memcpy(c->feed_streams, stream->feed_streams, sizeof(c->feed_streams)); memset(c->switch_feed_streams, -1, sizeof(c->switch_feed_streams)); if (stream->stream_type == STREAM_TYPE_REDIRECT) { c->http_error = 301; q = c->buffer; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 301 Moved\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Location: %s\r\n", stream->feed_filename); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: text/html\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<html><head><title>Moved</title></head><body>\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "You should be <a href=\"%s\">redirected</a>.\r\n", stream->feed_filename); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</body></html>\r\n"); /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; } /* If this is WMP, get the rate information */ if (extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) { if (modify_current_stream(c, ratebuf)) { for (i = 0; i < sizeof(c->feed_streams) / sizeof(c->feed_streams[0]); i++) { if (c->switch_feed_streams[i] >= 0) do_switch_stream(c, i); } } } if (post == 0 && stream->stream_type == STREAM_TYPE_LIVE) { current_bandwidth += stream->bandwidth; } if (post == 0 && max_bandwidth < current_bandwidth) { c->http_error = 200; q = c->buffer; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 Server too busy\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: text/html\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<html><head><title>Too busy</title></head><body>\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "The server is too busy to serve your request at this time.<p>\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "The bandwidth being served (including your stream) is %dkbit/sec, and this exceeds the limit of %dkbit/sec\r\n", current_bandwidth, max_bandwidth); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</body></html>\r\n"); /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; } if (redir_type != REDIR_NONE) { char *hostinfo = 0; for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) { if (strncasecmp(p, "Host:", 5) == 0) { hostinfo = p + 5; break; } p = strchr(p, '\n'); if (!p) break; p++; } if (hostinfo) { char *eoh; char hostbuf[260]; while (isspace(*hostinfo)) hostinfo++; eoh = strchr(hostinfo, '\n'); if (eoh) { if (eoh[-1] == '\r') eoh--; if (eoh - hostinfo < sizeof(hostbuf) - 1) { memcpy(hostbuf, hostinfo, eoh - hostinfo); hostbuf[eoh - hostinfo] = 0; c->http_error = 200; q = c->buffer; switch(redir_type) { case REDIR_ASX: q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 ASX Follows\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: video/x-ms-asf\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<ASX Version=\"3\">\r\n"); //q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<!-- Autogenerated by ffserver -->\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<ENTRY><REF HREF=\"http://%s/%s%s\"/></ENTRY>\r\n", hostbuf, filename, info); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</ASX>\r\n"); break; case REDIR_RAM: q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 RAM Follows\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: audio/x-pn-realaudio\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "# Autogenerated by ffserver\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "http://%s/%s%s\r\n", hostbuf, filename, info); break; case REDIR_ASF: q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 ASF Redirect follows\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: video/x-ms-asf\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "[Reference]\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Ref1=http://%s/%s%s\r\n", hostbuf, filename, info); break; case REDIR_RTSP: { char hostname[256], *p; /* extract only hostname */ pstrcpy(hostname, sizeof(hostname), hostbuf); p = strrchr(hostname, ':'); if (p) *p = '\0'; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 RTSP Redirect follows\r\n"); /* XXX: incorrect mime type ? */ q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: application/x-rtsp\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "rtsp://%s:%d/%s\r\n", hostname, ntohs(my_rtsp_addr.sin_port), filename); } break; case REDIR_SDP: { uint8_t *sdp_data; int sdp_data_size, len; struct sockaddr_in my_addr; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: application/sdp\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); len = sizeof(my_addr); getsockname(c->fd, (struct sockaddr *)&my_addr, &len); /* XXX: should use a dynamic buffer */ sdp_data_size = prepare_sdp_description(stream, &sdp_data, my_addr.sin_addr); if (sdp_data_size > 0) { memcpy(q, sdp_data, sdp_data_size); q += sdp_data_size; *q = '\0'; av_free(sdp_data); } } break; default: av_abort(); break; } /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; } } } snprintf(msg, sizeof(msg), "ASX/RAM file not handled"); goto send_error; } stream->conns_served++; /* XXX: add there authenticate and IP match */ if (post) { /* if post, it means a feed is being sent */ if (!stream->is_feed) { /* However it might be a status report from WMP! Lets log the data * as it might come in handy one day */ char *logline = 0; int client_id = 0; for (p = c->buffer; *p && *p != '\r' && *p != '\n'; ) { if (strncasecmp(p, "Pragma: log-line=", 17) == 0) { logline = p; break; } if (strncasecmp(p, "Pragma: client-id=", 18) == 0) { client_id = strtol(p + 18, 0, 10); } p = strchr(p, '\n'); if (!p) break; p++; } if (logline) { char *eol = strchr(logline, '\n'); logline += 17; if (eol) { if (eol[-1] == '\r') eol--; http_log("%.*s\n", (int) (eol - logline), logline); c->suppress_log = 1; } } #ifdef DEBUG_WMP http_log("\nGot request:\n%s\n", c->buffer); #endif if (client_id && extract_rates(ratebuf, sizeof(ratebuf), c->buffer)) { HTTPContext *wmpc; /* Now we have to find the client_id */ for (wmpc = first_http_ctx; wmpc; wmpc = wmpc->next) { if (wmpc->wmp_client_id == client_id) break; } if (wmpc) { if (modify_current_stream(wmpc, ratebuf)) { wmpc->switch_pending = 1; } } } snprintf(msg, sizeof(msg), "POST command not handled"); c->stream = 0; goto send_error; } if (http_start_receive_data(c) < 0) { snprintf(msg, sizeof(msg), "could not open feed"); goto send_error; } c->http_error = 0; c->state = HTTPSTATE_RECEIVE_DATA; return 0; } #ifdef DEBUG_WMP if (strcmp(stream->filename + strlen(stream->filename) - 4, ".asf") == 0) { http_log("\nGot request:\n%s\n", c->buffer); } #endif if (c->stream->stream_type == STREAM_TYPE_STATUS) goto send_stats; /* open input stream */ if (open_input_stream(c, info) < 0) { snprintf(msg, sizeof(msg), "Input stream corresponding to '%s' not found", url); goto send_error; } /* prepare http header */ q = c->buffer; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 200 OK\r\n"); mime_type = c->stream->fmt->mime_type; if (!mime_type) mime_type = "application/x-octet_stream"; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Pragma: no-cache\r\n"); /* for asf, we need extra headers */ if (!strcmp(c->stream->fmt->name,"asf_stream")) { /* Need to allocate a client id */ c->wmp_client_id = random() & 0x7fffffff; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Server: Cougar 4.1.0.3923\r\nCache-Control: no-cache\r\nPragma: client-id=%d\r\nPragma: features=\"broadcast\"\r\n", c->wmp_client_id); } q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-Type: %s\r\n", mime_type); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); /* prepare output buffer */ c->http_error = 0; c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; send_error: c->http_error = 404; q = c->buffer; q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "HTTP/1.0 404 Not Found\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "Content-type: %s\r\n", "text/html"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "\r\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<HTML>\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<HEAD><TITLE>404 Not Found</TITLE></HEAD>\n"); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "<BODY>%s</BODY>\n", msg); q += snprintf(q, q - (char *) c->buffer + c->buffer_size, "</HTML>\n"); /* prepare output buffer */ c->buffer_ptr = c->buffer; c->buffer_end = q; c->state = HTTPSTATE_SEND_HEADER; return 0; send_stats: compute_stats(c); c->http_error = 200; /* horrible : we use this value to avoid going to the send data state */ c->state = HTTPSTATE_SEND_HEADER; return 0; } static void fmt_bytecount(ByteIOContext *pb, int64_t count) { static const char *suffix = " kMGTP"; const char *s; for (s = suffix; count >= 100000 && s[1]; count /= 1000, s++) { } url_fprintf(pb, "%lld%c", count, *s); } static void compute_stats(HTTPContext *c) { HTTPContext *c1; FFStream *stream; char *p; time_t ti; int i, len; ByteIOContext pb1, *pb = &pb1; if (url_open_dyn_buf(pb) < 0) { /* XXX: return an error ? */ c->buffer_ptr = c->buffer; c->buffer_end = c->buffer; return; } url_fprintf(pb, "HTTP/1.0 200 OK\r\n"); url_fprintf(pb, "Content-type: %s\r\n", "text/html"); url_fprintf(pb, "Pragma: no-cache\r\n"); url_fprintf(pb, "\r\n"); url_fprintf(pb, "<HEAD><TITLE>FFServer Status</TITLE>\n"); if (c->stream->feed_filename) { url_fprintf(pb, "<link rel=\"shortcut icon\" href=\"%s\">\n", c->stream->feed_filename); } url_fprintf(pb, "</HEAD>\n<BODY>"); url_fprintf(pb, "<H1>FFServer Status</H1>\n"); /* format status */ url_fprintf(pb, "<H2>Available Streams</H2>\n"); url_fprintf(pb, "<TABLE cellspacing=0 cellpadding=4>\n"); url_fprintf(pb, "<TR><Th valign=top>Path<th align=left>Served<br>Conns<Th><br>bytes<Th valign=top>Format<Th>Bit rate<br>kbits/s<Th align=left>Video<br>kbits/s<th><br>Codec<Th align=left>Audio<br>kbits/s<th><br>Codec<Th align=left valign=top>Feed\n"); stream = first_stream; while (stream != NULL) { char sfilename[1024]; char *eosf; if (stream->feed != stream) { pstrcpy(sfilename, sizeof(sfilename) - 10, stream->filename); eosf = sfilename + strlen(sfilename); if (eosf - sfilename >= 4) { if (strcmp(eosf - 4, ".asf") == 0) { strcpy(eosf - 4, ".asx"); } else if (strcmp(eosf - 3, ".rm") == 0) { strcpy(eosf - 3, ".ram"); } else if (stream->fmt == &rtp_mux) { /* generate a sample RTSP director if unicast. Generate an SDP redirector if multicast */ eosf = strrchr(sfilename, '.'); if (!eosf) eosf = sfilename + strlen(sfilename); if (stream->is_multicast) strcpy(eosf, ".sdp"); else strcpy(eosf, ".rtsp"); } } url_fprintf(pb, "<TR><TD><A HREF=\"/%s\">%s</A> ", sfilename, stream->filename); url_fprintf(pb, "<td align=right> %d <td align=right> ", stream->conns_served); fmt_bytecount(pb, stream->bytes_served); switch(stream->stream_type) { case STREAM_TYPE_LIVE: { int audio_bit_rate = 0; int video_bit_rate = 0; const char *audio_codec_name = ""; const char *video_codec_name = ""; const char *audio_codec_name_extra = ""; const char *video_codec_name_extra = ""; for(i=0;i<stream->nb_streams;i++) { AVStream *st = stream->streams[i]; AVCodec *codec = avcodec_find_encoder(st->codec.codec_id); switch(st->codec.codec_type) { case CODEC_TYPE_AUDIO: audio_bit_rate += st->codec.bit_rate; if (codec) { if (*audio_codec_name) audio_codec_name_extra = "..."; audio_codec_name = codec->name; } break; case CODEC_TYPE_VIDEO: video_bit_rate += st->codec.bit_rate; if (codec) { if (*video_codec_name) video_codec_name_extra = "..."; video_codec_name = codec->name; } break; case CODEC_TYPE_DATA: video_bit_rate += st->codec.bit_rate; break; default: av_abort(); } } url_fprintf(pb, "<TD align=center> %s <TD align=right> %d <TD align=right> %d <TD> %s %s <TD align=right> %d <TD> %s %s", stream->fmt->name, stream->bandwidth, video_bit_rate / 1000, video_codec_name, video_codec_name_extra, audio_bit_rate / 1000, audio_codec_name, audio_codec_name_extra); if (stream->feed) { url_fprintf(pb, "<TD>%s", stream->feed->filename); } else { url_fprintf(pb, "<TD>%s", stream->feed_filename); } url_fprintf(pb, "\n"); } break; default: url_fprintf(pb, "<TD align=center> - <TD align=right> - <TD align=right> - <td><td align=right> - <TD>\n"); break; } } stream = stream->next; } url_fprintf(pb, "</TABLE>\n"); stream = first_stream; while (stream != NULL) { if (stream->feed == stream) { url_fprintf(pb, "<h2>Feed %s</h2>", stream->filename); if (stream->pid) { url_fprintf(pb, "Running as pid %d.\n", stream->pid); #if defined(linux) && !defined(CONFIG_NOCUTILS) { FILE *pid_stat; char ps_cmd[64]; /* This is somewhat linux specific I guess */ snprintf(ps_cmd, sizeof(ps_cmd), "ps -o \"%%cpu,cputime\" --no-headers %d", stream->pid); pid_stat = popen(ps_cmd, "r"); if (pid_stat) { char cpuperc[10]; char cpuused[64]; if (fscanf(pid_stat, "%10s %64s", cpuperc, cpuused) == 2) { url_fprintf(pb, "Currently using %s%% of the cpu. Total time used %s.\n", cpuperc, cpuused); } fclose(pid_stat); } } #endif url_fprintf(pb, "<p>"); } url_fprintf(pb, "<table cellspacing=0 cellpadding=4><tr><th>Stream<th>type<th>kbits/s<th align=left>codec<th align=left>Parameters\n"); for (i = 0; i < stream->nb_streams; i++) { AVStream *st = stream->streams[i]; AVCodec *codec = avcodec_find_encoder(st->codec.codec_id); const char *type = "unknown"; char parameters[64]; parameters[0] = 0; switch(st->codec.codec_type) { case CODEC_TYPE_AUDIO: type = "audio"; break; case CODEC_TYPE_VIDEO: type = "video"; snprintf(parameters, sizeof(parameters), "%dx%d, q=%d-%d, fps=%d", st->codec.width, st->codec.height, st->codec.qmin, st->codec.qmax, st->codec.frame_rate / st->codec.frame_rate_base); break; default: av_abort(); } url_fprintf(pb, "<tr><td align=right>%d<td>%s<td align=right>%d<td>%s<td>%s\n", i, type, st->codec.bit_rate/1000, codec ? codec->name : "", parameters); } url_fprintf(pb, "</table>\n"); } stream = stream->next; } #if 0 { float avg; AVCodecContext *enc; char buf[1024]; /* feed status */ stream = first_feed; while (stream != NULL) { url_fprintf(pb, "<H1>Feed '%s'</H1>\n", stream->filename); url_fprintf(pb, "<TABLE>\n"); url_fprintf(pb, "<TR><TD>Parameters<TD>Frame count<TD>Size<TD>Avg bitrate (kbits/s)\n"); for(i=0;i<stream->nb_streams;i++) { AVStream *st = stream->streams[i]; FeedData *fdata = st->priv_data; enc = &st->codec; avcodec_string(buf, sizeof(buf), enc); avg = fdata->avg_frame_size * (float)enc->rate * 8.0; if (enc->codec->type == CODEC_TYPE_AUDIO && enc->frame_size > 0) avg /= enc->frame_size; url_fprintf(pb, "<TR><TD>%s <TD> %d <TD> %Ld <TD> %0.1f\n", buf, enc->frame_number, fdata->data_count, avg / 1000.0); } url_fprintf(pb, "</TABLE>\n"); stream = stream->next_feed; } } #endif /* connection status */ url_fprintf(pb, "<H2>Connection Status</H2>\n"); url_fprintf(pb, "Number of connections: %d / %d<BR>\n", nb_connections, nb_max_connections); url_fprintf(pb, "Bandwidth in use: %dk / %dk<BR>\n", current_bandwidth, max_bandwidth); url_fprintf(pb, "<TABLE>\n"); url_fprintf(pb, "<TR><th>#<th>File<th>IP<th>Proto<th>State<th>Target bits/sec<th>Actual bits/sec<th>Bytes transferred\n"); c1 = first_http_ctx; i = 0; while (c1 != NULL) { int bitrate; int j; bitrate = 0; if (c1->stream) { for (j = 0; j < c1->stream->nb_streams; j++) { if (!c1->stream->feed) { bitrate += c1->stream->streams[j]->codec.bit_rate; } else { if (c1->feed_streams[j] >= 0) { bitrate += c1->stream->feed->streams[c1->feed_streams[j]]->codec.bit_rate; } } } } i++; p = inet_ntoa(c1->from_addr.sin_addr); url_fprintf(pb, "<TR><TD><B>%d</B><TD>%s%s<TD>%s<TD>%s<TD>%s<td align=right>", i, c1->stream ? c1->stream->filename : "", c1->state == HTTPSTATE_RECEIVE_DATA ? "(input)" : "", p, c1->protocol, http_state[c1->state]); fmt_bytecount(pb, bitrate); url_fprintf(pb, "<td align=right>"); fmt_bytecount(pb, compute_datarate(&c1->datarate, c1->data_count) * 8); url_fprintf(pb, "<td align=right>"); fmt_bytecount(pb, c1->data_count); url_fprintf(pb, "\n"); c1 = c1->next; } url_fprintf(pb, "</TABLE>\n"); /* date */ ti = time(NULL); p = ctime(&ti); url_fprintf(pb, "<HR size=1 noshade>Generated at %s", p); url_fprintf(pb, "</BODY>\n</HTML>\n"); len = url_close_dyn_buf(pb, &c->pb_buffer); c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; } /* check if the parser needs to be opened for stream i */ static void open_parser(AVFormatContext *s, int i) { AVStream *st = s->streams[i]; AVCodec *codec; if (!st->codec.codec) { codec = avcodec_find_decoder(st->codec.codec_id); if (codec && (codec->capabilities & CODEC_CAP_PARSE_ONLY)) { st->codec.parse_only = 1; if (avcodec_open(&st->codec, codec) < 0) { st->codec.parse_only = 0; } } } } static int open_input_stream(HTTPContext *c, const char *info) { char buf[128]; char input_filename[1024]; AVFormatContext *s; int buf_size, i; int64_t stream_pos; /* find file name */ if (c->stream->feed) { strcpy(input_filename, c->stream->feed->feed_filename); buf_size = FFM_PACKET_SIZE; /* compute position (absolute time) */ if (find_info_tag(buf, sizeof(buf), "date", info)) { stream_pos = parse_date(buf, 0); } else if (find_info_tag(buf, sizeof(buf), "buffer", info)) { int prebuffer = strtol(buf, 0, 10); stream_pos = av_gettime() - prebuffer * (int64_t)1000000; } else { stream_pos = av_gettime() - c->stream->prebuffer * (int64_t)1000; } } else { strcpy(input_filename, c->stream->feed_filename); buf_size = 0; /* compute position (relative time) */ if (find_info_tag(buf, sizeof(buf), "date", info)) { stream_pos = parse_date(buf, 1); } else { stream_pos = 0; } } if (input_filename[0] == '\0') return -1; #if 0 { time_t when = stream_pos / 1000000; http_log("Stream pos = %lld, time=%s", stream_pos, ctime(&when)); } #endif /* open stream */ if (av_open_input_file(&s, input_filename, c->stream->ifmt, buf_size, c->stream->ap_in) < 0) { http_log("%s not found", input_filename); return -1; } c->fmt_in = s; /* open each parser */ for(i=0;i<s->nb_streams;i++) open_parser(s, i); /* choose stream as clock source (we favorize video stream if present) for packet sending */ c->pts_stream_index = 0; for(i=0;i<c->stream->nb_streams;i++) { if (c->pts_stream_index == 0 && c->stream->streams[i]->codec.codec_type == CODEC_TYPE_VIDEO) { c->pts_stream_index = i; } } #if 0 if (c->fmt_in->iformat->read_seek) { c->fmt_in->iformat->read_seek(c->fmt_in, stream_pos); } #endif /* set the start time (needed for maxtime and RTP packet timing) */ c->start_time = cur_time; c->first_pts = AV_NOPTS_VALUE; return 0; } /* return the server clock (in us) */ static int64_t get_server_clock(HTTPContext *c) { /* compute current pts value from system time */ return (int64_t)(cur_time - c->start_time) * 1000LL; } /* return the estimated time at which the current packet must be sent (in us) */ static int64_t get_packet_send_clock(HTTPContext *c) { int bytes_left, bytes_sent, frame_bytes; frame_bytes = c->cur_frame_bytes; if (frame_bytes <= 0) { return c->cur_pts; } else { bytes_left = c->buffer_end - c->buffer_ptr; bytes_sent = frame_bytes - bytes_left; return c->cur_pts + (c->cur_frame_duration * bytes_sent) / frame_bytes; } } static int http_prepare_data(HTTPContext *c) { int i, len, ret; AVFormatContext *ctx; av_freep(&c->pb_buffer); switch(c->state) { case HTTPSTATE_SEND_DATA_HEADER: memset(&c->fmt_ctx, 0, sizeof(c->fmt_ctx)); pstrcpy(c->fmt_ctx.author, sizeof(c->fmt_ctx.author), c->stream->author); pstrcpy(c->fmt_ctx.comment, sizeof(c->fmt_ctx.comment), c->stream->comment); pstrcpy(c->fmt_ctx.copyright, sizeof(c->fmt_ctx.copyright), c->stream->copyright); pstrcpy(c->fmt_ctx.title, sizeof(c->fmt_ctx.title), c->stream->title); /* open output stream by using specified codecs */ c->fmt_ctx.oformat = c->stream->fmt; c->fmt_ctx.nb_streams = c->stream->nb_streams; for(i=0;i<c->fmt_ctx.nb_streams;i++) { AVStream *st; AVStream *src; st = av_mallocz(sizeof(AVStream)); c->fmt_ctx.streams[i] = st; /* if file or feed, then just take streams from FFStream struct */ if (!c->stream->feed || c->stream->feed == c->stream) src = c->stream->streams[i]; else src = c->stream->feed->streams[c->stream->feed_streams[i]]; *st = *src; st->priv_data = 0; st->codec.frame_number = 0; /* XXX: should be done in AVStream, not in codec */ /* I'm pretty sure that this is not correct... * However, without it, we crash */ st->codec.coded_frame = &dummy_frame; } c->got_key_frame = 0; /* prepare header and save header data in a stream */ if (url_open_dyn_buf(&c->fmt_ctx.pb) < 0) { /* XXX: potential leak */ return -1; } c->fmt_ctx.pb.is_streamed = 1; av_set_parameters(&c->fmt_ctx, NULL); av_write_header(&c->fmt_ctx); len = url_close_dyn_buf(&c->fmt_ctx.pb, &c->pb_buffer); c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; c->state = HTTPSTATE_SEND_DATA; c->last_packet_sent = 0; break; case HTTPSTATE_SEND_DATA: /* find a new packet */ { AVPacket pkt; /* read a packet from the input stream */ if (c->stream->feed) { ffm_set_write_index(c->fmt_in, c->stream->feed->feed_write_index, c->stream->feed->feed_size); } if (c->stream->max_time && c->stream->max_time + c->start_time - cur_time < 0) { /* We have timed out */ c->state = HTTPSTATE_SEND_DATA_TRAILER; } else { redo: if (av_read_frame(c->fmt_in, &pkt) < 0) { if (c->stream->feed && c->stream->feed->feed_opened) { /* if coming from feed, it means we reached the end of the ffm file, so must wait for more data */ c->state = HTTPSTATE_WAIT_FEED; return 1; /* state changed */ } else { if (c->stream->loop) { av_close_input_file(c->fmt_in); c->fmt_in = NULL; if (open_input_stream(c, "") < 0) goto no_loop; goto redo; } else { no_loop: /* must send trailer now because eof or error */ c->state = HTTPSTATE_SEND_DATA_TRAILER; } } } else { /* update first pts if needed */ if (c->first_pts == AV_NOPTS_VALUE) { c->first_pts = pkt.dts; c->start_time = cur_time; } /* send it to the appropriate stream */ if (c->stream->feed) { /* if coming from a feed, select the right stream */ if (c->switch_pending) { c->switch_pending = 0; for(i=0;i<c->stream->nb_streams;i++) { if (c->switch_feed_streams[i] == pkt.stream_index) { if (pkt.flags & PKT_FLAG_KEY) { do_switch_stream(c, i); } } if (c->switch_feed_streams[i] >= 0) { c->switch_pending = 1; } } } for(i=0;i<c->stream->nb_streams;i++) { if (c->feed_streams[i] == pkt.stream_index) { pkt.stream_index = i; if (pkt.flags & PKT_FLAG_KEY) { c->got_key_frame |= 1 << i; } /* See if we have all the key frames, then * we start to send. This logic is not quite * right, but it works for the case of a * single video stream with one or more * audio streams (for which every frame is * typically a key frame). */ if (!c->stream->send_on_key || ((c->got_key_frame + 1) >> c->stream->nb_streams)) { goto send_it; } } } } else { AVCodecContext *codec; send_it: /* specific handling for RTP: we use several output stream (one for each RTP connection). XXX: need more abstract handling */ if (c->is_packetized) { AVStream *st; /* compute send time and duration */ st = c->fmt_in->streams[pkt.stream_index]; c->cur_pts = pkt.dts; if (st->start_time != AV_NOPTS_VALUE) c->cur_pts -= st->start_time; c->cur_frame_duration = pkt.duration; #if 0 printf("index=%d pts=%0.3f duration=%0.6f\n", pkt.stream_index, (double)c->cur_pts / AV_TIME_BASE, (double)c->cur_frame_duration / AV_TIME_BASE); #endif /* find RTP context */ c->packet_stream_index = pkt.stream_index; ctx = c->rtp_ctx[c->packet_stream_index]; if(!ctx) { av_free_packet(&pkt); break; } codec = &ctx->streams[0]->codec; /* only one stream per RTP connection */ pkt.stream_index = 0; } else { ctx = &c->fmt_ctx; /* Fudge here */ codec = &ctx->streams[pkt.stream_index]->codec; } codec->coded_frame->key_frame = ((pkt.flags & PKT_FLAG_KEY) != 0); if (c->is_packetized) { int max_packet_size; if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP) max_packet_size = RTSP_TCP_MAX_PACKET_SIZE; else max_packet_size = url_get_max_packet_size(c->rtp_handles[c->packet_stream_index]); ret = url_open_dyn_packet_buf(&ctx->pb, max_packet_size); } else { ret = url_open_dyn_buf(&ctx->pb); } if (ret < 0) { /* XXX: potential leak */ return -1; } if (av_write_frame(ctx, &pkt)) { c->state = HTTPSTATE_SEND_DATA_TRAILER; } len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer); c->cur_frame_bytes = len; c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; codec->frame_number++; if (len == 0) goto redo; } av_free_packet(&pkt); } } } break; default: case HTTPSTATE_SEND_DATA_TRAILER: /* last packet test ? */ if (c->last_packet_sent || c->is_packetized) return -1; ctx = &c->fmt_ctx; /* prepare header */ if (url_open_dyn_buf(&ctx->pb) < 0) { /* XXX: potential leak */ return -1; } av_write_trailer(ctx); len = url_close_dyn_buf(&ctx->pb, &c->pb_buffer); c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; c->last_packet_sent = 1; break; } return 0; } /* in bit/s */ #define SHORT_TERM_BANDWIDTH 8000000 /* should convert the format at the same time */ /* send data starting at c->buffer_ptr to the output connection (either UDP or TCP connection) */ static int http_send_data(HTTPContext *c) { int len, ret; for(;;) { if (c->buffer_ptr >= c->buffer_end) { ret = http_prepare_data(c); if (ret < 0) return -1; else if (ret != 0) { /* state change requested */ break; } } else { if (c->is_packetized) { /* RTP data output */ len = c->buffer_end - c->buffer_ptr; if (len < 4) { /* fail safe - should never happen */ fail1: c->buffer_ptr = c->buffer_end; return 0; } len = (c->buffer_ptr[0] << 24) | (c->buffer_ptr[1] << 16) | (c->buffer_ptr[2] << 8) | (c->buffer_ptr[3]); if (len > (c->buffer_end - c->buffer_ptr)) goto fail1; if ((get_packet_send_clock(c) - get_server_clock(c)) > 0) { /* nothing to send yet: we can wait */ return 0; } c->data_count += len; update_datarate(&c->datarate, c->data_count); if (c->stream) c->stream->bytes_served += len; if (c->rtp_protocol == RTSP_PROTOCOL_RTP_TCP) { /* RTP packets are sent inside the RTSP TCP connection */ ByteIOContext pb1, *pb = &pb1; int interleaved_index, size; uint8_t header[4]; HTTPContext *rtsp_c; rtsp_c = c->rtsp_c; /* if no RTSP connection left, error */ if (!rtsp_c) return -1; /* if already sending something, then wait. */ if (rtsp_c->state != RTSPSTATE_WAIT_REQUEST) { break; } if (url_open_dyn_buf(pb) < 0) goto fail1; interleaved_index = c->packet_stream_index * 2; /* RTCP packets are sent at odd indexes */ if (c->buffer_ptr[1] == 200) interleaved_index++; /* write RTSP TCP header */ header[0] = '$'; header[1] = interleaved_index; header[2] = len >> 8; header[3] = len; put_buffer(pb, header, 4); /* write RTP packet data */ c->buffer_ptr += 4; put_buffer(pb, c->buffer_ptr, len); size = url_close_dyn_buf(pb, &c->packet_buffer); /* prepare asynchronous TCP sending */ rtsp_c->packet_buffer_ptr = c->packet_buffer; rtsp_c->packet_buffer_end = c->packet_buffer + size; c->buffer_ptr += len; /* send everything we can NOW */ len = write(rtsp_c->fd, rtsp_c->packet_buffer_ptr, rtsp_c->packet_buffer_end - rtsp_c->packet_buffer_ptr); if (len > 0) { rtsp_c->packet_buffer_ptr += len; } if (rtsp_c->packet_buffer_ptr < rtsp_c->packet_buffer_end) { /* if we could not send all the data, we will send it later, so a new state is needed to "lock" the RTSP TCP connection */ rtsp_c->state = RTSPSTATE_SEND_PACKET; break; } else { /* all data has been sent */ av_freep(&c->packet_buffer); } } else { /* send RTP packet directly in UDP */ c->buffer_ptr += 4; url_write(c->rtp_handles[c->packet_stream_index], c->buffer_ptr, len); c->buffer_ptr += len; /* here we continue as we can send several packets per 10 ms slot */ } } else { /* TCP data output */ len = write(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr); if (len < 0) { if (errno != EAGAIN && errno != EINTR) { /* error : close connection */ return -1; } else { return 0; } } else { c->buffer_ptr += len; } c->data_count += len; update_datarate(&c->datarate, c->data_count); if (c->stream) c->stream->bytes_served += len; break; } } } /* for(;;) */ return 0; } static int http_start_receive_data(HTTPContext *c) { int fd; if (c->stream->feed_opened) return -1; /* Don't permit writing to this one */ if (c->stream->readonly) return -1; /* open feed */ fd = open(c->stream->feed_filename, O_RDWR); if (fd < 0) return -1; c->feed_fd = fd; c->stream->feed_write_index = ffm_read_write_index(fd); c->stream->feed_size = lseek(fd, 0, SEEK_END); lseek(fd, 0, SEEK_SET); /* init buffer input */ c->buffer_ptr = c->buffer; c->buffer_end = c->buffer + FFM_PACKET_SIZE; c->stream->feed_opened = 1; return 0; } static int http_receive_data(HTTPContext *c) { HTTPContext *c1; if (c->buffer_end > c->buffer_ptr) { int len; len = read(c->fd, c->buffer_ptr, c->buffer_end - c->buffer_ptr); if (len < 0) { if (errno != EAGAIN && errno != EINTR) { /* error : close connection */ goto fail; } } else if (len == 0) { /* end of connection : close it */ goto fail; } else { c->buffer_ptr += len; c->data_count += len; update_datarate(&c->datarate, c->data_count); } } if (c->buffer_ptr - c->buffer >= 2 && c->data_count > FFM_PACKET_SIZE) { if (c->buffer[0] != 'f' || c->buffer[1] != 'm') { http_log("Feed stream has become desynchronized -- disconnecting\n"); goto fail; } } if (c->buffer_ptr >= c->buffer_end) { FFStream *feed = c->stream; /* a packet has been received : write it in the store, except if header */ if (c->data_count > FFM_PACKET_SIZE) { // printf("writing pos=0x%Lx size=0x%Lx\n", feed->feed_write_index, feed->feed_size); /* XXX: use llseek or url_seek */ lseek(c->feed_fd, feed->feed_write_index, SEEK_SET); write(c->feed_fd, c->buffer, FFM_PACKET_SIZE); feed->feed_write_index += FFM_PACKET_SIZE; /* update file size */ if (feed->feed_write_index > c->stream->feed_size) feed->feed_size = feed->feed_write_index; /* handle wrap around if max file size reached */ if (feed->feed_write_index >= c->stream->feed_max_size) feed->feed_write_index = FFM_PACKET_SIZE; /* write index */ ffm_write_write_index(c->feed_fd, feed->feed_write_index); /* wake up any waiting connections */ for(c1 = first_http_ctx; c1 != NULL; c1 = c1->next) { if (c1->state == HTTPSTATE_WAIT_FEED && c1->stream->feed == c->stream->feed) { c1->state = HTTPSTATE_SEND_DATA; } } } else { /* We have a header in our hands that contains useful data */ AVFormatContext s; AVInputFormat *fmt_in; ByteIOContext *pb = &s.pb; int i; memset(&s, 0, sizeof(s)); url_open_buf(pb, c->buffer, c->buffer_end - c->buffer, URL_RDONLY); pb->buf_end = c->buffer_end; /* ?? */ pb->is_streamed = 1; /* use feed output format name to find corresponding input format */ fmt_in = av_find_input_format(feed->fmt->name); if (!fmt_in) goto fail; if (fmt_in->priv_data_size > 0) { s.priv_data = av_mallocz(fmt_in->priv_data_size); if (!s.priv_data) goto fail; } else s.priv_data = NULL; if (fmt_in->read_header(&s, 0) < 0) { av_freep(&s.priv_data); goto fail; } /* Now we have the actual streams */ if (s.nb_streams != feed->nb_streams) { av_freep(&s.priv_data); goto fail; } for (i = 0; i < s.nb_streams; i++) { memcpy(&feed->streams[i]->codec, &s.streams[i]->codec, sizeof(AVCodecContext)); } av_freep(&s.priv_data); } c->buffer_ptr = c->buffer; } return 0; fail: c->stream->feed_opened = 0; close(c->feed_fd); return -1; } /********************************************************************/ /* RTSP handling */ static void rtsp_reply_header(HTTPContext *c, enum RTSPStatusCode error_number) { const char *str; time_t ti; char *p; char buf2[32]; switch(error_number) { #define DEF(n, c, s) case c: str = s; break; #include "rtspcodes.h" #undef DEF default: str = "Unknown Error"; break; } url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", error_number, str); url_fprintf(c->pb, "CSeq: %d\r\n", c->seq); /* output GMT time */ ti = time(NULL); p = ctime(&ti); strcpy(buf2, p); p = buf2 + strlen(p) - 1; if (*p == '\n') *p = '\0'; url_fprintf(c->pb, "Date: %s GMT\r\n", buf2); } static void rtsp_reply_error(HTTPContext *c, enum RTSPStatusCode error_number) { rtsp_reply_header(c, error_number); url_fprintf(c->pb, "\r\n"); } static int rtsp_parse_request(HTTPContext *c) { const char *p, *p1, *p2; char cmd[32]; char url[1024]; char protocol[32]; char line[1024]; ByteIOContext pb1; int len; RTSPHeader header1, *header = &header1; c->buffer_ptr[0] = '\0'; p = c->buffer; get_word(cmd, sizeof(cmd), &p); get_word(url, sizeof(url), &p); get_word(protocol, sizeof(protocol), &p); pstrcpy(c->method, sizeof(c->method), cmd); pstrcpy(c->url, sizeof(c->url), url); pstrcpy(c->protocol, sizeof(c->protocol), protocol); c->pb = &pb1; if (url_open_dyn_buf(c->pb) < 0) { /* XXX: cannot do more */ c->pb = NULL; /* safety */ return -1; } /* check version name */ if (strcmp(protocol, "RTSP/1.0") != 0) { rtsp_reply_error(c, RTSP_STATUS_VERSION); goto the_end; } /* parse each header line */ memset(header, 0, sizeof(RTSPHeader)); /* skip to next line */ while (*p != '\n' && *p != '\0') p++; if (*p == '\n') p++; while (*p != '\0') { p1 = strchr(p, '\n'); if (!p1) break; p2 = p1; if (p2 > p && p2[-1] == '\r') p2--; /* skip empty line */ if (p2 == p) break; len = p2 - p; if (len > sizeof(line) - 1) len = sizeof(line) - 1; memcpy(line, p, len); line[len] = '\0'; rtsp_parse_line(header, line); p = p1 + 1; } /* handle sequence number */ c->seq = header->seq; if (!strcmp(cmd, "DESCRIBE")) { rtsp_cmd_describe(c, url); } else if (!strcmp(cmd, "OPTIONS")) { rtsp_cmd_options(c, url); } else if (!strcmp(cmd, "SETUP")) { rtsp_cmd_setup(c, url, header); } else if (!strcmp(cmd, "PLAY")) { rtsp_cmd_play(c, url, header); } else if (!strcmp(cmd, "PAUSE")) { rtsp_cmd_pause(c, url, header); } else if (!strcmp(cmd, "TEARDOWN")) { rtsp_cmd_teardown(c, url, header); } else { rtsp_reply_error(c, RTSP_STATUS_METHOD); } the_end: len = url_close_dyn_buf(c->pb, &c->pb_buffer); c->pb = NULL; /* safety */ if (len < 0) { /* XXX: cannot do more */ return -1; } c->buffer_ptr = c->pb_buffer; c->buffer_end = c->pb_buffer + len; c->state = RTSPSTATE_SEND_REPLY; return 0; } /* XXX: move that to rtsp.c, but would need to replace FFStream by AVFormatContext */ static int prepare_sdp_description(FFStream *stream, uint8_t **pbuffer, struct in_addr my_ip) { ByteIOContext pb1, *pb = &pb1; int i, payload_type, port, private_payload_type, j; const char *ipstr, *title, *mediatype; AVStream *st; if (url_open_dyn_buf(pb) < 0) return -1; /* general media info */ url_fprintf(pb, "v=0\n"); ipstr = inet_ntoa(my_ip); url_fprintf(pb, "o=- 0 0 IN IP4 %s\n", ipstr); title = stream->title; if (title[0] == '\0') title = "No Title"; url_fprintf(pb, "s=%s\n", title); if (stream->comment[0] != '\0') url_fprintf(pb, "i=%s\n", stream->comment); if (stream->is_multicast) { url_fprintf(pb, "c=IN IP4 %s\n", inet_ntoa(stream->multicast_ip)); } /* for each stream, we output the necessary info */ private_payload_type = RTP_PT_PRIVATE; for(i = 0; i < stream->nb_streams; i++) { st = stream->streams[i]; if (st->codec.codec_id == CODEC_ID_MPEG2TS) { mediatype = "video"; } else { switch(st->codec.codec_type) { case CODEC_TYPE_AUDIO: mediatype = "audio"; break; case CODEC_TYPE_VIDEO: mediatype = "video"; break; default: mediatype = "application"; break; } } /* NOTE: the port indication is not correct in case of unicast. It is not an issue because RTSP gives it */ payload_type = rtp_get_payload_type(&st->codec); if (payload_type < 0) payload_type = private_payload_type++; if (stream->is_multicast) { port = stream->multicast_port + 2 * i; } else { port = 0; } url_fprintf(pb, "m=%s %d RTP/AVP %d\n", mediatype, port, payload_type); if (payload_type >= RTP_PT_PRIVATE) { /* for private payload type, we need to give more info */ switch(st->codec.codec_id) { case CODEC_ID_MPEG4: { uint8_t *data; url_fprintf(pb, "a=rtpmap:%d MP4V-ES/%d\n", payload_type, 90000); /* we must also add the mpeg4 header */ data = st->codec.extradata; if (data) { url_fprintf(pb, "a=fmtp:%d config=", payload_type); for(j=0;j<st->codec.extradata_size;j++) { url_fprintf(pb, "%02x", data[j]); } url_fprintf(pb, "\n"); } } break; default: /* XXX: add other codecs ? */ goto fail; } } url_fprintf(pb, "a=control:streamid=%d\n", i); } return url_close_dyn_buf(pb, pbuffer); fail: url_close_dyn_buf(pb, pbuffer); av_free(*pbuffer); return -1; } static void rtsp_cmd_options(HTTPContext *c, const char *url) { // rtsp_reply_header(c, RTSP_STATUS_OK); url_fprintf(c->pb, "RTSP/1.0 %d %s\r\n", RTSP_STATUS_OK, "OK"); url_fprintf(c->pb, "CSeq: %d\r\n", c->seq); url_fprintf(c->pb, "Public: %s\r\n", "OPTIONS, DESCRIBE, SETUP, TEARDOWN, PLAY, PAUSE"); url_fprintf(c->pb, "\r\n"); } static void rtsp_cmd_describe(HTTPContext *c, const char *url) { FFStream *stream; char path1[1024]; const char *path; uint8_t *content; int content_length, len; struct sockaddr_in my_addr; /* find which url is asked */ url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; for(stream = first_stream; stream != NULL; stream = stream->next) { if (!stream->is_feed && stream->fmt == &rtp_mux && !strcmp(path, stream->filename)) { goto found; } } /* no stream found */ rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */ return; found: /* prepare the media description in sdp format */ /* get the host IP */ len = sizeof(my_addr); getsockname(c->fd, (struct sockaddr *)&my_addr, &len); content_length = prepare_sdp_description(stream, &content, my_addr.sin_addr); if (content_length < 0) { rtsp_reply_error(c, RTSP_STATUS_INTERNAL); return; } rtsp_reply_header(c, RTSP_STATUS_OK); url_fprintf(c->pb, "Content-Type: application/sdp\r\n"); url_fprintf(c->pb, "Content-Length: %d\r\n", content_length); url_fprintf(c->pb, "\r\n"); put_buffer(c->pb, content, content_length); } static HTTPContext *find_rtp_session(const char *session_id) { HTTPContext *c; if (session_id[0] == '\0') return NULL; for(c = first_http_ctx; c != NULL; c = c->next) { if (!strcmp(c->session_id, session_id)) return c; } return NULL; } static RTSPTransportField *find_transport(RTSPHeader *h, enum RTSPProtocol protocol) { RTSPTransportField *th; int i; for(i=0;i<h->nb_transports;i++) { th = &h->transports[i]; if (th->protocol == protocol) return th; } return NULL; } static void rtsp_cmd_setup(HTTPContext *c, const char *url, RTSPHeader *h) { FFStream *stream; int stream_index, port; char buf[1024]; char path1[1024]; const char *path; HTTPContext *rtp_c; RTSPTransportField *th; struct sockaddr_in dest_addr; RTSPActionServerSetup setup; /* find which url is asked */ url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; /* now check each stream */ for(stream = first_stream; stream != NULL; stream = stream->next) { if (!stream->is_feed && stream->fmt == &rtp_mux) { /* accept aggregate filenames only if single stream */ if (!strcmp(path, stream->filename)) { if (stream->nb_streams != 1) { rtsp_reply_error(c, RTSP_STATUS_AGGREGATE); return; } stream_index = 0; goto found; } for(stream_index = 0; stream_index < stream->nb_streams; stream_index++) { snprintf(buf, sizeof(buf), "%s/streamid=%d", stream->filename, stream_index); if (!strcmp(path, buf)) goto found; } } } /* no stream found */ rtsp_reply_error(c, RTSP_STATUS_SERVICE); /* XXX: right error ? */ return; found: /* generate session id if needed */ if (h->session_id[0] == '\0') { snprintf(h->session_id, sizeof(h->session_id), "%08x%08x", (int)random(), (int)random()); } /* find rtp session, and create it if none found */ rtp_c = find_rtp_session(h->session_id); if (!rtp_c) { /* always prefer UDP */ th = find_transport(h, RTSP_PROTOCOL_RTP_UDP); if (!th) { th = find_transport(h, RTSP_PROTOCOL_RTP_TCP); if (!th) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } } rtp_c = rtp_new_connection(&c->from_addr, stream, h->session_id, th->protocol); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_BANDWIDTH); return; } /* open input stream */ if (open_input_stream(rtp_c, "") < 0) { rtsp_reply_error(c, RTSP_STATUS_INTERNAL); return; } } /* test if stream is OK (test needed because several SETUP needs to be done for a given file) */ if (rtp_c->stream != stream) { rtsp_reply_error(c, RTSP_STATUS_SERVICE); return; } /* test if stream is already set up */ if (rtp_c->rtp_ctx[stream_index]) { rtsp_reply_error(c, RTSP_STATUS_STATE); return; } /* check transport */ th = find_transport(h, rtp_c->rtp_protocol); if (!th || (th->protocol == RTSP_PROTOCOL_RTP_UDP && th->client_port_min <= 0)) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } /* setup default options */ setup.transport_option[0] = '\0'; dest_addr = rtp_c->from_addr; dest_addr.sin_port = htons(th->client_port_min); /* add transport option if needed */ if (ff_rtsp_callback) { setup.ipaddr = ntohl(dest_addr.sin_addr.s_addr); if (ff_rtsp_callback(RTSP_ACTION_SERVER_SETUP, rtp_c->session_id, (char *)&setup, sizeof(setup), stream->rtsp_option) < 0) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } dest_addr.sin_addr.s_addr = htonl(setup.ipaddr); } /* setup stream */ if (rtp_new_av_stream(rtp_c, stream_index, &dest_addr, c) < 0) { rtsp_reply_error(c, RTSP_STATUS_TRANSPORT); return; } /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id); switch(rtp_c->rtp_protocol) { case RTSP_PROTOCOL_RTP_UDP: port = rtp_get_local_port(rtp_c->rtp_handles[stream_index]); url_fprintf(c->pb, "Transport: RTP/AVP/UDP;unicast;" "client_port=%d-%d;server_port=%d-%d", th->client_port_min, th->client_port_min + 1, port, port + 1); break; case RTSP_PROTOCOL_RTP_TCP: url_fprintf(c->pb, "Transport: RTP/AVP/TCP;interleaved=%d-%d", stream_index * 2, stream_index * 2 + 1); break; default: break; } if (setup.transport_option[0] != '\0') { url_fprintf(c->pb, ";%s", setup.transport_option); } url_fprintf(c->pb, "\r\n"); url_fprintf(c->pb, "\r\n"); } /* find an rtp connection by using the session ID. Check consistency with filename */ static HTTPContext *find_rtp_session_with_url(const char *url, const char *session_id) { HTTPContext *rtp_c; char path1[1024]; const char *path; char buf[1024]; int s; rtp_c = find_rtp_session(session_id); if (!rtp_c) return NULL; /* find which url is asked */ url_split(NULL, 0, NULL, 0, NULL, 0, NULL, path1, sizeof(path1), url); path = path1; if (*path == '/') path++; if(!strcmp(path, rtp_c->stream->filename)) return rtp_c; for(s=0; s<rtp_c->stream->nb_streams; ++s) { snprintf(buf, sizeof(buf), "%s/streamid=%d", rtp_c->stream->filename, s); if(!strncmp(path, buf, sizeof(buf))) { // XXX: Should we reply with RTSP_STATUS_ONLY_AGGREGATE if nb_streams>1? return rtp_c; } } return NULL; } static void rtsp_cmd_play(HTTPContext *c, const char *url, RTSPHeader *h) { HTTPContext *rtp_c; rtp_c = find_rtp_session_with_url(url, h->session_id); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_SESSION); return; } if (rtp_c->state != HTTPSTATE_SEND_DATA && rtp_c->state != HTTPSTATE_WAIT_FEED && rtp_c->state != HTTPSTATE_READY) { rtsp_reply_error(c, RTSP_STATUS_STATE); return; } #if 0 /* XXX: seek in stream */ if (h->range_start != AV_NOPTS_VALUE) { printf("range_start=%0.3f\n", (double)h->range_start / AV_TIME_BASE); av_seek_frame(rtp_c->fmt_in, -1, h->range_start); } #endif rtp_c->state = HTTPSTATE_SEND_DATA; /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id); url_fprintf(c->pb, "\r\n"); } static void rtsp_cmd_pause(HTTPContext *c, const char *url, RTSPHeader *h) { HTTPContext *rtp_c; rtp_c = find_rtp_session_with_url(url, h->session_id); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_SESSION); return; } if (rtp_c->state != HTTPSTATE_SEND_DATA && rtp_c->state != HTTPSTATE_WAIT_FEED) { rtsp_reply_error(c, RTSP_STATUS_STATE); return; } rtp_c->state = HTTPSTATE_READY; rtp_c->first_pts = AV_NOPTS_VALUE; /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id); url_fprintf(c->pb, "\r\n"); } static void rtsp_cmd_teardown(HTTPContext *c, const char *url, RTSPHeader *h) { HTTPContext *rtp_c; rtp_c = find_rtp_session_with_url(url, h->session_id); if (!rtp_c) { rtsp_reply_error(c, RTSP_STATUS_SESSION); return; } /* abort the session */ close_connection(rtp_c); if (ff_rtsp_callback) { ff_rtsp_callback(RTSP_ACTION_SERVER_TEARDOWN, rtp_c->session_id, NULL, 0, rtp_c->stream->rtsp_option); } /* now everything is OK, so we can send the connection parameters */ rtsp_reply_header(c, RTSP_STATUS_OK); /* session ID */ url_fprintf(c->pb, "Session: %s\r\n", rtp_c->session_id); url_fprintf(c->pb, "\r\n"); } /********************************************************************/ /* RTP handling */ static HTTPContext *rtp_new_connection(struct sockaddr_in *from_addr, FFStream *stream, const char *session_id, enum RTSPProtocol rtp_protocol) { HTTPContext *c = NULL; const char *proto_str; /* XXX: should output a warning page when coming close to the connection limit */ if (nb_connections >= nb_max_connections) goto fail; /* add a new connection */ c = av_mallocz(sizeof(HTTPContext)); if (!c) goto fail; c->fd = -1; c->poll_entry = NULL; c->from_addr = *from_addr; c->buffer_size = IOBUFFER_INIT_SIZE; c->buffer = av_malloc(c->buffer_size); if (!c->buffer) goto fail; nb_connections++; c->stream = stream; pstrcpy(c->session_id, sizeof(c->session_id), session_id); c->state = HTTPSTATE_READY; c->is_packetized = 1; c->rtp_protocol = rtp_protocol; /* protocol is shown in statistics */ switch(c->rtp_protocol) { case RTSP_PROTOCOL_RTP_UDP_MULTICAST: proto_str = "MCAST"; break; case RTSP_PROTOCOL_RTP_UDP: proto_str = "UDP"; break; case RTSP_PROTOCOL_RTP_TCP: proto_str = "TCP"; break; default: proto_str = "???"; break; } pstrcpy(c->protocol, sizeof(c->protocol), "RTP/"); pstrcat(c->protocol, sizeof(c->protocol), proto_str); current_bandwidth += stream->bandwidth; c->next = first_http_ctx; first_http_ctx = c; return c; fail: if (c) { av_free(c->buffer); av_free(c); } return NULL; } /* add a new RTP stream in an RTP connection (used in RTSP SETUP command). If RTP/TCP protocol is used, TCP connection 'rtsp_c' is used. */ static int rtp_new_av_stream(HTTPContext *c, int stream_index, struct sockaddr_in *dest_addr, HTTPContext *rtsp_c) { AVFormatContext *ctx; AVStream *st; char *ipaddr; URLContext *h; uint8_t *dummy_buf; char buf2[32]; int max_packet_size; /* now we can open the relevant output stream */ ctx = av_alloc_format_context(); if (!ctx) return -1; ctx->oformat = &rtp_mux; st = av_mallocz(sizeof(AVStream)); if (!st) goto fail; ctx->nb_streams = 1; ctx->streams[0] = st; if (!c->stream->feed || c->stream->feed == c->stream) { memcpy(st, c->stream->streams[stream_index], sizeof(AVStream)); } else { memcpy(st, c->stream->feed->streams[c->stream->feed_streams[stream_index]], sizeof(AVStream)); } /* build destination RTP address */ ipaddr = inet_ntoa(dest_addr->sin_addr); switch(c->rtp_protocol) { case RTSP_PROTOCOL_RTP_UDP: case RTSP_PROTOCOL_RTP_UDP_MULTICAST: /* RTP/UDP case */ /* XXX: also pass as parameter to function ? */ if (c->stream->is_multicast) { int ttl; ttl = c->stream->multicast_ttl; if (!ttl) ttl = 16; snprintf(ctx->filename, sizeof(ctx->filename), "rtp://%s:%d?multicast=1&ttl=%d", ipaddr, ntohs(dest_addr->sin_port), ttl); } else { snprintf(ctx->filename, sizeof(ctx->filename), "rtp://%s:%d", ipaddr, ntohs(dest_addr->sin_port)); } if (url_open(&h, ctx->filename, URL_WRONLY) < 0) goto fail; c->rtp_handles[stream_index] = h; max_packet_size = url_get_max_packet_size(h); break; case RTSP_PROTOCOL_RTP_TCP: /* RTP/TCP case */ c->rtsp_c = rtsp_c; max_packet_size = RTSP_TCP_MAX_PACKET_SIZE; break; default: goto fail; } http_log("%s:%d - - [%s] \"PLAY %s/streamid=%d %s\"\n", ipaddr, ntohs(dest_addr->sin_port), ctime1(buf2), c->stream->filename, stream_index, c->protocol); /* normally, no packets should be output here, but the packet size may be checked */ if (url_open_dyn_packet_buf(&ctx->pb, max_packet_size) < 0) { /* XXX: close stream */ goto fail; } av_set_parameters(ctx, NULL); if (av_write_header(ctx) < 0) { fail: if (h) url_close(h); av_free(ctx); return -1; } url_close_dyn_buf(&ctx->pb, &dummy_buf); av_free(dummy_buf); c->rtp_ctx[stream_index] = ctx; return 0; } /********************************************************************/ /* ffserver initialization */ static AVStream *add_av_stream1(FFStream *stream, AVCodecContext *codec) { AVStream *fst; fst = av_mallocz(sizeof(AVStream)); if (!fst) return NULL; fst->priv_data = av_mallocz(sizeof(FeedData)); memcpy(&fst->codec, codec, sizeof(AVCodecContext)); fst->codec.coded_frame = &dummy_frame; fst->index = stream->nb_streams; av_set_pts_info(fst, 33, 1, 90000); stream->streams[stream->nb_streams++] = fst; return fst; } /* return the stream number in the feed */ static int add_av_stream(FFStream *feed, AVStream *st) { AVStream *fst; AVCodecContext *av, *av1; int i; av = &st->codec; for(i=0;i<feed->nb_streams;i++) { st = feed->streams[i]; av1 = &st->codec; if (av1->codec_id == av->codec_id && av1->codec_type == av->codec_type && av1->bit_rate == av->bit_rate) { switch(av->codec_type) { case CODEC_TYPE_AUDIO: if (av1->channels == av->channels && av1->sample_rate == av->sample_rate) goto found; break; case CODEC_TYPE_VIDEO: if (av1->width == av->width && av1->height == av->height && av1->frame_rate == av->frame_rate && av1->frame_rate_base == av->frame_rate_base && av1->gop_size == av->gop_size) goto found; break; default: av_abort(); } } } fst = add_av_stream1(feed, av); if (!fst) return -1; return feed->nb_streams - 1; found: return i; } static void remove_stream(FFStream *stream) { FFStream **ps; ps = &first_stream; while (*ps != NULL) { if (*ps == stream) { *ps = (*ps)->next; } else { ps = &(*ps)->next; } } } /* specific mpeg4 handling : we extract the raw parameters */ static void extract_mpeg4_header(AVFormatContext *infile) { int mpeg4_count, i, size; AVPacket pkt; AVStream *st; const uint8_t *p; mpeg4_count = 0; for(i=0;i<infile->nb_streams;i++) { st = infile->streams[i]; if (st->codec.codec_id == CODEC_ID_MPEG4 && st->codec.extradata_size == 0) { mpeg4_count++; } } if (!mpeg4_count) return; printf("MPEG4 without extra data: trying to find header in %s\n", infile->filename); while (mpeg4_count > 0) { if (av_read_packet(infile, &pkt) < 0) break; st = infile->streams[pkt.stream_index]; if (st->codec.codec_id == CODEC_ID_MPEG4 && st->codec.extradata_size == 0) { av_freep(&st->codec.extradata); /* fill extradata with the header */ /* XXX: we make hard suppositions here ! */ p = pkt.data; while (p < pkt.data + pkt.size - 4) { /* stop when vop header is found */ if (p[0] == 0x00 && p[1] == 0x00 && p[2] == 0x01 && p[3] == 0xb6) { size = p - pkt.data; // av_hex_dump(pkt.data, size); st->codec.extradata = av_malloc(size); st->codec.extradata_size = size; memcpy(st->codec.extradata, pkt.data, size); break; } p++; } mpeg4_count--; } av_free_packet(&pkt); } } /* compute the needed AVStream for each file */ static void build_file_streams(void) { FFStream *stream, *stream_next; AVFormatContext *infile; int i; /* gather all streams */ for(stream = first_stream; stream != NULL; stream = stream_next) { stream_next = stream->next; if (stream->stream_type == STREAM_TYPE_LIVE && !stream->feed) { /* the stream comes from a file */ /* try to open the file */ /* open stream */ stream->ap_in = av_mallocz(sizeof(AVFormatParameters)); if (stream->fmt == &rtp_mux) { /* specific case : if transport stream output to RTP, we use a raw transport stream reader */ stream->ap_in->mpeg2ts_raw = 1; stream->ap_in->mpeg2ts_compute_pcr = 1; } if (av_open_input_file(&infile, stream->feed_filename, stream->ifmt, 0, stream->ap_in) < 0) { http_log("%s not found", stream->feed_filename); /* remove stream (no need to spend more time on it) */ fail: remove_stream(stream); } else { /* find all the AVStreams inside and reference them in 'stream' */ if (av_find_stream_info(infile) < 0) { http_log("Could not find codec parameters from '%s'", stream->feed_filename); av_close_input_file(infile); goto fail; } extract_mpeg4_header(infile); for(i=0;i<infile->nb_streams;i++) { add_av_stream1(stream, &infile->streams[i]->codec); } av_close_input_file(infile); } } } } /* compute the needed AVStream for each feed */ static void build_feed_streams(void) { FFStream *stream, *feed; int i; /* gather all streams */ for(stream = first_stream; stream != NULL; stream = stream->next) { feed = stream->feed; if (feed) { if (!stream->is_feed) { /* we handle a stream coming from a feed */ for(i=0;i<stream->nb_streams;i++) { stream->feed_streams[i] = add_av_stream(feed, stream->streams[i]); } } } } /* gather all streams */ for(stream = first_stream; stream != NULL; stream = stream->next) { feed = stream->feed; if (feed) { if (stream->is_feed) { for(i=0;i<stream->nb_streams;i++) { stream->feed_streams[i] = i; } } } } /* create feed files if needed */ for(feed = first_feed; feed != NULL; feed = feed->next_feed) { int fd; if (url_exist(feed->feed_filename)) { /* See if it matches */ AVFormatContext *s; int matches = 0; if (av_open_input_file(&s, feed->feed_filename, NULL, FFM_PACKET_SIZE, NULL) >= 0) { /* Now see if it matches */ if (s->nb_streams == feed->nb_streams) { matches = 1; for(i=0;i<s->nb_streams;i++) { AVStream *sf, *ss; sf = feed->streams[i]; ss = s->streams[i]; if (sf->index != ss->index || sf->id != ss->id) { printf("Index & Id do not match for stream %d (%s)\n", i, feed->feed_filename); matches = 0; } else { AVCodecContext *ccf, *ccs; ccf = &sf->codec; ccs = &ss->codec; #define CHECK_CODEC(x) (ccf->x != ccs->x) if (CHECK_CODEC(codec) || CHECK_CODEC(codec_type)) { printf("Codecs do not match for stream %d\n", i); matches = 0; } else if (CHECK_CODEC(bit_rate) || CHECK_CODEC(flags)) { printf("Codec bitrates do not match for stream %d\n", i); matches = 0; } else if (ccf->codec_type == CODEC_TYPE_VIDEO) { if (CHECK_CODEC(frame_rate) || CHECK_CODEC(frame_rate_base) || CHECK_CODEC(width) || CHECK_CODEC(height)) { printf("Codec width, height and framerate do not match for stream %d\n", i); matches = 0; } } else if (ccf->codec_type == CODEC_TYPE_AUDIO) { if (CHECK_CODEC(sample_rate) || CHECK_CODEC(channels) || CHECK_CODEC(frame_size)) { printf("Codec sample_rate, channels, frame_size do not match for stream %d\n", i); matches = 0; } } else { printf("Unknown codec type\n"); matches = 0; } } if (!matches) { break; } } } else { printf("Deleting feed file '%s' as stream counts differ (%d != %d)\n", feed->feed_filename, s->nb_streams, feed->nb_streams); } av_close_input_file(s); } else { printf("Deleting feed file '%s' as it appears to be corrupt\n", feed->feed_filename); } if (!matches) { if (feed->readonly) { printf("Unable to delete feed file '%s' as it is marked readonly\n", feed->feed_filename); exit(1); } unlink(feed->feed_filename); } } if (!url_exist(feed->feed_filename)) { AVFormatContext s1, *s = &s1; if (feed->readonly) { printf("Unable to create feed file '%s' as it is marked readonly\n", feed->feed_filename); exit(1); } /* only write the header of the ffm file */ if (url_fopen(&s->pb, feed->feed_filename, URL_WRONLY) < 0) { fprintf(stderr, "Could not open output feed file '%s'\n", feed->feed_filename); exit(1); } s->oformat = feed->fmt; s->nb_streams = feed->nb_streams; for(i=0;i<s->nb_streams;i++) { AVStream *st; st = feed->streams[i]; s->streams[i] = st; } av_set_parameters(s, NULL); av_write_header(s); /* XXX: need better api */ av_freep(&s->priv_data); url_fclose(&s->pb); } /* get feed size and write index */ fd = open(feed->feed_filename, O_RDONLY); if (fd < 0) { fprintf(stderr, "Could not open output feed file '%s'\n", feed->feed_filename); exit(1); } feed->feed_write_index = ffm_read_write_index(fd); feed->feed_size = lseek(fd, 0, SEEK_END); /* ensure that we do not wrap before the end of file */ if (feed->feed_max_size < feed->feed_size) feed->feed_max_size = feed->feed_size; close(fd); } } /* compute the bandwidth used by each stream */ static void compute_bandwidth(void) { int bandwidth, i; FFStream *stream; for(stream = first_stream; stream != NULL; stream = stream->next) { bandwidth = 0; for(i=0;i<stream->nb_streams;i++) { AVStream *st = stream->streams[i]; switch(st->codec.codec_type) { case CODEC_TYPE_AUDIO: case CODEC_TYPE_VIDEO: bandwidth += st->codec.bit_rate; break; default: break; } } stream->bandwidth = (bandwidth + 999) / 1000; } } static void get_arg(char *buf, int buf_size, const char **pp) { const char *p; char *q; int quote; p = *pp; while (isspace(*p)) p++; q = buf; quote = 0; if (*p == '\"' || *p == '\'') quote = *p++; for(;;) { if (quote) { if (*p == quote) break; } else { if (isspace(*p)) break; } if (*p == '\0') break; if ((q - buf) < buf_size - 1) *q++ = *p; p++; } *q = '\0'; if (quote && *p == quote) p++; *pp = p; } /* add a codec and set the default parameters */ static void add_codec(FFStream *stream, AVCodecContext *av) { AVStream *st; /* compute default parameters */ switch(av->codec_type) { case CODEC_TYPE_AUDIO: if (av->bit_rate == 0) av->bit_rate = 64000; if (av->sample_rate == 0) av->sample_rate = 22050; if (av->channels == 0) av->channels = 1; break; case CODEC_TYPE_VIDEO: if (av->bit_rate == 0) av->bit_rate = 64000; if (av->frame_rate == 0){ av->frame_rate = 5; av->frame_rate_base = 1; } if (av->width == 0 || av->height == 0) { av->width = 160; av->height = 128; } /* Bitrate tolerance is less for streaming */ if (av->bit_rate_tolerance == 0) av->bit_rate_tolerance = av->bit_rate / 4; if (av->qmin == 0) av->qmin = 3; if (av->qmax == 0) av->qmax = 31; if (av->max_qdiff == 0) av->max_qdiff = 3; av->qcompress = 0.5; av->qblur = 0.5; if (!av->rc_eq) av->rc_eq = "tex^qComp"; if (!av->i_quant_factor) av->i_quant_factor = -0.8; if (!av->b_quant_factor) av->b_quant_factor = 1.25; if (!av->b_quant_offset) av->b_quant_offset = 1.25; if (!av->rc_max_rate) av->rc_max_rate = av->bit_rate * 2; break; default: av_abort(); } st = av_mallocz(sizeof(AVStream)); if (!st) return; stream->streams[stream->nb_streams++] = st; memcpy(&st->codec, av, sizeof(AVCodecContext)); } static int opt_audio_codec(const char *arg) { AVCodec *p; p = first_avcodec; while (p) { if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_AUDIO) break; p = p->next; } if (p == NULL) { return CODEC_ID_NONE; } return p->id; } static int opt_video_codec(const char *arg) { AVCodec *p; p = first_avcodec; while (p) { if (!strcmp(p->name, arg) && p->type == CODEC_TYPE_VIDEO) break; p = p->next; } if (p == NULL) { return CODEC_ID_NONE; } return p->id; } /* simplistic plugin support */ #ifdef CONFIG_HAVE_DLOPEN void load_module(const char *filename) { void *dll; void (*init_func)(void); dll = dlopen(filename, RTLD_NOW); if (!dll) { fprintf(stderr, "Could not load module '%s' - %s\n", filename, dlerror()); return; } init_func = dlsym(dll, "ffserver_module_init"); if (!init_func) { fprintf(stderr, "%s: init function 'ffserver_module_init()' not found\n", filename); dlclose(dll); } init_func(); } #endif static int parse_ffconfig(const char *filename) { FILE *f; char line[1024]; char cmd[64]; char arg[1024]; const char *p; int val, errors, line_num; FFStream **last_stream, *stream, *redirect; FFStream **last_feed, *feed; AVCodecContext audio_enc, video_enc; int audio_id, video_id; f = fopen(filename, "r"); if (!f) { perror(filename); return -1; } errors = 0; line_num = 0; first_stream = NULL; last_stream = &first_stream; first_feed = NULL; last_feed = &first_feed; stream = NULL; feed = NULL; redirect = NULL; audio_id = CODEC_ID_NONE; video_id = CODEC_ID_NONE; for(;;) { if (fgets(line, sizeof(line), f) == NULL) break; line_num++; p = line; while (isspace(*p)) p++; if (*p == '\0' || *p == '#') continue; get_arg(cmd, sizeof(cmd), &p); if (!strcasecmp(cmd, "Port")) { get_arg(arg, sizeof(arg), &p); my_http_addr.sin_port = htons (atoi(arg)); } else if (!strcasecmp(cmd, "BindAddress")) { get_arg(arg, sizeof(arg), &p); if (!inet_aton(arg, &my_http_addr.sin_addr)) { fprintf(stderr, "%s:%d: Invalid IP address: %s\n", filename, line_num, arg); errors++; } } else if (!strcasecmp(cmd, "NoDaemon")) { ffserver_daemon = 0; } else if (!strcasecmp(cmd, "RTSPPort")) { get_arg(arg, sizeof(arg), &p); my_rtsp_addr.sin_port = htons (atoi(arg)); } else if (!strcasecmp(cmd, "RTSPBindAddress")) { get_arg(arg, sizeof(arg), &p); if (!inet_aton(arg, &my_rtsp_addr.sin_addr)) { fprintf(stderr, "%s:%d: Invalid IP address: %s\n", filename, line_num, arg); errors++; } } else if (!strcasecmp(cmd, "MaxClients")) { get_arg(arg, sizeof(arg), &p); val = atoi(arg); if (val < 1 || val > HTTP_MAX_CONNECTIONS) { fprintf(stderr, "%s:%d: Invalid MaxClients: %s\n", filename, line_num, arg); errors++; } else { nb_max_connections = val; } } else if (!strcasecmp(cmd, "MaxBandwidth")) { get_arg(arg, sizeof(arg), &p); val = atoi(arg); if (val < 10 || val > 100000) { fprintf(stderr, "%s:%d: Invalid MaxBandwidth: %s\n", filename, line_num, arg); errors++; } else { max_bandwidth = val; } } else if (!strcasecmp(cmd, "CustomLog")) { get_arg(logfilename, sizeof(logfilename), &p); } else if (!strcasecmp(cmd, "<Feed")) { /*********************************************/ /* Feed related options */ char *q; if (stream || feed) { fprintf(stderr, "%s:%d: Already in a tag\n", filename, line_num); } else { feed = av_mallocz(sizeof(FFStream)); /* add in stream list */ *last_stream = feed; last_stream = &feed->next; /* add in feed list */ *last_feed = feed; last_feed = &feed->next_feed; get_arg(feed->filename, sizeof(feed->filename), &p); q = strrchr(feed->filename, '>'); if (*q) *q = '\0'; feed->fmt = guess_format("ffm", NULL, NULL); /* defaut feed file */ snprintf(feed->feed_filename, sizeof(feed->feed_filename), "/tmp/%s.ffm", feed->filename); feed->feed_max_size = 5 * 1024 * 1024; feed->is_feed = 1; feed->feed = feed; /* self feeding :-) */ } } else if (!strcasecmp(cmd, "Launch")) { if (feed) { int i; feed->child_argv = (char **) av_mallocz(64 * sizeof(char *)); feed->child_argv[0] = av_malloc(7); strcpy(feed->child_argv[0], "ffmpeg"); for (i = 1; i < 62; i++) { char argbuf[256]; get_arg(argbuf, sizeof(argbuf), &p); if (!argbuf[0]) break; feed->child_argv[i] = av_malloc(strlen(argbuf) + 1); strcpy(feed->child_argv[i], argbuf); } feed->child_argv[i] = av_malloc(30 + strlen(feed->filename)); snprintf(feed->child_argv[i], 256, "http://127.0.0.1:%d/%s", ntohs(my_http_addr.sin_port), feed->filename); } } else if (!strcasecmp(cmd, "ReadOnlyFile")) { if (feed) { get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p); feed->readonly = 1; } else if (stream) { get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p); } } else if (!strcasecmp(cmd, "File")) { if (feed) { get_arg(feed->feed_filename, sizeof(feed->feed_filename), &p); } else if (stream) { get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p); } } else if (!strcasecmp(cmd, "FileMaxSize")) { if (feed) { const char *p1; double fsize; get_arg(arg, sizeof(arg), &p); p1 = arg; fsize = strtod(p1, (char **)&p1); switch(toupper(*p1)) { case 'K': fsize *= 1024; break; case 'M': fsize *= 1024 * 1024; break; case 'G': fsize *= 1024 * 1024 * 1024; break; } feed->feed_max_size = (int64_t)fsize; } } else if (!strcasecmp(cmd, "</Feed>")) { if (!feed) { fprintf(stderr, "%s:%d: No corresponding <Feed> for </Feed>\n", filename, line_num); errors++; #if 0 } else { /* Make sure that we start out clean */ if (unlink(feed->feed_filename) < 0 && errno != ENOENT) { fprintf(stderr, "%s:%d: Unable to clean old feed file '%s': %s\n", filename, line_num, feed->feed_filename, strerror(errno)); errors++; } #endif } feed = NULL; } else if (!strcasecmp(cmd, "<Stream")) { /*********************************************/ /* Stream related options */ char *q; if (stream || feed) { fprintf(stderr, "%s:%d: Already in a tag\n", filename, line_num); } else { stream = av_mallocz(sizeof(FFStream)); *last_stream = stream; last_stream = &stream->next; get_arg(stream->filename, sizeof(stream->filename), &p); q = strrchr(stream->filename, '>'); if (*q) *q = '\0'; stream->fmt = guess_stream_format(NULL, stream->filename, NULL); memset(&audio_enc, 0, sizeof(AVCodecContext)); memset(&video_enc, 0, sizeof(AVCodecContext)); audio_id = CODEC_ID_NONE; video_id = CODEC_ID_NONE; if (stream->fmt) { audio_id = stream->fmt->audio_codec; video_id = stream->fmt->video_codec; } } } else if (!strcasecmp(cmd, "Feed")) { get_arg(arg, sizeof(arg), &p); if (stream) { FFStream *sfeed; sfeed = first_feed; while (sfeed != NULL) { if (!strcmp(sfeed->filename, arg)) break; sfeed = sfeed->next_feed; } if (!sfeed) { fprintf(stderr, "%s:%d: feed '%s' not defined\n", filename, line_num, arg); } else { stream->feed = sfeed; } } } else if (!strcasecmp(cmd, "Format")) { get_arg(arg, sizeof(arg), &p); if (!strcmp(arg, "status")) { stream->stream_type = STREAM_TYPE_STATUS; stream->fmt = NULL; } else { stream->stream_type = STREAM_TYPE_LIVE; /* jpeg cannot be used here, so use single frame jpeg */ if (!strcmp(arg, "jpeg")) strcpy(arg, "singlejpeg"); stream->fmt = guess_stream_format(arg, NULL, NULL); if (!stream->fmt) { fprintf(stderr, "%s:%d: Unknown Format: %s\n", filename, line_num, arg); errors++; } } if (stream->fmt) { audio_id = stream->fmt->audio_codec; video_id = stream->fmt->video_codec; } } else if (!strcasecmp(cmd, "InputFormat")) { stream->ifmt = av_find_input_format(arg); if (!stream->ifmt) { fprintf(stderr, "%s:%d: Unknown input format: %s\n", filename, line_num, arg); } } else if (!strcasecmp(cmd, "FaviconURL")) { if (stream && stream->stream_type == STREAM_TYPE_STATUS) { get_arg(stream->feed_filename, sizeof(stream->feed_filename), &p); } else { fprintf(stderr, "%s:%d: FaviconURL only permitted for status streams\n", filename, line_num); errors++; } } else if (!strcasecmp(cmd, "Author")) { if (stream) { get_arg(stream->author, sizeof(stream->author), &p); } } else if (!strcasecmp(cmd, "Comment")) { if (stream) { get_arg(stream->comment, sizeof(stream->comment), &p); } } else if (!strcasecmp(cmd, "Copyright")) { if (stream) { get_arg(stream->copyright, sizeof(stream->copyright), &p); } } else if (!strcasecmp(cmd, "Title")) { if (stream) { get_arg(stream->title, sizeof(stream->title), &p); } } else if (!strcasecmp(cmd, "Preroll")) { get_arg(arg, sizeof(arg), &p); if (stream) { stream->prebuffer = atof(arg) * 1000; } } else if (!strcasecmp(cmd, "StartSendOnKey")) { if (stream) { stream->send_on_key = 1; } } else if (!strcasecmp(cmd, "AudioCodec")) { get_arg(arg, sizeof(arg), &p); audio_id = opt_audio_codec(arg); if (audio_id == CODEC_ID_NONE) { fprintf(stderr, "%s:%d: Unknown AudioCodec: %s\n", filename, line_num, arg); errors++; } } else if (!strcasecmp(cmd, "VideoCodec")) { get_arg(arg, sizeof(arg), &p); video_id = opt_video_codec(arg); if (video_id == CODEC_ID_NONE) { fprintf(stderr, "%s:%d: Unknown VideoCodec: %s\n", filename, line_num, arg); errors++; } } else if (!strcasecmp(cmd, "MaxTime")) { get_arg(arg, sizeof(arg), &p); if (stream) { stream->max_time = atof(arg) * 1000; } } else if (!strcasecmp(cmd, "AudioBitRate")) { get_arg(arg, sizeof(arg), &p); if (stream) { audio_enc.bit_rate = atoi(arg) * 1000; } } else if (!strcasecmp(cmd, "AudioChannels")) { get_arg(arg, sizeof(arg), &p); if (stream) { audio_enc.channels = atoi(arg); } } else if (!strcasecmp(cmd, "AudioSampleRate")) { get_arg(arg, sizeof(arg), &p); if (stream) { audio_enc.sample_rate = atoi(arg); } } else if (!strcasecmp(cmd, "AudioQuality")) { get_arg(arg, sizeof(arg), &p); if (stream) { // audio_enc.quality = atof(arg) * 1000; } } else if (!strcasecmp(cmd, "VideoBitRateRange")) { if (stream) { int minrate, maxrate; get_arg(arg, sizeof(arg), &p); if (sscanf(arg, "%d-%d", &minrate, &maxrate) == 2) { video_enc.rc_min_rate = minrate * 1000; video_enc.rc_max_rate = maxrate * 1000; } else { fprintf(stderr, "%s:%d: Incorrect format for VideoBitRateRange -- should be <min>-<max>: %s\n", filename, line_num, arg); errors++; } } } else if (!strcasecmp(cmd, "VideoBufferSize")) { if (stream) { get_arg(arg, sizeof(arg), &p); video_enc.rc_buffer_size = atoi(arg) * 1024; } } else if (!strcasecmp(cmd, "VideoBitRateTolerance")) { if (stream) { get_arg(arg, sizeof(arg), &p); video_enc.bit_rate_tolerance = atoi(arg) * 1000; } } else if (!strcasecmp(cmd, "VideoBitRate")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.bit_rate = atoi(arg) * 1000; } } else if (!strcasecmp(cmd, "VideoSize")) { get_arg(arg, sizeof(arg), &p); if (stream) { parse_image_size(&video_enc.width, &video_enc.height, arg); if ((video_enc.width % 16) != 0 || (video_enc.height % 16) != 0) { fprintf(stderr, "%s:%d: Image size must be a multiple of 16\n", filename, line_num); errors++; } } } else if (!strcasecmp(cmd, "VideoFrameRate")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.frame_rate_base= DEFAULT_FRAME_RATE_BASE; video_enc.frame_rate = (int)(strtod(arg, NULL) * video_enc.frame_rate_base); } } else if (!strcasecmp(cmd, "VideoGopSize")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.gop_size = atoi(arg); } } else if (!strcasecmp(cmd, "VideoIntraOnly")) { if (stream) { video_enc.gop_size = 1; } } else if (!strcasecmp(cmd, "VideoHighQuality")) { if (stream) { video_enc.mb_decision = FF_MB_DECISION_BITS; } } else if (!strcasecmp(cmd, "Video4MotionVector")) { if (stream) { video_enc.mb_decision = FF_MB_DECISION_BITS; //FIXME remove video_enc.flags |= CODEC_FLAG_4MV; } } else if (!strcasecmp(cmd, "VideoQDiff")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.max_qdiff = atoi(arg); if (video_enc.max_qdiff < 1 || video_enc.max_qdiff > 31) { fprintf(stderr, "%s:%d: VideoQDiff out of range\n", filename, line_num); errors++; } } } else if (!strcasecmp(cmd, "VideoQMax")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.qmax = atoi(arg); if (video_enc.qmax < 1 || video_enc.qmax > 31) { fprintf(stderr, "%s:%d: VideoQMax out of range\n", filename, line_num); errors++; } } } else if (!strcasecmp(cmd, "VideoQMin")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.qmin = atoi(arg); if (video_enc.qmin < 1 || video_enc.qmin > 31) { fprintf(stderr, "%s:%d: VideoQMin out of range\n", filename, line_num); errors++; } } } else if (!strcasecmp(cmd, "LumaElim")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.luma_elim_threshold = atoi(arg); } } else if (!strcasecmp(cmd, "ChromaElim")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.chroma_elim_threshold = atoi(arg); } } else if (!strcasecmp(cmd, "LumiMask")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.lumi_masking = atof(arg); } } else if (!strcasecmp(cmd, "DarkMask")) { get_arg(arg, sizeof(arg), &p); if (stream) { video_enc.dark_masking = atof(arg); } } else if (!strcasecmp(cmd, "NoVideo")) { video_id = CODEC_ID_NONE; } else if (!strcasecmp(cmd, "NoAudio")) { audio_id = CODEC_ID_NONE; } else if (!strcasecmp(cmd, "ACL")) { IPAddressACL acl; struct hostent *he; get_arg(arg, sizeof(arg), &p); if (strcasecmp(arg, "allow") == 0) { acl.action = IP_ALLOW; } else if (strcasecmp(arg, "deny") == 0) { acl.action = IP_DENY; } else { fprintf(stderr, "%s:%d: ACL action '%s' is not ALLOW or DENY\n", filename, line_num, arg); errors++; } get_arg(arg, sizeof(arg), &p); he = gethostbyname(arg); if (!he) { fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n", filename, line_num, arg); errors++; } else { /* Only take the first */ acl.first.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr); acl.last = acl.first; } get_arg(arg, sizeof(arg), &p); if (arg[0]) { he = gethostbyname(arg); if (!he) { fprintf(stderr, "%s:%d: ACL refers to invalid host or ip address '%s'\n", filename, line_num, arg); errors++; } else { /* Only take the first */ acl.last.s_addr = ntohl(((struct in_addr *) he->h_addr_list[0])->s_addr); } } if (!errors) { IPAddressACL *nacl = (IPAddressACL *) av_mallocz(sizeof(*nacl)); IPAddressACL **naclp = 0; *nacl = acl; nacl->next = 0; if (stream) { naclp = &stream->acl; } else if (feed) { naclp = &feed->acl; } else { fprintf(stderr, "%s:%d: ACL found not in <stream> or <feed>\n", filename, line_num); errors++; } if (naclp) { while (*naclp) naclp = &(*naclp)->next; *naclp = nacl; } } } else if (!strcasecmp(cmd, "RTSPOption")) { get_arg(arg, sizeof(arg), &p); if (stream) { av_freep(&stream->rtsp_option); /* XXX: av_strdup ? */ stream->rtsp_option = av_malloc(strlen(arg) + 1); if (stream->rtsp_option) { strcpy(stream->rtsp_option, arg); } } } else if (!strcasecmp(cmd, "MulticastAddress")) { get_arg(arg, sizeof(arg), &p); if (stream) { if (!inet_aton(arg, &stream->multicast_ip)) { fprintf(stderr, "%s:%d: Invalid IP address: %s\n", filename, line_num, arg); errors++; } stream->is_multicast = 1; stream->loop = 1; /* default is looping */ } } else if (!strcasecmp(cmd, "MulticastPort")) { get_arg(arg, sizeof(arg), &p); if (stream) { stream->multicast_port = atoi(arg); } } else if (!strcasecmp(cmd, "MulticastTTL")) { get_arg(arg, sizeof(arg), &p); if (stream) { stream->multicast_ttl = atoi(arg); } } else if (!strcasecmp(cmd, "NoLoop")) { if (stream) { stream->loop = 0; } } else if (!strcasecmp(cmd, "</Stream>")) { if (!stream) { fprintf(stderr, "%s:%d: No corresponding <Stream> for </Stream>\n", filename, line_num); errors++; } if (stream->feed && stream->fmt && strcmp(stream->fmt->name, "ffm") != 0) { if (audio_id != CODEC_ID_NONE) { audio_enc.codec_type = CODEC_TYPE_AUDIO; audio_enc.codec_id = audio_id; add_codec(stream, &audio_enc); } if (video_id != CODEC_ID_NONE) { video_enc.codec_type = CODEC_TYPE_VIDEO; video_enc.codec_id = video_id; if (!video_enc.rc_buffer_size) { video_enc.rc_buffer_size = 40 * 1024; } add_codec(stream, &video_enc); } } stream = NULL; } else if (!strcasecmp(cmd, "<Redirect")) { /*********************************************/ char *q; if (stream || feed || redirect) { fprintf(stderr, "%s:%d: Already in a tag\n", filename, line_num); errors++; } else { redirect = av_mallocz(sizeof(FFStream)); *last_stream = redirect; last_stream = &redirect->next; get_arg(redirect->filename, sizeof(redirect->filename), &p); q = strrchr(redirect->filename, '>'); if (*q) *q = '\0'; redirect->stream_type = STREAM_TYPE_REDIRECT; } } else if (!strcasecmp(cmd, "URL")) { if (redirect) { get_arg(redirect->feed_filename, sizeof(redirect->feed_filename), &p); } } else if (!strcasecmp(cmd, "</Redirect>")) { if (!redirect) { fprintf(stderr, "%s:%d: No corresponding <Redirect> for </Redirect>\n", filename, line_num); errors++; } if (!redirect->feed_filename[0]) { fprintf(stderr, "%s:%d: No URL found for <Redirect>\n", filename, line_num); errors++; } redirect = NULL; } else if (!strcasecmp(cmd, "LoadModule")) { get_arg(arg, sizeof(arg), &p); #ifdef CONFIG_HAVE_DLOPEN load_module(arg); #else fprintf(stderr, "%s:%d: Module support not compiled into this version: '%s'\n", filename, line_num, arg); errors++; #endif } else { fprintf(stderr, "%s:%d: Incorrect keyword: '%s'\n", filename, line_num, cmd); errors++; } } fclose(f); if (errors) return -1; else return 0; } #if 0 static void write_packet(FFCodec *ffenc, uint8_t *buf, int size) { PacketHeader hdr; AVCodecContext *enc = &ffenc->enc; uint8_t *wptr; mk_header(&hdr, enc, size); wptr = http_fifo.wptr; fifo_write(&http_fifo, (uint8_t *)&hdr, sizeof(hdr), &wptr); fifo_write(&http_fifo, buf, size, &wptr); /* atomic modification of wptr */ http_fifo.wptr = wptr; ffenc->data_count += size; ffenc->avg_frame_size = ffenc->avg_frame_size * AVG_COEF + size * (1.0 - AVG_COEF); } #endif static void show_banner(void) { printf("ffserver version " FFMPEG_VERSION ", Copyright (c) 2000-2003 Fabrice Bellard\n"); } static void show_help(void) { show_banner(); printf("usage: ffserver [-L] [-h] [-f configfile]\n" "Hyper fast multi format Audio/Video streaming server\n" "\n" "-L : print the LICENSE\n" "-h : this help\n" "-f configfile : use configfile instead of /etc/ffserver.conf\n" ); } static void show_license(void) { show_banner(); printf( "This library is free software; you can redistribute it and/or\n" "modify it under the terms of the GNU Lesser General Public\n" "License as published by the Free Software Foundation; either\n" "version 2 of the License, or (at your option) any later version.\n" "\n" "This library is distributed in the hope that it will be useful,\n" "but WITHOUT ANY WARRANTY; without even the implied warranty of\n" "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU\n" "Lesser General Public License for more details.\n" "\n" "You should have received a copy of the GNU Lesser General Public\n" "License along with this library; if not, write to the Free Software\n" "Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA\n" ); } static void handle_child_exit(int sig) { pid_t pid; int status; while ((pid = waitpid(-1, &status, WNOHANG)) > 0) { FFStream *feed; for (feed = first_feed; feed; feed = feed->next) { if (feed->pid == pid) { int uptime = time(0) - feed->pid_start; feed->pid = 0; fprintf(stderr, "%s: Pid %d exited with status %d after %d seconds\n", feed->filename, pid, status, uptime); if (uptime < 30) { /* Turn off any more restarts */ feed->child_argv = 0; } } } } need_to_start_children = 1; } int main(int argc, char **argv) { const char *config_filename; int c; struct sigaction sigact; av_register_all(); config_filename = "/etc/ffserver.conf"; my_program_name = argv[0]; my_program_dir = getcwd(0, 0); ffserver_daemon = 1; for(;;) { c = getopt(argc, argv, "ndLh?f:"); if (c == -1) break; switch(c) { case 'L': show_license(); exit(1); case '?': case 'h': show_help(); exit(1); case 'n': no_launch = 1; break; case 'd': ffserver_debug = 1; ffserver_daemon = 0; break; case 'f': config_filename = optarg; break; default: exit(2); } } putenv("http_proxy"); /* Kill the http_proxy */ srandom(gettime_ms() + (getpid() << 16)); /* address on which the server will handle HTTP connections */ my_http_addr.sin_family = AF_INET; my_http_addr.sin_port = htons (8080); my_http_addr.sin_addr.s_addr = htonl (INADDR_ANY); /* address on which the server will handle RTSP connections */ my_rtsp_addr.sin_family = AF_INET; my_rtsp_addr.sin_port = htons (5454); my_rtsp_addr.sin_addr.s_addr = htonl (INADDR_ANY); nb_max_connections = 5; max_bandwidth = 1000; first_stream = NULL; logfilename[0] = '\0'; memset(&sigact, 0, sizeof(sigact)); sigact.sa_handler = handle_child_exit; sigact.sa_flags = SA_NOCLDSTOP | SA_RESTART; sigaction(SIGCHLD, &sigact, 0); if (parse_ffconfig(config_filename) < 0) { fprintf(stderr, "Incorrect config file - exiting.\n"); exit(1); } build_file_streams(); build_feed_streams(); compute_bandwidth(); /* put the process in background and detach it from its TTY */ if (ffserver_daemon) { int pid; pid = fork(); if (pid < 0) { perror("fork"); exit(1); } else if (pid > 0) { /* parent : exit */ exit(0); } else { /* child */ setsid(); chdir("/"); close(0); open("/dev/null", O_RDWR); if (strcmp(logfilename, "-") != 0) { close(1); dup(0); } close(2); dup(0); } } /* signal init */ signal(SIGPIPE, SIG_IGN); /* open log file if needed */ if (logfilename[0] != '\0') { if (!strcmp(logfilename, "-")) logfile = stdout; else logfile = fopen(logfilename, "w"); } if (http_server() < 0) { fprintf(stderr, "Could not start server\n"); exit(1); } return 0; }
Java
''' Ohm's law is a simple equation describing electrical circuits. It states that the voltage V through a resistor is equal to the current (I) times the resistance: V = I * R The units of these are volts, ampheres (or "amps"), and ohms, respectively. In real circuits, often R is actually measured in kiloohms (10**3 ohms) and I in milliamps (10**-3 amps). Let's create a Resistor class that models this behavior. The constructor takes two arguments - the resistance in ohms, and the voltage in volts: >>> resistor = Resistor(800, 5.5) >>> resistor.resistance 800 >>> resistor.voltage 5.5 The current is derived from these two using Ohm's law: (Hint: use @property) >>> resistor.current 0.006875 Since we may want the value in milliamps, let's make another property to provide that: >>> resistor.current_in_milliamps 6.875 Let's set it up so that we can change the current, and doing so will correspondingly modify the voltage (but keep the resistance constant). >>> resistor.current_in_milliamps = 3.5 >>> resistor.resistance 800 >>> round(resistor.voltage, 2) 2.8 >>> resistor.current = .006875 >>> round(resistor.voltage, 2) 5.5 >>> resistor.resistance 800 Also, we've made a design decision that a Resistor cannot change its resistance value once created: >>> resistor.resistance = 8200 Traceback (most recent call last): AttributeError: can't set attribute ''' # Write your code here: class Resistor: def __init__(self, resistance, voltage): self._resistance = resistance self.voltage = voltage @property def resistance(self): return self._resistance @property def current(self): return self.voltage / self.resistance @current.setter def current(self, value): self.voltage = self.resistance * value @property def current_in_milliamps(self): return self.current * 1000 @current_in_milliamps.setter def current_in_milliamps(self, value): self.current = value / 1000 # Do not edit any code below this line! if __name__ == '__main__': import doctest count, _ = doctest.testmod() if count == 0: print('*** ALL TESTS PASS ***\nGive someone a HIGH FIVE!') # Copyright 2015-2018 Aaron Maxwell. All rights reserved.
Java
--- layout: post title: 从垃圾回收算法到Object Pool description: "Just about everything you'll need to style in the theme: headings, paragraphs, blockquotes, tables, code blocks, and more." modified: 2014-02-28 tags: [javascript, GC] image: feature: abstract-3.jpg credit: dargadgetz creditlink: http://www.dargadgetz.com/ios-7-abstract-wallpaper-pack-for-iphone-5-and-ipod-touch-retina/ comments: true share: true --- 前言:这本是一篇InfoQ的投稿,编辑给我的修改意见是把前半部分的GC算法的去掉。因为这些算法在JVM和其它平台的几乎是一致,甚至只是子集(事实确实如此,这篇文章参考了的文章大部分是Javas虚拟机的GC算法)。但还是暂时保留下来作为1.0 版本吧,将来打算和其它的优化内容合在一起,重新发布。 ------ 浏览器的脚本引擎有一个不足之处是,你无法通过javascript语法强制让脚本引擎进行垃圾回收(Garbage Collection,在文中以GC代替)和内存释放。虽然你可以在脚本中执行 `delete someVariable` 或者 `someVariable = null` 又或者 `someVariable = void 0`。但事实上你做的都只是删除了变量对某个对象的引用而已,至于被删除引用的对象是否能够被回收,又何时能否被回收,这就只能由脚本引擎说得算了。 这会留下一个性能上的隐患,因为GC也是要消耗浏览器资源的。理想的状态应该是在浏览器进程空闲的时候进行GC,相反如果GC发生的同时也有许多脚本需要处理,这务必会影响程序的性能。为了保证良好的用户体验,我们要尽可能让程序的刷新率靠近每秒60帧。换而言之,你必须在16.7ms之内执行完每一帧的所有脚本。 这篇文章主要分为两部分,一是关于浏览器的脚本引擎如何进行垃圾回收;二是如何使用Object Pool解决GC引起性能问题。 ## 脚本引擎的垃圾回收算法 ### Reference Counting 早在Javascript 1.1版本和Netscape 3中(甚至在早期火狐中),一个对象是否被回收是由这个对象的被引用次数决定的。对象一旦被创建并被一个变量引用,那么它的引用次数便是1,如果该对象又被赋值给了另一个变量,那么引用便增为2.一旦某变量删除了对该对象的引用或者另被赋值,那么该对象的引用便又降为1.理论上来说,当一个对象的被引用次数降为0时,表示没有任何变量在引用该对象了,它已经毫无用处可以被回收从内存中释放了。 但是这个算法有一个缺陷,比如当存在如下图循环引用的情况时: {% highlight javascript %} A<-------| C----->X | | D----->Y |------->B E----->Z {% endhighlight %} A与B互相引用,A和B的被引用次数都不为0,按照算法规则是不会被垃圾回收。但实际情况是A与B成了座“孤岛”,没有任何以外的变量引用他们。他们不会被回收,又不会再被发现和引用,这便造成了内存泄露。 实际的例子是在IE6、7中,DOM对象的回收使用的就是Reference Counting算法,比如下面这个例子 {% highlight javascript %} var div = document.createElement("div"); div.onclick = function handler(){ doSomething(); }; {% endhighlight %} 引用的情况是: - div通过onclick属性对函数handler进行引用 - 函数对div也进行了引用,因为在handler的作用域中可以访问div 这样的循环会导致两个对象都没有办法被垃圾回收,引起内存泄露。 ### Mark-and-Sweep 目前大部分浏览器使用的是这一个垃圾回收算法,或是在这个算法上的变形。这个算法以图的形式将所有的对象连接起来,就像算法名称所示,回收过程分为两个阶段: 1. 标记(Mark):它首先假设存在一些根(root)节点(比如Javascript中的全局对象),从根节点出发,试图去访问其它的每一个与它相连的节点。在Javascript中,如果访问到的节点是基本数据类型(Primitive type),则对这个节点进行标记,如果不是基本数据类型,也就是Object或者Array,则对这个非基本类型递归这一过程,直到访问到所有节点。 2. 清除(Sweep):经过上面的步骤之后,那么那些存在但没有被标记的对象,则进行回收。 ![Alt text](http://www.html5rocks.com/en/tutorials/memory/effectivemanagement/images/image03.png) 如果说Reference Counting的回收条件是“当某个对象不再被需要”,那么Mark-and-Sweep的回收条件则是“当某个对象不再能被访问”。 同时我们再回过头来看在前一个算法中会造成内存泄露的例子,很明显如果将算法换成Mark-and-Sweep,即使A与B互相引用,但是从根节点出发无法被访问,那么还是会对他们进行回收。 ### V8 实际情况会比我们想象的复杂的多,比如V8引擎就一共使用了三种垃圾回收算法。 #### Two Generational Collector(分代收集算法) 分代收集算法实际只能算三色标记算法(Tri-color marking)的一种策略。该算法的依据是:根据对大量计算机程序进行统计,发现最新被分配内存空间的对象通常活的时间都不会太长。这也被称作“弱代假说”(infant mortality or the generational hypothesis)。 这个算法将内存空间分为两代(generation),年青一代(young generation)和老一代(old generation)。在年青一代区域内存的分配和回收频繁并且迅速,老一代的区域内存的分配缓慢并且次数较少。一个对象被划分为“年青”和“老”的依据是,它从出生到存活至今被分配的字节数。 V8引擎的最外层使用的是这个算法,但是在年青一代和老一代的内存空间中又有独立的垃圾回收算法。年青一代使用的是切尼算法(Cheney's algorithm),而老一代使用的是标记压缩(Mark-compact)算法。 #### Cheney's algorithm(切尼算法) 切尼算法将堆(heap)分为相等的两个空间,分别命名为from和to,新增对象的内存空间分配是从名为to的那一部分开始的。当to空间的内存不够分配时,年青一代的GC便被触发。首先GC会交换from和to,并对新的from空间(原来的to)进行扫描,所有“活着”的对象都面临着选择:是被复制到to空间还是被分配到老一代内存中。一般来说这样一个过程不会超过10毫秒。 假设我们已经将from和to空间互相交换过了,接下来需要做的如何找到“活着”的对象,并且将活着的对象转移到新的to空间上去: - 算法依次扫描被栈(stack)引用的堆(heap) 上的对象(至于栈和堆的关系,可以参考C#:在C#中数据类型被分为两种,值类型和引用类型,值类型只需要一段单独的内存,用于存储实际的数据,存储在栈上;引用类型需要两段内存,第一段存储实际的数据,它总是位于堆上,第二段是一个引用指向数据在堆中存放的位置,位于栈上): - 如果对象还没有被转移到新的to空间上,那么就在to空间创建一份拷贝,并且将当前from空间的该对象修改为一个指向to空间拷贝的指针。并更新栈上引用,指向新的拷贝; - 如果对象已经被转移到了新的to空间上,那么把栈上指向from的指针改为指向to上的新拷贝即可 - 算法依次扫描已经转移到to上的对象,并且检查它们在from空间上的引用,重复上面的步骤 #### Mark-compact algorithm(标记压缩算法) 标记压缩算法是标记清除算法的一种变形,它主要解决的是标记清除之后内存空间空间碎片化不连续的问题。以基于表(Table-based)的标记压缩算法为例: 1. 标记与清除过程与Mark-and-sweep算法相同 2. 压缩过程从堆的底部(低位)向头部(高位)进行,每当扫描到一个被标记的对象,将它转移至第一个可用低位。并且将当前的移动记录插入至表(break table)中,该记录包括对象重置的位置,以及重置位置与原位置的差别。表的位置就放在压缩的堆中,但是该位置对其他对象来说是未被使用的。 3. 随着压缩的进行,被标记的对象不断的向低位移动,因此表占用的空间可会被征用,需要转移到新的空间 4. 等到压缩完毕,堆中幸存的对象需要根据表的记录,来更新对其他对象的指针引用 需要注意的是,表可能是不连续的(break),因此在第三步中表可能只是某一部分在堆中移动。这样会导致表里的记录不是按堆中对象的顺序排列的。所以在压缩之后,需要对表进行一次排序。 为了更好的理解压缩过程,可以将堆比作书架的一格,其中一部分放满了不同厚度的图书。空闲空间就是图书之间的空隙。压缩就是将所有图书朝一个方向推移,以弥合所有空隙。它从最靠近隔板的图书开始,将它推向隔板,然后将离隔板第二近的图书推向第一本图书,接着将第三本图书推向第二本图书,依此类推。最后,所有图书在一端,所有空闲空间在另一端。 ## Object Pool 在文章的开头,我提到GC也是会占用资源影响到性能的。让我们来看一个实际的例子。 首先我来模拟一个场景,想象一个街机平面射击游戏,玩家控制飞船不断的发射子弹攻击BOSS,每一轮发射10000颗子弹,同时每一轮发射的时候只有10%的子弹会击中BOSS而损失掉: {% highlight javascript %} // 子弹 var Bullet = function () {}; var gun = []; // 射击 var shoot = function () { var num = 100 * 100; for (var i = 0; i < num; i++) { gun.push(new Bullet()); } }; var shootAgain = function () { // 每次射击都会损失10%的子弹 for (var i = 0, len = parseInt(gun.length * 0.1); i < len ;i++) { gun.shift(); } shoot(); console.log("TOTAL LEN------>", gun.length); }; // 无限执行下去 (function repeat() { setTimeout(function () { shootAgain(); repeat(); }, 100); })(); {% endhighlight %} 如果你在Chrome中执行代码,并且在devtools中timeline中查看内存(memory标签下)的使用情况,你会看到类似于下图的锯齿图: ![Alt text](http://www.html5rocks.com/en/tutorials/speed/static-mem-pools/fig1.jpg) 每一次峰值意味着使用的内存不断的增长,同时峰值之后的回落意味着一个GC的发生,将无用的内存进行回收。 ![Alt text](http://www.html5rocks.com/en/tutorials/speed/static-mem-pools/fig2.jpg) 就像开头说的那样,GC会影响你的性能,如何运行GC是由引擎自己决定的,你没有控制权,GC可以发生在代码执行的任何时候,并且会中断你的代码执行知道GC完成。 如上图那样锯齿状的原因是因为频繁的创建和销毁对象,为了阻止这样的事情发生,其中一个办法就是延长对象的寿命,尽可能的不去触发GC。因此我们可以利用Object Pool模式。 Object Pool采取的是这样一种策略,在程序初始化时一次性创建相当数量的对象,存放在“池(pool)”中,当需要使用时不是在创建新的对象,而是从池中获取,当对象使用完毕后,还回池中,以上面的子弹代码为例,我们可以增加两个关于“池”的方法: {% highlight javascript %} // 使用中的子弹 var activeBullets = []; // 池子 object pool var bulletPool = []; // 初始化创建20颗子弹,存入池中 for (var i=0; i < 20; i++) bulletPool.push( new Bullet() ); // 获得子弹 function getNewBullet() { var b = null; if (bulletPool.length > 0) b = bulletPool.pop(); else // 如果池中对象不够用了,再增加新的对象 b = new Bullet(); // 使用子弹 activeBullets.push(b); return b; } // 释放对象,还回池中 function freeBullet(b) { for (var i=0, l=activeBullets.length; i < l; i++) if (activeBullets[i] == b) array.slice(i, 1); bulletPool.push(b); } {% endhighlight %} 我们可以进一步的将Object Pool模式抽象出来,封装成一个lib: {% highlight javascript %} var ObjectPool = (function() { var ObjectPool = function(Cls) { // 池子里的对象必须是同一类, // 所以你首先要传入一个构造函数 this.cls = Cls; // metrics用于记录pool的当前状态 // 比如 totalalloc(总已分配数)、 totalfree(可用) this.metrics = {}; // 重置池子 this._clearMetrics(); this._objpool = []; }; ObjectPool.prototype = { // 分配 alloc: function () { var obj; // 如果池中已无对象可供分配 if (this._objpool.length == 0) { obj = new this.cls(); this.metrics.totalalloc++; } else { obj = this._objpool.pop(); this.metrics.totalfree--; } obj.init.apply(obj, arguments); return obj; }, // 释放对象 free: function(obj) { var k; this._objpool.push(obj); this.metrics.totalfree++; // 对象还回池中后, // 还需要对对象进行清理,清除脏数据 for (k in obj) { delete obj[k]; } // 重新初始化 obj.init.call(obj); }, // 垃圾回收 // 在Object Pool模式下,垃圾回收便显得多余了 // 如果有需求的话,还是提供这样一个接口 collect: function () { this._objpool = []; var inUse = this.metrics.totalalloc - this.metrics.totalfree; // 记录下当前未被回收但已分配的个数 this._clearMetrics(inUse); }, _clearMetrics: function (allocated) { this.metrics.totalalloc = allocated || 0; this.metrics.totalfree = 0; } } return ObjectPool })(); {% endhighlight %} 有了上面的类库,我的子弹代码可以继续改进: {% highlight javascript %} // 子弹类 var Bullet = function () {}; // 创建 Object Pool var bulletPool = new ObjectPool(Bullet); // 新的子弹 var bullet = bulletPool.alloc(); // 销毁子弹 bullPool.free(bullet) {% endhighlight %} 最后要说明的是Object Pool并非万能。如果对于一些性能要求较高的大型应用,预先的一次性创建大批对象同样是一种代价;而对于小型应用,因为Object Pool基本不会对内存进行回收,所以会长时间大量占用内存,这同样是值得商榷的。使用Object Pool之后内存的使用情况应该如下图所示: ![Alt text](http://www.html5rocks.com/en/tutorials/speed/static-mem-pools/fig3.jpg) 参考资料 - [Effectively managing memory at Gmail scale - HTML5 Rocks](http://www.html5rocks.com/en/tutorials/memory/effectivemanagement/) - [Static Memory Javascript with Object Pools - HTML5 Rocks](http://www.html5rocks.com/en/tutorials/speed/static-mem-pools/) - [High-Performance, Garbage-Collector-Friendly Code - Build New Games](http://buildnewgames.com/garbage-collector-friendly-code/) - [Garbage Collection (JavaScript: The Definitive Guide, 4th Edition)](http://docstore.mik.ua/orelly/webprog/jscript/ch11_03.htm) - [Mark-compact algorithm - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Mark-compact_algorithm) - [Cheney's algorithm - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Cheney%27s_algorithm) - [Garbage collection (computer science) - Wikipedia, the free encyclopedia](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)) - [Memory Management - JavaScript](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management)
Java
set(PROCESSORS 4) set(CMAKE_RELEASE_DIRECTORY /Users/kitware/CMakeReleaseDirectory) # set(USER_OVERRIDE "set(CMAKE_CXX_LINK_EXECUTABLE \\\"gcc <FLAGS> <CMAKE_CXX_LINK_FLAGS> <LINK_FLAGS> <OBJECTS> -o <TARGET> <LINK_LIBRARIES> -shared-libgcc -lstdc++-static\\\")") set(INSTALL_PREFIX /) set(HOST dashmacmini5) set(MAKE_PROGRAM "make") set(MAKE "${MAKE_PROGRAM} -j5") set(CPACK_BINARY_GENERATORS "PackageMaker TGZ TZ") set(CPACK_SOURCE_GENERATORS "TGZ TZ") set(INITIAL_CACHE " CMAKE_BUILD_TYPE:STRING=Release CMAKE_OSX_ARCHITECTURES:STRING=x86_64;i386 CMAKE_OSX_DEPLOYMENT_TARGET:STRING=10.5 CMAKE_SKIP_BOOTSTRAP_TEST:STRING=TRUE CPACK_SYSTEM_NAME:STRING=Darwin64-universal BUILD_QtDialog:BOOL=TRUE QT_QMAKE_EXECUTABLE:FILEPATH=/Users/kitware/Support/qt-4.7.4/install/bin/qmake ") get_filename_component(path "${CMAKE_CURRENT_LIST_FILE}" PATH) include(${path}/release_cmake.cmake)
Java
@(contestId: Long, form: Form[org.iatoki.judgels.uriel.forms.ContestAnnouncementUpsertForm]) @import play.i18n.Messages @import org.iatoki.judgels.uriel.controllers.routes @import org.iatoki.judgels.play.views.html.formErrorView @import org.iatoki.judgels.uriel.views.html.contest.announcement.upsertAnnouncementView @import org.iatoki.judgels.uriel.views.html.contest.supervisorjs @implicitFieldConstructor = @{ b3.horizontal.fieldConstructor("col-md-3", "col-md-9") } @formErrorView(form) @b3.form(routes.ContestAnnouncementController.postCreateAnnouncement(contestId)) { @upsertAnnouncementView(form) @b3.submit('class -> "btn btn-primary") { @Messages.get("commons.create") } } @supervisorjs(contestId)
Java
using UnityEngine; using System.Collections; public class Metrics : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
Java
<?php declare(strict_types=1); namespace PoPCMSSchema\QueriedObject\TypeResolvers\InterfaceType; use PoP\ComponentModel\TypeResolvers\InterfaceType\AbstractInterfaceTypeResolver; class QueryableInterfaceTypeResolver extends AbstractInterfaceTypeResolver { public function getTypeName(): string { return 'Queryable'; } public function getTypeDescription(): ?string { return $this->__('Entities that can be queried through an URL', 'queriedobject'); } }
Java
*, *:before, *:after { -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } span.grid_module { width: 10em; overflow: hidden; display: inline-block; vertical-align: bottom; text-overflow: ellipsis; } #tblda th,#tblda td { display: block; text-align: left; } #tblda th.thda { font-family: font_strong; font-size: 24px; color: #322F31; text-transform: uppercase; font-weight: normal; margin-bottom: 10px; } #blsd_padding table td { white-space: pre-wrap; } div#login-box { background-color: #fff; height: 235px; width: 380px; font-size: 14px; overflow: hidden; position: absolute; z-index: 99999; top: 25%; left: 35%; display: none; } .menu .tinnhan { padding: 10px; } .menu li h4 { margin-top: 0; } .clearfix::after { visibility: hidden; display: block; font-size: 0; content: " "; clear: both; height: 0; } * html .clearfix { zoom: 1; } /* IE6 */ *:first-child + html .clearfix { zoom: 1; } /* IE7 */ body { font-family: 'Open Sans', sans-serif; font-size: 13px; /* color: #322F31; */ min-width: 970px; line-height: 20px; margin: 0px; background-color: #f4f4f4; -webkit-font-smoothing: antialiased; } .cddt { position: relative; height: 100%; } ul li { list-style: none; } ul.menu { line-height: initial; /* margin-right: 2px; */ } .menu p { line-height: initial; } ul { padding: 0; margin: 0; } ul#top-subject li:nth-child(odd) { background-color: white; } ul#top-subject li:nth-child(even) { background-color: #faf8f1; } ul#top-subject -child {} ul#top-subject li:first-child,ul#top-subject li:last-child { background-color: white; } li.header { text-align: center; line-height: 50px; border-bottom: 1px solid #fff; } @font-face { font-family: font_strong; src: url('fonts/utm_bebas.ttf') format('truetype'), url('fonts/utm_bebas.eot#iefix') format('embedded-opentype'), url('fonts/utm_bebas.woff') format('woff'); font-weight: normal; font-style: normal; } @font-face { font-family: font_hvt; src: url('fonts/HelveticaWorld-Regular.eot'); font-weight: normal; font-style: normal; } /* Webkit override Scrollbar with CSS3 */ .box-left table { max-width: 100%; width: 100%; } .line2 { height: 1px; background: #322F31; } .line { height: 1px; background: #f4f4f4; } .linefix::before { content: ""; position: absolute; width: 100%; border-bottom: 1px solid #EEE; } .line_orn { height: 4px; background: #f4f4f4; margin-bottom: -4px; z-index: 99; position: relative; } .line_orn2 { height: 4px; background: url('/Images/orn2.png') repeat-x; } .clear { clear: both; } .main { margin: 0 auto; overflow: hidden; padding: 0; min-width: 1030px; max-width: 1030px; width: 100%; } .main2 { margin: 0 auto; /* overflow: hidden; */ padding: 0; min-width: 1030px; max-width: 1030px; width: 100%; height: 100%; } .title_path { height: 50px; background: #fff; border-radius: 0px; width: 100%; margin-top: 0px; border-bottom: 1px solid #f4f4f4; } .tileh3 { margin-top: 0px; position: absolute; color: #322F31; font-size: 18px; padding-left: 65px; line-height: 54px; float: left; font-weight: normal; background: url('/Images/iBooks-S3-icon.png') no-repeat 25px center; background-size: 30px auto; text-transform: uppercase; } /*========================Header===========================*/ .head_box { height: 60px; background: url(../Images/white95.png); z-index: 9999; position: fixed; left: 0px !important; margin: 0 auto; width: 100%; } .head_logo { width: 40px; height: 40px; background-image: url('/Images/hlogo.png'); background-size: 40px 40px; margin-top: 13px; float: left; } .head_username_box { margin-top: -3px; } .head_username_info:hover { text-decoration: none; } .head_username_info { font-size: 11px; font-weight: normal; color: #fff; text-decoration: none; } a.Link_orange:hover { color: #eee; text-decoration: none; } .head_menu_beak { background: #ddd; float: left; width: 0px; height: 20px; margin-top: 15px; } .head_menu { float: left; font-size: 22px; text-align: center; margin-top: 5px; margin-left: 20px; text-transform: uppercase; } .head_menu_item { float: left; margin-top: 15px; padding: 0px 5px; } .head_menu_text { color: #322F31; padding: 0 8px; text-decoration: none; font-family: font_strong; } a.head_menu_text:hover { color: #f7922a; } /*========================Slide + Tìm Kiếm===========================*/ input#searchinput { height: 27px; width: 220px; border: none; padding-left: 10px; outline: none; } input.search_button { position: absolute; right: 0px; top: 0px; background: url('/Images/ic_search_white_24dp.png') no-repeat 10px center #70b4de; border-left: 1px solid #eee; color: #fff; border-right: 0px; border-bottom: 0px; height: 30px; border-top: 0px; width: 100px; padding-left: 30px; cursor: pointer; } #camera_wrap { width: 100%; min-width: 1030px; display: block; margin: 0 auto; float: none; border-radius: 0px; max-height: 321px; height: 100%; min-height: 321px; background: url('/Images/ofical_banner.png') center center no-repeat #fff; z-index: -1; /* bottom: 0; */ position: absolute; margin-top: 60px; left: 0; - webkit - transition: all 1.0s ease; - moz - transition: all 1.0s ease; transition: all 1.0s ease; /* background-size: 100% auto; */ } .footer { width: 100%; min-width: 1030px; } .nddalg { z-index: 1; position: relative; margin-bottom: 55px; height: 55px; width: 230px; margin-left: -50px; } /*========================Cột bên phải===========================*/ .box_right { width: 300px; float: right; padding: 1px 1px; } .bg_right { position: relative; background-color: #fff; border-radius: 0px; border: 0px solid #eee; overflow: hidden; } .bg_title_category { background: url('/Images/iconTabArrow.gif') no-repeat 31px bottom; height: 50px; padding-left: 25px; padding-top: 18px; font-size: 18px; color: #f7922a; text-transform: uppercase; border-bottom: 1px solid #f7922a } a#tab-1 { text-indent: -9999; display: inline-block; text-indent: -9999px; background: url('/images/ic_folder_white_24dp2.png') no-repeat 0px center; width: 35px; text-decoration: none; } a#tab-2 { text-indent: -9999; display: inline-block; text-indent: -9999px; background: url('/images/ic_star_white_24dp.png') no-repeat 0px 98px; width: 35px; padding-top: 100px; text-decoration: none; margin-top: -100px; } .bg_title_category2 { background: url('/Images/ic_local_offer_white_24dp.png') no-repeat 10px center #70b4de; height: 32px; width: 265px; padding-left: 45px; padding-top: 13px; font-size: 18px; color: white; text-transform: uppercase; } .cate_link { color: #322F31; display: block; text-decoration: none; } .cate_item:hover { color: #f7922a; background-image: url('/Images/iconArrowRight_on.gif'); } .cate_item { font-weight: normal; padding: 13px 40px 13px 25px; background-image: url('/Images/iconArrowRight.gif'); background-position: right 25px top 16px; background-repeat: no-repeat; font-size: 16px; margin: 0px; } .bg_title_top { background: url('/Images/iconTabArrow.gif') no-repeat 31px bottom; height: 50px; padding-left: 25px; padding-top: 15px; font-size: 18px; color: #f7922a; text-transform: uppercase; border-bottom: 1px solid #f7922a; } .top_item { height: 120px; padding: 0 15px; border-bottom: 1px solid #f4f4f4; } .top_item:nth-child(2n) { height: 120px; width: 250px; /* padding: 0 25px; */ background-color: #fff; border-bottom: 1px solid #f4f4f4; } .top_viewall { height: 35px; text-align: right; padding: 10px 25px 0 0; } .top_img { width: auto; height: 65px; font-size: 12px; vertical-align: middle; } .anhtopdoan { width: 81px; height: 65px; float: left; overflow: hidden; background: #fff; margin-top: 15px; border-radius: 2px; border: 1px solid #f4f4f4; } .top_title_link { color: #322F31; text-decoration: none; } .top_title { overflow: hidden; white-space: nowrap; margin-top: 15px; text-overflow: ellipsis; width: 12em; height: 65px; line-height: 18px; font-weight: normal; float: right; font-size: 15px; /* margin-bottom: 0px; */ position: relative; } a.top_title_link :hover { text-decoration: none; color: #ff8401; } .top_cate { height: 20px; overflow: hidden; float: left; color: #ff8401; text-decoration: none; font-style: italic; padding-right: 5px; padding-top: 2px; width: 150px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } .top_view { height: 20px; overflow: hidden; float: right; color: #babcbc; padding-top: 2px; } .top_view:after { content: 'views'; color: #babcbc; } .link_bullet_next { font-style: italic; color: #babcbc; background-image: url('/Images/glyphCategoryArrow.png'); background-position: right 0px top 4px; background-repeat: no-repeat; text-decoration: none; padding-right: 15px; } a.link_bullet_next:hover { text-decoration: none; background-image: url('/Images/glyphCategoryArrow_hv.png'); color: #ff8401; } /*--================================FOOTER ==========================================*/ .footer_box { height: 285px; background: #202020; padding-top: 20px; margin-top: 50px; } .footer_logo { width: 285px; float: left; margin-top: 5px; } .footer_logo_menu { margin-top: 5px; display: inline-block; color: #f7922a; } .link_bullet_bold { background-position: right 0px top 3px; background-repeat: no-repeat; text-decoration: none; padding-right: 10px; font-size: 13px; text-transform: uppercase; color: #fff; font-weight: bold; } .footer_company { margin-left: 50px; margin-top: 6px; width: 420px; float: left; } .footer_title { font-size: 23px; color: #f7922a; margin-bottom: 30px; font-family: font_strong; font-weight: 200; word-spacing: 2px; } .footer_item { margin-top: 20px; overflow: hidden; } .footer_img { width: 65px; height: 65px; border-radius: 0px; float: left; margin-right: 15px; } .footer_text { width: 330px; float: left; color: #fff; font-weight: bold; } .footer_link { width: 275px; float: left; color: #cbcccc; margin-top: 3px; text-decoration: none; } .footer_address { margin-left: 40px; margin-top: 6px; width: 210px; float: right; color: #cbcccc; } .footer_email a { text-decoration: none !important; } .footer_address_text { margin-top: 20px; font-weight: bold; margin-bottom: 10px; color: #fff; } .footer_email { background: url('/Images/ic_email.png') no-repeat 0 5px; padding-left: 22px; color: #ff8401; margin-top: 15px; } .diachi { background: url('../Images/bg_icon_address.png') no-repeat 0px 4px; padding-left: 20px; } .footer_logo2 { background: url('/Images/hlogo.png') no-repeat 0px 0px; width: 100%; height: 40px; background-size: 40px 40px; float: left; text-align: left; font-size: 45px; color: #f7922a; margin-bottom: 15px; font-family: font_strong; font-weight: 200; word-spacing: 2px; text-decoration: none; } a.footer_logo2 { padding-top: 6px; padding-left: 50px; padding-bottom: 0px; margin-bottom: 10px; } .footer_logo p { color: #cbcccc; text-align: left; padding: 0; } a#to-top { width: 28px; height: 28px; display: block; position: fixed; bottom: 20px; right: 20px; text-indent: -9999px; border-radius: 3px; background: url(http://rgb.vn/ideas/wp-content/themes/rgb2014/images/iconArrowTop.png) no-repeat #d9d9d9; opacity: .5; filter: alpha(opacity=50); } .bottom_box { height: 73px; background: #f4f4f4; color: #322F31; font-size: 14px; } .bottom_copyright { margin-top: 18px; width: 100%; text-align: center; } .bottom_copyright p { color: #8a8a8a; margin: 0; } .bottom_author { margin-top: 15px; width: 370px; float: right; text-align: right; font-size: 11px; color: #D52026; } .bottom_link { color: #D52026; text-decoration: none; } /*--================================ CỘT BÊN TRÁI===========================================*/ .box_left { width: 690px; display: block; float: left; padding: 1px; margin: 0; margin-top: 110px; } .title_box { background-color: #fff; border-radius: 0px; height: 45px; border-bottom: 1px solid #f4f4f4; padding: 0px 5px; display: none; } /*===================================Trang chủ=================================*/ /*1. trang chu. tuy chon*/ .option_view { border-radius: 0px; border: 1px solid #70b4de; height: 30px; width: 330px; float: left; margin-top: 7px; background-color: white; margin-left: 20px; position: relative; } .option_view_small { border-radius: 0px; height: 30px; width: 60px; float: right; margin-top: 7px; background-color: white; margin-right: 20px; } .option_sort { line-height: 54px; width: 180px; float: right; margin-right: 25px; } .option_base { color: #FFB82E; background: url('/Images/ic_base1.png') 15px 7px no-repeat; width: 100px; height: 30px; border: none; padding-left: 30px; font-size: 14px; float: left; border-radius: 0px 0 0 0px; } .option_base:hover { cursor: pointer; color: white; background: url('/Images/ic_base2.png') 15px 8px no-repeat #FFB82E; } .option_base_select { color: white; background: url('/Images/ic_base2.png') 15px 7px no-repeat #FFB82E; width: 100px; height: 30px; border: none; padding-left: 30px; font-size: 14px; float: left; border-radius: 0px 0 0 0px; } .option_detail { color: #322F31; background: url('/Images/ic_detail1.png') 15px 8px no-repeat #f4f4f4; width: 100px; height: 30px; border: none; padding-left: 30px; font-size: 14px; border-radius: 0 0px 0px 0; } .option_detail:hover { cursor: pointer; color: white; background: url('/Images/ic_detail2.png') 15px 8px no-repeat #FFB82E; } .option_detail_select { color: white; background: url('/Images/ic_detail2.png') 15px 8px no-repeat #FFB82E; width: 100px; height: 30px; border: none; padding-left: 30px; font-size: 14px; border-radius: 0 0px 0px 0; } /*option small*/ .option_base_small { background: url('/Images/ic_base1.png') 8px 8px no-repeat; width: 30px; height: 30px; border: none; float: left; border-radius: 0px 0 0 0px; } .option_base_small:hover { cursor: pointer; background: url('/Images/ic_base2.png') 8px 8px no-repeat #322F31; } .option_base_select_small { background: url('/Images/ic_base2.png') 8px 8px no-repeat #322F31; width: 30px; height: 30px; border: none; float: left; border-radius: 0px 0 0 0px; } .option_detail_small { background: url('/Images/ic_detail1.png') 6px 8px no-repeat; width: 30px; height: 30px; border: none; border-radius: 0 0px 0px 0; } .option_detail_small:hover { cursor: pointer; background: url('/Images/ic_detail2.png') 6px 8px no-repeat #322F31; } .option_detail_select_small { background: url('/Images/ic_detail2.png') 6px 8px no-repeat #322F31; width: 30px; height: 30px; border: none; float: left; border-radius: 0 0px 0px 0; } /*================================Common. Control=====================================*/ /* CSS FOR dropdownlist */ .lable { padding-top: 5px; float: left; white-space: nowrap; color: #322F31; } .select_label { position: relative; } .select_label:before { right: 7px; top: -1px; background: #fff; width: 20px; height: 20px; content: ''; position: absolute; pointer-events: none; display: block; } .select_label:after { content: ''; font: 25px "Consolas", monospace; color: #babcbc; right: 10px; bottom: -3px; width: 20px; height: 20px; position: absolute; pointer-events: none; background: url('/Images/iconArrow.png') no-repeat 0px 0px #fff; } select { padding-right: 18px; } select { padding: 5px 5px 5px 15px; margin: 0; width: 50%; font-size: 15px; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; background: #fff; color: #babcbc; outline: none; cursor: pointer; border: 1px solid #f4f4f4; } select .dropDown { position: absolute; top: 40px; left: 0; width: 100%; border: 1px solid #32333b; border-width: 0 1px 1px; list-style: none; -moz-box-sizing: border-box; -webkit-box-sizing: border-box; box-sizing: border-box; } /*end dropdownlist*/ /*3.control.gridview*/ .grid_box { margin: 20px 0; padding: 0px 25px; } #blsd { border: 0px solid #eee; border-radius: 0px; background: #fff; border-top: 0px solid #f9994c; } /*================CHI TIẾT ĐỒ ÁN BEGIN===================================*/ #blsd_padding { padding: 10px 25px 25px 25px; font-size: 16px; word-wrap: break-word; } #blsd_padding tr { display: list-item; list-style: none; padding-top: 20px; } tr.trdssvbc * { white-space: initial !important; } #tblda #trHome td { display: inline-block; } #tblda tr.success th,#tblda tr.success td { display: inline-block; } textarea#Content { width: 600px; height: 100px; border: 1px solid #ddd; font-size: 16px; font-family: 'Open Sans', sans-serif; padding: 10px; border-radius: 3px; } fieldset { border: 1px solid #ddd; } input[type="file"] { /* background: #fff !important; */ opacity: 0.8; padding: 5px 0px; } #trHome { display: inline-block; color: #322F31; width: 635px; height: 50px; /* padding: 0px; */ /* margin: 0px; */ overflow: hidden; /* padding-left: 45px; */ font-weight: normal; /* background: url('/Images/iBooks-S3-icon.png') no-repeat 0px 20px; */ background-size: 30px auto; border-bottom: 1px solid #eee; margin-top: -13px; } tr#trHome a { text-decoration: none; color: #322F31; white-space: nowrap; } tr#trHome a:hover { text-decoration: none; color: #f7922a; } td#tdmon { width: 220px; overflow: hidden; max-width: 220px; padding-left: 30px; white-space: nowrap; text-overflow: ellipsis !important; background: url("/Images/ic_tab_white_18dp.png") no-repeat 0px center; background-size: 20px 20px; } td#tdgv { width: 150px; overflow: hidden; max-width: 150px; white-space: nowrap; text-overflow: ellipsis !important; background: url("/Images/ic_perm_contact_cal_white_18dp.png") no-repeat 0px center; background-size: 20px 20px; padding-left: 30px; } td#nbd { /* width: 175px; */ /* max-width: 175px; */ overflow: hidden; white-space: nowrap; text-overflow: ellipsis !important; background: url("/Images/ic_query_builder_white_18dp.png") no-repeat 0px center; background-size: 20px 20px; padding-left: 30px; } td#tdtendoan { font-size: 25px; color: #f7922a; font-family: font_strong; text-transform: uppercase; font-weight: 200; /* word-spacing: 2px; */ line-height: 1.2; /* margin-top: -30px !important; */ margin-bottom: 18px; } td#tdnoidung:before { content: '1.Nội Dung'; display: list-item; text-transform: uppercase; font-family: font_strong; font-size: 24px; color: #322F31; padding-bottom: 3px; margin-bottom: 15px; } td#tdyeucau:before { content: '2.Mục tiêu'; display: list-item; text-transform: uppercase; font-family: font_strong; font-size: 24px; color: #322F31; padding-bottom: 3px; margin-bottom: 15px; } td#tdketqua:before { content: '3.Kết Quả'; display: list-item; text-transform: uppercase; font-family: font_strong; font-size: 24px; color: #322F31; padding-bottom: 3px; margin-bottom: 15px; } td#tdghichu:before { content: '4.Ghi Chú'; display: list-item; text-transform: uppercase; font-family: font_strong; font-size: 24px; color: #322F31; padding-bottom: 3px; margin-bottom: 15px; } /*==================CHI TIẾT ĐỒ ÁN END*/ /*base*/ .grid_base_item { height: 170px; padding: 15px 0; overflow: hidden; position: relative; border-bottom: 3px dashed #f0e5f5; /* background: url('/Images/iconArrowRight_on.gif') no-repeat right 20px; */ } .anhdoan { width: 180px; height: 145px; border-radius: 2px; background: #fff; float: left; margin-right: 20px; overflow: hidden; border: 1px solid #f4f4f4; } .grid_base_img { width: auto; height: 145px; border-radius: 0px; background-color: white; float: left; vertical-align: middle; } .grid_base_title_link { color: #ff8401; text-decoration: none; display: block; } .grid_base_title { width: 25em; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; font-weight: bold; font-size: 17px; vertical-align: middle; margin-top: 15px; } .grid_base_title:hover { text-decoration: none; color: #ff8401; } .grid_detail_col2 { width: 190px; float: right; overflow: hidden; position: absolute; bottom: 15px; right: 0px; list-style: none; /* background: #9c0; */ text-align: left; padding: 0px 0px; color: #babcbc; } ul.grid_detail_col2.clearfix li { padding: 2px 0px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } .grid_detail_col1 { width: 235px; float: left; overflow: hidden; position: absolute; bottom: 15px; left: 225px; list-style: none; /* background: #c20000; */ padding: 0px 0px; text-align: left; color: #babcbc; } ul.grid_detail_col1.clearfix li { padding: 2px 0px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; } /* .grid_base_item:hover > .grid_base_info{ opacity: 0; -webkit-transition: opacity .25s ease-in-out; -moz-transition: opactiy .25s ease-in-out; -ms-transition: opacity .25s ease-in-out; -o-transition: opacity .25s ease-in-out; transition: opacity .25s ease-in-out; } */ .grid_base_img:hover { opacity: 0.5; -webkit-transition: opacity .25s ease-in-out; -moz-transition: opactiy .25s ease-in-out; -ms-transition: opacity .25s ease-in-out; -o-transition: opacity .25s ease-in-out; transition: opacity .25s ease-in-out; } .top_img:hover { opacity: 0.5; -webkit-transition: opacity .25s ease-in-out; -moz-transition: opactiy .25s ease-in-out; -ms-transition: opacity .25s ease-in-out; -o-transition: opacity .25s ease-in-out; transition: opacity .25s ease-in-out; } .nddalg:hover { opacity: 0.7; -webkit-transition: opacity .25s ease-in-out; -moz-transition: opactiy .25s ease-in-out; -ms-transition: opacity .25s ease-in-out; -o-transition: opacity .25s ease-in-out; transition: opacity .25s ease-in-out; } .grid_base_info { /* width: 135px; */ display: block; float: right; margin-top: 0px; /* height: 45px; */ background: #fff; } .grid_base_cate { height: 20px; overflow: hidden; color: #ff8401; text-decoration: none; font-style: italic; padding-right: 4px; position: absolute; right: 0px; white-space: nowrap; text-overflow: ellipsis; width: 190px; text-align: right; } .grid_base_view { height: 20px; overflow: hidden; float: right; color: #babcbc; margin-bottom: 5px; } .grid_base_view:after { content: ' views'; color: #babcbc; } span.grid_base_cate a { color: #ff8401; text-decoration: none; } span.grid_base_cate a:hover { color: #322F31; } /*detail*/ .grid_detai_item { overflow: hidden; padding-top: 7px; } .grid_detai_item:hover .Hover_likesave { display: block; } .grid_detail_left { width: 120px; float: left; } .grid_detail_right { width: 490px; float: right; } ul.grid_detail_col1.clearfix li a { text-decoration: none; position: relative; color: #f7922a; } ul.grid_detail_col1.clearfix li a:hover { text-decoration: none; color: #babcbc; } .grid_detail_img { width: 120px; height: 90px; margin: 10px 0; border-radius: 0px; float: left; background-image: url('/Images/img_code.jpg'); overflow: hidden; } .grid_detail_downview { width: 118px; height: 48px; border-radius: 0px; border: 1px solid #f4f4f4; color: #322F31; margin-bottom: 15px; } .grid_detail_down { width: 59px; height: 28px; font-weight: bold; background: url('/Images/ic_down.png') no-repeat 24px 7px; text-align: center; padding-top: 23px; float: left; } .grid_detail_view { width: 59px; height: 28px; font-weight: bold; background: url('/Images/ic_view.png') no-repeat 22px 9px; text-align: center; padding-top: 23px; float: right; } .grid_detail_title_link { color: #ff8401; text-decoration: none; } .grid_detail_title { margin-top: 10px; width: 490px; height: 45px; overflow: hidden; font-weight: bold; float: left; font-size: 14px; overflow: hidden; line-height: 22px; margin-bottom: 15px; } .grid_detail_title:hover { text-decoration: none; } .grid_detail_cate2 { background: url('/Images/ic_cate.png') no-repeat 2px 4px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_lang2 { background: url('/Images/ic_lang.png') no-repeat 0px 5px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; clear: both; } .grid_detail_user2 { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_img2 { width: 85px; height: 85px; float: left; margin: 5px 0px 15px 0px; border-radius: 0px; box-shadow: 1px 1px 3px #ac8f79; } .grid_detail_acc { width: 150px; float: right; margin-top: 10px; } .grid_detail_acc .info { margin-top: 5px; } .grid_detail_acc .username { color: #84c52c; font-size: 15px; font-weight: bold; text-decoration: none; } .grid_detail_acc .username:hover { text-decoration: none; } .grid_detail_copyright2 { background: url('/Images/ic_copyright.png') no-repeat 0 3px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_type2 { background: url('/Images/ic_type.png') no-repeat 1px 4px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_size2 { background: url('/Images/ic_size.png') no-repeat 1px 7px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_date2 { background: url('/Images/ic_date.png') no-repeat 0 4px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_like2 { background: url('/Images/ic_like.png') no-repeat 0 6px; padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_cate { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_user { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_copyright { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_type { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_date { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_like { padding-left: 20px; height: 25px; overflow: hidden; color: #d5c6ae; } .grid_detail_cate a, .grid_detail_user a, .grid_detail_cate2 a, .grid_detail_lang2 a, .grid_detail_user2 a { width: 140px; float: right; color: #ff8401; text-decoration: none; } .grid_detail_cate a:hover, .grid_detail_user a:hover, .grid_detail_cate2 a:hover, .grid_detail_lang2 a:hover, .grid_detail_user2 a:hover { text-decoration: none; } .grid_detail_copyright span, .grid_detail_date span, .grid_detail_type span, .grid_detail_like span { width: 140px; float: right; color: #322F31; } /*==========================================pager- phân trang==========================================================*/ .pagination { display: inline-block; padding-left: 0; margin: 30px 0; border-radius: 0px; float: right; width: 100%; background: #fff; height: 43px; max-width: 689px; border: 1px solid #dfdfdf; position: relative; display: inline-flex; } .pagination > li { display: inline; } .pagination > li > a, .pagination > li > span { position: relative; float: left; font-size: 15px; padding: 0px 10px; line-height: 43px; text-decoration: none; } .ul2 > li { display: inline-flex; } .ul2 > li > a, .ul2 > li > span { position: relative; padding: 10px 10px; font-size: 15px; text-decoration: none; } ul.ul2 { background: #fff; width: 100%; margin-right: 40px; margin-left: 10px; list-style: none; font-size: 15px; text-align: center; } .pagination > li:first-child > a, .pagination > li:first-child > span { /* border-right: 1px solid #dcdcdc; */ width: 15px; height: 43px; background: url('/Images/iconArrowLeft.gif') no-repeat center center; } .pagination > li:first-child > a:hover, .pagination > li:first-child > span:hover { /* border-right: 1px solid #dcdcdc; */ width: 15px; height: 43px; background: url('/Images/iconArrowLeft_on.gif') no-repeat center center; } /*==??==*/ .pagination > li:last-child > a, .pagination > li:last-child > span { /* border-left: 1px solid #dcdcdc; */ width: 15px; height: 43px; background: url('/Images/iconArrowRight.gif') no-repeat center center; position: absolute; right: 0px; } .pagination > li:last-child > a:hover, .pagination > li:last-child > span:hover { /* border-left: 1px solid #dcdcdc; */ width: 15px; height: 43px; background: url('/Images/iconArrowRight_on.gif') no-repeat center center; position: absolute; right: 0px; } /*===???==*/ .ul2 > li > a, .ul2 > li > span { color: #babcbc; background-color: #fff; border-color: #ddd; } .ul2 > li > a:hover, .ul2 > li > span:hover, .ul2 > li > a:focus, .ul2 > li > span:focus { color: #322F31f; background-color: #fff; border-color: #ddd; } .ul2 > .active > a, .ul2 > .active > span { z-index: 2; color: #ff8401; cursor: default; background-color: #fff; } .ul2 > .active > a:hover, .ul2 > .active > span:hover, .ul2 > .active > a:focus, .ul2 > .active > span:focus { z-index: 2; color: #ff8401; cursor: default; background-color: #fff; } .ul2 > .disabled > span, .ul2 > .disabled > a { color: #babcbc; cursor: not-allowed; background-color: #fff; } .ul2 > .disabled > span:hover, .ul2 > .disabled > span:focus, .ul2 > .disabled > a:hover, .ul2 > .disabled > a:focus { color: #322F31; cursor: not-allowed; background-color: #fff; } /*==???==*/ .pagination-lg > li > a, .pagination-lg > li > span { padding: 10px 16px; font-size: 15px; } .pagination-lg > li:first-child > a, .pagination-lg > li:first-child > span { border-top-left-radius: 6px; border-bottom-left-radius: 6px; } .pagination-lg > li:last-child > a, .pagination-lg > li:last-child > span { border-top-right-radius: 6px; border-bottom-right-radius: 6px; } .pagination-sm > li > a, .pagination-sm > li > span { padding: 5px 10px; font-size: 12px; } .pagination-sm > li:first-child > a, .pagination-sm > li:first-child > span { border-top-left-radius: 3px; border-bottom-left-radius: 3px; } .pagination-sm > li:last-child > a, .pagination-sm > li:last-child > span { border-top-right-radius: 3px; border-bottom-right-radius: 3px; } /*=================== Nút đăng đề tài ========================*/ .uploadbtn { height: 47px; border-radius: 0px; width: 300px; position: relative; background: #ff8401; display: block; } #uploadbtnlink { background: url("/Images/icm_upload2.png") no-repeat 10px 6px,url("/Images/bg_orange.jpg") repeat-x 0px 5px; color: #fff; float: left; height: 31px; width: 300px; padding-top: 15px; padding-left: 85px; text-decoration: none; font-size: 17px; border-radius: 0px; } #uploadbtnlink:hover { background: url("/Images/icm_upload2.png") no-repeat 10px 6px,url("/Images/uphv.png") no-repeat 0px 5px; } /*==============breadcrumbs=========*/ .breadcrumbs { height: 45px; width: 100%; background: #fff; border-bottom: 1px solid #eee; display: none; } ul.navigate-content { height: 45px; position: relative; display: inline-block; zoom: 1; padding: 0px 5px; width: 98%; overflow: hidden; margin-top: 0px; line-height: 45px; } ul.navigate-content li:first-child { background: none; padding-left: 0; } ul.navigate-content li { float: left; padding: 0 10px 0 30px; font-size: 111%; text-transform: uppercase; background: url("/Images/bull_navigation.png") no-repeat 10px 15px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden; position: relative; margin: 0px 0; line-height: 45px; overflow: hidden; font-family: arial, sans-serif; } ul.navigate-content li a { text-transform: uppercase; position: relative; color: #322F31; font-weight: 400; display: block; text-decoration: none; } ul.navigate-content li:hover a { color: #000; } ul.navigate-content li.active a { font-weight: bold; color: #474747; } /*DAng De Tai*/ .thumbnail { display: block; width: 150px; height: 200px; cursor: pointer; background-color: rgba(0,178,178,.7); } .thumbnail-icon { margin: 0 auto; } /*DSSV THAM GIA*/ ul.dssvtg { list-style: none; margin-left: 0px; padding-left: 0px; } a.btn.btn-primary.btn-sm.btn-flat { color: #f7922a; text-decoration: none; } a.btn.btn-primary.btn-sm.btn-flat:hover { color: #322F31; text-decoration: underline; } /*MENU BEN PHAI*/ .menubenphai { position: relative; float: right; z-index: 9999; text-align: center; font-size: 20px; color: #f7922a; min-height: 100%; display: block; right: 0; } ul.menubenphai { margin: 0; padding: 0; height: 100%; position: relative; } .menubenphai>ul { /* margin-top: 25px; */ padding: 0; margin: 0; height: 100%; /* display: block; */ } ul.menubenphai>li { display: inline-block; margin: 0 5px; height: 100%; } ul.menubenphai > li { /* display: none; */ margin: 0 5px; /* height: 60px; */ line-height: 60px; float: left; } li.userprofile img { width: 100px; height: 100px; position: relative; top: 15px; box-sizing: border-box; border-radius: 50%; text-align: center; border: 8px solid #DD770E; } li.userprofile h3 { /* float: right; */ text-decoration: none; /* margin: 0; */ margin-top: 0; } li.userprofile h2 { margin-bottom: 0; } input#dropdown-user:checked ~ .dropdown-menu { display: block; margin-top: -2px; padding-top: 0; } label[for="dropdown-user"] { cursor: pointer; } .ntk { /* position: absolute; */ /* width: 205px; */ /* right: 0px; */ z-index: 9999; /* display: none; */ } ul.dropdown-menu li.anhviet { margin-top: 5px; line-height: initial; } .anhviet a { text-decoration: none; color: #f7922a; padding: 5px 5px; } /*TIMKIEM*/ input { outline: none; } input[type=search] { -webkit-appearance: textfield; -webkit-box-sizing: content-box; font-family: inherit; font-size: 100%; } input::-webkit-search-decoration, input::-webkit-search-cancel-button { display: none; } input[type=search] { background: url('/Images/iconSearch.png') no-repeat 9px center; border: solid 1px transparent; padding: 9px 10px 9px 35px; width: 55px; -webkit-border-radius: 6px; -moz-border-radius: 6px; border-radius: 6px; -webkit-transition: all .5s; -moz-transition: all .5s; transition: all .5s; } input[type=search]:focus { width: 130px; border: 1px solid #f7922a; } input:-moz-placeholder { color: #babcbc; } input::-webkit-input-placeholder { color: #babcbc; } /* Demo 2 */ .menubenphai input[type=search] { width: 0px; color: transparent; cursor: pointer; position: absolute; right: -32px; top: 8px; /* margin-left: 30px; */ } .menubenphai input[type=search]:hover { background-color: #fff; } .menubenphai input[type=search]:focus { width: 250px; padding-right: 35px; color: #babcbc; background-color: #fff; cursor: auto; } .menubenphai input:-moz-placeholder { color: #babcbc; } .menubenphai input::-webkit-input-placeholder { color: #babcbc; } /*đăng nhập*/ #over { display: none; background: #000; position: fixed; left: 0; top: 0; width: 100%; height: 100%; opacity: 0.8; z-index: 999; } li.login { display: inline; } li.login a { display: inline; } .login .textdangnhap { font-size: 20px; padding-left: 130px; line-height: 50px; font-family: 'Open Sans', sans-serif; color: #f7922a; text-transform: uppercase; } .login .login_title { color: white; font-size: 16px; padding: 8px 0 5px 8px; text-align: left; } .login-content label { display: block; padding-bottom: 14px; } .login-content span { display: block; } .login-content .username span { padding-bottom: 7px; } .login-content .password span { padding-bottom: 7px; } .login-content { margin-left: 0px; margin-right: 0px; margin-bottom: 0px; margin-top: 5px; overflow: hidden; height: 180px; position: relative; } .login2 { margin: 0px 25px; overflow: hidden; } .img-close { float: right; margin-top: 10px; margin-right: 10px } .button { display: inline-block; width: 46px; text-align: center; color: #444; font-size: 14px; font-weight: bold; height: 36px; padding: 0px 8px; line-height: 36px; border-radius: 4px; transition: all 0.218s ease 0s; border: 1px solid #DCDCDC; background-color: #F5F5F5; background-image: -moz-linear-gradient(center top , #F5F5F5, #F1F1F1); cursor: pointer; margin-left: 120px !important; } .button:hover { border: 1px solid #DCDCDC; text-decoration: none; -moz-box-shadow: 0 1px 1px rgba(0,0,0,0.1); -webkit-box-shadow: 0 1px 1px rgba(0,0,0,0.1); box-shadow: 0 2px 2px rgba(0,0,0,0.1); } .login input { border: 1px solid #f4f4f4; color: black; height: 40px; padding: 0px 15px; word-spacing: 0.1em; width: 298px; font-size: 15px; margin: 5px 0px; } .submit-button { display: inline-block; padding: auto; margin: 15px 75px; width: 150px; } input.nutdn { position: absolute; bottom: 0px; left: 0px; margin: 0; padding: 0; width: 100%; background: #f7922a; height: 50px; border: none; color: #fff; font-size: 16px; cursor: pointer; } input.nutdn:hover { background: #f7822a } .login-content ul { list-style: none; margin: 0 auto; padding-left: 140px !important; } .login-content ul li { float: left; padding-right: 35px; } .login-content ul li a { text-decoration: none; color: #f7922a; } .login-content ul li a:hover { color: #322F31; } a.login-window { /* position: absolute; */ /* right: 0px; */ /* top: 3px; */ text-decoration: none; color: #f7922a; background: url('/Images/ic_account_circle_white_18dp.png') no-repeat 0px center; background-size: 19px; line-height: 30px; padding-left: 30px; font-size: 15px; } /*đăng nhập*/ td.action a { color: #fff; background: #f7922a; padding: 10px 40px; border-radius: 3px; text-decoration: none; font-weight: bold; margin-right: 20px; } td.action a:hover { background: #f75000; } input[type="button"] { width: 377px; background: #f7922a; padding: 0px; margin: 20px 0px; line-height: 40px; height: 40px; color: #fff; font-weight: bold; font-size: 14px; cursor: pointer; } li.lithoat { /* position: absolute; */ /* top: 10px; */ /* right: 0px; */ } .taikhoan { /* background: #9c0; */ position: relative; /* right: 0px; */ /* top: 0; */ color: #f7922a; margin-top: 3px; } .taikhoan a { text-decoration: none; color: #f7922a; font-size: 15px; line-height: 24px; } #liusername .username img { border-radius: 50%; width: 2em; height: 2em; position: relative; top: 11px; /* bottom: 30px; */ vertical-align: top; } #liusername .username strong { display: inline-block; vertical-align: middle; } .taikhoan ul { margin: 0; padding: 0; list-style: none; float: left; } .taikhoan ul li { /* display: inline-block; */ line-height: 30px; } #dropdown-messager:checked ~ .dropdown-menu { display: block; } ul.dropdown-menu.dropdown-menu-right li { border-bottom: 1px solid #fff; color: white; box-sizing: border-box; } .noactive h4, .noactive p { color: #333333; } .menu li.noactive { background-color: rgb(253, 239, 216); } ul.dropdown-menu { color: white; background-color: rgb(246, 162, 21); margin: 0; padding: 0; line-height: initial; } label[for="dropdown-messager"] { cursor: pointer; position: relative; display: block; color: #f7922a; } span#ms-count { border-radius: 50%; background-color: #5cb85c; position: absolute; top: 10px; font-size: 10px; font-weight: normal; width: 15px; height: 15px; line-height: 1em; text-align: center; padding: 2px; color: white; box-sizing: border-box; } .dssvtg ul li { list-style: none; } li.userprofile { list-style: none; /* margin-right: 20px; */ /* margin-top: 20px; */ /* float: left; */ text-align: center; background-color: #f7922a; } ul.dssvtg { list-style: none; padding-left: 0px; } ul.dssvtg li { display: inline-block; } td.tddssvbc { padding: 0; margin: 0; } tr.trdssvbc { /* background: #9c0; */ /* margin-top: -30px; */ /* display: block; */ } /*them moi*/ img.img-circle { border-radius: 50%; } input.btn.btn-default { border: 1px solid #f7922a; padding: 8px 30px; border-radius: 2px; cursor: pointer; background: #f7922a; color: #fff; font-weight: bold; } input.btn.btn-default:hover { background: #f7722a; color: #fff; } ul.list-group { list-style: none; margin-left: 0px; padding-left: 0px; /* background: #9c0; */ } li.panel.panel-default { background: #fff; border: 1px solid #eee; margin: 30px 0px; border-radius: 2px; } span.vote_td a { text-decoration: none; } header.panel-heading.clearfix { background: #f7f7f7; padding: 5px 0px; } .pull-left { float: left; padding: 5px 10px; } .pull-right { float: right; /* padding: 5px 20px; */ } .pull-right span strong { font-weight: normal; } section.panel-body { padding: 5px 20px; border-top: 1px solid #f4f4f4; } section.panel-body p { /* white-space: pre-wrap; */ word-wrap: break-word; } footer.panel-footer { background: #f7f7f7; padding: 5px 20px; } div#baocaowg { margin-top: 40px; } .pull-left strong { color: #322F31; font-weight: normal; } .hscn { padding: 20px 10px; } .dangdoanmoi legend { display: none; } .suadoanmoi fieldset,.dangdoanmoi fieldset { border: none; margin-top: 5px; margin: 0px; padding: 0px; overflow: hidden; } .suadoanmoi legend ,.dangdoanmoi legend { display: none; } img.img-thumbnail { border: 1px solid #f4f4f4; } .dangdoanmoi .editor-label,.suadoanmoi .editor-label { padding: 5px 0px; margin-top: 20px; color: #f7922a; font-weight: bold; font-size: 16px; text-transform: uppercase; } .dangdoanmoi .editor-field input,.suadoanmoi .editor-field input { /* background: #9c0; */ height: 25px; border: 1px solid #f4f4f4; width: 50%; } .dangdoanmoi input#Title,.suadoanmoi input#Title { width: 615px; padding: 5px 10px; border-radius: 2px; border: 1px solid #f4f4f4; } .dangdoanmoi img.img-thumbnail,.suadoanmoi img.img-thumbnail { border: 1px solid #f4f4f4; width: 180px; height: 145px; border-radius: 3px; } .dangdoanmoi input[type="submit"],.suadoanmoi input[type="submit"] { background: #f7922a; border: 1px solid #f7922a; color: #fff; padding: 10px 40px; border-radius: 3px; font-size: 15px; font-weight: bold; margin-top: 20px; cursor: pointer; } .dangdoanmoi input[type="submit"]:hover,.suadoanmoi input[type="submit"]:hover { background: #f7722a; } .dangdoanmoi textarea,.suadoanmoi textarea { border: 1px solid #f4f4f4; width: 615px; height: 100px; padding: 10px; font-size: 15px; border-radius: 2px; font-family: 'Open Sans', sans-serif; } .dangdoanmoi a { color: #f7922a; text-decoration: none; } .suadoanmoi a { color: #f7922a; text-decoration: none; } .hscn .display-label { color: #f7922a; margin: 5px 0px; font-weight: bold; } .hscn img.avatar.img-rounded { border-radius: 70px; } .clwbc { margin-left: -25px; margin-right: -25px; background: #f9f9f9; border-bottom: 1px solid #f0f0f0; border-top: 1px solid #f0f0f0; padding: 20px 25px; } .clwbc fieldset { border: none; padding: 0; margin: 0; } .clwbc textarea#Content { width: 620px; } .clwbc h3 { color: #f7922a; text-transform: uppercase; font-family: font_strong; font-size: 26px; font-weight: normal; } div#baocaowg h3 { color: #f7922a; text-transform: uppercase; font-family: font_strong; font-size: 26px; font-weight: normal; } .hsgvgv h3,.hshshs h3 { margin-top: -5px; color: #322F31; font-size: 18px; padding-left: 40px; line-height: 48px; font-weight: normal; background: url('/Images/ic_account_circle_white_18dp.png') no-repeat 0px center; background-size: 30px auto; text-transform: uppercase; border-bottom: 1px solid #f4f4f4; } .dangdoanmoi h3 { margin-top: -5px; color: #322F31; font-size: 18px; padding-left: 40px; line-height: 48px; font-weight: normal; background: url('/Images/ic_cloud_upload_grey600_24dp.png') no-repeat 0px center; background-size: 28px auto; text-transform: uppercase; border-bottom: 1px solid #f4f4f4; } .suadoanmoi h3 { margin-top: -5px; color: #322F31; font-size: 18px; padding-left: 40px; line-height: 48px; font-weight: normal; background: url('/Images/ic_mode_edit_grey600_36dp.png') no-repeat 0px center; background-size: 24px auto; text-transform: uppercase; border-bottom: 1px solid #f4f4f4; } footer.panel-footer a { text-decoration: none; color: #f7922a; /* background: url('/Images/ic_attachment_black_18dp.png') no-repeat 0px center; */ /* padding-left: 25px; */ } .ghtdkht { width: 600px; overflow: hidden; height: 20px; white-space: nowrap; text-overflow: ellipsis; color: #f7922a; } .trolaict:hover { background: #f7722a; } .trolaict { margin-top: -40px; background: #f7922a; width: 112px; height: 40px; line-height: 40px; padding: 0px 30px; border-radius: 2px; margin-left: 135px; color: #fff; } .trolaict a { color: #fff; font-weight: bold; font-size: 15px; display: inline; } a.username { display: block; height: 60px; position: relative; line-height: 60px; text-decoration: none; color: #f7922a; } li#liusername { float: left; position: relative; } a.halo { background: url('/images/logoff.png') no-repeat 0px 0px; width: 17px; background-size: 17px; /* line-height: 38px; */ /* margin-top: -10px !important; */ /* margin-left: 5px; */ /* text-indent: -9999px; */ display: inline-block; } .center-block { display: block; margin-right: auto; margin-left: auto; } .pull-right { float: right !important; } .btn-xacnhan a { padding: 0 20px 20px 0; } .pull-left { float: left !important; } .hide { display: none !important; } .show { display: block !important; } .invisible { visibility: hidden; } .text-hide { font: 0/0 a; color: transparent; text-shadow: none; background-color: transparent; border: 0; } .hidden { display: none; } .affix { position: fixed; } /*THONG BAO + TIN NHAN*/ .dropup, .dropdown { position: relative; } .dropdown-toggle:focus { outline: 0; } .dropdown-menu { position: absolute; top: 100%; left: 0; z-index: 1000; display: none; float: left; min-width: 160px; padding: 5px 0; margin: 2px 0 0; font-size: 14px; text-align: left; list-style: none; background-color: #fff; -webkit-background-clip: padding-box; background-clip: padding-box; /* border: 1px solid #ccc; */ /* border: 1px solid rgba(0, 0, 0, .15); */ /* border-radius: 4px; */ -webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, .175); box-shadow: 0 6px 12px rgba(0, 0, 0, .175); } .dropdown-menu:after { bottom: 100%; right: 10px; border: solid transparent; content: " "; height: 0; width: 0; position: absolute; pointer-events: none; border-color: rgba(255, 255, 255, 0); border-bottom-color: rgb(247, 146, 42); border-width: 10px; margin-left: -10px; } #liusername .dropdown-menu:after { right: 20%; } #messager .dropdown-menu:after { right: 2px; } .dropdown-menu.pull-right { right: 0; left: auto; } .dropdown-menu .divider { height: 1px; margin: 9px 0; overflow: hidden; background-color: #e5e5e5; } .dropdown-menu > li > a { display: block; padding: 3px 20px; clear: both; font-weight: normal; line-height: 1.42857143; color: #333; white-space: nowrap; position: relative; text-decoration: none; } .userprofile h2, .userprofile h3 { color: #ddd; } li.anhviet a { display: inline; clear: none; } a.anh { float: right; } a.viet { float: left; /* width: 50%; */ } a.viet img { /* width: 100%; */ /* height: 100%; */ } .dropdown-menu > li > a:hover, .dropdown-menu > li > a:focus { color: #262626; text-decoration: none; /* background-color: #f5f5f5; */ } .dropdown-menu > li.profile > a:hover, .dropdown-menu > li.profile > a:focus { background-color: transparent; } .dropdown-menu > .active > a, .dropdown-menu > .active > a:hover, .dropdown-menu > .active > a:focus { color: #fff; text-decoration: none; background-color: #337ab7; outline: 0; } .dropdown-menu > .disabled > a, .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { color: #777; } .dropdown-menu > .disabled > a:hover, .dropdown-menu > .disabled > a:focus { text-decoration: none; cursor: not-allowed; background-color: transparent; background-image: none; filter: progid:DXImageTransform.Microsoft.gradient(enabled = false); } .open > .dropdown-menu { display: block; } .open > a { outline: 0; } .dropdown-menu-right { right: 0; left: auto; } .dropdown-menu-left { right: auto; left: 0; } .dropdown-header { display: block; padding: 3px 20px; font-size: 12px; line-height: 1.42857143; color: #777; white-space: nowrap; } .dropdown-backdrop { position: fixed; top: 0; right: 0; bottom: 0; left: 0; z-index: 990; } .pull-right > .dropdown-menu { right: 0; left: auto; } .dropup .caret, .navbar-fixed-bottom .dropdown .caret { content: ""; border-top: 0; border-bottom: 4px solid; } .dropup .dropdown-menu, .navbar-fixed-bottom .dropdown .dropdown-menu { top: auto; bottom: 100%; margin-bottom: 2px; } @media (min-width: 768px) { .navbar-right .dropdown-menu { right: 0; left: auto; } .navbar-right .dropdown-menu-left { right: auto; left: 0; } } @font-face { font-family: 'Glyphicons Halflings'; src: url('../fonts/glyphicons-halflings-regular.eot'); src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff2') format('woff2'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg'); } .glyphicon { position: relative; top: 1px; display: inline-block; font-family: 'Glyphicons Halflings'; font-style: normal; font-weight: normal; line-height: 1; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; } span.glyphicon.glyphicon-time { margin-right: 3px; } #liusername span.glyphicon { color: white; } .thoat span.glyphicon { font-size: x-large; top: 0; } .thoat { text-align: center; } .thoat { } .glyphicon-asterisk:before { content: "\2a"; } .glyphicon-plus:before { content: "\2b"; } .glyphicon-euro:before, .glyphicon-eur:before { content: "\20ac"; } .glyphicon-minus:before { content: "\2212"; } .glyphicon-cloud:before { content: "\2601"; } .glyphicon-envelope:before { content: "\2709"; } .glyphicon-pencil:before { content: "\270f"; } .glyphicon-glass:before { content: "\e001"; } .glyphicon-music:before { content: "\e002"; } .glyphicon-search:before { content: "\e003"; } .glyphicon-heart:before { content: "\e005"; } .glyphicon-star:before { content: "\e006"; } .glyphicon-star-empty:before { content: "\e007"; } .glyphicon-user:before { content: "\e008"; } .glyphicon-film:before { content: "\e009"; } .glyphicon-th-large:before { content: "\e010"; } .glyphicon-th:before { content: "\e011"; } .glyphicon-th-list:before { content: "\e012"; } .glyphicon-ok:before { content: "\e013"; } .glyphicon-remove:before { content: "\e014"; } .glyphicon-zoom-in:before { content: "\e015"; } .glyphicon-zoom-out:before { content: "\e016"; } .glyphicon-off:before { content: "\e017"; } .glyphicon-signal:before { content: "\e018"; } .glyphicon-cog:before { content: "\e019"; } .glyphicon-trash:before { content: "\e020"; } .glyphicon-home:before { content: "\e021"; } .glyphicon-file:before { content: "\e022"; } .glyphicon-time:before { content: "\e023"; } .glyphicon-road:before { content: "\e024"; } .glyphicon-download-alt:before { content: "\e025"; } .glyphicon-download:before { content: "\e026"; } .glyphicon-upload:before { content: "\e027"; } .glyphicon-inbox:before { content: "\e028"; } .glyphicon-play-circle:before { content: "\e029"; } .glyphicon-repeat:before { content: "\e030"; } .glyphicon-refresh:before { content: "\e031"; } .glyphicon-list-alt:before { content: "\e032"; } .glyphicon-lock:before { content: "\e033"; } .glyphicon-flag:before { content: "\e034"; } .glyphicon-headphones:before { content: "\e035"; } .glyphicon-volume-off:before { content: "\e036"; } .glyphicon-volume-down:before { content: "\e037"; } .glyphicon-volume-up:before { content: "\e038"; } .glyphicon-qrcode:before { content: "\e039"; } .glyphicon-barcode:before { content: "\e040"; } .glyphicon-tag:before { content: "\e041"; } .glyphicon-tags:before { content: "\e042"; } .glyphicon-book:before { content: "\e043"; } .glyphicon-bookmark:before { content: "\e044"; } .glyphicon-print:before { content: "\e045"; } .glyphicon-camera:before { content: "\e046"; } .glyphicon-font:before { content: "\e047"; } .glyphicon-bold:before { content: "\e048"; } .glyphicon-italic:before { content: "\e049"; } .glyphicon-text-height:before { content: "\e050"; } .glyphicon-text-width:before { content: "\e051"; } .glyphicon-align-left:before { content: "\e052"; } .glyphicon-align-center:before { content: "\e053"; } .glyphicon-align-right:before { content: "\e054"; } .glyphicon-align-justify:before { content: "\e055"; } .glyphicon-list:before { content: "\e056"; } .glyphicon-indent-left:before { content: "\e057"; } .glyphicon-indent-right:before { content: "\e058"; } .glyphicon-facetime-video:before { content: "\e059"; } .glyphicon-picture:before { content: "\e060"; } .glyphicon-map-marker:before { content: "\e062"; } .glyphicon-adjust:before { content: "\e063"; } .glyphicon-tint:before { content: "\e064"; } .glyphicon-edit:before { content: "\e065"; } .glyphicon-share:before { content: "\e066"; } .glyphicon-check:before { content: "\e067"; } .glyphicon-move:before { content: "\e068"; } .glyphicon-step-backward:before { content: "\e069"; } .glyphicon-fast-backward:before { content: "\e070"; } .glyphicon-backward:before { content: "\e071"; } .glyphicon-play:before { content: "\e072"; } .glyphicon-pause:before { content: "\e073"; } .glyphicon-stop:before { content: "\e074"; } .glyphicon-forward:before { content: "\e075"; } .glyphicon-fast-forward:before { content: "\e076"; } .glyphicon-step-forward:before { content: "\e077"; } .glyphicon-eject:before { content: "\e078"; } .glyphicon-chevron-left:before { content: "\e079"; } .glyphicon-chevron-right:before { content: "\e080"; } .glyphicon-plus-sign:before { content: "\e081"; } .glyphicon-minus-sign:before { content: "\e082"; } .glyphicon-remove-sign:before { content: "\e083"; } .glyphicon-ok-sign:before { content: "\e084"; } .glyphicon-question-sign:before { content: "\e085"; } .glyphicon-info-sign:before { content: "\e086"; } .glyphicon-screenshot:before { content: "\e087"; } .glyphicon-remove-circle:before { content: "\e088"; } .glyphicon-ok-circle:before { content: "\e089"; } .glyphicon-ban-circle:before { content: "\e090"; } .glyphicon-arrow-left:before { content: "\e091"; } .glyphicon-arrow-right:before { content: "\e092"; } .glyphicon-arrow-up:before { content: "\e093"; } .glyphicon-arrow-down:before { content: "\e094"; } .glyphicon-share-alt:before { content: "\e095"; } .glyphicon-resize-full:before { content: "\e096"; } .glyphicon-resize-small:before { content: "\e097"; } .glyphicon-exclamation-sign:before { content: "\e101"; } .glyphicon-gift:before { content: "\e102"; } .glyphicon-leaf:before { content: "\e103"; } .glyphicon-fire:before { content: "\e104"; } .glyphicon-eye-open:before { content: "\e105"; } .glyphicon-eye-close:before { content: "\e106"; } .glyphicon-warning-sign:before { content: "\e107"; } .glyphicon-plane:before { content: "\e108"; } .glyphicon-calendar:before { content: "\e109"; } .glyphicon-random:before { content: "\e110"; } .glyphicon-comment:before { content: "\e111"; } .glyphicon-magnet:before { content: "\e112"; } .glyphicon-chevron-up:before { content: "\e113"; } .glyphicon-chevron-down:before { content: "\e114"; } .glyphicon-retweet:before { content: "\e115"; } .glyphicon-shopping-cart:before { content: "\e116"; } .glyphicon-folder-close:before { content: "\e117"; } .glyphicon-folder-open:before { content: "\e118"; } .glyphicon-resize-vertical:before { content: "\e119"; } .glyphicon-resize-horizontal:before { content: "\e120"; } .glyphicon-hdd:before { content: "\e121"; } .glyphicon-bullhorn:before { content: "\e122"; } .glyphicon-bell:before { content: "\e123"; } .glyphicon-certificate:before { content: "\e124"; } .glyphicon-thumbs-up:before { content: "\e125"; } .glyphicon-thumbs-down:before { content: "\e126"; } .glyphicon-hand-right:before { content: "\e127"; } .glyphicon-hand-left:before { content: "\e128"; } .glyphicon-hand-up:before { content: "\e129"; } .glyphicon-hand-down:before { content: "\e130"; } .glyphicon-circle-arrow-right:before { content: "\e131"; } .glyphicon-circle-arrow-left:before { content: "\e132"; } .glyphicon-circle-arrow-up:before { content: "\e133"; } .glyphicon-circle-arrow-down:before { content: "\e134"; } .glyphicon-globe:before { content: "\e135"; } .glyphicon-wrench:before { content: "\e136"; } .glyphicon-tasks:before { content: "\e137"; } .glyphicon-filter:before { content: "\e138"; } .glyphicon-briefcase:before { content: "\e139"; } .glyphicon-fullscreen:before { content: "\e140"; } .glyphicon-dashboard:before { content: "\e141"; } .glyphicon-paperclip:before { content: "\e142"; } .glyphicon-heart-empty:before { content: "\e143"; } .glyphicon-link:before { content: "\e144"; } .glyphicon-phone:before { content: "\e145"; } .glyphicon-pushpin:before { content: "\e146"; } .glyphicon-usd:before { content: "\e148"; } .glyphicon-gbp:before { content: "\e149"; } .glyphicon-sort:before { content: "\e150"; } .glyphicon-sort-by-alphabet:before { content: "\e151"; } .glyphicon-sort-by-alphabet-alt:before { content: "\e152"; } .glyphicon-sort-by-order:before { content: "\e153"; } .glyphicon-sort-by-order-alt:before { content: "\e154"; } .glyphicon-sort-by-attributes:before { content: "\e155"; } .glyphicon-sort-by-attributes-alt:before { content: "\e156"; } .glyphicon-unchecked:before { content: "\e157"; } .glyphicon-expand:before { content: "\e158"; } .glyphicon-collapse-down:before { content: "\e159"; } .glyphicon-collapse-up:before { content: "\e160"; } .glyphicon-log-in:before { content: "\e161"; } .glyphicon-flash:before { content: "\e162"; } .glyphicon-log-out:before { content: "\e163"; } .glyphicon-new-window:before { content: "\e164"; } .glyphicon-record:before { content: "\e165"; } .glyphicon-save:before { content: "\e166"; } .glyphicon-open:before { content: "\e167"; } .glyphicon-saved:before { content: "\e168"; } .glyphicon-import:before { content: "\e169"; } .glyphicon-export:before { content: "\e170"; } .glyphicon-send:before { content: "\e171"; } .glyphicon-floppy-disk:before { content: "\e172"; } .glyphicon-floppy-saved:before { content: "\e173"; } .glyphicon-floppy-remove:before { content: "\e174"; } .glyphicon-floppy-save:before { content: "\e175"; } .glyphicon-floppy-open:before { content: "\e176"; } .glyphicon-credit-card:before { content: "\e177"; } .glyphicon-transfer:before { content: "\e178"; } .glyphicon-cutlery:before { content: "\e179"; } .glyphicon-header:before { content: "\e180"; } .glyphicon-compressed:before { content: "\e181"; } .glyphicon-earphone:before { content: "\e182"; } .glyphicon-phone-alt:before { content: "\e183"; } .glyphicon-tower:before { content: "\e184"; } .glyphicon-stats:before { content: "\e185"; } .glyphicon-sd-video:before { content: "\e186"; } .glyphicon-hd-video:before { content: "\e187"; } .glyphicon-subtitles:before { content: "\e188"; } .glyphicon-sound-stereo:before { content: "\e189"; } .glyphicon-sound-dolby:before { content: "\e190"; } .glyphicon-sound-5-1:before { content: "\e191"; } .glyphicon-sound-6-1:before { content: "\e192"; } .glyphicon-sound-7-1:before { content: "\e193"; } .glyphicon-copyright-mark:before { content: "\e194"; } .glyphicon-registration-mark:before { content: "\e195"; } .glyphicon-cloud-download:before { content: "\e197"; } .glyphicon-cloud-upload:before { content: "\e198"; } .glyphicon-tree-conifer:before { content: "\e199"; } .glyphicon-tree-deciduous:before { content: "\e200"; } .glyphicon-cd:before { content: "\e201"; } .glyphicon-save-file:before { content: "\e202"; } .glyphicon-open-file:before { content: "\e203"; } .glyphicon-level-up:before { content: "\e204"; } .glyphicon-copy:before { content: "\e205"; } .glyphicon-paste:before { content: "\e206"; } .glyphicon-alert:before { content: "\e209"; } .glyphicon-equalizer:before { content: "\e210"; } .glyphicon-king:before { content: "\e211"; } .glyphicon-queen:before { content: "\e212"; } .glyphicon-pawn:before { content: "\e213"; } .glyphicon-bishop:before { content: "\e214"; } .glyphicon-knight:before { content: "\e215"; } .glyphicon-baby-formula:before { content: "\e216"; } .glyphicon-tent:before { content: "\26fa"; } .glyphicon-blackboard:before { content: "\e218"; } .glyphicon-bed:before { content: "\e219"; } .glyphicon-apple:before { content: "\f8ff"; } .glyphicon-erase:before { content: "\e221"; } .glyphicon-hourglass:before { content: "\231b"; } .glyphicon-lamp:before { content: "\e223"; } .glyphicon-duplicate:before { content: "\e224"; } .glyphicon-piggy-bank:before { content: "\e225"; } .glyphicon-scissors:before { content: "\e226"; } .glyphicon-bitcoin:before { content: "\e227"; } .glyphicon-btc:before { content: "\e227"; } .glyphicon-xbt:before { content: "\e227"; } .glyphicon-yen:before { content: "\00a5"; } .glyphicon-jpy:before { content: "\00a5"; } .glyphicon-ruble:before { content: "\20bd"; } .glyphicon-rub:before { content: "\20bd"; } .glyphicon-scale:before { content: "\e230"; } .glyphicon-ice-lolly:before { content: "\e231"; } .glyphicon-ice-lolly-tasted:before { content: "\e232"; } .glyphicon-education:before { content: "\e233"; } .glyphicon-option-horizontal:before { content: "\e234"; } .glyphicon-option-vertical:before { content: "\e235"; } .glyphicon-menu-hamburger:before { content: "\e236"; } .glyphicon-modal-window:before { content: "\e237"; } .glyphicon-oil:before { content: "\e238"; } .glyphicon-grain:before { content: "\e239"; } .glyphicon-sunglasses:before { content: "\e240"; } .glyphicon-text-size:before { content: "\e241"; } .glyphicon-text-color:before { content: "\e242"; } .glyphicon-text-background:before { content: "\e243"; } .glyphicon-object-align-top:before { content: "\e244"; } .glyphicon-object-align-bottom:before { content: "\e245"; } .glyphicon-object-align-horizontal:before { content: "\e246"; } .glyphicon-object-align-left:before { content: "\e247"; } .glyphicon-object-align-vertical:before { content: "\e248"; } .glyphicon-object-align-right:before { content: "\e249"; } .glyphicon-triangle-right:before { content: "\e250"; } .glyphicon-triangle-left:before { content: "\e251"; } .glyphicon-triangle-bottom:before { content: "\e252"; } .glyphicon-triangle-top:before { content: "\e253"; } .glyphicon-console:before { content: "\e254"; } .glyphicon-superscript:before { content: "\e255"; } .glyphicon-subscript:before { content: "\e256"; } .glyphicon-menu-left:before { content: "\e257"; } .glyphicon-menu-right:before { content: "\e258"; } .glyphicon-menu-down:before { content: "\e259"; } .glyphicon-menu-up:before { content: "\e260"; }
Java
/* * Copyright (C) 2014-2017 StormCore * * 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/>. */ #ifndef TRINITYCORE_TOTEM_H #define TRINITYCORE_TOTEM_H #include "TemporarySummon.h" enum TotemType { TOTEM_PASSIVE = 0, TOTEM_ACTIVE = 1, TOTEM_STATUE = 2 // copied straight from MaNGOS, may need more implementation to work }; class TC_GAME_API Totem : public Minion { public: Totem(SummonPropertiesEntry const* properties, Unit* owner); virtual ~Totem() { } void Update(uint32 time) override; void InitStats(uint32 duration) override; void InitSummon() override; void UnSummon(uint32 msTime = 0) override; uint32 GetSpell(uint8 slot = 0) const { return m_spells[slot]; } uint32 GetTotemDuration() const { return m_duration; } void SetTotemDuration(uint32 duration) { m_duration = duration; } TotemType GetTotemType() const { return m_type; } bool UpdateStats(Stats /*stat*/) override { return true; } bool UpdateAllStats() override { return true; } void UpdateResistances(uint32 /*school*/) override { } void UpdateArmor() override { } void UpdateMaxHealth() override { } void UpdateMaxPower(Powers /*power*/) override { } void UpdateAttackPowerAndDamage(bool /*ranged*/) override { } void UpdateDamagePhysical(WeaponAttackType /*attType*/) override { } bool IsImmunedToSpellEffect(SpellInfo const* spellInfo, uint32 index) const override; protected: TotemType m_type; uint32 m_duration; }; #endif
Java
#!/usr/bin/perl -w # # This script generates a C header file that maps the target device (as # indicated via the sdcc generated -Dpic18fxxx macro) to its device # family and the device families to their respective style of ADC and # USART programming for use in the SDCC PIC16 I/O library. # # Copyright 2010 Raphael Neider <rneider AT web.de> # # This file is part of SDCC. # # SDCC 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. # # SDCC 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 SDCC. If not, see <http://www.gnu.org/licenses/>. # # # Usage: perl pic18fam-h-gen.pl # # This will create pic18fam.h.gen in your current directory. # Check sanity of the file and move it to .../include/pic16/pic18fam.h. # If you assigned new I/O styles, implement them in # .../include/pic16/{adc,i2c,usart}.h and # .../lib/pic16/libio/*/*.c # use strict; my $head = '__SDCC_PIC'; my %families = (); my %adc = (); my %usart = (); my $update = "Please update your pic16/pic18fam.h manually and/or inform the maintainer."; while (<DATA>) { chomp; s/\s*#.*$//; # remove comments s/\s*//g; # strip whitespace next if (/^\s*$/); # ignore empty lines my $line = $_; my @fields = split(/:/, $line); die "Invalid record >$line<" if (4 != scalar @fields); my ($id, $memberlist, $adcstyle, $usartstyle) = @fields; # extract numeric family id $id = 0+$id; # extract family members my @arr = split(/,/, $memberlist); @arr = sort(map { uc($_); } @arr); $families{$id} = \@arr; # ADC style per device family $adcstyle = 0+$adcstyle; if (not defined $adc{$adcstyle}) { $adc{$adcstyle} = []; } # if push @{$adc{$adcstyle}}, $id; # (E)USART style per device family $usartstyle = 0+$usartstyle; if (not defined $usart{$usartstyle}) { $usart{$usartstyle} = []; } # if push @{$usart{$usartstyle}}, $id; } my $fname = "pic18fam.h.gen"; open(FH, ">", "$fname") or die "Could not open >$fname<"; print FH <<EOT /* * pic18fam.h - PIC16 families * * This file is has been generated using $0 . */ #ifndef __SDCC_PIC18FAM_H__ #define __SDCC_PIC18FAM_H__ 1 /* * Define device families. */ #undef __SDCC_PIC16_FAMILY EOT ; my $pp = "#if "; for my $id (sort keys %families) { my $list = $families{$id}; my $memb = "defined($head" . join(") \\\n || defined($head", @$list) . ")"; print FH <<EOT ${pp} ${memb} #define __SDCC_PIC16_FAMILY ${id} EOT ; $pp = "#elif "; } # for print FH <<EOT #else #warning No family associated with the target device. ${update} #endif /* * Define ADC style per device family. */ #undef __SDCC_ADC_STYLE EOT ; $pp = "#if "; for my $s (sort keys %adc) { my $fams = join (" \\\n || ", map { "(__SDCC_PIC16_FAMILY == $_)" } sort @{$adc{$s}}); print FH <<EOT ${pp} ${fams} #define __SDCC_ADC_STYLE ${s} EOT ; $pp = "#elif "; } # for print FH <<EOT #else #warning No ADC style associated with the target device. ${update} #endif /* * Define (E)USART style per device family. */ #undef __SDCC_USART_STYLE EOT ; $pp = "#if "; for my $s (sort keys %usart) { my $fams = join (" \\\n || ", map { "(__SDCC_PIC16_FAMILY == $_)" } sort @{$usart{$s}}); print FH <<EOT ${pp} ${fams} #define __SDCC_USART_STYLE ${s} EOT ; $pp = "#elif "; } # for print FH <<EOT #else #warning No (E)USART style associated with the target device. ${update} #endif EOT ; print FH <<EOT #endif /* !__SDCC_PIC18FAM_H__ */ EOT ; __END__ # # <id>:<head>{,<member>}:<adc>:<usart> # # Each line provides a colon separated list of # * a numeric family name, derived from the first family member as follows: # - 18F<num> -> printf("18%04d0", <num>) # - 18F<num1>J<num2> -> printf("18%02d%02d1", <num1>, <num2>) # - 18F<num1>K<num2> -> printf("18%02d%02d2", <num1>, <num2>) # * a comma-separated list of members of a device family, # where a family comprises all devices that share a single data sheet, # * the ADC style (numeric family name or 0, if not applicable) # * the USART style (numeric family name or 0, if not applicable) # # This data has been gathered manually from data sheets published by # Microchip Technology Inc. # 1812200:18f1220,18f1320:1812200:1812200 1812300:18f1230,18f1330:1812300:1812300 1813502:18f13k50,18f14k50:1813502:1813502 1822200:18f2220,18f2320,18f4220,18f4320:1822200:1822200 1822210:18f2221,18f2321,18f4221,18f4321:1822200:1822210 1823310:18f2331,18f2431,18f4331,18f4431:0:1822210 1823202:18f23k20,18f24k20,18f25k20,18f26k20,18f43k20,18f44k20,18f45k20,18f46k20:1822200:1822210 1823222:18f23k22,18f24k22,18f25k22,18f26k22,18f43k22,18f44k22,18f45k22,18f46k22:1823222:1822210 1824100:18f2410,18f2510,18f2515,18f2610,18f4410,18f4510,18f4515,18f4610:1822200:1822210 1802420:18f242,18f252,18f442,18f452:1802420:1822200 # TODO: verify family members and USART 1824200:18f2420,18f2520,18f4420,18f4520:1822200:1822210 1824230:18f2423,18f2523,18f4423,18f4523:1822200:1822210 1824500:18f2450,18f4450:1822200:1824500 1824550:18f2455,18f2550,18f4455,18f4550:1822200:1822210 1802480:18f248,18f258,18f448,18f458:1802420:1822200 # TODO: verify family members and USART 1824800:18f2480,18f2580,18f4480,18f4580:1822200:1824500 1824101:18f24j10,18f25j10,18f44j10,18f45j10:1822200:1822210 1824501:18f24j50,18f25j50,18f26j50,18f44j50,18f45j50,18f46j50:1824501:1824501 1825250:18f2525,18f2620,18f4525,18f4620:1822200:1822210 1825850:18f2585,18f2680,18f4585,18f4680:1822200:1824500 1826820:18f2682,18f2685,18f4682,18f4685:1822200:1824500 1865200:18f6520,18f6620,18f6720,18f8520,18f8620,18f8720:1822200:1865200 1865270:18f6527,18f6622,18f6627,18f6722,18f8527,18f8622,18f8627,18f8722:1822200:1824501 1865850:18f6585,18f6680,18f8585,18f8680:1822200:1822200 # TODO: verify family members and USART 1865501:18f65j50,18f66j50,18f66j55,18f67j50,18f85j50,18f86j50,18f86j55,18f87j50:1865501:1824501 1866601:18f66j60,18f66j65,18f67j60,18f86j60,18f86j65,18f87j60,18f96j60,18f96j65,18f97j60:1822200:1824501
Java
<?php /** * ifeelweb.de WordPress Plugin Framework * For more information see http://www.ifeelweb.de/wp-plugin-framework * * Adapter to use ZendFramework as admin application * * @author Timo Reith <timo@ifeelweb.de> * @copyright Copyright (c) ifeelweb.de * @version $Id: ZendFw.php 911603 2014-05-10 10:58:23Z worschtebrot $ * @package IfwPsn_Wp_Plugin_Application */ require_once dirname(__FILE__) . '/Interface.php'; class IfwPsn_Wp_Plugin_Application_Adapter_ZendFw implements IfwPsn_Wp_Plugin_Application_Adapter_Interface { /** * @var IfwPsn_Wp_Plugin_Manager */ protected $_pm; /** * @var IfwPsn_Zend_Application */ protected $_application; /** * @var string */ protected $_output; /** * The default error reporting level * @var int */ protected $_errorReporting; /** * @param IfwPsn_Wp_Plugin_Manager $pm */ public function __construct (IfwPsn_Wp_Plugin_Manager $pm) { $this->_pm = $pm; } /** * Loads the admin application */ public function load() { $this->_registerAutostart(); require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Zend/Application.php'; $this->_application = new IfwPsn_Zend_Application($this->_pm->getEnv()->getEnvironmet()); // set the dynamic options from php config file $this->_application->setOptions($this->_getApplicationOptions()); // run the application bootstrap $this->_pm->getLogger()->logPrefixed('Bootstrapping application...'); $this->_application->bootstrap(); } /** * */ protected function _registerAutostart() { require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Wp/Plugin/Application/Adapter/ZendFw/Autostart/EnqueueScripts.php'; require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Wp/Plugin/Application/Adapter/ZendFw/Autostart/StripSlashes.php'; require_once $this->_pm->getPathinfo()->getRootLib() . 'IfwPsn/Wp/Plugin/Application/Adapter/ZendFw/Autostart/ZendFormTranslation.php'; $result = array( new IfwPsn_Wp_Plugin_Application_Adapter_ZendFw_Autostart_EnqueueScripts($this), new IfwPsn_Wp_Plugin_Application_Adapter_ZendFw_Autostart_StripSlashes($this), new IfwPsn_Wp_Plugin_Application_Adapter_ZendFw_Autostart_ZendFormTranslation($this), ); foreach($result as $autostart) { $autostart->execute(); } } /** * Retrieves the application options * @return array */ protected function _getApplicationOptions() { $options = include $this->_pm->getPathinfo()->getRootAdminMenu() . 'configs/application.php'; if ($this->_pm->getEnv()->getEnvironmet() == 'development') { $options['resources']['FrontController']['params']['displayExceptions'] = 1; $options['phpSettings']['error_reporting'] = 6143; // E_ALL & ~E_STRICT $options['phpSettings']['display_errors'] = 1; $options['phpSettings']['display_startup_errors'] = 1; } return $options; } /** * @param $controllerName * @param string $module */ public function overwriteController($controllerName, $module = 'default') { $front = IfwPsn_Zend_Controller_Front::getInstance(); $request = new IfwPsn_Vendor_Zend_Controller_Request_Http(); $request->setParam('controller', $controllerName); $request->setParam('mod', $module); $front->setRequest($request); } /** * Inits the controller */ public function init() { $this->_activateErrorReporting(); try { // init the controller object to add actions before load-{page-id} action $this->_application->initController(); } catch (Exception $e) { $this->_handleException($e); } $this->_deactivateErrorReporting(); } /** * @return mixed|void */ public function render() { $this->_activateErrorReporting(); try { $this->_output = $this->_application->run(); } catch (Exception $e) { $this->_handleException($e); } $this->_deactivateErrorReporting(); } /** * @return mixed|void */ public function display() { $this->_activateErrorReporting(); try { echo $this->_output; } catch (Exception $e) { $this->_handleException($e); } $this->_deactivateErrorReporting(); } /** * Activates the error reporting in dev mode */ protected function _activateErrorReporting() { // store the default error level $this->_errorReporting = error_reporting(); if ($this->_pm->getEnv()->getEnvironmet() == 'development' || $this->_pm->getConfig()->debug->show_errors == '1') { // E_ALL & ~E_STRICT error_reporting(6143); } } /** * Resets the error reporting to default in dev mode */ protected function _deactivateErrorReporting() { if ($this->_pm->getEnv()->getEnvironmet() == 'development' || $this->_pm->getConfig()->debug->show_errors == '1') { error_reporting($this->_errorReporting); } } /** * @param Exception $e */ protected function _handleException(Exception $e) { $this->_pm->getLogger()->error($e->getMessage()); $request = IfwPsn_Zend_Controller_Front::getInstance()->getRequest(); // Repoint the request to the default error handler // $request->setModuleName('default'); // $request->setControllerName('Psn-ewrror'); // $request->setActionName('error'); // Set up the error handler $error = new IfwPsn_Vendor_Zend_Controller_Plugin_ErrorHandler(array( 'controller' => $this->_pm->getAbbrLower() . '-error' )); $error->type = IfwPsn_Vendor_Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER; $error->request = clone($request); $error->exception = $e; $request->setParam('error_handler', $error); } /** * @return IfwPsn_Wp_Plugin_Manager */ public function getPluginManager() { return $this->_pm; } }
Java
#ifndef _FFNet_Pattern_h_ #define _FFNet_Pattern_h_ /* FFNet_Pattern.h * * Copyright (C) 1997-2011, 2015 David Weenink * * 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. */ /* djmw 19950113 djmw 20020712 GPL header djmw 20110307 Latest modification */ #include "Pattern.h" #include "FFNet.h" void FFNet_Pattern_drawActivation( FFNet me, Pattern pattern, Graphics g, long ipattern ); #endif /* _FFNet_Pattern_h_ */
Java
/*************************************************************************** * Project TUPITUBE DESK * * Project Contact: info@maefloresta.com * * Project Website: http://www.maefloresta.com * * Project Leader: Gustav Gonzalez <info@maefloresta.com> * * * * Developers: * * 2010: * * Gustavo Gonzalez / xtingray * * * * KTooN's versions: * * * * 2006: * * David Cuadrado * * Jorge Cuadrado * * 2003: * * Fernado Roldan * * Simena Dinas * * * * Copyright (C) 2010 Gustav Gonzalez - http://www.maefloresta.com * * License: * * 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/>. * ***************************************************************************/ #ifndef TUPSOUNDPLAYER_H #define TUPSOUNDPLAYER_H #include "tglobal.h" #include "timagebutton.h" #include "tapplicationproperties.h" #include "tuplibraryobject.h" #include <QFrame> #include <QBoxLayout> #include <QSlider> #include <QLabel> #include <QSpinBox> #include <QMediaPlayer> #include <QUrl> #include <QTime> #include <QCheckBox> /** * @author Gustav Gonzalez **/ class TUPITUBE_EXPORT TupSoundPlayer : public QFrame { Q_OBJECT public: TupSoundPlayer(QWidget *parent = nullptr); ~TupSoundPlayer(); QSize sizeHint() const; void setSoundParams(TupLibraryObject *sound); void stopFile(); bool isPlaying(); void reset(); QString getSoundID() const; void updateInitFrame(int frame); void enableLipSyncInterface(bool enabled, int frame); signals: void frameUpdated(int frame); void muteEnabled(bool mute); private slots: void playFile(); void startPlayer(); void positionChanged(qint64 value); void durationChanged(qint64 value); void stateChanged(QMediaPlayer::State state); void updateSoundPos(int pos); void updateLoopState(); void muteAction(); private: QLabel *frameLabel; QMediaPlayer *player; QSlider *slider; QLabel *timer; TImageButton *playButton; TImageButton *muteButton; bool playing; qint64 duration; QTime soundTotalTime; QString totalTime; QCheckBox *loopBox; bool loop; bool mute; QSpinBox *frameBox; QWidget *frameWidget; QString soundID; }; #endif
Java
/* * arch/arm/mach-tegra/baseband-xmm-power.c * * Copyright (C) 2011 NVIDIA Corporation * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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/kernel.h> #include <linux/init.h> #include <linux/module.h> #include <linux/moduleparam.h> #include <linux/platform_device.h> #include <linux/gpio.h> #include <linux/interrupt.h> #include <linux/workqueue.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/fs.h> #include <linux/uaccess.h> #include <linux/wakelock.h> #include <linux/spinlock.h> #include <linux/usb.h> #include <linux/pm_runtime.h> #include <linux/suspend.h> #include <mach/usb_phy.h> #include "board.h" #include "devices.h" #include <mach/board_htc.h> #include <linux/pm_qos_params.h> #include <asm/mach-types.h> #include "gpio-names.h" #include "baseband-xmm-power.h" MODULE_LICENSE("GPL"); unsigned long modem_ver = XMM_MODEM_VER_1130; /* * HTC: version history * * v04 - bert_lin - 20111025 * 1. remove completion & wait for probe race, use nv solution instead * 2. add a attribute for host usb debugging * v05 - bert_lin - 20111026 * 1. sync patch from nv michael. re-arrange the first_time var * after flight off, device cant goes to L2 suspend * 2. modify the files to meet the coding style * v06 - bert_lin - 20111026 * 1. item 12: L0 -> flight -> suspend fail because of wakelock holding * check wakelock in L3 and release it if neccessary * v07 - bert_lin - 20111104 * workaround for item 18, AP L2->L0 fail! submit urb return -113 * add more logs on usb_chr for modem download issue * v08 - bert_lin - 20111125 * workaround, origin l3 -> host_wake -> deepsleep * after: L3 -> host_wakeup -> noirq suspend fail -> resume * v09 - bert_lin - 20111214 * autopm * v10 - bert_lin - 20111226 * log reduce */ /* HTC: macro, variables */ #include <mach/htc_hostdbg.h> #define MODULE_NAME "[XMM_v15]" unsigned int host_dbg_flag = 0; EXPORT_SYMBOL(host_dbg_flag); /* HTC: provide interface for user space to enable usb host debugging */ static ssize_t host_dbg_show(struct device *dev, struct device_attribute *attr, char *buf); static ssize_t host_dbg_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size); static DEVICE_ATTR(host_dbg, 0664, host_dbg_show, host_dbg_store); /* HTC: Create attribute for host debug purpose */ static ssize_t host_dbg_show(struct device *dev, struct device_attribute *attr, char *buf) { int ret = -EINVAL; ret = sprintf(buf, "%x\n", host_dbg_flag); return ret; } /** * HTC: get the runtime debug flags from user. * * @buf: user strings * @size: user strings plus one 0x0a char */ static ssize_t host_dbg_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { const int hedge = 2 + 8 + 1; /* hedge: "0x" 2 chars, max: 8 chars, plus one 0x0a char */ pr_info(MODULE_NAME "%s size = %d\n", __func__, size); if (size > hedge) { pr_info(MODULE_NAME "%s size > hedge:%d, return\n", __func__, hedge); return size; } host_dbg_flag = simple_strtoul(buf, NULL, 16); pr_info(MODULE_NAME "%s set host_dbg_flag as 0x%08x\n", __func__, host_dbg_flag); return size; } /*============================================================*/ struct pm_qos_request_list modem_boost_cpu_freq_req; EXPORT_SYMBOL_GPL(modem_boost_cpu_freq_req); #define BOOST_CPU_FREQ_MIN 1500000 EXPORT_SYMBOL(modem_ver); unsigned long modem_flash; EXPORT_SYMBOL(modem_flash); unsigned long modem_pm = 1; EXPORT_SYMBOL(modem_pm); unsigned long autosuspend_delay = 3000; /* 5000 msec */ EXPORT_SYMBOL(autosuspend_delay); unsigned long enum_delay_ms = 1000; /* ignored if !modem_flash */ module_param(modem_ver, ulong, 0644); MODULE_PARM_DESC(modem_ver, "baseband xmm power - modem software version"); module_param(modem_flash, ulong, 0644); MODULE_PARM_DESC(modem_flash, "baseband xmm power - modem flash (1 = flash, 0 = flashless)"); module_param(modem_pm, ulong, 0644); MODULE_PARM_DESC(modem_pm, "baseband xmm power - modem power management (1 = pm, 0 = no pm)"); module_param(enum_delay_ms, ulong, 0644); MODULE_PARM_DESC(enum_delay_ms, "baseband xmm power - delay in ms between modem on and enumeration"); module_param(autosuspend_delay, ulong, 0644); MODULE_PARM_DESC(autosuspend_delay, "baseband xmm power - autosuspend delay for autopm"); #define auto_sleep(x) \ if (in_interrupt() || in_atomic())\ mdelay(x);\ else\ msleep(x); static bool short_autosuspend; static int short_autosuspend_delay = 100; static struct usb_device_id xmm_pm_ids[] = { { USB_DEVICE(VENDOR_ID, PRODUCT_ID), .driver_info = 0 }, {} }; //for power on modem static struct gpio tegra_baseband_gpios[] = { { -1, GPIOF_OUT_INIT_LOW, "BB_RSTn" }, { -1, GPIOF_OUT_INIT_LOW, "BB_ON" }, { -1, GPIOF_OUT_INIT_LOW, "IPC_BB_WAKE" }, { -1, GPIOF_IN, "IPC_AP_WAKE" }, { -1, GPIOF_OUT_INIT_HIGH, "IPC_HSIC_ACTIVE" }, { -1, GPIOF_OUT_INIT_LOW, "IPC_HSIC_SUS_REQ" }, { -1, GPIOF_OUT_INIT_LOW, "BB_VDD_EN" }, { -1, GPIOF_OUT_INIT_LOW, "AP2BB_RST_PWRDWNn" }, { -1, GPIOF_IN, "BB2AP_RST2" }, }; /*HTC*/ //for power consumation , power off modem static struct gpio tegra_baseband_gpios_power_off_modem[] = { { -1, GPIOF_OUT_INIT_LOW, "BB_RSTn" }, { -1, GPIOF_OUT_INIT_LOW, "BB_ON" }, { -1, GPIOF_OUT_INIT_LOW, "IPC_BB_WAKE" }, { -1, GPIOF_OUT_INIT_LOW, "IPC_AP_WAKE" }, { -1, GPIOF_OUT_INIT_LOW, "IPC_HSIC_ACTIVE" }, { -1, GPIOF_OUT_INIT_LOW, "IPC_HSIC_SUS_REQ" }, { -1, GPIOF_OUT_INIT_LOW, "BB_VDD_EN" }, { -1, GPIOF_OUT_INIT_LOW, "AP2BB_RST_PWRDWNn" }, { -1, GPIOF_OUT_INIT_LOW, "BB2AP_RST2" }, }; static enum { IPC_AP_WAKE_UNINIT, IPC_AP_WAKE_IRQ_READY, IPC_AP_WAKE_INIT1, IPC_AP_WAKE_INIT2, IPC_AP_WAKE_L, IPC_AP_WAKE_H, } ipc_ap_wake_state = IPC_AP_WAKE_INIT2; enum baseband_xmm_powerstate_t baseband_xmm_powerstate; static struct workqueue_struct *workqueue; static struct work_struct init1_work; static struct work_struct init2_work; static struct work_struct L2_resume_work; //static struct delayed_work init4_work; static struct baseband_power_platform_data *baseband_power_driver_data; static int waiting_falling_flag = 0; static bool register_hsic_device; static struct wake_lock wakelock; static struct usb_device *usbdev; static bool CP_initiated_L2toL0; static bool modem_power_on; static bool first_time = true; static int power_onoff; static void baseband_xmm_power_L2_resume(void); static DEFINE_MUTEX(baseband_xmm_onoff_lock); #ifndef CONFIG_REMOVE_HSIC_L3_STATE static int baseband_xmm_power_driver_handle_resume( struct baseband_power_platform_data *data); #endif static bool wakeup_pending; static int uart_pin_pull_state=1; // 1 for UART, 0 for GPIO static bool modem_sleep_flag = false; //static struct regulator *endeavor_dsi_reg = NULL;//for avdd_csi_dsi static spinlock_t xmm_lock; static bool system_suspending; static int reenable_autosuspend; //ICS only static int htcpcbid=0; static struct workqueue_struct *workqueue_susp; static struct work_struct work_shortsusp, work_defaultsusp; static struct workqueue_struct *workqueue_debug; static struct work_struct work_reset_host_active; static int s_sku_id = 0; static const int SKU_ID_ENRC2_GLOBAL = 0x00034600; static const int SKU_ID_ENRC2_TMO = 0x00032900; static const int SKU_ID_ENDEAVORU = 0x0002F300; static struct kset *silent_reset_kset; static struct kobject *silent_reset_kobj; #ifndef MIN static inline int MIN( int x, int y ) { return x > y ? y : x; } #endif ssize_t debug_handler(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { if( !strncmp( buf, "0", MIN( count, strlen("0") ) ) ) { debug_gpio_dump(); } else if( !strncmp( buf, "1", MIN( count, strlen("1") ) ) ) { debug_gpio_dump(); trigger_radio_fatal_get_coredump(); } else if( !strncmp( buf, "2", MIN( count, strlen("2") ) ) ) { trigger_silent_reset("From User Space"); } else { pr_info("%s: do nothing\n", __func__); } return count; } EXPORT_SYMBOL_GPL(debug_handler); #define PRINT_GPIO(gpio,name) pr_info( "PRINT_GPIO %s <%d>", name, gpio_get_value(gpio) ) int debug_gpio_dump() { PRINT_GPIO( TEGRA_GPIO_PM4, "BB_VDD_EN" ); PRINT_GPIO( TEGRA_GPIO_PC1, "AP2BB_RST_PWRDWNn" ); PRINT_GPIO( TEGRA_GPIO_PN0, "AP2BB_RSTn" ); PRINT_GPIO( TEGRA_GPIO_PN3, "AP2BB_PWRON" ); PRINT_GPIO( TEGRA_GPIO_PN2, "BB2AP_RADIO_FATAL" ); PRINT_GPIO( TEGRA_GPIO_PN1, "IPC_HSIC_ACTIVE" ); PRINT_GPIO( TEGRA_GPIO_PV0, "HSIC_SUS_REQ" ); PRINT_GPIO( TEGRA_GPIO_PC6, "IPC_BB_WAKE" ); PRINT_GPIO( TEGRA_GPIO_PS2, "IPC_AP_WAKE" ); if(SKU_ID_ENDEAVORU != s_sku_id) { PRINT_GPIO( TEGRA_GPIO_PS5, "BB2AP_RST2" ); } return true; } EXPORT_SYMBOL_GPL(debug_gpio_dump); int trigger_radio_fatal_get_coredump(void) { #if 0 if (!reason) reason = "No Reason"; pr_info("Trigger Modem Fatal!! reason <%s>", reason); /*set BB2AP_SUSPEND_REQ Pin (TEGRA_GPIO_PV0) to OutPut High to trigger Modem fatal*/ int ret=gpio_direction_output(TEGRA_GPIO_PV0,1); if (ret < 0) pr_err("%s: set BB2AP_SUSPEND_REQ Pin to Output error", __func__); /* reset HOST_ACTIVE to notify modem since suspend req is not a wakeup source of modem. */ queue_work( workqueue_debug, &work_reset_host_active ); #else pr_info("Didn't trigger fatal for better user experience"); #endif return 0; } EXPORT_SYMBOL_GPL(trigger_radio_fatal_get_coredump); int trigger_silent_reset(char *reason) { #define MSIZE 30 char message[MSIZE] = "ResetReason="; char *envp[] = { message, NULL }; int left_size = MSIZE -1 -strlen(message); if (!reason) reason = "No Reason"; strncat(message, reason, MIN(strlen(reason),left_size)); pr_info("%s: message<%s>", __func__, message); if(silent_reset_kobj) { kobject_uevent_env( silent_reset_kobj, KOBJ_ADD, envp); } else { pr_err("%s: kobj is NULL.", __func__); } return 0; } EXPORT_SYMBOL_GPL(trigger_silent_reset); static DEVICE_ATTR(debug_handler, S_IRUSR | S_IWUSR | S_IRGRP, NULL, debug_handler); int Modem_is_6360() { return s_sku_id == SKU_ID_ENRC2_TMO; } EXPORT_SYMBOL_GPL(Modem_is_6360); int Modem_is_6260() { return ( s_sku_id == SKU_ID_ENRC2_GLOBAL || s_sku_id == SKU_ID_ENDEAVORU ); } EXPORT_SYMBOL_GPL(Modem_is_6260); int Modem_is_IMC(void) { return ( machine_is_enrc2b() || machine_is_endeavoru() || machine_is_enrc2u() ); } EXPORT_SYMBOL_GPL(Modem_is_IMC); static irqreturn_t radio_reset_irq(int irq, void *dev_id) { pr_err("%s: Radio reset detected!", __func__); debug_gpio_dump(); return IRQ_HANDLED; } #if 0 int enable_avdd_dsi_csi_power() { pr_info(MODULE_NAME "[xmm]%s\n",__func__); int ret=0; if (endeavor_dsi_reg == NULL) { endeavor_dsi_reg = regulator_get(NULL, "avdd_dsi_csi"); pr_info(MODULE_NAME "[xmm]%s regulator_getED\n",__func__); if (IS_ERR_OR_NULL(endeavor_dsi_reg)) { pr_err("dsi: Could not get regulator avdd_dsi_csi\n"); endeavor_dsi_reg = NULL; return PTR_ERR(endeavor_dsi_reg); } } ret = regulator_enable(endeavor_dsi_reg); if (ret < 0) { printk(KERN_ERR "DSI regulator avdd_dsi_csi couldn't be enabled\n",ret); } return ret; } int disable_avdd_dsi_csi_power() { pr_info(MODULE_NAME "[xmm]%s\n",__func__); int ret=0; if (endeavor_dsi_reg == NULL) { endeavor_dsi_reg = regulator_get(NULL, "avdd_dsi_csi"); pr_info(MODULE_NAME "[xmm]%s regulator_getED\n",__func__); if (IS_ERR_OR_NULL(endeavor_dsi_reg)) { pr_err("dsi: Could not get regulator avdd_dsi_csi\n"); endeavor_dsi_reg = NULL; return PTR_ERR(endeavor_dsi_reg); } } ret = regulator_disable(endeavor_dsi_reg); if (ret < 0) { printk(KERN_ERR "DSI regulator avdd_dsi_csi couldn't be disabled\n",ret); } endeavor_dsi_reg=NULL; return ret; } #endif int gpio_config_only_one(unsigned gpio, unsigned long flags, const char *label) { int err=0; if (flags & GPIOF_DIR_IN) err = gpio_direction_input(gpio); else err = gpio_direction_output(gpio, (flags & GPIOF_INIT_HIGH) ? 1 : 0); return err; } int gpio_config_only_array(struct gpio *array, size_t num) { int i, err=0; for (i = 0; i < num; i++, array++) { if( array->gpio != -1 ) { err = gpio_config_only_one(array->gpio, array->flags, array->label); if (err) goto err_free; } } return 0; err_free: //while (i--) //gpio_free((--array)->gpio); return err; } int gpio_request_only_one(unsigned gpio,const char *label) { int err = gpio_request(gpio, label); if (err) return err; else return 0; } int gpio_request_only_array(struct gpio *array, size_t num) { int i, err=0; for (i = 0; i < num; i++, array++) { if( array->gpio != -1 ) { err = gpio_request_only_one(array->gpio, array->label); if (err) goto err_free; } } return 0; err_free: while (i--) gpio_free((--array)->gpio); return err; } static int gpio_o_l_uart(int gpio, char* name) { int ret=0; pr_info(MODULE_NAME "%s ,name=%s gpio=%d\n", __func__,name,gpio); ret = gpio_direction_output(gpio, 0); if (ret < 0) { pr_err(" %s: gpio_direction_output failed %d\n", __func__, ret); gpio_free(gpio); return ret; } tegra_gpio_enable(gpio); gpio_export(gpio, true); return ret; } void modem_on_for_uart_config(void) { pr_info(MODULE_NAME "%s ,first_time=%s uart_pin_pull_low=%d\n", __func__,first_time?"true":"false",uart_pin_pull_state); if(uart_pin_pull_state==0){ //if uart pin pull low, then we put back to normal pr_info(MODULE_NAME "%s tegra_gpio_disable for UART\n", __func__); tegra_gpio_disable(TEGRA_GPIO_PJ7); tegra_gpio_disable(TEGRA_GPIO_PK7); tegra_gpio_disable(TEGRA_GPIO_PB0); tegra_gpio_disable(TEGRA_GPIO_PB1); uart_pin_pull_state=1;//set back to UART } } int modem_off_for_uart_config(void) { int err=0; pr_info(MODULE_NAME "%s uart_pin_pull_low=%d\n", __func__,uart_pin_pull_state); if(uart_pin_pull_state==1){ //if uart pin not pull low yet, then we pull them low+enable err=gpio_o_l_uart(TEGRA_GPIO_PJ7, "IMC_UART_TX"); err=gpio_o_l_uart(TEGRA_GPIO_PK7, "IMC_UART_RTS"); err=gpio_o_l_uart(TEGRA_GPIO_PB0 ,"IMC_UART_RX"); err=gpio_o_l_uart(TEGRA_GPIO_PB1, "IMC_UART_CTS"); uart_pin_pull_state=0;//chagne to gpio } return err; } int modem_off_for_usb_config(struct gpio *array, size_t num) { //pr_info(MODULE_NAME "%s 1219_01\n", __func__); int err=0; err = gpio_config_only_array(tegra_baseband_gpios_power_off_modem, ARRAY_SIZE(tegra_baseband_gpios_power_off_modem)); if (err < 0) { pr_err("%s - gpio_config_array gpio(s) for modem off failed\n", __func__); return -ENODEV; } return err; } #if 0 int modem_on_for_usb_config(struct gpio *array, size_t num) { pr_info(MODULE_NAME "%s \n", __func__); int err=0; err = gpio_config_only_array(tegra_baseband_gpios, ARRAY_SIZE(tegra_baseband_gpios)); if (err < 0) { pr_err("%s - gpio_config_array gpio(s) for modem off failed\n", __func__); return -ENODEV; } return err; } #endif int config_gpio_for_power_off(void) { int err=0; pr_info(MODULE_NAME "%s for power consumation 4st \n", __func__); #if 1 /* config baseband gpio(s) for modem off */ err = modem_off_for_usb_config(tegra_baseband_gpios_power_off_modem, ARRAY_SIZE(tegra_baseband_gpios_power_off_modem)); if (err < 0) { pr_err("%s - gpio_config_array gpio(s) for modem off failed\n", __func__); return -ENODEV; } #endif /* config uart gpio(s) for modem off */ err=modem_off_for_uart_config(); if (err < 0) { pr_err("%s - modem_off_for_uart_config gpio(s)\n", __func__); return -ENODEV; } return err; } #if 0 int config_gpio_for_power_on() { int err=0; pr_info(MODULE_NAME "%s for power consumation 4st \n", __func__); #if 1 /* config baseband gpio(s) for modem off */ err = modem_on_for_usb_config(tegra_baseband_gpios, ARRAY_SIZE(tegra_baseband_gpios)); if (err < 0) { pr_err("%s - gpio_config_array gpio(s) for modem off failed\n", __func__); return -ENODEV; } #endif /* config uart gpio(s) for modem off */ modem_on_for_uart_config(); return err; } #endif /*HTC--*/ extern void platfrom_set_flight_mode_onoff(bool mode_on); static int baseband_modem_power_on(struct baseband_power_platform_data *data) { /* HTC: called in atomic context */ int ret=0, i=0; pr_info("%s VP: 07/05 22.52{\n", __func__); if (!data) { pr_err("%s: data is NULL\n", __func__); return -1; } /* reset / power on sequence */ gpio_set_value(data->modem.xmm.bb_vdd_en, 1); /* give modem power */ auto_sleep(1); gpio_set_value(data->modem.xmm.bb_rst, 0); /* set to low first */ //pr_info("%s(%d)\n", __func__, __LINE__); for (i = 0; i < 7; i++) /* 5 ms BB_RST low */ udelay(1000); ret = gpio_get_value(data->modem.xmm.bb_rst_pwrdn); //pr_info("%s(%d) get AP2BB_RST_PWRDWNn=%d \n", __func__, __LINE__, ret); //pr_info("%s(%d) set AP2BB_RST_PWRDWNn=1\n", __func__, __LINE__); gpio_set_value(data->modem.xmm.bb_rst_pwrdn, 1); /* 20 ms RST_PWRDWNn high */ auto_sleep(25); /* need 20 but 40 is more safe */ //steven markded //pr_info("%s(%d) set modem.xmm.bb_rst=1\n", __func__, __LINE__); gpio_set_value(data->modem.xmm.bb_rst, 1); /* 1 ms BB_RST high */ auto_sleep(40); /* need 20 but 40 is more safe */ /* Use RST2 to identify if modem is powered on into boot rom. */ /* Fix issue of power leakage in ENRC2. */ if (machine_is_enrc2b() || machine_is_enrc2u()) { gpio_direction_input(data->modem.xmm.bb_rst2); } gpio_direction_input(data->modem.xmm.ipc_ap_wake); gpio_direction_input(TEGRA_GPIO_PN2); //pr_info("%s(%d) set modem.xmm.bb_on=1 duration is 60us\n", __func__, __LINE__); gpio_set_value(data->modem.xmm.bb_on, 1); /* power on sequence */ udelay(60); gpio_set_value(data->modem.xmm.bb_on, 0); //pr_info("%s(%d) set modem.xmm.bb_on=0\n", __func__, __LINE__); auto_sleep(10); //pr_info("%s:VP pm qos request CPU 1.5GHz\n", __func__); //pm_qos_update_request(&modem_boost_cpu_freq_req, (s32)BOOST_CPU_FREQ_MIN); /* Use RST2 to identify if modem is powered on into boot rom. */ /* Fix issue of power leakage in ENRC2. */ if (machine_is_enrc2b() || machine_is_enrc2u()) { int counter = 0; const int max_retry = 10; while (!gpio_get_value(data->modem.xmm.bb_rst2) && counter < max_retry) { counter++; mdelay(3); } if(counter == max_retry) pr_info("%s: Wait BB2AP_RST2 timeout.", __func__); } gpio_direction_output(data->modem.xmm.ipc_hsic_active, 1); modem_on_for_uart_config(); pr_info("%s }\n", __func__); return 0; } static int baseband_xmm_power_on(struct platform_device *device) { struct baseband_power_platform_data *data = (struct baseband_power_platform_data *) device->dev.platform_data; int ret; /* HTC: ENR#U wakeup src fix */ //int value; pr_info(MODULE_NAME "%s{\n", __func__); /* check for platform data */ if (!data) { pr_err("%s: !data\n", __func__); return -EINVAL; } if (baseband_xmm_powerstate != BBXMM_PS_UNINIT) { pr_err("%s: baseband_xmm_powerstate != BBXMM_PS_UNINIT\n", __func__); return -EINVAL; } #if 0 /*HTC*/ pr_info(MODULE_NAME " htc_get_pcbid_info= %d\n",htcpcbid ); if(htcpcbid < PROJECT_PHASE_XE) { enable_avdd_dsi_csi_power(); } #endif /* reset the state machine */ baseband_xmm_powerstate = BBXMM_PS_INIT; first_time = true; modem_sleep_flag = false; /* HTC use IPC_AP_WAKE_INIT2 */ if (modem_ver < XMM_MODEM_VER_1130) ipc_ap_wake_state = IPC_AP_WAKE_INIT1; else ipc_ap_wake_state = IPC_AP_WAKE_INIT2; /* pr_info("%s - %d\n", __func__, __LINE__); */ /* register usb host controller */ if (!modem_flash) { /* pr_info("%s - %d\n", __func__, __LINE__); */ /* register usb host controller only once */ if (register_hsic_device) { pr_info("%s(%d)register usb host controller\n", __func__, __LINE__); modem_power_on = true; if (data->hsic_register) data->modem.xmm.hsic_device = data->hsic_register(); else pr_err("%s: hsic_register is missing\n", __func__); register_hsic_device = false; } else { /* register usb host controller */ if (data->hsic_register) data->modem.xmm.hsic_device = data->hsic_register(); /* turn on modem */ pr_info("%s call baseband_modem_power_on\n", __func__); baseband_modem_power_on(data); } } if (machine_is_enrc2b() || machine_is_enrc2u()) { pr_info("%s: register BB2AP_RST2 handler", __func__); ret = request_irq( gpio_to_irq(TEGRA_GPIO_PS5), radio_reset_irq, IRQF_TRIGGER_FALLING, "RADIO_RESET", NULL ); if (ret < 0) pr_err("%s: register BB2AP_RST2 handler err <%d>", __func__, ret); } pr_info("%s: before enable irq wake", __func__); ret = enable_irq_wake(gpio_to_irq(data->modem.xmm.ipc_ap_wake)); if (ret < 0) pr_err("%s: enable_irq_wake ap_wake err <%d>", __func__, ret); ret = enable_irq_wake(gpio_to_irq(TEGRA_GPIO_PN2)); if (ret < 0) pr_err("%s: enable_irq_wake radio_fatal err <%d>", __func__, ret); if (machine_is_enrc2b() || machine_is_enrc2u()) { ret = enable_irq_wake(gpio_to_irq(TEGRA_GPIO_PS5)); if (ret < 0) pr_err("%s: enable_irq_wake radio_reset err <%d>", __func__, ret); } pr_info("%s }\n", __func__); return 0; } static int baseband_xmm_power_off(struct platform_device *device) { struct baseband_power_platform_data *data; int ret; /* HTC: ENR#U wakeup src fix */ unsigned long flags; pr_info("%s {\n", __func__); if (baseband_xmm_powerstate == BBXMM_PS_UNINIT) { pr_err("%s: baseband_xmm_powerstate != BBXMM_PS_UNINIT\n", __func__); return -EINVAL; } /* check for device / platform data */ if (!device) { pr_err("%s: !device\n", __func__); return -EINVAL; } data = (struct baseband_power_platform_data *) device->dev.platform_data; if (!data) { pr_err("%s: !data\n", __func__); return -EINVAL; } ipc_ap_wake_state = IPC_AP_WAKE_UNINIT; /* Set this flag to have proper flash-less first enumearation */ register_hsic_device = true; pr_info("%s: before disable irq wake", __func__); ret = disable_irq_wake(gpio_to_irq(data->modem.xmm.ipc_ap_wake)); if (ret < 0) pr_err("%s: disable_irq_wake ap_wake err <%d>", __func__, ret); ret = disable_irq_wake(gpio_to_irq(TEGRA_GPIO_PN2)); if (ret < 0) pr_err("%s: disable_irq_wake radio_fatal err <%d>", __func__, ret); if (machine_is_enrc2b() || machine_is_enrc2u()) { ret = disable_irq_wake(gpio_to_irq(TEGRA_GPIO_PS5)); if (ret < 0) pr_err("%s: disable_irq_wake radio_reset err <%d>", __func__, ret); pr_info("%s: before free radio_reset irq", __func__); free_irq( gpio_to_irq(TEGRA_GPIO_PS5), NULL ); if (ret < 0) pr_err("%s: free_irq radio_reset err <%d>", __func__, ret); } /* unregister usb host controller */ pr_info("%s: hsic device: %x\n", __func__, (unsigned int)data->modem.xmm.hsic_device); if (data->hsic_unregister && data->modem.xmm.hsic_device) { data->hsic_unregister(data->modem.xmm.hsic_device); data->modem.xmm.hsic_device = NULL; } else pr_err("%s: hsic_unregister is missing\n", __func__); /* set IPC_HSIC_ACTIVE low */ gpio_set_value(baseband_power_driver_data-> modem.xmm.ipc_hsic_active, 0); /* wait 20 ms */ msleep(20); /* drive bb_rst low */ //Sophia:0118:modem power down sequence: don't need to clear BB_RST //gpio_set_value(data->modem.xmm.bb_rst, 0); #ifdef BB_XMM_OEM1 //msleep(1); msleep(20); /* turn off the modem power */ gpio_set_value(baseband_power_driver_data->modem.xmm.bb_vdd_en, 0); msleep(68);//for IMC Modem discharge. #else /* !BB_XMM_OEM1 */ msleep(1); #endif /* !BB_XMM_OEM1 */ #if 1/*HTC*/ //for power consumation pr_info("%s config_gpio_for_power_off\n", __func__); config_gpio_for_power_off(); //err=config_gpio_for_power_off(); //if (err < 0) { // pr_err("%s - config_gpio_for_power_off gpio(s)\n", __func__); // return -ENODEV; //} #endif /* HTC: remove platfrom_set_flight_mode_onoff for ENR */ /* platfrom_set_flight_mode_onoff(true); */ baseband_xmm_powerstate = BBXMM_PS_UNINIT; modem_sleep_flag = false; CP_initiated_L2toL0 = false; spin_lock_irqsave(&xmm_lock, flags); wakeup_pending = false; system_suspending = false; spin_unlock_irqrestore(&xmm_lock, flags); register_hsic_device = true; //start reg process again for xmm on #if 0 /*HTC*/ pr_info(MODULE_NAME " htc_get_pcbid_info= %d\n", htcpcbid); if(htcpcbid< PROJECT_PHASE_XE) { disable_avdd_dsi_csi_power(); } #endif /*set Radio fatal Pin to OutPut Low*/ ret=gpio_direction_output(TEGRA_GPIO_PN2,0); if (ret < 0) pr_err("%s: set Radio fatal Pin to Output error\n", __func__); /*set BB2AP_SUSPEND_REQ Pin (TEGRA_GPIO_PV0) to OutPut Low*/ ret=gpio_direction_output(TEGRA_GPIO_PV0,0); if (ret < 0) pr_err("%s: set BB2AP_SUSPEND_REQ Pin to Output error\n", __func__); pr_info("%s }\n", __func__); return 0; } static ssize_t baseband_xmm_onoff(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { //int size; struct platform_device *device = to_platform_device(dev); mutex_lock(&baseband_xmm_onoff_lock); /* check input */ if (buf == NULL) { pr_err("%s: buf NULL\n", __func__); mutex_unlock(&baseband_xmm_onoff_lock); return -EINVAL; } /* pr_info("%s: count=%d\n", __func__, count); */ /* parse input */ #ifdef BB_XMM_OEM1 if (buf[0] == 0x01 || buf[0] == '1') { /* pr_info("%s: buf[0] = 0x%x\n", __func__, buf[0]); */ power_onoff = 1; } else power_onoff = 0; #else /* !BB_XMM_OEM1 */ size = sscanf(buf, "%d", &power_onoff); if (size != 1) { pr_err("%s: size=%d -EINVAL\n", __func__, size); mutex_unlock(&baseband_xmm_onoff_lock); return -EINVAL; } #endif /* !BB_XMM_OEM1 */ pr_info("%s power_onoff=%d count=%d, buf[0]=0x%x\n", __func__, power_onoff, count, buf[0]); if (power_onoff == 0) baseband_xmm_power_off(device); else if (power_onoff == 1) baseband_xmm_power_on(device); mutex_unlock(&baseband_xmm_onoff_lock); return count; } static DEVICE_ATTR(xmm_onoff, S_IRUSR | S_IWUSR | S_IRGRP, NULL, baseband_xmm_onoff); void baseband_xmm_set_power_status(unsigned int status) { struct baseband_power_platform_data *data = baseband_power_driver_data; //int value = 0; unsigned long flags; if (baseband_xmm_powerstate == status) return; pr_info(MODULE_NAME"%s{ status=%d\n", __func__,status); switch (status) { case BBXMM_PS_L0: if (modem_sleep_flag) { #ifdef CONFIG_REMOVE_HSIC_L3_STATE pr_info("%s, resume to L0 with modem_sleep_flag", __func__ ); #else pr_info("%s Resume from L3 without calling resume function\n", __func__); baseband_xmm_power_driver_handle_resume(data); #endif } pr_info("L0\n"); baseband_xmm_powerstate = status; /* HTC: don't hold the wakelock multiple times */ if (!wake_lock_active(&wakelock)) { pr_info("%s: wake_lock [%s] in L0\n", __func__, wakelock.name); #ifdef CONFIG_REMOVE_HSIC_L3_STATE wake_lock_timeout(&wakelock, HZ*2); #else wake_lock(&wakelock); //wake_lock_timeout(&wakelock, HZ * 5); #endif } if (modem_power_on) { modem_power_on = false; baseband_modem_power_on(data); } //pr_info("gpio host active high->\n"); /* hack to restart autosuspend after exiting LP0 * (aka re-entering L0 from L3) */ #if 0 //remove on 0305 if (usbdev) { struct usb_interface *intf; intf = usb_ifnum_to_if(usbdev, 0); //pr_info("%s - autopm_get - usbdev = %d - %d {\n", __func__, usbdev, __LINE__); //pr_info("%s: cnt %d intf=%p &intf->dev=%p kobje=%s\n", //__func__, atomic_read(&intf->dev.power.usage_count),intf,&intf->dev,kobject_name(&intf->dev.kobj)); if (usb_autopm_get_interface_async(intf) >= 0) { pr_info("get_interface_async succeeded" " - call put_interface\n"); //pr_info("%s - usb_put - usbdev = %d - %d {\n", __func__, usbdev, __LINE__); usb_autopm_put_interface_async(intf); //pr_info("%s - usb_put - usbdev = %d - %d {\n", __func__, usbdev, __LINE__); } else { pr_info("get_interface_async failed" " - do not call put_interface\n"); } } #endif break; case BBXMM_PS_L2: pr_info("L2 wake_unlock[%s]\n", wakelock.name); baseband_xmm_powerstate = status; spin_lock_irqsave(&xmm_lock, flags); if (wakeup_pending) { spin_unlock_irqrestore(&xmm_lock, flags); #ifdef CONFIG_REMOVE_HSIC_L3_STATE pr_info("%s: wakeup pending\n", __func__); #endif baseband_xmm_power_L2_resume(); } else { spin_unlock_irqrestore(&xmm_lock, flags); wake_unlock(&wakelock); modem_sleep_flag = true; } if (short_autosuspend && (&usbdev->dev)) { pr_info("autosuspend delay %d ms,disable short_autosuspend\n", (int)autosuspend_delay); queue_work(workqueue_susp, &work_defaultsusp); short_autosuspend = false; } #if 0 if (usbdev) { struct usb_interface *intf; intf = usb_ifnum_to_if(usbdev, 0); pr_info("%s: cnt %d intf=%p &intf->dev=%p kobje=%s\n", __func__, atomic_read(&intf->dev.power.usage_count),intf,&intf->dev,kobject_name(&intf->dev.kobj)); } #endif break; #ifndef CONFIG_REMOVE_HSIC_L3_STATE case BBXMM_PS_L3: if (baseband_xmm_powerstate == BBXMM_PS_L2TOL0) { pr_info("%s: baseband_xmm_powerstate == BBXMM_PS_L2TOL0\n", __func__); if (!gpio_get_value(data->modem.xmm.ipc_ap_wake)) { spin_lock_irqsave(&xmm_lock, flags); wakeup_pending = true; spin_unlock_irqrestore(&xmm_lock, flags); pr_info("%s: L2 race condition-CP wakeup pending\n", __func__); } } pr_info("L3\n"); baseband_xmm_powerstate = status; spin_lock_irqsave(&xmm_lock, flags); system_suspending = false; spin_unlock_irqrestore(&xmm_lock, flags); if (wake_lock_active(&wakelock)) { pr_info("L3 --- wake_unlock[%s]\n", wakelock.name); wake_unlock(&wakelock); } if (wakeup_pending == false) { gpio_set_value(data->modem.xmm.ipc_hsic_active, 0); waiting_falling_flag = 0; pr_info("gpio host active low->\n"); } break; #endif case BBXMM_PS_L2TOL0: pr_info("L2->L0\n"); spin_lock_irqsave(&xmm_lock, flags); system_suspending = false; wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); /* do this only from L2 state */ if (baseband_xmm_powerstate == BBXMM_PS_L2) { baseband_xmm_powerstate = status; //pr_info("BB XMM POWER STATE = %d\n", status); baseband_xmm_power_L2_resume(); } else goto exit_without_state_change; default: break; } baseband_xmm_powerstate = status; pr_info("BB XMM POWER STATE = %d\n", status); return; exit_without_state_change: pr_info("BB XMM POWER STATE = %d (not change to %d)\n", baseband_xmm_powerstate, status); return; } EXPORT_SYMBOL_GPL(baseband_xmm_set_power_status); irqreturn_t baseband_xmm_power_ipc_ap_wake_irq(int irq, void *dev_id) { int value; struct baseband_power_platform_data *data = baseband_power_driver_data; /* pr_info("%s\n", __func__); */ value = gpio_get_value(data->modem.xmm.ipc_ap_wake); if (ipc_ap_wake_state < IPC_AP_WAKE_IRQ_READY) { pr_err("%s - spurious irq\n", __func__); } else if (ipc_ap_wake_state == IPC_AP_WAKE_IRQ_READY) { if (!value) { pr_info("%s - IPC_AP_WAKE_INIT1" " - got falling edge\n", __func__); if (waiting_falling_flag == 0) { pr_info("%s return because irq must get the rising event at first\n", __func__); return IRQ_HANDLED; } /* go to IPC_AP_WAKE_INIT1 state */ ipc_ap_wake_state = IPC_AP_WAKE_INIT1; /* queue work */ queue_work(workqueue, &init1_work); } else { pr_info("%s - IPC_AP_WAKE_INIT1" " - wait for falling edge\n", __func__); waiting_falling_flag = 1; } } else if (ipc_ap_wake_state == IPC_AP_WAKE_INIT1) { if (!value) { pr_info("%s - IPC_AP_WAKE_INIT2" " - wait for rising edge\n", __func__); } else { pr_info("%s - IPC_AP_WAKE_INIT2" " - got rising edge\n", __func__); /* go to IPC_AP_WAKE_INIT2 state */ ipc_ap_wake_state = IPC_AP_WAKE_INIT2; /* queue work */ queue_work(workqueue, &init2_work); } } else { if (!value) { pr_info("%s - falling\n", __func__); /* First check it a CP ack or CP wake */ if (data->pin_state == 0) { /* AP L2 to L0 wakeup */ pr_info("VP: received rising wakeup ap l2->l0\n"); data->pin_state = 1; wake_up_interruptible(&data->bb_wait); } value = gpio_get_value (data->modem.xmm.ipc_bb_wake); if (value) { pr_info("cp ack for bb_wake\n"); ipc_ap_wake_state = IPC_AP_WAKE_L; return IRQ_HANDLED; } spin_lock(&xmm_lock); wakeup_pending = true; if (system_suspending) { spin_unlock(&xmm_lock); pr_info("system_suspending=1, Just set wakup_pending flag=true\n"); } else { #ifndef CONFIG_REMOVE_HSIC_L3_STATE if (baseband_xmm_powerstate == BBXMM_PS_L3) { spin_unlock(&xmm_lock); pr_info(" CP L3 -> L0\n"); pr_info("set wakeup_pending=true, wait for no-irq-resuem if you are not under LP0 yet !.\n"); pr_info("set wakeup_pending=true, wait for system resume if you already under LP0.\n"); } else #endif if (baseband_xmm_powerstate == BBXMM_PS_L2) { CP_initiated_L2toL0 = true; spin_unlock(&xmm_lock); baseband_xmm_set_power_status (BBXMM_PS_L2TOL0); } else { CP_initiated_L2toL0 = true; spin_unlock(&xmm_lock); pr_info(" CP wakeup pending- new race condition"); } } /* save gpio state */ ipc_ap_wake_state = IPC_AP_WAKE_L; } else { pr_info("%s - rising\n", __func__); value = gpio_get_value (data->modem.xmm.ipc_hsic_active); if (!value) { pr_info("host active low: ignore request\n"); ipc_ap_wake_state = IPC_AP_WAKE_H; return IRQ_HANDLED; } value = gpio_get_value (data->modem.xmm.ipc_bb_wake); if (value) { /* Clear the slave wakeup request */ gpio_set_value (data->modem.xmm.ipc_bb_wake, 0); pr_info("set gpio slave wakeup low done ->\n"); } if (reenable_autosuspend && usbdev) { struct usb_interface *intf; reenable_autosuspend = false; intf = usb_ifnum_to_if(usbdev, 0); if( NULL != intf ){ if (usb_autopm_get_interface_async(intf) >= 0) { pr_info("get_interface_async succeeded" " - call put_interface\n"); usb_autopm_put_interface_async(intf); } else { pr_info("get_interface_async failed" " - do not call put_interface\n"); } } } if (short_autosuspend&& (&usbdev->dev)) { pr_info("set autosuspend delay %d ms\n", short_autosuspend_delay); queue_work(workqueue_susp, &work_shortsusp); } modem_sleep_flag = false; baseband_xmm_set_power_status(BBXMM_PS_L0); /* save gpio state */ ipc_ap_wake_state = IPC_AP_WAKE_H; } } return IRQ_HANDLED; } EXPORT_SYMBOL(baseband_xmm_power_ipc_ap_wake_irq); static void baseband_xmm_power_reset_host_active_work(struct work_struct *work) { /* set host_active for interrupt modem */ int value = gpio_get_value(TEGRA_GPIO_PN1); pr_info("Oringial IPC_HSIC_ACTIVE =%d", value); gpio_set_value(TEGRA_GPIO_PN1,!value); msleep(100); gpio_set_value(TEGRA_GPIO_PN1,value); } static void baseband_xmm_power_init1_work(struct work_struct *work) { int value; pr_info("%s {\n", __func__); /* check if IPC_HSIC_ACTIVE high */ value = gpio_get_value(baseband_power_driver_data-> modem.xmm.ipc_hsic_active); if (value != 1) { pr_err("%s - expected IPC_HSIC_ACTIVE high!\n", __func__); return; } /* wait 100 ms */ msleep(100); /* set IPC_HSIC_ACTIVE low */ gpio_set_value(baseband_power_driver_data-> modem.xmm.ipc_hsic_active, 0); /* wait 10 ms */ msleep(10); /* set IPC_HSIC_ACTIVE high */ gpio_set_value(baseband_power_driver_data-> modem.xmm.ipc_hsic_active, 1); /* wait 20 ms */ msleep(20); #ifdef BB_XMM_OEM1 /* set IPC_HSIC_ACTIVE low */ gpio_set_value(baseband_power_driver_data-> modem.xmm.ipc_hsic_active, 0); printk(KERN_INFO"%s merge need check set IPC_HSIC_ACTIVE low\n", __func__); #endif /* BB_XMM_OEM1 */ pr_info("%s }\n", __func__); } static void baseband_xmm_power_init2_work(struct work_struct *work) { struct baseband_power_platform_data *data = baseband_power_driver_data; pr_info("%s\n", __func__); /* check input */ if (!data) return; /* register usb host controller only once */ if (register_hsic_device) { if (data->hsic_register) data->modem.xmm.hsic_device = data->hsic_register(); else pr_err("%s: hsic_register is missing\n", __func__); register_hsic_device = false; } } /* Do the work for AP/CP initiated L2->L0 */ static void baseband_xmm_power_L2_resume(void) { struct baseband_power_platform_data *data = baseband_power_driver_data; int value; unsigned long flags; pr_info("%s\n", __func__); if (!baseband_power_driver_data) return; /* claim the wakelock here to avoid any system suspend */ if (!wake_lock_active(&wakelock)) #ifdef CONFIG_REMOVE_HSIC_L3_STATE wake_lock_timeout(&wakelock, HZ*2); #else wake_lock(&wakelock); #endif modem_sleep_flag = false; spin_lock_irqsave(&xmm_lock, flags); wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); if (CP_initiated_L2toL0) { pr_info("CP L2->L0\n"); CP_initiated_L2toL0 = false; queue_work(workqueue, &L2_resume_work); #if 0 if (usbdev) { struct usb_interface *intf; intf = usb_ifnum_to_if(usbdev, 0); pr_info("%s: cnt %d intf=%p &intf->dev=%p kobje=%s\n", __func__, atomic_read(&intf->dev.power.usage_count),intf,&intf->dev,kobject_name(&intf->dev.kobj)); } #endif } else { /* set the slave wakeup request */ #ifdef CONFIG_REMOVE_HSIC_L3_STATE pr_info("AP/CP L2->L0\n"); #else pr_info("AP L2->L0\n"); #endif value = gpio_get_value(data->modem.xmm.ipc_ap_wake); if (value) { int ret=0, cptrycount=0, eresyscount=0; const int delay=200, MAXTRY=5, eredelay=3, MAX_ERETRY=100; unsigned long target_jiffies=0; data->pin_state = 0; retry_cpwake: if(cptrycount) { gpio_set_value(data->modem.xmm.ipc_bb_wake, 0); mdelay(1); debug_gpio_dump(); } target_jiffies = jiffies + msecs_to_jiffies(delay); /* wake bb */ gpio_set_value(data->modem.xmm.ipc_bb_wake, 1); retry: /* wait for cp */ pr_info("waiting for host wakeup from CP... <%d,%d>\n", cptrycount, eresyscount); ret = wait_event_interruptible_timeout( data->bb_wait, data->pin_state == 1 || (gpio_get_value(data->modem.xmm.ipc_ap_wake) == 0), MIN( (target_jiffies-jiffies), msecs_to_jiffies(delay) ) ); if (ret == 0) { pr_info("%s: wait for cp ack %d times\n", __func__, cptrycount); debug_gpio_dump(); cptrycount++; if(cptrycount == MAXTRY) { pr_err("!!AP L2->L0 Failed\n"); trigger_radio_fatal_get_coredump(); return; } goto retry_cpwake; } if (ret == -ERESTARTSYS ) { eresyscount++; pr_info("%s: caught signal, sleep and retry %d times\n", __func__, eresyscount); if(eresyscount == MAX_ERETRY) { pr_err("too many ERESTARTSYS <%d>, abort\n", eresyscount); debug_gpio_dump(); trigger_radio_fatal_get_coredump(); return; } msleep(eredelay); goto retry; } pr_info("Get gpio host wakeup low <-\n"); } else { pr_info("CP already ready\n"); } } } static void baseband_xmm_power_shortsusp(struct work_struct *work) { if (!usbdev || !&usbdev->dev) { pr_err("%s usbdev is invalid\n", __func__); return; } pm_runtime_set_autosuspend_delay(&usbdev->dev, short_autosuspend_delay); pr_info("%s set_autosuspend_delay <%d>", __func__, short_autosuspend_delay); } static void baseband_xmm_power_defaultsusp(struct work_struct *work) { if (!usbdev || !&usbdev->dev) { pr_err("%s usbdev is invalid\n", __func__); return; } pm_runtime_set_autosuspend_delay(&usbdev->dev, autosuspend_delay); //pr_info("%s set_autosuspend_delay <%d>", __func__, autosuspend_delay); } /* Do the work for CP initiated L2->L0 */ static void baseband_xmm_power_L2_resume_work(struct work_struct *work) { struct usb_interface *intf; pr_info("%s {\n", __func__); if (!usbdev) { pr_info("%s - !usbdev\n", __func__); return; } usb_lock_device(usbdev); intf = usb_ifnum_to_if(usbdev, 0); if( NULL != intf ){ if (usb_autopm_get_interface(intf) == 0) usb_autopm_put_interface(intf); } usb_unlock_device(usbdev); pr_info("} %s\n", __func__); } static void baseband_xmm_power_reset_on(void) { /* reset / power on sequence */ msleep(40); gpio_set_value(baseband_power_driver_data->modem.xmm.bb_rst, 1); msleep(1); gpio_set_value(baseband_power_driver_data->modem.xmm.bb_on, 1); udelay(40); gpio_set_value(baseband_power_driver_data->modem.xmm.bb_on, 0); } static struct baseband_xmm_power_work_t *baseband_xmm_power_work; static void baseband_xmm_power_work_func(struct work_struct *work) { struct baseband_xmm_power_work_t *bbxmm_work = (struct baseband_xmm_power_work_t *) work; pr_info("%s - work->sate=%d\n", __func__, bbxmm_work->state); switch (bbxmm_work->state) { case BBXMM_WORK_UNINIT: pr_info("BBXMM_WORK_UNINIT\n"); break; case BBXMM_WORK_INIT: pr_info("BBXMM_WORK_INIT\n"); /* go to next state */ bbxmm_work->state = (modem_flash && !modem_pm) ? BBXMM_WORK_INIT_FLASH_STEP1 : (modem_flash && modem_pm) ? BBXMM_WORK_INIT_FLASH_PM_STEP1 : (!modem_flash && modem_pm) ? BBXMM_WORK_INIT_FLASHLESS_PM_STEP1 : BBXMM_WORK_UNINIT; pr_info("Go to next state %d\n", bbxmm_work->state); queue_work(workqueue, work); break; case BBXMM_WORK_INIT_FLASH_STEP1: //pr_info("BBXMM_WORK_INIT_FLASH_STEP1\n"); /* register usb host controller */ pr_info("%s: register usb host controller\n", __func__); if (baseband_power_driver_data->hsic_register) baseband_power_driver_data->modem.xmm.hsic_device = baseband_power_driver_data->hsic_register(); else pr_err("%s: hsic_register is missing\n", __func__); break; case BBXMM_WORK_INIT_FLASH_PM_STEP1: //pr_info("BBXMM_WORK_INIT_FLASH_PM_STEP1\n"); /* [modem ver >= 1130] start with IPC_HSIC_ACTIVE low */ if (modem_ver >= XMM_MODEM_VER_1130) { pr_info("%s: ver > 1130:" " ipc_hsic_active -> 0\n", __func__); gpio_set_value(baseband_power_driver_data-> modem.xmm.ipc_hsic_active, 0); } /* reset / power on sequence */ baseband_xmm_power_reset_on(); /* set power status as on */ power_onoff = 1; /* optional delay * 0 = flashless * ==> causes next step to enumerate modem boot rom * (058b / 0041) * some delay > boot rom timeout * ==> causes next step to enumerate modem software * (1519 / 0020) * (requires modem to be flash version, not flashless * version) */ if (enum_delay_ms) msleep(enum_delay_ms); /* register usb host controller */ pr_info("%s: register usb host controller\n", __func__); if (baseband_power_driver_data->hsic_register) baseband_power_driver_data->modem.xmm.hsic_device = baseband_power_driver_data->hsic_register(); else pr_err("%s: hsic_register is missing\n", __func__); /* go to next state */ bbxmm_work->state = (modem_ver < XMM_MODEM_VER_1130) ? BBXMM_WORK_INIT_FLASH_PM_VER_LT_1130_STEP1 : BBXMM_WORK_INIT_FLASH_PM_VER_GE_1130_STEP1; queue_work(workqueue, work); pr_info("Go to next state %d\n", bbxmm_work->state); break; case BBXMM_WORK_INIT_FLASH_PM_VER_LT_1130_STEP1: pr_info("BBXMM_WORK_INIT_FLASH_PM_VER_LT_1130_STEP1\n"); break; case BBXMM_WORK_INIT_FLASH_PM_VER_GE_1130_STEP1: pr_info("BBXMM_WORK_INIT_FLASH_PM_VER_GE_1130_STEP1\n"); break; case BBXMM_WORK_INIT_FLASHLESS_PM_STEP1: //pr_info("BBXMM_WORK_INIT_FLASHLESS_PM_STEP1\n"); /* go to next state */ bbxmm_work->state = (modem_ver < XMM_MODEM_VER_1130) ? BBXMM_WORK_INIT_FLASHLESS_PM_VER_LT_1130_WAIT_IRQ : BBXMM_WORK_INIT_FLASHLESS_PM_VER_GE_1130_STEP1; queue_work(workqueue, work); break; case BBXMM_WORK_INIT_FLASHLESS_PM_VER_LT_1130_STEP1: pr_info("BBXMM_WORK_INIT_FLASHLESS_PM_VER_LT_1130_STEP1\n"); break; case BBXMM_WORK_INIT_FLASHLESS_PM_VER_GE_1130_STEP1: //pr_info("BBXMM_WORK_INIT_FLASHLESS_PM_VER_GE_1130_STEP1\n"); break; default: break; } } static void baseband_xmm_device_add_handler(struct usb_device *udev) { struct usb_interface *intf = usb_ifnum_to_if(udev, 0); const struct usb_device_id *id; pr_info("%s \n",__func__); if (intf == NULL) return; id = usb_match_id(intf, xmm_pm_ids); if (id) { pr_info("persist_enabled: %u\n", udev->persist_enabled); pr_info("Add device %d <%s %s>\n", udev->devnum, udev->manufacturer, udev->product); usbdev = udev; pm_runtime_set_autosuspend_delay(&udev->dev, autosuspend_delay);//for ICS 39kernel usb_enable_autosuspend(udev); // pr_info("enable autosuspend, timer <%d>", autosuspend_delay); } } static void baseband_xmm_device_remove_handler(struct usb_device *udev) { if (usbdev == udev) { pr_info("Remove device %d <%s %s>\n", udev->devnum, udev->manufacturer, udev->product); usbdev = 0; } } static int usb_xmm_notify(struct notifier_block *self, unsigned long action, void *blob) { switch (action) { case USB_DEVICE_ADD: baseband_xmm_device_add_handler(blob); break; case USB_DEVICE_REMOVE: baseband_xmm_device_remove_handler(blob); break; } return NOTIFY_OK; } static struct notifier_block usb_xmm_nb = { .notifier_call = usb_xmm_notify, }; static int baseband_xmm_power_pm_notifier_event(struct notifier_block *this, unsigned long event, void *ptr) { struct baseband_power_platform_data *data = baseband_power_driver_data; unsigned long flags; if (!data) return NOTIFY_DONE; pr_info("%s: event %ld\n", __func__, event); switch (event) { case PM_SUSPEND_PREPARE: pr_info("%s : PM_SUSPEND_PREPARE\n", __func__); if (wake_lock_active(&wakelock)) { pr_info("%s: wakelock was active, aborting suspend\n",__func__); return NOTIFY_STOP; } spin_lock_irqsave(&xmm_lock, flags); if (wakeup_pending) { wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); pr_info("%s : XMM busy : Abort system suspend\n", __func__); return NOTIFY_STOP; } system_suspending = true; spin_unlock_irqrestore(&xmm_lock, flags); return NOTIFY_OK; case PM_POST_SUSPEND: pr_info("%s : PM_POST_SUSPEND\n", __func__); spin_lock_irqsave(&xmm_lock, flags); system_suspending = false; if (wakeup_pending && (baseband_xmm_powerstate == BBXMM_PS_L2)) { wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); pr_info("%s : Service Pending CP wakeup\n", __func__); CP_initiated_L2toL0 = true; baseband_xmm_set_power_status (BBXMM_PS_L2TOL0); return NOTIFY_OK; } wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); return NOTIFY_OK; } return NOTIFY_DONE; } static struct notifier_block baseband_xmm_power_pm_notifier = { .notifier_call = baseband_xmm_power_pm_notifier_event, }; static int baseband_xmm_power_driver_probe(struct platform_device *device) { struct baseband_power_platform_data *data = (struct baseband_power_platform_data *) device->dev.platform_data; struct device *dev = &device->dev; unsigned long flags; int err, ret=0; pr_info(MODULE_NAME"%s 0705 - xmm_wake_pin_miss. \n", __func__); // pr_info(MODULE_NAME"enum_delay_ms=%d\n", enum_delay_ms); htcpcbid=htc_get_pcbid_info(); pr_info(MODULE_NAME"htcpcbid=%d\n", htcpcbid); /* check for platform data */ if (!data) return -ENODEV; /* check if supported modem */ if (data->baseband_type != BASEBAND_XMM) { pr_err("unsuppported modem\n"); return -ENODEV; } /* save platform data */ baseband_power_driver_data = data; /* init wait queue */ data->pin_state = 1; init_waitqueue_head(&data->bb_wait); /* create device file */ err = device_create_file(dev, &dev_attr_xmm_onoff); if (err < 0) { pr_err("%s - device_create_file failed\n", __func__); return -ENODEV; } err = device_create_file(dev, &dev_attr_debug_handler); if (err < 0) { pr_err("%s - device_create_file failed\n", __func__); return -ENODEV; } /* HTC: create device file for host debugging */ if (device_create_file(dev,&dev_attr_host_dbg)) pr_info(MODULE_NAME"Warning: host attribute can't be created\n"); /* init wake lock */ wake_lock_init(&wakelock, WAKE_LOCK_SUSPEND, "baseband_xmm_power"); /* init spin lock */ spin_lock_init(&xmm_lock); /* request baseband gpio(s) */ tegra_baseband_gpios[0].gpio = baseband_power_driver_data ->modem.xmm.bb_rst; tegra_baseband_gpios[1].gpio = baseband_power_driver_data ->modem.xmm.bb_on; tegra_baseband_gpios[2].gpio = baseband_power_driver_data ->modem.xmm.ipc_bb_wake; tegra_baseband_gpios[3].gpio = baseband_power_driver_data ->modem.xmm.ipc_ap_wake; tegra_baseband_gpios[4].gpio = baseband_power_driver_data ->modem.xmm.ipc_hsic_active; tegra_baseband_gpios[5].gpio = baseband_power_driver_data ->modem.xmm.ipc_hsic_sus_req; tegra_baseband_gpios[6].gpio = baseband_power_driver_data ->modem.xmm.bb_vdd_en; tegra_baseband_gpios[7].gpio = baseband_power_driver_data ->modem.xmm.bb_rst_pwrdn; tegra_baseband_gpios[8].gpio = baseband_power_driver_data ->modem.xmm.bb_rst2; /*HTC request these gpio on probe only, config them when running power_on/off function*/ err = gpio_request_only_array(tegra_baseband_gpios, ARRAY_SIZE(tegra_baseband_gpios)); if (err < 0) { pr_err("%s - request gpio(s) failed\n", __func__); return -ENODEV; } #if 1/*HTC*/ //assing for usb tegra_baseband_gpios_power_off_modem[0].gpio = baseband_power_driver_data ->modem.xmm.bb_rst; tegra_baseband_gpios_power_off_modem[1].gpio = baseband_power_driver_data ->modem.xmm.bb_on; tegra_baseband_gpios_power_off_modem[2].gpio = baseband_power_driver_data ->modem.xmm.ipc_bb_wake; tegra_baseband_gpios_power_off_modem[3].gpio = baseband_power_driver_data ->modem.xmm.ipc_ap_wake; tegra_baseband_gpios_power_off_modem[4].gpio = baseband_power_driver_data ->modem.xmm.ipc_hsic_active; tegra_baseband_gpios_power_off_modem[5].gpio = baseband_power_driver_data ->modem.xmm.ipc_hsic_sus_req; tegra_baseband_gpios_power_off_modem[6].gpio = baseband_power_driver_data ->modem.xmm.bb_vdd_en; tegra_baseband_gpios_power_off_modem[7].gpio = baseband_power_driver_data ->modem.xmm.bb_rst_pwrdn; tegra_baseband_gpios_power_off_modem[8].gpio = baseband_power_driver_data ->modem.xmm.bb_rst2; //request UART pr_info("%s request UART\n", __func__); err =gpio_request(TEGRA_GPIO_PJ7, "IMC_UART_TX"); err =gpio_request(TEGRA_GPIO_PK7, "IMC_UART_RTS"); err =gpio_request(TEGRA_GPIO_PB0 ,"IMC_UART_RX"); err =gpio_request(TEGRA_GPIO_PB1, "IMC_UART_CTS"); pr_info("%s pull UART o d\n", __func__); //for power consumation //all the needed config put on power_on function pr_info("%s config_gpio_for_power_off\n", __func__); err=config_gpio_for_power_off(); if (err < 0) { pr_err("%s - config_gpio_for_power_off gpio(s)\n", __func__); return -ENODEV; } #endif/*HTC*/ /* request baseband irq(s) */ if (modem_flash && modem_pm) { pr_info("%s: request_irq IPC_AP_WAKE_IRQ\n", __func__); ipc_ap_wake_state = IPC_AP_WAKE_UNINIT; err = request_threaded_irq( gpio_to_irq(data->modem.xmm.ipc_ap_wake), baseband_xmm_power_ipc_ap_wake_irq, NULL, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "IPC_AP_WAKE_IRQ", NULL); if (err < 0) { pr_err("%s - request irq IPC_AP_WAKE_IRQ failed\n", __func__); return err; } ipc_ap_wake_state = IPC_AP_WAKE_IRQ_READY; if (modem_ver >= XMM_MODEM_VER_1130) { pr_info("%s: ver > 1130: AP_WAKE_INIT1\n", __func__); /* ver 1130 or later starts in INIT1 state */ ipc_ap_wake_state = IPC_AP_WAKE_INIT1; } } /* init work queue */ workqueue = create_singlethread_workqueue("baseband_xmm_power_workqueue"); if (!workqueue) { pr_err("cannot create workqueue\n"); return -1; } workqueue_susp = alloc_workqueue("baseband_xmm_power_autosusp", WQ_UNBOUND | WQ_HIGHPRI | WQ_NON_REENTRANT, 1); if (!workqueue_susp) { pr_err("cannot create workqueue_susp\n"); return -1; } workqueue_debug = create_singlethread_workqueue("baseband_xmm_power_debug"); if (!workqueue_debug) { pr_err("cannot create workqueue_debug\n"); return -1; } baseband_xmm_power_work = (struct baseband_xmm_power_work_t *) kmalloc(sizeof(struct baseband_xmm_power_work_t), GFP_KERNEL); if (!baseband_xmm_power_work) { pr_err("cannot allocate baseband_xmm_power_work\n"); return -1; } INIT_WORK((struct work_struct *) baseband_xmm_power_work, baseband_xmm_power_work_func); baseband_xmm_power_work->state = BBXMM_WORK_INIT; queue_work(workqueue, (struct work_struct *) baseband_xmm_power_work); /* init work objects */ INIT_WORK(&init1_work, baseband_xmm_power_init1_work); INIT_WORK(&init2_work, baseband_xmm_power_init2_work); INIT_WORK(&L2_resume_work, baseband_xmm_power_L2_resume_work); INIT_WORK(&work_shortsusp, baseband_xmm_power_shortsusp); INIT_WORK(&work_defaultsusp, baseband_xmm_power_defaultsusp); INIT_WORK(&work_reset_host_active, baseband_xmm_power_reset_host_active_work); /* init state variables */ register_hsic_device = true; CP_initiated_L2toL0 = false; baseband_xmm_powerstate = BBXMM_PS_UNINIT; spin_lock_irqsave(&xmm_lock, flags); wakeup_pending = false; system_suspending = false; spin_unlock_irqrestore(&xmm_lock, flags); usb_register_notify(&usb_xmm_nb); register_pm_notifier(&baseband_xmm_power_pm_notifier); /*HTC*/ /*set Radio fatal Pin PN2 to OutPut Low*/ ret=gpio_direction_output(TEGRA_GPIO_PN2,0); if (ret < 0) pr_err("%s: set Radio fatal Pin to Output error\n", __func__); /*set BB2AP_SUSPEND_REQ Pin (TEGRA_GPIO_PV0) to OutPut Low*/ ret=gpio_direction_output(TEGRA_GPIO_PV0,0); if (ret < 0) pr_err("%s: set BB2AP_SUSPEND_REQ Pin to Output error\n", __func__); //Request SIM det to wakeup Source wahtever in flight mode on/off /*For SIM det*/ pr_info("%s: request enable irq wake SIM det to wakeup source\n", __func__); ret = enable_irq_wake(gpio_to_irq(TEGRA_GPIO_PI5)); if (ret < 0) pr_err("%s: enable_irq_wake error\n", __func__); pr_info("%s: init kobj for silent reset", __func__); silent_reset_kset = kset_create_and_add("SilentResetKset", NULL, NULL); if(!silent_reset_kset) { pr_err("%s: silent_reset_kset create failure.", __func__); } else { silent_reset_kobj = kobject_create_and_add("SilentResetTrigger", kobject_get(&dev->kobj)); if(!silent_reset_kobj) { pr_err("%s: silent_reset_kobj create failure.", __func__); kset_unregister(silent_reset_kset); silent_reset_kset = NULL; } else silent_reset_kobj->kset = silent_reset_kset; } pr_info("%s }\n", __func__); return 0; } static int baseband_xmm_power_driver_remove(struct platform_device *device) { struct baseband_power_platform_data *data = (struct baseband_power_platform_data *) device->dev.platform_data; struct device *dev = &device->dev; pr_info("%s\n", __func__); /* check for platform data */ if (!data) return 0; unregister_pm_notifier(&baseband_xmm_power_pm_notifier); usb_unregister_notify(&usb_xmm_nb); /* free work structure */ kfree(baseband_xmm_power_work); baseband_xmm_power_work = (struct baseband_xmm_power_work_t *) 0; /* free baseband irq(s) */ if (modem_flash && modem_pm) { free_irq(gpio_to_irq(baseband_power_driver_data ->modem.xmm.ipc_ap_wake), NULL); } /* free baseband gpio(s) */ gpio_free_array(tegra_baseband_gpios, ARRAY_SIZE(tegra_baseband_gpios)); /* destroy wake lock */ wake_lock_destroy(&wakelock); /* delete device file */ device_remove_file(dev, &dev_attr_xmm_onoff); device_remove_file(dev, &dev_attr_debug_handler); /* HTC: delete device file */ device_remove_file(dev, &dev_attr_host_dbg); /* destroy wake lock */ destroy_workqueue(workqueue_susp); destroy_workqueue(workqueue); if(silent_reset_kset) { kset_unregister(silent_reset_kset); silent_reset_kset = NULL; } if(silent_reset_kobj) { kobject_put(silent_reset_kobj); kobject_put(&dev->kobj); } /* unregister usb host controller */ if (data->hsic_unregister && data->modem.xmm.hsic_device) { data->hsic_unregister(data->modem.xmm.hsic_device); data->modem.xmm.hsic_device = NULL; } else pr_err("%s: hsic_unregister is missing\n", __func__); return 0; } #ifndef CONFIG_REMOVE_HSIC_L3_STATE static int baseband_xmm_power_driver_handle_resume( struct baseband_power_platform_data *data) { int value; unsigned long flags; unsigned long timeout; int delay = 10000; /* maxmum delay in msec */ //pr_info("%s\n", __func__); /* check for platform data */ if (!data) return 0; /* check if modem is on */ if (power_onoff == 0) { pr_info("%s - flight mode - nop\n", __func__); return 0; } modem_sleep_flag = false; spin_lock_irqsave(&xmm_lock, flags); /* Clear wakeup pending flag */ wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); /* L3->L0 */ baseband_xmm_set_power_status(BBXMM_PS_L3TOL0); value = gpio_get_value(data->modem.xmm.ipc_ap_wake); if (value) { pr_info("AP L3 -> L0\n"); pr_info("waiting for host wakeup...\n"); timeout = jiffies + msecs_to_jiffies(delay); /* wake bb */ gpio_set_value(data->modem.xmm.ipc_bb_wake, 1); pr_info("Set bb_wake high ->\n"); do { udelay(100); value = gpio_get_value(data->modem.xmm.ipc_ap_wake); if (!value) break; } while (time_before(jiffies, timeout)); if (!value) { pr_info("gpio host wakeup low <-\n"); pr_info("%s enable short_autosuspend\n", __func__); short_autosuspend = true; } else pr_info("!!AP L3->L0 Failed\n"); } else { pr_info("CP L3 -> L0\n"); } reenable_autosuspend = true; return 0; } #endif #ifdef CONFIG_PM #ifdef CONFIG_REMOVE_HSIC_L3_STATE static int baseband_xmm_power_driver_suspend(struct device *dev) { // int delay = 10000; /* maxmum delay in msec */ // struct platform_device *pdev = to_platform_device(dev); //struct baseband_power_platform_data *pdata = pdev->dev.platform_data; //pr_info("%s\n", __func__); /* check if modem is on */ if (power_onoff == 0) { pr_info("%s - flight mode - nop\n", __func__); return 0; } /* PMC is driving hsic bus * tegra_baseband_rail_off(); */ return 0; } #else static int baseband_xmm_power_driver_suspend(struct device *dev) { pr_info("%s\n", __func__); return 0; } #endif /* CONFIG_REMOVE_HSIC_L3_STATE */ static int baseband_xmm_power_driver_resume(struct device *dev) { //struct platform_device *pdev = to_platform_device(dev); //struct baseband_power_platform_data *data // = (struct baseband_power_platform_data *) // pdev->dev.platform_data; pr_info("%s\n", __func__); #ifdef CONFIG_REMOVE_HSIC_L3_STATE /* check if modem is on */ if (power_onoff == 0) { pr_info("%s - flight mode - nop\n", __func__); return 0; } /* PMC is driving hsic bus * tegra_baseband_rail_on(); */ reenable_autosuspend = true; #else baseband_xmm_power_driver_handle_resume(data); #endif return 0; } static int baseband_xmm_power_suspend_noirq(struct device *dev) { unsigned long flags; pr_info("%s\n", __func__); spin_lock_irqsave(&xmm_lock, flags); system_suspending = false; if (wakeup_pending) { wakeup_pending = false; spin_unlock_irqrestore(&xmm_lock, flags); pr_info("%s:**Abort Suspend: reason CP WAKEUP**\n", __func__); return -EBUSY; } spin_unlock_irqrestore(&xmm_lock, flags); return 0; } static int baseband_xmm_power_resume_noirq(struct device *dev) { pr_info("%s\n", __func__); return 0; } static const struct dev_pm_ops baseband_xmm_power_dev_pm_ops = { .suspend_noirq = baseband_xmm_power_suspend_noirq, .resume_noirq = baseband_xmm_power_resume_noirq, .suspend = baseband_xmm_power_driver_suspend, .resume = baseband_xmm_power_driver_resume, }; #endif static struct platform_driver baseband_power_driver = { .probe = baseband_xmm_power_driver_probe, .remove = baseband_xmm_power_driver_remove, .driver = { .name = "baseband_xmm_power", #ifdef CONFIG_PM .pm = &baseband_xmm_power_dev_pm_ops, #endif }, }; static int __init baseband_xmm_power_init(void) { /* HTC */ int mfg_mode = board_mfg_mode(); host_dbg_flag = 0; //pr_info("%s - host_dbg_flag<0x%x>, modem_ver<0x%x>, mfg_mode<%d>" // , __func__, host_dbg_flag, modem_ver, mfg_mode); if( mfg_mode ) { autosuspend_delay = 365*86400; short_autosuspend_delay = 365*86400; //pr_info("In MFG mode, autosuspend_delay <%d>, short_autosuspend_delay <%d>" // , autosuspend_delay, short_autosuspend_delay ); } s_sku_id = board_get_sku_tag(); pr_info("SKU_ID is 0x%x", s_sku_id); //printk("%s:VP adding pm qos request removed\n", __func__); //pm_qos_add_request(&modem_boost_cpu_freq_req, PM_QOS_CPU_FREQ_MIN, (s32)PM_QOS_CPU_FREQ_MIN_DEFAULT_VALUE); return platform_driver_register(&baseband_power_driver); } static void __exit baseband_xmm_power_exit(void) { pr_info("%s\n", __func__); platform_driver_unregister(&baseband_power_driver); //pm_qos_remove_request(&modem_boost_cpu_freq_req); } module_init(baseband_xmm_power_init) module_exit(baseband_xmm_power_exit)
Java
include ../../../Makefile.inc CLC_ROOT = ../../../inc all: exe_src exe_src_m2s exe_bin amd_compile m2c_compile run_m2s run_native check_result exe_src: @-$(CC) $(CC_FLAG) *src.c -o exe_src $(CC_INC) $(CC_LIB) > isgreaterequal_floatfloat.exe_src.log 2>&1 exe_src_m2s: @-$(CC) $(CC_FLAG) -m32 *src.c -o exe_src_m2s $(CC_INC) $(M2S_LIB) > isgreaterequal_floatfloat.exe_src_m2s.log 2>&1 exe_bin: @-$(CC) $(CC_FLAG) *bin.c -o exe_bin $(CC_INC) $(CC_LIB) > isgreaterequal_floatfloat.exe_bin.log 2>&1 amd_compile: @-$(AMD_CC) --amd --amd-dump-all --amd-device 11 isgreaterequal_floatfloat.cl > isgreaterequal_floatfloat.amdcc.log 2>&1 @-rm -rf /tmp/*.clp && rm -rf /tmp/*_amd_files m2c_compile: @-python compile.py run_m2s: @-M2S_OPENCL_BINARY=./isgreaterequal_floatfloat.opt.bin $(M2S) --si-sim functional ./exe_src_m2s > m2s.log 2>&1 run_native: @-./exe_src > native.log 2>&1 check_result: @-diff exe_src.result exe_src_m2s.result > check.log 2>&1 clean: rm -rf exe_src exe_src_m2s exe_bin *.ll *.log *files *bin *.s *.bc *.result
Java
# coding=utf-8 # --------------------------------------------------------------- # Desenvolvedor: Arannã Sousa Santos # Mês: 12 # Ano: 2015 # Projeto: pagseguro_xml # e-mail: asousas@live.com # --------------------------------------------------------------- import logging from pagseguro_xml.notificacao import ApiPagSeguroNotificacao_v3, CONST_v3 logger = logging.basicConfig(level=logging.DEBUG) PAGSEGURO_API_AMBIENTE = u'sandbox' PAGSEGURO_API_EMAIL = u'seu@email.com' PAGSEGURO_API_TOKEN_PRODUCAO = u'' PAGSEGURO_API_TOKEN_SANDBOX = u'' CHAVE_NOTIFICACAO = u'AA0000-AA00A0A0AA00-AA00AA000000-AA0000' # ela éh de producao api = ApiPagSeguroNotificacao_v3(ambiente=CONST_v3.AMBIENTE.SANDBOX) PAGSEGURO_API_TOKEN = PAGSEGURO_API_TOKEN_PRODUCAO ok, retorno = api.consulta_notificacao_transacao_v3(PAGSEGURO_API_EMAIL, PAGSEGURO_API_TOKEN, CHAVE_NOTIFICACAO) if ok: print u'-' * 50 print retorno.xml print u'-' * 50 for a in retorno.alertas: print a else: print u'Motivo do erro:', retorno
Java
<?php /** * @package Mambo * @author Mambo Foundation Inc see README.php * @copyright Mambo Foundation Inc. * See COPYRIGHT.php for copyright notices and details. * @license GNU/GPL Version 2, see LICENSE.php * Mambo 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. */ /** ensure this file is being included by a parent file */ defined( '_VALID_MOS' ) or die( 'Direct Access to this location is not allowed.' ); /** * AWSTATS BROWSERS DATABASE * If you want to add a Browser to extend AWStats database detection capabilities, * you must add an entry in BrowsersSearchIDOrder and in BrowsersHashIDLib. * * * BrowsersSearchIDOrder * This list is used to know in which order to search Browsers IDs (Most * frequent one are first in this list to increase detect speed). * It contains all matching criteria to search for in log fields. * Note: Browsers IDs are in lower case and ' ' and '+' are changed into '_' */ $browserSearchOrder = array ( // Most frequent standard web browsers are first in this list "icab", "go!zilla", "konqueror", "links", "lynx", "omniweb", "opera", "msie 6\.0", "apachebench", "wget", // Other standard web browsers "22acidownload", "aol\\-iweng", "amaya", "amigavoyager", "aweb", "bpftp", "chimera", "cyberdog", "dillo", "dreamcast", "downloadagent", "ecatch", "emailsiphon", "encompass", "friendlyspider", "fresco", "galeon", "getright", "headdump", "hotjava", "ibrowse", "intergo", "k-meleon", "linemodebrowser", "lotus-notes", "macweb", "multizilla", "ncsa_mosaic", "netpositive", "nutscrape", "msfrontpageexpress", "phoenix", "firebird", "firefox", "safari", "tzgeturl", "viking", "webfetcher", "webexplorer", "webmirror", "webvcr", // Site grabbers "teleport", "webcapture", "webcopier", // Music only browsers "real", "winamp", // Works for winampmpeg and winamp3httprdr "windows-media-player", "audion", "freeamp", "itunes", "jetaudio", "mint_audio", "mpg123", "nsplayer", "sonique", "uplayer", "xmms", "xaudio", // PDA/Phonecell browsers "alcatel", // Alcatel "mot-", // Motorola "nokia", // Nokia "panasonic", // Panasonic "philips", // Philips "sonyericsson", // SonyEricsson "ericsson", // Ericsson (must be after sonyericsson "mmef", "mspie", "wapalizer", "wapsilon", "webcollage", "up\.", // Works for UP.Browser and UP.Link // PDA/Phonecell I-Mode browsers "docomo", "portalmmm", // Others (TV) "webtv", // Other kind of browsers "csscheck", "w3m", "w3c_css_validator", "w3c_validator", "wdg_validator", "webzip", "staroffice", "mozilla", // Must be at end because a lot of browsers contains mozilla in string "libwww" // Must be at end because some browser have both "browser id" and "libwww" ); $browsersAlias = array ( // Common web browsers text (IE and Netscape must not be in this list) "icab"=>"iCab", "go!zilla"=>"Go!Zilla", "konqueror"=>"Konqueror", "links"=>"Links", "lynx"=>"Lynx", "omniweb"=>"OmniWeb", "opera"=>"Opera", "msie 6\.0"=>"Microsoft Internet Explorer 6.0", "apachebench"=>"ApacheBench", "wget"=>"Wget", "22acidownload"=>"22AciDownload", "aol\\-iweng"=>"AOL-Iweng", "amaya"=>"Amaya", "amigavoyager"=>"AmigaVoyager", "aweb"=>"AWeb", "bpftp"=>"BPFTP", "chimera"=>"Chimera", "cyberdog"=>"Cyberdog", "dillo"=>"Dillo", "dreamcast"=>"Dreamcast", "downloadagent"=>"DownloadAgent", "ecatch", "eCatch", "emailsiphon"=>"EmailSiphon", "encompass"=>"Encompass", "friendlyspider"=>"FriendlySpider", "fresco"=>"ANT Fresco", "galeon"=>"Galeon", "getright"=>"GetRight", "headdump"=>"HeadDump", "hotjava"=>"Sun HotJava", "ibrowse"=>"IBrowse", "intergo"=>"InterGO", "k-meleon"=>"K-Meleon", "linemodebrowser"=>"W3C Line Mode Browser", "lotus-notes"=>"Lotus Notes web client", "macweb"=>"MacWeb", "multizilla"=>"MultiZilla", "ncsa_mosaic"=>"NCSA Mosaic", "netpositive"=>"NetPositive", "nutscrape", "Nutscrape", "msfrontpageexpress"=>"MS FrontPage Express", "phoenix"=>"Phoenix", "firebird"=>"Mozilla Firebird", "firefox"=>"Mozilla Firefox", "safari"=>"Safari", "tzgeturl"=>"TzGetURL", "viking"=>"Viking", "webfetcher"=>"WebFetcher", "webexplorer"=>"IBM-WebExplorer", "webmirror"=>"WebMirror", "webvcr"=>"WebVCR", // Site grabbers "teleport"=>"TelePort Pro", "webcapture"=>"Acrobat", "webcopier", "WebCopier", // Music only browsers "real"=>"RealAudio or compatible (media player)", "winamp"=>"WinAmp (media player)", // Works for winampmpeg and winamp3httprdr "windows-media-player"=>"Windows Media Player (media player)", "audion"=>"Audion (media player)", "freeamp"=>"FreeAmp (media player)", "itunes"=>"Apple iTunes (media player)", "jetaudio"=>"JetAudio (media player)", "mint_audio"=>"Mint Audio (media player)", "mpg123"=>"mpg123 (media player)", "nsplayer"=>"NetShow Player (media player)", "sonique"=>"Sonique (media player)", "uplayer"=>"Ultra Player (media player)", "xmms"=>"XMMS (media player)", "xaudio"=>"Some XAudio Engine based MPEG player (media player)", // PDA/Phonecell browsers "alcatel"=>"Alcatel Browser (PDA/Phone browser)", "ericsson"=>"Ericsson Browser (PDA/Phone browser)", "mot-"=>"Motorola Browser (PDA/Phone browser)", "nokia"=>"Nokia Browser (PDA/Phone browser)", "panasonic"=>"Panasonic Browser (PDA/Phone browser)", "philips"=>"Philips Browser (PDA/Phone browser)", "sonyericsson"=>"Sony/Ericsson Browser (PDA/Phone browser)", "mmef"=>"Microsoft Mobile Explorer (PDA/Phone browser)", "mspie"=>"MS Pocket Internet Explorer (PDA/Phone browser)", "wapalizer"=>"WAPalizer (PDA/Phone browser)", "wapsilon"=>"WAPsilon (PDA/Phone browser)", "webcollage"=>"WebCollage (PDA/Phone browser)", "up\."=>"UP.Browser (PDA/Phone browser)", // Works for UP.Browser and UP.Link // PDA/Phonecell I-Mode browsers "docomo"=>"I-Mode phone (PDA/Phone browser)", "portalmmm"=>"I-Mode phone (PDA/Phone browser)", // Others (TV) "webtv"=>"WebTV browser", // Other kind of browsers "csscheck"=>"WDG CSS Validator", "w3m"=>"w3m", "w3c_css_validator"=>"W3C CSS Validator", "w3c_validator"=>"W3C HTML Validator", "wdg_validator"=>"WDG HTML Validator", "webzip"=>"WebZIP", "staroffice"=>"StarOffice", "mozilla"=>"Mozilla", "libwww"=>"LibWWW", ); // BrowsersHashAreGrabber // Put here an entry for each browser in BrowsersSearchIDOrder that are grabber // browsers. //--------------------------------------------------------------------------- $BrowsersHereAreGrabbers = array ( "teleport"=>"1", "webcapture"=>"1", "webcopier"=>"1", ); // BrowsersHashIcon // Each Browsers Search ID is associated to a string that is the name of icon // file for this browser. //--------------------------------------------------------------------------- $BrowsersHashIcon = array ( // Standard web browsers "msie"=>"msie", "netscape"=>"netscape", "icab"=>"icab", "go!zilla"=>"gozilla", "konqueror"=>"konqueror", "links"=>"notavailable", "lynx"=>"lynx", "omniweb"=>"omniweb", "opera"=>"opera", "wget"=>"notavailable", "22acidownload"=>"notavailable", "aol\\-iweng"=>"notavailable", "amaya"=>"amaya", "amigavoyager"=>"notavailable", "aweb"=>"notavailable", "bpftp"=>"notavailable", "chimera"=>"chimera", "cyberdog"=>"notavailable", "dillo"=>"notavailable", "dreamcast"=>"dreamcast", "downloadagent"=>"notavailable", "ecatch"=>"notavailable", "emailsiphon"=>"notavailable", "encompass"=>"notavailable", "friendlyspider"=>"notavailable", "fresco"=>"notavailable", "galeon"=>"galeon", "getright"=>"getright", "headdump"=>"notavailable", "hotjava"=>"notavailable", "ibrowse"=>"ibrowse", "intergo"=>"notavailable", "k-meleon"=>"kmeleon", "linemodebrowser"=>"notavailable", "lotus-notes"=>"notavailable", "macweb"=>"notavailable", "multizilla"=>"multizilla", "ncsa_mosaic"=>"notavailable", "netpositive"=>"netpositive", "nutscrape"=>"notavailable", "msfrontpageexpress"=>"notavailable", "phoenix"=>"phoenix", "firebird"=>"firebird", "safari"=>"safari", "tzgeturl"=>"notavailable", "viking"=>"notavailable", "webfetcher"=>"notavailable", "webexplorer"=>"notavailable", "webmirror"=>"notavailable", "webvcr"=>"notavailable", // Site grabbers "teleport"=>"teleport", "webcapture"=>"adobe", "webcopier"=>"webcopier", // Music only browsers "real"=>"mediaplayer", "winamp"=>"mediaplayer", // Works for winampmpeg and winamp3httprdr "windows-media-player"=>"mediaplayer", "audion"=>"mediaplayer", "freeamp"=>"mediaplayer", "itunes"=>"mediaplayer", "jetaudio"=>"mediaplayer", "mint_audio"=>"mediaplayer", "mpg123"=>"mediaplayer", "nsplayer"=>"mediaplayer", "sonique"=>"mediaplayer", "uplayer"=>"mediaplayer", "xmms"=>"mediaplayer", "xaudio"=>"mediaplayer", // PDA/Phonecell browsers "alcatel"=>"pdaphone", // Alcatel "ericsson"=>"pdaphone", // Ericsson "mot-"=>"pdaphone", // Motorola "nokia"=>"pdaphone", // Nokia "panasonic"=>"pdaphone", // Panasonic "philips"=>"pdaphone", // Philips "sonyericsson"=>"pdaphone", // Sony/Ericsson "mmef"=>"pdaphone", "mspie"=>"pdaphone", "wapalizer"=>"pdaphone", "wapsilon"=>"pdaphone", "webcollage"=>"pdaphone", "up\."=>"pdaphone", // Works for UP.Browser and UP.Link // PDA/Phonecell I-Mode browsers "docomo"=>"pdaphone", "portalmmm"=>"pdaphone", // Others (TV) "webtv"=>"webtv", // Other kind of browsers "csscheck"=>"notavailable", "w3m"=>"notavailable", "w3c_css_validator"=>"notavailable", "w3c_validator"=>"notavailable", "wdg_validator"=>"notavailable", "webzip"=>"webzip", "staroffice"=>"staroffice", "mozilla"=>"mozilla", "libwww"=>"notavailable" ); // TODO // Add Gecko category -> IE / Netscape / Gecko(except Netscape) / Other // IE (based on Mosaic) // Netscape family // Gecko except Netscape (Mozilla, Firebird (was Phoenix), Galeon, AmiZilla, Dino, and few others) // Opera (Opera 6/7) // KHTML (Konqueror, Safari) ?>
Java
<style type="text/css"> .ppsAdminMainLeftSide { width: 56%; float: left; } .ppsAdminMainRightSide { width: <?php echo (empty($this->optsDisplayOnMainPage) ? 100 : 40)?>%; float: left; text-align: center; } #ppsMainOccupancy { box-shadow: none !important; } </style> <section> <div class="supsystic-item supsystic-panel"> <div id="containerWrapper"> <?php _e('Main page Go here!!!!', PPS_LANG_CODE)?> </div> <div style="clear: both;"></div> </div> </section>
Java
/*************************************************************************** * * Copyright (c) 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009, * 2010, 2011 BalaBit IT Ltd, Budapest, Hungary * * 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. * * Note that this permission is granted for only version 2 of the GPL. * * As an additional exemption you are allowed to compile & link against the * OpenSSL libraries as published by the OpenSSL project. See the file * COPYING for details. * * 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. * * Author : Panther * Auditor : * Last audited version: * Notes: * ***************************************************************************/ #ifndef ZORP_ZORPADDR_H_INCLUDED #define ZORP_ZORPADDR_H_INCLUDED #include "ifcfg.h" #include "zshmem.h" #include "cfg.h" #include "stats.h" #endif
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc on Sat Aug 06 17:04:40 EDT 2005 --> <TITLE> Xalan-Java 2.7.0: Uses of Class org.apache.xml.serializer.utils.SystemIDResolver </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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/xml/serializer/utils/SystemIDResolver.html"><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-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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SystemIDResolver.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> <CENTER> <H2> <B>Uses of Class<br>org.apache.xml.serializer.utils.SystemIDResolver</B></H2> </CENTER> No usage of org.apache.xml.serializer.utils.SystemIDResolver <P> <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="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../../../org/apache/xml/serializer/utils/SystemIDResolver.html"><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-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;PREV&nbsp; &nbsp;NEXT</FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../../../index.html" TARGET="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="SystemIDResolver.html" TARGET="_top"><B>NO FRAMES</B></A></FONT></TD> </TR> </TABLE> <!-- =========== END OF NAVBAR =========== --> <HR> Copyright © 2005 Apache XML Project. All Rights Reserved. </BODY> </HTML>
Java