repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
TLOIN-3X-WIP/android_kernel_samsung_msm8660-common | net/core/user_dma.c | 4607 | 3337 | /*
* Copyright(c) 2004 - 2006 Intel Corporation. All rights reserved.
* Portions based on net/core/datagram.c and copyrighted by their authors.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 59
* Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* The full GNU General Public License is included in this distribution in the
* file called COPYING.
*/
/*
* This code allows the net stack to make use of a DMA engine for
* skb to iovec copies.
*/
#include <linux/dmaengine.h>
#include <linux/socket.h>
#include <net/tcp.h>
#include <net/netdma.h>
#define NET_DMA_DEFAULT_COPYBREAK 4096
int sysctl_tcp_dma_copybreak = NET_DMA_DEFAULT_COPYBREAK;
EXPORT_SYMBOL(sysctl_tcp_dma_copybreak);
/**
* dma_skb_copy_datagram_iovec - Copy a datagram to an iovec.
* @skb - buffer to copy
* @offset - offset in the buffer to start copying from
* @iovec - io vector to copy to
* @len - amount of data to copy from buffer to iovec
* @pinned_list - locked iovec buffer data
*
* Note: the iovec is modified during the copy.
*/
int dma_skb_copy_datagram_iovec(struct dma_chan *chan,
struct sk_buff *skb, int offset, struct iovec *to,
size_t len, struct dma_pinned_list *pinned_list)
{
int start = skb_headlen(skb);
int i, copy = start - offset;
struct sk_buff *frag_iter;
dma_cookie_t cookie = 0;
/* Copy header. */
if (copy > 0) {
if (copy > len)
copy = len;
cookie = dma_memcpy_to_iovec(chan, to, pinned_list,
skb->data + offset, copy);
if (cookie < 0)
goto fault;
len -= copy;
if (len == 0)
goto end;
offset += copy;
}
/* Copy paged appendix. Hmm... why does this look so complicated? */
for (i = 0; i < skb_shinfo(skb)->nr_frags; i++) {
int end;
WARN_ON(start > offset + len);
end = start + skb_shinfo(skb)->frags[i].size;
copy = end - offset;
if (copy > 0) {
skb_frag_t *frag = &skb_shinfo(skb)->frags[i];
struct page *page = frag->page;
if (copy > len)
copy = len;
cookie = dma_memcpy_pg_to_iovec(chan, to, pinned_list, page,
frag->page_offset + offset - start, copy);
if (cookie < 0)
goto fault;
len -= copy;
if (len == 0)
goto end;
offset += copy;
}
start = end;
}
skb_walk_frags(skb, frag_iter) {
int end;
WARN_ON(start > offset + len);
end = start + frag_iter->len;
copy = end - offset;
if (copy > 0) {
if (copy > len)
copy = len;
cookie = dma_skb_copy_datagram_iovec(chan, frag_iter,
offset - start,
to, copy,
pinned_list);
if (cookie < 0)
goto fault;
len -= copy;
if (len == 0)
goto end;
offset += copy;
}
start = end;
}
end:
if (!len) {
skb->dma_cookie = cookie;
return cookie;
}
fault:
return -EFAULT;
}
| gpl-2.0 |
Rashed97/caf-kernel-msm-3.10 | drivers/video/via/hw.c | 4607 | 60031 | /*
* Copyright 1998-2008 VIA Technologies, Inc. All Rights Reserved.
* Copyright 2001-2008 S3 Graphics, Inc. All Rights Reserved.
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public
* License as published by the Free Software Foundation;
* either version 2, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTIES OR REPRESENTATIONS; without even
* the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE.See the GNU General Public License
* for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
#include <linux/via-core.h>
#include <asm/olpc.h>
#include "global.h"
#include "via_clock.h"
static struct pll_limit cle266_pll_limits[] = {
{19, 19, 4, 0},
{26, 102, 5, 0},
{53, 112, 6, 0},
{41, 100, 7, 0},
{83, 108, 8, 0},
{87, 118, 9, 0},
{95, 115, 12, 0},
{108, 108, 13, 0},
{83, 83, 17, 0},
{67, 98, 20, 0},
{121, 121, 24, 0},
{99, 99, 29, 0},
{33, 33, 3, 1},
{15, 23, 4, 1},
{37, 121, 5, 1},
{82, 82, 6, 1},
{31, 84, 7, 1},
{83, 83, 8, 1},
{76, 127, 9, 1},
{33, 121, 4, 2},
{91, 118, 5, 2},
{83, 109, 6, 2},
{90, 90, 7, 2},
{93, 93, 2, 3},
{53, 53, 3, 3},
{73, 117, 4, 3},
{101, 127, 5, 3},
{99, 99, 7, 3}
};
static struct pll_limit k800_pll_limits[] = {
{22, 22, 2, 0},
{28, 28, 3, 0},
{81, 112, 3, 1},
{86, 166, 4, 1},
{109, 153, 5, 1},
{66, 116, 3, 2},
{93, 137, 4, 2},
{117, 208, 5, 2},
{30, 30, 2, 3},
{69, 125, 3, 3},
{89, 161, 4, 3},
{121, 208, 5, 3},
{66, 66, 2, 4},
{85, 85, 3, 4},
{141, 161, 4, 4},
{177, 177, 5, 4}
};
static struct pll_limit cx700_pll_limits[] = {
{98, 98, 3, 1},
{86, 86, 4, 1},
{109, 208, 5, 1},
{68, 68, 2, 2},
{95, 116, 3, 2},
{93, 166, 4, 2},
{110, 206, 5, 2},
{174, 174, 7, 2},
{82, 109, 3, 3},
{117, 161, 4, 3},
{112, 208, 5, 3},
{141, 202, 5, 4}
};
static struct pll_limit vx855_pll_limits[] = {
{86, 86, 4, 1},
{108, 208, 5, 1},
{110, 208, 5, 2},
{83, 112, 3, 3},
{103, 161, 4, 3},
{112, 209, 5, 3},
{142, 161, 4, 4},
{141, 176, 5, 4}
};
/* according to VIA Technologies these values are based on experiment */
static struct io_reg scaling_parameters[] = {
{VIACR, CR7A, 0xFF, 0x01}, /* LCD Scaling Parameter 1 */
{VIACR, CR7B, 0xFF, 0x02}, /* LCD Scaling Parameter 2 */
{VIACR, CR7C, 0xFF, 0x03}, /* LCD Scaling Parameter 3 */
{VIACR, CR7D, 0xFF, 0x04}, /* LCD Scaling Parameter 4 */
{VIACR, CR7E, 0xFF, 0x07}, /* LCD Scaling Parameter 5 */
{VIACR, CR7F, 0xFF, 0x0A}, /* LCD Scaling Parameter 6 */
{VIACR, CR80, 0xFF, 0x0D}, /* LCD Scaling Parameter 7 */
{VIACR, CR81, 0xFF, 0x13}, /* LCD Scaling Parameter 8 */
{VIACR, CR82, 0xFF, 0x16}, /* LCD Scaling Parameter 9 */
{VIACR, CR83, 0xFF, 0x19}, /* LCD Scaling Parameter 10 */
{VIACR, CR84, 0xFF, 0x1C}, /* LCD Scaling Parameter 11 */
{VIACR, CR85, 0xFF, 0x1D}, /* LCD Scaling Parameter 12 */
{VIACR, CR86, 0xFF, 0x1E}, /* LCD Scaling Parameter 13 */
{VIACR, CR87, 0xFF, 0x1F}, /* LCD Scaling Parameter 14 */
};
static struct io_reg common_vga[] = {
{VIACR, CR07, 0x10, 0x10}, /* [0] vertical total (bit 8)
[1] vertical display end (bit 8)
[2] vertical retrace start (bit 8)
[3] start vertical blanking (bit 8)
[4] line compare (bit 8)
[5] vertical total (bit 9)
[6] vertical display end (bit 9)
[7] vertical retrace start (bit 9) */
{VIACR, CR08, 0xFF, 0x00}, /* [0-4] preset row scan
[5-6] byte panning */
{VIACR, CR09, 0xDF, 0x40}, /* [0-4] max scan line
[5] start vertical blanking (bit 9)
[6] line compare (bit 9)
[7] scan doubling */
{VIACR, CR0A, 0xFF, 0x1E}, /* [0-4] cursor start
[5] cursor disable */
{VIACR, CR0B, 0xFF, 0x00}, /* [0-4] cursor end
[5-6] cursor skew */
{VIACR, CR0E, 0xFF, 0x00}, /* [0-7] cursor location (high) */
{VIACR, CR0F, 0xFF, 0x00}, /* [0-7] cursor location (low) */
{VIACR, CR11, 0xF0, 0x80}, /* [0-3] vertical retrace end
[6] memory refresh bandwidth
[7] CRTC register protect enable */
{VIACR, CR14, 0xFF, 0x00}, /* [0-4] underline location
[5] divide memory address clock by 4
[6] double word addressing */
{VIACR, CR17, 0xFF, 0x63}, /* [0-1] mapping of display address 13-14
[2] divide scan line clock by 2
[3] divide memory address clock by 2
[5] address wrap
[6] byte mode select
[7] sync enable */
{VIACR, CR18, 0xFF, 0xFF}, /* [0-7] line compare */
};
static struct fifo_depth_select display_fifo_depth_reg = {
/* IGA1 FIFO Depth_Select */
{IGA1_FIFO_DEPTH_SELECT_REG_NUM, {{SR17, 0, 7} } },
/* IGA2 FIFO Depth_Select */
{IGA2_FIFO_DEPTH_SELECT_REG_NUM,
{{CR68, 4, 7}, {CR94, 7, 7}, {CR95, 7, 7} } }
};
static struct fifo_threshold_select fifo_threshold_select_reg = {
/* IGA1 FIFO Threshold Select */
{IGA1_FIFO_THRESHOLD_REG_NUM, {{SR16, 0, 5}, {SR16, 7, 7} } },
/* IGA2 FIFO Threshold Select */
{IGA2_FIFO_THRESHOLD_REG_NUM, {{CR68, 0, 3}, {CR95, 4, 6} } }
};
static struct fifo_high_threshold_select fifo_high_threshold_select_reg = {
/* IGA1 FIFO High Threshold Select */
{IGA1_FIFO_HIGH_THRESHOLD_REG_NUM, {{SR18, 0, 5}, {SR18, 7, 7} } },
/* IGA2 FIFO High Threshold Select */
{IGA2_FIFO_HIGH_THRESHOLD_REG_NUM, {{CR92, 0, 3}, {CR95, 0, 2} } }
};
static struct display_queue_expire_num display_queue_expire_num_reg = {
/* IGA1 Display Queue Expire Num */
{IGA1_DISPLAY_QUEUE_EXPIRE_NUM_REG_NUM, {{SR22, 0, 4} } },
/* IGA2 Display Queue Expire Num */
{IGA2_DISPLAY_QUEUE_EXPIRE_NUM_REG_NUM, {{CR94, 0, 6} } }
};
/* Definition Fetch Count Registers*/
static struct fetch_count fetch_count_reg = {
/* IGA1 Fetch Count Register */
{IGA1_FETCH_COUNT_REG_NUM, {{SR1C, 0, 7}, {SR1D, 0, 1} } },
/* IGA2 Fetch Count Register */
{IGA2_FETCH_COUNT_REG_NUM, {{CR65, 0, 7}, {CR67, 2, 3} } }
};
static struct rgbLUT palLUT_table[] = {
/* {R,G,B} */
/* Index 0x00~0x03 */
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x2A}, {0x00, 0x2A, 0x00}, {0x00,
0x2A,
0x2A},
/* Index 0x04~0x07 */
{0x2A, 0x00, 0x00}, {0x2A, 0x00, 0x2A}, {0x2A, 0x15, 0x00}, {0x2A,
0x2A,
0x2A},
/* Index 0x08~0x0B */
{0x15, 0x15, 0x15}, {0x15, 0x15, 0x3F}, {0x15, 0x3F, 0x15}, {0x15,
0x3F,
0x3F},
/* Index 0x0C~0x0F */
{0x3F, 0x15, 0x15}, {0x3F, 0x15, 0x3F}, {0x3F, 0x3F, 0x15}, {0x3F,
0x3F,
0x3F},
/* Index 0x10~0x13 */
{0x00, 0x00, 0x00}, {0x05, 0x05, 0x05}, {0x08, 0x08, 0x08}, {0x0B,
0x0B,
0x0B},
/* Index 0x14~0x17 */
{0x0E, 0x0E, 0x0E}, {0x11, 0x11, 0x11}, {0x14, 0x14, 0x14}, {0x18,
0x18,
0x18},
/* Index 0x18~0x1B */
{0x1C, 0x1C, 0x1C}, {0x20, 0x20, 0x20}, {0x24, 0x24, 0x24}, {0x28,
0x28,
0x28},
/* Index 0x1C~0x1F */
{0x2D, 0x2D, 0x2D}, {0x32, 0x32, 0x32}, {0x38, 0x38, 0x38}, {0x3F,
0x3F,
0x3F},
/* Index 0x20~0x23 */
{0x00, 0x00, 0x3F}, {0x10, 0x00, 0x3F}, {0x1F, 0x00, 0x3F}, {0x2F,
0x00,
0x3F},
/* Index 0x24~0x27 */
{0x3F, 0x00, 0x3F}, {0x3F, 0x00, 0x2F}, {0x3F, 0x00, 0x1F}, {0x3F,
0x00,
0x10},
/* Index 0x28~0x2B */
{0x3F, 0x00, 0x00}, {0x3F, 0x10, 0x00}, {0x3F, 0x1F, 0x00}, {0x3F,
0x2F,
0x00},
/* Index 0x2C~0x2F */
{0x3F, 0x3F, 0x00}, {0x2F, 0x3F, 0x00}, {0x1F, 0x3F, 0x00}, {0x10,
0x3F,
0x00},
/* Index 0x30~0x33 */
{0x00, 0x3F, 0x00}, {0x00, 0x3F, 0x10}, {0x00, 0x3F, 0x1F}, {0x00,
0x3F,
0x2F},
/* Index 0x34~0x37 */
{0x00, 0x3F, 0x3F}, {0x00, 0x2F, 0x3F}, {0x00, 0x1F, 0x3F}, {0x00,
0x10,
0x3F},
/* Index 0x38~0x3B */
{0x1F, 0x1F, 0x3F}, {0x27, 0x1F, 0x3F}, {0x2F, 0x1F, 0x3F}, {0x37,
0x1F,
0x3F},
/* Index 0x3C~0x3F */
{0x3F, 0x1F, 0x3F}, {0x3F, 0x1F, 0x37}, {0x3F, 0x1F, 0x2F}, {0x3F,
0x1F,
0x27},
/* Index 0x40~0x43 */
{0x3F, 0x1F, 0x1F}, {0x3F, 0x27, 0x1F}, {0x3F, 0x2F, 0x1F}, {0x3F,
0x3F,
0x1F},
/* Index 0x44~0x47 */
{0x3F, 0x3F, 0x1F}, {0x37, 0x3F, 0x1F}, {0x2F, 0x3F, 0x1F}, {0x27,
0x3F,
0x1F},
/* Index 0x48~0x4B */
{0x1F, 0x3F, 0x1F}, {0x1F, 0x3F, 0x27}, {0x1F, 0x3F, 0x2F}, {0x1F,
0x3F,
0x37},
/* Index 0x4C~0x4F */
{0x1F, 0x3F, 0x3F}, {0x1F, 0x37, 0x3F}, {0x1F, 0x2F, 0x3F}, {0x1F,
0x27,
0x3F},
/* Index 0x50~0x53 */
{0x2D, 0x2D, 0x3F}, {0x31, 0x2D, 0x3F}, {0x36, 0x2D, 0x3F}, {0x3A,
0x2D,
0x3F},
/* Index 0x54~0x57 */
{0x3F, 0x2D, 0x3F}, {0x3F, 0x2D, 0x3A}, {0x3F, 0x2D, 0x36}, {0x3F,
0x2D,
0x31},
/* Index 0x58~0x5B */
{0x3F, 0x2D, 0x2D}, {0x3F, 0x31, 0x2D}, {0x3F, 0x36, 0x2D}, {0x3F,
0x3A,
0x2D},
/* Index 0x5C~0x5F */
{0x3F, 0x3F, 0x2D}, {0x3A, 0x3F, 0x2D}, {0x36, 0x3F, 0x2D}, {0x31,
0x3F,
0x2D},
/* Index 0x60~0x63 */
{0x2D, 0x3F, 0x2D}, {0x2D, 0x3F, 0x31}, {0x2D, 0x3F, 0x36}, {0x2D,
0x3F,
0x3A},
/* Index 0x64~0x67 */
{0x2D, 0x3F, 0x3F}, {0x2D, 0x3A, 0x3F}, {0x2D, 0x36, 0x3F}, {0x2D,
0x31,
0x3F},
/* Index 0x68~0x6B */
{0x00, 0x00, 0x1C}, {0x07, 0x00, 0x1C}, {0x0E, 0x00, 0x1C}, {0x15,
0x00,
0x1C},
/* Index 0x6C~0x6F */
{0x1C, 0x00, 0x1C}, {0x1C, 0x00, 0x15}, {0x1C, 0x00, 0x0E}, {0x1C,
0x00,
0x07},
/* Index 0x70~0x73 */
{0x1C, 0x00, 0x00}, {0x1C, 0x07, 0x00}, {0x1C, 0x0E, 0x00}, {0x1C,
0x15,
0x00},
/* Index 0x74~0x77 */
{0x1C, 0x1C, 0x00}, {0x15, 0x1C, 0x00}, {0x0E, 0x1C, 0x00}, {0x07,
0x1C,
0x00},
/* Index 0x78~0x7B */
{0x00, 0x1C, 0x00}, {0x00, 0x1C, 0x07}, {0x00, 0x1C, 0x0E}, {0x00,
0x1C,
0x15},
/* Index 0x7C~0x7F */
{0x00, 0x1C, 0x1C}, {0x00, 0x15, 0x1C}, {0x00, 0x0E, 0x1C}, {0x00,
0x07,
0x1C},
/* Index 0x80~0x83 */
{0x0E, 0x0E, 0x1C}, {0x11, 0x0E, 0x1C}, {0x15, 0x0E, 0x1C}, {0x18,
0x0E,
0x1C},
/* Index 0x84~0x87 */
{0x1C, 0x0E, 0x1C}, {0x1C, 0x0E, 0x18}, {0x1C, 0x0E, 0x15}, {0x1C,
0x0E,
0x11},
/* Index 0x88~0x8B */
{0x1C, 0x0E, 0x0E}, {0x1C, 0x11, 0x0E}, {0x1C, 0x15, 0x0E}, {0x1C,
0x18,
0x0E},
/* Index 0x8C~0x8F */
{0x1C, 0x1C, 0x0E}, {0x18, 0x1C, 0x0E}, {0x15, 0x1C, 0x0E}, {0x11,
0x1C,
0x0E},
/* Index 0x90~0x93 */
{0x0E, 0x1C, 0x0E}, {0x0E, 0x1C, 0x11}, {0x0E, 0x1C, 0x15}, {0x0E,
0x1C,
0x18},
/* Index 0x94~0x97 */
{0x0E, 0x1C, 0x1C}, {0x0E, 0x18, 0x1C}, {0x0E, 0x15, 0x1C}, {0x0E,
0x11,
0x1C},
/* Index 0x98~0x9B */
{0x14, 0x14, 0x1C}, {0x16, 0x14, 0x1C}, {0x18, 0x14, 0x1C}, {0x1A,
0x14,
0x1C},
/* Index 0x9C~0x9F */
{0x1C, 0x14, 0x1C}, {0x1C, 0x14, 0x1A}, {0x1C, 0x14, 0x18}, {0x1C,
0x14,
0x16},
/* Index 0xA0~0xA3 */
{0x1C, 0x14, 0x14}, {0x1C, 0x16, 0x14}, {0x1C, 0x18, 0x14}, {0x1C,
0x1A,
0x14},
/* Index 0xA4~0xA7 */
{0x1C, 0x1C, 0x14}, {0x1A, 0x1C, 0x14}, {0x18, 0x1C, 0x14}, {0x16,
0x1C,
0x14},
/* Index 0xA8~0xAB */
{0x14, 0x1C, 0x14}, {0x14, 0x1C, 0x16}, {0x14, 0x1C, 0x18}, {0x14,
0x1C,
0x1A},
/* Index 0xAC~0xAF */
{0x14, 0x1C, 0x1C}, {0x14, 0x1A, 0x1C}, {0x14, 0x18, 0x1C}, {0x14,
0x16,
0x1C},
/* Index 0xB0~0xB3 */
{0x00, 0x00, 0x10}, {0x04, 0x00, 0x10}, {0x08, 0x00, 0x10}, {0x0C,
0x00,
0x10},
/* Index 0xB4~0xB7 */
{0x10, 0x00, 0x10}, {0x10, 0x00, 0x0C}, {0x10, 0x00, 0x08}, {0x10,
0x00,
0x04},
/* Index 0xB8~0xBB */
{0x10, 0x00, 0x00}, {0x10, 0x04, 0x00}, {0x10, 0x08, 0x00}, {0x10,
0x0C,
0x00},
/* Index 0xBC~0xBF */
{0x10, 0x10, 0x00}, {0x0C, 0x10, 0x00}, {0x08, 0x10, 0x00}, {0x04,
0x10,
0x00},
/* Index 0xC0~0xC3 */
{0x00, 0x10, 0x00}, {0x00, 0x10, 0x04}, {0x00, 0x10, 0x08}, {0x00,
0x10,
0x0C},
/* Index 0xC4~0xC7 */
{0x00, 0x10, 0x10}, {0x00, 0x0C, 0x10}, {0x00, 0x08, 0x10}, {0x00,
0x04,
0x10},
/* Index 0xC8~0xCB */
{0x08, 0x08, 0x10}, {0x0A, 0x08, 0x10}, {0x0C, 0x08, 0x10}, {0x0E,
0x08,
0x10},
/* Index 0xCC~0xCF */
{0x10, 0x08, 0x10}, {0x10, 0x08, 0x0E}, {0x10, 0x08, 0x0C}, {0x10,
0x08,
0x0A},
/* Index 0xD0~0xD3 */
{0x10, 0x08, 0x08}, {0x10, 0x0A, 0x08}, {0x10, 0x0C, 0x08}, {0x10,
0x0E,
0x08},
/* Index 0xD4~0xD7 */
{0x10, 0x10, 0x08}, {0x0E, 0x10, 0x08}, {0x0C, 0x10, 0x08}, {0x0A,
0x10,
0x08},
/* Index 0xD8~0xDB */
{0x08, 0x10, 0x08}, {0x08, 0x10, 0x0A}, {0x08, 0x10, 0x0C}, {0x08,
0x10,
0x0E},
/* Index 0xDC~0xDF */
{0x08, 0x10, 0x10}, {0x08, 0x0E, 0x10}, {0x08, 0x0C, 0x10}, {0x08,
0x0A,
0x10},
/* Index 0xE0~0xE3 */
{0x0B, 0x0B, 0x10}, {0x0C, 0x0B, 0x10}, {0x0D, 0x0B, 0x10}, {0x0F,
0x0B,
0x10},
/* Index 0xE4~0xE7 */
{0x10, 0x0B, 0x10}, {0x10, 0x0B, 0x0F}, {0x10, 0x0B, 0x0D}, {0x10,
0x0B,
0x0C},
/* Index 0xE8~0xEB */
{0x10, 0x0B, 0x0B}, {0x10, 0x0C, 0x0B}, {0x10, 0x0D, 0x0B}, {0x10,
0x0F,
0x0B},
/* Index 0xEC~0xEF */
{0x10, 0x10, 0x0B}, {0x0F, 0x10, 0x0B}, {0x0D, 0x10, 0x0B}, {0x0C,
0x10,
0x0B},
/* Index 0xF0~0xF3 */
{0x0B, 0x10, 0x0B}, {0x0B, 0x10, 0x0C}, {0x0B, 0x10, 0x0D}, {0x0B,
0x10,
0x0F},
/* Index 0xF4~0xF7 */
{0x0B, 0x10, 0x10}, {0x0B, 0x0F, 0x10}, {0x0B, 0x0D, 0x10}, {0x0B,
0x0C,
0x10},
/* Index 0xF8~0xFB */
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00,
0x00,
0x00},
/* Index 0xFC~0xFF */
{0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00, 0x00, 0x00}, {0x00,
0x00,
0x00}
};
static struct via_device_mapping device_mapping[] = {
{VIA_LDVP0, "LDVP0"},
{VIA_LDVP1, "LDVP1"},
{VIA_DVP0, "DVP0"},
{VIA_CRT, "CRT"},
{VIA_DVP1, "DVP1"},
{VIA_LVDS1, "LVDS1"},
{VIA_LVDS2, "LVDS2"}
};
/* structure with function pointers to support clock control */
static struct via_clock clock;
static void load_fix_bit_crtc_reg(void);
static void init_gfx_chip_info(int chip_type);
static void init_tmds_chip_info(void);
static void init_lvds_chip_info(void);
static void device_screen_off(void);
static void device_screen_on(void);
static void set_display_channel(void);
static void device_off(void);
static void device_on(void);
static void enable_second_display_channel(void);
static void disable_second_display_channel(void);
void viafb_lock_crt(void)
{
viafb_write_reg_mask(CR11, VIACR, BIT7, BIT7);
}
void viafb_unlock_crt(void)
{
viafb_write_reg_mask(CR11, VIACR, 0, BIT7);
viafb_write_reg_mask(CR47, VIACR, 0, BIT0);
}
static void write_dac_reg(u8 index, u8 r, u8 g, u8 b)
{
outb(index, LUT_INDEX_WRITE);
outb(r, LUT_DATA);
outb(g, LUT_DATA);
outb(b, LUT_DATA);
}
static u32 get_dvi_devices(int output_interface)
{
switch (output_interface) {
case INTERFACE_DVP0:
return VIA_DVP0 | VIA_LDVP0;
case INTERFACE_DVP1:
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
return VIA_LDVP1;
else
return VIA_DVP1;
case INTERFACE_DFP_HIGH:
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
return 0;
else
return VIA_LVDS2 | VIA_DVP0;
case INTERFACE_DFP_LOW:
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
return 0;
else
return VIA_DVP1 | VIA_LVDS1;
case INTERFACE_TMDS:
return VIA_LVDS1;
}
return 0;
}
static u32 get_lcd_devices(int output_interface)
{
switch (output_interface) {
case INTERFACE_DVP0:
return VIA_DVP0;
case INTERFACE_DVP1:
return VIA_DVP1;
case INTERFACE_DFP_HIGH:
return VIA_LVDS2 | VIA_DVP0;
case INTERFACE_DFP_LOW:
return VIA_LVDS1 | VIA_DVP1;
case INTERFACE_DFP:
return VIA_LVDS1 | VIA_LVDS2;
case INTERFACE_LVDS0:
case INTERFACE_LVDS0LVDS1:
return VIA_LVDS1;
case INTERFACE_LVDS1:
return VIA_LVDS2;
}
return 0;
}
/*Set IGA path for each device*/
void viafb_set_iga_path(void)
{
int crt_iga_path = 0;
if (viafb_SAMM_ON == 1) {
if (viafb_CRT_ON) {
if (viafb_primary_dev == CRT_Device)
crt_iga_path = IGA1;
else
crt_iga_path = IGA2;
}
if (viafb_DVI_ON) {
if (viafb_primary_dev == DVI_Device)
viaparinfo->tmds_setting_info->iga_path = IGA1;
else
viaparinfo->tmds_setting_info->iga_path = IGA2;
}
if (viafb_LCD_ON) {
if (viafb_primary_dev == LCD_Device) {
if (viafb_dual_fb &&
(viaparinfo->chip_info->gfx_chip_name ==
UNICHROME_CLE266)) {
viaparinfo->
lvds_setting_info->iga_path = IGA2;
crt_iga_path = IGA1;
viaparinfo->
tmds_setting_info->iga_path = IGA1;
} else
viaparinfo->
lvds_setting_info->iga_path = IGA1;
} else {
viaparinfo->lvds_setting_info->iga_path = IGA2;
}
}
if (viafb_LCD2_ON) {
if (LCD2_Device == viafb_primary_dev)
viaparinfo->lvds_setting_info2->iga_path = IGA1;
else
viaparinfo->lvds_setting_info2->iga_path = IGA2;
}
} else {
viafb_SAMM_ON = 0;
if (viafb_CRT_ON && viafb_LCD_ON) {
crt_iga_path = IGA1;
viaparinfo->lvds_setting_info->iga_path = IGA2;
} else if (viafb_CRT_ON && viafb_DVI_ON) {
crt_iga_path = IGA1;
viaparinfo->tmds_setting_info->iga_path = IGA2;
} else if (viafb_LCD_ON && viafb_DVI_ON) {
viaparinfo->tmds_setting_info->iga_path = IGA1;
viaparinfo->lvds_setting_info->iga_path = IGA2;
} else if (viafb_LCD_ON && viafb_LCD2_ON) {
viaparinfo->lvds_setting_info->iga_path = IGA2;
viaparinfo->lvds_setting_info2->iga_path = IGA2;
} else if (viafb_CRT_ON) {
crt_iga_path = IGA1;
} else if (viafb_LCD_ON) {
viaparinfo->lvds_setting_info->iga_path = IGA2;
} else if (viafb_DVI_ON) {
viaparinfo->tmds_setting_info->iga_path = IGA1;
}
}
viaparinfo->shared->iga1_devices = 0;
viaparinfo->shared->iga2_devices = 0;
if (viafb_CRT_ON) {
if (crt_iga_path == IGA1)
viaparinfo->shared->iga1_devices |= VIA_CRT;
else
viaparinfo->shared->iga2_devices |= VIA_CRT;
}
if (viafb_DVI_ON) {
if (viaparinfo->tmds_setting_info->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= get_dvi_devices(
viaparinfo->chip_info->
tmds_chip_info.output_interface);
else
viaparinfo->shared->iga2_devices |= get_dvi_devices(
viaparinfo->chip_info->
tmds_chip_info.output_interface);
}
if (viafb_LCD_ON) {
if (viaparinfo->lvds_setting_info->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info.output_interface);
else
viaparinfo->shared->iga2_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info.output_interface);
}
if (viafb_LCD2_ON) {
if (viaparinfo->lvds_setting_info2->iga_path == IGA1)
viaparinfo->shared->iga1_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info2.output_interface);
else
viaparinfo->shared->iga2_devices |= get_lcd_devices(
viaparinfo->chip_info->
lvds_chip_info2.output_interface);
}
/* looks like the OLPC has its display wired to DVP1 and LVDS2 */
if (machine_is_olpc())
viaparinfo->shared->iga2_devices = VIA_DVP1 | VIA_LVDS2;
}
static void set_color_register(u8 index, u8 red, u8 green, u8 blue)
{
outb(0xFF, 0x3C6); /* bit mask of palette */
outb(index, 0x3C8);
outb(red, 0x3C9);
outb(green, 0x3C9);
outb(blue, 0x3C9);
}
void viafb_set_primary_color_register(u8 index, u8 red, u8 green, u8 blue)
{
viafb_write_reg_mask(0x1A, VIASR, 0x00, 0x01);
set_color_register(index, red, green, blue);
}
void viafb_set_secondary_color_register(u8 index, u8 red, u8 green, u8 blue)
{
viafb_write_reg_mask(0x1A, VIASR, 0x01, 0x01);
set_color_register(index, red, green, blue);
}
static void set_source_common(u8 index, u8 offset, u8 iga)
{
u8 value, mask = 1 << offset;
switch (iga) {
case IGA1:
value = 0x00;
break;
case IGA2:
value = mask;
break;
default:
printk(KERN_WARNING "viafb: Unsupported source: %d\n", iga);
return;
}
via_write_reg_mask(VIACR, index, value, mask);
}
static void set_crt_source(u8 iga)
{
u8 value;
switch (iga) {
case IGA1:
value = 0x00;
break;
case IGA2:
value = 0x40;
break;
default:
printk(KERN_WARNING "viafb: Unsupported source: %d\n", iga);
return;
}
via_write_reg_mask(VIASR, 0x16, value, 0x40);
}
static inline void set_ldvp0_source(u8 iga)
{
set_source_common(0x6C, 7, iga);
}
static inline void set_ldvp1_source(u8 iga)
{
set_source_common(0x93, 7, iga);
}
static inline void set_dvp0_source(u8 iga)
{
set_source_common(0x96, 4, iga);
}
static inline void set_dvp1_source(u8 iga)
{
set_source_common(0x9B, 4, iga);
}
static inline void set_lvds1_source(u8 iga)
{
set_source_common(0x99, 4, iga);
}
static inline void set_lvds2_source(u8 iga)
{
set_source_common(0x97, 4, iga);
}
void via_set_source(u32 devices, u8 iga)
{
if (devices & VIA_LDVP0)
set_ldvp0_source(iga);
if (devices & VIA_LDVP1)
set_ldvp1_source(iga);
if (devices & VIA_DVP0)
set_dvp0_source(iga);
if (devices & VIA_CRT)
set_crt_source(iga);
if (devices & VIA_DVP1)
set_dvp1_source(iga);
if (devices & VIA_LVDS1)
set_lvds1_source(iga);
if (devices & VIA_LVDS2)
set_lvds2_source(iga);
}
static void set_crt_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x00;
break;
case VIA_STATE_STANDBY:
value = 0x10;
break;
case VIA_STATE_SUSPEND:
value = 0x20;
break;
case VIA_STATE_OFF:
value = 0x30;
break;
default:
return;
}
via_write_reg_mask(VIACR, 0x36, value, 0x30);
}
static void set_dvp0_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0xC0;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x1E, value, 0xC0);
}
static void set_dvp1_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x30;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x1E, value, 0x30);
}
static void set_lvds1_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x03;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x2A, value, 0x03);
}
static void set_lvds2_state(u8 state)
{
u8 value;
switch (state) {
case VIA_STATE_ON:
value = 0x0C;
break;
case VIA_STATE_OFF:
value = 0x00;
break;
default:
return;
}
via_write_reg_mask(VIASR, 0x2A, value, 0x0C);
}
void via_set_state(u32 devices, u8 state)
{
/*
TODO: Can we enable/disable these devices? How?
if (devices & VIA_LDVP0)
if (devices & VIA_LDVP1)
*/
if (devices & VIA_DVP0)
set_dvp0_state(state);
if (devices & VIA_CRT)
set_crt_state(state);
if (devices & VIA_DVP1)
set_dvp1_state(state);
if (devices & VIA_LVDS1)
set_lvds1_state(state);
if (devices & VIA_LVDS2)
set_lvds2_state(state);
}
void via_set_sync_polarity(u32 devices, u8 polarity)
{
if (polarity & ~(VIA_HSYNC_NEGATIVE | VIA_VSYNC_NEGATIVE)) {
printk(KERN_WARNING "viafb: Unsupported polarity: %d\n",
polarity);
return;
}
if (devices & VIA_CRT)
via_write_misc_reg_mask(polarity << 6, 0xC0);
if (devices & VIA_DVP1)
via_write_reg_mask(VIACR, 0x9B, polarity << 5, 0x60);
if (devices & VIA_LVDS1)
via_write_reg_mask(VIACR, 0x99, polarity << 5, 0x60);
if (devices & VIA_LVDS2)
via_write_reg_mask(VIACR, 0x97, polarity << 5, 0x60);
}
u32 via_parse_odev(char *input, char **end)
{
char *ptr = input;
u32 odev = 0;
bool next = true;
int i, len;
while (next) {
next = false;
for (i = 0; i < ARRAY_SIZE(device_mapping); i++) {
len = strlen(device_mapping[i].name);
if (!strncmp(ptr, device_mapping[i].name, len)) {
odev |= device_mapping[i].device;
ptr += len;
if (*ptr == ',') {
ptr++;
next = true;
}
}
}
}
*end = ptr;
return odev;
}
void via_odev_to_seq(struct seq_file *m, u32 odev)
{
int i, count = 0;
for (i = 0; i < ARRAY_SIZE(device_mapping); i++) {
if (odev & device_mapping[i].device) {
if (count > 0)
seq_putc(m, ',');
seq_puts(m, device_mapping[i].name);
count++;
}
}
seq_putc(m, '\n');
}
static void load_fix_bit_crtc_reg(void)
{
viafb_unlock_crt();
/* always set to 1 */
viafb_write_reg_mask(CR03, VIACR, 0x80, BIT7);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg_mask(CR35, VIACR, 0x10, BIT4);
/* line compare should set all bits = 1 (extend modes) */
viafb_write_reg_mask(CR33, VIACR, 0x06, BIT0 + BIT1 + BIT2);
/*viafb_write_reg_mask(CR32, VIACR, 0x01, BIT0); */
viafb_lock_crt();
/* If K8M800, enable Prefetch Mode. */
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800)
|| (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890))
viafb_write_reg_mask(CR33, VIACR, 0x08, BIT3);
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266)
&& (viaparinfo->chip_info->gfx_chip_revision == CLE266_REVISION_AX))
viafb_write_reg_mask(SR1A, VIASR, 0x02, BIT1);
}
void viafb_load_reg(int timing_value, int viafb_load_reg_num,
struct io_register *reg,
int io_type)
{
int reg_mask;
int bit_num = 0;
int data;
int i, j;
int shift_next_reg;
int start_index, end_index, cr_index;
u16 get_bit;
for (i = 0; i < viafb_load_reg_num; i++) {
reg_mask = 0;
data = 0;
start_index = reg[i].start_bit;
end_index = reg[i].end_bit;
cr_index = reg[i].io_addr;
shift_next_reg = bit_num;
for (j = start_index; j <= end_index; j++) {
/*if (bit_num==8) timing_value = timing_value >>8; */
reg_mask = reg_mask | (BIT0 << j);
get_bit = (timing_value & (BIT0 << bit_num));
data =
data | ((get_bit >> shift_next_reg) << start_index);
bit_num++;
}
if (io_type == VIACR)
viafb_write_reg_mask(cr_index, VIACR, data, reg_mask);
else
viafb_write_reg_mask(cr_index, VIASR, data, reg_mask);
}
}
/* Write Registers */
void viafb_write_regx(struct io_reg RegTable[], int ItemNum)
{
int i;
/*DEBUG_MSG(KERN_INFO "Table Size : %x!!\n",ItemNum ); */
for (i = 0; i < ItemNum; i++)
via_write_reg_mask(RegTable[i].port, RegTable[i].index,
RegTable[i].value, RegTable[i].mask);
}
void viafb_load_fetch_count_reg(int h_addr, int bpp_byte, int set_iga)
{
int reg_value;
int viafb_load_reg_num;
struct io_register *reg = NULL;
switch (set_iga) {
case IGA1:
reg_value = IGA1_FETCH_COUNT_FORMULA(h_addr, bpp_byte);
viafb_load_reg_num = fetch_count_reg.
iga1_fetch_count_reg.reg_num;
reg = fetch_count_reg.iga1_fetch_count_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
break;
case IGA2:
reg_value = IGA2_FETCH_COUNT_FORMULA(h_addr, bpp_byte);
viafb_load_reg_num = fetch_count_reg.
iga2_fetch_count_reg.reg_num;
reg = fetch_count_reg.iga2_fetch_count_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
break;
}
}
void viafb_load_FIFO_reg(int set_iga, int hor_active, int ver_active)
{
int reg_value;
int viafb_load_reg_num;
struct io_register *reg = NULL;
int iga1_fifo_max_depth = 0, iga1_fifo_threshold =
0, iga1_fifo_high_threshold = 0, iga1_display_queue_expire_num = 0;
int iga2_fifo_max_depth = 0, iga2_fifo_threshold =
0, iga2_fifo_high_threshold = 0, iga2_display_queue_expire_num = 0;
if (set_iga == IGA1) {
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) {
iga1_fifo_max_depth = K800_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = K800_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
K800_IGA1_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64, else
expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga1_display_queue_expire_num = 16;
else
iga1_display_queue_expire_num =
K800_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_PM800) {
iga1_fifo_max_depth = P880_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = P880_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
P880_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
P880_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
/* If resolution > 1280x1024, expire length = 64, else
expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga1_display_queue_expire_num = 16;
else
iga1_display_queue_expire_num =
P880_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CN700) {
iga1_fifo_max_depth = CN700_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = CN700_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
CN700_IGA1_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga1_display_queue_expire_num = 16;
else
iga1_display_queue_expire_num =
CN700_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
iga1_fifo_max_depth = CX700_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = CX700_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
CX700_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
CX700_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890) {
iga1_fifo_max_depth = K8M890_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = K8M890_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
K8M890_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
K8M890_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M890) {
iga1_fifo_max_depth = P4M890_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = P4M890_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
P4M890_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
P4M890_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M900) {
iga1_fifo_max_depth = P4M900_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = P4M900_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
P4M900_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
P4M900_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX800) {
iga1_fifo_max_depth = VX800_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = VX800_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
VX800_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
VX800_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX855) {
iga1_fifo_max_depth = VX855_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = VX855_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
VX855_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
VX855_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX900) {
iga1_fifo_max_depth = VX900_IGA1_FIFO_MAX_DEPTH;
iga1_fifo_threshold = VX900_IGA1_FIFO_THRESHOLD;
iga1_fifo_high_threshold =
VX900_IGA1_FIFO_HIGH_THRESHOLD;
iga1_display_queue_expire_num =
VX900_IGA1_DISPLAY_QUEUE_EXPIRE_NUM;
}
/* Set Display FIFO Depath Select */
reg_value = IGA1_FIFO_DEPTH_SELECT_FORMULA(iga1_fifo_max_depth);
viafb_load_reg_num =
display_fifo_depth_reg.iga1_fifo_depth_select_reg.reg_num;
reg = display_fifo_depth_reg.iga1_fifo_depth_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
/* Set Display FIFO Threshold Select */
reg_value = IGA1_FIFO_THRESHOLD_FORMULA(iga1_fifo_threshold);
viafb_load_reg_num =
fifo_threshold_select_reg.
iga1_fifo_threshold_select_reg.reg_num;
reg =
fifo_threshold_select_reg.
iga1_fifo_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
/* Set FIFO High Threshold Select */
reg_value =
IGA1_FIFO_HIGH_THRESHOLD_FORMULA(iga1_fifo_high_threshold);
viafb_load_reg_num =
fifo_high_threshold_select_reg.
iga1_fifo_high_threshold_select_reg.reg_num;
reg =
fifo_high_threshold_select_reg.
iga1_fifo_high_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
/* Set Display Queue Expire Num */
reg_value =
IGA1_DISPLAY_QUEUE_EXPIRE_NUM_FORMULA
(iga1_display_queue_expire_num);
viafb_load_reg_num =
display_queue_expire_num_reg.
iga1_display_queue_expire_num_reg.reg_num;
reg =
display_queue_expire_num_reg.
iga1_display_queue_expire_num_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIASR);
} else {
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) {
iga2_fifo_max_depth = K800_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = K800_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
K800_IGA2_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga2_display_queue_expire_num = 16;
else
iga2_display_queue_expire_num =
K800_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_PM800) {
iga2_fifo_max_depth = P880_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = P880_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
P880_IGA2_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga2_display_queue_expire_num = 16;
else
iga2_display_queue_expire_num =
P880_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CN700) {
iga2_fifo_max_depth = CN700_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = CN700_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
CN700_IGA2_FIFO_HIGH_THRESHOLD;
/* If resolution > 1280x1024, expire length = 64,
else expire length = 128 */
if ((hor_active > 1280) && (ver_active > 1024))
iga2_display_queue_expire_num = 16;
else
iga2_display_queue_expire_num =
CN700_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
iga2_fifo_max_depth = CX700_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = CX700_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
CX700_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
CX700_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K8M890) {
iga2_fifo_max_depth = K8M890_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = K8M890_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
K8M890_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
K8M890_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M890) {
iga2_fifo_max_depth = P4M890_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = P4M890_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
P4M890_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
P4M890_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_P4M900) {
iga2_fifo_max_depth = P4M900_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = P4M900_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
P4M900_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
P4M900_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX800) {
iga2_fifo_max_depth = VX800_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = VX800_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
VX800_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
VX800_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX855) {
iga2_fifo_max_depth = VX855_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = VX855_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
VX855_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
VX855_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_VX900) {
iga2_fifo_max_depth = VX900_IGA2_FIFO_MAX_DEPTH;
iga2_fifo_threshold = VX900_IGA2_FIFO_THRESHOLD;
iga2_fifo_high_threshold =
VX900_IGA2_FIFO_HIGH_THRESHOLD;
iga2_display_queue_expire_num =
VX900_IGA2_DISPLAY_QUEUE_EXPIRE_NUM;
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_K800) {
/* Set Display FIFO Depath Select */
reg_value =
IGA2_FIFO_DEPTH_SELECT_FORMULA(iga2_fifo_max_depth)
- 1;
/* Patch LCD in IGA2 case */
viafb_load_reg_num =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg_num;
reg =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
} else {
/* Set Display FIFO Depath Select */
reg_value =
IGA2_FIFO_DEPTH_SELECT_FORMULA(iga2_fifo_max_depth);
viafb_load_reg_num =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg_num;
reg =
display_fifo_depth_reg.
iga2_fifo_depth_select_reg.reg;
viafb_load_reg(reg_value,
viafb_load_reg_num, reg, VIACR);
}
/* Set Display FIFO Threshold Select */
reg_value = IGA2_FIFO_THRESHOLD_FORMULA(iga2_fifo_threshold);
viafb_load_reg_num =
fifo_threshold_select_reg.
iga2_fifo_threshold_select_reg.reg_num;
reg =
fifo_threshold_select_reg.
iga2_fifo_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
/* Set FIFO High Threshold Select */
reg_value =
IGA2_FIFO_HIGH_THRESHOLD_FORMULA(iga2_fifo_high_threshold);
viafb_load_reg_num =
fifo_high_threshold_select_reg.
iga2_fifo_high_threshold_select_reg.reg_num;
reg =
fifo_high_threshold_select_reg.
iga2_fifo_high_threshold_select_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
/* Set Display Queue Expire Num */
reg_value =
IGA2_DISPLAY_QUEUE_EXPIRE_NUM_FORMULA
(iga2_display_queue_expire_num);
viafb_load_reg_num =
display_queue_expire_num_reg.
iga2_display_queue_expire_num_reg.reg_num;
reg =
display_queue_expire_num_reg.
iga2_display_queue_expire_num_reg.reg;
viafb_load_reg(reg_value, viafb_load_reg_num, reg, VIACR);
}
}
static struct via_pll_config get_pll_config(struct pll_limit *limits, int size,
int clk)
{
struct via_pll_config cur, up, down, best = {0, 1, 0};
const u32 f0 = 14318180; /* X1 frequency */
int i, f;
for (i = 0; i < size; i++) {
cur.rshift = limits[i].rshift;
cur.divisor = limits[i].divisor;
cur.multiplier = clk / ((f0 / cur.divisor)>>cur.rshift);
f = abs(get_pll_output_frequency(f0, cur) - clk);
up = down = cur;
up.multiplier++;
down.multiplier--;
if (abs(get_pll_output_frequency(f0, up) - clk) < f)
cur = up;
else if (abs(get_pll_output_frequency(f0, down) - clk) < f)
cur = down;
if (cur.multiplier < limits[i].multiplier_min)
cur.multiplier = limits[i].multiplier_min;
else if (cur.multiplier > limits[i].multiplier_max)
cur.multiplier = limits[i].multiplier_max;
f = abs(get_pll_output_frequency(f0, cur) - clk);
if (f < abs(get_pll_output_frequency(f0, best) - clk))
best = cur;
}
return best;
}
static struct via_pll_config get_best_pll_config(int clk)
{
struct via_pll_config config;
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
case UNICHROME_K400:
config = get_pll_config(cle266_pll_limits,
ARRAY_SIZE(cle266_pll_limits), clk);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
case UNICHROME_CN700:
config = get_pll_config(k800_pll_limits,
ARRAY_SIZE(k800_pll_limits), clk);
break;
case UNICHROME_CX700:
case UNICHROME_CN750:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
case UNICHROME_VX800:
config = get_pll_config(cx700_pll_limits,
ARRAY_SIZE(cx700_pll_limits), clk);
break;
case UNICHROME_VX855:
case UNICHROME_VX900:
config = get_pll_config(vx855_pll_limits,
ARRAY_SIZE(vx855_pll_limits), clk);
break;
}
return config;
}
/* Set VCLK*/
void viafb_set_vclock(u32 clk, int set_iga)
{
struct via_pll_config config = get_best_pll_config(clk);
if (set_iga == IGA1)
clock.set_primary_pll(config);
if (set_iga == IGA2)
clock.set_secondary_pll(config);
/* Fire! */
via_write_misc_reg_mask(0x0C, 0x0C); /* select external clock */
}
struct via_display_timing var_to_timing(const struct fb_var_screeninfo *var,
u16 cxres, u16 cyres)
{
struct via_display_timing timing;
u16 dx = (var->xres - cxres) / 2, dy = (var->yres - cyres) / 2;
timing.hor_addr = cxres;
timing.hor_sync_start = timing.hor_addr + var->right_margin + dx;
timing.hor_sync_end = timing.hor_sync_start + var->hsync_len;
timing.hor_total = timing.hor_sync_end + var->left_margin + dx;
timing.hor_blank_start = timing.hor_addr + dx;
timing.hor_blank_end = timing.hor_total - dx;
timing.ver_addr = cyres;
timing.ver_sync_start = timing.ver_addr + var->lower_margin + dy;
timing.ver_sync_end = timing.ver_sync_start + var->vsync_len;
timing.ver_total = timing.ver_sync_end + var->upper_margin + dy;
timing.ver_blank_start = timing.ver_addr + dy;
timing.ver_blank_end = timing.ver_total - dy;
return timing;
}
void viafb_fill_crtc_timing(const struct fb_var_screeninfo *var,
u16 cxres, u16 cyres, int iga)
{
struct via_display_timing crt_reg = var_to_timing(var,
cxres ? cxres : var->xres, cyres ? cyres : var->yres);
if (iga == IGA1)
via_set_primary_timing(&crt_reg);
else if (iga == IGA2)
via_set_secondary_timing(&crt_reg);
viafb_load_fetch_count_reg(var->xres, var->bits_per_pixel / 8, iga);
if (viaparinfo->chip_info->gfx_chip_name != UNICHROME_CLE266
&& viaparinfo->chip_info->gfx_chip_name != UNICHROME_K400)
viafb_load_FIFO_reg(iga, var->xres, var->yres);
viafb_set_vclock(PICOS2KHZ(var->pixclock) * 1000, iga);
}
void viafb_init_chip_info(int chip_type)
{
via_clock_init(&clock, chip_type);
init_gfx_chip_info(chip_type);
init_tmds_chip_info();
init_lvds_chip_info();
/*Set IGA path for each device */
viafb_set_iga_path();
viaparinfo->lvds_setting_info->display_method = viafb_lcd_dsp_method;
viaparinfo->lvds_setting_info->lcd_mode = viafb_lcd_mode;
viaparinfo->lvds_setting_info2->display_method =
viaparinfo->lvds_setting_info->display_method;
viaparinfo->lvds_setting_info2->lcd_mode =
viaparinfo->lvds_setting_info->lcd_mode;
}
void viafb_update_device_setting(int hres, int vres, int bpp, int flag)
{
if (flag == 0) {
viaparinfo->tmds_setting_info->h_active = hres;
viaparinfo->tmds_setting_info->v_active = vres;
} else {
if (viaparinfo->tmds_setting_info->iga_path == IGA2) {
viaparinfo->tmds_setting_info->h_active = hres;
viaparinfo->tmds_setting_info->v_active = vres;
}
}
}
static void init_gfx_chip_info(int chip_type)
{
u8 tmp;
viaparinfo->chip_info->gfx_chip_name = chip_type;
/* Check revision of CLE266 Chip */
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266) {
/* CR4F only define in CLE266.CX chip */
tmp = viafb_read_reg(VIACR, CR4F);
viafb_write_reg(CR4F, VIACR, 0x55);
if (viafb_read_reg(VIACR, CR4F) != 0x55)
viaparinfo->chip_info->gfx_chip_revision =
CLE266_REVISION_AX;
else
viaparinfo->chip_info->gfx_chip_revision =
CLE266_REVISION_CX;
/* restore orignal CR4F value */
viafb_write_reg(CR4F, VIACR, tmp);
}
if (viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700) {
tmp = viafb_read_reg(VIASR, SR43);
DEBUG_MSG(KERN_INFO "SR43:%X\n", tmp);
if (tmp & 0x02) {
viaparinfo->chip_info->gfx_chip_revision =
CX700_REVISION_700M2;
} else if (tmp & 0x40) {
viaparinfo->chip_info->gfx_chip_revision =
CX700_REVISION_700M;
} else {
viaparinfo->chip_info->gfx_chip_revision =
CX700_REVISION_700;
}
}
/* Determine which 2D engine we have */
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_VX800:
case UNICHROME_VX855:
case UNICHROME_VX900:
viaparinfo->chip_info->twod_engine = VIA_2D_ENG_M1;
break;
case UNICHROME_K8M890:
case UNICHROME_P4M900:
viaparinfo->chip_info->twod_engine = VIA_2D_ENG_H5;
break;
default:
viaparinfo->chip_info->twod_engine = VIA_2D_ENG_H2;
break;
}
}
static void init_tmds_chip_info(void)
{
viafb_tmds_trasmitter_identify();
if (INTERFACE_NONE == viaparinfo->chip_info->tmds_chip_info.
output_interface) {
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CX700:
{
/* we should check support by hardware layout.*/
if ((viafb_display_hardware_layout ==
HW_LAYOUT_DVI_ONLY)
|| (viafb_display_hardware_layout ==
HW_LAYOUT_LCD_DVI)) {
viaparinfo->chip_info->tmds_chip_info.
output_interface = INTERFACE_TMDS;
} else {
viaparinfo->chip_info->tmds_chip_info.
output_interface =
INTERFACE_NONE;
}
break;
}
case UNICHROME_K8M890:
case UNICHROME_P4M900:
case UNICHROME_P4M890:
/* TMDS on PCIE, we set DFPLOW as default. */
viaparinfo->chip_info->tmds_chip_info.output_interface =
INTERFACE_DFP_LOW;
break;
default:
{
/* set DVP1 default for DVI */
viaparinfo->chip_info->tmds_chip_info
.output_interface = INTERFACE_DVP1;
}
}
}
DEBUG_MSG(KERN_INFO "TMDS Chip = %d\n",
viaparinfo->chip_info->tmds_chip_info.tmds_chip_name);
viafb_init_dvi_size(&viaparinfo->shared->chip_info.tmds_chip_info,
&viaparinfo->shared->tmds_setting_info);
}
static void init_lvds_chip_info(void)
{
viafb_lvds_trasmitter_identify();
viafb_init_lcd_size();
viafb_init_lvds_output_interface(&viaparinfo->chip_info->lvds_chip_info,
viaparinfo->lvds_setting_info);
if (viaparinfo->chip_info->lvds_chip_info2.lvds_chip_name) {
viafb_init_lvds_output_interface(&viaparinfo->chip_info->
lvds_chip_info2, viaparinfo->lvds_setting_info2);
}
/*If CX700,two singel LCD, we need to reassign
LCD interface to different LVDS port */
if ((UNICHROME_CX700 == viaparinfo->chip_info->gfx_chip_name)
&& (HW_LAYOUT_LCD1_LCD2 == viafb_display_hardware_layout)) {
if ((INTEGRATED_LVDS == viaparinfo->chip_info->lvds_chip_info.
lvds_chip_name) && (INTEGRATED_LVDS ==
viaparinfo->chip_info->
lvds_chip_info2.lvds_chip_name)) {
viaparinfo->chip_info->lvds_chip_info.output_interface =
INTERFACE_LVDS0;
viaparinfo->chip_info->lvds_chip_info2.
output_interface =
INTERFACE_LVDS1;
}
}
DEBUG_MSG(KERN_INFO "LVDS Chip = %d\n",
viaparinfo->chip_info->lvds_chip_info.lvds_chip_name);
DEBUG_MSG(KERN_INFO "LVDS1 output_interface = %d\n",
viaparinfo->chip_info->lvds_chip_info.output_interface);
DEBUG_MSG(KERN_INFO "LVDS2 output_interface = %d\n",
viaparinfo->chip_info->lvds_chip_info.output_interface);
}
void viafb_init_dac(int set_iga)
{
int i;
u8 tmp;
if (set_iga == IGA1) {
/* access Primary Display's LUT */
viafb_write_reg_mask(SR1A, VIASR, 0x00, BIT0);
/* turn off LCK */
viafb_write_reg_mask(SR1B, VIASR, 0x00, BIT7 + BIT6);
for (i = 0; i < 256; i++) {
write_dac_reg(i, palLUT_table[i].red,
palLUT_table[i].green,
palLUT_table[i].blue);
}
/* turn on LCK */
viafb_write_reg_mask(SR1B, VIASR, 0xC0, BIT7 + BIT6);
} else {
tmp = viafb_read_reg(VIACR, CR6A);
/* access Secondary Display's LUT */
viafb_write_reg_mask(CR6A, VIACR, 0x40, BIT6);
viafb_write_reg_mask(SR1A, VIASR, 0x01, BIT0);
for (i = 0; i < 256; i++) {
write_dac_reg(i, palLUT_table[i].red,
palLUT_table[i].green,
palLUT_table[i].blue);
}
/* set IGA1 DAC for default */
viafb_write_reg_mask(SR1A, VIASR, 0x00, BIT0);
viafb_write_reg(CR6A, VIACR, tmp);
}
}
static void device_screen_off(void)
{
/* turn off CRT screen (IGA1) */
viafb_write_reg_mask(SR01, VIASR, 0x20, BIT5);
}
static void device_screen_on(void)
{
/* turn on CRT screen (IGA1) */
viafb_write_reg_mask(SR01, VIASR, 0x00, BIT5);
}
static void set_display_channel(void)
{
/*If viafb_LCD2_ON, on cx700, internal lvds's information
is keeped on lvds_setting_info2 */
if (viafb_LCD2_ON &&
viaparinfo->lvds_setting_info2->device_lcd_dualedge) {
/* For dual channel LCD: */
/* Set to Dual LVDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x20, BIT4 + BIT5);
} else if (viafb_LCD_ON && viafb_DVI_ON) {
/* For LCD+DFP: */
/* Set to LVDS1 + TMDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x10, BIT4 + BIT5);
} else if (viafb_DVI_ON) {
/* Set to single TMDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x30, BIT4 + BIT5);
} else if (viafb_LCD_ON) {
if (viaparinfo->lvds_setting_info->device_lcd_dualedge) {
/* For dual channel LCD: */
/* Set to Dual LVDS channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x20, BIT4 + BIT5);
} else {
/* Set to LVDS0 + LVDS1 channel. */
viafb_write_reg_mask(CRD2, VIACR, 0x00, BIT4 + BIT5);
}
}
}
static u8 get_sync(struct fb_var_screeninfo *var)
{
u8 polarity = 0;
if (!(var->sync & FB_SYNC_HOR_HIGH_ACT))
polarity |= VIA_HSYNC_NEGATIVE;
if (!(var->sync & FB_SYNC_VERT_HIGH_ACT))
polarity |= VIA_VSYNC_NEGATIVE;
return polarity;
}
static void hw_init(void)
{
int i;
inb(VIAStatus);
outb(0x00, VIAAR);
/* Write Common Setting for Video Mode */
viafb_write_regx(common_vga, ARRAY_SIZE(common_vga));
switch (viaparinfo->chip_info->gfx_chip_name) {
case UNICHROME_CLE266:
viafb_write_regx(CLE266_ModeXregs, NUM_TOTAL_CLE266_ModeXregs);
break;
case UNICHROME_K400:
viafb_write_regx(KM400_ModeXregs, NUM_TOTAL_KM400_ModeXregs);
break;
case UNICHROME_K800:
case UNICHROME_PM800:
viafb_write_regx(CN400_ModeXregs, NUM_TOTAL_CN400_ModeXregs);
break;
case UNICHROME_CN700:
case UNICHROME_K8M890:
case UNICHROME_P4M890:
case UNICHROME_P4M900:
viafb_write_regx(CN700_ModeXregs, NUM_TOTAL_CN700_ModeXregs);
break;
case UNICHROME_CX700:
case UNICHROME_VX800:
viafb_write_regx(CX700_ModeXregs, NUM_TOTAL_CX700_ModeXregs);
break;
case UNICHROME_VX855:
case UNICHROME_VX900:
viafb_write_regx(VX855_ModeXregs, NUM_TOTAL_VX855_ModeXregs);
break;
}
/* magic required on VX900 for correct modesetting on IGA1 */
via_write_reg_mask(VIACR, 0x45, 0x00, 0x01);
/* probably this should go to the scaling code one day */
via_write_reg_mask(VIACR, 0xFD, 0, 0x80); /* VX900 hw scale on IGA2 */
viafb_write_regx(scaling_parameters, ARRAY_SIZE(scaling_parameters));
/* Fill VPIT Parameters */
/* Write Misc Register */
outb(VPIT.Misc, VIA_MISC_REG_WRITE);
/* Write Sequencer */
for (i = 1; i <= StdSR; i++)
via_write_reg(VIASR, i, VPIT.SR[i - 1]);
viafb_write_reg_mask(0x15, VIASR, 0xA2, 0xA2);
/* Write Graphic Controller */
for (i = 0; i < StdGR; i++)
via_write_reg(VIAGR, i, VPIT.GR[i]);
/* Write Attribute Controller */
for (i = 0; i < StdAR; i++) {
inb(VIAStatus);
outb(i, VIAAR);
outb(VPIT.AR[i], VIAAR);
}
inb(VIAStatus);
outb(0x20, VIAAR);
load_fix_bit_crtc_reg();
}
int viafb_setmode(void)
{
int j, cxres = 0, cyres = 0;
int port;
u32 devices = viaparinfo->shared->iga1_devices
| viaparinfo->shared->iga2_devices;
u8 value, index, mask;
struct fb_var_screeninfo var2;
device_screen_off();
device_off();
via_set_state(devices, VIA_STATE_OFF);
hw_init();
/* Update Patch Register */
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CLE266
|| viaparinfo->chip_info->gfx_chip_name == UNICHROME_K400)
&& viafbinfo->var.xres == 1024 && viafbinfo->var.yres == 768) {
for (j = 0; j < res_patch_table[0].table_length; j++) {
index = res_patch_table[0].io_reg_table[j].index;
port = res_patch_table[0].io_reg_table[j].port;
value = res_patch_table[0].io_reg_table[j].value;
mask = res_patch_table[0].io_reg_table[j].mask;
viafb_write_reg_mask(index, port, value, mask);
}
}
via_set_primary_pitch(viafbinfo->fix.line_length);
via_set_secondary_pitch(viafb_dual_fb ? viafbinfo1->fix.line_length
: viafbinfo->fix.line_length);
via_set_primary_color_depth(viaparinfo->depth);
via_set_secondary_color_depth(viafb_dual_fb ? viaparinfo1->depth
: viaparinfo->depth);
via_set_source(viaparinfo->shared->iga1_devices, IGA1);
via_set_source(viaparinfo->shared->iga2_devices, IGA2);
if (viaparinfo->shared->iga2_devices)
enable_second_display_channel();
else
disable_second_display_channel();
/* Update Refresh Rate Setting */
/* Clear On Screen */
if (viafb_dual_fb) {
var2 = viafbinfo1->var;
} else if (viafb_SAMM_ON) {
viafb_fill_var_timing_info(&var2, viafb_get_best_mode(
viafb_second_xres, viafb_second_yres, viafb_refresh1));
cxres = viafbinfo->var.xres;
cyres = viafbinfo->var.yres;
var2.bits_per_pixel = viafbinfo->var.bits_per_pixel;
}
/* CRT set mode */
if (viafb_CRT_ON) {
if (viaparinfo->shared->iga2_devices & VIA_CRT
&& viafb_SAMM_ON)
viafb_fill_crtc_timing(&var2, cxres, cyres, IGA2);
else
viafb_fill_crtc_timing(&viafbinfo->var, 0, 0,
(viaparinfo->shared->iga1_devices & VIA_CRT)
? IGA1 : IGA2);
/* Patch if set_hres is not 8 alignment (1366) to viafb_setmode
to 8 alignment (1368),there is several pixels (2 pixels)
on right side of screen. */
if (viafbinfo->var.xres % 8) {
viafb_unlock_crt();
viafb_write_reg(CR02, VIACR,
viafb_read_reg(VIACR, CR02) - 1);
viafb_lock_crt();
}
}
if (viafb_DVI_ON) {
if (viaparinfo->shared->tmds_setting_info.iga_path == IGA2
&& viafb_SAMM_ON)
viafb_dvi_set_mode(&var2, cxres, cyres, IGA2);
else
viafb_dvi_set_mode(&viafbinfo->var, 0, 0,
viaparinfo->tmds_setting_info->iga_path);
}
if (viafb_LCD_ON) {
if (viafb_SAMM_ON &&
(viaparinfo->lvds_setting_info->iga_path == IGA2)) {
viafb_lcd_set_mode(&var2, cxres, cyres,
viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
} else {
/* IGA1 doesn't have LCD scaling, so set it center. */
if (viaparinfo->lvds_setting_info->iga_path == IGA1) {
viaparinfo->lvds_setting_info->display_method =
LCD_CENTERING;
}
viafb_lcd_set_mode(&viafbinfo->var, 0, 0,
viaparinfo->lvds_setting_info,
&viaparinfo->chip_info->lvds_chip_info);
}
}
if (viafb_LCD2_ON) {
if (viafb_SAMM_ON &&
(viaparinfo->lvds_setting_info2->iga_path == IGA2)) {
viafb_lcd_set_mode(&var2, cxres, cyres,
viaparinfo->lvds_setting_info2,
&viaparinfo->chip_info->lvds_chip_info2);
} else {
/* IGA1 doesn't have LCD scaling, so set it center. */
if (viaparinfo->lvds_setting_info2->iga_path == IGA1) {
viaparinfo->lvds_setting_info2->display_method =
LCD_CENTERING;
}
viafb_lcd_set_mode(&viafbinfo->var, 0, 0,
viaparinfo->lvds_setting_info2,
&viaparinfo->chip_info->lvds_chip_info2);
}
}
if ((viaparinfo->chip_info->gfx_chip_name == UNICHROME_CX700)
&& (viafb_LCD_ON || viafb_DVI_ON))
set_display_channel();
/* If set mode normally, save resolution information for hot-plug . */
if (!viafb_hotplug) {
viafb_hotplug_Xres = viafbinfo->var.xres;
viafb_hotplug_Yres = viafbinfo->var.yres;
viafb_hotplug_bpp = viafbinfo->var.bits_per_pixel;
viafb_hotplug_refresh = viafb_refresh;
if (viafb_DVI_ON)
viafb_DeviceStatus = DVI_Device;
else
viafb_DeviceStatus = CRT_Device;
}
device_on();
if (!viafb_SAMM_ON)
via_set_sync_polarity(devices, get_sync(&viafbinfo->var));
else {
via_set_sync_polarity(viaparinfo->shared->iga1_devices,
get_sync(&viafbinfo->var));
via_set_sync_polarity(viaparinfo->shared->iga2_devices,
get_sync(&var2));
}
clock.set_engine_pll_state(VIA_STATE_ON);
clock.set_primary_clock_source(VIA_CLKSRC_X1, true);
clock.set_secondary_clock_source(VIA_CLKSRC_X1, true);
#ifdef CONFIG_FB_VIA_X_COMPATIBILITY
clock.set_primary_pll_state(VIA_STATE_ON);
clock.set_primary_clock_state(VIA_STATE_ON);
clock.set_secondary_pll_state(VIA_STATE_ON);
clock.set_secondary_clock_state(VIA_STATE_ON);
#else
if (viaparinfo->shared->iga1_devices) {
clock.set_primary_pll_state(VIA_STATE_ON);
clock.set_primary_clock_state(VIA_STATE_ON);
} else {
clock.set_primary_pll_state(VIA_STATE_OFF);
clock.set_primary_clock_state(VIA_STATE_OFF);
}
if (viaparinfo->shared->iga2_devices) {
clock.set_secondary_pll_state(VIA_STATE_ON);
clock.set_secondary_clock_state(VIA_STATE_ON);
} else {
clock.set_secondary_pll_state(VIA_STATE_OFF);
clock.set_secondary_clock_state(VIA_STATE_OFF);
}
#endif /*CONFIG_FB_VIA_X_COMPATIBILITY*/
via_set_state(devices, VIA_STATE_ON);
device_screen_on();
return 1;
}
int viafb_get_refresh(int hres, int vres, u32 long_refresh)
{
const struct fb_videomode *best;
best = viafb_get_best_mode(hres, vres, long_refresh);
if (!best)
return 60;
if (abs(best->refresh - long_refresh) > 3) {
if (hres == 1200 && vres == 900)
return 49; /* OLPC DCON only supports 50 Hz */
else
return 60;
}
return best->refresh;
}
static void device_off(void)
{
viafb_dvi_disable();
viafb_lcd_disable();
}
static void device_on(void)
{
if (viafb_DVI_ON == 1)
viafb_dvi_enable();
if (viafb_LCD_ON == 1)
viafb_lcd_enable();
}
static void enable_second_display_channel(void)
{
/* to enable second display channel. */
viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT6);
viafb_write_reg_mask(CR6A, VIACR, BIT7, BIT7);
viafb_write_reg_mask(CR6A, VIACR, BIT6, BIT6);
}
static void disable_second_display_channel(void)
{
/* to disable second display channel. */
viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT6);
viafb_write_reg_mask(CR6A, VIACR, 0x00, BIT7);
viafb_write_reg_mask(CR6A, VIACR, BIT6, BIT6);
}
void viafb_set_dpa_gfx(int output_interface, struct GFX_DPA_SETTING\
*p_gfx_dpa_setting)
{
switch (output_interface) {
case INTERFACE_DVP0:
{
/* DVP0 Clock Polarity and Adjust: */
viafb_write_reg_mask(CR96, VIACR,
p_gfx_dpa_setting->DVP0, 0x0F);
/* DVP0 Clock and Data Pads Driving: */
viafb_write_reg_mask(SR1E, VIASR,
p_gfx_dpa_setting->DVP0ClockDri_S, BIT2);
viafb_write_reg_mask(SR2A, VIASR,
p_gfx_dpa_setting->DVP0ClockDri_S1,
BIT4);
viafb_write_reg_mask(SR1B, VIASR,
p_gfx_dpa_setting->DVP0DataDri_S, BIT1);
viafb_write_reg_mask(SR2A, VIASR,
p_gfx_dpa_setting->DVP0DataDri_S1, BIT5);
break;
}
case INTERFACE_DVP1:
{
/* DVP1 Clock Polarity and Adjust: */
viafb_write_reg_mask(CR9B, VIACR,
p_gfx_dpa_setting->DVP1, 0x0F);
/* DVP1 Clock and Data Pads Driving: */
viafb_write_reg_mask(SR65, VIASR,
p_gfx_dpa_setting->DVP1Driving, 0x0F);
break;
}
case INTERFACE_DFP_HIGH:
{
viafb_write_reg_mask(CR97, VIACR,
p_gfx_dpa_setting->DFPHigh, 0x0F);
break;
}
case INTERFACE_DFP_LOW:
{
viafb_write_reg_mask(CR99, VIACR,
p_gfx_dpa_setting->DFPLow, 0x0F);
break;
}
case INTERFACE_DFP:
{
viafb_write_reg_mask(CR97, VIACR,
p_gfx_dpa_setting->DFPHigh, 0x0F);
viafb_write_reg_mask(CR99, VIACR,
p_gfx_dpa_setting->DFPLow, 0x0F);
break;
}
}
}
void viafb_fill_var_timing_info(struct fb_var_screeninfo *var,
const struct fb_videomode *mode)
{
var->pixclock = mode->pixclock;
var->xres = mode->xres;
var->yres = mode->yres;
var->left_margin = mode->left_margin;
var->right_margin = mode->right_margin;
var->hsync_len = mode->hsync_len;
var->upper_margin = mode->upper_margin;
var->lower_margin = mode->lower_margin;
var->vsync_len = mode->vsync_len;
var->sync = mode->sync;
}
| gpl-2.0 |
TeamOrion-Devices/kernel_htc_msm8974 | drivers/video/backlight/ot200_bl.c | 4863 | 4913 | /*
* Copyright (C) 2012 Bachmann electronic GmbH
* Christian Gmeiner <christian.gmeiner@gmail.com>
*
* Backlight driver for ot200 visualisation device from
* Bachmann electronic GmbH.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 as published by
* the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/fb.h>
#include <linux/backlight.h>
#include <linux/gpio.h>
#include <linux/cs5535.h>
static struct cs5535_mfgpt_timer *pwm_timer;
/* this array defines the mapping of brightness in % to pwm frequency */
static const u8 dim_table[101] = {0, 0, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2,
2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4,
4, 5, 5, 5, 5, 6, 6, 6, 7, 7, 7, 8, 8, 9, 9,
10, 10, 11, 11, 12, 12, 13, 14, 15, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28,
30, 31, 33, 35, 37, 39, 41, 43, 45, 47, 50,
53, 55, 58, 61, 65, 68, 72, 75, 79, 84, 88,
93, 97, 103, 108, 114, 120, 126, 133, 140,
147, 155, 163};
struct ot200_backlight_data {
int current_brightness;
};
#define GPIO_DIMM 27
#define SCALE 1
#define CMP1MODE 0x2 /* compare on GE; output high on compare
* greater than or equal */
#define PWM_SETUP (SCALE | CMP1MODE << 6 | MFGPT_SETUP_CNTEN)
#define MAX_COMP2 163
static int ot200_backlight_update_status(struct backlight_device *bl)
{
struct ot200_backlight_data *data = bl_get_data(bl);
int brightness = bl->props.brightness;
if (bl->props.state & BL_CORE_FBBLANK)
brightness = 0;
/* enable or disable PWM timer */
if (brightness == 0)
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_SETUP, 0);
else if (data->current_brightness == 0) {
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_COUNTER, 0);
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_SETUP,
MFGPT_SETUP_CNTEN);
}
/* apply new brightness value */
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_CMP1,
MAX_COMP2 - dim_table[brightness]);
data->current_brightness = brightness;
return 0;
}
static int ot200_backlight_get_brightness(struct backlight_device *bl)
{
struct ot200_backlight_data *data = bl_get_data(bl);
return data->current_brightness;
}
static const struct backlight_ops ot200_backlight_ops = {
.update_status = ot200_backlight_update_status,
.get_brightness = ot200_backlight_get_brightness,
};
static int ot200_backlight_probe(struct platform_device *pdev)
{
struct backlight_device *bl;
struct ot200_backlight_data *data;
struct backlight_properties props;
int retval = 0;
/* request gpio */
if (gpio_request(GPIO_DIMM, "ot200 backlight dimmer") < 0) {
dev_err(&pdev->dev, "failed to request GPIO %d\n", GPIO_DIMM);
return -ENODEV;
}
/* request timer */
pwm_timer = cs5535_mfgpt_alloc_timer(7, MFGPT_DOMAIN_ANY);
if (!pwm_timer) {
dev_err(&pdev->dev, "MFGPT 7 not available\n");
retval = -ENODEV;
goto error_mfgpt_alloc;
}
data = kzalloc(sizeof(*data), GFP_KERNEL);
if (!data) {
retval = -ENOMEM;
goto error_kzalloc;
}
/* setup gpio */
cs5535_gpio_set(GPIO_DIMM, GPIO_OUTPUT_ENABLE);
cs5535_gpio_set(GPIO_DIMM, GPIO_OUTPUT_AUX1);
/* setup timer */
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_CMP1, 0);
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_CMP2, MAX_COMP2);
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_SETUP, PWM_SETUP);
data->current_brightness = 100;
props.max_brightness = 100;
props.brightness = 100;
props.type = BACKLIGHT_RAW;
bl = backlight_device_register(dev_name(&pdev->dev), &pdev->dev, data,
&ot200_backlight_ops, &props);
if (IS_ERR(bl)) {
dev_err(&pdev->dev, "failed to register backlight\n");
retval = PTR_ERR(bl);
goto error_backlight_device_register;
}
platform_set_drvdata(pdev, bl);
return 0;
error_backlight_device_register:
kfree(data);
error_kzalloc:
cs5535_mfgpt_free_timer(pwm_timer);
error_mfgpt_alloc:
gpio_free(GPIO_DIMM);
return retval;
}
static int ot200_backlight_remove(struct platform_device *pdev)
{
struct backlight_device *bl = platform_get_drvdata(pdev);
struct ot200_backlight_data *data = bl_get_data(bl);
backlight_device_unregister(bl);
/* on module unload set brightness to 100% */
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_COUNTER, 0);
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_SETUP, MFGPT_SETUP_CNTEN);
cs5535_mfgpt_write(pwm_timer, MFGPT_REG_CMP1,
MAX_COMP2 - dim_table[100]);
cs5535_mfgpt_free_timer(pwm_timer);
gpio_free(GPIO_DIMM);
kfree(data);
return 0;
}
static struct platform_driver ot200_backlight_driver = {
.driver = {
.name = "ot200-backlight",
.owner = THIS_MODULE,
},
.probe = ot200_backlight_probe,
.remove = ot200_backlight_remove,
};
module_platform_driver(ot200_backlight_driver);
MODULE_DESCRIPTION("backlight driver for ot200 visualisation device");
MODULE_AUTHOR("Christian Gmeiner <christian.gmeiner@gmail.com>");
MODULE_LICENSE("GPL");
MODULE_ALIAS("platform:ot200-backlight");
| gpl-2.0 |
Quaesar/android_kernel_hp_phobos | arch/arm/mach-pxa/pxa2xx.c | 4863 | 1349 | /*
* linux/arch/arm/mach-pxa/pxa2xx.c
*
* code specific to pxa2xx
*
* Copyright (C) 2008 Dmitry Baryshkov
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/device.h>
#include <linux/io.h>
#include <mach/hardware.h>
#include <mach/pxa2xx-regs.h>
#include <mach/mfp-pxa25x.h>
#include <mach/reset.h>
#include <mach/irda.h>
void pxa2xx_clear_reset_status(unsigned int mask)
{
/* RESET_STATUS_* has a 1:1 mapping with RCSR */
RCSR = mask;
}
static unsigned long pxa2xx_mfp_fir[] = {
GPIO46_FICP_RXD,
GPIO47_FICP_TXD,
};
static unsigned long pxa2xx_mfp_sir[] = {
GPIO46_STUART_RXD,
GPIO47_STUART_TXD,
};
static unsigned long pxa2xx_mfp_off[] = {
GPIO46_GPIO | MFP_LPM_DRIVE_LOW,
GPIO47_GPIO | MFP_LPM_DRIVE_LOW,
};
void pxa2xx_transceiver_mode(struct device *dev, int mode)
{
if (mode & IR_OFF) {
pxa2xx_mfp_config(pxa2xx_mfp_off, ARRAY_SIZE(pxa2xx_mfp_off));
} else if (mode & IR_SIRMODE) {
pxa2xx_mfp_config(pxa2xx_mfp_sir, ARRAY_SIZE(pxa2xx_mfp_sir));
} else if (mode & IR_FIRMODE) {
pxa2xx_mfp_config(pxa2xx_mfp_fir, ARRAY_SIZE(pxa2xx_mfp_fir));
} else
BUG();
}
EXPORT_SYMBOL_GPL(pxa2xx_transceiver_mode);
| gpl-2.0 |
QduZ9zEVr6/kernel-msm | arch/arm/mach-pxa/gumstix.c | 4863 | 5201 | /*
* linux/arch/arm/mach-pxa/gumstix.c
*
* Support for the Gumstix motherboards.
*
* Original Author: Craig Hughes
* Created: Feb 14, 2008
* Copyright: Craig Hughes
*
* 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.
*
* Implemented based on lubbock.c by Nicolas Pitre and code from Craig
* Hughes
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/partitions.h>
#include <linux/gpio.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/usb/gpio_vbus.h>
#include <asm/setup.h>
#include <asm/memory.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <asm/irq.h>
#include <asm/sizes.h>
#include <asm/mach/arch.h>
#include <asm/mach/map.h>
#include <asm/mach/irq.h>
#include <asm/mach/flash.h>
#include <mach/pxa25x.h>
#include <mach/mmc.h>
#include <mach/udc.h>
#include <mach/gumstix.h>
#include "generic.h"
static struct resource flash_resource = {
.start = 0x00000000,
.end = SZ_64M - 1,
.flags = IORESOURCE_MEM,
};
static struct mtd_partition gumstix_partitions[] = {
{
.name = "Bootloader",
.size = 0x00040000,
.offset = 0,
.mask_flags = MTD_WRITEABLE /* force read-only */
} , {
.name = "rootfs",
.size = MTDPART_SIZ_FULL,
.offset = MTDPART_OFS_APPEND
}
};
static struct flash_platform_data gumstix_flash_data = {
.map_name = "cfi_probe",
.parts = gumstix_partitions,
.nr_parts = ARRAY_SIZE(gumstix_partitions),
.width = 2,
};
static struct platform_device gumstix_flash_device = {
.name = "pxa2xx-flash",
.id = 0,
.dev = {
.platform_data = &gumstix_flash_data,
},
.resource = &flash_resource,
.num_resources = 1,
};
static struct platform_device *devices[] __initdata = {
&gumstix_flash_device,
};
#ifdef CONFIG_MMC_PXA
static struct pxamci_platform_data gumstix_mci_platform_data = {
.ocr_mask = MMC_VDD_32_33|MMC_VDD_33_34,
.gpio_card_detect = -1,
.gpio_card_ro = -1,
.gpio_power = -1,
};
static void __init gumstix_mmc_init(void)
{
pxa_set_mci_info(&gumstix_mci_platform_data);
}
#else
static void __init gumstix_mmc_init(void)
{
pr_debug("Gumstix mmc disabled\n");
}
#endif
#ifdef CONFIG_USB_PXA25X
static struct gpio_vbus_mach_info gumstix_udc_info = {
.gpio_vbus = GPIO_GUMSTIX_USB_GPIOn,
.gpio_pullup = GPIO_GUMSTIX_USB_GPIOx,
};
static struct platform_device gumstix_gpio_vbus = {
.name = "gpio-vbus",
.id = -1,
.dev = {
.platform_data = &gumstix_udc_info,
},
};
static void __init gumstix_udc_init(void)
{
platform_device_register(&gumstix_gpio_vbus);
}
#else
static void gumstix_udc_init(void)
{
pr_debug("Gumstix udc is disabled\n");
}
#endif
#ifdef CONFIG_BT
/* Normally, the bootloader would have enabled this 32kHz clock but many
** boards still have u-boot 1.1.4 so we check if it has been turned on and
** if not, we turn it on with a warning message. */
static void gumstix_setup_bt_clock(void)
{
int timeout = 500;
if (!(OSCC & OSCC_OOK))
pr_warning("32kHz clock was not on. Bootloader may need to "
"be updated\n");
else
return;
OSCC |= OSCC_OON;
do {
if (OSCC & OSCC_OOK)
break;
udelay(1);
} while (--timeout);
if (!timeout)
pr_err("Failed to start 32kHz clock\n");
}
static void __init gumstix_bluetooth_init(void)
{
int err;
gumstix_setup_bt_clock();
err = gpio_request(GPIO_GUMSTIX_BTRESET, "BTRST");
if (err) {
pr_err("gumstix: failed request gpio for bluetooth reset\n");
return;
}
err = gpio_direction_output(GPIO_GUMSTIX_BTRESET, 1);
if (err) {
pr_err("gumstix: can't reset bluetooth\n");
return;
}
gpio_set_value(GPIO_GUMSTIX_BTRESET, 0);
udelay(100);
gpio_set_value(GPIO_GUMSTIX_BTRESET, 1);
}
#else
static void gumstix_bluetooth_init(void)
{
pr_debug("Gumstix Bluetooth is disabled\n");
}
#endif
static unsigned long gumstix_pin_config[] __initdata = {
GPIO12_32KHz,
/* BTUART */
GPIO42_HWUART_RXD,
GPIO43_HWUART_TXD,
GPIO44_HWUART_CTS,
GPIO45_HWUART_RTS,
/* MMC */
GPIO6_MMC_CLK,
GPIO53_MMC_CLK,
GPIO8_MMC_CS0,
};
int __attribute__((weak)) am200_init(void)
{
return 0;
}
int __attribute__((weak)) am300_init(void)
{
return 0;
}
static void __init carrier_board_init(void)
{
/*
* put carrier/expansion board init here if
* they cannot be detected programatically
*/
am200_init();
am300_init();
}
static void __init gumstix_init(void)
{
pxa2xx_mfp_config(ARRAY_AND_SIZE(gumstix_pin_config));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
pxa_set_hwuart_info(NULL);
gumstix_bluetooth_init();
gumstix_udc_init();
gumstix_mmc_init();
(void) platform_add_devices(devices, ARRAY_SIZE(devices));
carrier_board_init();
}
MACHINE_START(GUMSTIX, "Gumstix")
.atag_offset = 0x100, /* match u-boot bi_boot_params */
.map_io = pxa25x_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa25x_init_irq,
.handle_irq = pxa25x_handle_irq,
.timer = &pxa_timer,
.init_machine = gumstix_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
JackpotClavin/android_kernel_lge_g2 | drivers/media/video/omap24xxcam.c | 4863 | 44330 | /*
* drivers/media/video/omap24xxcam.c
*
* OMAP 2 camera block driver.
*
* Copyright (C) 2004 MontaVista Software, Inc.
* Copyright (C) 2004 Texas Instruments.
* Copyright (C) 2007-2008 Nokia Corporation.
*
* Contact: Sakari Ailus <sakari.ailus@nokia.com>
*
* Based on code from Andy Lowe <source@mvista.com>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include <linux/delay.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/videodev2.h>
#include <linux/pci.h> /* needed for videobufs */
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/slab.h>
#include <linux/sched.h>
#include <linux/module.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include "omap24xxcam.h"
#define OMAP24XXCAM_VERSION "0.0.1"
#define RESET_TIMEOUT_NS 10000
static void omap24xxcam_reset(struct omap24xxcam_device *cam);
static int omap24xxcam_sensor_if_enable(struct omap24xxcam_device *cam);
static void omap24xxcam_device_unregister(struct v4l2_int_device *s);
static int omap24xxcam_remove(struct platform_device *pdev);
/* module parameters */
static int video_nr = -1; /* video device minor (-1 ==> auto assign) */
/*
* Maximum amount of memory to use for capture buffers.
* Default is 4800KB, enough to double-buffer SXGA.
*/
static int capture_mem = 1280 * 960 * 2 * 2;
static struct v4l2_int_device omap24xxcam;
/*
*
* Clocks.
*
*/
static void omap24xxcam_clock_put(struct omap24xxcam_device *cam)
{
if (cam->ick != NULL && !IS_ERR(cam->ick))
clk_put(cam->ick);
if (cam->fck != NULL && !IS_ERR(cam->fck))
clk_put(cam->fck);
cam->ick = cam->fck = NULL;
}
static int omap24xxcam_clock_get(struct omap24xxcam_device *cam)
{
int rval = 0;
cam->fck = clk_get(cam->dev, "fck");
if (IS_ERR(cam->fck)) {
dev_err(cam->dev, "can't get camera fck");
rval = PTR_ERR(cam->fck);
omap24xxcam_clock_put(cam);
return rval;
}
cam->ick = clk_get(cam->dev, "ick");
if (IS_ERR(cam->ick)) {
dev_err(cam->dev, "can't get camera ick");
rval = PTR_ERR(cam->ick);
omap24xxcam_clock_put(cam);
}
return rval;
}
static void omap24xxcam_clock_on(struct omap24xxcam_device *cam)
{
clk_enable(cam->fck);
clk_enable(cam->ick);
}
static void omap24xxcam_clock_off(struct omap24xxcam_device *cam)
{
clk_disable(cam->fck);
clk_disable(cam->ick);
}
/*
*
* Camera core
*
*/
/*
* Set xclk.
*
* To disable xclk, use value zero.
*/
static void omap24xxcam_core_xclk_set(const struct omap24xxcam_device *cam,
u32 xclk)
{
if (xclk) {
u32 divisor = CAM_MCLK / xclk;
if (divisor == 1)
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET,
CC_CTRL_XCLK,
CC_CTRL_XCLK_DIV_BYPASS);
else
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET,
CC_CTRL_XCLK, divisor);
} else
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET,
CC_CTRL_XCLK, CC_CTRL_XCLK_DIV_STABLE_LOW);
}
static void omap24xxcam_core_hwinit(const struct omap24xxcam_device *cam)
{
/*
* Setting the camera core AUTOIDLE bit causes problems with frame
* synchronization, so we will clear the AUTOIDLE bit instead.
*/
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET, CC_SYSCONFIG,
CC_SYSCONFIG_AUTOIDLE);
/* program the camera interface DMA packet size */
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET, CC_CTRL_DMA,
CC_CTRL_DMA_EN | (DMA_THRESHOLD / 4 - 1));
/* enable camera core error interrupts */
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET, CC_IRQENABLE,
CC_IRQENABLE_FW_ERR_IRQ
| CC_IRQENABLE_FSC_ERR_IRQ
| CC_IRQENABLE_SSC_ERR_IRQ
| CC_IRQENABLE_FIFO_OF_IRQ);
}
/*
* Enable the camera core.
*
* Data transfer to the camera DMA starts from next starting frame.
*/
static void omap24xxcam_core_enable(const struct omap24xxcam_device *cam)
{
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET, CC_CTRL,
cam->cc_ctrl);
}
/*
* Disable camera core.
*
* The data transfer will be stopped immediately (CC_CTRL_CC_RST). The
* core internal state machines will be reset. Use
* CC_CTRL_CC_FRAME_TRIG instead if you want to transfer the current
* frame completely.
*/
static void omap24xxcam_core_disable(const struct omap24xxcam_device *cam)
{
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET, CC_CTRL,
CC_CTRL_CC_RST);
}
/* Interrupt service routine for camera core interrupts. */
static void omap24xxcam_core_isr(struct omap24xxcam_device *cam)
{
u32 cc_irqstatus;
const u32 cc_irqstatus_err =
CC_IRQSTATUS_FW_ERR_IRQ
| CC_IRQSTATUS_FSC_ERR_IRQ
| CC_IRQSTATUS_SSC_ERR_IRQ
| CC_IRQSTATUS_FIFO_UF_IRQ
| CC_IRQSTATUS_FIFO_OF_IRQ;
cc_irqstatus = omap24xxcam_reg_in(cam->mmio_base + CC_REG_OFFSET,
CC_IRQSTATUS);
omap24xxcam_reg_out(cam->mmio_base + CC_REG_OFFSET, CC_IRQSTATUS,
cc_irqstatus);
if (cc_irqstatus & cc_irqstatus_err
&& !atomic_read(&cam->in_reset)) {
dev_dbg(cam->dev, "resetting camera, cc_irqstatus 0x%x\n",
cc_irqstatus);
omap24xxcam_reset(cam);
}
}
/*
*
* videobuf_buffer handling.
*
* Memory for mmapped videobuf_buffers is not allocated
* conventionally, but by several kmalloc allocations and then
* creating the scatterlist on our own. User-space buffers are handled
* normally.
*
*/
/*
* Free the memory-mapped buffer memory allocated for a
* videobuf_buffer and the associated scatterlist.
*/
static void omap24xxcam_vbq_free_mmap_buffer(struct videobuf_buffer *vb)
{
struct videobuf_dmabuf *dma = videobuf_to_dma(vb);
size_t alloc_size;
struct page *page;
int i;
if (dma->sglist == NULL)
return;
i = dma->sglen;
while (i) {
i--;
alloc_size = sg_dma_len(&dma->sglist[i]);
page = sg_page(&dma->sglist[i]);
do {
ClearPageReserved(page++);
} while (alloc_size -= PAGE_SIZE);
__free_pages(sg_page(&dma->sglist[i]),
get_order(sg_dma_len(&dma->sglist[i])));
}
kfree(dma->sglist);
dma->sglist = NULL;
}
/* Release all memory related to the videobuf_queue. */
static void omap24xxcam_vbq_free_mmap_buffers(struct videobuf_queue *vbq)
{
int i;
mutex_lock(&vbq->vb_lock);
for (i = 0; i < VIDEO_MAX_FRAME; i++) {
if (NULL == vbq->bufs[i])
continue;
if (V4L2_MEMORY_MMAP != vbq->bufs[i]->memory)
continue;
vbq->ops->buf_release(vbq, vbq->bufs[i]);
omap24xxcam_vbq_free_mmap_buffer(vbq->bufs[i]);
kfree(vbq->bufs[i]);
vbq->bufs[i] = NULL;
}
mutex_unlock(&vbq->vb_lock);
videobuf_mmap_free(vbq);
}
/*
* Allocate physically as contiguous as possible buffer for video
* frame and allocate and build DMA scatter-gather list for it.
*/
static int omap24xxcam_vbq_alloc_mmap_buffer(struct videobuf_buffer *vb)
{
unsigned int order;
size_t alloc_size, size = vb->bsize; /* vb->bsize is page aligned */
struct page *page;
int max_pages, err = 0, i = 0;
struct videobuf_dmabuf *dma = videobuf_to_dma(vb);
/*
* allocate maximum size scatter-gather list. Note this is
* overhead. We may not use as many entries as we allocate
*/
max_pages = vb->bsize >> PAGE_SHIFT;
dma->sglist = kcalloc(max_pages, sizeof(*dma->sglist), GFP_KERNEL);
if (dma->sglist == NULL) {
err = -ENOMEM;
goto out;
}
while (size) {
order = get_order(size);
/*
* do not over-allocate even if we would get larger
* contiguous chunk that way
*/
if ((PAGE_SIZE << order) > size)
order--;
/* try to allocate as many contiguous pages as possible */
page = alloc_pages(GFP_KERNEL, order);
/* if allocation fails, try to allocate smaller amount */
while (page == NULL) {
order--;
page = alloc_pages(GFP_KERNEL, order);
if (page == NULL && !order) {
err = -ENOMEM;
goto out;
}
}
size -= (PAGE_SIZE << order);
/* append allocated chunk of pages into scatter-gather list */
sg_set_page(&dma->sglist[i], page, PAGE_SIZE << order, 0);
dma->sglen++;
i++;
alloc_size = (PAGE_SIZE << order);
/* clear pages before giving them to user space */
memset(page_address(page), 0, alloc_size);
/* mark allocated pages reserved */
do {
SetPageReserved(page++);
} while (alloc_size -= PAGE_SIZE);
}
/*
* REVISIT: not fully correct to assign nr_pages == sglen but
* video-buf is passing nr_pages for e.g. unmap_sg calls
*/
dma->nr_pages = dma->sglen;
dma->direction = PCI_DMA_FROMDEVICE;
return 0;
out:
omap24xxcam_vbq_free_mmap_buffer(vb);
return err;
}
static int omap24xxcam_vbq_alloc_mmap_buffers(struct videobuf_queue *vbq,
unsigned int count)
{
int i, err = 0;
struct omap24xxcam_fh *fh =
container_of(vbq, struct omap24xxcam_fh, vbq);
mutex_lock(&vbq->vb_lock);
for (i = 0; i < count; i++) {
err = omap24xxcam_vbq_alloc_mmap_buffer(vbq->bufs[i]);
if (err)
goto out;
dev_dbg(fh->cam->dev, "sglen is %d for buffer %d\n",
videobuf_to_dma(vbq->bufs[i])->sglen, i);
}
mutex_unlock(&vbq->vb_lock);
return 0;
out:
while (i) {
i--;
omap24xxcam_vbq_free_mmap_buffer(vbq->bufs[i]);
}
mutex_unlock(&vbq->vb_lock);
return err;
}
/*
* This routine is called from interrupt context when a scatter-gather DMA
* transfer of a videobuf_buffer completes.
*/
static void omap24xxcam_vbq_complete(struct omap24xxcam_sgdma *sgdma,
u32 csr, void *arg)
{
struct omap24xxcam_device *cam =
container_of(sgdma, struct omap24xxcam_device, sgdma);
struct omap24xxcam_fh *fh = cam->streaming->private_data;
struct videobuf_buffer *vb = (struct videobuf_buffer *)arg;
const u32 csr_error = CAMDMA_CSR_MISALIGNED_ERR
| CAMDMA_CSR_SUPERVISOR_ERR | CAMDMA_CSR_SECURE_ERR
| CAMDMA_CSR_TRANS_ERR | CAMDMA_CSR_DROP;
unsigned long flags;
spin_lock_irqsave(&cam->core_enable_disable_lock, flags);
if (--cam->sgdma_in_queue == 0)
omap24xxcam_core_disable(cam);
spin_unlock_irqrestore(&cam->core_enable_disable_lock, flags);
do_gettimeofday(&vb->ts);
vb->field_count = atomic_add_return(2, &fh->field_count);
if (csr & csr_error) {
vb->state = VIDEOBUF_ERROR;
if (!atomic_read(&fh->cam->in_reset)) {
dev_dbg(cam->dev, "resetting camera, csr 0x%x\n", csr);
omap24xxcam_reset(cam);
}
} else
vb->state = VIDEOBUF_DONE;
wake_up(&vb->done);
}
static void omap24xxcam_vbq_release(struct videobuf_queue *vbq,
struct videobuf_buffer *vb)
{
struct videobuf_dmabuf *dma = videobuf_to_dma(vb);
/* wait for buffer, especially to get out of the sgdma queue */
videobuf_waiton(vbq, vb, 0, 0);
if (vb->memory == V4L2_MEMORY_MMAP) {
dma_unmap_sg(vbq->dev, dma->sglist, dma->sglen,
dma->direction);
dma->direction = DMA_NONE;
} else {
videobuf_dma_unmap(vbq->dev, videobuf_to_dma(vb));
videobuf_dma_free(videobuf_to_dma(vb));
}
vb->state = VIDEOBUF_NEEDS_INIT;
}
/*
* Limit the number of available kernel image capture buffers based on the
* number requested, the currently selected image size, and the maximum
* amount of memory permitted for kernel capture buffers.
*/
static int omap24xxcam_vbq_setup(struct videobuf_queue *vbq, unsigned int *cnt,
unsigned int *size)
{
struct omap24xxcam_fh *fh = vbq->priv_data;
if (*cnt <= 0)
*cnt = VIDEO_MAX_FRAME; /* supply a default number of buffers */
if (*cnt > VIDEO_MAX_FRAME)
*cnt = VIDEO_MAX_FRAME;
*size = fh->pix.sizeimage;
/* accessing fh->cam->capture_mem is ok, it's constant */
if (*size * *cnt > fh->cam->capture_mem)
*cnt = fh->cam->capture_mem / *size;
return 0;
}
static int omap24xxcam_dma_iolock(struct videobuf_queue *vbq,
struct videobuf_dmabuf *dma)
{
int err = 0;
dma->direction = PCI_DMA_FROMDEVICE;
if (!dma_map_sg(vbq->dev, dma->sglist, dma->sglen, dma->direction)) {
kfree(dma->sglist);
dma->sglist = NULL;
dma->sglen = 0;
err = -EIO;
}
return err;
}
static int omap24xxcam_vbq_prepare(struct videobuf_queue *vbq,
struct videobuf_buffer *vb,
enum v4l2_field field)
{
struct omap24xxcam_fh *fh = vbq->priv_data;
int err = 0;
/*
* Accessing pix here is okay since it's constant while
* streaming is on (and we only get called then).
*/
if (vb->baddr) {
/* This is a userspace buffer. */
if (fh->pix.sizeimage > vb->bsize) {
/* The buffer isn't big enough. */
err = -EINVAL;
} else
vb->size = fh->pix.sizeimage;
} else {
if (vb->state != VIDEOBUF_NEEDS_INIT) {
/*
* We have a kernel bounce buffer that has
* already been allocated.
*/
if (fh->pix.sizeimage > vb->size) {
/*
* The image size has been changed to
* a larger size since this buffer was
* allocated, so we need to free and
* reallocate it.
*/
omap24xxcam_vbq_release(vbq, vb);
vb->size = fh->pix.sizeimage;
}
} else {
/* We need to allocate a new kernel bounce buffer. */
vb->size = fh->pix.sizeimage;
}
}
if (err)
return err;
vb->width = fh->pix.width;
vb->height = fh->pix.height;
vb->field = field;
if (vb->state == VIDEOBUF_NEEDS_INIT) {
if (vb->memory == V4L2_MEMORY_MMAP)
/*
* we have built the scatter-gather list by ourself so
* do the scatter-gather mapping as well
*/
err = omap24xxcam_dma_iolock(vbq, videobuf_to_dma(vb));
else
err = videobuf_iolock(vbq, vb, NULL);
}
if (!err)
vb->state = VIDEOBUF_PREPARED;
else
omap24xxcam_vbq_release(vbq, vb);
return err;
}
static void omap24xxcam_vbq_queue(struct videobuf_queue *vbq,
struct videobuf_buffer *vb)
{
struct omap24xxcam_fh *fh = vbq->priv_data;
struct omap24xxcam_device *cam = fh->cam;
enum videobuf_state state = vb->state;
unsigned long flags;
int err;
/*
* FIXME: We're marking the buffer active since we have no
* pretty way of marking it active exactly when the
* scatter-gather transfer starts.
*/
vb->state = VIDEOBUF_ACTIVE;
err = omap24xxcam_sgdma_queue(&fh->cam->sgdma,
videobuf_to_dma(vb)->sglist,
videobuf_to_dma(vb)->sglen, vb->size,
omap24xxcam_vbq_complete, vb);
if (!err) {
spin_lock_irqsave(&cam->core_enable_disable_lock, flags);
if (++cam->sgdma_in_queue == 1
&& !atomic_read(&cam->in_reset))
omap24xxcam_core_enable(cam);
spin_unlock_irqrestore(&cam->core_enable_disable_lock, flags);
} else {
/*
* Oops. We're not supposed to get any errors here.
* The only way we could get an error is if we ran out
* of scatter-gather DMA slots, but we are supposed to
* have at least as many scatter-gather DMA slots as
* video buffers so that can't happen.
*/
dev_err(cam->dev, "failed to queue a video buffer for dma!\n");
dev_err(cam->dev, "likely a bug in the driver!\n");
vb->state = state;
}
}
static struct videobuf_queue_ops omap24xxcam_vbq_ops = {
.buf_setup = omap24xxcam_vbq_setup,
.buf_prepare = omap24xxcam_vbq_prepare,
.buf_queue = omap24xxcam_vbq_queue,
.buf_release = omap24xxcam_vbq_release,
};
/*
*
* OMAP main camera system
*
*/
/*
* Reset camera block to power-on state.
*/
static void omap24xxcam_poweron_reset(struct omap24xxcam_device *cam)
{
int max_loop = RESET_TIMEOUT_NS;
/* Reset whole camera subsystem */
omap24xxcam_reg_out(cam->mmio_base,
CAM_SYSCONFIG,
CAM_SYSCONFIG_SOFTRESET);
/* Wait till it's finished */
while (!(omap24xxcam_reg_in(cam->mmio_base, CAM_SYSSTATUS)
& CAM_SYSSTATUS_RESETDONE)
&& --max_loop) {
ndelay(1);
}
if (!(omap24xxcam_reg_in(cam->mmio_base, CAM_SYSSTATUS)
& CAM_SYSSTATUS_RESETDONE))
dev_err(cam->dev, "camera soft reset timeout\n");
}
/*
* (Re)initialise the camera block.
*/
static void omap24xxcam_hwinit(struct omap24xxcam_device *cam)
{
omap24xxcam_poweron_reset(cam);
/* set the camera subsystem autoidle bit */
omap24xxcam_reg_out(cam->mmio_base, CAM_SYSCONFIG,
CAM_SYSCONFIG_AUTOIDLE);
/* set the camera MMU autoidle bit */
omap24xxcam_reg_out(cam->mmio_base,
CAMMMU_REG_OFFSET + CAMMMU_SYSCONFIG,
CAMMMU_SYSCONFIG_AUTOIDLE);
omap24xxcam_core_hwinit(cam);
omap24xxcam_dma_hwinit(&cam->sgdma.dma);
}
/*
* Callback for dma transfer stalling.
*/
static void omap24xxcam_stalled_dma_reset(unsigned long data)
{
struct omap24xxcam_device *cam = (struct omap24xxcam_device *)data;
if (!atomic_read(&cam->in_reset)) {
dev_dbg(cam->dev, "dma stalled, resetting camera\n");
omap24xxcam_reset(cam);
}
}
/*
* Stop capture. Mark we're doing a reset, stop DMA transfers and
* core. (No new scatter-gather transfers will be queued whilst
* in_reset is non-zero.)
*
* If omap24xxcam_capture_stop is called from several places at
* once, only the first call will have an effect. Similarly, the last
* call omap24xxcam_streaming_cont will have effect.
*
* Serialisation is ensured by using cam->core_enable_disable_lock.
*/
static void omap24xxcam_capture_stop(struct omap24xxcam_device *cam)
{
unsigned long flags;
spin_lock_irqsave(&cam->core_enable_disable_lock, flags);
if (atomic_inc_return(&cam->in_reset) != 1) {
spin_unlock_irqrestore(&cam->core_enable_disable_lock, flags);
return;
}
omap24xxcam_core_disable(cam);
spin_unlock_irqrestore(&cam->core_enable_disable_lock, flags);
omap24xxcam_sgdma_sync(&cam->sgdma);
}
/*
* Reset and continue streaming.
*
* Note: Resetting the camera FIFO via the CC_RST bit in the CC_CTRL
* register is supposed to be sufficient to recover from a camera
* interface error, but it doesn't seem to be enough. If we only do
* that then subsequent image captures are out of sync by either one
* or two times DMA_THRESHOLD bytes. Resetting and re-initializing the
* entire camera subsystem prevents the problem with frame
* synchronization.
*/
static void omap24xxcam_capture_cont(struct omap24xxcam_device *cam)
{
unsigned long flags;
spin_lock_irqsave(&cam->core_enable_disable_lock, flags);
if (atomic_read(&cam->in_reset) != 1)
goto out;
omap24xxcam_hwinit(cam);
omap24xxcam_sensor_if_enable(cam);
omap24xxcam_sgdma_process(&cam->sgdma);
if (cam->sgdma_in_queue)
omap24xxcam_core_enable(cam);
out:
atomic_dec(&cam->in_reset);
spin_unlock_irqrestore(&cam->core_enable_disable_lock, flags);
}
static ssize_t
omap24xxcam_streaming_show(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct omap24xxcam_device *cam = dev_get_drvdata(dev);
return sprintf(buf, "%s\n", cam->streaming ? "active" : "inactive");
}
static DEVICE_ATTR(streaming, S_IRUGO, omap24xxcam_streaming_show, NULL);
/*
* Stop capture and restart it. I.e. reset the camera during use.
*/
static void omap24xxcam_reset(struct omap24xxcam_device *cam)
{
omap24xxcam_capture_stop(cam);
omap24xxcam_capture_cont(cam);
}
/*
* The main interrupt handler.
*/
static irqreturn_t omap24xxcam_isr(int irq, void *arg)
{
struct omap24xxcam_device *cam = (struct omap24xxcam_device *)arg;
u32 irqstatus;
unsigned int irqhandled = 0;
irqstatus = omap24xxcam_reg_in(cam->mmio_base, CAM_IRQSTATUS);
if (irqstatus &
(CAM_IRQSTATUS_DMA_IRQ2 | CAM_IRQSTATUS_DMA_IRQ1
| CAM_IRQSTATUS_DMA_IRQ0)) {
omap24xxcam_dma_isr(&cam->sgdma.dma);
irqhandled = 1;
}
if (irqstatus & CAM_IRQSTATUS_CC_IRQ) {
omap24xxcam_core_isr(cam);
irqhandled = 1;
}
if (irqstatus & CAM_IRQSTATUS_MMU_IRQ)
dev_err(cam->dev, "unhandled camera MMU interrupt!\n");
return IRQ_RETVAL(irqhandled);
}
/*
*
* Sensor handling.
*
*/
/*
* Enable the external sensor interface. Try to negotiate interface
* parameters with the sensor and start using the new ones. The calls
* to sensor_if_enable and sensor_if_disable need not to be balanced.
*/
static int omap24xxcam_sensor_if_enable(struct omap24xxcam_device *cam)
{
int rval;
struct v4l2_ifparm p;
rval = vidioc_int_g_ifparm(cam->sdev, &p);
if (rval) {
dev_err(cam->dev, "vidioc_int_g_ifparm failed with %d\n", rval);
return rval;
}
cam->if_type = p.if_type;
cam->cc_ctrl = CC_CTRL_CC_EN;
switch (p.if_type) {
case V4L2_IF_TYPE_BT656:
if (p.u.bt656.frame_start_on_rising_vs)
cam->cc_ctrl |= CC_CTRL_NOBT_SYNCHRO;
if (p.u.bt656.bt_sync_correct)
cam->cc_ctrl |= CC_CTRL_BT_CORRECT;
if (p.u.bt656.swap)
cam->cc_ctrl |= CC_CTRL_PAR_ORDERCAM;
if (p.u.bt656.latch_clk_inv)
cam->cc_ctrl |= CC_CTRL_PAR_CLK_POL;
if (p.u.bt656.nobt_hs_inv)
cam->cc_ctrl |= CC_CTRL_NOBT_HS_POL;
if (p.u.bt656.nobt_vs_inv)
cam->cc_ctrl |= CC_CTRL_NOBT_VS_POL;
switch (p.u.bt656.mode) {
case V4L2_IF_TYPE_BT656_MODE_NOBT_8BIT:
cam->cc_ctrl |= CC_CTRL_PAR_MODE_NOBT8;
break;
case V4L2_IF_TYPE_BT656_MODE_NOBT_10BIT:
cam->cc_ctrl |= CC_CTRL_PAR_MODE_NOBT10;
break;
case V4L2_IF_TYPE_BT656_MODE_NOBT_12BIT:
cam->cc_ctrl |= CC_CTRL_PAR_MODE_NOBT12;
break;
case V4L2_IF_TYPE_BT656_MODE_BT_8BIT:
cam->cc_ctrl |= CC_CTRL_PAR_MODE_BT8;
break;
case V4L2_IF_TYPE_BT656_MODE_BT_10BIT:
cam->cc_ctrl |= CC_CTRL_PAR_MODE_BT10;
break;
default:
dev_err(cam->dev,
"bt656 interface mode %d not supported\n",
p.u.bt656.mode);
return -EINVAL;
}
/*
* The clock rate that the sensor wants has changed.
* We have to adjust the xclk from OMAP 2 side to
* match the sensor's wish as closely as possible.
*/
if (p.u.bt656.clock_curr != cam->if_u.bt656.xclk) {
u32 xclk = p.u.bt656.clock_curr;
u32 divisor;
if (xclk == 0)
return -EINVAL;
if (xclk > CAM_MCLK)
xclk = CAM_MCLK;
divisor = CAM_MCLK / xclk;
if (divisor * xclk < CAM_MCLK)
divisor++;
if (CAM_MCLK / divisor < p.u.bt656.clock_min
&& divisor > 1)
divisor--;
if (divisor > 30)
divisor = 30;
xclk = CAM_MCLK / divisor;
if (xclk < p.u.bt656.clock_min
|| xclk > p.u.bt656.clock_max)
return -EINVAL;
cam->if_u.bt656.xclk = xclk;
}
omap24xxcam_core_xclk_set(cam, cam->if_u.bt656.xclk);
break;
default:
/* FIXME: how about other interfaces? */
dev_err(cam->dev, "interface type %d not supported\n",
p.if_type);
return -EINVAL;
}
return 0;
}
static void omap24xxcam_sensor_if_disable(const struct omap24xxcam_device *cam)
{
switch (cam->if_type) {
case V4L2_IF_TYPE_BT656:
omap24xxcam_core_xclk_set(cam, 0);
break;
}
}
/*
* Initialise the sensor hardware.
*/
static int omap24xxcam_sensor_init(struct omap24xxcam_device *cam)
{
int err = 0;
struct v4l2_int_device *sdev = cam->sdev;
omap24xxcam_clock_on(cam);
err = omap24xxcam_sensor_if_enable(cam);
if (err) {
dev_err(cam->dev, "sensor interface could not be enabled at "
"initialisation, %d\n", err);
cam->sdev = NULL;
goto out;
}
/* power up sensor during sensor initialization */
vidioc_int_s_power(sdev, 1);
err = vidioc_int_dev_init(sdev);
if (err) {
dev_err(cam->dev, "cannot initialize sensor, error %d\n", err);
/* Sensor init failed --- it's nonexistent to us! */
cam->sdev = NULL;
goto out;
}
dev_info(cam->dev, "sensor is %s\n", sdev->name);
out:
omap24xxcam_sensor_if_disable(cam);
omap24xxcam_clock_off(cam);
vidioc_int_s_power(sdev, 0);
return err;
}
static void omap24xxcam_sensor_exit(struct omap24xxcam_device *cam)
{
if (cam->sdev)
vidioc_int_dev_exit(cam->sdev);
}
static void omap24xxcam_sensor_disable(struct omap24xxcam_device *cam)
{
omap24xxcam_sensor_if_disable(cam);
omap24xxcam_clock_off(cam);
vidioc_int_s_power(cam->sdev, 0);
}
/*
* Power-up and configure camera sensor. It's ready for capturing now.
*/
static int omap24xxcam_sensor_enable(struct omap24xxcam_device *cam)
{
int rval;
omap24xxcam_clock_on(cam);
omap24xxcam_sensor_if_enable(cam);
rval = vidioc_int_s_power(cam->sdev, 1);
if (rval)
goto out;
rval = vidioc_int_init(cam->sdev);
if (rval)
goto out;
return 0;
out:
omap24xxcam_sensor_disable(cam);
return rval;
}
static void omap24xxcam_sensor_reset_work(struct work_struct *work)
{
struct omap24xxcam_device *cam =
container_of(work, struct omap24xxcam_device,
sensor_reset_work);
if (atomic_read(&cam->reset_disable))
return;
omap24xxcam_capture_stop(cam);
if (vidioc_int_reset(cam->sdev) == 0) {
vidioc_int_init(cam->sdev);
} else {
/* Can't reset it by vidioc_int_reset. */
omap24xxcam_sensor_disable(cam);
omap24xxcam_sensor_enable(cam);
}
omap24xxcam_capture_cont(cam);
}
/*
*
* IOCTL interface.
*
*/
static int vidioc_querycap(struct file *file, void *fh,
struct v4l2_capability *cap)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
strlcpy(cap->driver, CAM_NAME, sizeof(cap->driver));
strlcpy(cap->card, cam->vfd->name, sizeof(cap->card));
cap->capabilities = V4L2_CAP_VIDEO_CAPTURE | V4L2_CAP_STREAMING;
return 0;
}
static int vidioc_enum_fmt_vid_cap(struct file *file, void *fh,
struct v4l2_fmtdesc *f)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
rval = vidioc_int_enum_fmt_cap(cam->sdev, f);
return rval;
}
static int vidioc_g_fmt_vid_cap(struct file *file, void *fh,
struct v4l2_format *f)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
rval = vidioc_int_g_fmt_cap(cam->sdev, f);
mutex_unlock(&cam->mutex);
return rval;
}
static int vidioc_s_fmt_vid_cap(struct file *file, void *fh,
struct v4l2_format *f)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
if (cam->streaming) {
rval = -EBUSY;
goto out;
}
rval = vidioc_int_s_fmt_cap(cam->sdev, f);
out:
mutex_unlock(&cam->mutex);
if (!rval) {
mutex_lock(&ofh->vbq.vb_lock);
ofh->pix = f->fmt.pix;
mutex_unlock(&ofh->vbq.vb_lock);
}
memset(f, 0, sizeof(*f));
vidioc_g_fmt_vid_cap(file, fh, f);
return rval;
}
static int vidioc_try_fmt_vid_cap(struct file *file, void *fh,
struct v4l2_format *f)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
rval = vidioc_int_try_fmt_cap(cam->sdev, f);
mutex_unlock(&cam->mutex);
return rval;
}
static int vidioc_reqbufs(struct file *file, void *fh,
struct v4l2_requestbuffers *b)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
if (cam->streaming) {
mutex_unlock(&cam->mutex);
return -EBUSY;
}
omap24xxcam_vbq_free_mmap_buffers(&ofh->vbq);
mutex_unlock(&cam->mutex);
rval = videobuf_reqbufs(&ofh->vbq, b);
/*
* Either videobuf_reqbufs failed or the buffers are not
* memory-mapped (which would need special attention).
*/
if (rval < 0 || b->memory != V4L2_MEMORY_MMAP)
goto out;
rval = omap24xxcam_vbq_alloc_mmap_buffers(&ofh->vbq, rval);
if (rval)
omap24xxcam_vbq_free_mmap_buffers(&ofh->vbq);
out:
return rval;
}
static int vidioc_querybuf(struct file *file, void *fh,
struct v4l2_buffer *b)
{
struct omap24xxcam_fh *ofh = fh;
return videobuf_querybuf(&ofh->vbq, b);
}
static int vidioc_qbuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct omap24xxcam_fh *ofh = fh;
return videobuf_qbuf(&ofh->vbq, b);
}
static int vidioc_dqbuf(struct file *file, void *fh, struct v4l2_buffer *b)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
struct videobuf_buffer *vb;
int rval;
videobuf_dqbuf_again:
rval = videobuf_dqbuf(&ofh->vbq, b, file->f_flags & O_NONBLOCK);
if (rval)
goto out;
vb = ofh->vbq.bufs[b->index];
mutex_lock(&cam->mutex);
/* _needs_reset returns -EIO if reset is required. */
rval = vidioc_int_g_needs_reset(cam->sdev, (void *)vb->baddr);
mutex_unlock(&cam->mutex);
if (rval == -EIO)
schedule_work(&cam->sensor_reset_work);
else
rval = 0;
out:
/*
* This is a hack. We don't want to show -EIO to the user
* space. Requeue the buffer and try again if we're not doing
* this in non-blocking mode.
*/
if (rval == -EIO) {
videobuf_qbuf(&ofh->vbq, b);
if (!(file->f_flags & O_NONBLOCK))
goto videobuf_dqbuf_again;
/*
* We don't have a videobuf_buffer now --- maybe next
* time...
*/
rval = -EAGAIN;
}
return rval;
}
static int vidioc_streamon(struct file *file, void *fh, enum v4l2_buf_type i)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
if (cam->streaming) {
rval = -EBUSY;
goto out;
}
rval = omap24xxcam_sensor_if_enable(cam);
if (rval) {
dev_dbg(cam->dev, "vidioc_int_g_ifparm failed\n");
goto out;
}
rval = videobuf_streamon(&ofh->vbq);
if (!rval) {
cam->streaming = file;
sysfs_notify(&cam->dev->kobj, NULL, "streaming");
}
out:
mutex_unlock(&cam->mutex);
return rval;
}
static int vidioc_streamoff(struct file *file, void *fh, enum v4l2_buf_type i)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
struct videobuf_queue *q = &ofh->vbq;
int rval;
atomic_inc(&cam->reset_disable);
flush_work_sync(&cam->sensor_reset_work);
rval = videobuf_streamoff(q);
if (!rval) {
mutex_lock(&cam->mutex);
cam->streaming = NULL;
mutex_unlock(&cam->mutex);
sysfs_notify(&cam->dev->kobj, NULL, "streaming");
}
atomic_dec(&cam->reset_disable);
return rval;
}
static int vidioc_enum_input(struct file *file, void *fh,
struct v4l2_input *inp)
{
if (inp->index > 0)
return -EINVAL;
strlcpy(inp->name, "camera", sizeof(inp->name));
inp->type = V4L2_INPUT_TYPE_CAMERA;
return 0;
}
static int vidioc_g_input(struct file *file, void *fh, unsigned int *i)
{
*i = 0;
return 0;
}
static int vidioc_s_input(struct file *file, void *fh, unsigned int i)
{
if (i > 0)
return -EINVAL;
return 0;
}
static int vidioc_queryctrl(struct file *file, void *fh,
struct v4l2_queryctrl *a)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
rval = vidioc_int_queryctrl(cam->sdev, a);
return rval;
}
static int vidioc_g_ctrl(struct file *file, void *fh,
struct v4l2_control *a)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
rval = vidioc_int_g_ctrl(cam->sdev, a);
mutex_unlock(&cam->mutex);
return rval;
}
static int vidioc_s_ctrl(struct file *file, void *fh,
struct v4l2_control *a)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
rval = vidioc_int_s_ctrl(cam->sdev, a);
mutex_unlock(&cam->mutex);
return rval;
}
static int vidioc_g_parm(struct file *file, void *fh,
struct v4l2_streamparm *a) {
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
int rval;
mutex_lock(&cam->mutex);
rval = vidioc_int_g_parm(cam->sdev, a);
mutex_unlock(&cam->mutex);
return rval;
}
static int vidioc_s_parm(struct file *file, void *fh,
struct v4l2_streamparm *a)
{
struct omap24xxcam_fh *ofh = fh;
struct omap24xxcam_device *cam = ofh->cam;
struct v4l2_streamparm old_streamparm;
int rval;
mutex_lock(&cam->mutex);
if (cam->streaming) {
rval = -EBUSY;
goto out;
}
old_streamparm.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
rval = vidioc_int_g_parm(cam->sdev, &old_streamparm);
if (rval)
goto out;
rval = vidioc_int_s_parm(cam->sdev, a);
if (rval)
goto out;
rval = omap24xxcam_sensor_if_enable(cam);
/*
* Revert to old streaming parameters if enabling sensor
* interface with the new ones failed.
*/
if (rval)
vidioc_int_s_parm(cam->sdev, &old_streamparm);
out:
mutex_unlock(&cam->mutex);
return rval;
}
/*
*
* File operations.
*
*/
static unsigned int omap24xxcam_poll(struct file *file,
struct poll_table_struct *wait)
{
struct omap24xxcam_fh *fh = file->private_data;
struct omap24xxcam_device *cam = fh->cam;
struct videobuf_buffer *vb;
mutex_lock(&cam->mutex);
if (cam->streaming != file) {
mutex_unlock(&cam->mutex);
return POLLERR;
}
mutex_unlock(&cam->mutex);
mutex_lock(&fh->vbq.vb_lock);
if (list_empty(&fh->vbq.stream)) {
mutex_unlock(&fh->vbq.vb_lock);
return POLLERR;
}
vb = list_entry(fh->vbq.stream.next, struct videobuf_buffer, stream);
mutex_unlock(&fh->vbq.vb_lock);
poll_wait(file, &vb->done, wait);
if (vb->state == VIDEOBUF_DONE || vb->state == VIDEOBUF_ERROR)
return POLLIN | POLLRDNORM;
return 0;
}
static int omap24xxcam_mmap_buffers(struct file *file,
struct vm_area_struct *vma)
{
struct omap24xxcam_fh *fh = file->private_data;
struct omap24xxcam_device *cam = fh->cam;
struct videobuf_queue *vbq = &fh->vbq;
unsigned int first, last, size, i, j;
int err = 0;
mutex_lock(&cam->mutex);
if (cam->streaming) {
mutex_unlock(&cam->mutex);
return -EBUSY;
}
mutex_unlock(&cam->mutex);
mutex_lock(&vbq->vb_lock);
/* look for first buffer to map */
for (first = 0; first < VIDEO_MAX_FRAME; first++) {
if (NULL == vbq->bufs[first])
continue;
if (V4L2_MEMORY_MMAP != vbq->bufs[first]->memory)
continue;
if (vbq->bufs[first]->boff == (vma->vm_pgoff << PAGE_SHIFT))
break;
}
/* look for last buffer to map */
for (size = 0, last = first; last < VIDEO_MAX_FRAME; last++) {
if (NULL == vbq->bufs[last])
continue;
if (V4L2_MEMORY_MMAP != vbq->bufs[last]->memory)
continue;
size += vbq->bufs[last]->bsize;
if (size == (vma->vm_end - vma->vm_start))
break;
}
size = 0;
for (i = first; i <= last && i < VIDEO_MAX_FRAME; i++) {
struct videobuf_dmabuf *dma = videobuf_to_dma(vbq->bufs[i]);
for (j = 0; j < dma->sglen; j++) {
err = remap_pfn_range(
vma, vma->vm_start + size,
page_to_pfn(sg_page(&dma->sglist[j])),
sg_dma_len(&dma->sglist[j]), vma->vm_page_prot);
if (err)
goto out;
size += sg_dma_len(&dma->sglist[j]);
}
}
out:
mutex_unlock(&vbq->vb_lock);
return err;
}
static int omap24xxcam_mmap(struct file *file, struct vm_area_struct *vma)
{
struct omap24xxcam_fh *fh = file->private_data;
int rval;
/* let the video-buf mapper check arguments and set-up structures */
rval = videobuf_mmap_mapper(&fh->vbq, vma);
if (rval)
return rval;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
/* do mapping to our allocated buffers */
rval = omap24xxcam_mmap_buffers(file, vma);
/*
* In case of error, free vma->vm_private_data allocated by
* videobuf_mmap_mapper.
*/
if (rval)
kfree(vma->vm_private_data);
return rval;
}
static int omap24xxcam_open(struct file *file)
{
struct omap24xxcam_device *cam = omap24xxcam.priv;
struct omap24xxcam_fh *fh;
struct v4l2_format format;
if (!cam || !cam->vfd)
return -ENODEV;
fh = kzalloc(sizeof(*fh), GFP_KERNEL);
if (fh == NULL)
return -ENOMEM;
mutex_lock(&cam->mutex);
if (cam->sdev == NULL || !try_module_get(cam->sdev->module)) {
mutex_unlock(&cam->mutex);
goto out_try_module_get;
}
if (atomic_inc_return(&cam->users) == 1) {
omap24xxcam_hwinit(cam);
if (omap24xxcam_sensor_enable(cam)) {
mutex_unlock(&cam->mutex);
goto out_omap24xxcam_sensor_enable;
}
}
mutex_unlock(&cam->mutex);
fh->cam = cam;
mutex_lock(&cam->mutex);
vidioc_int_g_fmt_cap(cam->sdev, &format);
mutex_unlock(&cam->mutex);
/* FIXME: how about fh->pix when there are more users? */
fh->pix = format.fmt.pix;
file->private_data = fh;
spin_lock_init(&fh->vbq_lock);
videobuf_queue_sg_init(&fh->vbq, &omap24xxcam_vbq_ops, NULL,
&fh->vbq_lock, V4L2_BUF_TYPE_VIDEO_CAPTURE,
V4L2_FIELD_NONE,
sizeof(struct videobuf_buffer), fh, NULL);
return 0;
out_omap24xxcam_sensor_enable:
omap24xxcam_poweron_reset(cam);
module_put(cam->sdev->module);
out_try_module_get:
kfree(fh);
return -ENODEV;
}
static int omap24xxcam_release(struct file *file)
{
struct omap24xxcam_fh *fh = file->private_data;
struct omap24xxcam_device *cam = fh->cam;
atomic_inc(&cam->reset_disable);
flush_work_sync(&cam->sensor_reset_work);
/* stop streaming capture */
videobuf_streamoff(&fh->vbq);
mutex_lock(&cam->mutex);
if (cam->streaming == file) {
cam->streaming = NULL;
mutex_unlock(&cam->mutex);
sysfs_notify(&cam->dev->kobj, NULL, "streaming");
} else {
mutex_unlock(&cam->mutex);
}
atomic_dec(&cam->reset_disable);
omap24xxcam_vbq_free_mmap_buffers(&fh->vbq);
/*
* Make sure the reset work we might have scheduled is not
* pending! It may be run *only* if we have users. (And it may
* not be scheduled anymore since streaming is already
* disabled.)
*/
flush_work_sync(&cam->sensor_reset_work);
mutex_lock(&cam->mutex);
if (atomic_dec_return(&cam->users) == 0) {
omap24xxcam_sensor_disable(cam);
omap24xxcam_poweron_reset(cam);
}
mutex_unlock(&cam->mutex);
file->private_data = NULL;
module_put(cam->sdev->module);
kfree(fh);
return 0;
}
static struct v4l2_file_operations omap24xxcam_fops = {
.ioctl = video_ioctl2,
.poll = omap24xxcam_poll,
.mmap = omap24xxcam_mmap,
.open = omap24xxcam_open,
.release = omap24xxcam_release,
};
/*
*
* Power management.
*
*/
#ifdef CONFIG_PM
static int omap24xxcam_suspend(struct platform_device *pdev, pm_message_t state)
{
struct omap24xxcam_device *cam = platform_get_drvdata(pdev);
if (atomic_read(&cam->users) == 0)
return 0;
if (!atomic_read(&cam->reset_disable))
omap24xxcam_capture_stop(cam);
omap24xxcam_sensor_disable(cam);
omap24xxcam_poweron_reset(cam);
return 0;
}
static int omap24xxcam_resume(struct platform_device *pdev)
{
struct omap24xxcam_device *cam = platform_get_drvdata(pdev);
if (atomic_read(&cam->users) == 0)
return 0;
omap24xxcam_hwinit(cam);
omap24xxcam_sensor_enable(cam);
if (!atomic_read(&cam->reset_disable))
omap24xxcam_capture_cont(cam);
return 0;
}
#endif /* CONFIG_PM */
static const struct v4l2_ioctl_ops omap24xxcam_ioctl_fops = {
.vidioc_querycap = vidioc_querycap,
.vidioc_enum_fmt_vid_cap = vidioc_enum_fmt_vid_cap,
.vidioc_g_fmt_vid_cap = vidioc_g_fmt_vid_cap,
.vidioc_s_fmt_vid_cap = vidioc_s_fmt_vid_cap,
.vidioc_try_fmt_vid_cap = vidioc_try_fmt_vid_cap,
.vidioc_reqbufs = vidioc_reqbufs,
.vidioc_querybuf = vidioc_querybuf,
.vidioc_qbuf = vidioc_qbuf,
.vidioc_dqbuf = vidioc_dqbuf,
.vidioc_streamon = vidioc_streamon,
.vidioc_streamoff = vidioc_streamoff,
.vidioc_enum_input = vidioc_enum_input,
.vidioc_g_input = vidioc_g_input,
.vidioc_s_input = vidioc_s_input,
.vidioc_queryctrl = vidioc_queryctrl,
.vidioc_g_ctrl = vidioc_g_ctrl,
.vidioc_s_ctrl = vidioc_s_ctrl,
.vidioc_g_parm = vidioc_g_parm,
.vidioc_s_parm = vidioc_s_parm,
};
/*
*
* Camera device (i.e. /dev/video).
*
*/
static int omap24xxcam_device_register(struct v4l2_int_device *s)
{
struct omap24xxcam_device *cam = s->u.slave->master->priv;
struct video_device *vfd;
int rval;
/* We already have a slave. */
if (cam->sdev)
return -EBUSY;
cam->sdev = s;
if (device_create_file(cam->dev, &dev_attr_streaming) != 0) {
dev_err(cam->dev, "could not register sysfs entry\n");
rval = -EBUSY;
goto err;
}
/* initialize the video_device struct */
vfd = cam->vfd = video_device_alloc();
if (!vfd) {
dev_err(cam->dev, "could not allocate video device struct\n");
rval = -ENOMEM;
goto err;
}
vfd->release = video_device_release;
vfd->parent = cam->dev;
strlcpy(vfd->name, CAM_NAME, sizeof(vfd->name));
vfd->fops = &omap24xxcam_fops;
vfd->ioctl_ops = &omap24xxcam_ioctl_fops;
omap24xxcam_hwinit(cam);
rval = omap24xxcam_sensor_init(cam);
if (rval)
goto err;
if (video_register_device(vfd, VFL_TYPE_GRABBER, video_nr) < 0) {
dev_err(cam->dev, "could not register V4L device\n");
rval = -EBUSY;
goto err;
}
omap24xxcam_poweron_reset(cam);
dev_info(cam->dev, "registered device %s\n",
video_device_node_name(vfd));
return 0;
err:
omap24xxcam_device_unregister(s);
return rval;
}
static void omap24xxcam_device_unregister(struct v4l2_int_device *s)
{
struct omap24xxcam_device *cam = s->u.slave->master->priv;
omap24xxcam_sensor_exit(cam);
if (cam->vfd) {
if (!video_is_registered(cam->vfd)) {
/*
* The device was never registered, so release the
* video_device struct directly.
*/
video_device_release(cam->vfd);
} else {
/*
* The unregister function will release the
* video_device struct as well as
* unregistering it.
*/
video_unregister_device(cam->vfd);
}
cam->vfd = NULL;
}
device_remove_file(cam->dev, &dev_attr_streaming);
cam->sdev = NULL;
}
static struct v4l2_int_master omap24xxcam_master = {
.attach = omap24xxcam_device_register,
.detach = omap24xxcam_device_unregister,
};
static struct v4l2_int_device omap24xxcam = {
.module = THIS_MODULE,
.name = CAM_NAME,
.type = v4l2_int_type_master,
.u = {
.master = &omap24xxcam_master
},
};
/*
*
* Driver initialisation and deinitialisation.
*
*/
static int __devinit omap24xxcam_probe(struct platform_device *pdev)
{
struct omap24xxcam_device *cam;
struct resource *mem;
int irq;
cam = kzalloc(sizeof(*cam), GFP_KERNEL);
if (!cam) {
dev_err(&pdev->dev, "could not allocate memory\n");
goto err;
}
platform_set_drvdata(pdev, cam);
cam->dev = &pdev->dev;
/*
* Impose a lower limit on the amount of memory allocated for
* capture. We require at least enough memory to double-buffer
* QVGA (300KB).
*/
if (capture_mem < 320 * 240 * 2 * 2)
capture_mem = 320 * 240 * 2 * 2;
cam->capture_mem = capture_mem;
/* request the mem region for the camera registers */
mem = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!mem) {
dev_err(cam->dev, "no mem resource?\n");
goto err;
}
if (!request_mem_region(mem->start, resource_size(mem), pdev->name)) {
dev_err(cam->dev,
"cannot reserve camera register I/O region\n");
goto err;
}
cam->mmio_base_phys = mem->start;
cam->mmio_size = resource_size(mem);
/* map the region */
cam->mmio_base = (unsigned long)
ioremap_nocache(cam->mmio_base_phys, cam->mmio_size);
if (!cam->mmio_base) {
dev_err(cam->dev, "cannot map camera register I/O region\n");
goto err;
}
irq = platform_get_irq(pdev, 0);
if (irq <= 0) {
dev_err(cam->dev, "no irq for camera?\n");
goto err;
}
/* install the interrupt service routine */
if (request_irq(irq, omap24xxcam_isr, 0, CAM_NAME, cam)) {
dev_err(cam->dev,
"could not install interrupt service routine\n");
goto err;
}
cam->irq = irq;
if (omap24xxcam_clock_get(cam))
goto err;
INIT_WORK(&cam->sensor_reset_work, omap24xxcam_sensor_reset_work);
mutex_init(&cam->mutex);
spin_lock_init(&cam->core_enable_disable_lock);
omap24xxcam_sgdma_init(&cam->sgdma,
cam->mmio_base + CAMDMA_REG_OFFSET,
omap24xxcam_stalled_dma_reset,
(unsigned long)cam);
omap24xxcam.priv = cam;
if (v4l2_int_device_register(&omap24xxcam))
goto err;
return 0;
err:
omap24xxcam_remove(pdev);
return -ENODEV;
}
static int omap24xxcam_remove(struct platform_device *pdev)
{
struct omap24xxcam_device *cam = platform_get_drvdata(pdev);
if (!cam)
return 0;
if (omap24xxcam.priv != NULL)
v4l2_int_device_unregister(&omap24xxcam);
omap24xxcam.priv = NULL;
omap24xxcam_clock_put(cam);
if (cam->irq) {
free_irq(cam->irq, cam);
cam->irq = 0;
}
if (cam->mmio_base) {
iounmap((void *)cam->mmio_base);
cam->mmio_base = 0;
}
if (cam->mmio_base_phys) {
release_mem_region(cam->mmio_base_phys, cam->mmio_size);
cam->mmio_base_phys = 0;
}
kfree(cam);
return 0;
}
static struct platform_driver omap24xxcam_driver = {
.probe = omap24xxcam_probe,
.remove = omap24xxcam_remove,
#ifdef CONFIG_PM
.suspend = omap24xxcam_suspend,
.resume = omap24xxcam_resume,
#endif
.driver = {
.name = CAM_NAME,
.owner = THIS_MODULE,
},
};
module_platform_driver(omap24xxcam_driver);
MODULE_AUTHOR("Sakari Ailus <sakari.ailus@nokia.com>");
MODULE_DESCRIPTION("OMAP24xx Video for Linux camera driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(OMAP24XXCAM_VERSION);
module_param(video_nr, int, 0);
MODULE_PARM_DESC(video_nr,
"Minor number for video device (-1 ==> auto assign)");
module_param(capture_mem, int, 0);
MODULE_PARM_DESC(capture_mem, "Maximum amount of memory for capture "
"buffers (default 4800kiB)");
| gpl-2.0 |
n1kolaa/android_kernel_samsung_s3ve3g | arch/arm/mach-pxa/tavorevb.c | 4863 | 11429 | /*
* linux/arch/arm/mach-pxa/tavorevb.c
*
* Support for the Marvell PXA930 Evaluation Board
*
* Copyright (C) 2007-2008 Marvell International Ltd.
*
* 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
* publishhed by the Free Software Foundation.
*/
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/interrupt.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <linux/gpio.h>
#include <linux/smc91x.h>
#include <linux/pwm_backlight.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include <mach/pxa930.h>
#include <mach/pxafb.h>
#include <plat/pxa27x_keypad.h>
#include "devices.h"
#include "generic.h"
/* Tavor EVB MFP configurations */
static mfp_cfg_t tavorevb_mfp_cfg[] __initdata = {
/* Ethernet */
DF_nCS1_nCS3,
GPIO47_GPIO,
/* LCD */
GPIO23_LCD_DD0,
GPIO24_LCD_DD1,
GPIO25_LCD_DD2,
GPIO26_LCD_DD3,
GPIO27_LCD_DD4,
GPIO28_LCD_DD5,
GPIO29_LCD_DD6,
GPIO44_LCD_DD7,
GPIO21_LCD_CS,
GPIO22_LCD_CS2,
GPIO17_LCD_FCLK_RD,
GPIO18_LCD_LCLK_A0,
GPIO19_LCD_PCLK_WR,
/* LCD Backlight */
GPIO43_PWM3, /* primary backlight */
GPIO32_PWM0, /* secondary backlight */
/* Keypad */
GPIO0_KP_MKIN_0,
GPIO2_KP_MKIN_1,
GPIO4_KP_MKIN_2,
GPIO6_KP_MKIN_3,
GPIO8_KP_MKIN_4,
GPIO10_KP_MKIN_5,
GPIO12_KP_MKIN_6,
GPIO1_KP_MKOUT_0,
GPIO3_KP_MKOUT_1,
GPIO5_KP_MKOUT_2,
GPIO7_KP_MKOUT_3,
GPIO9_KP_MKOUT_4,
GPIO11_KP_MKOUT_5,
GPIO13_KP_MKOUT_6,
GPIO14_KP_DKIN_2,
GPIO15_KP_DKIN_3,
};
#define TAVOREVB_ETH_PHYS (0x14000000)
static struct resource smc91x_resources[] = {
[0] = {
.start = (TAVOREVB_ETH_PHYS + 0x300),
.end = (TAVOREVB_ETH_PHYS + 0xfffff),
.flags = IORESOURCE_MEM,
},
[1] = {
.start = PXA_GPIO_TO_IRQ(mfp_to_gpio(MFP_PIN_GPIO47)),
.end = PXA_GPIO_TO_IRQ(mfp_to_gpio(MFP_PIN_GPIO47)),
.flags = IORESOURCE_IRQ | IORESOURCE_IRQ_HIGHEDGE,
}
};
static struct smc91x_platdata tavorevb_smc91x_info = {
.flags = SMC91X_USE_16BIT | SMC91X_NOWAIT | SMC91X_USE_DMA,
};
static struct platform_device smc91x_device = {
.name = "smc91x",
.id = 0,
.num_resources = ARRAY_SIZE(smc91x_resources),
.resource = smc91x_resources,
.dev = {
.platform_data = &tavorevb_smc91x_info,
},
};
#if defined(CONFIG_KEYBOARD_PXA27x) || defined(CONFIG_KEYBOARD_PXA27x_MODULE)
static unsigned int tavorevb_matrix_key_map[] = {
/* KEY(row, col, key_code) */
KEY(0, 4, KEY_A), KEY(0, 5, KEY_B), KEY(0, 6, KEY_C),
KEY(1, 4, KEY_E), KEY(1, 5, KEY_F), KEY(1, 6, KEY_G),
KEY(2, 4, KEY_I), KEY(2, 5, KEY_J), KEY(2, 6, KEY_K),
KEY(3, 4, KEY_M), KEY(3, 5, KEY_N), KEY(3, 6, KEY_O),
KEY(4, 5, KEY_R), KEY(4, 6, KEY_S),
KEY(5, 4, KEY_U), KEY(5, 4, KEY_V), KEY(5, 6, KEY_W),
KEY(6, 4, KEY_Y), KEY(6, 5, KEY_Z),
KEY(0, 3, KEY_0), KEY(2, 0, KEY_1), KEY(2, 1, KEY_2), KEY(2, 2, KEY_3),
KEY(2, 3, KEY_4), KEY(1, 0, KEY_5), KEY(1, 1, KEY_6), KEY(1, 2, KEY_7),
KEY(1, 3, KEY_8), KEY(0, 2, KEY_9),
KEY(6, 6, KEY_SPACE),
KEY(0, 0, KEY_KPASTERISK), /* * */
KEY(0, 1, KEY_KPDOT), /* # */
KEY(4, 1, KEY_UP),
KEY(4, 3, KEY_DOWN),
KEY(4, 0, KEY_LEFT),
KEY(4, 2, KEY_RIGHT),
KEY(6, 0, KEY_HOME),
KEY(3, 2, KEY_END),
KEY(6, 1, KEY_DELETE),
KEY(5, 2, KEY_BACK),
KEY(6, 3, KEY_CAPSLOCK), /* KEY_LEFTSHIFT), */
KEY(4, 4, KEY_ENTER), /* scroll push */
KEY(6, 2, KEY_ENTER), /* keypad action */
KEY(3, 1, KEY_SEND),
KEY(5, 3, KEY_RECORD),
KEY(5, 0, KEY_VOLUMEUP),
KEY(5, 1, KEY_VOLUMEDOWN),
KEY(3, 0, KEY_F22), /* soft1 */
KEY(3, 3, KEY_F23), /* soft2 */
};
static struct pxa27x_keypad_platform_data tavorevb_keypad_info = {
.matrix_key_rows = 7,
.matrix_key_cols = 7,
.matrix_key_map = tavorevb_matrix_key_map,
.matrix_key_map_size = ARRAY_SIZE(tavorevb_matrix_key_map),
.debounce_interval = 30,
};
static void __init tavorevb_init_keypad(void)
{
pxa_set_keypad_info(&tavorevb_keypad_info);
}
#else
static inline void tavorevb_init_keypad(void) {}
#endif /* CONFIG_KEYBOARD_PXA27x || CONFIG_KEYBOARD_PXA27x_MODULE */
#if defined(CONFIG_FB_PXA) || defined(CONFIG_FB_PXA_MODULE)
static struct platform_pwm_backlight_data tavorevb_backlight_data[] = {
[0] = {
/* primary backlight */
.pwm_id = 2,
.max_brightness = 100,
.dft_brightness = 100,
.pwm_period_ns = 100000,
},
[1] = {
/* secondary backlight */
.pwm_id = 0,
.max_brightness = 100,
.dft_brightness = 100,
.pwm_period_ns = 100000,
},
};
static struct platform_device tavorevb_backlight_devices[] = {
[0] = {
.name = "pwm-backlight",
.id = 0,
.dev = {
.platform_data = &tavorevb_backlight_data[0],
},
},
[1] = {
.name = "pwm-backlight",
.id = 1,
.dev = {
.platform_data = &tavorevb_backlight_data[1],
},
},
};
static uint16_t panel_init[] = {
/* DSTB OUT */
SMART_CMD(0x00),
SMART_CMD_NOOP,
SMART_DELAY(1),
SMART_CMD(0x00),
SMART_CMD_NOOP,
SMART_DELAY(1),
SMART_CMD(0x00),
SMART_CMD_NOOP,
SMART_DELAY(1),
/* STB OUT */
SMART_CMD(0x00),
SMART_CMD(0x1D),
SMART_DAT(0x00),
SMART_DAT(0x05),
SMART_DELAY(1),
/* P-ON Init sequence */
SMART_CMD(0x00), /* OSC ON */
SMART_CMD(0x00),
SMART_DAT(0x00),
SMART_DAT(0x01),
SMART_CMD(0x00),
SMART_CMD(0x01), /* SOURCE DRIVER SHIFT DIRECTION and display RAM setting */
SMART_DAT(0x01),
SMART_DAT(0x27),
SMART_CMD(0x00),
SMART_CMD(0x02), /* LINE INV */
SMART_DAT(0x02),
SMART_DAT(0x00),
SMART_CMD(0x00),
SMART_CMD(0x03), /* IF mode(1) */
SMART_DAT(0x01), /* 8bit smart mode(8-8),high speed write mode */
SMART_DAT(0x30),
SMART_CMD(0x07),
SMART_CMD(0x00), /* RAM Write Mode */
SMART_DAT(0x00),
SMART_DAT(0x03),
SMART_CMD(0x00),
/* DISPLAY Setting, 262K, fixed(NO scroll), no split screen */
SMART_CMD(0x07),
SMART_DAT(0x40), /* 16/18/19 BPP */
SMART_DAT(0x00),
SMART_CMD(0x00),
SMART_CMD(0x08), /* BP, FP Seting, BP=2H, FP=3H */
SMART_DAT(0x03),
SMART_DAT(0x02),
SMART_CMD(0x00),
SMART_CMD(0x0C), /* IF mode(2), using internal clock & MPU */
SMART_DAT(0x00),
SMART_DAT(0x00),
SMART_CMD(0x00),
SMART_CMD(0x0D), /* Frame setting, 1Min. Frequence, 16CLK */
SMART_DAT(0x00),
SMART_DAT(0x10),
SMART_CMD(0x00),
SMART_CMD(0x12), /* Timing(1),ASW W=4CLK, ASW ST=1CLK */
SMART_DAT(0x03),
SMART_DAT(0x02),
SMART_CMD(0x00),
SMART_CMD(0x13), /* Timing(2),OEV ST=0.5CLK, OEV ED=1CLK */
SMART_DAT(0x01),
SMART_DAT(0x02),
SMART_CMD(0x00),
SMART_CMD(0x14), /* Timing(3), ASW HOLD=0.5CLK */
SMART_DAT(0x00),
SMART_DAT(0x00),
SMART_CMD(0x00),
SMART_CMD(0x15), /* Timing(4), CKV ST=0CLK, CKV ED=1CLK */
SMART_DAT(0x20),
SMART_DAT(0x00),
SMART_CMD(0x00),
SMART_CMD(0x1C),
SMART_DAT(0x00),
SMART_DAT(0x00),
SMART_CMD(0x03),
SMART_CMD(0x00),
SMART_DAT(0x04),
SMART_DAT(0x03),
SMART_CMD(0x03),
SMART_CMD(0x01),
SMART_DAT(0x03),
SMART_DAT(0x04),
SMART_CMD(0x03),
SMART_CMD(0x02),
SMART_DAT(0x04),
SMART_DAT(0x03),
SMART_CMD(0x03),
SMART_CMD(0x03),
SMART_DAT(0x03),
SMART_DAT(0x03),
SMART_CMD(0x03),
SMART_CMD(0x04),
SMART_DAT(0x01),
SMART_DAT(0x01),
SMART_CMD(0x03),
SMART_CMD(0x05),
SMART_DAT(0x00),
SMART_DAT(0x00),
SMART_CMD(0x04),
SMART_CMD(0x02),
SMART_DAT(0x00),
SMART_DAT(0x00),
SMART_CMD(0x04),
SMART_CMD(0x03),
SMART_DAT(0x01),
SMART_DAT(0x3F),
SMART_DELAY(0),
/* DISP RAM setting: 240*320 */
SMART_CMD(0x04), /* HADDR, START 0 */
SMART_CMD(0x06),
SMART_DAT(0x00),
SMART_DAT(0x00), /* x1,3 */
SMART_CMD(0x04), /* HADDR, END 4 */
SMART_CMD(0x07),
SMART_DAT(0x00),
SMART_DAT(0xEF), /* x2, 7 */
SMART_CMD(0x04), /* VADDR, START 8 */
SMART_CMD(0x08),
SMART_DAT(0x00), /* y1, 10 */
SMART_DAT(0x00), /* y1, 11 */
SMART_CMD(0x04), /* VADDR, END 12 */
SMART_CMD(0x09),
SMART_DAT(0x01), /* y2, 14 */
SMART_DAT(0x3F), /* y2, 15 */
SMART_CMD(0x02), /* RAM ADDR SETTING 16 */
SMART_CMD(0x00),
SMART_DAT(0x00),
SMART_DAT(0x00), /* x1, 19 */
SMART_CMD(0x02), /* RAM ADDR SETTING 20 */
SMART_CMD(0x01),
SMART_DAT(0x00), /* y1, 22 */
SMART_DAT(0x00), /* y1, 23 */
};
static uint16_t panel_on[] = {
/* Power-IC ON */
SMART_CMD(0x01),
SMART_CMD(0x02),
SMART_DAT(0x07),
SMART_DAT(0x7D),
SMART_CMD(0x01),
SMART_CMD(0x03),
SMART_DAT(0x00),
SMART_DAT(0x05),
SMART_CMD(0x01),
SMART_CMD(0x04),
SMART_DAT(0x00),
SMART_DAT(0x00),
SMART_CMD(0x01),
SMART_CMD(0x05),
SMART_DAT(0x00),
SMART_DAT(0x15),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0xC0),
SMART_DAT(0x10),
SMART_DELAY(30),
/* DISP ON */
SMART_CMD(0x01),
SMART_CMD(0x01),
SMART_DAT(0x00),
SMART_DAT(0x01),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0xFF),
SMART_DAT(0xFE),
SMART_DELAY(150),
};
static uint16_t panel_off[] = {
SMART_CMD(0x00),
SMART_CMD(0x1E),
SMART_DAT(0x00),
SMART_DAT(0x0A),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0xFF),
SMART_DAT(0xEE),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0xF8),
SMART_DAT(0x12),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0xE8),
SMART_DAT(0x11),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0xC0),
SMART_DAT(0x11),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0x40),
SMART_DAT(0x11),
SMART_CMD(0x01),
SMART_CMD(0x00),
SMART_DAT(0x00),
SMART_DAT(0x10),
};
static uint16_t update_framedata[] = {
/* write ram */
SMART_CMD(0x02),
SMART_CMD(0x02),
/* write frame data */
SMART_CMD_WRITE_FRAME,
};
static void ltm020d550_lcd_power(int on, struct fb_var_screeninfo *var)
{
struct fb_info *info = container_of(var, struct fb_info, var);
if (on) {
pxafb_smart_queue(info, ARRAY_AND_SIZE(panel_init));
pxafb_smart_queue(info, ARRAY_AND_SIZE(panel_on));
} else {
pxafb_smart_queue(info, ARRAY_AND_SIZE(panel_off));
}
if (pxafb_smart_flush(info))
pr_err("%s: timed out\n", __func__);
}
static void ltm020d550_update(struct fb_info *info)
{
pxafb_smart_queue(info, ARRAY_AND_SIZE(update_framedata));
pxafb_smart_flush(info);
}
static struct pxafb_mode_info toshiba_ltm020d550_modes[] = {
[0] = {
.xres = 240,
.yres = 320,
.bpp = 16,
.a0csrd_set_hld = 30,
.a0cswr_set_hld = 30,
.wr_pulse_width = 30,
.rd_pulse_width = 170,
.op_hold_time = 30,
.cmd_inh_time = 60,
/* L_LCLK_A0 and L_LCLK_RD active low */
.sync = FB_SYNC_HOR_HIGH_ACT |
FB_SYNC_VERT_HIGH_ACT,
},
};
static struct pxafb_mach_info tavorevb_lcd_info = {
.modes = toshiba_ltm020d550_modes,
.num_modes = 1,
.lcd_conn = LCD_SMART_PANEL_8BPP | LCD_PCLK_EDGE_FALL,
.pxafb_lcd_power = ltm020d550_lcd_power,
.smart_update = ltm020d550_update,
};
static void __init tavorevb_init_lcd(void)
{
platform_device_register(&tavorevb_backlight_devices[0]);
platform_device_register(&tavorevb_backlight_devices[1]);
pxa_set_fb_info(NULL, &tavorevb_lcd_info);
}
#else
static inline void tavorevb_init_lcd(void) {}
#endif /* CONFIG_FB_PXA || CONFIG_FB_PXA_MODULE */
static void __init tavorevb_init(void)
{
/* initialize MFP configurations */
pxa3xx_mfp_config(ARRAY_AND_SIZE(tavorevb_mfp_cfg));
pxa_set_ffuart_info(NULL);
pxa_set_btuart_info(NULL);
pxa_set_stuart_info(NULL);
platform_device_register(&smc91x_device);
tavorevb_init_lcd();
tavorevb_init_keypad();
}
MACHINE_START(TAVOREVB, "PXA930 Evaluation Board (aka TavorEVB)")
/* Maintainer: Eric Miao <eric.miao@marvell.com> */
.atag_offset = 0x100,
.map_io = pxa3xx_map_io,
.nr_irqs = PXA_NR_IRQS,
.init_irq = pxa3xx_init_irq,
.handle_irq = pxa3xx_handle_irq,
.timer = &pxa_timer,
.init_machine = tavorevb_init,
.restart = pxa_restart,
MACHINE_END
| gpl-2.0 |
TheStrix/android_kernel_xiaomi_armani_OLD | drivers/ssb/scan.c | 4863 | 10634 | /*
* Sonics Silicon Backplane
* Bus scanning
*
* Copyright (C) 2005-2007 Michael Buesch <m@bues.ch>
* Copyright (C) 2005 Martin Langer <martin-langer@gmx.de>
* Copyright (C) 2005 Stefano Brivio <st3@riseup.net>
* Copyright (C) 2005 Danny van Dyk <kugelfang@gentoo.org>
* Copyright (C) 2005 Andreas Jaggi <andreas.jaggi@waterwave.ch>
* Copyright (C) 2006 Broadcom Corporation.
*
* Licensed under the GNU/GPL. See COPYING for details.
*/
#include <linux/ssb/ssb.h>
#include <linux/ssb/ssb_regs.h>
#include <linux/pci.h>
#include <linux/io.h>
#include <pcmcia/cistpl.h>
#include <pcmcia/ds.h>
#include "ssb_private.h"
const char *ssb_core_name(u16 coreid)
{
switch (coreid) {
case SSB_DEV_CHIPCOMMON:
return "ChipCommon";
case SSB_DEV_ILINE20:
return "ILine 20";
case SSB_DEV_SDRAM:
return "SDRAM";
case SSB_DEV_PCI:
return "PCI";
case SSB_DEV_MIPS:
return "MIPS";
case SSB_DEV_ETHERNET:
return "Fast Ethernet";
case SSB_DEV_V90:
return "V90";
case SSB_DEV_USB11_HOSTDEV:
return "USB 1.1 Hostdev";
case SSB_DEV_ADSL:
return "ADSL";
case SSB_DEV_ILINE100:
return "ILine 100";
case SSB_DEV_IPSEC:
return "IPSEC";
case SSB_DEV_PCMCIA:
return "PCMCIA";
case SSB_DEV_INTERNAL_MEM:
return "Internal Memory";
case SSB_DEV_MEMC_SDRAM:
return "MEMC SDRAM";
case SSB_DEV_EXTIF:
return "EXTIF";
case SSB_DEV_80211:
return "IEEE 802.11";
case SSB_DEV_MIPS_3302:
return "MIPS 3302";
case SSB_DEV_USB11_HOST:
return "USB 1.1 Host";
case SSB_DEV_USB11_DEV:
return "USB 1.1 Device";
case SSB_DEV_USB20_HOST:
return "USB 2.0 Host";
case SSB_DEV_USB20_DEV:
return "USB 2.0 Device";
case SSB_DEV_SDIO_HOST:
return "SDIO Host";
case SSB_DEV_ROBOSWITCH:
return "Roboswitch";
case SSB_DEV_PARA_ATA:
return "PATA";
case SSB_DEV_SATA_XORDMA:
return "SATA XOR-DMA";
case SSB_DEV_ETHERNET_GBIT:
return "GBit Ethernet";
case SSB_DEV_PCIE:
return "PCI-E";
case SSB_DEV_MIMO_PHY:
return "MIMO PHY";
case SSB_DEV_SRAM_CTRLR:
return "SRAM Controller";
case SSB_DEV_MINI_MACPHY:
return "Mini MACPHY";
case SSB_DEV_ARM_1176:
return "ARM 1176";
case SSB_DEV_ARM_7TDMI:
return "ARM 7TDMI";
}
return "UNKNOWN";
}
static u16 pcidev_to_chipid(struct pci_dev *pci_dev)
{
u16 chipid_fallback = 0;
switch (pci_dev->device) {
case 0x4301:
chipid_fallback = 0x4301;
break;
case 0x4305 ... 0x4307:
chipid_fallback = 0x4307;
break;
case 0x4403:
chipid_fallback = 0x4402;
break;
case 0x4610 ... 0x4615:
chipid_fallback = 0x4610;
break;
case 0x4710 ... 0x4715:
chipid_fallback = 0x4710;
break;
case 0x4320 ... 0x4325:
chipid_fallback = 0x4309;
break;
case PCI_DEVICE_ID_BCM4401:
case PCI_DEVICE_ID_BCM4401B0:
case PCI_DEVICE_ID_BCM4401B1:
chipid_fallback = 0x4401;
break;
default:
ssb_printk(KERN_ERR PFX
"PCI-ID not in fallback list\n");
}
return chipid_fallback;
}
static u8 chipid_to_nrcores(u16 chipid)
{
switch (chipid) {
case 0x5365:
return 7;
case 0x4306:
return 6;
case 0x4310:
return 8;
case 0x4307:
case 0x4301:
return 5;
case 0x4401:
case 0x4402:
return 3;
case 0x4710:
case 0x4610:
case 0x4704:
return 9;
default:
ssb_printk(KERN_ERR PFX
"CHIPID not in nrcores fallback list\n");
}
return 1;
}
static u32 scan_read32(struct ssb_bus *bus, u8 current_coreidx,
u16 offset)
{
u32 lo, hi;
switch (bus->bustype) {
case SSB_BUSTYPE_SSB:
offset += current_coreidx * SSB_CORE_SIZE;
break;
case SSB_BUSTYPE_PCI:
break;
case SSB_BUSTYPE_PCMCIA:
if (offset >= 0x800) {
ssb_pcmcia_switch_segment(bus, 1);
offset -= 0x800;
} else
ssb_pcmcia_switch_segment(bus, 0);
lo = readw(bus->mmio + offset);
hi = readw(bus->mmio + offset + 2);
return lo | (hi << 16);
case SSB_BUSTYPE_SDIO:
offset += current_coreidx * SSB_CORE_SIZE;
return ssb_sdio_scan_read32(bus, offset);
}
return readl(bus->mmio + offset);
}
static int scan_switchcore(struct ssb_bus *bus, u8 coreidx)
{
switch (bus->bustype) {
case SSB_BUSTYPE_SSB:
break;
case SSB_BUSTYPE_PCI:
return ssb_pci_switch_coreidx(bus, coreidx);
case SSB_BUSTYPE_PCMCIA:
return ssb_pcmcia_switch_coreidx(bus, coreidx);
case SSB_BUSTYPE_SDIO:
return ssb_sdio_scan_switch_coreidx(bus, coreidx);
}
return 0;
}
void ssb_iounmap(struct ssb_bus *bus)
{
switch (bus->bustype) {
case SSB_BUSTYPE_SSB:
case SSB_BUSTYPE_PCMCIA:
iounmap(bus->mmio);
break;
case SSB_BUSTYPE_PCI:
#ifdef CONFIG_SSB_PCIHOST
pci_iounmap(bus->host_pci, bus->mmio);
#else
SSB_BUG_ON(1); /* Can't reach this code. */
#endif
break;
case SSB_BUSTYPE_SDIO:
break;
}
bus->mmio = NULL;
bus->mapped_device = NULL;
}
static void __iomem *ssb_ioremap(struct ssb_bus *bus,
unsigned long baseaddr)
{
void __iomem *mmio = NULL;
switch (bus->bustype) {
case SSB_BUSTYPE_SSB:
/* Only map the first core for now. */
/* fallthrough... */
case SSB_BUSTYPE_PCMCIA:
mmio = ioremap(baseaddr, SSB_CORE_SIZE);
break;
case SSB_BUSTYPE_PCI:
#ifdef CONFIG_SSB_PCIHOST
mmio = pci_iomap(bus->host_pci, 0, ~0UL);
#else
SSB_BUG_ON(1); /* Can't reach this code. */
#endif
break;
case SSB_BUSTYPE_SDIO:
/* Nothing to ioremap in the SDIO case, just fake it */
mmio = (void __iomem *)baseaddr;
break;
}
return mmio;
}
static int we_support_multiple_80211_cores(struct ssb_bus *bus)
{
/* More than one 802.11 core is only supported by special chips.
* There are chips with two 802.11 cores, but with dangling
* pins on the second core. Be careful and reject them here.
*/
#ifdef CONFIG_SSB_PCIHOST
if (bus->bustype == SSB_BUSTYPE_PCI) {
if (bus->host_pci->vendor == PCI_VENDOR_ID_BROADCOM &&
((bus->host_pci->device == 0x4313) ||
(bus->host_pci->device == 0x431A) ||
(bus->host_pci->device == 0x4321) ||
(bus->host_pci->device == 0x4324)))
return 1;
}
#endif /* CONFIG_SSB_PCIHOST */
return 0;
}
int ssb_bus_scan(struct ssb_bus *bus,
unsigned long baseaddr)
{
int err = -ENOMEM;
void __iomem *mmio;
u32 idhi, cc, rev, tmp;
int dev_i, i;
struct ssb_device *dev;
int nr_80211_cores = 0;
mmio = ssb_ioremap(bus, baseaddr);
if (!mmio)
goto out;
bus->mmio = mmio;
err = scan_switchcore(bus, 0); /* Switch to first core */
if (err)
goto err_unmap;
idhi = scan_read32(bus, 0, SSB_IDHIGH);
cc = (idhi & SSB_IDHIGH_CC) >> SSB_IDHIGH_CC_SHIFT;
rev = (idhi & SSB_IDHIGH_RCLO);
rev |= (idhi & SSB_IDHIGH_RCHI) >> SSB_IDHIGH_RCHI_SHIFT;
bus->nr_devices = 0;
if (cc == SSB_DEV_CHIPCOMMON) {
tmp = scan_read32(bus, 0, SSB_CHIPCO_CHIPID);
bus->chip_id = (tmp & SSB_CHIPCO_IDMASK);
bus->chip_rev = (tmp & SSB_CHIPCO_REVMASK) >>
SSB_CHIPCO_REVSHIFT;
bus->chip_package = (tmp & SSB_CHIPCO_PACKMASK) >>
SSB_CHIPCO_PACKSHIFT;
if (rev >= 4) {
bus->nr_devices = (tmp & SSB_CHIPCO_NRCORESMASK) >>
SSB_CHIPCO_NRCORESSHIFT;
}
tmp = scan_read32(bus, 0, SSB_CHIPCO_CAP);
bus->chipco.capabilities = tmp;
} else {
if (bus->bustype == SSB_BUSTYPE_PCI) {
bus->chip_id = pcidev_to_chipid(bus->host_pci);
bus->chip_rev = bus->host_pci->revision;
bus->chip_package = 0;
} else {
bus->chip_id = 0x4710;
bus->chip_rev = 0;
bus->chip_package = 0;
}
}
ssb_printk(KERN_INFO PFX "Found chip with id 0x%04X, rev 0x%02X and "
"package 0x%02X\n", bus->chip_id, bus->chip_rev,
bus->chip_package);
if (!bus->nr_devices)
bus->nr_devices = chipid_to_nrcores(bus->chip_id);
if (bus->nr_devices > ARRAY_SIZE(bus->devices)) {
ssb_printk(KERN_ERR PFX
"More than %d ssb cores found (%d)\n",
SSB_MAX_NR_CORES, bus->nr_devices);
goto err_unmap;
}
if (bus->bustype == SSB_BUSTYPE_SSB) {
/* Now that we know the number of cores,
* remap the whole IO space for all cores.
*/
err = -ENOMEM;
iounmap(mmio);
mmio = ioremap(baseaddr, SSB_CORE_SIZE * bus->nr_devices);
if (!mmio)
goto out;
bus->mmio = mmio;
}
/* Fetch basic information about each core/device */
for (i = 0, dev_i = 0; i < bus->nr_devices; i++) {
err = scan_switchcore(bus, i);
if (err)
goto err_unmap;
dev = &(bus->devices[dev_i]);
idhi = scan_read32(bus, i, SSB_IDHIGH);
dev->id.coreid = (idhi & SSB_IDHIGH_CC) >> SSB_IDHIGH_CC_SHIFT;
dev->id.revision = (idhi & SSB_IDHIGH_RCLO);
dev->id.revision |= (idhi & SSB_IDHIGH_RCHI) >> SSB_IDHIGH_RCHI_SHIFT;
dev->id.vendor = (idhi & SSB_IDHIGH_VC) >> SSB_IDHIGH_VC_SHIFT;
dev->core_index = i;
dev->bus = bus;
dev->ops = bus->ops;
printk(KERN_DEBUG PFX
"Core %d found: %s "
"(cc 0x%03X, rev 0x%02X, vendor 0x%04X)\n",
i, ssb_core_name(dev->id.coreid),
dev->id.coreid, dev->id.revision, dev->id.vendor);
switch (dev->id.coreid) {
case SSB_DEV_80211:
nr_80211_cores++;
if (nr_80211_cores > 1) {
if (!we_support_multiple_80211_cores(bus)) {
ssb_dprintk(KERN_INFO PFX "Ignoring additional "
"802.11 core\n");
continue;
}
}
break;
case SSB_DEV_EXTIF:
#ifdef CONFIG_SSB_DRIVER_EXTIF
if (bus->extif.dev) {
ssb_printk(KERN_WARNING PFX
"WARNING: Multiple EXTIFs found\n");
break;
}
bus->extif.dev = dev;
#endif /* CONFIG_SSB_DRIVER_EXTIF */
break;
case SSB_DEV_CHIPCOMMON:
if (bus->chipco.dev) {
ssb_printk(KERN_WARNING PFX
"WARNING: Multiple ChipCommon found\n");
break;
}
bus->chipco.dev = dev;
break;
case SSB_DEV_MIPS:
case SSB_DEV_MIPS_3302:
#ifdef CONFIG_SSB_DRIVER_MIPS
if (bus->mipscore.dev) {
ssb_printk(KERN_WARNING PFX
"WARNING: Multiple MIPS cores found\n");
break;
}
bus->mipscore.dev = dev;
#endif /* CONFIG_SSB_DRIVER_MIPS */
break;
case SSB_DEV_PCI:
case SSB_DEV_PCIE:
#ifdef CONFIG_SSB_DRIVER_PCICORE
if (bus->bustype == SSB_BUSTYPE_PCI) {
/* Ignore PCI cores on PCI-E cards.
* Ignore PCI-E cores on PCI cards. */
if (dev->id.coreid == SSB_DEV_PCI) {
if (pci_is_pcie(bus->host_pci))
continue;
} else {
if (!pci_is_pcie(bus->host_pci))
continue;
}
}
if (bus->pcicore.dev) {
ssb_printk(KERN_WARNING PFX
"WARNING: Multiple PCI(E) cores found\n");
break;
}
bus->pcicore.dev = dev;
#endif /* CONFIG_SSB_DRIVER_PCICORE */
break;
case SSB_DEV_ETHERNET:
if (bus->bustype == SSB_BUSTYPE_PCI) {
if (bus->host_pci->vendor == PCI_VENDOR_ID_BROADCOM &&
(bus->host_pci->device & 0xFF00) == 0x4300) {
/* This is a dangling ethernet core on a
* wireless device. Ignore it. */
continue;
}
}
break;
default:
break;
}
dev_i++;
}
bus->nr_devices = dev_i;
err = 0;
out:
return err;
err_unmap:
ssb_iounmap(bus);
goto out;
}
| gpl-2.0 |
nbr11/android_kernel_lge_hammerhead | drivers/net/ethernet/amd/lance.c | 5119 | 41400 | /* lance.c: An AMD LANCE/PCnet ethernet driver for Linux. */
/*
Written/copyright 1993-1998 by Donald Becker.
Copyright 1993 United States Government as represented by the
Director, National Security Agency.
This software may be used and distributed according to the terms
of the GNU General Public License, incorporated herein by reference.
This driver is for the Allied Telesis AT1500 and HP J2405A, and should work
with most other LANCE-based bus-master (NE2100/NE2500) ethercards.
The author may be reached as becker@scyld.com, or C/O
Scyld Computing Corporation
410 Severn Ave., Suite 210
Annapolis MD 21403
Andrey V. Savochkin:
- alignment problem with 1.3.* kernel and some minor changes.
Thomas Bogendoerfer (tsbogend@bigbug.franken.de):
- added support for Linux/Alpha, but removed most of it, because
it worked only for the PCI chip.
- added hook for the 32bit lance driver
- added PCnetPCI II (79C970A) to chip table
Paul Gortmaker (gpg109@rsphy1.anu.edu.au):
- hopefully fix above so Linux/Alpha can use ISA cards too.
8/20/96 Fixed 7990 autoIRQ failure and reversed unneeded alignment -djb
v1.12 10/27/97 Module support -djb
v1.14 2/3/98 Module support modified, made PCI support optional -djb
v1.15 5/27/99 Fixed bug in the cleanup_module(). dev->priv was freed
before unregister_netdev() which caused NULL pointer
reference later in the chain (in rtnetlink_fill_ifinfo())
-- Mika Kuoppala <miku@iki.fi>
Forward ported v1.14 to 2.1.129, merged the PCI and misc changes from
the 2.1 version of the old driver - Alan Cox
Get rid of check_region, check kmalloc return in lance_probe1
Arnaldo Carvalho de Melo <acme@conectiva.com.br> - 11/01/2001
Reworked detection, added support for Racal InterLan EtherBlaster cards
Vesselin Kostadinov <vesok at yahoo dot com > - 22/4/2004
*/
static const char version[] = "lance.c:v1.16 2006/11/09 dplatt@3do.com, becker@cesdis.gsfc.nasa.gov\n";
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/ioport.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/skbuff.h>
#include <linux/mm.h>
#include <linux/bitops.h>
#include <asm/io.h>
#include <asm/dma.h>
static unsigned int lance_portlist[] __initdata = { 0x300, 0x320, 0x340, 0x360, 0};
static int lance_probe1(struct net_device *dev, int ioaddr, int irq, int options);
static int __init do_lance_probe(struct net_device *dev);
static struct card {
char id_offset14;
char id_offset15;
} cards[] = {
{ //"normal"
.id_offset14 = 0x57,
.id_offset15 = 0x57,
},
{ //NI6510EB
.id_offset14 = 0x52,
.id_offset15 = 0x44,
},
{ //Racal InterLan EtherBlaster
.id_offset14 = 0x52,
.id_offset15 = 0x49,
},
};
#define NUM_CARDS 3
#ifdef LANCE_DEBUG
static int lance_debug = LANCE_DEBUG;
#else
static int lance_debug = 1;
#endif
/*
Theory of Operation
I. Board Compatibility
This device driver is designed for the AMD 79C960, the "PCnet-ISA
single-chip ethernet controller for ISA". This chip is used in a wide
variety of boards from vendors such as Allied Telesis, HP, Kingston,
and Boca. This driver is also intended to work with older AMD 7990
designs, such as the NE1500 and NE2100, and newer 79C961. For convenience,
I use the name LANCE to refer to all of the AMD chips, even though it properly
refers only to the original 7990.
II. Board-specific settings
The driver is designed to work the boards that use the faster
bus-master mode, rather than in shared memory mode. (Only older designs
have on-board buffer memory needed to support the slower shared memory mode.)
Most ISA boards have jumpered settings for the I/O base, IRQ line, and DMA
channel. This driver probes the likely base addresses:
{0x300, 0x320, 0x340, 0x360}.
After the board is found it generates a DMA-timeout interrupt and uses
autoIRQ to find the IRQ line. The DMA channel can be set with the low bits
of the otherwise-unused dev->mem_start value (aka PARAM1). If unset it is
probed for by enabling each free DMA channel in turn and checking if
initialization succeeds.
The HP-J2405A board is an exception: with this board it is easy to read the
EEPROM-set values for the base, IRQ, and DMA. (Of course you must already
_know_ the base address -- that field is for writing the EEPROM.)
III. Driver operation
IIIa. Ring buffers
The LANCE uses ring buffers of Tx and Rx descriptors. Each entry describes
the base and length of the data buffer, along with status bits. The length
of these buffers is set by LANCE_LOG_{RX,TX}_BUFFERS, which is log_2() of
the buffer length (rather than being directly the buffer length) for
implementation ease. The current values are 2 (Tx) and 4 (Rx), which leads to
ring sizes of 4 (Tx) and 16 (Rx). Increasing the number of ring entries
needlessly uses extra space and reduces the chance that an upper layer will
be able to reorder queued Tx packets based on priority. Decreasing the number
of entries makes it more difficult to achieve back-to-back packet transmission
and increases the chance that Rx ring will overflow. (Consider the worst case
of receiving back-to-back minimum-sized packets.)
The LANCE has the capability to "chain" both Rx and Tx buffers, but this driver
statically allocates full-sized (slightly oversized -- PKT_BUF_SZ) buffers to
avoid the administrative overhead. For the Rx side this avoids dynamically
allocating full-sized buffers "just in case", at the expense of a
memory-to-memory data copy for each packet received. For most systems this
is a good tradeoff: the Rx buffer will always be in low memory, the copy
is inexpensive, and it primes the cache for later packet processing. For Tx
the buffers are only used when needed as low-memory bounce buffers.
IIIB. 16M memory limitations.
For the ISA bus master mode all structures used directly by the LANCE,
the initialization block, Rx and Tx rings, and data buffers, must be
accessible from the ISA bus, i.e. in the lower 16M of real memory.
This is a problem for current Linux kernels on >16M machines. The network
devices are initialized after memory initialization, and the kernel doles out
memory from the top of memory downward. The current solution is to have a
special network initialization routine that's called before memory
initialization; this will eventually be generalized for all network devices.
As mentioned before, low-memory "bounce-buffers" are used when needed.
IIIC. Synchronization
The driver runs as two independent, single-threaded flows of control. One
is the send-packet routine, which enforces single-threaded use by the
dev->tbusy flag. The other thread is the interrupt handler, which is single
threaded by the hardware and other software.
The send packet thread has partial control over the Tx ring and 'dev->tbusy'
flag. It sets the tbusy flag whenever it's queuing a Tx packet. If the next
queue slot is empty, it clears the tbusy flag when finished otherwise it sets
the 'lp->tx_full' flag.
The interrupt handler has exclusive control over the Rx ring and records stats
from the Tx ring. (The Tx-done interrupt can't be selectively turned off, so
we can't avoid the interrupt overhead by having the Tx routine reap the Tx
stats.) After reaping the stats, it marks the queue entry as empty by setting
the 'base' to zero. Iff the 'lp->tx_full' flag is set, it clears both the
tx_full and tbusy flags.
*/
/* Set the number of Tx and Rx buffers, using Log_2(# buffers).
Reasonable default values are 16 Tx buffers, and 16 Rx buffers.
That translates to 4 and 4 (16 == 2^^4).
This is a compile-time option for efficiency.
*/
#ifndef LANCE_LOG_TX_BUFFERS
#define LANCE_LOG_TX_BUFFERS 4
#define LANCE_LOG_RX_BUFFERS 4
#endif
#define TX_RING_SIZE (1 << (LANCE_LOG_TX_BUFFERS))
#define TX_RING_MOD_MASK (TX_RING_SIZE - 1)
#define TX_RING_LEN_BITS ((LANCE_LOG_TX_BUFFERS) << 29)
#define RX_RING_SIZE (1 << (LANCE_LOG_RX_BUFFERS))
#define RX_RING_MOD_MASK (RX_RING_SIZE - 1)
#define RX_RING_LEN_BITS ((LANCE_LOG_RX_BUFFERS) << 29)
#define PKT_BUF_SZ 1544
/* Offsets from base I/O address. */
#define LANCE_DATA 0x10
#define LANCE_ADDR 0x12
#define LANCE_RESET 0x14
#define LANCE_BUS_IF 0x16
#define LANCE_TOTAL_SIZE 0x18
#define TX_TIMEOUT (HZ/5)
/* The LANCE Rx and Tx ring descriptors. */
struct lance_rx_head {
s32 base;
s16 buf_length; /* This length is 2s complement (negative)! */
s16 msg_length; /* This length is "normal". */
};
struct lance_tx_head {
s32 base;
s16 length; /* Length is 2s complement (negative)! */
s16 misc;
};
/* The LANCE initialization block, described in databook. */
struct lance_init_block {
u16 mode; /* Pre-set mode (reg. 15) */
u8 phys_addr[6]; /* Physical ethernet address */
u32 filter[2]; /* Multicast filter (unused). */
/* Receive and transmit ring base, along with extra bits. */
u32 rx_ring; /* Tx and Rx ring base pointers */
u32 tx_ring;
};
struct lance_private {
/* The Tx and Rx ring entries must be aligned on 8-byte boundaries. */
struct lance_rx_head rx_ring[RX_RING_SIZE];
struct lance_tx_head tx_ring[TX_RING_SIZE];
struct lance_init_block init_block;
const char *name;
/* The saved address of a sent-in-place packet/buffer, for skfree(). */
struct sk_buff* tx_skbuff[TX_RING_SIZE];
/* The addresses of receive-in-place skbuffs. */
struct sk_buff* rx_skbuff[RX_RING_SIZE];
unsigned long rx_buffs; /* Address of Rx and Tx buffers. */
/* Tx low-memory "bounce buffer" address. */
char (*tx_bounce_buffs)[PKT_BUF_SZ];
int cur_rx, cur_tx; /* The next free ring entry */
int dirty_rx, dirty_tx; /* The ring entries to be free()ed. */
int dma;
unsigned char chip_version; /* See lance_chip_type. */
spinlock_t devlock;
};
#define LANCE_MUST_PAD 0x00000001
#define LANCE_ENABLE_AUTOSELECT 0x00000002
#define LANCE_MUST_REINIT_RING 0x00000004
#define LANCE_MUST_UNRESET 0x00000008
#define LANCE_HAS_MISSED_FRAME 0x00000010
/* A mapping from the chip ID number to the part number and features.
These are from the datasheets -- in real life the '970 version
reportedly has the same ID as the '965. */
static struct lance_chip_type {
int id_number;
const char *name;
int flags;
} chip_table[] = {
{0x0000, "LANCE 7990", /* Ancient lance chip. */
LANCE_MUST_PAD + LANCE_MUST_UNRESET},
{0x0003, "PCnet/ISA 79C960", /* 79C960 PCnet/ISA. */
LANCE_ENABLE_AUTOSELECT + LANCE_MUST_REINIT_RING +
LANCE_HAS_MISSED_FRAME},
{0x2260, "PCnet/ISA+ 79C961", /* 79C961 PCnet/ISA+, Plug-n-Play. */
LANCE_ENABLE_AUTOSELECT + LANCE_MUST_REINIT_RING +
LANCE_HAS_MISSED_FRAME},
{0x2420, "PCnet/PCI 79C970", /* 79C970 or 79C974 PCnet-SCSI, PCI. */
LANCE_ENABLE_AUTOSELECT + LANCE_MUST_REINIT_RING +
LANCE_HAS_MISSED_FRAME},
/* Bug: the PCnet/PCI actually uses the PCnet/VLB ID number, so just call
it the PCnet32. */
{0x2430, "PCnet32", /* 79C965 PCnet for VL bus. */
LANCE_ENABLE_AUTOSELECT + LANCE_MUST_REINIT_RING +
LANCE_HAS_MISSED_FRAME},
{0x2621, "PCnet/PCI-II 79C970A", /* 79C970A PCInetPCI II. */
LANCE_ENABLE_AUTOSELECT + LANCE_MUST_REINIT_RING +
LANCE_HAS_MISSED_FRAME},
{0x0, "PCnet (unknown)",
LANCE_ENABLE_AUTOSELECT + LANCE_MUST_REINIT_RING +
LANCE_HAS_MISSED_FRAME},
};
enum {OLD_LANCE = 0, PCNET_ISA=1, PCNET_ISAP=2, PCNET_PCI=3, PCNET_VLB=4, PCNET_PCI_II=5, LANCE_UNKNOWN=6};
/* Non-zero if lance_probe1() needs to allocate low-memory bounce buffers.
Assume yes until we know the memory size. */
static unsigned char lance_need_isa_bounce_buffers = 1;
static int lance_open(struct net_device *dev);
static void lance_init_ring(struct net_device *dev, gfp_t mode);
static netdev_tx_t lance_start_xmit(struct sk_buff *skb,
struct net_device *dev);
static int lance_rx(struct net_device *dev);
static irqreturn_t lance_interrupt(int irq, void *dev_id);
static int lance_close(struct net_device *dev);
static struct net_device_stats *lance_get_stats(struct net_device *dev);
static void set_multicast_list(struct net_device *dev);
static void lance_tx_timeout (struct net_device *dev);
#ifdef MODULE
#define MAX_CARDS 8 /* Max number of interfaces (cards) per module */
static struct net_device *dev_lance[MAX_CARDS];
static int io[MAX_CARDS];
static int dma[MAX_CARDS];
static int irq[MAX_CARDS];
module_param_array(io, int, NULL, 0);
module_param_array(dma, int, NULL, 0);
module_param_array(irq, int, NULL, 0);
module_param(lance_debug, int, 0);
MODULE_PARM_DESC(io, "LANCE/PCnet I/O base address(es),required");
MODULE_PARM_DESC(dma, "LANCE/PCnet ISA DMA channel (ignored for some devices)");
MODULE_PARM_DESC(irq, "LANCE/PCnet IRQ number (ignored for some devices)");
MODULE_PARM_DESC(lance_debug, "LANCE/PCnet debug level (0-7)");
int __init init_module(void)
{
struct net_device *dev;
int this_dev, found = 0;
for (this_dev = 0; this_dev < MAX_CARDS; this_dev++) {
if (io[this_dev] == 0) {
if (this_dev != 0) /* only complain once */
break;
printk(KERN_NOTICE "lance.c: Module autoprobing not allowed. Append \"io=0xNNN\" value(s).\n");
return -EPERM;
}
dev = alloc_etherdev(0);
if (!dev)
break;
dev->irq = irq[this_dev];
dev->base_addr = io[this_dev];
dev->dma = dma[this_dev];
if (do_lance_probe(dev) == 0) {
dev_lance[found++] = dev;
continue;
}
free_netdev(dev);
break;
}
if (found != 0)
return 0;
return -ENXIO;
}
static void cleanup_card(struct net_device *dev)
{
struct lance_private *lp = dev->ml_priv;
if (dev->dma != 4)
free_dma(dev->dma);
release_region(dev->base_addr, LANCE_TOTAL_SIZE);
kfree(lp->tx_bounce_buffs);
kfree((void*)lp->rx_buffs);
kfree(lp);
}
void __exit cleanup_module(void)
{
int this_dev;
for (this_dev = 0; this_dev < MAX_CARDS; this_dev++) {
struct net_device *dev = dev_lance[this_dev];
if (dev) {
unregister_netdev(dev);
cleanup_card(dev);
free_netdev(dev);
}
}
}
#endif /* MODULE */
MODULE_LICENSE("GPL");
/* Starting in v2.1.*, the LANCE/PCnet probe is now similar to the other
board probes now that kmalloc() can allocate ISA DMA-able regions.
This also allows the LANCE driver to be used as a module.
*/
static int __init do_lance_probe(struct net_device *dev)
{
unsigned int *port;
int result;
if (high_memory <= phys_to_virt(16*1024*1024))
lance_need_isa_bounce_buffers = 0;
for (port = lance_portlist; *port; port++) {
int ioaddr = *port;
struct resource *r = request_region(ioaddr, LANCE_TOTAL_SIZE,
"lance-probe");
if (r) {
/* Detect the card with minimal I/O reads */
char offset14 = inb(ioaddr + 14);
int card;
for (card = 0; card < NUM_CARDS; ++card)
if (cards[card].id_offset14 == offset14)
break;
if (card < NUM_CARDS) {/*yes, the first byte matches*/
char offset15 = inb(ioaddr + 15);
for (card = 0; card < NUM_CARDS; ++card)
if ((cards[card].id_offset14 == offset14) &&
(cards[card].id_offset15 == offset15))
break;
}
if (card < NUM_CARDS) { /*Signature OK*/
result = lance_probe1(dev, ioaddr, 0, 0);
if (!result) {
struct lance_private *lp = dev->ml_priv;
int ver = lp->chip_version;
r->name = chip_table[ver].name;
return 0;
}
}
release_region(ioaddr, LANCE_TOTAL_SIZE);
}
}
return -ENODEV;
}
#ifndef MODULE
struct net_device * __init lance_probe(int unit)
{
struct net_device *dev = alloc_etherdev(0);
int err;
if (!dev)
return ERR_PTR(-ENODEV);
sprintf(dev->name, "eth%d", unit);
netdev_boot_setup_check(dev);
err = do_lance_probe(dev);
if (err)
goto out;
return dev;
out:
free_netdev(dev);
return ERR_PTR(err);
}
#endif
static const struct net_device_ops lance_netdev_ops = {
.ndo_open = lance_open,
.ndo_start_xmit = lance_start_xmit,
.ndo_stop = lance_close,
.ndo_get_stats = lance_get_stats,
.ndo_set_rx_mode = set_multicast_list,
.ndo_tx_timeout = lance_tx_timeout,
.ndo_change_mtu = eth_change_mtu,
.ndo_set_mac_address = eth_mac_addr,
.ndo_validate_addr = eth_validate_addr,
};
static int __init lance_probe1(struct net_device *dev, int ioaddr, int irq, int options)
{
struct lance_private *lp;
unsigned long dma_channels; /* Mark spuriously-busy DMA channels */
int i, reset_val, lance_version;
const char *chipname;
/* Flags for specific chips or boards. */
unsigned char hpJ2405A = 0; /* HP ISA adaptor */
int hp_builtin = 0; /* HP on-board ethernet. */
static int did_version; /* Already printed version info. */
unsigned long flags;
int err = -ENOMEM;
void __iomem *bios;
/* First we look for special cases.
Check for HP's on-board ethernet by looking for 'HP' in the BIOS.
There are two HP versions, check the BIOS for the configuration port.
This method provided by L. Julliard, Laurent_Julliard@grenoble.hp.com.
*/
bios = ioremap(0xf00f0, 0x14);
if (!bios)
return -ENOMEM;
if (readw(bios + 0x12) == 0x5048) {
static const short ioaddr_table[] = { 0x300, 0x320, 0x340, 0x360};
int hp_port = (readl(bios + 1) & 1) ? 0x499 : 0x99;
/* We can have boards other than the built-in! Verify this is on-board. */
if ((inb(hp_port) & 0xc0) == 0x80 &&
ioaddr_table[inb(hp_port) & 3] == ioaddr)
hp_builtin = hp_port;
}
iounmap(bios);
/* We also recognize the HP Vectra on-board here, but check below. */
hpJ2405A = (inb(ioaddr) == 0x08 && inb(ioaddr+1) == 0x00 &&
inb(ioaddr+2) == 0x09);
/* Reset the LANCE. */
reset_val = inw(ioaddr+LANCE_RESET); /* Reset the LANCE */
/* The Un-Reset needed is only needed for the real NE2100, and will
confuse the HP board. */
if (!hpJ2405A)
outw(reset_val, ioaddr+LANCE_RESET);
outw(0x0000, ioaddr+LANCE_ADDR); /* Switch to window 0 */
if (inw(ioaddr+LANCE_DATA) != 0x0004)
return -ENODEV;
/* Get the version of the chip. */
outw(88, ioaddr+LANCE_ADDR);
if (inw(ioaddr+LANCE_ADDR) != 88) {
lance_version = 0;
} else { /* Good, it's a newer chip. */
int chip_version = inw(ioaddr+LANCE_DATA);
outw(89, ioaddr+LANCE_ADDR);
chip_version |= inw(ioaddr+LANCE_DATA) << 16;
if (lance_debug > 2)
printk(" LANCE chip version is %#x.\n", chip_version);
if ((chip_version & 0xfff) != 0x003)
return -ENODEV;
chip_version = (chip_version >> 12) & 0xffff;
for (lance_version = 1; chip_table[lance_version].id_number; lance_version++) {
if (chip_table[lance_version].id_number == chip_version)
break;
}
}
/* We can't allocate private data from alloc_etherdev() because it must
a ISA DMA-able region. */
chipname = chip_table[lance_version].name;
printk("%s: %s at %#3x, ", dev->name, chipname, ioaddr);
/* There is a 16 byte station address PROM at the base address.
The first six bytes are the station address. */
for (i = 0; i < 6; i++)
dev->dev_addr[i] = inb(ioaddr + i);
printk("%pM", dev->dev_addr);
dev->base_addr = ioaddr;
/* Make certain the data structures used by the LANCE are aligned and DMAble. */
lp = kzalloc(sizeof(*lp), GFP_DMA | GFP_KERNEL);
if(lp==NULL)
return -ENODEV;
if (lance_debug > 6) printk(" (#0x%05lx)", (unsigned long)lp);
dev->ml_priv = lp;
lp->name = chipname;
lp->rx_buffs = (unsigned long)kmalloc(PKT_BUF_SZ*RX_RING_SIZE,
GFP_DMA | GFP_KERNEL);
if (!lp->rx_buffs)
goto out_lp;
if (lance_need_isa_bounce_buffers) {
lp->tx_bounce_buffs = kmalloc(PKT_BUF_SZ*TX_RING_SIZE,
GFP_DMA | GFP_KERNEL);
if (!lp->tx_bounce_buffs)
goto out_rx;
} else
lp->tx_bounce_buffs = NULL;
lp->chip_version = lance_version;
spin_lock_init(&lp->devlock);
lp->init_block.mode = 0x0003; /* Disable Rx and Tx. */
for (i = 0; i < 6; i++)
lp->init_block.phys_addr[i] = dev->dev_addr[i];
lp->init_block.filter[0] = 0x00000000;
lp->init_block.filter[1] = 0x00000000;
lp->init_block.rx_ring = ((u32)isa_virt_to_bus(lp->rx_ring) & 0xffffff) | RX_RING_LEN_BITS;
lp->init_block.tx_ring = ((u32)isa_virt_to_bus(lp->tx_ring) & 0xffffff) | TX_RING_LEN_BITS;
outw(0x0001, ioaddr+LANCE_ADDR);
inw(ioaddr+LANCE_ADDR);
outw((short) (u32) isa_virt_to_bus(&lp->init_block), ioaddr+LANCE_DATA);
outw(0x0002, ioaddr+LANCE_ADDR);
inw(ioaddr+LANCE_ADDR);
outw(((u32)isa_virt_to_bus(&lp->init_block)) >> 16, ioaddr+LANCE_DATA);
outw(0x0000, ioaddr+LANCE_ADDR);
inw(ioaddr+LANCE_ADDR);
if (irq) { /* Set iff PCI card. */
dev->dma = 4; /* Native bus-master, no DMA channel needed. */
dev->irq = irq;
} else if (hp_builtin) {
static const char dma_tbl[4] = {3, 5, 6, 0};
static const char irq_tbl[4] = {3, 4, 5, 9};
unsigned char port_val = inb(hp_builtin);
dev->dma = dma_tbl[(port_val >> 4) & 3];
dev->irq = irq_tbl[(port_val >> 2) & 3];
printk(" HP Vectra IRQ %d DMA %d.\n", dev->irq, dev->dma);
} else if (hpJ2405A) {
static const char dma_tbl[4] = {3, 5, 6, 7};
static const char irq_tbl[8] = {3, 4, 5, 9, 10, 11, 12, 15};
short reset_val = inw(ioaddr+LANCE_RESET);
dev->dma = dma_tbl[(reset_val >> 2) & 3];
dev->irq = irq_tbl[(reset_val >> 4) & 7];
printk(" HP J2405A IRQ %d DMA %d.\n", dev->irq, dev->dma);
} else if (lance_version == PCNET_ISAP) { /* The plug-n-play version. */
short bus_info;
outw(8, ioaddr+LANCE_ADDR);
bus_info = inw(ioaddr+LANCE_BUS_IF);
dev->dma = bus_info & 0x07;
dev->irq = (bus_info >> 4) & 0x0F;
} else {
/* The DMA channel may be passed in PARAM1. */
if (dev->mem_start & 0x07)
dev->dma = dev->mem_start & 0x07;
}
if (dev->dma == 0) {
/* Read the DMA channel status register, so that we can avoid
stuck DMA channels in the DMA detection below. */
dma_channels = ((inb(DMA1_STAT_REG) >> 4) & 0x0f) |
(inb(DMA2_STAT_REG) & 0xf0);
}
err = -ENODEV;
if (dev->irq >= 2)
printk(" assigned IRQ %d", dev->irq);
else if (lance_version != 0) { /* 7990 boards need DMA detection first. */
unsigned long irq_mask;
/* To auto-IRQ we enable the initialization-done and DMA error
interrupts. For ISA boards we get a DMA error, but VLB and PCI
boards will work. */
irq_mask = probe_irq_on();
/* Trigger an initialization just for the interrupt. */
outw(0x0041, ioaddr+LANCE_DATA);
mdelay(20);
dev->irq = probe_irq_off(irq_mask);
if (dev->irq)
printk(", probed IRQ %d", dev->irq);
else {
printk(", failed to detect IRQ line.\n");
goto out_tx;
}
/* Check for the initialization done bit, 0x0100, which means
that we don't need a DMA channel. */
if (inw(ioaddr+LANCE_DATA) & 0x0100)
dev->dma = 4;
}
if (dev->dma == 4) {
printk(", no DMA needed.\n");
} else if (dev->dma) {
if (request_dma(dev->dma, chipname)) {
printk("DMA %d allocation failed.\n", dev->dma);
goto out_tx;
} else
printk(", assigned DMA %d.\n", dev->dma);
} else { /* OK, we have to auto-DMA. */
for (i = 0; i < 4; i++) {
static const char dmas[] = { 5, 6, 7, 3 };
int dma = dmas[i];
int boguscnt;
/* Don't enable a permanently busy DMA channel, or the machine
will hang. */
if (test_bit(dma, &dma_channels))
continue;
outw(0x7f04, ioaddr+LANCE_DATA); /* Clear the memory error bits. */
if (request_dma(dma, chipname))
continue;
flags=claim_dma_lock();
set_dma_mode(dma, DMA_MODE_CASCADE);
enable_dma(dma);
release_dma_lock(flags);
/* Trigger an initialization. */
outw(0x0001, ioaddr+LANCE_DATA);
for (boguscnt = 100; boguscnt > 0; --boguscnt)
if (inw(ioaddr+LANCE_DATA) & 0x0900)
break;
if (inw(ioaddr+LANCE_DATA) & 0x0100) {
dev->dma = dma;
printk(", DMA %d.\n", dev->dma);
break;
} else {
flags=claim_dma_lock();
disable_dma(dma);
release_dma_lock(flags);
free_dma(dma);
}
}
if (i == 4) { /* Failure: bail. */
printk("DMA detection failed.\n");
goto out_tx;
}
}
if (lance_version == 0 && dev->irq == 0) {
/* We may auto-IRQ now that we have a DMA channel. */
/* Trigger an initialization just for the interrupt. */
unsigned long irq_mask;
irq_mask = probe_irq_on();
outw(0x0041, ioaddr+LANCE_DATA);
mdelay(40);
dev->irq = probe_irq_off(irq_mask);
if (dev->irq == 0) {
printk(" Failed to detect the 7990 IRQ line.\n");
goto out_dma;
}
printk(" Auto-IRQ detected IRQ%d.\n", dev->irq);
}
if (chip_table[lp->chip_version].flags & LANCE_ENABLE_AUTOSELECT) {
/* Turn on auto-select of media (10baseT or BNC) so that the user
can watch the LEDs even if the board isn't opened. */
outw(0x0002, ioaddr+LANCE_ADDR);
/* Don't touch 10base2 power bit. */
outw(inw(ioaddr+LANCE_BUS_IF) | 0x0002, ioaddr+LANCE_BUS_IF);
}
if (lance_debug > 0 && did_version++ == 0)
printk(version);
/* The LANCE-specific entries in the device structure. */
dev->netdev_ops = &lance_netdev_ops;
dev->watchdog_timeo = TX_TIMEOUT;
err = register_netdev(dev);
if (err)
goto out_dma;
return 0;
out_dma:
if (dev->dma != 4)
free_dma(dev->dma);
out_tx:
kfree(lp->tx_bounce_buffs);
out_rx:
kfree((void*)lp->rx_buffs);
out_lp:
kfree(lp);
return err;
}
static int
lance_open(struct net_device *dev)
{
struct lance_private *lp = dev->ml_priv;
int ioaddr = dev->base_addr;
int i;
if (dev->irq == 0 ||
request_irq(dev->irq, lance_interrupt, 0, lp->name, dev)) {
return -EAGAIN;
}
/* We used to allocate DMA here, but that was silly.
DMA lines can't be shared! We now permanently allocate them. */
/* Reset the LANCE */
inw(ioaddr+LANCE_RESET);
/* The DMA controller is used as a no-operation slave, "cascade mode". */
if (dev->dma != 4) {
unsigned long flags=claim_dma_lock();
enable_dma(dev->dma);
set_dma_mode(dev->dma, DMA_MODE_CASCADE);
release_dma_lock(flags);
}
/* Un-Reset the LANCE, needed only for the NE2100. */
if (chip_table[lp->chip_version].flags & LANCE_MUST_UNRESET)
outw(0, ioaddr+LANCE_RESET);
if (chip_table[lp->chip_version].flags & LANCE_ENABLE_AUTOSELECT) {
/* This is 79C960-specific: Turn on auto-select of media (AUI, BNC). */
outw(0x0002, ioaddr+LANCE_ADDR);
/* Only touch autoselect bit. */
outw(inw(ioaddr+LANCE_BUS_IF) | 0x0002, ioaddr+LANCE_BUS_IF);
}
if (lance_debug > 1)
printk("%s: lance_open() irq %d dma %d tx/rx rings %#x/%#x init %#x.\n",
dev->name, dev->irq, dev->dma,
(u32) isa_virt_to_bus(lp->tx_ring),
(u32) isa_virt_to_bus(lp->rx_ring),
(u32) isa_virt_to_bus(&lp->init_block));
lance_init_ring(dev, GFP_KERNEL);
/* Re-initialize the LANCE, and start it when done. */
outw(0x0001, ioaddr+LANCE_ADDR);
outw((short) (u32) isa_virt_to_bus(&lp->init_block), ioaddr+LANCE_DATA);
outw(0x0002, ioaddr+LANCE_ADDR);
outw(((u32)isa_virt_to_bus(&lp->init_block)) >> 16, ioaddr+LANCE_DATA);
outw(0x0004, ioaddr+LANCE_ADDR);
outw(0x0915, ioaddr+LANCE_DATA);
outw(0x0000, ioaddr+LANCE_ADDR);
outw(0x0001, ioaddr+LANCE_DATA);
netif_start_queue (dev);
i = 0;
while (i++ < 100)
if (inw(ioaddr+LANCE_DATA) & 0x0100)
break;
/*
* We used to clear the InitDone bit, 0x0100, here but Mark Stockton
* reports that doing so triggers a bug in the '974.
*/
outw(0x0042, ioaddr+LANCE_DATA);
if (lance_debug > 2)
printk("%s: LANCE open after %d ticks, init block %#x csr0 %4.4x.\n",
dev->name, i, (u32) isa_virt_to_bus(&lp->init_block), inw(ioaddr+LANCE_DATA));
return 0; /* Always succeed */
}
/* The LANCE has been halted for one reason or another (busmaster memory
arbitration error, Tx FIFO underflow, driver stopped it to reconfigure,
etc.). Modern LANCE variants always reload their ring-buffer
configuration when restarted, so we must reinitialize our ring
context before restarting. As part of this reinitialization,
find all packets still on the Tx ring and pretend that they had been
sent (in effect, drop the packets on the floor) - the higher-level
protocols will time out and retransmit. It'd be better to shuffle
these skbs to a temp list and then actually re-Tx them after
restarting the chip, but I'm too lazy to do so right now. dplatt@3do.com
*/
static void
lance_purge_ring(struct net_device *dev)
{
struct lance_private *lp = dev->ml_priv;
int i;
/* Free all the skbuffs in the Rx and Tx queues. */
for (i = 0; i < RX_RING_SIZE; i++) {
struct sk_buff *skb = lp->rx_skbuff[i];
lp->rx_skbuff[i] = NULL;
lp->rx_ring[i].base = 0; /* Not owned by LANCE chip. */
if (skb)
dev_kfree_skb_any(skb);
}
for (i = 0; i < TX_RING_SIZE; i++) {
if (lp->tx_skbuff[i]) {
dev_kfree_skb_any(lp->tx_skbuff[i]);
lp->tx_skbuff[i] = NULL;
}
}
}
/* Initialize the LANCE Rx and Tx rings. */
static void
lance_init_ring(struct net_device *dev, gfp_t gfp)
{
struct lance_private *lp = dev->ml_priv;
int i;
lp->cur_rx = lp->cur_tx = 0;
lp->dirty_rx = lp->dirty_tx = 0;
for (i = 0; i < RX_RING_SIZE; i++) {
struct sk_buff *skb;
void *rx_buff;
skb = alloc_skb(PKT_BUF_SZ, GFP_DMA | gfp);
lp->rx_skbuff[i] = skb;
if (skb) {
skb->dev = dev;
rx_buff = skb->data;
} else
rx_buff = kmalloc(PKT_BUF_SZ, GFP_DMA | gfp);
if (rx_buff == NULL)
lp->rx_ring[i].base = 0;
else
lp->rx_ring[i].base = (u32)isa_virt_to_bus(rx_buff) | 0x80000000;
lp->rx_ring[i].buf_length = -PKT_BUF_SZ;
}
/* The Tx buffer address is filled in as needed, but we do need to clear
the upper ownership bit. */
for (i = 0; i < TX_RING_SIZE; i++) {
lp->tx_skbuff[i] = NULL;
lp->tx_ring[i].base = 0;
}
lp->init_block.mode = 0x0000;
for (i = 0; i < 6; i++)
lp->init_block.phys_addr[i] = dev->dev_addr[i];
lp->init_block.filter[0] = 0x00000000;
lp->init_block.filter[1] = 0x00000000;
lp->init_block.rx_ring = ((u32)isa_virt_to_bus(lp->rx_ring) & 0xffffff) | RX_RING_LEN_BITS;
lp->init_block.tx_ring = ((u32)isa_virt_to_bus(lp->tx_ring) & 0xffffff) | TX_RING_LEN_BITS;
}
static void
lance_restart(struct net_device *dev, unsigned int csr0_bits, int must_reinit)
{
struct lance_private *lp = dev->ml_priv;
if (must_reinit ||
(chip_table[lp->chip_version].flags & LANCE_MUST_REINIT_RING)) {
lance_purge_ring(dev);
lance_init_ring(dev, GFP_ATOMIC);
}
outw(0x0000, dev->base_addr + LANCE_ADDR);
outw(csr0_bits, dev->base_addr + LANCE_DATA);
}
static void lance_tx_timeout (struct net_device *dev)
{
struct lance_private *lp = (struct lance_private *) dev->ml_priv;
int ioaddr = dev->base_addr;
outw (0, ioaddr + LANCE_ADDR);
printk ("%s: transmit timed out, status %4.4x, resetting.\n",
dev->name, inw (ioaddr + LANCE_DATA));
outw (0x0004, ioaddr + LANCE_DATA);
dev->stats.tx_errors++;
#ifndef final_version
if (lance_debug > 3) {
int i;
printk (" Ring data dump: dirty_tx %d cur_tx %d%s cur_rx %d.",
lp->dirty_tx, lp->cur_tx, netif_queue_stopped(dev) ? " (full)" : "",
lp->cur_rx);
for (i = 0; i < RX_RING_SIZE; i++)
printk ("%s %08x %04x %04x", i & 0x3 ? "" : "\n ",
lp->rx_ring[i].base, -lp->rx_ring[i].buf_length,
lp->rx_ring[i].msg_length);
for (i = 0; i < TX_RING_SIZE; i++)
printk ("%s %08x %04x %04x", i & 0x3 ? "" : "\n ",
lp->tx_ring[i].base, -lp->tx_ring[i].length,
lp->tx_ring[i].misc);
printk ("\n");
}
#endif
lance_restart (dev, 0x0043, 1);
dev->trans_start = jiffies; /* prevent tx timeout */
netif_wake_queue (dev);
}
static netdev_tx_t lance_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct lance_private *lp = dev->ml_priv;
int ioaddr = dev->base_addr;
int entry;
unsigned long flags;
spin_lock_irqsave(&lp->devlock, flags);
if (lance_debug > 3) {
outw(0x0000, ioaddr+LANCE_ADDR);
printk("%s: lance_start_xmit() called, csr0 %4.4x.\n", dev->name,
inw(ioaddr+LANCE_DATA));
outw(0x0000, ioaddr+LANCE_DATA);
}
/* Fill in a Tx ring entry */
/* Mask to ring buffer boundary. */
entry = lp->cur_tx & TX_RING_MOD_MASK;
/* Caution: the write order is important here, set the base address
with the "ownership" bits last. */
/* The old LANCE chips doesn't automatically pad buffers to min. size. */
if (chip_table[lp->chip_version].flags & LANCE_MUST_PAD) {
if (skb->len < ETH_ZLEN) {
if (skb_padto(skb, ETH_ZLEN))
goto out;
lp->tx_ring[entry].length = -ETH_ZLEN;
}
else
lp->tx_ring[entry].length = -skb->len;
} else
lp->tx_ring[entry].length = -skb->len;
lp->tx_ring[entry].misc = 0x0000;
dev->stats.tx_bytes += skb->len;
/* If any part of this buffer is >16M we must copy it to a low-memory
buffer. */
if ((u32)isa_virt_to_bus(skb->data) + skb->len > 0x01000000) {
if (lance_debug > 5)
printk("%s: bouncing a high-memory packet (%#x).\n",
dev->name, (u32)isa_virt_to_bus(skb->data));
skb_copy_from_linear_data(skb, &lp->tx_bounce_buffs[entry], skb->len);
lp->tx_ring[entry].base =
((u32)isa_virt_to_bus((lp->tx_bounce_buffs + entry)) & 0xffffff) | 0x83000000;
dev_kfree_skb(skb);
} else {
lp->tx_skbuff[entry] = skb;
lp->tx_ring[entry].base = ((u32)isa_virt_to_bus(skb->data) & 0xffffff) | 0x83000000;
}
lp->cur_tx++;
/* Trigger an immediate send poll. */
outw(0x0000, ioaddr+LANCE_ADDR);
outw(0x0048, ioaddr+LANCE_DATA);
if ((lp->cur_tx - lp->dirty_tx) >= TX_RING_SIZE)
netif_stop_queue(dev);
out:
spin_unlock_irqrestore(&lp->devlock, flags);
return NETDEV_TX_OK;
}
/* The LANCE interrupt handler. */
static irqreturn_t lance_interrupt(int irq, void *dev_id)
{
struct net_device *dev = dev_id;
struct lance_private *lp;
int csr0, ioaddr, boguscnt=10;
int must_restart;
ioaddr = dev->base_addr;
lp = dev->ml_priv;
spin_lock (&lp->devlock);
outw(0x00, dev->base_addr + LANCE_ADDR);
while ((csr0 = inw(dev->base_addr + LANCE_DATA)) & 0x8600 &&
--boguscnt >= 0) {
/* Acknowledge all of the current interrupt sources ASAP. */
outw(csr0 & ~0x004f, dev->base_addr + LANCE_DATA);
must_restart = 0;
if (lance_debug > 5)
printk("%s: interrupt csr0=%#2.2x new csr=%#2.2x.\n",
dev->name, csr0, inw(dev->base_addr + LANCE_DATA));
if (csr0 & 0x0400) /* Rx interrupt */
lance_rx(dev);
if (csr0 & 0x0200) { /* Tx-done interrupt */
int dirty_tx = lp->dirty_tx;
while (dirty_tx < lp->cur_tx) {
int entry = dirty_tx & TX_RING_MOD_MASK;
int status = lp->tx_ring[entry].base;
if (status < 0)
break; /* It still hasn't been Txed */
lp->tx_ring[entry].base = 0;
if (status & 0x40000000) {
/* There was an major error, log it. */
int err_status = lp->tx_ring[entry].misc;
dev->stats.tx_errors++;
if (err_status & 0x0400)
dev->stats.tx_aborted_errors++;
if (err_status & 0x0800)
dev->stats.tx_carrier_errors++;
if (err_status & 0x1000)
dev->stats.tx_window_errors++;
if (err_status & 0x4000) {
/* Ackk! On FIFO errors the Tx unit is turned off! */
dev->stats.tx_fifo_errors++;
/* Remove this verbosity later! */
printk("%s: Tx FIFO error! Status %4.4x.\n",
dev->name, csr0);
/* Restart the chip. */
must_restart = 1;
}
} else {
if (status & 0x18000000)
dev->stats.collisions++;
dev->stats.tx_packets++;
}
/* We must free the original skb if it's not a data-only copy
in the bounce buffer. */
if (lp->tx_skbuff[entry]) {
dev_kfree_skb_irq(lp->tx_skbuff[entry]);
lp->tx_skbuff[entry] = NULL;
}
dirty_tx++;
}
#ifndef final_version
if (lp->cur_tx - dirty_tx >= TX_RING_SIZE) {
printk("out-of-sync dirty pointer, %d vs. %d, full=%s.\n",
dirty_tx, lp->cur_tx,
netif_queue_stopped(dev) ? "yes" : "no");
dirty_tx += TX_RING_SIZE;
}
#endif
/* if the ring is no longer full, accept more packets */
if (netif_queue_stopped(dev) &&
dirty_tx > lp->cur_tx - TX_RING_SIZE + 2)
netif_wake_queue (dev);
lp->dirty_tx = dirty_tx;
}
/* Log misc errors. */
if (csr0 & 0x4000)
dev->stats.tx_errors++; /* Tx babble. */
if (csr0 & 0x1000)
dev->stats.rx_errors++; /* Missed a Rx frame. */
if (csr0 & 0x0800) {
printk("%s: Bus master arbitration failure, status %4.4x.\n",
dev->name, csr0);
/* Restart the chip. */
must_restart = 1;
}
if (must_restart) {
/* stop the chip to clear the error condition, then restart */
outw(0x0000, dev->base_addr + LANCE_ADDR);
outw(0x0004, dev->base_addr + LANCE_DATA);
lance_restart(dev, 0x0002, 0);
}
}
/* Clear any other interrupt, and set interrupt enable. */
outw(0x0000, dev->base_addr + LANCE_ADDR);
outw(0x7940, dev->base_addr + LANCE_DATA);
if (lance_debug > 4)
printk("%s: exiting interrupt, csr%d=%#4.4x.\n",
dev->name, inw(ioaddr + LANCE_ADDR),
inw(dev->base_addr + LANCE_DATA));
spin_unlock (&lp->devlock);
return IRQ_HANDLED;
}
static int
lance_rx(struct net_device *dev)
{
struct lance_private *lp = dev->ml_priv;
int entry = lp->cur_rx & RX_RING_MOD_MASK;
int i;
/* If we own the next entry, it's a new packet. Send it up. */
while (lp->rx_ring[entry].base >= 0) {
int status = lp->rx_ring[entry].base >> 24;
if (status != 0x03) { /* There was an error. */
/* There is a tricky error noted by John Murphy,
<murf@perftech.com> to Russ Nelson: Even with full-sized
buffers it's possible for a jabber packet to use two
buffers, with only the last correctly noting the error. */
if (status & 0x01) /* Only count a general error at the */
dev->stats.rx_errors++; /* end of a packet.*/
if (status & 0x20)
dev->stats.rx_frame_errors++;
if (status & 0x10)
dev->stats.rx_over_errors++;
if (status & 0x08)
dev->stats.rx_crc_errors++;
if (status & 0x04)
dev->stats.rx_fifo_errors++;
lp->rx_ring[entry].base &= 0x03ffffff;
}
else
{
/* Malloc up new buffer, compatible with net3. */
short pkt_len = (lp->rx_ring[entry].msg_length & 0xfff)-4;
struct sk_buff *skb;
if(pkt_len<60)
{
printk("%s: Runt packet!\n",dev->name);
dev->stats.rx_errors++;
}
else
{
skb = dev_alloc_skb(pkt_len+2);
if (skb == NULL)
{
printk("%s: Memory squeeze, deferring packet.\n", dev->name);
for (i=0; i < RX_RING_SIZE; i++)
if (lp->rx_ring[(entry+i) & RX_RING_MOD_MASK].base < 0)
break;
if (i > RX_RING_SIZE -2)
{
dev->stats.rx_dropped++;
lp->rx_ring[entry].base |= 0x80000000;
lp->cur_rx++;
}
break;
}
skb_reserve(skb,2); /* 16 byte align */
skb_put(skb,pkt_len); /* Make room */
skb_copy_to_linear_data(skb,
(unsigned char *)isa_bus_to_virt((lp->rx_ring[entry].base & 0x00ffffff)),
pkt_len);
skb->protocol=eth_type_trans(skb,dev);
netif_rx(skb);
dev->stats.rx_packets++;
dev->stats.rx_bytes += pkt_len;
}
}
/* The docs say that the buffer length isn't touched, but Andrew Boyd
of QNX reports that some revs of the 79C965 clear it. */
lp->rx_ring[entry].buf_length = -PKT_BUF_SZ;
lp->rx_ring[entry].base |= 0x80000000;
entry = (++lp->cur_rx) & RX_RING_MOD_MASK;
}
/* We should check that at least two ring entries are free. If not,
we should free one and mark stats->rx_dropped++. */
return 0;
}
static int
lance_close(struct net_device *dev)
{
int ioaddr = dev->base_addr;
struct lance_private *lp = dev->ml_priv;
netif_stop_queue (dev);
if (chip_table[lp->chip_version].flags & LANCE_HAS_MISSED_FRAME) {
outw(112, ioaddr+LANCE_ADDR);
dev->stats.rx_missed_errors = inw(ioaddr+LANCE_DATA);
}
outw(0, ioaddr+LANCE_ADDR);
if (lance_debug > 1)
printk("%s: Shutting down ethercard, status was %2.2x.\n",
dev->name, inw(ioaddr+LANCE_DATA));
/* We stop the LANCE here -- it occasionally polls
memory if we don't. */
outw(0x0004, ioaddr+LANCE_DATA);
if (dev->dma != 4)
{
unsigned long flags=claim_dma_lock();
disable_dma(dev->dma);
release_dma_lock(flags);
}
free_irq(dev->irq, dev);
lance_purge_ring(dev);
return 0;
}
static struct net_device_stats *lance_get_stats(struct net_device *dev)
{
struct lance_private *lp = dev->ml_priv;
if (chip_table[lp->chip_version].flags & LANCE_HAS_MISSED_FRAME) {
short ioaddr = dev->base_addr;
short saved_addr;
unsigned long flags;
spin_lock_irqsave(&lp->devlock, flags);
saved_addr = inw(ioaddr+LANCE_ADDR);
outw(112, ioaddr+LANCE_ADDR);
dev->stats.rx_missed_errors = inw(ioaddr+LANCE_DATA);
outw(saved_addr, ioaddr+LANCE_ADDR);
spin_unlock_irqrestore(&lp->devlock, flags);
}
return &dev->stats;
}
/* Set or clear the multicast filter for this adaptor.
*/
static void set_multicast_list(struct net_device *dev)
{
short ioaddr = dev->base_addr;
outw(0, ioaddr+LANCE_ADDR);
outw(0x0004, ioaddr+LANCE_DATA); /* Temporarily stop the lance. */
if (dev->flags&IFF_PROMISC) {
outw(15, ioaddr+LANCE_ADDR);
outw(0x8000, ioaddr+LANCE_DATA); /* Set promiscuous mode */
} else {
short multicast_table[4];
int i;
int num_addrs=netdev_mc_count(dev);
if(dev->flags&IFF_ALLMULTI)
num_addrs=1;
/* FIXIT: We don't use the multicast table, but rely on upper-layer filtering. */
memset(multicast_table, (num_addrs == 0) ? 0 : -1, sizeof(multicast_table));
for (i = 0; i < 4; i++) {
outw(8 + i, ioaddr+LANCE_ADDR);
outw(multicast_table[i], ioaddr+LANCE_DATA);
}
outw(15, ioaddr+LANCE_ADDR);
outw(0x0000, ioaddr+LANCE_DATA); /* Unset promiscuous mode */
}
lance_restart(dev, 0x0142, 0); /* Resume normal operation */
}
| gpl-2.0 |
crdroid-devices/android_kernel_lge_hammerhead | arch/mips/vr41xx/common/icu.c | 7679 | 17431 | /*
* icu.c, Interrupt Control Unit routines for the NEC VR4100 series.
*
* Copyright (C) 2001-2002 MontaVista Software Inc.
* Author: Yoichi Yuasa <source@mvista.com>
* Copyright (C) 2003-2006 Yoichi Yuasa <yuasa@linux-mips.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
*/
/*
* Changes:
* MontaVista Software Inc. <source@mvista.com>
* - New creation, NEC VR4122 and VR4131 are supported.
* - Added support for NEC VR4111 and VR4121.
*
* Yoichi Yuasa <yuasa@linux-mips.org>
* - Coped with INTASSIGN of NEC VR4133.
*/
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/ioport.h>
#include <linux/irq.h>
#include <linux/module.h>
#include <linux/smp.h>
#include <linux/types.h>
#include <asm/cpu.h>
#include <asm/io.h>
#include <asm/vr41xx/irq.h>
#include <asm/vr41xx/vr41xx.h>
static void __iomem *icu1_base;
static void __iomem *icu2_base;
static unsigned char sysint1_assign[16] = {
0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
static unsigned char sysint2_assign[16] = {
2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
#define ICU1_TYPE1_BASE 0x0b000080UL
#define ICU2_TYPE1_BASE 0x0b000200UL
#define ICU1_TYPE2_BASE 0x0f000080UL
#define ICU2_TYPE2_BASE 0x0f0000a0UL
#define ICU1_SIZE 0x20
#define ICU2_SIZE 0x1c
#define SYSINT1REG 0x00
#define PIUINTREG 0x02
#define INTASSIGN0 0x04
#define INTASSIGN1 0x06
#define GIUINTLREG 0x08
#define DSIUINTREG 0x0a
#define MSYSINT1REG 0x0c
#define MPIUINTREG 0x0e
#define MAIUINTREG 0x10
#define MKIUINTREG 0x12
#define MMACINTREG 0x12
#define MGIUINTLREG 0x14
#define MDSIUINTREG 0x16
#define NMIREG 0x18
#define SOFTREG 0x1a
#define INTASSIGN2 0x1c
#define INTASSIGN3 0x1e
#define SYSINT2REG 0x00
#define GIUINTHREG 0x02
#define FIRINTREG 0x04
#define MSYSINT2REG 0x06
#define MGIUINTHREG 0x08
#define MFIRINTREG 0x0a
#define PCIINTREG 0x0c
#define PCIINT0 0x0001
#define SCUINTREG 0x0e
#define SCUINT0 0x0001
#define CSIINTREG 0x10
#define MPCIINTREG 0x12
#define MSCUINTREG 0x14
#define MCSIINTREG 0x16
#define BCUINTREG 0x18
#define BCUINTR 0x0001
#define MBCUINTREG 0x1a
#define SYSINT1_IRQ_TO_PIN(x) ((x) - SYSINT1_IRQ_BASE) /* Pin 0-15 */
#define SYSINT2_IRQ_TO_PIN(x) ((x) - SYSINT2_IRQ_BASE) /* Pin 0-15 */
#define INT_TO_IRQ(x) ((x) + 2) /* Int0-4 -> IRQ2-6 */
#define icu1_read(offset) readw(icu1_base + (offset))
#define icu1_write(offset, value) writew((value), icu1_base + (offset))
#define icu2_read(offset) readw(icu2_base + (offset))
#define icu2_write(offset, value) writew((value), icu2_base + (offset))
#define INTASSIGN_MAX 4
#define INTASSIGN_MASK 0x0007
static inline uint16_t icu1_set(uint8_t offset, uint16_t set)
{
uint16_t data;
data = icu1_read(offset);
data |= set;
icu1_write(offset, data);
return data;
}
static inline uint16_t icu1_clear(uint8_t offset, uint16_t clear)
{
uint16_t data;
data = icu1_read(offset);
data &= ~clear;
icu1_write(offset, data);
return data;
}
static inline uint16_t icu2_set(uint8_t offset, uint16_t set)
{
uint16_t data;
data = icu2_read(offset);
data |= set;
icu2_write(offset, data);
return data;
}
static inline uint16_t icu2_clear(uint8_t offset, uint16_t clear)
{
uint16_t data;
data = icu2_read(offset);
data &= ~clear;
icu2_write(offset, data);
return data;
}
void vr41xx_enable_piuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(PIU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4111 ||
current_cpu_type() == CPU_VR4121) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_set(MPIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_piuint);
void vr41xx_disable_piuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(PIU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4111 ||
current_cpu_type() == CPU_VR4121) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_clear(MPIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_piuint);
void vr41xx_enable_aiuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(AIU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4111 ||
current_cpu_type() == CPU_VR4121) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_set(MAIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_aiuint);
void vr41xx_disable_aiuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(AIU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4111 ||
current_cpu_type() == CPU_VR4121) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_clear(MAIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_aiuint);
void vr41xx_enable_kiuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(KIU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4111 ||
current_cpu_type() == CPU_VR4121) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_set(MKIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_kiuint);
void vr41xx_disable_kiuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(KIU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4111 ||
current_cpu_type() == CPU_VR4121) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_clear(MKIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_kiuint);
void vr41xx_enable_macint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(ETHERNET_IRQ);
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_set(MMACINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL(vr41xx_enable_macint);
void vr41xx_disable_macint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(ETHERNET_IRQ);
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_clear(MMACINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL(vr41xx_disable_macint);
void vr41xx_enable_dsiuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(DSIU_IRQ);
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_set(MDSIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL(vr41xx_enable_dsiuint);
void vr41xx_disable_dsiuint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(DSIU_IRQ);
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
icu1_clear(MDSIUINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL(vr41xx_disable_dsiuint);
void vr41xx_enable_firint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(FIR_IRQ);
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_set(MFIRINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL(vr41xx_enable_firint);
void vr41xx_disable_firint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(FIR_IRQ);
unsigned long flags;
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_clear(MFIRINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
EXPORT_SYMBOL(vr41xx_disable_firint);
void vr41xx_enable_pciint(void)
{
struct irq_desc *desc = irq_to_desc(PCI_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_write(MPCIINTREG, PCIINT0);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_pciint);
void vr41xx_disable_pciint(void)
{
struct irq_desc *desc = irq_to_desc(PCI_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_write(MPCIINTREG, 0);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_pciint);
void vr41xx_enable_scuint(void)
{
struct irq_desc *desc = irq_to_desc(SCU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_write(MSCUINTREG, SCUINT0);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_scuint);
void vr41xx_disable_scuint(void)
{
struct irq_desc *desc = irq_to_desc(SCU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_write(MSCUINTREG, 0);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_scuint);
void vr41xx_enable_csiint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(CSI_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_set(MCSIINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_csiint);
void vr41xx_disable_csiint(uint16_t mask)
{
struct irq_desc *desc = irq_to_desc(CSI_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_clear(MCSIINTREG, mask);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_csiint);
void vr41xx_enable_bcuint(void)
{
struct irq_desc *desc = irq_to_desc(BCU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_write(MBCUINTREG, BCUINTR);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_enable_bcuint);
void vr41xx_disable_bcuint(void)
{
struct irq_desc *desc = irq_to_desc(BCU_IRQ);
unsigned long flags;
if (current_cpu_type() == CPU_VR4122 ||
current_cpu_type() == CPU_VR4131 ||
current_cpu_type() == CPU_VR4133) {
raw_spin_lock_irqsave(&desc->lock, flags);
icu2_write(MBCUINTREG, 0);
raw_spin_unlock_irqrestore(&desc->lock, flags);
}
}
EXPORT_SYMBOL(vr41xx_disable_bcuint);
static void disable_sysint1_irq(struct irq_data *d)
{
icu1_clear(MSYSINT1REG, 1 << SYSINT1_IRQ_TO_PIN(d->irq));
}
static void enable_sysint1_irq(struct irq_data *d)
{
icu1_set(MSYSINT1REG, 1 << SYSINT1_IRQ_TO_PIN(d->irq));
}
static struct irq_chip sysint1_irq_type = {
.name = "SYSINT1",
.irq_mask = disable_sysint1_irq,
.irq_unmask = enable_sysint1_irq,
};
static void disable_sysint2_irq(struct irq_data *d)
{
icu2_clear(MSYSINT2REG, 1 << SYSINT2_IRQ_TO_PIN(d->irq));
}
static void enable_sysint2_irq(struct irq_data *d)
{
icu2_set(MSYSINT2REG, 1 << SYSINT2_IRQ_TO_PIN(d->irq));
}
static struct irq_chip sysint2_irq_type = {
.name = "SYSINT2",
.irq_mask = disable_sysint2_irq,
.irq_unmask = enable_sysint2_irq,
};
static inline int set_sysint1_assign(unsigned int irq, unsigned char assign)
{
struct irq_desc *desc = irq_to_desc(irq);
uint16_t intassign0, intassign1;
unsigned int pin;
pin = SYSINT1_IRQ_TO_PIN(irq);
raw_spin_lock_irq(&desc->lock);
intassign0 = icu1_read(INTASSIGN0);
intassign1 = icu1_read(INTASSIGN1);
switch (pin) {
case 0:
intassign0 &= ~INTASSIGN_MASK;
intassign0 |= (uint16_t)assign;
break;
case 1:
intassign0 &= ~(INTASSIGN_MASK << 3);
intassign0 |= (uint16_t)assign << 3;
break;
case 2:
intassign0 &= ~(INTASSIGN_MASK << 6);
intassign0 |= (uint16_t)assign << 6;
break;
case 3:
intassign0 &= ~(INTASSIGN_MASK << 9);
intassign0 |= (uint16_t)assign << 9;
break;
case 8:
intassign0 &= ~(INTASSIGN_MASK << 12);
intassign0 |= (uint16_t)assign << 12;
break;
case 9:
intassign1 &= ~INTASSIGN_MASK;
intassign1 |= (uint16_t)assign;
break;
case 11:
intassign1 &= ~(INTASSIGN_MASK << 6);
intassign1 |= (uint16_t)assign << 6;
break;
case 12:
intassign1 &= ~(INTASSIGN_MASK << 9);
intassign1 |= (uint16_t)assign << 9;
break;
default:
raw_spin_unlock_irq(&desc->lock);
return -EINVAL;
}
sysint1_assign[pin] = assign;
icu1_write(INTASSIGN0, intassign0);
icu1_write(INTASSIGN1, intassign1);
raw_spin_unlock_irq(&desc->lock);
return 0;
}
static inline int set_sysint2_assign(unsigned int irq, unsigned char assign)
{
struct irq_desc *desc = irq_to_desc(irq);
uint16_t intassign2, intassign3;
unsigned int pin;
pin = SYSINT2_IRQ_TO_PIN(irq);
raw_spin_lock_irq(&desc->lock);
intassign2 = icu1_read(INTASSIGN2);
intassign3 = icu1_read(INTASSIGN3);
switch (pin) {
case 0:
intassign2 &= ~INTASSIGN_MASK;
intassign2 |= (uint16_t)assign;
break;
case 1:
intassign2 &= ~(INTASSIGN_MASK << 3);
intassign2 |= (uint16_t)assign << 3;
break;
case 3:
intassign2 &= ~(INTASSIGN_MASK << 6);
intassign2 |= (uint16_t)assign << 6;
break;
case 4:
intassign2 &= ~(INTASSIGN_MASK << 9);
intassign2 |= (uint16_t)assign << 9;
break;
case 5:
intassign2 &= ~(INTASSIGN_MASK << 12);
intassign2 |= (uint16_t)assign << 12;
break;
case 6:
intassign3 &= ~INTASSIGN_MASK;
intassign3 |= (uint16_t)assign;
break;
case 7:
intassign3 &= ~(INTASSIGN_MASK << 3);
intassign3 |= (uint16_t)assign << 3;
break;
case 8:
intassign3 &= ~(INTASSIGN_MASK << 6);
intassign3 |= (uint16_t)assign << 6;
break;
case 9:
intassign3 &= ~(INTASSIGN_MASK << 9);
intassign3 |= (uint16_t)assign << 9;
break;
case 10:
intassign3 &= ~(INTASSIGN_MASK << 12);
intassign3 |= (uint16_t)assign << 12;
break;
default:
raw_spin_unlock_irq(&desc->lock);
return -EINVAL;
}
sysint2_assign[pin] = assign;
icu1_write(INTASSIGN2, intassign2);
icu1_write(INTASSIGN3, intassign3);
raw_spin_unlock_irq(&desc->lock);
return 0;
}
int vr41xx_set_intassign(unsigned int irq, unsigned char intassign)
{
int retval = -EINVAL;
if (current_cpu_type() != CPU_VR4133)
return -EINVAL;
if (intassign > INTASSIGN_MAX)
return -EINVAL;
if (irq >= SYSINT1_IRQ_BASE && irq <= SYSINT1_IRQ_LAST)
retval = set_sysint1_assign(irq, intassign);
else if (irq >= SYSINT2_IRQ_BASE && irq <= SYSINT2_IRQ_LAST)
retval = set_sysint2_assign(irq, intassign);
return retval;
}
EXPORT_SYMBOL(vr41xx_set_intassign);
static int icu_get_irq(unsigned int irq)
{
uint16_t pend1, pend2;
uint16_t mask1, mask2;
int i;
pend1 = icu1_read(SYSINT1REG);
mask1 = icu1_read(MSYSINT1REG);
pend2 = icu2_read(SYSINT2REG);
mask2 = icu2_read(MSYSINT2REG);
mask1 &= pend1;
mask2 &= pend2;
if (mask1) {
for (i = 0; i < 16; i++) {
if (irq == INT_TO_IRQ(sysint1_assign[i]) && (mask1 & (1 << i)))
return SYSINT1_IRQ(i);
}
}
if (mask2) {
for (i = 0; i < 16; i++) {
if (irq == INT_TO_IRQ(sysint2_assign[i]) && (mask2 & (1 << i)))
return SYSINT2_IRQ(i);
}
}
printk(KERN_ERR "spurious ICU interrupt: %04x,%04x\n", pend1, pend2);
atomic_inc(&irq_err_count);
return -1;
}
static int __init vr41xx_icu_init(void)
{
unsigned long icu1_start, icu2_start;
int i;
switch (current_cpu_type()) {
case CPU_VR4111:
case CPU_VR4121:
icu1_start = ICU1_TYPE1_BASE;
icu2_start = ICU2_TYPE1_BASE;
break;
case CPU_VR4122:
case CPU_VR4131:
case CPU_VR4133:
icu1_start = ICU1_TYPE2_BASE;
icu2_start = ICU2_TYPE2_BASE;
break;
default:
printk(KERN_ERR "ICU: Unexpected CPU of NEC VR4100 series\n");
return -ENODEV;
}
if (request_mem_region(icu1_start, ICU1_SIZE, "ICU") == NULL)
return -EBUSY;
if (request_mem_region(icu2_start, ICU2_SIZE, "ICU") == NULL) {
release_mem_region(icu1_start, ICU1_SIZE);
return -EBUSY;
}
icu1_base = ioremap(icu1_start, ICU1_SIZE);
if (icu1_base == NULL) {
release_mem_region(icu1_start, ICU1_SIZE);
release_mem_region(icu2_start, ICU2_SIZE);
return -ENOMEM;
}
icu2_base = ioremap(icu2_start, ICU2_SIZE);
if (icu2_base == NULL) {
iounmap(icu1_base);
release_mem_region(icu1_start, ICU1_SIZE);
release_mem_region(icu2_start, ICU2_SIZE);
return -ENOMEM;
}
icu1_write(MSYSINT1REG, 0);
icu1_write(MGIUINTLREG, 0xffff);
icu2_write(MSYSINT2REG, 0);
icu2_write(MGIUINTHREG, 0xffff);
for (i = SYSINT1_IRQ_BASE; i <= SYSINT1_IRQ_LAST; i++)
irq_set_chip_and_handler(i, &sysint1_irq_type,
handle_level_irq);
for (i = SYSINT2_IRQ_BASE; i <= SYSINT2_IRQ_LAST; i++)
irq_set_chip_and_handler(i, &sysint2_irq_type,
handle_level_irq);
cascade_irq(INT0_IRQ, icu_get_irq);
cascade_irq(INT1_IRQ, icu_get_irq);
cascade_irq(INT2_IRQ, icu_get_irq);
cascade_irq(INT3_IRQ, icu_get_irq);
cascade_irq(INT4_IRQ, icu_get_irq);
return 0;
}
core_initcall(vr41xx_icu_init);
| gpl-2.0 |
MSM8226-Samsung/android_kernel_samsung_ms01lte | arch/mips/kernel/irq_txx9.c | 7679 | 4881 | /*
* Based on linux/arch/mips/jmr3927/rbhma3100/irq.c,
* linux/arch/mips/tx4927/common/tx4927_irq.c,
* linux/arch/mips/tx4938/common/irq.c
*
* Copyright 2001, 2003-2005 MontaVista Software Inc.
* Author: MontaVista Software, Inc.
* ahennessy@mvista.com
* source@mvista.com
* Copyright (C) 2000-2001 Toshiba Corporation
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/types.h>
#include <linux/irq.h>
#include <asm/txx9irq.h>
struct txx9_irc_reg {
u32 cer;
u32 cr[2];
u32 unused0;
u32 ilr[8];
u32 unused1[4];
u32 imr;
u32 unused2[7];
u32 scr;
u32 unused3[7];
u32 ssr;
u32 unused4[7];
u32 csr;
};
/* IRCER : Int. Control Enable */
#define TXx9_IRCER_ICE 0x00000001
/* IRCR : Int. Control */
#define TXx9_IRCR_LOW 0x00000000
#define TXx9_IRCR_HIGH 0x00000001
#define TXx9_IRCR_DOWN 0x00000002
#define TXx9_IRCR_UP 0x00000003
#define TXx9_IRCR_EDGE(cr) ((cr) & 0x00000002)
/* IRSCR : Int. Status Control */
#define TXx9_IRSCR_EIClrE 0x00000100
#define TXx9_IRSCR_EIClr_MASK 0x0000000f
/* IRCSR : Int. Current Status */
#define TXx9_IRCSR_IF 0x00010000
#define TXx9_IRCSR_ILV_MASK 0x00000700
#define TXx9_IRCSR_IVL_MASK 0x0000001f
#define irc_dlevel 0
#define irc_elevel 1
static struct txx9_irc_reg __iomem *txx9_ircptr __read_mostly;
static struct {
unsigned char level;
unsigned char mode;
} txx9irq[TXx9_MAX_IR] __read_mostly;
static void txx9_irq_unmask(struct irq_data *d)
{
unsigned int irq_nr = d->irq - TXX9_IRQ_BASE;
u32 __iomem *ilrp = &txx9_ircptr->ilr[(irq_nr % 16 ) / 2];
int ofs = irq_nr / 16 * 16 + (irq_nr & 1) * 8;
__raw_writel((__raw_readl(ilrp) & ~(0xff << ofs))
| (txx9irq[irq_nr].level << ofs),
ilrp);
#ifdef CONFIG_CPU_TX39XX
/* update IRCSR */
__raw_writel(0, &txx9_ircptr->imr);
__raw_writel(irc_elevel, &txx9_ircptr->imr);
#endif
}
static inline void txx9_irq_mask(struct irq_data *d)
{
unsigned int irq_nr = d->irq - TXX9_IRQ_BASE;
u32 __iomem *ilrp = &txx9_ircptr->ilr[(irq_nr % 16) / 2];
int ofs = irq_nr / 16 * 16 + (irq_nr & 1) * 8;
__raw_writel((__raw_readl(ilrp) & ~(0xff << ofs))
| (irc_dlevel << ofs),
ilrp);
#ifdef CONFIG_CPU_TX39XX
/* update IRCSR */
__raw_writel(0, &txx9_ircptr->imr);
__raw_writel(irc_elevel, &txx9_ircptr->imr);
/* flush write buffer */
__raw_readl(&txx9_ircptr->ssr);
#else
mmiowb();
#endif
}
static void txx9_irq_mask_ack(struct irq_data *d)
{
unsigned int irq_nr = d->irq - TXX9_IRQ_BASE;
txx9_irq_mask(d);
/* clear edge detection */
if (unlikely(TXx9_IRCR_EDGE(txx9irq[irq_nr].mode)))
__raw_writel(TXx9_IRSCR_EIClrE | irq_nr, &txx9_ircptr->scr);
}
static int txx9_irq_set_type(struct irq_data *d, unsigned int flow_type)
{
unsigned int irq_nr = d->irq - TXX9_IRQ_BASE;
u32 cr;
u32 __iomem *crp;
int ofs;
int mode;
if (flow_type & IRQF_TRIGGER_PROBE)
return 0;
switch (flow_type & IRQF_TRIGGER_MASK) {
case IRQF_TRIGGER_RISING: mode = TXx9_IRCR_UP; break;
case IRQF_TRIGGER_FALLING: mode = TXx9_IRCR_DOWN; break;
case IRQF_TRIGGER_HIGH: mode = TXx9_IRCR_HIGH; break;
case IRQF_TRIGGER_LOW: mode = TXx9_IRCR_LOW; break;
default:
return -EINVAL;
}
crp = &txx9_ircptr->cr[(unsigned int)irq_nr / 8];
cr = __raw_readl(crp);
ofs = (irq_nr & (8 - 1)) * 2;
cr &= ~(0x3 << ofs);
cr |= (mode & 0x3) << ofs;
__raw_writel(cr, crp);
txx9irq[irq_nr].mode = mode;
return 0;
}
static struct irq_chip txx9_irq_chip = {
.name = "TXX9",
.irq_ack = txx9_irq_mask_ack,
.irq_mask = txx9_irq_mask,
.irq_mask_ack = txx9_irq_mask_ack,
.irq_unmask = txx9_irq_unmask,
.irq_set_type = txx9_irq_set_type,
};
void __init txx9_irq_init(unsigned long baseaddr)
{
int i;
txx9_ircptr = ioremap(baseaddr, sizeof(struct txx9_irc_reg));
for (i = 0; i < TXx9_MAX_IR; i++) {
txx9irq[i].level = 4; /* middle level */
txx9irq[i].mode = TXx9_IRCR_LOW;
irq_set_chip_and_handler(TXX9_IRQ_BASE + i, &txx9_irq_chip,
handle_level_irq);
}
/* mask all IRC interrupts */
__raw_writel(0, &txx9_ircptr->imr);
for (i = 0; i < 8; i++)
__raw_writel(0, &txx9_ircptr->ilr[i]);
/* setup IRC interrupt mode (Low Active) */
for (i = 0; i < 2; i++)
__raw_writel(0, &txx9_ircptr->cr[i]);
/* enable interrupt control */
__raw_writel(TXx9_IRCER_ICE, &txx9_ircptr->cer);
__raw_writel(irc_elevel, &txx9_ircptr->imr);
}
int __init txx9_irq_set_pri(int irc_irq, int new_pri)
{
int old_pri;
if ((unsigned int)irc_irq >= TXx9_MAX_IR)
return 0;
old_pri = txx9irq[irc_irq].level;
txx9irq[irc_irq].level = new_pri;
return old_pri;
}
int txx9_irq(void)
{
u32 csr = __raw_readl(&txx9_ircptr->csr);
if (likely(!(csr & TXx9_IRCSR_IF)))
return TXX9_IRQ_BASE + (csr & (TXx9_MAX_IR - 1));
return -1;
}
| gpl-2.0 |
CyanHacker-Lollipop/kernel_htc_msm8974 | arch/mips/txx9/rbtx4927/irq.c | 7679 | 6075 | /*
* Toshiba RBTX4927 specific interrupt handlers
*
* Author: MontaVista Software, Inc.
* source@mvista.com
*
* Copyright 2001-2002 MontaVista Software Inc.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* 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.
*/
/*
* I8259A_IRQ_BASE+00
* I8259A_IRQ_BASE+01 PS2/Keyboard
* I8259A_IRQ_BASE+02 Cascade RBTX4927-ISA (irqs 8-15)
* I8259A_IRQ_BASE+03
* I8259A_IRQ_BASE+04
* I8259A_IRQ_BASE+05
* I8259A_IRQ_BASE+06
* I8259A_IRQ_BASE+07
* I8259A_IRQ_BASE+08
* I8259A_IRQ_BASE+09
* I8259A_IRQ_BASE+10
* I8259A_IRQ_BASE+11
* I8259A_IRQ_BASE+12 PS2/Mouse (not supported at this time)
* I8259A_IRQ_BASE+13
* I8259A_IRQ_BASE+14 IDE
* I8259A_IRQ_BASE+15
*
* MIPS_CPU_IRQ_BASE+00 Software 0
* MIPS_CPU_IRQ_BASE+01 Software 1
* MIPS_CPU_IRQ_BASE+02 Cascade TX4927-CP0
* MIPS_CPU_IRQ_BASE+03 Multiplexed -- do not use
* MIPS_CPU_IRQ_BASE+04 Multiplexed -- do not use
* MIPS_CPU_IRQ_BASE+05 Multiplexed -- do not use
* MIPS_CPU_IRQ_BASE+06 Multiplexed -- do not use
* MIPS_CPU_IRQ_BASE+07 CPU TIMER
*
* TXX9_IRQ_BASE+00
* TXX9_IRQ_BASE+01
* TXX9_IRQ_BASE+02
* TXX9_IRQ_BASE+03 Cascade RBTX4927-IOC
* TXX9_IRQ_BASE+04
* TXX9_IRQ_BASE+05 RBTX4927 RTL-8019AS ethernet
* TXX9_IRQ_BASE+06
* TXX9_IRQ_BASE+07
* TXX9_IRQ_BASE+08 TX4927 SerialIO Channel 0
* TXX9_IRQ_BASE+09 TX4927 SerialIO Channel 1
* TXX9_IRQ_BASE+10
* TXX9_IRQ_BASE+11
* TXX9_IRQ_BASE+12
* TXX9_IRQ_BASE+13
* TXX9_IRQ_BASE+14
* TXX9_IRQ_BASE+15
* TXX9_IRQ_BASE+16 TX4927 PCI PCI-C
* TXX9_IRQ_BASE+17
* TXX9_IRQ_BASE+18
* TXX9_IRQ_BASE+19
* TXX9_IRQ_BASE+20
* TXX9_IRQ_BASE+21
* TXX9_IRQ_BASE+22 TX4927 PCI PCI-ERR
* TXX9_IRQ_BASE+23 TX4927 PCI PCI-PMA (not used)
* TXX9_IRQ_BASE+24
* TXX9_IRQ_BASE+25
* TXX9_IRQ_BASE+26
* TXX9_IRQ_BASE+27
* TXX9_IRQ_BASE+28
* TXX9_IRQ_BASE+29
* TXX9_IRQ_BASE+30
* TXX9_IRQ_BASE+31
*
* RBTX4927_IRQ_IOC+00 FPCIB0 PCI-D (SouthBridge)
* RBTX4927_IRQ_IOC+01 FPCIB0 PCI-C (SouthBridge)
* RBTX4927_IRQ_IOC+02 FPCIB0 PCI-B (SouthBridge/IDE/pin=1,INTR)
* RBTX4927_IRQ_IOC+03 FPCIB0 PCI-A (SouthBridge/USB/pin=4)
* RBTX4927_IRQ_IOC+04
* RBTX4927_IRQ_IOC+05
* RBTX4927_IRQ_IOC+06
* RBTX4927_IRQ_IOC+07
*
* NOTES:
* SouthBridge/INTR is mapped to SouthBridge/A=PCI-B/#58
* SouthBridge/ISA/pin=0 no pci irq used by this device
* SouthBridge/IDE/pin=1 no pci irq used by this device, using INTR
* via ISA IRQ14
* SouthBridge/USB/pin=4 using pci irq SouthBridge/D=PCI-A=#59
* SouthBridge/PMC/pin=0 no pci irq used by this device
* SuperIO/PS2/Keyboard, using INTR via ISA IRQ1
* SuperIO/PS2/Mouse, using INTR via ISA IRQ12 (mouse not currently supported)
* JP7 is not bus master -- do NOT use -- only 4 pci bus master's
* allowed -- SouthBridge, JP4, JP5, JP6
*/
#include <linux/init.h>
#include <linux/types.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <asm/io.h>
#include <asm/mipsregs.h>
#include <asm/txx9/generic.h>
#include <asm/txx9/rbtx4927.h>
static int toshiba_rbtx4927_irq_nested(int sw_irq)
{
u8 level3;
level3 = readb(rbtx4927_imstat_addr) & 0x1f;
if (unlikely(!level3))
return -1;
return RBTX4927_IRQ_IOC + __fls8(level3);
}
static void toshiba_rbtx4927_irq_ioc_enable(struct irq_data *d)
{
unsigned char v;
v = readb(rbtx4927_imask_addr);
v |= (1 << (d->irq - RBTX4927_IRQ_IOC));
writeb(v, rbtx4927_imask_addr);
}
static void toshiba_rbtx4927_irq_ioc_disable(struct irq_data *d)
{
unsigned char v;
v = readb(rbtx4927_imask_addr);
v &= ~(1 << (d->irq - RBTX4927_IRQ_IOC));
writeb(v, rbtx4927_imask_addr);
mmiowb();
}
#define TOSHIBA_RBTX4927_IOC_NAME "RBTX4927-IOC"
static struct irq_chip toshiba_rbtx4927_irq_ioc_type = {
.name = TOSHIBA_RBTX4927_IOC_NAME,
.irq_mask = toshiba_rbtx4927_irq_ioc_disable,
.irq_unmask = toshiba_rbtx4927_irq_ioc_enable,
};
static void __init toshiba_rbtx4927_irq_ioc_init(void)
{
int i;
/* mask all IOC interrupts */
writeb(0, rbtx4927_imask_addr);
/* clear SoftInt interrupts */
writeb(0, rbtx4927_softint_addr);
for (i = RBTX4927_IRQ_IOC;
i < RBTX4927_IRQ_IOC + RBTX4927_NR_IRQ_IOC; i++)
irq_set_chip_and_handler(i, &toshiba_rbtx4927_irq_ioc_type,
handle_level_irq);
irq_set_chained_handler(RBTX4927_IRQ_IOCINT, handle_simple_irq);
}
static int rbtx4927_irq_dispatch(int pending)
{
int irq;
if (pending & STATUSF_IP7) /* cpu timer */
irq = MIPS_CPU_IRQ_BASE + 7;
else if (pending & STATUSF_IP2) { /* tx4927 pic */
irq = txx9_irq();
if (irq == RBTX4927_IRQ_IOCINT)
irq = toshiba_rbtx4927_irq_nested(irq);
} else if (pending & STATUSF_IP0) /* user line 0 */
irq = MIPS_CPU_IRQ_BASE + 0;
else if (pending & STATUSF_IP1) /* user line 1 */
irq = MIPS_CPU_IRQ_BASE + 1;
else
irq = -1;
return irq;
}
void __init rbtx4927_irq_setup(void)
{
txx9_irq_dispatch = rbtx4927_irq_dispatch;
tx4927_irq_init();
toshiba_rbtx4927_irq_ioc_init();
/* Onboard 10M Ether: High Active */
irq_set_irq_type(RBTX4927_RTL_8019_IRQ, IRQF_TRIGGER_HIGH);
}
| gpl-2.0 |
gdachs/linux | arch/avr32/boards/atngw100/setup.c | 8959 | 8610 | /*
* Board-specific setup code for the ATNGW100 Network Gateway
*
* Copyright (C) 2005-2006 Atmel Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/clk.h>
#include <linux/etherdevice.h>
#include <linux/gpio.h>
#include <linux/irq.h>
#include <linux/i2c.h>
#include <linux/i2c-gpio.h>
#include <linux/init.h>
#include <linux/linkage.h>
#include <linux/platform_device.h>
#include <linux/types.h>
#include <linux/leds.h>
#include <linux/spi/spi.h>
#include <linux/atmel-mci.h>
#include <linux/usb/atmel_usba_udc.h>
#include <asm/io.h>
#include <asm/setup.h>
#include <mach/at32ap700x.h>
#include <mach/board.h>
#include <mach/init.h>
#include <mach/portmux.h>
/* Oscillator frequencies. These are board-specific */
unsigned long at32_board_osc_rates[3] = {
[0] = 32768, /* 32.768 kHz on RTC osc */
[1] = 20000000, /* 20 MHz on osc0 */
[2] = 12000000, /* 12 MHz on osc1 */
};
/*
* The ATNGW100 mkII is very similar to the ATNGW100. Both have the AT32AP7000
* chip on board; the difference is that the ATNGW100 mkII has 128 MB 32-bit
* SDRAM (the ATNGW100 has 32 MB 16-bit SDRAM) and 256 MB 16-bit NAND flash
* (the ATNGW100 has none.)
*
* The RAM difference is handled by the boot loader, so the only difference we
* end up handling here is the NAND flash, EBI pin reservation and if LCDC or
* MACB1 should be enabled.
*/
#ifdef CONFIG_BOARD_ATNGW100_MKII
#include <linux/mtd/partitions.h>
#include <mach/smc.h>
static struct smc_timing nand_timing __initdata = {
.ncs_read_setup = 0,
.nrd_setup = 10,
.ncs_write_setup = 0,
.nwe_setup = 10,
.ncs_read_pulse = 30,
.nrd_pulse = 15,
.ncs_write_pulse = 30,
.nwe_pulse = 15,
.read_cycle = 30,
.write_cycle = 30,
.ncs_read_recover = 0,
.nrd_recover = 15,
.ncs_write_recover = 0,
/* WE# high -> RE# low min 60 ns */
.nwe_recover = 50,
};
static struct smc_config nand_config __initdata = {
.bus_width = 2,
.nrd_controlled = 1,
.nwe_controlled = 1,
.nwait_mode = 0,
.byte_write = 0,
.tdf_cycles = 2,
.tdf_mode = 0,
};
static struct mtd_partition nand_partitions[] = {
{
.name = "main",
.offset = 0x00000000,
.size = MTDPART_SIZ_FULL,
},
};
static struct atmel_nand_data atngw100mkii_nand_data __initdata = {
.cle = 21,
.ale = 22,
.rdy_pin = GPIO_PIN_PB(28),
.enable_pin = GPIO_PIN_PE(23),
.bus_width_16 = true,
.ecc_mode = NAND_ECC_SOFT,
.parts = nand_partitions,
.num_parts = ARRAY_SIZE(nand_partitions),
};
#endif
/* Initialized by bootloader-specific startup code. */
struct tag *bootloader_tags __initdata;
struct eth_addr {
u8 addr[6];
};
static struct eth_addr __initdata hw_addr[2];
static struct macb_platform_data __initdata eth_data[2];
static struct spi_board_info spi0_board_info[] __initdata = {
{
.modalias = "mtd_dataflash",
.max_speed_hz = 8000000,
.chip_select = 0,
},
};
static struct mci_platform_data __initdata mci0_data = {
.slot[0] = {
.bus_width = 4,
#if defined(CONFIG_BOARD_ATNGW100_MKII)
.detect_pin = GPIO_PIN_PC(25),
.wp_pin = GPIO_PIN_PE(22),
#else
.detect_pin = GPIO_PIN_PC(25),
.wp_pin = GPIO_PIN_PE(0),
#endif
},
};
static struct usba_platform_data atngw100_usba_data __initdata = {
#if defined(CONFIG_BOARD_ATNGW100_MKII)
.vbus_pin = GPIO_PIN_PE(26),
#else
.vbus_pin = -ENODEV,
#endif
};
/*
* The next two functions should go away as the boot loader is
* supposed to initialize the macb address registers with a valid
* ethernet address. But we need to keep it around for a while until
* we can be reasonably sure the boot loader does this.
*
* The phy_id is ignored as the driver will probe for it.
*/
static int __init parse_tag_ethernet(struct tag *tag)
{
int i;
i = tag->u.ethernet.mac_index;
if (i < ARRAY_SIZE(hw_addr))
memcpy(hw_addr[i].addr, tag->u.ethernet.hw_address,
sizeof(hw_addr[i].addr));
return 0;
}
__tagtable(ATAG_ETHERNET, parse_tag_ethernet);
static void __init set_hw_addr(struct platform_device *pdev)
{
struct resource *res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
const u8 *addr;
void __iomem *regs;
struct clk *pclk;
if (!res)
return;
if (pdev->id >= ARRAY_SIZE(hw_addr))
return;
addr = hw_addr[pdev->id].addr;
if (!is_valid_ether_addr(addr))
return;
/*
* Since this is board-specific code, we'll cheat and use the
* physical address directly as we happen to know that it's
* the same as the virtual address.
*/
regs = (void __iomem __force *)res->start;
pclk = clk_get(&pdev->dev, "pclk");
if (IS_ERR(pclk))
return;
clk_enable(pclk);
__raw_writel((addr[3] << 24) | (addr[2] << 16)
| (addr[1] << 8) | addr[0], regs + 0x98);
__raw_writel((addr[5] << 8) | addr[4], regs + 0x9c);
clk_disable(pclk);
clk_put(pclk);
}
void __init setup_board(void)
{
at32_map_usart(1, 0, 0); /* USART 1: /dev/ttyS0, DB9 */
at32_setup_serial_console(0);
}
static const struct gpio_led ngw_leds[] = {
{ .name = "sys", .gpio = GPIO_PIN_PA(16), .active_low = 1,
.default_trigger = "heartbeat",
},
{ .name = "a", .gpio = GPIO_PIN_PA(19), .active_low = 1, },
{ .name = "b", .gpio = GPIO_PIN_PE(19), .active_low = 1, },
};
static const struct gpio_led_platform_data ngw_led_data = {
.num_leds = ARRAY_SIZE(ngw_leds),
.leds = (void *) ngw_leds,
};
static struct platform_device ngw_gpio_leds = {
.name = "leds-gpio",
.id = -1,
.dev = {
.platform_data = (void *) &ngw_led_data,
}
};
static struct i2c_gpio_platform_data i2c_gpio_data = {
.sda_pin = GPIO_PIN_PA(6),
.scl_pin = GPIO_PIN_PA(7),
.sda_is_open_drain = 1,
.scl_is_open_drain = 1,
.udelay = 2, /* close to 100 kHz */
};
static struct platform_device i2c_gpio_device = {
.name = "i2c-gpio",
.id = 0,
.dev = {
.platform_data = &i2c_gpio_data,
},
};
static struct i2c_board_info __initdata i2c_info[] = {
/* NOTE: original ATtiny24 firmware is at address 0x0b */
};
static int __init atngw100_init(void)
{
unsigned i;
/*
* ATNGW100 mkII uses 32-bit SDRAM interface. Reserve the
* SDRAM-specific pins so that nobody messes with them.
*/
#ifdef CONFIG_BOARD_ATNGW100_MKII
at32_reserve_pin(GPIO_PIOE_BASE, ATMEL_EBI_PE_DATA_ALL);
smc_set_timing(&nand_config, &nand_timing);
smc_set_configuration(3, &nand_config);
at32_add_device_nand(0, &atngw100mkii_nand_data);
#endif
at32_add_device_usart(0);
set_hw_addr(at32_add_device_eth(0, ð_data[0]));
#ifndef CONFIG_BOARD_ATNGW100_MKII_LCD
set_hw_addr(at32_add_device_eth(1, ð_data[1]));
#endif
at32_add_device_spi(0, spi0_board_info, ARRAY_SIZE(spi0_board_info));
at32_add_device_mci(0, &mci0_data);
at32_add_device_usba(0, &atngw100_usba_data);
for (i = 0; i < ARRAY_SIZE(ngw_leds); i++) {
at32_select_gpio(ngw_leds[i].gpio,
AT32_GPIOF_OUTPUT | AT32_GPIOF_HIGH);
}
platform_device_register(&ngw_gpio_leds);
/* all these i2c/smbus pins should have external pullups for
* open-drain sharing among all I2C devices. SDA and SCL do;
* PB28/EXTINT3 (ATNGW100) and PE21 (ATNGW100 mkII) doesn't; it should
* be SMBALERT# (for PMBus), but it's not available off-board.
*/
#ifdef CONFIG_BOARD_ATNGW100_MKII
at32_select_periph(GPIO_PIOE_BASE, 1 << 21, 0, AT32_GPIOF_PULLUP);
#else
at32_select_periph(GPIO_PIOB_BASE, 1 << 28, 0, AT32_GPIOF_PULLUP);
#endif
at32_select_gpio(i2c_gpio_data.sda_pin,
AT32_GPIOF_MULTIDRV | AT32_GPIOF_OUTPUT | AT32_GPIOF_HIGH);
at32_select_gpio(i2c_gpio_data.scl_pin,
AT32_GPIOF_MULTIDRV | AT32_GPIOF_OUTPUT | AT32_GPIOF_HIGH);
platform_device_register(&i2c_gpio_device);
i2c_register_board_info(0, i2c_info, ARRAY_SIZE(i2c_info));
return 0;
}
postcore_initcall(atngw100_init);
static int __init atngw100_arch_init(void)
{
/* PB30 (ATNGW100) and PE30 (ATNGW100 mkII) is the otherwise unused
* jumper on the mainboard, with an external pullup; the jumper grounds
* it. Use it however you like, including letting U-Boot or Linux tweak
* boot sequences.
*/
#ifdef CONFIG_BOARD_ATNGW100_MKII
at32_select_gpio(GPIO_PIN_PE(30), 0);
gpio_request(GPIO_PIN_PE(30), "j15");
gpio_direction_input(GPIO_PIN_PE(30));
gpio_export(GPIO_PIN_PE(30), false);
#else
at32_select_gpio(GPIO_PIN_PB(30), 0);
gpio_request(GPIO_PIN_PB(30), "j15");
gpio_direction_input(GPIO_PIN_PB(30));
gpio_export(GPIO_PIN_PB(30), false);
#endif
/* set_irq_type() after the arch_initcall for EIC has run, and
* before the I2C subsystem could try using this IRQ.
*/
return irq_set_irq_type(AT32_EXTINT(3), IRQ_TYPE_EDGE_FALLING);
}
arch_initcall(atngw100_arch_init);
| gpl-2.0 |
HealthyMarshmallow/android_kernel_lge_g2 | arch/powerpc/platforms/cell/cbe_cpufreq_pervasive.c | 9471 | 2924 | /*
* pervasive backend for the cbe_cpufreq driver
*
* This driver makes use of the pervasive unit to
* engage the desired frequency.
*
* (C) Copyright IBM Deutschland Entwicklung GmbH 2005-2007
*
* Author: Christian Krafft <krafft@de.ibm.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, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include <linux/io.h>
#include <linux/kernel.h>
#include <linux/time.h>
#include <asm/machdep.h>
#include <asm/hw_irq.h>
#include <asm/cell-regs.h>
#include "cbe_cpufreq.h"
/* to write to MIC register */
static u64 MIC_Slow_Fast_Timer_table[] = {
[0 ... 7] = 0x007fc00000000000ull,
};
/* more values for the MIC */
static u64 MIC_Slow_Next_Timer_table[] = {
0x0000240000000000ull,
0x0000268000000000ull,
0x000029C000000000ull,
0x00002D0000000000ull,
0x0000300000000000ull,
0x0000334000000000ull,
0x000039C000000000ull,
0x00003FC000000000ull,
};
int cbe_cpufreq_set_pmode(int cpu, unsigned int pmode)
{
struct cbe_pmd_regs __iomem *pmd_regs;
struct cbe_mic_tm_regs __iomem *mic_tm_regs;
unsigned long flags;
u64 value;
#ifdef DEBUG
long time;
#endif
local_irq_save(flags);
mic_tm_regs = cbe_get_cpu_mic_tm_regs(cpu);
pmd_regs = cbe_get_cpu_pmd_regs(cpu);
#ifdef DEBUG
time = jiffies;
#endif
out_be64(&mic_tm_regs->slow_fast_timer_0, MIC_Slow_Fast_Timer_table[pmode]);
out_be64(&mic_tm_regs->slow_fast_timer_1, MIC_Slow_Fast_Timer_table[pmode]);
out_be64(&mic_tm_regs->slow_next_timer_0, MIC_Slow_Next_Timer_table[pmode]);
out_be64(&mic_tm_regs->slow_next_timer_1, MIC_Slow_Next_Timer_table[pmode]);
value = in_be64(&pmd_regs->pmcr);
/* set bits to zero */
value &= 0xFFFFFFFFFFFFFFF8ull;
/* set bits to next pmode */
value |= pmode;
out_be64(&pmd_regs->pmcr, value);
#ifdef DEBUG
/* wait until new pmode appears in status register */
value = in_be64(&pmd_regs->pmsr) & 0x07;
while (value != pmode) {
cpu_relax();
value = in_be64(&pmd_regs->pmsr) & 0x07;
}
time = jiffies - time;
time = jiffies_to_msecs(time);
pr_debug("had to wait %lu ms for a transition using " \
"pervasive unit\n", time);
#endif
local_irq_restore(flags);
return 0;
}
int cbe_cpufreq_get_pmode(int cpu)
{
int ret;
struct cbe_pmd_regs __iomem *pmd_regs;
pmd_regs = cbe_get_cpu_pmd_regs(cpu);
ret = in_be64(&pmd_regs->pmsr) & 0x07;
return ret;
}
| gpl-2.0 |
helicopter88/Find5-Kernel-Source-4.2 | drivers/block/paride/paride.c | 13823 | 8755 | /*
paride.c (c) 1997-8 Grant R. Guenther <grant@torque.net>
Under the terms of the GNU General Public License.
This is the base module for the family of device drivers
that support parallel port IDE devices.
*/
/* Changes:
1.01 GRG 1998.05.03 Use spinlocks
1.02 GRG 1998.05.05 init_proto, release_proto, ktti
1.03 GRG 1998.08.15 eliminate compiler warning
1.04 GRG 1998.11.28 added support for FRIQ
1.05 TMW 2000.06.06 use parport_find_number instead of
parport_enumerate
1.06 TMW 2001.03.26 more sane parport-or-not resource management
*/
#define PI_VERSION "1.06"
#include <linux/module.h>
#include <linux/kmod.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/string.h>
#include <linux/spinlock.h>
#include <linux/wait.h>
#include <linux/sched.h> /* TASK_* */
#include <linux/parport.h>
#include "paride.h"
MODULE_LICENSE("GPL");
#define MAX_PROTOS 32
static struct pi_protocol *protocols[MAX_PROTOS];
static DEFINE_SPINLOCK(pi_spinlock);
void pi_write_regr(PIA * pi, int cont, int regr, int val)
{
pi->proto->write_regr(pi, cont, regr, val);
}
EXPORT_SYMBOL(pi_write_regr);
int pi_read_regr(PIA * pi, int cont, int regr)
{
return pi->proto->read_regr(pi, cont, regr);
}
EXPORT_SYMBOL(pi_read_regr);
void pi_write_block(PIA * pi, char *buf, int count)
{
pi->proto->write_block(pi, buf, count);
}
EXPORT_SYMBOL(pi_write_block);
void pi_read_block(PIA * pi, char *buf, int count)
{
pi->proto->read_block(pi, buf, count);
}
EXPORT_SYMBOL(pi_read_block);
static void pi_wake_up(void *p)
{
PIA *pi = (PIA *) p;
unsigned long flags;
void (*cont) (void) = NULL;
spin_lock_irqsave(&pi_spinlock, flags);
if (pi->claim_cont && !parport_claim(pi->pardev)) {
cont = pi->claim_cont;
pi->claim_cont = NULL;
pi->claimed = 1;
}
spin_unlock_irqrestore(&pi_spinlock, flags);
wake_up(&(pi->parq));
if (cont)
cont();
}
int pi_schedule_claimed(PIA * pi, void (*cont) (void))
{
unsigned long flags;
spin_lock_irqsave(&pi_spinlock, flags);
if (pi->pardev && parport_claim(pi->pardev)) {
pi->claim_cont = cont;
spin_unlock_irqrestore(&pi_spinlock, flags);
return 0;
}
pi->claimed = 1;
spin_unlock_irqrestore(&pi_spinlock, flags);
return 1;
}
EXPORT_SYMBOL(pi_schedule_claimed);
void pi_do_claimed(PIA * pi, void (*cont) (void))
{
if (pi_schedule_claimed(pi, cont))
cont();
}
EXPORT_SYMBOL(pi_do_claimed);
static void pi_claim(PIA * pi)
{
if (pi->claimed)
return;
pi->claimed = 1;
if (pi->pardev)
wait_event(pi->parq,
!parport_claim((struct pardevice *) pi->pardev));
}
static void pi_unclaim(PIA * pi)
{
pi->claimed = 0;
if (pi->pardev)
parport_release((struct pardevice *) (pi->pardev));
}
void pi_connect(PIA * pi)
{
pi_claim(pi);
pi->proto->connect(pi);
}
EXPORT_SYMBOL(pi_connect);
void pi_disconnect(PIA * pi)
{
pi->proto->disconnect(pi);
pi_unclaim(pi);
}
EXPORT_SYMBOL(pi_disconnect);
static void pi_unregister_parport(PIA * pi)
{
if (pi->pardev) {
parport_unregister_device((struct pardevice *) (pi->pardev));
pi->pardev = NULL;
}
}
void pi_release(PIA * pi)
{
pi_unregister_parport(pi);
if (pi->proto->release_proto)
pi->proto->release_proto(pi);
module_put(pi->proto->owner);
}
EXPORT_SYMBOL(pi_release);
static int default_test_proto(PIA * pi, char *scratch, int verbose)
{
int j, k;
int e[2] = { 0, 0 };
pi->proto->connect(pi);
for (j = 0; j < 2; j++) {
pi_write_regr(pi, 0, 6, 0xa0 + j * 0x10);
for (k = 0; k < 256; k++) {
pi_write_regr(pi, 0, 2, k ^ 0xaa);
pi_write_regr(pi, 0, 3, k ^ 0x55);
if (pi_read_regr(pi, 0, 2) != (k ^ 0xaa))
e[j]++;
}
}
pi->proto->disconnect(pi);
if (verbose)
printk("%s: %s: port 0x%x, mode %d, test=(%d,%d)\n",
pi->device, pi->proto->name, pi->port,
pi->mode, e[0], e[1]);
return (e[0] && e[1]); /* not here if both > 0 */
}
static int pi_test_proto(PIA * pi, char *scratch, int verbose)
{
int res;
pi_claim(pi);
if (pi->proto->test_proto)
res = pi->proto->test_proto(pi, scratch, verbose);
else
res = default_test_proto(pi, scratch, verbose);
pi_unclaim(pi);
return res;
}
int paride_register(PIP * pr)
{
int k;
for (k = 0; k < MAX_PROTOS; k++)
if (protocols[k] && !strcmp(pr->name, protocols[k]->name)) {
printk("paride: %s protocol already registered\n",
pr->name);
return -1;
}
k = 0;
while ((k < MAX_PROTOS) && (protocols[k]))
k++;
if (k == MAX_PROTOS) {
printk("paride: protocol table full\n");
return -1;
}
protocols[k] = pr;
pr->index = k;
printk("paride: %s registered as protocol %d\n", pr->name, k);
return 0;
}
EXPORT_SYMBOL(paride_register);
void paride_unregister(PIP * pr)
{
if (!pr)
return;
if (protocols[pr->index] != pr) {
printk("paride: %s not registered\n", pr->name);
return;
}
protocols[pr->index] = NULL;
}
EXPORT_SYMBOL(paride_unregister);
static int pi_register_parport(PIA * pi, int verbose)
{
struct parport *port;
port = parport_find_base(pi->port);
if (!port)
return 0;
pi->pardev = parport_register_device(port,
pi->device, NULL,
pi_wake_up, NULL, 0, (void *) pi);
parport_put_port(port);
if (!pi->pardev)
return 0;
init_waitqueue_head(&pi->parq);
if (verbose)
printk("%s: 0x%x is %s\n", pi->device, pi->port, port->name);
pi->parname = (char *) port->name;
return 1;
}
static int pi_probe_mode(PIA * pi, int max, char *scratch, int verbose)
{
int best, range;
if (pi->mode != -1) {
if (pi->mode >= max)
return 0;
range = 3;
if (pi->mode >= pi->proto->epp_first)
range = 8;
if ((range == 8) && (pi->port % 8))
return 0;
pi->reserved = range;
return (!pi_test_proto(pi, scratch, verbose));
}
best = -1;
for (pi->mode = 0; pi->mode < max; pi->mode++) {
range = 3;
if (pi->mode >= pi->proto->epp_first)
range = 8;
if ((range == 8) && (pi->port % 8))
break;
pi->reserved = range;
if (!pi_test_proto(pi, scratch, verbose))
best = pi->mode;
}
pi->mode = best;
return (best > -1);
}
static int pi_probe_unit(PIA * pi, int unit, char *scratch, int verbose)
{
int max, s, e;
s = unit;
e = s + 1;
if (s == -1) {
s = 0;
e = pi->proto->max_units;
}
if (!pi_register_parport(pi, verbose))
return 0;
if (pi->proto->test_port) {
pi_claim(pi);
max = pi->proto->test_port(pi);
pi_unclaim(pi);
} else
max = pi->proto->max_mode;
if (pi->proto->probe_unit) {
pi_claim(pi);
for (pi->unit = s; pi->unit < e; pi->unit++)
if (pi->proto->probe_unit(pi)) {
pi_unclaim(pi);
if (pi_probe_mode(pi, max, scratch, verbose))
return 1;
pi_unregister_parport(pi);
return 0;
}
pi_unclaim(pi);
pi_unregister_parport(pi);
return 0;
}
if (!pi_probe_mode(pi, max, scratch, verbose)) {
pi_unregister_parport(pi);
return 0;
}
return 1;
}
int pi_init(PIA * pi, int autoprobe, int port, int mode,
int unit, int protocol, int delay, char *scratch,
int devtype, int verbose, char *device)
{
int p, k, s, e;
int lpts[7] = { 0x3bc, 0x378, 0x278, 0x268, 0x27c, 0x26c, 0 };
s = protocol;
e = s + 1;
if (!protocols[0])
request_module("paride_protocol");
if (autoprobe) {
s = 0;
e = MAX_PROTOS;
} else if ((s < 0) || (s >= MAX_PROTOS) || (port <= 0) ||
(!protocols[s]) || (unit < 0) ||
(unit >= protocols[s]->max_units)) {
printk("%s: Invalid parameters\n", device);
return 0;
}
for (p = s; p < e; p++) {
struct pi_protocol *proto = protocols[p];
if (!proto)
continue;
/* still racy */
if (!try_module_get(proto->owner))
continue;
pi->proto = proto;
pi->private = 0;
if (proto->init_proto && proto->init_proto(pi) < 0) {
pi->proto = NULL;
module_put(proto->owner);
continue;
}
if (delay == -1)
pi->delay = pi->proto->default_delay;
else
pi->delay = delay;
pi->devtype = devtype;
pi->device = device;
pi->parname = NULL;
pi->pardev = NULL;
init_waitqueue_head(&pi->parq);
pi->claimed = 0;
pi->claim_cont = NULL;
pi->mode = mode;
if (port != -1) {
pi->port = port;
if (pi_probe_unit(pi, unit, scratch, verbose))
break;
pi->port = 0;
} else {
k = 0;
while ((pi->port = lpts[k++]))
if (pi_probe_unit
(pi, unit, scratch, verbose))
break;
if (pi->port)
break;
}
if (pi->proto->release_proto)
pi->proto->release_proto(pi);
module_put(proto->owner);
}
if (!pi->port) {
if (autoprobe)
printk("%s: Autoprobe failed\n", device);
else
printk("%s: Adapter not found\n", device);
return 0;
}
if (pi->parname)
printk("%s: Sharing %s at 0x%x\n", pi->device,
pi->parname, pi->port);
pi->proto->log_adapter(pi, scratch, verbose);
return 1;
}
EXPORT_SYMBOL(pi_init);
| gpl-2.0 |
stevenremot/tlsd-prototype | src/Graphics/Render/RenderEvents.cpp | 1 | 1304 | /*
This file is part of The Lost Souls Downfall prototype.
The Lost Souls Downfall prototype is free software: you can
redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software
Foundation, either version 3 of the License, or (at your option)
any later version.
The Lost Souls Downfall prototype is distributed in the hope that
it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with The Lost Souls Downfall prototype. If not, see
<http://www.gnu.org/licenses/>.
*/
#include "RenderEvents.h"
namespace Graphics
{
namespace Render
{
const Event::Event::Type RenderMeshFileEvent::Type = "render_mesh_file";
const Event::Event::Type RenderAnimatedMeshFileEvent::Type = "render_animated_mesh_file";
const Event::Event::Type RenderModel3DEvent::Type = "render_model_3d";
const Event::Event::Type RenderCameraEvent::Type = "render_camera";
const Event::Event::Type CameraRenderedEvent::Type = "camera-rendered";
}
}
| gpl-3.0 |
Wyss/MOODS | src/scratch/pssm_algorithms.c | 1 | 12225 |
#include "pssm_algoritm.h"
#include "ksort.h"
#define cmp_gt_double(a, b) ((a) > (b))
KSORT_INIT(double, double, cmp_gt_double);
int mlf_free(moods_mlf_t mlf) {
const int msize = (int) kv_size(matrices);
int i;
for (i=0; i < msize; i++) {
kv_destroy(mlf->matrices.a[i]);
kv_destroy(mlf->output[i]);
// somthing for orders and L
}
kv_destroy(mlf->window_positions);
kv_destroy(mlf->m);
kv_destroy(mlf->thresholds);
kv_destroy(mlf->matrices);
kv_destroy(mlf->m);
kv_destroy(mlf->thresholds);
free(mlf);
}
typedef struct {
int q;
score_matrix_vec_t *matrices;
OutputListElementMulti_vec_t *output;
int_vec_t *window_positions;
int_vec_t *m;
int_matrix_t *orders;
score_matrix_t *L;
score_vec_t *thresholds;
} moods_mlf_t;
double * expectedDifferences(const score_matrix_t smatrix, const double *bg, int *rc) {
int numA = (int) kv_size(smatrix);
int m = (int) kv_size( kv_A(smatrix, 0) );
int i,j;
score_t max;
score_t temp;
double * ed = NULL;
ed = (double *) malloc(m*sizeof(double));
if (ed == NULL) {
goto ed_fail;
}
for (i = 0; i < m; ++i) {
max = SCORE_MIN;
for (j = 0; j < numA; ++j) {
temp = kv_A(kv_A(smatrix, j), i);
if (max < temp) {
max = temp;
}
}
ed[i] = max;
for (j = 0; j < numA; ++j) {
ed[i] -= bg[j] * kv_A(kv_A(smatrix, j), i);
}
}
*rc = 0;
return ed;
ed_fail:
*rc = 1;
return ed;
}
int multipleMatrixLookaheadFiltrationDNASetup(const int q,
const score_matrix_vec_t matrices,
OutputListElementMulti_t *output,
int *window_positions, int *m, int** orders,
score_t **L,
const double *bg, const score_t *thresholds) {
const int BITSHIFT = 2;
const unsigned int numA = 4; // 2**BITSIFT
// intArray m(matrices.size(), 0);
int i, j, k, rc;
const int msize = (int) kv_size(matrices);
for (i = 0; i < msize; ++i) {
m[i] = (int) kv_size(kv_A(kv_A(matrices, i), 0));
}
// Calculate entropies for all matrices
double **goodnesses = NULL;
goodnesses = (double **) malloc(msize*sizeof(double *));
if (goodnesses == NULL) {
goto mlf_fail;
}
for (i = 0; i < msize; ++i) {
goodnesses[i] = expectedDifferences(kv_A(matrices, i), bg, &rc);
if (rc < 0) {
goto mlf_fail;
}
}
int *window_positions = NULL;
window_positions = (int *) malloc(msize*sizeof(int));
if (window_positions == NULL) {
goto mlf_fail;
}
double current_goodness;
int window_pos;
double max_goodness;
for (k = 0; k < msize; ++k) {
if (q >= kv_A(m, k)) {
window_positions[0] = 0;
} else {
current_goodness = 0;
for (i = 0; i < q; ++i) {
current_goodness += goodnesses[k][i];
}
max_goodness = current_goodness;
window_pos = 0;
const int il = m[k] - q;
for (i = 0 i < il; ++i) {
current_goodness -= goodnesses[k][i];
current_goodness += goodnesses[k][i+q];
if (current_goodness > max_goodness) {
max_goodness = current_goodness;
window_pos = i+1;
}
}
window_positions[k] = window_pos;
}
}
// Calculate lookahead scores for all matrices
score_t **T = NULL;
T = (score_t **) malloc(msize*sizeof(score_t*));
if (T == NULL) {
goto mlf_fail;
}
score_t *C = NULL;
for (k = 0; k < msize; ++k) {
C = (score_t *) calloc(m[k], sizeof(score_t));
if (C == NULL) {
goto mlf_fail;
}
for (j = m[k] - 1; j > 0; --j) {
score_t max = SCORE_MIN;
for (i = 0; i < numA; ++i) {
if (max < matrices[k][i][j])
max = matrices[k][i][j];
}
C[j - 1] = C[j] + max;
}
T[k] = C;
}
// Pre-window scores
score_t *P = NULL;
P = (score_t *) malloc(msize*sizeof(score_t));
if (P == NULL) {
goto mlf_fail;
}
for (k = 0; k < msize; ++k) {
score_t B = 0;
for (j = 0; j < window_positions[k]; ++j) {
score_t max = SCORE_MIN;
for (i = 0; i < numA; ++i) {
if (max < matrices[k][i][j]) {
max = matrices[k][i][j];
}
}
B += max;
}
P[k] = B;
}
// Arrange matrix indeces not in window by entropy, for use in scanning
int_vec_t *orders = NULL;
int_vec_t *order;
orders = (int_vec_t *) calloc(msize, sizeof(int_vec_t));
if (orders == NULL) {
goto mlf_fail;
}
score_t **L = NULL;
L = (score_t **) malloc(msize*sizeof(score_t *));
if (L == NULL) {
goto mlf_fail;
}
for (k = 0; k < msize; ++k) {
if (q >= m[k]) {
orders[k] = NULL;
L[k] = NULL;
} else {
// intArray order(m[k]-q, 0);
// intorder = (int *) calloc(m[k]-q, sizeof(int));
kv_resize(int, order[k], m[k]-q);
order = &orders[k];
for (i = 0, il = window_positions[k]; i < il; ++i) {
order->a[i] = i;
}
for (i = window_positions[k]+q, il=m[k]; i < il; ++i) {
order->a[i - q] = i;
}
// compareRows comp;
// comp.goodness = &(goodnesses[k]);
// sort(order.begin(), order.end(), comp);
ks_mergesort_double(m[k]-q, order->a, 0);
score_t * K = NULL;
K = (score_t *) calloc(m[k] - q, sizeof(score_t));
if (K == NULL) {
goto mlf_fail;
}
for (j = m[k]-q-1; j > 0; --j) {
score_t max = INT_MIN;
for (i = 0; i < numA; ++i) {
if (max < matrices[k][i][order[j]]) {
max = matrices[k][i][order[j]];
}
}
K[j - 1] = K[j] + max;
}
L[k] = K;
}
}
const bits_t size = 1 << (BITSHIFT * q); // numA^q
// const bits_t BITAND = size - 1;
// vector<vector< OutputListElementMulti> > output(size);
OutputListElementMulti_vec_t* output = NULL;
output = (OutputListElementMulti_vec_t*) calloc(size, sizeof(OutputListElementMulti_vec_t));
if (output == NULL) {
goto mlf_fail;
}
bit_t *sA = (bit_t *) calloc(q, sizeof(bit_t));
if (sA == NULL) {
goto mlf_fail;
}
OutputListElementMulti_t *temp_ptr;
OutputListElementMulti_t temp;
while (1) {
bits_t code = 0;
for (int j = 0; j < q; ++j) {
code = (code << BITSHIFT) | sA[j];
}
for (k = 0; k < msize; ++k ) {
if (m[k] <= q) {
score_t score = 0;
const int il = m[k];
for (i = 0; i < il; ++i) {
score += matrices[k][sA[i]][i];
}
if (score >= tol[k]) {
temp.full = 1;
temp.matrix = k;
temp.score = score;
// push plus takes care of memory allocation
kv_push_safe(OutputListElementMulti_vec_t, output[code], temp, temp_ptr, mlf_fail);
}
} else {
score_t score = 0;
for (i = 0; i < q; ++i) {
score += matrices[k][sA[i]][i + window_positions[k]];
}
if (score + P[k] + T[k][q + window_positions[k]-1] >= thresholds[k]) {
temp.full = 0;
temp.matrix = k;
temp.score = score;
kv_push_safe(OutputListElementMulti_vec_t, output[code], temp, temp_ptr, mlf_fail);
}
}
}
int pos = 0;
while (pos < q) {
if (sA[pos] < numA - 1) {
++sA[pos];
break;
} else {
sA[pos] = 0;
++pos;
}
}
if (pos == q) {
break;
}
}
return 0;
mlf_fail:
// do stuff
return -1;
}
int doScan(const unsigned char *s,
moods_mlf_t *in,
match_data_t ** matches)
{
const int BITSHIFT = 2;
const bits_t size = 1 << (BITSHIFT * q); // numA^q
const bits_t BITAND = size - 1;
const position_t n = strlen(s);
// unpack datastructure
const int q = in->q;
const score_matrix_vec_t *matrices = in->matrices;
OutputListElementMulti_t *output = in->output;
const int_vec_t *window_positions = in->window_positions;
const int_vec_t *m = in->m;
int_matrix_t *orders = in->orders;
const score_matrix_t *L = in->L;
const score_vec_t *thresholds = in->thresholds;
const int msize = (int) kv_size(matrices);
// Scanning
// allocate an array of match_data_t vectors
match_data_vec_t *ret = NULL;
ret = calloc( msize, sizeof(match_data_vec_t));
if (ret == NULL) {
goto scan_fail;
}
match_data_t hit;
score_t score;
position_t k;
position_t limit;
position_t ii;
score_t tolerance;
int *z;
bits_t code = 0;
for (position_t ii = 0; ii < q - 1; ++ii) {
code = (code << BITSHIFT) + s[ii];
}
for (position_t i = 0; i < n - q + 1; ++i) {
code = ((code << BITSHIFT) + s[i + q - 1]) & BITAND;
int lim;
if ((lim=kv_size(output[code]) != 0) {
OutputListElementMulti_t *y = output[code].a;
OutputListElementMulti_t *yl = y + lim;
for (; y < yl; ++y) {
if (y->full) { // A Hit for a matrix of length <= q
hit.position = i;
hit.score = y->score;
kv_push(match_data_t, ret[y->matrix], hit);
continue;
}
// A possible hit for a longer matrix. Don't check if matrix can't be positioned entirely on the sequence here
if ( ((i - window_positions[y->matrix]) >= 0) && \
( (i + m[y->matrix] - window_positions[y->matrix]) <= n) ) {
score = y->score;
k = y->matrix;
limit = m[k] - q;
ii = i - window_positions[k];
tolerance = thresholds[k];
z = orders[k];
for (int j = 0; j < limit ;++j) {
score += matrices[k][s[ii+(*z)]][*z];
if (score + L[k][j] < tolerance) {
break;
}
++z;
}
if (score >= tolerance) {
hit.position = i - window_positions[k];
hit.score = score;
kv_push(match_data_t, ret[k], hit);
}
}
}
}
}
for (position_t i = n - q + 1; i < n; ++i) { // possible hits for matrices shorter than q near the end of sequence
code = (code << BITSHIFT) & BITAND; // dummy character to the end of code
int lim;
if ( (lim = kv_size(output[code]) != 0) {
OutputListElementMulti_t *y = output[code].a;
OutputListElementMulti_t *yl = y + lim;
for (; y < yl; ++y) {
if (y->full && m[y->matrix] < n - i + 1) { // only sufficiently short hits are considered
hit.position = i;
hit.score = y->score;
kv_push(match_data_t, ret[y->matrix], hit);
}
}
}
}
*matches = ret;
return 0;
scan_fail:
// do something
{
int i;
for (i=0; i < msize; i++) {
kv_destroy(ret[i])
}
free(ret);
}
} | gpl-3.0 |
wittsend/em-planar-actuator-controller | empac/pwm.c | 1 | 3312 | /*
* pwm.c
*
* Author : Matthew Witt (pxf5695@autuni.ac.nz)
* Created: 3/08/2017 7:30:31 PM
*
* Project Repository:https://github.com/wittsend/em-planar-actuator-controller
*
* Functions for initialising and controlling the PWM outputs
*
* More Info:
* Atmel AT90USB1287 Datasheet:http://www.atmel.com/images/doc7593.pdf
* Relevant reference materials or datasheets if applicable
*
* Functions:
* void xPwmInit(void)
* void yPwmInit(void)
*
*/
//////////////[Includes]////////////////////////////////////////////////////////////////////////////
#include "pwm.h"
//////////////[Defines]/////////////////////////////////////////////////////////////////////////////
//////////////[Functions]///////////////////////////////////////////////////////////////////////////
/*
* Function:
* void xPwmInit(void)
*
* Initialises the timer X and the 3 PWM channels used for the x axis stator windings.
*
* Inputs:
* none
*
* Returns:
* none
*
* Implementation:
* Timer X is initialised and each PWM channel is set up. The timer is set up to run in
* 10bit fast PWM mode, which means that the timer counter counts from 0 to 2^10 - 1 (1023). The
* duty cycle is set by the value stored in OCRnX where n is the number of the associated timer and
* X is the PWM channel. There are three PWM channels per timer. The OCR value can be a number
* anywhere between 0 and 1023. The fast PWM mode below is set to clear the PWM pin X when
* the timer counter is equal to OCRnX and to set pin X when the timer counter reaches the TOP value
* (1023)
*
* Improvements:
* Macros and defines for pin names and timer settings.
*
*/
void xPwmInit(void)
{
TCCR1A
= (0x02<<COM3A0) //Clear OC3A on compare match, set on TOP
| (0x02<<COM3B0) //Clear OC3B on compare match, set on TOP
| (0x02<<COM3C0) //Clear OC3C on compare match, set on TOP
| (0x03<<WGM30); //WG mode 7 Fast 10bit PWM
TCCR1B
= (0x01<<WGM32) //WG mode 7 Fast 10bit PWM
| (0x01<<CS30); //clk/1 (7.8kHz PWM)
OCR1A = 0x003F; //Initial values for OCR3
OCR1B = 0x003F;
OCR1C = 0x003F;
}
/*
* Function:
* void yPwmInit(void)
*
* Initialises the timer X and the 3 PWM channels used for the y axis stator windings.
*
* Inputs:
* none
*
* Returns:
* none
*
* Implementation:
* Timer X is initialised and each PWM channel is set up. The timer is set up to run in
* 10bit fast PWM mode, which means that the timer counter counts from 0 to 2^10 - 1 (1023). The
* duty cycle is set by the value stored in OCRnX where n is the number of the associated timer and
* X is the PWM channel. There are three PWM channels per timer. The OCR value can be a number
* anywhere between 0 and 1023. The fast PWM mode below is set to clear the PWM pin X when
* the timer counter is equal to OCRnX and to set pin X when the timer counter reaches the TOP value
* (1023)
*
* Improvements:
* Macros and defines for pin names and timer settings.
*
*/
void yPwmInit(void)
{
TCCR3A
= (0x02<<COM3A0) //Clear OC3A on compare match, set on TOP
| (0x02<<COM3B0) //Clear OC3B on compare match, set on TOP
| (0x02<<COM3C0) //Clear OC3C on compare match, set on TOP
| (0x03<<WGM30); //WG mode 7 Fast 10bit PWM
TCCR3B
= (0x01<<WGM32) //WG mode 7 Fast 10bit PWM
| (0x01<<CS30); //clk/1 (7.8kHz PWM)
OCR3A = 0x003F; //Initial values for OCR3
OCR3B = 0x003F;
OCR3C = 0x003F;
} | gpl-3.0 |
ArcticaProject/vcxsrv | freetype/src/autofit/afhints.c | 1 | 38752 | /***************************************************************************/
/* */
/* afhints.c */
/* */
/* Auto-fitter hinting routines (body). */
/* */
/* Copyright 2003-2007, 2009-2014 by */
/* David Turner, Robert Wilhelm, and Werner Lemberg. */
/* */
/* This file is part of the FreeType project, and may only be used, */
/* modified, and distributed under the terms of the FreeType project */
/* license, LICENSE.TXT. By continuing to use, modify, or distribute */
/* this file you indicate that you have read the license and */
/* understand and accept it fully. */
/* */
/***************************************************************************/
#include "afhints.h"
#include "aferrors.h"
#include <internal/ftcalc.h>
#include <internal/ftdebug.h>
/*************************************************************************/
/* */
/* The macro FT_COMPONENT is used in trace mode. It is an implicit */
/* parameter of the FT_TRACE() and FT_ERROR() macros, used to print/log */
/* messages during execution. */
/* */
#undef FT_COMPONENT
#define FT_COMPONENT trace_afhints
/* Get new segment for given axis. */
FT_LOCAL_DEF( FT_Error )
af_axis_hints_new_segment( AF_AxisHints axis,
FT_Memory memory,
AF_Segment *asegment )
{
FT_Error error = FT_Err_Ok;
AF_Segment segment = NULL;
if ( axis->num_segments >= axis->max_segments )
{
FT_Int old_max = axis->max_segments;
FT_Int new_max = old_max;
FT_Int big_max = (FT_Int)( FT_INT_MAX / sizeof ( *segment ) );
if ( old_max >= big_max )
{
error = FT_THROW( Out_Of_Memory );
goto Exit;
}
new_max += ( new_max >> 2 ) + 4;
if ( new_max < old_max || new_max > big_max )
new_max = big_max;
if ( FT_RENEW_ARRAY( axis->segments, old_max, new_max ) )
goto Exit;
axis->max_segments = new_max;
}
segment = axis->segments + axis->num_segments++;
Exit:
*asegment = segment;
return error;
}
/* Get new edge for given axis, direction, and position, */
/* without initializing the edge itself. */
FT_LOCAL( FT_Error )
af_axis_hints_new_edge( AF_AxisHints axis,
FT_Int fpos,
AF_Direction dir,
FT_Memory memory,
AF_Edge *anedge )
{
FT_Error error = FT_Err_Ok;
AF_Edge edge = NULL;
AF_Edge edges;
if ( axis->num_edges >= axis->max_edges )
{
FT_Int old_max = axis->max_edges;
FT_Int new_max = old_max;
FT_Int big_max = (FT_Int)( FT_INT_MAX / sizeof ( *edge ) );
if ( old_max >= big_max )
{
error = FT_THROW( Out_Of_Memory );
goto Exit;
}
new_max += ( new_max >> 2 ) + 4;
if ( new_max < old_max || new_max > big_max )
new_max = big_max;
if ( FT_RENEW_ARRAY( axis->edges, old_max, new_max ) )
goto Exit;
axis->max_edges = new_max;
}
edges = axis->edges;
edge = edges + axis->num_edges;
while ( edge > edges )
{
if ( edge[-1].fpos < fpos )
break;
/* we want the edge with same position and minor direction */
/* to appear before those in the major one in the list */
if ( edge[-1].fpos == fpos && dir == axis->major_dir )
break;
edge[0] = edge[-1];
edge--;
}
axis->num_edges++;
Exit:
*anedge = edge;
return error;
}
#ifdef FT_DEBUG_AUTOFIT
#include FT_CONFIG_STANDARD_LIBRARY_H
/* The dump functions are used in the `ftgrid' demo program, too. */
#define AF_DUMP( varformat ) \
do \
{ \
if ( to_stdout ) \
printf varformat; \
else \
FT_TRACE7( varformat ); \
} while ( 0 )
static const char*
af_dir_str( AF_Direction dir )
{
const char* result;
switch ( dir )
{
case AF_DIR_UP:
result = "up";
break;
case AF_DIR_DOWN:
result = "down";
break;
case AF_DIR_LEFT:
result = "left";
break;
case AF_DIR_RIGHT:
result = "right";
break;
default:
result = "none";
}
return result;
}
#define AF_INDEX_NUM( ptr, base ) (int)( (ptr) ? ( (ptr) - (base) ) : -1 )
#ifdef __cplusplus
extern "C" {
#endif
void
af_glyph_hints_dump_points( AF_GlyphHints hints,
FT_Bool to_stdout )
{
AF_Point points = hints->points;
AF_Point limit = points + hints->num_points;
AF_Point point;
AF_DUMP(( "Table of points:\n"
" [ index | xorg | yorg | xscale | yscale"
" | xfit | yfit | flags ]\n" ));
for ( point = points; point < limit; point++ )
AF_DUMP(( " [ %5d | %5d | %5d | %6.2f | %6.2f"
" | %5.2f | %5.2f | %c ]\n",
AF_INDEX_NUM( point, points ),
point->fx,
point->fy,
point->ox / 64.0,
point->oy / 64.0,
point->x / 64.0,
point->y / 64.0,
( point->flags & AF_FLAG_WEAK_INTERPOLATION ) ? 'w' : ' '));
AF_DUMP(( "\n" ));
}
#ifdef __cplusplus
}
#endif
static const char*
af_edge_flags_to_string( AF_Edge_Flags flags )
{
static char temp[32];
int pos = 0;
if ( flags & AF_EDGE_ROUND )
{
ft_memcpy( temp + pos, "round", 5 );
pos += 5;
}
if ( flags & AF_EDGE_SERIF )
{
if ( pos > 0 )
temp[pos++] = ' ';
ft_memcpy( temp + pos, "serif", 5 );
pos += 5;
}
if ( pos == 0 )
return "normal";
temp[pos] = '\0';
return temp;
}
/* Dump the array of linked segments. */
#ifdef __cplusplus
extern "C" {
#endif
void
af_glyph_hints_dump_segments( AF_GlyphHints hints,
FT_Bool to_stdout )
{
FT_Int dimension;
for ( dimension = 1; dimension >= 0; dimension-- )
{
AF_AxisHints axis = &hints->axis[dimension];
AF_Point points = hints->points;
AF_Edge edges = axis->edges;
AF_Segment segments = axis->segments;
AF_Segment limit = segments + axis->num_segments;
AF_Segment seg;
AF_DUMP(( "Table of %s segments:\n",
dimension == AF_DIMENSION_HORZ ? "vertical"
: "horizontal" ));
if ( axis->num_segments )
AF_DUMP(( " [ index | pos | dir | from"
" | to | link | serif | edge"
" | height | extra | flags ]\n" ));
else
AF_DUMP(( " (none)\n" ));
for ( seg = segments; seg < limit; seg++ )
AF_DUMP(( " [ %5d | %5.2g | %5s | %4d"
" | %4d | %4d | %5d | %4d"
" | %6d | %5d | %11s ]\n",
AF_INDEX_NUM( seg, segments ),
dimension == AF_DIMENSION_HORZ
? (int)seg->first->ox / 64.0
: (int)seg->first->oy / 64.0,
af_dir_str( (AF_Direction)seg->dir ),
AF_INDEX_NUM( seg->first, points ),
AF_INDEX_NUM( seg->last, points ),
AF_INDEX_NUM( seg->link, segments ),
AF_INDEX_NUM( seg->serif, segments ),
AF_INDEX_NUM( seg->edge, edges ),
seg->height,
seg->height - ( seg->max_coord - seg->min_coord ),
af_edge_flags_to_string( (AF_Edge_Flags)seg->flags ) ));
AF_DUMP(( "\n" ));
}
}
#ifdef __cplusplus
}
#endif
/* Fetch number of segments. */
#ifdef __cplusplus
extern "C" {
#endif
FT_Error
af_glyph_hints_get_num_segments( AF_GlyphHints hints,
FT_Int dimension,
FT_Int* num_segments )
{
AF_Dimension dim;
AF_AxisHints axis;
dim = ( dimension == 0 ) ? AF_DIMENSION_HORZ : AF_DIMENSION_VERT;
axis = &hints->axis[dim];
*num_segments = axis->num_segments;
return FT_Err_Ok;
}
#ifdef __cplusplus
}
#endif
/* Fetch offset of segments into user supplied offset array. */
#ifdef __cplusplus
extern "C" {
#endif
FT_Error
af_glyph_hints_get_segment_offset( AF_GlyphHints hints,
FT_Int dimension,
FT_Int idx,
FT_Pos *offset,
FT_Bool *is_blue,
FT_Pos *blue_offset )
{
AF_Dimension dim;
AF_AxisHints axis;
AF_Segment seg;
if ( !offset )
return FT_THROW( Invalid_Argument );
dim = ( dimension == 0 ) ? AF_DIMENSION_HORZ : AF_DIMENSION_VERT;
axis = &hints->axis[dim];
if ( idx < 0 || idx >= axis->num_segments )
return FT_THROW( Invalid_Argument );
seg = &axis->segments[idx];
*offset = ( dim == AF_DIMENSION_HORZ ) ? seg->first->ox
: seg->first->oy;
if ( seg->edge )
*is_blue = (FT_Bool)( seg->edge->blue_edge != 0 );
else
*is_blue = FALSE;
if ( *is_blue )
*blue_offset = seg->edge->blue_edge->cur;
else
*blue_offset = 0;
return FT_Err_Ok;
}
#ifdef __cplusplus
}
#endif
/* Dump the array of linked edges. */
#ifdef __cplusplus
extern "C" {
#endif
void
af_glyph_hints_dump_edges( AF_GlyphHints hints,
FT_Bool to_stdout )
{
FT_Int dimension;
for ( dimension = 1; dimension >= 0; dimension-- )
{
AF_AxisHints axis = &hints->axis[dimension];
AF_Edge edges = axis->edges;
AF_Edge limit = edges + axis->num_edges;
AF_Edge edge;
/*
* note: AF_DIMENSION_HORZ corresponds to _vertical_ edges
* since they have a constant X coordinate.
*/
AF_DUMP(( "Table of %s edges:\n",
dimension == AF_DIMENSION_HORZ ? "vertical"
: "horizontal" ));
if ( axis->num_edges )
AF_DUMP(( " [ index | pos | dir | link"
" | serif | blue | opos | pos | flags ]\n" ));
else
AF_DUMP(( " (none)\n" ));
for ( edge = edges; edge < limit; edge++ )
AF_DUMP(( " [ %5d | %5.2g | %5s | %4d"
" | %5d | %c | %5.2f | %5.2f | %11s ]\n",
AF_INDEX_NUM( edge, edges ),
(int)edge->opos / 64.0,
af_dir_str( (AF_Direction)edge->dir ),
AF_INDEX_NUM( edge->link, edges ),
AF_INDEX_NUM( edge->serif, edges ),
edge->blue_edge ? 'y' : 'n',
edge->opos / 64.0,
edge->pos / 64.0,
af_edge_flags_to_string( (AF_Edge_Flags)edge->flags ) ));
AF_DUMP(( "\n" ));
}
}
#ifdef __cplusplus
}
#endif
#undef AF_DUMP
#endif /* !FT_DEBUG_AUTOFIT */
/* Compute the direction value of a given vector. */
FT_LOCAL_DEF( AF_Direction )
af_direction_compute( FT_Pos dx,
FT_Pos dy )
{
FT_Pos ll, ss; /* long and short arm lengths */
AF_Direction dir; /* candidate direction */
if ( dy >= dx )
{
if ( dy >= -dx )
{
dir = AF_DIR_UP;
ll = dy;
ss = dx;
}
else
{
dir = AF_DIR_LEFT;
ll = -dx;
ss = dy;
}
}
else /* dy < dx */
{
if ( dy >= -dx )
{
dir = AF_DIR_RIGHT;
ll = dx;
ss = dy;
}
else
{
dir = AF_DIR_DOWN;
ll = dy;
ss = dx;
}
}
/* return no direction if arm lengths differ too much */
/* (value 14 is heuristic, corresponding to approx. 4.1 degrees) */
ss *= 14;
if ( FT_ABS( ll ) <= FT_ABS( ss ) )
dir = AF_DIR_NONE;
return dir;
}
FT_LOCAL_DEF( void )
af_glyph_hints_init( AF_GlyphHints hints,
FT_Memory memory )
{
FT_ZERO( hints );
hints->memory = memory;
}
FT_LOCAL_DEF( void )
af_glyph_hints_done( AF_GlyphHints hints )
{
FT_Memory memory = hints->memory;
int dim;
if ( !( hints && hints->memory ) )
return;
/*
* note that we don't need to free the segment and edge
* buffers since they are really within the hints->points array
*/
for ( dim = 0; dim < AF_DIMENSION_MAX; dim++ )
{
AF_AxisHints axis = &hints->axis[dim];
axis->num_segments = 0;
axis->max_segments = 0;
FT_FREE( axis->segments );
axis->num_edges = 0;
axis->max_edges = 0;
FT_FREE( axis->edges );
}
FT_FREE( hints->contours );
hints->max_contours = 0;
hints->num_contours = 0;
FT_FREE( hints->points );
hints->num_points = 0;
hints->max_points = 0;
hints->memory = NULL;
}
/* Reset metrics. */
FT_LOCAL_DEF( void )
af_glyph_hints_rescale( AF_GlyphHints hints,
AF_StyleMetrics metrics )
{
hints->metrics = metrics;
hints->scaler_flags = metrics->scaler.flags;
}
/* Recompute all AF_Point in AF_GlyphHints from the definitions */
/* in a source outline. */
FT_LOCAL_DEF( FT_Error )
af_glyph_hints_reload( AF_GlyphHints hints,
FT_Outline* outline )
{
FT_Error error = FT_Err_Ok;
AF_Point points;
FT_UInt old_max, new_max;
FT_Fixed x_scale = hints->x_scale;
FT_Fixed y_scale = hints->y_scale;
FT_Pos x_delta = hints->x_delta;
FT_Pos y_delta = hints->y_delta;
FT_Memory memory = hints->memory;
hints->num_points = 0;
hints->num_contours = 0;
hints->axis[0].num_segments = 0;
hints->axis[0].num_edges = 0;
hints->axis[1].num_segments = 0;
hints->axis[1].num_edges = 0;
/* first of all, reallocate the contours array if necessary */
new_max = (FT_UInt)outline->n_contours;
old_max = hints->max_contours;
if ( new_max > old_max )
{
new_max = ( new_max + 3 ) & ~3; /* round up to a multiple of 4 */
if ( FT_RENEW_ARRAY( hints->contours, old_max, new_max ) )
goto Exit;
hints->max_contours = new_max;
}
/*
* then reallocate the points arrays if necessary --
* note that we reserve two additional point positions, used to
* hint metrics appropriately
*/
new_max = (FT_UInt)( outline->n_points + 2 );
old_max = hints->max_points;
if ( new_max > old_max )
{
new_max = ( new_max + 2 + 7 ) & ~7; /* round up to a multiple of 8 */
if ( FT_RENEW_ARRAY( hints->points, old_max, new_max ) )
goto Exit;
hints->max_points = new_max;
}
hints->num_points = outline->n_points;
hints->num_contours = outline->n_contours;
/* We can't rely on the value of `FT_Outline.flags' to know the fill */
/* direction used for a glyph, given that some fonts are broken (e.g., */
/* the Arphic ones). We thus recompute it each time we need to. */
/* */
hints->axis[AF_DIMENSION_HORZ].major_dir = AF_DIR_UP;
hints->axis[AF_DIMENSION_VERT].major_dir = AF_DIR_LEFT;
if ( FT_Outline_Get_Orientation( outline ) == FT_ORIENTATION_POSTSCRIPT )
{
hints->axis[AF_DIMENSION_HORZ].major_dir = AF_DIR_DOWN;
hints->axis[AF_DIMENSION_VERT].major_dir = AF_DIR_RIGHT;
}
hints->x_scale = x_scale;
hints->y_scale = y_scale;
hints->x_delta = x_delta;
hints->y_delta = y_delta;
hints->xmin_delta = 0;
hints->xmax_delta = 0;
points = hints->points;
if ( hints->num_points == 0 )
goto Exit;
{
AF_Point point;
AF_Point point_limit = points + hints->num_points;
/* compute coordinates & Bezier flags, next and prev */
{
FT_Vector* vec = outline->points;
char* tag = outline->tags;
AF_Point end = points + outline->contours[0];
AF_Point prev = end;
FT_Int contour_index = 0;
for ( point = points; point < point_limit; point++, vec++, tag++ )
{
point->in_dir = (FT_Char)AF_DIR_NONE;
point->out_dir = (FT_Char)AF_DIR_NONE;
point->fx = (FT_Short)vec->x;
point->fy = (FT_Short)vec->y;
point->ox = point->x = FT_MulFix( vec->x, x_scale ) + x_delta;
point->oy = point->y = FT_MulFix( vec->y, y_scale ) + y_delta;
switch ( FT_CURVE_TAG( *tag ) )
{
case FT_CURVE_TAG_CONIC:
point->flags = AF_FLAG_CONIC;
break;
case FT_CURVE_TAG_CUBIC:
point->flags = AF_FLAG_CUBIC;
break;
default:
point->flags = AF_FLAG_NONE;
}
point->prev = prev;
prev->next = point;
prev = point;
if ( point == end )
{
if ( ++contour_index < outline->n_contours )
{
end = points + outline->contours[contour_index];
prev = end;
}
}
}
}
/* set up the contours array */
{
AF_Point* contour = hints->contours;
AF_Point* contour_limit = contour + hints->num_contours;
short* end = outline->contours;
short idx = 0;
for ( ; contour < contour_limit; contour++, end++ )
{
contour[0] = points + idx;
idx = (short)( end[0] + 1 );
}
}
{
/*
* Compute directions of `in' and `out' vectors.
*
* Note that distances between points that are very near to each
* other are accumulated. In other words, the auto-hinter
* prepends the small vectors between near points to the first
* non-near vector. All intermediate points are tagged as
* weak; the directions are adjusted also to be equal to the
* accumulated one.
*/
/* value 20 in `near_limit' is heuristic */
FT_UInt units_per_em = hints->metrics->scaler.face->units_per_EM;
FT_Int near_limit = 20 * units_per_em / 2048;
FT_Int near_limit2 = 2 * near_limit - 1;
AF_Point* contour;
AF_Point* contour_limit = hints->contours + hints->num_contours;
for ( contour = hints->contours; contour < contour_limit; contour++ )
{
AF_Point first = *contour;
AF_Point next, prev, curr;
FT_Pos out_x, out_y;
FT_Bool is_first;
/* since the first point of a contour could be part of a */
/* series of near points, go backwards to find the first */
/* non-near point and adjust `first' */
point = first;
prev = first->prev;
while ( prev != first )
{
out_x = point->fx - prev->fx;
out_y = point->fy - prev->fy;
/*
* We use Taxicab metrics to measure the vector length.
*
* Note that the accumulated distances so far could have the
* opposite direction of the distance measured here. For this
* reason we use `near_limit2' for the comparison to get a
* non-near point even in the worst case.
*/
if ( FT_ABS( out_x ) + FT_ABS( out_y ) >= near_limit2 )
break;
point = prev;
prev = prev->prev;
}
/* adjust first point */
first = point;
/* now loop over all points of the contour to get */
/* `in' and `out' vector directions */
curr = first;
/*
* We abuse the `u' and `v' fields to store index deltas to the
* next and previous non-near point, respectively.
*
* To avoid problems with not having non-near points, we point to
* `first' by default as the next non-near point.
*
*/
curr->u = (FT_Pos)( first - curr );
first->v = -curr->u;
out_x = 0;
out_y = 0;
is_first = 1;
for ( point = first;
point != first || is_first;
point = point->next )
{
AF_Direction out_dir;
is_first = 0;
next = point->next;
out_x += next->fx - point->fx;
out_y += next->fy - point->fy;
if ( FT_ABS( out_x ) + FT_ABS( out_y ) < near_limit )
{
next->flags |= AF_FLAG_WEAK_INTERPOLATION;
continue;
}
curr->u = (FT_Pos)( next - curr );
next->v = -curr->u;
out_dir = af_direction_compute( out_x, out_y );
/* adjust directions for all points inbetween; */
/* the loop also updates position of `curr' */
curr->out_dir = (FT_Char)out_dir;
for ( curr = curr->next; curr != next; curr = curr->next )
{
curr->in_dir = (FT_Char)out_dir;
curr->out_dir = (FT_Char)out_dir;
}
next->in_dir = (FT_Char)out_dir;
curr->u = (FT_Pos)( first - curr );
first->v = -curr->u;
out_x = 0;
out_y = 0;
}
}
/*
* The next step is to `simplify' an outline's topology so that we
* can identify local extrema more reliably: A series of
* non-horizontal or non-vertical vectors pointing into the same
* quadrant are handled as a single, long vector. From a
* topological point of the view, the intermediate points are of no
* interest and thus tagged as weak.
*/
for ( point = points; point < point_limit; point++ )
{
if ( point->flags & AF_FLAG_WEAK_INTERPOLATION )
continue;
if ( point->in_dir == AF_DIR_NONE &&
point->out_dir == AF_DIR_NONE )
{
/* check whether both vectors point into the same quadrant */
FT_Pos in_x, in_y;
FT_Pos out_x, out_y;
AF_Point next_u = point + point->u;
AF_Point prev_v = point + point->v;
in_x = point->fx - prev_v->fx;
in_y = point->fy - prev_v->fy;
out_x = next_u->fx - point->fx;
out_y = next_u->fy - point->fy;
if ( ( in_x ^ out_x ) >= 0 && ( in_y ^ out_y ) >= 0 )
{
/* yes, so tag current point as weak */
/* and update index deltas */
point->flags |= AF_FLAG_WEAK_INTERPOLATION;
prev_v->u = (FT_Pos)( next_u - prev_v );
next_u->v = -prev_v->u;
}
}
}
/*
* Finally, check for remaining weak points. Everything else not
* collected in edges so far is then implicitly classified as strong
* points.
*/
for ( point = points; point < point_limit; point++ )
{
if ( point->flags & AF_FLAG_WEAK_INTERPOLATION )
continue;
if ( point->flags & AF_FLAG_CONTROL )
{
/* control points are always weak */
Is_Weak_Point:
point->flags |= AF_FLAG_WEAK_INTERPOLATION;
}
else if ( point->out_dir == point->in_dir )
{
if ( point->out_dir != AF_DIR_NONE )
{
/* current point lies on a horizontal or */
/* vertical segment (but doesn't start or end it) */
goto Is_Weak_Point;
}
{
AF_Point next_u = point + point->u;
AF_Point prev_v = point + point->v;
if ( ft_corner_is_flat( point->fx - prev_v->fx,
point->fy - prev_v->fy,
next_u->fx - point->fx,
next_u->fy - point->fy ) )
{
/* either the `in' or the `out' vector is much more */
/* dominant than the other one, so tag current point */
/* as weak and update index deltas */
prev_v->u = (FT_Pos)( next_u - prev_v );
next_u->v = -prev_v->u;
goto Is_Weak_Point;
}
}
}
else if ( point->in_dir == -point->out_dir )
{
/* current point forms a spike */
goto Is_Weak_Point;
}
}
}
}
Exit:
return error;
}
/* Store the hinted outline in an FT_Outline structure. */
FT_LOCAL_DEF( void )
af_glyph_hints_save( AF_GlyphHints hints,
FT_Outline* outline )
{
AF_Point point = hints->points;
AF_Point limit = point + hints->num_points;
FT_Vector* vec = outline->points;
char* tag = outline->tags;
for ( ; point < limit; point++, vec++, tag++ )
{
vec->x = point->x;
vec->y = point->y;
if ( point->flags & AF_FLAG_CONIC )
tag[0] = FT_CURVE_TAG_CONIC;
else if ( point->flags & AF_FLAG_CUBIC )
tag[0] = FT_CURVE_TAG_CUBIC;
else
tag[0] = FT_CURVE_TAG_ON;
}
}
/****************************************************************
*
* EDGE POINT GRID-FITTING
*
****************************************************************/
/* Align all points of an edge to the same coordinate value, */
/* either horizontally or vertically. */
FT_LOCAL_DEF( void )
af_glyph_hints_align_edge_points( AF_GlyphHints hints,
AF_Dimension dim )
{
AF_AxisHints axis = & hints->axis[dim];
AF_Segment segments = axis->segments;
AF_Segment segment_limit = segments + axis->num_segments;
AF_Segment seg;
if ( dim == AF_DIMENSION_HORZ )
{
for ( seg = segments; seg < segment_limit; seg++ )
{
AF_Edge edge = seg->edge;
AF_Point point, first, last;
if ( edge == NULL )
continue;
first = seg->first;
last = seg->last;
point = first;
for (;;)
{
point->x = edge->pos;
point->flags |= AF_FLAG_TOUCH_X;
if ( point == last )
break;
point = point->next;
}
}
}
else
{
for ( seg = segments; seg < segment_limit; seg++ )
{
AF_Edge edge = seg->edge;
AF_Point point, first, last;
if ( edge == NULL )
continue;
first = seg->first;
last = seg->last;
point = first;
for (;;)
{
point->y = edge->pos;
point->flags |= AF_FLAG_TOUCH_Y;
if ( point == last )
break;
point = point->next;
}
}
}
}
/****************************************************************
*
* STRONG POINT INTERPOLATION
*
****************************************************************/
/* Hint the strong points -- this is equivalent to the TrueType `IP' */
/* hinting instruction. */
FT_LOCAL_DEF( void )
af_glyph_hints_align_strong_points( AF_GlyphHints hints,
AF_Dimension dim )
{
AF_Point points = hints->points;
AF_Point point_limit = points + hints->num_points;
AF_AxisHints axis = &hints->axis[dim];
AF_Edge edges = axis->edges;
AF_Edge edge_limit = edges + axis->num_edges;
AF_Flags touch_flag;
if ( dim == AF_DIMENSION_HORZ )
touch_flag = AF_FLAG_TOUCH_X;
else
touch_flag = AF_FLAG_TOUCH_Y;
if ( edges < edge_limit )
{
AF_Point point;
AF_Edge edge;
for ( point = points; point < point_limit; point++ )
{
FT_Pos u, ou, fu; /* point position */
FT_Pos delta;
if ( point->flags & touch_flag )
continue;
/* if this point is candidate to weak interpolation, we */
/* interpolate it after all strong points have been processed */
if ( ( point->flags & AF_FLAG_WEAK_INTERPOLATION ) )
continue;
if ( dim == AF_DIMENSION_VERT )
{
u = point->fy;
ou = point->oy;
}
else
{
u = point->fx;
ou = point->ox;
}
fu = u;
/* is the point before the first edge? */
edge = edges;
delta = edge->fpos - u;
if ( delta >= 0 )
{
u = edge->pos - ( edge->opos - ou );
goto Store_Point;
}
/* is the point after the last edge? */
edge = edge_limit - 1;
delta = u - edge->fpos;
if ( delta >= 0 )
{
u = edge->pos + ( ou - edge->opos );
goto Store_Point;
}
{
FT_PtrDist min, max, mid;
FT_Pos fpos;
/* find enclosing edges */
min = 0;
max = edge_limit - edges;
#if 1
/* for a small number of edges, a linear search is better */
if ( max <= 8 )
{
FT_PtrDist nn;
for ( nn = 0; nn < max; nn++ )
if ( edges[nn].fpos >= u )
break;
if ( edges[nn].fpos == u )
{
u = edges[nn].pos;
goto Store_Point;
}
min = nn;
}
else
#endif
while ( min < max )
{
mid = ( max + min ) >> 1;
edge = edges + mid;
fpos = edge->fpos;
if ( u < fpos )
max = mid;
else if ( u > fpos )
min = mid + 1;
else
{
/* we are on the edge */
u = edge->pos;
goto Store_Point;
}
}
/* point is not on an edge */
{
AF_Edge before = edges + min - 1;
AF_Edge after = edges + min + 0;
/* assert( before && after && before != after ) */
if ( before->scale == 0 )
before->scale = FT_DivFix( after->pos - before->pos,
after->fpos - before->fpos );
u = before->pos + FT_MulFix( fu - before->fpos,
before->scale );
}
}
Store_Point:
/* save the point position */
if ( dim == AF_DIMENSION_HORZ )
point->x = u;
else
point->y = u;
point->flags |= touch_flag;
}
}
}
/****************************************************************
*
* WEAK POINT INTERPOLATION
*
****************************************************************/
/* Shift the original coordinates of all points between `p1' and */
/* `p2' to get hinted coordinates, using the same difference as */
/* given by `ref'. */
static void
af_iup_shift( AF_Point p1,
AF_Point p2,
AF_Point ref )
{
AF_Point p;
FT_Pos delta = ref->u - ref->v;
if ( delta == 0 )
return;
for ( p = p1; p < ref; p++ )
p->u = p->v + delta;
for ( p = ref + 1; p <= p2; p++ )
p->u = p->v + delta;
}
/* Interpolate the original coordinates of all points between `p1' and */
/* `p2' to get hinted coordinates, using `ref1' and `ref2' as the */
/* reference points. The `u' and `v' members are the current and */
/* original coordinate values, respectively. */
/* */
/* Details can be found in the TrueType bytecode specification. */
static void
af_iup_interp( AF_Point p1,
AF_Point p2,
AF_Point ref1,
AF_Point ref2 )
{
AF_Point p;
FT_Pos u;
FT_Pos v1 = ref1->v;
FT_Pos v2 = ref2->v;
FT_Pos d1 = ref1->u - v1;
FT_Pos d2 = ref2->u - v2;
if ( p1 > p2 )
return;
if ( v1 == v2 )
{
for ( p = p1; p <= p2; p++ )
{
u = p->v;
if ( u <= v1 )
u += d1;
else
u += d2;
p->u = u;
}
return;
}
if ( v1 < v2 )
{
for ( p = p1; p <= p2; p++ )
{
u = p->v;
if ( u <= v1 )
u += d1;
else if ( u >= v2 )
u += d2;
else
u = ref1->u + FT_MulDiv( u - v1, ref2->u - ref1->u, v2 - v1 );
p->u = u;
}
}
else
{
for ( p = p1; p <= p2; p++ )
{
u = p->v;
if ( u <= v2 )
u += d2;
else if ( u >= v1 )
u += d1;
else
u = ref1->u + FT_MulDiv( u - v1, ref2->u - ref1->u, v2 - v1 );
p->u = u;
}
}
}
/* Hint the weak points -- this is equivalent to the TrueType `IUP' */
/* hinting instruction. */
FT_LOCAL_DEF( void )
af_glyph_hints_align_weak_points( AF_GlyphHints hints,
AF_Dimension dim )
{
AF_Point points = hints->points;
AF_Point point_limit = points + hints->num_points;
AF_Point* contour = hints->contours;
AF_Point* contour_limit = contour + hints->num_contours;
AF_Flags touch_flag;
AF_Point point;
AF_Point end_point;
AF_Point first_point;
/* PASS 1: Move segment points to edge positions */
if ( dim == AF_DIMENSION_HORZ )
{
touch_flag = AF_FLAG_TOUCH_X;
for ( point = points; point < point_limit; point++ )
{
point->u = point->x;
point->v = point->ox;
}
}
else
{
touch_flag = AF_FLAG_TOUCH_Y;
for ( point = points; point < point_limit; point++ )
{
point->u = point->y;
point->v = point->oy;
}
}
for ( ; contour < contour_limit; contour++ )
{
AF_Point first_touched, last_touched;
point = *contour;
end_point = point->prev;
first_point = point;
/* find first touched point */
for (;;)
{
if ( point > end_point ) /* no touched point in contour */
goto NextContour;
if ( point->flags & touch_flag )
break;
point++;
}
first_touched = point;
for (;;)
{
FT_ASSERT( point <= end_point &&
( point->flags & touch_flag ) != 0 );
/* skip any touched neighbours */
while ( point < end_point &&
( point[1].flags & touch_flag ) != 0 )
point++;
last_touched = point;
/* find the next touched point, if any */
point++;
for (;;)
{
if ( point > end_point )
goto EndContour;
if ( ( point->flags & touch_flag ) != 0 )
break;
point++;
}
/* interpolate between last_touched and point */
af_iup_interp( last_touched + 1, point - 1,
last_touched, point );
}
EndContour:
/* special case: only one point was touched */
if ( last_touched == first_touched )
af_iup_shift( first_point, end_point, first_touched );
else /* interpolate the last part */
{
if ( last_touched < end_point )
af_iup_interp( last_touched + 1, end_point,
last_touched, first_touched );
if ( first_touched > points )
af_iup_interp( first_point, first_touched - 1,
last_touched, first_touched );
}
NextContour:
;
}
/* now save the interpolated values back to x/y */
if ( dim == AF_DIMENSION_HORZ )
{
for ( point = points; point < point_limit; point++ )
point->x = point->u;
}
else
{
for ( point = points; point < point_limit; point++ )
point->y = point->u;
}
}
#ifdef AF_CONFIG_OPTION_USE_WARPER
/* Apply (small) warp scale and warp delta for given dimension. */
FT_LOCAL_DEF( void )
af_glyph_hints_scale_dim( AF_GlyphHints hints,
AF_Dimension dim,
FT_Fixed scale,
FT_Pos delta )
{
AF_Point points = hints->points;
AF_Point points_limit = points + hints->num_points;
AF_Point point;
if ( dim == AF_DIMENSION_HORZ )
{
for ( point = points; point < points_limit; point++ )
point->x = FT_MulFix( point->fx, scale ) + delta;
}
else
{
for ( point = points; point < points_limit; point++ )
point->y = FT_MulFix( point->fy, scale ) + delta;
}
}
#endif /* AF_CONFIG_OPTION_USE_WARPER */
/* END */
| gpl-3.0 |
daedalus/showtime | src/networking/net_posix.c | 1 | 11363 | /*
* Networking under POSIX
* Copyright (C) 2007-2008 Andreas Öman
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <sys/ioctl.h>
#include <netdb.h>
#include <poll.h>
#include <assert.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <fcntl.h>
#include <errno.h>
#include <net/if.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <arpa/inet.h>
#include <ifaddrs.h>
#include <pthread.h>
#include "showtime.h"
#include "net.h"
#if ENABLE_HTTPSERVER
#include "http_server.h"
#include "ssdp.h"
#endif
#if ENABLE_OPENSSL
static SSL_CTX *showtime_ssl_ctx;
static pthread_mutex_t *ssl_locks;
static unsigned long
ssl_tid_fn(void)
{
return (unsigned long)pthread_self();
}
static void
ssl_lock_fn(int mode, int n, const char *file, int line)
{
if(mode & CRYPTO_LOCK)
pthread_mutex_lock(&ssl_locks[n]);
else
pthread_mutex_unlock(&ssl_locks[n]);
}
/**
*
*/
static int
ssl_read(tcpcon_t *tc, void *buf, size_t len, int all)
{
int c, tot = 0;
if(!all) {
c = SSL_read(tc->ssl, buf, len);
return c > 0 ? c : -1;
}
while(tot != len) {
c = SSL_read(tc->ssl, buf + tot, len - tot);
if(c < 1)
return -1;
tot += c;
}
return tot;
}
/**
*
*/
static int
ssl_write(tcpcon_t *tc, const void *data, size_t len)
{
return SSL_write(tc->ssl, data, len) != len ? ECONNRESET : 0;
}
#endif
#if ENABLE_POLARSSL
/**
*
*/
static int
polarssl_read(tcpcon_t *tc, void *buf, size_t len, int all)
{
int ret, tot = 0;
if(!all) {
ret = ssl_read(tc->ssl, buf, len);
return ret > 0 ? ret : -1;
}
while(tot != len) {
ret = ssl_read(tc->ssl, buf + tot, len - tot);
if(ret < 0)
return -1;
tot += ret;
}
return tot;
}
/**
*
*/
static int
polarssl_write(tcpcon_t *tc, const void *data, size_t len)
{
return ssl_write(tc->ssl, data, len) != len ? ECONNRESET : 0;
}
#endif
/**
*
*/
static int
tcp_write(tcpcon_t *tc, const void *data, size_t len)
{
#ifdef MSG_NOSIGNAL
return send(tc->fd, data, len, MSG_NOSIGNAL) != len ? ECONNRESET : 0;
#else
return send(tc->fd, data, len, 0 ) != len ? ECONNRESET : 0;
#endif
}
/**
*
*/
static int
tcp_read(tcpcon_t *tc, void *buf, size_t len, int all)
{
int x;
size_t off = 0;
while(1) {
x = recv(tc->fd, buf + off, len - off, all ? MSG_WAITALL : 0);
if(x <= 0)
return -1;
if(all) {
off += x;
if(off == len)
return len;
} else {
return x < 1 ? -1 : x;
}
}
}
/**
*
*/
static int
getstreamsocket(int family, char *errbuf, size_t errbufsize)
{
int fd;
int val = 1;
fd = socket(family, SOCK_STREAM, 0);
if(fd == -1) {
snprintf(errbuf, errbufsize, "Unable to create socket: %s",
strerror(errno));
return -1;
}
/**
* Switch to nonblocking
*/
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) | O_NONBLOCK);
/* Darwin send() does not have MSG_NOSIGNAL, but has SO_NOSIGPIPE sockopt */
#ifdef SO_NOSIGPIPE
if(setsockopt(fd, SOL_SOCKET, SO_NOSIGPIPE, &val, sizeof(val)) == -1) {
snprintf(errbuf, errbufsize, "setsockopt SO_NOSIGPIPE error: %s",
strerror(errno));
close(fd);
return -1;
}
#endif
if(setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val)) < 0)
TRACE(TRACE_INFO, "TCP", "Unable to turn on TCP_NODELAY");
return fd;
}
/**
*
*/
tcpcon_t *
tcp_connect(const char *hostname, int port, char *errbuf, size_t errbufsize,
int timeout, int ssl)
{
struct hostent *hp;
char *tmphstbuf;
int fd, val, r, err, herr;
const char *errtxt;
#if !defined(__APPLE__)
struct hostent hostbuf;
size_t hstbuflen;
int res;
#endif
struct sockaddr_in6 in6;
struct sockaddr_in in;
socklen_t errlen = sizeof(int);
if(!strcmp(hostname, "localhost")) {
if((fd = getstreamsocket(AF_INET, errbuf, errbufsize)) == -1)
return NULL;
memset(&in, 0, sizeof(in));
in.sin_family = AF_INET;
in.sin_port = htons(port);
in.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
r = connect(fd, (struct sockaddr *)&in, sizeof(struct sockaddr_in));
} else {
#if defined(__APPLE__)
herr = 0;
tmphstbuf = NULL; /* free NULL is a nop */
/* TODO: AF_INET6 */
hp = gethostbyname(hostname);
if(hp == NULL)
herr = h_errno;
#else
hstbuflen = 1024;
tmphstbuf = malloc(hstbuflen);
while((res = gethostbyname_r(hostname, &hostbuf, tmphstbuf, hstbuflen,
&hp, &herr)) == ERANGE) {
hstbuflen *= 2;
tmphstbuf = realloc(tmphstbuf, hstbuflen);
}
#endif
if(herr != 0) {
switch(herr) {
case HOST_NOT_FOUND:
errtxt = "Unknown host";
break;
case NO_ADDRESS:
errtxt = "The requested name is valid but does not have an IP address";
break;
case NO_RECOVERY:
errtxt = "A non-recoverable name server error occurred";
break;
case TRY_AGAIN:
errtxt = "A temporary error occurred on an authoritative name server";
break;
default:
errtxt = "Unknown error";
break;
}
snprintf(errbuf, errbufsize, "%s", errtxt);
free(tmphstbuf);
return NULL;
} else if(hp == NULL) {
snprintf(errbuf, errbufsize, "Resolver internal error");
free(tmphstbuf);
return NULL;
}
if((fd = getstreamsocket(hp->h_addrtype, errbuf, errbufsize)) == -1) {
free(tmphstbuf);
return NULL;
}
switch(hp->h_addrtype) {
case AF_INET:
memset(&in, 0, sizeof(in));
in.sin_family = AF_INET;
in.sin_port = htons(port);
memcpy(&in.sin_addr, hp->h_addr_list[0], sizeof(struct in_addr));
r = connect(fd, (struct sockaddr *)&in, sizeof(struct sockaddr_in));
break;
case AF_INET6:
memset(&in6, 0, sizeof(in6));
in6.sin6_family = AF_INET6;
in6.sin6_port = htons(port);
memcpy(&in6.sin6_addr, hp->h_addr_list[0], sizeof(struct in6_addr));
r = connect(fd, (struct sockaddr *)&in, sizeof(struct sockaddr_in6));
break;
default:
snprintf(errbuf, errbufsize, "Invalid protocol family");
free(tmphstbuf);
return NULL;
}
free(tmphstbuf);
}
if(r == -1) {
if(errno == EINPROGRESS) {
struct pollfd pfd;
pfd.fd = fd;
pfd.events = POLLOUT;
pfd.revents = 0;
r = poll(&pfd, 1, timeout);
if(r == 0) {
/* Timeout */
snprintf(errbuf, errbufsize, "Connection attempt timed out");
close(fd);
return NULL;
}
if(r == -1) {
snprintf(errbuf, errbufsize, "poll() error: %s", strerror(errno));
close(fd);
return NULL;
}
getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&err, &errlen);
} else {
err = errno;
}
} else {
err = 0;
}
if(err != 0) {
snprintf(errbuf, errbufsize, "%s", strerror(err));
close(fd);
return NULL;
}
fcntl(fd, F_SETFL, fcntl(fd, F_GETFL) & ~O_NONBLOCK);
val = 1;
setsockopt(fd, IPPROTO_TCP, TCP_NODELAY, &val, sizeof(val));
tcpcon_t *tc = calloc(1, sizeof(tcpcon_t));
tc->fd = fd;
htsbuf_queue_init(&tc->spill, 0);
if(ssl) {
#if ENABLE_OPENSSL
if(showtime_ssl_ctx != NULL) {
char errmsg[120];
if((tc->ssl = SSL_new(showtime_ssl_ctx)) == NULL) {
ERR_error_string(ERR_get_error(), errmsg);
snprintf(errbuf, errlen, "SSL: %s", errmsg);
tcp_close(tc);
return NULL;
}
if(SSL_set_fd(tc->ssl, tc->fd) == 0) {
ERR_error_string(ERR_get_error(), errmsg);
snprintf(errbuf, errlen, "SSL fd: %s", errmsg);
tcp_close(tc);
return NULL;
}
if(SSL_connect(tc->ssl) <= 0) {
ERR_error_string(ERR_get_error(), errmsg);
snprintf(errbuf, errlen, "SSL connect: %s", errmsg);
tcp_close(tc);
return NULL;
}
SSL_set_mode(tc->ssl, SSL_MODE_AUTO_RETRY);
tc->read = ssl_read;
tc->write = ssl_write;
} else
#elif ENABLE_POLARSSL
if(1) {
tc->ssl = malloc(sizeof(ssl_context));
if(ssl_init(tc->ssl)) {
snprintf(errbuf, errlen, "SSL failed to initialize");
close(fd);
free(tc->ssl);
free(tc);
return NULL;
}
tc->ssn = malloc(sizeof(ssl_session));
tc->hs = malloc(sizeof(havege_state));
havege_init(tc->hs);
memset(tc->ssn, 0, sizeof(ssl_session));
ssl_set_endpoint(tc->ssl, SSL_IS_CLIENT );
ssl_set_authmode(tc->ssl, SSL_VERIFY_NONE );
ssl_set_rng(tc->ssl, havege_rand, tc->hs );
ssl_set_bio(tc->ssl, net_recv, &tc->fd, net_send, &tc->fd);
ssl_set_ciphers(tc->ssl, ssl_default_ciphers );
ssl_set_session(tc->ssl, 1, 600, tc->ssn );
tc->read = polarssl_read;
tc->write = polarssl_write;
} else
#endif
{
snprintf(errbuf, errlen, "SSL not supported");
tcp_close(tc);
return NULL;
}
} else {
tc->read = tcp_read;
tc->write = tcp_write;
}
return tc;
}
/**
*
*/
void
tcp_close(tcpcon_t *tc)
{
#if ENABLE_OPENSSL
if(tc->ssl != NULL) {
SSL_shutdown(tc->ssl);
SSL_free(tc->ssl);
}
#endif
#if ENABLE_POLARSSL
if(tc->ssl != NULL) {
ssl_close_notify(tc->ssl);
ssl_free(tc->ssl);
free(tc->ssl);
free(tc->ssn);
free(tc->hs);
}
#endif
close(tc->fd);
htsbuf_queue_flush(&tc->spill);
free(tc);
}
void
tcp_shutdown(tcpcon_t *tc)
{
shutdown(tc->fd, SHUT_RDWR);
}
/**
*
*/
void
tcp_huge_buffer(tcpcon_t *tc)
{
int v = 192 * 1024;
if(setsockopt(tc->fd, SOL_SOCKET, SO_RCVBUF, &v, sizeof(v)) == -1)
TRACE(TRACE_ERROR, "TCP", "Unable to increase RCVBUF");
}
/**
*
*/
netif_t *
net_get_interfaces(void)
{
struct ifaddrs *ifa_list, *ifa;
struct netif *ni, *n;
int num = 0;
if(getifaddrs(&ifa_list) != 0) {
TRACE(TRACE_ERROR, "net", "getifaddrs failed: %s", strerror(errno));
return NULL;
}
for(ifa = ifa_list; ifa != NULL; ifa = ifa->ifa_next)
num++;
n = ni = calloc(1, sizeof(struct netif) * (num + 1));
for(ifa = ifa_list; ifa != NULL; ifa = ifa->ifa_next) {
if((ifa->ifa_flags & (IFF_UP | IFF_LOOPBACK)) != IFF_UP ||
ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
continue;
n->ipv4 = ntohl(((struct sockaddr_in *)ifa->ifa_addr)->sin_addr.s_addr);
if(n->ipv4 == 0)
continue;
snprintf(n->ifname, sizeof(n->ifname), "%s", ifa->ifa_name);
n++;
}
freeifaddrs (ifa_list);
return ni;
}
/**
* Called from code in arch/
*/
void
net_initialize(void)
{
#if ENABLE_OPENSSL
SSL_library_init();
SSL_load_error_strings();
showtime_ssl_ctx = SSL_CTX_new(SSLv23_client_method());
int i, n = CRYPTO_num_locks();
ssl_locks = malloc(sizeof(pthread_mutex_t) * n);
for(i = 0; i < n; i++)
pthread_mutex_init(&ssl_locks[i], NULL);
CRYPTO_set_locking_callback(ssl_lock_fn);
CRYPTO_set_id_callback(ssl_tid_fn);
#endif
}
| gpl-3.0 |
mashiqi/lasso | Adaboost_mashqi_version-1.0/Adaboost_mashiqi_cpp.cpp | 1 | 23527 | #include "mex.h"
#include "matrix.h"
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <algorithm>
#include <math.h>
using std::vector;
// macro definition
#define XX(i,j) X_Pointer[(i)+(j)*nSample]
#define YY(i) y_Pointer[(i)]
// construct the tree structure
typedef struct tree{
int index; // indicate making stump by which index
double threshold; // threshold for making hyperplane
double direction; // We mark these entries that less than threshold as on the left branch, otherwise are on the right branch.
// If(direction==-1), then the entries on the left are predicted -1, right are 1;
// If(direction== 1), then the entries on the right are predicted -1, left are 1;
double leftIsLeaf, rightIsLeaf; // 0:non-leaf, 1:leaf
double leftPrediction, rightPrediction; // if(is leaf), there will be some prediction value
struct tree *nextLeftTree, *nextRightTree; // if(isn't leaf), there will be pointers to subtree
} treeStruct;
// construct the output structure for the Adaboost function
typedef struct AdaboostOutput{
vector<treeStruct> tree; // the regression tree
vector<double> beta; // the coefficient of every Adaboost weak tree
vector< vector<double> > weight; // every nth column of variable 'weight' is a weight vector for the nth tree
vector<double> trainingError; // the training error
vector<double> exponentialLoss; // the exponential loss
} AdaboostOutputStruct;
// function declaration
AdaboostOutputStruct Adaboost_mashiqi( vector< vector<double> > X,
vector<double> y,
int nSample,
int nPredictor,
int stairNumber,
int treeNumber,
double epsTolerance,
bool printInfo,
bool printFigure,
double stopReason);
vector<double> RegressFunction( vector<double> x,
double threshold,
double direction);
void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[])
/*
// Adaboost algorithm, MATLAB/C++ interface 'mexFunction' function.
//
//
// AUTHOR - Shiqi Ma (mashiqi01@gmail.com, http://mashiqi.github.io/)
// DATE - 02/07/2015
// VERSION - 1.0
//
//
// There should be some instructions. Coming soon!
//
//
// INPUT ARGUMENTS:
//
// nlhs the arguments number of inputs
//
// nrhs the arguments number of outputs
//
// prhs[0] X
//
// prhs[1] y
//
// prhs[2] options
// |---.(int)maxIteration - the maximum number of algorithm iterations
// |---.(int)stairNumber - stair number
// |---.(int)treeNumber - maximum tree number
// |---.(double)epsTolerance - the tolerance threshold
// |---.(bool)printInfo - flag indicating whether to show algorithm's detail information
// |---.(bool)printFigure - flag indicating whether to show figures
// |---.(int)stopReason - algorithm stop reasons:
// 0 - initial value;
// 1 - convergence reached;
// 2 - maxIteration reached;
//
//
// OUTPUT ARGUMENTS:
//
// plhs[0] (treeStruct)tree // the regression tree
// |---.(vector<double>)index; // indicate making stump by which index
// |---.(vector<double>)threshold; // threshold for making hyperplane
// |---.(vector<double>)direction; // If(direction== 1(-1)), the entries on the left are predicted as -1(1), right are 1(-1)
// |---.(vector<double>)leftIsLeaf, rightIsLeaf; // 0:non-leaf, 1:leaf
// |---.(vector<double>)leftPrediction, rightPrediction; // if(is leaf), there will be some prediction value
// |---.(vector<treeStruct>)*nextLeftTree, *nextRightTree; // if(isn't leaf), there will be pointers to subtree
//
// plhs[1] (vector<double>)beta // the coefficient of every Adaboost weak tree
//
// plhs[2] (vector< vector<double> >)weight // every nth column of variable 'weight' is a weight vector for the nth tree
//
// plhs[3] (vector<double>)trainingError // the training error
//
// plhs[4] (vector<double>)exponentialLoss // the exponential loss
//
//
// EXAMPLE:
//
// This function do not have an example.
//
//
// REFERENCE:
//
// [1] http://www.mathworks.com/matlabcentral/fileexchange/42130-boosted-binary-regression-trees
*/
{
// ------------------------ Check for proper number of input and output arguments ---------------- //
if (nrhs != 3) {
mexErrMsgIdAndTxt("struct:nrhs", "Three inputs required.");
} else if (nlhs != 5) {
mexErrMsgIdAndTxt("struct:nlhs", "Five outputs required.");
} else if (!mxIsStruct(prhs[2])) {
mexErrMsgIdAndTxt("struct:wrongType", "Third input must be a structure.");
}
// ------------------------ Convert arguments to a C/C++ friendly format ------------------------ //
// get the dimensional information
int nSample = mxGetM( prhs[0] );
int nPredictor = mxGetN( prhs[0] );
// convert X and y to double type
double* X_Pointer = (double*)mxGetData( prhs[0] );
double* y_Pointer = (double*)mxGetData( prhs[1] );
vector< vector<double> > X(nSample);
vector<double> y(nSample);
for( int iSample = 0; iSample < nSample; iSample++ ) {
vector<double> iRow(nPredictor);
for( int iPredictor = 0; iPredictor < nPredictor; iPredictor++ ) {
iRow[iPredictor] = XX(iSample,iPredictor);
}
X[iSample] = iRow;
y[iSample] = YY(iSample);
}
// stair number
double *pStairNumber; pStairNumber = (double*)mxGetData(mxGetField( prhs[2], 0, "stairNumber"));
int stairNumber = (int)pStairNumber[0]; pStairNumber = NULL;
if(stairNumber <= 1) {
mexPrintf("%s%d\n", "stairNumber: ", stairNumber);
mexErrMsgTxt("stair number should greater than 1!");
}
// maximum tree number
double *pTreeNumber; pTreeNumber = (double*)mxGetData(mxGetField( prhs[2], 0, "treeNumber"));
int treeNumber = (int)pTreeNumber[0]; pTreeNumber = NULL;
// the tolerance threshold
double *pEpsTolerance; pEpsTolerance = (double*)mxGetData(mxGetField( prhs[2], 0, "epsTolerance"));
double epsTolerance = pEpsTolerance[0]; pEpsTolerance = NULL;
// flag indicating whether to show algorithm's detail information
bool *pPrintInfo; pPrintInfo = (bool*)mxGetData(mxGetField( prhs[2], 0, "printInfo"));
bool printInfo = pPrintInfo[0]; pPrintInfo = NULL;
// flag indicating whether to show figures
bool *pPrintFigure; pPrintFigure = (bool*)mxGetData(mxGetField( prhs[2], 0, "printFigure"));
bool printFigure = pPrintFigure[0]; pPrintFigure = NULL;
// algorithm stop reasons:
// 0 - initial value;
// 1 - convergence reached;
// 2 - maxIteration reached;
double *pStopReason; pStopReason = (double*)mxGetData(mxGetField( prhs[2], 0, "stopReason"));
double stopReason = (int)pStopReason[0]; pStopReason = NULL;
// ------------------------ true function applys ------------------------------------------------ //
AdaboostOutputStruct adaboostOutput;
adaboostOutput = Adaboost_mashiqi( X,
y,
nSample,
nPredictor,
stairNumber, // stair number
treeNumber, // maximum tree number
epsTolerance, // the tolerance threshold
printInfo, // flag indicating whether to show algorithm's detail information
printFigure, // flag indicating whether to show figures
stopReason); // algorithm stop reasons
// ------------------------ Convert arguments to a MATLAB friendly format ------------------------ //
/////////////////// for output arguments [1]: tree ///////////////////
vector<treeStruct> tempTreeVector(adaboostOutput.tree);
const char **fnames; /* pointers to field names */
const char *fieldname = "index";
mxArray *pMxArray;
int countOfField = 0;
fnames = (const char **) mxCalloc(1, sizeof(*fnames));
fnames = &fieldname;
plhs[0] = mxCreateStructMatrix(1, 1, 1, fnames);
mxFree((void *)fnames);
// for tree.index
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxINT32_CLASS, mxREAL);
int *pTreeIndex = (int*)mxGetData(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pTreeIndex[iTree] = (tempTreeVector[iTree]).index + 1;
}
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: index*/, pMxArray);
// for tree.threshold
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *pTreeThreshold = mxGetPr(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pTreeThreshold[iTree] = (tempTreeVector[iTree]).threshold;
}
fieldname = "threshold";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: threshold*/, pMxArray);
// for tree.direction
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *pTreeDirection = mxGetPr(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pTreeDirection[iTree] = (tempTreeVector[iTree]).direction;
}
fieldname = "direction";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: direction*/, pMxArray);
// for tree.leftIsLeaf
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *pLeftIsLeaf = mxGetPr(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pLeftIsLeaf[iTree] = (tempTreeVector[iTree]).leftIsLeaf;
}
fieldname = "leftIsLeaf";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: direction*/, pMxArray);
// for tree.rightIsLeaf
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *pRightIsLeaf = mxGetPr(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pRightIsLeaf[iTree] = (tempTreeVector[iTree]).rightIsLeaf;
}
fieldname = "rightIsLeaf";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: direction*/, pMxArray);
// for tree.leftPrediction
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *pLeftPrediction = mxGetPr(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pLeftPrediction[iTree] = (tempTreeVector[iTree]).leftPrediction;
}
fieldname = "leftPrediction";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: leftPrediction*/, pMxArray);
// for tree.rightPrediction
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *pRightPrediction = mxGetPr(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pRightPrediction[iTree] = (tempTreeVector[iTree]).rightPrediction;
}
fieldname = "rightPrediction";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: rightPrediction*/, pMxArray);
// for tree.nextLeftTree
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
treeStruct *pNextLeftTree = (treeStruct*)mxGetData(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pNextLeftTree = NULL;
pNextLeftTree++;
}
fieldname = "nextLeftTree";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: nextLeftTree*/, pMxArray);
// for tree.nextRightTree
pMxArray = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
treeStruct *pNextRightTree = (treeStruct*)mxGetData(pMxArray);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
pNextRightTree = NULL;
pNextRightTree++;
}
fieldname = "nextRightTree";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: nextRightTree*/, pMxArray);
// for tree.treeNumber
pMxArray = mxCreateNumericMatrix(1, 1, mxINT32_CLASS, mxREAL);
int *int_pTreeNumber = (int*)mxGetData(pMxArray);
int_pTreeNumber[0] = treeNumber;
fieldname = "treeNumber";
mxAddField(plhs[0], fieldname); // add field name
mxSetFieldByNumber( plhs[0], 0, countOfField++/*field: treeNumber*/, pMxArray);
/////////////////// for output arguments [2]: beta ///////////////////
plhs[1] = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *p1 = mxGetPr(plhs[1]);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
p1[iTree] = adaboostOutput.beta[iTree];
}
/////////////////// for output arguments [3]: weight ///////////////////
plhs[2] = mxCreateNumericMatrix(nSample, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *p2 = mxGetPr(plhs[2]);
for( int iTree = 0; iTree != treeNumber; iTree++ ) {
for( int iSample = 0; iSample != nSample; iSample++ ) {
p2[iSample+iTree*nSample] = adaboostOutput.weight[iTree][iSample];
}
}
/////////////////// for output arguments [4]: trainingError ///////////////////
plhs[3] = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *p3 = mxGetPr(plhs[3]);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
p3[iTree] = adaboostOutput.trainingError[iTree];
}
/////////////////// for output arguments [5]: exponentialLoss ///////////////////
plhs[4] = mxCreateNumericMatrix(1, treeNumber, mxDOUBLE_CLASS, mxREAL);
double *p4 = mxGetPr(plhs[4]);
for ( int iTree = 0; iTree < treeNumber; iTree++ ) {
p4[iTree] = adaboostOutput.exponentialLoss[iTree];
}
}
AdaboostOutputStruct Adaboost_mashiqi( vector< vector<double> > X,
vector<double> y,
int nSample,
int nPredictor,
int stairNumber,
int treeNumber,
double epsTolerance,
bool printInfo,
bool printFigure,
double stopReason)
/*
// Adaboost algorithm.
//
//
// AUTHOR - Shiqi Ma (mashiqi01@gmail.com, http://mashiqi.github.io/)
// DATE - 02/07/2015
// VERSION - 1.0
//
//
// There should be some instructions. Coming soon!
//
//
// INPUT ARGUMENTS:
//
// X - X
//
// y - y
//
// nSample - number of samples
//
// nPredictor - number of predictors
//
// stairNumber - stair number
//
// treeNumber - maximum tree number
//
// epsTolerance - the tolerance threshold
//
// printInfo - flag indicating whether to show algorithm's detail information
//
// printFigure - flag indicating whether to show figures
//
// stopReason - algorithm stop reasons
//
//
// OUTPUT ARGUMENTS:
//
// adaboostOutput
// |---.(vector<treeStruct>)tree // the regression tree
// | |---.(int)index; // indicate making stump by which index
// | |---.(double)threshold; // threshold for making hyperplane
// | |---.(double)direction; // We mark these entries that less than threshold as on the left branch, otherwise are on the right branch.
// | // If(direction== 1), then the entries on the left are predicted -1, right are 1;
// | // If(direction==-1), then the entries on the left are predicted 1, right are -1;
// | |---.(double)leftIsLeaf, rightIsLeaf; // 0:non-leaf, 1:leaf
// | |---.(double)leftPrediction, rightPrediction; // if(is leaf), there will be some prediction value
// | |---.(treeStruct)*nextLeftTree, *nextRightTree; // if(isn't leaf), there will be pointers to subtree
// |
// |---.(vector<double>)beta // the coefficient of every Adaboost weak tree
// |---.(vector< vector<double> >)weight // every nth column of variable 'weight' is a weight vector for the nth tree
// |---.(vector<double>)trainingError // the training error
// |---.(vector<double>)exponentialLoss // the exponential loss
//
//
// EXAMPLE:
//
// This function do not have an example.
//
//
// REFERENCE:
//
// [1] Hastie, Trevor, et al. The elements of statistical learning. Vol.
// 2. No. 1. New York: Springer, 2009.
*/
{
// initialization
vector<treeStruct> AdaboostTree( treeNumber );
vector<double> columnOfX(nSample);
vector<double> beta(treeNumber);
vector<double> columnOfWeight(nSample);
vector<double> nPrediction(nSample,0);
vector<double> prediction(nSample,0);
vector<double> trainingError( treeNumber, 0);
vector<double> exponentialLoss( treeNumber, 0);
double errorValOpt;
vector<double> nPredictionOpt(nSample,0);
int indexOpt;
double thresholdOpt;
double directionOpt;
double leftIsLeafOpt, rightIsLeafOpt;
double leftPredictionOpt, rightPredictionOpt;
treeStruct *nextLeftTreeOpt, *nextRightTreeOpt;
double rangeMin, rangeMax, stairSize;
std::vector<double> candidateThreshold(stairNumber);
double threshold;
double direction;
double errorVal;
double sumWeight;
// initialize the weight matrix
vector< vector<double> > weight( treeNumber+1 );
{
vector<double> iColumn(nSample, 1.0/((double)nSample) );
weight[0] = iColumn;
}
for( int iTree = 1; iTree != treeNumber+1; iTree++ ) {
vector<double> iColumn(nSample,0);
weight[iTree] = iColumn;
}
AdaboostOutputStruct adaboostOutput;
adaboostOutput.tree = AdaboostTree;
adaboostOutput.beta = beta;
adaboostOutput.weight = weight;
adaboostOutput.trainingError = trainingError;
adaboostOutput.exponentialLoss = exponentialLoss;
// Adaboost algorithm begins
for( int iTree = 0; iTree != treeNumber; iTree++ ) {
if(printInfo) {
mexPrintf("treeNumber = %d \t iTree = %d\n",treeNumber,iTree);
}
errorValOpt = DBL_MAX;
// compute the stump
for( int index = 0; index != nPredictor; index++ ) {
// extract column of X
for( int i = 0; i != nSample; i++ ) {
columnOfX[i] = X[i][index];
}
// compute the value range of this column of X
rangeMin = *min_element(columnOfX.begin(),columnOfX.end());
rangeMax = *max_element(columnOfX.begin(),columnOfX.end());
stairSize = (rangeMax - rangeMin) / (stairNumber - 1);
// compute the candidate threshold according the stair number and the min/max of x
for( int i = 0; i != stairNumber; i++ ) {
candidateThreshold[i] = rangeMin + stairSize*i;
}
candidateThreshold[0] -= 0.1;
candidateThreshold[stairNumber-1] += 0.1;
//make split according to these candidate threshold values
for(int j = 0; j != stairNumber ; j++) {
threshold = candidateThreshold[j];
direction = -1;
for(; direction <= 1; direction += 2 ) {
// make prediction
nPrediction = RegressFunction( columnOfX, threshold, direction );
// now compute training error
errorVal = 0;
for( int i = 0; i != nSample; i++ ) {
if( nPrediction[i] != y[i] )
errorVal += weight[iTree][i];
}
// store optimal tree information
if( errorVal < errorValOpt ) {
errorValOpt = errorVal;
nPredictionOpt = nPrediction;
indexOpt = index;
thresholdOpt = threshold;
directionOpt = direction;
leftIsLeafOpt = 1;
rightIsLeafOpt = 1;
nextLeftTreeOpt = NULL;
nextRightTreeOpt = NULL;
if(direction == -1) {
leftPredictionOpt = -1;
rightPredictionOpt = 1;
}
else {
leftPredictionOpt = 1;
rightPredictionOpt = -1;
}
}
}
}
}
// store the nth tree
AdaboostTree[iTree].index = indexOpt;
AdaboostTree[iTree].threshold = thresholdOpt;
AdaboostTree[iTree].direction = directionOpt;
AdaboostTree[iTree].leftIsLeaf = leftIsLeafOpt;
AdaboostTree[iTree].rightIsLeaf = rightIsLeafOpt;
AdaboostTree[iTree].nextLeftTree = nextLeftTreeOpt;
AdaboostTree[iTree].nextRightTree = nextRightTreeOpt;
if(directionOpt == -1) {
AdaboostTree[iTree].leftPrediction = leftPredictionOpt;
AdaboostTree[iTree].rightPrediction = rightPredictionOpt;
}
else {
AdaboostTree[iTree].leftPrediction = leftPredictionOpt;
AdaboostTree[iTree].rightPrediction = rightPredictionOpt;
}
// update parameters
// update beta. Please refer to the (10.12) of the reference book.
beta[iTree] = log((1-errorValOpt) / errorValOpt);
// update weight. Please refer to the (10.14) of the reference book.
for(int iSample = 0; iSample != nSample; iSample++ ) {
if( nPredictionOpt[iSample] != y[iSample] )
weight[iTree+1][iSample] = weight[iTree][iSample] * exp(beta[iTree]);
else
weight[iTree+1][iSample] = weight[iTree][iSample];
}
// normalize the weight vector
sumWeight = 0;
for(int i = 0; i != nSample; i++ ) {
sumWeight += weight[iTree+1][i];
}
for(int i = 0; i != nSample; i++ ) {
weight[iTree+1][i] = weight[iTree+1][i]/sumWeight;
}
// make prediction
for(int i = 0; i != nSample; i++ ) {
prediction[i] += beta[iTree]*nPredictionOpt[i];
}
for(int i = 0; i != nSample; i++ ) {
if( !( (y[i]>0 && prediction[i]>0) || (y[i]<0 && prediction[i]<0) || (y[i]==0 && prediction[i]==0) ) )
// execute the following line when signs are not equal
trainingError[iTree]++;
}
trainingError[iTree] = trainingError[iTree] / nSample;
for(int i = 0; i != nSample; i++ ) {
exponentialLoss[iTree] += exp(-y[i]*prediction[i]);
}
exponentialLoss[iTree] = exponentialLoss[iTree] / nSample;
// store results to the output structure
adaboostOutput.tree[iTree] = AdaboostTree[iTree];
adaboostOutput.beta[iTree] = beta[iTree];
for(int i = 0; i != nSample; i++ ) {
columnOfWeight[i] = weight[iTree][i];
}
adaboostOutput.weight[iTree] = columnOfWeight;
adaboostOutput.trainingError[iTree] = trainingError[iTree];
adaboostOutput.exponentialLoss[iTree] = exponentialLoss[iTree];
}
return adaboostOutput;
}
vector<double> RegressFunction( vector<double> x,
double threshold,
double direction)
/*
// Regression function for Adaboost algorithm.
//
//
// AUTHOR - Shiqi Ma (mashiqi01@gmail.com, http://mashiqi.github.io/)
// DATE - 02/07/2015
// VERSION - 1.0
//
//
// There should be some instructions. Coming soon!
//
//
// INPUT ARGUMENTS:
//
// x - the vertical vector
//
// threshold - should be a scalar
//
// direction - should be the same length as "x"
//
//
// OUTPUT ARGUMENTS:
//
// yHat - prediction
//
//
// EXAMPLE:
//
// This function do not have an example.
//
//
// REFERENCE:
//
// [1] Hastie, Trevor, et al. The elements of statistical learning. Vol.
// 2. No. 1. New York: Springer, 2009.
*/
{
// initialization
int nSample = x.size();
std::vector<double> yHat(nSample,1); // initialize all entries of yHat to 1
double error_IfRightIs1 = 0, error_IfLeftIs1 = 0;
if(direction == 1) {
for(int i = 0; i != nSample; i++ ) {
if(x[i] < threshold)
yHat[i] = -1;
}
}
else {
for(int i = 0; i != nSample; i++ ) {
if(x[i] > threshold)
yHat[i] = -1;
}
}
return yHat;
} | gpl-3.0 |
3dyne/3dyne_legacy_tools | util/imgtools/tga2arr.c | 1 | 6694 | /*
* 3dyne Legacy Tools GPL Source Code
*
* Copyright (C) 1996-2012 Matthias C. Berger & Simon Berger.
*
* This file is part of the 3dyne Legacy Tools GPL Source Code ("3dyne Legacy
* Tools Source Code").
*
* 3dyne Legacy Tools Source Code is free software: you can redistribute it
* and/or modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* 3dyne Legacy Tools Source Code is distributed in the hope that it will be
* useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details.
*
* You should have received a copy of the GNU General Public License along with
* 3dyne Legacy Tools Source Code. If not, see <http://www.gnu.org/licenses/>.
*
* In addition, the 3dyne Legacy Tools Source Code is also subject to certain
* additional terms. You should have received a copy of these additional terms
* immediately following the terms and conditions of the GNU General Public
* License which accompanied the 3dyne Legacy Tools Source Code.
*
* Contributors:
* Matthias C. Berger (mcb77@gmx.de) - initial API and implementation
* Simon Berger (simberger@gmail.com) - initial API and implementation
*/
// tga242arr.c
// log:
// 1.11.98 : big change from P8 to RGB565
#include <stdio.h>
#include <sys/types.h>
#include "arr.h"
#include "tga.h"
#include "pal.h"
#include "shock.h"
#include "cmdpars.h"
#include "cdb_service.h"
void PrintUsage()
{
printf( "usage: tga242arr -t tga -a arr -p pal [ -i ident ] [ --rgb565 ]\n" );
}
unsigned short RGB888ToRGB565( rgb_t *rgb )
{
unsigned short c,r,g,b;
r = rgb->red;
r>>=3;
g = rgb->green;
g>>=2;
b = rgb->blue;
b>>=3;
r<<=11;
g<<=5;
c = r | b | g;
return c;
}
void main( int argc, char* argv[] )
{
u_int32_t i, i2, arrcount;
int x, y, xs, ys, xh, yh;
char dumpheaders = 0;
char* tganame;
char* arrname;
char* palname;
char* arrident;
char* arrnext;
char* arrmode;
int reducemode;
int mm;
int ts, td;
int pixels;
int rsum, gsum, bsum;
int x2, y2;
int blur;
FILE* tgahandle;
FILE* arrhandle;
FILE* palhandle;
pal_t* pal = NULL;
tga_t* tga[2];
arr_t* arr;
rgb_t rgb;
dumpheaders = CheckCmdSwitch( "-d", argc, argv );
palname = GetCmdOpt( "-p", argc, argv );
tganame = GetCmdOpt( "-t", argc, argv );
if( tganame == NULL )
{
printf( "no tga given.\n" );
PrintUsage();
exit( 0 );
}
if ( CheckCmdSwitch( "--rgb565", argc, argv ) )
{
reducemode = ARR_F_RGB565;
}
else
{
reducemode = ARR_F_P8;
}
arrident = GetCmdOpt( "-i", argc, argv );
if( arrident == NULL )
__warning( "no arr ident given.\n" );
else if( strlen( arrident ) >= 32 )
arrident[31] = '\0';
printf( "tga: %s\n", tganame );
tgahandle = fopen( tganame, "rb" );
CHKPTR( tgahandle );
tga[0] = TGA_Read( tgahandle );
CHKPTR( tga[0] );
// TGA_Dump( tga[0] );
fclose( tgahandle );
if( dumpheaders )
TGA_Dump( tga[0] );
tga[1] = TGA_Create( tga[0]->image_width/*/2*/, tga[0]->image_height/*/2*/, TGA_TYPE_TRUECOLOR );
__chkptr( tga[1] );
arrname = GetCmdOpt( "-a", argc, argv );
if( arrname == NULL )
{
printf( "no arr given.\n" );
PrintUsage();
exit( 0 );
}
printf( "arr: %s\n", arrname );
switch( tga[0]->image_type )
{
case TGA_TYPE_TRUECOLOR:
printf( "tga is 24bit.\n" );
if( palname == NULL )
{
CDB_StartUp( 0 );
palname = CDB_GetString( "misc/default_pal" );
if( palname == NULL )
{
PrintUsage();
__error( "no pal found.\n" );
}
}
printf( "pal: %s\n", palname );
palhandle = fopen( palname, "rb" );
CHKPTR( palhandle );
pal = PAL_Read( palhandle );
CHKPTR( pal );
fclose( palhandle );
arr = ARR_Create( tga[0]->image_width, tga[0]->image_height, 4, 1, arrident, reducemode );
CHKPTR( arr );
printf( "reducing color. " );
xs = tga[0]->image_width;
ys = tga[0]->image_height;
arrcount = 0;
for ( mm = 0; mm < 4; mm++ ) {
ts = mm & 1;
td = (mm+1) & 1;
// printf("%d->%d\n",ts,td);
// reduce
// printf(" i: %d, x: %d, y: %d\n", mm, xs, ys );
pixels = xs * ys;
for( i = 0; i < pixels; i++ )
{
rgb.red = tga[ts]->image.red[i];
rgb.green = tga[ts]->image.green[i];
rgb.blue = tga[ts]->image.blue[i];
if ( reducemode == ARR_F_P8 )
arr->data[arrcount++] = PAL_ReduceColor( pal, &rgb );
else
{
*((unsigned short*)(&arr->data[arrcount])) = RGB888ToRGB565( &rgb );
arrcount+=2;
}
if( (i & 0xff) == 0 )
{
printf( "." );
fflush( stdout );
}
}
if ( mm == 3 )
break;
// mipmap
xh = xs / 2;
yh = ys / 2;
if ( xh < 4 || yh < 4 )
blur = 0;
else
blur = 1;
for ( y = 0; y < yh; y++ ) {
for ( x = 0; x < xh; x++ ) {
x2 = x*2;
y2 = y*2;
if ( blur )
{
rsum = tga[ts]->image.red[ y2*xs + x2 ];
gsum = tga[ts]->image.green[ y2*xs + x2 ];
bsum = tga[ts]->image.blue[ y2*xs + x2 ];
rsum += tga[ts]->image.red[ y2*xs + (x2+1) ];
gsum += tga[ts]->image.green[ y2*xs + (x2+1) ];
bsum += tga[ts]->image.blue[ y2*xs + (x2+1) ];
rsum += tga[ts]->image.red[ (y2+1)*xs + x2 ];
gsum += tga[ts]->image.green[ (y2+1)*xs + x2 ];
bsum += tga[ts]->image.blue[ (y2+1)*xs + x2 ];
rsum += tga[ts]->image.red[ (y2+1)*xs + (x2+1) ];
gsum += tga[ts]->image.green[ (y2+1)*xs + (x2+1) ];
bsum += tga[ts]->image.blue[ (y2+1)*xs + (x2+1) ];
tga[td]->image.red[ y*xh + x ] = rsum / 4;
tga[td]->image.green[ y*xh + x ] = gsum / 4;
tga[td]->image.blue[ y*xh + x ] = bsum / 4;
}
else
{
rsum = tga[ts]->image.red[ y2*xs + x2 ];
gsum = tga[ts]->image.green[ y2*xs + x2 ];
bsum = tga[ts]->image.blue[ y2*xs + x2 ];
tga[td]->image.red[ y*xh + x ] = 255; //rsum;
tga[td]->image.green[ y*xh + x ] = 0;//gsum;
tga[td]->image.blue[ y*xh + x ] = 0; //bsum;
}
}
}
xs = xh;
ys = yh;
}
printf( "\n" );
break;
/*
case TGA_TYPE_INDEXED:
printf( "tga is indexed./n" );
arr = ARR_Create( tga->image_width, tga->image_height, 1, arr_ident, NULL );
CHKPTR( arr );
printf( "copying ...\n" );
memcpy( arr->data, tga->image_indexed.data, tga->image_indexed.bytes );
break;
*/
default:
__error( "we need an uncompressed 24(/8)bit tga.\n" );
ARR_Free( arr );
break;
}
arrhandle = fopen( arrname, "wb" );
CHKPTR( arrhandle );
ARR_Write( arrhandle, arr );
fclose( arrhandle );
}
| gpl-3.0 |
KuehnhammerTobias/ioqw | code/client/snd_codec_opus.c | 1 | 12055 | /*
=======================================================================================================================================
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
Copyright (C) 2005 Stuart Dalton (badcdev@gmail.com).
Copyright (C) 2005-2006 Joerg Dietrich <dietrich_joerg@gmx.de>.
This file is part of Spearmint Source Code.
Spearmint Source Code is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version.
Spearmint Source Code is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
You should have received a copy of the GNU General Public License along with Spearmint Source Code.
If not, see <http://www.gnu.org/licenses/>.
In addition, Spearmint Source Code is also subject to certain additional terms. You should have received a copy of these additional
terms immediately following the terms and conditions of the GNU General Public License. If not, please request a copy in writing from
id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o
ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
=======================================================================================================================================
*/
// Ogg Opus support is enabled by this define
#ifdef USE_CODEC_OPUS
// includes for the Q3 sound system
#include "client.h"
#include "snd_codec.h"
// includes for the Ogg Opus codec
#include <errno.h>
#include <opusfile.h>
// samples are 16 bit
#define OPUS_SAMPLEWIDTH 2
// Q3 Ogg Opus codec
snd_codec_t opus_codec = {
"opus",
S_OggOpus_CodecLoad,
S_OggOpus_CodecOpenStream,
S_OggOpus_CodecReadStream,
S_OggOpus_CodecCloseStream,
NULL
};
/*
=======================================================================================================================================
Callbacks for opusfile
=======================================================================================================================================
*/
/*
=======================================================================================================================================
S_OggOpus_Callback_read
fread() replacement.
=======================================================================================================================================
*/
int S_OggOpus_Callback_read(void *datasource, unsigned char *ptr, int size) {
snd_stream_t *stream;
int bytesRead = 0;
// check if input is valid
if (!ptr) {
errno = EFAULT;
return -1;
}
if (!size) {
// it's not an error, caller just wants zero bytes!
errno = 0;
return 0;
}
if (size < 0) {
errno = EINVAL;
return -1;
}
if (!datasource) {
errno = EBADF;
return -1;
}
// we use a snd_stream_t in the generic pointer to pass around
stream = (snd_stream_t *)datasource;
// read it with the Q3 function FS_Read()
bytesRead = FS_Read(ptr, size, stream->file);
// update the file position
stream->pos += bytesRead;
return bytesRead;
}
/*
=======================================================================================================================================
S_OggOpus_Callback_seek
fseek() replacement.
=======================================================================================================================================
*/
int S_OggOpus_Callback_seek(void *datasource, opus_int64 offset, int whence) {
snd_stream_t *stream;
int retVal = 0;
// check if input is valid
if (!datasource) {
errno = EBADF;
return -1;
}
// snd_stream_t in the generic pointer
stream = (snd_stream_t *)datasource;
// we must map the whence to its Q3 counterpart
switch (whence) {
case SEEK_SET:
{
// set the file position in the actual file with the Q3 function
retVal = FS_Seek(stream->file, (long)offset, FS_SEEK_SET);
// something has gone wrong, so we return here
if (retVal != 0) {
return retVal;
}
// keep track of file position
stream->pos = (int)offset;
break;
}
case SEEK_CUR:
{
// set the file position in the actual file with the Q3 function
retVal = FS_Seek(stream->file, (long)offset, FS_SEEK_CUR);
// something has gone wrong, so we return here
if (retVal != 0) {
return retVal;
}
// keep track of file position
stream->pos += (int)offset;
break;
}
case SEEK_END:
{
// set the file position in the actual file with the Q3 function
retVal = FS_Seek(stream->file, (long)offset, FS_SEEK_END);
// something has gone wrong, so we return here
if (retVal != 0) {
return retVal;
}
// keep track of file position
stream->pos = stream->length + (int)offset;
break;
}
default:
{
// unknown whence, so we return an error
errno = EINVAL;
return -1;
}
}
// stream->pos shouldn't be smaller than zero or bigger than the filesize
stream->pos = (stream->pos < 0) ? 0 : stream->pos;
stream->pos = (stream->pos > stream->length) ? stream->length : stream->pos;
return 0;
}
/*
=======================================================================================================================================
S_OggOpus_Callback_close
fclose() replacement.
=======================================================================================================================================
*/
int S_OggOpus_Callback_close(void *datasource) {
// we do nothing here and close all things manually in S_OggOpus_CodecCloseStream()
return 0;
}
/*
=======================================================================================================================================
S_OggOpus_Callback_tell
ftell() replacement.
=======================================================================================================================================
*/
opus_int64 S_OggOpus_Callback_tell(void *datasource) {
snd_stream_t *stream;
// check if input is valid
if (!datasource) {
errno = EBADF;
return -1;
}
// snd_stream_t in the generic pointer
stream = (snd_stream_t *)datasource;
return (opus_int64)FS_FTell(stream->file);
}
// the callback structure
const OpusFileCallbacks S_OggOpus_Callbacks = {
&S_OggOpus_Callback_read,
&S_OggOpus_Callback_seek,
&S_OggOpus_Callback_tell,
&S_OggOpus_Callback_close
};
/*
=======================================================================================================================================
S_OggOpus_CodecOpenStream
=======================================================================================================================================
*/
snd_stream_t *S_OggOpus_CodecOpenStream(const char *filename) {
snd_stream_t *stream;
// Opus codec control structure
OggOpusFile *of;
// some variables used to get informations about the file
const OpusHead *opusInfo;
ogg_int64_t numSamples;
// check if input is valid
if (!filename) {
return NULL;
}
// open the stream
stream = S_CodecUtilOpen(filename, &opus_codec);
if (!stream) {
return NULL;
}
// open the codec with our callbacks and stream as the generic pointer
of = op_open_callbacks(stream, &S_OggOpus_Callbacks, NULL, 0, NULL);
if (!of) {
S_CodecUtilClose(&stream);
return NULL;
}
// the stream must be seekable
if (!op_seekable(of)) {
op_free(of);
S_CodecUtilClose(&stream);
return NULL;
}
// get the info about channels and rate
opusInfo = op_head(of, -1);
if (!opusInfo) {
op_free(of);
S_CodecUtilClose(&stream);
return NULL;
}
if (opusInfo->stream_count != 1) {
op_free(of);
S_CodecUtilClose(&stream);
Com_Printf("Only Ogg Opus files with one stream are support\n");
return NULL;
}
if (opusInfo->channel_count != 1 && opusInfo->channel_count != 2) {
op_free(of);
S_CodecUtilClose(&stream);
Com_Printf("Only mono and stereo Ogg Opus files are supported\n");
return NULL;
}
// get the number of sample-frames in the file
numSamples = op_pcm_total(of, -1);
// fill in the info-structure in the stream
stream->info.rate = 48000;
stream->info.width = OPUS_SAMPLEWIDTH;
stream->info.channels = opusInfo->channel_count;
stream->info.samples = numSamples;
stream->info.size = stream->info.samples * stream->info.channels * stream->info.width;
stream->info.dataofs = 0;
// we use stream->pos for the file pointer in the compressed ogg file
stream->pos = 0;
// we use the generic pointer in stream for the opus codec control structure
stream->ptr = of;
return stream;
}
/*
=======================================================================================================================================
S_OggOpus_CodecCloseStream
=======================================================================================================================================
*/
void S_OggOpus_CodecCloseStream(snd_stream_t *stream) {
// check if input is valid
if (!stream) {
return;
}
// let the opus codec cleanup its stuff
op_free((OggOpusFile *)stream->ptr);
// close the stream
S_CodecUtilClose(&stream);
}
/*
=======================================================================================================================================
S_OggOpus_CodecReadStream
=======================================================================================================================================
*/
int S_OggOpus_CodecReadStream(snd_stream_t *stream, int bytes, void *buffer) {
// buffer handling
int samplesRead, samplesLeft, c;
opus_int16 *bufPtr;
// check if input is valid
if (!(stream && buffer)) {
return 0;
}
if (bytes <= 0) {
return 0;
}
samplesRead = 0;
samplesLeft = bytes / stream->info.channels / stream->info.width;
bufPtr = buffer;
if (samplesLeft <= 0) {
return 0;
}
// cycle until we have the requested or all available bytes read
while (-1) {
// read some samples from the opus codec
c = op_read((OggOpusFile *)stream->ptr, bufPtr + samplesRead * stream->info.channels, samplesLeft * stream->info.channels, NULL);
// no more samples are left
if (c <= 0) {
break;
}
samplesRead += c;
samplesLeft -= c;
// we have enough samples
if (samplesLeft <= 0) {
break;
}
}
return samplesRead * stream->info.channels * stream->info.width;
}
/*
=======================================================================================================================================
S_OggOpus_CodecLoad
We handle S_OggOpus_CodecLoad as a special case of the streaming functions where we read the whole stream at once.
=======================================================================================================================================
*/
void *S_OggOpus_CodecLoad(const char *filename, snd_info_t *info) {
snd_stream_t *stream;
byte *buffer;
int bytesRead;
// check if input is valid
if (!(filename && info)) {
return NULL;
}
// open the file as a stream
stream = S_OggOpus_CodecOpenStream(filename);
if (!stream) {
return NULL;
}
// copy over the info
info->rate = stream->info.rate;
info->width = stream->info.width;
info->channels = stream->info.channels;
info->samples = stream->info.samples;
info->size = stream->info.size;
info->dataofs = stream->info.dataofs;
// allocate a buffer
// this buffer must be free-ed by the caller of this function
buffer = Hunk_AllocateTempMemory(info->size);
if (!buffer) {
S_OggOpus_CodecCloseStream(stream);
return NULL;
}
// fill the buffer
bytesRead = S_OggOpus_CodecReadStream(stream, info->size, buffer);
// we don't even have read a single byte
if (bytesRead <= 0) {
Hunk_FreeTempMemory(buffer);
S_OggOpus_CodecCloseStream(stream);
return NULL;
}
S_OggOpus_CodecCloseStream(stream);
return buffer;
}
#endif // USE_CODEC_OPUS
| gpl-3.0 |
HoraceAndTheSpider/amiberry | guisan-dev/src/widgets/window.cpp | 1 | 9916 | /* _______ __ __ __ ______ __ __ _______ __ __
* / _____/\ / /\ / /\ / /\ / ____/\ / /\ / /\ / ___ /\ / |\/ /\
* / /\____\// / // / // / // /\___\// /_// / // /\_/ / // , |/ / /
* / / /__ / / // / // / // / / / ___ / // ___ / // /| ' / /
* / /_// /\ / /_// / // / // /_/_ / / // / // /\_/ / // / | / /
* /______/ //______/ //_/ //_____/\ /_/ //_/ //_/ //_/ //_/ /|_/ /
* \______\/ \______\/ \_\/ \_____\/ \_\/ \_\/ \_\/ \_\/ \_\/ \_\/
*
* Copyright (c) 2004, 2005, 2006, 2007 Olof Naessén and Per Larsson
*
* Js_./
* Per Larsson a.k.a finalman _RqZ{a<^_aa
* Olof Naessén a.k.a jansem/yakslem _asww7!uY`> )\a//
* _Qhm`] _f "'c 1!5m
* Visit: http://guichan.darkbits.org )Qk<P ` _: :+' .' "{[
* .)j(] .d_/ '-( P . S
* License: (BSD) <Td/Z <fP"5(\"??"\a. .L
* Redistribution and use in source and _dV>ws?a-?' ._/L #'
* binary forms, with or without )4d[#7r, . ' )d`)[
* modification, are permitted provided _Q-5'5W..j/?' -?!\)cam'
* that the following conditions are met: j<<WP+k/);. _W=j f
* 1. Redistributions of source code must .$%w\/]Q . ."' . mj$
* retain the above copyright notice, ]E.pYY(Q]>. a J@\
* this list of conditions and the j(]1u<sE"L,. . ./^ ]{a
* following disclaimer. 4'_uomm\. )L);-4 (3=
* 2. Redistributions in binary form must )_]X{Z('a_"a7'<a"a, ]"[
* reproduce the above copyright notice, #}<]m7`Za??4,P-"'7. ).m
* this list of conditions and the ]d2e)Q(<Q( ?94 b- LQ/
* following disclaimer in the <B!</]C)d_, '(<' .f. =C+m
* documentation and/or other materials .Z!=J ]e []('-4f _ ) -.)m]'
* provided with the distribution. .w[5]' _[ /.)_-"+? _/ <W"
* 3. Neither the name of Guichan nor the :$we` _! + _/ . j?
* names of its contributors may be used =3)= _f (_yQmWW$#( "
* to endorse or promote products derived - W, sQQQQmZQ#Wwa]..
* from this software without specific (js, \[QQW$QWW#?!V"".
* prior written permission. ]y:.<\.. .
* -]n w/ ' [.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT )/ )/ !
* HOLDERS AND CONTRIBUTORS "AS IS" AND ANY < (; sac , '
* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, ]^ .- %
* BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF c < r
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR aga< <La
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 5% )P'-3L
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR _bQf` y`..)a
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, ,J?4P'.P"_(\?d'.,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES _Pa,)!f/<[]/ ?"
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT _2-..:. .r+_,.. .
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ?a.<%"' " -'.a_ _,
* 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.
*/
/*
* For comments regarding functions please see the header file.
*/
#include "guisan/widgets/window.hpp"
#include "guisan/exception.hpp"
#include "guisan/font.hpp"
#include "guisan/graphics.hpp"
#include "guisan/mouseinput.hpp"
namespace gcn
{
Window::Window()
: mIsMoving(false)
{
setBorderSize(1);
setPadding(2);
setTitleBarHeight(16);
setAlignment(Graphics::CENTER);
addMouseListener(this);
setMovable(true);
Window::setOpaque(true);
}
Window::Window(const std::string& caption)
: mIsMoving(false)
{
setCaption(caption);
setBorderSize(1);
setPadding(2);
setTitleBarHeight(16);
setAlignment(Graphics::CENTER);
addMouseListener(this);
setMovable(true);
Window::setOpaque(true);
}
Window::~Window()
= default;
void Window::setPadding(unsigned int padding)
{
mPadding = padding;
}
int Window::getPadding() const
{
return mPadding;
}
void Window::setTitleBarHeight(unsigned int height)
{
mTitleBarHeight = height;
}
int Window::getTitleBarHeight() const
{
return mTitleBarHeight;
}
void Window::setCaption(const std::string& caption)
{
mCaption = caption;
}
const std::string& Window::getCaption() const
{
return mCaption;
}
void Window::setAlignment(unsigned int alignment)
{
mAlignment = alignment;
}
int Window::getAlignment() const
{
return mAlignment;
}
void Window::draw(Graphics* graphics)
{
auto faceColor = getBaseColor();
auto alpha = getBaseColor().a;
//int width = getWidth() + getBorderSize() * 2 - 1;
//int height = getHeight() + getBorderSize() * 2 - 1;
Color highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
Color shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
Rectangle d = getChildrenArea();
// Fill the background around the content
graphics->setColor(faceColor);
// Fill top
graphics->fillRectangle(Rectangle(0, 0, getWidth(), d.y - 1));
// Fill left
graphics->fillRectangle(Rectangle(0, d.y - 1, d.x - 1, getHeight() - d.y + 1));
// Fill right
graphics->fillRectangle(Rectangle(d.x + d.width + 1,
d.y - 1,
getWidth() - d.x - d.width - 1,
getHeight() - d.y + 1));
// Fill bottom
graphics->fillRectangle(Rectangle(d.x - 1,
d.y + d.height + 1,
d.width + 2,
getHeight() - d.height - d.y - 1));
if (isOpaque())
{
graphics->fillRectangle(d);
}
// Construct a rectangle one pixel bigger than the content
d.x -= 1;
d.y -= 1;
d.width += 2;
d.height += 2;
// Draw a border around the content
graphics->setColor(shadowColor);
// Top line
graphics->drawLine(d.x,
d.y,
d.x + d.width - 2,
d.y);
// Left line
graphics->drawLine(d.x,
d.y + 1,
d.x,
d.y + d.height - 1);
graphics->setColor(highlightColor);
// Right line
graphics->drawLine(d.x + d.width - 1,
d.y,
d.x + d.width - 1,
d.y + d.height - 2);
// Bottom line
graphics->drawLine(d.x + 1,
d.y + d.height - 1,
d.x + d.width - 1,
d.y + d.height - 1);
drawChildren(graphics);
int textX;
auto textY = (int(getTitleBarHeight()) - getFont()->getHeight()) / 2;
switch (getAlignment())
{
case Graphics::LEFT:
textX = 4;
break;
case Graphics::CENTER:
textX = getWidth() / 2;
break;
case Graphics::RIGHT:
textX = getWidth() - 4;
break;
default:
throw GCN_EXCEPTION("Unknown alignment.");
}
graphics->setColor(getForegroundColor());
graphics->setFont(getFont());
graphics->pushClipArea(Rectangle(0, 0, getWidth(), getTitleBarHeight() - 1));
graphics->drawText(getCaption(), textX, textY, getAlignment());
graphics->popClipArea();
}
void Window::drawBorder(Graphics* graphics)
{
auto faceColor = getBaseColor();
auto alpha = getBaseColor().a;
int width = getWidth() + getBorderSize() * 2 - 1;
int height = getHeight() + getBorderSize() * 2 - 1;
auto highlightColor = faceColor + 0x303030;
highlightColor.a = alpha;
auto shadowColor = faceColor - 0x303030;
shadowColor.a = alpha;
for (unsigned int i = 0; i < getBorderSize(); ++i)
{
graphics->setColor(highlightColor);
graphics->drawLine(i, i, width - i, i);
graphics->drawLine(i, i + 1, i, height - i - 1);
graphics->setColor(shadowColor);
graphics->drawLine(width - i, i + 1, width - i, height - i);
graphics->drawLine(i, height - i, width - i - 1, height - i);
}
}
void Window::mousePressed(MouseEvent& mouseEvent)
{
if (mouseEvent.getSource() != this)
{
return;
}
if (getParent() != nullptr)
{
getParent()->moveToTop(this);
}
mDragOffsetX = mouseEvent.getX();
mDragOffsetY = mouseEvent.getY();
mIsMoving = mouseEvent.getY() <= (int)mTitleBarHeight;
}
void Window::mouseReleased(MouseEvent& mouseEvent)
{
mIsMoving = false;
}
void Window::mouseDragged(MouseEvent& mouseEvent)
{
if (mouseEvent.isConsumed() || mouseEvent.getSource() != this)
{
return;
}
if (isMovable() && mIsMoving)
{
setPosition(mouseEvent.getX() - mDragOffsetX + getX(),
mouseEvent.getY() - mDragOffsetY + getY());
}
mouseEvent.consume();
}
Rectangle Window::getChildrenArea()
{
return {
getPadding(),
getTitleBarHeight(),
getWidth() - getPadding() * 2,
getHeight() - getPadding() - getTitleBarHeight()
};
}
void Window::setMovable(bool movable)
{
mMovable = movable;
}
bool Window::isMovable() const
{
return mMovable;
}
void Window::setOpaque(bool opaque)
{
mOpaque = opaque;
}
bool Window::isOpaque() const
{
return mOpaque;
}
void Window::resizeToContent()
{
auto w = 0, h = 0;
for (auto& mWidget : mWidgets)
{
if (mWidget->getX() + mWidget->getWidth() > w)
{
w = mWidget->getX() + mWidget->getWidth();
}
if (mWidget->getY() + mWidget->getHeight() > h)
{
h = mWidget->getY() + mWidget->getHeight();
}
}
setSize(w + 2 * getPadding(), h + getPadding() + getTitleBarHeight());
}
}
| gpl-3.0 |
zhoushiwei/QGLView | examples/contribs/quarto/quarto.cpp | 1 | 7387 | /****************************************************************************
Copyright (C) 2002-2014 Gilles Debunne. All rights reserved.
This file is part of the QGLViewer library version 2.6.1.
http://www.libqglviewer.com - contact@libqglviewer.com
This file may be used under the terms of the GNU General Public License
versions 2.0 or 3.0 as published by the Free Software Foundation and
appearing in the LICENSE file included in the packaging of this file.
In addition, as a special exception, Gilles Debunne gives you certain
additional rights, described in the file GPL_EXCEPTION in this package.
libQGLViewer uses dual licensing. Commercial/proprietary software must
purchase a libQGLViewer Commercial License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*****************************************************************************/
#include "quarto.h"
#include <signal.h>
#include <qvariant.h>
#include <qapplication.h>
#include <qframe.h>
#include <qgroupbox.h>
#include <qlabel.h>
#include <qmessagebox.h>
#include <qpushbutton.h>
#include <qwidget.h>
#include <qlayout.h>
#include <qtooltip.h>
#include <qdialog.h>
#if QT_VERSION < 0x040000
# include <qdragobject.h>
# include <qheader.h>
#endif
#if QT_VERSION < 0x040000
Quarto::Quarto( QWidget* parent, const char* name, WFlags fl )
: QMainWindow( parent, name, fl )
{
setName( "Quarto" );
setCaption( trUtf8( "Quarto" ) );
#else
Quarto::Quarto(QWidget* parent)
: QMainWindow( parent )
{
setWindowTitle( "Quarto" );
#endif
//************************************************************************************************************************//
//************************************************************************************************************************//
// Definition de l'apparence de l'interface graphique ( Tous les Widgets ) //
//************************************************************************************************************************//
//************************************************************************************************************************//
// Parametres principaux
resize( 800, 400 );
setCentralWidget(this);
//***************************//
// Fenetre de vue du plateau //
//***************************//
QuartoLayout = new QVBoxLayout( centralWidget());
MainHLayout = new QHBoxLayout( NULL );
GLFrameJeu = new QFrame( centralWidget() );
GLFrameJeu->setMouseTracking( true );
GLFrameJeu->setFrameShape( QFrame::StyledPanel );
GLFrameJeu->setFrameShadow( QFrame::Raised );
GLFrameJeu->setFrameStyle( QFrame::Sunken | QFrame::Panel );
GLFrameJeu->setLineWidth( 2 );
// Create our OpenGL widget
vuePlateau = new GLViewJeu( GLFrameJeu );
HLayout1 = new QHBoxLayout( GLFrameJeu );
//**********************************//
// Partie Selection //
//********************************//
VLayout1 = new QVBoxLayout( NULL );
HLayout1->addWidget( vuePlateau );
// Ajout au tableau de fenetres
MainHLayout->addWidget( GLFrameJeu );
//######################//
// Groupe de fonctions //
//####################//
GameGroupBox = new QGroupBox( centralWidget() );
QWidget* privateLayoutWidget = new QWidget( GameGroupBox );
VLayout2 = new QVBoxLayout(privateLayoutWidget);
// Indication du tour des joueurs
HLayout2 = new QHBoxLayout(NULL);
GameGroupBox->setMaximumSize( 600, 100 );
privateLayoutWidget->setGeometry( QRect( 10, 15, 280, 80 ) );
// titre
TourDeJeuLabel = new QLabel( privateLayoutWidget );
QFont TourDeJeuLabel_font( TourDeJeuLabel->font() );
TourDeJeuLabel_font.setPointSize( 14 );
TourDeJeuLabel->setFont( TourDeJeuLabel_font );
TourDeJeuLabel->setText( trUtf8( "Now playing :" ) );
HLayout2->addWidget( TourDeJeuLabel );
// indicateur
NomLabel = new QLabel( privateLayoutWidget );
QFont NomLabel_font( NomLabel->font() );
NomLabel_font.setPointSize( 14 );
NomLabel->setFont( NomLabel_font );
HLayout2->addWidget( NomLabel );
VLayout2->addLayout( HLayout2 );
VLayout1->addWidget( GameGroupBox );
//############################//
// Fenetre de vue des pieces //
//##########################//
GLFramePieces = new QFrame( centralWidget() );
GLFramePieces->setMouseTracking( true );
GLFramePieces->setFrameShape( QFrame::StyledPanel );
GLFramePieces->setFrameShadow( QFrame::Raised );
GLFramePieces->setFrameStyle( QFrame::Sunken | QFrame::Panel );
GLFramePieces->setLineWidth( 2 );
// Create our OpenGL widget
vuePieces = new GLViewPieces( GLFramePieces );
HLayout4 = new QHBoxLayout( GLFramePieces );
HLayout4->addWidget( vuePieces );
// Ajout au tableau de fenetres
VLayout1->addWidget( GLFramePieces );
// Bouttons utiles
HLayout3 = new QHBoxLayout( NULL );
// Boutton de reset
ResetButton = new QPushButton( privateLayoutWidget );
QFont ResetButton_font( ResetButton->font() );
ResetButton_font.setPointSize( 14 );
ResetButton->setFont( ResetButton_font );
ResetButton->setText( trUtf8( "New Game" ) );
HLayout3->addWidget( ResetButton );
// Boutton de quit
QuitButton = new QPushButton( privateLayoutWidget );
QFont QuitButton_font( QuitButton->font() );
QuitButton_font.setPointSize( 14 );
QuitButton->setFont( QuitButton_font );
QuitButton->setText( trUtf8( "Quit" ) );
HLayout3->addWidget( QuitButton );
VLayout2->addLayout( HLayout3 );
// Ajout au tableau de fenetres
MainHLayout->addLayout( VLayout1 );
QuartoLayout->addLayout( MainHLayout );
//******************************************//
// Signals and Slots Connections //
//******************************************//
connect( ResetButton, SIGNAL( clicked() ), this, SLOT( New() ) );
connect( QuitButton, SIGNAL( clicked() ), this, SLOT( Exit() ) );
connect( vuePlateau, SIGNAL( update() ), vuePieces, SLOT( updateGL() ) );
connect( this, SIGNAL( updategl() ), vuePieces, SLOT( updateGL() ) );
connect( this, SIGNAL( updategl() ), vuePlateau, SLOT( updateGL() ) );
connect( vuePlateau, SIGNAL( piecePlacee() ), this, SLOT( piecePlacee() ) );
connect( vuePieces, SIGNAL( changeJoueur() ), this, SLOT( changeTour() ) );
connect( vuePlateau, SIGNAL( endGame() ), this, SLOT( finDeJeu() ) );
// On initialise l'interface
init(true);
}
Quarto::~Quarto()
{
delete(vuePlateau);
delete(vuePieces);
delete(setofpiece);
}
void Quarto::init(bool begin)
{
if (begin)
setofpiece=new SetOfPiece();
else
setofpiece->init();
vuePlateau->reset();
vuePlateau->setPieces(setofpiece);
vuePieces->setPieces(setofpiece);
NomLabel->setText( trUtf8( "Player 1" ) );
joueur=true;
pieceplacee=true;
}
void Quarto::New()
{
init(false);
Q_EMIT updategl();
}
void Quarto::Exit()
{
qApp->exit();
}
void Quarto::piecePlacee() { pieceplacee=true; }
void Quarto::changeTour()
{
if (pieceplacee)
{
if (joueur)
NomLabel->setText( trUtf8( "Player 2" ) );
else
NomLabel->setText( trUtf8( "Player 1" ) );
joueur = !joueur;
pieceplacee=false;
}
}
void Quarto::finDeJeu()
{
if (QMessageBox::information(this, "Game over", "Game is over, "+NomLabel->text()+" won.", "New game", "Exit") == 0)
New();
else
Exit();
}
| gpl-3.0 |
thektulu/lout | z03.c | 1 | 40421 | /*@z03.c:File Service:Declarations, no_fpos@******************************** */
/* */
/* THE LOUT DOCUMENT FORMATTING SYSTEM (VERSION 3.39) */
/* COPYRIGHT (C) 1991, 2008 Jeffrey H. Kingston */
/* */
/* Jeffrey H. Kingston (jeff@it.usyd.edu.au) */
/* School of Information Technologies */
/* The University of Sydney 2006 */
/* AUSTRALIA */
/* */
/* 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, 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 */
/* */
/* FILE: z03.c */
/* MODULE: File Service */
/* EXTERNS: InitFiles(), AddToPath(), DefineFile(), FirstFile(), */
/* NextFile(), FileNum(), FileName(), EchoFilePos(), */
/* PosOfFile(), OpenFile(), OpenIncGraphicFile() */
/* EchoFileFrom() */
/* */
/*****************************************************************************/
#include "externs.h"
#if USE_STAT
#include <sys/types.h>
#include <sys/stat.h>
#endif
#define INIT_TAB 3 /* initial file table size */
/*****************************************************************************/
/* */
/* FILE_TABLE */
/* */
/* A symbol table permitting access to file records by number or name. */
/* The table will automatically enlarge to accept any number of entries, */
/* but there is an arbitrary limit of 65535 files imposed so that file */
/* numbers can be stored in 16 bit fields. */
/* */
/* ftab_new(newsize) New empty table, newsize capacity */
/* ftab_insert(x, &S) Insert new file object x into S */
/* ftab_retrieve(str, S) Retrieve file object of name str */
/* ftab_num(S, num) Retrieve file object of number num */
/* ftab_debug(S, fp) Debug print of table S to file fp */
/* */
/*****************************************************************************/
typedef struct
{ int filetab_size; /* size of table */
int filetab_count; /* number of files in table */
struct filetab_rec
{ OBJECT by_number; /* file record by number */
OBJECT by_name_hash; /* file record by name hash */
} filetab[1];
} *FILE_TABLE;
#define ftab_size(S) (S)->filetab_size
#define ftab_count(S) (S)->filetab_count
#define ftab_num(S, i) (S)->filetab[i].by_number
#define ftab_name(S, i) (S)->filetab[i].by_name_hash
#define hash(pos, str, S) \
{ FULL_CHAR *p = str; \
pos = *p++; \
while( *p ) pos += *p++; \
pos = pos % ftab_size(S); \
}
static FILE_TABLE ftab_new(int newsize)
{ FILE_TABLE S; int i;
ifdebug(DMA, D, DebugRegisterUsage(MEM_FILES, 1,
2*sizeof(int) + newsize * sizeof(struct filetab_rec)));
S = (FILE_TABLE) malloc(2*sizeof(int) + newsize * sizeof(struct filetab_rec));
if( S == (FILE_TABLE) NULL )
Error(3, 1, "run out of memory when enlarging file table", FATAL, no_fpos);
ftab_size(S) = newsize;
ftab_count(S) = 0;
for( i = 0; i < newsize; i++ )
{ ftab_num(S, i) = ftab_name(S, i) = nilobj;
}
return S;
} /* end ftab_new */
static void ftab_insert(OBJECT x, FILE_TABLE *S);
static FILE_TABLE ftab_rehash(FILE_TABLE S, int newsize)
{ FILE_TABLE NewS; int i;
NewS = ftab_new(newsize);
for( i = 1; i <= ftab_count(S); i++ )
ftab_insert(ftab_num(S, i), &NewS);
for( i = 0; i < ftab_size(S); i++ )
{ if( ftab_name(S, i) != nilobj ) DisposeObject(ftab_name(S, i));
}
ifdebug(DMA, D, DebugRegisterUsage(MEM_FILES, -1,
-(2*sizeof(int) + ftab_size(S) * sizeof(struct filetab_rec))));
free(S);
return NewS;
} /* end ftab_rehash */
static void ftab_insert(OBJECT x, FILE_TABLE *S)
{ int pos, num;
if( ftab_count(*S) == ftab_size(*S) - 1 ) /* one less since 0 unused */
*S = ftab_rehash(*S, 2*ftab_size(*S));
num = ++ftab_count(*S);
if( num > MAX_FILES )
Error(3, 2, "too many files (maximum is %d)",
FATAL, &fpos(x), MAX_FILES);
hash(pos, string(x), *S);
if( ftab_name(*S, pos) == nilobj ) New(ftab_name(*S, pos), ACAT);
Link(ftab_name(*S, pos), x);
file_number(x) = num;
ftab_num(*S, num) = x;
} /* end ftab_insert */
static OBJECT ftab_retrieve(FULL_CHAR *str, FILE_TABLE S)
{ OBJECT x, link, y; int pos;
hash(pos, str, S);
x = ftab_name(S, pos);
if( x == nilobj ) return nilobj;
for( link = Down(x); link != x; link = NextDown(link) )
{ Child(y, link);
if( StringEqual(str, string(y)) ) return y;
}
return nilobj;
} /* end ftab_retrieve */
#if DEBUG_ON
static void ftab_debug(FILE_TABLE S)
{ int i; OBJECT x, link, y;
FULL_CHAR buff[MAX_BUFF];
debug2(DFS, D, " table size: %d; current number of files: %d",
ftab_size(S), ftab_count(S));
for( i = 0; i < ftab_size(S); i++ )
{ x = ftab_num(S, i);
debug2(DFS, D, " ftab_num(S, %d) = %s", i,
x == nilobj ? AsciiToFull("<nilobj>") :
!is_word(type(x)) ? AsciiToFull("not WORD!") : string(x) );
}
debug0(DFS, D, "");
for( i = 0; i < ftab_size(S); i++ )
{ x = ftab_name(S, i);
if( x == nilobj )
{
debug1(DFS, D, " ftab_name(S, %d) = <nilobj>", i);
}
else if( type(x) != ACAT )
{
debug1(DFS, D, " ftab_name(S, %d) = not ACAT!>", i);
}
else
{
StringCopy(buff, STR_EMPTY);
for( link = Down(x); link != x; link = NextDown(link) )
{ Child(y, link);
StringCat(buff, STR_SPACE);
StringCat(buff, is_word(type(y)) ? string(y):AsciiToFull("not-WORD!"));
}
debug2(DFS, D, " ftab_name(S, %d) =%s", i, buff);
}
}
} /* end ftab_debug */
static char *file_types[] /* the type names for debug */
= { "source", "include", "incgraphic", "database", "index",
"font", "prepend", "hyph", "hyphpacked",
"mapping", "filter" };
#endif
static OBJECT empty_path; /* file path with just "" in */
static FILE_TABLE file_tab; /* the file table */
static OBJECT file_type[MAX_TYPES]; /* files of each type */
static OBJECT file_path[MAX_PATHS]; /* the search paths */
/* ***don't need these any more
static char *file_mode[MAX_TYPES] =
{ READ_TEXT, READ_TEXT, READ_TEXT, READ_BINARY, READ_TEXT,
READ_TEXT, READ_TEXT, READ_BINARY, READ_TEXT, READ_TEXT };
*** */
/*****************************************************************************/
/* */
/* no_fpos */
/* */
/* A null file position value. */
/* */
/*****************************************************************************/
static FILE_POS no_file_pos = {0, 0, 0, 0, 0};
FILE_POS *no_fpos = &no_file_pos;
/*@::InitFiles(), AddToPath(), DefineFile()@**********************************/
/* */
/* InitFiles() */
/* */
/* Initialize this module. */
/* */
/*****************************************************************************/
void InitFiles(void)
{ int i; OBJECT tmp;
for( i = 0; i < MAX_TYPES; i++ ) New(file_type[i], ACAT);
for( i = 0; i < MAX_PATHS; i++ ) New(file_path[i], ACAT);
file_tab = ftab_new(INIT_TAB);
New(empty_path, ACAT);
tmp = MakeWord(WORD, STR_EMPTY, no_fpos);
Link(empty_path, tmp);
} /* end InitFiles */
/*****************************************************************************/
/* */
/* AddToPath(fpath, dirname) */
/* */
/* Add the directory dirname to the end of search path fpath. */
/* */
/*****************************************************************************/
void AddToPath(int fpath, OBJECT dirname)
{ Link(file_path[fpath], dirname);
} /* end AddToPath */
/*****************************************************************************/
/* */
/* FILE_NUM DefineFile(str, suffix, xfpos, ftype, fpath) */
/* */
/* Declare a file whose name is str plus suffix and whose fpos is xfpos. */
/* The file type is ftype, and its search path is fpath. */
/* */
/* If ignore_dup is TRUE, any repeated definition of the same file with */
/* the same type will be ignored. The result in that case will be the */
/* */
/*****************************************************************************/
FILE_NUM DefineFile(FULL_CHAR *str, FULL_CHAR *suffix,
FILE_POS *xfpos, int ftype, int fpath)
{ register int i;
OBJECT fname;
assert( ftype < MAX_TYPES, "DefineFile: ftype!" );
debug5(DFS, DD, "DefineFile(%s, %s,%s, %s, %d)",
str, suffix, EchoFilePos(xfpos), file_types[ftype], fpath);
if( ftype == SOURCE_FILE && (i = StringLength(str)) >= 3 )
{
/* check that file name does not end in ".li" or ".ld" */
if( StringEqual(&str[i-StringLength(DATA_SUFFIX)], DATA_SUFFIX) )
Error(3, 3, "database file %s where source file expected",
FATAL, xfpos, str);
if( StringEqual(&str[i-StringLength(INDEX_SUFFIX)], INDEX_SUFFIX) )
Error(3, 4, "database index file %s where source file expected",
FATAL, xfpos, str);
}
if( StringLength(str) + StringLength(suffix) >= MAX_WORD )
Error(3, 5, "file name %s%s is too long", FATAL, no_fpos, str, suffix);
fname = MakeWordTwo(WORD, str, suffix, xfpos);
Link(file_type[ftype], fname);
path(fname) = fpath;
updated(fname) = FALSE;
line_count(fname) = 0;
type_of_file(fname) = ftype;
used_suffix(fname) = FALSE;
ftab_insert(fname, &file_tab);
debug1(DFS, DD, "DefineFile returning %s", string(fname));
ifdebug(DFS, DD, ftab_debug(file_tab));
return file_number(fname);
} /* end DefineFile */
/*@::FirstFile(), NextFile(), FileNum()@**************************************/
/* */
/* FILE_NUM FirstFile(ftype) */
/* */
/* Returns first file of type ftype, else NO_FILE. */
/* */
/*****************************************************************************/
FILE_NUM FirstFile(int ftype)
{ FILE_NUM i;
OBJECT link, y;
debug1(DFS, DD, "FirstFile( %s )", file_types[ftype]);
link = Down(file_type[ftype]);
if( type(link) == ACAT ) i = NO_FILE;
else
{ Child(y, link);
i = file_number(y);
}
debug1(DFS, DD, "FirstFile returning %s", i==NO_FILE ? STR_NONE : FileName(i));
return i;
} /* end FirstFile */
/*****************************************************************************/
/* */
/* FILE_NUM NextFile(i) */
/* */
/* Returns the next file after file i of the type of i, else NO_FILE. */
/* */
/*****************************************************************************/
FILE_NUM NextFile(FILE_NUM i)
{ OBJECT link, y;
debug1(DFS, DD, "NextFile( %s )", FileName(i));
link = NextDown(Up(ftab_num(file_tab, i)));
if( type(link) == ACAT ) i = NO_FILE;
else
{ Child(y, link);
i = file_number(y);
}
debug1(DFS, DD, "NextFile returning %s", i==NO_FILE ? STR_NONE : FileName(i));
return i;
} /* end NextFile */
/*****************************************************************************/
/* */
/* FILE_NUM FileNum(str, suffix) */
/* */
/* Return the number of the file with name str plus suffix, else NO_FILE. */
/* */
/*****************************************************************************/
FILE_NUM FileNum(FULL_CHAR *str, FULL_CHAR *suffix)
{ register int i; OBJECT fname;
FULL_CHAR buff[MAX_BUFF];
debug2(DFS, DD, "FileNum(%s, %s)", str, suffix);
if( StringLength(str) + StringLength(suffix) >= MAX_BUFF )
Error(3, 6, "file name %s%s is too long", FATAL, no_fpos, str, suffix);
StringCopy(buff, str);
StringCat(buff, suffix);
fname = ftab_retrieve(buff, file_tab);
i = fname == nilobj ? NO_FILE : file_number(fname);
debug1(DFS, DD, "FileNum returning %s",
i == NO_FILE ? STR_NONE : FileName( (FILE_NUM) i));
return (FILE_NUM) i;
} /* end FileNum */
/*****************************************************************************/
/* */
/* FILE_NUM DatabaseFileNum(FILE_POS *xfpos) */
/* */
/* Return a suitable database file number for writing something out whose */
/* file position is xfpos. */
/* */
/*****************************************************************************/
FILE_NUM DatabaseFileNum(FILE_POS *xfpos)
{ OBJECT x;
FILE_NUM fnum; FULL_CHAR *str;
debug2(DFS, D, "DatabaseFileNum(%s %s)", EchoFilePos(xfpos),
EchoFileSource(file_num(*xfpos)));
x = ftab_num(file_tab, file_num(*xfpos));
switch( type_of_file(x) )
{
case SOURCE_FILE:
case INCLUDE_FILE:
/* return the corresponding database file (may need to be defined) */
str = FileName(file_num(*xfpos));
fnum = FileNum(str, DATA_SUFFIX);
if( fnum == NO_FILE )
{ debug0(DFS, DD, " calling DefineFile from DatabaseFileNum");
fnum = DefineFile(str, DATA_SUFFIX, xfpos, DATABASE_FILE, SOURCE_PATH);
}
break;
case DATABASE_FILE:
/* return the enclosing source file (recursively if necessary) */
if( file_num(fpos(x)) == NO_FILE )
{
/* xfpos lies in a cross-reference database file; use itself */
/* ***
Error(3, 18, "DatabaseFileNum: database file position unknown",
INTERN, no_fpos);
*** */
fnum = file_num(*xfpos);
}
else
{
/* xfpos lies in a user-defined database file; use its source */
fnum = DatabaseFileNum(&fpos(x));
}
break;
case FILTER_FILE:
/* return the enclosing source file (recursively if necessary) */
if( file_num(fpos(x)) == NO_FILE )
Error(3, 7, "DatabaseFileNum: filter file position unknown",
INTERN, no_fpos);
fnum = DatabaseFileNum(&fpos(x));
break;
default:
Error(3, 8, "DatabaseFileNum: unexpected file type", INTERN, no_fpos);
fnum = NO_FILE;
break;
}
debug2(DFS, D, "DatabaseFileNum returning %d (%s)", fnum,
fnum == NO_FILE ? AsciiToFull("NO_FILE") : FileName(fnum));
return fnum;
} /* end DatabaseFileNum */
/*@::FileName(), EchoFilePos(), PosOfFile()@**********************************/
/* */
/* FULL_CHAR *FileName(fnum) */
/* FULL_CHAR *FullFileName(fnum) */
/* */
/* Return the string name of this file. This is as given to DefineFile */
/* until OpenFile is called, after which it is the full path name. */
/* */
/* FullFileName is the same except it will add a .lt to the file name */
/* if that was needed when the file was opened for reading. */
/* */
/*****************************************************************************/
FULL_CHAR *FileName(FILE_NUM fnum)
{ OBJECT x;
x = ftab_num(file_tab, fnum);
assert( x != nilobj, "FileName: x == nilobj!" );
if( Down(x) != x ) Child(x, Down(x));
return string(x);
} /* end FileName */
FULL_CHAR *FullFileName(FILE_NUM fnum)
{ OBJECT x;
static FULL_CHAR ffbuff[2][MAX_BUFF];
static int ffbp = 1;
x = ftab_num(file_tab, fnum);
assert( x != nilobj, "FileName: x == nilobj!" );
if( used_suffix(x) )
{
if( Down(x) != x ) Child(x, Down(x));
ffbp = (ffbp + 1) % 2;
StringCopy(ffbuff[ffbp], string(x));
StringCat(ffbuff[ffbp], SOURCE_SUFFIX);
return ffbuff[ffbp];
}
else
{
if( Down(x) != x ) Child(x, Down(x));
return string(x);
}
} /* end FullFileName */
/*****************************************************************************/
/* */
/* int FileType(FILE_NUM fnum) */
/* */
/* Return the type of file fnum. */
/* */
/*****************************************************************************/
int FileType(FILE_NUM fnum)
{ OBJECT x;
x = ftab_num(file_tab, fnum);
assert( x != nilobj, "FileType: x == nilobj!" );
if( Down(x) != x ) Child(x, Down(x));
return type_of_file(x);
} /* end FileType */
/*****************************************************************************/
/* */
/* FULL_CHAR *EchoFilePos(pos) */
/* */
/* Returns a string reporting the value of file position pos. */
/* */
/*****************************************************************************/
static FULL_CHAR buff[2][MAX_BUFF]; static int bp = 1;
static void append_fpos(FILE_POS *pos)
{ OBJECT x;
x = ftab_num(file_tab, file_num(*pos));
assert( x != nilobj, "EchoFilePos: file_tab entry is nilobj!" );
if( file_num(fpos(x)) > 0 )
{ append_fpos( &fpos(x) );
if( StringLength(buff[bp]) + 2 >= MAX_BUFF )
Error(3, 9, "file position %s... is too long to print",
FATAL, no_fpos, buff[bp]);
StringCat(buff[bp], STR_SPACE);
StringCat(buff[bp], STR_DIR);
}
if( StringLength(buff[bp]) + StringLength(string(x)) + 13 >= MAX_BUFF )
Error(3, 10, "file position %s... is too long to print",
FATAL, no_fpos, buff[bp]);
StringCat(buff[bp], STR_SPACE);
StringCat(buff[bp], STR_QUOTE);
StringCat(buff[bp], string(x));
StringCat(buff[bp], STR_QUOTE);
if( line_num(*pos) != 0 )
{ StringCat(buff[bp], STR_SPACE);
StringCat(buff[bp], StringInt( (int) line_num(*pos)));
StringCat(buff[bp], AsciiToFull(","));
StringCat(buff[bp], StringInt( (int) col_num(*pos)));
}
} /* end append_fpos */
FULL_CHAR *EchoFilePos(FILE_POS *pos)
{ bp = (bp + 1) % 2;
StringCopy(buff[bp], STR_EMPTY);
if( file_num(*pos) > 0 ) append_fpos(pos);
return buff[bp];
} /* end EchoFilePos */
FULL_CHAR *EchoAltFilePos(FILE_POS *pos)
{
bp = (bp + 1) % 2;
StringCopy(buff[bp], STR_EMPTY);
if( file_num(*pos) > 0 )
{
/* *** x = ftab_num(file_tab, file_num(*pos)); *** */
StringCat(buff[bp], FullFileName(file_num(*pos)));
if( line_num(*pos) != 0 )
{ StringCat(buff[bp], AsciiToFull(":"));
StringCat(buff[bp], StringInt( (int) line_num(*pos)));
StringCat(buff[bp], AsciiToFull(":"));
StringCat(buff[bp], StringInt( (int) col_num(*pos)));
}
}
return buff[bp];
} /* end EchoFilePos */
/*@::EchoFileSource(), EchoFileLine(), PosOfFile()@***************************/
/* */
/* FULL_CHAR *EchoFileSource(fnum) */
/* */
/* Returns a string reporting the "file source" information for file fnum. */
/* */
/*****************************************************************************/
FULL_CHAR *EchoFileSource(FILE_NUM fnum)
{ OBJECT x, nextx;
bp = (bp + 1) % 2;
StringCopy(buff[bp], STR_EMPTY);
if( fnum > 0 )
{ StringCat(buff[bp], STR_SPACE);
x = ftab_num(file_tab, fnum);
assert( x != nilobj, "EchoFileSource: x == nilobj!" );
if( type_of_file(x) == FILTER_FILE )
{ StringCat(buff[bp], AsciiToFull(condcatgets(MsgCat, 3, 11, "filter")));
/* for estrip's benefit: Error(3, 11, "filter"); */
StringCat(buff[bp], STR_SPACE);
}
StringCat(buff[bp], AsciiToFull(condcatgets(MsgCat, 3, 12, "file")));
/* for estrip's benefit: Error(3, 12, "file"); */
StringCat(buff[bp], STR_SPACE);
/* *** x = ftab_num(file_tab, fnum); *** */
StringCat(buff[bp], STR_QUOTE);
StringCat(buff[bp], FullFileName(fnum));
StringCat(buff[bp], STR_QUOTE);
if( file_num(fpos(x)) > 0 )
{ StringCat(buff[bp], AsciiToFull(" ("));
for(;;)
{ nextx = ftab_num(file_tab, file_num(fpos(x)));
StringCat(buff[bp], AsciiToFull(condcatgets(MsgCat, 3, 13, "from")));
/* for estrip's benefit: Error(3, 13, "from"); */
StringCat(buff[bp], STR_SPACE);
StringCat(buff[bp], STR_QUOTE);
StringCat(buff[bp], string(nextx));
StringCat(buff[bp], STR_QUOTE);
StringCat(buff[bp], STR_SPACE);
StringCat(buff[bp], AsciiToFull(condcatgets(MsgCat, 3, 14, "line")));
/* for estrip's benefit: Error(3, 14, "line"); */
StringCat(buff[bp], STR_SPACE);
StringCat(buff[bp], StringInt( (int) line_num(fpos(x))));
if( file_num(fpos(nextx)) == 0 ) break;
StringCat(buff[bp], AsciiToFull(", "));
x = nextx;
}
StringCat(buff[bp], AsciiToFull(")"));
}
}
return buff[bp];
} /* end EchoFileSource */
/*****************************************************************************/
/* */
/* FULL_CHAR *EchoFileLine(pos) */
/* */
/* Returns a string reporting the "line source" information for pos. */
/* */
/*****************************************************************************/
FULL_CHAR *EchoFileLine(FILE_POS *pos)
{ bp = (bp + 1) % 2;
StringCopy(buff[bp], STR_EMPTY);
if( file_num(*pos) > 0 && line_num(*pos) != 0 )
{ StringCat(buff[bp], StringInt( (int) line_num(*pos)));
StringCat(buff[bp], AsciiToFull(","));
StringCat(buff[bp], StringInt( (int) col_num(*pos)));
}
return buff[bp];
} /* end EchoFileLIne */
/*****************************************************************************/
/* */
/* FILE_POS *PosOfFile(fnum) */
/* */
/* Returns a pointer to the file position where file fnum was encountered. */
/* */
/*****************************************************************************/
FILE_POS *PosOfFile(FILE_NUM fnum)
{ OBJECT x = ftab_num(file_tab, fnum);
assert( x != nilobj, "PosOfFile: file_tab entry is nilobj!" );
return &fpos(x);
}
/*@::SearchPath()@************************************************************/
/* */
/* static FILE *SearchPath(str, fpath, check_ld, check_lt, full_name, xfpos,*/
/* read_mode) */
/* */
/* Search the given path for a file whose name is str. If found, open */
/* it with mode read_mode; return the resulting FILE *. */
/* */
/* If check_ld is TRUE, it means that the file to be opened is a .li file */
/* and OpenFile() is required to check whether the corresponding .ld file */
/* is present. If it is, then the search must stop. Furthermore, if the */
/* .li file is out of date wrt the .ld file, it is to be removed. */
/* */
/* If check_lt is TRUE, it means that the file to be opened is a source */
/* file and OpenFile() is required to check for a .lt suffix version. */
/* */
/* Also return the full path name in object *full_name if different from */
/* the existing name, else nilobj. */
/* */
/* Set *used_source_suffix to TRUE if the .lt source suffix had to be */
/* added in order to find the file. */
/* */
/*****************************************************************************/
static FILE *SearchPath(FULL_CHAR *str, OBJECT fpath, BOOLEAN check_ld,
BOOLEAN check_lt, OBJECT *full_name, FILE_POS *xfpos, char *read_mode,
BOOLEAN *used_source_suffix)
{ FULL_CHAR buff[MAX_BUFF], buff2[MAX_BUFF];
OBJECT link, y = nilobj, cpath; FILE *fp, *fp2;
debug4(DFS, DD, "[ SearchPath(%s, %s, %s, %s, -)", str, EchoObject(fpath),
bool(check_ld), bool(check_lt));
*used_source_suffix = FALSE;
/* if file name is "stdin" just return it */
if( StringEqual(str, STR_STDIN) )
{
debug0(DFS, DD, "] SearchPath returning stdin");
*full_name = nilobj;
return stdin;
}
/* use fpath if relative file name, use empty_path if absolute filename */
cpath = StringBeginsWith(str, STR_DIR) ? empty_path : fpath;
/* try opening each path name in the search path */
fp = null;
for( link = Down(cpath); fp == null && link != cpath; link = NextDown(link) )
{ Child(y, link);
/* set buff to the full path name */
if( StringLength(string(y)) == 0 )
{ StringCopy(buff, str);
}
else
{ if( StringLength(string(y)) + StringLength(STR_DIR) +
StringLength(str) >= MAX_BUFF )
Error(3, 15, "file path name %s%s%s is too long",
FATAL, &fpos(y), string(y), STR_DIR, str);
StringCopy(buff, string(y));
StringCat(buff, STR_DIR);
StringCat(buff, str);
}
/* try opening the full path name */
fp = StringFOpen(buff, read_mode);
debug1(DFS, DD, fp == null ? " fail %s" : " succeed %s", buff);
/* if failed to find .li file, exit if corresponding .ld file */
if( check_ld && fp == null )
{
StringCopy(buff2, buff);
StringCopy(&buff2[StringLength(buff2) - StringLength(INDEX_SUFFIX)],
DATA_SUFFIX);
fp2 = StringFOpen(buff2, READ_FILE);
debug1(DFS, DD, fp2 == null ? " fail %s" : " succeed %s", buff2);
if( fp2 != null )
{ fclose(fp2);
debug0(DFS, DD, "] SearchPath returning null (adjacent .ld file)");
*full_name = nilobj;
return null;
}
}
#if USE_STAT
/*****************************************************************/
/* */
/* If your compiler won't compile this bit, it is probably */
/* because you either don't have the stat() system call on */
/* your system (it is not ANSI C), or because it can't be */
/* found in the header files declared at the top of this file. */
/* */
/* The simple correct thing to do is to set the USESTAT macro */
/* in the makefile to 0. You won't lose much. */
/* */
/*****************************************************************/
/* if found .li file, compare dates with corresponding .ld file */
if( check_ld && fp != null )
{
struct stat indexstat, datastat;
StringCopy(buff2, buff);
StringCopy(&buff2[StringLength(buff2) - StringLength(INDEX_SUFFIX)],
DATA_SUFFIX);
debug2(DFS, DD, "SearchPath comparing dates of .li %s and .ld %s",
buff, buff2);
if( stat( (char *) buff, &indexstat) == 0 &&
stat( (char *) buff2, &datastat) == 0 )
{
debug2(DFS, DD, "SearchPath mtimes are .li %d and .ld %d",
(int) indexstat.st_mtime, (int) datastat.st_mtime);
if( datastat.st_mtime > indexstat.st_mtime )
{ fclose(fp);
debug1(DFS, DD, "SearchPath calling StringRemove(%s)", buff);
StringRemove(buff);
debug0(DFS, DD, "] SearchPath returning null (.li out of date)");
*full_name = nilobj;
return null;
}
}
}
#endif
/* if check_lt, see if buff.lt exists as well as or instead of buff */
if( check_lt )
{
StringCopy(buff2, buff);
StringCat(buff2, SOURCE_SUFFIX);
fp2 = StringFOpen(buff2, READ_FILE);
debug1(DFS, DD, fp2 == null ? " fail %s" : " succeed %s", buff2);
if( fp2 != null )
{ if( fp != null )
Error(3, 16, "files %s and %s both exist", FATAL, xfpos,buff,buff2);
fp = fp2;
*used_source_suffix = TRUE;
}
}
}
debug1(DFS, DD, "] SearchPath returning (fp %s null)", fp==null ? "==" : "!=");
*full_name = (fp == null || StringLength(string(y)) == 0) ? nilobj :
MakeWord(WORD, buff, xfpos);
return fp;
} /* end SearchPath */
/*@::OpenFile(), OpenIncGraphicFile()@****************************************/
/* */
/* FILE *OpenFile(fnum, check_ld, check_lt) */
/* */
/* Open for reading the file whose number is fnum. This involves */
/* searching for it along its path if not previously opened. */
/* */
/* If check_ld is TRUE, it means that the file to be opened is a .li file */
/* and OpenFile() is required to check whether the corresponding .ld file */
/* is present. If it is, then the search must stop. Furthermore, if the */
/* .li file is out of date wrt the .ld file, it is to be removed. */
/* */
/* If check_lt is TRUE, it means that the file to be opened is a source */
/* file and OpenFile() is required to check for a .lt suffix version */
/* if the file does not open without it. */
/* */
/*****************************************************************************/
FILE *OpenFile(FILE_NUM fnum, BOOLEAN check_ld, BOOLEAN check_lt)
{ FILE *fp; OBJECT fname, full_name, y; BOOLEAN used_source_suffix;
ifdebug(DPP, D, ProfileOn("OpenFile"));
debug2(DFS, DD, "[ OpenFile(%s, %s)", FileName(fnum), bool(check_ld));
fname = ftab_num(file_tab, fnum);
if( Down(fname) != fname )
{ Child(y, Down(fname));
/* fp = StringFOpen(string(y), file_mode[type_of_file(fname)]); */
fp = StringFOpen(string(y), READ_FILE);
debug1(DFS,DD,fp==null ? " failed on %s" : " succeeded on %s", string(y));
}
else
{
/* ***
fp = SearchPath(string(fname), file_path[path(fname)], check_ld,
check_lt, &full_name, &fpos(fname), file_mode[type_of_file(fname)],
&used_source_suffix);
*** */
fp = SearchPath(string(fname), file_path[path(fname)], check_ld, check_lt,
&full_name, &fpos(fname), READ_FILE, &used_source_suffix);
if( full_name != nilobj ) Link(fname, full_name);
used_suffix(fname) = used_source_suffix;
}
ifdebug(DPP, D, ProfileOff("OpenFile"));
debug1(DFS, DD, "] OpenFile returning (fp %s null)", fp==null ? "==" : "!=");
return fp;
} /* end OpenFile */
/*****************************************************************************/
/* */
/* FILE *OpenIncGraphicFile(str, typ, full_name, xfpos, compressed) */
/* */
/* Open for reading the @IncludeGraphic file str; typ is INCGRAPHIC or */
/* SINCGRAPHIC; xfpos is the file position of the file name. */
/* */
/* Return the full name in full_name. Set compressed to TRUE if the file */
/* was a compressed file. */
/* */
/*****************************************************************************/
#define MAX_COMPRESSED 6
static char *compress_suffixes[MAX_COMPRESSED]
= { ".gz", "-gz", ".z", "-z", "_z", ".Z" };
FILE *OpenIncGraphicFile(FULL_CHAR *str, unsigned char typ,
OBJECT *full_name, FILE_POS *xfpos, BOOLEAN *compressed)
{ FILE *fp; int p, i; BOOLEAN used_source_suffix;
debug2(DFS, DD, "OpenIncGraphicFile(%s, %s, -)", str, Image(typ));
assert( typ == INCGRAPHIC || typ == SINCGRAPHIC, "OpenIncGraphicFile!" );
p = (typ == INCGRAPHIC ? INCLUDE_PATH : SYSINCLUDE_PATH);
fp = SearchPath(str, file_path[p], FALSE, FALSE, full_name, xfpos,
READ_FILE, &used_source_suffix);
if( *full_name == nilobj ) *full_name = MakeWord(WORD, str, xfpos);
if( fp == null )
{
/* if file didn't open, nothing more to do */
*compressed = FALSE;
fp = null;
}
else
{
/* if file is compressed, uncompress it into file LOUT_EPS */
for( i = 0; i < MAX_COMPRESSED; i++ )
{ if( StringEndsWith(string(*full_name), AsciiToFull(compress_suffixes[i])) )
break;
}
if( i < MAX_COMPRESSED )
{ char buff[MAX_BUFF];
fclose(fp);
sprintf(buff, UNCOMPRESS_COM, (char *) string(*full_name), LOUT_EPS);
if( SafeExecution )
{
Error(3, 17, "safe execution prohibiting command: %s", WARN, xfpos,buff);
*compressed = FALSE;
fp = null;
}
else
{
system(buff);
fp = fopen(LOUT_EPS, READ_FILE);
*compressed = TRUE;
}
}
else *compressed = FALSE;
}
debug2(DFS, DD, "OpenIncGraphicFile returning (fp %s null, *full_name = %s)",
fp==null ? "==" : "!=", string(*full_name));
return fp;
} /* end OpenIncGraphicFile */
/*****************************************************************************/
/* */
/* FileSetUpdated(fnum, newlines) */
/* */
/* Declare that file fnum has been updated, and that it now contains */
/* newlines lines. */
/* */
/*****************************************************************************/
void FileSetUpdated(FILE_NUM fnum, int newlines)
{
debug2(DFS, DD, "FileSetUpdated(%s, %d)", FileName(fnum), newlines);
updated(ftab_num(file_tab, fnum)) = TRUE;
line_count(ftab_num(file_tab, fnum)) = newlines;
debug0(DFS, DD, "FileSetUpdated returning");
} /* end FileSetUpdated */
/*****************************************************************************/
/* */
/* int FileGetLineCount(FILE_NUM fnum) */
/* */
/* Return the number of lines so far written to file fnum. */
/* */
/*****************************************************************************/
int FileGetLineCount(FILE_NUM fnum)
{ int res;
debug1(DFS, DD, "FileGetLineCount(%s)", FileName(fnum));
res = line_count(ftab_num(file_tab, fnum));
debug1(DFS, DD, "FileGetLineCount returning %d", res);
return res;
} /* end FileGetLineCount */
/*****************************************************************************/
/* */
/* BOOLEAN FileTestUpdated(fnum) */
/* */
/* Test whether file fnum has been declared to be updated. */
/* */
/*****************************************************************************/
BOOLEAN FileTestUpdated(FILE_NUM fnum)
{ return (BOOLEAN) updated(ftab_num(file_tab, fnum));
} /* end FileTestUpdated */
| gpl-3.0 |
cran/rAverage | src/combinations.c | 1 | 2416 | #include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "rAverage.h"
int binomial(int n, int k)
{
int i=n-1,j=n;
if(n==k) return(1);
while(i>(n-k)) {
j *= i;
i--;
}
i = k-1;
while(i>1) {
k *= i;
i--;
}
i = j/k;
return(i);
}
int combin_length(int n)
{
int choose;
double length = n;
double middle_int;
double middle_dec;
middle_dec = modf(length/2,&middle_int);
if(middle_dec >= 0.5)
middle_int++;
choose = binomial(length,middle_int);
n = middle_int * choose;
return(n);
}
void combin(int *n, int *k, int *out)
{
// Inizializzazione variabili
int j,i=*k-1,t=-1;
int h,pos,add;
int sequence[*k], base[*k], origin[*k], stop[*k];
for(j=0; j<*k; j++) {
out[j] = j+1;
sequence[j] = j+1;
base[j] = j+1;
origin[j] = j+1;
stop[j] = *n-*k+1+j;
}
// Costruzione combinazioni
while(sequence[0] < stop[0]) {
for(j=0; j<*k; j++) {
t++;
sequence[j] = base[j];
out[t] = sequence[j];
}
while(sequence[*k-1] < stop[*k-1]) {
sequence[*k-1] = sequence[*k-1]+1;
for(j=0; j<*k; j++) {
t++;
out[t] = sequence[j];
}
}
if(sequence[i]==stop[i]) {
i--;
for(j=0; j<*k; j++) {
if(j < i)
base[j] = origin[j];
else
base[j] = origin[j]+1;
}
} else {
h = 0;
for(j=*k-1; j>=i; j--)
h = h + (sequence[j]==stop[j]);
pos = *k-h-1;
add = base[pos]+1;
for(j=0; j<=h; j++)
base[pos+j] = add+j;
}
}
}
void grid(int *lev, int *fact, int *out)
{
int a=0,b=0,j=0,h=0,trace=1;
int eachrep,numrep=1;
for(a=0; a<*fact; a++) {
// eachrep
eachrep = 1;
for(j=a+1; j<*fact; j++)
eachrep = eachrep*lev[j];
// numrep
numrep = 1;
for(j=0; j<a; j++)
numrep *= lev[j];
// index
for(j=0; j<numrep; j++) {
for(trace=1; trace<=lev[a]; trace++) {
for(b=0; b<eachrep; b++) {
out[h] = trace;
h++;
}
}
}
}
}
| gpl-3.0 |
robocyte/mantaflow | source/vortexpart.cpp | 1 | 4691 | /******************************************************************************
*
* MantaFlow fluid solver framework
* Copyright 2011 Tobias Pfaff, Nils Thuerey
*
* This program is free software, distributed under the terms of the
* GNU General Public License (GPL)
* http://www.gnu.org/licenses
*
* Vortex particles
*
******************************************************************************/
#include "vortexpart.h"
#include "integrator.h"
#include "mesh.h"
using namespace std;
namespace Manta
{
// vortex particle effect: (cyl coord around wp)
// u = -|wp|*rho*exp( (-rho^2-z^2)/(2sigma^2) ) e_phi
inline Vec3 VortexKernel(const Vec3& p, const vector<VortexParticleData>& vp, Real scale)
{
Vec3 u(_0);
for (size_t i=0; i<vp.size(); i++)
{
if (vp[i].flag & ParticleBase::PDELETE) continue;
// cutoff radius
const Vec3 r = p - vp[i].pos;
const Real rlen2 = normSquare(r);
const Real sigma2 = square(vp[i].sigma);
if (rlen2 > 6.0 * sigma2 || rlen2 < 1e-8) continue;
// split vortex strength
Vec3 vortNorm = vp[i].vorticity;
Real strength = normalize(vortNorm) * scale;
// transform in cylinder coordinate system
const Real rlen = sqrt(rlen2);
const Real z = dot(r, vortNorm);
const Vec3 ePhi = cross(r, vortNorm) / rlen;
const Real rho2 = rlen2 - z*z;
Real vortex = 0;
if (rho2 > 1e-10)
{
// evaluate Kernel
vortex = strength * sqrt(rho2) * exp (rlen2 * -0.5/sigma2);
}
u += vortex * ePhi;
}
return u;
}
struct KnVpAdvectMesh : public KernelBase
{
KnVpAdvectMesh(vector<Node>& nodes, const vector<VortexParticleData>& vp, Real scale)
: KernelBase(nodes.size())
, nodes(nodes)
, vp(vp)
, scale(scale)
, u((size))
{
run();
}
inline void op(int idx, vector<Node>& nodes, const vector<VortexParticleData>& vp, Real scale ,vector<Vec3> & u)
{
if (nodes[idx].flags & Mesh::NfFixed)
u[idx] = _0;
else
u[idx] = VortexKernel(nodes[idx].pos, vp, scale);
}
inline operator vector<Vec3> () { return u; }
inline vector<Vec3> & getRet() { return u; }
inline vector<Node>& getArg0() { return nodes; }
typedef vector<Node> type0;
inline const vector<VortexParticleData>& getArg1() { return vp; }
typedef vector<VortexParticleData> type1;
inline Real& getArg2() { return scale; }
typedef Real type2;
void run()
{
const int _sz = size;
#pragma omp parallel
{
this->threadId = omp_get_thread_num();
this->threadNum = omp_get_num_threads();
#pragma omp for
for (int i=0; i < _sz; i++)
op(i,nodes,vp,scale,u);
}
}
vector<Node>& nodes;
const vector<VortexParticleData>& vp;
Real scale;
vector<Vec3> u;
};
struct KnVpAdvectSelf : public KernelBase
{
KnVpAdvectSelf(vector<VortexParticleData>& vp, Real scale)
: KernelBase(vp.size())
, vp(vp)
, scale(scale)
, u((size))
{
run();
}
inline void op(int idx, vector<VortexParticleData>& vp, Real scale, vector<Vec3> & u)
{
if (vp[idx].flag & ParticleBase::PDELETE)
u[idx] = _0;
else
u[idx] = VortexKernel(vp[idx].pos, vp, scale);
}
inline operator vector<Vec3> () { return u; }
inline vector<Vec3> & getRet() { return u; }
inline vector<VortexParticleData>& getArg0() { return vp; }
typedef vector<VortexParticleData> type0;
inline Real& getArg1() { return scale; }
typedef Real type1;
void run()
{
const int _sz = size;
#pragma omp parallel
{
this->threadId = omp_get_thread_num();
this->threadNum = omp_get_num_threads();
#pragma omp for
for (int i=0; i < _sz; i++)
op(i,vp,scale,u);
}
}
vector<VortexParticleData>& vp;
Real scale;
vector<Vec3> u;
};
VortexParticleSystem::VortexParticleSystem(FluidSolver* parent)
: ParticleSystem<VortexParticleData>(parent)
{
}
void VortexParticleSystem::advectSelf(Real scale, int integrationMode)
{
KnVpAdvectSelf kernel(mData, scale* getParent()->getDt());
integratePointSet( kernel, integrationMode);
}
void VortexParticleSystem::applyToMesh(Mesh& mesh, Real scale, int integrationMode)
{
KnVpAdvectMesh kernel(mesh.getNodeData(), mData, scale* getParent()->getDt());
integratePointSet(kernel, integrationMode);
}
ParticleBase* VortexParticleSystem::clone()
{
VortexParticleSystem* nm = new VortexParticleSystem(getParent());
compress();
nm->mData = mData;
nm->setName(getName());
return nm;
}
} // namespace
| gpl-3.0 |
williamfdevine/PrettyLinux | drivers/mailbox/mailbox-xgene-slimpro.c | 1 | 7513 | /*
* APM X-Gene SLIMpro MailBox Driver
*
* Copyright (c) 2015, Applied Micro Circuits Corporation
* Author: Feng Kan fkan@apm.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, see <http://www.gnu.org/licenses/>.
*
*/
#include <linux/acpi.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/mailbox_controller.h>
#include <linux/module.h>
#include <linux/of.h>
#include <linux/platform_device.h>
#include <linux/spinlock.h>
#define MBOX_CON_NAME "slimpro-mbox"
#define MBOX_REG_SET_OFFSET 0x1000
#define MBOX_CNT 8
#define MBOX_STATUS_AVAIL_MASK BIT(16)
#define MBOX_STATUS_ACK_MASK BIT(0)
/* Configuration and Status Registers */
#define REG_DB_IN 0x00
#define REG_DB_DIN0 0x04
#define REG_DB_DIN1 0x08
#define REG_DB_OUT 0x10
#define REG_DB_DOUT0 0x14
#define REG_DB_DOUT1 0x18
#define REG_DB_STAT 0x20
#define REG_DB_STATMASK 0x24
/**
* X-Gene SlimPRO mailbox channel information
*
* @dev: Device to which it is attached
* @chan: Pointer to mailbox communication channel
* @reg: Base address to access channel registers
* @irq: Interrupt number of the channel
* @rx_msg: Received message storage
*/
struct slimpro_mbox_chan
{
struct device *dev;
struct mbox_chan *chan;
void __iomem *reg;
int irq;
u32 rx_msg[3];
};
/**
* X-Gene SlimPRO Mailbox controller data
*
* X-Gene SlimPRO Mailbox controller has 8 commnunication channels.
* Each channel has a separate IRQ number assgined to it.
*
* @mb_ctrl: Representation of the commnunication channel controller
* @mc: Array of SlimPRO mailbox channels of the controller
* @chans: Array of mailbox communication channels
*
*/
struct slimpro_mbox
{
struct mbox_controller mb_ctrl;
struct slimpro_mbox_chan mc[MBOX_CNT];
struct mbox_chan chans[MBOX_CNT];
};
static void mb_chan_send_msg(struct slimpro_mbox_chan *mb_chan, u32 *msg)
{
writel(msg[1], mb_chan->reg + REG_DB_DOUT0);
writel(msg[2], mb_chan->reg + REG_DB_DOUT1);
writel(msg[0], mb_chan->reg + REG_DB_OUT);
}
static void mb_chan_recv_msg(struct slimpro_mbox_chan *mb_chan)
{
mb_chan->rx_msg[1] = readl(mb_chan->reg + REG_DB_DIN0);
mb_chan->rx_msg[2] = readl(mb_chan->reg + REG_DB_DIN1);
mb_chan->rx_msg[0] = readl(mb_chan->reg + REG_DB_IN);
}
static int mb_chan_status_ack(struct slimpro_mbox_chan *mb_chan)
{
u32 val = readl(mb_chan->reg + REG_DB_STAT);
if (val & MBOX_STATUS_ACK_MASK)
{
writel(MBOX_STATUS_ACK_MASK, mb_chan->reg + REG_DB_STAT);
return 1;
}
return 0;
}
static int mb_chan_status_avail(struct slimpro_mbox_chan *mb_chan)
{
u32 val = readl(mb_chan->reg + REG_DB_STAT);
if (val & MBOX_STATUS_AVAIL_MASK)
{
mb_chan_recv_msg(mb_chan);
writel(MBOX_STATUS_AVAIL_MASK, mb_chan->reg + REG_DB_STAT);
return 1;
}
return 0;
}
static irqreturn_t slimpro_mbox_irq(int irq, void *id)
{
struct slimpro_mbox_chan *mb_chan = id;
if (mb_chan_status_ack(mb_chan))
{
mbox_chan_txdone(mb_chan->chan, 0);
}
if (mb_chan_status_avail(mb_chan))
{
mbox_chan_received_data(mb_chan->chan, mb_chan->rx_msg);
}
return IRQ_HANDLED;
}
static int slimpro_mbox_send_data(struct mbox_chan *chan, void *msg)
{
struct slimpro_mbox_chan *mb_chan = chan->con_priv;
mb_chan_send_msg(mb_chan, msg);
return 0;
}
static int slimpro_mbox_startup(struct mbox_chan *chan)
{
struct slimpro_mbox_chan *mb_chan = chan->con_priv;
int rc;
u32 val;
rc = devm_request_irq(mb_chan->dev, mb_chan->irq, slimpro_mbox_irq, 0,
MBOX_CON_NAME, mb_chan);
if (unlikely(rc))
{
dev_err(mb_chan->dev, "failed to register mailbox interrupt %d\n",
mb_chan->irq);
return rc;
}
/* Enable HW interrupt */
writel(MBOX_STATUS_ACK_MASK | MBOX_STATUS_AVAIL_MASK,
mb_chan->reg + REG_DB_STAT);
/* Unmask doorbell status interrupt */
val = readl(mb_chan->reg + REG_DB_STATMASK);
val &= ~(MBOX_STATUS_ACK_MASK | MBOX_STATUS_AVAIL_MASK);
writel(val, mb_chan->reg + REG_DB_STATMASK);
return 0;
}
static void slimpro_mbox_shutdown(struct mbox_chan *chan)
{
struct slimpro_mbox_chan *mb_chan = chan->con_priv;
u32 val;
/* Mask doorbell status interrupt */
val = readl(mb_chan->reg + REG_DB_STATMASK);
val |= (MBOX_STATUS_ACK_MASK | MBOX_STATUS_AVAIL_MASK);
writel(val, mb_chan->reg + REG_DB_STATMASK);
devm_free_irq(mb_chan->dev, mb_chan->irq, mb_chan);
}
static struct mbox_chan_ops slimpro_mbox_ops =
{
.send_data = slimpro_mbox_send_data,
.startup = slimpro_mbox_startup,
.shutdown = slimpro_mbox_shutdown,
};
static int slimpro_mbox_probe(struct platform_device *pdev)
{
struct slimpro_mbox *ctx;
struct resource *regs;
void __iomem *mb_base;
int rc;
int i;
ctx = devm_kzalloc(&pdev->dev, sizeof(struct slimpro_mbox), GFP_KERNEL);
if (!ctx)
{
return -ENOMEM;
}
platform_set_drvdata(pdev, ctx);
regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
mb_base = devm_ioremap(&pdev->dev, regs->start, resource_size(regs));
if (!mb_base)
{
return -ENOMEM;
}
/* Setup mailbox links */
for (i = 0; i < MBOX_CNT; i++)
{
ctx->mc[i].irq = platform_get_irq(pdev, i);
if (ctx->mc[i].irq < 0)
{
if (i == 0)
{
dev_err(&pdev->dev, "no available IRQ\n");
return -EINVAL;
}
dev_info(&pdev->dev, "no IRQ for channel %d\n", i);
break;
}
ctx->mc[i].dev = &pdev->dev;
ctx->mc[i].reg = mb_base + i * MBOX_REG_SET_OFFSET;
ctx->mc[i].chan = &ctx->chans[i];
ctx->chans[i].con_priv = &ctx->mc[i];
}
/* Setup mailbox controller */
ctx->mb_ctrl.dev = &pdev->dev;
ctx->mb_ctrl.chans = ctx->chans;
ctx->mb_ctrl.txdone_irq = true;
ctx->mb_ctrl.ops = &slimpro_mbox_ops;
ctx->mb_ctrl.num_chans = i;
rc = mbox_controller_register(&ctx->mb_ctrl);
if (rc)
{
dev_err(&pdev->dev,
"APM X-Gene SLIMpro MailBox register failed:%d\n", rc);
return rc;
}
dev_info(&pdev->dev, "APM X-Gene SLIMpro MailBox registered\n");
return 0;
}
static int slimpro_mbox_remove(struct platform_device *pdev)
{
struct slimpro_mbox *smb = platform_get_drvdata(pdev);
mbox_controller_unregister(&smb->mb_ctrl);
return 0;
}
static const struct of_device_id slimpro_of_match[] =
{
{.compatible = "apm,xgene-slimpro-mbox" },
{ },
};
MODULE_DEVICE_TABLE(of, slimpro_of_match);
#ifdef CONFIG_ACPI
static const struct acpi_device_id slimpro_acpi_ids[] =
{
{"APMC0D01", 0},
{}
};
MODULE_DEVICE_TABLE(acpi, slimpro_acpi_ids);
#endif
static struct platform_driver slimpro_mbox_driver =
{
.probe = slimpro_mbox_probe,
.remove = slimpro_mbox_remove,
.driver = {
.name = "xgene-slimpro-mbox",
.of_match_table = of_match_ptr(slimpro_of_match),
.acpi_match_table = ACPI_PTR(slimpro_acpi_ids)
},
};
static int __init slimpro_mbox_init(void)
{
return platform_driver_register(&slimpro_mbox_driver);
}
static void __exit slimpro_mbox_exit(void)
{
platform_driver_unregister(&slimpro_mbox_driver);
}
subsys_initcall(slimpro_mbox_init);
module_exit(slimpro_mbox_exit);
MODULE_DESCRIPTION("APM X-Gene SLIMpro Mailbox Driver");
MODULE_LICENSE("GPL");
| gpl-3.0 |
lilmatt/ventafone | speex-source/libspeex/testenc.c | 1 | 3840 | #ifdef HAVE_CONFIG_H
#import "config.h"
#endif
#import "speex.h"
#import <stdio.h>
#import <stdlib.h>
#import "speex_callbacks.h"
#ifdef FIXED_DEBUG
extern long long spx_mips;
#endif
#define FRAME_SIZE 160
#import <math.h>
int test_enc(int argc, char **argv)
{
char *inFile, *outFile, *bitsFile;
FILE *fin, *fout, *fbits=NULL;
short in_short[FRAME_SIZE];
short out_short[FRAME_SIZE];
int snr_frames = 0;
char cbits[200];
int nbBits;
int i;
void *st;
void *dec;
SpeexBits bits;
spx_int32_t tmp;
int bitCount=0;
spx_int32_t skip_group_delay;
SpeexCallback callback;
st = speex_encoder_init(speex_lib_get_mode(SPEEX_MODEID_NB));
dec = speex_decoder_init(speex_lib_get_mode(SPEEX_MODEID_NB));
/* BEGIN: You probably don't need the following in a real application */
callback.callback_id = SPEEX_INBAND_CHAR;
callback.func = speex_std_char_handler;
callback.data = stderr;
speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback);
callback.callback_id = SPEEX_INBAND_MODE_REQUEST;
callback.func = speex_std_mode_request_handler;
callback.data = st;
speex_decoder_ctl(dec, SPEEX_SET_HANDLER, &callback);
/* END of unnecessary stuff */
tmp=1;
speex_decoder_ctl(dec, SPEEX_SET_ENH, &tmp);
tmp=0;
speex_encoder_ctl(st, SPEEX_SET_VBR, &tmp);
tmp=8;
speex_encoder_ctl(st, SPEEX_SET_QUALITY, &tmp);
tmp=1;
speex_encoder_ctl(st, SPEEX_SET_COMPLEXITY, &tmp);
/* Turn this off if you want to measure SNR (on by default) */
tmp=1;
speex_encoder_ctl(st, SPEEX_SET_HIGHPASS, &tmp);
speex_decoder_ctl(dec, SPEEX_SET_HIGHPASS, &tmp);
speex_encoder_ctl(st, SPEEX_GET_LOOKAHEAD, &skip_group_delay);
speex_decoder_ctl(dec, SPEEX_GET_LOOKAHEAD, &tmp);
skip_group_delay += tmp;
if (argc != 4 && argc != 3)
{
fprintf (stderr, "Usage: encode [in file] [out file] [bits file]\nargc = %d", argc);
exit(1);
}
inFile = argv[1];
fin = fopen(inFile, "rb");
outFile = argv[2];
fout = fopen(outFile, "wb+");
if (argc==4)
{
bitsFile = argv[3];
fbits = fopen(bitsFile, "wb");
}
speex_bits_init(&bits);
while (!feof(fin))
{
fread(in_short, sizeof(short), FRAME_SIZE, fin);
if (feof(fin))
break;
speex_bits_reset(&bits);
speex_encode_int(st, in_short, &bits);
nbBits = speex_bits_write(&bits, cbits, 200);
bitCount+=bits.nbBits;
if (argc==4)
fwrite(cbits, 1, nbBits, fbits);
speex_bits_rewind(&bits);
speex_decode_int(dec, &bits, out_short);
speex_bits_reset(&bits);
fwrite(&out_short[skip_group_delay], sizeof(short), FRAME_SIZE-skip_group_delay, fout);
skip_group_delay = 0;
}
fprintf (stderr, "Total encoded size: %d bits\n", bitCount);
speex_encoder_destroy(st);
speex_decoder_destroy(dec);
speex_bits_destroy(&bits);
#ifndef DISABLE_FLOAT_API
{
float sigpow,errpow,snr, seg_snr=0;
sigpow = 0;
errpow = 0;
/* This code just computes SNR, so you don't need it either */
rewind(fin);
rewind(fout);
while ( FRAME_SIZE == fread(in_short, sizeof(short), FRAME_SIZE, fin)
&&
FRAME_SIZE == fread(out_short, sizeof(short), FRAME_SIZE,fout) )
{
float s=0, e=0;
for (i=0;i<FRAME_SIZE;++i) {
s += (float)in_short[i] * in_short[i];
e += ((float)in_short[i]-out_short[i]) * ((float)in_short[i]-out_short[i]);
}
seg_snr += 10*log10((s+160)/(e+160));
sigpow += s;
errpow += e;
snr_frames++;
}
snr = 10 * log10( sigpow / errpow );
seg_snr /= snr_frames;
fprintf(stderr,"SNR = %f\nsegmental SNR = %f\n",snr, seg_snr);
#ifdef FIXED_DEBUG
printf ("Total: %f MIPS\n", (float)(1e-6*50*spx_mips/snr_frames));
#endif
}
#endif
fclose(fin);
fclose(fout);
return 0;
}
| gpl-3.0 |
echoline/PocketSphinxLauncher | main.c | 1 | 3873 | /* PocketSphinxLauncher
* Copyright (C) 2012 Eli Cohen
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <gtk/gtk.h>
#include "dat.h"
#include "fns.h"
//char *adcdev = NULL;
char *modeldir = NULL;
char *hmmdir = NULL;
char *lmdump = NULL;
char *lmdict = NULL;
void sphinx_gui_visibility(GtkStatusIcon *status_icon, gpointer user_data) {
sphinx_gui_listen_t *listen_stuff = (sphinx_gui_listen_t*)user_data;
listen_stuff->visible = !listen_stuff->visible;
gtk_widget_set_visible(listen_stuff->window, listen_stuff->visible);
}
int main(int argc, char *argv[]) {
GtkWidget *vbox;
GtkWidget *hbox;
GtkWidget *text;
GtkWidget *button;
GtkWidget *scrolled;
sphinx_gui_listen_t listen_stuff;
int i;
fprintf (stderr, "PocketSphinx Copyright (c) 1999-2013 Carnegie Mellon University.\n", argv[0]);
fprintf (stderr, "%s Copyright (c) 2013 Eli Cohen\n", argv[0]);
// for (i = 0; i < argc; i++) {
// if (!g_strcmp0(argv[i], "-adcdev")) {
// i++;
// if (i < argc)
// adcdev = g_strdup(argv[i]);
// }
// }
gtk_init (&argc, &argv);
sphinx_gui_config_load();
sphinx_gui_config_save();
listen_stuff.window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
g_signal_connect (listen_stuff.window, "destroy", gtk_main_quit, NULL);
gtk_widget_set_size_request(listen_stuff.window, 640, 240);
vbox = gtk_box_new (GTK_ORIENTATION_VERTICAL, 2);
gtk_container_set_border_width (GTK_CONTAINER (vbox), 3);
gtk_container_add (GTK_CONTAINER (listen_stuff.window), vbox);
scrolled = gtk_scrolled_window_new(NULL, NULL);
listen_stuff.list = sphinx_gui_list_new();
gtk_scrolled_window_add_with_viewport(GTK_SCROLLED_WINDOW(scrolled),
listen_stuff.list);
gtk_box_pack_start (GTK_BOX(vbox), scrolled, TRUE, TRUE, 2);
hbox = gtk_box_new (GTK_ORIENTATION_HORIZONTAL, 2);
button = gtk_button_new_from_stock("gtk-add");
gtk_box_pack_start (GTK_BOX(hbox), button, FALSE, TRUE, 2);
g_signal_connect(button, "clicked", G_CALLBACK(sphinx_gui_list_add),
listen_stuff.list);
button = gtk_button_new_from_stock("gtk-remove");
gtk_box_pack_start (GTK_BOX(hbox), button, FALSE, TRUE, 2);
g_signal_connect(button, "clicked", G_CALLBACK(sphinx_gui_list_remove),
listen_stuff.list);
listen_stuff.status = gtk_image_new_from_stock("gtk-no",
GTK_ICON_SIZE_MENU);
gtk_box_pack_start (GTK_BOX(hbox), listen_stuff.status, FALSE, TRUE, 2);
listen_stuff.label = gtk_label_new("");
gtk_box_pack_start (GTK_BOX(hbox), listen_stuff.label, TRUE, TRUE, 2);
button = gtk_button_new_with_label("Configure");
gtk_box_pack_start (GTK_BOX(hbox), button, FALSE, TRUE, 2);
g_signal_connect(button, "clicked", G_CALLBACK(sphinx_gui_configure),
&listen_stuff);
gtk_box_pack_start (GTK_BOX(vbox), hbox, FALSE, TRUE, 2);
listen_stuff.tray = gtk_status_icon_new_from_stock("gtk-no");
g_signal_connect(listen_stuff.tray, "activate",
G_CALLBACK(sphinx_gui_visibility), &listen_stuff);
if (!sphinx_gui_listen(&listen_stuff)) {
listen_stuff.status = gtk_image_new_from_stock("gtk-no",
GTK_ICON_SIZE_MENU);
listen_stuff.tray = gtk_status_icon_new_from_stock("gtk-no");
}
g_timeout_add(1, &sphinx_gui_listen_timeout, &listen_stuff);
listen_stuff.visible = TRUE;
gtk_widget_show_all (listen_stuff.window);
gtk_main ();
return 0;
}
| gpl-3.0 |
Zulcom/Programming-Basis-II | Lab12/Maximovich Yuriy/12.cpp | 1 | 1953 | #include <iostream>
#include <cstdlib>
#include <cmath>
#include <clocale>
#include <iomanip>
#include <conio.h>
#define M_PI 3.14159265358979323846
using namespace std;
double arctg(double x)
{
return atan(x)*atan(x);
}
double sinus(double x)
{
return sin(exp(x));
}
double exponenta(double x)
{
return exp(-1 * x * x);
}
double(*integral[3])(double) = { arctg, sinus, exponenta };
double rectangle(double(*f)(double), double niz, double verh, double E)
{
double sum = 0, predsum = 0;
int n = 10;
double h = (verh - niz) / n;
double x = niz + h;
for (int i = 1; i <= n; ++i)
{
double b = f(x);
sum += b;
x += h;
}
sum *= h;
while (abs((sum - predsum) / 4) > E)
{
n *= 2;
predsum = sum;
sum = 0;
h = (verh - niz) / n;
x = niz + h;
for (int i = 1; i <= n; ++i)
{
double b = f(x);
sum += b;
x += h;
}
sum *= h;
}
return sum;
}
int main()
{
setlocale(LC_ALL, "russian");
double a, b, c, d, E;
cout << "Введите пределы интегрирования:" << endl;
cout << "a и b , где b > a: ";
cin >> a >> b;
cout << "c и d, где d > c: ";
cin >> c >> d;
cout << "Введите точность вычисления: ";
cin >> E;
while (true)
{
if (a > b || c > d)
{
cout << "Значения введены неверно. Введите заново!" << endl << endl;
cout << "Введите пределы интегрирования:" << endl;
cout << "a и b , где b > a: ";
cin >> a >> b;
cout << "c и d, где d > c: ";
cin >> c >> d;
cout << "Введите точность вычисления: ";
cin >> E;
}
else break;
}
double summa = 0;
summa += rectangle(integral[0], c, d, E);
summa += rectangle(integral[1], 0, M_PI, E);
summa += rectangle(integral[2], a, b, E);
cout << "Сумма интегралов по правилу правых прямоугольников равна: " << summa;
_getch();
return 0;
}
| gpl-3.0 |
faywong/watermarking | c_peter_meerwald/Meerwald/wm_kund3_d.c | 1 | 8004 | #include "wm.h"
#include "signature.h"
#include "dwt.h"
#include "pgm.h"
char *progname;
void usage(void) {
fprintf(stderr, "usage: %s [-e n] [-f n] [-F n] [-h] [-l n] [-o file] [-q n] [-s file] [-v n] file\n\n", progname);
fprintf(stderr, "\t-e n\t\twavelet filtering method\n");
fprintf(stderr, "\t-f n\t\tfilter number\n");
fprintf(stderr, "\t-F file\t\tfilter definition file\n");
fprintf(stderr, "\t-h\t\tprint usage\n");
fprintf(stderr, "\t-l n\t\tembedding level\n");
fprintf(stderr, "\t-o file\t\textracted signature file\n");
fprintf(stderr, "\t-q n\t\tsignature strength\n");
fprintf(stderr, "\t-s file\t\toriginal signature file\n");
fprintf(stderr, "\t-v n\t\tverbosity level\n");
exit(0);
}
int main(int argc, char *argv[]) {
FILE *in = stdin;
FILE *out = stdout;
FILE *sig = NULL;
gray **input_image;
char signature_name[MAXPATHLEN];
char output_name[MAXPATHLEN] = "(stdout)";
char input_name[MAXPATHLEN] = "(stdin)";
int r, c;
int quality = 0;
int seed = 0;
int n = 0;
int method = -1;
int filter = 0;
char filter_name[MAXPATHLEN] = "";
char *binstr;
int level = 0;
int in_rows, in_cols, in_format;
gray in_maxval;
int rows, cols;
int row, col;
Image_tree dwts, p;
int verbose = 0;
progname = argv[0];
pgm_init(&argc, argv);
wm_init();
while ((c = getopt(argc, argv, "e:f:F:h?l:o:q:s:v:")) != EOF) {
switch (c) {
case 'e':
method = atoi(optarg);
if (method < 0) {
fprintf(stderr, "%s: wavelet filtering method %d out of range\n", progname, method);
exit(1);
}
break;
case 'f':
filter = atoi(optarg);
if (filter <= 0) {
fprintf(stderr, "%s: filter number %d out of range\n", progname, filter);
exit(1);
}
break;
case 'F':
strcpy(filter_name, optarg);
break;
case 'h':
case '?':
usage();
break;
case 'l':
level = atoi(optarg);
if (level < 1) {
fprintf(stderr, "%s: embedding level out of range\n", progname);
exit(1);
}
break;
case 'o':
if ((out = fopen(optarg, "w")) == NULL) {
fprintf(stderr, "%s: unable to open output file %s\n", progname, optarg);
exit(1);
}
strcpy(output_name, optarg);
break;
case 'q':
quality = atoi(optarg);
if (quality < 1) {
fprintf(stderr, "%s: quality level %d out of range\n", progname, quality);
exit(1);
}
break;
case 's':
if ((sig = fopen(optarg, "r")) == NULL) {
fprintf(stderr, "%s: unable to open signature file %s\n", progname, optarg);
exit(1);
}
strcpy(signature_name, optarg);
break;
case 'v':
verbose = atoi(optarg);
if (verbose < 0) {
fprintf(stderr, "%s: verbosity level %d out of range\n", progname, verbose);
exit(1);
}
break;
}
}
argc -= optind;
argv += optind;
if (argc > 1) {
usage();
exit(1);
}
if (argc == 1 && *argv[0] != '-') {
if ((in = fopen(argv[0], "rb")) == NULL) {
fprintf(stderr, "%s: unable to open input file %s\n", progname, argv[0]);
exit(1);
}
else
strcpy(input_name, argv[0]);
}
if (sig) {
char line[32];
fgets(line, sizeof(line), sig);
if (strspn(line, "KD3SG") >= 5) {
fscanf(sig, "%d\n", &nbit_signature);
if (quality == 0)
fscanf(sig, "%d\n", &quality);
else
fscanf(sig, "%*d\n");
if (method < 0)
fscanf(sig, "%d\n", &method);
else
fscanf(sig, "%*d\n");
if (filter == 0)
fscanf(sig, "%d\n", &filter);
else
fscanf(sig, "%*d\n");
if (!strcmp(filter_name, ""))
fscanf(sig, "%[^\n\r]\n", filter_name);
else
fscanf(sig, "%*[^\n\r]\n");
if (level == 0)
fscanf(sig, "%d\n", &level);
else
fscanf(sig, "%*d\n");
fscanf(sig, "%d\n", &seed);
srandom(seed);
nbit_signature2 = nbit_signature;
n_signature = n_signature2 = NBITSTOBYTES(nbit_signature2);
binstr = malloc((nbit_signature2 + 1) * sizeof(char));
fscanf(sig, "%[01]\n", binstr);
binstr_to_sig2(binstr);
free(binstr);
init_signature_bits();
}
else {
fprintf(stderr, "%s: invalid signature file %s\n", progname, signature_name);
exit(1);
}
fclose(sig);
}
else {
fprintf(stderr, "%s: signature file not specified, use -s file option\n", progname);
exit(1);
}
pgm_readpgminit(in, &in_cols, &in_rows, &in_maxval, &in_format);
cols = in_cols;
rows = in_rows;
if (verbose > 0)
fprintf(stderr, "%s: extracting %d bits with quality %d from\n"
" %d x %d host image, decomposition level %d\n",
progname, nbit_signature, quality, cols, rows, level);
input_image = pgm_allocarray(in_cols, in_rows);
for (row = 0; row < in_rows; row++)
pgm_readpgmrow(in, input_image[row], in_cols, in_maxval, in_format);
fclose(in);
init_dwt(cols, rows, filter_name, filter, level, method);
/*#ifdef POLLEN_STUFF
#include "pollen_stuff.c"
#endif
#ifdef PARAM_STUFF
#include "param_stuff.c"
#endif*/
dwts = fdwt(input_image);
p = dwts;
#define STEP 3
// consider each resolution level
while (p->coarse->level < level)
// descend one level
p = p->coarse;
// start to extracting watermark from beginning at each level
{
// get width and height of detail images at current level
int lwidth = p->vertical->image->width;
int lheight = p->vertical->image->height;
if (verbose > 1)
fprintf(stderr, "%s: extracting at level %d now, size %d x %d\n",
progname, p->coarse->level, lwidth, lheight);
// consider each coefficient at resolution level
for (row = 0; row < lwidth - STEP; row += STEP)
for (col = 0; col < lheight - STEP; col += STEP) {
double h, v, d;
double *f1 = &h, *f2 = &v, *f3 = &d;
double delta;
// key-dependant coefficient selection
r = row + 1 + random() % (STEP-2);
c = col + 1 + random() % (STEP-2);
// get coefficient values, one from each detail image
h = get_pixel(p->horizontal->image, c, r);
v = get_pixel(p->vertical->image, c, r);
d = get_pixel(p->diagonal->image, c, r);
// order pointer to coefficient values such that f1 <= f2 <= f3
#define SWAP(A, B) {double *t = A; A = B; B = t;}
if (*f1 > *f2) SWAP(f1, f2);
if (*f2 > *f3) SWAP(f2, f3);
if (*f1 > *f2) SWAP(f1, f2);
// calculate delta, the width of the bins
delta = (*f3 - *f1) / (double) (2 * quality - 1);
// set middle coefficient to closest appropriate bin,
// according to watermark bit
if (quality == 1)
set_signature_bit(n, (*f3 - *f2) < (*f2 - *f1));
else {
double l = *f1;
int i = 0;
while ((l + delta) < *f2) {
l += delta;
i++;
}
if (i % 2)
set_signature_bit(n, (l + delta - *f2) > (*f2 - l));
else
set_signature_bit(n, (l + delta - *f2) < (*f2 - l));
}
if (verbose > 2)
fprintf(stderr, "%s: extracted bit #%d (= %d =? %d) at (%d/%d),\n"
" f1=%lf, f2=%lf, f3=%lf\n", progname, n,
get_signature_bit(n), get_signature2_bit(n),
c, r, *f1, *f2, *f3);
n++;
}
}
fprintf(out, "KD3WM\n");
fprintf(out, "%d\n", n);
nbit_signature = n;
binstr = malloc(sizeof(char) * (nbit_signature + 1));
sig_to_binstr(binstr);
fprintf(out, "%s\n", binstr);
free(binstr);
fclose(out);
pgm_freearray(input_image, rows);
exit(0);
}
| gpl-3.0 |
bend/CPPWrappers | Net/HttpProtocol.cpp | 1 | 1293 | /*
* Copyright © Ben D.
* dbapps2@gmail.com
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <Net/HttpProtocol.h>
HttpProtocol::HttpProtocol(Host& h):
TcpSocket(),
m_host(h)
{
}
AbstractSocket::Status HttpProtocol::sendRequest(HttpRequest& request)
{
m_response.clean();
if (request.checkAndFix() < 0)
return InvalidRequest;
if (connect(m_host) != Done)
return getStatus();
if (sendString(request.toString()) != Done)
return getStatus();
string str = "";
while (receiveString(str, 1024) == Done)
{
m_response.append(str);
}
}
HttpResponse& HttpProtocol::getResponse()
{
return m_response;
}
| gpl-3.0 |
nuoHep/simc | engine/player/sc_set_bonus.cpp | 1 | 12509 | // ==========================================================================
// Dedmonwakeen's Raid DPS/TPS Simulator.
// Send questions to natehieter@gmail.com
// ==========================================================================
#include "set_bonus.hpp"
#include "dbc/dbc.hpp"
#include "dbc/item_set_bonus.hpp"
#include "item/item.hpp"
#include "player/sc_player.hpp"
#include "sim/sc_expressions.hpp"
#include "sim/sc_sim.hpp"
set_bonus_t::set_bonus_t( player_t* player ) :
actor( player ),
set_bonus_spec_data( SET_BONUS_MAX ),
set_bonus_spec_count( SET_BONUS_MAX )
{
for ( size_t i = 0; i < set_bonus_spec_data.size(); i++ )
{
set_bonus_spec_data[ i ].resize( actor->dbc->specialization_max_per_class() );
set_bonus_spec_count[ i ].resize( actor->dbc->specialization_max_per_class() );
// For now only 2, and 4 set bonuses
for ( size_t j = 0; j < set_bonus_spec_data[ i ].size(); j++ )
{
set_bonus_spec_data[ i ][ j ].resize( N_BONUSES, set_bonus_data_t(spell_data_t::not_found()) );
set_bonus_spec_count[ i ][ j ] = 0;
}
}
if ( actor->is_pet() || actor->is_enemy() )
return;
auto set_bonuses = item_set_bonus_t::data( actor->dbc->ptr );
// Initialize the set bonus data structure with correct set bonus data.
// Spells are not setup yet.
for ( const auto& bonus : set_bonuses )
{
if ( bonus.class_id != -1 && bonus.class_id != util::class_id( actor->type ) )
continue;
// Ensure Blizzard does not go crazy and add set bonuses past 8 item requirement
assert( bonus.bonus <= B_MAX );
// T17 onwards and PVP, new world, spec specific set bonuses. Overrides are
// going to be provided by the new set_bonus= option, so no need to
// translate anything from the old set bonus options.
//
// All specs share the same set bonus
if ( bonus.spec == -1 )
{
for ( size_t spec_idx = 0; spec_idx < set_bonus_spec_data[ bonus.enum_id ].size(); spec_idx++ )
{
// Don't allow generic set bonus to override spec specific one, if it exists. The exporter
// should export data so that this will never happen, but be extra careful.
if ( set_bonus_spec_data[ bonus.enum_id ][ spec_idx ][ bonus.bonus - 1 ].bonus )
{
continue;
}
set_bonus_spec_data[ bonus.enum_id ][ spec_idx ][ bonus.bonus - 1 ].bonus = &bonus;
}
}
// Note, Spec specific set bonuses are allowed to override "generic" bonuses (bonus.spec == -1)
else
{
assert( bonus.spec > 0 );
specialization_e spec = static_cast< specialization_e >( bonus.spec );
set_bonus_spec_data[ bonus.enum_id ][ dbc::spec_idx( spec ) ][ bonus.bonus - 1 ].bonus = &bonus;
}
}
}
// Initialize set bonus counts based on the items of the actor
void set_bonus_t::initialize_items()
{
// Don't allow 2 worn items of the same id to count as 2 slots
std::vector<unsigned> item_ids;
for ( auto& item : actor->items)
{
if ( item.parsed.data.id == 0 )
continue;
if ( item.parsed.data.id_set == 0 )
continue;
auto set_bonuses = item_set_bonus_t::data( actor->dbc->ptr );
for ( const auto& bonus : set_bonuses )
{
if ( bonus.set_id != static_cast<unsigned>( item.parsed.data.id_set ) )
continue;
if ( bonus.class_id != -1 && ! bonus.has_spec( static_cast<int>( actor->_spec ) ) )
continue;
if ( range::find( item_ids, item.parsed.data.id ) != item_ids.end() )
{
continue;
}
// T17+ and PVP is spec specific, T16 and lower is "role specific"
set_bonus_spec_count[ bonus.enum_id ][ dbc::spec_idx( actor->_spec ) ]++;
item_ids.push_back( item.parsed.data.id );
break;
}
}
}
std::vector<const item_set_bonus_t*> set_bonus_t::enabled_set_bonus_data() const
{
std::vector<const item_set_bonus_t*> bonuses;
// Disable all set bonuses, and set bonus options if challenge mode is set
if ( actor->sim->challenge_mode == 1 )
return bonuses;
if ( actor->sim->disable_set_bonuses == 1 ) // Or if global disable set bonus override is used.
return bonuses;
for ( auto& spec_data : set_bonus_spec_data )
{
for ( auto& bonus_type : spec_data )
{
for ( auto& bonus_data : bonus_type )
{
// Most specs have the fourth specialization empty, or only have
// limited number of roles, so there's no set bonuses for those entries
if ( bonus_data.bonus == nullptr )
continue;
if ( bonus_data.spell->id() == 0 )
{
continue;
}
bonuses.push_back( bonus_data.bonus );
}
}
}
return bonuses;
}
// Fast accessor to a set bonus spell, returns the spell, or spell_data_t::not_found()
const spell_data_t* set_bonus_t::set(specialization_e spec, set_bonus_type_e set_bonus, set_bonus_e bonus) const
{
if ( dbc::spec_idx(spec) < 0 )
{
return spell_data_t::nil();
}
#ifndef NDEBUG
assert(set_bonus_spec_data.size() > (unsigned)set_bonus);
assert(set_bonus_spec_data[set_bonus].size() > (unsigned)dbc::spec_idx(spec));
assert(set_bonus_spec_data[set_bonus][dbc::spec_idx(spec)].size() > (unsigned)bonus);
#endif
return set_bonus_spec_data[set_bonus][dbc::spec_idx(spec)][bonus].spell;
}
void set_bonus_t::initialize()
{
// Disable all set bonuses, and set bonus options if challenge mode is set
if ( actor->sim->challenge_mode == 1 )
return;
if ( actor->sim->disable_set_bonuses == 1 ) // Or if global disable set bonus override is used.
return;
initialize_items();
// Enable set bonuses then. This is a combination of item-based enablation
// (enough items to enable a set bonus), and override based set bonus
// enablation. As always, user options override everything else.
for ( size_t idx = 0; idx < set_bonus_spec_data.size(); idx++ )
{
for ( size_t spec_idx = 0; spec_idx < set_bonus_spec_data[ idx ].size(); spec_idx++ )
{
for ( size_t bonus_idx = 0; bonus_idx < set_bonus_spec_data[ idx ][ spec_idx ].size(); bonus_idx++ )
{
set_bonus_data_t& data = set_bonus_spec_data[ idx ][ spec_idx ][ bonus_idx ];
// Most specs have the fourth specialization empty, or only have
// limited number of roles, so there's no set bonuses for those entries
if ( data.bonus == nullptr )
continue;
unsigned spec_role_idx = static_cast<int>( spec_idx );
// Set bonus is overridden, or we have sufficient number of items to enable the bonus
if ( data.overridden >= 1 ||
( set_bonus_spec_count[idx][spec_role_idx] >= data.bonus->bonus && data.overridden == -1 ) ||
( data.bonus->has_spec( actor->_spec ) &&
( ! util::str_in_str_ci( data.bonus->set_opt_name, "lfr" ) &&
( ( actor->sim->enable_2_set == data.bonus->tier && data.bonus->bonus == 2 ) ||
( actor->sim->enable_4_set == data.bonus->tier && data.bonus->bonus == 4 ) ) ) ) )
{
if ( data.bonus->bonus == 2 )
{
if ( actor->sim->disable_2_set != data.bonus->tier )
{
data.spell = actor->find_spell( data.bonus->spell_id );
data.enabled = true;
}
else
{
data.enabled = false;
}
}
else if ( data.bonus->bonus == 4 )
{
if ( actor->sim->disable_4_set != data.bonus->tier )
{
data.spell = actor->find_spell( data.bonus->spell_id );
data.enabled = true;
}
else
{
data.enabled = false;
}
}
else
{
data.spell = actor->find_spell( data.bonus->spell_id );
data.enabled = true;
}
}
}
}
}
actor->sim->print_debug("Initialized set bonus: {}", *this);
}
bool set_bonus_t::has_set_bonus(specialization_e spec, set_bonus_type_e set_bonus, set_bonus_e bonus) const
{
if ( dbc::spec_idx(spec) < 0 )
{
return false;
}
return set_bonus_spec_data[set_bonus][dbc::spec_idx(spec)][bonus].enabled;
}
std::string set_bonus_t::to_string() const
{
return fmt::format( "{}", *this );
}
void format_to( const set_bonus_t& sb, fmt::format_context::iterator out )
{
int i = 0;
for ( size_t idx = 0; idx < sb.set_bonus_spec_data.size(); idx++ )
{
for ( size_t spec_idx = 0; spec_idx < sb.set_bonus_spec_data[ idx ].size(); spec_idx++ )
{
for ( size_t bonus_idx = 0; bonus_idx < sb.set_bonus_spec_data[ idx ][ spec_idx ].size(); bonus_idx++ )
{
auto& data = sb.set_bonus_spec_data[ idx ][ spec_idx ][ bonus_idx ];
if ( data.bonus == nullptr )
continue;
unsigned spec_role_idx = static_cast<int>( spec_idx );
if ( data.overridden >= 1 ||
( data.overridden == -1 && sb.set_bonus_spec_count[ idx ][ spec_role_idx ] >= data.bonus->bonus ) )
{
fmt::format_to( out, "{}{{ {}, {}, {}, {} piece bonus {} }}",
i > 0 ? ", " : "",
data.bonus->set_name,
data.bonus->set_opt_name,
util::specialization_string( sb.actor->specialization() ),
data.bonus->bonus,
( data.overridden >= 1 ) ? " (overridden)" : "");
++i;
}
}
}
}
}
std::string set_bonus_t::to_profile_string( const std::string& newline ) const
{
std::string s;
for ( size_t idx = 0; idx < set_bonus_spec_data.size(); idx++ )
{
for ( size_t spec_idx = 0; spec_idx < set_bonus_spec_data[ idx ].size(); spec_idx++ )
{
for ( size_t bonus_idx = 0; bonus_idx < set_bonus_spec_data[ idx ][ spec_idx ].size(); bonus_idx++ )
{
const set_bonus_data_t& data = set_bonus_spec_data[ idx ][ spec_idx ][ bonus_idx ];
if ( data.bonus == nullptr )
continue;
unsigned spec_role_idx = static_cast<int>( spec_idx );
if ( data.overridden >= 1 ||
( data.overridden == -1 && set_bonus_spec_count[ idx ][ spec_role_idx ] >= data.bonus->bonus ) )
{
s += fmt::format("# set_bonus={}_{}pc=1{}",
data.bonus->set_opt_name,
data.bonus->bonus,
newline);
}
}
}
}
return s;
}
std::unique_ptr<expr_t> set_bonus_t::create_expression( const player_t* , util::string_view type )
{
set_bonus_type_e set_bonus = SET_BONUS_NONE;
set_bonus_e bonus = B_NONE;
if ( ! parse_set_bonus_option( type, set_bonus, bonus ) )
{
throw std::invalid_argument(fmt::format("Cannot parse set bonus '{}'.", type));
}
bool state = set_bonus_spec_data[ set_bonus ][ dbc::spec_idx( actor->specialization() ) ][ bonus ].spell->id() > 0;
return expr_t::create_constant( type, static_cast<double>(state) );
}
bool set_bonus_t::parse_set_bonus_option( util::string_view opt_str,
set_bonus_type_e& set_bonus,
set_bonus_e& bonus )
{
set_bonus = SET_BONUS_NONE;
bonus = B_NONE;
auto split = util::string_split<util::string_view>( opt_str, "_" );
if ( split.size() < 2 )
{
return false;
}
auto bonus_offset = split.back().find( "pc" );
if ( bonus_offset == std::string::npos )
{
return false;
}
auto b = util::to_unsigned( split.back().substr( 0, bonus_offset ) );
if ( b > B_MAX )
{
return false;
}
bonus = static_cast<set_bonus_e>( b - 1 );
auto set_name = opt_str.substr( 0, opt_str.size() - split.back().size() - 1 );
auto set_bonuses = item_set_bonus_t::data( SC_USE_PTR );
for ( const auto& bonus : set_bonuses )
{
if ( bonus.class_id != -1 && bonus.class_id != util::class_id( actor->type ) )
continue;
if ( set_bonus == SET_BONUS_NONE && util::str_compare_ci( set_name, bonus.set_opt_name ) )
{
set_bonus = static_cast< set_bonus_type_e >( bonus.enum_id );
break;
}
}
return set_bonus != SET_BONUS_NONE && bonus != B_NONE;
}
std::string set_bonus_t::generate_set_bonus_options() const
{
std::vector<std::string> opts;
auto set_bonuses = item_set_bonus_t::data( SC_USE_PTR );
for ( const auto& bonus : set_bonuses )
{
std::string opt = fmt::format( "{}_{}pc", bonus.set_opt_name, bonus.bonus );
if ( std::find( opts.begin(), opts.end(), opt ) == opts.end() )
{
opts.push_back(opt);
}
}
return util::string_join( opts, ", " );
}
| gpl-3.0 |
SkyFireArchives/SkyFireEMU_406a | src/server/scripts/Northrend/Ulduar/Ulduar/boss_thorim.cpp | 2 | 3213 | /*
* Copyright (C) 2011-2019 Project SkyFire <http://www.projectskyfire.org/>
* Copyright (C) 2008-2019 TrinityCore <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 3 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScriptMgr.h"
#include "ScriptedCreature.h"
#include "ulduar.h"
enum Yells
{
SAY_AGGRO_1 = -1603270,
SAY_AGGRO_2 = -1603271,
SAY_SPECIAL_1 = -1603272,
SAY_SPECIAL_2 = -1603273,
SAY_SPECIAL_3 = -1603274,
SAY_JUMPDOWN = -1603275,
SAY_SLAY_1 = -1603276,
SAY_SLAY_2 = -1603277,
SAY_BERSERK = -1603278,
SAY_WIPE = -1603279,
SAY_DEATH = -1603280,
SAY_END_NORMAL_1 = -1603281,
SAY_END_NORMAL_2 = -1603282,
SAY_END_NORMAL_3 = -1603283,
SAY_END_HARD_1 = -1603284,
SAY_END_HARD_2 = -1603285,
SAY_END_HARD_3 = -1603286,
SAY_YS_HELP = -1603287,
};
class boss_thorim : public CreatureScript
{
public:
boss_thorim() : CreatureScript("boss_thorim") { }
CreatureAI* GetAI(Creature* creature) const
{
return GetUlduarAI<boss_thorimAI>(creature);
}
struct boss_thorimAI : public BossAI
{
boss_thorimAI(Creature* creature) : BossAI(creature, BOSS_THORIM)
{
}
void Reset()
{
_Reset();
}
void EnterEvadeMode()
{
DoScriptText(SAY_WIPE, me);
_EnterEvadeMode();
}
void KilledUnit(Unit* /*victim*/)
{
DoScriptText(RAND(SAY_SLAY_1, SAY_SLAY_2), me);
}
void JustDied(Unit* /*victim*/)
{
DoScriptText(SAY_DEATH, me);
_JustDied();
}
void EnterCombat(Unit* /*who*/)
{
DoScriptText(RAND(SAY_AGGRO_1, SAY_AGGRO_2), me);
_EnterCombat();
}
void UpdateAI(const uint32 diff)
{
if (!UpdateVictim())
return;
//SPELLS TODO:
//
DoMeleeAttackIfReady();
EnterEvadeIfOutOfCombatArea(diff);
}
};
};
void AddSC_boss_thorim()
{
new boss_thorim();
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | external/elfutils/0.153/src/unstrip.c | 2 | 69796 | /* Combine stripped files with separate symbols and debug information.
Copyright (C) 2007-2012 Red Hat, Inc.
This file is part of Red Hat elfutils.
Written by Roland McGrath <roland@redhat.com>, 2007.
Red Hat elfutils 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.
Red Hat elfutils 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 Red Hat elfutils; if not, write to the Free Software Foundation,
Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301 USA.
Red Hat elfutils is an included package of the Open Invention Network.
An included package of the Open Invention Network is a package for which
Open Invention Network licensees cross-license their patents. No patent
license is granted, either expressly or impliedly, by designation as an
included package. Should you wish to participate in the Open Invention
Network licensing program, please visit www.openinventionnetwork.com
<http://www.openinventionnetwork.com>. */
/* TODO:
* SHX_XINDEX
* prelink vs .debug_* linked addresses
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <argp.h>
#include <assert.h>
#include <errno.h>
#include <error.h>
#include <fcntl.h>
#include <fnmatch.h>
#include <libintl.h>
#include <locale.h>
#include <mcheck.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdio_ext.h>
#include <inttypes.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/stat.h>
#include <gelf.h>
#include <libebl.h>
#include <libdwfl.h>
#include "system.h"
#ifndef _
# define _(str) gettext (str)
#endif
/* Name and version of program. */
static void print_version (FILE *stream, struct argp_state *state);
ARGP_PROGRAM_VERSION_HOOK_DEF = print_version;
/* Bug report address. */
ARGP_PROGRAM_BUG_ADDRESS_DEF = PACKAGE_BUGREPORT;
/* Definitions of arguments for argp functions. */
static const struct argp_option options[] =
{
/* Group 2 will follow group 1 from dwfl_standard_argp. */
{ "match-file-names", 'f', NULL, 0,
N_("Match MODULE against file names, not module names"), 2 },
{ "ignore-missing", 'i', NULL, 0, N_("Silently skip unfindable files"), 0 },
{ NULL, 0, NULL, 0, N_("Output options:"), 0 },
{ "output", 'o', "FILE", 0, N_("Place output into FILE"), 0 },
{ "output-directory", 'd', "DIRECTORY",
0, N_("Create multiple output files under DIRECTORY"), 0 },
{ "module-names", 'm', NULL, 0, N_("Use module rather than file names"), 0 },
{ "all", 'a', NULL, 0,
N_("Create output for modules that have no separate debug information"),
0 },
{ "relocate", 'R', NULL, 0,
N_("Apply relocations to section contents in ET_REL files"), 0 },
{ "list-only", 'n', NULL, 0,
N_("Only list module and file names, build IDs"), 0 },
{ NULL, 0, NULL, 0, NULL, 0 }
};
struct arg_info
{
const char *output_file;
const char *output_dir;
Dwfl *dwfl;
char **args;
bool list;
bool all;
bool ignore;
bool modnames;
bool match_files;
bool relocate;
};
/* Handle program arguments. */
static error_t
parse_opt (int key, char *arg, struct argp_state *state)
{
struct arg_info *info = state->input;
switch (key)
{
case ARGP_KEY_INIT:
state->child_inputs[0] = &info->dwfl;
break;
case 'o':
if (info->output_file != NULL)
{
argp_error (state, _("-o option specified twice"));
return EINVAL;
}
info->output_file = arg;
break;
case 'd':
if (info->output_dir != NULL)
{
argp_error (state, _("-d option specified twice"));
return EINVAL;
}
info->output_dir = arg;
break;
case 'm':
info->modnames = true;
break;
case 'f':
info->match_files = true;
break;
case 'a':
info->all = true;
break;
case 'i':
info->ignore = true;
break;
case 'n':
info->list = true;
break;
case 'R':
info->relocate = true;
break;
case ARGP_KEY_ARGS:
case ARGP_KEY_NO_ARGS:
/* We "consume" all the arguments here. */
info->args = &state->argv[state->next];
if (info->output_file != NULL && info->output_dir != NULL)
{
argp_error (state, _("only one of -o or -d allowed"));
return EINVAL;
}
if (info->list && (info->dwfl == NULL
|| info->output_dir != NULL
|| info->output_file != NULL))
{
argp_error (state,
_("-n cannot be used with explicit files or -o or -d"));
return EINVAL;
}
if (info->output_dir != NULL)
{
struct stat64 st;
error_t fail = 0;
if (stat64 (info->output_dir, &st) < 0)
fail = errno;
else if (!S_ISDIR (st.st_mode))
fail = ENOTDIR;
if (fail)
{
argp_failure (state, EXIT_FAILURE, fail,
_("output directory '%s'"), info->output_dir);
return fail;
}
}
if (info->dwfl == NULL)
{
if (state->next + 2 != state->argc)
{
argp_error (state, _("exactly two file arguments are required"));
return EINVAL;
}
if (info->ignore || info->all || info->modnames || info->relocate)
{
argp_error (state, _("\
-m, -a, -R, and -i options not allowed with explicit files"));
return EINVAL;
}
/* Bail out immediately to prevent dwfl_standard_argp's parser
from defaulting to "-e a.out". */
return ENOSYS;
}
else if (info->output_file == NULL && info->output_dir == NULL
&& !info->list)
{
argp_error (state,
_("-o or -d is required when using implicit files"));
return EINVAL;
}
break;
default:
return ARGP_ERR_UNKNOWN;
}
return 0;
}
/* Print the version information. */
static void
print_version (FILE *stream, struct argp_state *state __attribute__ ((unused)))
{
fprintf (stream, "unstrip (%s) %s\n", PACKAGE_NAME, PACKAGE_VERSION);
fprintf (stream, _("\
Copyright (C) %s Red Hat, Inc.\n\
This is free software; see the source for copying conditions. There is NO\n\
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.\n\
"), "2012");
fprintf (stream, gettext ("Written by %s.\n"), "Roland McGrath");
}
#define ELF_CHECK(call, msg) \
do \
{ \
if (!(call)) \
error (EXIT_FAILURE, 0, msg, elf_errmsg (-1)); \
} while (0)
/* Copy INELF to newly-created OUTELF, exit via error for any problems. */
static void
copy_elf (Elf *outelf, Elf *inelf)
{
ELF_CHECK (gelf_newehdr (outelf, gelf_getclass (inelf)),
_("cannot create ELF header: %s"));
GElf_Ehdr ehdr_mem;
GElf_Ehdr *ehdr = gelf_getehdr (inelf, &ehdr_mem);
ELF_CHECK (gelf_update_ehdr (outelf, ehdr),
_("cannot copy ELF header: %s"));
if (ehdr->e_phnum > 0)
{
ELF_CHECK (gelf_newphdr (outelf, ehdr->e_phnum),
_("cannot create program headers: %s"));
GElf_Phdr phdr_mem;
for (uint_fast16_t i = 0; i < ehdr->e_phnum; ++i)
ELF_CHECK (gelf_update_phdr (outelf, i,
gelf_getphdr (inelf, i, &phdr_mem)),
_("cannot copy program header: %s"));
}
Elf_Scn *scn = NULL;
while ((scn = elf_nextscn (inelf, scn)) != NULL)
{
Elf_Scn *newscn = elf_newscn (outelf);
GElf_Shdr shdr_mem;
ELF_CHECK (gelf_update_shdr (newscn, gelf_getshdr (scn, &shdr_mem)),
_("cannot copy section header: %s"));
Elf_Data *data = elf_getdata (scn, NULL);
ELF_CHECK (data != NULL, _("cannot get section data: %s"));
Elf_Data *newdata = elf_newdata (newscn);
ELF_CHECK (newdata != NULL, _("cannot copy section data: %s"));
*newdata = *data;
elf_flagdata (newdata, ELF_C_SET, ELF_F_DIRTY);
}
}
/* Create directories containing PATH. */
static void
make_directories (const char *path)
{
const char *lastslash = strrchr (path, '/');
if (lastslash == NULL)
return;
while (lastslash > path && lastslash[-1] == '/')
--lastslash;
if (lastslash == path)
return;
char *dir = strndupa (path, lastslash - path);
while (mkdir (dir, 0777) < 0 && errno != EEXIST)
if (errno == ENOENT)
make_directories (dir);
else
error (EXIT_FAILURE, errno, _("cannot create directory '%s'"), dir);
}
/* The binutils linker leaves gratuitous section symbols in .symtab
that strip has to remove. Older linkers likewise include a
symbol for every section, even unallocated ones, in .dynsym.
Because of this, the related sections can shrink in the stripped
file from their original size. Older versions of strip do not
adjust the sh_size field in the debuginfo file's SHT_NOBITS
version of the section header, so it can appear larger. */
static bool
section_can_shrink (const GElf_Shdr *shdr)
{
switch (shdr->sh_type)
{
case SHT_SYMTAB:
case SHT_DYNSYM:
case SHT_HASH:
case SHT_GNU_versym:
return true;
}
return false;
}
/* See if this symbol table has a leading section symbol for every single
section, in order. The binutils linker produces this. While we're here,
update each section symbol's st_value. */
static size_t
symtab_count_leading_section_symbols (Elf *elf, Elf_Scn *scn, size_t shnum,
Elf_Data *newsymdata)
{
Elf_Data *data = elf_getdata (scn, NULL);
Elf_Data *shndxdata = NULL; /* XXX */
for (size_t i = 1; i < shnum; ++i)
{
GElf_Sym sym_mem;
GElf_Word shndx = SHN_UNDEF;
GElf_Sym *sym = gelf_getsymshndx (data, shndxdata, i, &sym_mem, &shndx);
ELF_CHECK (sym != NULL, _("cannot get symbol table entry: %s"));
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (elf_getscn (elf, i), &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
if (sym->st_shndx != SHN_XINDEX)
shndx = sym->st_shndx;
if (shndx != i || GELF_ST_TYPE (sym->st_info) != STT_SECTION)
return i;
sym->st_value = shdr->sh_addr;
if (sym->st_shndx != SHN_XINDEX)
shndx = SHN_UNDEF;
ELF_CHECK (gelf_update_symshndx (newsymdata, shndxdata, i, sym, shndx),
_("cannot update symbol table: %s"));
}
return shnum;
}
static void
update_shdr (Elf_Scn *outscn, GElf_Shdr *newshdr)
{
ELF_CHECK (gelf_update_shdr (outscn, newshdr),
_("cannot update section header: %s"));
}
/* We expanded the output section, so update its header. */
static void
update_sh_size (Elf_Scn *outscn, const Elf_Data *data)
{
GElf_Shdr shdr_mem;
GElf_Shdr *newshdr = gelf_getshdr (outscn, &shdr_mem);
ELF_CHECK (newshdr != NULL, _("cannot get section header: %s"));
newshdr->sh_size = data->d_size;
update_shdr (outscn, newshdr);
}
/* Update relocation sections using the symbol table. */
static void
adjust_relocs (Elf_Scn *outscn, Elf_Scn *inscn, const GElf_Shdr *shdr,
size_t map[], const GElf_Shdr *symshdr)
{
Elf_Data *data = elf_getdata (outscn, NULL);
inline void adjust_reloc (GElf_Xword *info)
{
size_t ndx = GELF_R_SYM (*info);
if (ndx != STN_UNDEF)
*info = GELF_R_INFO (map[ndx - 1], GELF_R_TYPE (*info));
}
switch (shdr->sh_type)
{
case SHT_REL:
for (size_t i = 0; i < shdr->sh_size / shdr->sh_entsize; ++i)
{
GElf_Rel rel_mem;
GElf_Rel *rel = gelf_getrel (data, i, &rel_mem);
adjust_reloc (&rel->r_info);
ELF_CHECK (gelf_update_rel (data, i, rel),
_("cannot update relocation: %s"));
}
break;
case SHT_RELA:
for (size_t i = 0; i < shdr->sh_size / shdr->sh_entsize; ++i)
{
GElf_Rela rela_mem;
GElf_Rela *rela = gelf_getrela (data, i, &rela_mem);
adjust_reloc (&rela->r_info);
ELF_CHECK (gelf_update_rela (data, i, rela),
_("cannot update relocation: %s"));
}
break;
case SHT_GROUP:
{
GElf_Shdr shdr_mem;
GElf_Shdr *newshdr = gelf_getshdr (outscn, &shdr_mem);
ELF_CHECK (newshdr != NULL, _("cannot get section header: %s"));
if (newshdr->sh_info != STN_UNDEF)
{
newshdr->sh_info = map[newshdr->sh_info - 1];
update_shdr (outscn, newshdr);
}
break;
}
case SHT_HASH:
/* We must expand the table and rejigger its contents. */
{
const size_t nsym = symshdr->sh_size / symshdr->sh_entsize;
const size_t onent = shdr->sh_size / shdr->sh_entsize;
assert (data->d_size == shdr->sh_size);
#define CONVERT_HASH(Hash_Word) \
{ \
const Hash_Word *const old_hash = data->d_buf; \
const size_t nbucket = old_hash[0]; \
const size_t nchain = old_hash[1]; \
const Hash_Word *const old_bucket = &old_hash[2]; \
const Hash_Word *const old_chain = &old_bucket[nbucket]; \
assert (onent == 2 + nbucket + nchain); \
\
const size_t nent = 2 + nbucket + nsym; \
Hash_Word *const new_hash = xcalloc (nent, sizeof new_hash[0]); \
Hash_Word *const new_bucket = &new_hash[2]; \
Hash_Word *const new_chain = &new_bucket[nbucket]; \
\
new_hash[0] = nbucket; \
new_hash[1] = nsym; \
for (size_t i = 0; i < nbucket; ++i) \
if (old_bucket[i] != STN_UNDEF) \
new_bucket[i] = map[old_bucket[i] - 1]; \
\
for (size_t i = 1; i < nchain; ++i) \
if (old_chain[i] != STN_UNDEF) \
new_chain[map[i - 1]] = map[old_chain[i] - 1]; \
\
data->d_buf = new_hash; \
data->d_size = nent * sizeof new_hash[0]; \
}
switch (shdr->sh_entsize)
{
case 4:
CONVERT_HASH (Elf32_Word);
break;
case 8:
CONVERT_HASH (Elf64_Xword);
break;
default:
abort ();
}
elf_flagdata (data, ELF_C_SET, ELF_F_DIRTY);
update_sh_size (outscn, data);
#undef CONVERT_HASH
}
break;
case SHT_GNU_versym:
/* We must expand the table and move its elements around. */
{
const size_t nent = symshdr->sh_size / symshdr->sh_entsize;
const size_t onent = shdr->sh_size / shdr->sh_entsize;
assert (nent >= onent);
/* We don't bother using gelf_update_versym because there is
really no conversion to be done. */
assert (sizeof (Elf32_Versym) == sizeof (GElf_Versym));
assert (sizeof (Elf64_Versym) == sizeof (GElf_Versym));
GElf_Versym *versym = xcalloc (nent, sizeof versym[0]);
for (size_t i = 1; i < onent; ++i)
{
GElf_Versym *v = gelf_getversym (data, i, &versym[map[i - 1]]);
ELF_CHECK (v != NULL, _("cannot get symbol version: %s"));
}
data->d_buf = versym;
data->d_size = nent * shdr->sh_entsize;
elf_flagdata (data, ELF_C_SET, ELF_F_DIRTY);
update_sh_size (outscn, data);
}
break;
default:
error (EXIT_FAILURE, 0,
_("unexpected section type in [%Zu] with sh_link to symtab"),
elf_ndxscn (inscn));
}
}
/* Adjust all the relocation sections in the file. */
static void
adjust_all_relocs (Elf *elf, Elf_Scn *symtab, const GElf_Shdr *symshdr,
size_t map[])
{
size_t new_sh_link = elf_ndxscn (symtab);
Elf_Scn *scn = NULL;
while ((scn = elf_nextscn (elf, scn)) != NULL)
if (scn != symtab)
{
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
if (shdr->sh_type != SHT_NOBITS && shdr->sh_link == new_sh_link)
adjust_relocs (scn, scn, shdr, map, symshdr);
}
}
/* The original file probably had section symbols for all of its
sections, even the unallocated ones. To match it as closely as
possible, add in section symbols for the added sections. */
static Elf_Data *
add_new_section_symbols (Elf_Scn *old_symscn, size_t old_shnum,
Elf *elf, bool rel, Elf_Scn *symscn, size_t shnum)
{
const size_t added = shnum - old_shnum;
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (symscn, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
const size_t nsym = shdr->sh_size / shdr->sh_entsize;
size_t symndx_map[nsym - 1];
shdr->sh_info += added;
shdr->sh_size += added * shdr->sh_entsize;
update_shdr (symscn, shdr);
Elf_Data *symdata = elf_getdata (symscn, NULL);
Elf_Data *shndxdata = NULL; /* XXX */
symdata->d_size = shdr->sh_size;
symdata->d_buf = xmalloc (symdata->d_size);
/* Copy the existing section symbols. */
Elf_Data *old_symdata = elf_getdata (old_symscn, NULL);
for (size_t i = 0; i < old_shnum; ++i)
{
GElf_Sym sym_mem;
GElf_Word shndx = SHN_UNDEF;
GElf_Sym *sym = gelf_getsymshndx (old_symdata, shndxdata,
i, &sym_mem, &shndx);
ELF_CHECK (gelf_update_symshndx (symdata, shndxdata, i,
sym, shndx),
_("cannot update symbol table: %s"));
if (i > 0)
symndx_map[i - 1] = i;
}
/* Add in the new section symbols. */
for (size_t i = old_shnum; i < shnum; ++i)
{
GElf_Shdr i_shdr_mem;
GElf_Shdr *i_shdr = gelf_getshdr (elf_getscn (elf, i), &i_shdr_mem);
ELF_CHECK (i_shdr != NULL, _("cannot get section header: %s"));
GElf_Sym sym =
{
.st_value = rel ? 0 : i_shdr->sh_addr,
.st_info = GELF_ST_INFO (STB_LOCAL, STT_SECTION),
.st_shndx = i < SHN_LORESERVE ? i : SHN_XINDEX
};
GElf_Word shndx = i < SHN_LORESERVE ? SHN_UNDEF : i;
ELF_CHECK (gelf_update_symshndx (symdata, shndxdata, i,
&sym, shndx),
_("cannot update symbol table: %s"));
}
/* Now copy the rest of the existing symbols. */
for (size_t i = old_shnum; i < nsym; ++i)
{
GElf_Sym sym_mem;
GElf_Word shndx = SHN_UNDEF;
GElf_Sym *sym = gelf_getsymshndx (old_symdata, shndxdata,
i, &sym_mem, &shndx);
ELF_CHECK (gelf_update_symshndx (symdata, shndxdata,
i + added, sym, shndx),
_("cannot update symbol table: %s"));
symndx_map[i - 1] = i + added;
}
/* Adjust any relocations referring to the old symbol table. */
adjust_all_relocs (elf, symscn, shdr, symndx_map);
return symdata;
}
/* This has the side effect of updating STT_SECTION symbols' values,
in case of prelink adjustments. */
static Elf_Data *
check_symtab_section_symbols (Elf *elf, bool rel, Elf_Scn *scn,
size_t shnum, size_t shstrndx,
Elf_Scn *oscn, size_t oshnum, size_t oshstrndx,
size_t debuglink)
{
size_t n = symtab_count_leading_section_symbols (elf, oscn, oshnum,
elf_getdata (scn, NULL));
if (n == oshnum)
return add_new_section_symbols (oscn, n, elf, rel, scn, shnum);
if (n == oshstrndx || (n == debuglink && n == oshstrndx - 1))
return add_new_section_symbols (oscn, n, elf, rel, scn, shstrndx);
return NULL;
}
struct section
{
Elf_Scn *scn;
const char *name;
Elf_Scn *outscn;
struct Ebl_Strent *strent;
GElf_Shdr shdr;
};
static int
compare_alloc_sections (const struct section *s1, const struct section *s2,
bool rel)
{
if (!rel)
{
/* Sort by address. */
if (s1->shdr.sh_addr < s2->shdr.sh_addr)
return -1;
if (s1->shdr.sh_addr > s2->shdr.sh_addr)
return 1;
}
/* At the same address, preserve original section order. */
return (ssize_t) elf_ndxscn (s1->scn) - (ssize_t) elf_ndxscn (s2->scn);
}
static int
compare_unalloc_sections (const GElf_Shdr *shdr1, const GElf_Shdr *shdr2,
const char *name1, const char *name2)
{
/* Sort by sh_flags as an arbitrary ordering. */
if (shdr1->sh_flags < shdr2->sh_flags)
return -1;
if (shdr1->sh_flags > shdr2->sh_flags)
return 1;
/* Sort by name as last resort. */
return strcmp (name1, name2);
}
static int
compare_sections (const void *a, const void *b, bool rel)
{
const struct section *s1 = a;
const struct section *s2 = b;
/* Sort all non-allocated sections last. */
if ((s1->shdr.sh_flags ^ s2->shdr.sh_flags) & SHF_ALLOC)
return (s1->shdr.sh_flags & SHF_ALLOC) ? -1 : 1;
return ((s1->shdr.sh_flags & SHF_ALLOC)
? compare_alloc_sections (s1, s2, rel)
: compare_unalloc_sections (&s1->shdr, &s2->shdr,
s1->name, s2->name));
}
static int
compare_sections_rel (const void *a, const void *b)
{
return compare_sections (a, b, true);
}
static int
compare_sections_nonrel (const void *a, const void *b)
{
return compare_sections (a, b, false);
}
struct symbol
{
size_t *map;
union
{
const char *name;
struct Ebl_Strent *strent;
};
union
{
struct
{
GElf_Addr value;
GElf_Xword size;
GElf_Word shndx;
union
{
struct
{
uint8_t info;
uint8_t other;
} info;
int16_t compare;
};
};
/* For a symbol discarded after first sort, this matches its better's
map pointer. */
size_t *duplicate;
};
};
/* Collect input symbols into our internal form. */
static void
collect_symbols (Elf *outelf, bool rel, Elf_Scn *symscn, Elf_Scn *strscn,
const size_t nent, const GElf_Addr bias,
const size_t scnmap[], struct symbol *table, size_t *map,
struct section *split_bss)
{
Elf_Data *symdata = elf_getdata (symscn, NULL);
Elf_Data *strdata = elf_getdata (strscn, NULL);
Elf_Data *shndxdata = NULL; /* XXX */
for (size_t i = 1; i < nent; ++i)
{
GElf_Sym sym_mem;
GElf_Word shndx = SHN_UNDEF;
GElf_Sym *sym = gelf_getsymshndx (symdata, shndxdata, i,
&sym_mem, &shndx);
ELF_CHECK (sym != NULL, _("cannot get symbol table entry: %s"));
if (sym->st_shndx != SHN_XINDEX)
shndx = sym->st_shndx;
if (sym->st_name >= strdata->d_size)
error (EXIT_FAILURE, 0,
_("invalid string offset in symbol [%Zu]"), i);
struct symbol *s = &table[i - 1];
s->map = &map[i - 1];
s->name = strdata->d_buf + sym->st_name;
s->value = sym->st_value + bias;
s->size = sym->st_size;
s->shndx = shndx;
s->info.info = sym->st_info;
s->info.other = sym->st_other;
if (scnmap != NULL && shndx != SHN_UNDEF && shndx < SHN_LORESERVE)
s->shndx = scnmap[shndx - 1];
if (GELF_ST_TYPE (s->info.info) == STT_SECTION && !rel)
{
/* Update the value to match the output section. */
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (elf_getscn (outelf, s->shndx),
&shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
s->value = shdr->sh_addr;
}
else if (split_bss != NULL
&& s->value < split_bss->shdr.sh_addr
&& s->value >= split_bss[-1].shdr.sh_addr
&& shndx == elf_ndxscn (split_bss->outscn))
/* This symbol was in .bss and was split into .dynbss. */
s->shndx = elf_ndxscn (split_bss[-1].outscn);
}
}
#define CMP(value) \
if (s1->value < s2->value) \
return -1; \
if (s1->value > s2->value) \
return 1
/* Compare symbols with a consistent ordering,
but one only meaningful for equality. */
static int
compare_symbols (const void *a, const void *b)
{
const struct symbol *s1 = a;
const struct symbol *s2 = b;
CMP (value);
CMP (size);
CMP (shndx);
return (s1->compare - s2->compare) ?: strcmp (s1->name, s2->name);
}
/* Compare symbols for output order after slots have been assigned. */
static int
compare_symbols_output (const void *a, const void *b)
{
const struct symbol *s1 = a;
const struct symbol *s2 = b;
int cmp;
/* Sort discarded symbols last. */
cmp = (s1->name == NULL) - (s2->name == NULL);
if (cmp == 0)
/* Local symbols must come first. */
cmp = ((GELF_ST_BIND (s2->info.info) == STB_LOCAL)
- (GELF_ST_BIND (s1->info.info) == STB_LOCAL));
if (cmp == 0)
/* binutils always puts section symbols first. */
cmp = ((GELF_ST_TYPE (s2->info.info) == STT_SECTION)
- (GELF_ST_TYPE (s1->info.info) == STT_SECTION));
if (cmp == 0)
{
if (GELF_ST_TYPE (s1->info.info) == STT_SECTION)
{
/* binutils always puts section symbols in section index order. */
CMP (shndx);
else
assert (s1 == s2);
}
/* Nothing really matters, so preserve the original order. */
CMP (map);
else
assert (s1 == s2);
}
return cmp;
}
#undef CMP
/* Return true iff the flags, size, and name match. */
static bool
sections_match (const struct section *sections, size_t i,
const GElf_Shdr *shdr, const char *name)
{
return (sections[i].shdr.sh_flags == shdr->sh_flags
&& (sections[i].shdr.sh_size == shdr->sh_size
|| (sections[i].shdr.sh_size < shdr->sh_size
&& section_can_shrink (§ions[i].shdr)))
&& !strcmp (sections[i].name, name));
}
/* Locate a matching allocated section in SECTIONS. */
static struct section *
find_alloc_section (const GElf_Shdr *shdr, GElf_Addr bias, const char *name,
struct section sections[], size_t nalloc)
{
const GElf_Addr addr = shdr->sh_addr + bias;
size_t l = 0, u = nalloc;
while (l < u)
{
size_t i = (l + u) / 2;
if (addr < sections[i].shdr.sh_addr)
u = i;
else if (addr > sections[i].shdr.sh_addr)
l = i + 1;
else
{
/* We've found allocated sections with this address.
Find one with matching size, flags, and name. */
while (i > 0 && sections[i - 1].shdr.sh_addr == addr)
--i;
for (; i < nalloc && sections[i].shdr.sh_addr == addr;
++i)
if (sections_match (sections, i, shdr, name))
return §ions[i];
break;
}
}
return NULL;
}
static inline const char *
get_section_name (size_t ndx, const GElf_Shdr *shdr, const Elf_Data *shstrtab)
{
if (shdr->sh_name >= shstrtab->d_size)
error (EXIT_FAILURE, 0, _("cannot read section [%Zu] name: %s"),
ndx, elf_errmsg (-1));
return shstrtab->d_buf + shdr->sh_name;
}
/* Fix things up when prelink has moved some allocated sections around
and the debuginfo file's section headers no longer match up.
This fills in SECTIONS[0..NALLOC-1].outscn or exits.
If there was a .bss section that was split into two sections
with the new one preceding it in sh_addr, we return that pointer. */
static struct section *
find_alloc_sections_prelink (Elf *debug, Elf_Data *debug_shstrtab,
Elf *main, const GElf_Ehdr *main_ehdr,
Elf_Data *main_shstrtab, GElf_Addr bias,
struct section *sections,
size_t nalloc, size_t nsections)
{
/* Clear assignments that might have been bogus. */
for (size_t i = 0; i < nalloc; ++i)
sections[i].outscn = NULL;
Elf_Scn *undo = NULL;
for (size_t i = nalloc; i < nsections; ++i)
{
const struct section *sec = §ions[i];
if (sec->shdr.sh_type == SHT_PROGBITS
&& !(sec->shdr.sh_flags & SHF_ALLOC)
&& !strcmp (sec->name, ".gnu.prelink_undo"))
{
undo = sec->scn;
break;
}
}
/* Find the original allocated sections before prelinking. */
struct section *undo_sections = NULL;
size_t undo_nalloc = 0;
if (undo != NULL)
{
Elf_Data *undodata = elf_rawdata (undo, NULL);
ELF_CHECK (undodata != NULL,
_("cannot read '.gnu.prelink_undo' section: %s"));
union
{
Elf32_Ehdr e32;
Elf64_Ehdr e64;
} ehdr;
Elf_Data dst =
{
.d_buf = &ehdr,
.d_size = sizeof ehdr,
.d_type = ELF_T_EHDR,
.d_version = EV_CURRENT
};
Elf_Data src = *undodata;
src.d_size = gelf_fsize (main, ELF_T_EHDR, 1, EV_CURRENT);
src.d_type = ELF_T_EHDR;
ELF_CHECK (gelf_xlatetom (main, &dst, &src,
main_ehdr->e_ident[EI_DATA]) != NULL,
_("cannot read '.gnu.prelink_undo' section: %s"));
uint_fast16_t phnum;
uint_fast16_t shnum;
if (ehdr.e32.e_ident[EI_CLASS] == ELFCLASS32)
{
phnum = ehdr.e32.e_phnum;
shnum = ehdr.e32.e_shnum;
}
else
{
phnum = ehdr.e64.e_phnum;
shnum = ehdr.e64.e_shnum;
}
size_t phsize = gelf_fsize (main, ELF_T_PHDR, phnum, EV_CURRENT);
src.d_buf += src.d_size + phsize;
src.d_size = gelf_fsize (main, ELF_T_SHDR, shnum - 1, EV_CURRENT);
src.d_type = ELF_T_SHDR;
if ((size_t) (src.d_buf - undodata->d_buf) > undodata->d_size
|| undodata->d_size - (src.d_buf - undodata->d_buf) != src.d_size)
error (EXIT_FAILURE, 0, _("invalid contents in '%s' section"),
".gnu.prelink_undo");
union
{
Elf32_Shdr s32[shnum - 1];
Elf64_Shdr s64[shnum - 1];
} shdr;
dst.d_buf = &shdr;
dst.d_size = sizeof shdr;
ELF_CHECK (gelf_xlatetom (main, &dst, &src,
main_ehdr->e_ident[EI_DATA]) != NULL,
_("cannot read '.gnu.prelink_undo' section: %s"));
undo_sections = xmalloc ((shnum - 1) * sizeof undo_sections[0]);
for (size_t i = 0; i < shnum - 1; ++i)
{
struct section *sec = &undo_sections[undo_nalloc];
if (ehdr.e32.e_ident[EI_CLASS] == ELFCLASS32)
{
#define COPY(field) sec->shdr.field = shdr.s32[i].field
COPY (sh_name);
COPY (sh_type);
COPY (sh_flags);
COPY (sh_addr);
COPY (sh_offset);
COPY (sh_size);
COPY (sh_link);
COPY (sh_info);
COPY (sh_addralign);
COPY (sh_entsize);
#undef COPY
}
else
sec->shdr = shdr.s64[i];
if (sec->shdr.sh_flags & SHF_ALLOC)
{
sec->shdr.sh_addr += bias;
sec->name = get_section_name (i + 1, &sec->shdr, main_shstrtab);
sec->scn = elf_getscn (main, i + 1); /* Really just for ndx. */
sec->outscn = NULL;
sec->strent = NULL;
++undo_nalloc;
}
}
qsort (undo_sections, undo_nalloc,
sizeof undo_sections[0], compare_sections_nonrel);
}
bool fail = false;
inline void check_match (bool match, Elf_Scn *scn, const char *name)
{
if (!match)
{
fail = true;
error (0, 0, _("cannot find matching section for [%Zu] '%s'"),
elf_ndxscn (scn), name);
}
}
Elf_Scn *scn = NULL;
while ((scn = elf_nextscn (debug, scn)) != NULL)
{
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
if (!(shdr->sh_flags & SHF_ALLOC))
continue;
const char *name = get_section_name (elf_ndxscn (scn), shdr,
debug_shstrtab);
if (undo_sections != NULL)
{
struct section *sec = find_alloc_section (shdr, 0, name,
undo_sections,
undo_nalloc);
if (sec != NULL)
{
sec->outscn = scn;
continue;
}
}
/* If there is no prelink info, we are just here to find
the sections to give error messages about. */
for (size_t i = 0; shdr != NULL && i < nalloc; ++i)
if (sections[i].outscn == scn)
shdr = NULL;
check_match (shdr == NULL, scn, name);
}
if (fail)
exit (EXIT_FAILURE);
/* Now we have lined up output sections for each of the original sections
before prelinking. Translate those to the prelinked sections.
This matches what prelink's undo_sections does. */
struct section *split_bss = NULL;
for (size_t i = 0; i < undo_nalloc; ++i)
{
const struct section *undo_sec = &undo_sections[i];
const char *name = undo_sec->name;
scn = undo_sec->scn; /* This is just for elf_ndxscn. */
for (size_t j = 0; j < nalloc; ++j)
{
struct section *sec = §ions[j];
#define RELA_SCALED(field) \
(2 * sec->shdr.field == 3 * undo_sec->shdr.field)
if (sec->outscn == NULL
&& sec->shdr.sh_name == undo_sec->shdr.sh_name
&& sec->shdr.sh_flags == undo_sec->shdr.sh_flags
&& sec->shdr.sh_addralign == undo_sec->shdr.sh_addralign
&& (((sec->shdr.sh_type == undo_sec->shdr.sh_type
&& sec->shdr.sh_entsize == undo_sec->shdr.sh_entsize
&& (sec->shdr.sh_size == undo_sec->shdr.sh_size
|| (sec->shdr.sh_size > undo_sec->shdr.sh_size
&& main_ehdr->e_type == ET_EXEC
&& !strcmp (sec->name, ".dynstr"))))
|| (sec->shdr.sh_size == undo_sec->shdr.sh_size
&& ((sec->shdr.sh_entsize == undo_sec->shdr.sh_entsize
&& undo_sec->shdr.sh_type == SHT_NOBITS)
|| undo_sec->shdr.sh_type == SHT_PROGBITS)
&& !strcmp (sec->name, ".plt")))
|| (sec->shdr.sh_type == SHT_RELA
&& undo_sec->shdr.sh_type == SHT_REL
&& RELA_SCALED (sh_entsize) && RELA_SCALED (sh_size))
|| (sec->shdr.sh_entsize == undo_sec->shdr.sh_entsize
&& (sec->shdr.sh_type == undo_sec->shdr.sh_type
|| (sec->shdr.sh_type == SHT_PROGBITS
&& undo_sec->shdr.sh_type == SHT_NOBITS))
&& sec->shdr.sh_size < undo_sec->shdr.sh_size
&& (!strcmp (sec->name, ".bss")
|| !strcmp (sec->name, ".sbss"))
&& (split_bss = sec) > sections)))
{
sec->outscn = undo_sec->outscn;
undo_sec = NULL;
break;
}
}
check_match (undo_sec == NULL, scn, name);
}
free (undo_sections);
if (fail)
exit (EXIT_FAILURE);
return split_bss;
}
/* Create new .shstrtab contents, subroutine of copy_elided_sections.
This can't be open coded there and still use variable-length auto arrays,
since the end of our block would free other VLAs too. */
static Elf_Data *
new_shstrtab (Elf *unstripped, size_t unstripped_shnum,
Elf_Data *shstrtab, size_t unstripped_shstrndx,
struct section *sections, size_t stripped_shnum,
struct Ebl_Strtab *strtab)
{
if (strtab == NULL)
return NULL;
struct Ebl_Strent *unstripped_strent[unstripped_shnum - 1];
memset (unstripped_strent, 0, sizeof unstripped_strent);
for (struct section *sec = sections;
sec < §ions[stripped_shnum - 1];
++sec)
if (sec->outscn != NULL)
{
if (sec->strent == NULL)
{
sec->strent = ebl_strtabadd (strtab, sec->name, 0);
ELF_CHECK (sec->strent != NULL,
_("cannot add section name to string table: %s"));
}
unstripped_strent[elf_ndxscn (sec->outscn) - 1] = sec->strent;
}
/* Add names of sections we aren't touching. */
for (size_t i = 0; i < unstripped_shnum - 1; ++i)
if (unstripped_strent[i] == NULL)
{
Elf_Scn *scn = elf_getscn (unstripped, i + 1);
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
const char *name = get_section_name (i + 1, shdr, shstrtab);
unstripped_strent[i] = ebl_strtabadd (strtab, name, 0);
ELF_CHECK (unstripped_strent[i] != NULL,
_("cannot add section name to string table: %s"));
}
else
unstripped_strent[i] = NULL;
/* Now finalize the string table so we can get offsets. */
Elf_Data *strtab_data = elf_getdata (elf_getscn (unstripped,
unstripped_shstrndx), NULL);
ELF_CHECK (elf_flagdata (strtab_data, ELF_C_SET, ELF_F_DIRTY),
_("cannot update section header string table data: %s"));
ebl_strtabfinalize (strtab, strtab_data);
/* Update the sh_name fields of sections we aren't modifying later. */
for (size_t i = 0; i < unstripped_shnum - 1; ++i)
if (unstripped_strent[i] != NULL)
{
Elf_Scn *scn = elf_getscn (unstripped, i + 1);
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
shdr->sh_name = ebl_strtaboffset (unstripped_strent[i]);
if (i + 1 == unstripped_shstrndx)
shdr->sh_size = strtab_data->d_size;
update_shdr (scn, shdr);
}
return strtab_data;
}
/* Fill in any SHT_NOBITS sections in UNSTRIPPED by
copying their contents and sh_type from STRIPPED. */
static void
copy_elided_sections (Elf *unstripped, Elf *stripped,
const GElf_Ehdr *stripped_ehdr, GElf_Addr bias)
{
size_t unstripped_shstrndx;
ELF_CHECK (elf_getshdrstrndx (unstripped, &unstripped_shstrndx) == 0,
_("cannot get section header string table section index: %s"));
size_t stripped_shstrndx;
ELF_CHECK (elf_getshdrstrndx (stripped, &stripped_shstrndx) == 0,
_("cannot get section header string table section index: %s"));
size_t unstripped_shnum;
ELF_CHECK (elf_getshdrnum (unstripped, &unstripped_shnum) == 0,
_("cannot get section count: %s"));
size_t stripped_shnum;
ELF_CHECK (elf_getshdrnum (stripped, &stripped_shnum) == 0,
_("cannot get section count: %s"));
if (unlikely (stripped_shnum > unstripped_shnum))
error (EXIT_FAILURE, 0, _("\
more sections in stripped file than debug file -- arguments reversed?"));
/* Cache the stripped file's section details. */
struct section sections[stripped_shnum - 1];
Elf_Scn *scn = NULL;
while ((scn = elf_nextscn (stripped, scn)) != NULL)
{
size_t i = elf_ndxscn (scn) - 1;
GElf_Shdr *shdr = gelf_getshdr (scn, §ions[i].shdr);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
sections[i].name = elf_strptr (stripped, stripped_shstrndx,
shdr->sh_name);
if (sections[i].name == NULL)
error (EXIT_FAILURE, 0, _("cannot read section [%Zu] name: %s"),
elf_ndxscn (scn), elf_errmsg (-1));
sections[i].scn = scn;
sections[i].outscn = NULL;
sections[i].strent = NULL;
}
const struct section *stripped_symtab = NULL;
/* Sort the sections, allocated by address and others after. */
qsort (sections, stripped_shnum - 1, sizeof sections[0],
stripped_ehdr->e_type == ET_REL
? compare_sections_rel : compare_sections_nonrel);
size_t nalloc = stripped_shnum - 1;
while (nalloc > 0 && !(sections[nalloc - 1].shdr.sh_flags & SHF_ALLOC))
{
--nalloc;
if (sections[nalloc].shdr.sh_type == SHT_SYMTAB)
stripped_symtab = §ions[nalloc];
}
/* Locate a matching unallocated section in SECTIONS. */
inline struct section *find_unalloc_section (const GElf_Shdr *shdr,
const char *name)
{
size_t l = nalloc, u = stripped_shnum - 1;
while (l < u)
{
size_t i = (l + u) / 2;
struct section *sec = §ions[i];
int cmp = compare_unalloc_sections (shdr, &sec->shdr,
name, sec->name);
if (cmp < 0)
u = i;
else if (cmp > 0)
l = i + 1;
else
return sec;
}
return NULL;
}
Elf_Data *shstrtab = elf_getdata (elf_getscn (unstripped,
unstripped_shstrndx), NULL);
ELF_CHECK (shstrtab != NULL,
_("cannot read section header string table: %s"));
/* Match each debuginfo section with its corresponding stripped section. */
bool check_prelink = false;
Elf_Scn *unstripped_symtab = NULL;
size_t alloc_avail = 0;
scn = NULL;
while ((scn = elf_nextscn (unstripped, scn)) != NULL)
{
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
if (shdr->sh_type == SHT_SYMTAB)
{
unstripped_symtab = scn;
continue;
}
const size_t ndx = elf_ndxscn (scn);
if (ndx == unstripped_shstrndx)
continue;
const char *name = get_section_name (ndx, shdr, shstrtab);
struct section *sec = NULL;
if (shdr->sh_flags & SHF_ALLOC)
{
if (stripped_ehdr->e_type != ET_REL)
{
/* Look for the section that matches. */
sec = find_alloc_section (shdr, bias, name, sections, nalloc);
if (sec == NULL)
{
/* We couldn't figure it out. It may be a prelink issue. */
check_prelink = true;
continue;
}
}
else
{
/* The sh_addr of allocated sections does not help us,
but the order usually matches. */
if (likely (sections_match (sections, alloc_avail, shdr, name)))
sec = §ions[alloc_avail++];
else
for (size_t i = alloc_avail + 1; i < nalloc; ++i)
if (sections_match (sections, i, shdr, name))
{
sec = §ions[i];
break;
}
}
}
else
{
/* Look for the section that matches. */
sec = find_unalloc_section (shdr, name);
if (sec == NULL)
{
/* An additional unallocated section is fine if not SHT_NOBITS.
We looked it up anyway in case it's an unallocated section
copied in both files (e.g. SHT_NOTE), and don't keep both. */
if (shdr->sh_type != SHT_NOBITS)
continue;
/* Somehow some old .debug files wound up with SHT_NOBITS
.comment sections, so let those pass. */
if (!strcmp (name, ".comment"))
continue;
}
}
if (sec == NULL)
error (EXIT_FAILURE, 0,
_("cannot find matching section for [%Zu] '%s'"),
elf_ndxscn (scn), name);
sec->outscn = scn;
}
/* If that failed due to changes made by prelink, we take another tack.
We keep track of a .bss section that was partly split into .dynbss
so that collect_symbols can update symbols' st_shndx fields. */
struct section *split_bss = NULL;
if (check_prelink)
{
Elf_Data *data = elf_getdata (elf_getscn (stripped, stripped_shstrndx),
NULL);
ELF_CHECK (data != NULL,
_("cannot read section header string table: %s"));
split_bss = find_alloc_sections_prelink (unstripped, shstrtab,
stripped, stripped_ehdr,
data, bias, sections,
nalloc, stripped_shnum - 1);
}
/* Make sure each main file section has a place to go. */
const struct section *stripped_dynsym = NULL;
size_t debuglink = SHN_UNDEF;
size_t ndx_section[stripped_shnum - 1];
struct Ebl_Strtab *strtab = NULL;
for (struct section *sec = sections;
sec < §ions[stripped_shnum - 1];
++sec)
{
size_t secndx = elf_ndxscn (sec->scn);
if (sec->outscn == NULL)
{
/* We didn't find any corresponding section for this. */
if (secndx == stripped_shstrndx)
{
/* We only need one .shstrtab. */
ndx_section[secndx - 1] = unstripped_shstrndx;
continue;
}
if (unstripped_symtab != NULL && sec == stripped_symtab)
{
/* We don't need a second symbol table. */
ndx_section[secndx - 1] = elf_ndxscn (unstripped_symtab);
continue;
}
if (unstripped_symtab != NULL && stripped_symtab != NULL
&& secndx == stripped_symtab->shdr.sh_link)
{
/* ... nor its string table. */
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (unstripped_symtab, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
ndx_section[secndx - 1] = shdr->sh_link;
continue;
}
if (!(sec->shdr.sh_flags & SHF_ALLOC)
&& !strcmp (sec->name, ".gnu_debuglink"))
{
/* This was created by stripping. We don't want it. */
debuglink = secndx;
ndx_section[secndx - 1] = SHN_UNDEF;
continue;
}
sec->outscn = elf_newscn (unstripped);
Elf_Data *newdata = elf_newdata (sec->outscn);
ELF_CHECK (newdata != NULL && gelf_update_shdr (sec->outscn,
&sec->shdr),
_("cannot add new section: %s"));
if (strtab == NULL)
strtab = ebl_strtabinit (true);
sec->strent = ebl_strtabadd (strtab, sec->name, 0);
ELF_CHECK (sec->strent != NULL,
_("cannot add section name to string table: %s"));
}
/* Cache the mapping of original section indices to output sections. */
ndx_section[secndx - 1] = elf_ndxscn (sec->outscn);
}
/* We added some sections, so we need a new shstrtab. */
Elf_Data *strtab_data = new_shstrtab (unstripped, unstripped_shnum,
shstrtab, unstripped_shstrndx,
sections, stripped_shnum,
strtab);
/* Get the updated section count. */
ELF_CHECK (elf_getshdrnum (unstripped, &unstripped_shnum) == 0,
_("cannot get section count: %s"));
bool placed[unstripped_shnum - 1];
memset (placed, 0, sizeof placed);
/* Now update the output sections and copy in their data. */
GElf_Off offset = 0;
for (const struct section *sec = sections;
sec < §ions[stripped_shnum - 1];
++sec)
if (sec->outscn != NULL)
{
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (sec->outscn, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
/* In an ET_REL file under --relocate, the sh_addr of SHF_ALLOC
sections will have been set nonzero by relocation. This
touched the shdrs of whichever file had the symtab. sh_addr
is still zero in the corresponding shdr. The relocated
address is what we want to use. */
if (stripped_ehdr->e_type != ET_REL
|| !(shdr_mem.sh_flags & SHF_ALLOC)
|| shdr_mem.sh_addr == 0)
shdr_mem.sh_addr = sec->shdr.sh_addr;
shdr_mem.sh_type = sec->shdr.sh_type;
shdr_mem.sh_size = sec->shdr.sh_size;
shdr_mem.sh_info = sec->shdr.sh_info;
shdr_mem.sh_link = sec->shdr.sh_link;
if (sec->shdr.sh_link != SHN_UNDEF)
shdr_mem.sh_link = ndx_section[sec->shdr.sh_link - 1];
if (shdr_mem.sh_flags & SHF_INFO_LINK)
shdr_mem.sh_info = ndx_section[sec->shdr.sh_info - 1];
if (strtab != NULL)
shdr_mem.sh_name = ebl_strtaboffset (sec->strent);
Elf_Data *indata = elf_getdata (sec->scn, NULL);
ELF_CHECK (indata != NULL, _("cannot get section data: %s"));
Elf_Data *outdata = elf_getdata (sec->outscn, NULL);
ELF_CHECK (outdata != NULL, _("cannot copy section data: %s"));
*outdata = *indata;
elf_flagdata (outdata, ELF_C_SET, ELF_F_DIRTY);
/* Preserve the file layout of the allocated sections. */
if (stripped_ehdr->e_type != ET_REL && (shdr_mem.sh_flags & SHF_ALLOC))
{
shdr_mem.sh_offset = sec->shdr.sh_offset;
placed[elf_ndxscn (sec->outscn) - 1] = true;
const GElf_Off end_offset = (shdr_mem.sh_offset
+ (shdr_mem.sh_type == SHT_NOBITS
? 0 : shdr_mem.sh_size));
if (end_offset > offset)
offset = end_offset;
}
update_shdr (sec->outscn, &shdr_mem);
if (shdr_mem.sh_type == SHT_SYMTAB || shdr_mem.sh_type == SHT_DYNSYM)
{
/* We must adjust all the section indices in the symbol table. */
Elf_Data *shndxdata = NULL; /* XXX */
for (size_t i = 1; i < shdr_mem.sh_size / shdr_mem.sh_entsize; ++i)
{
GElf_Sym sym_mem;
GElf_Word shndx = SHN_UNDEF;
GElf_Sym *sym = gelf_getsymshndx (outdata, shndxdata,
i, &sym_mem, &shndx);
ELF_CHECK (sym != NULL,
_("cannot get symbol table entry: %s"));
if (sym->st_shndx != SHN_XINDEX)
shndx = sym->st_shndx;
if (shndx != SHN_UNDEF && shndx < SHN_LORESERVE)
{
if (shndx >= stripped_shnum)
error (EXIT_FAILURE, 0,
_("symbol [%Zu] has invalid section index"), i);
shndx = ndx_section[shndx - 1];
if (shndx < SHN_LORESERVE)
{
sym->st_shndx = shndx;
shndx = SHN_UNDEF;
}
else
sym->st_shndx = SHN_XINDEX;
ELF_CHECK (gelf_update_symshndx (outdata, shndxdata,
i, sym, shndx),
_("cannot update symbol table: %s"));
}
}
if (shdr_mem.sh_type == SHT_SYMTAB)
stripped_symtab = sec;
if (shdr_mem.sh_type == SHT_DYNSYM)
stripped_dynsym = sec;
}
}
/* We may need to update the symbol table. */
Elf_Data *symdata = NULL;
struct Ebl_Strtab *symstrtab = NULL;
Elf_Data *symstrdata = NULL;
if (unstripped_symtab != NULL && (stripped_symtab != NULL
|| check_prelink /* Section adjustments. */
|| (stripped_ehdr->e_type != ET_REL
&& bias != 0)))
{
/* Merge the stripped file's symbol table into the unstripped one. */
const size_t stripped_nsym = (stripped_symtab == NULL ? 1
: (stripped_symtab->shdr.sh_size
/ stripped_symtab->shdr.sh_entsize));
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (unstripped_symtab, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
const size_t unstripped_nsym = shdr->sh_size / shdr->sh_entsize;
/* First collect all the symbols from both tables. */
const size_t total_syms = stripped_nsym - 1 + unstripped_nsym - 1;
struct symbol symbols[total_syms];
size_t symndx_map[total_syms];
if (stripped_symtab != NULL)
collect_symbols (unstripped, stripped_ehdr->e_type == ET_REL,
stripped_symtab->scn,
elf_getscn (stripped, stripped_symtab->shdr.sh_link),
stripped_nsym, 0, ndx_section,
symbols, symndx_map, NULL);
Elf_Scn *unstripped_strtab = elf_getscn (unstripped, shdr->sh_link);
collect_symbols (unstripped, stripped_ehdr->e_type == ET_REL,
unstripped_symtab, unstripped_strtab, unstripped_nsym,
stripped_ehdr->e_type == ET_REL ? 0 : bias, NULL,
&symbols[stripped_nsym - 1],
&symndx_map[stripped_nsym - 1], split_bss);
/* Next, sort our array of all symbols. */
qsort (symbols, total_syms, sizeof symbols[0], compare_symbols);
/* Now we can weed out the duplicates. Assign remaining symbols
new slots, collecting a map from old indices to new. */
size_t nsym = 0;
for (struct symbol *s = symbols; s < &symbols[total_syms]; ++s)
{
/* Skip a section symbol for a removed section. */
if (s->shndx == SHN_UNDEF
&& GELF_ST_TYPE (s->info.info) == STT_SECTION)
{
s->name = NULL; /* Mark as discarded. */
*s->map = STN_UNDEF;
s->duplicate = NULL;
continue;
}
struct symbol *n = s;
while (n + 1 < &symbols[total_syms] && !compare_symbols (s, n + 1))
++n;
while (s < n)
{
/* This is a duplicate. Its twin will get the next slot. */
s->name = NULL; /* Mark as discarded. */
s->duplicate = n->map;
++s;
}
/* Allocate the next slot. */
*s->map = ++nsym;
}
/* Now we sort again, to determine the order in the output. */
qsort (symbols, total_syms, sizeof symbols[0], compare_symbols_output);
if (nsym < total_syms)
/* The discarded symbols are now at the end of the table. */
assert (symbols[nsym].name == NULL);
/* Now a final pass updates the map with the final order,
and builds up the new string table. */
symstrtab = ebl_strtabinit (true);
for (size_t i = 0; i < nsym; ++i)
{
assert (symbols[i].name != NULL);
assert (*symbols[i].map != 0);
*symbols[i].map = 1 + i;
symbols[i].strent = ebl_strtabadd (symstrtab, symbols[i].name, 0);
}
/* Scan the discarded symbols too, just to update their slots
in SYMNDX_MAP to refer to their live duplicates. */
for (size_t i = nsym; i < total_syms; ++i)
{
assert (symbols[i].name == NULL);
if (symbols[i].duplicate == NULL)
assert (*symbols[i].map == STN_UNDEF);
else
{
assert (*symbols[i].duplicate != STN_UNDEF);
*symbols[i].map = *symbols[i].duplicate;
}
}
/* Now we are ready to write the new symbol table. */
symdata = elf_getdata (unstripped_symtab, NULL);
symstrdata = elf_getdata (unstripped_strtab, NULL);
Elf_Data *shndxdata = NULL; /* XXX */
ebl_strtabfinalize (symstrtab, symstrdata);
elf_flagdata (symstrdata, ELF_C_SET, ELF_F_DIRTY);
shdr->sh_size = symdata->d_size = (1 + nsym) * shdr->sh_entsize;
symdata->d_buf = xmalloc (symdata->d_size);
GElf_Sym sym;
memset (&sym, 0, sizeof sym);
ELF_CHECK (gelf_update_symshndx (symdata, shndxdata, 0, &sym, SHN_UNDEF),
_("cannot update symbol table: %s"));
shdr->sh_info = 1;
for (size_t i = 0; i < nsym; ++i)
{
struct symbol *s = &symbols[i];
/* Fill in the symbol details. */
sym.st_name = ebl_strtaboffset (s->strent);
sym.st_value = s->value; /* Already biased to output address. */
sym.st_size = s->size;
sym.st_shndx = s->shndx; /* Already mapped to output index. */
sym.st_info = s->info.info;
sym.st_other = s->info.other;
/* Keep track of the number of leading local symbols. */
if (GELF_ST_BIND (sym.st_info) == STB_LOCAL)
{
assert (shdr->sh_info == 1 + i);
shdr->sh_info = 1 + i + 1;
}
ELF_CHECK (gelf_update_symshndx (symdata, shndxdata, 1 + i,
&sym, SHN_UNDEF),
_("cannot update symbol table: %s"));
}
elf_flagdata (symdata, ELF_C_SET, ELF_F_DIRTY);
update_shdr (unstripped_symtab, shdr);
if (stripped_symtab != NULL)
{
/* Adjust any relocations referring to the old symbol table. */
const size_t old_sh_link = elf_ndxscn (stripped_symtab->scn);
for (const struct section *sec = sections;
sec < §ions[stripped_shnum - 1];
++sec)
if (sec->outscn != NULL && sec->shdr.sh_link == old_sh_link)
adjust_relocs (sec->outscn, sec->scn, &sec->shdr,
symndx_map, shdr);
}
/* Also adjust references to the other old symbol table. */
adjust_all_relocs (unstripped, unstripped_symtab, shdr,
&symndx_map[stripped_nsym - 1]);
}
else if (stripped_symtab != NULL && stripped_shnum != unstripped_shnum)
check_symtab_section_symbols (unstripped,
stripped_ehdr->e_type == ET_REL,
stripped_symtab->scn,
unstripped_shnum, unstripped_shstrndx,
stripped_symtab->outscn,
stripped_shnum, stripped_shstrndx,
debuglink);
if (stripped_dynsym != NULL)
(void) check_symtab_section_symbols (unstripped,
stripped_ehdr->e_type == ET_REL,
stripped_dynsym->outscn,
unstripped_shnum,
unstripped_shstrndx,
stripped_dynsym->scn, stripped_shnum,
stripped_shstrndx, debuglink);
/* We need to preserve the layout of the stripped file so the
phdrs will match up. This requires us to do our own layout of
the added sections. We do manual layout even for ET_REL just
so we can try to match what the original probably had. */
elf_flagelf (unstripped, ELF_C_SET, ELF_F_LAYOUT);
if (offset == 0)
/* For ET_REL we are starting the layout from scratch. */
offset = gelf_fsize (unstripped, ELF_T_EHDR, 1, EV_CURRENT);
bool skip_reloc = false;
do
{
skip_reloc = !skip_reloc;
for (size_t i = 0; i < unstripped_shnum - 1; ++i)
if (!placed[i])
{
scn = elf_getscn (unstripped, 1 + i);
GElf_Shdr shdr_mem;
GElf_Shdr *shdr = gelf_getshdr (scn, &shdr_mem);
ELF_CHECK (shdr != NULL, _("cannot get section header: %s"));
/* We must make sure we have read in the data of all sections
beforehand and marked them to be written out. When we're
modifying the existing file in place, we might overwrite
this part of the file before we get to handling the section. */
ELF_CHECK (elf_flagdata (elf_getdata (scn, NULL),
ELF_C_SET, ELF_F_DIRTY),
_("cannot read section data: %s"));
if (skip_reloc
&& (shdr->sh_type == SHT_REL || shdr->sh_type == SHT_RELA))
continue;
GElf_Off align = shdr->sh_addralign ?: 1;
offset = (offset + align - 1) & -align;
shdr->sh_offset = offset;
if (shdr->sh_type != SHT_NOBITS)
offset += shdr->sh_size;
update_shdr (scn, shdr);
if (unstripped_shstrndx == 1 + i)
{
/* Place the section headers immediately after
.shstrtab, and update the ELF header. */
GElf_Ehdr ehdr_mem;
GElf_Ehdr *ehdr = gelf_getehdr (unstripped, &ehdr_mem);
ELF_CHECK (ehdr != NULL, _("cannot get ELF header: %s"));
GElf_Off sh_align = gelf_getclass (unstripped) * 4;
offset = (offset + sh_align - 1) & -sh_align;
ehdr->e_shnum = unstripped_shnum;
ehdr->e_shoff = offset;
offset += unstripped_shnum * ehdr->e_shentsize;
ELF_CHECK (gelf_update_ehdr (unstripped, ehdr),
_("cannot update ELF header: %s"));
}
placed[i] = true;
}
}
while (skip_reloc);
if (stripped_ehdr->e_phnum > 0)
ELF_CHECK (gelf_newphdr (unstripped, stripped_ehdr->e_phnum),
_("cannot create program headers: %s"));
/* Copy each program header from the stripped file. */
for (uint_fast16_t i = 0; i < stripped_ehdr->e_phnum; ++i)
{
GElf_Phdr phdr_mem;
GElf_Phdr *phdr = gelf_getphdr (stripped, i, &phdr_mem);
ELF_CHECK (phdr != NULL, _("cannot get program header: %s"));
ELF_CHECK (gelf_update_phdr (unstripped, i, phdr),
_("cannot update program header: %s"));
}
/* Finally, write out the file. */
ELF_CHECK (elf_update (unstripped, ELF_C_WRITE) > 0,
_("cannot write output file: %s"));
if (strtab != NULL)
{
ebl_strtabfree (strtab);
free (strtab_data->d_buf);
}
if (symdata != NULL)
free (symdata->d_buf);
if (symstrtab != NULL)
{
ebl_strtabfree (symstrtab);
free (symstrdata->d_buf);
}
}
/* Process one pair of files, already opened. */
static void
handle_file (const char *output_file, bool create_dirs,
Elf *stripped, const GElf_Ehdr *stripped_ehdr,
Elf *unstripped)
{
/* Determine the address bias between the debuginfo file and the main
file, which may have been modified by prelinking. */
GElf_Addr bias = 0;
if (unstripped != NULL)
for (uint_fast16_t i = 0; i < stripped_ehdr->e_phnum; ++i)
{
GElf_Phdr phdr_mem;
GElf_Phdr *phdr = gelf_getphdr (stripped, i, &phdr_mem);
ELF_CHECK (phdr != NULL, _("cannot get program header: %s"));
if (phdr->p_type == PT_LOAD)
{
GElf_Phdr unstripped_phdr_mem;
GElf_Phdr *unstripped_phdr = gelf_getphdr (unstripped, i,
&unstripped_phdr_mem);
ELF_CHECK (unstripped_phdr != NULL,
_("cannot get program header: %s"));
bias = phdr->p_vaddr - unstripped_phdr->p_vaddr;
break;
}
}
/* One day we could adjust all the DWARF data (like prelink itself does). */
if (bias != 0)
{
if (output_file == NULL)
error (0, 0, _("\
DWARF data not adjusted for prelinking bias; consider prelink -u"));
else
error (0, 0, _("\
DWARF data in '%s' not adjusted for prelinking bias; consider prelink -u"),
output_file);
}
if (output_file == NULL)
/* Modify the unstripped file in place. */
copy_elided_sections (unstripped, stripped, stripped_ehdr, bias);
else
{
if (create_dirs)
make_directories (output_file);
/* Copy the unstripped file and then modify it. */
int outfd = open64 (output_file, O_RDWR | O_CREAT,
stripped_ehdr->e_type == ET_REL ? 0666 : 0777);
if (outfd < 0)
error (EXIT_FAILURE, errno, _("cannot open '%s'"), output_file);
Elf *outelf = elf_begin (outfd, ELF_C_WRITE, NULL);
ELF_CHECK (outelf != NULL, _("cannot create ELF descriptor: %s"));
if (unstripped == NULL)
{
/* Actually, we are just copying out the main file as it is. */
copy_elf (outelf, stripped);
if (stripped_ehdr->e_type != ET_REL)
elf_flagelf (outelf, ELF_C_SET, ELF_F_LAYOUT);
ELF_CHECK (elf_update (outelf, ELF_C_WRITE) > 0,
_("cannot write output file: %s"));
}
else
{
copy_elf (outelf, unstripped);
copy_elided_sections (outelf, stripped, stripped_ehdr, bias);
}
elf_end (outelf);
close (outfd);
}
}
static int
open_file (const char *file, bool writable)
{
int fd = open64 (file, writable ? O_RDWR : O_RDONLY);
if (fd < 0)
error (EXIT_FAILURE, errno, _("cannot open '%s'"), file);
return fd;
}
/* Handle a pair of files we need to open by name. */
static void
handle_explicit_files (const char *output_file, bool create_dirs,
const char *stripped_file, const char *unstripped_file)
{
int stripped_fd = open_file (stripped_file, false);
Elf *stripped = elf_begin (stripped_fd, ELF_C_READ, NULL);
GElf_Ehdr stripped_ehdr;
ELF_CHECK (gelf_getehdr (stripped, &stripped_ehdr),
_("cannot create ELF descriptor: %s"));
int unstripped_fd = -1;
Elf *unstripped = NULL;
if (unstripped_file != NULL)
{
unstripped_fd = open_file (unstripped_file, output_file == NULL);
unstripped = elf_begin (unstripped_fd,
(output_file == NULL ? ELF_C_RDWR : ELF_C_READ),
NULL);
GElf_Ehdr unstripped_ehdr;
ELF_CHECK (gelf_getehdr (unstripped, &unstripped_ehdr),
_("cannot create ELF descriptor: %s"));
if (memcmp (stripped_ehdr.e_ident, unstripped_ehdr.e_ident, EI_NIDENT)
|| stripped_ehdr.e_type != unstripped_ehdr.e_type
|| stripped_ehdr.e_machine != unstripped_ehdr.e_machine
|| stripped_ehdr.e_phnum != unstripped_ehdr.e_phnum)
error (EXIT_FAILURE, 0, _("'%s' and '%s' do not seem to match"),
stripped_file, unstripped_file);
}
handle_file (output_file, create_dirs, stripped, &stripped_ehdr, unstripped);
elf_end (stripped);
close (stripped_fd);
elf_end (unstripped);
close (unstripped_fd);
}
/* Handle a pair of files opened implicitly by libdwfl for one module. */
static void
handle_dwfl_module (const char *output_file, bool create_dirs,
Dwfl_Module *mod, bool all, bool ignore, bool relocate)
{
GElf_Addr bias;
Elf *stripped = dwfl_module_getelf (mod, &bias);
if (stripped == NULL)
{
if (ignore)
return;
const char *file;
const char *modname = dwfl_module_info (mod, NULL, NULL, NULL,
NULL, NULL, &file, NULL);
if (file == NULL)
error (EXIT_FAILURE, 0,
_("cannot find stripped file for module '%s': %s"),
modname, dwfl_errmsg (-1));
else
error (EXIT_FAILURE, 0,
_("cannot open stripped file '%s' for module '%s': %s"),
modname, file, dwfl_errmsg (-1));
}
Elf *debug = dwarf_getelf (dwfl_module_getdwarf (mod, &bias));
if (debug == NULL && !all)
{
if (ignore)
return;
const char *file;
const char *modname = dwfl_module_info (mod, NULL, NULL, NULL,
NULL, NULL, NULL, &file);
if (file == NULL)
error (EXIT_FAILURE, 0,
_("cannot find debug file for module '%s': %s"),
modname, dwfl_errmsg (-1));
else
error (EXIT_FAILURE, 0,
_("cannot open debug file '%s' for module '%s': %s"),
modname, file, dwfl_errmsg (-1));
}
if (debug == stripped)
{
if (all)
debug = NULL;
else
{
const char *file;
const char *modname = dwfl_module_info (mod, NULL, NULL, NULL,
NULL, NULL, &file, NULL);
error (EXIT_FAILURE, 0, _("module '%s' file '%s' is not stripped"),
modname, file);
}
}
GElf_Ehdr stripped_ehdr;
ELF_CHECK (gelf_getehdr (stripped, &stripped_ehdr),
_("cannot create ELF descriptor: %s"));
if (stripped_ehdr.e_type == ET_REL)
{
if (!relocate)
{
/* We can't use the Elf handles already open,
because the DWARF sections have been relocated. */
const char *stripped_file = NULL;
const char *unstripped_file = NULL;
(void) dwfl_module_info (mod, NULL, NULL, NULL, NULL, NULL,
&stripped_file, &unstripped_file);
handle_explicit_files (output_file, create_dirs,
stripped_file, unstripped_file);
return;
}
/* Relocation is what we want! This ensures that all sections that can
get sh_addr values assigned have them, even ones not used in DWARF.
They might still be used in the symbol table. */
if (dwfl_module_relocations (mod) < 0)
error (EXIT_FAILURE, 0,
_("cannot cache section addresses for module '%s': %s"),
dwfl_module_info (mod, NULL, NULL, NULL, NULL, NULL, NULL, NULL),
dwfl_errmsg (-1));
}
handle_file (output_file, create_dirs, stripped, &stripped_ehdr, debug);
}
/* Handle one module being written to the output directory. */
static void
handle_output_dir_module (const char *output_dir, Dwfl_Module *mod,
bool all, bool ignore, bool modnames, bool relocate)
{
if (! modnames)
{
/* Make sure we've searched for the ELF file. */
GElf_Addr bias;
(void) dwfl_module_getelf (mod, &bias);
}
const char *file;
const char *name = dwfl_module_info (mod, NULL, NULL, NULL,
NULL, NULL, &file, NULL);
if (file == NULL && ignore)
return;
char *output_file;
if (asprintf (&output_file, "%s/%s", output_dir, modnames ? name : file) < 0)
error (EXIT_FAILURE, 0, _("memory exhausted"));
handle_dwfl_module (output_file, true, mod, all, ignore, relocate);
}
static void
list_module (Dwfl_Module *mod)
{
/* Make sure we have searched for the files. */
GElf_Addr bias;
bool have_elf = dwfl_module_getelf (mod, &bias) != NULL;
bool have_dwarf = dwfl_module_getdwarf (mod, &bias) != NULL;
const char *file;
const char *debug;
Dwarf_Addr start;
Dwarf_Addr end;
const char *name = dwfl_module_info (mod, NULL, &start, &end,
NULL, NULL, &file, &debug);
if (file != NULL && debug != NULL && (debug == file || !strcmp (debug, file)))
debug = ".";
const unsigned char *id;
GElf_Addr id_vaddr;
int id_len = dwfl_module_build_id (mod, &id, &id_vaddr);
printf ("%#" PRIx64 "+%#" PRIx64 " ", start, end - start);
if (id_len > 0)
{
do
printf ("%02" PRIx8, *id++);
while (--id_len > 0);
if (id_vaddr != 0)
printf ("@%#" PRIx64, id_vaddr);
}
else
putchar ('-');
printf (" %s %s %s\n",
file ?: have_elf ? "." : "-",
debug ?: have_dwarf ? "." : "-",
name);
}
struct match_module_info
{
char **patterns;
Dwfl_Module *found;
bool match_files;
};
static int
match_module (Dwfl_Module *mod,
void **userdata __attribute__ ((unused)),
const char *name,
Dwarf_Addr start __attribute__ ((unused)),
void *arg)
{
struct match_module_info *info = arg;
if (info->patterns[0] == NULL) /* Match all. */
{
match:
info->found = mod;
return DWARF_CB_ABORT;
}
if (info->match_files)
{
/* Make sure we've searched for the ELF file. */
GElf_Addr bias;
(void) dwfl_module_getelf (mod, &bias);
const char *file;
const char *check = dwfl_module_info (mod, NULL, NULL, NULL,
NULL, NULL, &file, NULL);
assert (check == name);
if (file == NULL)
return DWARF_CB_OK;
name = file;
}
for (char **p = info->patterns; *p != NULL; ++p)
if (fnmatch (*p, name, 0) == 0)
goto match;
return DWARF_CB_OK;
}
/* Handle files opened implicitly via libdwfl. */
static void
handle_implicit_modules (const struct arg_info *info)
{
struct match_module_info mmi = { info->args, NULL, info->match_files };
inline ptrdiff_t next (ptrdiff_t offset)
{
return dwfl_getmodules (info->dwfl, &match_module, &mmi, offset);
}
ptrdiff_t offset = next (0);
if (offset == 0)
error (EXIT_FAILURE, 0, _("no matching modules found"));
if (info->list)
do
list_module (mmi.found);
while ((offset = next (offset)) > 0);
else if (info->output_dir == NULL)
{
if (next (offset) != 0)
error (EXIT_FAILURE, 0, _("matched more than one module"));
handle_dwfl_module (info->output_file, false, mmi.found,
info->all, info->ignore, info->relocate);
}
else
do
handle_output_dir_module (info->output_dir, mmi.found,
info->all, info->ignore,
info->modnames, info->relocate);
while ((offset = next (offset)) > 0);
}
int
main (int argc, char **argv)
{
/* Make memory leak detection possible. */
mtrace ();
/* We use no threads here which can interfere with handling a stream. */
__fsetlocking (stdin, FSETLOCKING_BYCALLER);
__fsetlocking (stdout, FSETLOCKING_BYCALLER);
__fsetlocking (stderr, FSETLOCKING_BYCALLER);
/* Set locale. */
setlocale (LC_ALL, "");
/* Make sure the message catalog can be found. */
bindtextdomain (PACKAGE_TARNAME, LOCALEDIR);
/* Initialize the message catalog. */
textdomain (PACKAGE_TARNAME);
/* Parse and process arguments. */
const struct argp_child argp_children[] =
{
{
.argp = dwfl_standard_argp (),
.header = N_("Input selection options:"),
.group = 1,
},
{ .argp = NULL },
};
const struct argp argp =
{
.options = options,
.parser = parse_opt,
.children = argp_children,
.args_doc = N_("STRIPPED-FILE DEBUG-FILE\n[MODULE...]"),
.doc = N_("\
Combine stripped files with separate symbols and debug information.\v\
The first form puts the result in DEBUG-FILE if -o was not given.\n\
\n\
MODULE arguments give file name patterns matching modules to process.\n\
With -f these match the file name of the main (stripped) file \
(slashes are never special), otherwise they match the simple module names. \
With no arguments, process all modules found.\n\
\n\
Multiple modules are written to files under OUTPUT-DIRECTORY, \
creating subdirectories as needed. \
With -m these files have simple module names, otherwise they have the \
name of the main file complete with directory underneath OUTPUT-DIRECTORY.\n\
\n\
With -n no files are written, but one line to standard output for each module:\
\n\tSTART+SIZE BUILDID FILE DEBUGFILE MODULENAME\n\
START and SIZE are hexadecimal giving the address bounds of the module. \
BUILDID is hexadecimal for the build ID bits, or - if no ID is known; \
the hexadecimal may be followed by @0xADDR giving the address where the \
ID resides if that is known. \
FILE is the file name found for the module, or - if none was found, \
or . if an ELF image is available but not from any named file. \
DEBUGFILE is the separate debuginfo file name, \
or - if no debuginfo was found, or . if FILE contains the debug information.\
")
};
int remaining;
struct arg_info info = { .args = NULL };
error_t result = argp_parse (&argp, argc, argv, 0, &remaining, &info);
if (result == ENOSYS)
assert (info.dwfl == NULL);
else if (result)
return EXIT_FAILURE;
assert (info.args != NULL);
/* Tell the library which version we are expecting. */
elf_version (EV_CURRENT);
if (info.dwfl == NULL)
{
assert (result == ENOSYS);
if (info.output_dir != NULL)
{
char *file;
if (asprintf (&file, "%s/%s", info.output_dir, info.args[0]) < 0)
error (EXIT_FAILURE, 0, _("memory exhausted"));
handle_explicit_files (file, true, info.args[0], info.args[1]);
free (file);
}
else
handle_explicit_files (info.output_file, false,
info.args[0], info.args[1]);
}
else
{
/* parse_opt checked this. */
assert (info.output_file != NULL || info.output_dir != NULL || info.list);
handle_implicit_modules (&info);
dwfl_end (info.dwfl);
}
return 0;
}
#include "debugpred.h"
| gpl-3.0 |
pexip/os-gettext | gettext-tools/gnulib-lib/unictype/ctype_space.c | 2 | 1054 | /* ISO C <ctype.h> like properties of Unicode characters.
Copyright (C) 2002, 2006-2007, 2009-2020 Free Software Foundation, Inc.
Written by Bruno Haible <bruno@clisp.org>, 2002.
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 <https://www.gnu.org/licenses/>. */
#include <config.h>
/* Specification. */
#include "unictype.h"
#include "bitmap.h"
/* Define u_is_space table. */
#include "ctype_space.h"
bool
uc_is_space (ucs4_t uc)
{
return bitmap_lookup (&u_is_space, uc);
}
| gpl-3.0 |
Philips14171/qt-creator-opensource-src-4.2.1 | src/plugins/projectexplorer/devicesupport/desktopdeviceconfigurationwidget.cpp | 2 | 3322 | /****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of Qt Creator.
**
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
****************************************************************************/
#include "desktopdeviceconfigurationwidget.h"
#include "ui_desktopdeviceconfigurationwidget.h"
#include <projectexplorer/projectexplorerconstants.h>
#include <utils/utilsicons.h>
#include <utils/portlist.h>
#include <utils/qtcassert.h>
using namespace ProjectExplorer::Constants;
namespace ProjectExplorer {
DesktopDeviceConfigurationWidget::DesktopDeviceConfigurationWidget(const IDevice::Ptr &device,
QWidget *parent) :
IDeviceWidget(device, parent),
m_ui(new Ui::DesktopDeviceConfigurationWidget)
{
m_ui->setupUi(this);
connect(m_ui->freePortsLineEdit, &QLineEdit::textChanged,
this, &DesktopDeviceConfigurationWidget::updateFreePorts);
initGui();
}
DesktopDeviceConfigurationWidget::~DesktopDeviceConfigurationWidget()
{
delete m_ui;
}
void DesktopDeviceConfigurationWidget::updateDeviceFromUi()
{
updateFreePorts();
}
void DesktopDeviceConfigurationWidget::updateFreePorts()
{
device()->setFreePorts(Utils::PortList::fromString(m_ui->freePortsLineEdit->text()));
m_ui->portsWarningLabel->setVisible(!device()->freePorts().hasMore());
}
void DesktopDeviceConfigurationWidget::initGui()
{
QTC_CHECK(device()->machineType() == IDevice::Hardware);
m_ui->machineTypeValueLabel->setText(tr("Physical Device"));
m_ui->freePortsLineEdit->setPlaceholderText(
QString::fromLatin1("eg: %1-%2").arg(DESKTOP_PORT_START).arg(DESKTOP_PORT_END));
m_ui->portsWarningLabel->setPixmap(Utils::Icons::WARNING.pixmap());
m_ui->portsWarningLabel->setToolTip(QLatin1String("<font color=\"red\">")
+ tr("You will need at least one port for QML debugging.")
+ QLatin1String("</font>"));
QRegExpValidator * const portsValidator
= new QRegExpValidator(QRegExp(Utils::PortList::regularExpression()), this);
m_ui->freePortsLineEdit->setValidator(portsValidator);
m_ui->freePortsLineEdit->setText(device()->freePorts().toString());
updateFreePorts();
}
} // namespace ProjectExplorer
| gpl-3.0 |
videogamepreservation/micropolis | src/tk/tkentry.c | 2 | 55452 | /*
* tkEntry.c --
*
* This module implements entry widgets for the Tk
* toolkit. An entry displays a string and allows
* the string to be edited.
*
* Copyright 1990 Regents of the University of California.
* Permission to use, copy, modify, and distribute this
* software and its documentation for any purpose and without
* fee is hereby granted, provided that the above copyright
* notice appear in all copies. The University of California
* makes no representations about the suitability of this
* software for any purpose. It is provided "as is" without
* express or implied warranty.
*/
#ifndef lint
static char rcsid[] = "$Header: /user6/ouster/wish/RCS/tkEntry.c,v 1.37 92/08/21 16:09:15 ouster Exp $ SPRITE (Berkeley)";
#endif
#include "default.h"
#include "tkconfig.h"
#include "tkint.h"
/*
* A data structure of the following type is kept for each entry
* widget managed by this file:
*/
typedef struct {
Tk_Window tkwin; /* Window that embodies the entry. NULL
* means that the window has been destroyed
* but the data structures haven't yet been
* cleaned up.*/
Tcl_Interp *interp; /* Interpreter associated with entry. */
int numChars; /* Number of non-NULL characters in
* string (may be 0). */
char *string; /* Pointer to storage for string;
* NULL-terminated; malloc-ed. */
char *textVarName; /* Name of variable (malloc'ed) or NULL.
* If non-NULL, entry's string tracks the
* contents of this variable and vice versa. */
Tk_Uid state; /* Normal or disabled. Entry is read-only
* when disabled. */
/*
* Information used when displaying widget:
*/
Tk_3DBorder normalBorder; /* Used for drawing border around whole
* window, plus used for background. */
int borderWidth; /* Width of 3-D border around window. */
int relief; /* 3-D effect: TK_RELIEF_RAISED, etc. */
XFontStruct *fontPtr; /* Information about text font, or NULL. */
XColor *fgColorPtr; /* Text color in normal mode. */
GC textGC; /* For drawing normal text. */
Tk_3DBorder selBorder; /* Border and background for selected
* characters. */
int selBorderWidth; /* Width of border around selection. */
XColor *selFgColorPtr; /* Foreground color for selected text. */
GC selTextGC; /* For drawing selected text. */
Tk_3DBorder cursorBorder; /* Used to draw vertical bar for insertion
* cursor. */
int cursorWidth; /* Total width of insert cursor. */
int cursorBorderWidth; /* Width of 3-D border around insert cursor. */
int cursorOnTime; /* Number of milliseconds cursor should spend
* in "on" state for each blink. */
int cursorOffTime; /* Number of milliseconds cursor should spend
* in "off" state for each blink. */
Tk_TimerToken cursorBlinkHandler;
/* Timer handler used to blink cursor on and
* off. */
int avgWidth; /* Width of average character. */
int prefWidth; /* Desired width of window, measured in
* average characters. */
int offset; /* 0 if window is flat, or borderWidth if
* raised or sunken. */
int leftIndex; /* Index of left-most character visible in
* window. */
int cursorPos; /* Index of character before which next
* typed character will be inserted. */
/*
* Information about what's selected, if any.
*/
int selectFirst; /* Index of first selected character (-1 means
* nothing selected. */
int selectLast; /* Index of last selected character (-1 means
* nothing selected. */
int selectAnchor; /* Fixed end of selection (i.e. "select to"
* operation will use this as one end of the
* selection). */
int exportSelection; /* Non-zero means tie internal entry selection
* to X selection. */
/*
* Information for scanning:
*/
int scanMarkX; /* X-position at which scan started (e.g.
* button was pressed here). */
int scanMarkIndex; /* Index of character that was at left of
* window when scan started. */
/*
* Miscellaneous information:
*/
Cursor cursor; /* Current cursor for window, or None. */
char *scrollCmd; /* Command prefix for communicating with
* scrollbar(s). Malloc'ed. NULL means
* no command to issue. */
int flags; /* Miscellaneous flags; see below for
* definitions. */
} Entry;
/*
* Assigned bits of "flags" fields of Entry structures, and what those
* bits mean:
*
* REDRAW_PENDING: Non-zero means a DoWhenIdle handler has
* already been queued to redisplay the entry.
* BORDER_NEEDED: Non-zero means 3-D border must be redrawn
* around window during redisplay. Normally
* only text portion needs to be redrawn.
* CURSOR_ON: Non-zero means cursor is displayed at
* present. 0 means it isn't displayed.
* GOT_FOCUS: Non-zero means this window has the input
* focus.
*/
#define REDRAW_PENDING 1
#define BORDER_NEEDED 2
#define CURSOR_ON 4
#define GOT_FOCUS 8
/*
* Information used for argv parsing.
*/
static Tk_ConfigSpec configSpecs[] = {
{TK_CONFIG_BORDER, "-background", "background", "Background",
DEF_ENTRY_BG_COLOR, Tk_Offset(Entry, normalBorder),
TK_CONFIG_COLOR_ONLY},
{TK_CONFIG_BORDER, "-background", "background", "Background",
DEF_ENTRY_BG_MONO, Tk_Offset(Entry, normalBorder),
TK_CONFIG_MONO_ONLY},
{TK_CONFIG_SYNONYM, "-bd", "borderWidth", (char *) NULL,
(char *) NULL, 0, 0},
{TK_CONFIG_SYNONYM, "-bg", "background", (char *) NULL,
(char *) NULL, 0, 0},
{TK_CONFIG_PIXELS, "-borderwidth", "borderWidth", "BorderWidth",
DEF_ENTRY_BORDER_WIDTH, Tk_Offset(Entry, borderWidth), 0},
{TK_CONFIG_ACTIVE_CURSOR, "-cursor", "cursor", "Cursor",
DEF_ENTRY_CURSOR, Tk_Offset(Entry, cursor), TK_CONFIG_NULL_OK},
{TK_CONFIG_BORDER, "-cursorbackground", "cursorBackground", "Foreground",
DEF_ENTRY_CURSOR_BG, Tk_Offset(Entry, cursorBorder), 0},
{TK_CONFIG_PIXELS, "-cursorborderwidth", "cursorBorderWidth", "BorderWidth",
DEF_ENTRY_CURSOR_BD_COLOR, Tk_Offset(Entry, cursorBorderWidth),
TK_CONFIG_COLOR_ONLY},
{TK_CONFIG_PIXELS, "-cursorborderwidth", "cursorBorderWidth", "BorderWidth",
DEF_ENTRY_CURSOR_BD_MONO, Tk_Offset(Entry, cursorBorderWidth),
TK_CONFIG_MONO_ONLY},
{TK_CONFIG_INT, "-cursorofftime", "cursorOffTime", "OffTime",
DEF_ENTRY_CURSOR_OFF_TIME, Tk_Offset(Entry, cursorOffTime), 0},
{TK_CONFIG_INT, "-cursorontime", "cursorOnTime", "OnTime",
DEF_ENTRY_CURSOR_ON_TIME, Tk_Offset(Entry, cursorOnTime), 0},
{TK_CONFIG_PIXELS, "-cursorwidth", "cursorWidth", "CursorWidth",
DEF_ENTRY_CURSOR_WIDTH, Tk_Offset(Entry, cursorWidth), 0},
{TK_CONFIG_BOOLEAN, "-exportselection", "exportSelection",
"ExportSelection", DEF_ENTRY_EXPORT_SELECTION,
Tk_Offset(Entry, exportSelection), 0},
{TK_CONFIG_SYNONYM, "-fg", "foreground", (char *) NULL,
(char *) NULL, 0, 0},
{TK_CONFIG_FONT, "-font", "font", "Font",
DEF_ENTRY_FONT, Tk_Offset(Entry, fontPtr), 0},
{TK_CONFIG_COLOR, "-foreground", "foreground", "Foreground",
DEF_ENTRY_FG, Tk_Offset(Entry, fgColorPtr), 0},
{TK_CONFIG_RELIEF, "-relief", "relief", "Relief",
DEF_ENTRY_RELIEF, Tk_Offset(Entry, relief), 0},
{TK_CONFIG_STRING, "-scrollcommand", "scrollCommand", "ScrollCommand",
DEF_ENTRY_SCROLL_COMMAND, Tk_Offset(Entry, scrollCmd), 0},
{TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground",
DEF_ENTRY_SELECT_COLOR, Tk_Offset(Entry, selBorder),
TK_CONFIG_COLOR_ONLY},
{TK_CONFIG_BORDER, "-selectbackground", "selectBackground", "Foreground",
DEF_ENTRY_SELECT_MONO, Tk_Offset(Entry, selBorder),
TK_CONFIG_MONO_ONLY},
{TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth",
DEF_ENTRY_SELECT_BD_COLOR, Tk_Offset(Entry, selBorderWidth),
TK_CONFIG_COLOR_ONLY},
{TK_CONFIG_PIXELS, "-selectborderwidth", "selectBorderWidth", "BorderWidth",
DEF_ENTRY_SELECT_BD_MONO, Tk_Offset(Entry, selBorderWidth),
TK_CONFIG_MONO_ONLY},
{TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background",
DEF_ENTRY_SELECT_FG_COLOR, Tk_Offset(Entry, selFgColorPtr),
TK_CONFIG_COLOR_ONLY},
{TK_CONFIG_COLOR, "-selectforeground", "selectForeground", "Background",
DEF_ENTRY_SELECT_FG_MONO, Tk_Offset(Entry, selFgColorPtr),
TK_CONFIG_MONO_ONLY},
{TK_CONFIG_UID, "-state", "state", "State",
DEF_ENTRY_STATE, Tk_Offset(Entry, state), 0},
{TK_CONFIG_STRING, "-textvariable", "textVariable", "Variable",
DEF_ENTRY_TEXT_VARIABLE, Tk_Offset(Entry, textVarName),
TK_CONFIG_NULL_OK},
{TK_CONFIG_INT, "-width", "width", "Width",
DEF_ENTRY_WIDTH, Tk_Offset(Entry, prefWidth), 0},
{TK_CONFIG_END, (char *) NULL, (char *) NULL, (char *) NULL,
(char *) NULL, 0, 0}
};
/*
* Flags for GetEntryIndex procedure:
*/
#define ZERO_OK 1
#define LAST_PLUS_ONE_OK 2
/*
* Forward declarations for procedures defined later in this file:
*/
static int ConfigureEntry _ANSI_ARGS_((Tcl_Interp *interp,
Entry *entryPtr, int argc, char **argv,
int flags));
static void DeleteChars _ANSI_ARGS_((Entry *entryPtr, int index,
int count));
static void DestroyEntry _ANSI_ARGS_((ClientData clientData));
static void DisplayEntry _ANSI_ARGS_((ClientData clientData));
static int GetEntryIndex _ANSI_ARGS_((Tcl_Interp *interp,
Entry *entryPtr, char *string, int *indexPtr));
static void InsertChars _ANSI_ARGS_((Entry *entryPtr, int index,
char *string));
static void EntryBlinkProc _ANSI_ARGS_((ClientData clientData));
static void EntryEventProc _ANSI_ARGS_((ClientData clientData,
XEvent *eventPtr));
static void EntryFocusProc _ANSI_ARGS_ ((ClientData clientData,
int gotFocus));
static int EntryFetchSelection _ANSI_ARGS_((ClientData clientData,
int offset, char *buffer, int maxBytes));
static void EntryLostSelection _ANSI_ARGS_((
ClientData clientData));
static void EventuallyRedraw _ANSI_ARGS_((Entry *entryPtr));
static void EntryScanTo _ANSI_ARGS_((Entry *entryPtr, int y));
static void EntrySetValue _ANSI_ARGS_((Entry *entryPtr,
char *value));
static void EntrySelectTo _ANSI_ARGS_((
Entry *entryPtr, int index));
static char * EntryTextVarProc _ANSI_ARGS_((ClientData clientData,
Tcl_Interp *interp, char *name1, char *name2,
int flags));
static void EntryUpdateScrollbar _ANSI_ARGS_((Entry *entryPtr));
static int EntryWidgetCmd _ANSI_ARGS_((ClientData clientData,
Tcl_Interp *interp, int argc, char **argv));
/*
*--------------------------------------------------------------
*
* Tk_EntryCmd --
*
* This procedure is invoked to process the "entry" Tcl
* command. See the user documentation for details on what
* it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
int
Tk_EntryCmd(clientData, interp, argc, argv)
ClientData clientData; /* Main window associated with
* interpreter. */
Tcl_Interp *interp; /* Current interpreter. */
int argc; /* Number of arguments. */
char **argv; /* Argument strings. */
{
Tk_Window tkwin = (Tk_Window) clientData;
register Entry *entryPtr;
Tk_Window new;
if (argc < 2) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " pathName ?options?\"", (char *) NULL);
return TCL_ERROR;
}
new = Tk_CreateWindowFromPath(interp, tkwin, argv[1], (char *) NULL);
if (new == NULL) {
return TCL_ERROR;
}
/*
* Initialize the fields of the structure that won't be initialized
* by ConfigureEntry, or that ConfigureEntry requires to be
* initialized already (e.g. resource pointers).
*/
entryPtr = (Entry *) ckalloc(sizeof(Entry));
entryPtr->tkwin = new;
entryPtr->interp = interp;
entryPtr->numChars = 0;
entryPtr->string = (char *) ckalloc(1);
entryPtr->string[0] = '\0';
entryPtr->textVarName = NULL;
entryPtr->state = tkNormalUid;
entryPtr->normalBorder = NULL;
entryPtr->fontPtr = NULL;
entryPtr->fgColorPtr = NULL;
entryPtr->textGC = None;
entryPtr->selBorder = NULL;
entryPtr->selFgColorPtr = NULL;
entryPtr->selTextGC = NULL;
entryPtr->cursorBorder = NULL;
entryPtr->cursorBlinkHandler = (Tk_TimerToken) NULL;
entryPtr->leftIndex = 0;
entryPtr->cursorPos = 0;
entryPtr->selectFirst = -1;
entryPtr->selectLast = -1;
entryPtr->selectAnchor = 0;
entryPtr->exportSelection = 1;
entryPtr->scanMarkX = 0;
entryPtr->cursor = None;
entryPtr->scrollCmd = NULL;
entryPtr->flags = 0;
Tk_SetClass(entryPtr->tkwin, "Entry");
Tk_CreateEventHandler(entryPtr->tkwin, ExposureMask|StructureNotifyMask,
EntryEventProc, (ClientData) entryPtr);
Tk_CreateSelHandler(entryPtr->tkwin, XA_STRING, EntryFetchSelection,
(ClientData) entryPtr, XA_STRING);
Tcl_CreateCommand(interp, Tk_PathName(entryPtr->tkwin), EntryWidgetCmd,
(ClientData) entryPtr, (void (*)()) NULL);
if (ConfigureEntry(interp, entryPtr, argc-2, argv+2, 0) != TCL_OK) {
goto error;
}
Tk_CreateFocusHandler(entryPtr->tkwin, EntryFocusProc,
(ClientData) entryPtr);
interp->result = Tk_PathName(entryPtr->tkwin);
return TCL_OK;
error:
Tk_DestroyWindow(entryPtr->tkwin);
return TCL_ERROR;
}
/*
*--------------------------------------------------------------
*
* EntryWidgetCmd --
*
* This procedure is invoked to process the Tcl command
* that corresponds to a widget managed by this module.
* See the user documentation for details on what it does.
*
* Results:
* A standard Tcl result.
*
* Side effects:
* See the user documentation.
*
*--------------------------------------------------------------
*/
static int
EntryWidgetCmd(clientData, interp, argc, argv)
ClientData clientData; /* Information about entry widget. */
Tcl_Interp *interp; /* Current interpreter. */
int argc; /* Number of arguments. */
char **argv; /* Argument strings. */
{
register Entry *entryPtr = (Entry *) clientData;
int result = TCL_OK;
int length;
char c;
if (argc < 2) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " option ?arg arg ...?\"", (char *) NULL);
return TCL_ERROR;
}
Tk_Preserve((ClientData) entryPtr);
c = argv[1][0];
length = strlen(argv[1]);
if ((c == 'c') && (strncmp(argv[1], "configure", length) == 0)
&& (length >= 2)) {
if (argc == 2) {
result = Tk_ConfigureInfo(interp, entryPtr->tkwin, configSpecs,
(char *) entryPtr, (char *) NULL, 0);
} else if (argc == 3) {
result = Tk_ConfigureInfo(interp, entryPtr->tkwin, configSpecs,
(char *) entryPtr, argv[2], 0);
} else {
result = ConfigureEntry(interp, entryPtr, argc-2, argv+2,
TK_CONFIG_ARGV_ONLY);
}
} else if ((c == 'c') && (strncmp(argv[1], "cursor", length) == 0)
&& (length >= 2)) {
if (argc != 3) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " cursor pos\"",
(char *) NULL);
goto error;
}
if (GetEntryIndex(interp, entryPtr, argv[2], &entryPtr->cursorPos)
!= TCL_OK) {
goto error;
}
EventuallyRedraw(entryPtr);
} else if ((c == 'd') && (strncmp(argv[1], "delete", length) == 0)) {
int first, last;
if ((argc < 3) || (argc > 4)) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " delete firstIndex ?lastIndex?\"",
(char *) NULL);
goto error;
}
if (GetEntryIndex(interp, entryPtr, argv[2], &first) != TCL_OK) {
goto error;
}
if (argc == 3) {
last = first;
} else {
if (GetEntryIndex(interp, entryPtr, argv[3], &last) != TCL_OK) {
goto error;
}
}
if ((last >= first) && (entryPtr->state == tkNormalUid)) {
DeleteChars(entryPtr, first, last+1-first);
}
} else if ((c == 'g') && (strncmp(argv[1], "get", length) == 0)) {
if (argc != 2) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " get\"", (char *) NULL);
goto error;
}
interp->result = entryPtr->string;
} else if ((c == 'i') && (strncmp(argv[1], "index", length) == 0)
&& (length >= 2)) {
int index;
if (argc != 3) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " index string\"", (char *) NULL);
goto error;
}
if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) {
goto error;
}
sprintf(interp->result, "%d", index);
} else if ((c == 'i') && (strncmp(argv[1], "insert", length) == 0)
&& (length >= 2)) {
int index;
if (argc != 4) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " insert index text\"",
(char *) NULL);
goto error;
}
if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) {
goto error;
}
if (entryPtr->state == tkNormalUid) {
InsertChars(entryPtr, index, argv[3]);
}
} else if ((c == 's') && (length >= 2)
&& (strncmp(argv[1], "scan", length) == 0)) {
int x;
if (argc != 4) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " scan mark|dragto x\"", (char *) NULL);
goto error;
}
if (Tcl_GetInt(interp, argv[3], &x) != TCL_OK) {
goto error;
}
if ((argv[2][0] == 'm')
&& (strncmp(argv[2], "mark", strlen(argv[2])) == 0)) {
entryPtr->scanMarkX = x;
entryPtr->scanMarkIndex = entryPtr->leftIndex;
} else if ((argv[2][0] == 'd')
&& (strncmp(argv[2], "dragto", strlen(argv[2])) == 0)) {
EntryScanTo(entryPtr, x);
} else {
Tcl_AppendResult(interp, "bad scan option \"", argv[2],
"\": must be mark or dragto", (char *) NULL);
goto error;
}
} else if ((c == 's') && (length >= 2)
&& (strncmp(argv[1], "select", length) == 0)) {
int index;
if (argc < 3) {
Tcl_AppendResult(interp, "too few args: should be \"",
argv[0], " select option ?index?\"", (char *) NULL);
goto error;
}
length = strlen(argv[2]);
c = argv[2][0];
if ((c == 'c') && (argv[2] != NULL)
&& (strncmp(argv[2], "clear", length) == 0)) {
if (argc != 3) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " select clear\"", (char *) NULL);
goto error;
}
if (entryPtr->selectFirst != -1) {
entryPtr->selectFirst = entryPtr->selectLast = -1;
EventuallyRedraw(entryPtr);
}
goto done;
}
if (argc >= 4) {
if (GetEntryIndex(interp, entryPtr, argv[3], &index) != TCL_OK) {
goto error;
}
}
if ((c == 'a') && (strncmp(argv[2], "adjust", length) == 0)) {
if (argc != 4) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " select adjust index\"",
(char *) NULL);
goto error;
}
if (entryPtr->selectFirst >= 0) {
if (index < (entryPtr->selectFirst + entryPtr->selectLast)/2) {
entryPtr->selectAnchor = entryPtr->selectLast + 1;
} else {
entryPtr->selectAnchor = entryPtr->selectFirst;
}
}
EntrySelectTo(entryPtr, index);
} else if ((c == 'f') && (strncmp(argv[2], "from", length) == 0)) {
if (argc != 4) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " select from index\"",
(char *) NULL);
goto error;
}
entryPtr->selectAnchor = index;
} else if ((c == 't') && (strncmp(argv[2], "to", length) == 0)) {
if (argc != 4) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " select to index\"",
(char *) NULL);
goto error;
}
EntrySelectTo(entryPtr, index);
} else {
Tcl_AppendResult(interp, "bad select option \"", argv[2],
"\": must be adjust, clear, from, or to", (char *) NULL);
goto error;
}
} else if ((c == 'v') && (strncmp(argv[1], "view", length) == 0)) {
int index;
if (argc != 3) {
Tcl_AppendResult(interp, "wrong # args: should be \"",
argv[0], " view index\"", (char *) NULL);
goto error;
}
if (GetEntryIndex(interp, entryPtr, argv[2], &index) != TCL_OK) {
goto error;
}
if ((index >= entryPtr->numChars) && (index > 0)) {
index = entryPtr->numChars-1;
}
entryPtr->leftIndex = index;
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
} else {
Tcl_AppendResult(interp, "bad option \"", argv[1],
"\": must be configure, cursor, delete, get, index, ",
"insert, scan, select, or view", (char *) NULL);
goto error;
}
done:
Tk_Release((ClientData) entryPtr);
return result;
error:
Tk_Release((ClientData) entryPtr);
return TCL_ERROR;
}
/*
*----------------------------------------------------------------------
*
* DestroyEntry --
*
* This procedure is invoked by Tk_EventuallyFree or Tk_Release
* to clean up the internal structure of an entry at a safe time
* (when no-one is using it anymore).
*
* Results:
* None.
*
* Side effects:
* Everything associated with the entry is freed up.
*
*----------------------------------------------------------------------
*/
static void
DestroyEntry(clientData)
ClientData clientData; /* Info about entry widget. */
{
register Entry *entryPtr = (Entry *) clientData;
ckfree(entryPtr->string);
if (entryPtr->normalBorder != NULL) {
Tk_Free3DBorder(entryPtr->normalBorder);
}
if (entryPtr->textVarName != NULL) {
Tcl_UntraceVar(entryPtr->interp, entryPtr->textVarName,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, (ClientData) entryPtr);
ckfree(entryPtr->textVarName);
}
if (entryPtr->fontPtr != NULL) {
Tk_FreeFontStruct(entryPtr->fontPtr);
}
if (entryPtr->fgColorPtr != NULL) {
Tk_FreeColor(entryPtr->fgColorPtr);
}
if (entryPtr->textGC != None) {
Tk_FreeGC(entryPtr->textGC);
}
if (entryPtr->selBorder != NULL) {
Tk_Free3DBorder(entryPtr->selBorder);
}
if (entryPtr->selFgColorPtr != NULL) {
Tk_FreeColor(entryPtr->selFgColorPtr);
}
if (entryPtr->selTextGC != None) {
Tk_FreeGC(entryPtr->selTextGC);
}
if (entryPtr->cursorBorder != NULL) {
Tk_Free3DBorder(entryPtr->cursorBorder);
}
if (entryPtr->cursorBlinkHandler != NULL) {
Tk_DeleteTimerHandler(entryPtr->cursorBlinkHandler);
entryPtr->cursorBlinkHandler = NULL;
}
if (entryPtr->cursor != None) {
Tk_FreeCursor(entryPtr->cursor);
}
if (entryPtr->scrollCmd != NULL) {
ckfree(entryPtr->scrollCmd);
}
ckfree((char *) entryPtr);
}
/*
*----------------------------------------------------------------------
*
* ConfigureEntry --
*
* This procedure is called to process an argv/argc list, plus
* the Tk option database, in order to configure (or reconfigure)
* an entry widget.
*
* Results:
* The return value is a standard Tcl result. If TCL_ERROR is
* returned, then interp->result contains an error message.
*
* Side effects:
* Configuration information, such as colors, border width,
* etc. get set for entryPtr; old resources get freed,
* if there were any.
*
*----------------------------------------------------------------------
*/
static int
ConfigureEntry(interp, entryPtr, argc, argv, flags)
Tcl_Interp *interp; /* Used for error reporting. */
register Entry *entryPtr; /* Information about widget; may or may
* not already have values for some fields. */
int argc; /* Number of valid entries in argv. */
char **argv; /* Arguments. */
int flags; /* Flags to pass to Tk_ConfigureWidget. */
{
XGCValues gcValues;
GC new;
int width, height, fontHeight, oldExport;
/*
* Eliminate any existing trace on a variable monitored by the entry.
*/
if (entryPtr->textVarName != NULL) {
Tcl_UntraceVar(interp, entryPtr->textVarName,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, (ClientData) entryPtr);
}
oldExport = entryPtr->exportSelection;
if (Tk_ConfigureWidget(interp, entryPtr->tkwin, configSpecs,
argc, argv, (char *) entryPtr, flags) != TCL_OK) {
return TCL_ERROR;
}
/*
* If the entry is tied to the value of a variable, then set up
* a trace on the variable's value, create the variable if it doesn't
* exist, and set the entry's value from the variable's value.
*/
if (entryPtr->textVarName != NULL) {
char *value;
value = Tcl_GetVar(interp, entryPtr->textVarName, TCL_GLOBAL_ONLY);
if (value == NULL) {
Tcl_SetVar(interp, entryPtr->textVarName, entryPtr->string,
TCL_GLOBAL_ONLY);
} else {
EntrySetValue(entryPtr, value);
}
Tcl_TraceVar(interp, entryPtr->textVarName,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, (ClientData) entryPtr);
}
/*
* A few other options also need special processing, such as parsing
* the geometry and setting the background from a 3-D border.
*/
if ((entryPtr->state != tkNormalUid)
&& (entryPtr->state != tkDisabledUid)) {
Tcl_AppendResult(interp, "bad state value \"", entryPtr->state,
"\": must be normal or disabled", (char *) NULL);
entryPtr->state = tkNormalUid;
return TCL_ERROR;
}
Tk_SetBackgroundFromBorder(entryPtr->tkwin, entryPtr->normalBorder);
gcValues.foreground = entryPtr->fgColorPtr->pixel;
gcValues.font = entryPtr->fontPtr->fid;
gcValues.graphics_exposures = False;
new = Tk_GetGC(entryPtr->tkwin, GCForeground|GCFont|GCGraphicsExposures,
&gcValues);
if (entryPtr->textGC != None) {
Tk_FreeGC(entryPtr->textGC);
}
entryPtr->textGC = new;
gcValues.foreground = entryPtr->selFgColorPtr->pixel;
gcValues.font = entryPtr->fontPtr->fid;
new = Tk_GetGC(entryPtr->tkwin, GCForeground|GCFont, &gcValues);
if (entryPtr->selTextGC != None) {
Tk_FreeGC(entryPtr->selTextGC);
}
entryPtr->selTextGC = new;
if (entryPtr->cursorWidth > 2*entryPtr->fontPtr->min_bounds.width) {
entryPtr->cursorWidth = 2*entryPtr->fontPtr->min_bounds.width;
if (entryPtr->cursorWidth == 0) {
entryPtr->cursorWidth = 2;
}
}
if (entryPtr->cursorBorderWidth > entryPtr->cursorWidth/2) {
entryPtr->cursorBorderWidth = entryPtr->cursorWidth/2;
}
/*
* Restart the cursor timing sequence in case the on-time or off-time
* just changed.
*/
if (entryPtr->flags & GOT_FOCUS) {
EntryFocusProc((ClientData) entryPtr, 1);
}
/*
* Claim the selection if we've suddenly started exporting it.
*/
if (entryPtr->exportSelection && (!oldExport)
&& (entryPtr->selectFirst != -1)) {
Tk_OwnSelection(entryPtr->tkwin, EntryLostSelection,
(ClientData) entryPtr);
}
/*
* Register the desired geometry for the window, and arrange for
* the window to be redisplayed.
*/
fontHeight = entryPtr->fontPtr->ascent + entryPtr->fontPtr->descent;
entryPtr->avgWidth = XTextWidth(entryPtr->fontPtr, "0", 1);
width = entryPtr->prefWidth*entryPtr->avgWidth + (15*fontHeight)/10;
height = fontHeight + 2*entryPtr->borderWidth + 2;
Tk_GeometryRequest(entryPtr->tkwin, width, height);
Tk_SetInternalBorder(entryPtr->tkwin, entryPtr->borderWidth);
if (entryPtr->relief != TK_RELIEF_FLAT) {
entryPtr->offset = entryPtr->borderWidth;
} else {
entryPtr->offset = 0;
}
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
return TCL_OK;
}
/*
*--------------------------------------------------------------
*
* DisplayEntry --
*
* This procedure redraws the contents of an entry window.
*
* Results:
* None.
*
* Side effects:
* Information appears on the screen.
*
*--------------------------------------------------------------
*/
static void
DisplayEntry(clientData)
ClientData clientData; /* Information about window. */
{
register Entry *entryPtr = (Entry *) clientData;
register Tk_Window tkwin = entryPtr->tkwin;
int startX, baseY, selStartX, selEndX, index, cursorX;
int xBound, count;
Pixmap pixmap;
entryPtr->flags &= ~REDRAW_PENDING;
if ((entryPtr->tkwin == NULL) || !Tk_IsMapped(tkwin)) {
return;
}
/*
* In order to avoid screen flashes, this procedure redraws the
* textual area of the entry into off-screen memory, then copies
* it back on-screen in a single operation. This means there's
* no point in time where the on-screen image has been cleared.
*/
pixmap = XCreatePixmap(Tk_Display(tkwin), Tk_WindowId(tkwin),
Tk_Width(tkwin), Tk_Height(tkwin),
Tk_DefaultDepth(Tk_Screen(tkwin)));
/*
* Compute x-coordinate of the "leftIndex" character, plus limit
* of visible x-coordinates (actually, pixel just after last visible
* one), plus vertical position of baseline of text.
*/
startX = entryPtr->offset;
xBound = Tk_Width(tkwin) - entryPtr->offset;
baseY = (Tk_Height(tkwin) + entryPtr->fontPtr->ascent
- entryPtr->fontPtr->descent)/2;
/*
* Draw the background in three layers. From bottom to top the
* layers are: normal background, selection background, and
* insertion cursor background.
*/
Tk_Fill3DRectangle(Tk_Display(tkwin), pixmap, entryPtr->normalBorder,
0, 0, Tk_Width(tkwin), Tk_Height(tkwin), 0, TK_RELIEF_FLAT);
if (entryPtr->selectLast >= entryPtr->leftIndex) {
if (entryPtr->selectFirst <= entryPtr->leftIndex) {
selStartX = startX;
index = entryPtr->leftIndex;
} else {
(void) TkMeasureChars(entryPtr->fontPtr,
entryPtr->string+entryPtr->leftIndex,
entryPtr->selectFirst - entryPtr->leftIndex, startX,
xBound, TK_PARTIAL_OK|TK_NEWLINES_NOT_SPECIAL, &selStartX);
index = entryPtr->selectFirst;
}
if (selStartX < xBound) {
(void) TkMeasureChars(entryPtr->fontPtr,
entryPtr->string + index, entryPtr->selectLast +1 - index,
selStartX, xBound, TK_PARTIAL_OK|TK_NEWLINES_NOT_SPECIAL,
&selEndX);
Tk_Fill3DRectangle(Tk_Display(tkwin), pixmap, entryPtr->selBorder,
selStartX - entryPtr->selBorderWidth,
baseY - entryPtr->fontPtr->ascent
- entryPtr->selBorderWidth,
(selEndX - selStartX) + 2*entryPtr->selBorderWidth,
entryPtr->fontPtr->ascent + entryPtr->fontPtr->descent
+ 2*entryPtr->selBorderWidth,
entryPtr->selBorderWidth, TK_RELIEF_RAISED);
} else {
selEndX = xBound;
}
}
/*
* Draw a special background for the insertion cursor, overriding
* even the selection background. As a special workaround to keep the
* cursor visible on mono displays, write background in the cursor
* area (instead of nothing) when the cursor isn't on. Otherwise
* the selection would hide the cursor.
*/
if ((entryPtr->cursorPos >= entryPtr->leftIndex)
&& (entryPtr->state == tkNormalUid)
&& (entryPtr->flags & GOT_FOCUS)) {
(void) TkMeasureChars(entryPtr->fontPtr,
entryPtr->string + entryPtr->leftIndex,
entryPtr->cursorPos - entryPtr->leftIndex, startX,
xBound, TK_PARTIAL_OK|TK_NEWLINES_NOT_SPECIAL, &cursorX);
if (cursorX < xBound) {
if (entryPtr->flags & CURSOR_ON) {
Tk_Fill3DRectangle(Tk_Display(tkwin), pixmap,
entryPtr->cursorBorder,
cursorX - (entryPtr->cursorWidth)/2,
baseY - entryPtr->fontPtr->ascent,
entryPtr->cursorWidth,
entryPtr->fontPtr->ascent + entryPtr->fontPtr->descent,
entryPtr->cursorBorderWidth, TK_RELIEF_RAISED);
} else if (Tk_DefaultDepth(Tk_Screen(tkwin)) == 1) {
Tk_Fill3DRectangle(Tk_Display(tkwin), pixmap,
entryPtr->normalBorder,
cursorX - (entryPtr->cursorWidth)/2,
baseY - entryPtr->fontPtr->ascent,
entryPtr->cursorWidth,
entryPtr->fontPtr->ascent + entryPtr->fontPtr->descent,
0, TK_RELIEF_FLAT);
}
}
}
/*
* Draw the text in three pieces: first the piece to the left of
* the selection, then the selection, then the piece to the right
* of the selection.
*/
if (entryPtr->selectLast < entryPtr->leftIndex) {
TkDisplayChars(Tk_Display(tkwin), pixmap, entryPtr->textGC,
entryPtr->fontPtr, entryPtr->string + entryPtr->leftIndex,
entryPtr->numChars - entryPtr->leftIndex, startX, baseY,
TK_NEWLINES_NOT_SPECIAL);
} else {
count = entryPtr->selectFirst - entryPtr->leftIndex;
if (count > 0) {
TkDisplayChars(Tk_Display(tkwin), pixmap, entryPtr->textGC,
entryPtr->fontPtr, entryPtr->string + entryPtr->leftIndex,
count, startX, baseY, TK_NEWLINES_NOT_SPECIAL);
index = entryPtr->selectFirst;
} else {
index = entryPtr->leftIndex;
}
count = entryPtr->selectLast + 1 - index;
if ((selStartX < xBound) && (count > 0)) {
TkDisplayChars(Tk_Display(tkwin), pixmap, entryPtr->selTextGC,
entryPtr->fontPtr, entryPtr->string + index, count,
selStartX, baseY, TK_NEWLINES_NOT_SPECIAL);
}
count = entryPtr->numChars - entryPtr->selectLast - 1;
if ((selEndX < xBound) && (count > 0)) {
TkDisplayChars(Tk_Display(tkwin), pixmap, entryPtr->textGC,
entryPtr->fontPtr,
entryPtr->string + entryPtr->selectLast + 1,
count, selEndX, baseY, TK_NEWLINES_NOT_SPECIAL);
}
}
/*
* Draw the border last, so it will overwrite any text that extends
* past the viewable part of the window.
*/
if (entryPtr->relief != TK_RELIEF_FLAT) {
Tk_Draw3DRectangle(Tk_Display(tkwin), pixmap,
entryPtr->normalBorder, 0, 0, Tk_Width(tkwin),
Tk_Height(tkwin), entryPtr->borderWidth,
entryPtr->relief);
}
/*
* Everything's been redisplayed; now copy the pixmap onto the screen
* and free up the pixmap.
*/
XCopyArea(Tk_Display(tkwin), pixmap, Tk_WindowId(tkwin), entryPtr->textGC,
0, 0, Tk_Width(tkwin), Tk_Height(tkwin), 0, 0);
XFreePixmap(Tk_Display(tkwin), pixmap);
entryPtr->flags &= ~BORDER_NEEDED;
}
/*
*----------------------------------------------------------------------
*
* InsertChars --
*
* Add new characters to an entry widget.
*
* Results:
* None.
*
* Side effects:
* New information gets added to entryPtr; it will be redisplayed
* soon, but not necessarily immediately.
*
*----------------------------------------------------------------------
*/
static void
InsertChars(entryPtr, index, string)
register Entry *entryPtr; /* Entry that is to get the new
* elements. */
int index; /* Add the new elements before this
* element. */
char *string; /* New characters to add (NULL-terminated
* string). */
{
int length;
char *new;
length = strlen(string);
if (length == 0) {
return;
}
new = (char *) ckalloc((unsigned) (entryPtr->numChars + length + 1));
strncpy(new, entryPtr->string, index);
strcpy(new+index, string);
strcpy(new+index+length, entryPtr->string+index);
ckfree(entryPtr->string);
entryPtr->string = new;
entryPtr->numChars += length;
/*
* Inserting characters invalidates all indexes into the string.
* Touch up the indexes so that they still refer to the same
* characters (at new positions).
*/
if (entryPtr->selectFirst >= index) {
entryPtr->selectFirst += length;
}
if (entryPtr->selectLast >= index) {
entryPtr->selectLast += length;
}
if (entryPtr->selectAnchor >= index) {
entryPtr->selectAnchor += length;
}
if (entryPtr->leftIndex > index) {
entryPtr->leftIndex += length;
}
if (entryPtr->cursorPos >= index) {
entryPtr->cursorPos += length;
}
if (entryPtr->textVarName != NULL) {
Tcl_SetVar(entryPtr->interp, entryPtr->textVarName, entryPtr->string,
TCL_GLOBAL_ONLY);
}
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* DeleteChars --
*
* Remove one or more characters from an entry widget.
*
* Results:
* None.
*
* Side effects:
* Memory gets freed, the entry gets modified and (eventually)
* redisplayed.
*
*----------------------------------------------------------------------
*/
static void
DeleteChars(entryPtr, index, count)
register Entry *entryPtr; /* Entry widget to modify. */
int index; /* Index of first character to delete. */
int count; /* How many characters to delete. */
{
char *new;
if ((index + count) > entryPtr->numChars) {
count = entryPtr->numChars - index;
}
if (count <= 0) {
return;
}
new = (char *) ckalloc((unsigned) (entryPtr->numChars + 1 - count));
strncpy(new, entryPtr->string, index);
strcpy(new+index, entryPtr->string+index+count);
ckfree(entryPtr->string);
entryPtr->string = new;
entryPtr->numChars -= count;
/*
* Deleting characters results in the remaining characters being
* renumbered. Update the various indexes into the string to reflect
* this change.
*/
if (entryPtr->selectFirst >= index) {
if (entryPtr->selectFirst >= (index+count)) {
entryPtr->selectFirst -= count;
} else {
entryPtr->selectFirst = index;
}
}
if (entryPtr->selectLast >= index) {
if (entryPtr->selectLast >= (index+count)) {
entryPtr->selectLast -= count;
} else {
entryPtr->selectLast = index-1;
}
}
if (entryPtr->selectLast < entryPtr->selectFirst) {
entryPtr->selectFirst = entryPtr->selectLast = -1;
}
if (entryPtr->selectAnchor >= index) {
if (entryPtr->selectAnchor >= (index+count)) {
entryPtr->selectAnchor -= count;
} else {
entryPtr->selectAnchor = index;
}
}
if (entryPtr->leftIndex > index) {
if (entryPtr->leftIndex >= (index+count)) {
entryPtr->leftIndex -= count;
} else {
entryPtr->leftIndex = index;
}
}
if (entryPtr->cursorPos >= index) {
if (entryPtr->cursorPos >= (index+count)) {
entryPtr->cursorPos -= count;
} else {
entryPtr->cursorPos = index;
}
}
if (entryPtr->textVarName != NULL) {
Tcl_SetVar(entryPtr->interp, entryPtr->textVarName, entryPtr->string,
TCL_GLOBAL_ONLY);
}
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* EntrySetValue --
*
* Replace the contents of a text entry with a given value. This
* procedure is invoked when updating the entry from the entry's
* associated variable.
*
* Results:
* None.
*
* Side effects:
* The string displayed in the entry will change. Any selection
* in the entry is lost and the insertion point gets set to the
* end of the entry. Note: this procedure does *not* update the
* entry's associated variable, since that could result in an
* infinite loop.
*
*----------------------------------------------------------------------
*/
static void
EntrySetValue(entryPtr, value)
register Entry *entryPtr; /* Entry whose value is to be
* changed. */
char *value; /* New text to display in entry. */
{
ckfree(entryPtr->string);
entryPtr->numChars = strlen(value);
entryPtr->string = (char *) ckalloc((unsigned) (entryPtr->numChars + 1));
strcpy(entryPtr->string, value);
entryPtr->selectFirst = entryPtr->selectLast = -1;
entryPtr->leftIndex = 0;
entryPtr->cursorPos = entryPtr->numChars;
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
}
/*
*--------------------------------------------------------------
*
* EntryEventProc --
*
* This procedure is invoked by the Tk dispatcher for various
* events on entryes.
*
* Results:
* None.
*
* Side effects:
* When the window gets deleted, internal structures get
* cleaned up. When it gets exposed, it is redisplayed.
*
*--------------------------------------------------------------
*/
static void
EntryEventProc(clientData, eventPtr)
ClientData clientData; /* Information about window. */
XEvent *eventPtr; /* Information about event. */
{
Entry *entryPtr = (Entry *) clientData;
if (eventPtr->type == Expose) {
EventuallyRedraw(entryPtr);
entryPtr->flags |= BORDER_NEEDED;
} else if (eventPtr->type == DestroyNotify) {
Tcl_DeleteCommand(entryPtr->interp, Tk_PathName(entryPtr->tkwin));
entryPtr->tkwin = NULL;
if (entryPtr->flags & REDRAW_PENDING) {
Tk_CancelIdleCall(DisplayEntry, (ClientData) entryPtr);
}
Tk_EventuallyFree((ClientData) entryPtr, DestroyEntry);
} else if (eventPtr->type == ConfigureNotify) {
Tk_Preserve((ClientData) entryPtr);
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
Tk_Release((ClientData) entryPtr);
}
}
/*
*--------------------------------------------------------------
*
* GetEntryIndex --
*
* Parse an index into an entry and return either its value
* or an error.
*
* Results:
* A standard Tcl result. If all went well, then *indexPtr is
* filled in with the index (into entryPtr) corresponding to
* string. The index value is guaranteed to lie between 0 and
* the number of characters in the string, inclusive. If an
* error occurs then an error message is left in interp->result.
*
* Side effects:
* None.
*
*--------------------------------------------------------------
*/
static int
GetEntryIndex(interp, entryPtr, string, indexPtr)
Tcl_Interp *interp; /* For error messages. */
Entry *entryPtr; /* Entry for which the index is being
* specified. */
char *string; /* Specifies character in entryPtr. */
int *indexPtr; /* Where to store converted index. */
{
int length;
length = strlen(string);
if (string[0] == 'e') {
if (strncmp(string, "end", length) == 0) {
*indexPtr = entryPtr->numChars;
} else {
badIndex:
/*
* Some of the paths here leave messages in interp->result,
* so we have to clear it out before storing our own message.
*/
Tcl_SetResult(interp, (char *) NULL, TCL_STATIC);
Tcl_AppendResult(interp, "bad entry index \"", string,
"\"", (char *) NULL);
return TCL_ERROR;
}
} else if (string[0] == 'c') {
if (strncmp(string, "cursor", length) == 0) {
*indexPtr = entryPtr->cursorPos;
} else {
goto badIndex;
}
} else if (string[0] == 's') {
if (entryPtr->selectFirst == -1) {
interp->result = "selection isn't in entry";
return TCL_ERROR;
}
if (length < 5) {
goto badIndex;
}
if (strncmp(string, "sel.first", length) == 0) {
*indexPtr = entryPtr->selectFirst;
} else if (strncmp(string, "sel.last", length) == 0) {
*indexPtr = entryPtr->selectLast;
} else {
goto badIndex;
}
} else if (string[0] == '@') {
int x, dummy;
if (Tcl_GetInt(interp, string+1, &x) != TCL_OK) {
goto badIndex;
}
if (entryPtr->numChars == 0) {
*indexPtr = 0;
} else {
*indexPtr = entryPtr->leftIndex + TkMeasureChars(entryPtr->fontPtr,
entryPtr->string + entryPtr->leftIndex,
entryPtr->numChars - entryPtr->leftIndex,
entryPtr->offset, x, TK_NEWLINES_NOT_SPECIAL, &dummy);
}
} else {
if (Tcl_GetInt(interp, string, indexPtr) != TCL_OK) {
goto badIndex;
}
if (*indexPtr < 0){
*indexPtr = 0;
} else if (*indexPtr > entryPtr->numChars) {
*indexPtr = entryPtr->numChars;
}
}
return TCL_OK;
}
/*
*----------------------------------------------------------------------
*
* EntryScanTo --
*
* Given a y-coordinate (presumably of the curent mouse location)
* drag the view in the window to implement the scan operation.
*
* Results:
* None.
*
* Side effects:
* The view in the window may change.
*
*----------------------------------------------------------------------
*/
static void
EntryScanTo(entryPtr, x)
register Entry *entryPtr; /* Information about widget. */
int x; /* X-coordinate to use for scan
* operation. */
{
int newLeftIndex;
/*
* Compute new leftIndex for entry by amplifying the difference
* between the current position and the place where the scan
* started (the "mark" position). If we run off the left or right
* side of the entry, then reset the mark point so that the current
* position continues to correspond to the edge of the window.
* This means that the picture will start dragging as soon as the
* mouse reverses direction (without this reset, might have to slide
* mouse a long ways back before the picture starts moving again).
*/
newLeftIndex = entryPtr->scanMarkIndex
- (10*(x - entryPtr->scanMarkX))/entryPtr->avgWidth;
if (newLeftIndex >= entryPtr->numChars) {
newLeftIndex = entryPtr->scanMarkIndex = entryPtr->numChars-1;
entryPtr->scanMarkX = x;
}
if (newLeftIndex < 0) {
newLeftIndex = entryPtr->scanMarkIndex = 0;
entryPtr->scanMarkX = x;
}
if (newLeftIndex != entryPtr->leftIndex) {
entryPtr->leftIndex = newLeftIndex;
EventuallyRedraw(entryPtr);
EntryUpdateScrollbar(entryPtr);
}
}
/*
*----------------------------------------------------------------------
*
* EntrySelectTo --
*
* Modify the selection by moving its un-anchored end. This could
* make the selection either larger or smaller.
*
* Results:
* None.
*
* Side effects:
* The selection changes.
*
*----------------------------------------------------------------------
*/
static void
EntrySelectTo(entryPtr, index)
register Entry *entryPtr; /* Information about widget. */
int index; /* Index of element that is to
* become the "other" end of the
* selection. */
{
int newFirst, newLast;
/*
* Grab the selection if we don't own it already.
*/
if ((entryPtr->selectFirst == -1) && (entryPtr->exportSelection)) {
Tk_OwnSelection(entryPtr->tkwin, EntryLostSelection,
(ClientData) entryPtr);
}
if (index < 0) {
index = 0;
}
if (index >= entryPtr->numChars) {
index = entryPtr->numChars-1;
}
if (entryPtr->selectAnchor > entryPtr->numChars) {
entryPtr->selectAnchor = entryPtr->numChars;
}
if (entryPtr->selectAnchor <= index) {
newFirst = entryPtr->selectAnchor;
newLast = index;
} else {
newFirst = index;
newLast = entryPtr->selectAnchor - 1;
if (newLast < 0) {
newFirst = newLast = -1;
}
}
if ((entryPtr->selectFirst == newFirst)
&& (entryPtr->selectLast == newLast)) {
return;
}
entryPtr->selectFirst = newFirst;
entryPtr->selectLast = newLast;
EventuallyRedraw(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* EntryFetchSelection --
*
* This procedure is called back by Tk when the selection is
* requested by someone. It returns part or all of the selection
* in a buffer provided by the caller.
*
* Results:
* The return value is the number of non-NULL bytes stored
* at buffer. Buffer is filled (or partially filled) with a
* NULL-terminated string containing part or all of the selection,
* as given by offset and maxBytes.
*
* Side effects:
* None.
*
*----------------------------------------------------------------------
*/
static int
EntryFetchSelection(clientData, offset, buffer, maxBytes)
ClientData clientData; /* Information about entry widget. */
int offset; /* Offset within selection of first
* character to be returned. */
char *buffer; /* Location in which to place
* selection. */
int maxBytes; /* Maximum number of bytes to place
* at buffer, not including terminating
* NULL character. */
{
Entry *entryPtr = (Entry *) clientData;
int count;
if ((entryPtr->selectFirst < 0) || !(entryPtr->exportSelection)) {
return -1;
}
count = entryPtr->selectLast + 1 - entryPtr->selectFirst - offset;
if (count > maxBytes) {
count = maxBytes;
}
if (count <= 0) {
return 0;
}
strncpy(buffer, entryPtr->string + entryPtr->selectFirst + offset, count);
buffer[count] = '\0';
return count;
}
/*
*----------------------------------------------------------------------
*
* EntryLostSelection --
*
* This procedure is called back by Tk when the selection is
* grabbed away from an entry widget.
*
* Results:
* None.
*
* Side effects:
* The existing selection is unhighlighted, and the window is
* marked as not containing a selection.
*
*----------------------------------------------------------------------
*/
static void
EntryLostSelection(clientData)
ClientData clientData; /* Information about entry widget. */
{
Entry *entryPtr = (Entry *) clientData;
if ((entryPtr->selectFirst != -1) && entryPtr->exportSelection) {
entryPtr->selectFirst = -1;
entryPtr->selectLast = -1;
EventuallyRedraw(entryPtr);
}
}
/*
*----------------------------------------------------------------------
*
* EventuallyRedraw --
*
* Ensure that an entry is eventually redrawn on the display.
*
* Results:
* None.
*
* Side effects:
* Information gets redisplayed. Right now we don't do selective
* redisplays: the whole window will be redrawn. This doesn't
* seem to hurt performance noticeably, but if it does then this
* could be changed.
*
*----------------------------------------------------------------------
*/
static void
EventuallyRedraw(entryPtr)
register Entry *entryPtr; /* Information about widget. */
{
if ((entryPtr->tkwin == NULL) || !Tk_IsMapped(entryPtr->tkwin)) {
return;
}
/*
* Right now we don't do selective redisplays: the whole window
* will be redrawn. This doesn't seem to hurt performance noticeably,
* but if it does then this could be changed.
*/
if (!(entryPtr->flags & REDRAW_PENDING)) {
entryPtr->flags |= REDRAW_PENDING;
Tk_DoWhenIdle(DisplayEntry, (ClientData) entryPtr);
}
}
/*
*----------------------------------------------------------------------
*
* EntryUpdateScrollbar --
*
* This procedure is invoked whenever information has changed in
* an entry in a way that would invalidate a scrollbar display.
* If there is an associated scrollbar, then this command updates
* it by invoking a Tcl command.
*
* Results:
* None.
*
* Side effects:
* A Tcl command is invoked, and an additional command may be
* invoked to process errors in the command.
*
*----------------------------------------------------------------------
*/
static void
EntryUpdateScrollbar(entryPtr)
register Entry *entryPtr; /* Information about widget. */
{
char args[100];
int result, last, charsInWindow, endX;
if (entryPtr->scrollCmd == NULL) {
return;
}
/*
* The most painful part here is guessing how many characters
* actually fit in the window. This is only an estimate in the
* case where the window isn't completely filled with characters.
*/
charsInWindow = TkMeasureChars(entryPtr->fontPtr,
entryPtr->string + entryPtr->leftIndex,
entryPtr->numChars - entryPtr->leftIndex, entryPtr->offset,
Tk_Width(entryPtr->tkwin),
TK_AT_LEAST_ONE|TK_NEWLINES_NOT_SPECIAL, &endX);
if (charsInWindow == 0) {
last = entryPtr->leftIndex;
} else {
last = entryPtr->leftIndex + charsInWindow - 1;
}
if (endX < Tk_Width(entryPtr->tkwin)) {
charsInWindow += (Tk_Width(entryPtr->tkwin) - endX)/entryPtr->avgWidth;
}
sprintf(args, " %d %d %d %d", entryPtr->numChars, charsInWindow,
entryPtr->leftIndex, last);
result = Tcl_VarEval(entryPtr->interp, entryPtr->scrollCmd, args,
(char *) NULL);
if (result != TCL_OK) {
TkBindError(entryPtr->interp);
}
Tcl_SetResult(entryPtr->interp, (char *) NULL, TCL_STATIC);
}
/*
*----------------------------------------------------------------------
*
* EntryBlinkProc --
*
* This procedure is called as a timer handler to blink the
* insertion cursor off and on.
*
* Results:
* None.
*
* Side effects:
* The cursor gets turned on or off, redisplay gets invoked,
* and this procedure reschedules itself.
*
*----------------------------------------------------------------------
*/
static void
EntryBlinkProc(clientData)
ClientData clientData; /* Pointer to record describing entry. */
{
register Entry *entryPtr = (Entry *) clientData;
if (!(entryPtr->flags & GOT_FOCUS) || (entryPtr->cursorOffTime == 0)) {
return;
}
if (entryPtr->flags & CURSOR_ON) {
entryPtr->flags &= ~CURSOR_ON;
entryPtr->cursorBlinkHandler = Tk_CreateTimerHandler(
entryPtr->cursorOffTime, EntryBlinkProc, (ClientData) entryPtr);
} else {
entryPtr->flags |= CURSOR_ON;
entryPtr->cursorBlinkHandler = Tk_CreateTimerHandler(
entryPtr->cursorOnTime, EntryBlinkProc, (ClientData) entryPtr);
}
EventuallyRedraw(entryPtr);
}
/*
*----------------------------------------------------------------------
*
* EntryFocusProc --
*
* This procedure is called whenever the entry gets or loses the
* input focus. It's also called whenever the window is reconfigured
* while it has the focus.
*
* Results:
* None.
*
* Side effects:
* The cursor gets turned on or off.
*
*----------------------------------------------------------------------
*/
static void
EntryFocusProc(clientData, gotFocus)
ClientData clientData; /* Pointer to structure describing entry. */
int gotFocus; /* 1 means window is getting focus, 0 means
* it's losing it. */
{
register Entry *entryPtr = (Entry *) clientData;
if (entryPtr->cursorBlinkHandler != NULL) {
Tk_DeleteTimerHandler(entryPtr->cursorBlinkHandler);
entryPtr->cursorBlinkHandler = NULL;
}
if (gotFocus) {
entryPtr->flags |= GOT_FOCUS | CURSOR_ON;
if (entryPtr->cursorOffTime != 0) {
entryPtr->cursorBlinkHandler = Tk_CreateTimerHandler(
entryPtr->cursorOnTime, EntryBlinkProc,
(ClientData) entryPtr);
}
} else {
entryPtr->flags &= ~(GOT_FOCUS | CURSOR_ON);
entryPtr->cursorBlinkHandler = (Tk_TimerToken) NULL;
}
EventuallyRedraw(entryPtr);
}
/*
*--------------------------------------------------------------
*
* EntryTextVarProc --
*
* This procedure is invoked when someone changes the variable
* whose contents are to be displayed in an entry.
*
* Results:
* NULL is always returned.
*
* Side effects:
* The text displayed in the entry will change to match the
* variable.
*
*--------------------------------------------------------------
*/
/* ARGSUSED */
static char *
EntryTextVarProc(clientData, interp, name1, name2, flags)
ClientData clientData; /* Information about button. */
Tcl_Interp *interp; /* Interpreter containing variable. */
char *name1; /* Name of variable. */
char *name2; /* Second part of variable name. */
int flags; /* Information about what happened. */
{
register Entry *entryPtr = (Entry *) clientData;
char *value;
/*
* If the variable is unset, then immediately recreate it unless
* the whole interpreter is going away.
*/
if (flags & TCL_TRACE_UNSETS) {
if ((flags & TCL_TRACE_DESTROYED) && !(flags & TCL_INTERP_DESTROYED)) {
Tcl_SetVar2(interp, name1, name2, entryPtr->string,
flags & TCL_GLOBAL_ONLY);
Tcl_TraceVar2(interp, name1, name2,
TCL_GLOBAL_ONLY|TCL_TRACE_WRITES|TCL_TRACE_UNSETS,
EntryTextVarProc, clientData);
}
return (char *) NULL;
}
/*
* Update the entry's text with the value of the variable, unless
* the entry already has that value (this happens when the variable
* changes value because we changed it because someone typed in
* the entry).
*/
value = Tcl_GetVar2(interp, name1, name2, flags & TCL_GLOBAL_ONLY);
if (value == NULL) {
value = "";
}
if (strcmp(value, entryPtr->string) != 0) {
EntrySetValue(entryPtr, value);
}
return (char *) NULL;
}
| gpl-3.0 |
LloydMoore/RPi-Dev | BotPsoc/BotPsoc.cydsn/Generated_Source/PSoC5/PiSPI_MISO.c | 2 | 4222 | /*******************************************************************************
* File Name: PiSPI_MISO.c
* Version 1.90
*
* Description:
* This file contains API to enable firmware control of a Pins component.
*
* Note:
*
********************************************************************************
* Copyright 2008-2012, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/
#include "cytypes.h"
#include "PiSPI_MISO.h"
/* APIs are not generated for P15[7:6] on PSoC 5 */
#if !(CY_PSOC5A &&\
PiSPI_MISO__PORT == 15 && ((PiSPI_MISO__MASK & 0xC0) != 0))
/*******************************************************************************
* Function Name: PiSPI_MISO_Write
********************************************************************************
*
* Summary:
* Assign a new value to the digital port's data output register.
*
* Parameters:
* prtValue: The value to be assigned to the Digital Port.
*
* Return:
* None
*
*******************************************************************************/
void PiSPI_MISO_Write(uint8 value)
{
uint8 staticBits = (PiSPI_MISO_DR & (uint8)(~PiSPI_MISO_MASK));
PiSPI_MISO_DR = staticBits | ((uint8)(value << PiSPI_MISO_SHIFT) & PiSPI_MISO_MASK);
}
/*******************************************************************************
* Function Name: PiSPI_MISO_SetDriveMode
********************************************************************************
*
* Summary:
* Change the drive mode on the pins of the port.
*
* Parameters:
* mode: Change the pins to this drive mode.
*
* Return:
* None
*
*******************************************************************************/
void PiSPI_MISO_SetDriveMode(uint8 mode)
{
CyPins_SetPinDriveMode(PiSPI_MISO_0, mode);
}
/*******************************************************************************
* Function Name: PiSPI_MISO_Read
********************************************************************************
*
* Summary:
* Read the current value on the pins of the Digital Port in right justified
* form.
*
* Parameters:
* None
*
* Return:
* Returns the current value of the Digital Port as a right justified number
*
* Note:
* Macro PiSPI_MISO_ReadPS calls this function.
*
*******************************************************************************/
uint8 PiSPI_MISO_Read(void)
{
return (PiSPI_MISO_PS & PiSPI_MISO_MASK) >> PiSPI_MISO_SHIFT;
}
/*******************************************************************************
* Function Name: PiSPI_MISO_ReadDataReg
********************************************************************************
*
* Summary:
* Read the current value assigned to a Digital Port's data output register
*
* Parameters:
* None
*
* Return:
* Returns the current value assigned to the Digital Port's data output register
*
*******************************************************************************/
uint8 PiSPI_MISO_ReadDataReg(void)
{
return (PiSPI_MISO_DR & PiSPI_MISO_MASK) >> PiSPI_MISO_SHIFT;
}
/* If Interrupts Are Enabled for this Pins component */
#if defined(PiSPI_MISO_INTSTAT)
/*******************************************************************************
* Function Name: PiSPI_MISO_ClearInterrupt
********************************************************************************
* Summary:
* Clears any active interrupts attached to port and returns the value of the
* interrupt status register.
*
* Parameters:
* None
*
* Return:
* Returns the value of the interrupt status register
*
*******************************************************************************/
uint8 PiSPI_MISO_ClearInterrupt(void)
{
return (PiSPI_MISO_INTSTAT & PiSPI_MISO_MASK) >> PiSPI_MISO_SHIFT;
}
#endif /* If Interrupts Are Enabled for this Pins component */
#endif /* CY_PSOC5A... */
/* [] END OF FILE */
| gpl-3.0 |
qbism/li2mod | l_gslog.c | 2 | 3450 | /*============================================================================
This file is part of Lithium II Mod for Quake II
Copyright (C) 1997, 1998, 1999, 2010 Matthew A. Ayres
Lithium II Mod 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.
Lithium II Mod 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 Lithium II Mod. If not, see <http://www.gnu.org/licenses/>.
Quake II is a trademark of Id Software, Inc.
Code by Matt "WhiteFang" Ayres, matt@lithium.com
============================================================================*/
#include "g_local.h"
FILE *gslog_file = NULL;
lvar_t *use_gslog;
lvar_t *gslog;
lvar_t *gslog_flush;
void GSLog(char *format, ...) {
va_list argptr;
char buf[256];
if(!gslog_file)
return;
va_start(argptr, format);
vsnprintf(buf, sizeof(buf), format, argptr);
va_end(argptr);
#ifdef WIN32
strlcat(buf, "\n", sizeof(buf));
#else
strlcat(buf, "\r\n", sizeof(buf));
#endif
fprintf(gslog_file, "%s", buf);
if(gslog_flush->value)
fflush(gslog_file);
}
void GSLog_InitGame(void) {
use_gslog = lvar("use_gslog", "0", "^", VAR_USE);
gslog = lvar("gslog", "gslog.log", "str", VAR_NONE);
gslog_flush = lvar("gslog_flush", "0", "^", VAR_OTHER);
}
#include "time.h"
char *monthname[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
void GSLog_InitLevel(void) {
time_t t;
struct tm *tm;
if(!use_gslog->value)
return;
gslog_file = fopen(file_gamedir(gslog->string), "at");
GSLog("\t\tStdLog\t1.2");
GSLog("\t\tPatchName\tLithium II");
time(&t);
tm = localtime(&t);
GSLog("\t\tLogDate\t%d %s %04d", tm->tm_mday, monthname[MIN(MAX(tm->tm_mon, 0), 12)], 1900 + tm->tm_year);
GSLog("\t\tLogTime\t%02d:%02d:%02d", tm->tm_hour, tm->tm_min, tm->tm_sec);
GSLog("\t\tLogDeathFlags\t%d", (int)dmflags->value);
GSLog("\t\tMap\t%s", level.level_name);
GSLog("\t\tGameStart\t\t\t%d", (int)level.time);
}
void GSLog_ExitLevel(void) {
if(!gslog_file)
return;
GSLog("\t\tGameEnd\t\t\t%d", (int)level.time);
fclose(gslog_file);
gslog_file = NULL;
}
void GSLog_Shutdown(void) {
GSLog_ExitLevel();
}
void GSLog_ClientBegin(edict_t *ent) {
GSLog("\t\tPlayerConnect\t%s\t\t%d", ent->client->pers.netname, (int)level.time);
}
void GSLog_ClientDisconnect(edict_t *ent) {
if(ent->client)
GSLog("\t\tPlayerLeft\t%s\t\t%d", ent->client->pers.netname, (int)level.time);
}
void GSLog_PlayerRename(char *oldname, char *newname) {
if(!strcmp(oldname, newname) || !strlen(oldname))
return;
GSLog("\t\tPlayerRename\t%s\t%s\t%d", oldname, newname, (int)level.time);
}
void GSLog_Score(char *attacker, char *target, char *type, char *weapon, int score, int time, int ping) {
GSLog("%s\t%s\t%s\t%s\t%d\t%d\t%d", attacker, target, type, weapon, score, time, ping);
}
void GSLog_Bonus(edict_t *ent, char *type, int score) {
GSLog_Score(ent->client->pers.netname, "", type, "", score, (int)level.time, ent->client->ping);
}
| gpl-3.0 |
sabel83/metashell | 3rd/templight/clang/lib/Parse/ParseStmt.cpp | 2 | 89426 | //===--- ParseStmt.cpp - Statement and Block Parser -----------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file implements the Statement and Block portions of the Parser
// interface.
//
//===----------------------------------------------------------------------===//
#include "clang/AST/PrettyDeclStackTrace.h"
#include "clang/Basic/Attributes.h"
#include "clang/Basic/PrettyStackTrace.h"
#include "clang/Parse/LoopHint.h"
#include "clang/Parse/Parser.h"
#include "clang/Parse/RAIIObjectsForParser.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/TypoCorrection.h"
using namespace clang;
//===----------------------------------------------------------------------===//
// C99 6.8: Statements and Blocks.
//===----------------------------------------------------------------------===//
/// Parse a standalone statement (for instance, as the body of an 'if',
/// 'while', or 'for').
StmtResult Parser::ParseStatement(SourceLocation *TrailingElseLoc,
ParsedStmtContext StmtCtx) {
StmtResult Res;
// We may get back a null statement if we found a #pragma. Keep going until
// we get an actual statement.
do {
StmtVector Stmts;
Res = ParseStatementOrDeclaration(Stmts, StmtCtx, TrailingElseLoc);
} while (!Res.isInvalid() && !Res.get());
return Res;
}
/// ParseStatementOrDeclaration - Read 'statement' or 'declaration'.
/// StatementOrDeclaration:
/// statement
/// declaration
///
/// statement:
/// labeled-statement
/// compound-statement
/// expression-statement
/// selection-statement
/// iteration-statement
/// jump-statement
/// [C++] declaration-statement
/// [C++] try-block
/// [MS] seh-try-block
/// [OBC] objc-throw-statement
/// [OBC] objc-try-catch-statement
/// [OBC] objc-synchronized-statement
/// [GNU] asm-statement
/// [OMP] openmp-construct [TODO]
///
/// labeled-statement:
/// identifier ':' statement
/// 'case' constant-expression ':' statement
/// 'default' ':' statement
///
/// selection-statement:
/// if-statement
/// switch-statement
///
/// iteration-statement:
/// while-statement
/// do-statement
/// for-statement
///
/// expression-statement:
/// expression[opt] ';'
///
/// jump-statement:
/// 'goto' identifier ';'
/// 'continue' ';'
/// 'break' ';'
/// 'return' expression[opt] ';'
/// [GNU] 'goto' '*' expression ';'
///
/// [OBC] objc-throw-statement:
/// [OBC] '@' 'throw' expression ';'
/// [OBC] '@' 'throw' ';'
///
StmtResult
Parser::ParseStatementOrDeclaration(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc) {
ParenBraceBracketBalancer BalancerRAIIObj(*this);
ParsedAttributesWithRange Attrs(AttrFactory);
MaybeParseCXX11Attributes(Attrs, nullptr, /*MightBeObjCMessageSend*/ true);
if (!MaybeParseOpenCLUnrollHintAttribute(Attrs))
return StmtError();
StmtResult Res = ParseStatementOrDeclarationAfterAttributes(
Stmts, StmtCtx, TrailingElseLoc, Attrs);
MaybeDestroyTemplateIds();
assert((Attrs.empty() || Res.isInvalid() || Res.isUsable()) &&
"attributes on empty statement");
if (Attrs.empty() || Res.isInvalid())
return Res;
return Actions.ProcessStmtAttributes(Res.get(), Attrs, Attrs.Range);
}
namespace {
class StatementFilterCCC final : public CorrectionCandidateCallback {
public:
StatementFilterCCC(Token nextTok) : NextToken(nextTok) {
WantTypeSpecifiers = nextTok.isOneOf(tok::l_paren, tok::less, tok::l_square,
tok::identifier, tok::star, tok::amp);
WantExpressionKeywords =
nextTok.isOneOf(tok::l_paren, tok::identifier, tok::arrow, tok::period);
WantRemainingKeywords =
nextTok.isOneOf(tok::l_paren, tok::semi, tok::identifier, tok::l_brace);
WantCXXNamedCasts = false;
}
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (FieldDecl *FD = candidate.getCorrectionDeclAs<FieldDecl>())
return !candidate.getCorrectionSpecifier() || isa<ObjCIvarDecl>(FD);
if (NextToken.is(tok::equal))
return candidate.getCorrectionDeclAs<VarDecl>();
if (NextToken.is(tok::period) &&
candidate.getCorrectionDeclAs<NamespaceDecl>())
return false;
return CorrectionCandidateCallback::ValidateCandidate(candidate);
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<StatementFilterCCC>(*this);
}
private:
Token NextToken;
};
}
StmtResult Parser::ParseStatementOrDeclarationAfterAttributes(
StmtVector &Stmts, ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc, ParsedAttributesWithRange &Attrs) {
const char *SemiError = nullptr;
StmtResult Res;
SourceLocation GNUAttributeLoc;
// Cases in this switch statement should fall through if the parser expects
// the token to end in a semicolon (in which case SemiError should be set),
// or they directly 'return;' if not.
Retry:
tok::TokenKind Kind = Tok.getKind();
SourceLocation AtLoc;
switch (Kind) {
case tok::at: // May be a @try or @throw statement
{
ProhibitAttributes(Attrs); // TODO: is it correct?
AtLoc = ConsumeToken(); // consume @
return ParseObjCAtStatement(AtLoc, StmtCtx);
}
case tok::code_completion:
Actions.CodeCompleteOrdinaryName(getCurScope(), Sema::PCC_Statement);
cutOffParsing();
return StmtError();
case tok::identifier: {
Token Next = NextToken();
if (Next.is(tok::colon)) { // C99 6.8.1: labeled-statement
// identifier ':' statement
return ParseLabeledStatement(Attrs, StmtCtx);
}
// Look up the identifier, and typo-correct it to a keyword if it's not
// found.
if (Next.isNot(tok::coloncolon)) {
// Try to limit which sets of keywords should be included in typo
// correction based on what the next token is.
StatementFilterCCC CCC(Next);
if (TryAnnotateName(&CCC) == ANK_Error) {
// Handle errors here by skipping up to the next semicolon or '}', and
// eat the semicolon if that's what stopped us.
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
return StmtError();
}
// If the identifier was typo-corrected, try again.
if (Tok.isNot(tok::identifier))
goto Retry;
}
// Fall through
LLVM_FALLTHROUGH;
}
default: {
if ((getLangOpts().CPlusPlus || getLangOpts().MicrosoftExt ||
(StmtCtx & ParsedStmtContext::AllowDeclarationsInC) !=
ParsedStmtContext()) &&
(GNUAttributeLoc.isValid() || isDeclarationStatement())) {
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
DeclGroupPtrTy Decl;
if (GNUAttributeLoc.isValid()) {
DeclStart = GNUAttributeLoc;
Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, Attrs,
&GNUAttributeLoc);
} else {
Decl = ParseDeclaration(DeclaratorContext::Block, DeclEnd, Attrs);
}
if (Attrs.Range.getBegin().isValid())
DeclStart = Attrs.Range.getBegin();
return Actions.ActOnDeclStmt(Decl, DeclStart, DeclEnd);
}
if (Tok.is(tok::r_brace)) {
Diag(Tok, diag::err_expected_statement);
return StmtError();
}
return ParseExprStatement(StmtCtx);
}
case tok::kw___attribute: {
GNUAttributeLoc = Tok.getLocation();
ParseGNUAttributes(Attrs);
goto Retry;
}
case tok::kw_case: // C99 6.8.1: labeled-statement
return ParseCaseStatement(StmtCtx);
case tok::kw_default: // C99 6.8.1: labeled-statement
return ParseDefaultStatement(StmtCtx);
case tok::l_brace: // C99 6.8.2: compound-statement
return ParseCompoundStatement();
case tok::semi: { // C99 6.8.3p3: expression[opt] ';'
bool HasLeadingEmptyMacro = Tok.hasLeadingEmptyMacro();
return Actions.ActOnNullStmt(ConsumeToken(), HasLeadingEmptyMacro);
}
case tok::kw_if: // C99 6.8.4.1: if-statement
return ParseIfStatement(TrailingElseLoc);
case tok::kw_switch: // C99 6.8.4.2: switch-statement
return ParseSwitchStatement(TrailingElseLoc);
case tok::kw_while: // C99 6.8.5.1: while-statement
return ParseWhileStatement(TrailingElseLoc);
case tok::kw_do: // C99 6.8.5.2: do-statement
Res = ParseDoStatement();
SemiError = "do/while";
break;
case tok::kw_for: // C99 6.8.5.3: for-statement
return ParseForStatement(TrailingElseLoc);
case tok::kw_goto: // C99 6.8.6.1: goto-statement
Res = ParseGotoStatement();
SemiError = "goto";
break;
case tok::kw_continue: // C99 6.8.6.2: continue-statement
Res = ParseContinueStatement();
SemiError = "continue";
break;
case tok::kw_break: // C99 6.8.6.3: break-statement
Res = ParseBreakStatement();
SemiError = "break";
break;
case tok::kw_return: // C99 6.8.6.4: return-statement
Res = ParseReturnStatement();
SemiError = "return";
break;
case tok::kw_co_return: // C++ Coroutines: co_return statement
Res = ParseReturnStatement();
SemiError = "co_return";
break;
case tok::kw_asm: {
ProhibitAttributes(Attrs);
bool msAsm = false;
Res = ParseAsmStatement(msAsm);
Res = Actions.ActOnFinishFullStmt(Res.get());
if (msAsm) return Res;
SemiError = "asm";
break;
}
case tok::kw___if_exists:
case tok::kw___if_not_exists:
ProhibitAttributes(Attrs);
ParseMicrosoftIfExistsStatement(Stmts);
// An __if_exists block is like a compound statement, but it doesn't create
// a new scope.
return StmtEmpty();
case tok::kw_try: // C++ 15: try-block
return ParseCXXTryBlock();
case tok::kw___try:
ProhibitAttributes(Attrs); // TODO: is it correct?
return ParseSEHTryBlock();
case tok::kw___leave:
Res = ParseSEHLeaveStatement();
SemiError = "__leave";
break;
case tok::annot_pragma_vis:
ProhibitAttributes(Attrs);
HandlePragmaVisibility();
return StmtEmpty();
case tok::annot_pragma_pack:
ProhibitAttributes(Attrs);
HandlePragmaPack();
return StmtEmpty();
case tok::annot_pragma_msstruct:
ProhibitAttributes(Attrs);
HandlePragmaMSStruct();
return StmtEmpty();
case tok::annot_pragma_align:
ProhibitAttributes(Attrs);
HandlePragmaAlign();
return StmtEmpty();
case tok::annot_pragma_weak:
ProhibitAttributes(Attrs);
HandlePragmaWeak();
return StmtEmpty();
case tok::annot_pragma_weakalias:
ProhibitAttributes(Attrs);
HandlePragmaWeakAlias();
return StmtEmpty();
case tok::annot_pragma_redefine_extname:
ProhibitAttributes(Attrs);
HandlePragmaRedefineExtname();
return StmtEmpty();
case tok::annot_pragma_fp_contract:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "fp_contract";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_fp:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "clang fp";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_fenv_access:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_stdc_fenv_access_scope);
ConsumeAnnotationToken();
return StmtEmpty();
case tok::annot_pragma_fenv_round:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "STDC FENV_ROUND";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_float_control:
ProhibitAttributes(Attrs);
Diag(Tok, diag::err_pragma_file_or_compound_scope) << "float_control";
ConsumeAnnotationToken();
return StmtError();
case tok::annot_pragma_opencl_extension:
ProhibitAttributes(Attrs);
HandlePragmaOpenCLExtension();
return StmtEmpty();
case tok::annot_pragma_captured:
ProhibitAttributes(Attrs);
return HandlePragmaCaptured();
case tok::annot_pragma_openmp:
ProhibitAttributes(Attrs);
return ParseOpenMPDeclarativeOrExecutableDirective(StmtCtx);
case tok::annot_pragma_ms_pointers_to_members:
ProhibitAttributes(Attrs);
HandlePragmaMSPointersToMembers();
return StmtEmpty();
case tok::annot_pragma_ms_pragma:
ProhibitAttributes(Attrs);
HandlePragmaMSPragma();
return StmtEmpty();
case tok::annot_pragma_ms_vtordisp:
ProhibitAttributes(Attrs);
HandlePragmaMSVtorDisp();
return StmtEmpty();
case tok::annot_pragma_loop_hint:
ProhibitAttributes(Attrs);
return ParsePragmaLoopHint(Stmts, StmtCtx, TrailingElseLoc, Attrs);
case tok::annot_pragma_dump:
HandlePragmaDump();
return StmtEmpty();
case tok::annot_pragma_attribute:
HandlePragmaAttribute();
return StmtEmpty();
}
// If we reached this code, the statement must end in a semicolon.
if (!TryConsumeToken(tok::semi) && !Res.isInvalid()) {
// If the result was valid, then we do want to diagnose this. Use
// ExpectAndConsume to emit the diagnostic, even though we know it won't
// succeed.
ExpectAndConsume(tok::semi, diag::err_expected_semi_after_stmt, SemiError);
// Skip until we see a } or ;, but don't eat it.
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
}
return Res;
}
/// Parse an expression statement.
StmtResult Parser::ParseExprStatement(ParsedStmtContext StmtCtx) {
// If a case keyword is missing, this is where it should be inserted.
Token OldToken = Tok;
ExprStatementTokLoc = Tok.getLocation();
// expression[opt] ';'
ExprResult Expr(ParseExpression());
if (Expr.isInvalid()) {
// If the expression is invalid, skip ahead to the next semicolon or '}'.
// Not doing this opens us up to the possibility of infinite loops if
// ParseExpression does not consume any tokens.
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
return Actions.ActOnExprStmtError();
}
if (Tok.is(tok::colon) && getCurScope()->isSwitchScope() &&
Actions.CheckCaseExpression(Expr.get())) {
// If a constant expression is followed by a colon inside a switch block,
// suggest a missing case keyword.
Diag(OldToken, diag::err_expected_case_before_expression)
<< FixItHint::CreateInsertion(OldToken.getLocation(), "case ");
// Recover parsing as a case statement.
return ParseCaseStatement(StmtCtx, /*MissingCase=*/true, Expr);
}
// Otherwise, eat the semicolon.
ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
return handleExprStmt(Expr, StmtCtx);
}
/// ParseSEHTryBlockCommon
///
/// seh-try-block:
/// '__try' compound-statement seh-handler
///
/// seh-handler:
/// seh-except-block
/// seh-finally-block
///
StmtResult Parser::ParseSEHTryBlock() {
assert(Tok.is(tok::kw___try) && "Expected '__try'");
SourceLocation TryLoc = ConsumeToken();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult TryBlock(ParseCompoundStatement(
/*isStmtExpr=*/false,
Scope::DeclScope | Scope::CompoundStmtScope | Scope::SEHTryScope));
if (TryBlock.isInvalid())
return TryBlock;
StmtResult Handler;
if (Tok.is(tok::identifier) &&
Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHExceptBlock(Loc);
} else if (Tok.is(tok::kw___finally)) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHFinallyBlock(Loc);
} else {
return StmtError(Diag(Tok, diag::err_seh_expected_handler));
}
if(Handler.isInvalid())
return Handler;
return Actions.ActOnSEHTryBlock(false /* IsCXXTry */,
TryLoc,
TryBlock.get(),
Handler.get());
}
/// ParseSEHExceptBlock - Handle __except
///
/// seh-except-block:
/// '__except' '(' seh-filter-expression ')' compound-statement
///
StmtResult Parser::ParseSEHExceptBlock(SourceLocation ExceptLoc) {
PoisonIdentifierRAIIObject raii(Ident__exception_code, false),
raii2(Ident___exception_code, false),
raii3(Ident_GetExceptionCode, false);
if (ExpectAndConsume(tok::l_paren))
return StmtError();
ParseScope ExpectScope(this, Scope::DeclScope | Scope::ControlScope |
Scope::SEHExceptScope);
if (getLangOpts().Borland) {
Ident__exception_info->setIsPoisoned(false);
Ident___exception_info->setIsPoisoned(false);
Ident_GetExceptionInfo->setIsPoisoned(false);
}
ExprResult FilterExpr;
{
ParseScopeFlags FilterScope(this, getCurScope()->getFlags() |
Scope::SEHFilterScope);
FilterExpr = Actions.CorrectDelayedTyposInExpr(ParseExpression());
}
if (getLangOpts().Borland) {
Ident__exception_info->setIsPoisoned(true);
Ident___exception_info->setIsPoisoned(true);
Ident_GetExceptionInfo->setIsPoisoned(true);
}
if(FilterExpr.isInvalid())
return StmtError();
if (ExpectAndConsume(tok::r_paren))
return StmtError();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult Block(ParseCompoundStatement());
if(Block.isInvalid())
return Block;
return Actions.ActOnSEHExceptBlock(ExceptLoc, FilterExpr.get(), Block.get());
}
/// ParseSEHFinallyBlock - Handle __finally
///
/// seh-finally-block:
/// '__finally' compound-statement
///
StmtResult Parser::ParseSEHFinallyBlock(SourceLocation FinallyLoc) {
PoisonIdentifierRAIIObject raii(Ident__abnormal_termination, false),
raii2(Ident___abnormal_termination, false),
raii3(Ident_AbnormalTermination, false);
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
ParseScope FinallyScope(this, 0);
Actions.ActOnStartSEHFinallyBlock();
StmtResult Block(ParseCompoundStatement());
if(Block.isInvalid()) {
Actions.ActOnAbortSEHFinallyBlock();
return Block;
}
return Actions.ActOnFinishSEHFinallyBlock(FinallyLoc, Block.get());
}
/// Handle __leave
///
/// seh-leave-statement:
/// '__leave' ';'
///
StmtResult Parser::ParseSEHLeaveStatement() {
SourceLocation LeaveLoc = ConsumeToken(); // eat the '__leave'.
return Actions.ActOnSEHLeaveStmt(LeaveLoc, getCurScope());
}
/// ParseLabeledStatement - We have an identifier and a ':' after it.
///
/// labeled-statement:
/// identifier ':' statement
/// [GNU] identifier ':' attributes[opt] statement
///
StmtResult Parser::ParseLabeledStatement(ParsedAttributesWithRange &attrs,
ParsedStmtContext StmtCtx) {
assert(Tok.is(tok::identifier) && Tok.getIdentifierInfo() &&
"Not an identifier!");
// The substatement is always a 'statement', not a 'declaration', but is
// otherwise in the same context as the labeled-statement.
StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
Token IdentTok = Tok; // Save the whole token.
ConsumeToken(); // eat the identifier.
assert(Tok.is(tok::colon) && "Not a label!");
// identifier ':' statement
SourceLocation ColonLoc = ConsumeToken();
// Read label attributes, if present.
StmtResult SubStmt;
if (Tok.is(tok::kw___attribute)) {
ParsedAttributesWithRange TempAttrs(AttrFactory);
ParseGNUAttributes(TempAttrs);
// In C++, GNU attributes only apply to the label if they are followed by a
// semicolon, to disambiguate label attributes from attributes on a labeled
// declaration.
//
// This doesn't quite match what GCC does; if the attribute list is empty
// and followed by a semicolon, GCC will reject (it appears to parse the
// attributes as part of a statement in that case). That looks like a bug.
if (!getLangOpts().CPlusPlus || Tok.is(tok::semi))
attrs.takeAllFrom(TempAttrs);
else if (isDeclarationStatement()) {
StmtVector Stmts;
// FIXME: We should do this whether or not we have a declaration
// statement, but that doesn't work correctly (because ProhibitAttributes
// can't handle GNU attributes), so only call it in the one case where
// GNU attributes are allowed.
SubStmt = ParseStatementOrDeclarationAfterAttributes(Stmts, StmtCtx,
nullptr, TempAttrs);
if (!TempAttrs.empty() && !SubStmt.isInvalid())
SubStmt = Actions.ProcessStmtAttributes(SubStmt.get(), TempAttrs,
TempAttrs.Range);
} else {
Diag(Tok, diag::err_expected_after) << "__attribute__" << tok::semi;
}
}
// If we've not parsed a statement yet, parse one now.
if (!SubStmt.isInvalid() && !SubStmt.isUsable())
SubStmt = ParseStatement(nullptr, StmtCtx);
// Broken substmt shouldn't prevent the label from being added to the AST.
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(ColonLoc);
LabelDecl *LD = Actions.LookupOrCreateLabel(IdentTok.getIdentifierInfo(),
IdentTok.getLocation());
Actions.ProcessDeclAttributeList(Actions.CurScope, LD, attrs);
attrs.clear();
return Actions.ActOnLabelStmt(IdentTok.getLocation(), LD, ColonLoc,
SubStmt.get());
}
/// ParseCaseStatement
/// labeled-statement:
/// 'case' constant-expression ':' statement
/// [GNU] 'case' constant-expression '...' constant-expression ':' statement
///
StmtResult Parser::ParseCaseStatement(ParsedStmtContext StmtCtx,
bool MissingCase, ExprResult Expr) {
assert((MissingCase || Tok.is(tok::kw_case)) && "Not a case stmt!");
// The substatement is always a 'statement', not a 'declaration', but is
// otherwise in the same context as the labeled-statement.
StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
// It is very very common for code to contain many case statements recursively
// nested, as in (but usually without indentation):
// case 1:
// case 2:
// case 3:
// case 4:
// case 5: etc.
//
// Parsing this naively works, but is both inefficient and can cause us to run
// out of stack space in our recursive descent parser. As a special case,
// flatten this recursion into an iterative loop. This is complex and gross,
// but all the grossness is constrained to ParseCaseStatement (and some
// weirdness in the actions), so this is just local grossness :).
// TopLevelCase - This is the highest level we have parsed. 'case 1' in the
// example above.
StmtResult TopLevelCase(true);
// DeepestParsedCaseStmt - This is the deepest statement we have parsed, which
// gets updated each time a new case is parsed, and whose body is unset so
// far. When parsing 'case 4', this is the 'case 3' node.
Stmt *DeepestParsedCaseStmt = nullptr;
// While we have case statements, eat and stack them.
SourceLocation ColonLoc;
do {
SourceLocation CaseLoc = MissingCase ? Expr.get()->getExprLoc() :
ConsumeToken(); // eat the 'case'.
ColonLoc = SourceLocation();
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteCase(getCurScope());
cutOffParsing();
return StmtError();
}
/// We don't want to treat 'case x : y' as a potential typo for 'case x::y'.
/// Disable this form of error recovery while we're parsing the case
/// expression.
ColonProtectionRAIIObject ColonProtection(*this);
ExprResult LHS;
if (!MissingCase) {
LHS = ParseCaseExpression(CaseLoc);
if (LHS.isInvalid()) {
// If constant-expression is parsed unsuccessfully, recover by skipping
// current case statement (moving to the colon that ends it).
if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
return StmtError();
}
} else {
LHS = Expr;
MissingCase = false;
}
// GNU case range extension.
SourceLocation DotDotDotLoc;
ExprResult RHS;
if (TryConsumeToken(tok::ellipsis, DotDotDotLoc)) {
Diag(DotDotDotLoc, diag::ext_gnu_case_range);
RHS = ParseCaseExpression(CaseLoc);
if (RHS.isInvalid()) {
if (!SkipUntil(tok::colon, tok::r_brace, StopAtSemi | StopBeforeMatch))
return StmtError();
}
}
ColonProtection.restore();
if (TryConsumeToken(tok::colon, ColonLoc)) {
} else if (TryConsumeToken(tok::semi, ColonLoc) ||
TryConsumeToken(tok::coloncolon, ColonLoc)) {
// Treat "case blah;" or "case blah::" as a typo for "case blah:".
Diag(ColonLoc, diag::err_expected_after)
<< "'case'" << tok::colon
<< FixItHint::CreateReplacement(ColonLoc, ":");
} else {
SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Diag(ExpectedLoc, diag::err_expected_after)
<< "'case'" << tok::colon
<< FixItHint::CreateInsertion(ExpectedLoc, ":");
ColonLoc = ExpectedLoc;
}
StmtResult Case =
Actions.ActOnCaseStmt(CaseLoc, LHS, DotDotDotLoc, RHS, ColonLoc);
// If we had a sema error parsing this case, then just ignore it and
// continue parsing the sub-stmt.
if (Case.isInvalid()) {
if (TopLevelCase.isInvalid()) // No parsed case stmts.
return ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
// Otherwise, just don't add it as a nested case.
} else {
// If this is the first case statement we parsed, it becomes TopLevelCase.
// Otherwise we link it into the current chain.
Stmt *NextDeepest = Case.get();
if (TopLevelCase.isInvalid())
TopLevelCase = Case;
else
Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, Case.get());
DeepestParsedCaseStmt = NextDeepest;
}
// Handle all case statements.
} while (Tok.is(tok::kw_case));
// If we found a non-case statement, start by parsing it.
StmtResult SubStmt;
if (Tok.isNot(tok::r_brace)) {
SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
} else {
// Nicely diagnose the common error "switch (X) { case 4: }", which is
// not valid. If ColonLoc doesn't point to a valid text location, there was
// another parsing error, so avoid producing extra diagnostics.
if (ColonLoc.isValid()) {
SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
<< FixItHint::CreateInsertion(AfterColonLoc, " ;");
}
SubStmt = StmtError();
}
// Install the body into the most deeply-nested case.
if (DeepestParsedCaseStmt) {
// Broken sub-stmt shouldn't prevent forming the case statement properly.
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(SourceLocation());
Actions.ActOnCaseStmtBody(DeepestParsedCaseStmt, SubStmt.get());
}
// Return the top level parsed statement tree.
return TopLevelCase;
}
/// ParseDefaultStatement
/// labeled-statement:
/// 'default' ':' statement
/// Note that this does not parse the 'statement' at the end.
///
StmtResult Parser::ParseDefaultStatement(ParsedStmtContext StmtCtx) {
assert(Tok.is(tok::kw_default) && "Not a default stmt!");
// The substatement is always a 'statement', not a 'declaration', but is
// otherwise in the same context as the labeled-statement.
StmtCtx &= ~ParsedStmtContext::AllowDeclarationsInC;
SourceLocation DefaultLoc = ConsumeToken(); // eat the 'default'.
SourceLocation ColonLoc;
if (TryConsumeToken(tok::colon, ColonLoc)) {
} else if (TryConsumeToken(tok::semi, ColonLoc)) {
// Treat "default;" as a typo for "default:".
Diag(ColonLoc, diag::err_expected_after)
<< "'default'" << tok::colon
<< FixItHint::CreateReplacement(ColonLoc, ":");
} else {
SourceLocation ExpectedLoc = PP.getLocForEndOfToken(PrevTokLocation);
Diag(ExpectedLoc, diag::err_expected_after)
<< "'default'" << tok::colon
<< FixItHint::CreateInsertion(ExpectedLoc, ":");
ColonLoc = ExpectedLoc;
}
StmtResult SubStmt;
if (Tok.isNot(tok::r_brace)) {
SubStmt = ParseStatement(/*TrailingElseLoc=*/nullptr, StmtCtx);
} else {
// Diagnose the common error "switch (X) {... default: }", which is
// not valid.
SourceLocation AfterColonLoc = PP.getLocForEndOfToken(ColonLoc);
Diag(AfterColonLoc, diag::err_label_end_of_compound_statement)
<< FixItHint::CreateInsertion(AfterColonLoc, " ;");
SubStmt = true;
}
// Broken sub-stmt shouldn't prevent forming the case statement properly.
if (SubStmt.isInvalid())
SubStmt = Actions.ActOnNullStmt(ColonLoc);
return Actions.ActOnDefaultStmt(DefaultLoc, ColonLoc,
SubStmt.get(), getCurScope());
}
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr) {
return ParseCompoundStatement(isStmtExpr,
Scope::DeclScope | Scope::CompoundStmtScope);
}
/// ParseCompoundStatement - Parse a "{}" block.
///
/// compound-statement: [C99 6.8.2]
/// { block-item-list[opt] }
/// [GNU] { label-declarations block-item-list } [TODO]
///
/// block-item-list:
/// block-item
/// block-item-list block-item
///
/// block-item:
/// declaration
/// [GNU] '__extension__' declaration
/// statement
///
/// [GNU] label-declarations:
/// [GNU] label-declaration
/// [GNU] label-declarations label-declaration
///
/// [GNU] label-declaration:
/// [GNU] '__label__' identifier-list ';'
///
StmtResult Parser::ParseCompoundStatement(bool isStmtExpr,
unsigned ScopeFlags) {
assert(Tok.is(tok::l_brace) && "Not a compount stmt!");
// Enter a scope to hold everything within the compound stmt. Compound
// statements can always hold declarations.
ParseScope CompoundScope(this, ScopeFlags);
// Parse the statements in the body.
return ParseCompoundStatementBody(isStmtExpr);
}
/// Parse any pragmas at the start of the compound expression. We handle these
/// separately since some pragmas (FP_CONTRACT) must appear before any C
/// statement in the compound, but may be intermingled with other pragmas.
void Parser::ParseCompoundStatementLeadingPragmas() {
bool checkForPragmas = true;
while (checkForPragmas) {
switch (Tok.getKind()) {
case tok::annot_pragma_vis:
HandlePragmaVisibility();
break;
case tok::annot_pragma_pack:
HandlePragmaPack();
break;
case tok::annot_pragma_msstruct:
HandlePragmaMSStruct();
break;
case tok::annot_pragma_align:
HandlePragmaAlign();
break;
case tok::annot_pragma_weak:
HandlePragmaWeak();
break;
case tok::annot_pragma_weakalias:
HandlePragmaWeakAlias();
break;
case tok::annot_pragma_redefine_extname:
HandlePragmaRedefineExtname();
break;
case tok::annot_pragma_opencl_extension:
HandlePragmaOpenCLExtension();
break;
case tok::annot_pragma_fp_contract:
HandlePragmaFPContract();
break;
case tok::annot_pragma_fp:
HandlePragmaFP();
break;
case tok::annot_pragma_fenv_access:
HandlePragmaFEnvAccess();
break;
case tok::annot_pragma_fenv_round:
HandlePragmaFEnvRound();
break;
case tok::annot_pragma_float_control:
HandlePragmaFloatControl();
break;
case tok::annot_pragma_ms_pointers_to_members:
HandlePragmaMSPointersToMembers();
break;
case tok::annot_pragma_ms_pragma:
HandlePragmaMSPragma();
break;
case tok::annot_pragma_ms_vtordisp:
HandlePragmaMSVtorDisp();
break;
case tok::annot_pragma_dump:
HandlePragmaDump();
break;
default:
checkForPragmas = false;
break;
}
}
}
/// Consume any extra semi-colons resulting in null statements,
/// returning true if any tok::semi were consumed.
bool Parser::ConsumeNullStmt(StmtVector &Stmts) {
if (!Tok.is(tok::semi))
return false;
SourceLocation StartLoc = Tok.getLocation();
SourceLocation EndLoc;
while (Tok.is(tok::semi) && !Tok.hasLeadingEmptyMacro() &&
Tok.getLocation().isValid() && !Tok.getLocation().isMacroID()) {
EndLoc = Tok.getLocation();
// Don't just ConsumeToken() this tok::semi, do store it in AST.
StmtResult R =
ParseStatementOrDeclaration(Stmts, ParsedStmtContext::SubStmt);
if (R.isUsable())
Stmts.push_back(R.get());
}
// Did not consume any extra semi.
if (EndLoc.isInvalid())
return false;
Diag(StartLoc, diag::warn_null_statement)
<< FixItHint::CreateRemoval(SourceRange(StartLoc, EndLoc));
return true;
}
StmtResult Parser::handleExprStmt(ExprResult E, ParsedStmtContext StmtCtx) {
bool IsStmtExprResult = false;
if ((StmtCtx & ParsedStmtContext::InStmtExpr) != ParsedStmtContext()) {
// For GCC compatibility we skip past NullStmts.
unsigned LookAhead = 0;
while (GetLookAheadToken(LookAhead).is(tok::semi)) {
++LookAhead;
}
// Then look to see if the next two tokens close the statement expression;
// if so, this expression statement is the last statement in a statment
// expression.
IsStmtExprResult = GetLookAheadToken(LookAhead).is(tok::r_brace) &&
GetLookAheadToken(LookAhead + 1).is(tok::r_paren);
}
if (IsStmtExprResult)
E = Actions.ActOnStmtExprResult(E);
return Actions.ActOnExprStmt(E, /*DiscardedValue=*/!IsStmtExprResult);
}
/// ParseCompoundStatementBody - Parse a sequence of statements and invoke the
/// ActOnCompoundStmt action. This expects the '{' to be the current token, and
/// consume the '}' at the end of the block. It does not manipulate the scope
/// stack.
StmtResult Parser::ParseCompoundStatementBody(bool isStmtExpr) {
PrettyStackTraceLoc CrashInfo(PP.getSourceManager(),
Tok.getLocation(),
"in compound statement ('{}')");
// Record the current FPFeatures, restore on leaving the
// compound statement.
Sema::FPFeaturesStateRAII SaveFPFeatures(Actions);
InMessageExpressionRAIIObject InMessage(*this, false);
BalancedDelimiterTracker T(*this, tok::l_brace);
if (T.consumeOpen())
return StmtError();
Sema::CompoundScopeRAII CompoundScope(Actions, isStmtExpr);
// Parse any pragmas at the beginning of the compound statement.
ParseCompoundStatementLeadingPragmas();
Actions.ActOnAfterCompoundStatementLeadingPragmas();
StmtVector Stmts;
// "__label__ X, Y, Z;" is the GNU "Local Label" extension. These are
// only allowed at the start of a compound stmt regardless of the language.
while (Tok.is(tok::kw___label__)) {
SourceLocation LabelLoc = ConsumeToken();
SmallVector<Decl *, 8> DeclsInGroup;
while (1) {
if (Tok.isNot(tok::identifier)) {
Diag(Tok, diag::err_expected) << tok::identifier;
break;
}
IdentifierInfo *II = Tok.getIdentifierInfo();
SourceLocation IdLoc = ConsumeToken();
DeclsInGroup.push_back(Actions.LookupOrCreateLabel(II, IdLoc, LabelLoc));
if (!TryConsumeToken(tok::comma))
break;
}
DeclSpec DS(AttrFactory);
DeclGroupPtrTy Res =
Actions.FinalizeDeclaratorGroup(getCurScope(), DS, DeclsInGroup);
StmtResult R = Actions.ActOnDeclStmt(Res, LabelLoc, Tok.getLocation());
ExpectAndConsumeSemi(diag::err_expected_semi_declaration);
if (R.isUsable())
Stmts.push_back(R.get());
}
ParsedStmtContext SubStmtCtx =
ParsedStmtContext::Compound |
(isStmtExpr ? ParsedStmtContext::InStmtExpr : ParsedStmtContext());
while (!tryParseMisplacedModuleImport() && Tok.isNot(tok::r_brace) &&
Tok.isNot(tok::eof)) {
if (Tok.is(tok::annot_pragma_unused)) {
HandlePragmaUnused();
continue;
}
if (ConsumeNullStmt(Stmts))
continue;
StmtResult R;
if (Tok.isNot(tok::kw___extension__)) {
R = ParseStatementOrDeclaration(Stmts, SubStmtCtx);
} else {
// __extension__ can start declarations and it can also be a unary
// operator for expressions. Consume multiple __extension__ markers here
// until we can determine which is which.
// FIXME: This loses extension expressions in the AST!
SourceLocation ExtLoc = ConsumeToken();
while (Tok.is(tok::kw___extension__))
ConsumeToken();
ParsedAttributesWithRange attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs, nullptr,
/*MightBeObjCMessageSend*/ true);
// If this is the start of a declaration, parse it as such.
if (isDeclarationStatement()) {
// __extension__ silences extension warnings in the subdeclaration.
// FIXME: Save the __extension__ on the decl as a node somehow?
ExtensionRAIIObject O(Diags);
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
DeclGroupPtrTy Res =
ParseDeclaration(DeclaratorContext::Block, DeclEnd, attrs);
R = Actions.ActOnDeclStmt(Res, DeclStart, DeclEnd);
} else {
// Otherwise this was a unary __extension__ marker.
ExprResult Res(ParseExpressionWithLeadingExtension(ExtLoc));
if (Res.isInvalid()) {
SkipUntil(tok::semi);
continue;
}
// Eat the semicolon at the end of stmt and convert the expr into a
// statement.
ExpectAndConsumeSemi(diag::err_expected_semi_after_expr);
R = handleExprStmt(Res, SubStmtCtx);
if (R.isUsable())
R = Actions.ProcessStmtAttributes(R.get(), attrs, attrs.Range);
}
}
if (R.isUsable())
Stmts.push_back(R.get());
}
SourceLocation CloseLoc = Tok.getLocation();
// We broke out of the while loop because we found a '}' or EOF.
if (!T.consumeClose()) {
// If this is the '})' of a statement expression, check that it's written
// in a sensible way.
if (isStmtExpr && Tok.is(tok::r_paren))
checkCompoundToken(CloseLoc, tok::r_brace, CompoundToken::StmtExprEnd);
} else {
// Recover by creating a compound statement with what we parsed so far,
// instead of dropping everything and returning StmtError().
}
if (T.getCloseLocation().isValid())
CloseLoc = T.getCloseLocation();
return Actions.ActOnCompoundStmt(T.getOpenLocation(), CloseLoc,
Stmts, isStmtExpr);
}
/// ParseParenExprOrCondition:
/// [C ] '(' expression ')'
/// [C++] '(' condition ')'
/// [C++1z] '(' init-statement[opt] condition ')'
///
/// This function parses and performs error recovery on the specified condition
/// or expression (depending on whether we're in C++ or C mode). This function
/// goes out of its way to recover well. It returns true if there was a parser
/// error (the right paren couldn't be found), which indicates that the caller
/// should try to recover harder. It returns false if the condition is
/// successfully parsed. Note that a successful parse can still have semantic
/// errors in the condition.
/// Additionally, if LParenLoc and RParenLoc are non-null, it will assign
/// the location of the outer-most '(' and ')', respectively, to them.
bool Parser::ParseParenExprOrCondition(StmtResult *InitStmt,
Sema::ConditionResult &Cond,
SourceLocation Loc,
Sema::ConditionKind CK,
SourceLocation *LParenLoc,
SourceLocation *RParenLoc) {
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
if (getLangOpts().CPlusPlus)
Cond = ParseCXXCondition(InitStmt, Loc, CK);
else {
ExprResult CondExpr = ParseExpression();
// If required, convert to a boolean value.
if (CondExpr.isInvalid())
Cond = Sema::ConditionError();
else
Cond = Actions.ActOnCondition(getCurScope(), Loc, CondExpr.get(), CK);
}
// If the parser was confused by the condition and we don't have a ')', try to
// recover by skipping ahead to a semi and bailing out. If condexp is
// semantically invalid but we have well formed code, keep going.
if (Cond.isInvalid() && Tok.isNot(tok::r_paren)) {
SkipUntil(tok::semi);
// Skipping may have stopped if it found the containing ')'. If so, we can
// continue parsing the if statement.
if (Tok.isNot(tok::r_paren))
return true;
}
// Otherwise the condition is valid or the rparen is present.
T.consumeClose();
if (LParenLoc != nullptr) {
*LParenLoc = T.getOpenLocation();
}
if (RParenLoc != nullptr) {
*RParenLoc = T.getCloseLocation();
}
// Check for extraneous ')'s to catch things like "if (foo())) {". We know
// that all callers are looking for a statement after the condition, so ")"
// isn't valid.
while (Tok.is(tok::r_paren)) {
Diag(Tok, diag::err_extraneous_rparen_in_condition)
<< FixItHint::CreateRemoval(Tok.getLocation());
ConsumeParen();
}
return false;
}
namespace {
enum MisleadingStatementKind { MSK_if, MSK_else, MSK_for, MSK_while };
struct MisleadingIndentationChecker {
Parser &P;
SourceLocation StmtLoc;
SourceLocation PrevLoc;
unsigned NumDirectives;
MisleadingStatementKind Kind;
bool ShouldSkip;
MisleadingIndentationChecker(Parser &P, MisleadingStatementKind K,
SourceLocation SL)
: P(P), StmtLoc(SL), PrevLoc(P.getCurToken().getLocation()),
NumDirectives(P.getPreprocessor().getNumDirectives()), Kind(K),
ShouldSkip(P.getCurToken().is(tok::l_brace)) {
if (!P.MisleadingIndentationElseLoc.isInvalid()) {
StmtLoc = P.MisleadingIndentationElseLoc;
P.MisleadingIndentationElseLoc = SourceLocation();
}
if (Kind == MSK_else && !ShouldSkip)
P.MisleadingIndentationElseLoc = SL;
}
/// Compute the column number will aligning tabs on TabStop (-ftabstop), this
/// gives the visual indentation of the SourceLocation.
static unsigned getVisualIndentation(SourceManager &SM, SourceLocation Loc) {
unsigned TabStop = SM.getDiagnostics().getDiagnosticOptions().TabStop;
unsigned ColNo = SM.getSpellingColumnNumber(Loc);
if (ColNo == 0 || TabStop == 1)
return ColNo;
std::pair<FileID, unsigned> FIDAndOffset = SM.getDecomposedLoc(Loc);
bool Invalid;
StringRef BufData = SM.getBufferData(FIDAndOffset.first, &Invalid);
if (Invalid)
return 0;
const char *EndPos = BufData.data() + FIDAndOffset.second;
// FileOffset are 0-based and Column numbers are 1-based
assert(FIDAndOffset.second + 1 >= ColNo &&
"Column number smaller than file offset?");
unsigned VisualColumn = 0; // Stored as 0-based column, here.
// Loop from beginning of line up to Loc's file position, counting columns,
// expanding tabs.
for (const char *CurPos = EndPos - (ColNo - 1); CurPos != EndPos;
++CurPos) {
if (*CurPos == '\t')
// Advance visual column to next tabstop.
VisualColumn += (TabStop - VisualColumn % TabStop);
else
VisualColumn++;
}
return VisualColumn + 1;
}
void Check() {
Token Tok = P.getCurToken();
if (P.getActions().getDiagnostics().isIgnored(
diag::warn_misleading_indentation, Tok.getLocation()) ||
ShouldSkip || NumDirectives != P.getPreprocessor().getNumDirectives() ||
Tok.isOneOf(tok::semi, tok::r_brace) || Tok.isAnnotation() ||
Tok.getLocation().isMacroID() || PrevLoc.isMacroID() ||
StmtLoc.isMacroID() ||
(Kind == MSK_else && P.MisleadingIndentationElseLoc.isInvalid())) {
P.MisleadingIndentationElseLoc = SourceLocation();
return;
}
if (Kind == MSK_else)
P.MisleadingIndentationElseLoc = SourceLocation();
SourceManager &SM = P.getPreprocessor().getSourceManager();
unsigned PrevColNum = getVisualIndentation(SM, PrevLoc);
unsigned CurColNum = getVisualIndentation(SM, Tok.getLocation());
unsigned StmtColNum = getVisualIndentation(SM, StmtLoc);
if (PrevColNum != 0 && CurColNum != 0 && StmtColNum != 0 &&
((PrevColNum > StmtColNum && PrevColNum == CurColNum) ||
!Tok.isAtStartOfLine()) &&
SM.getPresumedLineNumber(StmtLoc) !=
SM.getPresumedLineNumber(Tok.getLocation()) &&
(Tok.isNot(tok::identifier) ||
P.getPreprocessor().LookAhead(0).isNot(tok::colon))) {
P.Diag(Tok.getLocation(), diag::warn_misleading_indentation) << Kind;
P.Diag(StmtLoc, diag::note_previous_statement);
}
}
};
}
/// ParseIfStatement
/// if-statement: [C99 6.8.4.1]
/// 'if' '(' expression ')' statement
/// 'if' '(' expression ')' statement 'else' statement
/// [C++] 'if' '(' condition ')' statement
/// [C++] 'if' '(' condition ')' statement 'else' statement
///
StmtResult Parser::ParseIfStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_if) && "Not an if stmt!");
SourceLocation IfLoc = ConsumeToken(); // eat the 'if'.
bool IsConstexpr = false;
if (Tok.is(tok::kw_constexpr)) {
Diag(Tok, getLangOpts().CPlusPlus17 ? diag::warn_cxx14_compat_constexpr_if
: diag::ext_constexpr_if);
IsConstexpr = true;
ConsumeToken();
}
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "if";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
// C99 6.8.4p3 - In C99, the if statement is a block. This is not
// the case for C90.
//
// C++ 6.4p3:
// A name introduced by a declaration in a condition is in scope from its
// point of declaration until the end of the substatements controlled by the
// condition.
// C++ 3.3.2p4:
// Names declared in the for-init-statement, and in the condition of if,
// while, for, and switch statements are local to the if, while, for, or
// switch statement (including the controlled statement).
//
ParseScope IfScope(this, Scope::DeclScope | Scope::ControlScope, C99orCXX);
// Parse the condition.
StmtResult InitStmt;
Sema::ConditionResult Cond;
SourceLocation LParen;
SourceLocation RParen;
if (ParseParenExprOrCondition(&InitStmt, Cond, IfLoc,
IsConstexpr ? Sema::ConditionKind::ConstexprIf
: Sema::ConditionKind::Boolean,
&LParen, &RParen))
return StmtError();
llvm::Optional<bool> ConstexprCondition;
if (IsConstexpr)
ConstexprCondition = Cond.getKnownValue();
bool IsBracedThen = Tok.is(tok::l_brace);
// C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
// there is no compound stmt. C90 does not have this clause. We only do this
// if the body isn't a compound statement to avoid push/pop in common cases.
//
// C++ 6.4p1:
// The substatement in a selection-statement (each substatement, in the else
// form of the if statement) implicitly defines a local scope.
//
// For C++ we create a scope for the condition and a new scope for
// substatements because:
// -When the 'then' scope exits, we want the condition declaration to still be
// active for the 'else' scope too.
// -Sema will detect name clashes by considering declarations of a
// 'ControlScope' as part of its direct subscope.
// -If we wanted the condition and substatement to be in the same scope, we
// would have to notify ParseStatement not to create a new scope. It's
// simpler to let it create a new scope.
//
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, IsBracedThen);
MisleadingIndentationChecker MIChecker(*this, MSK_if, IfLoc);
// Read the 'then' stmt.
SourceLocation ThenStmtLoc = Tok.getLocation();
SourceLocation InnerStatementTrailingElseLoc;
StmtResult ThenStmt;
{
EnterExpressionEvaluationContext PotentiallyDiscarded(
Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
Sema::ExpressionEvaluationContextRecord::EK_Other,
/*ShouldEnter=*/ConstexprCondition && !*ConstexprCondition);
ThenStmt = ParseStatement(&InnerStatementTrailingElseLoc);
}
if (Tok.isNot(tok::kw_else))
MIChecker.Check();
// Pop the 'if' scope if needed.
InnerScope.Exit();
// If it has an else, parse it.
SourceLocation ElseLoc;
SourceLocation ElseStmtLoc;
StmtResult ElseStmt;
if (Tok.is(tok::kw_else)) {
if (TrailingElseLoc)
*TrailingElseLoc = Tok.getLocation();
ElseLoc = ConsumeToken();
ElseStmtLoc = Tok.getLocation();
// C99 6.8.4p3 - In C99, the body of the if statement is a scope, even if
// there is no compound stmt. C90 does not have this clause. We only do
// this if the body isn't a compound statement to avoid push/pop in common
// cases.
//
// C++ 6.4p1:
// The substatement in a selection-statement (each substatement, in the else
// form of the if statement) implicitly defines a local scope.
//
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX,
Tok.is(tok::l_brace));
MisleadingIndentationChecker MIChecker(*this, MSK_else, ElseLoc);
EnterExpressionEvaluationContext PotentiallyDiscarded(
Actions, Sema::ExpressionEvaluationContext::DiscardedStatement, nullptr,
Sema::ExpressionEvaluationContextRecord::EK_Other,
/*ShouldEnter=*/ConstexprCondition && *ConstexprCondition);
ElseStmt = ParseStatement();
if (ElseStmt.isUsable())
MIChecker.Check();
// Pop the 'else' scope if needed.
InnerScope.Exit();
} else if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteAfterIf(getCurScope(), IsBracedThen);
cutOffParsing();
return StmtError();
} else if (InnerStatementTrailingElseLoc.isValid()) {
Diag(InnerStatementTrailingElseLoc, diag::warn_dangling_else);
}
IfScope.Exit();
// If the then or else stmt is invalid and the other is valid (and present),
// make turn the invalid one into a null stmt to avoid dropping the other
// part. If both are invalid, return error.
if ((ThenStmt.isInvalid() && ElseStmt.isInvalid()) ||
(ThenStmt.isInvalid() && ElseStmt.get() == nullptr) ||
(ThenStmt.get() == nullptr && ElseStmt.isInvalid())) {
// Both invalid, or one is invalid and other is non-present: return error.
return StmtError();
}
// Now if either are invalid, replace with a ';'.
if (ThenStmt.isInvalid())
ThenStmt = Actions.ActOnNullStmt(ThenStmtLoc);
if (ElseStmt.isInvalid())
ElseStmt = Actions.ActOnNullStmt(ElseStmtLoc);
return Actions.ActOnIfStmt(IfLoc, IsConstexpr, LParen, InitStmt.get(), Cond,
RParen, ThenStmt.get(), ElseLoc, ElseStmt.get());
}
/// ParseSwitchStatement
/// switch-statement:
/// 'switch' '(' expression ')' statement
/// [C++] 'switch' '(' condition ')' statement
StmtResult Parser::ParseSwitchStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_switch) && "Not a switch stmt!");
SourceLocation SwitchLoc = ConsumeToken(); // eat the 'switch'.
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "switch";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
// C99 6.8.4p3 - In C99, the switch statement is a block. This is
// not the case for C90. Start the switch scope.
//
// C++ 6.4p3:
// A name introduced by a declaration in a condition is in scope from its
// point of declaration until the end of the substatements controlled by the
// condition.
// C++ 3.3.2p4:
// Names declared in the for-init-statement, and in the condition of if,
// while, for, and switch statements are local to the if, while, for, or
// switch statement (including the controlled statement).
//
unsigned ScopeFlags = Scope::SwitchScope;
if (C99orCXX)
ScopeFlags |= Scope::DeclScope | Scope::ControlScope;
ParseScope SwitchScope(this, ScopeFlags);
// Parse the condition.
StmtResult InitStmt;
Sema::ConditionResult Cond;
SourceLocation LParen;
SourceLocation RParen;
if (ParseParenExprOrCondition(&InitStmt, Cond, SwitchLoc,
Sema::ConditionKind::Switch, &LParen, &RParen))
return StmtError();
StmtResult Switch = Actions.ActOnStartOfSwitchStmt(
SwitchLoc, LParen, InitStmt.get(), Cond, RParen);
if (Switch.isInvalid()) {
// Skip the switch body.
// FIXME: This is not optimal recovery, but parsing the body is more
// dangerous due to the presence of case and default statements, which
// will have no place to connect back with the switch.
if (Tok.is(tok::l_brace)) {
ConsumeBrace();
SkipUntil(tok::r_brace);
} else
SkipUntil(tok::semi);
return Switch;
}
// C99 6.8.4p3 - In C99, the body of the switch statement is a scope, even if
// there is no compound stmt. C90 does not have this clause. We only do this
// if the body isn't a compound statement to avoid push/pop in common cases.
//
// C++ 6.4p1:
// The substatement in a selection-statement (each substatement, in the else
// form of the if statement) implicitly defines a local scope.
//
// See comments in ParseIfStatement for why we create a scope for the
// condition and a new scope for substatement in C++.
//
getCurScope()->AddFlags(Scope::BreakScope);
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
// We have incremented the mangling number for the SwitchScope and the
// InnerScope, which is one too many.
if (C99orCXX)
getCurScope()->decrementMSManglingNumber();
// Read the body statement.
StmtResult Body(ParseStatement(TrailingElseLoc));
// Pop the scopes.
InnerScope.Exit();
SwitchScope.Exit();
return Actions.ActOnFinishSwitchStmt(SwitchLoc, Switch.get(), Body.get());
}
/// ParseWhileStatement
/// while-statement: [C99 6.8.5.1]
/// 'while' '(' expression ')' statement
/// [C++] 'while' '(' condition ')' statement
StmtResult Parser::ParseWhileStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_while) && "Not a while stmt!");
SourceLocation WhileLoc = Tok.getLocation();
ConsumeToken(); // eat the 'while'.
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "while";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
// C99 6.8.5p5 - In C99, the while statement is a block. This is not
// the case for C90. Start the loop scope.
//
// C++ 6.4p3:
// A name introduced by a declaration in a condition is in scope from its
// point of declaration until the end of the substatements controlled by the
// condition.
// C++ 3.3.2p4:
// Names declared in the for-init-statement, and in the condition of if,
// while, for, and switch statements are local to the if, while, for, or
// switch statement (including the controlled statement).
//
unsigned ScopeFlags;
if (C99orCXX)
ScopeFlags = Scope::BreakScope | Scope::ContinueScope |
Scope::DeclScope | Scope::ControlScope;
else
ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
ParseScope WhileScope(this, ScopeFlags);
// Parse the condition.
Sema::ConditionResult Cond;
SourceLocation LParen;
SourceLocation RParen;
if (ParseParenExprOrCondition(nullptr, Cond, WhileLoc,
Sema::ConditionKind::Boolean, &LParen, &RParen))
return StmtError();
// C99 6.8.5p5 - In C99, the body of the while statement is a scope, even if
// there is no compound stmt. C90 does not have this clause. We only do this
// if the body isn't a compound statement to avoid push/pop in common cases.
//
// C++ 6.5p2:
// The substatement in an iteration-statement implicitly defines a local scope
// which is entered and exited each time through the loop.
//
// See comments in ParseIfStatement for why we create a scope for the
// condition and a new scope for substatement in C++.
//
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
MisleadingIndentationChecker MIChecker(*this, MSK_while, WhileLoc);
// Read the body statement.
StmtResult Body(ParseStatement(TrailingElseLoc));
if (Body.isUsable())
MIChecker.Check();
// Pop the body scope if needed.
InnerScope.Exit();
WhileScope.Exit();
if (Cond.isInvalid() || Body.isInvalid())
return StmtError();
return Actions.ActOnWhileStmt(WhileLoc, LParen, Cond, RParen, Body.get());
}
/// ParseDoStatement
/// do-statement: [C99 6.8.5.2]
/// 'do' statement 'while' '(' expression ')' ';'
/// Note: this lets the caller parse the end ';'.
StmtResult Parser::ParseDoStatement() {
assert(Tok.is(tok::kw_do) && "Not a do stmt!");
SourceLocation DoLoc = ConsumeToken(); // eat the 'do'.
// C99 6.8.5p5 - In C99, the do statement is a block. This is not
// the case for C90. Start the loop scope.
unsigned ScopeFlags;
if (getLangOpts().C99)
ScopeFlags = Scope::BreakScope | Scope::ContinueScope | Scope::DeclScope;
else
ScopeFlags = Scope::BreakScope | Scope::ContinueScope;
ParseScope DoScope(this, ScopeFlags);
// C99 6.8.5p5 - In C99, the body of the do statement is a scope, even if
// there is no compound stmt. C90 does not have this clause. We only do this
// if the body isn't a compound statement to avoid push/pop in common cases.
//
// C++ 6.5p2:
// The substatement in an iteration-statement implicitly defines a local scope
// which is entered and exited each time through the loop.
//
bool C99orCXX = getLangOpts().C99 || getLangOpts().CPlusPlus;
ParseScope InnerScope(this, Scope::DeclScope, C99orCXX, Tok.is(tok::l_brace));
// Read the body statement.
StmtResult Body(ParseStatement());
// Pop the body scope if needed.
InnerScope.Exit();
if (Tok.isNot(tok::kw_while)) {
if (!Body.isInvalid()) {
Diag(Tok, diag::err_expected_while);
Diag(DoLoc, diag::note_matching) << "'do'";
SkipUntil(tok::semi, StopBeforeMatch);
}
return StmtError();
}
SourceLocation WhileLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "do/while";
SkipUntil(tok::semi, StopBeforeMatch);
return StmtError();
}
// Parse the parenthesized expression.
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
// A do-while expression is not a condition, so can't have attributes.
DiagnoseAndSkipCXX11Attributes();
ExprResult Cond = ParseExpression();
// Correct the typos in condition before closing the scope.
if (Cond.isUsable())
Cond = Actions.CorrectDelayedTyposInExpr(Cond);
T.consumeClose();
DoScope.Exit();
if (Cond.isInvalid() || Body.isInvalid())
return StmtError();
return Actions.ActOnDoStmt(DoLoc, Body.get(), WhileLoc, T.getOpenLocation(),
Cond.get(), T.getCloseLocation());
}
bool Parser::isForRangeIdentifier() {
assert(Tok.is(tok::identifier));
const Token &Next = NextToken();
if (Next.is(tok::colon))
return true;
if (Next.isOneOf(tok::l_square, tok::kw_alignas)) {
TentativeParsingAction PA(*this);
ConsumeToken();
SkipCXX11Attributes();
bool Result = Tok.is(tok::colon);
PA.Revert();
return Result;
}
return false;
}
/// ParseForStatement
/// for-statement: [C99 6.8.5.3]
/// 'for' '(' expr[opt] ';' expr[opt] ';' expr[opt] ')' statement
/// 'for' '(' declaration expr[opt] ';' expr[opt] ')' statement
/// [C++] 'for' '(' for-init-statement condition[opt] ';' expression[opt] ')'
/// [C++] statement
/// [C++0x] 'for'
/// 'co_await'[opt] [Coroutines]
/// '(' for-range-declaration ':' for-range-initializer ')'
/// statement
/// [OBJC2] 'for' '(' declaration 'in' expr ')' statement
/// [OBJC2] 'for' '(' expr 'in' expr ')' statement
///
/// [C++] for-init-statement:
/// [C++] expression-statement
/// [C++] simple-declaration
///
/// [C++0x] for-range-declaration:
/// [C++0x] attribute-specifier-seq[opt] type-specifier-seq declarator
/// [C++0x] for-range-initializer:
/// [C++0x] expression
/// [C++0x] braced-init-list [TODO]
StmtResult Parser::ParseForStatement(SourceLocation *TrailingElseLoc) {
assert(Tok.is(tok::kw_for) && "Not a for stmt!");
SourceLocation ForLoc = ConsumeToken(); // eat the 'for'.
SourceLocation CoawaitLoc;
if (Tok.is(tok::kw_co_await))
CoawaitLoc = ConsumeToken();
if (Tok.isNot(tok::l_paren)) {
Diag(Tok, diag::err_expected_lparen_after) << "for";
SkipUntil(tok::semi);
return StmtError();
}
bool C99orCXXorObjC = getLangOpts().C99 || getLangOpts().CPlusPlus ||
getLangOpts().ObjC;
// C99 6.8.5p5 - In C99, the for statement is a block. This is not
// the case for C90. Start the loop scope.
//
// C++ 6.4p3:
// A name introduced by a declaration in a condition is in scope from its
// point of declaration until the end of the substatements controlled by the
// condition.
// C++ 3.3.2p4:
// Names declared in the for-init-statement, and in the condition of if,
// while, for, and switch statements are local to the if, while, for, or
// switch statement (including the controlled statement).
// C++ 6.5.3p1:
// Names declared in the for-init-statement are in the same declarative-region
// as those declared in the condition.
//
unsigned ScopeFlags = 0;
if (C99orCXXorObjC)
ScopeFlags = Scope::DeclScope | Scope::ControlScope;
ParseScope ForScope(this, ScopeFlags);
BalancedDelimiterTracker T(*this, tok::l_paren);
T.consumeOpen();
ExprResult Value;
bool ForEach = false;
StmtResult FirstPart;
Sema::ConditionResult SecondPart;
ExprResult Collection;
ForRangeInfo ForRangeInfo;
FullExprArg ThirdPart(Actions);
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteOrdinaryName(getCurScope(),
C99orCXXorObjC? Sema::PCC_ForInit
: Sema::PCC_Expression);
cutOffParsing();
return StmtError();
}
ParsedAttributesWithRange attrs(AttrFactory);
MaybeParseCXX11Attributes(attrs);
SourceLocation EmptyInitStmtSemiLoc;
// Parse the first part of the for specifier.
if (Tok.is(tok::semi)) { // for (;
ProhibitAttributes(attrs);
// no first part, eat the ';'.
SourceLocation SemiLoc = Tok.getLocation();
if (!Tok.hasLeadingEmptyMacro() && !SemiLoc.isMacroID())
EmptyInitStmtSemiLoc = SemiLoc;
ConsumeToken();
} else if (getLangOpts().CPlusPlus && Tok.is(tok::identifier) &&
isForRangeIdentifier()) {
ProhibitAttributes(attrs);
IdentifierInfo *Name = Tok.getIdentifierInfo();
SourceLocation Loc = ConsumeToken();
MaybeParseCXX11Attributes(attrs);
ForRangeInfo.ColonLoc = ConsumeToken();
if (Tok.is(tok::l_brace))
ForRangeInfo.RangeExpr = ParseBraceInitializer();
else
ForRangeInfo.RangeExpr = ParseExpression();
Diag(Loc, diag::err_for_range_identifier)
<< ((getLangOpts().CPlusPlus11 && !getLangOpts().CPlusPlus17)
? FixItHint::CreateInsertion(Loc, "auto &&")
: FixItHint());
ForRangeInfo.LoopVar = Actions.ActOnCXXForRangeIdentifier(
getCurScope(), Loc, Name, attrs, attrs.Range.getEnd());
} else if (isForInitDeclaration()) { // for (int X = 4;
ParenBraceBracketBalancer BalancerRAIIObj(*this);
// Parse declaration, which eats the ';'.
if (!C99orCXXorObjC) { // Use of C99-style for loops in C90 mode?
Diag(Tok, diag::ext_c99_variable_decl_in_for_loop);
Diag(Tok, diag::warn_gcc_variable_decl_in_for_loop);
}
// In C++0x, "for (T NS:a" might not be a typo for ::
bool MightBeForRangeStmt = getLangOpts().CPlusPlus;
ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
SourceLocation DeclStart = Tok.getLocation(), DeclEnd;
DeclGroupPtrTy DG = ParseSimpleDeclaration(
DeclaratorContext::ForInit, DeclEnd, attrs, false,
MightBeForRangeStmt ? &ForRangeInfo : nullptr);
FirstPart = Actions.ActOnDeclStmt(DG, DeclStart, Tok.getLocation());
if (ForRangeInfo.ParsedForRangeDecl()) {
Diag(ForRangeInfo.ColonLoc, getLangOpts().CPlusPlus11 ?
diag::warn_cxx98_compat_for_range : diag::ext_for_range);
ForRangeInfo.LoopVar = FirstPart;
FirstPart = StmtResult();
} else if (Tok.is(tok::semi)) { // for (int x = 4;
ConsumeToken();
} else if ((ForEach = isTokIdentifier_in())) {
Actions.ActOnForEachDeclStmt(DG);
// ObjC: for (id x in expr)
ConsumeToken(); // consume 'in'
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCForCollection(getCurScope(), DG);
cutOffParsing();
return StmtError();
}
Collection = ParseExpression();
} else {
Diag(Tok, diag::err_expected_semi_for);
}
} else {
ProhibitAttributes(attrs);
Value = Actions.CorrectDelayedTyposInExpr(ParseExpression());
ForEach = isTokIdentifier_in();
// Turn the expression into a stmt.
if (!Value.isInvalid()) {
if (ForEach)
FirstPart = Actions.ActOnForEachLValueExpr(Value.get());
else {
// We already know this is not an init-statement within a for loop, so
// if we are parsing a C++11 range-based for loop, we should treat this
// expression statement as being a discarded value expression because
// we will err below. This way we do not warn on an unused expression
// that was an error in the first place, like with: for (expr : expr);
bool IsRangeBasedFor =
getLangOpts().CPlusPlus11 && !ForEach && Tok.is(tok::colon);
FirstPart = Actions.ActOnExprStmt(Value, !IsRangeBasedFor);
}
}
if (Tok.is(tok::semi)) {
ConsumeToken();
} else if (ForEach) {
ConsumeToken(); // consume 'in'
if (Tok.is(tok::code_completion)) {
Actions.CodeCompleteObjCForCollection(getCurScope(), nullptr);
cutOffParsing();
return StmtError();
}
Collection = ParseExpression();
} else if (getLangOpts().CPlusPlus11 && Tok.is(tok::colon) && FirstPart.get()) {
// User tried to write the reasonable, but ill-formed, for-range-statement
// for (expr : expr) { ... }
Diag(Tok, diag::err_for_range_expected_decl)
<< FirstPart.get()->getSourceRange();
SkipUntil(tok::r_paren, StopBeforeMatch);
SecondPart = Sema::ConditionError();
} else {
if (!Value.isInvalid()) {
Diag(Tok, diag::err_expected_semi_for);
} else {
// Skip until semicolon or rparen, don't consume it.
SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
if (Tok.is(tok::semi))
ConsumeToken();
}
}
}
// Parse the second part of the for specifier.
getCurScope()->AddFlags(Scope::BreakScope | Scope::ContinueScope);
if (!ForEach && !ForRangeInfo.ParsedForRangeDecl() &&
!SecondPart.isInvalid()) {
// Parse the second part of the for specifier.
if (Tok.is(tok::semi)) { // for (...;;
// no second part.
} else if (Tok.is(tok::r_paren)) {
// missing both semicolons.
} else {
if (getLangOpts().CPlusPlus) {
// C++2a: We've parsed an init-statement; we might have a
// for-range-declaration next.
bool MightBeForRangeStmt = !ForRangeInfo.ParsedForRangeDecl();
ColonProtectionRAIIObject ColonProtection(*this, MightBeForRangeStmt);
SecondPart =
ParseCXXCondition(nullptr, ForLoc, Sema::ConditionKind::Boolean,
MightBeForRangeStmt ? &ForRangeInfo : nullptr);
if (ForRangeInfo.ParsedForRangeDecl()) {
Diag(FirstPart.get() ? FirstPart.get()->getBeginLoc()
: ForRangeInfo.ColonLoc,
getLangOpts().CPlusPlus20
? diag::warn_cxx17_compat_for_range_init_stmt
: diag::ext_for_range_init_stmt)
<< (FirstPart.get() ? FirstPart.get()->getSourceRange()
: SourceRange());
if (EmptyInitStmtSemiLoc.isValid()) {
Diag(EmptyInitStmtSemiLoc, diag::warn_empty_init_statement)
<< /*for-loop*/ 2
<< FixItHint::CreateRemoval(EmptyInitStmtSemiLoc);
}
}
} else {
ExprResult SecondExpr = ParseExpression();
if (SecondExpr.isInvalid())
SecondPart = Sema::ConditionError();
else
SecondPart =
Actions.ActOnCondition(getCurScope(), ForLoc, SecondExpr.get(),
Sema::ConditionKind::Boolean);
}
}
}
// Parse the third part of the for statement.
if (!ForEach && !ForRangeInfo.ParsedForRangeDecl()) {
if (Tok.isNot(tok::semi)) {
if (!SecondPart.isInvalid())
Diag(Tok, diag::err_expected_semi_for);
else
// Skip until semicolon or rparen, don't consume it.
SkipUntil(tok::r_paren, StopAtSemi | StopBeforeMatch);
}
if (Tok.is(tok::semi)) {
ConsumeToken();
}
if (Tok.isNot(tok::r_paren)) { // for (...;...;)
ExprResult Third = ParseExpression();
// FIXME: The C++11 standard doesn't actually say that this is a
// discarded-value expression, but it clearly should be.
ThirdPart = Actions.MakeFullDiscardedValueExpr(Third.get());
}
}
// Match the ')'.
T.consumeClose();
// C++ Coroutines [stmt.iter]:
// 'co_await' can only be used for a range-based for statement.
if (CoawaitLoc.isValid() && !ForRangeInfo.ParsedForRangeDecl()) {
Diag(CoawaitLoc, diag::err_for_co_await_not_range_for);
CoawaitLoc = SourceLocation();
}
// We need to perform most of the semantic analysis for a C++0x for-range
// statememt before parsing the body, in order to be able to deduce the type
// of an auto-typed loop variable.
StmtResult ForRangeStmt;
StmtResult ForEachStmt;
if (ForRangeInfo.ParsedForRangeDecl()) {
ExprResult CorrectedRange =
Actions.CorrectDelayedTyposInExpr(ForRangeInfo.RangeExpr.get());
ForRangeStmt = Actions.ActOnCXXForRangeStmt(
getCurScope(), ForLoc, CoawaitLoc, FirstPart.get(),
ForRangeInfo.LoopVar.get(), ForRangeInfo.ColonLoc, CorrectedRange.get(),
T.getCloseLocation(), Sema::BFRK_Build);
// Similarly, we need to do the semantic analysis for a for-range
// statement immediately in order to close over temporaries correctly.
} else if (ForEach) {
ForEachStmt = Actions.ActOnObjCForCollectionStmt(ForLoc,
FirstPart.get(),
Collection.get(),
T.getCloseLocation());
} else {
// In OpenMP loop region loop control variable must be captured and be
// private. Perform analysis of first part (if any).
if (getLangOpts().OpenMP && FirstPart.isUsable()) {
Actions.ActOnOpenMPLoopInitialization(ForLoc, FirstPart.get());
}
}
// C99 6.8.5p5 - In C99, the body of the for statement is a scope, even if
// there is no compound stmt. C90 does not have this clause. We only do this
// if the body isn't a compound statement to avoid push/pop in common cases.
//
// C++ 6.5p2:
// The substatement in an iteration-statement implicitly defines a local scope
// which is entered and exited each time through the loop.
//
// See comments in ParseIfStatement for why we create a scope for
// for-init-statement/condition and a new scope for substatement in C++.
//
ParseScope InnerScope(this, Scope::DeclScope, C99orCXXorObjC,
Tok.is(tok::l_brace));
// The body of the for loop has the same local mangling number as the
// for-init-statement.
// It will only be incremented if the body contains other things that would
// normally increment the mangling number (like a compound statement).
if (C99orCXXorObjC)
getCurScope()->decrementMSManglingNumber();
MisleadingIndentationChecker MIChecker(*this, MSK_for, ForLoc);
// Read the body statement.
StmtResult Body(ParseStatement(TrailingElseLoc));
if (Body.isUsable())
MIChecker.Check();
// Pop the body scope if needed.
InnerScope.Exit();
// Leave the for-scope.
ForScope.Exit();
if (Body.isInvalid())
return StmtError();
if (ForEach)
return Actions.FinishObjCForCollectionStmt(ForEachStmt.get(),
Body.get());
if (ForRangeInfo.ParsedForRangeDecl())
return Actions.FinishCXXForRangeStmt(ForRangeStmt.get(), Body.get());
return Actions.ActOnForStmt(ForLoc, T.getOpenLocation(), FirstPart.get(),
SecondPart, ThirdPart, T.getCloseLocation(),
Body.get());
}
/// ParseGotoStatement
/// jump-statement:
/// 'goto' identifier ';'
/// [GNU] 'goto' '*' expression ';'
///
/// Note: this lets the caller parse the end ';'.
///
StmtResult Parser::ParseGotoStatement() {
assert(Tok.is(tok::kw_goto) && "Not a goto stmt!");
SourceLocation GotoLoc = ConsumeToken(); // eat the 'goto'.
StmtResult Res;
if (Tok.is(tok::identifier)) {
LabelDecl *LD = Actions.LookupOrCreateLabel(Tok.getIdentifierInfo(),
Tok.getLocation());
Res = Actions.ActOnGotoStmt(GotoLoc, Tok.getLocation(), LD);
ConsumeToken();
} else if (Tok.is(tok::star)) {
// GNU indirect goto extension.
Diag(Tok, diag::ext_gnu_indirect_goto);
SourceLocation StarLoc = ConsumeToken();
ExprResult R(ParseExpression());
if (R.isInvalid()) { // Skip to the semicolon, but don't consume it.
SkipUntil(tok::semi, StopBeforeMatch);
return StmtError();
}
Res = Actions.ActOnIndirectGotoStmt(GotoLoc, StarLoc, R.get());
} else {
Diag(Tok, diag::err_expected) << tok::identifier;
return StmtError();
}
return Res;
}
/// ParseContinueStatement
/// jump-statement:
/// 'continue' ';'
///
/// Note: this lets the caller parse the end ';'.
///
StmtResult Parser::ParseContinueStatement() {
SourceLocation ContinueLoc = ConsumeToken(); // eat the 'continue'.
return Actions.ActOnContinueStmt(ContinueLoc, getCurScope());
}
/// ParseBreakStatement
/// jump-statement:
/// 'break' ';'
///
/// Note: this lets the caller parse the end ';'.
///
StmtResult Parser::ParseBreakStatement() {
SourceLocation BreakLoc = ConsumeToken(); // eat the 'break'.
return Actions.ActOnBreakStmt(BreakLoc, getCurScope());
}
/// ParseReturnStatement
/// jump-statement:
/// 'return' expression[opt] ';'
/// 'return' braced-init-list ';'
/// 'co_return' expression[opt] ';'
/// 'co_return' braced-init-list ';'
StmtResult Parser::ParseReturnStatement() {
assert((Tok.is(tok::kw_return) || Tok.is(tok::kw_co_return)) &&
"Not a return stmt!");
bool IsCoreturn = Tok.is(tok::kw_co_return);
SourceLocation ReturnLoc = ConsumeToken(); // eat the 'return'.
ExprResult R;
if (Tok.isNot(tok::semi)) {
if (!IsCoreturn)
PreferredType.enterReturn(Actions, Tok.getLocation());
// FIXME: Code completion for co_return.
if (Tok.is(tok::code_completion) && !IsCoreturn) {
Actions.CodeCompleteExpression(getCurScope(),
PreferredType.get(Tok.getLocation()));
cutOffParsing();
return StmtError();
}
if (Tok.is(tok::l_brace) && getLangOpts().CPlusPlus) {
R = ParseInitializer();
if (R.isUsable())
Diag(R.get()->getBeginLoc(),
getLangOpts().CPlusPlus11
? diag::warn_cxx98_compat_generalized_initializer_lists
: diag::ext_generalized_initializer_lists)
<< R.get()->getSourceRange();
} else
R = ParseExpression();
if (R.isInvalid()) {
SkipUntil(tok::r_brace, StopAtSemi | StopBeforeMatch);
return StmtError();
}
}
if (IsCoreturn)
return Actions.ActOnCoreturnStmt(getCurScope(), ReturnLoc, R.get());
return Actions.ActOnReturnStmt(ReturnLoc, R.get(), getCurScope());
}
StmtResult Parser::ParsePragmaLoopHint(StmtVector &Stmts,
ParsedStmtContext StmtCtx,
SourceLocation *TrailingElseLoc,
ParsedAttributesWithRange &Attrs) {
// Create temporary attribute list.
ParsedAttributesWithRange TempAttrs(AttrFactory);
SourceLocation StartLoc = Tok.getLocation();
// Get loop hints and consume annotated token.
while (Tok.is(tok::annot_pragma_loop_hint)) {
LoopHint Hint;
if (!HandlePragmaLoopHint(Hint))
continue;
ArgsUnion ArgHints[] = {Hint.PragmaNameLoc, Hint.OptionLoc, Hint.StateLoc,
ArgsUnion(Hint.ValueExpr)};
TempAttrs.addNew(Hint.PragmaNameLoc->Ident, Hint.Range, nullptr,
Hint.PragmaNameLoc->Loc, ArgHints, 4,
ParsedAttr::AS_Pragma);
}
// Get the next statement.
MaybeParseCXX11Attributes(Attrs);
StmtResult S = ParseStatementOrDeclarationAfterAttributes(
Stmts, StmtCtx, TrailingElseLoc, Attrs);
Attrs.takeAllFrom(TempAttrs);
// Start of attribute range may already be set for some invalid input.
// See PR46336.
if (Attrs.Range.getBegin().isInvalid())
Attrs.Range.setBegin(StartLoc);
return S;
}
Decl *Parser::ParseFunctionStatementBody(Decl *Decl, ParseScope &BodyScope) {
assert(Tok.is(tok::l_brace));
SourceLocation LBraceLoc = Tok.getLocation();
PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, LBraceLoc,
"parsing function body");
// Save and reset current vtordisp stack if we have entered a C++ method body.
bool IsCXXMethod =
getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Sema::PragmaStackSentinelRAII
PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
// Do not enter a scope for the brace, as the arguments are in the same scope
// (the function body) as the body itself. Instead, just read the statement
// list and put it into a CompoundStmt for safe keeping.
StmtResult FnBody(ParseCompoundStatementBody());
// If the function body could not be parsed, make a bogus compoundstmt.
if (FnBody.isInvalid()) {
Sema::CompoundScopeRAII CompoundScope(Actions);
FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
}
BodyScope.Exit();
return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
}
/// ParseFunctionTryBlock - Parse a C++ function-try-block.
///
/// function-try-block:
/// 'try' ctor-initializer[opt] compound-statement handler-seq
///
Decl *Parser::ParseFunctionTryBlock(Decl *Decl, ParseScope &BodyScope) {
assert(Tok.is(tok::kw_try) && "Expected 'try'");
SourceLocation TryLoc = ConsumeToken();
PrettyDeclStackTraceEntry CrashInfo(Actions.Context, Decl, TryLoc,
"parsing function try block");
// Constructor initializer list?
if (Tok.is(tok::colon))
ParseConstructorInitializer(Decl);
else
Actions.ActOnDefaultCtorInitializers(Decl);
// Save and reset current vtordisp stack if we have entered a C++ method body.
bool IsCXXMethod =
getLangOpts().CPlusPlus && Decl && isa<CXXMethodDecl>(Decl);
Sema::PragmaStackSentinelRAII
PragmaStackSentinel(Actions, "InternalPragmaState", IsCXXMethod);
SourceLocation LBraceLoc = Tok.getLocation();
StmtResult FnBody(ParseCXXTryBlockCommon(TryLoc, /*FnTry*/true));
// If we failed to parse the try-catch, we just give the function an empty
// compound statement as the body.
if (FnBody.isInvalid()) {
Sema::CompoundScopeRAII CompoundScope(Actions);
FnBody = Actions.ActOnCompoundStmt(LBraceLoc, LBraceLoc, None, false);
}
BodyScope.Exit();
return Actions.ActOnFinishFunctionBody(Decl, FnBody.get());
}
bool Parser::trySkippingFunctionBody() {
assert(SkipFunctionBodies &&
"Should only be called when SkipFunctionBodies is enabled");
if (!PP.isCodeCompletionEnabled()) {
SkipFunctionBody();
return true;
}
// We're in code-completion mode. Skip parsing for all function bodies unless
// the body contains the code-completion point.
TentativeParsingAction PA(*this);
bool IsTryCatch = Tok.is(tok::kw_try);
CachedTokens Toks;
bool ErrorInPrologue = ConsumeAndStoreFunctionPrologue(Toks);
if (llvm::any_of(Toks, [](const Token &Tok) {
return Tok.is(tok::code_completion);
})) {
PA.Revert();
return false;
}
if (ErrorInPrologue) {
PA.Commit();
SkipMalformedDecl();
return true;
}
if (!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
PA.Revert();
return false;
}
while (IsTryCatch && Tok.is(tok::kw_catch)) {
if (!SkipUntil(tok::l_brace, StopAtCodeCompletion) ||
!SkipUntil(tok::r_brace, StopAtCodeCompletion)) {
PA.Revert();
return false;
}
}
PA.Commit();
return true;
}
/// ParseCXXTryBlock - Parse a C++ try-block.
///
/// try-block:
/// 'try' compound-statement handler-seq
///
StmtResult Parser::ParseCXXTryBlock() {
assert(Tok.is(tok::kw_try) && "Expected 'try'");
SourceLocation TryLoc = ConsumeToken();
return ParseCXXTryBlockCommon(TryLoc);
}
/// ParseCXXTryBlockCommon - Parse the common part of try-block and
/// function-try-block.
///
/// try-block:
/// 'try' compound-statement handler-seq
///
/// function-try-block:
/// 'try' ctor-initializer[opt] compound-statement handler-seq
///
/// handler-seq:
/// handler handler-seq[opt]
///
/// [Borland] try-block:
/// 'try' compound-statement seh-except-block
/// 'try' compound-statement seh-finally-block
///
StmtResult Parser::ParseCXXTryBlockCommon(SourceLocation TryLoc, bool FnTry) {
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
StmtResult TryBlock(ParseCompoundStatement(
/*isStmtExpr=*/false, Scope::DeclScope | Scope::TryScope |
Scope::CompoundStmtScope |
(FnTry ? Scope::FnTryCatchScope : 0)));
if (TryBlock.isInvalid())
return TryBlock;
// Borland allows SEH-handlers with 'try'
if ((Tok.is(tok::identifier) &&
Tok.getIdentifierInfo() == getSEHExceptKeyword()) ||
Tok.is(tok::kw___finally)) {
// TODO: Factor into common return ParseSEHHandlerCommon(...)
StmtResult Handler;
if(Tok.getIdentifierInfo() == getSEHExceptKeyword()) {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHExceptBlock(Loc);
}
else {
SourceLocation Loc = ConsumeToken();
Handler = ParseSEHFinallyBlock(Loc);
}
if(Handler.isInvalid())
return Handler;
return Actions.ActOnSEHTryBlock(true /* IsCXXTry */,
TryLoc,
TryBlock.get(),
Handler.get());
}
else {
StmtVector Handlers;
// C++11 attributes can't appear here, despite this context seeming
// statement-like.
DiagnoseAndSkipCXX11Attributes();
if (Tok.isNot(tok::kw_catch))
return StmtError(Diag(Tok, diag::err_expected_catch));
while (Tok.is(tok::kw_catch)) {
StmtResult Handler(ParseCXXCatchBlock(FnTry));
if (!Handler.isInvalid())
Handlers.push_back(Handler.get());
}
// Don't bother creating the full statement if we don't have any usable
// handlers.
if (Handlers.empty())
return StmtError();
return Actions.ActOnCXXTryBlock(TryLoc, TryBlock.get(), Handlers);
}
}
/// ParseCXXCatchBlock - Parse a C++ catch block, called handler in the standard
///
/// handler:
/// 'catch' '(' exception-declaration ')' compound-statement
///
/// exception-declaration:
/// attribute-specifier-seq[opt] type-specifier-seq declarator
/// attribute-specifier-seq[opt] type-specifier-seq abstract-declarator[opt]
/// '...'
///
StmtResult Parser::ParseCXXCatchBlock(bool FnCatch) {
assert(Tok.is(tok::kw_catch) && "Expected 'catch'");
SourceLocation CatchLoc = ConsumeToken();
BalancedDelimiterTracker T(*this, tok::l_paren);
if (T.expectAndConsume())
return StmtError();
// C++ 3.3.2p3:
// The name in a catch exception-declaration is local to the handler and
// shall not be redeclared in the outermost block of the handler.
ParseScope CatchScope(this, Scope::DeclScope | Scope::ControlScope |
Scope::CatchScope |
(FnCatch ? Scope::FnTryCatchScope : 0));
// exception-declaration is equivalent to '...' or a parameter-declaration
// without default arguments.
Decl *ExceptionDecl = nullptr;
if (Tok.isNot(tok::ellipsis)) {
ParsedAttributesWithRange Attributes(AttrFactory);
MaybeParseCXX11Attributes(Attributes);
DeclSpec DS(AttrFactory);
DS.takeAttributesFrom(Attributes);
if (ParseCXXTypeSpecifierSeq(DS))
return StmtError();
Declarator ExDecl(DS, DeclaratorContext::CXXCatch);
ParseDeclarator(ExDecl);
ExceptionDecl = Actions.ActOnExceptionDeclarator(getCurScope(), ExDecl);
} else
ConsumeToken();
T.consumeClose();
if (T.getCloseLocation().isInvalid())
return StmtError();
if (Tok.isNot(tok::l_brace))
return StmtError(Diag(Tok, diag::err_expected) << tok::l_brace);
// FIXME: Possible draft standard bug: attribute-specifier should be allowed?
StmtResult Block(ParseCompoundStatement());
if (Block.isInvalid())
return Block;
return Actions.ActOnCXXCatchBlock(CatchLoc, ExceptionDecl, Block.get());
}
void Parser::ParseMicrosoftIfExistsStatement(StmtVector &Stmts) {
IfExistsCondition Result;
if (ParseMicrosoftIfExistsCondition(Result))
return;
// Handle dependent statements by parsing the braces as a compound statement.
// This is not the same behavior as Visual C++, which don't treat this as a
// compound statement, but for Clang's type checking we can't have anything
// inside these braces escaping to the surrounding code.
if (Result.Behavior == IEB_Dependent) {
if (!Tok.is(tok::l_brace)) {
Diag(Tok, diag::err_expected) << tok::l_brace;
return;
}
StmtResult Compound = ParseCompoundStatement();
if (Compound.isInvalid())
return;
StmtResult DepResult = Actions.ActOnMSDependentExistsStmt(Result.KeywordLoc,
Result.IsIfExists,
Result.SS,
Result.Name,
Compound.get());
if (DepResult.isUsable())
Stmts.push_back(DepResult.get());
return;
}
BalancedDelimiterTracker Braces(*this, tok::l_brace);
if (Braces.consumeOpen()) {
Diag(Tok, diag::err_expected) << tok::l_brace;
return;
}
switch (Result.Behavior) {
case IEB_Parse:
// Parse the statements below.
break;
case IEB_Dependent:
llvm_unreachable("Dependent case handled above");
case IEB_Skip:
Braces.skipToEnd();
return;
}
// Condition is true, parse the statements.
while (Tok.isNot(tok::r_brace)) {
StmtResult R =
ParseStatementOrDeclaration(Stmts, ParsedStmtContext::Compound);
if (R.isUsable())
Stmts.push_back(R.get());
}
Braces.consumeClose();
}
bool Parser::ParseOpenCLUnrollHintAttribute(ParsedAttributes &Attrs) {
MaybeParseGNUAttributes(Attrs);
if (Attrs.empty())
return true;
if (Attrs.begin()->getKind() != ParsedAttr::AT_OpenCLUnrollHint)
return true;
if (!(Tok.is(tok::kw_for) || Tok.is(tok::kw_while) || Tok.is(tok::kw_do))) {
Diag(Tok, diag::err_opencl_unroll_hint_on_non_loop);
return false;
}
return true;
}
| gpl-3.0 |
scummvm/scummvm | devtools/create_engine/files/metaengine.cpp | 2 | 2287 | /* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "common/translation.h"
#include "xyzzy/metaengine.h"
#include "xyzzy/detection.h"
#include "xyzzy/xyzzy.h"
namespace Xyzzy {
static const ADExtraGuiOptionsMap optionsList[] = {
{
GAMEOPTION_ORIGINAL_SAVELOAD,
{
_s("Use original save/load screens"),
_s("Use the original save/load screens instead of the ScummVM ones"),
"original_menus",
false,
0,
0
}
},
AD_EXTRA_GUI_OPTIONS_TERMINATOR
};
} // End of namespace Xyzzy
const char *XyzzyMetaEngine::getName() const {
return "xyzzy";
}
const ADExtraGuiOptionsMap *XyzzyMetaEngine::getAdvancedExtraGuiOptions() const {
return Xyzzy::optionsList;
}
Common::Error XyzzyMetaEngine::createInstance(OSystem *syst, Engine **engine, const ADGameDescription *desc) const {
*engine = new Xyzzy::XyzzyEngine(syst, desc);
return Common::kNoError;
}
bool XyzzyMetaEngine::hasFeature(MetaEngineFeature f) const {
return
(f == kSavesUseExtendedFormat) ||
(f == kSimpleSavesNames) ||
(f == kSupportsListSaves) ||
(f == kSupportsDeleteSave) ||
(f == kSavesSupportMetaInfo) ||
(f == kSavesSupportThumbnail) ||
(f == kSavesSupportCreationDate) ||
(f == kSavesSupportPlayTime) ||
(f == kSupportsLoadingDuringStartup);
}
#if PLUGIN_ENABLED_DYNAMIC(XYZZY)
REGISTER_PLUGIN_DYNAMIC(XYZZY, PLUGIN_TYPE_ENGINE, XyzzyMetaEngine);
#else
REGISTER_PLUGIN_STATIC(XYZZY, PLUGIN_TYPE_ENGINE, XyzzyMetaEngine);
#endif
| gpl-3.0 |
ACRMGroup/bioplib | src/KnownSeqLen.c | 3 | 3589 | /************************************************************************/
/**
\file KnownSeqLen.c
\version V1.11
\date 07.07.14
\brief
\copyright (c) UCL / Dr. Andrew C. R. Martin 1993-2014
\author Dr. Andrew C. R. Martin
\par
Institute of Structural & Molecular Biology,
University College London,
Gower Street,
London.
WC1E 6BT.
\par
andrew@bioinf.org.uk
andrew.martin@ucl.ac.uk
**************************************************************************
This code is NOT IN THE PUBLIC DOMAIN, but it may be copied
according to the conditions laid out in the accompanying file
COPYING.DOC.
The code may be modified as required, but any modifications must be
documented so that the person responsible can be identified.
The code may not be sold commercially or included as part of a
commercial product except as described in the file COPYING.DOC.
**************************************************************************
Description:
============
**************************************************************************
Usage:
======
**************************************************************************
Revision History:
=================
- V1.0 29.09.92 Original
- V1.1 07.06.93 Corrected allocation
- V1.2 18.06.93 Handles multi-chains and skips NTER and CTER residues.
Added SplitSeq()
- V1.3 09.07.93 SplitSeq() cleans up properly if allocation failed
- V1.4 11.05.94 Added TrueSeqLen()
- V1.5 13.05.94 Fixed bug in PDB2Seq().
Added KnownSeqLen().
- V1.6 07.09.94 Fixed allocation bug in SplitSeq()
- V1.7 19.07.95 Added check for ATOM records
- V1.8 24.01.96 Fixed bug when no ATOM records in linked list
Returns a blank string
- V1.9 26.08.97 Renamed DoPDB2Seq() with handling of Asx/Glx and
protein-only. Added macros to recreate the
old PDB2Seq() interface and similar new calls
- V1.10 02.10.00 Added NoX option
- V1.11 07.07.14 Use bl prefix for functions By: CTP
*************************************************************************/
/* Doxygen
-------
#GROUP Handling Sequence Data
#SUBGROUP Obtaining information
#FUNCTION blKnownSeqLen()
Scans a 1-letter code sequence and calculate the length without
`-', ` ' or '?' residues
*/
/************************************************************************/
/* Includes
*/
/************************************************************************/
/* Defines and macros
*/
/************************************************************************/
/* Globals
*/
/************************************************************************/
/* Prototypes
*/
/************************************************************************/
/*>int blKnownSeqLen(char *sequence)
---------------------------------
*//**
\param[in] *sequence A sequence containing deletions
\return Length without deletions
Scans a 1-letter code sequence and calculate the length without
`-', ` ' or '?' residues
- 13.05.94 Original By: ACRM
- 07.07.14 Use bl prefix for functions By: CTP
*/
int blKnownSeqLen(char *sequence)
{
int length = 0,
i = 0;
for(i=0; sequence[i]; i++)
{
if(sequence[i] != '-' && sequence[i] != ' ' && sequence[i] != '?')
length++;
}
return(length);
}
| gpl-3.0 |
rosswhitfield/mantid | Framework/MDAlgorithms/src/MaskMD.cpp | 3 | 9496 | // Mantid Repository : https://github.com/mantidproject/mantid
//
// Copyright © 2018 ISIS Rutherford Appleton Laboratory UKRI,
// NScD Oak Ridge National Laboratory, European Spallation Source,
// Institut Laue - Langevin & CSNS, Institute of High Energy Physics, CAS
// SPDX - License - Identifier: GPL - 3.0 +
#include "MantidMDAlgorithms/MaskMD.h"
#include "MantidAPI/IMDWorkspace.h"
#include "MantidGeometry/MDGeometry/MDBoxImplicitFunction.h"
#include "MantidKernel/ArrayProperty.h"
#include "MantidKernel/MandatoryValidator.h"
#include <algorithm>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
using namespace Mantid::Kernel;
using namespace Mantid::API;
using namespace Mantid::Geometry;
using boost::regex;
namespace Mantid::MDAlgorithms {
/*
* The list of dimension names often looks like "[H,0,0],[0,K,0]" with "[H,0,0]"
* being the first dimension but getProperty returns a vector of
* the string split on every comma
* This function parses the string, and does not split on commas within brackets
*/
std::vector<std::string> parseDimensionNames(const std::string &names_string) {
// This regex has two parts which are separated by the "|" (or)
// The first part matches anything which is bounded by square brackets
// unless they contain square brackets (so that it only matches inner pairs)
// The second part matches anything that doesn't contain a comma
// NB, the order of the two parts matters
regex expression(R"(\[([^\[]*)\]|[^,]+)");
boost::sregex_token_iterator iter(names_string.begin(), names_string.end(), expression, 0);
boost::sregex_token_iterator end;
std::vector<std::string> names_result(iter, end);
return names_result;
}
// Register the algorithm into the AlgorithmFactory
DECLARE_ALGORITHM(MaskMD)
/// Local type to group min, max extents with a dimension index.
struct InputArgument {
double min, max;
size_t index;
};
/// Comparator to allow sorting by dimension index.
struct LessThanIndex {
bool operator()(const InputArgument &a, const InputArgument &b) const { return a.index < b.index; }
};
//----------------------------------------------------------------------------------------------
/// Algorithm's name for identification. @see Algorithm::name
const std::string MaskMD::name() const { return "MaskMD"; }
/// Algorithm's version for identification. @see Algorithm::version
int MaskMD::version() const { return 1; }
/// Algorithm's category for identification. @see Algorithm::category
const std::string MaskMD::category() const { return "MDAlgorithms\\Transforms"; }
//----------------------------------------------------------------------------------------------
//----------------------------------------------------------------------------------------------
/** Initialize the algorithm's properties.
*/
void MaskMD::init() {
declareProperty(std::make_unique<PropertyWithValue<bool>>("ClearExistingMasks", true, Direction::Input),
"Clears any existing masks before applying the provided masking.");
declareProperty(std::make_unique<WorkspaceProperty<IMDWorkspace>>("Workspace", "", Direction::InOut),
"An input/output workspace.");
declareProperty(std::make_unique<ArrayProperty<std::string>>(
"Dimensions", std::make_shared<MandatoryValidator<std::vector<std::string>>>(), Direction::Input),
"Dimension ids/names all comma separated.\n"
"According to the dimensionality of the workspace, these names will be "
"grouped,\n"
"so the number of entries must be n*(number of dimensions in the "
"workspace).");
declareProperty(std::make_unique<ArrayProperty<double>>(
"Extents", std::make_shared<MandatoryValidator<std::vector<double>>>(), Direction::Input),
"Extents {min, max} corresponding to each of the dimensions specified, "
"according to the order those identifies have been specified.");
}
/**
Free helper function.
try to fetch the workspace index.
@param ws : The workspace to find the dimensions in
@param candidateNameOrId: Either the name or the id of a dimension in the
workspace.
@return the index of the dimension in the workspace.
@throws runtime_error if the requested dimension is unknown either by id, or by
name in the workspace.
*/
size_t tryFetchDimensionIndex(const Mantid::API::IMDWorkspace_sptr &ws, const std::string &candidateNameOrId) {
size_t dimWorkspaceIndex;
try {
dimWorkspaceIndex = ws->getDimensionIndexById(candidateNameOrId);
} catch (const std::runtime_error &) {
// this will throw if the name is unknown.
dimWorkspaceIndex = ws->getDimensionIndexByName(candidateNameOrId);
}
return dimWorkspaceIndex;
}
//----------------------------------------------------------------------------------------------
/** Execute the algorithm.
*/
void MaskMD::exec() {
IMDWorkspace_sptr ws = getProperty("Workspace");
std::string dimensions_string = getPropertyValue("Dimensions");
std::vector<double> extents = getProperty("Extents");
// Dimension names may contain brackets with commas (i.e. [H,0,0])
// so getProperty would return an incorrect vector of names;
// instead get the string and parse it here
std::vector<std::string> dimensions = parseDimensionNames(dimensions_string);
// Report what dimension names were found
g_log.debug() << "Dimension names parsed as: \n";
for (const auto &name : dimensions) {
g_log.debug() << name << '\n';
}
size_t nDims = ws->getNumDims();
size_t nDimensionIds = dimensions.size();
size_t nGroups = nDimensionIds / nDims;
bool bClearExistingMasks = getProperty("ClearExistingMasks");
if (bClearExistingMasks) {
ws->clearMDMasking();
}
this->interruption_point();
this->progress(0.0);
// Explicitly cast nGroups and group to double to avoid compiler warnings
// loss of precision does not matter as we are only using the result
// for reporting algorithm progress
const auto nGroups_double = static_cast<double>(nGroups);
// Loop over all groups
for (size_t group = 0; group < nGroups; ++group) {
std::vector<InputArgument> arguments(nDims);
// Loop over all arguments within the group. and construct InputArguments
// for sorting.
for (size_t i = 0; i < nDims; ++i) {
size_t index = i + (group * nDims);
InputArgument &arg = arguments[i];
// Try to get the index of the dimension in the workspace.
arg.index = tryFetchDimensionIndex(ws, dimensions[index]);
arg.min = extents[index * 2];
arg.max = extents[(index * 2) + 1];
}
// Sort all the inputs by the dimension index. Without this it will not be
// possible to construct the MDImplicit function property.
LessThanIndex comparator;
std::sort(arguments.begin(), arguments.end(), comparator);
// Create inputs for a box implicit function
VMD mins(nDims);
VMD maxs(nDims);
for (size_t i = 0; i < nDims; ++i) {
mins[i] = float(arguments[i].min);
maxs[i] = float(arguments[i].max);
}
// Add new masking.
ws->setMDMasking(std::make_unique<MDBoxImplicitFunction>(mins, maxs));
this->interruption_point();
auto group_double = static_cast<double>(group);
this->progress(group_double / nGroups_double);
}
this->progress(1.0); // Ensure algorithm progress is reported as complete
}
std::map<std::string, std::string> MaskMD::validateInputs() {
// Create the map
std::map<std::string, std::string> validation_output;
// Get properties to validate
IMDWorkspace_sptr ws = getProperty("Workspace");
std::string dimensions_string = getPropertyValue("Dimensions");
std::vector<double> extents = getProperty("Extents");
std::vector<std::string> dimensions = parseDimensionNames(dimensions_string);
std::stringstream messageStream;
// Check named dimensions can be found in workspace
for (const auto &dimension_name : dimensions) {
try {
tryFetchDimensionIndex(ws, dimension_name);
} catch (const std::runtime_error &) {
messageStream << "Dimension '" << dimension_name << "' not found. ";
}
}
if (messageStream.rdbuf()->in_avail() != 0) {
validation_output["Dimensions"] = messageStream.str();
messageStream.str(std::string());
}
size_t nDims = ws->getNumDims();
size_t nDimensionIds = dimensions.size();
// Check cardinality on names/ids
if (nDimensionIds % nDims != 0) {
messageStream << "Number of dimension ids/names must be n * " << nDims << ". The following names were given: ";
for (const auto &name : dimensions) {
messageStream << name << ", ";
}
validation_output["Dimensions"] = messageStream.str();
messageStream.str(std::string());
}
// Check cardinality on extents
if (extents.size() != (2 * dimensions.size())) {
messageStream << "Number of extents must be " << 2 * dimensions.size() << ". ";
validation_output["Extents"] = messageStream.str();
}
// Check extent value provided.
for (size_t i = 0; (i < nDimensionIds) && ((i * 2 + 1) < extents.size()); ++i) {
double min = extents[i * 2];
double max = extents[(i * 2) + 1];
if (min > max) {
messageStream << "Cannot have minimum extents " << min << " larger than maximum extents " << max << ". ";
validation_output["Extents"] = messageStream.str();
}
}
return validation_output;
}
} // namespace Mantid::MDAlgorithms
| gpl-3.0 |
FreeScienceCommunity/remote-desktop-clients | eclipse_projects/Opaque/jni/src/gtk/spice-channel.c | 3 | 87376 | /* -*- Mode: C; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
Copyright (C) 2010 Red Hat, Inc.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#include "spice-client.h"
#include "spice-common.h"
#include "glib-compat.h"
#include "spice-channel-priv.h"
#include "spice-session-priv.h"
#include "spice-marshal.h"
#include "bio-gsocket.h"
#include <openssl/rsa.h>
#include <openssl/evp.h>
#include <openssl/x509.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509v3.h>
#ifdef HAVE_SYS_SOCKET_H
#include <sys/socket.h>
#endif
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#include <netinet/tcp.h> // TCP_NODELAY
#endif
#ifdef HAVE_ARPA_INET_H
#include <arpa/inet.h>
#endif
#include <ctype.h>
#include "gio-coroutine.h"
static void spice_channel_handle_msg(SpiceChannel *channel, SpiceMsgIn *msg);
static void spice_channel_write_msg(SpiceChannel *channel, SpiceMsgOut *out);
static void spice_channel_send_link(SpiceChannel *channel);
static void channel_disconnect(SpiceChannel *channel);
static void channel_reset(SpiceChannel *channel, gboolean migrating);
static void spice_channel_reset_capabilities(SpiceChannel *channel);
static void spice_channel_send_migration_handshake(SpiceChannel *channel);
/**
* SECTION:spice-channel
* @short_description: the base channel class
* @title: Spice Channel
* @section_id:
* @see_also: #SpiceSession, #SpiceMainChannel and other channels
* @stability: Stable
* @include: spice-channel.h
*
* #SpiceChannel is the base class for the different kind of Spice
* channel connections, such as #SpiceMainChannel, or
* #SpiceInputsChannel.
*/
/* ------------------------------------------------------------------ */
/* gobject glue */
#define SPICE_CHANNEL_GET_PRIVATE(obj) \
(G_TYPE_INSTANCE_GET_PRIVATE ((obj), SPICE_TYPE_CHANNEL, SpiceChannelPrivate))
G_DEFINE_TYPE(SpiceChannel, spice_channel, G_TYPE_OBJECT);
/* Properties */
enum {
PROP_0,
PROP_SESSION,
PROP_CHANNEL_TYPE,
PROP_CHANNEL_ID,
PROP_TOTAL_READ_BYTES,
};
/* Signals */
enum {
SPICE_CHANNEL_EVENT,
SPICE_CHANNEL_OPEN_FD,
SPICE_CHANNEL_LAST_SIGNAL,
};
static guint signals[SPICE_CHANNEL_LAST_SIGNAL];
static void spice_channel_iterate_write(SpiceChannel *channel);
static void spice_channel_iterate_read(SpiceChannel *channel);
static void spice_channel_init(SpiceChannel *channel)
{
SpiceChannelPrivate *c;
c = channel->priv = SPICE_CHANNEL_GET_PRIVATE(channel);
c->out_serial = 1;
c->in_serial = 1;
c->fd = -1;
strcpy(c->name, "?");
c->caps = g_array_new(FALSE, TRUE, sizeof(guint32));
c->common_caps = g_array_new(FALSE, TRUE, sizeof(guint32));
c->remote_caps = g_array_new(FALSE, TRUE, sizeof(guint32));
c->remote_common_caps = g_array_new(FALSE, TRUE, sizeof(guint32));
spice_channel_set_common_capability(channel, SPICE_COMMON_CAP_PROTOCOL_AUTH_SELECTION);
spice_channel_set_common_capability(channel, SPICE_COMMON_CAP_MINI_HEADER);
g_queue_init(&c->xmit_queue);
STATIC_MUTEX_INIT(c->xmit_queue_lock);
}
static void spice_channel_constructed(GObject *gobject)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
const char *desc = spice_channel_type_to_string(c->channel_type);
snprintf(c->name, sizeof(c->name), "%s-%d:%d",
desc, c->channel_type, c->channel_id);
CHANNEL_DEBUG(channel, "%s", __FUNCTION__);
const char *disabled = g_getenv("SPICE_DISABLE_CHANNELS");
if (disabled && strstr(disabled, desc))
c->disable_channel_msg = TRUE;
spice_session_channel_new(c->session, channel);
/* Chain up to the parent class */
if (G_OBJECT_CLASS(spice_channel_parent_class)->constructed)
G_OBJECT_CLASS(spice_channel_parent_class)->constructed(gobject);
}
static void spice_channel_dispose(GObject *gobject)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "%s %p", __FUNCTION__, gobject);
if (c->session)
spice_session_channel_destroy(c->session, channel);
spice_channel_disconnect(channel, SPICE_CHANNEL_CLOSED);
if (c->session) {
g_object_unref(c->session);
c->session = NULL;
}
/* Chain up to the parent class */
if (G_OBJECT_CLASS(spice_channel_parent_class)->dispose)
G_OBJECT_CLASS(spice_channel_parent_class)->dispose(gobject);
}
static void spice_channel_finalize(GObject *gobject)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "%s %p", __FUNCTION__, gobject);
g_idle_remove_by_data(gobject);
STATIC_MUTEX_CLEAR(c->xmit_queue_lock);
if (c->caps)
g_array_free(c->caps, TRUE);
if (c->common_caps)
g_array_free(c->common_caps, TRUE);
if (c->remote_caps)
g_array_free(c->remote_caps, TRUE);
if (c->remote_common_caps)
g_array_free(c->remote_common_caps, TRUE);
/* Chain up to the parent class */
if (G_OBJECT_CLASS(spice_channel_parent_class)->finalize)
G_OBJECT_CLASS(spice_channel_parent_class)->finalize(gobject);
}
static void spice_channel_get_property(GObject *gobject,
guint prop_id,
GValue *value,
GParamSpec *pspec)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
switch (prop_id) {
case PROP_SESSION:
g_value_set_object(value, c->session);
break;
case PROP_CHANNEL_TYPE:
g_value_set_int(value, c->channel_type);
break;
case PROP_CHANNEL_ID:
g_value_set_int(value, c->channel_id);
break;
case PROP_TOTAL_READ_BYTES:
g_value_set_ulong(value, c->total_read_bytes);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(gobject, prop_id, pspec);
break;
}
}
G_GNUC_INTERNAL
gint spice_channel_get_channel_id(SpiceChannel *channel)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
g_return_val_if_fail(c != NULL, 0);
return c->channel_id;
}
G_GNUC_INTERNAL
gint spice_channel_get_channel_type(SpiceChannel *channel)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
g_return_val_if_fail(c != NULL, 0);
return c->channel_type;
}
static void spice_channel_set_property(GObject *gobject,
guint prop_id,
const GValue *value,
GParamSpec *pspec)
{
SpiceChannel *channel = SPICE_CHANNEL(gobject);
SpiceChannelPrivate *c = channel->priv;
switch (prop_id) {
case PROP_SESSION:
c->session = g_value_dup_object(value);
break;
case PROP_CHANNEL_TYPE:
c->channel_type = g_value_get_int(value);
break;
case PROP_CHANNEL_ID:
c->channel_id = g_value_get_int(value);
break;
default:
G_OBJECT_WARN_INVALID_PROPERTY_ID(gobject, prop_id, pspec);
break;
}
}
static void spice_channel_class_init(SpiceChannelClass *klass)
{
GObjectClass *gobject_class = G_OBJECT_CLASS (klass);
klass->iterate_write = spice_channel_iterate_write;
klass->iterate_read = spice_channel_iterate_read;
klass->channel_disconnect = channel_disconnect;
klass->channel_reset = channel_reset;
gobject_class->constructed = spice_channel_constructed;
gobject_class->dispose = spice_channel_dispose;
gobject_class->finalize = spice_channel_finalize;
gobject_class->get_property = spice_channel_get_property;
gobject_class->set_property = spice_channel_set_property;
klass->handle_msg = spice_channel_handle_msg;
g_object_class_install_property
(gobject_class, PROP_SESSION,
g_param_spec_object("spice-session",
"Spice session",
"",
SPICE_TYPE_SESSION,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY |
G_PARAM_STATIC_STRINGS));
g_object_class_install_property
(gobject_class, PROP_CHANNEL_TYPE,
g_param_spec_int("channel-type",
"Channel type",
"",
-1, INT_MAX, -1,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY |
G_PARAM_STATIC_STRINGS));
g_object_class_install_property
(gobject_class, PROP_CHANNEL_ID,
g_param_spec_int("channel-id",
"Channel ID",
"",
-1, INT_MAX, -1,
G_PARAM_READWRITE |
G_PARAM_CONSTRUCT_ONLY |
G_PARAM_STATIC_STRINGS));
g_object_class_install_property
(gobject_class, PROP_TOTAL_READ_BYTES,
g_param_spec_ulong("total-read-bytes",
"Total read bytes",
"",
0, G_MAXULONG, 0,
G_PARAM_READABLE |
G_PARAM_STATIC_STRINGS));
/**
* SpiceChannel::channel-event:
* @channel: the channel that emitted the signal
* @event: a #SpiceChannelEvent
*
* The #SpiceChannel::channel-event signal is emitted when the
* state of the connection change.
**/
signals[SPICE_CHANNEL_EVENT] =
g_signal_new("channel-event",
G_OBJECT_CLASS_TYPE(gobject_class),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET(SpiceChannelClass, channel_event),
NULL, NULL,
g_cclosure_marshal_VOID__ENUM,
G_TYPE_NONE,
1,
SPICE_TYPE_CHANNEL_EVENT);
/**
* SpiceChannel::open-fd:
* @channel: the channel that emitted the signal
* @with_tls: wether TLS connection is requested
*
* The #SpiceChannel::open-fd signal is emitted when a new
* connection is requested. This signal is emitted when the
* connection is made with spice_session_open_fd().
**/
signals[SPICE_CHANNEL_OPEN_FD] =
g_signal_new("open-fd",
G_OBJECT_CLASS_TYPE(gobject_class),
G_SIGNAL_RUN_FIRST,
G_STRUCT_OFFSET(SpiceChannelClass, open_fd),
NULL, NULL,
g_cclosure_marshal_VOID__INT,
G_TYPE_NONE,
1,
G_TYPE_INT);
g_type_class_add_private(klass, sizeof(SpiceChannelPrivate));
SSL_library_init();
SSL_load_error_strings();
}
/* ---------------------------------------------------------------- */
/* private header api */
static inline void spice_header_set_msg_type(uint8_t *header, gboolean is_mini_header,
uint16_t type)
{
if (is_mini_header) {
((SpiceMiniDataHeader *)header)->type = type;
} else {
((SpiceDataHeader *)header)->type = type;
}
}
static inline void spice_header_set_msg_size(uint8_t *header, gboolean is_mini_header,
uint32_t size)
{
if (is_mini_header) {
((SpiceMiniDataHeader *)header)->size = size;
} else {
((SpiceDataHeader *)header)->size = size;
}
}
G_GNUC_INTERNAL
uint16_t spice_header_get_msg_type(uint8_t *header, gboolean is_mini_header)
{
if (is_mini_header) {
return ((SpiceMiniDataHeader *)header)->type;
} else {
return ((SpiceDataHeader *)header)->type;
}
}
G_GNUC_INTERNAL
uint32_t spice_header_get_msg_size(uint8_t *header, gboolean is_mini_header)
{
if (is_mini_header) {
return ((SpiceMiniDataHeader *)header)->size;
} else {
return ((SpiceDataHeader *)header)->size;
}
}
static inline int spice_header_get_header_size(gboolean is_mini_header)
{
return is_mini_header ? sizeof(SpiceMiniDataHeader) : sizeof(SpiceDataHeader);
}
static inline void spice_header_set_msg_serial(uint8_t *header, gboolean is_mini_header,
uint64_t serial)
{
if (!is_mini_header) {
((SpiceDataHeader *)header)->serial = serial;
}
}
static inline void spice_header_reset_msg_sub_list(uint8_t *header, gboolean is_mini_header)
{
if (!is_mini_header) {
((SpiceDataHeader *)header)->sub_list = 0;
}
}
static inline uint64_t spice_header_get_in_msg_serial(SpiceMsgIn *in)
{
SpiceChannelPrivate *c = in->channel->priv;
uint8_t *header = in->header;
if (c->use_mini_header) {
return c->in_serial;
} else {
return ((SpiceDataHeader *)header)->serial;
}
}
static inline uint64_t spice_header_get_out_msg_serial(SpiceMsgOut *out)
{
SpiceChannelPrivate *c = out->channel->priv;
if (c->use_mini_header) {
return c->out_serial;
} else {
return ((SpiceDataHeader *)out->header)->serial;
}
}
static inline uint32_t spice_header_get_msg_sub_list(uint8_t *header, gboolean is_mini_header)
{
if (is_mini_header) {
return 0;
} else {
return ((SpiceDataHeader *)header)->sub_list;
}
}
/* ---------------------------------------------------------------- */
/* private msg api */
G_GNUC_INTERNAL
SpiceMsgIn *spice_msg_in_new(SpiceChannel *channel)
{
SpiceMsgIn *in;
g_return_val_if_fail(channel != NULL, NULL);
in = g_slice_new0(SpiceMsgIn);
in->refcount = 1;
in->channel = channel;
return in;
}
G_GNUC_INTERNAL
SpiceMsgIn *spice_msg_in_sub_new(SpiceChannel *channel, SpiceMsgIn *parent,
SpiceSubMessage *sub)
{
SpiceMsgIn *in;
g_return_val_if_fail(channel != NULL, NULL);
in = spice_msg_in_new(channel);
spice_header_set_msg_type(in->header, channel->priv->use_mini_header, sub->type);
spice_header_set_msg_size(in->header, channel->priv->use_mini_header, sub->size);
in->data = (uint8_t*)(sub+1);
in->dpos = sub->size;
in->parent = parent;
spice_msg_in_ref(parent);
return in;
}
G_GNUC_INTERNAL
void spice_msg_in_ref(SpiceMsgIn *in)
{
g_return_if_fail(in != NULL);
in->refcount++;
}
G_GNUC_INTERNAL
void spice_msg_in_unref(SpiceMsgIn *in)
{
g_return_if_fail(in != NULL);
in->refcount--;
if (in->refcount > 0)
return;
if (in->parsed)
in->pfree(in->parsed);
if (in->parent) {
spice_msg_in_unref(in->parent);
} else {
free(in->data);
}
g_slice_free(SpiceMsgIn, in);
}
G_GNUC_INTERNAL
int spice_msg_in_type(SpiceMsgIn *in)
{
g_return_val_if_fail(in != NULL, -1);
return spice_header_get_msg_type(in->header, in->channel->priv->use_mini_header);
}
G_GNUC_INTERNAL
void *spice_msg_in_parsed(SpiceMsgIn *in)
{
g_return_val_if_fail(in != NULL, NULL);
return in->parsed;
}
G_GNUC_INTERNAL
void *spice_msg_in_raw(SpiceMsgIn *in, int *len)
{
g_return_val_if_fail(in != NULL, NULL);
g_return_val_if_fail(len != NULL, NULL);
*len = in->dpos;
return in->data;
}
static void hexdump(const char *prefix, unsigned char *data, int len)
{
int i;
for (i = 0; i < len; i++) {
if (i % 16 == 0)
fprintf(stderr, "%s:", prefix);
if (i % 4 == 0)
fprintf(stderr, " ");
fprintf(stderr, " %02x", data[i]);
if (i % 16 == 15)
fprintf(stderr, "\n");
}
if (i % 16 != 0)
fprintf(stderr, "\n");
}
G_GNUC_INTERNAL
void spice_msg_in_hexdump(SpiceMsgIn *in)
{
SpiceChannelPrivate *c = in->channel->priv;
fprintf(stderr, "--\n<< hdr: %s serial %" PRIu64 " type %d size %d sub-list %d\n",
c->name, spice_header_get_in_msg_serial(in),
spice_header_get_msg_type(in->header, c->use_mini_header),
spice_header_get_msg_size(in->header, c->use_mini_header),
spice_header_get_msg_sub_list(in->header, c->use_mini_header));
hexdump("<< msg", in->data, in->dpos);
}
G_GNUC_INTERNAL
void spice_msg_out_hexdump(SpiceMsgOut *out, unsigned char *data, int len)
{
SpiceChannelPrivate *c = out->channel->priv;
fprintf(stderr, "--\n>> hdr: %s serial %" PRIu64 " type %d size %d sub-list %d\n",
c->name,
spice_header_get_out_msg_serial(out),
spice_header_get_msg_type(out->header, c->use_mini_header),
spice_header_get_msg_size(out->header, c->use_mini_header),
spice_header_get_msg_sub_list(out->header, c->use_mini_header));
hexdump(">> msg", data, len);
}
static gboolean msg_check_read_only (int channel_type, int msg_type)
{
if (msg_type < 100) // those are the common messages
return FALSE;
switch (channel_type) {
/* messages allowed to be sent in read-only mode */
case SPICE_CHANNEL_MAIN:
switch (msg_type) {
case SPICE_MSGC_MAIN_CLIENT_INFO:
case SPICE_MSGC_MAIN_MIGRATE_CONNECTED:
case SPICE_MSGC_MAIN_MIGRATE_CONNECT_ERROR:
case SPICE_MSGC_MAIN_ATTACH_CHANNELS:
case SPICE_MSGC_MAIN_MIGRATE_END:
return FALSE;
}
break;
case SPICE_CHANNEL_DISPLAY:
return FALSE;
}
return TRUE;
}
G_GNUC_INTERNAL
SpiceMsgOut *spice_msg_out_new(SpiceChannel *channel, int type)
{
SpiceChannelPrivate *c = channel->priv;
SpiceMsgOut *out;
g_return_val_if_fail(c != NULL, NULL);
out = g_slice_new0(SpiceMsgOut);
out->refcount = 1;
out->channel = channel;
out->ro_check = msg_check_read_only(c->channel_type, type);
out->marshallers = c->marshallers;
out->marshaller = spice_marshaller_new();
out->header = spice_marshaller_reserve_space(out->marshaller,
spice_header_get_header_size(c->use_mini_header));
spice_marshaller_set_base(out->marshaller, spice_header_get_header_size(c->use_mini_header));
spice_header_set_msg_type(out->header, c->use_mini_header, type);
spice_header_set_msg_serial(out->header, c->use_mini_header, c->out_serial);
spice_header_reset_msg_sub_list(out->header, c->use_mini_header);
c->out_serial++;
return out;
}
G_GNUC_INTERNAL
void spice_msg_out_ref(SpiceMsgOut *out)
{
g_return_if_fail(out != NULL);
out->refcount++;
}
G_GNUC_INTERNAL
void spice_msg_out_unref(SpiceMsgOut *out)
{
g_return_if_fail(out != NULL);
out->refcount--;
if (out->refcount > 0)
return;
spice_marshaller_destroy(out->marshaller);
g_slice_free(SpiceMsgOut, out);
}
/* system context */
static gboolean spice_channel_idle_wakeup(gpointer user_data)
{
SpiceChannel *channel = SPICE_CHANNEL(user_data);
SpiceChannelPrivate *c = channel->priv;
/*
* Note:
*
* - This must be done before the wakeup as that may eventually
* call channel_reset() which checks this.
* - The lock calls are really necessary, this fixes the following race:
* 1) usb-event-thread calls spice_msg_out_send()
* 2) spice_msg_out_send calls g_timeout_add_full(...)
* 3) we run, set xmit_queue_wakeup_id to 0
* 4) spice_msg_out_send stores the result of g_timeout_add_full() in
* xmit_queue_wakeup_id, overwriting the 0 we just stored
* 5) xmit_queue_wakeup_id now says there is a wakeup pending which is
* false
*/
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
c->xmit_queue_wakeup_id = 0;
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
spice_channel_wakeup(channel, FALSE);
return FALSE;
}
/* any context (system/co-routine/usb-event-thread) */
G_GNUC_INTERNAL
void spice_msg_out_send(SpiceMsgOut *out)
{
SpiceChannelPrivate *c;
gboolean was_empty;
g_return_if_fail(out != NULL);
g_return_if_fail(out->channel != NULL);
c = out->channel->priv;
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
if (c->xmit_queue_blocked) {
g_warning("message queue is blocked, dropping message");
goto end;
}
was_empty = g_queue_is_empty(&c->xmit_queue);
g_queue_push_tail(&c->xmit_queue, out);
/* One wakeup is enough to empty the entire queue -> only do a wakeup
if the queue was empty, and there isn't one pending already. */
if (was_empty && !c->xmit_queue_wakeup_id) {
c->xmit_queue_wakeup_id =
/* Use g_timeout_add_full so that can specify the priority */
g_timeout_add_full(G_PRIORITY_HIGH, 0,
spice_channel_idle_wakeup,
out->channel, NULL);
}
end:
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
}
/* coroutine context */
G_GNUC_INTERNAL
void spice_msg_out_send_internal(SpiceMsgOut *out)
{
g_return_if_fail(out != NULL);
spice_channel_write_msg(out->channel, out);
}
/* ---------------------------------------------------------------- */
struct SPICE_CHANNEL_EVENT {
SpiceChannelEvent event;
};
/* main context */
static void do_emit_main_context(GObject *object, int signum, gpointer params)
{
switch (signum) {
case SPICE_CHANNEL_EVENT: {
struct SPICE_CHANNEL_EVENT *p = params;
g_signal_emit(object, signals[signum], 0, p->event);
break;
}
case SPICE_CHANNEL_OPEN_FD:
g_warning("this signal is only sent directly from main context");
break;
default:
g_warn_if_reached();
}
}
/*
* Write all 'data' of length 'datalen' bytes out to
* the wire
*/
/* coroutine context */
static void spice_channel_flush_wire(SpiceChannel *channel,
const void *data,
size_t datalen)
{
SpiceChannelPrivate *c = channel->priv;
const char *ptr = data;
size_t offset = 0;
GIOCondition cond;
while (offset < datalen) {
int ret;
if (c->has_error) return;
cond = 0;
if (c->tls) {
ret = SSL_write(c->ssl, ptr+offset, datalen-offset);
if (ret < 0) {
ret = SSL_get_error(c->ssl, ret);
if (ret == SSL_ERROR_WANT_READ)
cond |= G_IO_IN;
if (ret == SSL_ERROR_WANT_WRITE)
cond |= G_IO_OUT;
ret = -1;
}
} else {
GError *error = NULL;
ret = g_socket_send(c->sock, ptr+offset, datalen-offset,
NULL, &error);
if (ret < 0) {
if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
cond = G_IO_OUT;
} else {
CHANNEL_DEBUG(channel, "Send error %s", error->message);
}
g_clear_error(&error);
ret = -1;
}
}
if (ret == -1) {
if (cond != 0) {
g_coroutine_socket_wait(&c->coroutine, c->sock, cond);
continue;
} else {
CHANNEL_DEBUG(channel, "Closing the channel: spice_channel_flush %d", errno);
c->has_error = TRUE;
return;
}
}
if (ret == 0) {
CHANNEL_DEBUG(channel, "Closing the connection: spice_channel_flush");
c->has_error = TRUE;
return;
}
offset += ret;
}
}
#if HAVE_SASL
/*
* Encode all buffered data, write all encrypted data out
* to the wire
*/
static void spice_channel_flush_sasl(SpiceChannel *channel, const void *data, size_t len)
{
SpiceChannelPrivate *c = channel->priv;
const char *output;
unsigned int outputlen;
int err;
err = sasl_encode(c->sasl_conn, data, len, &output, &outputlen);
if (err != SASL_OK) {
g_warning ("Failed to encode SASL data %s",
sasl_errstring(err, NULL, NULL));
c->has_error = TRUE;
return;
}
//CHANNEL_DEBUG(channel, "Flush SASL %d: %p %d", len, output, outputlen);
spice_channel_flush_wire(channel, output, outputlen);
}
#endif
/* coroutine context */
static void spice_channel_write(SpiceChannel *channel, const void *data, size_t len)
{
#if HAVE_SASL
SpiceChannelPrivate *c = channel->priv;
if (c->sasl_conn)
spice_channel_flush_sasl(channel, data, len);
else
#endif
spice_channel_flush_wire(channel, data, len);
}
/* coroutine context */
static void spice_channel_write_msg(SpiceChannel *channel, SpiceMsgOut *out)
{
uint8_t *data;
int free_data;
size_t len;
uint32_t msg_size;
g_return_if_fail(channel != NULL);
g_return_if_fail(out != NULL);
g_return_if_fail(channel == out->channel);
if (out->ro_check &&
spice_channel_get_read_only(channel)) {
g_warning("Try to send message while read-only. Please report a bug.");
return;
}
msg_size = spice_marshaller_get_total_size(out->marshaller) -
spice_header_get_header_size(channel->priv->use_mini_header);
spice_header_set_msg_size(out->header, channel->priv->use_mini_header, msg_size);
data = spice_marshaller_linearize(out->marshaller, 0, &len, &free_data);
/* spice_msg_out_hexdump(out, data, len); */
spice_channel_write(channel, data, len);
if (free_data)
free(data);
spice_msg_out_unref(out);
}
/*
* Read at least 1 more byte of data straight off the wire
* into the requested buffer.
*/
/* coroutine context */
static int spice_channel_read_wire(SpiceChannel *channel, void *data, size_t len)
{
SpiceChannelPrivate *c = channel->priv;
int ret;
GIOCondition cond;
reread:
if (c->has_error) return 0; /* has_error is set by disconnect(), return no error */
cond = 0;
if (c->tls) {
ret = SSL_read(c->ssl, data, len);
if (ret < 0) {
ret = SSL_get_error(c->ssl, ret);
if (ret == SSL_ERROR_WANT_READ)
cond |= G_IO_IN;
if (ret == SSL_ERROR_WANT_WRITE)
cond |= G_IO_OUT;
ret = -1;
}
} else {
GError *error = NULL;
ret = g_socket_receive(c->sock, data, len, NULL, &error);
if (ret < 0) {
if (g_error_matches(error, G_IO_ERROR, G_IO_ERROR_WOULD_BLOCK)) {
cond = G_IO_IN;
} else {
CHANNEL_DEBUG(channel, "Read error %s", error->message);
}
g_clear_error(&error);
ret = -1;
}
}
if (ret == -1) {
if (cond != 0) {
g_coroutine_socket_wait(&c->coroutine, c->sock, cond);
goto reread;
} else {
c->has_error = TRUE;
return -errno;
}
}
if (ret == 0) {
CHANNEL_DEBUG(channel, "Closing the connection: spice_channel_read() - ret=0");
c->has_error = TRUE;
return 0;
}
return ret;
}
#if HAVE_SASL
/*
* Read at least 1 more byte of data out of the SASL decrypted
* data buffer, into the internal read buffer
*/
static int spice_channel_read_sasl(SpiceChannel *channel, void *data, size_t len)
{
SpiceChannelPrivate *c = channel->priv;
/* CHANNEL_DEBUG(channel, "Read %lu SASL %p size %d offset %d", len, c->sasl_decoded, */
/* c->sasl_decoded_length, c->sasl_decoded_offset); */
if (c->sasl_decoded == NULL || c->sasl_decoded_length == 0) {
char encoded[8192]; /* should stay lower than maxbufsize */
int err, ret;
g_warn_if_fail(c->sasl_decoded_offset == 0);
ret = spice_channel_read_wire(channel, encoded, sizeof(encoded));
if (ret < 0)
return ret;
err = sasl_decode(c->sasl_conn, encoded, ret,
&c->sasl_decoded, &c->sasl_decoded_length);
if (err != SASL_OK) {
g_warning("Failed to decode SASL data %s",
sasl_errstring(err, NULL, NULL));
c->has_error = TRUE;
return -EINVAL;
}
c->sasl_decoded_offset = 0;
}
if (c->sasl_decoded_length == 0)
return 0;
len = MIN(c->sasl_decoded_length - c->sasl_decoded_offset, len);
memcpy(data, c->sasl_decoded + c->sasl_decoded_offset, len);
c->sasl_decoded_offset += len;
if (c->sasl_decoded_offset == c->sasl_decoded_length) {
c->sasl_decoded_length = c->sasl_decoded_offset = 0;
c->sasl_decoded = NULL;
}
return len;
}
#endif
/*
* Fill the 'data' buffer up with exactly 'len' bytes worth of data
*/
/* coroutine context */
static int spice_channel_read(SpiceChannel *channel, void *data, size_t length)
{
SpiceChannelPrivate *c = channel->priv;
gsize len = length;
int ret;
while (len > 0) {
if (c->has_error) return 0; /* has_error is set by disconnect(), return no error */
#if HAVE_SASL
if (c->sasl_conn)
ret = spice_channel_read_sasl(channel, data, len);
else
#endif
ret = spice_channel_read_wire(channel, data, len);
if (ret < 0)
return ret;
g_assert(ret <= len);
len -= ret;
data = ((char*)data) + ret;
#if DEBUG
if (len > 0)
CHANNEL_DEBUG(channel, "still needs %" G_GSIZE_FORMAT, len);
#endif
}
c->total_read_bytes += length;
return length;
}
/* coroutine context */
static void spice_channel_send_spice_ticket(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
EVP_PKEY *pubkey;
int nRSASize;
BIO *bioKey;
RSA *rsa;
char *password;
uint8_t *encrypted;
int rc;
bioKey = BIO_new(BIO_s_mem());
g_return_if_fail(bioKey != NULL);
BIO_write(bioKey, c->peer_msg->pub_key, SPICE_TICKET_PUBKEY_BYTES);
pubkey = d2i_PUBKEY_bio(bioKey, NULL);
g_return_if_fail(pubkey != NULL);
rsa = pubkey->pkey.rsa;
nRSASize = RSA_size(rsa);
encrypted = g_alloca(nRSASize);
/*
The use of RSA encryption limit the potential maximum password length.
for RSA_PKCS1_OAEP_PADDING it is RSA_size(rsa) - 41.
*/
g_object_get(c->session, "password", &password, NULL);
if (password == NULL)
password = g_strdup("");
rc = RSA_public_encrypt(strlen(password) + 1, (uint8_t*)password,
encrypted, rsa, RSA_PKCS1_OAEP_PADDING);
g_warn_if_fail(rc > 0);
spice_channel_write(channel, encrypted, nRSASize);
memset(encrypted, 0, nRSASize);
EVP_PKEY_free(pubkey);
BIO_free(bioKey);
g_free(password);
}
/* coroutine context */
static void spice_channel_recv_auth(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
uint32_t link_res;
int rc;
rc = spice_channel_read(channel, &link_res, sizeof(link_res));
if (rc != sizeof(link_res)) {
CHANNEL_DEBUG(channel, "incomplete auth reply (%d/%" G_GSIZE_FORMAT ")",
rc, sizeof(link_res));
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_LINK);
return;
}
if (link_res != SPICE_LINK_ERR_OK) {
CHANNEL_DEBUG(channel, "link result: reply %d", link_res);
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_AUTH);
return;
}
c->state = SPICE_CHANNEL_STATE_READY;
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_OPENED);
if (c->state == SPICE_CHANNEL_STATE_MIGRATION_HANDSHAKE) {
spice_channel_send_migration_handshake(channel);
}
if (c->state != SPICE_CHANNEL_STATE_MIGRATING)
spice_channel_up(channel);
}
G_GNUC_INTERNAL
void spice_channel_up(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
CHANNEL_DEBUG(channel, "channel up, state %d", c->state);
if (SPICE_CHANNEL_GET_CLASS(channel)->channel_up)
SPICE_CHANNEL_GET_CLASS(channel)->channel_up(channel);
}
/* coroutine context */
static void spice_channel_send_link(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
uint8_t *buffer, *p;
int protocol, i;
c->link_hdr.magic = SPICE_MAGIC;
c->link_hdr.size = sizeof(c->link_msg);
g_object_get(c->session, "protocol", &protocol, NULL);
switch (protocol) {
case 1: /* protocol 1 == major 1, old 0.4 protocol, last active minor */
c->link_hdr.major_version = 1;
c->link_hdr.minor_version = 3;
c->parser = spice_get_server_channel_parser1(c->channel_type, NULL);
c->marshallers = spice_message_marshallers_get1();
break;
case SPICE_VERSION_MAJOR: /* protocol 2 == current */
c->link_hdr.major_version = SPICE_VERSION_MAJOR;
c->link_hdr.minor_version = SPICE_VERSION_MINOR;
c->parser = spice_get_server_channel_parser(c->channel_type, NULL);
c->marshallers = spice_message_marshallers_get();
break;
default:
g_critical("unknown major %d", protocol);
return;
}
c->link_msg.connection_id = spice_session_get_connection_id(c->session);
c->link_msg.channel_type = c->channel_type;
c->link_msg.channel_id = c->channel_id;
c->link_msg.caps_offset = sizeof(c->link_msg);
c->link_msg.num_common_caps = c->common_caps->len;
c->link_msg.num_channel_caps = c->caps->len;
c->link_hdr.size += (c->link_msg.num_common_caps +
c->link_msg.num_channel_caps) * sizeof(uint32_t);
buffer = spice_malloc(sizeof(c->link_hdr) + c->link_hdr.size);
p = buffer;
memcpy(p, &c->link_hdr, sizeof(c->link_hdr)); p += sizeof(c->link_hdr);
memcpy(p, &c->link_msg, sizeof(c->link_msg)); p += sizeof(c->link_msg);
for (i = 0; i < c->common_caps->len; i++) {
*(uint32_t *)p = g_array_index(c->common_caps, uint32_t, i);
p += sizeof(uint32_t);
}
for (i = 0; i < c->caps->len; i++) {
*(uint32_t *)p = g_array_index(c->caps, uint32_t, i);
p += sizeof(uint32_t);
}
CHANNEL_DEBUG(channel, "channel type %d id %d num common caps %d num caps %d",
c->link_msg.channel_type,
c->link_msg.channel_id,
c->link_msg.num_common_caps,
c->link_msg.num_channel_caps);
spice_channel_write(channel, buffer, p - buffer);
free(buffer);
}
/* coroutine context */
static gboolean spice_channel_recv_link_hdr(SpiceChannel *channel, gboolean *switch_protocol)
{
SpiceChannelPrivate *c = channel->priv;
int rc;
*switch_protocol = FALSE;
rc = spice_channel_read(channel, &c->peer_hdr, sizeof(c->peer_hdr));
if (rc != sizeof(c->peer_hdr)) {
g_warning("incomplete link header (%d/%" G_GSIZE_FORMAT ")",
rc, sizeof(c->peer_hdr));
goto error;
}
if (c->peer_hdr.magic != SPICE_MAGIC) {
g_warning("invalid SPICE_MAGIC!");
goto error;
}
CHANNEL_DEBUG(channel, "Peer version: %d:%d", c->peer_hdr.major_version, c->peer_hdr.minor_version);
if (c->peer_hdr.major_version != c->link_hdr.major_version) {
g_warning("major mismatch (got %d, expected %d)",
c->peer_hdr.major_version, c->link_hdr.major_version);
goto error;
}
c->peer_msg = spice_malloc(c->peer_hdr.size);
if (c->peer_msg == NULL) {
g_warning("invalid peer header size: %u", c->peer_hdr.size);
goto error;
}
return TRUE;
error:
/* Windows socket seems to give early CONNRESET errors. The server
does not linger when closing the socket if the protocol is
incompatible. Try with the oldest protocol in this case: */
if (c->link_hdr.major_version != 1) {
SPICE_DEBUG("%s: error, switching to protocol 1 (spice 0.4)", c->name);
*switch_protocol = TRUE;
g_object_set(c->session, "protocol", 1, NULL);
return FALSE;
}
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_LINK);
return FALSE;
}
#if HAVE_SASL
/*
* NB, keep in sync with similar method in spice/server/reds.c
*/
static gchar *addr_to_string(GSocketAddress *addr)
{
GInetSocketAddress *iaddr = G_INET_SOCKET_ADDRESS(addr);
guint16 port;
GInetAddress *host;
gchar *hoststr;
gchar *ret;
host = g_inet_socket_address_get_address(iaddr);
port = g_inet_socket_address_get_port(iaddr);
hoststr = g_inet_address_to_string(host);
ret = g_strdup_printf("%s;%hu", hoststr, port);
g_free(hoststr);
return ret;
}
static gboolean
spice_channel_gather_sasl_credentials(SpiceChannel *channel,
sasl_interact_t *interact)
{
SpiceChannelPrivate *c;
int ninteract;
g_return_val_if_fail(channel != NULL, FALSE);
g_return_val_if_fail(channel->priv != NULL, FALSE);
c = channel->priv;
/* FIXME: we could keep connection open and ask connection details if missing */
for (ninteract = 0 ; interact[ninteract].id != 0 ; ninteract++) {
switch (interact[ninteract].id) {
case SASL_CB_AUTHNAME:
case SASL_CB_USER:
g_warn_if_reached();
break;
case SASL_CB_PASS:
if (spice_session_get_password(c->session) == NULL)
return FALSE;
interact[ninteract].result = spice_session_get_password(c->session);
interact[ninteract].len = strlen(interact[ninteract].result);
break;
}
}
CHANNEL_DEBUG(channel, "Filled SASL interact");
return TRUE;
}
/*
*
* Init msg from server
*
* u32 mechlist-length
* u8-array mechlist-string
*
* Start msg to server
*
* u32 mechname-length
* u8-array mechname-string
* u32 clientout-length
* u8-array clientout-string
*
* Start msg from server
*
* u32 serverin-length
* u8-array serverin-string
* u8 continue
*
* Step msg to server
*
* u32 clientout-length
* u8-array clientout-string
*
* Step msg from server
*
* u32 serverin-length
* u8-array serverin-string
* u8 continue
*/
#define SASL_MAX_MECHLIST_LEN 300
#define SASL_MAX_MECHNAME_LEN 100
#define SASL_MAX_DATA_LEN (1024 * 1024)
/* Perform the SASL authentication process
*/
static gboolean spice_channel_perform_auth_sasl(SpiceChannel *channel)
{
SpiceChannelPrivate *c;
sasl_conn_t *saslconn = NULL;
sasl_security_properties_t secprops;
const char *clientout;
char *serverin = NULL;
unsigned int clientoutlen;
int err;
char *localAddr = NULL, *remoteAddr = NULL;
const void *val;
sasl_ssf_t ssf;
static const sasl_callback_t saslcb[] = {
{ .id = SASL_CB_PASS },
{ .id = 0 },
};
sasl_interact_t *interact = NULL;
guint32 len;
char *mechlist;
const char *mechname;
gboolean ret = FALSE;
GSocketAddress *addr = NULL;
guint8 complete;
g_return_val_if_fail(channel != NULL, FALSE);
g_return_val_if_fail(channel->priv != NULL, FALSE);
c = channel->priv;
/* Sets up the SASL library as a whole */
err = sasl_client_init(NULL);
CHANNEL_DEBUG(channel, "Client initialize SASL authentication %d", err);
if (err != SASL_OK) {
g_critical("failed to initialize SASL library: %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
/* Get local address in form IPADDR:PORT */
addr = g_socket_get_local_address(c->sock, NULL);
if (!addr) {
g_critical("failed to get local address");
goto error;
}
if ((g_socket_address_get_family(addr) == G_SOCKET_FAMILY_IPV4 ||
g_socket_address_get_family(addr) == G_SOCKET_FAMILY_IPV6) &&
(localAddr = addr_to_string(addr)) == NULL)
goto error;
g_clear_object(&addr);
/* Get remote address in form IPADDR:PORT */
addr = g_socket_get_remote_address(c->sock, NULL);
if (!addr) {
g_critical("failed to get peer address");
goto error;
}
if ((g_socket_address_get_family(addr) == G_SOCKET_FAMILY_IPV4 ||
g_socket_address_get_family(addr) == G_SOCKET_FAMILY_IPV6) &&
(remoteAddr = addr_to_string(addr)) == NULL)
goto error;
g_clear_object(&addr);
CHANNEL_DEBUG(channel, "Client SASL new host:'%s' local:'%s' remote:'%s'",
spice_session_get_host(c->session), localAddr, remoteAddr);
/* Setup a handle for being a client */
err = sasl_client_new("spice",
spice_session_get_host(c->session),
localAddr,
remoteAddr,
saslcb,
SASL_SUCCESS_DATA,
&saslconn);
g_free(localAddr);
g_free(remoteAddr);
if (err != SASL_OK) {
g_critical("Failed to create SASL client context: %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
if (c->ssl) {
sasl_ssf_t ssf;
ssf = SSL_get_cipher_bits(c->ssl, NULL);
err = sasl_setprop(saslconn, SASL_SSF_EXTERNAL, &ssf);
if (err != SASL_OK) {
g_critical("cannot set SASL external SSF %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
}
memset(&secprops, 0, sizeof secprops);
/* If we've got TLS, we don't care about SSF */
secprops.min_ssf = c->ssl ? 0 : 56; /* Equiv to DES supported by all Kerberos */
secprops.max_ssf = c->ssl ? 0 : 100000; /* Very strong ! AES == 256 */
secprops.maxbufsize = 100000;
/* If we're not TLS, then forbid any anonymous or trivially crackable auth */
secprops.security_flags = c->ssl ? 0 :
SASL_SEC_NOANONYMOUS | SASL_SEC_NOPLAINTEXT;
err = sasl_setprop(saslconn, SASL_SEC_PROPS, &secprops);
if (err != SASL_OK) {
g_critical("cannot set security props %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
/* Get the supported mechanisms from the server */
spice_channel_read(channel, &len, sizeof(len));
if (c->has_error)
goto error;
if (len > SASL_MAX_MECHLIST_LEN) {
g_critical("mechlistlen %d too long", len);
goto error;
}
mechlist = g_malloc(len + 1);
spice_channel_read(channel, mechlist, len);
mechlist[len] = '\0';
if (c->has_error) {
g_free(mechlist);
mechlist = NULL;
goto error;
}
restart:
/* Start the auth negotiation on the client end first */
CHANNEL_DEBUG(channel, "Client start negotiation mechlist '%s'", mechlist);
err = sasl_client_start(saslconn,
mechlist,
&interact,
&clientout,
&clientoutlen,
&mechname);
if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
g_critical("Failed to start SASL negotiation: %d (%s)",
err, sasl_errdetail(saslconn));
g_free(mechlist);
mechlist = NULL;
goto error;
}
/* Need to gather some credentials from the client */
if (err == SASL_INTERACT) {
if (!spice_channel_gather_sasl_credentials(channel, interact)) {
CHANNEL_DEBUG(channel, "Failed to collect auth credentials");
goto error;
}
goto restart;
}
CHANNEL_DEBUG(channel, "Server start negotiation with mech %s. Data %d bytes %p '%s'",
mechname, clientoutlen, clientout, clientout);
if (clientoutlen > SASL_MAX_DATA_LEN) {
g_critical("SASL negotiation data too long: %d bytes",
clientoutlen);
goto error;
}
/* Send back the chosen mechname */
len = strlen(mechname);
spice_channel_write(channel, &len, sizeof(guint32));
spice_channel_write(channel, mechname, len);
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (clientout) {
len = clientoutlen + 1;
spice_channel_write(channel, &len, sizeof(guint32));
spice_channel_write(channel, clientout, len);
} else {
len = 0;
spice_channel_write(channel, &len, sizeof(guint32));
}
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Getting sever start negotiation reply");
/* Read the 'START' message reply from server */
spice_channel_read(channel, &len, sizeof(len));
if (c->has_error)
goto error;
if (len > SASL_MAX_DATA_LEN) {
g_critical("SASL negotiation data too long: %d bytes",
len);
goto error;
}
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (len > 0) {
serverin = g_malloc(len);
spice_channel_read(channel, serverin, len);
serverin[len - 1] = '\0';
len--;
} else {
serverin = NULL;
}
spice_channel_read(channel, &complete, sizeof(guint8));
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Client start result complete: %d. Data %d bytes %p '%s'",
complete, len, serverin, serverin);
/* Loop-the-loop...
* Even if the server has completed, the client must *always* do at least one step
* in this loop to verify the server isn't lying about something. Mutual auth */
for (;;) {
if (complete && err == SASL_OK)
break;
restep:
err = sasl_client_step(saslconn,
serverin,
len,
&interact,
&clientout,
&clientoutlen);
if (err != SASL_OK && err != SASL_CONTINUE && err != SASL_INTERACT) {
g_critical("Failed SASL step: %d (%s)",
err, sasl_errdetail(saslconn));
goto error;
}
/* Need to gather some credentials from the client */
if (err == SASL_INTERACT) {
if (!spice_channel_gather_sasl_credentials(channel,
interact)) {
CHANNEL_DEBUG(channel, "%s", "Failed to collect auth credentials");
goto error;
}
goto restep;
}
if (serverin) {
g_free(serverin);
serverin = NULL;
}
CHANNEL_DEBUG(channel, "Client step result %d. Data %d bytes %p '%s'", err, clientoutlen, clientout, clientout);
/* Previous server call showed completion & we're now locally complete too */
if (complete && err == SASL_OK)
break;
/* Not done, prepare to talk with the server for another iteration */
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (clientout) {
len = clientoutlen + 1;
spice_channel_write(channel, &len, sizeof(guint32));
spice_channel_write(channel, clientout, len);
} else {
len = 0;
spice_channel_write(channel, &len, sizeof(guint32));
}
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Server step with %d bytes %p", clientoutlen, clientout);
spice_channel_read(channel, &len, sizeof(guint32));
if (c->has_error)
goto error;
if (len > SASL_MAX_DATA_LEN) {
g_critical("SASL negotiation data too long: %d bytes", len);
goto error;
}
/* NB, distinction of NULL vs "" is *critical* in SASL */
if (len) {
serverin = g_malloc(len);
spice_channel_read(channel, serverin, len);
serverin[len - 1] = '\0';
len--;
} else {
serverin = NULL;
}
spice_channel_read(channel, &complete, sizeof(guint8));
if (c->has_error)
goto error;
CHANNEL_DEBUG(channel, "Client step result complete: %d. Data %d bytes %p '%s'",
complete, len, serverin, serverin);
/* This server call shows complete, and earlier client step was OK */
if (complete) {
g_free(serverin);
serverin = NULL;
if (err == SASL_CONTINUE) /* something went wrong */
goto complete;
break;
}
}
/* Check for suitable SSF if non-TLS */
if (!c->ssl) {
err = sasl_getprop(saslconn, SASL_SSF, &val);
if (err != SASL_OK) {
g_critical("cannot query SASL ssf on connection %d (%s)",
err, sasl_errstring(err, NULL, NULL));
goto error;
}
ssf = *(const int *)val;
CHANNEL_DEBUG(channel, "SASL SSF value %d", ssf);
if (ssf < 56) { /* 56 == DES level, good for Kerberos */
g_critical("negotiation SSF %d was not strong enough", ssf);
goto error;
}
}
complete:
CHANNEL_DEBUG(channel, "%s", "SASL authentication complete");
spice_channel_read(channel, &len, sizeof(len));
if (len != SPICE_LINK_ERR_OK)
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_AUTH);
ret = len == SPICE_LINK_ERR_OK;
/* This must come *after* check-auth-result, because the former
* is defined to be sent unencrypted, and setting saslconn turns
* on the SSF layer encryption processing */
c->sasl_conn = saslconn;
return ret;
error:
g_clear_object(&addr);
if (saslconn)
sasl_dispose(&saslconn);
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_AUTH);
c->has_error = TRUE; /* force disconnect */
return FALSE;
}
#endif /* HAVE_SASL */
/* coroutine context */
static void spice_channel_recv_link_msg(SpiceChannel *channel, gboolean *switch_tls)
{
SpiceChannelPrivate *c;
int rc, num_caps, i;
uint32_t *caps;
g_return_if_fail(channel != NULL);
g_return_if_fail(channel->priv != NULL);
c = channel->priv;
rc = spice_channel_read(channel, (uint8_t*)c->peer_msg + c->peer_pos,
c->peer_hdr.size - c->peer_pos);
c->peer_pos += rc;
if (c->peer_pos != c->peer_hdr.size) {
g_critical("%s: %s: incomplete link reply (%d/%d)",
c->name, __FUNCTION__, rc, c->peer_hdr.size);
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_LINK);
return;
}
switch (c->peer_msg->error) {
case SPICE_LINK_ERR_OK:
/* nothing */
break;
case SPICE_LINK_ERR_NEED_SECURED:
*switch_tls = true;
CHANNEL_DEBUG(channel, "switching to tls");
return;
default:
g_warning("%s: %s: unhandled error %d",
c->name, __FUNCTION__, c->peer_msg->error);
goto error;
}
num_caps = c->peer_msg->num_channel_caps + c->peer_msg->num_common_caps;
CHANNEL_DEBUG(channel, "%s: %d caps", __FUNCTION__, num_caps);
/* see original spice/client code: */
/* g_return_if_fail(c->peer_msg + c->peer_msg->caps_offset * sizeof(uint32_t) > c->peer_msg + c->peer_hdr.size); */
caps = (uint32_t *)((uint8_t *)c->peer_msg + c->peer_msg->caps_offset);
g_array_set_size(c->remote_common_caps, c->peer_msg->num_common_caps);
for (i = 0; i < c->peer_msg->num_common_caps; i++, caps++) {
g_array_index(c->remote_common_caps, uint32_t, i) = *caps;
CHANNEL_DEBUG(channel, "got common caps %u:0x%X", i, *caps);
}
g_array_set_size(c->remote_caps, c->peer_msg->num_channel_caps);
for (i = 0; i < c->peer_msg->num_channel_caps; i++, caps++) {
g_array_index(c->remote_caps, uint32_t, i) = *caps;
CHANNEL_DEBUG(channel, "got channel caps %u:0x%X", i, *caps);
}
if (!spice_channel_test_common_capability(channel,
SPICE_COMMON_CAP_PROTOCOL_AUTH_SELECTION)) {
CHANNEL_DEBUG(channel, "Server supports spice ticket auth only");
spice_channel_send_spice_ticket(channel);
} else {
SpiceLinkAuthMechanism auth = { 0, };
#if HAVE_SASL
if (spice_channel_test_common_capability(channel, SPICE_COMMON_CAP_AUTH_SASL)) {
CHANNEL_DEBUG(channel, "Choosing SASL mechanism");
auth.auth_mechanism = SPICE_COMMON_CAP_AUTH_SASL;
spice_channel_write(channel, &auth, sizeof(auth));
spice_channel_perform_auth_sasl(channel);
} else
#endif
if (spice_channel_test_common_capability(channel, SPICE_COMMON_CAP_AUTH_SPICE)) {
auth.auth_mechanism = SPICE_COMMON_CAP_AUTH_SPICE;
spice_channel_write(channel, &auth, sizeof(auth));
spice_channel_send_spice_ticket(channel);
} else {
g_warning("No compatible AUTH mechanism");
goto error;
}
}
c->use_mini_header = spice_channel_test_common_capability(channel,
SPICE_COMMON_CAP_MINI_HEADER);
CHANNEL_DEBUG(channel, "use mini header: %d", c->use_mini_header);
return;
error:
SPICE_CHANNEL_GET_CLASS(channel)->channel_disconnect(channel);
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_LINK);
}
/* system context */
G_GNUC_INTERNAL
void spice_channel_wakeup(SpiceChannel *channel, gboolean cancel)
{
GCoroutine *c = &channel->priv->coroutine;
if (cancel)
g_coroutine_condition_cancel(c);
g_coroutine_wakeup(c);
}
G_GNUC_INTERNAL
gboolean spice_channel_get_read_only(SpiceChannel *channel)
{
return spice_session_get_read_only(channel->priv->session);
}
/* coroutine context */
G_GNUC_INTERNAL
void spice_channel_recv_msg(SpiceChannel *channel,
handler_msg_in msg_handler, gpointer data)
{
SpiceChannelPrivate *c = channel->priv;
SpiceMsgIn *in;
int msg_size;
int msg_type;
int sub_list_offset = 0;
in = spice_msg_in_new(channel);
/* receive message */
spice_channel_read(channel, in->header,
spice_header_get_header_size(c->use_mini_header));
if (c->has_error)
goto end;
msg_size = spice_header_get_msg_size(in->header, c->use_mini_header);
/* FIXME: do not allow others to take ref on in, and use realloc here?
* this would avoid malloc/free on each message?
*/
in->data = spice_malloc(msg_size);
spice_channel_read(channel, in->data, msg_size);
if (c->has_error)
goto end;
in->dpos = msg_size;
msg_type = spice_header_get_msg_type(in->header, c->use_mini_header);
sub_list_offset = spice_header_get_msg_sub_list(in->header, c->use_mini_header);
if (msg_type == SPICE_MSG_LIST || sub_list_offset) {
SpiceSubMessageList *sub_list;
SpiceSubMessage *sub;
SpiceMsgIn *sub_in;
int i;
sub_list = (SpiceSubMessageList *)(in->data + sub_list_offset);
for (i = 0; i < sub_list->size; i++) {
sub = (SpiceSubMessage *)(in->data + sub_list->sub_messages[i]);
sub_in = spice_msg_in_sub_new(channel, in, sub);
sub_in->parsed = c->parser(sub_in->data, sub_in->data + sub_in->dpos,
spice_header_get_msg_type(sub_in->header,
c->use_mini_header),
c->peer_hdr.minor_version,
&sub_in->psize, &sub_in->pfree);
if (sub_in->parsed == NULL) {
g_critical("failed to parse sub-message: %s type %d",
c->name, spice_header_get_msg_type(sub_in->header, c->use_mini_header));
goto end;
}
msg_handler(channel, sub_in, data);
spice_msg_in_unref(sub_in);
}
}
/* ack message */
if (c->message_ack_count) {
c->message_ack_count--;
if (!c->message_ack_count) {
SpiceMsgOut *out = spice_msg_out_new(channel, SPICE_MSGC_ACK);
spice_msg_out_send_internal(out);
c->message_ack_count = c->message_ack_window;
}
}
if (msg_type == SPICE_MSG_LIST) {
goto end;
}
/* parse message */
in->parsed = c->parser(in->data, in->data + msg_size, msg_type,
c->peer_hdr.minor_version, &in->psize, &in->pfree);
if (in->parsed == NULL) {
g_critical("failed to parse message: %s type %d",
c->name, msg_type);
goto end;
}
/* process message */
/* spice_msg_in_hexdump(in); */
msg_handler(channel, in, data);
end:
/* If the server uses full header, the serial is not necessarily equal
* to c->in_serial (the server can sometimes skip serials) */
c->last_message_serial = spice_header_get_in_msg_serial(in);
c->in_serial++;
spice_msg_in_unref(in);
}
static const char *to_string[] = {
NULL,
[ SPICE_CHANNEL_MAIN ] = "main",
[ SPICE_CHANNEL_DISPLAY ] = "display",
[ SPICE_CHANNEL_INPUTS ] = "inputs",
[ SPICE_CHANNEL_CURSOR ] = "cursor",
[ SPICE_CHANNEL_PLAYBACK ] = "playback",
[ SPICE_CHANNEL_RECORD ] = "record",
[ SPICE_CHANNEL_TUNNEL ] = "tunnel",
[ SPICE_CHANNEL_SMARTCARD ] = "smartcard",
[ SPICE_CHANNEL_USBREDIR ] = "usbredir",
[ SPICE_CHANNEL_PORT ] = "port",
};
/**
* spice_channel_type_to_string:
* @type: a channel-type property value
*
* Convert a channel-type property value to a string.
*
* Returns: string representation of @type.
* Since: 0.20
**/
const gchar* spice_channel_type_to_string(gint type)
{
const char *str = NULL;
if (type >= 0 && type < G_N_ELEMENTS(to_string)) {
str = to_string[type];
}
return str ? str : "unknown channel type";
}
/**
* spice_channel_string_to_type:
* @str: a string representation of the channel-type property
*
* Convert a channel-type property value to a string.
*
* Returns: the channel-type property value for a @str channel
* Since: 0.21
**/
gint spice_channel_string_to_type(const gchar *str)
{
int i;
g_return_val_if_fail(str != NULL, -1);
for (i = 0; i < G_N_ELEMENTS(to_string); i++)
if (g_strcmp0(str, to_string[i]) == 0)
return i;
return -1;
}
G_GNUC_INTERNAL
gchar *spice_channel_supported_string(void)
{
return g_strjoin(", ",
spice_channel_type_to_string(SPICE_CHANNEL_MAIN),
spice_channel_type_to_string(SPICE_CHANNEL_DISPLAY),
spice_channel_type_to_string(SPICE_CHANNEL_INPUTS),
spice_channel_type_to_string(SPICE_CHANNEL_CURSOR),
spice_channel_type_to_string(SPICE_CHANNEL_PLAYBACK),
spice_channel_type_to_string(SPICE_CHANNEL_RECORD),
#ifdef USE_SMARTCARD
spice_channel_type_to_string(SPICE_CHANNEL_SMARTCARD),
#endif
#ifdef USE_USBREDIR
spice_channel_type_to_string(SPICE_CHANNEL_USBREDIR),
#endif
NULL);
}
/**
* spice_channel_new:
* @s: the @SpiceSession the channel is linked to
* @type: the requested SPICECHANNELPRIVATE type
* @id: the channel-id
*
* Create a new #SpiceChannel of type @type, and channel ID @id.
*
* Returns: a weak reference to #SpiceChannel, the session owns the reference
**/
SpiceChannel *spice_channel_new(SpiceSession *s, int type, int id)
{
SpiceChannel *channel;
GType gtype = 0;
g_return_val_if_fail(s != NULL, NULL);
switch (type) {
case SPICE_CHANNEL_MAIN:
gtype = SPICE_TYPE_MAIN_CHANNEL;
break;
case SPICE_CHANNEL_DISPLAY:
gtype = SPICE_TYPE_DISPLAY_CHANNEL;
break;
case SPICE_CHANNEL_CURSOR:
gtype = SPICE_TYPE_CURSOR_CHANNEL;
break;
case SPICE_CHANNEL_INPUTS:
gtype = SPICE_TYPE_INPUTS_CHANNEL;
break;
case SPICE_CHANNEL_PLAYBACK:
case SPICE_CHANNEL_RECORD: {
if (!s->priv->audio) {
g_debug("audio channel is disabled, not creating it");
return NULL;
}
gtype = type == SPICE_CHANNEL_RECORD ?
SPICE_TYPE_RECORD_CHANNEL : SPICE_TYPE_PLAYBACK_CHANNEL;
break;
}
#ifdef USE_SMARTCARD
case SPICE_CHANNEL_SMARTCARD: {
if (!s->priv->smartcard) {
g_debug("smartcard channel is disabled, not creating it");
return NULL;
}
gtype = SPICE_TYPE_SMARTCARD_CHANNEL;
break;
}
#endif
#ifdef USE_USBREDIR
case SPICE_CHANNEL_USBREDIR: {
if (!s->priv->usbredir) {
g_debug("usbredir channel is disabled, not creating it");
return NULL;
}
gtype = SPICE_TYPE_USBREDIR_CHANNEL;
break;
}
#endif
case SPICE_CHANNEL_PORT:
gtype = SPICE_TYPE_PORT_CHANNEL;
break;
default:
g_debug("unsupported channel kind: %s: %d",
spice_channel_type_to_string(type), type);
return NULL;
}
channel = SPICE_CHANNEL(g_object_new(gtype,
"spice-session", s,
"channel-type", type,
"channel-id", id,
NULL));
return channel;
}
/**
* spice_channel_destroy:
* @channel:
*
* Disconnect and unref the @channel. Called by @spice_session_disconnect()
*
**/
void spice_channel_destroy(SpiceChannel *channel)
{
g_return_if_fail(channel != NULL);
CHANNEL_DEBUG(channel, "channel destroy");
spice_channel_disconnect(channel, SPICE_CHANNEL_NONE);
g_object_unref(channel);
}
/* any context */
static void spice_channel_flushed(SpiceChannel *channel, gboolean success)
{
SpiceChannelPrivate *c = channel->priv;
GSList *l;
for (l = c->flushing; l != NULL; l = l->next) {
GSimpleAsyncResult *result = G_SIMPLE_ASYNC_RESULT(l->data);
g_simple_async_result_set_op_res_gboolean(result, success);
g_simple_async_result_complete_in_idle(result);
}
g_slist_free_full(c->flushing, g_object_unref);
c->flushing = NULL;
}
/* coroutine context */
static void spice_channel_iterate_write(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
SpiceMsgOut *out;
do {
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
out = g_queue_pop_head(&c->xmit_queue);
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
if (out)
spice_channel_write_msg(channel, out);
} while (out);
spice_channel_flushed(channel, TRUE);
}
/* coroutine context */
static void spice_channel_iterate_read(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
g_coroutine_socket_wait(&c->coroutine, c->sock, G_IO_IN);
/* treat all incoming data (block on message completion) */
while (!c->has_error &&
c->state != SPICE_CHANNEL_STATE_MIGRATING &&
g_socket_condition_check(c->sock, G_IO_IN) & G_IO_IN) {
do
spice_channel_recv_msg(channel,
(handler_msg_in)SPICE_CHANNEL_GET_CLASS(channel)->handle_msg, NULL);
#if HAVE_SASL
/* flush the sasl buffer too */
while (c->sasl_decoded != NULL);
#else
while (FALSE);
#endif
}
}
static gboolean wait_migration(gpointer data)
{
SpiceChannel *channel = SPICE_CHANNEL(data);
SpiceChannelPrivate *c = channel->priv;
if (c->state != SPICE_CHANNEL_STATE_MIGRATING) {
CHANNEL_DEBUG(channel, "unfreeze channel");
return TRUE;
}
return FALSE;
}
/* coroutine context */
static gboolean spice_channel_iterate(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
GIOCondition ret;
if (c->state == SPICE_CHANNEL_STATE_MIGRATING &&
!g_coroutine_condition_wait(&c->coroutine, wait_migration, channel))
CHANNEL_DEBUG(channel, "migration wait cancelled");
if (c->has_error) {
CHANNEL_DEBUG(channel, "channel has error, breaking loop");
return FALSE;
}
/* flush any pending write and read */
SPICE_CHANNEL_GET_CLASS(channel)->iterate_write(channel);
SPICE_CHANNEL_GET_CLASS(channel)->iterate_read(channel);
ret = g_socket_condition_check(c->sock, G_IO_IN | G_IO_ERR | G_IO_HUP);
if (c->state > SPICE_CHANNEL_STATE_CONNECTING &&
ret & (G_IO_ERR|G_IO_HUP)) {
SPICE_DEBUG("got socket error: %d", ret);
emit_main_context(channel, SPICE_CHANNEL_EVENT,
c->state == SPICE_CHANNEL_STATE_READY ?
SPICE_CHANNEL_ERROR_IO : SPICE_CHANNEL_ERROR_LINK);
c->has_error = TRUE;
return FALSE;
}
return TRUE;
}
/* we use an idle function to allow the coroutine to exit before we actually
* unref the object since the coroutine's state is part of the object */
static gboolean spice_channel_delayed_unref(gpointer data)
{
SpiceChannel *channel = SPICE_CHANNEL(data);
SpiceChannelPrivate *c = channel->priv;
g_return_val_if_fail(channel != NULL, FALSE);
CHANNEL_DEBUG(channel, "Delayed unref channel %p", channel);
g_return_val_if_fail(c->coroutine.coroutine.exited == TRUE, FALSE);
g_object_unref(G_OBJECT(data));
return FALSE;
}
static X509_LOOKUP_METHOD spice_x509_mem_lookup = {
"spice_x509_mem_lookup",
0
};
static int spice_channel_load_ca(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
STACK_OF(X509_INFO) *inf;
X509_INFO *itmp;
X509_LOOKUP *lookup;
BIO *in;
int i, count = 0;
guint8 *ca;
guint size;
const gchar *ca_file;
int rc;
g_return_val_if_fail(c->ctx != NULL, 0);
lookup = X509_STORE_add_lookup(c->ctx->cert_store, &spice_x509_mem_lookup);
ca_file = spice_session_get_ca_file(c->session);
spice_session_get_ca(c->session, &ca, &size);
CHANNEL_DEBUG(channel, "Load CA, file: %s, data: %p", ca_file, ca);
g_warn_if_fail(ca_file || ca);
if (ca != NULL) {
in = BIO_new_mem_buf(ca, size);
inf = PEM_X509_INFO_read_bio(in, NULL, NULL, NULL);
BIO_free(in);
for (i = 0; i < sk_X509_INFO_num(inf); i++) {
itmp = sk_X509_INFO_value(inf, i);
if (itmp->x509) {
X509_STORE_add_cert(lookup->store_ctx, itmp->x509);
count++;
}
if (itmp->crl) {
X509_STORE_add_crl(lookup->store_ctx, itmp->crl);
count++;
}
}
sk_X509_INFO_pop_free(inf, X509_INFO_free);
}
if (ca_file != NULL) {
rc = SSL_CTX_load_verify_locations(c->ctx, ca_file, NULL);
if (rc != 1)
g_warning("loading ca certs from %s failed", ca_file);
else
count++;
}
if (count == 0) {
rc = SSL_CTX_set_default_verify_paths(c->ctx);
if (rc != 1)
g_warning("loading ca certs from default location failed");
else
count++;
}
return count;
}
/* coroutine context */
static void *spice_channel_coroutine(void *data)
{
SpiceChannel *channel = SPICE_CHANNEL(data);
SpiceChannelPrivate *c = channel->priv;
guint verify;
int rc, delay_val = 1;
gboolean switch_tls = FALSE;
gboolean switch_protocol = FALSE;
/* When some other SSL/TLS version becomes obsolete, add it to this
* variable. */
long ssl_options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3;
CHANNEL_DEBUG(channel, "Started background coroutine %p", &c->coroutine);
if (spice_session_get_client_provided_socket(c->session)) {
if (c->fd < 0) {
g_critical("fd not provided!");
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_CONNECT);
goto cleanup;
}
if (!(c->sock = g_socket_new_from_fd(c->fd, NULL))) {
CHANNEL_DEBUG(channel, "Failed to open socket from fd %d", c->fd);
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_CONNECT);
goto cleanup;
}
g_socket_set_blocking(c->sock, FALSE);
g_socket_set_keepalive(c->sock, TRUE);
goto connected;
}
reconnect:
c->conn = spice_session_channel_open_host(c->session, channel, &c->tls);
if (c->conn == NULL) {
if (!c->tls) {
CHANNEL_DEBUG(channel, "trying with TLS port");
c->tls = true; /* FIXME: does that really work with provided fd */
goto reconnect;
} else {
CHANNEL_DEBUG(channel, "Connect error");
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_CONNECT);
goto cleanup;
}
}
c->sock = g_object_ref(g_socket_connection_get_socket(c->conn));
c->has_error = FALSE;
if (c->tls) {
c->ctx = SSL_CTX_new(SSLv23_method());
if (c->ctx == NULL) {
g_critical("SSL_CTX_new failed");
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_TLS);
goto cleanup;
}
SSL_CTX_set_options(c->ctx, ssl_options);
verify = spice_session_get_verify(c->session);
if (verify &
(SPICE_SESSION_VERIFY_SUBJECT | SPICE_SESSION_VERIFY_HOSTNAME)) {
rc = spice_channel_load_ca(channel);
if (rc == 0) {
g_warning("no cert loaded");
if (verify & SPICE_SESSION_VERIFY_PUBKEY) {
g_warning("only pubkey active");
verify = SPICE_SESSION_VERIFY_PUBKEY;
} else {
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_TLS);
goto cleanup;
}
}
}
{
const gchar *ciphers = spice_session_get_ciphers(c->session);
if (ciphers != NULL) {
rc = SSL_CTX_set_cipher_list(c->ctx, ciphers);
if (rc != 1)
g_warning("loading cipher list %s failed", ciphers);
}
}
c->ssl = SSL_new(c->ctx);
if (c->ssl == NULL) {
g_critical("SSL_new failed");
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_TLS);
goto cleanup;
}
BIO *bio = bio_new_gsocket(c->sock);
SSL_set_bio(c->ssl, bio, bio);
{
guint8 *pubkey;
guint pubkey_len;
spice_session_get_pubkey(c->session, &pubkey, &pubkey_len);
c->sslverify = spice_openssl_verify_new(c->ssl, verify,
spice_session_get_host(c->session),
(char*)pubkey, pubkey_len,
spice_session_get_cert_subject(c->session));
}
ssl_reconnect:
rc = SSL_connect(c->ssl);
if (rc <= 0) {
rc = SSL_get_error(c->ssl, rc);
if (rc == SSL_ERROR_WANT_READ || rc == SSL_ERROR_WANT_WRITE) {
g_coroutine_socket_wait(&c->coroutine, c->sock, G_IO_OUT|G_IO_ERR|G_IO_HUP);
goto ssl_reconnect;
} else {
g_warning("%s: SSL_connect: %s",
c->name, ERR_error_string(rc, NULL));
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_ERROR_TLS);
goto cleanup;
}
}
}
connected:
rc = setsockopt(g_socket_get_fd(c->sock), IPPROTO_TCP, TCP_NODELAY,
(const char*)&delay_val, sizeof(delay_val));
if ((rc != 0)
#ifdef ENOTSUP
&& (errno != ENOTSUP)
#endif
) {
g_warning("%s: could not set sockopt TCP_NODELAY: %s", c->name,
strerror(errno));
}
spice_channel_send_link(channel);
if (spice_channel_recv_link_hdr(channel, &switch_protocol) == FALSE)
goto cleanup;
spice_channel_recv_link_msg(channel, &switch_tls);
if (switch_tls)
goto cleanup;
spice_channel_recv_auth(channel);
while (spice_channel_iterate(channel))
;
cleanup:
CHANNEL_DEBUG(channel, "Coroutine exit %s", c->name);
SPICE_CHANNEL_GET_CLASS(channel)->channel_disconnect(channel);
if (switch_protocol || (switch_tls && !c->tls)) {
c->tls = switch_tls;
spice_channel_connect(channel);
g_object_unref(channel);
} else
g_idle_add(spice_channel_delayed_unref, data);
/* Co-routine exits now - the SpiceChannel object may no longer exist,
so don't do anything else now unless you like SEGVs */
return NULL;
}
static gboolean connect_delayed(gpointer data)
{
SpiceChannel *channel = data;
SpiceChannelPrivate *c = channel->priv;
struct coroutine *co;
CHANNEL_DEBUG(channel, "Open coroutine starting %p", channel);
c->connect_delayed_id = 0;
co = &c->coroutine.coroutine;
co->stack_size = 16 << 20; /* 16Mb */
co->entry = spice_channel_coroutine;
co->release = NULL;
coroutine_init(co);
coroutine_yieldto(co, channel);
return FALSE;
}
static gboolean channel_connect(SpiceChannel *channel)
{
SpiceChannelPrivate *c = channel->priv;
g_return_val_if_fail(c != NULL, FALSE);
if (c->session == NULL || c->channel_type == -1 || c->channel_id == -1) {
/* unset properties or unknown channel type */
g_warning("%s: channel setup incomplete", __FUNCTION__);
return false;
}
if (c->state != SPICE_CHANNEL_STATE_UNCONNECTED) {
g_warning("Invalid channel_connect state: %d", c->state);
return true;
}
if (spice_session_get_client_provided_socket(c->session)) {
if (c->fd == -1) {
g_signal_emit(channel, signals[SPICE_CHANNEL_OPEN_FD], 0, c->tls);
return true;
}
}
c->state = SPICE_CHANNEL_STATE_CONNECTING;
c->xmit_queue_blocked = FALSE;
g_return_val_if_fail(c->sock == NULL, FALSE);
g_object_ref(G_OBJECT(channel)); /* Unref'd when co-routine exits */
/* we connect in idle, to let previous coroutine exit, if present */
c->connect_delayed_id = g_idle_add(connect_delayed, channel);
return true;
}
/**
* spice_channel_connect:
* @channel:
*
* Connect the channel, using #SpiceSession connection informations
*
* Returns: %TRUE on success.
**/
gboolean spice_channel_connect(SpiceChannel *channel)
{
g_return_val_if_fail(SPICE_IS_CHANNEL(channel), FALSE);
SpiceChannelPrivate *c = channel->priv;
if (c->state >= SPICE_CHANNEL_STATE_CONNECTING)
return TRUE;
return channel_connect(channel);
}
/**
* spice_channel_open_fd:
* @channel:
* @fd: a file descriptor (socket) or -1.
* request mechanism
*
* Connect the channel using @fd socket.
*
* If @fd is -1, a valid fd will be requested later via the
* SpiceChannel::open-fd signal.
*
* Returns: %TRUE on success.
**/
gboolean spice_channel_open_fd(SpiceChannel *channel, int fd)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
g_return_val_if_fail(c != NULL, FALSE);
g_return_val_if_fail(fd >= -1, FALSE);
c->fd = fd;
return channel_connect(channel);
}
/* system or coroutine context */
static void channel_reset(SpiceChannel *channel, gboolean migrating)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
if (c->connect_delayed_id) {
g_source_remove(c->connect_delayed_id);
c->connect_delayed_id = 0;
}
#if HAVE_SASL
if (c->sasl_conn) {
sasl_dispose(&c->sasl_conn);
c->sasl_conn = NULL;
c->sasl_decoded_offset = c->sasl_decoded_length = 0;
}
#endif
spice_openssl_verify_free(c->sslverify);
c->sslverify = NULL;
if (c->ssl) {
SSL_free(c->ssl);
c->ssl = NULL;
}
if (c->ctx) {
SSL_CTX_free(c->ctx);
c->ctx = NULL;
}
if (c->conn) {
g_object_unref(c->conn);
c->conn = NULL;
}
if (c->sock) {
g_object_unref(c->sock);
c->sock = NULL;
}
c->fd = -1;
free(c->peer_msg);
c->peer_msg = NULL;
c->peer_pos = 0;
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
c->xmit_queue_blocked = TRUE; /* Disallow queuing new messages */
gboolean was_empty = g_queue_is_empty(&c->xmit_queue);
g_queue_foreach(&c->xmit_queue, (GFunc)spice_msg_out_unref, NULL);
g_queue_clear(&c->xmit_queue);
if (c->xmit_queue_wakeup_id) {
g_source_remove(c->xmit_queue_wakeup_id);
c->xmit_queue_wakeup_id = 0;
}
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
spice_channel_flushed(channel, was_empty);
g_array_set_size(c->remote_common_caps, 0);
g_array_set_size(c->remote_caps, 0);
g_array_set_size(c->common_caps, 0);
/* Restore our default capabilities in case the channel gets re-used */
spice_channel_set_common_capability(channel, SPICE_COMMON_CAP_PROTOCOL_AUTH_SELECTION);
spice_channel_set_common_capability(channel, SPICE_COMMON_CAP_MINI_HEADER);
spice_channel_reset_capabilities(channel);
}
/* system or coroutine context */
G_GNUC_INTERNAL
void spice_channel_reset(SpiceChannel *channel, gboolean migrating)
{
SPICE_CHANNEL_GET_CLASS(channel)->channel_reset(channel, migrating);
}
/* system or coroutine context */
static void channel_disconnect(SpiceChannel *channel)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
g_return_if_fail(c != NULL);
if (c->state == SPICE_CHANNEL_STATE_UNCONNECTED)
return;
c->has_error = TRUE; /* break the loop */
if (c->state == SPICE_CHANNEL_STATE_READY)
emit_main_context(channel, SPICE_CHANNEL_EVENT, SPICE_CHANNEL_CLOSED);
c->state = SPICE_CHANNEL_STATE_UNCONNECTED;
spice_channel_reset(channel, FALSE);
g_return_if_fail(SPICE_IS_CHANNEL(channel));
}
/**
* spice_channel_disconnect:
* @channel:
* @reason: a channel event emitted on main context (or #SPICE_CHANNEL_NONE)
*
* Close the socket and reset connection specific data. Finally, emit
* @reason #SpiceChannel::channel-event on main context if not
* #SPICE_CHANNEL_NONE.
**/
void spice_channel_disconnect(SpiceChannel *channel, SpiceChannelEvent reason)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
CHANNEL_DEBUG(channel, "channel disconnect %d", reason);
g_return_if_fail(c != NULL);
if (c->state == SPICE_CHANNEL_STATE_UNCONNECTED)
return;
if (reason == SPICE_CHANNEL_SWITCHING)
c->state = SPICE_CHANNEL_STATE_SWITCHING;
c->has_error = TRUE; /* break the loop */
if (c->state == SPICE_CHANNEL_STATE_MIGRATING) {
c->state = SPICE_CHANNEL_STATE_READY;
} else
spice_channel_wakeup(channel, TRUE);
if (reason != SPICE_CHANNEL_NONE)
g_signal_emit(G_OBJECT(channel), signals[SPICE_CHANNEL_EVENT], 0, reason);
}
static gboolean test_capability(GArray *caps, guint32 cap)
{
guint32 c, word_index = cap / 32;
gboolean ret;
if (caps == NULL)
return FALSE;
if (caps->len < word_index + 1)
return FALSE;
c = g_array_index(caps, guint32, word_index);
ret = (c & (1 << (cap % 32))) != 0;
SPICE_DEBUG("test cap %d in 0x%X: %s", cap, c, ret ? "yes" : "no");
return ret;
}
/**
* spice_channel_test_capability:
* @channel:
* @cap:
*
* Test availability of remote "channel kind capability".
*
* Returns: %TRUE if @cap (channel kind capability) is available.
**/
gboolean spice_channel_test_capability(SpiceChannel *self, guint32 cap)
{
SpiceChannelPrivate *c;
g_return_val_if_fail(SPICE_IS_CHANNEL(self), FALSE);
c = self->priv;
return test_capability(c->remote_caps, cap);
}
/**
* spice_channel_test_common_capability:
* @channel:
* @cap:
*
* Test availability of remote "common channel capability".
*
* Returns: %TRUE if @cap (common channel capability) is available.
**/
gboolean spice_channel_test_common_capability(SpiceChannel *self, guint32 cap)
{
SpiceChannelPrivate *c;
g_return_val_if_fail(SPICE_IS_CHANNEL(self), FALSE);
c = self->priv;
return test_capability(c->remote_common_caps, cap);
}
static void set_capability(GArray *caps, guint32 cap)
{
guint word_index = cap / 32;
g_return_if_fail(caps != NULL);
if (caps->len <= word_index)
g_array_set_size(caps, word_index + 1);
g_array_index(caps, guint32, word_index) =
g_array_index(caps, guint32, word_index) | (1 << (cap % 32));
}
/**
* spice_channel_set_capability:
* @channel:
* @cap: a capability
*
* Enable specific channel-kind capability.
* Deprecated: 0.13: this function has been removed
**/
#undef spice_channel_set_capability
void spice_channel_set_capability(SpiceChannel *channel, guint32 cap)
{
SpiceChannelPrivate *c;
g_return_if_fail(SPICE_IS_CHANNEL(channel));
c = channel->priv;
set_capability(c->caps, cap);
}
G_GNUC_INTERNAL
void spice_caps_set(GArray *caps, guint32 cap, const gchar *desc)
{
g_return_if_fail(caps != NULL);
g_return_if_fail(desc != NULL);
if (g_strcmp0(g_getenv(desc), "0") == 0)
return;
set_capability(caps, cap);
}
G_GNUC_INTERNAL
SpiceSession* spice_channel_get_session(SpiceChannel *channel)
{
g_return_val_if_fail(SPICE_IS_CHANNEL(channel), NULL);
return channel->priv->session;
}
G_GNUC_INTERNAL
enum spice_channel_state spice_channel_get_state(SpiceChannel *channel)
{
g_return_val_if_fail(SPICE_IS_CHANNEL(channel),
SPICE_CHANNEL_STATE_UNCONNECTED);
return channel->priv->state;
}
G_GNUC_INTERNAL
void spice_channel_swap(SpiceChannel *channel, SpiceChannel *swap, gboolean swap_msgs)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
SpiceChannelPrivate *s = SPICE_CHANNEL_GET_PRIVATE(swap);
g_return_if_fail(c != NULL);
g_return_if_fail(s != NULL);
g_return_if_fail(s->session != NULL);
g_return_if_fail(s->sock != NULL);
#define SWAP(Field) ({ \
typeof (c->Field) Field = c->Field; \
c->Field = s->Field; \
s->Field = Field; \
})
/* TODO: split channel in 2 objects: a controller and a swappable
state object */
SWAP(conn);
SWAP(sock);
SWAP(ctx);
SWAP(ssl);
SWAP(sslverify);
SWAP(tls);
SWAP(use_mini_header);
if (swap_msgs) {
SWAP(xmit_queue);
SWAP(xmit_queue_blocked);
SWAP(in_serial);
SWAP(out_serial);
}
SWAP(caps);
SWAP(common_caps);
SWAP(remote_caps);
SWAP(remote_common_caps);
#if HAVE_SASL
SWAP(sasl_conn);
SWAP(sasl_decoded);
SWAP(sasl_decoded_length);
SWAP(sasl_decoded_offset);
#endif
}
/* coroutine context */
static void spice_channel_handle_msg(SpiceChannel *channel, SpiceMsgIn *msg)
{
SpiceChannelClass *klass = SPICE_CHANNEL_GET_CLASS(channel);
int type = spice_msg_in_type(msg);
spice_msg_handler handler;
g_return_if_fail(type < klass->handlers->len);
if (type > SPICE_MSG_BASE_LAST && channel->priv->disable_channel_msg)
return;
handler = g_array_index(klass->handlers, spice_msg_handler, type);
g_return_if_fail(handler != NULL);
handler(channel, msg);
}
static void spice_channel_reset_capabilities(SpiceChannel *channel)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
g_array_set_size(c->caps, 0);
if (SPICE_CHANNEL_GET_CLASS(channel)->channel_reset_capabilities) {
SPICE_CHANNEL_GET_CLASS(channel)->channel_reset_capabilities(channel);
}
}
static void spice_channel_send_migration_handshake(SpiceChannel *channel)
{
SpiceChannelPrivate *c = SPICE_CHANNEL_GET_PRIVATE(channel);
if (SPICE_CHANNEL_GET_CLASS(channel)->channel_send_migration_handshake) {
SPICE_CHANNEL_GET_CLASS(channel)->channel_send_migration_handshake(channel);
} else {
c->state = SPICE_CHANNEL_STATE_MIGRATING;
}
}
/**
* spice_channel_flush_async:
* @channel: a #SpiceChannel
* @cancellable: (allow-none): optional GCancellable object, %NULL to ignore
* @callback: (scope async): callback to call when the request is satisfied
* @user_data: (closure): the data to pass to callback function
*
* Forces an asynchronous write of all user-space buffered data for
* the given channel.
*
* When the operation is finished callback will be called. You can
* then call spice_channel_flush_finish() to get the result of the
* operation.
*
* Since: 0.15
**/
void spice_channel_flush_async(SpiceChannel *self, GCancellable *cancellable,
GAsyncReadyCallback callback, gpointer user_data)
{
GSimpleAsyncResult *simple;
SpiceChannelPrivate *c;
gboolean was_empty;
g_return_if_fail(SPICE_IS_CHANNEL(self));
c = self->priv;
if (c->state != SPICE_CHANNEL_STATE_READY) {
g_simple_async_report_error_in_idle(G_OBJECT(self), callback, user_data,
SPICE_CLIENT_ERROR, SPICE_CLIENT_ERROR_FAILED,
"The channel is not ready yet");
return;
}
simple = g_simple_async_result_new(G_OBJECT(self), callback, user_data,
spice_channel_flush_async);
STATIC_MUTEX_LOCK(c->xmit_queue_lock);
was_empty = g_queue_is_empty(&c->xmit_queue);
STATIC_MUTEX_UNLOCK(c->xmit_queue_lock);
if (was_empty) {
g_simple_async_result_set_op_res_gboolean(simple, TRUE);
g_simple_async_result_complete_in_idle(simple);
g_object_unref(simple);
return;
}
c->flushing = g_slist_append(c->flushing, simple);
}
/**
* spice_channel_flush_finish:
* @channel: a #SpiceChannel
* @result: a #GAsyncResult
* @error: a #GError location to store the error occurring, or %NULL
* to ignore.
*
* Finishes flushing a channel.
*
* Returns: %TRUE if flush operation succeeded, %FALSE otherwise.
* Since: 0.15
**/
gboolean spice_channel_flush_finish(SpiceChannel *self, GAsyncResult *result,
GError **error)
{
GSimpleAsyncResult *simple;
g_return_val_if_fail(SPICE_IS_CHANNEL(self), FALSE);
g_return_val_if_fail(result != NULL, FALSE);
simple = (GSimpleAsyncResult *)result;
if (g_simple_async_result_propagate_error(simple, error))
return -1;
g_return_val_if_fail(g_simple_async_result_is_valid(result, G_OBJECT(self),
spice_channel_flush_async), FALSE);
CHANNEL_DEBUG(self, "flushed finished!");
return g_simple_async_result_get_op_res_gboolean(simple);
}
| gpl-3.0 |
sabel83/metashell | 3rd/templight/clang/test/OpenMP/master_taskloop_reduction_codegen.cpp | 3 | 15108 | // RUN: %clang_cc1 -fopenmp -x c++ %s -verify -debug-info-kind=limited -emit-llvm -o - -triple powerpc64le-unknown-linux-gnu -fnoopenmp-use-tls -std=c++98 | FileCheck %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ %s -verify -debug-info-kind=limited -emit-llvm -o - -triple powerpc64le-unknown-linux-gnu -fnoopenmp-use-tls -std=c++98 | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
struct S {
float a;
S() : a(0.0f) {}
~S() {}
};
#pragma omp declare reduction(+:S:omp_out.a += omp_in.a) initializer(omp_priv = omp_orig)
float g;
int a;
#pragma omp threadprivate(a)
int main (int argc, char *argv[])
{
int i, n;
float a[100], b[100], sum, e[argc + 100];
S c[100];
float &d = g;
/* Some initializations */
n = 100;
for (i=0; i < n; i++)
a[i] = b[i] = i * 1.0;
sum = 0.0;
#pragma omp master taskloop reduction(+:sum, c[:n], d, e)
for (i=0; i < n; i++) {
sum = sum + (a[i] * b[i]);
c[i].a = i*i;
d += i*i;
e[i] = i;
}
}
// CHECK-LABEL: @main(
// CHECK: [[RETVAL:%.*]] = alloca i32,
// CHECK: [[ARGC_ADDR:%.*]] = alloca i32,
// CHECK: [[ARGV_ADDR:%.*]] = alloca i8**,
// CHECK: [[I:%.*]] = alloca i32,
// CHECK: [[N:%.*]] = alloca i32,
// CHECK: [[A:%.*]] = alloca [100 x float],
// CHECK: [[B:%.*]] = alloca [100 x float],
// CHECK: [[SUM:%.*]] = alloca float,
// CHECK: [[SAVED_STACK:%.*]] = alloca i8*,
// CHECK: [[C:%.*]] = alloca [100 x %struct.S],
// CHECK: [[D:%.*]] = alloca float*,
// CHECK: [[AGG_CAPTURED:%.*]] = alloca [[STRUCT_ANON:%.*]],
// CHECK: [[DOTRD_INPUT_:%.*]] = alloca [4 x %struct.kmp_taskred_input_t],
// CHECK: alloca i32,
// CHECK: [[DOTCAPTURE_EXPR_:%.*]] = alloca i32,
// CHECK: [[DOTCAPTURE_EXPR_9:%.*]] = alloca i32,
// CHECK: [[TMP0:%.*]] = call i32 @__kmpc_global_thread_num(%struct.ident_t*
// CHECK: store i32 0, i32* [[RETVAL]],
// CHECK: store i32 [[ARGC:%.*]], i32* [[ARGC_ADDR]],
// CHECK: store i8** [[ARGV:%.*]], i8*** [[ARGV_ADDR]],
// CHECK: [[TMP1:%.*]] = load i32, i32* [[ARGC_ADDR]],
// CHECK: [[ADD:%.*]] = add nsw i32 [[TMP1]], 100
// CHECK: [[TMP2:%.*]] = zext i32 [[ADD]] to i64
// CHECK: [[VLA:%.+]] = alloca float, i64 %
// CHECK: [[RES:%.+]] = call {{.*}}i32 @__kmpc_master(
// CHECK-NEXT: [[IS_MASTER:%.+]] = icmp ne i32 [[RES]], 0
// CHECK-NEXT: br i1 [[IS_MASTER]], label {{%?}}[[THEN:.+]], label {{%?}}[[EXIT:[^,]+]]
// CHECK: [[THEN]]
// CHECK: call void @__kmpc_taskgroup(%struct.ident_t*
// CHECK-DAG: [[TMP21:%.*]] = bitcast float* [[SUM]] to i8*
// CHECK-DAG: store i8* [[TMP21]], i8** [[TMP20:%[^,]+]],
// CHECK-DAG: [[TMP20]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_:%.+]], i32 0, i32 0
// CHECK-DAG: [[TMP21:%.*]] = bitcast float* [[SUM]] to i8*
// CHECK-DAG: store i8* [[TMP21]], i8** [[TMP20:%[^,]+]],
// CHECK-DAG: [[TMP20]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_]], i32 0, i32 1
// CHECK-DAG: [[TMP22:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_]], i32 0, i32 2
// CHECK-DAG: store i64 4, i64* [[TMP22]],
// CHECK-DAG: [[TMP23:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_INIT1:.+]] to i8*), i8** [[TMP23]],
// CHECK-DAG: [[TMP24:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP24]],
// CHECK-DAG: [[TMP25:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_COMB1:.+]] to i8*), i8** [[TMP25]],
// CHECK-DAG: [[TMP26:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_]], i32 0, i32 6
// CHECK-DAG: [[TMP27:%.*]] = bitcast i32* [[TMP26]] to i8*
// CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP27]], i8 0, i64 4, i1 false)
// CHECK-DAG: [[ARRAYIDX5:%.*]] = getelementptr inbounds [100 x %struct.S], [100 x %struct.S]* [[C]], i64 0, i64 0
// CHECK-DAG: [[LB_ADD_LEN:%.*]] = add nsw i64 -1, %
// CHECK-DAG: [[ARRAYIDX6:%.*]] = getelementptr inbounds [100 x %struct.S], [100 x %struct.S]* [[C]], i64 0, i64 [[LB_ADD_LEN]]
// CHECK-DAG: [[TMP31:%.*]] = bitcast %struct.S* [[ARRAYIDX5]] to i8*
// CHECK-DAG: store i8* [[TMP31]], i8** [[TMP28:%[^,]+]],
// CHECK-DAG: [[TMP28]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4:%.+]], i32 0, i32 0
// CHECK-DAG: [[TMP31:%.*]] = bitcast %struct.S* [[ARRAYIDX5]] to i8*
// CHECK-DAG: store i8* [[TMP31]], i8** [[TMP28:%[^,]+]],
// CHECK-DAG: [[TMP28]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4]], i32 0, i32 1
// CHECK-DAG: [[TMP32:%.*]] = ptrtoint %struct.S* [[ARRAYIDX6]] to i64
// CHECK-DAG: [[TMP33:%.*]] = ptrtoint %struct.S* [[ARRAYIDX5]] to i64
// CHECK-DAG: [[TMP34:%.*]] = sub i64 [[TMP32]], [[TMP33]]
// CHECK-DAG: [[TMP35:%.*]] = sdiv exact i64 [[TMP34]], ptrtoint (float* getelementptr (float, float* null, i32 1) to i64)
// CHECK-DAG: [[TMP36:%.*]] = add nuw i64 [[TMP35]], 1
// CHECK-DAG: [[TMP37:%.*]] = mul nuw i64 [[TMP36]], ptrtoint (float* getelementptr (float, float* null, i32 1) to i64)
// CHECK-DAG: store i64 [[TMP37]], i64* [[TMP38:%[^,]+]],
// CHECK-DAG: [[TMP38]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4]], i32 0, i32 2
// CHECK-DAG: [[TMP39:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_INIT2:.+]] to i8*), i8** [[TMP39]],
// CHECK-DAG: [[TMP40:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4]], i32 0, i32 4
// CHECK-DAG: store i8* bitcast (void (i8*)* @[[RED_FINI2:.+]] to i8*), i8** [[TMP40]],
// CHECK-DAG: [[TMP41:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_COMB2:.+]] to i8*), i8** [[TMP41]],
// CHECK-DAG: [[TMP42:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_4]], i32 0, i32 6
// CHECK-DAG: store i32 1, i32* [[TMP42]],
// CHECK-DAG: [[TMP44:%.*]] = load float*, float** [[D]],
// CHECK-DAG: [[TMP45:%.*]] = bitcast float* [[TMP44]] to i8*
// CHECK-DAG: store i8* [[TMP45]], i8** [[TMP43:%[^,]+]],
// CHECK-DAG: [[TMP43]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7:%.+]], i32 0, i32 0
// CHECK-DAG: [[TMP45:%.*]] = bitcast float* [[TMP44]] to i8*
// CHECK-DAG: store i8* [[TMP45]], i8** [[TMP43:%[^,]+]],
// CHECK-DAG: [[TMP43]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7]], i32 0, i32 1
// CHECK-DAG: [[TMP46:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7]], i32 0, i32 2
// CHECK-DAG: store i64 4, i64* [[TMP46]],
// CHECK-DAG: [[TMP47:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_INIT3:.+]] to i8*), i8** [[TMP47]],
// CHECK-DAG: [[TMP48:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP48]],
// CHECK-DAG: [[TMP49:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_COMB3:.+]] to i8*), i8** [[TMP49]],
// CHECK-DAG: [[TMP50:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_7]], i32 0, i32 6
// CHECK-DAG: [[TMP51:%.*]] = bitcast i32* [[TMP50]] to i8*
// CHECK-DAG: call void @llvm.memset.p0i8.i64(i8* align 8 [[TMP51]], i8 0, i64 4, i1 false)
// CHECK-DAG: [[TMP53:%.*]] = bitcast float* [[VLA]] to i8*
// CHECK-DAG: store i8* [[TMP53]], i8** [[TMP52:%[^,]+]],
// CHECK-DAG: [[TMP52]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8:%.+]], i32 0, i32 0
// CHECK-DAG: [[TMP53:%.*]] = bitcast float* [[VLA]] to i8*
// CHECK-DAG: store i8* [[TMP53]], i8** [[TMP52:%[^,]+]],
// CHECK-DAG: [[TMP52]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8]], i32 0, i32 1
// CHECK-DAG: [[TMP54:%.*]] = mul nuw i64 [[TMP2]], 4
// CHECK-DAG: [[TMP55:%.*]] = udiv exact i64 [[TMP54]], ptrtoint (float* getelementptr (float, float* null, i32 1) to i64)
// CHECK-DAG: store i64 [[TMP54]], i64* [[TMP56:%[^,]+]],
// CHECK-DAG: [[TMP56]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8]], i32 0, i32 2
// CHECK-DAG: [[TMP57:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8]], i32 0, i32 3
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_INIT4:.+]] to i8*), i8** [[TMP57]],
// CHECK-DAG: [[TMP58:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8]], i32 0, i32 4
// CHECK-DAG: store i8* null, i8** [[TMP58]],
// CHECK-DAG: [[TMP59:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8]], i32 0, i32 5
// CHECK-DAG: store i8* bitcast (void (i8*, i8*)* @[[RED_COMB4:.+]] to i8*), i8** [[TMP59]],
// CHECK-DAG: [[TMP60:%.*]] = getelementptr inbounds %struct.kmp_taskred_input_t, %struct.kmp_taskred_input_t* [[DOTRD_INPUT_GEP_8]], i32 0, i32 6
// CHECK-DAG: store i32 1, i32* [[TMP60]],
// CHECK-DAG: [[DOTRD_INPUT_GEP_]] = getelementptr inbounds [4 x %struct.kmp_taskred_input_t], [4 x %struct.kmp_taskred_input_t]* [[DOTRD_INPUT_]], i64 0, i64
// CHECK-DAG: [[DOTRD_INPUT_GEP_4]] = getelementptr inbounds [4 x %struct.kmp_taskred_input_t], [4 x %struct.kmp_taskred_input_t]* [[DOTRD_INPUT_]], i64 0, i64
// CHECK-DAG: [[DOTRD_INPUT_GEP_7]] = getelementptr inbounds [4 x %struct.kmp_taskred_input_t], [4 x %struct.kmp_taskred_input_t]* [[DOTRD_INPUT_]], i64 0, i64
// CHECK-DAG: [[DOTRD_INPUT_GEP_8]] = getelementptr inbounds [4 x %struct.kmp_taskred_input_t], [4 x %struct.kmp_taskred_input_t]* [[DOTRD_INPUT_]], i64 0, i64
// CHECK: [[TMP61:%.*]] = bitcast [4 x %struct.kmp_taskred_input_t]* [[DOTRD_INPUT_]] to i8*
// CHECK: [[TMP62:%.*]] = call i8* @__kmpc_taskred_init(i32 [[TMP0]], i32 4, i8* [[TMP61]])
// CHECK: [[TMP63:%.*]] = load i32, i32* [[N]],
// CHECK: store i32 [[TMP63]], i32* [[DOTCAPTURE_EXPR_]],
// CHECK: [[TMP64:%.*]] = load i32, i32* [[DOTCAPTURE_EXPR_]],
// CHECK: [[SUB:%.*]] = sub nsw i32 [[TMP64]], 0
// CHECK: [[DIV:%.*]] = sdiv i32 [[SUB]], 1
// CHECK: [[SUB12:%.*]] = sub nsw i32 [[DIV]], 1
// CHECK: store i32 [[SUB12]], i32* [[DOTCAPTURE_EXPR_9]],
// CHECK: [[TMP65:%.*]] = call i8* @__kmpc_omp_task_alloc(%struct.ident_t* {{.+}}, i32 [[TMP0]], i32 1, i64 888, i64 40, i32 (i32, i8*)* bitcast (i32 (i32, %struct.kmp_task_t_with_privates*)* @[[TASK:.+]] to i32 (i32, i8*)*))
// CHECK: call void @__kmpc_taskloop(%struct.ident_t* {{.+}}, i32 [[TMP0]], i8* [[TMP65]], i32 1, i64* %{{.+}}, i64* %{{.+}}, i64 %{{.+}}, i32 1, i32 0, i64 0, i8* null)
// CHECK: call void @__kmpc_end_taskgroup(%struct.ident_t*
// CHECK: call {{.*}}void @__kmpc_end_master(
// CHECK-NEXT: br label {{%?}}[[EXIT]]
// CHECK: [[EXIT]]
// CHECK: ret i32
// CHECK: define internal void @[[RED_INIT1]](i8* noalias %{{.+}}, i8* noalias %{{.+}})
// CHECK: store float 0.000000e+00, float* %
// CHECK: ret void
// CHECK: define internal void @[[RED_COMB1]](i8* %0, i8* %1)
// CHECK: fadd float %
// CHECK: store float %{{.+}}, float* %
// CHECK: ret void
// CHECK: define internal void @[[RED_INIT2]](i8* noalias %{{.+}}, i8* noalias %{{.+}})
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK-NOT: call i8* @__kmpc_threadprivate_cached(
// CHECK: call void [[OMP_INIT1:@.+]](
// CHECK: ret void
// CHECK: define internal void [[OMP_COMB1:@.+]](%struct.S* noalias %0, %struct.S* noalias %1)
// CHECK: fadd float %
// CHECK: define internal void [[OMP_INIT1]](%struct.S* noalias %0, %struct.S* noalias %1)
// CHECK: call void @llvm.memcpy.p0i8.p0i8.i64(
// CHECK: define internal void @[[RED_FINI2]](i8* %0)
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK: call void @
// CHECK: ret void
// CHECK: define internal void @[[RED_COMB2]](i8* %0, i8* %1)
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK: call void [[OMP_COMB1]](
// CHECK: ret void
// CHECK: define internal void @[[RED_INIT3]](i8* noalias %{{.+}}, i8* noalias %{{.+}})
// CHECK: store float 0.000000e+00, float* %
// CHECK: ret void
// CHECK: define internal void @[[RED_COMB3]](i8* %0, i8* %1)
// CHECK: fadd float %
// CHECK: store float %{{.+}}, float* %
// CHECK: ret void
// CHECK: define internal void @[[RED_INIT4]](i8* noalias %{{.+}}, i8* noalias %{{.+}})
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK: store float 0.000000e+00, float* %
// CHECK: ret void
// CHECK: define internal void @[[RED_COMB4]](i8* %0, i8* %1)
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK: fadd float %
// CHECK: store float %{{.+}}, float* %
// CHECK: ret void
// CHECK-NOT: call i8* @__kmpc_threadprivate_cached(
// CHECK: call i8* @__kmpc_task_reduction_get_th_data(
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK: call i8* @__kmpc_task_reduction_get_th_data(
// CHECK-NOT: call i8* @__kmpc_threadprivate_cached(
// CHECK: call i8* @__kmpc_task_reduction_get_th_data(
// CHECK: call i8* @__kmpc_threadprivate_cached(
// CHECK: call i8* @__kmpc_task_reduction_get_th_data(
// CHECK-NOT: call i8* @__kmpc_threadprivate_cached(
// CHECK-DAG: distinct !DISubprogram(linkageName: "[[TASK]]", scope: !
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_INIT1]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_COMB1]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_INIT2]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_FINI2]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_COMB2]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_INIT3]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_COMB3]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_INIT4]]"
// CHECK-DAG: !DISubprogram(linkageName: "[[RED_COMB4]]"
| gpl-3.0 |
dymkowsk/mantid | Framework/Algorithms/src/InvertMask.cpp | 3 | 1842 | #include "MantidAlgorithms/InvertMask.h"
#include "MantidKernel/System.h"
#include "MantidAPI/WorkspaceProperty.h"
#include "MantidDataObjects/MaskWorkspace.h"
using namespace Mantid::Kernel;
using namespace Mantid::API;
namespace Mantid {
namespace Algorithms {
DECLARE_ALGORITHM(InvertMask)
void InvertMask::init() {
this->declareProperty(
make_unique<API::WorkspaceProperty<DataObjects::MaskWorkspace>>(
"InputWorkspace", "Anonymous", Direction::Input),
"MaskWorkspace to be inverted. ");
this->declareProperty(
make_unique<API::WorkspaceProperty<DataObjects::MaskWorkspace>>(
"OutputWorkspace", "AnonynmousOutput", Direction::Output),
"MaskWorkspace has inverted bits from input MaskWorkspace.");
}
void InvertMask::exec() {
// 1. Get input
DataObjects::MaskWorkspace_const_sptr inWS =
this->getProperty("InputWorkspace");
if (!inWS) {
throw std::invalid_argument("InputWorkspace is not a MaskWorkspace.");
}
// 2. Do Invert by calling Child Algorithm
API::IAlgorithm_sptr invert =
createChildAlgorithm("BinaryOperateMasks", 0.0, 1.0, true);
invert->setPropertyValue("InputWorkspace1", inWS->getName());
invert->setProperty("OperationType", "NOT");
invert->setProperty("OutputWorkspace", "tempws");
invert->execute();
if (!invert->isExecuted()) {
g_log.error()
<< "ChildAlgorithm BinaryOperateMask() cannot be executed. \n";
throw std::runtime_error(
"ChildAlgorithm BinaryOperateMask() cannot be executed. ");
}
DataObjects::MaskWorkspace_sptr outputws =
invert->getProperty("OutputWorkspace");
if (!outputws) {
throw std::runtime_error("Output Workspace is not a MaskWorkspace. ");
}
// 3. Set
this->setProperty("OutputWorkspace", outputws);
}
} // namespace Mantid
} // namespace Algorithms
| gpl-3.0 |
BramBonne/snoopsnitch-pcapinterface | contrib/libosmo-asn1-rrc/src/RRCConnectionRelease-CCCH-v690ext-IEs.c | 3 | 5608 | /*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "PDU-definitions"
* found in "../asn/PDU-definitions.asn"
* `asn1c -fcompound-names -fnative-types`
*/
#include "RRCConnectionRelease-CCCH-v690ext-IEs.h"
int
RRCConnectionRelease_CCCH_v690ext_IEs_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
/* Replace with underlying type checker */
td->check_constraints = asn_DEF_RRCConnectionRelease_v690ext_IEs.check_constraints;
return td->check_constraints(td, sptr, ctfailcb, app_key);
}
/*
* This type is implemented using RRCConnectionRelease_v690ext_IEs,
* so here we adjust the DEF accordingly.
*/
static void
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) {
td->free_struct = asn_DEF_RRCConnectionRelease_v690ext_IEs.free_struct;
td->print_struct = asn_DEF_RRCConnectionRelease_v690ext_IEs.print_struct;
td->ber_decoder = asn_DEF_RRCConnectionRelease_v690ext_IEs.ber_decoder;
td->der_encoder = asn_DEF_RRCConnectionRelease_v690ext_IEs.der_encoder;
td->xer_decoder = asn_DEF_RRCConnectionRelease_v690ext_IEs.xer_decoder;
td->xer_encoder = asn_DEF_RRCConnectionRelease_v690ext_IEs.xer_encoder;
td->uper_decoder = asn_DEF_RRCConnectionRelease_v690ext_IEs.uper_decoder;
td->uper_encoder = asn_DEF_RRCConnectionRelease_v690ext_IEs.uper_encoder;
if(!td->per_constraints)
td->per_constraints = asn_DEF_RRCConnectionRelease_v690ext_IEs.per_constraints;
td->elements = asn_DEF_RRCConnectionRelease_v690ext_IEs.elements;
td->elements_count = asn_DEF_RRCConnectionRelease_v690ext_IEs.elements_count;
td->specifics = asn_DEF_RRCConnectionRelease_v690ext_IEs.specifics;
}
void
RRCConnectionRelease_CCCH_v690ext_IEs_free(asn_TYPE_descriptor_t *td,
void *struct_ptr, int contents_only) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
td->free_struct(td, struct_ptr, contents_only);
}
int
RRCConnectionRelease_CCCH_v690ext_IEs_print(asn_TYPE_descriptor_t *td, const void *struct_ptr,
int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->print_struct(td, struct_ptr, ilevel, cb, app_key);
}
asn_dec_rval_t
RRCConnectionRelease_CCCH_v690ext_IEs_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const void *bufptr, size_t size, int tag_mode) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode);
}
asn_enc_rval_t
RRCConnectionRelease_CCCH_v690ext_IEs_encode_der(asn_TYPE_descriptor_t *td,
void *structure, int tag_mode, ber_tlv_tag_t tag,
asn_app_consume_bytes_f *cb, void *app_key) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->der_encoder(td, structure, tag_mode, tag, cb, app_key);
}
asn_dec_rval_t
RRCConnectionRelease_CCCH_v690ext_IEs_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const char *opt_mname, const void *bufptr, size_t size) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size);
}
asn_enc_rval_t
RRCConnectionRelease_CCCH_v690ext_IEs_encode_xer(asn_TYPE_descriptor_t *td, void *structure,
int ilevel, enum xer_encoder_flags_e flags,
asn_app_consume_bytes_f *cb, void *app_key) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->xer_encoder(td, structure, ilevel, flags, cb, app_key);
}
asn_dec_rval_t
RRCConnectionRelease_CCCH_v690ext_IEs_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data);
}
asn_enc_rval_t
RRCConnectionRelease_CCCH_v690ext_IEs_encode_uper(asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints,
void *structure, asn_per_outp_t *per_out) {
RRCConnectionRelease_CCCH_v690ext_IEs_1_inherit_TYPE_descriptor(td);
return td->uper_encoder(td, constraints, structure, per_out);
}
static ber_tlv_tag_t asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (16 << 2))
};
asn_TYPE_descriptor_t asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs = {
"RRCConnectionRelease-CCCH-v690ext-IEs",
"RRCConnectionRelease-CCCH-v690ext-IEs",
RRCConnectionRelease_CCCH_v690ext_IEs_free,
RRCConnectionRelease_CCCH_v690ext_IEs_print,
RRCConnectionRelease_CCCH_v690ext_IEs_constraint,
RRCConnectionRelease_CCCH_v690ext_IEs_decode_ber,
RRCConnectionRelease_CCCH_v690ext_IEs_encode_der,
RRCConnectionRelease_CCCH_v690ext_IEs_decode_xer,
RRCConnectionRelease_CCCH_v690ext_IEs_encode_xer,
RRCConnectionRelease_CCCH_v690ext_IEs_decode_uper,
RRCConnectionRelease_CCCH_v690ext_IEs_encode_uper,
0, /* Use generic outmost tag fetcher */
asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1,
sizeof(asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1)
/sizeof(asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1[0]), /* 1 */
asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1, /* Same as above */
sizeof(asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1)
/sizeof(asn_DEF_RRCConnectionRelease_CCCH_v690ext_IEs_tags_1[0]), /* 1 */
0, /* No PER visible constraints */
0, 0, /* Defined elsewhere */
0 /* No specifics */
};
| gpl-3.0 |
briskycat/qTox | updater/update.cpp | 3 | 4191 | /*
Copyright © 2014 by The qTox Project
This file is part of qTox, a Qt-based graphical interface for Tox.
qTox is libre 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.
qTox 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 qTox. If not, see <http://www.gnu.org/licenses/>
*/
#include "update.h"
#include "serialize.h"
#include "widget.h"
#include <QFile>
#include <QDebug>
#include <QMessageBox>
#include <QDir>
#include <QCoreApplication>
unsigned char key[crypto_sign_PUBLICKEYBYTES] =
{
0x20, 0x89, 0x39, 0xaa, 0x9a, 0xe8, 0xb5, 0x21, 0x0e, 0xac, 0x02, 0xa9, 0xc4, 0x92, 0xd9, 0xa2,
0x17, 0x83, 0xbd, 0x78, 0x0a, 0xda, 0x33, 0xcd, 0xa5, 0xc6, 0x44, 0xc7, 0xfc, 0xed, 0x00, 0x13
};
QByteArray getLocalFlist()
{
QByteArray flist;
QFile flistFile("flist");
if (!flistFile.open(QIODevice::ReadOnly))
{
qWarning() << "getLocalFlist: Can't open local flist";
return flist;
}
flist = flistFile.readAll();
flistFile.close();
return flist;
}
bool isUpToDate(UpdateFileMeta fileMeta)
{
QString appDir = qApp->applicationDirPath();
QFile file(appDir+QDir::separator()+fileMeta.installpath);
if (!file.open(QIODevice::ReadOnly))
return false;
// If the data we have is corrupted or old, mark it for update
QByteArray data = file.readAll();
if (crypto_sign_verify_detached(fileMeta.sig, (unsigned char*)data.data(), data.size(), key) != 0)
return false;
return true;
}
QList<UpdateFileMeta> genUpdateDiff(QList<UpdateFileMeta> updateFlist, Widget* w)
{
QList<UpdateFileMeta> diff;
float progressDiff = 45;
float progress = 5;
for (UpdateFileMeta file : updateFlist)
{
if (!isUpToDate(file))
diff += file;
progress += progressDiff / updateFlist.size();
w->setProgress(progress);
}
return diff;
}
QList<UpdateFileMeta> parseFlist(QByteArray flistData)
{
QList<UpdateFileMeta> flist;
if (flistData.isEmpty())
{
qWarning() << "AutoUpdater::parseflist: Empty data";
return flist;
}
// Check version
if (flistData[0] != '1')
{
qWarning() << "AutoUpdater: parseflist: Bad version "<<(uint8_t)flistData[0];
return flist;
}
flistData = flistData.mid(1);
// Check signature
if (flistData.size() < (int)(crypto_sign_BYTES))
{
qWarning() << "AutoUpdater::parseflist: Truncated data";
return flist;
}
else
{
QByteArray msgData = flistData.mid(crypto_sign_BYTES);
unsigned char* msg = (unsigned char*)msgData.data();
if (crypto_sign_verify_detached((unsigned char*)flistData.data(), msg, msgData.size(), key) != 0)
{
qCritical() << "AutoUpdater: parseflist: FORGED FLIST FILE";
return flist;
}
flistData = flistData.mid(crypto_sign_BYTES);
}
// Parse. We assume no errors handling needed since the signature is valid.
while (!flistData.isEmpty())
{
UpdateFileMeta newFile;
memcpy(newFile.sig, flistData.data(), crypto_sign_BYTES);
flistData = flistData.mid(crypto_sign_BYTES);
newFile.id = dataToString(flistData);
flistData = flistData.mid(newFile.id.size() + getVUint32Size(flistData));
newFile.installpath = dataToString(flistData);
flistData = flistData.mid(newFile.installpath.size() + getVUint32Size(flistData));
newFile.size = dataToUint64(flistData);
flistData = flistData.mid(8);
flist += newFile;
}
return flist;
}
| gpl-3.0 |
maciekswat/dolfin_1.3.0 | dolfin/mesh/MeshOrdering.cpp | 3 | 2439 | // Copyright (C) 2007-2012 Anders Logg
//
// This file is part of DOLFIN.
//
// DOLFIN is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// DOLFIN 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 DOLFIN. If not, see <http://www.gnu.org/licenses/>.
//
// First added: 2007-01-30
// Last changed: 2012-06-25
#include <vector>
#include <boost/shared_ptr.hpp>
#include <dolfin/common/NoDeleter.h>
#include <dolfin/log/log.h>
#include "Cell.h"
#include "Mesh.h"
#include "MeshOrdering.h"
using namespace dolfin;
//-----------------------------------------------------------------------------
void MeshOrdering::order(Mesh& mesh)
{
log(TRACE, "Ordering mesh.");
// Special case
if (mesh.num_cells() == 0)
return;
// Get global vertex numbering
dolfin_assert(mesh.topology().have_global_indices(0));
const std::vector<std::size_t>& local_to_global_vertex_indices
= mesh.topology().global_indices(0);
// Skip ordering for dimension 0
if (mesh.topology().dim() == 0)
return;
// Iterate over all cells and order the mesh entities locally
Progress p("Ordering mesh", mesh.num_cells());
for (CellIterator cell(mesh); !cell.end(); ++cell)
{
cell->order(local_to_global_vertex_indices);
p++;
}
}
//-----------------------------------------------------------------------------
bool MeshOrdering::ordered(const Mesh& mesh)
{
// Special case
if (mesh.num_cells() == 0)
return true;
// Get global vertex numbering
dolfin_assert(mesh.topology().have_global_indices(0));
const std::vector<std::size_t>& local_to_global_vertex_indices
= mesh.topology().global_indices(0);
// Check if all cells are ordered
Progress p("Checking mesh ordering", mesh.num_cells());
for (CellIterator cell(mesh); !cell.end(); ++cell)
{
if (!cell->ordered(local_to_global_vertex_indices))
return false;
p++;
}
return true;
}
//-----------------------------------------------------------------------------
| gpl-3.0 |
geosphere/snoopsnitch | contrib/libosmo-asn1-rrc/src/MAC-ehs-WindowSize-TDD128-v9c0ext.c | 3 | 6301 | /*
* Generated by asn1c-0.9.24 (http://lionet.info/asn1c)
* From ASN.1 module "InformationElements"
* found in "../asn/InformationElements.asn"
* `asn1c -fcompound-names -fnative-types`
*/
#include "MAC-ehs-WindowSize-TDD128-v9c0ext.h"
int
MAC_ehs_WindowSize_TDD128_v9c0ext_constraint(asn_TYPE_descriptor_t *td, const void *sptr,
asn_app_constraint_failed_f *ctfailcb, void *app_key) {
/* Replace with underlying type checker */
td->check_constraints = asn_DEF_NativeEnumerated.check_constraints;
return td->check_constraints(td, sptr, ctfailcb, app_key);
}
/*
* This type is implemented using NativeEnumerated,
* so here we adjust the DEF accordingly.
*/
static void
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(asn_TYPE_descriptor_t *td) {
td->free_struct = asn_DEF_NativeEnumerated.free_struct;
td->print_struct = asn_DEF_NativeEnumerated.print_struct;
td->ber_decoder = asn_DEF_NativeEnumerated.ber_decoder;
td->der_encoder = asn_DEF_NativeEnumerated.der_encoder;
td->xer_decoder = asn_DEF_NativeEnumerated.xer_decoder;
td->xer_encoder = asn_DEF_NativeEnumerated.xer_encoder;
td->uper_decoder = asn_DEF_NativeEnumerated.uper_decoder;
td->uper_encoder = asn_DEF_NativeEnumerated.uper_encoder;
if(!td->per_constraints)
td->per_constraints = asn_DEF_NativeEnumerated.per_constraints;
td->elements = asn_DEF_NativeEnumerated.elements;
td->elements_count = asn_DEF_NativeEnumerated.elements_count;
/* td->specifics = asn_DEF_NativeEnumerated.specifics; // Defined explicitly */
}
void
MAC_ehs_WindowSize_TDD128_v9c0ext_free(asn_TYPE_descriptor_t *td,
void *struct_ptr, int contents_only) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
td->free_struct(td, struct_ptr, contents_only);
}
int
MAC_ehs_WindowSize_TDD128_v9c0ext_print(asn_TYPE_descriptor_t *td, const void *struct_ptr,
int ilevel, asn_app_consume_bytes_f *cb, void *app_key) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->print_struct(td, struct_ptr, ilevel, cb, app_key);
}
asn_dec_rval_t
MAC_ehs_WindowSize_TDD128_v9c0ext_decode_ber(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const void *bufptr, size_t size, int tag_mode) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->ber_decoder(opt_codec_ctx, td, structure, bufptr, size, tag_mode);
}
asn_enc_rval_t
MAC_ehs_WindowSize_TDD128_v9c0ext_encode_der(asn_TYPE_descriptor_t *td,
void *structure, int tag_mode, ber_tlv_tag_t tag,
asn_app_consume_bytes_f *cb, void *app_key) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->der_encoder(td, structure, tag_mode, tag, cb, app_key);
}
asn_dec_rval_t
MAC_ehs_WindowSize_TDD128_v9c0ext_decode_xer(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
void **structure, const char *opt_mname, const void *bufptr, size_t size) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->xer_decoder(opt_codec_ctx, td, structure, opt_mname, bufptr, size);
}
asn_enc_rval_t
MAC_ehs_WindowSize_TDD128_v9c0ext_encode_xer(asn_TYPE_descriptor_t *td, void *structure,
int ilevel, enum xer_encoder_flags_e flags,
asn_app_consume_bytes_f *cb, void *app_key) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->xer_encoder(td, structure, ilevel, flags, cb, app_key);
}
asn_dec_rval_t
MAC_ehs_WindowSize_TDD128_v9c0ext_decode_uper(asn_codec_ctx_t *opt_codec_ctx, asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints, void **structure, asn_per_data_t *per_data) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->uper_decoder(opt_codec_ctx, td, constraints, structure, per_data);
}
asn_enc_rval_t
MAC_ehs_WindowSize_TDD128_v9c0ext_encode_uper(asn_TYPE_descriptor_t *td,
asn_per_constraints_t *constraints,
void *structure, asn_per_outp_t *per_out) {
MAC_ehs_WindowSize_TDD128_v9c0ext_1_inherit_TYPE_descriptor(td);
return td->uper_encoder(td, constraints, structure, per_out);
}
static asn_per_constraints_t asn_PER_type_MAC_ehs_WindowSize_TDD128_v9c0ext_constr_1 = {
{ APC_CONSTRAINED, 2, 2, 0, 3 } /* (0..3) */,
{ APC_UNCONSTRAINED, -1, -1, 0, 0 },
0, 0 /* No PER value map */
};
static asn_INTEGER_enum_map_t asn_MAP_MAC_ehs_WindowSize_TDD128_v9c0ext_value2enum_1[] = {
{ 0, 5, "mws96" },
{ 1, 6, "mws160" },
{ 2, 6, "mws192" },
{ 3, 6, "mws256" }
};
static unsigned int asn_MAP_MAC_ehs_WindowSize_TDD128_v9c0ext_enum2value_1[] = {
1, /* mws160(1) */
2, /* mws192(2) */
3, /* mws256(3) */
0 /* mws96(0) */
};
static asn_INTEGER_specifics_t asn_SPC_MAC_ehs_WindowSize_TDD128_v9c0ext_specs_1 = {
asn_MAP_MAC_ehs_WindowSize_TDD128_v9c0ext_value2enum_1, /* "tag" => N; sorted by tag */
asn_MAP_MAC_ehs_WindowSize_TDD128_v9c0ext_enum2value_1, /* N => "tag"; sorted by N */
4, /* Number of elements in the maps */
0, /* Enumeration is not extensible */
1, /* Strict enumeration */
0, /* Native long size */
0
};
static ber_tlv_tag_t asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1[] = {
(ASN_TAG_CLASS_UNIVERSAL | (10 << 2))
};
asn_TYPE_descriptor_t asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext = {
"MAC-ehs-WindowSize-TDD128-v9c0ext",
"MAC-ehs-WindowSize-TDD128-v9c0ext",
MAC_ehs_WindowSize_TDD128_v9c0ext_free,
MAC_ehs_WindowSize_TDD128_v9c0ext_print,
MAC_ehs_WindowSize_TDD128_v9c0ext_constraint,
MAC_ehs_WindowSize_TDD128_v9c0ext_decode_ber,
MAC_ehs_WindowSize_TDD128_v9c0ext_encode_der,
MAC_ehs_WindowSize_TDD128_v9c0ext_decode_xer,
MAC_ehs_WindowSize_TDD128_v9c0ext_encode_xer,
MAC_ehs_WindowSize_TDD128_v9c0ext_decode_uper,
MAC_ehs_WindowSize_TDD128_v9c0ext_encode_uper,
0, /* Use generic outmost tag fetcher */
asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1,
sizeof(asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1)
/sizeof(asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1[0]), /* 1 */
asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1, /* Same as above */
sizeof(asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1)
/sizeof(asn_DEF_MAC_ehs_WindowSize_TDD128_v9c0ext_tags_1[0]), /* 1 */
&asn_PER_type_MAC_ehs_WindowSize_TDD128_v9c0ext_constr_1,
0, 0, /* Defined elsewhere */
&asn_SPC_MAC_ehs_WindowSize_TDD128_v9c0ext_specs_1 /* Additional specs */
};
| gpl-3.0 |
franticspider/voglc21 | vogl/drivers/ibmpc/cga.c | 3 | 2530 | #include "vogl.h"
#include <stdio.h>
#ifdef TC
#include <dos.h>
#define _dos_allocmem allocmem
#define _dos_freemem freemem
#endif
#define C_PIX_ASPECT 2.4
#define NPARA (640 * 200 / 16)
static unsigned allocated = 0, old_mode;
static unsigned char *backbuf;
extern unsigned int _buffer_segment;
extern unsigned int _buffer_offset;
extern unsigned int _cur_color;
static unsigned int save_seg;
extern int cga_clear(),
cga_frontbuf(),
cga_swapbuf(),
_cga_set_buffer(),
pc_fill(),
pc_font(),
pc_getkey(),
pc_checkkey(),
pc_locator(),
pc_string(),
setmode();
static int
cga_init()
{
vdevice.sizeX = 199 * C_PIX_ASPECT;
vdevice.sizeY = 199;
vdevice.sizeSx = 639;
vdevice.sizeSy = 199;
vdevice.depth = 1;
_buffer_segment = 0xB800;
_buffer_offset = 0;
_cur_color = 1;
old_mode = setmode(6);
pc_locinit(vdevice.sizeSx, vdevice.sizeSy);
return (1);
}
/*
* cga_vclear
*
* Just clears the current viewport.
*/
static
cga_vclear()
{
int x[4], y[4];
if (vdevice.maxVx != vdevice.sizeSx
|| vdevice.maxVy != vdevice.sizeSy
|| vdevice.minVx != vdevice.sizeSx
|| vdevice.minVy != vdevice.sizeSy) {
x[0] = x[3] = vdevice.minVx;
y[0] = y[1] = vdevice.maxVy;
y[2] = y[3] = vdevice.minVy;
x[1] = x[2] = vdevice.maxVx;
pc_fill(5, x, y);
} else {
cga_clear();
}
return(0);
}
/*
* cga_exit
*
* Sets the display back to text mode.
*/
static
cga_exit()
{
unshowmouse();
if (allocated)
_dos_freemem(save_seg);
setmode(old_mode);
return (1);
}
static
cga_draw(x, y)
int x, y;
{
cgaline(vdevice.cpVx, vdevice.sizeSy - vdevice.cpVy, x, vdevice.sizeSy - y, _cur_color);
vdevice.cpVx = x;
vdevice.cpVy = y;
return(0);
}
static
cga_char(c)
int c;
{
cgachar(c, vdevice.cpVx, vdevice.sizeSy - vdevice.cpVy, _cur_color, 1 - _cur_color);
return(0);
}
static
cga_color(i)
int i;
{
_cur_color = (i > 0 ? 1 : 0);
return(0);
}
static
cga_backbuf()
{
if (!allocated) {
if (_dos_allocmem(NPARA, &_buffer_segment) != 0)
verror("cga_backbuf: couldn't allocate space");
allocated = 1;
save_seg = _buffer_segment;
}
return(1);
}
static int
noop()
{
return (-1);
}
static DevEntry cgadev = {
"cga",
"large",
"small",
cga_backbuf,
cga_char,
pc_checkkey,
cga_vclear,
cga_color,
cga_draw,
cga_exit,
pc_fill,
pc_font,
cga_frontbuf,
pc_getkey,
cga_init,
pc_locator,
noop,
noop,
noop,
pc_string,
cga_swapbuf,
noop
};
/*
* _cga_devcpy
*
* copy the pc device into vdevice.dev.
*/
_cga_devcpy()
{
vdevice.dev = cgadev;
return(0);
}
| gpl-3.0 |
Theadd/Designi | JuceLibraryCode/modules/juce_graphics/native/juce_win32_Fonts.cpp | 4 | 16913 | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
namespace FontEnumerators
{
static int CALLBACK fontEnum2 (ENUMLOGFONTEXW* lpelfe, NEWTEXTMETRICEXW*, int type, LPARAM lParam)
{
if (lpelfe != nullptr && (type & RASTER_FONTTYPE) == 0)
{
const String fontName (lpelfe->elfLogFont.lfFaceName);
((StringArray*) lParam)->addIfNotAlreadyThere (fontName.removeCharacters ("@"));
}
return 1;
}
static int CALLBACK fontEnum1 (ENUMLOGFONTEXW* lpelfe, NEWTEXTMETRICEXW*, int type, LPARAM lParam)
{
if (lpelfe != nullptr && (type & RASTER_FONTTYPE) == 0)
{
LOGFONTW lf = { 0 };
lf.lfWeight = FW_DONTCARE;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfPitchAndFamily = FF_DONTCARE;
const String fontName (lpelfe->elfLogFont.lfFaceName);
fontName.copyToUTF16 (lf.lfFaceName, sizeof (lf.lfFaceName));
HDC dc = CreateCompatibleDC (0);
EnumFontFamiliesEx (dc, &lf,
(FONTENUMPROCW) &fontEnum2,
lParam, 0);
DeleteDC (dc);
}
return 1;
}
}
StringArray Font::findAllTypefaceNames()
{
StringArray results;
#if JUCE_USE_DIRECTWRITE
const Direct2DFactories& factories = Direct2DFactories::getInstance();
if (factories.systemFonts != nullptr)
{
ComSmartPtr<IDWriteFontFamily> fontFamily;
uint32 fontFamilyCount = 0;
fontFamilyCount = factories.systemFonts->GetFontFamilyCount();
for (uint32 i = 0; i < fontFamilyCount; ++i)
{
HRESULT hr = factories.systemFonts->GetFontFamily (i, fontFamily.resetAndGetPointerAddress());
if (SUCCEEDED (hr))
results.addIfNotAlreadyThere (getFontFamilyName (fontFamily));
}
}
else
#endif
{
HDC dc = CreateCompatibleDC (0);
{
LOGFONTW lf = { 0 };
lf.lfWeight = FW_DONTCARE;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfPitchAndFamily = FF_DONTCARE;
EnumFontFamiliesEx (dc, &lf,
(FONTENUMPROCW) &FontEnumerators::fontEnum1,
(LPARAM) &results, 0);
}
DeleteDC (dc);
}
results.sort (true);
return results;
}
StringArray Font::findAllTypefaceStyles (const String& family)
{
if (FontStyleHelpers::isPlaceholderFamilyName (family))
return findAllTypefaceStyles (FontStyleHelpers::getConcreteFamilyNameFromPlaceholder (family));
StringArray results;
#if JUCE_USE_DIRECTWRITE
const Direct2DFactories& factories = Direct2DFactories::getInstance();
if (factories.systemFonts != nullptr)
{
BOOL fontFound = false;
uint32 fontIndex = 0;
HRESULT hr = factories.systemFonts->FindFamilyName (family.toWideCharPointer(), &fontIndex, &fontFound);
if (! fontFound)
fontIndex = 0;
// Get the font family using the search results
// Fonts like: Times New Roman, Times New Roman Bold, Times New Roman Italic are all in the same font family
ComSmartPtr<IDWriteFontFamily> fontFamily;
hr = factories.systemFonts->GetFontFamily (fontIndex, fontFamily.resetAndGetPointerAddress());
// Get the font faces
ComSmartPtr<IDWriteFont> dwFont;
uint32 fontFacesCount = 0;
fontFacesCount = fontFamily->GetFontCount();
for (uint32 i = 0; i < fontFacesCount; ++i)
{
hr = fontFamily->GetFont (i, dwFont.resetAndGetPointerAddress());
// Ignore any algorithmically generated bold and oblique styles..
if (dwFont->GetSimulations() == DWRITE_FONT_SIMULATIONS_NONE)
results.addIfNotAlreadyThere (getFontFaceName (dwFont));
}
}
else
#endif
{
results.add ("Regular");
results.add ("Italic");
results.add ("Bold");
results.add ("Bold Italic");
}
return results;
}
extern bool juce_isRunningInWine();
struct DefaultFontNames
{
DefaultFontNames()
{
if (juce_isRunningInWine())
{
// If we're running in Wine, then use fonts that might be available on Linux..
defaultSans = "Bitstream Vera Sans";
defaultSerif = "Bitstream Vera Serif";
defaultFixed = "Bitstream Vera Sans Mono";
}
else
{
defaultSans = "Verdana";
defaultSerif = "Times New Roman";
defaultFixed = "Lucida Console";
defaultFallback = "Tahoma"; // (contains plenty of unicode characters)
}
}
String defaultSans, defaultSerif, defaultFixed, defaultFallback;
};
Typeface::Ptr Font::getDefaultTypefaceForFont (const Font& font)
{
static DefaultFontNames defaultNames;
Font newFont (font);
const String& faceName = font.getTypefaceName();
if (faceName == getDefaultSansSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSans);
else if (faceName == getDefaultSerifFontName()) newFont.setTypefaceName (defaultNames.defaultSerif);
else if (faceName == getDefaultMonospacedFontName()) newFont.setTypefaceName (defaultNames.defaultFixed);
if (font.getTypefaceStyle() == getDefaultStyle())
newFont.setTypefaceStyle ("Regular");
return Typeface::createSystemTypefaceFor (newFont);
}
//==============================================================================
class WindowsTypeface : public Typeface
{
public:
WindowsTypeface (const Font& font)
: Typeface (font.getTypefaceName(),
font.getTypefaceStyle()),
fontH (0),
previousFontH (0),
dc (CreateCompatibleDC (0)),
ascent (1.0f), heightToPointsFactor (1.0f),
defaultGlyph (-1)
{
loadFont();
if (GetTextMetrics (dc, &tm))
{
heightToPointsFactor = (72.0f / GetDeviceCaps (dc, LOGPIXELSY)) * heightInPoints / (float) tm.tmHeight;
ascent = tm.tmAscent / (float) tm.tmHeight;
defaultGlyph = getGlyphForChar (dc, tm.tmDefaultChar);
createKerningPairs (dc, (float) tm.tmHeight);
}
}
~WindowsTypeface()
{
SelectObject (dc, previousFontH); // Replacing the previous font before deleting the DC avoids a warning in BoundsChecker
DeleteDC (dc);
if (fontH != 0)
DeleteObject (fontH);
}
float getAscent() const { return ascent; }
float getDescent() const { return 1.0f - ascent; }
float getHeightToPointsFactor() const { return heightToPointsFactor; }
float getStringWidth (const String& text)
{
const CharPointer_UTF16 utf16 (text.toUTF16());
const size_t numChars = utf16.length();
HeapBlock<int16> results (numChars + 1);
results[numChars] = -1;
float x = 0;
if (GetGlyphIndices (dc, utf16, (int) numChars, reinterpret_cast <WORD*> (results.getData()),
GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR)
{
for (size_t i = 0; i < numChars; ++i)
x += getKerning (dc, results[i], results[i + 1]);
}
return x;
}
void getGlyphPositions (const String& text, Array <int>& resultGlyphs, Array <float>& xOffsets)
{
const CharPointer_UTF16 utf16 (text.toUTF16());
const size_t numChars = utf16.length();
HeapBlock<int16> results (numChars + 1);
results[numChars] = -1;
float x = 0;
if (GetGlyphIndices (dc, utf16, (int) numChars, reinterpret_cast <WORD*> (results.getData()),
GGI_MARK_NONEXISTING_GLYPHS) != GDI_ERROR)
{
resultGlyphs.ensureStorageAllocated ((int) numChars);
xOffsets.ensureStorageAllocated ((int) numChars + 1);
for (size_t i = 0; i < numChars; ++i)
{
resultGlyphs.add (results[i]);
xOffsets.add (x);
x += getKerning (dc, results[i], results[i + 1]);
}
}
xOffsets.add (x);
}
bool getOutlineForGlyph (int glyphNumber, Path& glyphPath)
{
if (glyphNumber < 0)
glyphNumber = defaultGlyph;
GLYPHMETRICS gm;
// (although GetGlyphOutline returns a DWORD, it may be -1 on failure, so treat it as signed int..)
const int bufSize = (int) GetGlyphOutline (dc, (UINT) glyphNumber, GGO_NATIVE | GGO_GLYPH_INDEX,
&gm, 0, 0, &identityMatrix);
if (bufSize > 0)
{
HeapBlock<char> data (bufSize);
GetGlyphOutline (dc, (UINT) glyphNumber, GGO_NATIVE | GGO_GLYPH_INDEX, &gm,
bufSize, data, &identityMatrix);
const TTPOLYGONHEADER* pheader = reinterpret_cast<TTPOLYGONHEADER*> (data.getData());
const float scaleX = 1.0f / tm.tmHeight;
const float scaleY = -scaleX;
while ((char*) pheader < data + bufSize)
{
glyphPath.startNewSubPath (scaleX * pheader->pfxStart.x.value,
scaleY * pheader->pfxStart.y.value);
const TTPOLYCURVE* curve = (const TTPOLYCURVE*) ((const char*) pheader + sizeof (TTPOLYGONHEADER));
const char* const curveEnd = ((const char*) pheader) + pheader->cb;
while ((const char*) curve < curveEnd)
{
if (curve->wType == TT_PRIM_LINE)
{
for (int i = 0; i < curve->cpfx; ++i)
glyphPath.lineTo (scaleX * curve->apfx[i].x.value,
scaleY * curve->apfx[i].y.value);
}
else if (curve->wType == TT_PRIM_QSPLINE)
{
for (int i = 0; i < curve->cpfx - 1; ++i)
{
const float x2 = scaleX * curve->apfx[i].x.value;
const float y2 = scaleY * curve->apfx[i].y.value;
float x3 = scaleX * curve->apfx[i + 1].x.value;
float y3 = scaleY * curve->apfx[i + 1].y.value;
if (i < curve->cpfx - 2)
{
x3 = 0.5f * (x2 + x3);
y3 = 0.5f * (y2 + y3);
}
glyphPath.quadraticTo (x2, y2, x3, y3);
}
}
curve = (const TTPOLYCURVE*) &(curve->apfx [curve->cpfx]);
}
pheader = (const TTPOLYGONHEADER*) curve;
glyphPath.closeSubPath();
}
}
return true;
}
private:
static const MAT2 identityMatrix;
HFONT fontH;
HGDIOBJ previousFontH;
HDC dc;
TEXTMETRIC tm;
float ascent, heightToPointsFactor;
int defaultGlyph, heightInPoints;
struct KerningPair
{
int glyph1, glyph2;
float kerning;
bool operator== (const KerningPair& other) const noexcept
{
return glyph1 == other.glyph1 && glyph2 == other.glyph2;
}
bool operator< (const KerningPair& other) const noexcept
{
return glyph1 < other.glyph1
|| (glyph1 == other.glyph1 && glyph2 < other.glyph2);
}
};
SortedSet<KerningPair> kerningPairs;
void loadFont()
{
SetMapperFlags (dc, 0);
SetMapMode (dc, MM_TEXT);
LOGFONTW lf = { 0 };
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfOutPrecision = OUT_OUTLINE_PRECIS;
lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
lf.lfQuality = PROOF_QUALITY;
lf.lfItalic = (BYTE) (style == "Italic" ? TRUE : FALSE);
lf.lfWeight = style == "Bold" ? FW_BOLD : FW_NORMAL;
lf.lfHeight = -256;
name.copyToUTF16 (lf.lfFaceName, sizeof (lf.lfFaceName));
HFONT standardSizedFont = CreateFontIndirect (&lf);
if (standardSizedFont != 0)
{
if ((previousFontH = SelectObject (dc, standardSizedFont)) != 0)
{
fontH = standardSizedFont;
OUTLINETEXTMETRIC otm;
if (GetOutlineTextMetrics (dc, sizeof (otm), &otm) != 0)
{
heightInPoints = otm.otmEMSquare;
lf.lfHeight = -(int) heightInPoints;
fontH = CreateFontIndirect (&lf);
SelectObject (dc, fontH);
DeleteObject (standardSizedFont);
}
}
}
}
void createKerningPairs (HDC dc, const float height)
{
HeapBlock<KERNINGPAIR> rawKerning;
const DWORD numKPs = GetKerningPairs (dc, 0, 0);
rawKerning.calloc (numKPs);
GetKerningPairs (dc, numKPs, rawKerning);
kerningPairs.ensureStorageAllocated ((int) numKPs);
for (DWORD i = 0; i < numKPs; ++i)
{
KerningPair kp;
kp.glyph1 = getGlyphForChar (dc, rawKerning[i].wFirst);
kp.glyph2 = getGlyphForChar (dc, rawKerning[i].wSecond);
const int standardWidth = getGlyphWidth (dc, kp.glyph1);
kp.kerning = (standardWidth + rawKerning[i].iKernAmount) / height;
kerningPairs.add (kp);
kp.glyph2 = -1; // add another entry for the standard width version..
kp.kerning = standardWidth / height;
kerningPairs.add (kp);
}
}
static int getGlyphForChar (HDC dc, juce_wchar character)
{
const WCHAR charToTest[] = { (WCHAR) character, 0 };
WORD index = 0;
if (GetGlyphIndices (dc, charToTest, 1, &index, GGI_MARK_NONEXISTING_GLYPHS) == GDI_ERROR
|| index == 0xffff)
return -1;
return index;
}
static int getGlyphWidth (HDC dc, int glyphNumber)
{
GLYPHMETRICS gm;
gm.gmCellIncX = 0;
GetGlyphOutline (dc, (UINT) glyphNumber, GGO_NATIVE | GGO_GLYPH_INDEX, &gm, 0, 0, &identityMatrix);
return gm.gmCellIncX;
}
float getKerning (HDC dc, const int glyph1, const int glyph2)
{
KerningPair kp;
kp.glyph1 = glyph1;
kp.glyph2 = glyph2;
int index = kerningPairs.indexOf (kp);
if (index < 0)
{
kp.glyph2 = -1;
index = kerningPairs.indexOf (kp);
if (index < 0)
{
kp.glyph2 = -1;
kp.kerning = getGlyphWidth (dc, kp.glyph1) / (float) tm.tmHeight;
kerningPairs.add (kp);
return kp.kerning;
}
}
return kerningPairs.getReference (index).kerning;
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (WindowsTypeface)
};
const MAT2 WindowsTypeface::identityMatrix = { { 0, 1 }, { 0, 0 }, { 0, 0 }, { 0, 1 } };
Typeface::Ptr Typeface::createSystemTypefaceFor (const Font& font)
{
#if JUCE_USE_DIRECTWRITE
const Direct2DFactories& factories = Direct2DFactories::getInstance();
if (factories.systemFonts != nullptr)
return new WindowsDirectWriteTypeface (font, factories.systemFonts);
#endif
return new WindowsTypeface (font);
}
void Typeface::scanFolderForFonts (const File&)
{
jassertfalse; // not implemented on this platform
}
| gpl-3.0 |
LANGFAN/ardupilot | libraries/AP_BattMonitor/AP_BattMonitor_SMBus_I2C.cpp | 4 | 5774 | #include <AP_HAL/AP_HAL.h>
#include <AP_Common/AP_Common.h>
#include <AP_Math/AP_Math.h>
#include "AP_BattMonitor.h"
#include "AP_BattMonitor_SMBus_I2C.h"
#include <utility>
extern const AP_HAL::HAL& hal;
#include <AP_HAL/AP_HAL.h>
#if CONFIG_HAL_BOARD != HAL_BOARD_PX4
#define BATTMONITOR_SMBUS_TEMP 0x08 // temperature register
#define BATTMONITOR_SMBUS_VOLTAGE 0x09 // voltage register
#define BATTMONITOR_SMBUS_FULL_CHARGE_CAPACITY 0x10 // full capacity register
#define BATTMONITOR_SMBUS_BATTERY_STATUS 0x16 // battery status register including alarms
#define BATTMONITOR_SMBUS_DESIGN_CAPACITY 0x18 // design capacity register
#define BATTMONITOR_SMBUS_DESIGN_VOLTAGE 0x19 // design voltage register
#define BATTMONITOR_SMBUS_SERIALNUM 0x1c // serial number register
#define BATTMONITOR_SMBUS_MANUFACTURE_NAME 0x20 // manufacturer name
#define BATTMONITOR_SMBUS_DEVICE_NAME 0x21 // device name
#define BATTMONITOR_SMBUS_DEVICE_CHEMISTRY 0x22 // device chemistry
#define BATTMONITOR_SMBUS_MANUFACTURE_INFO 0x25 // manufacturer info including cell voltage
#define BATTMONITOR_SMBUS_CELL_VOLTAGE 0x28 // cell voltage register
#define BATTMONITOR_SMBUS_CURRENT 0x2a // current register
// Constructor
AP_BattMonitor_SMBus_I2C::AP_BattMonitor_SMBus_I2C(AP_BattMonitor &mon, uint8_t instance,
AP_BattMonitor::BattMonitor_State &mon_state,
AP_HAL::OwnPtr<AP_HAL::I2CDevice> dev)
: AP_BattMonitor_SMBus(mon, instance, mon_state)
, _dev(std::move(dev))
{}
/// Read the battery voltage and current. Should be called at 10hz
void AP_BattMonitor_SMBus_I2C::read()
{
uint16_t data;
uint8_t buff[4];
uint32_t tnow = AP_HAL::micros();
// read voltage
if (read_word(BATTMONITOR_SMBUS_VOLTAGE, data)) {
_state.voltage = (float)data / 1000.0f;
_state.last_time_micros = tnow;
_state.healthy = true;
}
// read current
if (read_block(BATTMONITOR_SMBUS_CURRENT, buff, 4, false) == 4) {
_state.current_amps = (float)((int32_t)((uint32_t)buff[3]<<24 | (uint32_t)buff[2]<<16 | (uint32_t)buff[1]<<8 | (uint32_t)buff[0])) / 1000.0f;
_state.last_time_micros = tnow;
}
// timeout after 5 seconds
if ((tnow - _state.last_time_micros) > AP_BATTMONITOR_SMBUS_TIMEOUT_MICROS) {
_state.healthy = false;
}
}
// read word from register
// returns true if read was successful, false if failed
bool AP_BattMonitor_SMBus_I2C::read_word(uint8_t reg, uint16_t& data) const
{
// take i2c bus semaphore
if (!_dev->get_semaphore()->take_nonblocking()) {
return false;
}
uint8_t buff[3]; // buffer to hold results
// read three bytes and place in last three bytes of buffer
if (!_dev->read_registers(reg, buff, sizeof(buff))) {
_dev->get_semaphore()->give();
return false;
}
// check PEC
uint8_t pec = get_PEC(BATTMONITOR_SMBUS_I2C_ADDR, reg, true, buff, 2);
if (pec != buff[2]) {
_dev->get_semaphore()->give();
return false;
}
// convert buffer to word
data = (uint16_t)buff[1]<<8 | (uint16_t)buff[0];
// give back i2c semaphore
_dev->get_semaphore()->give();
// return success
return true;
}
// read_block - returns number of characters read if successful, zero if unsuccessful
uint8_t AP_BattMonitor_SMBus_I2C::read_block(uint8_t reg, uint8_t* data, uint8_t max_len, bool append_zero) const
{
uint8_t buff[max_len+2]; // buffer to hold results (2 extra byte returned holding length and PEC)
// take i2c bus semaphore
if (!_dev->get_semaphore()->take_nonblocking()) {
return 0;
}
// read bytes
if (!_dev->read_registers(reg, buff, sizeof(buff))) {
_dev->get_semaphore()->give();
return 0;
}
// give back i2c semaphore
_dev->get_semaphore()->give();
// get length
uint8_t bufflen = buff[0];
// sanity check length returned by smbus
if (bufflen == 0 || bufflen > max_len) {
return 0;
}
// check PEC
uint8_t pec = get_PEC(BATTMONITOR_SMBUS_I2C_ADDR, reg, true, buff, bufflen+1);
if (pec != buff[bufflen+1]) {
return 0;
}
// copy data (excluding PEC)
memcpy(data, &buff[1], bufflen);
// optionally add zero to end
if (append_zero) {
data[bufflen] = '\0';
}
// return success
return bufflen;
}
#define SMBUS_PEC_POLYNOME 0x07 // Polynome for CRC generation
/// get_PEC - calculate packet error correction code of buffer
uint8_t AP_BattMonitor_SMBus_I2C::get_PEC(const uint8_t i2c_addr, uint8_t cmd, bool reading, const uint8_t buff[], uint8_t len) const
{
// exit immediately if no data
if (len <= 0) {
return 0;
}
// prepare temp buffer for calcing crc
uint8_t tmp_buff[len+3];
tmp_buff[0] = i2c_addr << 1;
tmp_buff[1] = cmd;
tmp_buff[2] = tmp_buff[0] | (uint8_t)reading;
memcpy(&tmp_buff[3],buff,len);
// initialise crc to zero
uint8_t crc = 0;
uint8_t shift_reg = 0;
bool do_invert;
// for each byte in the stream
for (uint8_t i=0; i<sizeof(tmp_buff); i++) {
// load next data byte into the shift register
shift_reg = tmp_buff[i];
// for each bit in the current byte
for (uint8_t j=0; j<8; j++) {
do_invert = (crc ^ shift_reg) & 0x80;
crc <<= 1;
shift_reg <<= 1;
if(do_invert) {
crc ^= SMBUS_PEC_POLYNOME;
}
}
}
// return result
return crc;
}
#endif // CONFIG_HAL_BOARD != HAL_BOARD_PX4
| gpl-3.0 |
lthall/Leonard_ardupilot | libraries/AP_Baro/AP_Baro_DPS280.cpp | 4 | 8510 | /*
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/>.
*/
/*
DPS280 barometer driver
*/
#include "AP_Baro_DPS280.h"
#if AP_BARO_DPS280_ENABLED
#include <utility>
#include <stdio.h>
#include <AP_Math/definitions.h>
extern const AP_HAL::HAL &hal;
#define DPS280_REG_PRESS 0x00
#define DPS280_REG_TEMP 0x03
#define DPS280_REG_PCONF 0x06
#define DPS280_REG_TCONF 0x07
#define DPS280_REG_MCONF 0x08
#define DPS280_REG_CREG 0x09
#define DPS280_REG_ISTS 0x0A
#define DPS280_REG_FSTS 0x0B
#define DPS280_REG_RESET 0x0C
#define DPS280_REG_PID 0x0D
#define DPS280_REG_COEF 0x10
#define DPS280_REG_CSRC 0x28
#define DPS280_WHOAMI 0x10
#define TEMPERATURE_LIMIT_C 120
AP_Baro_DPS280::AP_Baro_DPS280(AP_Baro &baro, AP_HAL::OwnPtr<AP_HAL::Device> _dev)
: AP_Baro_Backend(baro)
, dev(std::move(_dev))
{
}
AP_Baro_Backend *AP_Baro_DPS280::probe(AP_Baro &baro,
AP_HAL::OwnPtr<AP_HAL::Device> _dev, bool _is_dps310)
{
if (!_dev) {
return nullptr;
}
AP_Baro_DPS280 *sensor = new AP_Baro_DPS280(baro, std::move(_dev));
if (sensor) {
sensor->is_dps310 = _is_dps310;
}
if (!sensor || !sensor->init()) {
delete sensor;
return nullptr;
}
return sensor;
}
AP_Baro_Backend *AP_Baro_DPS310::probe(AP_Baro &baro,
AP_HAL::OwnPtr<AP_HAL::Device> _dev)
{
// same as DPS280 but with is_dps310 set for temperature fix
return AP_Baro_DPS280::probe(baro, std::move(_dev), true);
}
/*
handle bit width for 16 bit config registers
*/
void AP_Baro_DPS280::fix_config_bits16(int16_t &v, uint8_t bits) const
{
if (v > int16_t((1U<<(bits-1))-1)) {
v = v - (1U<<bits);
}
}
/*
handle bit width for 32 bit config registers
*/
void AP_Baro_DPS280::fix_config_bits32(int32_t &v, uint8_t bits) const
{
if (v > int32_t((1U<<(bits-1))-1)) {
v = v - (1U<<bits);
}
}
/*
read calibration data
*/
bool AP_Baro_DPS280::read_calibration(void)
{
uint8_t buf[18];
if (!dev->read_registers(DPS280_REG_COEF, buf, 18)) {
return false;
}
calibration.C0 = (buf[0] << 4) + ((buf[1] >>4) & 0x0F);
calibration.C1 = (buf[2] + ((buf[1] & 0x0F)<<8));
calibration.C00 = ((buf[4]<<4) + (buf[3]<<12)) + ((buf[5]>>4) & 0x0F);
calibration.C10 = ((buf[5] & 0x0F)<<16) + buf[7] + (buf[6]<<8);
calibration.C01 = (buf[9] + (buf[8]<<8));
calibration.C11 = (buf[11] + (buf[10]<<8));
calibration.C20 = (buf[13] + (buf[12]<<8));
calibration.C21 = (buf[15] + (buf[14]<<8));
calibration.C30 = (buf[17] + (buf[16]<<8));
fix_config_bits16(calibration.C0, 12);
fix_config_bits16(calibration.C1, 12);
fix_config_bits32(calibration.C00, 20);
fix_config_bits32(calibration.C10, 20);
fix_config_bits16(calibration.C01, 16);
fix_config_bits16(calibration.C11, 16);
fix_config_bits16(calibration.C20, 16);
fix_config_bits16(calibration.C21, 16);
fix_config_bits16(calibration.C30, 16);
/* get calibration source */
if (!dev->read_registers(DPS280_REG_CSRC, &calibration.temp_source, 1)) {
return false;
}
calibration.temp_source &= 0x80;
return true;
}
void AP_Baro_DPS280::set_config_registers(void)
{
dev->write_register(DPS280_REG_CREG, 0x0C, true); // shift for 16x oversampling
dev->write_register(DPS280_REG_PCONF, 0x54, true); // 32 Hz, 16x oversample
dev->write_register(DPS280_REG_TCONF, 0x54 | calibration.temp_source, true); // 32 Hz, 16x oversample
dev->write_register(DPS280_REG_MCONF, 0x07); // continuous temp and pressure.
if (is_dps310) {
// work around broken temperature handling on some sensors
// using undocumented register writes
// see https://github.com/infineon/DPS310-Pressure-Sensor/blob/dps310/src/DpsClass.cpp#L442
dev->write_register(0x0E, 0xA5);
dev->write_register(0x0F, 0x96);
dev->write_register(0x62, 0x02);
dev->write_register(0x0E, 0x00);
dev->write_register(0x0F, 0x00);
}
}
bool AP_Baro_DPS280::init()
{
if (!dev) {
return false;
}
dev->get_semaphore()->take_blocking();
// setup to allow reads on SPI
if (dev->bus_type() == AP_HAL::Device::BUS_TYPE_SPI) {
dev->set_read_flag(0x80);
}
dev->set_speed(AP_HAL::Device::SPEED_HIGH);
// the DPS310 can get into a state on boot where the whoami is not
// read correctly at startup. Toggling the CS line gets its out of
// this state
dev->set_chip_select(true);
dev->set_chip_select(false);
uint8_t whoami=0;
if (!dev->read_registers(DPS280_REG_PID, &whoami, 1) ||
whoami != DPS280_WHOAMI) {
dev->get_semaphore()->give();
return false;
}
if (!read_calibration()) {
dev->get_semaphore()->give();
return false;
}
dev->setup_checked_registers(4, 20);
set_config_registers();
instance = _frontend.register_sensor();
dev->set_device_type(DEVTYPE_BARO_DPS280);
set_bus_id(instance, dev->get_bus_id());
dev->get_semaphore()->give();
// request 64Hz update. New data will be available at 32Hz
dev->register_periodic_callback((1000 / 64) * AP_USEC_PER_MSEC, FUNCTOR_BIND_MEMBER(&AP_Baro_DPS280::timer, void));
return true;
}
/*
calculate corrected pressure and temperature
*/
void AP_Baro_DPS280::calculate_PT(int32_t UT, int32_t UP, float &pressure, float &temperature)
{
const struct dps280_cal &cal = calibration;
// scaling for 16x oversampling
const float scaling_16 = 1.0f/253952;
float temp_scaled;
float press_scaled;
temp_scaled = float(UT) * scaling_16;
temperature = cal.C0 * 0.5f + cal.C1 * temp_scaled;
press_scaled = float(UP) * scaling_16;
pressure = cal.C00;
pressure += press_scaled * (cal.C10 + press_scaled * (cal.C20 + press_scaled * cal.C30));
pressure += temp_scaled * cal.C01;
pressure += temp_scaled * press_scaled * (cal.C11 + press_scaled * cal.C21);
}
/*
check health and possibly reset
*/
void AP_Baro_DPS280::check_health(void)
{
dev->check_next_register();
if (fabsf(last_temperature) > TEMPERATURE_LIMIT_C) {
err_count++;
}
if (err_count > 16) {
err_count = 0;
dev->write_register(DPS280_REG_RESET, 0x09);
set_config_registers();
pending_reset = true;
}
}
// acumulate a new sensor reading
void AP_Baro_DPS280::timer(void)
{
uint8_t buf[6];
uint8_t ready;
if (pending_reset) {
// reset registers after software reset from check_health()
pending_reset = false;
set_config_registers();
return;
}
if (!dev->read_registers(DPS280_REG_MCONF, &ready, 1) ||
!(ready & (1U<<4)) ||
!dev->read_registers(DPS280_REG_PRESS, buf, 3) ||
!dev->read_registers(DPS280_REG_TEMP, &buf[3], 3)) {
// data not ready
err_count++;
check_health();
return;
}
int32_t press = (buf[2]) + (buf[1]<<8) + (buf[0]<<16);
int32_t temp = (buf[5]) + (buf[4]<<8) + (buf[3]<<16);
fix_config_bits32(press, 24);
fix_config_bits32(temp, 24);
float pressure, temperature;
calculate_PT(temp, press, pressure, temperature);
last_temperature = temperature;
if (!pressure_ok(pressure)) {
return;
}
check_health();
if (fabsf(last_temperature) <= TEMPERATURE_LIMIT_C) {
err_count = 0;
}
WITH_SEMAPHORE(_sem);
pressure_sum += pressure;
temperature_sum += temperature;
count++;
}
// transfer data to the frontend
void AP_Baro_DPS280::update(void)
{
if (count == 0) {
return;
}
WITH_SEMAPHORE(_sem);
_copy_to_frontend(instance, pressure_sum/count, temperature_sum/count);
pressure_sum = 0;
temperature_sum = 0;
count=0;
}
#endif // AP_BARO_DPS280_ENABLED
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | external/wpa_supplicant_8_rtl/src/eap_server/eap_server_peap.c | 4 | 32310 | /*
* hostapd / EAP-PEAP (draft-josefsson-pppext-eap-tls-eap-10.txt)
* Copyright (c) 2004-2008, Jouni Malinen <j@w1.fi>
*
* This software may be distributed under the terms of the BSD license.
* See README for more details.
*/
#include "includes.h"
#include "common.h"
#include "crypto/sha1.h"
#include "crypto/tls.h"
#include "crypto/random.h"
#include "eap_i.h"
#include "eap_tls_common.h"
#include "eap_common/eap_tlv_common.h"
#include "eap_common/eap_peap_common.h"
#include "tncs.h"
/* Maximum supported PEAP version
* 0 = Microsoft's PEAP version 0; draft-kamath-pppext-peapv0-00.txt
* 1 = draft-josefsson-ppext-eap-tls-eap-05.txt
*/
#define EAP_PEAP_VERSION 1
static void eap_peap_reset(struct eap_sm *sm, void *priv);
struct eap_peap_data {
struct eap_ssl_data ssl;
enum {
START, PHASE1, PHASE1_ID2, PHASE2_START, PHASE2_ID,
PHASE2_METHOD, PHASE2_SOH,
PHASE2_TLV, SUCCESS_REQ, FAILURE_REQ, SUCCESS, FAILURE
} state;
int peap_version;
int recv_version;
const struct eap_method *phase2_method;
void *phase2_priv;
int force_version;
struct wpabuf *pending_phase2_resp;
enum { TLV_REQ_NONE, TLV_REQ_SUCCESS, TLV_REQ_FAILURE } tlv_request;
int crypto_binding_sent;
int crypto_binding_used;
enum { NO_BINDING, OPTIONAL_BINDING, REQUIRE_BINDING } crypto_binding;
u8 binding_nonce[32];
u8 ipmk[40];
u8 cmk[20];
u8 *phase2_key;
size_t phase2_key_len;
struct wpabuf *soh_response;
};
static const char * eap_peap_state_txt(int state)
{
switch (state) {
case START:
return "START";
case PHASE1:
return "PHASE1";
case PHASE1_ID2:
return "PHASE1_ID2";
case PHASE2_START:
return "PHASE2_START";
case PHASE2_ID:
return "PHASE2_ID";
case PHASE2_METHOD:
return "PHASE2_METHOD";
case PHASE2_SOH:
return "PHASE2_SOH";
case PHASE2_TLV:
return "PHASE2_TLV";
case SUCCESS_REQ:
return "SUCCESS_REQ";
case FAILURE_REQ:
return "FAILURE_REQ";
case SUCCESS:
return "SUCCESS";
case FAILURE:
return "FAILURE";
default:
return "Unknown?!";
}
}
static void eap_peap_state(struct eap_peap_data *data, int state)
{
wpa_printf(MSG_DEBUG, "EAP-PEAP: %s -> %s",
eap_peap_state_txt(data->state),
eap_peap_state_txt(state));
data->state = state;
}
static void eap_peap_req_success(struct eap_sm *sm,
struct eap_peap_data *data)
{
if (data->state == FAILURE || data->state == FAILURE_REQ) {
eap_peap_state(data, FAILURE);
return;
}
if (data->peap_version == 0) {
data->tlv_request = TLV_REQ_SUCCESS;
eap_peap_state(data, PHASE2_TLV);
} else {
eap_peap_state(data, SUCCESS_REQ);
}
}
static void eap_peap_req_failure(struct eap_sm *sm,
struct eap_peap_data *data)
{
if (data->state == FAILURE || data->state == FAILURE_REQ ||
data->state == SUCCESS_REQ || data->tlv_request != TLV_REQ_NONE) {
eap_peap_state(data, FAILURE);
return;
}
if (data->peap_version == 0) {
data->tlv_request = TLV_REQ_FAILURE;
eap_peap_state(data, PHASE2_TLV);
} else {
eap_peap_state(data, FAILURE_REQ);
}
}
static void * eap_peap_init(struct eap_sm *sm)
{
struct eap_peap_data *data;
data = os_zalloc(sizeof(*data));
if (data == NULL)
return NULL;
data->peap_version = EAP_PEAP_VERSION;
data->force_version = -1;
if (sm->user && sm->user->force_version >= 0) {
data->force_version = sm->user->force_version;
wpa_printf(MSG_DEBUG, "EAP-PEAP: forcing version %d",
data->force_version);
data->peap_version = data->force_version;
}
data->state = START;
data->crypto_binding = OPTIONAL_BINDING;
if (eap_server_tls_ssl_init(sm, &data->ssl, 0)) {
wpa_printf(MSG_INFO, "EAP-PEAP: Failed to initialize SSL.");
eap_peap_reset(sm, data);
return NULL;
}
return data;
}
static void eap_peap_reset(struct eap_sm *sm, void *priv)
{
struct eap_peap_data *data = priv;
if (data == NULL)
return;
if (data->phase2_priv && data->phase2_method)
data->phase2_method->reset(sm, data->phase2_priv);
eap_server_tls_ssl_deinit(sm, &data->ssl);
wpabuf_free(data->pending_phase2_resp);
os_free(data->phase2_key);
wpabuf_free(data->soh_response);
bin_clear_free(data, sizeof(*data));
}
static struct wpabuf * eap_peap_build_start(struct eap_sm *sm,
struct eap_peap_data *data, u8 id)
{
struct wpabuf *req;
req = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_PEAP, 1,
EAP_CODE_REQUEST, id);
if (req == NULL) {
wpa_printf(MSG_ERROR, "EAP-PEAP: Failed to allocate memory for"
" request");
eap_peap_state(data, FAILURE);
return NULL;
}
wpabuf_put_u8(req, EAP_TLS_FLAGS_START | data->peap_version);
eap_peap_state(data, PHASE1);
return req;
}
static struct wpabuf * eap_peap_build_phase2_req(struct eap_sm *sm,
struct eap_peap_data *data,
u8 id)
{
struct wpabuf *buf, *encr_req, msgbuf;
const u8 *req;
size_t req_len;
if (data->phase2_method == NULL || data->phase2_priv == NULL) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase 2 method not ready");
return NULL;
}
buf = data->phase2_method->buildReq(sm, data->phase2_priv, id);
if (buf == NULL)
return NULL;
req = wpabuf_head(buf);
req_len = wpabuf_len(buf);
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: Encrypting Phase 2 data",
req, req_len);
if (data->peap_version == 0 &&
data->phase2_method->method != EAP_TYPE_TLV) {
req += sizeof(struct eap_hdr);
req_len -= sizeof(struct eap_hdr);
}
wpabuf_set(&msgbuf, req, req_len);
encr_req = eap_server_tls_encrypt(sm, &data->ssl, &msgbuf);
wpabuf_free(buf);
return encr_req;
}
#ifdef EAP_SERVER_TNC
static struct wpabuf * eap_peap_build_phase2_soh(struct eap_sm *sm,
struct eap_peap_data *data,
u8 id)
{
struct wpabuf *buf1, *buf, *encr_req, msgbuf;
const u8 *req;
size_t req_len;
buf1 = tncs_build_soh_request();
if (buf1 == NULL)
return NULL;
buf = eap_msg_alloc(EAP_VENDOR_MICROSOFT, 0x21, wpabuf_len(buf1),
EAP_CODE_REQUEST, id);
if (buf == NULL) {
wpabuf_free(buf1);
return NULL;
}
wpabuf_put_buf(buf, buf1);
wpabuf_free(buf1);
req = wpabuf_head(buf);
req_len = wpabuf_len(buf);
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: Encrypting Phase 2 SOH data",
req, req_len);
req += sizeof(struct eap_hdr);
req_len -= sizeof(struct eap_hdr);
wpabuf_set(&msgbuf, req, req_len);
encr_req = eap_server_tls_encrypt(sm, &data->ssl, &msgbuf);
wpabuf_free(buf);
return encr_req;
}
#endif /* EAP_SERVER_TNC */
static void eap_peap_get_isk(struct eap_peap_data *data,
u8 *isk, size_t isk_len)
{
size_t key_len;
os_memset(isk, 0, isk_len);
if (data->phase2_key == NULL)
return;
key_len = data->phase2_key_len;
if (key_len > isk_len)
key_len = isk_len;
os_memcpy(isk, data->phase2_key, key_len);
}
static int eap_peap_derive_cmk(struct eap_sm *sm, struct eap_peap_data *data)
{
u8 *tk;
u8 isk[32], imck[60];
/*
* Tunnel key (TK) is the first 60 octets of the key generated by
* phase 1 of PEAP (based on TLS).
*/
tk = eap_server_tls_derive_key(sm, &data->ssl, "client EAP encryption",
EAP_TLS_KEY_LEN);
if (tk == NULL)
return -1;
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: TK", tk, 60);
eap_peap_get_isk(data, isk, sizeof(isk));
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: ISK", isk, sizeof(isk));
/*
* IPMK Seed = "Inner Methods Compound Keys" | ISK
* TempKey = First 40 octets of TK
* IPMK|CMK = PRF+(TempKey, IPMK Seed, 60)
* (note: draft-josefsson-pppext-eap-tls-eap-10.txt includes a space
* in the end of the label just before ISK; is that just a typo?)
*/
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: TempKey", tk, 40);
if (peap_prfplus(data->peap_version, tk, 40,
"Inner Methods Compound Keys",
isk, sizeof(isk), imck, sizeof(imck)) < 0) {
os_free(tk);
return -1;
}
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: IMCK (IPMKj)",
imck, sizeof(imck));
os_free(tk);
/* TODO: fast-connect: IPMK|CMK = TK */
os_memcpy(data->ipmk, imck, 40);
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: IPMK (S-IPMKj)", data->ipmk, 40);
os_memcpy(data->cmk, imck + 40, 20);
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: CMK (CMKj)", data->cmk, 20);
return 0;
}
static struct wpabuf * eap_peap_build_phase2_tlv(struct eap_sm *sm,
struct eap_peap_data *data,
u8 id)
{
struct wpabuf *buf, *encr_req;
size_t mlen;
mlen = 6; /* Result TLV */
if (data->crypto_binding != NO_BINDING)
mlen += 60; /* Cryptobinding TLV */
#ifdef EAP_SERVER_TNC
if (data->soh_response)
mlen += wpabuf_len(data->soh_response);
#endif /* EAP_SERVER_TNC */
buf = eap_msg_alloc(EAP_VENDOR_IETF, EAP_TYPE_TLV, mlen,
EAP_CODE_REQUEST, id);
if (buf == NULL)
return NULL;
wpabuf_put_u8(buf, 0x80); /* Mandatory */
wpabuf_put_u8(buf, EAP_TLV_RESULT_TLV);
/* Length */
wpabuf_put_be16(buf, 2);
/* Status */
wpabuf_put_be16(buf, data->tlv_request == TLV_REQ_SUCCESS ?
EAP_TLV_RESULT_SUCCESS : EAP_TLV_RESULT_FAILURE);
if (data->peap_version == 0 && data->tlv_request == TLV_REQ_SUCCESS &&
data->crypto_binding != NO_BINDING) {
u8 *mac;
u8 eap_type = EAP_TYPE_PEAP;
const u8 *addr[2];
size_t len[2];
u16 tlv_type;
#ifdef EAP_SERVER_TNC
if (data->soh_response) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Adding MS-SOH "
"Response TLV");
wpabuf_put_buf(buf, data->soh_response);
wpabuf_free(data->soh_response);
data->soh_response = NULL;
}
#endif /* EAP_SERVER_TNC */
if (eap_peap_derive_cmk(sm, data) < 0 ||
random_get_bytes(data->binding_nonce, 32)) {
wpabuf_free(buf);
return NULL;
}
/* Compound_MAC: HMAC-SHA1-160(cryptobinding TLV | EAP type) */
addr[0] = wpabuf_put(buf, 0);
len[0] = 60;
addr[1] = &eap_type;
len[1] = 1;
tlv_type = EAP_TLV_CRYPTO_BINDING_TLV;
wpabuf_put_be16(buf, tlv_type);
wpabuf_put_be16(buf, 56);
wpabuf_put_u8(buf, 0); /* Reserved */
wpabuf_put_u8(buf, data->peap_version); /* Version */
wpabuf_put_u8(buf, data->recv_version); /* RecvVersion */
wpabuf_put_u8(buf, 0); /* SubType: 0 = Request, 1 = Response */
wpabuf_put_data(buf, data->binding_nonce, 32); /* Nonce */
mac = wpabuf_put(buf, 20); /* Compound_MAC */
wpa_hexdump(MSG_MSGDUMP, "EAP-PEAP: Compound_MAC CMK",
data->cmk, 20);
wpa_hexdump(MSG_MSGDUMP, "EAP-PEAP: Compound_MAC data 1",
addr[0], len[0]);
wpa_hexdump(MSG_MSGDUMP, "EAP-PEAP: Compound_MAC data 2",
addr[1], len[1]);
hmac_sha1_vector(data->cmk, 20, 2, addr, len, mac);
wpa_hexdump(MSG_MSGDUMP, "EAP-PEAP: Compound_MAC",
mac, SHA1_MAC_LEN);
data->crypto_binding_sent = 1;
}
wpa_hexdump_buf_key(MSG_DEBUG, "EAP-PEAP: Encrypting Phase 2 TLV data",
buf);
encr_req = eap_server_tls_encrypt(sm, &data->ssl, buf);
wpabuf_free(buf);
return encr_req;
}
static struct wpabuf * eap_peap_build_phase2_term(struct eap_sm *sm,
struct eap_peap_data *data,
u8 id, int success)
{
struct wpabuf *encr_req, msgbuf;
size_t req_len;
struct eap_hdr *hdr;
req_len = sizeof(*hdr);
hdr = os_zalloc(req_len);
if (hdr == NULL)
return NULL;
hdr->code = success ? EAP_CODE_SUCCESS : EAP_CODE_FAILURE;
hdr->identifier = id;
hdr->length = host_to_be16(req_len);
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: Encrypting Phase 2 data",
(u8 *) hdr, req_len);
wpabuf_set(&msgbuf, hdr, req_len);
encr_req = eap_server_tls_encrypt(sm, &data->ssl, &msgbuf);
os_free(hdr);
return encr_req;
}
static struct wpabuf * eap_peap_buildReq(struct eap_sm *sm, void *priv, u8 id)
{
struct eap_peap_data *data = priv;
if (data->ssl.state == FRAG_ACK) {
return eap_server_tls_build_ack(id, EAP_TYPE_PEAP,
data->peap_version);
}
if (data->ssl.state == WAIT_FRAG_ACK) {
return eap_server_tls_build_msg(&data->ssl, EAP_TYPE_PEAP,
data->peap_version, id);
}
switch (data->state) {
case START:
return eap_peap_build_start(sm, data, id);
case PHASE1:
case PHASE1_ID2:
if (tls_connection_established(sm->ssl_ctx, data->ssl.conn)) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase1 done, "
"starting Phase2");
eap_peap_state(data, PHASE2_START);
}
break;
case PHASE2_ID:
case PHASE2_METHOD:
wpabuf_free(data->ssl.tls_out);
data->ssl.tls_out_pos = 0;
data->ssl.tls_out = eap_peap_build_phase2_req(sm, data, id);
break;
#ifdef EAP_SERVER_TNC
case PHASE2_SOH:
wpabuf_free(data->ssl.tls_out);
data->ssl.tls_out_pos = 0;
data->ssl.tls_out = eap_peap_build_phase2_soh(sm, data, id);
break;
#endif /* EAP_SERVER_TNC */
case PHASE2_TLV:
wpabuf_free(data->ssl.tls_out);
data->ssl.tls_out_pos = 0;
data->ssl.tls_out = eap_peap_build_phase2_tlv(sm, data, id);
break;
case SUCCESS_REQ:
wpabuf_free(data->ssl.tls_out);
data->ssl.tls_out_pos = 0;
data->ssl.tls_out = eap_peap_build_phase2_term(sm, data, id,
1);
break;
case FAILURE_REQ:
wpabuf_free(data->ssl.tls_out);
data->ssl.tls_out_pos = 0;
data->ssl.tls_out = eap_peap_build_phase2_term(sm, data, id,
0);
break;
default:
wpa_printf(MSG_DEBUG, "EAP-PEAP: %s - unexpected state %d",
__func__, data->state);
return NULL;
}
return eap_server_tls_build_msg(&data->ssl, EAP_TYPE_PEAP,
data->peap_version, id);
}
static Boolean eap_peap_check(struct eap_sm *sm, void *priv,
struct wpabuf *respData)
{
const u8 *pos;
size_t len;
pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_PEAP, respData, &len);
if (pos == NULL || len < 1) {
wpa_printf(MSG_INFO, "EAP-PEAP: Invalid frame");
return TRUE;
}
return FALSE;
}
static int eap_peap_phase2_init(struct eap_sm *sm, struct eap_peap_data *data,
EapType eap_type)
{
if (data->phase2_priv && data->phase2_method) {
data->phase2_method->reset(sm, data->phase2_priv);
data->phase2_method = NULL;
data->phase2_priv = NULL;
}
data->phase2_method = eap_server_get_eap_method(EAP_VENDOR_IETF,
eap_type);
if (!data->phase2_method)
return -1;
sm->init_phase2 = 1;
data->phase2_priv = data->phase2_method->init(sm);
sm->init_phase2 = 0;
return 0;
}
static int eap_tlv_validate_cryptobinding(struct eap_sm *sm,
struct eap_peap_data *data,
const u8 *crypto_tlv,
size_t crypto_tlv_len)
{
u8 buf[61], mac[SHA1_MAC_LEN];
const u8 *pos;
if (crypto_tlv_len != 4 + 56) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Invalid cryptobinding TLV "
"length %d", (int) crypto_tlv_len);
return -1;
}
pos = crypto_tlv;
pos += 4; /* TLV header */
if (pos[1] != data->peap_version) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Cryptobinding TLV Version "
"mismatch (was %d; expected %d)",
pos[1], data->peap_version);
return -1;
}
if (pos[3] != 1) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Unexpected Cryptobinding TLV "
"SubType %d", pos[3]);
return -1;
}
pos += 4;
pos += 32; /* Nonce */
/* Compound_MAC: HMAC-SHA1-160(cryptobinding TLV | EAP type) */
os_memcpy(buf, crypto_tlv, 60);
os_memset(buf + 4 + 4 + 32, 0, 20); /* Compound_MAC */
buf[60] = EAP_TYPE_PEAP;
hmac_sha1(data->cmk, 20, buf, sizeof(buf), mac);
if (os_memcmp_const(mac, pos, SHA1_MAC_LEN) != 0) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Invalid Compound_MAC in "
"cryptobinding TLV");
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: CMK", data->cmk, 20);
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Cryptobinding seed data",
buf, 61);
return -1;
}
wpa_printf(MSG_DEBUG, "EAP-PEAP: Valid cryptobinding TLV received");
return 0;
}
static void eap_peap_process_phase2_tlv(struct eap_sm *sm,
struct eap_peap_data *data,
struct wpabuf *in_data)
{
const u8 *pos;
size_t left;
const u8 *result_tlv = NULL, *crypto_tlv = NULL;
size_t result_tlv_len = 0, crypto_tlv_len = 0;
int tlv_type, mandatory, tlv_len;
pos = eap_hdr_validate(EAP_VENDOR_IETF, EAP_TYPE_TLV, in_data, &left);
if (pos == NULL) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Invalid EAP-TLV header");
return;
}
/* Parse TLVs */
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Received TLVs", pos, left);
while (left >= 4) {
mandatory = !!(pos[0] & 0x80);
tlv_type = pos[0] & 0x3f;
tlv_type = (tlv_type << 8) | pos[1];
tlv_len = ((int) pos[2] << 8) | pos[3];
pos += 4;
left -= 4;
if ((size_t) tlv_len > left) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: TLV underrun "
"(tlv_len=%d left=%lu)", tlv_len,
(unsigned long) left);
eap_peap_state(data, FAILURE);
return;
}
switch (tlv_type) {
case EAP_TLV_RESULT_TLV:
result_tlv = pos;
result_tlv_len = tlv_len;
break;
case EAP_TLV_CRYPTO_BINDING_TLV:
crypto_tlv = pos;
crypto_tlv_len = tlv_len;
break;
default:
wpa_printf(MSG_DEBUG, "EAP-PEAP: Unsupported TLV Type "
"%d%s", tlv_type,
mandatory ? " (mandatory)" : "");
if (mandatory) {
eap_peap_state(data, FAILURE);
return;
}
/* Ignore this TLV, but process other TLVs */
break;
}
pos += tlv_len;
left -= tlv_len;
}
if (left) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Last TLV too short in "
"Request (left=%lu)", (unsigned long) left);
eap_peap_state(data, FAILURE);
return;
}
/* Process supported TLVs */
if (crypto_tlv && data->crypto_binding_sent) {
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Cryptobinding TLV",
crypto_tlv, crypto_tlv_len);
if (eap_tlv_validate_cryptobinding(sm, data, crypto_tlv - 4,
crypto_tlv_len + 4) < 0) {
eap_peap_state(data, FAILURE);
return;
}
data->crypto_binding_used = 1;
} else if (!crypto_tlv && data->crypto_binding_sent &&
data->crypto_binding == REQUIRE_BINDING) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: No cryptobinding TLV");
eap_peap_state(data, FAILURE);
return;
}
if (result_tlv) {
int status;
const char *requested;
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Result TLV",
result_tlv, result_tlv_len);
if (result_tlv_len < 2) {
wpa_printf(MSG_INFO, "EAP-PEAP: Too short Result TLV "
"(len=%lu)",
(unsigned long) result_tlv_len);
eap_peap_state(data, FAILURE);
return;
}
requested = data->tlv_request == TLV_REQ_SUCCESS ? "Success" :
"Failure";
status = WPA_GET_BE16(result_tlv);
if (status == EAP_TLV_RESULT_SUCCESS) {
wpa_printf(MSG_INFO, "EAP-PEAP: TLV Result - Success "
"- requested %s", requested);
if (data->tlv_request == TLV_REQ_SUCCESS)
eap_peap_state(data, SUCCESS);
else
eap_peap_state(data, FAILURE);
} else if (status == EAP_TLV_RESULT_FAILURE) {
wpa_printf(MSG_INFO, "EAP-PEAP: TLV Result - Failure "
"- requested %s", requested);
eap_peap_state(data, FAILURE);
} else {
wpa_printf(MSG_INFO, "EAP-PEAP: Unknown TLV Result "
"Status %d", status);
eap_peap_state(data, FAILURE);
}
}
}
#ifdef EAP_SERVER_TNC
static void eap_peap_process_phase2_soh(struct eap_sm *sm,
struct eap_peap_data *data,
struct wpabuf *in_data)
{
const u8 *pos, *vpos;
size_t left;
const u8 *soh_tlv = NULL;
size_t soh_tlv_len = 0;
int tlv_type, mandatory, tlv_len, vtlv_len;
u8 next_type;
u32 vendor_id;
pos = eap_hdr_validate(EAP_VENDOR_MICROSOFT, 0x21, in_data, &left);
if (pos == NULL) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Not a valid SoH EAP "
"Extensions Method header - skip TNC");
goto auth_method;
}
/* Parse TLVs */
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Received TLVs (SoH)", pos, left);
while (left >= 4) {
mandatory = !!(pos[0] & 0x80);
tlv_type = pos[0] & 0x3f;
tlv_type = (tlv_type << 8) | pos[1];
tlv_len = ((int) pos[2] << 8) | pos[3];
pos += 4;
left -= 4;
if ((size_t) tlv_len > left) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: TLV underrun "
"(tlv_len=%d left=%lu)", tlv_len,
(unsigned long) left);
eap_peap_state(data, FAILURE);
return;
}
switch (tlv_type) {
case EAP_TLV_VENDOR_SPECIFIC_TLV:
if (tlv_len < 4) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Too short "
"vendor specific TLV (len=%d)",
(int) tlv_len);
eap_peap_state(data, FAILURE);
return;
}
vendor_id = WPA_GET_BE32(pos);
if (vendor_id != EAP_VENDOR_MICROSOFT) {
if (mandatory) {
eap_peap_state(data, FAILURE);
return;
}
break;
}
vpos = pos + 4;
mandatory = !!(vpos[0] & 0x80);
tlv_type = vpos[0] & 0x3f;
tlv_type = (tlv_type << 8) | vpos[1];
vtlv_len = ((int) vpos[2] << 8) | vpos[3];
vpos += 4;
if (vpos + vtlv_len > pos + left) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Vendor TLV "
"underrun");
eap_peap_state(data, FAILURE);
return;
}
if (tlv_type == 1) {
soh_tlv = vpos;
soh_tlv_len = vtlv_len;
break;
}
wpa_printf(MSG_DEBUG, "EAP-PEAP: Unsupported MS-TLV "
"Type %d%s", tlv_type,
mandatory ? " (mandatory)" : "");
if (mandatory) {
eap_peap_state(data, FAILURE);
return;
}
/* Ignore this TLV, but process other TLVs */
break;
default:
wpa_printf(MSG_DEBUG, "EAP-PEAP: Unsupported TLV Type "
"%d%s", tlv_type,
mandatory ? " (mandatory)" : "");
if (mandatory) {
eap_peap_state(data, FAILURE);
return;
}
/* Ignore this TLV, but process other TLVs */
break;
}
pos += tlv_len;
left -= tlv_len;
}
if (left) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Last TLV too short in "
"Request (left=%lu)", (unsigned long) left);
eap_peap_state(data, FAILURE);
return;
}
/* Process supported TLVs */
if (soh_tlv) {
int failure = 0;
wpabuf_free(data->soh_response);
data->soh_response = tncs_process_soh(soh_tlv, soh_tlv_len,
&failure);
if (failure) {
eap_peap_state(data, FAILURE);
return;
}
} else {
wpa_printf(MSG_DEBUG, "EAP-PEAP: No SoH TLV received");
eap_peap_state(data, FAILURE);
return;
}
auth_method:
eap_peap_state(data, PHASE2_METHOD);
next_type = sm->user->methods[0].method;
sm->user_eap_method_index = 1;
wpa_printf(MSG_DEBUG, "EAP-PEAP: try EAP type %d", next_type);
eap_peap_phase2_init(sm, data, next_type);
}
#endif /* EAP_SERVER_TNC */
static void eap_peap_process_phase2_response(struct eap_sm *sm,
struct eap_peap_data *data,
struct wpabuf *in_data)
{
u8 next_type = EAP_TYPE_NONE;
const struct eap_hdr *hdr;
const u8 *pos;
size_t left;
if (data->state == PHASE2_TLV) {
eap_peap_process_phase2_tlv(sm, data, in_data);
return;
}
#ifdef EAP_SERVER_TNC
if (data->state == PHASE2_SOH) {
eap_peap_process_phase2_soh(sm, data, in_data);
return;
}
#endif /* EAP_SERVER_TNC */
if (data->phase2_priv == NULL) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: %s - Phase2 not "
"initialized?!", __func__);
return;
}
hdr = wpabuf_head(in_data);
pos = (const u8 *) (hdr + 1);
if (wpabuf_len(in_data) > sizeof(*hdr) && *pos == EAP_TYPE_NAK) {
left = wpabuf_len(in_data) - sizeof(*hdr);
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Phase2 type Nak'ed; "
"allowed types", pos + 1, left - 1);
eap_sm_process_nak(sm, pos + 1, left - 1);
if (sm->user && sm->user_eap_method_index < EAP_MAX_METHODS &&
sm->user->methods[sm->user_eap_method_index].method !=
EAP_TYPE_NONE) {
next_type = sm->user->methods[
sm->user_eap_method_index++].method;
wpa_printf(MSG_DEBUG, "EAP-PEAP: try EAP type %d",
next_type);
} else {
eap_peap_req_failure(sm, data);
next_type = EAP_TYPE_NONE;
}
eap_peap_phase2_init(sm, data, next_type);
return;
}
if (data->phase2_method->check(sm, data->phase2_priv, in_data)) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase2 check() asked to "
"ignore the packet");
return;
}
data->phase2_method->process(sm, data->phase2_priv, in_data);
if (sm->method_pending == METHOD_PENDING_WAIT) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase2 method is in "
"pending wait state - save decrypted response");
wpabuf_free(data->pending_phase2_resp);
data->pending_phase2_resp = wpabuf_dup(in_data);
}
if (!data->phase2_method->isDone(sm, data->phase2_priv))
return;
if (!data->phase2_method->isSuccess(sm, data->phase2_priv)) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase2 method failed");
eap_peap_req_failure(sm, data);
next_type = EAP_TYPE_NONE;
eap_peap_phase2_init(sm, data, next_type);
return;
}
os_free(data->phase2_key);
if (data->phase2_method->getKey) {
data->phase2_key = data->phase2_method->getKey(
sm, data->phase2_priv, &data->phase2_key_len);
if (data->phase2_key == NULL) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase2 getKey "
"failed");
eap_peap_req_failure(sm, data);
eap_peap_phase2_init(sm, data, EAP_TYPE_NONE);
return;
}
}
switch (data->state) {
case PHASE1_ID2:
case PHASE2_ID:
case PHASE2_SOH:
if (eap_user_get(sm, sm->identity, sm->identity_len, 1) != 0) {
wpa_hexdump_ascii(MSG_DEBUG, "EAP_PEAP: Phase2 "
"Identity not found in the user "
"database",
sm->identity, sm->identity_len);
eap_peap_req_failure(sm, data);
next_type = EAP_TYPE_NONE;
break;
}
#ifdef EAP_SERVER_TNC
if (data->state != PHASE2_SOH && sm->tnc &&
data->peap_version == 0) {
eap_peap_state(data, PHASE2_SOH);
wpa_printf(MSG_DEBUG, "EAP-PEAP: Try to initialize "
"TNC (NAP SOH)");
next_type = EAP_TYPE_NONE;
break;
}
#endif /* EAP_SERVER_TNC */
eap_peap_state(data, PHASE2_METHOD);
next_type = sm->user->methods[0].method;
sm->user_eap_method_index = 1;
wpa_printf(MSG_DEBUG, "EAP-PEAP: try EAP type %d", next_type);
break;
case PHASE2_METHOD:
eap_peap_req_success(sm, data);
next_type = EAP_TYPE_NONE;
break;
case FAILURE:
break;
default:
wpa_printf(MSG_DEBUG, "EAP-PEAP: %s - unexpected state %d",
__func__, data->state);
break;
}
eap_peap_phase2_init(sm, data, next_type);
}
static void eap_peap_process_phase2(struct eap_sm *sm,
struct eap_peap_data *data,
const struct wpabuf *respData,
struct wpabuf *in_buf)
{
struct wpabuf *in_decrypted;
const struct eap_hdr *hdr;
size_t len;
wpa_printf(MSG_DEBUG, "EAP-PEAP: received %lu bytes encrypted data for"
" Phase 2", (unsigned long) wpabuf_len(in_buf));
if (data->pending_phase2_resp) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Pending Phase 2 response - "
"skip decryption and use old data");
eap_peap_process_phase2_response(sm, data,
data->pending_phase2_resp);
wpabuf_free(data->pending_phase2_resp);
data->pending_phase2_resp = NULL;
return;
}
in_decrypted = tls_connection_decrypt(sm->ssl_ctx, data->ssl.conn,
in_buf);
if (in_decrypted == NULL) {
wpa_printf(MSG_INFO, "EAP-PEAP: Failed to decrypt Phase 2 "
"data");
eap_peap_state(data, FAILURE);
return;
}
wpa_hexdump_buf_key(MSG_DEBUG, "EAP-PEAP: Decrypted Phase 2 EAP",
in_decrypted);
if (data->peap_version == 0 && data->state != PHASE2_TLV) {
const struct eap_hdr *resp;
struct eap_hdr *nhdr;
struct wpabuf *nbuf =
wpabuf_alloc(sizeof(struct eap_hdr) +
wpabuf_len(in_decrypted));
if (nbuf == NULL) {
wpabuf_free(in_decrypted);
return;
}
resp = wpabuf_head(respData);
nhdr = wpabuf_put(nbuf, sizeof(*nhdr));
nhdr->code = resp->code;
nhdr->identifier = resp->identifier;
nhdr->length = host_to_be16(sizeof(struct eap_hdr) +
wpabuf_len(in_decrypted));
wpabuf_put_buf(nbuf, in_decrypted);
wpabuf_free(in_decrypted);
in_decrypted = nbuf;
}
hdr = wpabuf_head(in_decrypted);
if (wpabuf_len(in_decrypted) < (int) sizeof(*hdr)) {
wpa_printf(MSG_INFO, "EAP-PEAP: Too short Phase 2 "
"EAP frame (len=%lu)",
(unsigned long) wpabuf_len(in_decrypted));
wpabuf_free(in_decrypted);
eap_peap_req_failure(sm, data);
return;
}
len = be_to_host16(hdr->length);
if (len > wpabuf_len(in_decrypted)) {
wpa_printf(MSG_INFO, "EAP-PEAP: Length mismatch in "
"Phase 2 EAP frame (len=%lu hdr->length=%lu)",
(unsigned long) wpabuf_len(in_decrypted),
(unsigned long) len);
wpabuf_free(in_decrypted);
eap_peap_req_failure(sm, data);
return;
}
wpa_printf(MSG_DEBUG, "EAP-PEAP: received Phase 2: code=%d "
"identifier=%d length=%lu", hdr->code, hdr->identifier,
(unsigned long) len);
switch (hdr->code) {
case EAP_CODE_RESPONSE:
eap_peap_process_phase2_response(sm, data, in_decrypted);
break;
case EAP_CODE_SUCCESS:
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase 2 Success");
if (data->state == SUCCESS_REQ) {
eap_peap_state(data, SUCCESS);
}
break;
case EAP_CODE_FAILURE:
wpa_printf(MSG_DEBUG, "EAP-PEAP: Phase 2 Failure");
eap_peap_state(data, FAILURE);
break;
default:
wpa_printf(MSG_INFO, "EAP-PEAP: Unexpected code=%d in "
"Phase 2 EAP header", hdr->code);
break;
}
wpabuf_free(in_decrypted);
}
static int eap_peap_process_version(struct eap_sm *sm, void *priv,
int peer_version)
{
struct eap_peap_data *data = priv;
data->recv_version = peer_version;
if (data->force_version >= 0 && peer_version != data->force_version) {
wpa_printf(MSG_INFO, "EAP-PEAP: peer did not select the forced"
" version (forced=%d peer=%d) - reject",
data->force_version, peer_version);
return -1;
}
if (peer_version < data->peap_version) {
wpa_printf(MSG_DEBUG, "EAP-PEAP: peer ver=%d, own ver=%d; "
"use version %d",
peer_version, data->peap_version, peer_version);
data->peap_version = peer_version;
}
return 0;
}
static void eap_peap_process_msg(struct eap_sm *sm, void *priv,
const struct wpabuf *respData)
{
struct eap_peap_data *data = priv;
switch (data->state) {
case PHASE1:
if (eap_server_tls_phase1(sm, &data->ssl) < 0) {
eap_peap_state(data, FAILURE);
break;
}
break;
case PHASE2_START:
eap_peap_state(data, PHASE2_ID);
eap_peap_phase2_init(sm, data, EAP_TYPE_IDENTITY);
break;
case PHASE1_ID2:
case PHASE2_ID:
case PHASE2_METHOD:
case PHASE2_SOH:
case PHASE2_TLV:
eap_peap_process_phase2(sm, data, respData, data->ssl.tls_in);
break;
case SUCCESS_REQ:
eap_peap_state(data, SUCCESS);
break;
case FAILURE_REQ:
eap_peap_state(data, FAILURE);
break;
default:
wpa_printf(MSG_DEBUG, "EAP-PEAP: Unexpected state %d in %s",
data->state, __func__);
break;
}
}
static void eap_peap_process(struct eap_sm *sm, void *priv,
struct wpabuf *respData)
{
struct eap_peap_data *data = priv;
if (eap_server_tls_process(sm, &data->ssl, respData, data,
EAP_TYPE_PEAP, eap_peap_process_version,
eap_peap_process_msg) < 0)
eap_peap_state(data, FAILURE);
}
static Boolean eap_peap_isDone(struct eap_sm *sm, void *priv)
{
struct eap_peap_data *data = priv;
return data->state == SUCCESS || data->state == FAILURE;
}
static u8 * eap_peap_getKey(struct eap_sm *sm, void *priv, size_t *len)
{
struct eap_peap_data *data = priv;
u8 *eapKeyData;
if (data->state != SUCCESS)
return NULL;
if (data->crypto_binding_used) {
u8 csk[128];
/*
* Note: It looks like Microsoft implementation requires null
* termination for this label while the one used for deriving
* IPMK|CMK did not use null termination.
*/
if (peap_prfplus(data->peap_version, data->ipmk, 40,
"Session Key Generating Function",
(u8 *) "\00", 1, csk, sizeof(csk)) < 0)
return NULL;
wpa_hexdump_key(MSG_DEBUG, "EAP-PEAP: CSK", csk, sizeof(csk));
eapKeyData = os_malloc(EAP_TLS_KEY_LEN);
if (eapKeyData) {
os_memcpy(eapKeyData, csk, EAP_TLS_KEY_LEN);
*len = EAP_TLS_KEY_LEN;
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Derived key",
eapKeyData, EAP_TLS_KEY_LEN);
} else {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Failed to derive "
"key");
}
return eapKeyData;
}
/* TODO: PEAPv1 - different label in some cases */
eapKeyData = eap_server_tls_derive_key(sm, &data->ssl,
"client EAP encryption",
EAP_TLS_KEY_LEN);
if (eapKeyData) {
*len = EAP_TLS_KEY_LEN;
wpa_hexdump(MSG_DEBUG, "EAP-PEAP: Derived key",
eapKeyData, EAP_TLS_KEY_LEN);
} else {
wpa_printf(MSG_DEBUG, "EAP-PEAP: Failed to derive key");
}
return eapKeyData;
}
static Boolean eap_peap_isSuccess(struct eap_sm *sm, void *priv)
{
struct eap_peap_data *data = priv;
return data->state == SUCCESS;
}
int eap_server_peap_register(void)
{
struct eap_method *eap;
int ret;
eap = eap_server_method_alloc(EAP_SERVER_METHOD_INTERFACE_VERSION,
EAP_VENDOR_IETF, EAP_TYPE_PEAP, "PEAP");
if (eap == NULL)
return -1;
eap->init = eap_peap_init;
eap->reset = eap_peap_reset;
eap->buildReq = eap_peap_buildReq;
eap->check = eap_peap_check;
eap->process = eap_peap_process;
eap->isDone = eap_peap_isDone;
eap->getKey = eap_peap_getKey;
eap->isSuccess = eap_peap_isSuccess;
ret = eap_server_method_register(eap);
if (ret)
eap_server_method_free(eap);
return ret;
}
| gpl-3.0 |
ignatenkobrain/eiskaltdcpp | json/jsoncpp/src/json_reader.cpp | 4 | 22334 | // Copyright 2007-2011 Baptiste Lepilleur
// Distributed under MIT license, or public domain if desired and
// recognized in your jurisdiction.
// See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
#if !defined(JSON_IS_AMALGAMATION)
# include <json/assertions.h>
# include <json/reader.h>
# include <json/value.h>
# include "json_tool.h"
#endif // if !defined(JSON_IS_AMALGAMATION)
#include <utility>
#include <cstdio>
#include <cassert>
#include <cstring>
#include <istream>
#include <stdexcept>
#if defined(_MSC_VER) && _MSC_VER >= 1400 // VC++ 8.0
#pragma warning( disable : 4996 ) // disable warning about strdup being deprecated.
#endif
namespace Json {
// Implementation of class Features
// ////////////////////////////////
Features::Features()
: allowComments_( true )
, strictRoot_( false )
{
}
Features
Features::all()
{
return Features();
}
Features
Features::strictMode()
{
Features features;
features.allowComments_ = false;
features.strictRoot_ = true;
return features;
}
// Implementation of class Reader
// ////////////////////////////////
static inline bool
in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4 )
{
return c == c1 || c == c2 || c == c3 || c == c4;
}
static inline bool
in( Reader::Char c, Reader::Char c1, Reader::Char c2, Reader::Char c3, Reader::Char c4, Reader::Char c5 )
{
return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
}
static bool
containsNewLine( Reader::Location begin,
Reader::Location end )
{
for ( ;begin < end; ++begin )
if ( *begin == '\n' || *begin == '\r' )
return true;
return false;
}
// Class Reader
// //////////////////////////////////////////////////////////////////
Reader::Reader()
: errors_(),
document_(),
begin_(),
end_(),
current_(),
lastValueEnd_(),
lastValue_(),
commentsBefore_(),
features_( Features::all() ),
collectComments_()
{
}
Reader::Reader( const Features &features )
: errors_(),
document_(),
begin_(),
end_(),
current_(),
lastValueEnd_(),
lastValue_(),
commentsBefore_(),
features_( features ),
collectComments_()
{
}
bool
Reader::parse( const std::string &document,
Value &root,
bool collectComments )
{
document_ = document;
const char *begin = document_.c_str();
const char *end = begin + document_.length();
return parse( begin, end, root, collectComments );
}
bool
Reader::parse( std::istream& sin,
Value &root,
bool collectComments )
{
//std::istream_iterator<char> begin(sin);
//std::istream_iterator<char> end;
// Those would allow streamed input from a file, if parse() were a
// template function.
// Since std::string is reference-counted, this at least does not
// create an extra copy.
std::string doc;
std::getline(sin, doc, (char)EOF);
return parse( doc, root, collectComments );
}
bool
Reader::parse( const char *beginDoc, const char *endDoc,
Value &root,
bool collectComments )
{
if ( !features_.allowComments_ )
{
collectComments = false;
}
begin_ = beginDoc;
end_ = endDoc;
collectComments_ = collectComments;
current_ = begin_;
lastValueEnd_ = 0;
lastValue_ = 0;
commentsBefore_ = "";
errors_.clear();
while ( !nodes_.empty() )
nodes_.pop();
nodes_.push( &root );
bool successful = readValue();
Token token;
skipCommentTokens( token );
if ( collectComments_ && !commentsBefore_.empty() )
root.setComment( commentsBefore_, commentAfter );
if ( features_.strictRoot_ )
{
if ( !root.isArray() && !root.isObject() )
{
// Set error location to start of doc, ideally should be first token found in doc
token.type_ = tokenError;
token.start_ = beginDoc;
token.end_ = endDoc;
addError( "A valid JSON document must be either an array or an object value.",
token );
return false;
}
}
return successful;
}
bool
Reader::readValue()
{
Token token;
skipCommentTokens( token );
bool successful = true;
if ( collectComments_ && !commentsBefore_.empty() )
{
currentValue().setComment( commentsBefore_, commentBefore );
commentsBefore_ = "";
}
switch ( token.type_ )
{
case tokenObjectBegin:
successful = readObject( token );
break;
case tokenArrayBegin:
successful = readArray( token );
break;
case tokenNumber:
successful = decodeNumber( token );
break;
case tokenString:
successful = decodeString( token );
break;
case tokenTrue:
currentValue() = true;
break;
case tokenFalse:
currentValue() = false;
break;
case tokenNull:
currentValue() = Value();
break;
default:
return addError( "Syntax error: value, object or array expected.", token );
}
if ( collectComments_ )
{
lastValueEnd_ = current_;
lastValue_ = ¤tValue();
}
return successful;
}
void
Reader::skipCommentTokens( Token &token )
{
if ( features_.allowComments_ )
{
do
{
readToken( token );
}
while ( token.type_ == tokenComment );
}
else
{
readToken( token );
}
}
bool
Reader::expectToken( TokenType type, Token &token, const char *message )
{
readToken( token );
if ( token.type_ != type )
return addError( message, token );
return true;
}
bool
Reader::readToken( Token &token )
{
skipSpaces();
token.start_ = current_;
Char c = getNextChar();
bool ok = true;
switch ( c )
{
case '{':
token.type_ = tokenObjectBegin;
break;
case '}':
token.type_ = tokenObjectEnd;
break;
case '[':
token.type_ = tokenArrayBegin;
break;
case ']':
token.type_ = tokenArrayEnd;
break;
case '"':
token.type_ = tokenString;
ok = readString();
break;
case '/':
token.type_ = tokenComment;
ok = readComment();
break;
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case '-':
token.type_ = tokenNumber;
readNumber();
break;
case 't':
token.type_ = tokenTrue;
ok = match( "rue", 3 );
break;
case 'f':
token.type_ = tokenFalse;
ok = match( "alse", 4 );
break;
case 'n':
token.type_ = tokenNull;
ok = match( "ull", 3 );
break;
case ',':
token.type_ = tokenArraySeparator;
break;
case ':':
token.type_ = tokenMemberSeparator;
break;
case 0:
token.type_ = tokenEndOfStream;
break;
default:
ok = false;
break;
}
if ( !ok )
token.type_ = tokenError;
token.end_ = current_;
return true;
}
void
Reader::skipSpaces()
{
while ( current_ != end_ )
{
Char c = *current_;
if ( c == ' ' || c == '\t' || c == '\r' || c == '\n' )
++current_;
else
break;
}
}
bool
Reader::match( Location pattern,
int patternLength )
{
if ( end_ - current_ < patternLength )
return false;
int index = patternLength;
while ( index-- )
if ( current_[index] != pattern[index] )
return false;
current_ += patternLength;
return true;
}
bool
Reader::readComment()
{
Location commentBegin = current_ - 1;
Char c = getNextChar();
bool successful = false;
if ( c == '*' )
successful = readCStyleComment();
else if ( c == '/' )
successful = readCppStyleComment();
if ( !successful )
return false;
if ( collectComments_ )
{
CommentPlacement placement = commentBefore;
if ( lastValueEnd_ && !containsNewLine( lastValueEnd_, commentBegin ) )
{
if ( c != '*' || !containsNewLine( commentBegin, current_ ) )
placement = commentAfterOnSameLine;
}
addComment( commentBegin, current_, placement );
}
return true;
}
void
Reader::addComment( Location begin,
Location end,
CommentPlacement placement )
{
assert( collectComments_ );
if ( placement == commentAfterOnSameLine )
{
assert( lastValue_ != 0 );
lastValue_->setComment( std::string( begin, end ), placement );
}
else
{
if ( !commentsBefore_.empty() )
commentsBefore_ += "\n";
commentsBefore_ += std::string( begin, end );
}
}
bool
Reader::readCStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '*' && *current_ == '/' )
break;
}
return getNextChar() == '/';
}
bool
Reader::readCppStyleComment()
{
while ( current_ != end_ )
{
Char c = getNextChar();
if ( c == '\r' || c == '\n' )
break;
}
return true;
}
void
Reader::readNumber()
{
while ( current_ != end_ )
{
if ( !(*current_ >= '0' && *current_ <= '9') &&
!in( *current_, '.', 'e', 'E', '+', '-' ) )
break;
++current_;
}
}
bool
Reader::readString()
{
Char c = 0;
while ( current_ != end_ )
{
c = getNextChar();
if ( c == '\\' )
getNextChar();
else if ( c == '"' )
break;
}
return c == '"';
}
bool
Reader::readObject( Token &/*tokenStart*/ )
{
Token tokenName;
std::string name;
currentValue() = Value( objectValue );
while ( readToken( tokenName ) )
{
bool initialTokenOk = true;
while ( tokenName.type_ == tokenComment && initialTokenOk )
initialTokenOk = readToken( tokenName );
if ( !initialTokenOk )
break;
if ( tokenName.type_ == tokenObjectEnd && name.empty() ) // empty object
return true;
if ( tokenName.type_ != tokenString )
break;
name = "";
if ( !decodeString( tokenName, name ) )
return recoverFromError( tokenObjectEnd );
Token colon;
if ( !readToken( colon ) || colon.type_ != tokenMemberSeparator )
{
return addErrorAndRecover( "Missing ':' after object member name",
colon,
tokenObjectEnd );
}
Value &value = currentValue()[ name ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenObjectEnd );
Token comma;
if ( !readToken( comma )
|| ( comma.type_ != tokenObjectEnd &&
comma.type_ != tokenArraySeparator &&
comma.type_ != tokenComment ) )
{
return addErrorAndRecover( "Missing ',' or '}' in object declaration",
comma,
tokenObjectEnd );
}
bool finalizeTokenOk = true;
while ( comma.type_ == tokenComment &&
finalizeTokenOk )
finalizeTokenOk = readToken( comma );
if ( comma.type_ == tokenObjectEnd )
return true;
}
return addErrorAndRecover( "Missing '}' or object member name",
tokenName,
tokenObjectEnd );
}
bool
Reader::readArray( Token &/*tokenStart*/ )
{
currentValue() = Value( arrayValue );
skipSpaces();
if ( *current_ == ']' ) // empty array
{
Token endArray;
readToken( endArray );
return true;
}
int index = 0;
for (;;)
{
Value &value = currentValue()[ index++ ];
nodes_.push( &value );
bool ok = readValue();
nodes_.pop();
if ( !ok ) // error already set
return recoverFromError( tokenArrayEnd );
Token token;
// Accept Comment after last item in the array.
ok = readToken( token );
while ( token.type_ == tokenComment && ok )
{
ok = readToken( token );
}
bool badTokenType = ( token.type_ != tokenArraySeparator &&
token.type_ != tokenArrayEnd );
if ( !ok || badTokenType )
{
return addErrorAndRecover( "Missing ',' or ']' in array declaration",
token,
tokenArrayEnd );
}
if ( token.type_ == tokenArrayEnd )
break;
}
return true;
}
bool
Reader::decodeNumber( Token &token )
{
bool isDouble = false;
for ( Location inspect = token.start_; inspect != token.end_; ++inspect )
{
isDouble = isDouble
|| in( *inspect, '.', 'e', 'E', '+' )
|| ( *inspect == '-' && inspect != token.start_ );
}
if ( isDouble )
return decodeDouble( token );
// Attempts to parse the number as an integer. If the number is
// larger than the maximum supported value of an integer then
// we decode the number as a double.
Location current = token.start_;
bool isNegative = *current == '-';
if ( isNegative )
++current;
Value::LargestUInt maxIntegerValue = isNegative ? Value::LargestUInt(-Value::minLargestInt)
: Value::maxLargestUInt;
Value::LargestUInt threshold = maxIntegerValue / 10;
Value::LargestUInt value = 0;
while ( current < token.end_ )
{
Char c = *current++;
if ( c < '0' || c > '9' )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
Value::UInt digit(c - '0');
if ( value >= threshold )
{
// We've hit or exceeded the max value divided by 10 (rounded down). If
// a) we've only just touched the limit, b) this is the last digit, and
// c) it's small enough to fit in that rounding delta, we're okay.
// Otherwise treat this number as a double to avoid overflow.
if (value > threshold ||
current != token.end_ ||
digit > maxIntegerValue % 10)
{
return decodeDouble( token );
}
}
value = value * 10 + digit;
}
if ( isNegative )
currentValue() = -Value::LargestInt( value );
else if ( value <= Value::LargestUInt(Value::maxInt) )
currentValue() = Value::LargestInt( value );
else
currentValue() = value;
return true;
}
bool
Reader::decodeDouble( Token &token )
{
double value = 0;
const int bufferSize = 32;
int count;
int length = int(token.end_ - token.start_);
// Sanity check to avoid buffer overflow exploits.
if (length < 0) {
return addError( "Unable to parse token length", token );
}
// Avoid using a string constant for the format control string given to
// sscanf, as this can cause hard to debug crashes on OS X. See here for more
// info:
//
// http://developer.apple.com/library/mac/#DOCUMENTATION/DeveloperTools/gcc-4.0.1/gcc/Incompatibilities.html
char format[] = "%lf";
if ( length <= bufferSize )
{
Char buffer[bufferSize+1];
memcpy( buffer, token.start_, length );
buffer[length] = 0;
count = sscanf( buffer, format, &value );
}
else
{
std::string buffer( token.start_, token.end_ );
count = sscanf( buffer.c_str(), format, &value );
}
if ( count != 1 )
return addError( "'" + std::string( token.start_, token.end_ ) + "' is not a number.", token );
currentValue() = value;
return true;
}
bool
Reader::decodeString( Token &token )
{
std::string decoded;
if ( !decodeString( token, decoded ) )
return false;
currentValue() = decoded;
return true;
}
bool
Reader::decodeString( Token &token, std::string &decoded )
{
decoded.reserve( token.end_ - token.start_ - 2 );
Location current = token.start_ + 1; // skip '"'
Location end = token.end_ - 1; // do not include '"'
while ( current != end )
{
Char c = *current++;
if ( c == '"' )
break;
else if ( c == '\\' )
{
if ( current == end )
return addError( "Empty escape sequence in string", token, current );
Char escape = *current++;
switch ( escape )
{
case '"': decoded += '"'; break;
case '/': decoded += '/'; break;
case '\\': decoded += '\\'; break;
case 'b': decoded += '\b'; break;
case 'f': decoded += '\f'; break;
case 'n': decoded += '\n'; break;
case 'r': decoded += '\r'; break;
case 't': decoded += '\t'; break;
case 'u':
{
unsigned int unicode;
if ( !decodeUnicodeCodePoint( token, current, end, unicode ) )
return false;
decoded += codePointToUTF8(unicode);
}
break;
default:
return addError( "Bad escape sequence in string", token, current );
}
}
else
{
decoded += c;
}
}
return true;
}
bool
Reader::decodeUnicodeCodePoint( Token &token,
Location ¤t,
Location end,
unsigned int &unicode )
{
if ( !decodeUnicodeEscapeSequence( token, current, end, unicode ) )
return false;
if (unicode >= 0xD800 && unicode <= 0xDBFF)
{
// surrogate pairs
if (end - current < 6)
return addError( "additional six characters expected to parse unicode surrogate pair.", token, current );
unsigned int surrogatePair;
if (*(current++) == '\\' && *(current++)== 'u')
{
if (decodeUnicodeEscapeSequence( token, current, end, surrogatePair ))
{
unicode = 0x10000 + ((unicode & 0x3FF) << 10) + (surrogatePair & 0x3FF);
}
else
return false;
}
else
return addError( "expecting another \\u token to begin the second half of a unicode surrogate pair", token, current );
}
return true;
}
bool
Reader::decodeUnicodeEscapeSequence( Token &token,
Location ¤t,
Location end,
unsigned int &unicode )
{
if ( end - current < 4 )
return addError( "Bad unicode escape sequence in string: four digits expected.", token, current );
unicode = 0;
for ( int index =0; index < 4; ++index )
{
Char c = *current++;
unicode *= 16;
if ( c >= '0' && c <= '9' )
unicode += c - '0';
else if ( c >= 'a' && c <= 'f' )
unicode += c - 'a' + 10;
else if ( c >= 'A' && c <= 'F' )
unicode += c - 'A' + 10;
else
return addError( "Bad unicode escape sequence in string: hexadecimal digit expected.", token, current );
}
return true;
}
bool
Reader::addError( const std::string &message,
Token &token,
Location extra )
{
ErrorInfo info;
info.token_ = token;
info.message_ = message;
info.extra_ = extra;
errors_.push_back( info );
return false;
}
bool
Reader::recoverFromError( TokenType skipUntilToken )
{
int errorCount = int(errors_.size());
Token skip;
for (;;)
{
if ( !readToken(skip) )
errors_.resize( errorCount ); // discard errors caused by recovery
if ( skip.type_ == skipUntilToken || skip.type_ == tokenEndOfStream )
break;
}
errors_.resize( errorCount );
return false;
}
bool
Reader::addErrorAndRecover( const std::string &message,
Token &token,
TokenType skipUntilToken )
{
addError( message, token );
return recoverFromError( skipUntilToken );
}
Value &
Reader::currentValue()
{
return *(nodes_.top());
}
Reader::Char
Reader::getNextChar()
{
if ( current_ == end_ )
return 0;
return *current_++;
}
void
Reader::getLocationLineAndColumn( Location location,
int &line,
int &column ) const
{
Location current = begin_;
Location lastLineStart = current;
line = 0;
while ( current < location && current != end_ )
{
Char c = *current++;
if ( c == '\r' )
{
if ( *current == '\n' )
++current;
lastLineStart = current;
++line;
}
else if ( c == '\n' )
{
lastLineStart = current;
++line;
}
}
// column & line start at 1
column = int(location - lastLineStart) + 1;
++line;
}
std::string
Reader::getLocationLineAndColumn( Location location ) const
{
int line, column;
getLocationLineAndColumn( location, line, column );
char buffer[18+16+16+1];
#if defined(_MSC_VER) && defined(__STDC_SECURE_LIB__)
sprintf_s(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#else
snprintf(buffer, sizeof(buffer), "Line %d, Column %d", line, column);
#endif
return buffer;
}
// Deprecated. Preserved for backward compatibility
std::string
Reader::getFormatedErrorMessages() const
{
return getFormattedErrorMessages();
}
std::string
Reader::getFormattedErrorMessages() const
{
std::string formattedMessage;
for ( Errors::const_iterator itError = errors_.begin();
itError != errors_.end();
++itError )
{
const ErrorInfo &error = *itError;
formattedMessage += "* " + getLocationLineAndColumn( error.token_.start_ ) + "\n";
formattedMessage += " " + error.message_ + "\n";
if ( error.extra_ )
formattedMessage += "See " + getLocationLineAndColumn( error.extra_ ) + " for detail.\n";
}
return formattedMessage;
}
std::istream& operator>>( std::istream &sin, Value &root )
{
Json::Reader reader;
bool ok = reader.parse(sin, root, true);
if (!ok) {
fprintf(
stderr,
"Error from reader: %s",
reader.getFormattedErrorMessages().c_str());
JSON_FAIL_MESSAGE("reader error");
}
return sin;
}
} // namespace Json
| gpl-3.0 |
asfadmin/ASF_MapReady | src/libasf_export/brs2jpg.c | 4 | 1267 | #include "asf.h"
#include "asf_meta.h"
#include "asf_export.h"
int brs2jpg(char *browseFile, char *workreportFile, char *outFile)
{
FILE *fp;
char *baseName, tmpDataFile[1024], tmpDir[1024], line[1024];
meta_parameters *meta;
// Create temporary directory
baseName = get_basename(outFile);
strcpy(tmpDir, baseName);
strcat(tmpDir, "-");
strcat(tmpDir, time_stamp_dir());
create_clean_dir(tmpDir);
// Generate ASF internal file
meta = raw_init();
meta->general->image_data_type = BROWSE_IMAGE;
fp = FOPEN(workreportFile, "r");
while (fgets(line, 1024, fp)) {
if (strncmp(line, "Brs_NoOfBrowseLines", 19) == 0)
sscanf(line, "Brs_NoOfBrowseLines=\"%d\"", &meta->general->line_count);
else if (strncmp(line, "Brs_NoOfBrowsePixels", 20) == 0)
sscanf(line, "Brs_NoOfBrowsePixels=\"%d\"", &meta->general->sample_count);
else if (strncmp(line, "Brs_BrowseBitPixel=\"8\"", 22) == 0)
meta->general->data_type = ASF_BYTE;
}
FCLOSE(fp);
sprintf(tmpDataFile, "%s/%s.img", tmpDir, baseName);
meta_write(meta, tmpDataFile);
fileCopy(browseFile, tmpDataFile);
// Export to JPEG and clean up
asf_export(JPEG, SIGMA, tmpDataFile, outFile);
remove_dir(tmpDir);
meta_free(meta);
return EXIT_SUCCESS;
}
| gpl-3.0 |
neutered/propgcc | gdb/gdb/osabi.c | 5 | 18784 | /* OS ABI variant handling for GDB.
Copyright (C) 2001, 2002, 2003, 2004, 2007, 2008, 2009, 2010, 2011
Free Software Foundation, Inc.
This file is part of GDB.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>. */
#include "defs.h"
#include "gdb_assert.h"
#include "gdb_string.h"
#include "osabi.h"
#include "arch-utils.h"
#include "gdbcmd.h"
#include "command.h"
#include "elf-bfd.h"
#ifndef GDB_OSABI_DEFAULT
#define GDB_OSABI_DEFAULT GDB_OSABI_UNKNOWN
#endif
/* State for the "set osabi" command. */
static enum { osabi_auto, osabi_default, osabi_user } user_osabi_state;
static enum gdb_osabi user_selected_osabi;
static const char *gdb_osabi_available_names[GDB_OSABI_INVALID + 3] = {
"auto",
"default",
"none",
NULL
};
static const char *set_osabi_string;
/* This table matches the indices assigned to enum gdb_osabi. Keep
them in sync. */
static const char * const gdb_osabi_names[] =
{
"none",
"SVR4",
"GNU/Hurd",
"Solaris",
"OSF/1",
"GNU/Linux",
"FreeBSD a.out",
"FreeBSD ELF",
"NetBSD a.out",
"NetBSD ELF",
"OpenBSD ELF",
"Windows CE",
"DJGPP",
"Irix",
"Interix",
"HP/UX ELF",
"HP/UX SOM",
"QNX Neutrino",
"Cygwin",
"AIX",
"DICOS",
"Darwin",
"Symbian",
"<invalid>"
};
const char *
gdbarch_osabi_name (enum gdb_osabi osabi)
{
if (osabi >= GDB_OSABI_UNKNOWN && osabi < GDB_OSABI_INVALID)
return gdb_osabi_names[osabi];
return gdb_osabi_names[GDB_OSABI_INVALID];
}
/* Lookup the OS ABI corresponding to the specified target description
string. */
enum gdb_osabi
osabi_from_tdesc_string (const char *name)
{
int i;
for (i = 0; i < ARRAY_SIZE (gdb_osabi_names); i++)
if (strcmp (name, gdb_osabi_names[i]) == 0)
{
/* See note above: the name table matches the indices assigned
to enum gdb_osabi. */
enum gdb_osabi osabi = (enum gdb_osabi) i;
if (osabi == GDB_OSABI_INVALID)
return GDB_OSABI_UNKNOWN;
else
return osabi;
}
return GDB_OSABI_UNKNOWN;
}
/* Handler for a given architecture/OS ABI pair. There should be only
one handler for a given OS ABI each architecture family. */
struct gdb_osabi_handler
{
struct gdb_osabi_handler *next;
const struct bfd_arch_info *arch_info;
enum gdb_osabi osabi;
void (*init_osabi)(struct gdbarch_info, struct gdbarch *);
};
static struct gdb_osabi_handler *gdb_osabi_handler_list;
void
gdbarch_register_osabi (enum bfd_architecture arch, unsigned long machine,
enum gdb_osabi osabi,
void (*init_osabi)(struct gdbarch_info,
struct gdbarch *))
{
struct gdb_osabi_handler **handler_p;
const struct bfd_arch_info *arch_info = bfd_lookup_arch (arch, machine);
const char **name_ptr;
/* Registering an OS ABI handler for "unknown" is not allowed. */
if (osabi == GDB_OSABI_UNKNOWN)
{
internal_error
(__FILE__, __LINE__,
_("gdbarch_register_osabi: An attempt to register a handler for "
"OS ABI \"%s\" for architecture %s was made. The handler will "
"not be registered"),
gdbarch_osabi_name (osabi),
bfd_printable_arch_mach (arch, machine));
return;
}
gdb_assert (arch_info);
for (handler_p = &gdb_osabi_handler_list; *handler_p != NULL;
handler_p = &(*handler_p)->next)
{
if ((*handler_p)->arch_info == arch_info
&& (*handler_p)->osabi == osabi)
{
internal_error
(__FILE__, __LINE__,
_("gdbarch_register_osabi: A handler for OS ABI \"%s\" "
"has already been registered for architecture %s"),
gdbarch_osabi_name (osabi),
arch_info->printable_name);
/* If user wants to continue, override previous definition. */
(*handler_p)->init_osabi = init_osabi;
return;
}
}
(*handler_p)
= (struct gdb_osabi_handler *) xmalloc (sizeof (struct gdb_osabi_handler));
(*handler_p)->next = NULL;
(*handler_p)->arch_info = arch_info;
(*handler_p)->osabi = osabi;
(*handler_p)->init_osabi = init_osabi;
/* Add this OS ABI to the list of enum values for "set osabi", if it isn't
already there. */
for (name_ptr = gdb_osabi_available_names; *name_ptr; name_ptr ++)
{
if (*name_ptr == gdbarch_osabi_name (osabi))
return;
}
*name_ptr++ = gdbarch_osabi_name (osabi);
*name_ptr = NULL;
}
/* Sniffer to find the OS ABI for a given file's architecture and flavour.
It is legal to have multiple sniffers for each arch/flavour pair, to
disambiguate one OS's a.out from another, for example. The first sniffer
to return something other than GDB_OSABI_UNKNOWN wins, so a sniffer should
be careful to claim a file only if it knows for sure what it is. */
struct gdb_osabi_sniffer
{
struct gdb_osabi_sniffer *next;
enum bfd_architecture arch; /* bfd_arch_unknown == wildcard */
enum bfd_flavour flavour;
enum gdb_osabi (*sniffer)(bfd *);
};
static struct gdb_osabi_sniffer *gdb_osabi_sniffer_list;
void
gdbarch_register_osabi_sniffer (enum bfd_architecture arch,
enum bfd_flavour flavour,
enum gdb_osabi (*sniffer_fn)(bfd *))
{
struct gdb_osabi_sniffer *sniffer;
sniffer =
(struct gdb_osabi_sniffer *) xmalloc (sizeof (struct gdb_osabi_sniffer));
sniffer->arch = arch;
sniffer->flavour = flavour;
sniffer->sniffer = sniffer_fn;
sniffer->next = gdb_osabi_sniffer_list;
gdb_osabi_sniffer_list = sniffer;
}
enum gdb_osabi
gdbarch_lookup_osabi (bfd *abfd)
{
struct gdb_osabi_sniffer *sniffer;
enum gdb_osabi osabi, match;
int match_specific;
/* If we aren't in "auto" mode, return the specified OS ABI. */
if (user_osabi_state == osabi_user)
return user_selected_osabi;
/* If we don't have a binary, just return unknown. The caller may
have other sources the OSABI can be extracted from, e.g., the
target description. */
if (abfd == NULL)
return GDB_OSABI_UNKNOWN;
match = GDB_OSABI_UNKNOWN;
match_specific = 0;
for (sniffer = gdb_osabi_sniffer_list; sniffer != NULL;
sniffer = sniffer->next)
{
if ((sniffer->arch == bfd_arch_unknown /* wildcard */
|| sniffer->arch == bfd_get_arch (abfd))
&& sniffer->flavour == bfd_get_flavour (abfd))
{
osabi = (*sniffer->sniffer) (abfd);
if (osabi < GDB_OSABI_UNKNOWN || osabi >= GDB_OSABI_INVALID)
{
internal_error
(__FILE__, __LINE__,
_("gdbarch_lookup_osabi: invalid OS ABI (%d) from sniffer "
"for architecture %s flavour %d"),
(int) osabi,
bfd_printable_arch_mach (bfd_get_arch (abfd), 0),
(int) bfd_get_flavour (abfd));
}
else if (osabi != GDB_OSABI_UNKNOWN)
{
/* A specific sniffer always overrides a generic sniffer.
Croak on multiple match if the two matches are of the
same class. If the user wishes to continue, we'll use
the first match. */
if (match != GDB_OSABI_UNKNOWN)
{
if ((match_specific && sniffer->arch != bfd_arch_unknown)
|| (!match_specific && sniffer->arch == bfd_arch_unknown))
{
internal_error
(__FILE__, __LINE__,
_("gdbarch_lookup_osabi: multiple %sspecific OS ABI "
"match for architecture %s flavour %d: first "
"match \"%s\", second match \"%s\""),
match_specific ? "" : "non-",
bfd_printable_arch_mach (bfd_get_arch (abfd), 0),
(int) bfd_get_flavour (abfd),
gdbarch_osabi_name (match),
gdbarch_osabi_name (osabi));
}
else if (sniffer->arch != bfd_arch_unknown)
{
match = osabi;
match_specific = 1;
}
}
else
{
match = osabi;
if (sniffer->arch != bfd_arch_unknown)
match_specific = 1;
}
}
}
}
return match;
}
/* Return non-zero if architecture A can run code written for
architecture B. */
static int
can_run_code_for (const struct bfd_arch_info *a, const struct bfd_arch_info *b)
{
/* BFD's 'A->compatible (A, B)' functions return zero if A and B are
incompatible. But if they are compatible, it returns the 'more
featureful' of the two arches. That is, if A can run code
written for B, but B can't run code written for A, then it'll
return A.
struct bfd_arch_info objects are singletons: that is, there's
supposed to be exactly one instance for a given machine. So you
can tell whether two are equivalent by comparing pointers. */
return (a == b || a->compatible (a, b) == a);
}
void
gdbarch_init_osabi (struct gdbarch_info info, struct gdbarch *gdbarch)
{
struct gdb_osabi_handler *handler;
if (info.osabi == GDB_OSABI_UNKNOWN)
{
/* Don't complain about an unknown OSABI. Assume the user knows
what they are doing. */
return;
}
for (handler = gdb_osabi_handler_list; handler != NULL;
handler = handler->next)
{
if (handler->osabi != info.osabi)
continue;
/* If the architecture described by ARCH_INFO can run code for
the architcture we registered the handler for, then the
handler is applicable. Note, though, that if the handler is
for an architecture that is a superset of ARCH_INFO, we can't
use that --- it would be perfectly correct for it to install
gdbarch methods that refer to registers / instructions /
other facilities ARCH_INFO doesn't have.
NOTE: kettenis/20021027: There may be more than one machine
type that is compatible with the desired machine type. Right
now we simply return the first match, which is fine for now.
However, we might want to do something smarter in the future. */
/* NOTE: cagney/2003-10-23: The code for "a can_run_code_for b"
is implemented using BFD's compatible method (a->compatible
(b) == a -- the lowest common denominator between a and b is
a). That method's definition of compatible may not be as you
expect. For instance the test "amd64 can run code for i386"
(or more generally "64-bit ISA can run code for the 32-bit
ISA"). BFD doesn't normally consider 32-bit and 64-bit
"compatible" so it doesn't succeed. */
if (can_run_code_for (info.bfd_arch_info, handler->arch_info))
{
(*handler->init_osabi) (info, gdbarch);
return;
}
}
warning
("A handler for the OS ABI \"%s\" is not built into this configuration\n"
"of GDB. Attempting to continue with the default %s settings.\n",
gdbarch_osabi_name (info.osabi),
info.bfd_arch_info->printable_name);
}
/* Limit on the amount of data to be read. */
#define MAX_NOTESZ 128
/* Return non-zero if NOTE matches NAME, DESCSZ and TYPE. */
static int
check_note (bfd *abfd, asection *sect, const char *note,
const char *name, unsigned long descsz, unsigned long type)
{
unsigned long notesz;
/* Calculate the size of this note. */
notesz = strlen (name) + 1;
notesz = ((notesz + 3) & ~3);
notesz += descsz;
notesz = ((notesz + 3) & ~3);
/* If this assertion triggers, increase MAX_NOTESZ. */
gdb_assert (notesz <= MAX_NOTESZ);
/* Check whether SECT is big enough to comtain the complete note. */
if (notesz > bfd_section_size (abfd, sect))
return 0;
/* Check the note name. */
if (bfd_h_get_32 (abfd, note) != (strlen (name) + 1)
|| strcmp (note + 12, name) != 0)
return 0;
/* Check the descriptor size. */
if (bfd_h_get_32 (abfd, note + 4) != descsz)
return 0;
/* Check the note type. */
if (bfd_h_get_32 (abfd, note + 8) != type)
return 0;
return 1;
}
/* Generic sniffer for ELF flavoured files. */
void
generic_elf_osabi_sniff_abi_tag_sections (bfd *abfd, asection *sect, void *obj)
{
enum gdb_osabi *osabi = obj;
const char *name;
unsigned int sectsize;
char *note;
name = bfd_get_section_name (abfd, sect);
sectsize = bfd_section_size (abfd, sect);
/* Limit the amount of data to read. */
if (sectsize > MAX_NOTESZ)
sectsize = MAX_NOTESZ;
note = alloca (sectsize);
bfd_get_section_contents (abfd, sect, note, 0, sectsize);
/* .note.ABI-tag notes, used by GNU/Linux and FreeBSD. */
if (strcmp (name, ".note.ABI-tag") == 0)
{
/* GNU. */
if (check_note (abfd, sect, note, "GNU", 16, NT_GNU_ABI_TAG))
{
unsigned int abi_tag = bfd_h_get_32 (abfd, note + 16);
switch (abi_tag)
{
case GNU_ABI_TAG_LINUX:
*osabi = GDB_OSABI_LINUX;
break;
case GNU_ABI_TAG_HURD:
*osabi = GDB_OSABI_HURD;
break;
case GNU_ABI_TAG_SOLARIS:
*osabi = GDB_OSABI_SOLARIS;
break;
case GNU_ABI_TAG_FREEBSD:
*osabi = GDB_OSABI_FREEBSD_ELF;
break;
case GNU_ABI_TAG_NETBSD:
*osabi = GDB_OSABI_NETBSD_ELF;
break;
default:
internal_error (__FILE__, __LINE__,
_("generic_elf_osabi_sniff_abi_tag_sections: "
"unknown OS number %d"),
abi_tag);
}
return;
}
/* FreeBSD. */
if (check_note (abfd, sect, note, "FreeBSD", 4, NT_FREEBSD_ABI_TAG))
{
/* There is no need to check the version yet. */
*osabi = GDB_OSABI_FREEBSD_ELF;
return;
}
return;
}
/* .note.netbsd.ident notes, used by NetBSD. */
if (strcmp (name, ".note.netbsd.ident") == 0
&& check_note (abfd, sect, note, "NetBSD", 4, NT_NETBSD_IDENT))
{
/* There is no need to check the version yet. */
*osabi = GDB_OSABI_NETBSD_ELF;
return;
}
/* .note.openbsd.ident notes, used by OpenBSD. */
if (strcmp (name, ".note.openbsd.ident") == 0
&& check_note (abfd, sect, note, "OpenBSD", 4, NT_OPENBSD_IDENT))
{
/* There is no need to check the version yet. */
*osabi = GDB_OSABI_OPENBSD_ELF;
return;
}
/* .note.netbsdcore.procinfo notes, used by NetBSD. */
if (strcmp (name, ".note.netbsdcore.procinfo") == 0)
{
*osabi = GDB_OSABI_NETBSD_ELF;
return;
}
}
static enum gdb_osabi
generic_elf_osabi_sniffer (bfd *abfd)
{
unsigned int elfosabi;
enum gdb_osabi osabi = GDB_OSABI_UNKNOWN;
elfosabi = elf_elfheader (abfd)->e_ident[EI_OSABI];
switch (elfosabi)
{
case ELFOSABI_NONE:
/* When the EI_OSABI field in the ELF header is ELFOSABI_NONE
(0), then the ELF structures in the file are conforming to
the base specification for that machine (there are no
OS-specific extensions). In order to determine the real OS
in use we must look for OS-specific notes. */
bfd_map_over_sections (abfd,
generic_elf_osabi_sniff_abi_tag_sections,
&osabi);
break;
case ELFOSABI_FREEBSD:
osabi = GDB_OSABI_FREEBSD_ELF;
break;
case ELFOSABI_NETBSD:
osabi = GDB_OSABI_NETBSD_ELF;
break;
case ELFOSABI_LINUX:
osabi = GDB_OSABI_LINUX;
break;
case ELFOSABI_HURD:
osabi = GDB_OSABI_HURD;
break;
case ELFOSABI_SOLARIS:
osabi = GDB_OSABI_SOLARIS;
break;
case ELFOSABI_HPUX:
/* For some reason the default value for the EI_OSABI field is
ELFOSABI_HPUX for all PA-RISC targets (with the exception of
GNU/Linux). We use HP-UX ELF as the default, but let any
OS-specific notes override this. */
osabi = GDB_OSABI_HPUX_ELF;
bfd_map_over_sections (abfd,
generic_elf_osabi_sniff_abi_tag_sections,
&osabi);
break;
}
if (osabi == GDB_OSABI_UNKNOWN)
{
/* The FreeBSD folks have been naughty; they stored the string
"FreeBSD" in the padding of the e_ident field of the ELF
header to "brand" their ELF binaries in FreeBSD 3.x. */
if (memcmp (&elf_elfheader (abfd)->e_ident[8],
"FreeBSD", sizeof ("FreeBSD")) == 0)
osabi = GDB_OSABI_FREEBSD_ELF;
}
return osabi;
}
static void
set_osabi (char *args, int from_tty, struct cmd_list_element *c)
{
struct gdbarch_info info;
if (strcmp (set_osabi_string, "auto") == 0)
user_osabi_state = osabi_auto;
else if (strcmp (set_osabi_string, "default") == 0)
{
user_selected_osabi = GDB_OSABI_DEFAULT;
user_osabi_state = osabi_user;
}
else if (strcmp (set_osabi_string, "none") == 0)
{
user_selected_osabi = GDB_OSABI_UNKNOWN;
user_osabi_state = osabi_user;
}
else
{
int i;
for (i = 1; i < GDB_OSABI_INVALID; i++)
if (strcmp (set_osabi_string, gdbarch_osabi_name (i)) == 0)
{
user_selected_osabi = i;
user_osabi_state = osabi_user;
break;
}
if (i == GDB_OSABI_INVALID)
internal_error (__FILE__, __LINE__,
_("Invalid OS ABI \"%s\" passed to command handler."),
set_osabi_string);
}
/* NOTE: At some point (true multiple architectures) we'll need to be more
graceful here. */
gdbarch_info_init (&info);
if (! gdbarch_update_p (info))
internal_error (__FILE__, __LINE__, _("Updating OS ABI failed."));
}
static void
show_osabi (struct ui_file *file, int from_tty, struct cmd_list_element *c,
const char *value)
{
if (user_osabi_state == osabi_auto)
fprintf_filtered (file,
_("The current OS ABI is \"auto\" "
"(currently \"%s\").\n"),
gdbarch_osabi_name (gdbarch_osabi (get_current_arch ())));
else
fprintf_filtered (file, _("The current OS ABI is \"%s\".\n"),
gdbarch_osabi_name (user_selected_osabi));
if (GDB_OSABI_DEFAULT != GDB_OSABI_UNKNOWN)
fprintf_filtered (file, _("The default OS ABI is \"%s\".\n"),
gdbarch_osabi_name (GDB_OSABI_DEFAULT));
}
extern initialize_file_ftype _initialize_gdb_osabi; /* -Wmissing-prototype */
void
_initialize_gdb_osabi (void)
{
if (strcmp (gdb_osabi_names[GDB_OSABI_INVALID], "<invalid>") != 0)
internal_error
(__FILE__, __LINE__,
_("_initialize_gdb_osabi: gdb_osabi_names[] is inconsistent"));
/* Register a generic sniffer for ELF flavoured files. */
gdbarch_register_osabi_sniffer (bfd_arch_unknown,
bfd_target_elf_flavour,
generic_elf_osabi_sniffer);
/* Register the "set osabi" command. */
add_setshow_enum_cmd ("osabi", class_support, gdb_osabi_available_names,
&set_osabi_string,
_("Set OS ABI of target."),
_("Show OS ABI of target."),
NULL, set_osabi, show_osabi,
&setlist, &showlist);
user_osabi_state = osabi_auto;
}
| gpl-3.0 |
ih24n69/android_kernel_samsung_young23g | drivers/mtd/nand/sc8830_nand.c | 6 | 59989 | /*
* Copyright (C) 2012 Spreadtrum Communications Inc.
*
* 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.
*/
#define DOLPHIN_KERNEL
#ifdef DOLPHIN_UBOOT
#include <common.h>
#include <malloc.h>
#include <asm/io.h>
#include <asm/errno.h>
#include <config.h>
#include <asm/arch/sci_types.h>
#include <asm/arch/pinmap.h>
#include <asm/arch/bits.h>
#include <nand.h>
#include <linux/mtd/nand.h>
#include <asm/arch-sc8830/sprd_nfc_reg_v2.h>
//#include <asm/arch/sc8810_reg_base.h>
#include <asm/arch/regs_ana.h>
#include <asm/arch/analog_reg_v3.h>
//#include <asm/arch/sc8810_reg_ahb.h>
//#include <asm/arch/sc8810_reg_global.h>
#include <asm/arch/gpio_drvapi.h>
#include <asm/arch/regs_global.h>
//#include <asm/arch/regs_cpc.h>
//#include <asm/arch/pin_reg_v3.h>
#ifdef CONFIG_NAND_SPL
#define udelay(x) \
do { \
volatile int i; \
int cnt = 200 * (x); \
for (i=0; i<cnt; i++);\
} while(0);
#endif
#define mdelay(_ms) udelay((_ms)*1000)
#define NAND_DBG
#if defined(CONFIG_NAND_SPL) || !defined(NAND_DBG)
#define DPRINT(arg...) do{}while(0)
#else
#define DPRINT printf
#endif
#define ASSERT(cond) { assert(cond); }
#define NFC_MC_ICMD_ID (0xCD)
#define NFC_MC_ADDR_ID (0x0A)
#define NFC_MC_WRB0_ID (0xB0)
#define NFC_MC_WRB1_ID (0xB1)
#define NFC_MC_MRDT_ID (0xD0)
#define NFC_MC_MWDT_ID (0xD1)
#define NFC_MC_SRDT_ID (0xD2)
#define NFC_MC_SWDT_ID (0xD3)
#define NFC_MC_IDST_ID (0xDD)
#define NFC_MC_CSEN_ID (0xCE)
#define NFC_MC_NOP_ID (0xF0)
#define NFC_MC_DONE_ID (0xFF)
#define NFC_MAX_CHIP 1
#define NFC_TIMEOUT_VAL 0x1000000
#define NAND_MC_CMD(x) (uint16_t)(((x & 0xff) << 8) | NFC_MC_ICMD_ID)
#define NAND_MC_ADDR(x) (uint16_t)(((x & 0xff) << 8) | (NFC_MC_ADDR_ID << 4))
#define NAND_MC_WRB0(x) (uint16_t)(NFC_MC_WRB0_ID)
#define NAND_MC_MRDT (uint16_t)(NFC_MC_MRDT_ID)
#define NAND_MC_MWDT (uint16_t)(NFC_MC_MWDT_ID)
#define NAND_MC_SRDT (uint16_t)(NFC_MC_SRDT_ID)
#define NAND_MC_SWDT (uint16_t)(NFC_MC_SWDT_ID)
#define NAND_MC_IDST(x) (uint16_t)((NFC_MC_IDST_ID) | ((x -1) << 8))
#define NAND_MC_NOP(x) (uint16_t)(((x & 0xff) << 8) | NFC_MC_NOP_ID)
#define NAND_MC_BUFFER_SIZE (24)
static int mtderasesize = 0;
static int mtdwritesize = 0;
static int mtdoobsize = 0;
#endif //DOLPHIN_UBOOT end
#ifdef DOLPHIN_KERNEL
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/interrupt.h>
#include <linux/dma-mapping.h>
#include <linux/platform_device.h>
#include <linux/delay.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/io.h>
#include <linux/irq.h>
#include <linux/slab.h>
#include <linux/spinlock.h>
#include <mach/globalregs.h>
#include <mach/pinmap.h>
#include "sc8830_nand.h"
#define DPRINT printk
#endif //DOLPHIN_KERNEL
#define SPRD_ASSERT(cond) { if (!(cond)) while(1); }
#define STATIC_FUNC static
#include "sprd_nand_param.h"
/* 2 bit correct, sc8810 support 1, 2, 4, 8, 12,14, 24 */
#define CONFIG_SYS_NAND_ECC_MODE (2)
//#define CONFIG_SYS_NAND_ECC_MODE 8
/* Number of ECC bytes per OOB - S3C6400 calculates 4 bytes ECC in 1-bit mode */
#define CONFIG_SYS_NAND_ECCBYTES (4)
//#define CONFIG_SYS_NAND_ECCBYTES 14
#define NAND_MC_BUFFER_SIZE (24)
#define CONFIG_SYS_NAND_ECCSIZE (512)
#define CONFIG_SYS_NAND_5_ADDR_CYCLE 5
#define SPRD_NAND_CLOCK (153)
#define IRQ_TIMEOUT 100//unit:ms,IRQ timeout value
#define DRIVER_NAME "sc8830_nand"
enum NAND_ERR_CORRECT_S {
NAND_FATAL_ERROR=0,
NAND_ERR_NEED_RETRY,
NAND_ERR_FIXED,
NAND_NO_ERROR
};
enum NAND_HANDLE_STATUS_S {
NAND_HANDLE_DONE=0,
NAND_HANDLE_TIMEOUT,
NAND_HANDLE_ERR
};
static enum NAND_HANDLE_STATUS_S handle_status = NAND_HANDLE_DONE;
static enum NAND_ERR_CORRECT_S ret_irq_en = NAND_NO_ERROR;
STATIC_FUNC void nfc_enable_interrupt(void);
STATIC_FUNC void nfc_disable_interrupt(void);
STATIC_FUNC void nfc_clear_interrupt(void);
//#define NAND_IRQ_EN
#ifdef NAND_IRQ_EN
#include <linux/completion.h>
#include <mach/irqs.h>
static struct completion nfc_op_completion;
STATIC_FUNC void nfc_wait_op_done(void);
#endif
struct sprd_dolphin_nand_info {
struct mtd_info *mtd;
struct nand_chip *nand;
#ifdef DOLPHIN_UBOOT
struct device *pdev;
#endif
#ifdef DOLPHIN_KERNEL
struct platform_device *pdev;
#endif
struct sprd_nand_param *param;
uint32_t chip; //chip index
uint32_t v_mbuf; //virtual main buffer address
uint32_t p_mbuf; //phy main buffer address
uint32_t v_oob; // virtual oob buffer address
uint32_t p_oob; //phy oob buffer address
uint32_t page; //page address
uint16_t column; //column address
uint16_t oob_size;
uint16_t m_size; //main part size per sector
uint16_t s_size; //oob size per sector
uint8_t a_cycles;//address cycles, 3, 4, 5
uint8_t sct_pg; //sector per page
uint8_t info_pos;
uint8_t info_size;
uint8_t ecc_mode;//0-1bit, 1-2bit, 2-4bit, 3-8bit,4-12bit,5-16bit,6-24bit
uint8_t ecc_pos; // ecc postion
uint8_t wp_en; //write protect enable
uint16_t write_size;
uint16_t page_per_bl;//page per block
uint16_t buf_head;
uint16_t _buf_tail;
uint8_t ins_num;//instruction number
uint32_t ins[NAND_MC_BUFFER_SIZE >> 1];
};
#define mtd_to_dolphin(m) (&g_dolphin)
//gloable variable
static struct nand_ecclayout sprd_dolphin_nand_oob_default = {
.eccbytes = 0,
.eccpos = {0},
.oobfree = {
{.offset = 2,
.length = 46}}
};
struct sprd_dolphin_nand_info g_dolphin = {0};
//save the data read by read_byte and read_word api interface functon
static __attribute__((aligned(4))) uint8_t s_oob_data[NAND_MAX_OOBSIZE];
//static __attribute__((aligned(4))) uint8_t s_oob_data[8];
//static __attribute__((aligned(4))) uint8_t s_id_status[8];
STATIC_FUNC int sprd_dolphin_nand_read_id(struct sprd_dolphin_nand_info *dolphin, uint32_t *buf);
STATIC_FUNC int sprd_dolphin_nand_reset(struct sprd_dolphin_nand_info *dolphin);
STATIC_FUNC int sprd_dolphin_nand_wait_finish(struct sprd_dolphin_nand_info *dolphin);
STATIC_FUNC uint32_t sprd_dolphin_reg_read(uint32_t addr)
{
return readl(addr);
}
STATIC_FUNC void sprd_dolphin_reg_write(uint32_t addr, uint32_t val)
{
writel(val, addr);
}
STATIC_FUNC void sprd_dolphin_reg_or(uint32_t addr, uint32_t val)
{
sprd_dolphin_reg_write(addr, sprd_dolphin_reg_read(addr) | val);
}
STATIC_FUNC void sprd_dolphin_reg_and(uint32_t addr, uint32_t mask)
{
sprd_dolphin_reg_write(addr, sprd_dolphin_reg_read(addr) & mask);
}
STATIC_FUNC void sprd_dolphin_nand_int_clr(uint32_t bit_clear)
{
sprd_dolphin_reg_write(NFC_INT_REG, bit_clear);
}
STATIC_FUNC void nfc_clear_interrupt(void)
{
uint32_t value = 0;
value = ( INT_STSMCH_CLR | INT_WP_CLR | INT_TO_CLR | INT_DONE_CLR);
sprd_dolphin_reg_or(NFC_INT_REG, value); /* clear all interrupt status */
//value = NFC_CMD_CLR;
//sprd_dolphin_reg_or(NFC_START_REG, value); /* clear all interrupt status */
}
STATIC_FUNC void nfc_enable_interrupt(void)
{
uint32_t value = 0;
value = (INT_TO_EN | INT_DONE_EN);
sprd_dolphin_reg_or(NFC_INT_REG, value); /* clear all interrupt status */
}
STATIC_FUNC void nfc_disable_interrupt(void)
{
uint32_t value = 0;
value = ~(INT_TO_EN | INT_DONE_EN);
sprd_dolphin_reg_and(NFC_INT_REG, value); /* clear all interrupt status */
}
unsigned int ecc_mode_convert(uint32_t mode)
{
uint32_t mode_m;
switch(mode)
{
case 1:
mode_m = 0;
break;
case 2:
mode_m = 1;
break;
case 4:
mode_m = 2;
break;
case 8:
mode_m = 3;
break;
case 12:
mode_m = 4;
break;
case 16:
mode_m = 5;
break;
case 24:
mode_m = 6;
break;
case 40:
mode_m = 7;
break;
case 60:
mode_m = 8;
break;
default:
mode_m = 0;
break;
}
return mode_m;
}
STATIC_FUNC void dolphin_set_timing_config(struct sprd_nand_timing *timing , uint32_t nfc_clk_MHz) {
u32 reg_val, temp_val;
reg_val = 0;
/* get acs value : 0ns */
reg_val |= ((2 & 0x1F) << NFC_ACS_OFFSET);
/* get ace value + 6ns read delay time, and rwl added */
temp_val = (timing->ace_ns + 6) * nfc_clk_MHz / 1000;
if (((timing->ace_ns * nfc_clk_MHz) % 1000) != 0) {
temp_val++;
}
reg_val |= ((temp_val & 0x1F) << NFC_ACE_OFFSET);
/* get rws value : 20 ns */
temp_val = 20 * nfc_clk_MHz / 1000;
if (((timing->ace_ns * nfc_clk_MHz) % 1000) != 0) {
temp_val++;
}
reg_val |= ((temp_val & 0x3F) << NFC_RWS_OFFSET);
/* get rws value : 0 ns */
reg_val |= ((2 & 0x1F) << NFC_RWE_OFFSET);
/* get rwh value */
temp_val = (timing->rwh_ns + 6) * nfc_clk_MHz / 1000;
if (((timing->ace_ns * nfc_clk_MHz) % 1000) != 0) {
temp_val++;
}
reg_val |= ((temp_val & 0x1F) << NFC_RWH_OFFSET);
/* get rwl value, 6 is read delay time*/
temp_val = (timing->rwl_ns + 6) * nfc_clk_MHz / 1000;
if (((timing->ace_ns * nfc_clk_MHz) % 1000) != 0) {
temp_val++;
}
reg_val |= (temp_val & 0x3F);
DPRINT("%s nand timing val: 0x%x\n\r", __func__, reg_val);
sprd_dolphin_reg_write(NFC_TIMING_REG, reg_val);
}
#ifdef CONFIG_NAND_SPL
struct sprd_dolphin_boot_header_info {
uint32_t check_sum;
uint32_t sct_size; //
uint32_t acycle; // 3, 4, 5
uint32_t bus_width; //0 ,1
uint32_t spare_size; //spare part sise for one sector
uint32_t ecc_mode; //0--1bit, 1--2bit,2--4bit,3--8bit,4--12bit, 5--16bit, 6--24bit
uint32_t ecc_pos; // ecc postion at spare part
uint32_t sct_per_page; //sector per page
uint32_t info_pos;
uint32_t info_size;
uint32_t magic_num; //0xaa55a5a5
uint32_t ecc_value[27];
};
void boad_nand_param_init(struct sprd_dolphin_nand_info *dolphin, struct nand_chip *chip, uint8 *id)
{
int extid;
uint32_t writesize;
uint32_t oobsize;
uint32_t erasesize;
uint32_t busw;
/* The 4th id byte is the important one */
extid = id[3];
writesize = 1024 << (extid & 0x3);
extid >>= 2;
/* Calc oobsize */
oobsize = (8 << (extid & 0x01)) * (writesize >> 9);
extid >>= 2;
/* Calc blocksize. Blocksize is multiples of 64KiB */
erasesize = (64 * 1024) << (extid & 0x03);
extid >>= 2;
/* Get buswidth information */
busw = (extid & 0x01) ? NAND_BUSWIDTH_16 : 0;
dolphin->write_size = writesize;
dolphin->m_size =CONFIG_SYS_NAND_ECCSIZE;
dolphin->sct_pg = writesize / CONFIG_SYS_NAND_ECCSIZE;
dolphin->s_size = oobsize / dolphin->sct_pg;
dolphin->ecc_mode = ecc_mode_convert(CONFIG_SYS_NAND_ECC_MODE);
dolphin->ecc_pos = dolphin->s_size - ((14 * CONFIG_SYS_NAND_ECC_MODE + 7) / 8);
dolphin->info_pos = dolphin->ecc_pos - 1;
dolphin->info_size = 1;
dolphin->page_per_bl = erasesize / dolphin->write_size;
dolphin->a_cycles = CONFIG_SYS_NAND_5_ADDR_CYCLE;
if(NAND_BUSWIDTH_16 == busw)
{
chip->options |= NAND_BUSWIDTH_16;
}
else
{
chip->options &= ~NAND_BUSWIDTH_16;
}
}
/*
* because the dolphin firmware use the nand identify process
* and the data at the header of nand_spl is the nand param used at nand read and write,
* so in nand_spl, don't need read the id or use the onfi spec to calculate the nand param,
* just use the param at the nand_spl header instead of
*/
void nand_hardware_config(struct mtd_info *mtd, struct nand_chip *chip)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct sprd_nand_param* param;
struct sprd_nand_oob* oob;
struct sprd_nand_timing* timing;
uint8 *id;
sprd_dolphin_nand_reset(dolphin);
mdelay(1);
sprd_dolphin_nand_read_id(dolphin, (uint32_t *)s_oob_data);
boad_nand_param_init(dolphin, dolphin->nand, s_oob_data);
id = s_oob_data;
param = SprdGetNandParam(id);
if (param != NULL) {
dolphin->param = param;
oob = ¶m->sOOB;
timing = ¶m->sTiming;
dolphin_set_timing_config(timing, SPRD_NAND_CLOCK);
//save the param config
dolphin->write_size = param->nPageSize;
dolphin->page_per_bl = param->nBlkSize / param->nPageSize;
dolphin->m_size = param->nSecSize;
dolphin->sct_pg = (param->nPageSize / param->nSecSize);
dolphin->oob_size = param->nSpareSize;
dolphin->a_cycles = param->nCycles;
dolphin->s_size = oob->nOOBSize;
dolphin->info_pos = oob->nInfoPos;
dolphin->info_size = oob->nInfoSize;
dolphin->ecc_pos = oob->nEccPos;
dolphin->ecc_mode = ecc_mode_convert(oob->nEccBits);
dolphin->nand=chip;
dolphin->mtd = mtd;
chip->ecc.bytes = (oob->nEccBits * 14 + 7) / 8;
#ifdef DOLPHIN_UBOOT
chip->eccbitmode = oob->nEccBits;
#endif
if(param->nBusWidth)
{
chip->options |= NAND_BUSWIDTH_16;
}
else
{
chip->options &= ~NAND_BUSWIDTH_16;
}
}
mtd->writesize = dolphin->write_size;
mtd->oobsize = dolphin->s_size * dolphin->sct_pg;
mtd->erasesize = dolphin->page_per_bl * dolphin->write_size;
}
#else
STATIC_FUNC void sprd_dolphin_nand_ecc_layout_gen(struct sprd_nand_oob *oob, uint8_t sector_num, struct nand_ecclayout *layout)
{
uint8_t sct = 0;
uint32_t i = 0;
uint32_t offset;
uint32_t used_len ; //one sector ecc data size(byte)
uint32_t eccbytes = 0; //one page ecc data size(byte)
uint32_t oobfree_len = 0;
used_len = (14 * oob->nEccBits + 7) / 8 + oob->nInfoSize;
if(sector_num > ARRAY_SIZE(layout->oobfree))
{
while(1);
}
for(sct = 0; sct < sector_num; sct++)
{
//offset = (oob_size * sct) + ecc_pos;
//for(i = 0; i < ecc_len; i++)
offset = (oob->nOOBSize * sct) + oob->nInfoPos;
for(i = 0; i < used_len; i++)
{
layout->eccpos[eccbytes++] = offset + i;
}
layout->oobfree[sct].offset = oob->nOOBSize * sct;
layout->oobfree[sct].length = oob->nOOBSize - used_len ;
oobfree_len += oob->nOOBSize - used_len;
}
//for bad mark postion
layout->oobfree[0].offset = 2;
layout->oobfree[0].length = oob->nOOBSize - used_len - 2;
oobfree_len -= 2;
layout->eccbytes = used_len * sector_num;
}
void nand_hardware_config(struct mtd_info *mtd, struct nand_chip *chip, uint8_t id[5])
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct sprd_nand_param* param;
struct sprd_nand_oob* oob;
struct sprd_nand_timing* timing;
param = SprdGetNandParam(id);
if (param != NULL) {
dolphin->param = param;
oob = ¶m->sOOB;
timing = ¶m->sTiming;
dolphin_set_timing_config(timing, SPRD_NAND_CLOCK);
//save the param config
dolphin->write_size = param->nPageSize;
dolphin->page_per_bl = param->nBlkSize / param->nPageSize;
dolphin->m_size = param->nSecSize;
dolphin->sct_pg = (param->nPageSize / param->nSecSize);
dolphin->oob_size = param->nSpareSize;
dolphin->a_cycles = param->nCycles;
dolphin->s_size = oob->nOOBSize;
dolphin->info_pos = oob->nInfoPos;
dolphin->info_size = oob->nInfoSize;
dolphin->ecc_pos = oob->nEccPos;
dolphin->ecc_mode = ecc_mode_convert(oob->nEccBits);
dolphin->nand=chip;
dolphin->mtd = mtd;
chip->ecc.bytes = (oob->nEccBits * 14 + 7) / 8;
#ifdef DOLPHIN_UBOOT
chip->eccbitmode = oob->nEccBits;
#endif
if(param->nBusWidth)
{
chip->options |= NAND_BUSWIDTH_16;
}
else
{
chip->options &= ~NAND_BUSWIDTH_16;
}
/* Calculate the address shift from the page size */
chip->page_shift = ffs(mtd->writesize) - 1;
/* Convert chipsize to number of pages per chip -1. */
chip->pagemask = (chip->chipsize >> chip->page_shift) - 1;
sprd_dolphin_nand_ecc_layout_gen(oob, dolphin->sct_pg, &sprd_dolphin_nand_oob_default);
chip->ecc.layout = &sprd_dolphin_nand_oob_default;
mtd->writesize = dolphin->write_size;
mtd->oobsize = dolphin->oob_size;
mtd->erasesize = dolphin->page_per_bl * dolphin->write_size;
}
else {
int steps;
struct sprd_nand_oob oob_tmp;
//save the param config
steps = mtd->writesize / CONFIG_SYS_NAND_ECCSIZE;
dolphin->ecc_mode = ecc_mode_convert(CONFIG_SYS_NAND_ECC_MODE);
dolphin->m_size = CONFIG_SYS_NAND_ECCSIZE;
dolphin->s_size = mtd->oobsize / steps;
dolphin->a_cycles = mtd->writesize / CONFIG_SYS_NAND_ECCSIZE;
dolphin->sct_pg = steps;
dolphin->info_pos = dolphin->s_size - CONFIG_SYS_NAND_ECCBYTES - 1;
dolphin->info_size = 1;
dolphin->write_size = mtd->writesize;
dolphin->page_per_bl = mtd->erasesize / mtd->writesize;
dolphin->oob_size = mtd->oobsize;
dolphin->ecc_pos = dolphin->s_size - CONFIG_SYS_NAND_ECCBYTES;
dolphin->mtd = mtd;
oob_tmp.nOOBSize = dolphin->s_size;
oob_tmp.nInfoPos = dolphin->info_pos;
oob_tmp.nInfoSize = dolphin->info_size;
oob_tmp.nEccPos = dolphin->ecc_pos;
oob_tmp.nEccBits = CONFIG_SYS_NAND_ECC_MODE;
sprd_dolphin_nand_ecc_layout_gen(&oob_tmp, dolphin->sct_pg, &sprd_dolphin_nand_oob_default);
chip->ecc.layout = &sprd_dolphin_nand_oob_default;
#ifdef DOLPHIN_UBOOT
chip->eccbitmode = CONFIG_SYS_NAND_ECC_MODE;
#endif
if(chip->chipsize > (128 << 20)) {
dolphin->a_cycles = 5;
}
else {
dolphin->a_cycles = 4;
}
}
}
#endif //end CONFIG_NAND_SPL
#ifdef DOLPHIN_UBOOT
#ifndef CONFIG_NAND_SPL
typedef struct {
uint8_t *m_buf;
uint8_t *s_buf;
uint8_t m_sct;
uint8_t s_sct;
uint8_t dir; //if dir is 0, read dadta from NFC buffer, if 1, write data to NFC buffer
uint16_t m_size;
uint16_t s_size;
} sprd_dolphin_nand_data_param;
STATIC_FUNC unsigned int sprd_dolphin_data_trans(sprd_dolphin_nand_data_param *param)
{
uint32_t cfg0 = 0;
uint32_t cfg1 = 0;
uint32_t cfg2 = 0;
cfg0 = NFC_ONLY_MST_MODE | MAIN_SPAR_APT | NFC_WPN;
if(param->dir)
{
cfg0 |= NFC_RW;
}
if(param->m_sct != 0)
{
cfg0 |= (param->m_sct - 1) << SECTOR_NUM_OFFSET;
cfg0 |= MAIN_USE;
cfg1 |= (param->m_size - 1);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)param->m_buf);
}
if(param->s_sct != 0)
{
cfg0 |= SPAR_USE;
cfg1 |= (param->s_size - 1) << SPAR_SIZE_OFFSET;
cfg2 |= (param->s_sct - 1) << SPAR_SECTOR_NUM_OFFSET;
sprd_dolphin_reg_write(NFC_SPAR_ADDR_REG, (uint32_t)param->s_buf);
}
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_CFG1_REG, cfg1);
sprd_dolphin_reg_write(NFC_CFG2_REG, cfg2);
sprd_dolphin_nand_int_clr(INT_STSMCH_CLR | INT_WP_CLR | INT_TO_CLR | INT_DONE_CLR);//clear all interrupt
sprd_dolphin_reg_write(NFC_START_REG, NFC_START);
sprd_dolphin_nand_wait_finish(&g_dolphin);
return 0;
}
void sprd_ecc_ctrl(struct sprd_ecc_param *param, uint32_t dir)
{
uint32_t cfg0 = 0;
uint32_t cfg1 = 0;
uint32_t cfg2 = 0;
cfg0 = NFC_ONLY_ECC_MODE | MAIN_SPAR_APT;
if(dir)
{
cfg0 |= NFC_RW;
}
cfg1 |=(param->sinfo_size - 1) << SPAR_INFO_SIZE_OFFSET;
cfg1 |=(param->sp_size - 1) << SPAR_SIZE_OFFSET;
cfg1 |= (param->m_size - 1);
cfg2 |= (param->sinfo_pos)<< SPAR_INFO_POS_OFFSET;
cfg2 |= ecc_mode_convert(param->mode) << ECC_MODE_OFFSET;
cfg2 |= param->ecc_pos;
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_CFG1_REG, cfg1);
sprd_dolphin_reg_write(NFC_CFG2_REG, cfg2);
sprd_dolphin_nand_int_clr(INT_STSMCH_CLR | INT_WP_CLR | INT_TO_CLR | INT_DONE_CLR);//clear all interrupt
sprd_dolphin_reg_write(NFC_START_REG, NFC_START);
sprd_dolphin_nand_wait_finish(&g_dolphin);
}
unsigned int sprd_ecc_encode(struct sprd_ecc_param *param)
{
struct sprd_dolphin_nand_info *dolphin;
sprd_dolphin_nand_data_param d_param;
dolphin = &g_dolphin;
memset(&d_param, 0, sizeof(d_param));
d_param.m_buf = param->p_mbuf;
d_param.s_buf = param->p_sbuf;
d_param.m_sct = param->ecc_num;
d_param.s_sct = param->ecc_num;
d_param.dir = 1;
d_param.m_size = param->m_size;
d_param.s_size = param->sp_size;
Dcache_CleanRegion((unsigned int)d_param.m_buf, d_param.m_sct*d_param.m_size);
Dcache_CleanRegion((unsigned int)d_param.s_buf, d_param.s_sct*d_param.s_size);
sprd_dolphin_data_trans(&d_param);
sprd_ecc_ctrl(param, 1);
d_param.dir = 0;
d_param.m_sct = 0;
Dcache_InvalRegion((unsigned int)d_param.m_buf , d_param.m_sct*d_param.m_size);
Dcache_InvalRegion((unsigned int)d_param.s_buf , d_param.s_sct*d_param.s_size);
sprd_dolphin_data_trans(&d_param); //read the ecc value from nfc buffer
return 0;
}
#endif //CONFIG_NAND_SPL end
#endif //DOLPHIN_UBOOT END
//add one macro instruction to nand controller
STATIC_FUNC void sprd_dolphin_nand_ins_init(struct sprd_dolphin_nand_info *dolphin)
{
dolphin->ins_num = 0;
}
STATIC_FUNC void sprd_dolphin_nand_ins_add(uint16_t ins, struct sprd_dolphin_nand_info *dolphin)
{
uint16_t *buf = (uint16_t *)dolphin->ins;
if(dolphin->ins_num >= NAND_MC_BUFFER_SIZE)
{
while(1);
}
*(buf + dolphin->ins_num) = ins;
dolphin->ins_num++;
}
STATIC_FUNC void sprd_dolphin_nand_ins_exec(struct sprd_dolphin_nand_info *dolphin)
{
uint32_t i;
uint32_t cfg0;
for(i = 0; i < ((dolphin->ins_num + 1) >> 1); i++)
{
sprd_dolphin_reg_write(NFC_INST0_REG + (i << 2), dolphin->ins[i]);
}
cfg0 = sprd_dolphin_reg_read(NFC_CFG0_REG);
if(dolphin->wp_en)
{
cfg0 &= ~NFC_WPN;
}
else
{
cfg0 |= NFC_WPN;
}
if(dolphin->chip)
{
cfg0 |= CS_SEL;
}
else
{
cfg0 &= ~CS_SEL;
}
sprd_dolphin_nand_int_clr(INT_STSMCH_CLR | INT_WP_CLR | INT_TO_CLR | INT_DONE_CLR);//clear all interrupt
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_START_REG, NFC_START);
}
STATIC_FUNC int sprd_dolphin_nand_wait_finish(struct sprd_dolphin_nand_info *dolphin)
{
unsigned int value;
unsigned int counter = 0;
while((counter < NFC_TIMEOUT_VAL/*time out*/))
{
value = sprd_dolphin_reg_read(NFC_INT_REG);
if(value & INT_DONE_RAW)
{
break;
}
counter ++;
}
sprd_dolphin_reg_write(NFC_INT_REG, 0xf00); //clear all interrupt status
if(counter >= NFC_TIMEOUT_VAL)
{
//while (1);
return -1;
}
return 0;
}
STATIC_FUNC void sprd_dolphin_nand_wp_en(struct sprd_dolphin_nand_info *dolphin, int en)
{
if(en)
{
dolphin->wp_en = 1;
}
else
{
dolphin->wp_en = 0;
}
}
STATIC_FUNC void sprd_dolphin_select_chip(struct mtd_info *mtd, int chip)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
if(chip < 0) { //for release caller
return;
}
//DPRINT("sprd_dolphin_select_chip, %x\r\n", chip);
dolphin->chip = chip;
#ifdef CONFIG_NAND_SPL
nand_hardware_config(mtd,dolphin->nand);
#endif
}
STATIC_FUNC void sprd_dolphin_nand_read_status(struct sprd_dolphin_nand_info *dolphin)
{
uint32_t *buf;
//DPRINT("%s enter\n", __func__);
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_STATUS), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_NOP(10), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_IDST(1), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
sprd_dolphin_reg_write(NFC_CFG0_REG, NFC_ONLY_NAND_MODE);
sprd_dolphin_nand_ins_exec(dolphin);
sprd_dolphin_nand_wait_finish(dolphin);
buf = (uint32_t *)s_oob_data;
*buf = sprd_dolphin_reg_read(NFC_STATUS0_REG);
dolphin->buf_head = 0;
dolphin->_buf_tail = 1;
//DPRINT("%s leave\n", __func__);
}
STATIC_FUNC int sprd_dolphin_nand_read_id(struct sprd_dolphin_nand_info *dolphin, uint32_t *buf)
{
//DPRINT("%s enter\n", __func__);
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READID), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_NOP(10), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_IDST(8), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
sprd_dolphin_reg_write(NFC_CFG0_REG, NFC_ONLY_NAND_MODE);
sprd_dolphin_nand_ins_exec(dolphin);
if (sprd_dolphin_nand_wait_finish(dolphin) != 0)
{
return -1;
}
*buf = sprd_dolphin_reg_read(NFC_STATUS0_REG);
*(buf + 1) = sprd_dolphin_reg_read(NFC_STATUS1_REG);
dolphin->buf_head = 0;
dolphin->_buf_tail = 8;
//DPRINT("%s leave\n", __func__);
return 0;
}
STATIC_FUNC int sprd_dolphin_nand_reset(struct sprd_dolphin_nand_info *dolphin)
{
//DPRINT("%s enter\n", __func__);
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_RESET), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_WRB0_ID, dolphin); //wait rb
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
//config register
sprd_dolphin_reg_write(NFC_CFG0_REG, NFC_ONLY_NAND_MODE);
sprd_dolphin_nand_ins_exec(dolphin);
if (sprd_dolphin_nand_wait_finish(dolphin) != 0)
{
return 0;
}
//DPRINT("%s leave\n", __func__);
return 0;
}
STATIC_FUNC u32 sprd_dolphin_get_decode_sts(u32 index)
{
uint32_t err;
uint32_t shift;
uint32_t reg_addr;
reg_addr = NFC_STATUS0_REG + (index & 0xfffffffc);
shift = (index & 0x3) << 3;
err = sprd_dolphin_reg_read(reg_addr);
err >>= shift;
if((err & ECC_ALL_FF))
{
err &= ERR_ERR_NUM0_MASK;
}
else
{
err = 0;
}
return err;
}
#ifdef DOLPHIN_UBOOT
//read large page
STATIC_FUNC int sprd_dolphin_nand_read_lp(struct mtd_info *mtd,uint8_t *mbuf, uint8_t *sbuf,uint32_t raw)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct nand_chip *chip = dolphin->nand;
uint32_t column;
uint32_t page_addr;
uint32_t cfg0;
uint32_t cfg1;
uint32_t cfg2;
uint32_t i;
uint32_t err;
page_addr = dolphin->page;
if(sbuf) {
column = mtd->writesize;
}
else
{
column = 0;
}
if(chip->options & NAND_BUSWIDTH_16)
{
column >>= 1;
}
//DPRINT("sprd_dolphin_nand_read_lp,page_addr = %x,column = %x\r\n",page_addr, column);
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READ0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
column >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
if (5 == dolphin->a_cycles)// five address cycles
{
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READSTART), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_WRB0_ID, dolphin); //wait rb
if(mbuf && sbuf)
{
sprd_dolphin_nand_ins_add(NAND_MC_SRDT, dolphin);
//switch to main part
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_RNDOUT), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_RNDOUTSTART), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_MRDT, dolphin);
}
else
{
sprd_dolphin_nand_ins_add(NAND_MC_MRDT, dolphin);
}
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
//config registers
cfg0 = NFC_AUTO_MODE | MAIN_SPAR_APT | ((dolphin->sct_pg - 1)<< SECTOR_NUM_OFFSET);
if((!raw) && mbuf && sbuf)
{
cfg0 |= ECC_EN | DETECT_ALL_FF;
}
if(chip->options & NAND_BUSWIDTH_16)
{
cfg0 |= BUS_WIDTH;
}
cfg1 = (dolphin->info_size) << SPAR_INFO_SIZE_OFFSET;
cfg2 = (dolphin->ecc_mode << 12) | (dolphin->info_pos << SPAR_INFO_POS_OFFSET) | ((dolphin->sct_pg - 1) << SPAR_SECTOR_NUM_OFFSET) | dolphin->ecc_pos;
#ifndef CONFIG_NAND_SPL
if (mbuf)
{
Dcache_CleanRegion((unsigned int)mbuf, dolphin->m_size*dolphin->sct_pg);
Dcache_InvalRegion((unsigned int)mbuf, dolphin->m_size*dolphin->sct_pg);
}
if (sbuf)
{
Dcache_CleanRegion((unsigned int)sbuf, dolphin->s_size*dolphin->sct_pg);
Dcache_InvalRegion((unsigned int)sbuf, dolphin->s_size*dolphin->sct_pg);
}
#endif
if(mbuf && sbuf)
{
cfg1 |= (dolphin->m_size - 1) | ((dolphin->s_size - 1)<< SPAR_SIZE_OFFSET);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)mbuf);
sprd_dolphin_reg_write(NFC_SPAR_ADDR_REG, (uint32_t)sbuf);
cfg0 |= MAIN_USE | SPAR_USE;
}
else
{
if(mbuf)
{
cfg1 |= (dolphin->m_size - 1);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)mbuf);
}
if(sbuf)
{
cfg1 |= (dolphin->s_size - 1);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)sbuf);
}
cfg0 |= MAIN_USE;
}
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_CFG1_REG, cfg1);
sprd_dolphin_reg_write(NFC_CFG2_REG, cfg2);
sprd_dolphin_nand_ins_exec(dolphin);
sprd_dolphin_nand_wait_finish(dolphin);
if(!raw) {
for(i = 0; i < dolphin->sct_pg; i++) {
err = sprd_dolphin_get_decode_sts(i);
if(err == ERR_ERR_NUM0_MASK) {
mtd->ecc_stats.failed++;
}
else {
mtd->ecc_stats.corrected += err;
}
}
}
return 0;
}
STATIC_FUNC int sprd_dolphin_nand_write_lp(struct mtd_info *mtd,const uint8_t *mbuf, uint8_t *sbuf,uint32_t raw)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct nand_chip *chip = dolphin->nand;
uint32_t column;
uint32_t page_addr;
uint32_t cfg0;
uint32_t cfg1;
uint32_t cfg2;
page_addr = dolphin->page;
if(mbuf) {
column = 0;
}
else {
column = mtd->writesize;
}
if(chip->options & NAND_BUSWIDTH_16)
{
column >>= 1;
}
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_SEQIN), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
column >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
if (5 == dolphin->a_cycles)// five address cycles
{
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_MWDT, dolphin);
if(mbuf && sbuf)
{
sprd_dolphin_nand_ins_add(NAND_MC_SWDT, dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_PAGEPROG), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_WRB0_ID, dolphin); //wait rb
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
//config registers
cfg0 = NFC_AUTO_MODE | NFC_RW | NFC_WPN | MAIN_SPAR_APT | ((dolphin->sct_pg - 1)<< SECTOR_NUM_OFFSET);
if((!raw) && mbuf && sbuf)
{
cfg0 |= ECC_EN;
}
if(chip->options & NAND_BUSWIDTH_16)
{
cfg0 |= BUS_WIDTH;
}
cfg1 = ((dolphin->info_size) << SPAR_INFO_SIZE_OFFSET);
cfg2 = (dolphin->ecc_mode << 12) | (dolphin->info_pos << SPAR_INFO_POS_OFFSET) | ((dolphin->sct_pg - 1) << SPAR_SECTOR_NUM_OFFSET) | dolphin->ecc_pos;
#ifndef CONFIG_NAND_SPL
if (mbuf)
{
Dcache_CleanRegion((unsigned int)mbuf, dolphin->m_size*dolphin->sct_pg);
Dcache_InvalRegion((unsigned int)mbuf, dolphin->m_size*dolphin->sct_pg);
}
if (sbuf)
{
Dcache_CleanRegion((unsigned int)sbuf, dolphin->s_size*dolphin->sct_pg);
Dcache_InvalRegion((unsigned int)sbuf, dolphin->s_size*dolphin->sct_pg);
}
#endif
if(mbuf && sbuf)
{
cfg0 |= MAIN_USE | SPAR_USE;
cfg1 |= (dolphin->m_size - 1) | ((dolphin->s_size - 1) << SPAR_SIZE_OFFSET);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)mbuf);
sprd_dolphin_reg_write(NFC_SPAR_ADDR_REG, (uint32_t)sbuf);
}
else
{
cfg0 |= MAIN_USE;
if(mbuf)
{
cfg1 |= dolphin->m_size - 1;
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)mbuf);
}
else
{
cfg1 |= dolphin->s_size - 1;
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, (uint32_t)sbuf);
}
}
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_CFG1_REG, cfg1);
sprd_dolphin_reg_write(NFC_CFG2_REG, cfg2);
sprd_dolphin_nand_ins_exec(dolphin);
sprd_dolphin_nand_wait_finish(dolphin);
return 0;
}
#endif
#ifdef DOLPHIN_KERNEL
#ifdef NAND_IRQ_EN
STATIC_FUNC void sprd_dolphin_nand_ins_exec_irq(struct sprd_dolphin_nand_info *dolphin)
{
uint32_t i;
uint32_t cfg0;
uint32_t value = 0;
//DPRINT("%s enter\n", __func__);
for(i = 0; i < ((dolphin->ins_num + 1) >> 1); i++)
{
sprd_dolphin_reg_write(NFC_INST0_REG + (i << 2), dolphin->ins[i]);
}
cfg0 = sprd_dolphin_reg_read(NFC_CFG0_REG);
if(dolphin->wp_en)
{
cfg0 &= ~NFC_WPN;
}
else
{
cfg0 |= NFC_WPN;
}
if(dolphin->chip)
{
cfg0 |= CS_SEL;
}
else
{
cfg0 &= ~CS_SEL;
}
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
nfc_clear_interrupt();
nfc_enable_interrupt();
sprd_dolphin_reg_write(NFC_START_REG, NFC_START);
//DPRINT("%s leave\n", __func__);
}
STATIC_FUNC int sprd_dolphin_nand_wait_finish_irq(struct sprd_dolphin_nand_info *dolphin)
{
unsigned int value;
unsigned int counter = 0;
//DPRINT("%s enter\n", __func__);
nfc_wait_op_done();
if(handle_status==NAND_HANDLE_DONE)
{
ret_irq_en=NAND_NO_ERROR;
}
else if(handle_status==NAND_HANDLE_TIMEOUT)
{
ret_irq_en=NAND_ERR_NEED_RETRY;
}
else if(handle_status==NAND_HANDLE_ERR)
{
ret_irq_en=NAND_ERR_NEED_RETRY;
}
//DPRINT("%s leave\n", __func__);
return 0;
}
STATIC_FUNC void nfc_wait_op_done(void)
{
if (!wait_for_completion_timeout(&nfc_op_completion, msecs_to_jiffies(IRQ_TIMEOUT)))
{
handle_status=NAND_HANDLE_ERR;
DPRINT(KERN_ERR "%s, wait irq timeout\n", __func__);
}
}
STATIC_FUNC irqreturn_t nfc_irq_handler(int irq, void *dev_id)
{
unsigned int value;
//DPRINT("%s enter\n", __func__); /*diable irq*/
nfc_disable_interrupt();
value = sprd_dolphin_reg_read(NFC_INT_REG);
//DPRINT("%s, NFC_INT_REG:0x%x\n", __func__, value);
/*record handle status*/
if(value & INT_TO_STS)
{
DPRINT(KERN_ALERT "%s, timeout occur NFC_INT_REG:0x%x\n", __func__, value);
handle_status=NAND_HANDLE_TIMEOUT;
}
else if(value & INT_DONE_STS)
{
handle_status=NAND_HANDLE_DONE;
}
/*clear irq status*/
//value = (INT_DONE_CLR | INT_TO_CLR);
//sprd_dolphin_reg_or(NFC_INT_REG, value); /* clear all interrupt status */
//value = NFC_CMD_CLR;
//sprd_dolphin_reg_or(NFC_START_REG, value); /* clear all interrupt status */
nfc_clear_interrupt();
complete(&nfc_op_completion);
//DPRINT("%s leave\n", __func__);
return IRQ_HANDLED;
}
#endif
//read large page
STATIC_FUNC int sprd_dolphin_nand_read_lp(struct mtd_info *mtd,uint8_t *mbuf, uint8_t *sbuf,uint32_t raw)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct nand_chip *chip = dolphin->nand;
uint32_t column;
uint32_t page_addr;
uint32_t cfg0;
uint32_t cfg1;
uint32_t cfg2;
uint32_t i;
uint32_t err;
page_addr = dolphin->page;
//DPRINT("%s enter\n", __func__);
if(sbuf) {
column = mtd->writesize;
}
else
{
column = 0;
}
if(chip->options & NAND_BUSWIDTH_16)
{
column >>= 1;
}
//DPRINT("sprd_dolphin_nand_read_lp,page_addr = %x,column = %x\r\n",page_addr, column);
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READ0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
column >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
if (5 == dolphin->a_cycles)// five address cycles
{
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READSTART), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_WRB0_ID, dolphin); //wait rb
if(mbuf && sbuf)
{
sprd_dolphin_nand_ins_add(NAND_MC_SRDT, dolphin);
//switch to main part
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_RNDOUT), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(0), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_RNDOUTSTART), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_MRDT, dolphin);
}
else
{
sprd_dolphin_nand_ins_add(NAND_MC_MRDT, dolphin);
}
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
//config registers
cfg0 = NFC_AUTO_MODE | MAIN_SPAR_APT | ((dolphin->sct_pg - 1)<< SECTOR_NUM_OFFSET);
if((!raw) && mbuf && sbuf)
{
cfg0 |= ECC_EN | DETECT_ALL_FF;
}
if(chip->options & NAND_BUSWIDTH_16)
{
cfg0 |= BUS_WIDTH;
}
cfg1 = (dolphin->info_size) << SPAR_INFO_SIZE_OFFSET;
cfg2 = (dolphin->ecc_mode << 12) | (dolphin->info_pos << SPAR_INFO_POS_OFFSET) | ((dolphin->sct_pg - 1) << SPAR_SECTOR_NUM_OFFSET) | dolphin->ecc_pos;
if(mbuf && sbuf)
{
cfg1 |= (dolphin->m_size - 1) | ((dolphin->s_size - 1)<< SPAR_SIZE_OFFSET);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, dolphin->p_mbuf);
sprd_dolphin_reg_write(NFC_SPAR_ADDR_REG, dolphin->p_oob);
cfg0 |= MAIN_USE | SPAR_USE;
}
else
{
if(mbuf)
{
cfg1 |= (dolphin->m_size - 1);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, dolphin->p_mbuf);
}
if(sbuf)
{
cfg1 |= (dolphin->s_size - 1);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, dolphin->p_oob);
}
cfg0 |= MAIN_USE;
}
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_CFG1_REG, cfg1);
sprd_dolphin_reg_write(NFC_CFG2_REG, cfg2);
#ifdef NAND_IRQ_EN
sprd_dolphin_nand_ins_exec_irq(dolphin);
sprd_dolphin_nand_wait_finish_irq(dolphin);
#else
sprd_dolphin_nand_ins_exec(dolphin);
sprd_dolphin_nand_wait_finish(dolphin);
#endif
if(!raw) {
for(i = 0; i < dolphin->sct_pg; i++) {
err = sprd_dolphin_get_decode_sts(i);
if(err == ERR_ERR_NUM0_MASK) {
mtd->ecc_stats.failed++;
}
else {
mtd->ecc_stats.corrected += err;
}
}
}
if(mbuf) {
memcpy(mbuf, (const void *)dolphin->v_mbuf, dolphin->write_size);
}
if(sbuf) {
memcpy(sbuf, (const void *)dolphin->v_oob, dolphin->oob_size);
}
return 0;
}
STATIC_FUNC int sprd_dolphin_nand_write_lp(struct mtd_info *mtd,const uint8_t *mbuf, uint8_t *sbuf,uint32_t raw)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct nand_chip *chip = dolphin->nand;
uint32_t column;
uint32_t page_addr;
uint32_t cfg0;
uint32_t cfg1;
uint32_t cfg2;
page_addr = dolphin->page;
//DPRINT("%s, page addr is %lx\n", __func__, page_addr);
if(mbuf) {
column = 0;
}
else {
column = mtd->writesize;
}
if(chip->options & NAND_BUSWIDTH_16)
{
column >>= 1;
}
if(mbuf) {
memcpy((void *)dolphin->v_mbuf, (const void *)mbuf, dolphin->write_size);
}
if(sbuf) {
memcpy((void *)dolphin->v_oob, (const void *)sbuf, dolphin->oob_size);
}
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_SEQIN), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
column >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(column & 0xff), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
if (5 == dolphin->a_cycles)// five address cycles
{
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_MWDT, dolphin);
if(mbuf && sbuf)
{
sprd_dolphin_nand_ins_add(NAND_MC_SWDT, dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_PAGEPROG), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_WRB0_ID, dolphin); //wait rb
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
//config registers
cfg0 = NFC_AUTO_MODE | NFC_RW | NFC_WPN | MAIN_SPAR_APT | ((dolphin->sct_pg - 1)<< SECTOR_NUM_OFFSET);
if((!raw) && mbuf && sbuf)
{
cfg0 |= ECC_EN;
}
if(chip->options & NAND_BUSWIDTH_16)
{
cfg0 |= BUS_WIDTH;
}
cfg1 = ((dolphin->info_size) << SPAR_INFO_SIZE_OFFSET);
cfg2 = (dolphin->ecc_mode << 12) | (dolphin->info_pos << SPAR_INFO_POS_OFFSET) | ((dolphin->sct_pg - 1) << SPAR_SECTOR_NUM_OFFSET) | dolphin->ecc_pos;
if(mbuf && sbuf)
{
cfg0 |= MAIN_USE | SPAR_USE;
cfg1 |= (dolphin->m_size - 1) | ((dolphin->s_size - 1) << SPAR_SIZE_OFFSET);
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, dolphin->p_mbuf);
sprd_dolphin_reg_write(NFC_SPAR_ADDR_REG, dolphin->p_oob);
}
else
{
cfg0 |= MAIN_USE;
if(mbuf)
{
cfg1 |= dolphin->m_size - 1;
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, dolphin->p_mbuf);
}
else
{
cfg1 |= dolphin->s_size - 1;
sprd_dolphin_reg_write(NFC_MAIN_ADDR_REG, dolphin->p_oob);
}
}
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
sprd_dolphin_reg_write(NFC_CFG1_REG, cfg1);
sprd_dolphin_reg_write(NFC_CFG2_REG, cfg2);
#ifdef NAND_IRQ_EN
sprd_dolphin_nand_ins_exec_irq(dolphin);
sprd_dolphin_nand_wait_finish_irq(dolphin);
#else
sprd_dolphin_nand_ins_exec(dolphin);
sprd_dolphin_nand_wait_finish(dolphin);
#endif
return 0;
}
#endif
STATIC_FUNC int sprd_dolphin_nand_read_sp(struct mtd_info *mtd,uint8_t *mbuf, uint8_t *sbuf,uint32_t raw)
{
return 0;
}
STATIC_FUNC int sprd_dolphin_nand_write_sp(struct mtd_info *mtd,const uint8_t *mbuf, uint8_t *sbuf,uint32_t raw)
{
return 0;
}
STATIC_FUNC void sprd_dolphin_erase(struct mtd_info *mtd, int page_addr)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
uint32_t cfg0 = 0;
//DPRINT("%s, page addr is %x\r\n", __func__ , page_addr);
sprd_dolphin_nand_ins_init(dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_ERASE1), dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
if((5 == dolphin->a_cycles) || ((4 == dolphin->a_cycles) && (512 == dolphin->write_size)))
{
page_addr >>= 8;
sprd_dolphin_nand_ins_add(NAND_MC_ADDR(page_addr & 0xff), dolphin);
}
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_ERASE2), dolphin);
sprd_dolphin_nand_ins_add(NFC_MC_WRB0_ID, dolphin); //wait rb
sprd_dolphin_nand_ins_add(NFC_MC_DONE_ID, dolphin);
cfg0 = NFC_WPN | NFC_ONLY_NAND_MODE;
sprd_dolphin_reg_write(NFC_CFG0_REG, cfg0);
#ifdef NAND_IRQ_EN
sprd_dolphin_nand_ins_exec_irq(dolphin);
sprd_dolphin_nand_wait_finish_irq(dolphin);
#else
sprd_dolphin_nand_ins_exec(dolphin);
sprd_dolphin_nand_wait_finish(dolphin);
#endif
//DPRINT("%s leave\n", __func__);
}
STATIC_FUNC uint8_t sprd_dolphin_read_byte(struct mtd_info *mtd)
{
uint8_t ch = 0xff;
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
if(dolphin->buf_head < dolphin->_buf_tail)
{
ch = s_oob_data[dolphin->buf_head ++];
}
return ch;
}
STATIC_FUNC uint16_t sprd_dolphin_read_word(struct mtd_info *mtd)
{
uint16_t data = 0xffff;
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
if(dolphin->buf_head < (dolphin->_buf_tail - 1))
{
data = s_oob_data[dolphin->buf_head ++];
data |= ((uint16_t)s_oob_data[dolphin->buf_head ++]) << 8;
}
return data;
}
STATIC_FUNC int sprd_dolphin_waitfunc(struct mtd_info *mtd, struct nand_chip *chip)
{
return 0;
}
STATIC_FUNC int sprd_dolphin_ecc_calculate(struct mtd_info *mtd, const uint8_t *data,
uint8_t *ecc_code)
{
return 0;
}
STATIC_FUNC int sprd_dolphin_ecc_correct(struct mtd_info *mtd, uint8_t *data,
uint8_t *read_ecc, uint8_t *calc_ecc)
{
return 0;
}
STATIC_FUNC int sprd_dolphin_read_page(struct mtd_info *mtd, struct nand_chip *chip,
uint8_t *buf, int oob_required,int page)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
dolphin->page = page;
if(512 == mtd->writesize)
{
sprd_dolphin_nand_read_sp(mtd, buf, chip->oob_poi, 0);
}
else
{
sprd_dolphin_nand_read_lp(mtd, buf, chip->oob_poi, 0);
}
return 0;
}
STATIC_FUNC int sprd_dolphin_read_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
uint8_t *buf, int oob_required, int page)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
dolphin->page = page;
if(512 == mtd->writesize)
{
sprd_dolphin_nand_read_sp(mtd, buf, chip->oob_poi, 1);
}
else
{
sprd_dolphin_nand_read_lp(mtd, buf, chip->oob_poi, 1);
}
return 0;
}
STATIC_FUNC int sprd_dolphin_read_oob(struct mtd_info *mtd, struct nand_chip *chip,
int page, int sndcmd)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
dolphin->page = page;
if(512 == mtd->writesize)
{
sprd_dolphin_nand_read_sp(mtd, 0, chip->oob_poi, 1);
}
else
{
sprd_dolphin_nand_read_lp(mtd, 0, chip->oob_poi, 1);
}
return 0;
}
STATIC_FUNC void sprd_dolphin_write_page(struct mtd_info *mtd, struct nand_chip *chip,
const uint8_t *buf,int oob_required)
{
if(512 == mtd->writesize)
{
sprd_dolphin_nand_write_sp(mtd, buf, chip->oob_poi, 0);
}
else
{
sprd_dolphin_nand_write_lp(mtd, buf, chip->oob_poi, 0);
}
}
STATIC_FUNC void sprd_dolphin_write_page_raw(struct mtd_info *mtd, struct nand_chip *chip,
const uint8_t *buf,int oob_required)
{
if(512 == mtd->writesize)
{
sprd_dolphin_nand_write_sp(mtd, buf, chip->oob_poi, 1);
}
else
{
sprd_dolphin_nand_write_lp(mtd, buf, chip->oob_poi, 1);
}
}
STATIC_FUNC int sprd_dolphin_write_oob(struct mtd_info *mtd, struct nand_chip *chip,
int page)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
dolphin->page = page;
if(512 == mtd->writesize)
{
sprd_dolphin_nand_write_sp(mtd, 0, chip->oob_poi, 1);
}
else
{
sprd_dolphin_nand_write_lp(mtd, 0, chip->oob_poi, 1);
}
return 0;
}
/**
* nand_block_bad - [DEFAULT] Read bad block marker from the chip
* @mtd: MTD device structure
* @ofs: offset from device start
* @getchip: 0, if the chip is already selected
*
* Check, if the block is bad.
*/
STATIC_FUNC int sprd_dolphin_block_bad(struct mtd_info *mtd, loff_t ofs, int getchip)
{
int page, chipnr, res = 0;
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
struct nand_chip *chip = mtd->priv;
uint16_t bad;
uint16_t *buf;
page = (int)((long)ofs >> chip->page_shift) & chip->pagemask;
if (getchip) {
chipnr = (int)((long)ofs >> chip->chip_shift);
/* Select the NAND device */
chip->select_chip(mtd, chipnr);
}
chip->cmdfunc(mtd, NAND_CMD_READOOB, 0, page);
if(512 == dolphin->write_size) {
sprd_dolphin_nand_read_sp(mtd, 0, s_oob_data, 1);
}
else {
sprd_dolphin_nand_read_lp(mtd, 0, s_oob_data, 1);
}
dolphin->buf_head = 0;
dolphin->_buf_tail = mtd->oobsize;
buf = (uint16_t *)(s_oob_data + chip->badblockpos);
if (chip->options & NAND_BUSWIDTH_16) {
bad = *(buf);
if ((bad & 0xFF) != 0xff) {
res = 1;
}
} else {
bad = *(buf) & 0xff;
if (bad != 0xff){
res = 1;
}
}
return res;
}
STATIC_FUNC void sprd_dolphin_nand_cmdfunc(struct mtd_info *mtd, unsigned int command,
int column, int page_addr)
{
struct sprd_dolphin_nand_info *dolphin = mtd_to_dolphin(mtd);
/* Emulate NAND_CMD_READOOB */
if (command == NAND_CMD_READOOB) {
column += mtd->writesize;
command = NAND_CMD_READ0;
}
/*
* program and erase have their own busy handlers
* status, sequential in, and deplete1 need no delay
*/
switch (command) {
case NAND_CMD_STATUS:
sprd_dolphin_nand_read_status(dolphin);
break;
case NAND_CMD_READID:
sprd_dolphin_nand_read_id(dolphin, (uint32_t *)s_oob_data);
break;
case NAND_CMD_RESET:
sprd_dolphin_nand_reset(dolphin);
break;
case NAND_CMD_ERASE1:
sprd_dolphin_erase(mtd, page_addr);
break;
case NAND_CMD_READ0:
case NAND_CMD_SEQIN:
dolphin->column = column;
dolphin->page = page_addr;
default:
break;
}
}
STATIC_FUNC void sprd_dolphin_nand_hwecc_ctl(struct mtd_info *mtd, int mode)
{
return; //do nothing
}
#ifdef DOLPHIN_UBOOT
#define DOLPHIN_AHB_BASE SPRD_AHB_PHYS
#define DOLPHIN_PIN_BASE SPRD_PIN_PHYS
#define DOLPHIN_AHB_RST (DOLPHIN_AHB_BASE + 0x0004)
#define DOLPHIN_NANC_CLK_CFG (DOLPHIN_AHB_BASE + 0x0060)
#define DOLPHIN_ADISLAVE_BASE SPRD_ADISLAVE_PHYS
#define DOLPHIN_ANA_CTL_GLB_BASE (DOLPHIN_ADISLAVE_BASE + 0x8800)
#define DOLPHIN_NFC_REG_BASE SPRD_NFC_PHYS
#define DOLPHIN_NFC_TIMING_REG (DOLPHIN_NFC_REG_BASE + 0x14)
#define DOLPHIN_NFC_TIMEOUT_REG (DOLPHIN_NFC_REG_BASE + 0x34)
#endif
#ifdef DOLPHIN_KERNEL
#define DOLPHIN_AHB_BASE SPRD_AHB_BASE
#define DOLPHIN_PIN_BASE SPRD_PIN_BASE
#define DOLPHIN_AHB_RST (DOLPHIN_AHB_BASE + 0x0004)
#define DOLPHIN_NANC_CLK_CFG (DOLPHIN_AHB_BASE + 0x0060)
#define DOLPHIN_ADISLAVE_BASE SPRD_ADISLAVE_BASE
#define DOLPHIN_ANA_CTL_GLB_BASE (DOLPHIN_ADISLAVE_BASE + 0x8800)
#define DOLPHIN_NFC_REG_BASE SPRD_NFC_BASE
#define DOLPHIN_NFC_TIMING_REG (DOLPHIN_NFC_REG_BASE + 0x14)
#define DOLPHIN_NFC_TIMEOUT_REG (DOLPHIN_NFC_REG_BASE + 0x34)
#endif
STATIC_FUNC void sprd_dolphin_nand_hw_init(struct sprd_dolphin_nand_info *dolphin)
{
int i = 0;
uint32_t val;
//sprd_dolphin_reg_and(DOLPHIN_NANC_CLK_CFG, ~(BIT(1) | BIT(0)));
//sprd_dolphin_reg_or(DOLPHIN_NANC_CLK_CFG, BIT(0));
sprd_dolphin_reg_or((REGS_AP_CLK_BASE + 0x44), BIT(1));
sprd_dolphin_reg_or(DOLPHIN_AHB_BASE, BIT(6));
sprd_dolphin_reg_or(DOLPHIN_AHB_RST,BIT(9));
mdelay(1);
sprd_dolphin_reg_and(DOLPHIN_AHB_RST, ~(BIT(9)));
val = (3) | (4 << NFC_RWH_OFFSET) | (3 << NFC_RWE_OFFSET) | (3 << NFC_RWS_OFFSET) | (3 << NFC_ACE_OFFSET) | (3 << NFC_ACS_OFFSET);
sprd_dolphin_reg_write(DOLPHIN_NFC_TIMING_REG, val);
sprd_dolphin_reg_write(DOLPHIN_NFC_TIMEOUT_REG, 0xffffffff);
//sprd_dolphin_reg_write(DOLPHIN_NFC_REG_BASE + 0x118, 3);
#if 0
sprd_dolphin_reg_or(DOLPHIN_PIN_BASE + REG_PIN_NFWPN, BIT(7) | BIT(8) | BIT(9));
sprd_dolphin_reg_and(DOLPHIN_PIN_BASE + REG_PIN_NFWPN, ~(BIT(4) | BIT(5)));
sprd_dolphin_reg_or(DOLPHIN_PIN_BASE + REG_PIN_NFRB, BIT(7) | BIT(8) | BIT(9));
sprd_dolphin_reg_and(DOLPHIN_PIN_BASE + REG_PIN_NFRB, ~(BIT(4) | BIT(5)));
for(i = 0; i < 22; ++i)
{
sprd_dolphin_reg_or(DOLPHIN_PIN_BASE + REG_PIN_NFCLE + (i << 2), BIT(7) | BIT(8) | BIT(9));
sprd_dolphin_reg_and(DOLPHIN_PIN_BASE + REG_PIN_NFCLE + (i << 2), ~(BIT(4) | BIT(5)));
}
#endif
#if 0
i = sprd_dolphin_reg_read(DOLPHIN_ANA_CTL_GLB_BASE+0x3c);
i &= ~0x7F00;
i |= 0x38 << 8;
sprd_dolphin_reg_write(DOLPHIN_ANA_CTL_GLB_BASE + 0x3c, i);
i = sprd_dolphin_reg_read(DOLPHIN_ANA_CTL_GLB_BASE+0x20);
i &= ~0xFF;
i |= 0x38 << 0;
sprd_dolphin_reg_write(DOLPHIN_ANA_CTL_GLB_BASE + 0x20, i);
#endif
//close write protect
sprd_dolphin_nand_wp_en(dolphin, 0);
}
int board_nand_init(struct nand_chip *chip)
{
DPRINT("board_nand_init\r\n");
sprd_dolphin_nand_hw_init(&g_dolphin);
chip->select_chip = sprd_dolphin_select_chip;
chip->cmdfunc = sprd_dolphin_nand_cmdfunc;
chip->read_byte = sprd_dolphin_read_byte;
chip->read_word = sprd_dolphin_read_word;
chip->waitfunc = sprd_dolphin_waitfunc;
chip->ecc.mode = NAND_ECC_HW;
chip->ecc.calculate = sprd_dolphin_ecc_calculate;
chip->ecc.hwctl = sprd_dolphin_nand_hwecc_ctl;
chip->ecc.correct = sprd_dolphin_ecc_correct;
chip->ecc.read_page = sprd_dolphin_read_page;
chip->ecc.read_page_raw = sprd_dolphin_read_page_raw;
chip->ecc.write_page = sprd_dolphin_write_page;
chip->ecc.write_page_raw = sprd_dolphin_write_page_raw;
chip->ecc.read_oob = sprd_dolphin_read_oob;
chip->ecc.write_oob = sprd_dolphin_write_oob;
chip->erase_cmd = sprd_dolphin_erase;
chip->ecc.bytes = CONFIG_SYS_NAND_ECCBYTES;
g_dolphin.ecc_mode = ecc_mode_convert(CONFIG_SYS_NAND_ECC_MODE);
g_dolphin.nand = chip;
#ifdef DOLPHIN_KERNEL
chip->ecc.strength = CONFIG_SYS_NAND_ECC_MODE;
#endif
#ifdef DOLPHIN_UBOOT
chip->eccbitmode = CONFIG_SYS_NAND_ECC_MODE;
#endif
//dolphin_set_timing_config(&g_dolphin, SPRD_NAND_CLOCK); /* 153 is current clock 153MHz */
chip->ecc.size = CONFIG_SYS_NAND_ECCSIZE;
chip->chip_delay = 20;
chip->priv = &g_dolphin;
//DPRINT("v2 board eccbitmode %d\n", chip->eccbitmode);
chip->options = NAND_BUSWIDTH_16;
return 0;
}
#ifdef DOLPHIN_UBOOT
#ifndef CONFIG_NAND_SPL
void McuReadNandType(unsigned char *array)
{
}
#endif
static unsigned long nfc_read_status(void)
{
unsigned long status = 0;
sprd_dolphin_nand_read_status(&g_dolphin);
status = s_oob_data[0];
return status;
}
#ifndef CONFIG_NAND_SPL
static int sprd_scan_one_block(int blk, int erasesize, int writesize)
{
int i, cmd;
int status = 1, ii;
u32 size = 0;
int oobsize = mtdoobsize;
int column, page_addr;
page_addr = blk * (erasesize / writesize);
for (ii = 0; ii < 2; ii ++) {
DPRINT("please debug here : %s %d\n", __FUNCTION__, __LINE__);
sprd_dolphin_nand_ins_init(&g_dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READ0), &g_dolphin);
sprd_dolphin_nand_ins_add(NAND_MC_CMD(NAND_CMD_READSTART), &g_dolphin);
if ((s_oob_data[0] != 0xff) || (s_oob_data[1] != 0xff))
break;
} //for (ii = 0; ii < 2; ii ++)
if ((s_oob_data[0] == 0xff) && (s_oob_data[1] == 0xff))
status = 0; //good block
else
status = 1; //bad block
return status;
}
static unsigned long nand_ctl_erase_block(int blk, int erasesize, int writesize)
{
int cmd, status;
int page_addr;
page_addr = blk * (erasesize / writesize);
sprd_dolphin_erase(&g_dolphin, page_addr);
status = nfc_read_status();
return status;
}
#endif
#ifndef CONFIG_NAND_SPL
void nand_scan_patition(int blocks, int erasesize, int writesize)
{
int blk;
int ret;
int status;
//read_chip_id();
for (blk = 0; blk < blocks; blk ++) {
ret = sprd_scan_one_block(blk, erasesize, writesize);
if (ret != 0) {
DPRINT("\n%d is bad, scrub to erase it, ", blk);
ret = nand_ctl_erase_block(blk, erasesize, writesize);
DPRINT("0x%02x\n", ret);
} else {
ret = nand_ctl_erase_block(blk, erasesize, writesize);
DPRINT("erasing block : %d %d % \r", blk, (blk * 100 ) / blocks);
}
}
}
int nand_scan_block(int block, int erasesize, int writesize){
int ret = 0;
ret = nand_ctl_erase_block(block, erasesize, writesize);
ret = ret&1;
return ret;
}
#endif
#endif //DOLPHIN_UBOOT end
#ifdef DOLPHIN_KERNEL
extern int parse_mtd_partitions(struct mtd_info *master, const char **types,
struct mtd_partition **pparts,
struct mtd_part_parser_data *data);
static struct mtd_info *sprd_mtd = NULL;
#ifdef CONFIG_MTD_CMDLINE_PARTS
const char *part_probes[] = { "cmdlinepart", NULL };
#endif
STATIC_FUNC int sprd_nand_dma_init(struct sprd_dolphin_nand_info *dolphin)
{
dma_addr_t phys_addr = 0;
void *virt_ptr = 0;
virt_ptr = dma_alloc_coherent(NULL, dolphin->write_size, &phys_addr, GFP_KERNEL);
if (virt_ptr == NULL) {
DPRINT(KERN_ERR "NAND - Failed to allocate memory for DMA main buffer\n");
return -ENOMEM;
}
dolphin->v_mbuf = (u32)virt_ptr;
dolphin->p_mbuf = (u32)phys_addr;
virt_ptr = dma_alloc_coherent(NULL, dolphin->oob_size, &phys_addr, GFP_KERNEL);
if (virt_ptr == NULL) {
DPRINT(KERN_ERR "NAND - Failed to allocate memory for DMA oob buffer\n");
dma_free_coherent(NULL, dolphin->write_size, (void *)dolphin->v_mbuf, (dma_addr_t)dolphin->p_mbuf);
return -ENOMEM;
}
dolphin->v_oob = (u32)virt_ptr;
dolphin->p_oob = (u32)phys_addr;
return 0;
}
STATIC_FUNC void sprd_nand_dma_deinit(struct sprd_dolphin_nand_info *dolphin)
{
dma_free_coherent(NULL, dolphin->write_size, (void *)dolphin->v_mbuf, (dma_addr_t)dolphin->p_mbuf);
dma_free_coherent(NULL, dolphin->write_size, (void *)dolphin->v_oob, (dma_addr_t)dolphin->p_oob);
}
STATIC_FUNC int sprd_nand_probe(struct platform_device *pdev)
{
struct nand_chip *this;
struct resource *regs = NULL;
struct mtd_partition *partitions = NULL;
int num_partitions = 0;
int ret = 0;
#ifdef NAND_IRQ_EN
int err = 0;
init_completion(&nfc_op_completion);
err = request_irq(IRQ_NFC_INT, nfc_irq_handler, 0, DRIVER_NAME, NULL);
if (err) {
DPRINT(KERN_ERR "request_irq error\n");
goto prob_err;
}
DPRINT(KERN_ALERT "request_irq ok\n");
#endif
regs = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!regs) {
dev_err(&pdev->dev,"resources unusable\n");
goto prob_err;
}
memset(&g_dolphin, 0 , sizeof(g_dolphin));
platform_set_drvdata(pdev, &g_dolphin);
g_dolphin.pdev = pdev;
sprd_mtd = kmalloc(sizeof(struct mtd_info) + sizeof(struct nand_chip), GFP_KERNEL);
this = (struct nand_chip *)(&sprd_mtd[1]);
memset((char *)sprd_mtd, 0, sizeof(struct mtd_info));
memset((char *)this, 0, sizeof(struct nand_chip));
sprd_mtd->priv = this;
this->options |= NAND_BUSWIDTH_16;
//this->options |= NAND_NO_READRDY;
board_nand_init(this);
if (sprd_dolphin_nand_reset(&g_dolphin) != 0)
{
ret = -ENXIO;
DPRINT(KERN_ERR "nand reset failed!!!!!!!!!!!!!\n");
goto prob_err;
}
msleep(1);
if (sprd_dolphin_nand_read_id(&g_dolphin, (uint32_t *)s_oob_data) != 0)
{
ret = -ENXIO;
DPRINT(KERN_ERR "nand read id failed, no nand device!!!!!!!!!!!!!\n");
}
DPRINT(KERN_ALERT "nand read id ok, nand exists!!!!!!!!!!!!!\n");
//nand_scan(sprd_mtd, 1);
/* first scan to find the device and get the page size */
if (nand_scan_ident(sprd_mtd, 1, NULL)) {
ret = -ENXIO;
goto prob_err;
}
sprd_dolphin_nand_read_id(&g_dolphin, (uint32_t *)s_oob_data);
nand_hardware_config(sprd_mtd, this, s_oob_data);
if(sprd_nand_dma_init(&g_dolphin) != 0) {
return -ENOMEM;
}
//this->IO_ADDR_R = g_dolphin.v_mbuf;
//this->IO_ADDR_W = g_dolphin.v_mbuf;
/* second phase scan */
if (nand_scan_tail(sprd_mtd)) {
ret = -ENXIO;
goto prob_err;
}
sprd_mtd->name = "sprd-nand";
num_partitions = parse_mtd_partitions(sprd_mtd, part_probes, &partitions, 0);
if ((!partitions) || (num_partitions == 0)) {
DPRINT(KERN_ALERT "No parititions defined, or unsupported device.\n");
goto release;
}
#ifdef CONFIG_MTD_CMDLINE_PARTS
mtd_device_register(sprd_mtd, partitions, num_partitions);
#endif
return 0;
release:
nand_release(sprd_mtd);
sprd_nand_dma_deinit(&g_dolphin);
prob_err:
sprd_dolphin_reg_and(DOLPHIN_AHB_BASE,~(BIT(6)));
kfree(sprd_mtd);
return ret;
}
STATIC_FUNC int sprd_nand_remove(struct platform_device *pdev)
{
platform_set_drvdata(pdev, NULL);
nand_release(sprd_mtd);
sprd_nand_dma_deinit(&g_dolphin);
kfree(sprd_mtd);
return 0;
}
#ifdef CONFIG_PM
STATIC_FUNC int sprd_nand_suspend(struct platform_device *dev, pm_message_t pm)
{
//nothing to do
return 0;
}
STATIC_FUNC int sprd_nand_resume(struct platform_device *dev)
{
sprd_dolphin_nand_hw_init(&g_dolphin);
return 0;
}
#else
#define sprd_nand_suspend NULL
#define sprd_nand_resume NULL
#endif
static struct platform_driver sprd_nand_driver = {
.probe = sprd_nand_probe,
.remove = sprd_nand_remove,
.suspend = sprd_nand_suspend,
.resume = sprd_nand_resume,
.driver = {
.name = "sprd-nand",
.owner = THIS_MODULE,
},
};
STATIC_FUNC int __init sprd_nand_init(void)
{
return platform_driver_register(&sprd_nand_driver);
}
STATIC_FUNC void __exit sprd_nand_exit(void)
{
platform_driver_unregister(&sprd_nand_driver);
}
module_init(sprd_nand_init);
module_exit(sprd_nand_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("giya.li@spreadtrum.com");
MODULE_DESCRIPTION("SPRD dolphin MTD NAND driver");
MODULE_ALIAS("platform:sprd-nand");
#endif
| gpl-3.0 |
gmorph/ardupilot | libraries/SITL/SIM_QuadPlane.cpp | 6 | 3663 | /*
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/>.
*/
/*
simple quadplane simulator class
*/
#include "SIM_QuadPlane.h"
#include <stdio.h>
using namespace SITL;
QuadPlane::QuadPlane(const char *home_str, const char *frame_str) :
Plane(home_str, frame_str)
{
// default to X frame
const char *frame_type = "x";
uint8_t motor_offset = 4;
if (strstr(frame_str, "-octa-quad")) {
frame_type = "octa-quad";
} else if (strstr(frame_str, "-octaquad")) {
frame_type = "octa-quad";
} else if (strstr(frame_str, "-octa")) {
frame_type = "octa";
} else if (strstr(frame_str, "-hexax")) {
frame_type = "hexax";
} else if (strstr(frame_str, "-hexa")) {
frame_type = "hexa";
} else if (strstr(frame_str, "-plus")) {
frame_type = "+";
} else if (strstr(frame_str, "-y6")) {
frame_type = "y6";
} else if (strstr(frame_str, "-tri")) {
frame_type = "tri";
} else if (strstr(frame_str, "-tilttrivec")) {
frame_type = "tilttrivec";
// fwd motor gives zero thrust
thrust_scale = 0;
} else if (strstr(frame_str, "-tilttri")) {
frame_type = "tilttri";
// fwd motor gives zero thrust
thrust_scale = 0;
} else if (strstr(frame_str, "firefly")) {
frame_type = "firefly";
// elevon style surfaces
elevons = true;
// fwd motor gives zero thrust
thrust_scale = 0;
// vtol motors start at 2
motor_offset = 2;
} else if (strstr(frame_str, "cl84")) {
frame_type = "tilttri";
// fwd motor gives zero thrust
thrust_scale = 0;
}
frame = Frame::find_frame(frame_type);
if (frame == nullptr) {
printf("Failed to find frame '%s'\n", frame_type);
exit(1);
}
if (strstr(frame_str, "cl84")) {
// setup retract servos at front
frame->motors[0].servo_type = Motor::SERVO_RETRACT;
frame->motors[0].servo_rate = 7*60.0/90; // 7 seconds to change
frame->motors[1].servo_type = Motor::SERVO_RETRACT;
frame->motors[1].servo_rate = 7*60.0/90; // 7 seconds to change
}
// leave first 4 servos free for plane
frame->motor_offset = motor_offset;
// we use zero terminal velocity to let the plane model handle the drag
frame->init(mass, 0.51, 0, 0);
ground_behavior = GROUND_BEHAVIOR_NO_MOVEMENT;
}
/*
update the quadplane simulation by one time step
*/
void QuadPlane::update(const struct sitl_input &input)
{
// get wind vector setup
update_wind(input);
// first plane forces
Vector3f rot_accel;
calculate_forces(input, rot_accel, accel_body);
// now quad forces
Vector3f quad_rot_accel;
Vector3f quad_accel_body;
frame->calculate_forces(*this, input, quad_rot_accel, quad_accel_body);
rot_accel += quad_rot_accel;
accel_body += quad_accel_body;
update_dynamics(rot_accel);
// update lat/lon/altitude
update_position();
// update magnetic field
update_mag_field_bf();
}
| gpl-3.0 |
NeCarbon/vice-players | RakNet/DS_Table.cpp | 6 | 27176 | #include "DS_Table.h"
#include "DS_OrderedList.h"
#include <string.h>
#include "RakAssert.h"
#include "RakAssert.h"
#include "Itoa.h"
using namespace DataStructures;
#ifdef _MSC_VER
#pragma warning( push )
#endif
void ExtendRows(Table::Row* input, int index)
{
(void) index;
input->cells.Insert(RakNet::OP_NEW<Table::Cell>(_FILE_AND_LINE_), _FILE_AND_LINE_ );
}
void FreeRow(Table::Row* input, int index)
{
(void) index;
unsigned i;
for (i=0; i < input->cells.Size(); i++)
{
RakNet::OP_DELETE(input->cells[i], _FILE_AND_LINE_);
}
RakNet::OP_DELETE(input, _FILE_AND_LINE_);
}
Table::Cell::Cell()
{
isEmpty=true;
c=0;
ptr=0;
i=0.0;
}
Table::Cell::~Cell()
{
Clear();
}
Table::Cell& Table::Cell::operator = ( const Table::Cell& input )
{
isEmpty=input.isEmpty;
i=input.i;
ptr=input.ptr;
if (c)
rakFree_Ex(c, _FILE_AND_LINE_);
if (input.c)
{
c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ );
memcpy(c, input.c, (int) i);
}
else
c=0;
return *this;
}
Table::Cell::Cell( const Table::Cell & input)
{
isEmpty=input.isEmpty;
i=input.i;
ptr=input.ptr;
if (input.c)
{
if (c)
rakFree_Ex(c, _FILE_AND_LINE_);
c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ );
memcpy(c, input.c, (int) i);
}
}
void Table::Cell::Set(double input)
{
Clear();
i=input;
c=0;
ptr=0;
isEmpty=false;
}
void Table::Cell::Set(unsigned int input)
{
Set((int) input);
}
void Table::Cell::Set(int input)
{
Clear();
i=(double) input;
c=0;
ptr=0;
isEmpty=false;
}
void Table::Cell::Set(const char *input)
{
Clear();
if (input)
{
i=(int)strlen(input)+1;
c = (char*) rakMalloc_Ex( (int) i, _FILE_AND_LINE_ );
strcpy(c, input);
}
else
{
c=0;
i=0;
}
ptr=0;
isEmpty=false;
}
void Table::Cell::Set(const char *input, int inputLength)
{
Clear();
if (input)
{
c = (char*) rakMalloc_Ex( inputLength, _FILE_AND_LINE_ );
i=inputLength;
memcpy(c, input, inputLength);
}
else
{
c=0;
i=0;
}
ptr=0;
isEmpty=false;
}
void Table::Cell::SetPtr(void* p)
{
Clear();
c=0;
ptr=p;
isEmpty=false;
}
void Table::Cell::Get(int *output)
{
RakAssert(isEmpty==false);
int o = (int) i;
*output=o;
}
void Table::Cell::Get(double *output)
{
RakAssert(isEmpty==false);
*output=i;
}
void Table::Cell::Get(char *output)
{
RakAssert(isEmpty==false);
strcpy(output, c);
}
void Table::Cell::Get(char *output, int *outputLength)
{
RakAssert(isEmpty==false);
memcpy(output, c, (int) i);
if (outputLength)
*outputLength=(int) i;
}
RakNet::RakString Table::Cell::ToString(ColumnType columnType)
{
if (isEmpty)
return RakNet::RakString();
if (columnType==NUMERIC)
{
return RakNet::RakString("%f", i);
}
else if (columnType==STRING)
{
return RakNet::RakString(c);
}
else if (columnType==BINARY)
{
return RakNet::RakString("<Binary>");
}
else if (columnType==POINTER)
{
return RakNet::RakString("%p", ptr);
}
return RakNet::RakString();
}
Table::Cell::Cell(double numericValue, char *charValue, void *ptr, ColumnType type)
{
SetByType(numericValue,charValue,ptr,type);
}
void Table::Cell::SetByType(double numericValue, char *charValue, void *ptr, ColumnType type)
{
isEmpty=true;
if (type==NUMERIC)
{
Set(numericValue);
}
else if (type==STRING)
{
Set(charValue);
}
else if (type==BINARY)
{
Set(charValue, (int) numericValue);
}
else if (type==POINTER)
{
SetPtr(ptr);
}
else
{
ptr=(void*) charValue;
}
}
Table::ColumnType Table::Cell::EstimateColumnType(void) const
{
if (c)
if (i!=0.0f)
return BINARY;
else
return STRING;
if (ptr)
return POINTER;
return NUMERIC;
}
void Table::Cell::Clear(void)
{
if (isEmpty==false && c)
{
rakFree_Ex(c, _FILE_AND_LINE_);
c=0;
}
isEmpty=true;
}
Table::ColumnDescriptor::ColumnDescriptor()
{
}
Table::ColumnDescriptor::~ColumnDescriptor()
{
}
Table::ColumnDescriptor::ColumnDescriptor(const char cn[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType ct)
{
columnType=ct;
strcpy(columnName, cn);
}
void Table::Row::UpdateCell(unsigned columnIndex, double value)
{
cells[columnIndex]->Clear();
cells[columnIndex]->Set(value);
// cells[columnIndex]->i=value;
// cells[columnIndex]->c=0;
// cells[columnIndex]->isEmpty=false;
}
void Table::Row::UpdateCell(unsigned columnIndex, const char *str)
{
cells[columnIndex]->Clear();
cells[columnIndex]->Set(str);
}
void Table::Row::UpdateCell(unsigned columnIndex, int byteLength, const char *data)
{
cells[columnIndex]->Clear();
cells[columnIndex]->Set(data,byteLength);
}
Table::Table()
{
}
Table::~Table()
{
Clear();
}
unsigned Table::AddColumn(const char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH], ColumnType columnType)
{
if (columnName[0]==0)
return (unsigned) -1;
// Add this column.
columns.Insert(Table::ColumnDescriptor(columnName, columnType), _FILE_AND_LINE_);
// Extend the rows by one
rows.ForEachData(ExtendRows);
return columns.Size()-1;
}
void Table::RemoveColumn(unsigned columnIndex)
{
if (columnIndex >= columns.Size())
return;
columns.RemoveAtIndex(columnIndex);
// Remove this index from each row.
int i;
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur = rows.GetListHead();
while (cur)
{
for (i=0; i < cur->size; i++)
{
RakNet::OP_DELETE(cur->data[i]->cells[columnIndex], _FILE_AND_LINE_);
cur->data[i]->cells.RemoveAtIndex(columnIndex);
}
cur=cur->next;
}
}
unsigned Table::ColumnIndex(const char *columnName) const
{
unsigned columnIndex;
for (columnIndex=0; columnIndex<columns.Size(); columnIndex++)
if (strcmp(columnName, columns[columnIndex].columnName)==0)
return columnIndex;
return (unsigned)-1;
}
unsigned Table::ColumnIndex(char columnName[_TABLE_MAX_COLUMN_NAME_LENGTH]) const
{
return ColumnIndex((const char *) columnName);
}
char* Table::ColumnName(unsigned index) const
{
if (index >= columns.Size())
return 0;
else
return (char*)columns[index].columnName;
}
Table::ColumnType Table::GetColumnType(unsigned index) const
{
if (index >= columns.Size())
return (Table::ColumnType) 0;
else
return columns[index].columnType;
}
unsigned Table::GetColumnCount(void) const
{
return columns.Size();
}
unsigned Table::GetRowCount(void) const
{
return rows.Size();
}
Table::Row* Table::AddRow(unsigned rowId)
{
Row *newRow;
newRow = RakNet::OP_NEW<Row>( _FILE_AND_LINE_ );
if (rows.Insert(rowId, newRow)==false)
{
RakNet::OP_DELETE(newRow, _FILE_AND_LINE_);
return 0; // Already exists
}
unsigned rowIndex;
for (rowIndex=0; rowIndex < columns.Size(); rowIndex++)
newRow->cells.Insert( RakNet::OP_NEW<Table::Cell>(_FILE_AND_LINE_), _FILE_AND_LINE_ );
return newRow;
}
Table::Row* Table::AddRow(unsigned rowId, DataStructures::List<Cell> &initialCellValues)
{
Row *newRow = RakNet::OP_NEW<Row>( _FILE_AND_LINE_ );
unsigned rowIndex;
for (rowIndex=0; rowIndex < columns.Size(); rowIndex++)
{
if (rowIndex < initialCellValues.Size() && initialCellValues[rowIndex].isEmpty==false)
{
Table::Cell *c;
c = RakNet::OP_NEW<Table::Cell>(_FILE_AND_LINE_);
c->SetByType(initialCellValues[rowIndex].i,initialCellValues[rowIndex].c,initialCellValues[rowIndex].ptr,columns[rowIndex].columnType);
newRow->cells.Insert(c, _FILE_AND_LINE_ );
}
else
newRow->cells.Insert(RakNet::OP_NEW<Table::Cell>(_FILE_AND_LINE_), _FILE_AND_LINE_ );
}
rows.Insert(rowId, newRow);
return newRow;
}
Table::Row* Table::AddRow(unsigned rowId, DataStructures::List<Cell*> &initialCellValues, bool copyCells)
{
Row *newRow = RakNet::OP_NEW<Row>( _FILE_AND_LINE_ );
unsigned rowIndex;
for (rowIndex=0; rowIndex < columns.Size(); rowIndex++)
{
if (rowIndex < initialCellValues.Size() && initialCellValues[rowIndex] && initialCellValues[rowIndex]->isEmpty==false)
{
if (copyCells==false)
newRow->cells.Insert(RakNet::OP_NEW_4<Table::Cell>( _FILE_AND_LINE_, initialCellValues[rowIndex]->i, initialCellValues[rowIndex]->c, initialCellValues[rowIndex]->ptr, columns[rowIndex].columnType), _FILE_AND_LINE_);
else
{
Table::Cell *c = RakNet::OP_NEW<Table::Cell>( _FILE_AND_LINE_ );
newRow->cells.Insert(c, _FILE_AND_LINE_);
*c=*(initialCellValues[rowIndex]);
}
}
else
newRow->cells.Insert(RakNet::OP_NEW<Table::Cell>(_FILE_AND_LINE_), _FILE_AND_LINE_);
}
rows.Insert(rowId, newRow);
return newRow;
}
Table::Row* Table::AddRowColumns(unsigned rowId, Row *row, DataStructures::List<unsigned> columnIndices)
{
Row *newRow = RakNet::OP_NEW<Row>( _FILE_AND_LINE_ );
unsigned columnIndex;
for (columnIndex=0; columnIndex < columnIndices.Size(); columnIndex++)
{
if (row->cells[columnIndices[columnIndex]]->isEmpty==false)
{
newRow->cells.Insert(RakNet::OP_NEW_4<Table::Cell>( _FILE_AND_LINE_,
row->cells[columnIndices[columnIndex]]->i,
row->cells[columnIndices[columnIndex]]->c,
row->cells[columnIndices[columnIndex]]->ptr,
columns[columnIndex].columnType
), _FILE_AND_LINE_);
}
else
{
newRow->cells.Insert(RakNet::OP_NEW<Table::Cell>(_FILE_AND_LINE_), _FILE_AND_LINE_);
}
}
rows.Insert(rowId, newRow);
return newRow;
}
bool Table::RemoveRow(unsigned rowId)
{
Row *out;
if (rows.Delete(rowId, out))
{
DeleteRow(out);
return true;
}
return false;
}
void Table::RemoveRows(Table *tableContainingRowIDs)
{
unsigned i;
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur = tableContainingRowIDs->GetRows().GetListHead();
while (cur)
{
for (i=0; i < (unsigned)cur->size; i++)
{
rows.Delete(cur->keys[i]);
}
cur=cur->next;
}
return;
}
bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, int value)
{
RakAssert(columns[columnIndex].columnType==NUMERIC);
Row *row = GetRowByID(rowId);
if (row)
{
row->UpdateCell(columnIndex, value);
return true;
}
return false;
}
bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, char *str)
{
RakAssert(columns[columnIndex].columnType==STRING);
Row *row = GetRowByID(rowId);
if (row)
{
row->UpdateCell(columnIndex, str);
return true;
}
return false;
}
bool Table::UpdateCell(unsigned rowId, unsigned columnIndex, int byteLength, char *data)
{
RakAssert(columns[columnIndex].columnType==BINARY);
Row *row = GetRowByID(rowId);
if (row)
{
row->UpdateCell(columnIndex, byteLength, data);
return true;
}
return false;
}
bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int value)
{
RakAssert(columns[columnIndex].columnType==NUMERIC);
Row *row = GetRowByIndex(rowIndex,0);
if (row)
{
row->UpdateCell(columnIndex, value);
return true;
}
return false;
}
bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, char *str)
{
RakAssert(columns[columnIndex].columnType==STRING);
Row *row = GetRowByIndex(rowIndex,0);
if (row)
{
row->UpdateCell(columnIndex, str);
return true;
}
return false;
}
bool Table::UpdateCellByIndex(unsigned rowIndex, unsigned columnIndex, int byteLength, char *data)
{
RakAssert(columns[columnIndex].columnType==BINARY);
Row *row = GetRowByIndex(rowIndex,0);
if (row)
{
row->UpdateCell(columnIndex, byteLength, data);
return true;
}
return false;
}
void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, int *output)
{
RakAssert(columns[columnIndex].columnType==NUMERIC);
Row *row = GetRowByIndex(rowIndex,0);
if (row)
{
row->cells[columnIndex]->Get(output);
}
}
void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output)
{
RakAssert(columns[columnIndex].columnType==STRING);
Row *row = GetRowByIndex(rowIndex,0);
if (row)
{
row->cells[columnIndex]->Get(output);
}
}
void Table::GetCellValueByIndex(unsigned rowIndex, unsigned columnIndex, char *output, int *outputLength)
{
RakAssert(columns[columnIndex].columnType==BINARY);
Row *row = GetRowByIndex(rowIndex,0);
if (row)
{
row->cells[columnIndex]->Get(output, outputLength);
}
}
Table::FilterQuery::FilterQuery()
{
columnName[0]=0;
}
Table::FilterQuery::~FilterQuery()
{
}
Table::FilterQuery::FilterQuery(unsigned column, Cell *cell, FilterQueryType op)
{
columnIndex=column;
cellValue=cell;
operation=op;
}
Table::Row* Table::GetRowByID(unsigned rowId) const
{
Row *row;
if (rows.Get(rowId, row))
return row;
return 0;
}
Table::Row* Table::GetRowByIndex(unsigned rowIndex, unsigned *key) const
{
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur = rows.GetListHead();
while (cur)
{
if (rowIndex < (unsigned)cur->size)
{
if (key)
*key=cur->keys[rowIndex];
return cur->data[rowIndex];
}
if (rowIndex <= (unsigned)cur->size)
rowIndex-=cur->size;
else
return 0;
cur=cur->next;
}
return 0;
}
void Table::QueryTable(unsigned *columnIndicesSubset, unsigned numColumnSubset, FilterQuery *inclusionFilters, unsigned numInclusionFilters, unsigned *rowIds, unsigned numRowIDs, Table *result)
{
unsigned i;
DataStructures::List<unsigned> columnIndicesToReturn;
// Clear the result table.
result->Clear();
if (columnIndicesSubset && numColumnSubset>0)
{
for (i=0; i < numColumnSubset; i++)
{
if (columnIndicesSubset[i]<columns.Size())
columnIndicesToReturn.Insert(columnIndicesSubset[i], _FILE_AND_LINE_);
}
}
else
{
for (i=0; i < columns.Size(); i++)
columnIndicesToReturn.Insert(i, _FILE_AND_LINE_);
}
if (columnIndicesToReturn.Size()==0)
return; // No valid columns specified
for (i=0; i < columnIndicesToReturn.Size(); i++)
{
result->AddColumn(columns[columnIndicesToReturn[i]].columnName,columns[columnIndicesToReturn[i]].columnType);
}
// Get the column indices of the filter queries.
DataStructures::List<unsigned> inclusionFilterColumnIndices;
if (inclusionFilters && numInclusionFilters>0)
{
for (i=0; i < numInclusionFilters; i++)
{
if (inclusionFilters[i].columnName[0])
inclusionFilters[i].columnIndex=ColumnIndex(inclusionFilters[i].columnName);
if (inclusionFilters[i].columnIndex<columns.Size())
inclusionFilterColumnIndices.Insert(inclusionFilters[i].columnIndex, _FILE_AND_LINE_);
else
inclusionFilterColumnIndices.Insert((unsigned)-1, _FILE_AND_LINE_);
}
}
if (rowIds==0 || numRowIDs==0)
{
// All rows
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur = rows.GetListHead();
while (cur)
{
for (i=0; i < (unsigned)cur->size; i++)
{
QueryRow(inclusionFilterColumnIndices, columnIndicesToReturn, cur->keys[i], cur->data[i], inclusionFilters, result);
}
cur=cur->next;
}
}
else
{
// Specific rows
Row *row;
for (i=0; i < numRowIDs; i++)
{
if (rows.Get(rowIds[i], row))
{
QueryRow(inclusionFilterColumnIndices, columnIndicesToReturn, rowIds[i], row, inclusionFilters, result);
}
}
}
}
void Table::QueryRow(DataStructures::List<unsigned> &inclusionFilterColumnIndices, DataStructures::List<unsigned> &columnIndicesToReturn, unsigned key, Table::Row* row, FilterQuery *inclusionFilters, Table *result)
{
bool pass=false;
unsigned columnIndex;
unsigned j;
// If no inclusion filters, just add the row
if (inclusionFilterColumnIndices.Size()==0)
{
result->AddRowColumns(key, row, columnIndicesToReturn);
}
else
{
// Go through all inclusion filters. Only add this row if all filters pass.
for (j=0; j<inclusionFilterColumnIndices.Size(); j++)
{
columnIndex=inclusionFilterColumnIndices[j];
if (columnIndex!=(unsigned)-1 && row->cells[columnIndex]->isEmpty==false )
{
if (columns[inclusionFilterColumnIndices[j]].columnType==STRING &&
(row->cells[columnIndex]->c==0 ||
inclusionFilters[j].cellValue->c==0) )
continue;
switch (inclusionFilters[j].operation)
{
case QF_EQUAL:
switch(columns[inclusionFilterColumnIndices[j]].columnType)
{
case NUMERIC:
pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i;
break;
case STRING:
pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)==0;
break;
case BINARY:
pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i &&
memcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c, (int) row->cells[columnIndex]->i)==0;
break;
case POINTER:
pass=row->cells[columnIndex]->ptr==inclusionFilters[j].cellValue->ptr;
break;
}
break;
case QF_NOT_EQUAL:
switch(columns[inclusionFilterColumnIndices[j]].columnType)
{
case NUMERIC:
pass=row->cells[columnIndex]->i!=inclusionFilters[j].cellValue->i;
break;
case STRING:
pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)!=0;
break;
case BINARY:
pass=row->cells[columnIndex]->i==inclusionFilters[j].cellValue->i &&
memcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c, (int) row->cells[columnIndex]->i)==0;
break;
case POINTER:
pass=row->cells[columnIndex]->ptr!=inclusionFilters[j].cellValue->ptr;
break;
}
break;
case QF_GREATER_THAN:
switch(columns[inclusionFilterColumnIndices[j]].columnType)
{
case NUMERIC:
pass=row->cells[columnIndex]->i>inclusionFilters[j].cellValue->i;
break;
case STRING:
pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)>0;
break;
case BINARY:
break;
case POINTER:
pass=row->cells[columnIndex]->ptr>inclusionFilters[j].cellValue->ptr;
break;
}
break;
case QF_GREATER_THAN_EQ:
switch(columns[inclusionFilterColumnIndices[j]].columnType)
{
case NUMERIC:
pass=row->cells[columnIndex]->i>=inclusionFilters[j].cellValue->i;
break;
case STRING:
pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)>=0;
break;
case BINARY:
break;
case POINTER:
pass=row->cells[columnIndex]->ptr>=inclusionFilters[j].cellValue->ptr;
break;
}
break;
case QF_LESS_THAN:
switch(columns[inclusionFilterColumnIndices[j]].columnType)
{
case NUMERIC:
pass=row->cells[columnIndex]->i<inclusionFilters[j].cellValue->i;
break;
case STRING:
pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)<0;
break;
case BINARY:
break;
case POINTER:
pass=row->cells[columnIndex]->ptr<inclusionFilters[j].cellValue->ptr;
break;
}
break;
case QF_LESS_THAN_EQ:
switch(columns[inclusionFilterColumnIndices[j]].columnType)
{
case NUMERIC:
pass=row->cells[columnIndex]->i<=inclusionFilters[j].cellValue->i;
break;
case STRING:
pass=strcmp(row->cells[columnIndex]->c,inclusionFilters[j].cellValue->c)<=0;
break;
case BINARY:
break;
case POINTER:
pass=row->cells[columnIndex]->ptr<=inclusionFilters[j].cellValue->ptr;
break;
}
break;
case QF_IS_EMPTY:
pass=false;
break;
case QF_NOT_EMPTY:
pass=true;
break;
default:
pass=false;
RakAssert(0);
break;
}
}
else
{
if (inclusionFilters[j].operation==QF_IS_EMPTY)
pass=true;
else
pass=false; // No value for this cell
}
if (pass==false)
break;
}
if (pass)
{
result->AddRowColumns(key, row, columnIndicesToReturn);
}
}
}
static Table::SortQuery *_sortQueries;
static unsigned _numSortQueries;
static DataStructures::List<unsigned> *_columnIndices;
static DataStructures::List<Table::ColumnDescriptor> *_columns;
int RowSort(Table::Row* const &first, Table::Row* const &second) // first is the one inserting, second is the one already there.
{
unsigned i, columnIndex;
for (i=0; i<_numSortQueries; i++)
{
columnIndex=(*_columnIndices)[i];
if (columnIndex==(unsigned)-1)
continue;
if (first->cells[columnIndex]->isEmpty==true && second->cells[columnIndex]->isEmpty==false)
return 1; // Empty cells always go at the end
if (first->cells[columnIndex]->isEmpty==false && second->cells[columnIndex]->isEmpty==true)
return -1; // Empty cells always go at the end
if (_sortQueries[i].operation==Table::QS_INCREASING_ORDER)
{
if ((*_columns)[columnIndex].columnType==Table::NUMERIC)
{
if (first->cells[columnIndex]->i>second->cells[columnIndex]->i)
return 1;
if (first->cells[columnIndex]->i<second->cells[columnIndex]->i)
return -1;
}
else
{
// String
if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)>0)
return 1;
if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)<0)
return -1;
}
}
else
{
if ((*_columns)[columnIndex].columnType==Table::NUMERIC)
{
if (first->cells[columnIndex]->i<second->cells[columnIndex]->i)
return 1;
if (first->cells[columnIndex]->i>second->cells[columnIndex]->i)
return -1;
}
else
{
// String
if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)<0)
return 1;
if (strcmp(first->cells[columnIndex]->c,second->cells[columnIndex]->c)>0)
return -1;
}
}
}
return 0;
}
void Table::SortTable(Table::SortQuery *sortQueries, unsigned numSortQueries, Table::Row** out)
{
unsigned i;
unsigned outLength;
DataStructures::List<unsigned> columnIndices;
_sortQueries=sortQueries;
_numSortQueries=numSortQueries;
_columnIndices=&columnIndices;
_columns=&columns;
bool anyValid=false;
for (i=0; i < numSortQueries; i++)
{
if (sortQueries[i].columnIndex<columns.Size() && columns[sortQueries[i].columnIndex].columnType!=BINARY)
{
columnIndices.Insert(sortQueries[i].columnIndex, _FILE_AND_LINE_);
anyValid=true;
}
else
columnIndices.Insert((unsigned)-1, _FILE_AND_LINE_); // Means don't check this column
}
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur;
cur = rows.GetListHead();
if (anyValid==false)
{
outLength=0;
while (cur)
{
for (i=0; i < (unsigned)cur->size; i++)
{
out[(outLength)++]=cur->data[i];
}
cur=cur->next;
}
return;
}
// Start adding to ordered list.
DataStructures::OrderedList<Row*, Row*, RowSort> orderedList;
while (cur)
{
for (i=0; i < (unsigned)cur->size; i++)
{
RakAssert(cur->data[i]);
orderedList.Insert(cur->data[i],cur->data[i], true, _FILE_AND_LINE_);
}
cur=cur->next;
}
outLength=0;
for (i=0; i < orderedList.Size(); i++)
out[(outLength)++]=orderedList[i];
}
void Table::PrintColumnHeaders(char *out, int outLength, char columnDelineator) const
{
if (outLength<=0)
return;
if (outLength==1)
{
*out=0;
return;
}
unsigned i;
out[0]=0;
int len;
for (i=0; i < columns.Size(); i++)
{
if (i!=0)
{
len = (int) strlen(out);
if (len < outLength-1)
sprintf(out+len, "%c", columnDelineator);
else
return;
}
len = (int) strlen(out);
if (len < outLength-(int) strlen(columns[i].columnName))
sprintf(out+len, "%s", columns[i].columnName);
else
return;
}
}
void Table::PrintRow(char *out, int outLength, char columnDelineator, bool printDelineatorForBinary, Table::Row* inputRow) const
{
if (outLength<=0)
return;
if (outLength==1)
{
*out=0;
return;
}
if (inputRow->cells.Size()!=columns.Size())
{
strncpy(out, "Cell width does not match column width.\n", outLength);
out[outLength-1]=0;
return;
}
char buff[512];
unsigned i;
int len;
out[0]=0;
for (i=0; i < columns.Size(); i++)
{
if (columns[i].columnType==NUMERIC)
{
if (inputRow->cells[i]->isEmpty==false)
{
sprintf(buff, "%f", inputRow->cells[i]->i);
len=(int)strlen(buff);
}
else
len=0;
if (i+1!=columns.Size())
buff[len++]=columnDelineator;
buff[len]=0;
}
else if (columns[i].columnType==STRING)
{
if (inputRow->cells[i]->isEmpty==false && inputRow->cells[i]->c)
{
strncpy(buff, inputRow->cells[i]->c, 512-2);
buff[512-2]=0;
len=(int)strlen(buff);
}
else
len=0;
if (i+1!=columns.Size())
buff[len++]=columnDelineator;
buff[len]=0;
}
else if (columns[i].columnType==POINTER)
{
if (inputRow->cells[i]->isEmpty==false && inputRow->cells[i]->ptr)
{
sprintf(buff, "%p", inputRow->cells[i]->ptr);
len=(int)strlen(buff);
}
else
len=0;
if (i+1!=columns.Size())
buff[len++]=columnDelineator;
buff[len]=0;
}
else
{
if (printDelineatorForBinary)
{
if (i+1!=columns.Size())
buff[0]=columnDelineator;
buff[1]=0;
}
else
buff[0]=0;
}
len=(int)strlen(out);
if (outLength==len+1)
break;
strncpy(out+len, buff, outLength-len);
out[outLength-1]=0;
}
}
void Table::Clear(void)
{
rows.ForEachData(FreeRow);
rows.Clear();
columns.Clear(true, _FILE_AND_LINE_);
}
const List<Table::ColumnDescriptor>& Table::GetColumns(void) const
{
return columns;
}
const DataStructures::BPlusTree<unsigned, Table::Row*, _TABLE_BPLUS_TREE_ORDER>& Table::GetRows(void) const
{
return rows;
}
DataStructures::Page<unsigned, DataStructures::Table::Row*, _TABLE_BPLUS_TREE_ORDER> * Table::GetListHead(void)
{
return rows.GetListHead();
}
unsigned Table::GetAvailableRowId(void) const
{
bool setKey=false;
unsigned key=0;
int i;
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur = rows.GetListHead();
while (cur)
{
for (i=0; i < cur->size; i++)
{
if (setKey==false)
{
key=cur->keys[i]+1;
setKey=true;
}
else
{
if (key!=cur->keys[i])
return key;
key++;
}
}
cur=cur->next;
}
return key;
}
void Table::DeleteRow(Table::Row *row)
{
unsigned rowIndex;
for (rowIndex=0; rowIndex < row->cells.Size(); rowIndex++)
{
RakNet::OP_DELETE(row->cells[rowIndex], _FILE_AND_LINE_);
}
RakNet::OP_DELETE(row, _FILE_AND_LINE_);
}
Table& Table::operator = ( const Table& input )
{
Clear();
unsigned int i;
for (i=0; i < input.GetColumnCount(); i++)
AddColumn(input.ColumnName(i), input.GetColumnType(i));
DataStructures::Page<unsigned, Row*, _TABLE_BPLUS_TREE_ORDER> *cur = input.GetRows().GetListHead();
while (cur)
{
for (i=0; i < (unsigned int) cur->size; i++)
{
AddRow(cur->keys[i], cur->data[i]->cells, false);
}
cur=cur->next;
}
return *this;
}
#ifdef _MSC_VER
#pragma warning( pop )
#endif
| gpl-3.0 |
videogamepreservation/enemyterritory | src/bspc/tree.c | 6 | 8639 | /*
===========================================================================
Wolfenstein: Enemy Territory GPL Source Code
Copyright (C) 1999-2010 id Software LLC, a ZeniMax Media company.
This file is part of the Wolfenstein: Enemy Territory GPL Source Code (Wolf ET Source Code).
Wolf ET Source Code is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Wolf ET Source Code is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Wolf ET Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Wolf: ET Source Code is also subject to certain additional terms. You should have received a copy of these additional terms immediately following the terms and conditions of the GNU General Public License which accompanied the Wolf ET Source Code. If not, please request a copy in writing from id Software at the address below.
If you have questions concerning this license or the applicable additional terms, you may contact in writing id Software LLC, c/o ZeniMax Media Inc., Suite 120, Rockville, Maryland 20850 USA.
===========================================================================
*/
//===========================================================================
//
// Name: textures.c
// Function: textures
// Programmer: Mr Elusive (MrElusive@worldentity.com)
// Last update: 1999-08-10
// Tab Size: 3
//===========================================================================
#include "qbsp.h"
extern int c_nodes;
int c_pruned;
int freedtreemem = 0;
void RemovePortalFromNode( portal_t *portal, node_t *l );
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
node_t *NodeForPoint( node_t *node, vec3_t origin ) {
plane_t *plane;
vec_t d;
while ( node->planenum != PLANENUM_LEAF )
{
plane = &mapplanes[node->planenum];
d = DotProduct( origin, plane->normal ) - plane->dist;
if ( d >= 0 ) {
node = node->children[0];
} else {
node = node->children[1];
}
}
return node;
} //end of the function NodeForPoint
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Tree_FreePortals_r( node_t *node ) {
portal_t *p, *nextp;
int s;
// free children
if ( node->planenum != PLANENUM_LEAF ) {
Tree_FreePortals_r( node->children[0] );
Tree_FreePortals_r( node->children[1] );
}
// free portals
for ( p = node->portals; p; p = nextp )
{
s = ( p->nodes[1] == node );
nextp = p->next[s];
RemovePortalFromNode( p, p->nodes[!s] );
#ifdef ME
if ( p->winding ) {
freedtreemem += MemorySize( p->winding );
}
freedtreemem += MemorySize( p );
#endif //ME
FreePortal( p );
}
node->portals = NULL;
} //end of the function Tree_FreePortals_r
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Tree_Free_r( node_t *node ) {
// face_t *f, *nextf;
bspbrush_t *brush, *nextbrush;
//free children
if ( node->planenum != PLANENUM_LEAF ) {
Tree_Free_r( node->children[0] );
Tree_Free_r( node->children[1] );
} //end if
//free bspbrushes
// FreeBrushList (node->brushlist);
for ( brush = node->brushlist; brush; brush = nextbrush )
{
nextbrush = brush->next;
#ifdef ME
freedtreemem += MemorySize( brush );
#endif //ME
FreeBrush( brush );
} //end for
node->brushlist = NULL;
/*
NOTE: only used when creating Q2 bsp
// free faces
for (f = node->faces; f; f = nextf)
{
nextf = f->next;
#ifdef ME
if (f->w) freedtreemem += MemorySize(f->w);
freedtreemem += sizeof(face_t);
#endif //ME
FreeFace(f);
} //end for
*/
// free the node
if ( node->volume ) {
#ifdef ME
freedtreemem += MemorySize( node->volume );
#endif //ME
FreeBrush( node->volume );
} //end if
if ( numthreads == 1 ) {
c_nodes--;
}
#ifdef ME
freedtreemem += MemorySize( node );
#endif //ME
FreeMemory( node );
} //end of the function Tree_Free_r
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Tree_Free( tree_t *tree ) {
//if no tree just return
if ( !tree ) {
return;
}
//
freedtreemem = 0;
//
Tree_FreePortals_r( tree->headnode );
Tree_Free_r( tree->headnode );
#ifdef ME
freedtreemem += MemorySize( tree );
#endif //ME
FreeMemory( tree );
#ifdef ME
Log_Print( "freed " );
PrintMemorySize( freedtreemem );
Log_Print( " of tree memory\n" );
#endif //ME
} //end of the function Tree_Free
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
tree_t *Tree_Alloc( void ) {
tree_t *tree;
tree = GetMemory( sizeof( *tree ) );
memset( tree, 0, sizeof( *tree ) );
ClearBounds( tree->mins, tree->maxs );
return tree;
} //end of the function Tree_Alloc
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Tree_Print_r( node_t *node, int depth ) {
int i;
plane_t *plane;
bspbrush_t *bb;
for ( i = 0 ; i < depth ; i++ )
printf( " " );
if ( node->planenum == PLANENUM_LEAF ) {
if ( !node->brushlist ) {
printf( "NULL\n" );
} else
{
for ( bb = node->brushlist ; bb ; bb = bb->next )
printf( "%i ", bb->original->brushnum );
printf( "\n" );
}
return;
}
plane = &mapplanes[node->planenum];
printf( "#%i (%5.2f %5.2f %5.2f):%5.2f\n", node->planenum,
plane->normal[0], plane->normal[1], plane->normal[2],
plane->dist );
Tree_Print_r( node->children[0], depth + 1 );
Tree_Print_r( node->children[1], depth + 1 );
} //end of the function Tree_Print_r
//===========================================================================
// NODES THAT DON'T SEPERATE DIFFERENT CONTENTS CAN BE PRUNED
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Tree_PruneNodes_r( node_t *node ) {
bspbrush_t *b, *next;
if ( node->planenum == PLANENUM_LEAF ) {
return;
}
Tree_PruneNodes_r( node->children[0] );
Tree_PruneNodes_r( node->children[1] );
if ( create_aas ) {
if ( ( node->children[0]->contents & CONTENTS_LADDER ) ||
( node->children[1]->contents & CONTENTS_LADDER ) ) {
return;
}
}
if ( ( node->children[0]->contents & CONTENTS_SOLID )
&& ( node->children[1]->contents & CONTENTS_SOLID ) ) {
if ( node->faces ) {
Error( "node->faces seperating CONTENTS_SOLID" );
}
if ( node->children[0]->faces || node->children[1]->faces ) {
Error( "!node->faces with children" );
}
// FIXME: free stuff
node->planenum = PLANENUM_LEAF;
node->contents = CONTENTS_SOLID;
node->detail_seperator = false;
if ( node->brushlist ) {
Error( "PruneNodes: node->brushlist" );
}
// combine brush lists
node->brushlist = node->children[1]->brushlist;
for ( b = node->children[0]->brushlist; b; b = next )
{
next = b->next;
b->next = node->brushlist;
node->brushlist = b;
} //end for
//free the child nodes
FreeMemory( node->children[0] );
FreeMemory( node->children[1] );
//two nodes are cut away
c_pruned += 2;
} //end if
} //end of the function Tree_PruneNodes_r
//===========================================================================
//
// Parameter: -
// Returns: -
// Changes Globals: -
//===========================================================================
void Tree_PruneNodes( node_t *node ) {
Log_Print( "------- Prune Nodes --------\n" );
c_pruned = 0;
Tree_PruneNodes_r( node );
Log_Print( "%5i pruned nodes\n", c_pruned );
} //end of the function Tree_PruneNodes
| gpl-3.0 |
chrisdroid/nexmon | utilities/mdk3/src/linkedlist.c | 6 | 6260 | #include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include "linkedlist.h"
pthread_mutex_t clist_mutex = PTHREAD_MUTEX_INITIALIZER;
struct clist *search_status(struct clist *c, int desired_status)
{
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clist *first = c;
do {
if (c->status == desired_status) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clistwidsclient *search_status_widsclient(struct clistwidsclient *c, int desired_status, int desired_channel)
{
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clistwidsclient *first = c;
do {
if ((c->status == desired_status) && ((c->bssid->channel == desired_channel) || (desired_channel = -1))) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clist *search_data(struct clist *c, unsigned char *desired_data, int data_len)
{
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clist *first = c;
do {
if (data_len <= c->data_len) {
if (! (memcmp(c->data, desired_data, data_len))) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clistwidsap *search_bssid(struct clistwidsap *c, struct ether_addr desired_bssid)
{
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clistwidsap *first = c;
do {
if (MAC_MATCHES(c->bssid, desired_bssid)) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clistwidsclient *search_client(struct clistwidsclient *c, struct ether_addr mac)
{
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clistwidsclient *first = c;
do {
if (MAC_MATCHES(c->mac, mac)) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clistauthdos *search_ap(struct clistauthdos *c, struct ether_addr ap)
{
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clistauthdos *first = c;
do {
if (MAC_MATCHES(c->ap, ap)) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clist *add_to_clist(struct clist *c, unsigned char *data, int status, int data_len)
{
pthread_mutex_lock(&clist_mutex);
struct clist *new_item = (struct clist *) malloc(sizeof(struct clist));
new_item->data = malloc(data_len);
new_item->data_len = data_len;
if (c) {
new_item->next = c->next;
c->next = new_item;
} else {
new_item->next = new_item;
}
memcpy(new_item->data, data, data_len);
new_item->status = status;
pthread_mutex_unlock(&clist_mutex);
return new_item;
}
struct clistwidsap *add_to_clistwidsap(struct clistwidsap *c, struct ether_addr bssid, int channel, uint16_t capa, char *ssid)
{
pthread_mutex_lock(&clist_mutex);
struct clistwidsap *new_item = (struct clistwidsap *) malloc(sizeof(struct clistwidsap));
new_item->bssid = bssid;
if (c) {
new_item->next = c->next;
c->next = new_item;
} else {
new_item->next = new_item;
}
new_item->channel = channel;
new_item->capa = capa;
new_item->ssid = malloc(strlen(ssid) + 1);
strcpy(new_item->ssid, ssid);
pthread_mutex_unlock(&clist_mutex);
return new_item;
}
struct clistwidsclient *add_to_clistwidsclient(struct clistwidsclient *c, struct ether_addr mac, int status, unsigned char *data, int data_len, uint16_t sequence, struct clistwidsap *bssid)
{
pthread_mutex_lock(&clist_mutex);
struct clistwidsclient *new_item = (struct clistwidsclient *) malloc(sizeof(struct clistwidsclient));
new_item->mac = mac;
new_item->data = malloc(data_len);
if (c) {
new_item->next = c->next;
c->next = new_item;
} else {
new_item->next = new_item;
}
memcpy(new_item->data, data, data_len);
new_item->status = status;
new_item->data_len = data_len;
new_item->bssid = bssid;
new_item->retries = 0;
new_item->seq = sequence;
pthread_mutex_unlock(&clist_mutex);
return new_item;
}
struct clistauthdos *add_to_clistauthdos(struct clistauthdos *c, struct ether_addr ap, unsigned char status, unsigned int responses, unsigned int missing)
{
pthread_mutex_lock(&clist_mutex);
struct clistauthdos *new_item = (struct clistauthdos *) malloc(sizeof(struct clistauthdos));
new_item->ap = ap;
if (c) {
new_item->next = c->next;
c->next = new_item;
} else {
new_item->next = new_item;
}
new_item->status = status;
new_item->responses = responses;
new_item->missing = missing;
pthread_mutex_unlock(&clist_mutex);
return new_item;
}
struct clistauthdos *search_authdos_status(struct clistauthdos *c, int desired_status) {
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clistauthdos *first = c;
do {
if (c->status == desired_status) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clistwidsap *search_bssid_on_channel(struct clistwidsap *c, int desired_channel) {
if (!c) return NULL;
pthread_mutex_lock(&clist_mutex);
struct clistwidsap *first = c;
do {
if (desired_channel == c->channel) {
pthread_mutex_unlock(&clist_mutex);
return c;
}
c = c->next;
} while (c != first);
pthread_mutex_unlock(&clist_mutex);
return NULL;
}
struct clistwidsap *shuffle_widsaps(struct clistwidsap *c) {
int i, rnd = random() % SHUFFLE_DISTANCE;
struct clistwidsap *r = c;
for(i=0; i<rnd; i++) r = r->next;
return r;
}
struct clistwidsclient *shuffle_widsclients(struct clistwidsclient *c) {
int i, rnd = random() % SHUFFLE_DISTANCE;
struct clistwidsclient *r = c;
for(i=0; i<rnd; i++) r = r->next;
return r;
}
| gpl-3.0 |
Serabass/vice-players | Vendor/CEGUI/cegui/src/WindowRendererSets/Falagard/FalEditboxProperties.cpp | 7 | 3269 | /***********************************************************************
filename: FalEditboxProperties.cpp
created: Wed Jul 29 2009
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2009 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "FalEditboxProperties.h"
#include "FalEditbox.h"
#include "CEGUIPropertyHelper.h"
// Start of CEGUI namespace section
namespace CEGUI
{
namespace FalagardEditboxProperties
{
//----------------------------------------------------------------------------//
String BlinkCaret::get(const PropertyReceiver* receiver) const
{
FalagardEditbox* wr = static_cast<FalagardEditbox*>(
static_cast<const Window*>(receiver)->getWindowRenderer());
return PropertyHelper::boolToString(wr->isCaretBlinkEnabled());
}
//----------------------------------------------------------------------------//
void BlinkCaret::set(PropertyReceiver* receiver, const String& value)
{
FalagardEditbox* wr = static_cast<FalagardEditbox*>(
static_cast<const Window*>(receiver)->getWindowRenderer());
wr->setCaretBlinkEnabled(PropertyHelper::stringToBool(value));
}
//----------------------------------------------------------------------------//
String BlinkCaretTimeout::get(const PropertyReceiver* receiver) const
{
FalagardEditbox* wr = static_cast<FalagardEditbox*>(
static_cast<const Window*>(receiver)->getWindowRenderer());
return PropertyHelper::floatToString(wr->getCaretBlinkTimeout());
}
//----------------------------------------------------------------------------//
void BlinkCaretTimeout::set(PropertyReceiver* receiver, const String& value)
{
FalagardEditbox* wr = static_cast<FalagardEditbox*>(
static_cast<const Window*>(receiver)->getWindowRenderer());
wr->setCaretBlinkTimeout(PropertyHelper::stringToFloat(value));
}
} // End of FalagardEditboxProperties namespace section
} // End of CEGUI namespace section
| gpl-3.0 |
piksels-and-lines-orchestra/gimp | app/core/gimplayerpropundo.c | 7 | 3857 | /* Gimp - The GNU Image Manipulation Program
* Copyright (C) 1995 Spencer Kimball and Peter Mattis
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "config.h"
#include <gegl.h>
#include "libgimpbase/gimpbase.h"
#include "core-types.h"
#include "gimpimage.h"
#include "gimplayer.h"
#include "gimplayerpropundo.h"
static void gimp_layer_prop_undo_constructed (GObject *object);
static void gimp_layer_prop_undo_pop (GimpUndo *undo,
GimpUndoMode undo_mode,
GimpUndoAccumulator *accum);
G_DEFINE_TYPE (GimpLayerPropUndo, gimp_layer_prop_undo, GIMP_TYPE_ITEM_UNDO)
#define parent_class gimp_layer_prop_undo_parent_class
static void
gimp_layer_prop_undo_class_init (GimpLayerPropUndoClass *klass)
{
GObjectClass *object_class = G_OBJECT_CLASS (klass);
GimpUndoClass *undo_class = GIMP_UNDO_CLASS (klass);
object_class->constructed = gimp_layer_prop_undo_constructed;
undo_class->pop = gimp_layer_prop_undo_pop;
}
static void
gimp_layer_prop_undo_init (GimpLayerPropUndo *undo)
{
}
static void
gimp_layer_prop_undo_constructed (GObject *object)
{
GimpLayerPropUndo *layer_prop_undo = GIMP_LAYER_PROP_UNDO (object);
GimpLayer *layer;
if (G_OBJECT_CLASS (parent_class)->constructed)
G_OBJECT_CLASS (parent_class)->constructed (object);
g_assert (GIMP_IS_LAYER (GIMP_ITEM_UNDO (object)->item));
layer = GIMP_LAYER (GIMP_ITEM_UNDO (object)->item);
switch (GIMP_UNDO (object)->undo_type)
{
case GIMP_UNDO_LAYER_MODE:
layer_prop_undo->mode = gimp_layer_get_mode (layer);
break;
case GIMP_UNDO_LAYER_OPACITY:
layer_prop_undo->opacity = gimp_layer_get_opacity (layer);
break;
case GIMP_UNDO_LAYER_LOCK_ALPHA:
layer_prop_undo->lock_alpha = gimp_layer_get_lock_alpha (layer);
break;
default:
g_assert_not_reached ();
}
}
static void
gimp_layer_prop_undo_pop (GimpUndo *undo,
GimpUndoMode undo_mode,
GimpUndoAccumulator *accum)
{
GimpLayerPropUndo *layer_prop_undo = GIMP_LAYER_PROP_UNDO (undo);
GimpLayer *layer = GIMP_LAYER (GIMP_ITEM_UNDO (undo)->item);
GIMP_UNDO_CLASS (parent_class)->pop (undo, undo_mode, accum);
switch (undo->undo_type)
{
case GIMP_UNDO_LAYER_MODE:
{
GimpLayerModeEffects mode;
mode = gimp_layer_get_mode (layer);
gimp_layer_set_mode (layer, layer_prop_undo->mode, FALSE);
layer_prop_undo->mode = mode;
}
break;
case GIMP_UNDO_LAYER_OPACITY:
{
gdouble opacity;
opacity = gimp_layer_get_opacity (layer);
gimp_layer_set_opacity (layer, layer_prop_undo->opacity, FALSE);
layer_prop_undo->opacity = opacity;
}
break;
case GIMP_UNDO_LAYER_LOCK_ALPHA:
{
gboolean lock_alpha;
lock_alpha = gimp_layer_get_lock_alpha (layer);
gimp_layer_set_lock_alpha (layer, layer_prop_undo->lock_alpha, FALSE);
layer_prop_undo->lock_alpha = lock_alpha;
}
break;
default:
g_assert_not_reached ();
}
}
| gpl-3.0 |
ChloeG/artoolkit5 | lib/SRC/KPM/FreakMatcher/detectors/gaussian_scale_space_pyramid.cpp | 8 | 14755 | //
// gaussian_scale_space_pyramid.cpp
// ARToolKit5
//
// This file is part of ARToolKit.
//
// ARToolKit is free software: you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// ARToolKit 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 ARToolKit. If not, see <http://www.gnu.org/licenses/>.
//
// 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 neither derived from nor 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.
//
// Copyright 2013-2015 Daqri, LLC.
//
// Author(s): Chris Broaddus
//
#include "gaussian_scale_space_pyramid.h"
#include <framework/error.h>
//#include <framework/logger.h>
using namespace vision;
namespace vision {
void binomial_4th_order(float* dst,
unsigned short* tmp,
const unsigned char* src,
size_t width,
size_t height) {
unsigned short* tmp_ptr;
float* dst_ptr;
size_t width_minus_1, width_minus_2;
size_t height_minus_2;
ASSERT(width >= 5, "Image is too small");
ASSERT(height >= 5, "Image is too small");
width_minus_1 = width-1;
width_minus_2 = width-2;
height_minus_2 = height-2;
tmp_ptr = tmp;
// Apply horizontal filter
for(size_t row = 0; row < height; row++) {
const unsigned char* src_ptr = &src[row*width];
// Left border is computed by extending the border pixel beyond the image
*(tmp_ptr++) = ((src_ptr[0]<<1)+(src_ptr[0]<<2)) + ((src_ptr[0]+src_ptr[1])<<2) + (src_ptr[0]+src_ptr[2]);
*(tmp_ptr++) = ((src_ptr[1]<<1)+(src_ptr[1]<<2)) + ((src_ptr[0]+src_ptr[2])<<2) + (src_ptr[0]+src_ptr[3]);
// Compute non-border pixels
for(size_t col = 2; col < width_minus_2; col++, tmp_ptr++) {
*tmp_ptr = ((src_ptr[col]<<1)+(src_ptr[col]<<2)) + ((src_ptr[col-1]+src_ptr[col+1])<<2) + (src_ptr[col-2]+src_ptr[col+2]);
}
// Right border. Computed similarily as the left border.
*(tmp_ptr++) = ((src_ptr[width_minus_2]<<1)+(src_ptr[width_minus_2]<<2)) + ((src_ptr[width_minus_2-1]+src_ptr[width_minus_2+1])<<2) + (src_ptr[width_minus_2-2]+src_ptr[width_minus_2+1]);
*(tmp_ptr++) = ((src_ptr[width_minus_1]<<1)+(src_ptr[width_minus_1]<<2)) + ((src_ptr[width_minus_1-1]+src_ptr[width_minus_1])<<2) + (src_ptr[width_minus_1-2]+src_ptr[width_minus_1]);
}
const unsigned short* pm2;
const unsigned short* pm1;
const unsigned short* p;
const unsigned short* pp1;
const unsigned short* pp2;
// Apply vertical filter along top border. This is applied twice as there are two
// border pixels.
pm2 = tmp;
pm1 = tmp;
p = tmp;
pp1 = p+width;
pp2 = pp1+width;
dst_ptr = dst;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (((*p<<1)+(*p<<2)) + ((*pm1+*pp1)<<2) + (*pm2+*pp2))*(1.f/256.f);
}
pm2 = tmp;
pm1 = tmp;
p = tmp+width;
pp1 = p+width;
pp2 = pp1+width;
dst_ptr = dst+width;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (((*p<<1)+(*p<<2)) + ((*pm1+*pp1)<<2) + (*pm2+*pp2))*(1.f/256.f);
}
// Apply vertical filter for non-border pixels.
pm2 = tmp;
pm1 = pm2+width;
p = pm1+width;
pp1 = p+width;
pp2 = pp1+width;
for(size_t row = 2; row < height_minus_2; row++) {
pm2 = &tmp[(row-2)*width];
pm1 = pm2+width;
p = pm1+width;
pp1 = p+width;
pp2 = pp1+width;
dst_ptr = &dst[row*width];
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (((*p<<1)+(*p<<2)) + ((*pm1+*pp1)<<2) + (*pm2+*pp2))*(1.f/256.f);
}
}
// Apply vertical filter for bottom border. Similar to top border.
pm2 = tmp+(height-4)*width;
pm1 = pm2+width;
p = pm1+width;
pp1 = p+width;
pp2 = pp1;
dst_ptr = dst+(height-2)*width;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (((*p<<1)+(*p<<2)) + ((*pm1+*pp1)<<2) + (*pm2+*pp2))*(1.f/256.f);
}
pm2 = tmp+(height-3)*width;
pm1 = pm2+width;
p = pm1+width;
pp1 = p;
pp2 = p;
dst_ptr = dst+(height-1)*width;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (((*p<<1)+(*p<<2)) + ((*pm1+*pp1)<<2) + (*pm2+*pp2))*(1.f/256.f);
}
}
void binomial_4th_order(float* dst,
float* tmp,
const float* src,
size_t width,
size_t height) {
float* tmp_ptr;
float* dst_ptr;
size_t width_minus_1, width_minus_2;
size_t height_minus_2;
ASSERT(width >= 5, "Image is too small");
ASSERT(height >= 5, "Image is too small");
width_minus_1 = width-1;
width_minus_2 = width-2;
height_minus_2 = height-2;
tmp_ptr = tmp;
// Apply horizontal filter
for(size_t row = 0; row < height; row++) {
const float* src_ptr = &src[row*width];
// Left border is computed by extending the border pixel beyond the image
*(tmp_ptr++) = 6.f*src_ptr[0] + 4.f*(src_ptr[0]+src_ptr[1]) + src_ptr[0] + src_ptr[2];
*(tmp_ptr++) = 6.f*src_ptr[1] + 4.f*(src_ptr[0]+src_ptr[2]) + src_ptr[0] + src_ptr[3];
// Compute non-border pixels
for(size_t col = 2; col < width_minus_2; col++, tmp_ptr++) {
*tmp_ptr = (6.f*src_ptr[col] + 4.f*(src_ptr[col-1]+src_ptr[col+1]) + src_ptr[col-2] + src_ptr[col+2]);
}
// Right border. Computed similarily as the left border.
*(tmp_ptr++) = 6.f*src_ptr[width_minus_2] + 4.f*(src_ptr[width_minus_2-1]+src_ptr[width_minus_2+1]) + src_ptr[width_minus_2-2] + src_ptr[width_minus_2+1];
*(tmp_ptr++) = 6.f*src_ptr[width_minus_1] + 4.f*(src_ptr[width_minus_1-1]+src_ptr[width_minus_1]) + src_ptr[width_minus_1-2] + src_ptr[width_minus_1];
}
const float* pm2;
const float* pm1;
const float* p;
const float* pp1;
const float* pp2;
// Apply vertical filter along top border. This is applied twice as there are two
// border pixels.
pm2 = tmp;
pm1 = tmp;
p = tmp;
pp1 = p+width;
pp2 = pp1+width;
dst_ptr = dst;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (6.f*(*p) + 4.f*(*pm1+*pp1) + (*pm2) + (*pp2))*(1.f/256.f);;
}
pm2 = tmp;
pm1 = tmp;
p = tmp+width;
pp1 = p+width;
pp2 = pp1+width;
dst_ptr = dst+width;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (6.f*(*p) + 4.f*(*pm1+*pp1) + (*pm2) + (*pp2))*(1.f/256.f);;
}
// Apply vertical filter for non-border pixels.
for(size_t row = 2; row < height_minus_2; row++) {
pm2 = &tmp[(row-2)*width];
pm1 = pm2+width;
p = pm1+width;
pp1 = p+width;
pp2 = pp1+width;
dst_ptr = &dst[row*width];
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (6.f*(*p) + 4.f*(*pm1+*pp1) + (*pm2) + (*pp2))*(1.f/256.f);;
}
}
// Apply vertical filter for bottom border. Similar to top border.
pm2 = tmp+(height-4)*width;
pm1 = pm2+width;
p = pm1+width;
pp1 = p+width;
pp2 = pp1;
dst_ptr = dst+(height-2)*width;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (6.f*(*p) + 4.f*(*pm1+*pp1) + (*pm2) + (*pp2))*(1.f/256.f);;
}
pm2 = tmp+(height-3)*width;
pm1 = pm2+width;
p = pm1+width;
pp1 = p;
pp2 = p;
dst_ptr = dst+(height-1)*width;
for(size_t col = 0; col < width; col++, dst_ptr++, pm2++, pm1++, p++, pp1++, pp2++) {
*dst_ptr = (6.f*(*p) + 4.f*(*pm1+*pp1) + (*pm2) + (*pp2))*(1.f/256.f);;
}
}
void downsample_bilinear(float* dst, const float* src, size_t src_width, size_t src_height) {
size_t dst_width;
size_t dst_height;
const float* src_ptr1;
const float* src_ptr2;
dst_width = src_width>>1;
dst_height = src_height>>1;
for(size_t row = 0; row < dst_height; row++) {
src_ptr1 = &src[(row<<1)*src_width];
src_ptr2 = src_ptr1 + src_width;
for(size_t col = 0; col < dst_width; col++, src_ptr1+=2, src_ptr2+=2) {
*(dst++) = (src_ptr1[0]+src_ptr1[1]+src_ptr2[0]+src_ptr2[1])*0.25f;
}
}
}
}
GaussianScaleSpacePyramid::GaussianScaleSpacePyramid()
: mNumOctaves(0)
, mNumScalesPerOctave(0)
, mK(0)
, mOneOverLogK(0)
{}
void GaussianScaleSpacePyramid::configure(int num_octaves, int num_scales_per_octaves) {
mNumOctaves = num_octaves;
mNumScalesPerOctave = num_scales_per_octaves;
mK = std::pow(2.f, 1.f/(mNumScalesPerOctave-1));
mOneOverLogK = 1.f/std::log(mK);
}
BinomialPyramid32f::BinomialPyramid32f() {
}
BinomialPyramid32f::~BinomialPyramid32f()
{}
void BinomialPyramid32f::alloc(size_t width,
size_t height,
int num_octaves) {
//LOG_DEBUG("Binomial pyramid allocating memory for: w = %u, h = %u, levels = %u", width, height, num_octaves);
GaussianScaleSpacePyramid::configure(num_octaves, 3);
// Allocate the pyramid memory
mPyramid.resize(num_octaves*mNumScalesPerOctave);
for(int i = 0; i < num_octaves; i++) {
for(size_t j = 0; j < mNumScalesPerOctave; j++) {
mPyramid[i*mNumScalesPerOctave+j].alloc(IMAGE_F32, width>>i, height>>i, AUTO_STEP, 1);
}
}
mTemp_us16.resize(width*height);
mTemp_f32_1.resize(width*height);
mTemp_f32_2.resize(width*height);
mNumOctaves = num_octaves;
}
void BinomialPyramid32f::release() {
mPyramid.clear();
}
void BinomialPyramid32f::build(const Image& image) {
ASSERT(image.type() == IMAGE_UINT8, "Image must be grayscale");
ASSERT(image.channels() == 1, "Image must have 1 channel");
ASSERT(mPyramid.size() == mNumOctaves*mNumScalesPerOctave, "Pyramid has not been allocated yet");
ASSERT(image.width() == mPyramid[0].width(), "Image of wrong size for pyramid");
ASSERT(image.height() == mPyramid[0].height(), "Image of wrong size for pyramid");
// First octave
apply_filter(mPyramid[0], image);
apply_filter(mPyramid[1], mPyramid[0]);
apply_filter_twice(mPyramid[2], mPyramid[1]);
// Remaining octaves
for(size_t i = 1; i < mNumOctaves; i++) {
// Downsample
downsample_bilinear((float*)mPyramid[i*mNumScalesPerOctave].get(),
(const float*)mPyramid[i*mNumScalesPerOctave-1].get(),
mPyramid[i*mNumScalesPerOctave-1].width(),
mPyramid[i*mNumScalesPerOctave-1].height());
// Apply binomial filters
apply_filter(mPyramid[i*mNumScalesPerOctave+1], mPyramid[i*mNumScalesPerOctave]);
apply_filter_twice(mPyramid[i*mNumScalesPerOctave+2], mPyramid[i*mNumScalesPerOctave+1]);
}
}
void BinomialPyramid32f::apply_filter(Image& dst, const Image& src) {
ASSERT(dst.type() == IMAGE_F32, "Destination image should be a float");
switch(src.type()) {
case IMAGE_UINT8:
binomial_4th_order((float*)dst.get(),
&mTemp_us16[0],
(const unsigned char*)src.get(),
src.width(),
src.height());
break;
case IMAGE_F32:
binomial_4th_order((float*)dst.get(),
&mTemp_f32_1[0],
(const float*)src.get(),
src.width(),
src.height());
break;
case IMAGE_UNKNOWN:
throw EXCEPTION("Unknown image type");
default:
throw EXCEPTION("Unsupported image type");
}
}
void BinomialPyramid32f::apply_filter_twice(Image& dst, const Image& src) {
Image tmp((unsigned char*)&mTemp_f32_2[0], src.type(), src.width(), src.height(), (int)src.step(), 1);
apply_filter(tmp, src);
apply_filter(dst, tmp);
} | gpl-3.0 |
digdoritos/gimp | app/pdb/palette-cmds.c | 8 | 48262 | /* GIMP - The GNU Image Manipulation Program
* Copyright (C) 1995-2003 Spencer Kimball and Peter Mattis
*
* 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/>.
*/
/* NOTE: This file is auto-generated by pdbgen.pl. */
#include "config.h"
#include <cairo.h>
#include <string.h>
#include <gegl.h>
#include <gdk-pixbuf/gdk-pixbuf.h>
#include "libgimpcolor/gimpcolor.h"
#include "libgimpbase/gimpbase.h"
#include "pdb-types.h"
#include "core/gimp.h"
#include "core/gimpcontext.h"
#include "core/gimpdatafactory.h"
#include "core/gimppalette.h"
#include "core/gimpparamspecs.h"
#include "gimppdb.h"
#include "gimppdb-utils.h"
#include "gimpprocedure.h"
#include "internal-procs.h"
static GimpValueArray *
palette_new_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gchar *actual_name = NULL;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpData *data = gimp_data_factory_data_new (gimp->palette_factory,
context, name);
if (data)
actual_name = g_strdup (gimp_object_get_name (data));
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_take_string (gimp_value_array_index (return_vals, 1), actual_name);
return return_vals;
}
static GimpValueArray *
palette_duplicate_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gchar *copy_name = NULL;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
{
GimpPalette *palette_copy = (GimpPalette *)
gimp_data_factory_data_duplicate (gimp->palette_factory,
GIMP_DATA (palette));
if (palette_copy)
copy_name = g_strdup (gimp_object_get_name (palette_copy));
else
success = FALSE;
}
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_take_string (gimp_value_array_index (return_vals, 1), copy_name);
return return_vals;
}
static GimpValueArray *
palette_rename_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
const gchar *new_name;
gchar *actual_name = NULL;
name = g_value_get_string (gimp_value_array_index (args, 0));
new_name = g_value_get_string (gimp_value_array_index (args, 1));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, TRUE, error);
if (palette)
{
gimp_object_set_name (GIMP_OBJECT (palette), new_name);
actual_name = g_strdup (gimp_object_get_name (palette));
}
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_take_string (gimp_value_array_index (return_vals, 1), actual_name);
return return_vals;
}
static GimpValueArray *
palette_delete_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
const gchar *name;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette && gimp_data_is_deletable (GIMP_DATA (palette)))
success = gimp_data_factory_data_delete (gimp->palette_factory,
GIMP_DATA (palette),
TRUE, error);
else
success = FALSE;
}
return gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
}
static GimpValueArray *
palette_is_editable_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gboolean editable = FALSE;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
editable = gimp_data_is_writable (GIMP_DATA (palette));
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_set_boolean (gimp_value_array_index (return_vals, 1), editable);
return return_vals;
}
static GimpValueArray *
palette_get_info_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gint32 num_colors = 0;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
num_colors = gimp_palette_get_n_colors (palette);
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_set_int (gimp_value_array_index (return_vals, 1), num_colors);
return return_vals;
}
static GimpValueArray *
palette_get_colors_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gint32 num_colors = 0;
GimpRGB *colors = NULL;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
{
GList *list = gimp_palette_get_colors (palette);
gint i;
num_colors = gimp_palette_get_n_colors (palette);
colors = g_new (GimpRGB, num_colors);
for (i = 0; i < num_colors; i++, list = g_list_next (list))
{
GimpPaletteEntry *entry = list->data;
colors[i] = entry->color;
}
}
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
{
g_value_set_int (gimp_value_array_index (return_vals, 1), num_colors);
gimp_value_take_colorarray (gimp_value_array_index (return_vals, 2), colors, num_colors);
}
return return_vals;
}
static GimpValueArray *
palette_get_columns_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gint32 num_columns = 0;
name = g_value_get_string (gimp_value_array_index (args, 0));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
num_columns = gimp_palette_get_columns (palette);
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_set_int (gimp_value_array_index (return_vals, 1), num_columns);
return return_vals;
}
static GimpValueArray *
palette_set_columns_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
const gchar *name;
gint32 columns;
name = g_value_get_string (gimp_value_array_index (args, 0));
columns = g_value_get_int (gimp_value_array_index (args, 1));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, TRUE, error);
if (palette)
gimp_palette_set_columns (palette, columns);
else
success = FALSE;
}
return gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
}
static GimpValueArray *
palette_add_entry_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
const gchar *entry_name;
GimpRGB color;
gint32 entry_num = 0;
name = g_value_get_string (gimp_value_array_index (args, 0));
entry_name = g_value_get_string (gimp_value_array_index (args, 1));
gimp_value_get_rgb (gimp_value_array_index (args, 2), &color);
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, TRUE, error);
if (palette)
{
GimpPaletteEntry *entry =
gimp_palette_add_entry (palette, -1, entry_name, &color);
entry_num = entry->position;
}
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_set_int (gimp_value_array_index (return_vals, 1), entry_num);
return return_vals;
}
static GimpValueArray *
palette_delete_entry_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
const gchar *name;
gint32 entry_num;
name = g_value_get_string (gimp_value_array_index (args, 0));
entry_num = g_value_get_int (gimp_value_array_index (args, 1));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, TRUE, error);
if (palette)
{
GimpPaletteEntry *entry = gimp_palette_get_entry (palette, entry_num);
if (entry)
gimp_palette_delete_entry (palette, entry);
else
success = FALSE;
}
else
success = FALSE;
}
return gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
}
static GimpValueArray *
palette_entry_get_color_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gint32 entry_num;
GimpRGB color = { 0.0, 0.0, 0.0, 1.0 };
name = g_value_get_string (gimp_value_array_index (args, 0));
entry_num = g_value_get_int (gimp_value_array_index (args, 1));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
{
GimpPaletteEntry *entry = gimp_palette_get_entry (palette, entry_num);
if (entry)
color = entry->color;
else
success = FALSE;
}
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
gimp_value_set_rgb (gimp_value_array_index (return_vals, 1), &color);
return return_vals;
}
static GimpValueArray *
palette_entry_set_color_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
const gchar *name;
gint32 entry_num;
GimpRGB color;
name = g_value_get_string (gimp_value_array_index (args, 0));
entry_num = g_value_get_int (gimp_value_array_index (args, 1));
gimp_value_get_rgb (gimp_value_array_index (args, 2), &color);
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, TRUE, error);
if (palette)
success = gimp_palette_set_entry_color (palette, entry_num, &color);
else
success = FALSE;
}
return gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
}
static GimpValueArray *
palette_entry_get_name_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
GimpValueArray *return_vals;
const gchar *name;
gint32 entry_num;
gchar *entry_name = NULL;
name = g_value_get_string (gimp_value_array_index (args, 0));
entry_num = g_value_get_int (gimp_value_array_index (args, 1));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, FALSE, error);
if (palette)
{
GimpPaletteEntry *entry = gimp_palette_get_entry (palette, entry_num);
if (entry)
entry_name = g_strdup (entry->name);
else
success = FALSE;
}
else
success = FALSE;
}
return_vals = gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
if (success)
g_value_take_string (gimp_value_array_index (return_vals, 1), entry_name);
return return_vals;
}
static GimpValueArray *
palette_entry_set_name_invoker (GimpProcedure *procedure,
Gimp *gimp,
GimpContext *context,
GimpProgress *progress,
const GimpValueArray *args,
GError **error)
{
gboolean success = TRUE;
const gchar *name;
gint32 entry_num;
const gchar *entry_name;
name = g_value_get_string (gimp_value_array_index (args, 0));
entry_num = g_value_get_int (gimp_value_array_index (args, 1));
entry_name = g_value_get_string (gimp_value_array_index (args, 2));
if (success)
{
GimpPalette *palette = gimp_pdb_get_palette (gimp, name, TRUE, error);
if (palette)
success = gimp_palette_set_entry_name (palette, entry_num, entry_name);
else
success = FALSE;
}
return gimp_procedure_get_return_values (procedure, success,
error ? *error : NULL);
}
void
register_palette_procs (GimpPDB *pdb)
{
GimpProcedure *procedure;
/*
* gimp-palette-new
*/
procedure = gimp_procedure_new (palette_new_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-new");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-new",
"Creates a new palette",
"This procedure creates a new, uninitialized palette",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The requested name of the new palette",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_string ("actual-name",
"actual name",
"The actual new palette name",
FALSE, FALSE, FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-duplicate
*/
procedure = gimp_procedure_new (palette_duplicate_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-duplicate");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-duplicate",
"Duplicates a palette",
"This procedure creates an identical palette by a different name",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_string ("copy-name",
"copy name",
"The name of the palette's copy",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-rename
*/
procedure = gimp_procedure_new (palette_rename_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-rename");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-rename",
"Rename a palette",
"This procedure renames a palette",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("new-name",
"new name",
"The new name of the palette",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_string ("actual-name",
"actual name",
"The actual new name of the palette",
FALSE, FALSE, FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-delete
*/
procedure = gimp_procedure_new (palette_delete_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-delete");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-delete",
"Deletes a palette",
"This procedure deletes a palette",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-is-editable
*/
procedure = gimp_procedure_new (palette_is_editable_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-is-editable");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-is-editable",
"Tests if palette can be edited",
"Returns TRUE if you have permission to change the palette",
"Bill Skaggs <weskaggs@primate.ucdavis.edu>",
"Bill Skaggs",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
g_param_spec_boolean ("editable",
"editable",
"TRUE if the palette can be edited",
FALSE,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-get-info
*/
procedure = gimp_procedure_new (palette_get_info_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-get-info");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-get-info",
"Retrieve information about the specified palette.",
"This procedure retrieves information about the specified palette. This includes the name, and the number of colors.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_int32 ("num-colors",
"num colors",
"The number of colors in the palette",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-get-colors
*/
procedure = gimp_procedure_new (palette_get_colors_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-get-colors");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-get-colors",
"Gets all colors from the specified palette.",
"This procedure retrieves all color entries of the specified palette.",
"Sven Neumann <sven@gimp.org>",
"Sven Neumann",
"2006",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_int32 ("num-colors",
"num colors",
"Length of the colors array",
0, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_color_array ("colors",
"colors",
"The colors in the palette",
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-get-columns
*/
procedure = gimp_procedure_new (palette_get_columns_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-get-columns");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-get-columns",
"Retrieves the number of columns to use to display this palette",
"This procedures retrieves the preferred number of columns to use when the palette is being displayed.",
"Sven Neumann <sven@gimp.org>",
"Sven Neumann",
"2005",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_int32 ("num-columns",
"num columns",
"The number of columns used to display this palette",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-set-columns
*/
procedure = gimp_procedure_new (palette_set_columns_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-set-columns");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-set-columns",
"Sets the number of columns to use when displaying the palette",
"This procedures controls how many colors are shown per row when the palette is being displayed. This value can only be changed if the palette is writable. The maximum allowed value is 64.",
"Sven Neumann <sven@gimp.org>",
"Sven Neumann",
"2005",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_int32 ("columns",
"columns",
"The new number of columns",
0, 64, 0,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-add-entry
*/
procedure = gimp_procedure_new (palette_add_entry_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-add-entry");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-add-entry",
"Adds a palette entry to the specified palette.",
"This procedure adds an entry to the specified palette. It returns an error if the entry palette does not exist.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("entry-name",
"entry name",
"The name of the entry",
FALSE, TRUE, FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_rgb ("color",
"color",
"The new entry's color color",
FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_int32 ("entry-num",
"entry num",
"The index of the added entry",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-delete-entry
*/
procedure = gimp_procedure_new (palette_delete_entry_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-delete-entry");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-delete-entry",
"Deletes a palette entry from the specified palette.",
"This procedure deletes an entry from the specified palette. It returns an error if the entry palette does not exist.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_int32 ("entry-num",
"entry num",
"The index of the added entry",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-entry-get-color
*/
procedure = gimp_procedure_new (palette_entry_get_color_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-entry-get-color");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-entry-get-color",
"Gets the specified palette entry from the specified palette.",
"This procedure retrieves the color of the zero-based entry specified for the specified palette. It returns an error if the entry does not exist.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_int32 ("entry-num",
"entry num",
"The entry to retrieve",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_rgb ("color",
"color",
"The color requested",
FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-entry-set-color
*/
procedure = gimp_procedure_new (palette_entry_set_color_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-entry-set-color");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-entry-set-color",
"Sets the specified palette entry in the specified palette.",
"This procedure sets the color of the zero-based entry specified for the specified palette. It returns an error if the entry does not exist.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_int32 ("entry-num",
"entry num",
"The entry to retrieve",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_rgb ("color",
"color",
"The new color",
FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-entry-get-name
*/
procedure = gimp_procedure_new (palette_entry_get_name_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-entry-get-name");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-entry-get-name",
"Gets the specified palette entry from the specified palette.",
"This procedure retrieves the name of the zero-based entry specified for the specified palette. It returns an error if the entry does not exist.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_int32 ("entry-num",
"entry num",
"The entry to retrieve",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_procedure_add_return_value (procedure,
gimp_param_spec_string ("entry-name",
"entry name",
"The name requested",
FALSE, FALSE, FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
/*
* gimp-palette-entry-set-name
*/
procedure = gimp_procedure_new (palette_entry_set_name_invoker);
gimp_object_set_static_name (GIMP_OBJECT (procedure),
"gimp-palette-entry-set-name");
gimp_procedure_set_static_strings (procedure,
"gimp-palette-entry-set-name",
"Sets the specified palette entry in the specified palette.",
"This procedure sets the name of the zero-based entry specified for the specified palette. It returns an error if the entry does not exist.",
"Michael Natterer <mitch@gimp.org>",
"Michael Natterer",
"2004",
NULL);
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("name",
"name",
"The palette name",
FALSE, FALSE, TRUE,
NULL,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_int32 ("entry-num",
"entry num",
"The entry to retrieve",
G_MININT32, G_MAXINT32, 0,
GIMP_PARAM_READWRITE));
gimp_procedure_add_argument (procedure,
gimp_param_spec_string ("entry-name",
"entry name",
"The new name",
FALSE, TRUE, FALSE,
NULL,
GIMP_PARAM_READWRITE));
gimp_pdb_register_procedure (pdb, procedure);
g_object_unref (procedure);
}
| gpl-3.0 |
stahta01/msys2_codeblocks | src/plugins/contrib/source_exporter/wxPdfDocument/src/pdfgradient.cpp | 8 | 5164 | ///////////////////////////////////////////////////////////////////////////////
// Name: pdfgradient.cpp
// Purpose: Implementation of wxPdfDocument gradient classes
// Author: Ulrich Telle
// Created: 2009-06-11
// Copyright: (c) Ulrich Telle
// Licence: wxWindows licence
///////////////////////////////////////////////////////////////////////////////
/// \file pdfgradient.cpp Implementation of the wxPdfDocument gradient classes
// For compilers that support precompilation, includes <wx/wx.h>.
#include <wx/wxprec.h>
#ifdef __BORLANDC__
#pragma hdrstop
#endif
#ifndef WX_PRECOMP
#include <wx/wx.h>
#endif
#include <wx/tokenzr.h>
#include "wx/pdfcoonspatchmesh.h"
#include "wx/pdfgradient.h"
#include "wx/pdfutility.h"
// --- Gradients
wxPdfGradient::wxPdfGradient(wxPdfGradientType type)
{
m_type = type;
}
wxPdfGradient::~wxPdfGradient()
{
}
wxPdfAxialGradient::wxPdfAxialGradient(const wxPdfColour& colour1, const wxPdfColour& colour2, double x1, double y1, double x2, double y2, double intexp)
: wxPdfGradient(wxPDF_GRADIENT_AXIAL)
{
m_colour1 = colour1;
m_colour2 = colour2;
m_x1 = x1;
m_y1 = y1;
m_x2 = x2;
m_y2 = y2;
m_intexp = intexp;
}
wxPdfAxialGradient::~wxPdfAxialGradient()
{
}
wxPdfMidAxialGradient::wxPdfMidAxialGradient(const wxPdfColour& colour1, const wxPdfColour& colour2, double x1, double y1, double x2, double y2, double midpoint, double intexp)
: wxPdfAxialGradient(colour1, colour2, x1, y1, x2, y2, intexp)
{
m_type = wxPDF_GRADIENT_MIDAXIAL;
m_midpoint = midpoint;
}
wxPdfMidAxialGradient::~wxPdfMidAxialGradient()
{
}
wxPdfRadialGradient::wxPdfRadialGradient(const wxPdfColour& colour1, const wxPdfColour& colour2,
double x1, double y1, double r1,
double x2, double y2, double r2, double intexp)
: wxPdfAxialGradient(colour1, colour2, x1, y1, x2, y2, intexp)
{
m_type = wxPDF_GRADIENT_RADIAL;
m_r1 = r1;
m_r2 = r2;
}
wxPdfRadialGradient::~wxPdfRadialGradient()
{
}
wxPdfCoonsPatch::wxPdfCoonsPatch(int edgeFlag, wxPdfColour colours[], double x[], double y[])
{
m_edgeFlag = edgeFlag;
size_t n = (edgeFlag == 0) ? 4 : 2;
size_t j;
for (j = 0; j < n; j++)
{
m_colours[j] = colours[j];
}
n = (edgeFlag == 0) ? 12 : 8;
for (j = 0; j < n; j++)
{
m_x[j] = x[j];
m_y[j] = y[j];
}
}
wxPdfCoonsPatch::~wxPdfCoonsPatch()
{
}
wxPdfCoonsPatchMesh::wxPdfCoonsPatchMesh()
{
m_ok = false;
m_colourType = wxPDF_COLOURTYPE_UNKNOWN;
}
wxPdfCoonsPatchMesh::~wxPdfCoonsPatchMesh()
{
size_t n = m_patches.size();
if (n > 0)
{
size_t j;
for (j = 0; j < n; j++)
{
delete ((wxPdfCoonsPatch*) m_patches[j]);
}
}
}
bool
wxPdfCoonsPatchMesh::AddPatch(int edgeFlag, wxPdfColour colours[], double x[], double y[])
{
wxPdfColourType colourType = m_colourType;
if (m_patches.size() == 0 && edgeFlag != 0) return false;
int n = (edgeFlag == 0) ? 4 : 2;
int j;
for (j = 0; j < n; j++)
{
if (colourType == wxPDF_COLOURTYPE_UNKNOWN)
{
colourType = colours[j].GetColourType();
}
if (colours[j].GetColourType() != colourType) return false;
}
m_colourType = colourType;
wxPdfCoonsPatch* patch = new wxPdfCoonsPatch(edgeFlag, colours, x, y);
m_patches.Add(patch);
m_ok = true;
return true;
}
wxPdfCoonsPatchGradient::wxPdfCoonsPatchGradient(const wxPdfCoonsPatchMesh& mesh, double minCoord, double maxCoord)
: wxPdfGradient(wxPDF_GRADIENT_COONS)
{
int edgeFlag;
double *x;
double *y;
const wxArrayPtrVoid* patches = mesh.GetPatches();
size_t n = patches->size();
size_t j, k, nc;
unsigned char ch;
int bpcd = 65535; //16 BitsPerCoordinate
int coord;
wxPdfColour *colours;
m_colourType = mesh.GetColourType();
// build the data stream
for (j = 0; j < n; j++)
{
wxPdfCoonsPatch* patch = (wxPdfCoonsPatch*) (*patches)[j];
edgeFlag = patch->GetEdgeFlag();
ch = edgeFlag;
m_buffer.Write(&ch,1); //start with the edge flag as 8 bit
x = patch->GetX();
y = patch->GetY();
nc = (edgeFlag == 0) ? 12 : 8;
for (k = 0; k < nc; k++)
{
// each point as 16 bit
coord = (int) (((x[k] - minCoord) / (maxCoord - minCoord)) * bpcd);
if (coord < 0) coord = 0;
if (coord > bpcd) coord = bpcd;
ch = (coord >> 8) & 0xFF;
m_buffer.Write(&ch,1);
ch = coord & 0xFF;
m_buffer.Write(&ch,1);
coord = (int) (((y[k] - minCoord) / (maxCoord - minCoord)) * bpcd);
if (coord < 0) coord = 0;
if (coord > bpcd) coord = bpcd;
ch = (coord >> 8) & 0xFF;
m_buffer.Write(&ch,1);
ch = coord & 0xFF;
m_buffer.Write(&ch,1);
}
colours = patch->GetColours();
nc = (edgeFlag == 0) ? 4 : 2;
for (k = 0; k < nc; k++)
{
// each colour component as 8 bit
wxStringTokenizer tkz(colours[k].GetColourValue(), wxS(" "));
while ( tkz.HasMoreTokens() )
{
ch = ((int) (wxPdfUtility::String2Double(tkz.GetNextToken()) * 255)) & 0xFF;
m_buffer.Write(&ch,1);
}
}
}
}
wxPdfCoonsPatchGradient::~wxPdfCoonsPatchGradient()
{
}
| gpl-3.0 |
subaddiction/zeus_cgminer-3.1.1 | driver-bflsc.c | 8 | 52008 | /*
* Copyright 2013 Andrew Smith
* Copyright 2013 Con Kolivas
*
* 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. See COPYING for more details.
*/
#include <float.h>
#include <limits.h>
#include <pthread.h>
#include <stdint.h>
#include <stdio.h>
#include <strings.h>
#include <sys/time.h>
#include <unistd.h>
#include "config.h"
#ifdef WIN32
#include <windows.h>
#endif
#include "compat.h"
#include "miner.h"
#include "usbutils.h"
#define BLANK ""
#define LFSTR "<LF>"
/*
* With Firmware 1.0.0 and a result queue of 20 the Max is:
* header = 9
* 64+1+32+1+1+(1+8)*8+1 per line = 172 * 20
* OK = 3
* Total: 3452
*/
#define BFLSC_BUFSIZ (0x1000)
#define BFLSC_DI_FIRMWARE "FIRMWARE"
#define BFLSC_DI_ENGINES "ENGINES"
#define BFLSC_DI_JOBSINQUE "JOBS IN QUEUE"
#define BFLSC_DI_XLINKMODE "XLINK MODE"
#define BFLSC_DI_XLINKPRESENT "XLINK PRESENT"
#define BFLSC_DI_DEVICESINCHAIN "DEVICES IN CHAIN"
#define BFLSC_DI_CHAINPRESENCE "CHAIN PRESENCE MASK"
#define FULLNONCE 0x100000000ULL
struct bflsc_dev {
// Work
unsigned int ms_work;
int work_queued;
int work_complete;
int nonces_hw; // TODO: this - need to add a paramter to submit_nonce()
// so can pass 'dev' to hw_error
uint64_t hashes_unsent;
uint64_t hashes_sent;
uint64_t nonces_found;
struct timeval last_check_result;
struct timeval last_dev_result; // array > 0
struct timeval last_nonce_result; // > 0 nonce
// Info
char getinfo[(BFLSC_BUFSIZ+4)*4];
char *firmware;
int engines; // each engine represents a 'thread' in a chip
char *xlink_mode;
char *xlink_present;
// Status
bool dead; // TODO: handle seperate x-link devices failing?
bool overheat;
// Stats
float temp1;
float temp2;
float vcc1;
float vcc2;
float vmain;
float temp1_max;
float temp2_max;
time_t temp1_max_time;
time_t temp2_max_time;
float temp1_5min_av; // TODO:
float temp2_5min_av; // TODO:
// To handle the fact that flushing the queue may not remove all work
// (normally one item is still being processed)
// and also that once the queue is flushed, results may still be in
// the output queue - but we don't want to process them at the time of doing an LP
// when result_id > flush_id+1, flushed work can be discarded since it
// is no longer in the device
uint64_t flush_id; // counter when results were last flushed
uint64_t result_id; // counter when results were last checked
bool flushed; // are any flushed?
};
// TODO: I stole cgpu_info.device_file
// ... need to update miner.h to instead have a generic void *device_info = NULL;
// ... and these structure definitions need to be in miner.h if API needs to see them
// ... but then again maybe not - maybe another devinfo that the driver provides
// However, clean up all that for all devices in miner.h ... miner.h is a mess at the moment
struct bflsc_info {
pthread_rwlock_t stat_lock;
struct thr_info results_thr;
uint64_t hashes_sent;
uint32_t update_count;
struct timeval last_update;
int sc_count;
struct bflsc_dev *sc_devs;
unsigned int scan_sleep_time;
unsigned int results_sleep_time;
unsigned int default_ms_work;
bool shutdown;
bool flash_led;
bool not_first_work; // allow ignoring the first nonce error
};
#define BFLSC_XLINKHDR '@'
#define BFLSC_MAXPAYLOAD 255
struct DataForwardToChain {
uint8_t header;
uint8_t deviceAddress;
uint8_t payloadSize;
uint8_t payloadData[BFLSC_MAXPAYLOAD];
};
#define DATAFORWARDSIZE(data) (1 + 1 + 1 + data.payloadSize)
#define MIDSTATE_BYTES 32
#define MERKLE_OFFSET 64
#define MERKLE_BYTES 12
#define BFLSC_QJOBSIZ (MIDSTATE_BYTES+MERKLE_BYTES+1)
#define BFLSC_EOB 0xaa
struct QueueJobStructure {
uint8_t payloadSize;
uint8_t midState[MIDSTATE_BYTES];
uint8_t blockData[MERKLE_BYTES];
uint8_t endOfBlock;
};
#define QUE_RES_LINES_MIN 3
#define QUE_MIDSTATE 0
#define QUE_BLOCKDATA 1
#define QUE_NONCECOUNT 2
#define QUE_FLD_MIN 3
#define QUE_FLD_MAX 11
#define BFLSC_SIGNATURE 0xc1
#define BFLSC_EOW 0xfe
// N.B. this will only work with 5 jobs
// requires a different jobs[N] for each job count
// but really only need to handle 5 anyway
struct QueueJobPackStructure {
uint8_t payloadSize;
uint8_t signature;
uint8_t jobsInArray;
struct QueueJobStructure jobs[5];
uint8_t endOfWrapper;
};
// TODO: Implement in API and also in usb device selection
struct SaveString {
uint8_t payloadSize;
uint8_t payloadData[BFLSC_MAXPAYLOAD];
};
// Commands
#define BFLSC_IDENTIFY "ZGX"
#define BFLSC_IDENTIFY_LEN (sizeof(BFLSC_IDENTIFY)-1)
#define BFLSC_DETAILS "ZCX"
#define BFLSC_DETAILS_LEN (sizeof(BFLSC_DETAILS)-1)
#define BFLSC_FIRMWARE "ZJX"
#define BFLSC_FIRMWARE_LEN (sizeof(BFLSC_FIRMWARE)-1)
#define BFLSC_FLASH "ZMX"
#define BFLSC_FLASH_LEN (sizeof(BFLSC_FLASH)-1)
#define BFLSC_VOLTAGE "ZTX"
#define BFLSC_VOLTAGE_LEN (sizeof(BFLSC_VOLTAGE)-1)
#define BFLSC_TEMPERATURE "ZLX"
#define BFLSC_TEMPERATURE_LEN (sizeof(BFLSC_TEMPERATURE)-1)
#define BFLSC_QJOB "ZNX"
#define BFLSC_QJOB_LEN (sizeof(BFLSC_QJOB)-1)
#define BFLSC_QJOBS "ZWX"
#define BFLSC_QJOBS_LEN (sizeof(BFLSC_QJOBS)-1)
#define BFLSC_QRES "ZOX"
#define BFLSC_QRES_LEN (sizeof(BFLSC_QRES)-1)
#define BFLSC_QFLUSH "ZQX"
#define BFLSC_QFLUSH_LEN (sizeof(BFLSC_QFLUSH)-1)
#define BFLSC_FANAUTO "Z5X"
#define BFLSC_FANOUT_LEN (sizeof(BFLSC_FANAUTO)-1)
#define BFLSC_FAN0 "Z0X"
#define BFLSC_FAN0_LEN (sizeof(BFLSC_FAN0)-1)
#define BFLSC_FAN1 "Z1X"
#define BFLSC_FAN1_LEN (sizeof(BFLSC_FAN1)-1)
#define BFLSC_FAN2 "Z2X"
#define BFLSC_FAN2_LEN (sizeof(BFLSC_FAN2)-1)
#define BFLSC_FAN3 "Z3X"
#define BFLSC_FAN3_LEN (sizeof(BFLSC_FAN3)-1)
#define BFLSC_FAN4 "Z4X"
#define BFLSC_FAN4_LEN (sizeof(BFLSC_FAN4)-1)
#define BFLSC_SAVESTR "ZSX"
#define BFLSC_SAVESTR_LEN (sizeof(BFLSC_SAVESTR)-1)
#define BFLSC_LOADSTR "ZUX"
#define BFLSC_LOADSTR_LEN (sizeof(BFLSC_LOADSTR)-1)
// Replies
#define BFLSC_IDENTITY "BitFORCE SC"
#define BFLSC_BFLSC "SHA256 SC"
#define BFLSC_OK "OK\n"
#define BFLSC_OK_LEN (sizeof(BFLSC_OK)-1)
#define BFLSC_SUCCESS "SUCCESS\n"
#define BFLSC_SUCCESS_LEN (sizeof(BFLSC_SUCCESS)-1)
#define BFLSC_RESULT "COUNT:"
#define BFLSC_RESULT_LEN (sizeof(BFLSC_RESULT)-1)
#define BFLSC_ANERR "ERR:"
#define BFLSC_ANERR_LEN (sizeof(BFLSC_ANERR)-1)
#define BFLSC_TIMEOUT BFLSC_ANERR "TIMEOUT"
#define BFLSC_TIMEOUT_LEN (sizeof(BFLSC_TIMEOUT)-1)
#define BFLSC_INVALID BFLSC_ANERR "INVALID DATA"
#define BFLSC_INVALID_LEN (sizeof(BFLSC_INVALID)-1)
#define BFLSC_ERRSIG BFLSC_ANERR "SIGNATURE"
#define BFLSC_ERRSIG_LEN (sizeof(BFLSC_ERRSIG)-1)
#define BFLSC_OKQ "OK:QUEUED"
#define BFLSC_OKQ_LEN (sizeof(BFLSC_OKQ)-1)
// Followed by N=1..5
#define BFLSC_OKQN "OK:QUEUED "
#define BFLSC_OKQN_LEN (sizeof(BFLSC_OKQN)-1)
#define BFLSC_QFULL "QUEUE FULL"
#define BFLSC_QFULL_LEN (sizeof(BFLSC_QFULL)-1)
#define BFLSC_HITEMP "HIGH TEMPERATURE RECOVERY"
#define BFLSC_HITEMP_LEN (sizeof(BFLSC_HITEMP)-1)
#define BFLSC_EMPTYSTR "MEMORY EMPTY"
#define BFLSC_EMPTYSTR_LEN (sizeof(BFLSC_EMPTYSTR)-1)
// Queued and non-queued are the same
#define FullNonceRangeJob QueueJobStructure
#define BFLSC_JOBSIZ BFLSC_QJOBSIZ
// Non queued commands
#define BFLSC_SENDWORK "ZDX"
#define BFLSC_SENDWORK_LEN (sizeof(BFLSC_SENDWORK)-1)
// Non queued commands (not used)
#define BFLSC_WORKSTATUS "ZFX"
#define BFLSC_WORKSTATUS_LEN (sizeof(BFLSC_WORKSTATUS)-1)
#define BFLSC_SENDRANGE "ZPX"
#define BFLSC_SENDRANGE_LEN (sizeof(BFLSC_SENDRANGE)-1)
// Non queued work replies (not used)
#define BFLSC_NONCE "NONCE-FOUND:"
#define BFLSC_NONCE_LEN (sizeof(BFLSC_NONCE)-1)
#define BFLSC_NO_NONCE "NO-NONCE"
#define BFLSC_NO_NONCE_LEN (sizeof(BFLSC_NO_NONCE)-1)
#define BFLSC_IDLE "IDLE"
#define BFLSC_IDLE_LEN (sizeof(BFLSC_IDLE)-1)
#define BFLSC_BUSY "BUSY"
#define BFLSC_BUSY_LEN (sizeof(BFLSC_BUSY)-1)
#define BFLSC_MINIRIG "BAM"
#define BFLSC_SINGLE "BAS"
#define BFLSC_LITTLESINGLE "BAL"
#define BFLSC_JALAPENO "BAJ"
// Default expected time for a nonce range
// - thus no need to check until this + last time work was found
// 60GH/s MiniRig (1 board) or Single
#define BAM_WORK_TIME 71.58
#define BAS_WORK_TIME 71.58
// 30GH/s Little Single
#define BAL_WORK_TIME 143.17
// 4.5GH/s Jalapeno
#define BAJ_WORK_TIME 954.44
// Defaults (slightly over half the work time) but ensure none are above 100
// SCAN_TIME - delay after sending work
// RES_TIME - delay between checking for results
#define BAM_SCAN_TIME 20
#define BAM_RES_TIME 2
#define BAS_SCAN_TIME 360
#define BAS_RES_TIME 36
#define BAL_SCAN_TIME 720
#define BAL_RES_TIME 72
#define BAJ_SCAN_TIME 1000
#define BAJ_RES_TIME 100
#define BFLSC_MAX_SLEEP 2000
#define BFLSC_TEMP_SLEEPMS 5
#define BFLSC_QUE_SIZE 20
#define BFLSC_QUE_FULL_ENOUGH 13
#define BFLSC_QUE_WATERMARK 6
// Must drop this far below cutoff before resuming work
#define BFLSC_TEMP_RECOVER 5
// If initialisation fails the first time,
// sleep this amount (ms) and try again
#define REINIT_TIME_FIRST_MS 100
// Max ms per sleep
#define REINIT_TIME_MAX_MS 800
// Keep trying up to this many us
#define REINIT_TIME_MAX 3000000
static const char *blank = "";
struct device_drv bflsc_drv;
static void xlinkstr(char *xlink, int dev, struct bflsc_info *sc_info)
{
if (dev > 0)
sprintf(xlink, " x-%d", dev);
else {
if (sc_info->sc_count > 1)
strcpy(xlink, " master");
else
*xlink = '\0';
}
}
static void bflsc_applog(struct cgpu_info *bflsc, int dev, enum usb_cmds cmd, int amount, int err)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
char xlink[17];
xlinkstr(xlink, dev, sc_info);
usb_applog(bflsc, cmd, xlink, amount, err);
}
// Break an input up into lines with LFs removed
// false means an error, but if *lines > 0 then data was also found
// error would be no data or missing LF at the end
static bool tolines(struct cgpu_info *bflsc, int dev, char *buf, int *lines, char ***items, enum usb_cmds cmd)
{
bool ok = true;
char *ptr;
#define p_lines (*lines)
#define p_items (*items)
p_lines = 0;
p_items = NULL;
if (!buf || !(*buf)) {
applog(LOG_DEBUG, "USB: %s%i: (%d) empty %s",
bflsc->drv->name, bflsc->device_id, dev, usb_cmdname(cmd));
return false;
}
ptr = strdup(buf);
while (ptr && *ptr) {
p_items = realloc(p_items, ++p_lines * sizeof(*p_items));
if (unlikely(!p_items))
quit(1, "Failed to realloc p_items in tolines");
p_items[p_lines-1] = ptr;
ptr = strchr(ptr, '\n');
if (ptr)
*(ptr++) = '\0';
else {
if (ok) {
applog(LOG_DEBUG, "USB: %s%i: (%d) missing lf(s) in %s",
bflsc->drv->name, bflsc->device_id, dev, usb_cmdname(cmd));
}
ok = false;
}
}
return ok;
}
static void freetolines(int *lines, char ***items)
{
if (*lines > 0) {
free(**items);
free(*items);
}
*lines = 0;
*items = NULL;
}
enum breakmode {
NOCOLON,
ONECOLON,
ALLCOLON // Temperature uses this
};
// Break down a single line into 'fields'
// 'lf' will be a pointer to the final LF if it is there (or NULL)
// firstname will be the allocated buf copy pointer which is also
// the string before ':' for ONECOLON and ALLCOLON
// If any string is missing the ':' when it was expected, false is returned
static bool breakdown(enum breakmode mode, char *buf, int *count, char **firstname, char ***fields, char **lf)
{
char *ptr, *colon, *comma;
bool ok;
#define p_count (*count)
#define p_firstname (*firstname)
#define p_fields (*fields)
#define p_lf (*lf)
p_count = 0;
p_firstname = NULL;
p_fields = NULL;
p_lf = NULL;
if (!buf || !(*buf))
return false;
ptr = p_firstname = strdup(buf);
p_lf = strchr(p_firstname, '\n');
if (mode == ONECOLON) {
colon = strchr(ptr, ':');
if (colon) {
ptr = colon;
*(ptr++) = '\0';
} else
ok = false;
}
while (*ptr == ' ')
ptr++;
ok = true;
while (ptr && *ptr) {
if (mode == ALLCOLON) {
colon = strchr(ptr, ':');
if (colon)
ptr = colon + 1;
else
ok = false;
}
while (*ptr == ' ')
ptr++;
comma = strchr(ptr, ',');
if (comma)
*(comma++) = '\0';
p_fields = realloc(p_fields, ++p_count * sizeof(*p_fields));
if (unlikely(!p_fields))
quit(1, "Failed to realloc p_fields in breakdown");
p_fields[p_count-1] = ptr;
ptr = comma;
}
return ok;
}
static void freebreakdown(int *count, char **firstname, char ***fields)
{
if (*firstname)
free(*firstname);
if (*count > 0)
free(*fields);
*count = 0;
*firstname = NULL;
*fields = NULL;
}
static int write_to_dev(struct cgpu_info *bflsc, int dev, char *buf, int buflen, int *amount, enum usb_cmds cmd)
{
struct DataForwardToChain data;
int len;
if (dev == 0)
return usb_write(bflsc, buf, buflen, amount, cmd);
data.header = BFLSC_XLINKHDR;
data.deviceAddress = (uint8_t)dev;
data.payloadSize = buflen;
memcpy(data.payloadData, buf, buflen);
len = DATAFORWARDSIZE(data);
// TODO: handle xlink timeout message - here or at call?
return usb_write(bflsc, (char *)&data, len, amount, cmd);
}
static bool getok(struct cgpu_info *bflsc, enum usb_cmds cmd, int *err, int *amount)
{
char buf[BFLSC_BUFSIZ+1];
*err = usb_ftdi_read_nl(bflsc, buf, sizeof(buf)-1, amount, cmd);
if (*err < 0 || *amount < (int)BFLSC_OK_LEN)
return false;
else
return true;
}
static bool getokerr(struct cgpu_info *bflsc, enum usb_cmds cmd, int *err, int *amount, char *buf, size_t bufsiz)
{
*err = usb_ftdi_read_nl(bflsc, buf, bufsiz-1, amount, cmd);
if (*err < 0 || *amount < (int)BFLSC_OK_LEN)
return false;
else {
if (*amount > (int)BFLSC_ANERR_LEN && strncmp(buf, BFLSC_ANERR, BFLSC_ANERR_LEN) == 0)
return false;
else
return true;
}
}
static void bflsc_send_flush_work(struct cgpu_info *bflsc, int dev)
{
int err, amount;
// Device is gone
if (bflsc->usbinfo.nodev)
return;
mutex_lock(&bflsc->device_mutex);
err = write_to_dev(bflsc, dev, BFLSC_QFLUSH, BFLSC_QFLUSH_LEN, &amount, C_QUEFLUSH);
if (err < 0 || amount != BFLSC_QFLUSH_LEN) {
mutex_unlock(&bflsc->device_mutex);
bflsc_applog(bflsc, dev, C_QUEFLUSH, amount, err);
} else {
// TODO: do we care if we don't get 'OK'? (always will in normal processing)
err = getok(bflsc, C_QUEFLUSHREPLY, &err, &amount);
mutex_unlock(&bflsc->device_mutex);
// TODO: report an error if not 'OK' ?
}
}
/* return True = attempted usb_ftdi_read_ok()
* set ignore to true means no applog/ignore errors */
static bool bflsc_qres(struct cgpu_info *bflsc, char *buf, size_t bufsiz, int dev, int *err, int *amount, bool ignore)
{
bool readok = false;
mutex_lock(&(bflsc->device_mutex));
*err = write_to_dev(bflsc, dev, BFLSC_QRES, BFLSC_QRES_LEN, amount, C_REQUESTRESULTS);
if (*err < 0 || *amount != BFLSC_QRES_LEN) {
mutex_unlock(&(bflsc->device_mutex));
if (!ignore)
bflsc_applog(bflsc, dev, C_REQUESTRESULTS, *amount, *err);
// TODO: do what? flag as dead device?
// count how many times it has happened and reset/fail it
// or even make sure it is all x-link and that means device
// has failed after some limit of this?
// of course all other I/O must also be failing ...
} else {
readok = true;
*err = usb_ftdi_read_ok(bflsc, buf, bufsiz-1, amount, C_GETRESULTS);
mutex_unlock(&(bflsc->device_mutex));
if (*err < 0 || *amount < 1) {
if (!ignore)
bflsc_applog(bflsc, dev, C_GETRESULTS, *amount, *err);
// TODO: do what? ... see above
}
}
return readok;
}
static void __bflsc_initialise(struct cgpu_info *bflsc)
{
int err;
// TODO: this is a standard BFL FPGA Initialisation
// it probably will need changing ...
// TODO: does x-link bypass the other device FTDI? (I think it does)
// So no initialisation required except for the master device?
if (bflsc->usbinfo.nodev)
return;
// Reset
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_RESET,
FTDI_VALUE_RESET, bflsc->usbdev->found->interface, C_RESET);
applog(LOG_DEBUG, "%s%i: reset got err %d",
bflsc->drv->name, bflsc->device_id, err);
if (bflsc->usbinfo.nodev)
return;
// Set data control
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_DATA,
FTDI_VALUE_DATA, bflsc->usbdev->found->interface, C_SETDATA);
applog(LOG_DEBUG, "%s%i: setdata got err %d",
bflsc->drv->name, bflsc->device_id, err);
if (bflsc->usbinfo.nodev)
return;
// Set the baud
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_BAUD, FTDI_VALUE_BAUD,
(FTDI_INDEX_BAUD & 0xff00) | bflsc->usbdev->found->interface,
C_SETBAUD);
applog(LOG_DEBUG, "%s%i: setbaud got err %d",
bflsc->drv->name, bflsc->device_id, err);
if (bflsc->usbinfo.nodev)
return;
// Set Flow Control
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_FLOW,
FTDI_VALUE_FLOW, bflsc->usbdev->found->interface, C_SETFLOW);
applog(LOG_DEBUG, "%s%i: setflowctrl got err %d",
bflsc->drv->name, bflsc->device_id, err);
if (bflsc->usbinfo.nodev)
return;
// Set Modem Control
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_MODEM,
FTDI_VALUE_MODEM, bflsc->usbdev->found->interface, C_SETMODEM);
applog(LOG_DEBUG, "%s%i: setmodemctrl got err %d",
bflsc->drv->name, bflsc->device_id, err);
if (bflsc->usbinfo.nodev)
return;
// Clear any sent data
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_RESET,
FTDI_VALUE_PURGE_TX, bflsc->usbdev->found->interface, C_PURGETX);
applog(LOG_DEBUG, "%s%i: purgetx got err %d",
bflsc->drv->name, bflsc->device_id, err);
if (bflsc->usbinfo.nodev)
return;
// Clear any received data
err = usb_transfer(bflsc, FTDI_TYPE_OUT, FTDI_REQUEST_RESET,
FTDI_VALUE_PURGE_RX, bflsc->usbdev->found->interface, C_PURGERX);
applog(LOG_DEBUG, "%s%i: purgerx got err %d",
bflsc->drv->name, bflsc->device_id, err);
}
static void bflsc_initialise(struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
char buf[BFLSC_BUFSIZ+1];
int err, amount;
int dev;
mutex_lock(&(bflsc->device_mutex));
__bflsc_initialise(bflsc);
mutex_unlock(&(bflsc->device_mutex));
for (dev = 0; dev < sc_info->sc_count; dev++) {
bflsc_send_flush_work(bflsc, dev);
bflsc_qres(bflsc, buf, sizeof(buf), dev, &err, &amount, true);
}
}
static bool getinfo(struct cgpu_info *bflsc, int dev)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct bflsc_dev sc_dev;
char buf[BFLSC_BUFSIZ+1];
int err, amount;
char **items, *firstname, **fields, *lf;
int i, lines, count;
bool res, ok;
char *tmp;
/*
* Kano's first dev Jalapeno output:
* DEVICE: BitFORCE SC<LF>
* FIRMWARE: 1.0.0<LF>
* ENGINES: 30<LF>
* FREQUENCY: [UNKNOWN]<LF>
* XLINK MODE: MASTER<LF>
* XLINK PRESENT: YES<LF>
* --DEVICES IN CHAIN: 0<LF>
* --CHAIN PRESENCE MASK: 00000000<LF>
* OK<LF>
*/
// TODO: if dev is ever > 0 must handle xlink timeout message
err = write_to_dev(bflsc, dev, BFLSC_DETAILS, BFLSC_DETAILS_LEN, &amount, C_REQUESTDETAILS);
if (err < 0 || amount != BFLSC_DETAILS_LEN) {
applog(LOG_ERR, "%s detect (%s) send details request failed (%d:%d)",
bflsc->drv->dname, bflsc->device_path, amount, err);
return false;
}
err = usb_ftdi_read_ok(bflsc, buf, sizeof(buf)-1, &amount, C_GETDETAILS);
if (err < 0 || amount < 1) {
if (err < 0) {
applog(LOG_ERR, "%s detect (%s) get details return invalid/timed out (%d:%d)",
bflsc->drv->dname, bflsc->device_path, amount, err);
} else {
applog(LOG_ERR, "%s detect (%s) get details returned nothing (%d:%d)",
bflsc->drv->dname, bflsc->device_path, amount, err);
}
return false;
}
memset(&sc_dev, 0, sizeof(struct bflsc_dev));
sc_info->sc_count = 1;
res = tolines(bflsc, dev, &(buf[0]), &lines, &items, C_GETDETAILS);
if (!res)
return false;
tmp = str_text(buf);
strcpy(sc_dev.getinfo, tmp);
free(tmp);
for (i = 0; i < lines-2; i++) {
res = breakdown(ONECOLON, items[i], &count, &firstname, &fields, &lf);
if (lf)
*lf = '\0';
if (!res || count != 1) {
tmp = str_text(items[i]);
applog(LOG_WARNING, "%s detect (%s) invalid details line: '%s' %d",
bflsc->drv->dname, bflsc->device_path, tmp, count);
free(tmp);
dev_error(bflsc, REASON_DEV_COMMS_ERROR);
goto mata;
}
if (strcmp(firstname, BFLSC_DI_FIRMWARE) == 0) {
sc_dev.firmware = strdup(fields[0]);
if (strcmp(sc_dev.firmware, "1.0.0")) {
tmp = str_text(items[i]);
applog(LOG_WARNING, "%s detect (%s) Warning unknown firmware '%s'",
bflsc->drv->dname, bflsc->device_path, tmp);
free(tmp);
}
}
else if (strcmp(firstname, BFLSC_DI_ENGINES) == 0) {
sc_dev.engines = atoi(fields[0]);
if (sc_dev.engines < 1) {
tmp = str_text(items[i]);
applog(LOG_WARNING, "%s detect (%s) invalid engine count: '%s'",
bflsc->drv->dname, bflsc->device_path, tmp);
free(tmp);
goto mata;
}
}
else if (strcmp(firstname, BFLSC_DI_XLINKMODE) == 0)
sc_dev.xlink_mode = strdup(fields[0]);
else if (strcmp(firstname, BFLSC_DI_XLINKPRESENT) == 0)
sc_dev.xlink_present = strdup(fields[0]);
else if (strcmp(firstname, BFLSC_DI_DEVICESINCHAIN) == 0) {
sc_info->sc_count = atoi(fields[0]) + 1;
if (sc_info->sc_count < 1 || sc_info->sc_count > 30) {
tmp = str_text(items[i]);
applog(LOG_WARNING, "%s detect (%s) invalid s-link count: '%s'",
bflsc->drv->dname, bflsc->device_path, tmp);
free(tmp);
goto mata;
}
}
freebreakdown(&count, &firstname, &fields);
}
sc_info->sc_devs = calloc(sc_info->sc_count, sizeof(struct bflsc_dev));
if (unlikely(!sc_info->sc_devs))
quit(1, "Failed to calloc in getinfo");
memcpy(&(sc_info->sc_devs[0]), &sc_dev, sizeof(sc_dev));
// TODO: do we care about getting this info for the rest if > 0 x-link
ok = true;
goto ne;
mata:
freebreakdown(&count, &firstname, &fields);
ok = false;
ne:
freetolines(&lines, &items);
return ok;
}
static bool bflsc_detect_one(struct libusb_device *dev, struct usb_find_devices *found)
{
struct bflsc_info *sc_info = NULL;
char buf[BFLSC_BUFSIZ+1];
char devpath[20];
int i, err, amount;
struct timeval init_start, init_now;
int init_sleep, init_count;
bool ident_first;
char *newname;
struct cgpu_info *bflsc = calloc(1, sizeof(*bflsc));
if (unlikely(!bflsc))
quit(1, "Failed to calloc bflsc in bflsc_detect_one");
bflsc->drv = &bflsc_drv;
bflsc->deven = DEV_ENABLED;
bflsc->threads = 1;
sc_info = calloc(1, sizeof(*sc_info));
if (unlikely(!sc_info))
quit(1, "Failed to calloc sc_info in bflsc_detect_one");
// TODO: fix ... everywhere ...
bflsc->device_file = (FILE *)sc_info;
if (!usb_init(bflsc, dev, found))
goto shin;
sprintf(devpath, "%d:%d",
(int)(bflsc->usbinfo.bus_number),
(int)(bflsc->usbinfo.device_address));
// Allow 2 complete attempts if the 1st time returns an unrecognised reply
ident_first = true;
retry:
init_count = 0;
init_sleep = REINIT_TIME_FIRST_MS;
cgtime(&init_start);
reinit:
__bflsc_initialise(bflsc);
err = write_to_dev(bflsc, 0, BFLSC_IDENTIFY, BFLSC_IDENTIFY_LEN, &amount, C_REQUESTIDENTIFY);
if (err < 0 || amount != BFLSC_IDENTIFY_LEN) {
applog(LOG_ERR, "%s detect (%s) send identify request failed (%d:%d)",
bflsc->drv->dname, devpath, amount, err);
goto unshin;
}
err = usb_ftdi_read_nl(bflsc, buf, sizeof(buf)-1, &amount, C_GETIDENTIFY);
if (err < 0 || amount < 1) {
init_count++;
cgtime(&init_now);
if (us_tdiff(&init_now, &init_start) <= REINIT_TIME_MAX) {
if (init_count == 2) {
applog(LOG_WARNING, "%s detect (%s) 2nd init failed (%d:%d) - retrying",
bflsc->drv->dname, devpath, amount, err);
}
nmsleep(init_sleep);
if ((init_sleep * 2) <= REINIT_TIME_MAX_MS)
init_sleep *= 2;
goto reinit;
}
if (init_count > 0)
applog(LOG_WARNING, "%s detect (%s) init failed %d times %.2fs",
bflsc->drv->dname, devpath, init_count, tdiff(&init_now, &init_start));
if (err < 0) {
applog(LOG_ERR, "%s detect (%s) error identify reply (%d:%d)",
bflsc->drv->dname, devpath, amount, err);
} else {
applog(LOG_ERR, "%s detect (%s) empty identify reply (%d)",
bflsc->drv->dname, devpath, amount);
}
goto unshin;
}
buf[amount] = '\0';
if (unlikely(!strstr(buf, BFLSC_BFLSC))) {
applog(LOG_DEBUG, "%s detect (%s) found an FPGA '%s' ignoring",
bflsc->drv->dname, devpath, buf);
goto unshin;
}
if (unlikely(strstr(buf, BFLSC_IDENTITY))) {
if (ident_first) {
applog(LOG_DEBUG, "%s detect (%s) didn't recognise '%s' trying again ...",
bflsc->drv->dname, devpath, buf);
ident_first = false;
goto retry;
}
applog(LOG_DEBUG, "%s detect (%s) didn't recognise '%s' on 2nd attempt",
bflsc->drv->dname, devpath, buf);
goto unshin;
}
bflsc->device_path = strdup(devpath);
if (!getinfo(bflsc, 0))
goto unshin;
sc_info->scan_sleep_time = BAS_SCAN_TIME;
sc_info->results_sleep_time = BAS_RES_TIME;
sc_info->default_ms_work = BAS_WORK_TIME;
/* When getinfo() "FREQUENCY: [UNKNOWN]" is fixed -
* use 'freq * engines' to estimate.
* Otherwise for now: */
newname = NULL;
if (sc_info->sc_count > 1) {
newname = BFLSC_MINIRIG;
sc_info->scan_sleep_time = BAM_SCAN_TIME;
sc_info->results_sleep_time = BAM_RES_TIME;
sc_info->default_ms_work = BAM_WORK_TIME;
} else {
if (sc_info->sc_devs[0].engines < 34) { // 16 * 2 + 2
newname = BFLSC_JALAPENO;
sc_info->scan_sleep_time = BAJ_SCAN_TIME;
sc_info->results_sleep_time = BAJ_RES_TIME;
sc_info->default_ms_work = BAJ_WORK_TIME;
} else if (sc_info->sc_devs[0].engines < 130) { // 16 * 8 + 2
newname = BFLSC_LITTLESINGLE;
sc_info->scan_sleep_time = BAL_SCAN_TIME;
sc_info->results_sleep_time = BAL_RES_TIME;
sc_info->default_ms_work = BAL_WORK_TIME;
}
}
for (i = 0; i < sc_info->sc_count; i++)
sc_info->sc_devs[i].ms_work = sc_info->default_ms_work;
if (newname) {
if (!bflsc->drv->copy)
bflsc->drv = copy_drv(bflsc->drv);
bflsc->drv->name = newname;
}
// We have a real BFLSC!
applog(LOG_DEBUG, "%s (%s) identified as: '%s'",
bflsc->drv->dname, devpath, bflsc->drv->name);
if (!add_cgpu(bflsc))
goto unshin;
update_usb_stats(bflsc);
mutex_init(&bflsc->device_mutex);
rwlock_init(&sc_info->stat_lock);
return true;
unshin:
usb_uninit(bflsc);
shin:
free(bflsc->device_path);
free(bflsc->device_file);
if (bflsc->name != blank)
free(bflsc->name);
if (bflsc->drv->copy)
free(bflsc->drv);
free(bflsc);
return false;
}
static void bflsc_detect(void)
{
usb_detect(&bflsc_drv, bflsc_detect_one);
}
static void get_bflsc_statline_before(char *buf, struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
float temp = 0;
float vcc1 = 0;
int i;
rd_lock(&(sc_info->stat_lock));
for (i = 0; i < sc_info->sc_count; i++) {
if (sc_info->sc_devs[i].temp1 > temp)
temp = sc_info->sc_devs[i].temp1;
if (sc_info->sc_devs[i].temp2 > temp)
temp = sc_info->sc_devs[i].temp2;
if (sc_info->sc_devs[i].vcc1 > vcc1)
vcc1 = sc_info->sc_devs[i].vcc1;
}
rd_unlock(&(sc_info->stat_lock));
tailsprintf(buf, " max%3.0fC %4.2fV | ", temp, vcc1);
}
static void flush_one_dev(struct cgpu_info *bflsc, int dev)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct work *work, *tmp;
bool did = false;
bflsc_send_flush_work(bflsc, dev);
rd_lock(&bflsc->qlock);
HASH_ITER(hh, bflsc->queued_work, work, tmp) {
if (work->queued && work->subid == dev) {
// devflag is used to flag stale work
work->devflag = true;
did = true;
}
}
rd_unlock(&bflsc->qlock);
if (did) {
wr_lock(&(sc_info->stat_lock));
sc_info->sc_devs[dev].flushed = true;
sc_info->sc_devs[dev].flush_id = sc_info->sc_devs[dev].result_id;
sc_info->sc_devs[dev].work_queued = 0;
wr_unlock(&(sc_info->stat_lock));
}
}
static void bflsc_flush_work(struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
int dev;
for (dev = 0; dev < sc_info->sc_count; dev++)
flush_one_dev(bflsc, dev);
}
static void bflsc_flash_led(struct cgpu_info *bflsc, int dev)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
int err, amount;
// Device is gone
if (bflsc->usbinfo.nodev)
return;
// It is not critical flashing the led so don't get stuck if we
// can't grab the mutex now
if (mutex_trylock(&bflsc->device_mutex))
return;
err = write_to_dev(bflsc, dev, BFLSC_FLASH, BFLSC_FLASH_LEN, &amount, C_REQUESTFLASH);
if (err < 0 || amount != BFLSC_FLASH_LEN) {
mutex_unlock(&(bflsc->device_mutex));
bflsc_applog(bflsc, dev, C_REQUESTFLASH, amount, err);
} else {
getok(bflsc, C_FLASHREPLY, &err, &amount);
mutex_unlock(&(bflsc->device_mutex));
}
// Once we've tried - don't do it until told to again
// - even if it failed
sc_info->flash_led = false;
return;
}
static bool bflsc_get_temp(struct cgpu_info *bflsc, int dev)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct bflsc_dev *sc_dev;
char temp_buf[BFLSC_BUFSIZ+1];
char volt_buf[BFLSC_BUFSIZ+1];
char *tmp;
int err, amount;
char *firstname, **fields, *lf;
char xlink[17];
int count;
bool res;
float temp, temp1, temp2;
float vcc1, vcc2, vmain;
// Device is gone
if (bflsc->usbinfo.nodev)
return false;
if (dev >= sc_info->sc_count) {
applog(LOG_ERR, "%s%i: temp invalid xlink device %d - limit %d",
bflsc->drv->name, bflsc->device_id, dev, sc_info->sc_count - 1);
return false;
}
// Flash instead of Temp
if (sc_info->flash_led) {
bflsc_flash_led(bflsc, dev);
return true;
}
/* It is not very critical getting temp so don't get stuck if we
* can't grab the mutex here */
if (mutex_trylock(&bflsc->device_mutex))
return false;
xlinkstr(&(xlink[0]), dev, sc_info);
err = write_to_dev(bflsc, dev, BFLSC_TEMPERATURE, BFLSC_TEMPERATURE_LEN, &amount, C_REQUESTTEMPERATURE);
if (err < 0 || amount != BFLSC_TEMPERATURE_LEN) {
mutex_unlock(&(bflsc->device_mutex));
applog(LOG_ERR, "%s%i: Error: Request%s temp invalid/timed out (%d:%d)",
bflsc->drv->name, bflsc->device_id, xlink, amount, err);
return false;
}
err = usb_ftdi_read_nl(bflsc, temp_buf, sizeof(temp_buf)-1, &amount, C_GETTEMPERATURE);
if (err < 0 || amount < 1) {
mutex_unlock(&(bflsc->device_mutex));
if (err < 0) {
applog(LOG_ERR, "%s%i: Error: Get%s temp return invalid/timed out (%d:%d)",
bflsc->drv->name, bflsc->device_id, xlink, amount, err);
} else {
applog(LOG_ERR, "%s%i: Error: Get%s temp returned nothing (%d:%d)",
bflsc->drv->name, bflsc->device_id, xlink, amount, err);
}
return false;
}
// N.B. we only get the voltages if the temp succeeds - temp is the important one
err = write_to_dev(bflsc, dev, BFLSC_VOLTAGE, BFLSC_VOLTAGE_LEN, &amount, C_REQUESTVOLTS);
if (err < 0 || amount != BFLSC_VOLTAGE_LEN) {
mutex_unlock(&(bflsc->device_mutex));
applog(LOG_ERR, "%s%i: Error: Request%s volts invalid/timed out (%d:%d)",
bflsc->drv->name, bflsc->device_id, xlink, amount, err);
return false;
}
err = usb_ftdi_read_nl(bflsc, volt_buf, sizeof(volt_buf)-1, &amount, C_GETTEMPERATURE);
if (err < 0 || amount < 1) {
mutex_unlock(&(bflsc->device_mutex));
if (err < 0) {
applog(LOG_ERR, "%s%i: Error: Get%s temp return invalid/timed out (%d:%d)",
bflsc->drv->name, bflsc->device_id, xlink, amount, err);
} else {
applog(LOG_ERR, "%s%i: Error: Get%s temp returned nothing (%d:%d)",
bflsc->drv->name, bflsc->device_id, xlink, amount, err);
}
return false;
}
mutex_unlock(&(bflsc->device_mutex));
res = breakdown(ALLCOLON, temp_buf, &count, &firstname, &fields, &lf);
if (lf)
*lf = '\0';
if (!res || count != 2 || !lf) {
tmp = str_text(temp_buf);
applog(LOG_WARNING, "%s%i: Invalid%s temp reply: '%s'",
bflsc->drv->name, bflsc->device_id, xlink, tmp);
free(tmp);
freebreakdown(&count, &firstname, &fields);
dev_error(bflsc, REASON_DEV_COMMS_ERROR);
return false;
}
temp = temp1 = (float)atoi(fields[0]);
temp2 = (float)atoi(fields[1]);
res = breakdown(NOCOLON, volt_buf, &count, &firstname, &fields, &lf);
if (lf)
*lf = '\0';
if (!res || count != 3 || !lf) {
tmp = str_text(volt_buf);
applog(LOG_WARNING, "%s%i: Invalid%s volt reply: '%s'",
bflsc->drv->name, bflsc->device_id, xlink, tmp);
free(tmp);
freebreakdown(&count, &firstname, &fields);
dev_error(bflsc, REASON_DEV_COMMS_ERROR);
return false;
}
sc_dev = &sc_info->sc_devs[dev];
vcc1 = (float)atoi(fields[0]) / 1000.0;
vcc2 = (float)atoi(fields[1]) / 1000.0;
vmain = (float)atoi(fields[2]) / 1000.0;
if (vcc1 > 0 || vcc2 > 0 || vmain > 0) {
wr_lock(&(sc_info->stat_lock));
if (vcc1 > 0) {
if (unlikely(sc_dev->vcc1 == 0))
sc_dev->vcc1 = vcc1;
else {
sc_dev->vcc1 += vcc1 * 0.63;
sc_dev->vcc1 /= 1.63;
}
}
if (vcc2 > 0) {
if (unlikely(sc_dev->vcc2 == 0))
sc_dev->vcc2 = vcc2;
else {
sc_dev->vcc2 += vcc2 * 0.63;
sc_dev->vcc2 /= 1.63;
}
}
if (vmain > 0) {
if (unlikely(sc_dev->vmain == 0))
sc_dev->vmain = vmain;
else {
sc_dev->vmain += vmain * 0.63;
sc_dev->vmain /= 1.63;
}
}
wr_unlock(&(sc_info->stat_lock));
}
if (temp1 > 0 || temp2 > 0) {
wr_lock(&(sc_info->stat_lock));
if (unlikely(!sc_dev->temp1))
sc_dev->temp1 = temp1;
else {
sc_dev->temp1 += temp1 * 0.63;
sc_dev->temp1 /= 1.63;
}
if (unlikely(!sc_dev->temp2))
sc_dev->temp2 = temp2;
else {
sc_dev->temp2 += temp2 * 0.63;
sc_dev->temp2 /= 1.63;
}
if (temp1 > sc_dev->temp1_max) {
sc_dev->temp1_max = temp1;
sc_dev->temp1_max_time = time(NULL);
}
if (temp2 > sc_dev->temp2_max) {
sc_dev->temp2_max = temp2;
sc_dev->temp2_max_time = time(NULL);
}
if (unlikely(sc_dev->temp1_5min_av == 0))
sc_dev->temp1_5min_av = temp1;
else {
sc_dev->temp1_5min_av += temp1 * .0042;
sc_dev->temp1_5min_av /= 1.0042;
}
if (unlikely(sc_dev->temp2_5min_av == 0))
sc_dev->temp2_5min_av = temp2;
else {
sc_dev->temp2_5min_av += temp2 * .0042;
sc_dev->temp2_5min_av /= 1.0042;
}
wr_unlock(&(sc_info->stat_lock));
if (temp < temp2)
temp = temp2;
bflsc->temp = temp;
if (bflsc->cutofftemp > 0 && temp > bflsc->cutofftemp) {
applog(LOG_WARNING, "%s%i:%s temp (%.1f) hit thermal cutoff limit %d, stopping work!",
bflsc->drv->name, bflsc->device_id, xlink,
temp, bflsc->cutofftemp);
dev_error(bflsc, REASON_DEV_THERMAL_CUTOFF);
sc_dev->overheat = true;
flush_one_dev(bflsc, dev);
return false;
}
if (bflsc->cutofftemp > 0 && temp < (bflsc->cutofftemp - BFLSC_TEMP_RECOVER))
sc_dev->overheat = false;
}
freebreakdown(&count, &firstname, &fields);
return true;
}
static void process_nonces(struct cgpu_info *bflsc, int dev, char *xlink, char *data, int count, char **fields, int *nonces)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
char midstate[MIDSTATE_BYTES], blockdata[MERKLE_BYTES];
struct work *work;
uint32_t nonce;
int i, num;
bool res;
char *tmp;
if (count < QUE_FLD_MIN) {
tmp = str_text(data);
applog(LOG_ERR, "%s%i:%s work returned too small (%d,%s)",
bflsc->drv->name, bflsc->device_id, xlink, count, tmp);
free(tmp);
inc_hw_errors(bflsc->thr[0]);
return;
}
if (count > QUE_FLD_MAX) {
applog(LOG_ERR, "%s%i:%s work returned too large (%d) processing %d anyway",
bflsc->drv->name, bflsc->device_id, xlink, count, QUE_FLD_MAX);
count = QUE_FLD_MAX;
inc_hw_errors(bflsc->thr[0]);
}
num = atoi(fields[QUE_NONCECOUNT]);
if (num != count - QUE_FLD_MIN) {
tmp = str_text(data);
applog(LOG_ERR, "%s%i:%s incorrect data count (%d) will use %d instead from (%s)",
bflsc->drv->name, bflsc->device_id, xlink, num, count - QUE_FLD_MAX, tmp);
free(tmp);
inc_hw_errors(bflsc->thr[0]);
}
memset(midstate, 0, MIDSTATE_BYTES);
memset(blockdata, 0, MERKLE_BYTES);
hex2bin((unsigned char *)midstate, fields[QUE_MIDSTATE], MIDSTATE_BYTES);
hex2bin((unsigned char *)blockdata, fields[QUE_BLOCKDATA], MERKLE_BYTES);
work = find_queued_work_bymidstate(bflsc, midstate, MIDSTATE_BYTES,
blockdata, MERKLE_OFFSET, MERKLE_BYTES);
if (!work) {
if (sc_info->not_first_work) {
applog(LOG_ERR, "%s%i:%s failed to find nonce work - can't be processed - ignored",
bflsc->drv->name, bflsc->device_id, xlink);
inc_hw_errors(bflsc->thr[0]);
}
return;
}
res = false;
for (i = QUE_FLD_MIN; i < count; i++) {
if (strlen(fields[i]) != 8) {
tmp = str_text(data);
applog(LOG_ERR, "%s%i:%s invalid nonce (%s) will try to process anyway",
bflsc->drv->name, bflsc->device_id, xlink, tmp);
free(tmp);
}
hex2bin((void*)&nonce, fields[i], 4);
nonce = htobe32(nonce);
wr_lock(&(sc_info->stat_lock));
sc_info->sc_devs[dev].nonces_found++;
wr_unlock(&(sc_info->stat_lock));
submit_nonce(bflsc->thr[0], work, nonce);
(*nonces)++;
res = true;
}
wr_lock(&(sc_info->stat_lock));
if (res)
sc_info->sc_devs[dev].result_id++;
sc_info->sc_devs[dev].work_complete++;
sc_info->sc_devs[dev].hashes_unsent += FULLNONCE;
// If not flushed (stale)
if (!(work->devflag))
sc_info->sc_devs[dev].work_queued -= 1;
wr_unlock(&(sc_info->stat_lock));
work_completed(bflsc, work);
}
static int process_results(struct cgpu_info *bflsc, int dev, char *buf, int *nonces)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
char **items, *firstname, **fields, *lf;
int que, i, lines, count;
char xlink[17];
char *tmp, *tmp2;
*nonces = 0;
xlinkstr(&(xlink[0]), dev, sc_info);
tolines(bflsc, dev, buf, &lines, &items, C_GETRESULTS);
if (lines < 1) {
tmp = str_text(buf);
applog(LOG_ERR, "%s%i:%s empty result (%s) ignored",
bflsc->drv->name, bflsc->device_id, xlink, tmp);
free(tmp);
que = 0;
goto arigatou;
}
if (lines < QUE_RES_LINES_MIN) {
tmp = str_text(buf);
applog(LOG_ERR, "%s%i:%s result too small (%s) ignored",
bflsc->drv->name, bflsc->device_id, xlink, tmp);
free(tmp);
que = 0;
goto arigatou;
}
breakdown(ONECOLON, items[1], &count, &firstname, &fields, &lf);
if (count < 1) {
tmp = str_text(buf);
tmp2 = str_text(items[1]);
applog(LOG_ERR, "%s%i:%s empty result count (%s) in (%s) will try anyway",
bflsc->drv->name, bflsc->device_id, xlink, tmp2, tmp);
free(tmp2);
free(tmp);
} else if (count != 1) {
tmp = str_text(buf);
tmp2 = str_text(items[1]);
applog(LOG_ERR, "%s%i:%s incorrect result count %d (%s) in (%s) will try anyway",
bflsc->drv->name, bflsc->device_id, xlink, count, tmp2, tmp);
free(tmp2);
free(tmp);
}
que = atoi(fields[0]);
if (que != (lines - QUE_RES_LINES_MIN)) {
i = que;
// 1+ In case the last line isn't 'OK' - try to process it
que = 1 + lines - QUE_RES_LINES_MIN;
tmp = str_text(buf);
tmp2 = str_text(items[0]);
applog(LOG_ERR, "%s%i:%s incorrect result count %d (%s) will try %d (%s)",
bflsc->drv->name, bflsc->device_id, xlink, i, tmp2, que, tmp);
free(tmp2);
free(tmp);
}
freebreakdown(&count, &firstname, &fields);
for (i = 0; i < que; i++) {
breakdown(NOCOLON, items[i + QUE_RES_LINES_MIN - 1], &count, &firstname, &fields, &lf);
process_nonces(bflsc, dev, &(xlink[0]), items[i], count, fields, nonces);
freebreakdown(&count, &firstname, &fields);
sc_info->not_first_work = true;
}
arigatou:
freetolines(&lines, &items);
return que;
}
#define TVF(tv) ((float)((tv)->tv_sec) + ((float)((tv)->tv_usec) / 1000000.0))
#define TVFMS(tv) (TVF(tv) * 1000.0)
// Thread to simply keep looking for results
static void *bflsc_get_results(void *userdata)
{
struct cgpu_info *bflsc = (struct cgpu_info *)userdata;
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct timeval elapsed, now;
float oldest, f;
char buf[BFLSC_BUFSIZ+1];
int err, amount;
int i, que, dev, nonces;
bool readok;
cgtime(&now);
for (i = 0; i < sc_info->sc_count; i++) {
copy_time(&(sc_info->sc_devs[i].last_check_result), &now);
copy_time(&(sc_info->sc_devs[i].last_dev_result), &now);
copy_time(&(sc_info->sc_devs[i].last_nonce_result), &now);
}
while (sc_info->shutdown == false) {
if (bflsc->usbinfo.nodev)
return NULL;
dev = -1;
oldest = FLT_MAX;
cgtime(&now);
// Find the first oldest ... that also needs checking
for (i = 0; i < sc_info->sc_count; i++) {
timersub(&now, &(sc_info->sc_devs[i].last_check_result), &elapsed);
f = TVFMS(&elapsed);
if (f < oldest && f >= sc_info->sc_devs[i].ms_work) {
f = oldest;
dev = i;
}
}
if (bflsc->usbinfo.nodev)
return NULL;
if (dev == -1)
goto utsura;
cgtime(&(sc_info->sc_devs[dev].last_check_result));
readok = bflsc_qres(bflsc, buf, sizeof(buf), dev, &err, &amount, false);
if (err < 0 || (!readok && amount != BFLSC_QRES_LEN) || (readok && amount < 1)) {
// TODO: do what else?
} else {
que = process_results(bflsc, dev, buf, &nonces);
sc_info->not_first_work = true; // in case it failed processing it
if (que > 0)
cgtime(&(sc_info->sc_devs[dev].last_dev_result));
if (nonces > 0)
cgtime(&(sc_info->sc_devs[dev].last_nonce_result));
// TODO: if not getting results ... reinit?
}
utsura:
nmsleep(sc_info->results_sleep_time);
}
return NULL;
}
static bool bflsc_thread_prepare(struct thr_info *thr)
{
struct cgpu_info *bflsc = thr->cgpu;
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct timeval now;
if (thr_info_create(&(sc_info->results_thr), NULL, bflsc_get_results, (void *)bflsc)) {
applog(LOG_ERR, "%s%i: thread create failed", bflsc->drv->name, bflsc->device_id);
return false;
}
pthread_detach(sc_info->results_thr.pth);
cgtime(&now);
get_datestamp(bflsc->init, &now);
return true;
}
static void bflsc_shutdown(struct thr_info *thr)
{
struct cgpu_info *bflsc = thr->cgpu;
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
bflsc_flush_work(bflsc);
sc_info->shutdown = true;
}
static void bflsc_thread_enable(struct thr_info *thr)
{
struct cgpu_info *bflsc = thr->cgpu;
if (bflsc->usbinfo.nodev)
return;
bflsc_initialise(bflsc);
}
static bool bflsc_send_work(struct cgpu_info *bflsc, int dev, struct work *work)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct FullNonceRangeJob data;
char buf[BFLSC_BUFSIZ+1];
int err, amount;
int len;
int try;
// Device is gone
if (bflsc->usbinfo.nodev)
return false;
// TODO: handle this everywhere
if (sc_info->sc_devs[dev].overheat == true)
return false;
// Initially code only deals with sending one work item
data.payloadSize = BFLSC_JOBSIZ;
memcpy(data.midState, work->midstate, MIDSTATE_BYTES);
memcpy(data.blockData, work->data + MERKLE_OFFSET, MERKLE_BYTES);
data.endOfBlock = BFLSC_EOB;
try = 0;
mutex_lock(&(bflsc->device_mutex));
re_send:
err = write_to_dev(bflsc, dev, BFLSC_QJOB, BFLSC_QJOB_LEN, &amount, C_REQUESTQUEJOB);
if (err < 0 || amount != BFLSC_QJOB_LEN) {
mutex_unlock(&(bflsc->device_mutex));
bflsc_applog(bflsc, dev, C_REQUESTQUEJOB, amount, err);
return false;
}
if (!getok(bflsc, C_REQUESTQUEJOBSTATUS, &err, &amount)) {
mutex_unlock(&(bflsc->device_mutex));
bflsc_applog(bflsc, dev, C_REQUESTQUEJOBSTATUS, amount, err);
return false;
}
len = sizeof(struct FullNonceRangeJob);
err = write_to_dev(bflsc, dev, (char *)&data, len, &amount, C_QUEJOB);
if (err < 0 || amount != len) {
mutex_unlock(&(bflsc->device_mutex));
bflsc_applog(bflsc, dev, C_QUEJOB, amount, err);
return false;
}
if (!getokerr(bflsc, C_QUEJOBSTATUS, &err, &amount, buf, sizeof(buf))) {
// TODO: check for QUEUE FULL and set work_queued to BFLSC_QUE_SIZE
// and report a code bug LOG_ERR - coz it should never happen
// Try twice
if (try++ < 1 && amount > 1 &&
strncasecmp(buf, BFLSC_TIMEOUT, BFLSC_TIMEOUT_LEN) == 0)
goto re_send;
mutex_unlock(&(bflsc->device_mutex));
bflsc_applog(bflsc, dev, C_QUEJOBSTATUS, amount, err);
return false;
}
mutex_unlock(&(bflsc->device_mutex));
wr_lock(&(sc_info->stat_lock));
sc_info->sc_devs[dev].work_queued++;
wr_unlock(&(sc_info->stat_lock));
work->subid = dev;
return true;
}
static bool bflsc_queue_full(struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct work *work = NULL;
int i, dev, tried, que;
bool ret = false;
int tries = 0;
tried = -1;
// if something is wrong with a device try the next one available
// TODO: try them all? Add an unavailable flag to sc_devs[i] init to 0 here first
while (++tries < 3) {
// Device is gone - shouldn't normally get here
if (bflsc->usbinfo.nodev) {
ret = true;
break;
}
dev = -1;
rd_lock(&(sc_info->stat_lock));
// Anything waiting - gets the work first
for (i = 0; i < sc_info->sc_count; i++) {
// TODO: and ignore x-link dead - once I work out how to decide it is dead
if (i != tried && sc_info->sc_devs[i].work_queued == 0 &&
!sc_info->sc_devs[i].overheat) {
dev = i;
break;
}
}
if (dev == -1) {
que = BFLSC_QUE_SIZE * 10; // 10x is certainly above the MAX it could be
// The first device with the smallest amount queued
for (i = 0; i < sc_info->sc_count; i++) {
if (i != tried && sc_info->sc_devs[i].work_queued < que &&
!sc_info->sc_devs[i].overheat) {
dev = i;
que = sc_info->sc_devs[i].work_queued;
}
}
if (que > BFLSC_QUE_FULL_ENOUGH)
dev = -1;
}
rd_unlock(&(sc_info->stat_lock));
// nothing needs work yet
if (dev == -1) {
ret = true;
break;
}
if (!work)
work = get_queued(bflsc);
if (unlikely(!work))
break;
if (bflsc_send_work(bflsc, dev, work)) {
work = NULL;
break;
} else
tried = dev;
}
if (unlikely(work))
work_completed(bflsc, work);
return ret;
}
static int64_t bflsc_scanwork(struct thr_info *thr)
{
struct cgpu_info *bflsc = thr->cgpu;
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
int64_t ret, unsent;
bool flushed, cleanup;
struct work *work, *tmp;
int dev, waited, i;
// Device is gone
if (bflsc->usbinfo.nodev)
return -1;
flushed = false;
// Single lock check if any are flagged as flushed
rd_lock(&(sc_info->stat_lock));
for (dev = 0; dev < sc_info->sc_count; dev++)
flushed |= sc_info->sc_devs[dev].flushed;
rd_unlock(&(sc_info->stat_lock));
// > 0 flagged as flushed
if (flushed) {
// TODO: something like this ......
for (dev = 0; dev < sc_info->sc_count; dev++) {
cleanup = false;
// Is there any flushed work that can be removed?
rd_lock(&(sc_info->stat_lock));
if (sc_info->sc_devs[dev].flushed) {
if (sc_info->sc_devs[dev].result_id > (sc_info->sc_devs[dev].flush_id + 1))
cleanup = true;
}
rd_unlock(&(sc_info->stat_lock));
// yes remove the flushed work that can be removed
if (cleanup) {
wr_lock(&bflsc->qlock);
HASH_ITER(hh, bflsc->queued_work, work, tmp) {
if (work->devflag && work->subid == dev) {
bflsc->queued_count--;
HASH_DEL(bflsc->queued_work, work);
discard_work(work);
}
}
wr_unlock(&bflsc->qlock);
wr_lock(&(sc_info->stat_lock));
sc_info->sc_devs[dev].flushed = false;
wr_unlock(&(sc_info->stat_lock));
}
}
}
waited = restart_wait(sc_info->scan_sleep_time);
if (waited == ETIMEDOUT) {
unsigned int old_sleep_time, new_sleep_time = 0;
int min_queued = BFLSC_QUE_SIZE;
/* Only adjust the scan_sleep_time if we did not receive a
* restart message while waiting. Try to adjust sleep time
* so we drop to BFLSC_QUE_WATERMARK before getting more work.
*/
rd_lock(&sc_info->stat_lock);
old_sleep_time = sc_info->scan_sleep_time;
for (i = 0; i < sc_info->sc_count; i++) {
if (sc_info->sc_devs[i].work_queued < min_queued)
min_queued = sc_info->sc_devs[i].work_queued;
}
rd_unlock(&sc_info->stat_lock);
new_sleep_time = old_sleep_time;
/* Increase slowly but decrease quickly */
if (min_queued > BFLSC_QUE_WATERMARK && old_sleep_time < BFLSC_MAX_SLEEP)
new_sleep_time = old_sleep_time * 21 / 20;
else if (min_queued < BFLSC_QUE_WATERMARK)
new_sleep_time = old_sleep_time * 2 / 3;
/* Do not sleep more than BFLSC_MAX_SLEEP so we can always
* report in at least 2 results per 5s log interval. */
if (new_sleep_time != old_sleep_time) {
if (new_sleep_time > BFLSC_MAX_SLEEP)
new_sleep_time = BFLSC_MAX_SLEEP;
else if (new_sleep_time == 0)
new_sleep_time = 1;
applog(LOG_DEBUG, "%s%i: Changed scan sleep time to %d",
bflsc->drv->name, bflsc->device_id, new_sleep_time);
wr_lock(&sc_info->stat_lock);
sc_info->scan_sleep_time = new_sleep_time;
wr_unlock(&sc_info->stat_lock);
}
}
// Count up the work done since we last were here
ret = 0;
wr_lock(&(sc_info->stat_lock));
for (dev = 0; dev < sc_info->sc_count; dev++) {
unsent = sc_info->sc_devs[dev].hashes_unsent;
sc_info->sc_devs[dev].hashes_unsent = 0;
sc_info->sc_devs[dev].hashes_sent += unsent;
sc_info->hashes_sent += unsent;
ret += unsent;
}
wr_unlock(&(sc_info->stat_lock));
return ret;
}
static bool bflsc_get_stats(struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
bool allok = true;
int i;
// Device is gone
if (bflsc->usbinfo.nodev)
return false;
for (i = 0; i < sc_info->sc_count; i++) {
if (!bflsc_get_temp(bflsc, i))
allok = false;
// Device is gone
if (bflsc->usbinfo.nodev)
return false;
if (i < (sc_info->sc_count - 1))
nmsleep(BFLSC_TEMP_SLEEPMS);
}
return allok;
}
static void bflsc_identify(struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
// TODO: handle x-link
sc_info->flash_led = true;
}
static bool bflsc_thread_init(struct thr_info *thr)
{
struct cgpu_info *bflsc = thr->cgpu;
if (bflsc->usbinfo.nodev)
return false;
bflsc_initialise(bflsc);
return true;
}
// there should be a new API function to return device info that isn't the standard stuff
// instead of bflsc_api_stats - since the stats should really just be internal code info
// and the new one should be UNusual device stats/extra details - like the stuff below
static struct api_data *bflsc_api_stats(struct cgpu_info *bflsc)
{
struct bflsc_info *sc_info = (struct bflsc_info *)(bflsc->device_file);
struct api_data *root = NULL;
//if no x-link ... etc
rd_lock(&(sc_info->stat_lock));
root = api_add_temp(root, "Temp1", &(sc_info->sc_devs[0].temp1), true);
root = api_add_temp(root, "Temp2", &(sc_info->sc_devs[0].temp2), true);
root = api_add_volts(root, "Vcc1", &(sc_info->sc_devs[0].vcc1), true);
root = api_add_volts(root, "Vcc2", &(sc_info->sc_devs[0].vcc2), true);
root = api_add_volts(root, "Vmain", &(sc_info->sc_devs[0].vmain), true);
root = api_add_temp(root, "Temp1 Max", &(sc_info->sc_devs[0].temp1_max), true);
root = api_add_temp(root, "Temp2 Max", &(sc_info->sc_devs[0].temp2_max), true);
root = api_add_time(root, "Temp1 Max Time", &(sc_info->sc_devs[0].temp1_max_time), true);
root = api_add_time(root, "Temp2 Max Time", &(sc_info->sc_devs[0].temp2_max_time), true);
rd_unlock(&(sc_info->stat_lock));
root = api_add_escape(root, "GetInfo", sc_info->sc_devs[0].getinfo, false);
/*
else a whole lot of something like these ... etc
root = api_add_temp(root, "X-%d-Temp1", &(sc_info->temp1), false);
root = api_add_temp(root, "X-%d-Temp2", &(sc_info->temp2), false);
root = api_add_volts(root, "X-%d-Vcc1", &(sc_info->vcc1), false);
root = api_add_volts(root, "X-%d-Vcc2", &(sc_info->vcc2), false);
root = api_add_volts(root, "X-%d-Vmain", &(sc_info->vmain), false);
*/
return root;
}
struct device_drv bflsc_drv = {
.drv_id = DRIVER_BFLSC,
.dname = "BitForceSC",
.name = BFLSC_SINGLE,
.drv_detect = bflsc_detect,
.get_api_stats = bflsc_api_stats,
.get_statline_before = get_bflsc_statline_before,
.get_stats = bflsc_get_stats,
.identify_device = bflsc_identify,
.thread_prepare = bflsc_thread_prepare,
.thread_init = bflsc_thread_init,
.hash_work = hash_queued_work,
.scanwork = bflsc_scanwork,
.queue_full = bflsc_queue_full,
.flush_work = bflsc_flush_work,
.thread_shutdown = bflsc_shutdown,
.thread_enable = bflsc_thread_enable
};
| gpl-3.0 |
theli-ua/tomahawk | src/libtomahawk/database/DatabaseCommand_UpdateSearchIndex.cpp | 9 | 2284 | /* === This file is part of Tomahawk Player - <http://tomahawk-player.org> ===
*
* Copyright 2010-2014, Christian Muehlhaeuser <muesli@tomahawk-player.org>
* Copyright 2012 Leo Franchi <lfranchi@kde.org>
*
* Tomahawk 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.
*
* Tomahawk 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 Tomahawk. If not, see <http://www.gnu.org/licenses/>.
*/
#include "DatabaseCommand_UpdateSearchIndex.h"
#include <QSqlRecord>
#include "DatabaseImpl.h"
#include "Source.h"
#include "TomahawkSqlQuery.h"
#include "fuzzyindex/DatabaseFuzzyIndex.h"
#include "utils/Logger.h"
namespace Tomahawk
{
DatabaseCommand_UpdateSearchIndex::DatabaseCommand_UpdateSearchIndex()
: DatabaseCommand()
{
tDebug() << Q_FUNC_INFO << "Updating index.";
}
DatabaseCommand_UpdateSearchIndex::~DatabaseCommand_UpdateSearchIndex()
{
tDebug() << Q_FUNC_INFO;
}
void
DatabaseCommand_UpdateSearchIndex::exec( DatabaseImpl* db )
{
db->m_fuzzyIndex->beginIndexing();
TomahawkSqlQuery q = db->newquery();
q.exec( "SELECT track.id, track.name, artist.name, artist.id FROM track, artist WHERE artist.id = track.artist" );
while ( q.next() )
{
IndexData ida;
ida.id = q.value( 0 ).toUInt();
ida.artistId = q.value( 3 ).toUInt();
ida.track = q.value( 1 ).toString();
ida.artist = q.value( 2 ).toString();
db->m_fuzzyIndex->appendFields( ida );
}
q.exec( "SELECT album.id, album.name FROM album" );
while ( q.next() )
{
IndexData ida;
ida.id = q.value( 0 ).toUInt();
ida.album = q.value( 1 ).toString();
db->m_fuzzyIndex->appendFields( ida );
}
tDebug( LOGVERBOSE ) << "Building index finished.";
db->m_fuzzyIndex->endIndexing();
}
}
| gpl-3.0 |
venenux/mupen64 | r4300/exception.c | 9 | 4354 | /**
* Mupen64 - exception.c
* Copyright (C) 2002 Hacktarux
*
* Mupen64 homepage: http://mupen64.emulation64.com
* email address: hacktarux@yahoo.fr
*
* If you want to contribute to the project please contact
* me first (maybe someone is already making what you are
* planning to do).
*
*
* This program is free software; you can redistribute it and/
* or modify it under the terms of the GNU General Public Li-
* cence as published by the Free Software Foundation; either
* version 2 of the Licence, or any later version.
*
* This program is distributed in the hope that it will be use-
* ful, but WITHOUT ANY WARRANTY; without even the implied war-
* ranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public Licence for more details.
*
* You should have received a copy of the GNU General Public
* Licence along with this program; if not, write to the Free
* Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139,
* USA.
*
**/
#include "exception.h"
#include "r4300.h"
#include "macros.h"
#include "../memory/memory.h"
#include "recomph.h"
extern unsigned long interp_addr;
void address_error_exception()
{
printf("address_error_exception\n");
stop=1;
}
void TLB_invalid_exception()
{
if (delay_slot)
{
skip_jump = 1;
printf("delay slot\nTLB refill exception\n");
stop=1;
}
printf("TLB invalid exception\n");
stop=1;
}
void XTLB_refill_exception(unsigned long long int addresse)
{
printf("XTLB refill exception\n");
stop=1;
}
void TLB_refill_exception(unsigned long address, int w)
{
int usual_handler = 0, i;
//printf("TLB_refill_exception:%x\n", address);
if (!dynacore && w != 2) update_count();
if (w == 1) Cause = (3 << 2);
else Cause = (2 << 2);
BadVAddr = address;
Context = (Context & 0xFF80000F) | ((address >> 9) & 0x007FFFF0);
EntryHi = address & 0xFFFFE000;
if (Status & 0x2) // Test de EXL
{
if (interpcore) interp_addr = 0x80000180;
else jump_to(0x80000180);
if(delay_slot==1 || delay_slot==3) Cause |= 0x80000000;
else Cause &= 0x7FFFFFFF;
}
else
{
if (!interpcore)
{
if (w!=2)
EPC = PC->addr;
else
EPC = address;
}
else EPC = interp_addr;
Cause &= ~0x80000000;
Status |= 0x2; //EXL=1
if (address >= 0x80000000 && address < 0xc0000000)
usual_handler = 1;
for (i=0; i<32; i++)
{
if (/*tlb_e[i].v_even &&*/ address >= tlb_e[i].start_even &&
address <= tlb_e[i].end_even)
usual_handler = 1;
if (/*tlb_e[i].v_odd &&*/ address >= tlb_e[i].start_odd &&
address <= tlb_e[i].end_odd)
usual_handler = 1;
}
if (usual_handler)
{
if (interpcore) interp_addr = 0x80000180;
else jump_to(0x80000180);
}
else
{
if (interpcore) interp_addr = 0x80000000;
else jump_to(0x80000000);
}
}
if(delay_slot==1 || delay_slot==3)
{
Cause |= 0x80000000;
EPC-=4;
}
else
{
Cause &= 0x7FFFFFFF;
}
if(w != 2) EPC-=4;
if (interpcore) last_addr = interp_addr;
else last_addr = PC->addr;
if (dynacore)
{
dyna_jump();
if (!dyna_interp) delay_slot = 0;
}
if (!dynacore || dyna_interp)
{
dyna_interp = 0;
if (delay_slot)
{
if (interp_addr) skip_jump = interp_addr;
else skip_jump = PC->addr;
next_interupt = 0;
}
}
}
void TLB_mod_exception()
{
printf("TLB mod exception\n");
stop=1;
}
void integer_overflow_exception()
{
printf("integer overflow exception\n");
stop=1;
}
void coprocessor_unusable_exception()
{
printf("coprocessor_unusable_exception\n");
stop=1;
}
void exception_general()
{
update_count();
Status |= 2;
if (!interpcore) EPC = PC->addr;
else EPC = interp_addr;
if(delay_slot==1 || delay_slot==3)
{
Cause |= 0x80000000;
EPC-=4;
}
else
{
Cause &= 0x7FFFFFFF;
}
if (interpcore)
{
interp_addr = 0x80000180;
last_addr = interp_addr;
}
else
{
jump_to(0x80000180);
last_addr = PC->addr;
}
if (dynacore)
{
dyna_jump();
if (!dyna_interp) delay_slot = 0;
}
if (!dynacore || dyna_interp)
{
dyna_interp = 0;
if (delay_slot)
{
if (interpcore) skip_jump = interp_addr;
else skip_jump = PC->addr;
next_interupt = 0;
}
}
}
| gpl-3.0 |
zzq12345/jet | reader-videoguard1.c | 10 | 9651 | #include "globals.h"
#ifdef READER_VIDEOGUARD
#include "reader-common.h"
#include "reader-videoguard-common.h"
static int32_t vg1_do_cmd(struct s_reader *reader, const unsigned char *ins, const unsigned char *txbuff, unsigned char *rxbuff, unsigned char *cta_res)
{
uint16_t cta_lr;
unsigned char ins2[5];
memcpy(ins2, ins, 5);
unsigned char len = 0;
len = ins2[4];
if(txbuff == NULL)
{
if(!write_cmd_vg(ins2, NULL) || !status_ok(cta_res + len))
{
return -1;
}
if(rxbuff != NULL)
{
memcpy(rxbuff, ins2, 5);
memcpy(rxbuff + 5, cta_res, len);
memcpy(rxbuff + 5 + len, cta_res + len, 2);
}
}
else
{
if(!write_cmd_vg(ins2, (uchar *) txbuff) || !status_ok(cta_res))
{
return -2;
}
if(rxbuff != NULL)
{
memcpy(rxbuff, ins2, 5);
memcpy(rxbuff + 5, txbuff, len);
memcpy(rxbuff + 5 + len, cta_res, 2);
}
}
return len;
}
static void read_tiers(struct s_reader *reader)
{
struct videoguard_data *csystem_data = reader->csystem_data;
def_resp;
// const unsigned char ins2a[5] = { 0x48, 0x2a, 0x00, 0x00, 0x00 };
int32_t l;
// return; // Not working at present so just do nothing
// l = vg1_do_cmd(reader, ins2a, NULL, NULL, cta_res);
// if (l < 0 || !status_ok(cta_res + l))
// {
// return;
// }
unsigned char ins76[5] = { 0x48, 0x76, 0x00, 0x00, 0x00 };
ins76[3] = 0x7f;
ins76[4] = 2;
if(!write_cmd_vg(ins76, NULL) || !status_ok(cta_res + 2))
{
return;
}
ins76[3] = 0;
ins76[4] = 0x0a;
int32_t num = cta_res[1];
int32_t i;
cs_clear_entitlement(reader); //reset the entitlements
for(i = 0; i < num; i++)
{
ins76[2] = i;
l = vg1_do_cmd(reader, ins76, NULL, NULL, cta_res);
if(l < 0 || !status_ok(cta_res + l))
{
return;
}
if(cta_res[2] == 0 && cta_res[3] == 0)
{
break;
}
uint16_t tier_id = (cta_res[2] << 8) | cta_res[3];
// add entitlements to list
struct tm timeinfo;
memset(&timeinfo, 0, sizeof(struct tm));
rev_date_calc_tm(&cta_res[4], &timeinfo, csystem_data->card_baseyear);
char tiername[83];
cs_add_entitlement(reader, reader->caid, b2ll(4, reader->prid[0]), tier_id, 0, 0, mktime(&timeinfo), 4, 1);
rdr_log(reader, "tier: %04x, expiry date: %04d/%02d/%02d-%02d:%02d:%02d %s", tier_id, timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec, get_tiername(tier_id, reader->caid, tiername));
}
}
static int32_t videoguard1_card_init(struct s_reader *reader, ATR *newatr)
{
get_hist;
/* 40 B0 09 4A 50 01 4E 5A */
if((hist_size < 7) || (hist[1] != 0xB0) || (hist[3] != 0x4A) || (hist[4] != 0x50))
{
return ERROR;
}
get_atr;
def_resp;
if(!cs_malloc(&reader->csystem_data, sizeof(struct videoguard_data)))
{ return ERROR; }
struct videoguard_data *csystem_data = reader->csystem_data;
/* set information on the card stored in reader-videoguard-common.c */
set_known_card_info(reader, atr, &atr_size);
if((reader->ndsversion != NDS1) && ((csystem_data->card_system_version != NDS1) || (reader->ndsversion != NDSAUTO)))
{
/* known ATR and not NDS1
or unknown ATR and not forced to NDS1
or known NDS1 ATR and forced to another NDS version
... probably not NDS1 */
return ERROR;
}
rdr_log(reader, "type: %s, baseyear: %i", csystem_data->card_desc, csystem_data->card_baseyear);
if(reader->ndsversion == NDS1)
{
rdr_log(reader, "forced to NDS1+");
}
/* NDS1 Class 48 only cards only need a very basic initialisation
NDS1 Class 48 only cards do not respond to vg1_do_cmd(ins7416)
nor do they return list of valid command therefore do not even try
NDS1 Class 48 only cards need to be told the length as (48, ins, 00, 80, 01)
does not return the length */
int32_t l = 0;
unsigned char buff[256];
memset(buff, 0, sizeof(buff));
/* Try to get the boxid from the card, even if BoxID specified in the config file
also used to check if it is an NDS1 card as the returned information will
not be encrypted if it is an NDS1 card */
static const unsigned char ins36[5] = { 0x48, 0x36, 0x00, 0x00, 0x90 };
unsigned char boxID[4];
int32_t boxidOK = 0;
l = vg1_do_cmd(reader, ins36, NULL, buff, cta_res);
if(buff[7] > 0x0F)
{
rdr_log(reader, "class48 ins36: encrypted - therefore not an NDS1 card");
return ERROR;
}
else
{
/* skipping the initial fixed fields: cmdecho (4) + length (1) + encr/rev++ (4) */
int32_t i = 9;
int32_t gotUA = 0;
while(i < l)
{
if(!gotUA && buff[i] < 0xF0) /* then we guess that the next 4 bytes is the UA */
{
gotUA = 1;
i += 4;
}
else
{
switch(buff[i]) /* object length vary depending on type */
{
case 0x00: /* padding */
{
i += 1;
break;
}
case 0xEF: /* card status */
{
i += 3;
break;
}
case 0xD1:
{
i += 4;
break;
}
case 0xDF: /* next server contact */
{
i += 5;
break;
}
case 0xF3: /* boxID */
{
memcpy(&boxID, &buff[i + 1], sizeof(boxID));
boxidOK = 1;
i += 5;
break;
}
case 0xF6:
{
i += 6;
break;
}
case 0xFC: /* No idea seems to with with NDS1 */
{
i += 14;
break;
}
case 0x01: /* date & time */
{
i += 7;
break;
}
case 0xFA:
{
i += 9;
break;
}
case 0x5E:
case 0x67: /* signature */
case 0xDE:
case 0xE2:
case 0xE9: /* tier dates */
case 0xF8: /* Old PPV Event Record */
case 0xFD:
{
i += buff[i + 1] + 2; /* skip length + 2 bytes (type and length) */
break;
}
default: /* default to assume a length byte */
{
rdr_log(reader, "class48 ins36: returned unknown type=0x%02X - parsing may fail", buff[i]);
i += buff[i + 1] + 2;
}
}
}
}
}
// rdr_log(reader, "calculated BoxID: %02X%02X%02X%02X", boxID[0], boxID[1], boxID[2], boxID[3]);
/* the boxid is specified in the config */
if(reader->boxid > 0)
{
int32_t i;
for(i = 0; i < 4; i++)
{
boxID[i] = (reader->boxid >> (8 * (3 - i))) % 0x100;
}
// rdr_log(reader, "config BoxID: %02X%02X%02X%02X", boxID[0], boxID[1], boxID[2], boxID[3]);
}
if(!boxidOK)
{
rdr_log(reader, "no boxID available");
return ERROR;
}
// Send BoxID
static const unsigned char ins4C[5] = { 0x48, 0x4C, 0x00, 0x00, 0x09 };
unsigned char payload4C[9] = { 0, 0, 0, 0, 3, 0, 0, 0, 4 };
memcpy(payload4C, boxID, 4);
if(!write_cmd_vg(ins4C, payload4C) || !status_ok(cta_res + l))
{
rdr_log(reader, "class48 ins4C: sending boxid failed");
return ERROR;
}
static const unsigned char ins58[5] = { 0x48, 0x58, 0x00, 0x00, 0x17 };
l = vg1_do_cmd(reader, ins58, NULL, buff, cta_res);
if(l < 0)
{
rdr_log(reader, "class48 ins58: failed");
return ERROR;
}
memset(reader->hexserial, 0, 8);
memcpy(reader->hexserial + 2, cta_res + 1, 4);
memcpy(reader->sa, cta_res + 1, 3);
// reader->caid = cta_res[24] * 0x100 + cta_res[25];
/* Force caid until can figure out how to get it */
reader->caid = 0x9 * 0x100 + 0x69;
/* we have one provider, 0x0000 */
reader->nprov = 1;
memset(reader->prid, 0x00, sizeof(reader->prid));
rdr_log_sensitive(reader, "type: VideoGuard, caid: %04X, serial: {%02X%02X%02X%02X}, BoxID: {%02X%02X%02X%02X}",
reader->caid, reader->hexserial[2], reader->hexserial[3], reader->hexserial[4], reader->hexserial[5],
boxID[0], boxID[1], boxID[2], boxID[3]);
rdr_log(reader, "ready for requests - this is in testing please send -d 255 logs");
return OK;
}
static int32_t videoguard1_do_ecm(struct s_reader *reader, const ECM_REQUEST *er, struct s_ecm_answer *ea)
{
unsigned char cta_res[CTA_RES_LEN];
unsigned char ins40[5] = { 0x48, 0x40, 0x00, 0x80, 0xFF };
static const unsigned char ins54[5] = { 0x48, 0x54, 0x00, 0x00, 0x0D };
int32_t posECMpart2 = er->ecm[6] + 7;
int32_t lenECMpart2 = er->ecm[posECMpart2];
unsigned char tbuff[264];
unsigned char rbuff[264];
memcpy(&tbuff[0], &(er->ecm[posECMpart2 + 1]), lenECMpart2);
ins40[4] = lenECMpart2;
int32_t l;
l = vg1_do_cmd(reader, ins40, tbuff, NULL, cta_res);
if(l > 0 && status_ok(cta_res))
{
l = vg1_do_cmd(reader, ins54, NULL, rbuff, cta_res);
if(l > 0 && status_ok(cta_res + l))
{
if(!cw_is_valid(rbuff + 5)) //sky cards report 90 00 = ok but send cw = 00 when channel not subscribed
{
rdr_log(reader, "class48 ins54 status 90 00 but cw=00 -> channel not subscribed");
return ERROR;
}
if(er->ecm[0] & 1)
{
memset(ea->cw + 0, 0, 8);
memcpy(ea->cw + 8, rbuff + 5, 8);
}
else
{
memcpy(ea->cw + 0, rbuff + 5, 8);
memset(ea->cw + 8, 0, 8);
}
return OK;
}
}
rdr_log(reader, "class48 ins54 (%d) status not ok %02x %02x", l, cta_res[0], cta_res[1]);
return ERROR;
}
static int32_t videoguard1_do_emm(struct s_reader *reader, EMM_PACKET *ep)
{
return videoguard_do_emm(reader, ep, 0x48, read_tiers, vg1_do_cmd);
}
static int32_t videoguard1_card_info(struct s_reader *reader)
{
/* info is displayed in init, or when processing info */
struct videoguard_data *csystem_data = reader->csystem_data;
rdr_log(reader, "card detected");
rdr_log(reader, "type: %s", csystem_data->card_desc);
read_tiers(reader);
return OK;
}
const struct s_cardsystem reader_videoguard1 =
{
.desc = "videoguard1",
.caids = (uint16_t[]){ 0x09, 0 },
.do_emm = videoguard1_do_emm,
.do_ecm = videoguard1_do_ecm,
.card_info = videoguard1_card_info,
.card_init = videoguard1_card_init,
.get_emm_type = videoguard_get_emm_type,
.get_emm_filter = videoguard_get_emm_filter,
};
#endif
| gpl-3.0 |
cmoski/hudson | lib/SeriesFactorSet.cpp | 11 | 1041 | /*
* Copyright (C) 2007,2008 Alberto Giannetti
*
* This file is part of Hudson.
*
* Hudson 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.
*
* Hudson 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 Hudson. If not, see <http://www.gnu.org/licenses/>.
*/
// Hudson
#include "SeriesFactorSet.hpp"
SeriesFactorSet::SeriesFactorSet( Position::ID id ):
_id(id),
_factor(1)
{
}
bool SeriesFactorSet::insert( const SeriesFactor& sf )
{
if( ! __SeriesFactorSet::insert(sf).second )
return false;
// Cache new overall factor for performance
_factor *= sf.factor();
return true;
}
| gpl-3.0 |
bluegr/scummvm | engines/titanic/support/direct_draw.cpp | 11 | 3110 | /* 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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "titanic/support/direct_draw.h"
#include "titanic/debugger.h"
#include "titanic/titanic.h"
#include "common/debug.h"
#include "engines/util.h"
#include "graphics/pixelformat.h"
#include "graphics/screen.h"
namespace Titanic {
DirectDraw::DirectDraw() : _windowed(false), _width(0), _height(0),
_bpp(0), _numBackSurfaces(0) {
}
void DirectDraw::setDisplayMode(int width, int height, int bpp, int refreshRate) {
debugC(DEBUG_BASIC, kDebugGraphics, "DirectDraw::SetDisplayMode (%d x %d), %d bpp",
width, height, bpp);
assert(bpp == 16);
Graphics::PixelFormat pixelFormat(2, 5, 6, 5, 0, 11, 5, 0, 0);
initGraphics(width, height, &pixelFormat);
}
void DirectDraw::diagnostics() {
debugC(DEBUG_BASIC, kDebugGraphics, "Running DirectDraw Diagnostic...");
}
DirectDrawSurface *DirectDraw::createSurfaceFromDesc(const DDSurfaceDesc &desc) {
DirectDrawSurface *surface = new DirectDrawSurface();
surface->create(desc._w, desc._h, desc._bpp);
return surface;
}
/*------------------------------------------------------------------------*/
DirectDrawManager::DirectDrawManager(TitanicEngine *vm, bool windowed) {
_mainSurface = nullptr;
_backSurfaces[0] = _backSurfaces[1] = nullptr;
_directDraw._windowed = windowed;
}
void DirectDrawManager::initVideo(int width, int height, int bpp, int numBackSurfaces) {
debugC(DEBUG_BASIC, kDebugGraphics, "Initialising video surfaces");
assert(numBackSurfaces == 0);
_directDraw._width = width;
_directDraw._numBackSurfaces = numBackSurfaces;
_directDraw._height = height;
_directDraw._bpp = bpp;
if (_directDraw._windowed) {
initWindowed();
} else {
initFullScreen();
}
}
void DirectDrawManager::initFullScreen() {
debugC(DEBUG_BASIC, kDebugGraphics, "Creating surfaces");
_directDraw.setDisplayMode(_directDraw._width, _directDraw._height,
_directDraw._bpp, 0);
// Set up the main surface to point to the screen
_mainSurface = new DirectDrawSurface();
_mainSurface->create(g_vm->_screen);
}
DirectDrawSurface *DirectDrawManager::createSurface(int w, int h, int bpp, int surfaceNum) {
if (surfaceNum)
return nullptr;
assert(_mainSurface);
return _directDraw.createSurfaceFromDesc(DDSurfaceDesc(w, h, bpp));
}
} // End of namespace Titanic
| gpl-3.0 |
Deiz/naev | src/ntime.c | 12 | 7153 | /*
* See Licensing and Copyright notice in naev.h
*/
/**
* @file ntime.c
*
* @brief Handles the Naev time.
*
* 1 SCU = 5e3 STP = 50e6 STU
* 1 STP = 10e3 STU
* 1 STU = 1 second
*
* Generally displayed as:
* <SCU>:<STP>.<STU> UST
* The number of STU digits can be variable, for example:
*
* 630:3726.1 UST
* 630:3726.12 UST
* 630:3726.124 UST
* 630:3726.1248 UST
* 630:3726.12489 UST
*
* Are all valid.
*
* Acronyms:
* - UST : Universal Synchronized Time
* - STU : Smallest named time unit. Equal to the Earth second.
* - STP : Most commonly used time unit. STPs are the new hours. 1 STP = 10,000 STU (about 2.8 Earth hours).
* - SCU : Used for long-term time periods. 1 SCU = 5000 STP (about 579 Earth days).
*/
#include "ntime.h"
#include "naev.h"
#include <stdio.h>
#include "nstring.h"
#include <stdlib.h>
#include "hook.h"
#include "economy.h"
#define NT_STU_DIV (1000) /* Divider for extracting STU. */
#define NT_STU_DT (30) /* Update rate, how many STU are in a real second. */
#define NT_SCU_STU ((ntime_t)NT_SCU_STP*(ntime_t)NT_STP_STU) /* STU in an SCU */
#define NT_STP_DIV ((ntime_t)NT_STP_STU*(ntime_t)NT_STU_DIV) /* Divider for extracting STP. */
#define NT_SCU_DIV ((ntime_t)NT_SCU_STU*(ntime_t)NT_STU_DIV) /* Divider for extracting STP. */
/**
* @brief Used for storing time increments to not trigger hooks during Lua
* calls and such.
*/
typedef struct NTimeUpdate_s {
struct NTimeUpdate_s *next; /**< Next in the linked list. */
ntime_t inc; /**< Time increment associated. */
} NTimeUpdate_t;
static NTimeUpdate_t *ntime_inclist = NULL; /**< Time increment list. */
static ntime_t naev_time = 0; /**< Contains the current time in mSTU. */
static double naev_remainder = 0.; /**< Remainder when updating, to try to keep in perfect sync. */
static int ntime_enable = 1; /** Allow updates? */
/**
* @brief Updatse the time based on realtime.
*/
void ntime_update( double dt )
{
double dtt, tu;
ntime_t inc;
/* Only if we need to update. */
if (!ntime_enable)
return;
/* Calculate the effective time. */
dtt = naev_remainder + dt*NT_STU_DT*NT_STU_DIV;
/* Time to update. */
tu = floor( dtt );
inc = (ntime_t) tu;
naev_remainder = dtt - tu; /* Leave remainder. */
/* Increment. */
naev_time += inc;
hooks_updateDate( inc );
}
/**
* @brief Creates a time structure.
*/
ntime_t ntime_create( int scu, int stp, int stu )
{
ntime_t tscu, tstp, tstu;
tscu = scu;
tstp = stp;
tstu = stu;
return tscu*NT_SCU_DIV + tstp*NT_STP_DIV + tstu*NT_STU_DIV;
}
/**
* @brief Gets the current time.
*
* @return The current time in mSTU.
*/
ntime_t ntime_get (void)
{
return naev_time;
}
/**
* @brief Gets the current time broken into individual components.
*/
void ntime_getR( int *scu, int *stp, int *stu, double *rem )
{
*scu = ntime_getSCU( naev_time );
*stp = ntime_getSTP( naev_time );
*stu = ntime_getSTU( naev_time );
*rem = ntime_getRemainder( naev_time ) + naev_remainder;
}
/**
* @brief Gets the SCU of a time.
*/
int ntime_getSCU( ntime_t t )
{
return (t / NT_SCU_DIV);
}
/**
* @brief Gets the STP of a time.
*/
int ntime_getSTP( ntime_t t )
{
return (t / NT_STP_DIV) % NT_SCU_STP;
}
/**
* @brief Gets the STU of a time.
*/
int ntime_getSTU( ntime_t t )
{
return (t / NT_STU_DIV) % NT_STP_STU;
}
/**
* @brief Converts the time to STU.
* @param t Time to convert.
* @return Time in STU.
*/
double ntime_convertSTU( ntime_t t )
{
return ((double)t / (double)NT_STU_DIV);
}
/**
* @brief Gets the remainder.
*/
double ntime_getRemainder( ntime_t t )
{
return (double)(t % NT_STU_DIV);
}
/**
* @brief Gets the time in a pretty human readable format.
*
* @param t Time to print (in STU), if 0 it'll use the current time.
* @param d Number of digits to use.
* @return The time in a human readable format (must free).
*/
char* ntime_pretty( ntime_t t, int d )
{
char str[64];
ntime_prettyBuf( str, sizeof(str), t, d );
return strdup(str);
}
/**
* @brief Gets the time in a pretty human readable format filling a preset buffer.
*
* @param[out] str Buffer to use.
* @param max Maximum length of the buffer (recommended 64).
* @param t Time to print (in STU), if 0 it'll use the current time.
* @param d Number of digits to use.
* @return The time in a human readable format (must free).
*/
void ntime_prettyBuf( char *str, int max, ntime_t t, int d )
{
ntime_t nt;
int scu, stp, stu;
if (t==0)
nt = naev_time;
else
nt = t;
/* UST (Universal Synchronized Time) - unit is STU (Synchronized Time Unit) */
scu = ntime_getSCU( nt );
stp = ntime_getSTP( nt );
stu = ntime_getSTU( nt );
if ((scu==0) && (stp==0)) /* only STU */
nsnprintf( str, max, "%04d STU", stu );
else if ((scu==0) || (d==0))
nsnprintf( str, max, "%.*f STP", d, stp + 0.0001 * stu );
else /* UST format */
nsnprintf( str, max, "UST %d:%.*f", scu, d, stp + 0.0001 * stu );
}
/**
* @brief Sets the time absolutely, does NOT generate an event, used at init.
*
* @param t Absolute time to set to in STU.
*/
void ntime_set( ntime_t t )
{
naev_time = t;
naev_remainder = 0.;
}
/**
* @brief Loads time including remainder.
*/
void ntime_setR( int scu, int stp, int stu, double rem )
{
naev_time = ntime_create( scu, stp, stu );
naev_time += floor(rem);
naev_remainder = fmod( rem, 1. );
}
/**
* @brief Sets the time relatively.
*
* @param t Time modifier in STU.
*/
void ntime_inc( ntime_t t )
{
naev_time += t;
economy_update( t );
/* Run hooks. */
if (t > 0)
hooks_updateDate( t );
}
/**
* @brief Allows the time to update when the game is updating.
*
* @param enable Whether or not to enable time updating.
*/
void ntime_allowUpdate( int enable )
{
ntime_enable = enable;
}
/**
* @brief Sets the time relatively.
*
* This does NOT call hooks and such, they must be run with ntime_refresh
* manually later.
*
* @param t Time modifier in STU.
*/
void ntime_incLagged( ntime_t t )
{
NTimeUpdate_t *ntu, *iter;
/* Create the time increment. */
ntu = malloc(sizeof(NTimeUpdate_t));
ntu->next = NULL;
ntu->inc = t;
/* Only member. */
if (ntime_inclist == NULL)
ntime_inclist = ntu;
else {
/* Find end of list. */
for (iter = ntime_inclist; iter->next != NULL; iter = iter->next);
/* Append to end. */
iter->next = ntu;
}
}
/**
* @brief Checks to see if ntime has any hooks pending to run.
*/
void ntime_refresh (void)
{
NTimeUpdate_t *ntu;
/* We have to run all the increments one by one to ensure all hooks get
* run and that no collisions occur. */
while (ntime_inclist != NULL) {
ntu = ntime_inclist;
/* Run hook stuff and actually update time. */
naev_time += ntu->inc;
economy_update( ntu->inc );
/* Remove the increment. */
ntime_inclist = ntu->next;
/* Free the increment. */
free(ntu);
}
}
| gpl-3.0 |
RobsonRojas/frertos-udemy | FreeRTOSKeil/FreeRTOSv9.0.0/FreeRTOS/Demo/CORTEX_M4F_MSP432_LaunchPad_IAR_CCS_Keil/driverlib/timer32.c | 12 | 4997 | /*
* -------------------------------------------
* MSP432 DriverLib - v3_10_00_09
* -------------------------------------------
*
* --COPYRIGHT--,BSD,BSD
* Copyright (c) 2014, Texas Instruments Incorporated
* 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 Texas Instruments Incorporated nor the names of
* its contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
* OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
* OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
* EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
* --/COPYRIGHT--*/
#include <timer32.h>
#include <interrupt.h>
#include <debug.h>
void Timer32_initModule(uint32_t timer, uint32_t preScaler, uint32_t resolution,
uint32_t mode)
{
/* Setting up one shot or continuous mode */
if (mode == TIMER32_PERIODIC_MODE)
BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_MODE_OFS)
= 1;
else if (mode == TIMER32_FREE_RUN_MODE)
BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_MODE_OFS)
= 0;
else
ASSERT(false);
/* Setting the resolution of the timer */
if (resolution == TIMER32_1_MODULE6BIT)
BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_SIZE_OFS)
= 0;
else if (resolution == TIMER32_32BIT)
BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_SIZE_OFS)
= 1;
else
ASSERT(false);
/* Setting the PreScaler */
ASSERT(
resolution == TIMER32_PRESCALER_1
|| resolution == TIMER32_PRESCALER_16
|| resolution == TIMER32_PRESCALER_256);
TIMER32_CMSIS(timer)->CONTROL = TIMER32_CMSIS(timer)->CONTROL
& (~TIMER32_CONTROL_PRESCALE_MASK) | preScaler;
}
void Timer32_setCount(uint32_t timer, uint32_t count)
{
if (!BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_SIZE_OFS)
&& (count > UINT16_MAX))
TIMER32_CMSIS(timer)->LOAD = UINT16_MAX;
else
TIMER32_CMSIS(timer)->LOAD = count;
}
void Timer32_setCountInBackground(uint32_t timer, uint32_t count)
{
if (!BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_SIZE_OFS)
&& (count > UINT16_MAX))
TIMER32_CMSIS(timer)->BGLOAD = UINT16_MAX;
else
TIMER32_CMSIS(timer)->BGLOAD = count;
}
uint32_t Timer32_getValue(uint32_t timer)
{
return TIMER32_CMSIS(timer)->VALUE;
}
void Timer32_startTimer(uint32_t timer, bool oneShot)
{
ASSERT(timer == TIMER32_0_MODULE || timer == TIMER32_1_MODULE);
if (oneShot)
BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_ONESHOT_OFS)
= 1;
else
BITBAND_PERI(TIMER32_CMSIS(timer)->CONTROL, TIMER32_CONTROL_ONESHOT_OFS)
= 0;
TIMER32_CMSIS(timer)->CONTROL |= TIMER32_CONTROL_ENABLE;
}
void Timer32_haltTimer(uint32_t timer)
{
ASSERT(timer == TIMER32_0_MODULE || timer == TIMER32_1_MODULE);
TIMER32_CMSIS(timer)->CONTROL &= ~TIMER32_CONTROL_ENABLE;
}
void Timer32_enableInterrupt(uint32_t timer)
{
TIMER32_CMSIS(timer)->CONTROL |= TIMER32_CONTROL_IE;
}
void Timer32_disableInterrupt(uint32_t timer)
{
TIMER32_CMSIS(timer)->CONTROL &= ~TIMER32_CONTROL_IE;
}
void Timer32_clearInterruptFlag(uint32_t timer)
{
TIMER32_CMSIS(timer)->INTCLR |= 0x01;
}
uint32_t Timer32_getInterruptStatus(uint32_t timer)
{
return TIMER32_CMSIS(timer)->MIS;
}
void Timer32_registerInterrupt(uint32_t timerInterrupt,
void (*intHandler)(void))
{
Interrupt_registerInterrupt(timerInterrupt, intHandler);
Interrupt_enableInterrupt(timerInterrupt);
}
void Timer32_unregisterInterrupt(uint32_t timerInterrupt)
{
Interrupt_disableInterrupt(timerInterrupt);
Interrupt_unregisterInterrupt(timerInterrupt);
}
| gpl-3.0 |
bcareil/endless-sky | source/Angle.cpp | 14 | 2699 | /* Angle.cpp
Copyright (c) 2014 by Michael Zahniser
Endless Sky 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.
Endless Sky 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 "Angle.h"
#include "pi.h"
#include "Random.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <vector>
using namespace std;
namespace {
// Suppose you want to be able to turn 360 degrees in one second. Then you are
// turning 6 degrees per time step. If the Angle lookup is 2^16 steps, then 6
// degrees is 1092 steps, and your turn speed is accurate to +- 0.05%. That seems
// plenty accurate to me. At that step size, the lookup table is exactly 1 MB.
static const int32_t STEPS = 0x10000;
static const int32_t MASK = STEPS - 1;
double DEG_TO_STEP = STEPS / 360.;
double STEP_TO_RAD = PI / (STEPS / 2);
}
Angle Angle::Random()
{
return Angle(static_cast<int32_t>(Random::Int(STEPS)));
}
Angle Angle::Random(double range)
{
int64_t steps = fabs(range) * DEG_TO_STEP + .5;
int32_t mod = min(steps, int64_t(STEPS - 1)) + 1;
return Angle(static_cast<int32_t>(Random::Int(mod)));
}
Angle::Angle()
: angle(0)
{
}
Angle::Angle(double degrees)
: angle(static_cast<int64_t>(degrees * DEG_TO_STEP + .5) & MASK)
{
}
Angle Angle::operator+(const Angle &other) const
{
Angle result = *this;
result += other;
return result;
}
Angle &Angle::operator+=(const Angle &other)
{
angle += other.angle;
angle &= MASK;
return *this;
}
Angle Angle::operator-(const Angle &other) const
{
Angle result = *this;
result -= other;
return result;
}
Angle &Angle::operator-=(const Angle &other)
{
angle -= other.angle;
angle &= MASK;
return *this;
}
Angle Angle::operator-() const
{
return Angle((-angle) & MASK);
}
Point Angle::Unit() const
{
static vector<Point> cache;
if(cache.empty())
{
cache.reserve(STEPS);
for(int i = 0; i < STEPS; ++i)
{
double radians = i * STEP_TO_RAD;
cache.emplace_back(sin(radians), -cos(radians));
}
}
return cache[angle];
}
// Return a point rotated by this angle around (0, 0).
Point Angle::Rotate(const Point &point) const
{
if(!point)
return point;
Point unit = Unit();
unit.Set(-unit.Y() * point.X() - unit.X() * point.Y(),
-unit.Y() * point.Y() + unit.X() * point.X());
return unit;
}
Angle::Angle(int32_t angle)
: angle(angle)
{
}
| gpl-3.0 |
ccalleu/halo-halo | CSipSimple/jni/pjsip/sources/pjmedia/src/pjmedia/splitcomb.c | 16 | 23321 | /* $Id: splitcomb.c 3664 2011-07-19 03:42:28Z nanang $ */
/*
* Copyright (C) 2008-2011 Teluu Inc. (http://www.teluu.com)
* Copyright (C) 2003-2008 Benny Prijono <benny@prijono.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 <pjmedia/splitcomb.h>
#include <pjmedia/delaybuf.h>
#include <pjmedia/errno.h>
#include <pj/assert.h>
#include <pj/log.h>
#include <pj/pool.h>
#define SIGNATURE PJMEDIA_SIG_PORT_SPLIT_COMB
#define SIGNATURE_PORT PJMEDIA_SIG_PORT_SPLIT_COMB_P
#define THIS_FILE "splitcomb.c"
#define TMP_SAMP_TYPE pj_int16_t
/* Maximum number of channels. */
#define MAX_CHANNELS 16
/* Maximum number of buffers to be accommodated by delaybuf */
#define MAX_BUF_CNT PJMEDIA_SOUND_BUFFER_COUNT
/* Maximum number of burst before we pause the media flow */
#define MAX_BURST (buf_cnt + 6)
/* Maximum number of NULL frames received before we pause the
* media flow.
*/
#define MAX_NULL_FRAMES (rport->max_burst)
/* Operations */
#define OP_PUT (1)
#define OP_GET (-1)
/*
* Media flow directions:
*
* put_frame() +-----+
* UPSTREAM ------------>|split|<--> DOWNSTREAM
* <------------|comb |
* get_frame() +-----+
*
*/
enum sc_dir
{
/* This is the media direction from the splitcomb to the
* downstream port(s), which happens when:
* - put_frame() is called to the splitcomb
* - get_frame() is called to the reverse channel port.
*/
DIR_DOWNSTREAM,
/* This is the media direction from the downstream port to
* the splitcomb, which happens when:
* - get_frame() is called to the splitcomb
* - put_frame() is called to the reverse channel port.
*/
DIR_UPSTREAM
};
/*
* This structure describes the splitter/combiner.
*/
struct splitcomb
{
pjmedia_port base;
unsigned options;
/* Array of ports, one for each channel */
struct {
pjmedia_port *port;
pj_bool_t reversed;
} port_desc[MAX_CHANNELS];
/* Temporary buffers needed to extract mono frame from
* multichannel frame. We could use stack for this, but this
* way it should be safer for devices with small stack size.
*/
TMP_SAMP_TYPE *get_buf;
TMP_SAMP_TYPE *put_buf;
};
/*
* This structure describes reverse port.
*/
struct reverse_port
{
pjmedia_port base;
struct splitcomb*parent;
unsigned ch_num;
/* Maximum burst before media flow is suspended.
* With reverse port, it's possible that either end of the
* port doesn't actually process the media flow (meaning, it
* stops calling get_frame()/put_frame()). When this happens,
* the other end will encounter excessive underflow or overflow,
* depending on which direction is not actively processed by
* the stopping end.
*
* To avoid excessive underflow/overflow, the media flow will
* be suspended once underflow/overflow goes over this max_burst
* limit.
*/
int max_burst;
/* When the media interface port of the splitcomb or the reverse
* channel port is registered to conference bridge, the bridge
* will transmit NULL frames to the media port when the media
* port is not receiving any audio from other slots (for example,
* when no other slots are connected to the media port).
*
* When this happens, we will generate zero frame to our buffer,
* to avoid underflow/overflow. But after too many NULL frames
* are received, we will pause the media flow instead, to save
* some processing.
*
* This value controls how many NULL frames can be received
* before we suspend media flow for a particular direction.
*/
unsigned max_null_frames;
/* A reverse port need a temporary buffer to store frames
* (because of the different phase, see splitcomb.h for details).
* Since we can not expect get_frame() and put_frame() to be
* called evenly one after another, we use delay buffers to
* accomodate the burst.
*
* We maintain state for each direction, hence the array. The
* array is indexed by direction (sc_dir).
*/
struct {
/* The delay buffer where frames will be stored */
pjmedia_delay_buf *dbuf;
/* Flag to indicate that audio flow on this direction
* is currently being suspended (perhaps because nothing
* is processing the frame on the other end).
*/
pj_bool_t paused;
/* Operation level. When the level exceeds a maximum value,
* the media flow on this direction will be paused.
*/
int level;
/* Timestamp. */
pj_timestamp ts;
/* Number of NULL frames transmitted to this port so far.
* NULL frame indicate that nothing is transmitted, and
* once we get too many of this, we should pause the media
* flow to reduce processing.
*/
unsigned null_cnt;
} buf[2];
/* Must have temporary put buffer for the delay buf,
* unfortunately.
*/
pj_int16_t *tmp_up_buf;
};
/*
* Prototypes.
*/
static pj_status_t put_frame(pjmedia_port *this_port,
pjmedia_frame *frame);
static pj_status_t get_frame(pjmedia_port *this_port,
pjmedia_frame *frame);
static pj_status_t on_destroy(pjmedia_port *this_port);
static pj_status_t rport_put_frame(pjmedia_port *this_port,
pjmedia_frame *frame);
static pj_status_t rport_get_frame(pjmedia_port *this_port,
pjmedia_frame *frame);
static pj_status_t rport_on_destroy(pjmedia_port *this_port);
/*
* Create the splitter/combiner.
*/
PJ_DEF(pj_status_t) pjmedia_splitcomb_create( pj_pool_t *pool,
unsigned clock_rate,
unsigned channel_count,
unsigned samples_per_frame,
unsigned bits_per_sample,
unsigned options,
pjmedia_port **p_splitcomb)
{
const pj_str_t name = pj_str("splitcomb");
struct splitcomb *sc;
/* Sanity check */
PJ_ASSERT_RETURN(pool && clock_rate && channel_count &&
samples_per_frame && bits_per_sample &&
p_splitcomb, PJ_EINVAL);
/* Only supports 16 bits per sample */
PJ_ASSERT_RETURN(bits_per_sample == 16, PJ_EINVAL);
*p_splitcomb = NULL;
/* Create the splitter/combiner structure */
sc = PJ_POOL_ZALLOC_T(pool, struct splitcomb);
PJ_ASSERT_RETURN(sc != NULL, PJ_ENOMEM);
/* Create temporary buffers */
sc->get_buf = (TMP_SAMP_TYPE*)
pj_pool_alloc(pool, samples_per_frame *
sizeof(TMP_SAMP_TYPE) /
channel_count);
PJ_ASSERT_RETURN(sc->get_buf, PJ_ENOMEM);
sc->put_buf = (TMP_SAMP_TYPE*)
pj_pool_alloc(pool, samples_per_frame *
sizeof(TMP_SAMP_TYPE) /
channel_count);
PJ_ASSERT_RETURN(sc->put_buf, PJ_ENOMEM);
/* Save options */
sc->options = options;
/* Initialize port */
pjmedia_port_info_init(&sc->base.info, &name, SIGNATURE, clock_rate,
channel_count, bits_per_sample, samples_per_frame);
sc->base.put_frame = &put_frame;
sc->base.get_frame = &get_frame;
sc->base.on_destroy = &on_destroy;
/* Init ports array */
/*
sc->port_desc = pj_pool_zalloc(pool, channel_count*sizeof(*sc->port_desc));
*/
pj_bzero(sc->port_desc, sizeof(sc->port_desc));
/* Done for now */
*p_splitcomb = &sc->base;
return PJ_SUCCESS;
}
/*
* Attach media port with the same phase as the splitter/combiner.
*/
PJ_DEF(pj_status_t) pjmedia_splitcomb_set_channel( pjmedia_port *splitcomb,
unsigned ch_num,
unsigned options,
pjmedia_port *port)
{
struct splitcomb *sc = (struct splitcomb*) splitcomb;
/* Sanity check */
PJ_ASSERT_RETURN(splitcomb && port, PJ_EINVAL);
/* Make sure this is really a splitcomb port */
PJ_ASSERT_RETURN(sc->base.info.signature == SIGNATURE, PJ_EINVAL);
/* Check the channel number */
PJ_ASSERT_RETURN(ch_num < PJMEDIA_PIA_CCNT(&sc->base.info), PJ_EINVAL);
/* options is unused for now */
PJ_UNUSED_ARG(options);
sc->port_desc[ch_num].port = port;
sc->port_desc[ch_num].reversed = PJ_FALSE;
return PJ_SUCCESS;
}
/*
* Create reverse phase port for the specified channel.
*/
PJ_DEF(pj_status_t) pjmedia_splitcomb_create_rev_channel( pj_pool_t *pool,
pjmedia_port *splitcomb,
unsigned ch_num,
unsigned options,
pjmedia_port **p_chport)
{
const pj_str_t name = pj_str("scomb-rev");
struct splitcomb *sc = (struct splitcomb*) splitcomb;
struct reverse_port *rport;
unsigned buf_cnt;
const pjmedia_audio_format_detail *sc_afd, *p_afd;
pjmedia_port *port;
pj_status_t status;
/* Sanity check */
PJ_ASSERT_RETURN(pool && splitcomb, PJ_EINVAL);
/* Make sure this is really a splitcomb port */
PJ_ASSERT_RETURN(sc->base.info.signature == SIGNATURE, PJ_EINVAL);
/* Check the channel number */
PJ_ASSERT_RETURN(ch_num < PJMEDIA_PIA_CCNT(&sc->base.info), PJ_EINVAL);
/* options is unused for now */
PJ_UNUSED_ARG(options);
sc_afd = pjmedia_format_get_audio_format_detail(&splitcomb->info.fmt, 1);
/* Create the port */
rport = PJ_POOL_ZALLOC_T(pool, struct reverse_port);
rport->parent = sc;
rport->ch_num = ch_num;
/* Initialize port info... */
port = &rport->base;
pjmedia_port_info_init(&port->info, &name, SIGNATURE_PORT,
sc_afd->clock_rate, 1,
sc_afd->bits_per_sample,
PJMEDIA_PIA_SPF(&splitcomb->info) /
sc_afd->channel_count);
p_afd = pjmedia_format_get_audio_format_detail(&port->info.fmt, 1);
/* ... and the callbacks */
port->put_frame = &rport_put_frame;
port->get_frame = &rport_get_frame;
port->on_destroy = &rport_on_destroy;
/* Buffer settings */
buf_cnt = options & 0xFF;
if (buf_cnt == 0)
buf_cnt = MAX_BUF_CNT;
rport->max_burst = MAX_BURST;
rport->max_null_frames = MAX_NULL_FRAMES;
/* Create downstream/put buffers */
status = pjmedia_delay_buf_create(pool, "scombdb-dn",
p_afd->clock_rate,
PJMEDIA_PIA_SPF(&port->info),
p_afd->channel_count,
buf_cnt * p_afd->frame_time_usec / 1000,
0, &rport->buf[DIR_DOWNSTREAM].dbuf);
if (status != PJ_SUCCESS) {
return status;
}
/* Create upstream/get buffers */
status = pjmedia_delay_buf_create(pool, "scombdb-up",
p_afd->clock_rate,
PJMEDIA_PIA_SPF(&port->info),
p_afd->channel_count,
buf_cnt * p_afd->frame_time_usec / 1000,
0, &rport->buf[DIR_UPSTREAM].dbuf);
if (status != PJ_SUCCESS) {
pjmedia_delay_buf_destroy(rport->buf[DIR_DOWNSTREAM].dbuf);
return status;
}
/* And temporary upstream/get buffer */
rport->tmp_up_buf = (pj_int16_t*)
pj_pool_alloc(pool,
PJMEDIA_PIA_AVG_FSZ(&port->info));
/* Save port in the splitcomb */
sc->port_desc[ch_num].port = &rport->base;
sc->port_desc[ch_num].reversed = PJ_TRUE;
/* Done */
*p_chport = port;
return status;
}
/*
* Extract one mono frame from a multichannel frame.
*/
static void extract_mono_frame( const pj_int16_t *in,
pj_int16_t *out,
unsigned ch,
unsigned ch_cnt,
unsigned samples_count)
{
unsigned i;
in += ch;
for (i=0; i<samples_count; ++i) {
*out++ = *in;
in += ch_cnt;
}
}
/*
* Put one mono frame into a multichannel frame
*/
static void store_mono_frame( const pj_int16_t *in,
pj_int16_t *out,
unsigned ch,
unsigned ch_cnt,
unsigned samples_count)
{
unsigned i;
out += ch;
for (i=0; i<samples_count; ++i) {
*out = *in++;
out += ch_cnt;
}
}
/* Update operation on the specified direction */
static void op_update(struct reverse_port *rport, int dir, int op)
{
char *dir_name[2] = {"downstream", "upstream"};
rport->buf[dir].level += op;
if (op == OP_PUT) {
rport->buf[dir].ts.u64 += PJMEDIA_PIA_SPF(&rport->base.info);
}
if (rport->buf[dir].paused) {
if (rport->buf[dir].level < -rport->max_burst) {
/* Prevent the level from overflowing and resets back to zero */
rport->buf[dir].level = -rport->max_burst;
} else if (rport->buf[dir].level > rport->max_burst) {
/* Prevent the level from overflowing and resets back to zero */
rport->buf[dir].level = rport->max_burst;
} else {
/* Level has fallen below max level, we can resume
* media flow.
*/
PJ_LOG(5,(rport->base.info.name.ptr,
"Resuming media flow on %s direction (level=%d)",
dir_name[dir], rport->buf[dir].level));
rport->buf[dir].level = 0;
rport->buf[dir].paused = PJ_FALSE;
//This will cause disruption in audio, and it seems to be
//working fine without this anyway, so we disable it for now.
//pjmedia_delay_buf_learn(rport->buf[dir].dbuf);
}
} else {
if (rport->buf[dir].level >= rport->max_burst ||
rport->buf[dir].level <= -rport->max_burst)
{
/* Level has reached maximum level, the other side of
* rport is not sending/retrieving frames. Pause the
* rport on this direction.
*/
PJ_LOG(5,(rport->base.info.name.ptr,
"Pausing media flow on %s direction (level=%d)",
dir_name[dir], rport->buf[dir].level));
rport->buf[dir].paused = PJ_TRUE;
}
}
}
/*
* "Write" a multichannel frame downstream. This would split
* the multichannel frame into individual mono channel, and write
* it to the appropriate port.
*/
static pj_status_t put_frame(pjmedia_port *this_port,
pjmedia_frame *frame)
{
struct splitcomb *sc = (struct splitcomb*) this_port;
unsigned ch;
/* Handle null frame */
if (frame->type == PJMEDIA_FRAME_TYPE_NONE) {
for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) {
pjmedia_port *port = sc->port_desc[ch].port;
if (!port) continue;
if (!sc->port_desc[ch].reversed) {
pjmedia_port_put_frame(port, frame);
} else {
struct reverse_port *rport = (struct reverse_port*)port;
/* Update the number of NULL frames received. Once we have too
* many of this, we'll stop calling op_update() to let the
* media be suspended.
*/
if (++rport->buf[DIR_DOWNSTREAM].null_cnt >
rport->max_null_frames)
{
/* Prevent the counter from overflowing and resetting
* back to zero
*/
rport->buf[DIR_DOWNSTREAM].null_cnt =
rport->max_null_frames + 1;
continue;
}
/* Write zero port to delaybuf so that it doesn't underflow.
* If we don't do this, get_frame() on this direction will
* cause delaybuf to generate missing frame and the last
* frame transmitted to delaybuf will be replayed multiple
* times, which doesn't sound good.
*/
/* Update rport state. */
op_update(rport, DIR_DOWNSTREAM, OP_PUT);
/* Discard frame if rport is paused on this direction */
if (rport->buf[DIR_DOWNSTREAM].paused)
continue;
/* Generate zero frame. */
pjmedia_zero_samples(sc->put_buf,
PJMEDIA_PIA_SPF(&this_port->info));
/* Put frame to delay buffer */
pjmedia_delay_buf_put(rport->buf[DIR_DOWNSTREAM].dbuf,
sc->put_buf);
}
}
return PJ_SUCCESS;
}
/* Not sure how we would handle partial frame, so better reject
* it for now.
*/
PJ_ASSERT_RETURN(frame->size == PJMEDIA_PIA_AVG_FSZ(&this_port->info),
PJ_EINVAL);
/*
* Write mono frame into each channels
*/
for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) {
pjmedia_port *port = sc->port_desc[ch].port;
if (!port)
continue;
/* Extract the mono frame to temporary buffer */
extract_mono_frame((const pj_int16_t*)frame->buf, sc->put_buf, ch,
PJMEDIA_PIA_CCNT(&this_port->info),
frame->size * 8 /
PJMEDIA_PIA_BITS(&this_port->info) /
PJMEDIA_PIA_CCNT(&this_port->info));
if (!sc->port_desc[ch].reversed) {
/* Write to normal port */
pjmedia_frame mono_frame;
mono_frame.buf = sc->put_buf;
mono_frame.size = frame->size / PJMEDIA_PIA_CCNT(&this_port->info);
mono_frame.type = frame->type;
mono_frame.timestamp.u64 = frame->timestamp.u64;
/* Write */
pjmedia_port_put_frame(port, &mono_frame);
} else {
/* Write to reversed phase port */
struct reverse_port *rport = (struct reverse_port*)port;
/* Reset NULL frame counter */
rport->buf[DIR_DOWNSTREAM].null_cnt = 0;
/* Update rport state. */
op_update(rport, DIR_DOWNSTREAM, OP_PUT);
if (!rport->buf[DIR_DOWNSTREAM].paused) {
pjmedia_delay_buf_put(rport->buf[DIR_DOWNSTREAM].dbuf,
sc->put_buf);
}
}
}
return PJ_SUCCESS;
}
/*
* Get a multichannel frame upstream.
* This will get mono channel frame from each port and put the
* mono frame into the multichannel frame.
*/
static pj_status_t get_frame(pjmedia_port *this_port,
pjmedia_frame *frame)
{
struct splitcomb *sc = (struct splitcomb*) this_port;
unsigned ch;
pj_bool_t has_frame = PJ_FALSE;
/* Read frame from each port */
for (ch=0; ch < PJMEDIA_PIA_CCNT(&this_port->info); ++ch) {
pjmedia_port *port = sc->port_desc[ch].port;
pjmedia_frame mono_frame;
pj_status_t status;
if (!port) {
pjmedia_zero_samples(sc->get_buf,
PJMEDIA_PIA_SPF(&this_port->info) /
PJMEDIA_PIA_CCNT(&this_port->info));
} else if (sc->port_desc[ch].reversed == PJ_FALSE) {
/* Read from normal port */
mono_frame.buf = sc->get_buf;
mono_frame.size = PJMEDIA_PIA_AVG_FSZ(&port->info);
mono_frame.timestamp.u64 = frame->timestamp.u64;
status = pjmedia_port_get_frame(port, &mono_frame);
if (status != PJ_SUCCESS ||
mono_frame.type != PJMEDIA_FRAME_TYPE_AUDIO)
{
pjmedia_zero_samples(sc->get_buf,
PJMEDIA_PIA_SPF(&port->info));
}
frame->timestamp.u64 = mono_frame.timestamp.u64;
} else {
/* Read from temporary buffer for reverse port */
struct reverse_port *rport = (struct reverse_port*)port;
/* Update rport state. */
op_update(rport, DIR_UPSTREAM, OP_GET);
if (!rport->buf[DIR_UPSTREAM].paused) {
pjmedia_delay_buf_get(rport->buf[DIR_UPSTREAM].dbuf,
sc->get_buf);
} else {
pjmedia_zero_samples(sc->get_buf,
PJMEDIA_PIA_SPF(&port->info));
}
frame->timestamp.u64 = rport->buf[DIR_UPSTREAM].ts.u64;
}
/* Combine the mono frame into multichannel frame */
store_mono_frame(sc->get_buf,
(pj_int16_t*)frame->buf, ch,
PJMEDIA_PIA_CCNT(&this_port->info),
PJMEDIA_PIA_SPF(&this_port->info) /
PJMEDIA_PIA_CCNT(&this_port->info));
has_frame = PJ_TRUE;
}
/* Return NO_FRAME is we don't get any frames from downstream ports */
if (has_frame) {
frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info);
} else
frame->type = PJMEDIA_FRAME_TYPE_NONE;
return PJ_SUCCESS;
}
static pj_status_t on_destroy(pjmedia_port *this_port)
{
/* Nothing to do for the splitcomb
* Reverse ports must be destroyed separately.
*/
PJ_UNUSED_ARG(this_port);
return PJ_SUCCESS;
}
/*
* Put a frame in the reverse port (upstream direction). This frame
* will be picked up by get_frame() above.
*/
static pj_status_t rport_put_frame(pjmedia_port *this_port,
pjmedia_frame *frame)
{
struct reverse_port *rport = (struct reverse_port*) this_port;
pj_assert(frame->size <= PJMEDIA_PIA_AVG_FSZ(&rport->base.info));
/* Handle NULL frame */
if (frame->type != PJMEDIA_FRAME_TYPE_AUDIO) {
/* Update the number of NULL frames received. Once we have too
* many of this, we'll stop calling op_update() to let the
* media be suspended.
*/
if (++rport->buf[DIR_UPSTREAM].null_cnt > rport->max_null_frames) {
/* Prevent the counter from overflowing and resetting back
* to zero
*/
rport->buf[DIR_UPSTREAM].null_cnt = rport->max_null_frames + 1;
return PJ_SUCCESS;
}
/* Write zero port to delaybuf so that it doesn't underflow.
* If we don't do this, get_frame() on this direction will
* cause delaybuf to generate missing frame and the last
* frame transmitted to delaybuf will be replayed multiple
* times, which doesn't sound good.
*/
/* Update rport state. */
op_update(rport, DIR_UPSTREAM, OP_PUT);
/* Discard frame if rport is paused on this direction */
if (rport->buf[DIR_UPSTREAM].paused)
return PJ_SUCCESS;
/* Generate zero frame. */
pjmedia_zero_samples(rport->tmp_up_buf,
PJMEDIA_PIA_SPF(&this_port->info));
/* Put frame to delay buffer */
return pjmedia_delay_buf_put(rport->buf[DIR_UPSTREAM].dbuf,
rport->tmp_up_buf);
}
/* Not sure how to handle partial frame, so better reject for now */
PJ_ASSERT_RETURN(frame->size == PJMEDIA_PIA_AVG_FSZ(&this_port->info),
PJ_EINVAL);
/* Reset NULL frame counter */
rport->buf[DIR_UPSTREAM].null_cnt = 0;
/* Update rport state. */
op_update(rport, DIR_UPSTREAM, OP_PUT);
/* Discard frame if rport is paused on this direction */
if (rport->buf[DIR_UPSTREAM].paused)
return PJ_SUCCESS;
/* Unfortunately must copy to temporary buffer since delay buf
* modifies the frame content.
*/
pjmedia_copy_samples(rport->tmp_up_buf, (const pj_int16_t*)frame->buf,
PJMEDIA_PIA_SPF(&this_port->info));
/* Put frame to delay buffer */
return pjmedia_delay_buf_put(rport->buf[DIR_UPSTREAM].dbuf,
rport->tmp_up_buf);
}
/* Get a mono frame from a reversed phase channel (downstream direction).
* The frame is put by put_frame() call to the splitcomb.
*/
static pj_status_t rport_get_frame(pjmedia_port *this_port,
pjmedia_frame *frame)
{
struct reverse_port *rport = (struct reverse_port*) this_port;
/* Update state */
op_update(rport, DIR_DOWNSTREAM, OP_GET);
/* Return no frame if media flow on this direction is being
* paused.
*/
if (rport->buf[DIR_DOWNSTREAM].paused) {
frame->type = PJMEDIA_FRAME_TYPE_NONE;
return PJ_SUCCESS;
}
/* Get frame from delay buffer */
frame->size = PJMEDIA_PIA_AVG_FSZ(&this_port->info);
frame->type = PJMEDIA_FRAME_TYPE_AUDIO;
frame->timestamp.u64 = rport->buf[DIR_DOWNSTREAM].ts.u64;
return pjmedia_delay_buf_get(rport->buf[DIR_DOWNSTREAM].dbuf,
(short*)frame->buf);
}
static pj_status_t rport_on_destroy(pjmedia_port *this_port)
{
struct reverse_port *rport = (struct reverse_port*) this_port;
pjmedia_delay_buf_destroy(rport->buf[DIR_DOWNSTREAM].dbuf);
pjmedia_delay_buf_destroy(rport->buf[DIR_UPSTREAM].dbuf);
return PJ_SUCCESS;
}
| gpl-3.0 |
willmh93/CodeMagic | Source/Box2D/Testbed/Framework/Test.cpp | 16 | 12236 | /*
* Copyright (c) 2006-2009 Erin Catto http://www.box2d.org
*
* This software is provided 'as-is', without any express or implied
* warranty. In no event will the authors be held liable for any damages
* arising from the use of this software.
* Permission is granted to anyone to use this software for any purpose,
* including commercial applications, and to alter it and redistribute it
* freely, subject to the following restrictions:
* 1. The origin of this software must not be misrepresented; you must not
* claim that you wrote the original software. If you use this software
* in a product, an acknowledgment in the product documentation would be
* appreciated but is not required.
* 2. Altered source versions must be plainly marked as such, and must not be
* misrepresented as being the original software.
* 3. This notice may not be removed or altered from any source distribution.
*/
#include "Test.h"
#include <stdio.h>
void DestructionListener::SayGoodbye(b2Joint* joint)
{
if (test->m_mouseJoint == joint)
{
test->m_mouseJoint = NULL;
}
else
{
test->JointDestroyed(joint);
}
}
Test::Test()
{
b2Vec2 gravity;
gravity.Set(0.0f, -10.0f);
m_world = new b2World(gravity);
m_bomb = NULL;
m_textLine = 30;
m_mouseJoint = NULL;
m_pointCount = 0;
m_destructionListener.test = this;
m_world->SetDestructionListener(&m_destructionListener);
m_world->SetContactListener(this);
m_world->SetDebugDraw(&g_debugDraw);
m_bombSpawning = false;
m_stepCount = 0;
b2BodyDef bodyDef;
m_groundBody = m_world->CreateBody(&bodyDef);
memset(&m_maxProfile, 0, sizeof(b2Profile));
memset(&m_totalProfile, 0, sizeof(b2Profile));
}
Test::~Test()
{
// By deleting the world, we delete the bomb, mouse joint, etc.
delete m_world;
m_world = NULL;
}
void Test::PreSolve(b2Contact* contact, const b2Manifold* oldManifold)
{
const b2Manifold* manifold = contact->GetManifold();
if (manifold->pointCount == 0)
{
return;
}
b2Fixture* fixtureA = contact->GetFixtureA();
b2Fixture* fixtureB = contact->GetFixtureB();
b2PointState state1[b2_maxManifoldPoints], state2[b2_maxManifoldPoints];
b2GetPointStates(state1, state2, oldManifold, manifold);
b2WorldManifold worldManifold;
contact->GetWorldManifold(&worldManifold);
for (int32 i = 0; i < manifold->pointCount && m_pointCount < k_maxContactPoints; ++i)
{
ContactPoint* cp = m_points + m_pointCount;
cp->fixtureA = fixtureA;
cp->fixtureB = fixtureB;
cp->position = worldManifold.points[i];
cp->normal = worldManifold.normal;
cp->state = state2[i];
cp->normalImpulse = manifold->points[i].normalImpulse;
cp->tangentImpulse = manifold->points[i].tangentImpulse;
cp->separation = worldManifold.separations[i];
++m_pointCount;
}
}
void Test::DrawTitle(const char *string)
{
g_debugDraw.DrawString(5, DRAW_STRING_NEW_LINE, string);
m_textLine = 3 * DRAW_STRING_NEW_LINE;
}
class QueryCallback : public b2QueryCallback
{
public:
QueryCallback(const b2Vec2& point)
{
m_point = point;
m_fixture = NULL;
}
bool ReportFixture(b2Fixture* fixture)
{
b2Body* body = fixture->GetBody();
if (body->GetType() == b2_dynamicBody)
{
bool inside = fixture->TestPoint(m_point);
if (inside)
{
m_fixture = fixture;
// We are done, terminate the query.
return false;
}
}
// Continue the query.
return true;
}
b2Vec2 m_point;
b2Fixture* m_fixture;
};
void Test::MouseDown(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint != NULL)
{
return;
}
// Make a small box.
b2AABB aabb;
b2Vec2 d;
d.Set(0.001f, 0.001f);
aabb.lowerBound = p - d;
aabb.upperBound = p + d;
// Query the world for overlapping shapes.
QueryCallback callback(p);
m_world->QueryAABB(&callback, aabb);
if (callback.m_fixture)
{
b2Body* body = callback.m_fixture->GetBody();
b2MouseJointDef md;
md.bodyA = m_groundBody;
md.bodyB = body;
md.target = p;
md.maxForce = 1000.0f * body->GetMass();
m_mouseJoint = (b2MouseJoint*)m_world->CreateJoint(&md);
body->SetAwake(true);
}
}
void Test::SpawnBomb(const b2Vec2& worldPt)
{
m_bombSpawnPoint = worldPt;
m_bombSpawning = true;
}
void Test::CompleteBombSpawn(const b2Vec2& p)
{
if (m_bombSpawning == false)
{
return;
}
const float multiplier = 30.0f;
b2Vec2 vel = m_bombSpawnPoint - p;
vel *= multiplier;
LaunchBomb(m_bombSpawnPoint,vel);
m_bombSpawning = false;
}
void Test::ShiftMouseDown(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint != NULL)
{
return;
}
SpawnBomb(p);
}
void Test::MouseUp(const b2Vec2& p)
{
if (m_mouseJoint)
{
m_world->DestroyJoint(m_mouseJoint);
m_mouseJoint = NULL;
}
if (m_bombSpawning)
{
CompleteBombSpawn(p);
}
}
void Test::MouseMove(const b2Vec2& p)
{
m_mouseWorld = p;
if (m_mouseJoint)
{
m_mouseJoint->SetTarget(p);
}
}
void Test::LaunchBomb()
{
b2Vec2 p(RandomFloat(-15.0f, 15.0f), 30.0f);
b2Vec2 v = -5.0f * p;
LaunchBomb(p, v);
}
void Test::LaunchBomb(const b2Vec2& position, const b2Vec2& velocity)
{
if (m_bomb)
{
m_world->DestroyBody(m_bomb);
m_bomb = NULL;
}
b2BodyDef bd;
bd.type = b2_dynamicBody;
bd.position = position;
bd.bullet = true;
m_bomb = m_world->CreateBody(&bd);
m_bomb->SetLinearVelocity(velocity);
b2CircleShape circle;
circle.m_radius = 0.3f;
b2FixtureDef fd;
fd.shape = &circle;
fd.density = 20.0f;
fd.restitution = 0.0f;
b2Vec2 minV = position - b2Vec2(0.3f,0.3f);
b2Vec2 maxV = position + b2Vec2(0.3f,0.3f);
b2AABB aabb;
aabb.lowerBound = minV;
aabb.upperBound = maxV;
m_bomb->CreateFixture(&fd);
}
void Test::Step(Settings* settings)
{
float32 timeStep = settings->hz > 0.0f ? 1.0f / settings->hz : float32(0.0f);
if (settings->pause)
{
if (settings->singleStep)
{
settings->singleStep = 0;
}
else
{
timeStep = 0.0f;
}
g_debugDraw.DrawString(5, m_textLine, "****PAUSED****");
m_textLine += DRAW_STRING_NEW_LINE;
}
uint32 flags = 0;
flags += settings->drawShapes * b2Draw::e_shapeBit;
flags += settings->drawJoints * b2Draw::e_jointBit;
flags += settings->drawAABBs * b2Draw::e_aabbBit;
flags += settings->drawCOMs * b2Draw::e_centerOfMassBit;
g_debugDraw.SetFlags(flags);
m_world->SetAllowSleeping(settings->enableSleep);
m_world->SetWarmStarting(settings->enableWarmStarting);
m_world->SetContinuousPhysics(settings->enableContinuous);
m_world->SetSubStepping(settings->enableSubStepping);
m_pointCount = 0;
m_world->Step(timeStep, settings->velocityIterations, settings->positionIterations);
m_world->DrawDebugData();
g_debugDraw.Flush();
if (timeStep > 0.0f)
{
++m_stepCount;
}
if (settings->drawStats)
{
int32 bodyCount = m_world->GetBodyCount();
int32 contactCount = m_world->GetContactCount();
int32 jointCount = m_world->GetJointCount();
g_debugDraw.DrawString(5, m_textLine, "bodies/contacts/joints = %d/%d/%d", bodyCount, contactCount, jointCount);
m_textLine += DRAW_STRING_NEW_LINE;
int32 proxyCount = m_world->GetProxyCount();
int32 height = m_world->GetTreeHeight();
int32 balance = m_world->GetTreeBalance();
float32 quality = m_world->GetTreeQuality();
g_debugDraw.DrawString(5, m_textLine, "proxies/height/balance/quality = %d/%d/%d/%g", proxyCount, height, balance, quality);
m_textLine += DRAW_STRING_NEW_LINE;
}
// Track maximum profile times
{
const b2Profile& p = m_world->GetProfile();
m_maxProfile.step = b2Max(m_maxProfile.step, p.step);
m_maxProfile.collide = b2Max(m_maxProfile.collide, p.collide);
m_maxProfile.solve = b2Max(m_maxProfile.solve, p.solve);
m_maxProfile.solveInit = b2Max(m_maxProfile.solveInit, p.solveInit);
m_maxProfile.solveVelocity = b2Max(m_maxProfile.solveVelocity, p.solveVelocity);
m_maxProfile.solvePosition = b2Max(m_maxProfile.solvePosition, p.solvePosition);
m_maxProfile.solveTOI = b2Max(m_maxProfile.solveTOI, p.solveTOI);
m_maxProfile.broadphase = b2Max(m_maxProfile.broadphase, p.broadphase);
m_totalProfile.step += p.step;
m_totalProfile.collide += p.collide;
m_totalProfile.solve += p.solve;
m_totalProfile.solveInit += p.solveInit;
m_totalProfile.solveVelocity += p.solveVelocity;
m_totalProfile.solvePosition += p.solvePosition;
m_totalProfile.solveTOI += p.solveTOI;
m_totalProfile.broadphase += p.broadphase;
}
if (settings->drawProfile)
{
const b2Profile& p = m_world->GetProfile();
b2Profile aveProfile;
memset(&aveProfile, 0, sizeof(b2Profile));
if (m_stepCount > 0)
{
float32 scale = 1.0f / m_stepCount;
aveProfile.step = scale * m_totalProfile.step;
aveProfile.collide = scale * m_totalProfile.collide;
aveProfile.solve = scale * m_totalProfile.solve;
aveProfile.solveInit = scale * m_totalProfile.solveInit;
aveProfile.solveVelocity = scale * m_totalProfile.solveVelocity;
aveProfile.solvePosition = scale * m_totalProfile.solvePosition;
aveProfile.solveTOI = scale * m_totalProfile.solveTOI;
aveProfile.broadphase = scale * m_totalProfile.broadphase;
}
g_debugDraw.DrawString(5, m_textLine, "step [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.step, aveProfile.step, m_maxProfile.step);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "collide [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.collide, aveProfile.collide, m_maxProfile.collide);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "solve [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solve, aveProfile.solve, m_maxProfile.solve);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "solve init [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveInit, aveProfile.solveInit, m_maxProfile.solveInit);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "solve velocity [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveVelocity, aveProfile.solveVelocity, m_maxProfile.solveVelocity);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "solve position [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solvePosition, aveProfile.solvePosition, m_maxProfile.solvePosition);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "solveTOI [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.solveTOI, aveProfile.solveTOI, m_maxProfile.solveTOI);
m_textLine += DRAW_STRING_NEW_LINE;
g_debugDraw.DrawString(5, m_textLine, "broad-phase [ave] (max) = %5.2f [%6.2f] (%6.2f)", p.broadphase, aveProfile.broadphase, m_maxProfile.broadphase);
m_textLine += DRAW_STRING_NEW_LINE;
}
if (m_mouseJoint)
{
b2Vec2 p1 = m_mouseJoint->GetAnchorB();
b2Vec2 p2 = m_mouseJoint->GetTarget();
b2Color c;
c.Set(0.0f, 1.0f, 0.0f);
g_debugDraw.DrawPoint(p1, 4.0f, c);
g_debugDraw.DrawPoint(p2, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
g_debugDraw.DrawSegment(p1, p2, c);
}
if (m_bombSpawning)
{
b2Color c;
c.Set(0.0f, 0.0f, 1.0f);
g_debugDraw.DrawPoint(m_bombSpawnPoint, 4.0f, c);
c.Set(0.8f, 0.8f, 0.8f);
g_debugDraw.DrawSegment(m_mouseWorld, m_bombSpawnPoint, c);
}
if (settings->drawContactPoints)
{
const float32 k_impulseScale = 0.1f;
const float32 k_axisScale = 0.3f;
for (int32 i = 0; i < m_pointCount; ++i)
{
ContactPoint* point = m_points + i;
if (point->state == b2_addState)
{
// Add
g_debugDraw.DrawPoint(point->position, 10.0f, b2Color(0.3f, 0.95f, 0.3f));
}
else if (point->state == b2_persistState)
{
// Persist
g_debugDraw.DrawPoint(point->position, 5.0f, b2Color(0.3f, 0.3f, 0.95f));
}
if (settings->drawContactNormals == 1)
{
b2Vec2 p1 = point->position;
b2Vec2 p2 = p1 + k_axisScale * point->normal;
g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.9f));
}
else if (settings->drawContactImpulse == 1)
{
b2Vec2 p1 = point->position;
b2Vec2 p2 = p1 + k_impulseScale * point->normalImpulse * point->normal;
g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
if (settings->drawFrictionImpulse == 1)
{
b2Vec2 tangent = b2Cross(point->normal, 1.0f);
b2Vec2 p1 = point->position;
b2Vec2 p2 = p1 + k_impulseScale * point->tangentImpulse * tangent;
g_debugDraw.DrawSegment(p1, p2, b2Color(0.9f, 0.9f, 0.3f));
}
}
}
}
void Test::ShiftOrigin(const b2Vec2& newOrigin)
{
m_world->ShiftOrigin(newOrigin);
}
| gpl-3.0 |
gargvishesh/multi2sim_pcm | src/arch/arm/asm/asm-thumb.c | 17 | 82393 | /*
* Multi2Sim
* Copyright (C) 2012 Rafael Ubal (ubal@ece.neu.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 <lib/mhandle/mhandle.h>
#include <lib/util/misc.h>
#include <lib/util/string.h>
#include <lib/util/debug.h>
#include "asm-thumb.h"
/* Hard-coded instructions */
void arm_thumb32_disasm_init()
{
int i;
/* Allocate Memory */
arm_thumb32_asm_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv7_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv8_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv9_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv10_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv11_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv12_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv13_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv14_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_lv15_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_mul6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst_dual_table = xcalloc(32, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst1_dual_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst2_dual_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_asm_ldst3_dual_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_shft_reg6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_imm6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_reg7_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_misc_table = xcalloc(8, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_misc1_table = xcalloc(8, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_bin_imm_table = xcalloc(32, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_bin_imm1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_bin_imm2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_dproc_bin_imm3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_brnch_ctrl_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_brnch_ctrl1_table = xcalloc(8, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_st_single6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte3_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte4_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte5_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_byte6_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_hfword_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_hfword1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_hfword2_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_word_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_ld_word1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_mult_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_mult1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_mult_long_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_mov_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
arm_thumb32_mov1_table = xcalloc(16, sizeof(struct arm_thumb32_inst_info_t));
/* Load store Multiple tables */
arm_thumb32_asm_table[1].next_table = arm_thumb32_asm_lv1_table;
arm_thumb32_asm_table[1].next_table_high = 26;
arm_thumb32_asm_table[1].next_table_low = 26;
arm_thumb32_asm_lv1_table[0].next_table = arm_thumb32_asm_lv2_table;
arm_thumb32_asm_lv1_table[0].next_table_high = 25;
arm_thumb32_asm_lv1_table[0].next_table_low = 25;
arm_thumb32_asm_lv2_table[0].next_table = arm_thumb32_asm_lv3_table;
arm_thumb32_asm_lv2_table[0].next_table_high = 22;
arm_thumb32_asm_lv2_table[0].next_table_low = 22;
arm_thumb32_asm_lv3_table[0].next_table = arm_thumb32_asm_ldst_mul_table;
arm_thumb32_asm_lv3_table[0].next_table_high = 24;
arm_thumb32_asm_lv3_table[0].next_table_low = 23;
arm_thumb32_asm_ldst_mul_table[1].next_table = arm_thumb32_asm_ldst_mul1_table;
arm_thumb32_asm_ldst_mul_table[1].next_table_high = 20;
arm_thumb32_asm_ldst_mul_table[1].next_table_low = 20;
arm_thumb32_asm_ldst_mul1_table[1].next_table = arm_thumb32_asm_ldst_mul2_table;
arm_thumb32_asm_ldst_mul1_table[1].next_table_high = 21;
arm_thumb32_asm_ldst_mul1_table[1].next_table_low = 21;
arm_thumb32_asm_ldst_mul2_table[1].next_table = arm_thumb32_asm_ldst_mul3_table;
arm_thumb32_asm_ldst_mul2_table[1].next_table_high = 19;
arm_thumb32_asm_ldst_mul2_table[1].next_table_low = 16;
arm_thumb32_asm_ldst_mul_table[2].next_table = arm_thumb32_asm_ldst_mul4_table;
arm_thumb32_asm_ldst_mul_table[2].next_table_high = 20;
arm_thumb32_asm_ldst_mul_table[2].next_table_low = 20;
arm_thumb32_asm_ldst_mul4_table[0].next_table = arm_thumb32_asm_ldst_mul5_table;
arm_thumb32_asm_ldst_mul4_table[0].next_table_high = 21;
arm_thumb32_asm_ldst_mul4_table[0].next_table_low = 21;
arm_thumb32_asm_ldst_mul5_table[1].next_table = arm_thumb32_asm_ldst_mul6_table;
arm_thumb32_asm_ldst_mul5_table[1].next_table_high = 19;
arm_thumb32_asm_ldst_mul5_table[1].next_table_low = 16;
/* Load store Dual tables */
arm_thumb32_asm_lv3_table[1].next_table = arm_thumb32_asm_ldst_dual_table;
arm_thumb32_asm_lv3_table[1].next_table_high = 24;
arm_thumb32_asm_lv3_table[1].next_table_low = 20;
arm_thumb32_asm_ldst_dual_table[(0x07)].next_table = arm_thumb32_asm_ldst1_dual_table;
arm_thumb32_asm_ldst_dual_table[(0x07)].next_table_high = 19;
arm_thumb32_asm_ldst_dual_table[(0x07)].next_table_low = 16;
arm_thumb32_asm_ldst_dual_table[(0x08)].next_table = arm_thumb32_asm_ldst2_dual_table;
arm_thumb32_asm_ldst_dual_table[(0x08)].next_table_high = 19;
arm_thumb32_asm_ldst_dual_table[(0x08)].next_table_low = 16;
arm_thumb32_asm_ldst_dual_table[(0x0d)].next_table = arm_thumb32_asm_ldst3_dual_table;
arm_thumb32_asm_ldst_dual_table[(0x0d)].next_table_high = 7;
arm_thumb32_asm_ldst_dual_table[(0x0d)].next_table_low = 4;
/* Data Processing Shifted Reg Tables */
arm_thumb32_asm_lv2_table[1].next_table = arm_thumb32_dproc_shft_reg_table;
arm_thumb32_asm_lv2_table[1].next_table_high = 24;
arm_thumb32_asm_lv2_table[1].next_table_low = 21;
arm_thumb32_dproc_shft_reg_table[0].next_table = arm_thumb32_dproc_shft_reg1_table;
arm_thumb32_dproc_shft_reg_table[0].next_table_high = 11;
arm_thumb32_dproc_shft_reg_table[0].next_table_low = 8;
arm_thumb32_dproc_shft_reg_table[2].next_table = arm_thumb32_dproc_shft_reg2_table;
arm_thumb32_dproc_shft_reg_table[2].next_table_high = 19;
arm_thumb32_dproc_shft_reg_table[2].next_table_low = 16;
arm_thumb32_dproc_shft_reg_table[3].next_table = arm_thumb32_dproc_shft_reg3_table;
arm_thumb32_dproc_shft_reg_table[3].next_table_high = 19;
arm_thumb32_dproc_shft_reg_table[3].next_table_low = 16;
arm_thumb32_dproc_shft_reg_table[4].next_table = arm_thumb32_dproc_shft_reg4_table;
arm_thumb32_dproc_shft_reg_table[4].next_table_high = 11;
arm_thumb32_dproc_shft_reg_table[4].next_table_low = 8;
arm_thumb32_dproc_shft_reg_table[8].next_table = arm_thumb32_dproc_shft_reg5_table;
arm_thumb32_dproc_shft_reg_table[8].next_table_high = 11;
arm_thumb32_dproc_shft_reg_table[8].next_table_low = 8;
arm_thumb32_dproc_shft_reg_table[(0xd)].next_table = arm_thumb32_dproc_shft_reg6_table;
arm_thumb32_dproc_shft_reg_table[(0xd)].next_table_high = 11;
arm_thumb32_dproc_shft_reg_table[(0xd)].next_table_low = 8;
arm_thumb32_dproc_shft_reg2_table[(0xf)].next_table = arm_thumb32_mov_table;
arm_thumb32_dproc_shft_reg2_table[(0xf)].next_table_high = 5;
arm_thumb32_dproc_shft_reg2_table[(0xf)].next_table_low = 4;
/* Data Processing Immediate Tables */
arm_thumb32_asm_table[2].next_table = arm_thumb32_asm_lv4_table;
arm_thumb32_asm_table[2].next_table_high = 15;
arm_thumb32_asm_table[2].next_table_low = 15;
arm_thumb32_asm_lv4_table[0].next_table = arm_thumb32_asm_lv5_table;
arm_thumb32_asm_lv4_table[0].next_table_high = 25;
arm_thumb32_asm_lv4_table[0].next_table_low = 25;
arm_thumb32_asm_lv5_table[0].next_table = arm_thumb32_dproc_imm_table;
arm_thumb32_asm_lv5_table[0].next_table_high = 24;
arm_thumb32_asm_lv5_table[0].next_table_low = 21;
arm_thumb32_dproc_imm_table[0].next_table = arm_thumb32_dproc_imm1_table;
arm_thumb32_dproc_imm_table[0].next_table_high = 11;
arm_thumb32_dproc_imm_table[0].next_table_low = 8;
arm_thumb32_dproc_imm_table[2].next_table = arm_thumb32_dproc_imm2_table;
arm_thumb32_dproc_imm_table[2].next_table_high = 19;
arm_thumb32_dproc_imm_table[2].next_table_low = 16;
arm_thumb32_dproc_imm_table[3].next_table = arm_thumb32_dproc_imm3_table;
arm_thumb32_dproc_imm_table[3].next_table_high = 19;
arm_thumb32_dproc_imm_table[3].next_table_low = 16;
arm_thumb32_dproc_imm_table[4].next_table = arm_thumb32_dproc_imm4_table;
arm_thumb32_dproc_imm_table[4].next_table_high = 11;
arm_thumb32_dproc_imm_table[4].next_table_low = 8;
arm_thumb32_dproc_imm_table[8].next_table = arm_thumb32_dproc_imm5_table;
arm_thumb32_dproc_imm_table[8].next_table_high = 11;
arm_thumb32_dproc_imm_table[8].next_table_low = 8;
arm_thumb32_dproc_imm_table[(0xd)].next_table = arm_thumb32_dproc_imm6_table;
arm_thumb32_dproc_imm_table[(0xd)].next_table_high = 11;
arm_thumb32_dproc_imm_table[(0xd)].next_table_low = 8;
/* Data Processing Plain Binary Immediate Tables */
arm_thumb32_asm_lv5_table[1].next_table = arm_thumb32_dproc_bin_imm_table;
arm_thumb32_asm_lv5_table[1].next_table_high = 24;
arm_thumb32_asm_lv5_table[1].next_table_low = 20;
arm_thumb32_dproc_bin_imm_table[0].next_table = arm_thumb32_dproc_bin_imm1_table;
arm_thumb32_dproc_bin_imm_table[0].next_table_high = 19;
arm_thumb32_dproc_bin_imm_table[0].next_table_low = 16;
arm_thumb32_dproc_bin_imm_table[(0x0a)].next_table = arm_thumb32_dproc_bin_imm2_table;
arm_thumb32_dproc_bin_imm_table[(0x0a)].next_table_high = 19;
arm_thumb32_dproc_bin_imm_table[(0x0a)].next_table_low = 16;
arm_thumb32_dproc_bin_imm_table[(0x16)].next_table = arm_thumb32_dproc_bin_imm3_table;
arm_thumb32_dproc_bin_imm_table[(0x16)].next_table_high = 19;
arm_thumb32_dproc_bin_imm_table[(0x16)].next_table_low = 16;
/* Branch_control table */
arm_thumb32_asm_lv4_table[1].next_table = arm_thumb32_brnch_ctrl_table;
arm_thumb32_asm_lv4_table[1].next_table_high = 14;
arm_thumb32_asm_lv4_table[1].next_table_low = 12;
arm_thumb32_brnch_ctrl_table[0].next_table = arm_thumb32_brnch_ctrl1_table;
arm_thumb32_brnch_ctrl_table[0].next_table_high = 25;
arm_thumb32_brnch_ctrl_table[0].next_table_low = 25;
arm_thumb32_brnch_ctrl_table[2].next_table = arm_thumb32_brnch_ctrl1_table;
arm_thumb32_brnch_ctrl_table[2].next_table_high = 25;
arm_thumb32_brnch_ctrl_table[2].next_table_low = 23;
/* Single Data table */
arm_thumb32_asm_table[3].next_table = arm_thumb32_asm_lv6_table;
arm_thumb32_asm_table[3].next_table_high = 26;
arm_thumb32_asm_table[3].next_table_low = 26;
arm_thumb32_asm_lv6_table[0].next_table = arm_thumb32_asm_lv7_table;
arm_thumb32_asm_lv6_table[0].next_table_high = 25;
arm_thumb32_asm_lv6_table[0].next_table_low = 24;
arm_thumb32_asm_lv7_table[0].next_table = arm_thumb32_asm_lv8_table;
arm_thumb32_asm_lv7_table[0].next_table_high = 22;
arm_thumb32_asm_lv7_table[0].next_table_low = 20;
for(i = 0; i < 8; i++)
{
if(!(i % 2))
{
arm_thumb32_asm_lv8_table[i].next_table = arm_thumb32_st_single_table;
arm_thumb32_asm_lv8_table[i].next_table_high = 23;
arm_thumb32_asm_lv8_table[i].next_table_low = 21;
}
}
arm_thumb32_st_single_table[0].next_table = arm_thumb32_st_single1_table;
arm_thumb32_st_single_table[0].next_table_high = 11;
arm_thumb32_st_single_table[0].next_table_low = 11;
arm_thumb32_st_single1_table[1].next_table = arm_thumb32_st_single2_table;
arm_thumb32_st_single1_table[1].next_table_high = 9;
arm_thumb32_st_single1_table[1].next_table_low = 9;
arm_thumb32_st_single_table[1].next_table = arm_thumb32_st_single3_table;
arm_thumb32_st_single_table[1].next_table_high = 11;
arm_thumb32_st_single_table[1].next_table_low = 11;
arm_thumb32_st_single3_table[1].next_table = arm_thumb32_st_single4_table;
arm_thumb32_st_single3_table[1].next_table_high = 9;
arm_thumb32_st_single3_table[1].next_table_low = 9;
arm_thumb32_st_single_table[2].next_table = arm_thumb32_st_single5_table;
arm_thumb32_st_single_table[2].next_table_high = 11;
arm_thumb32_st_single_table[2].next_table_low = 11;
arm_thumb32_st_single5_table[1].next_table = arm_thumb32_st_single6_table;
arm_thumb32_st_single5_table[1].next_table_high = 9;
arm_thumb32_st_single5_table[1].next_table_low = 9;
/* Load Byte Table */
arm_thumb32_asm_lv7_table[1].next_table = arm_thumb32_asm_lv9_table;
arm_thumb32_asm_lv7_table[1].next_table_high = 22;
arm_thumb32_asm_lv7_table[1].next_table_low = 20;
arm_thumb32_asm_lv9_table[1].next_table = arm_thumb32_ld_byte_table;
arm_thumb32_asm_lv9_table[1].next_table_high = 24;
arm_thumb32_asm_lv9_table[1].next_table_low = 23;
arm_thumb32_asm_lv8_table[1].next_table = arm_thumb32_ld_byte_table;
arm_thumb32_asm_lv8_table[1].next_table_high = 24;
arm_thumb32_asm_lv8_table[1].next_table_low = 23;
arm_thumb32_ld_byte_table[0].next_table = arm_thumb32_ld_byte1_table;
arm_thumb32_ld_byte_table[0].next_table_high = 19;
arm_thumb32_ld_byte_table[0].next_table_low = 16;
for(i = 0; i < 15; i++)
{
arm_thumb32_ld_byte1_table[i].next_table = arm_thumb32_ld_byte2_table;
arm_thumb32_ld_byte1_table[i].next_table_high = 11;
arm_thumb32_ld_byte1_table[i].next_table_low = 11;
}
arm_thumb32_ld_byte2_table[1].next_table = arm_thumb32_ld_byte3_table;
arm_thumb32_ld_byte2_table[1].next_table_high = 10;
arm_thumb32_ld_byte2_table[1].next_table_low = 8;
arm_thumb32_ld_byte_table[2].next_table = arm_thumb32_ld_byte4_table;
arm_thumb32_ld_byte_table[2].next_table_high = 19;
arm_thumb32_ld_byte_table[2].next_table_low = 16;
for(i = 0; i < 15; i++)
{
arm_thumb32_ld_byte4_table[i].next_table = arm_thumb32_ld_byte5_table;
arm_thumb32_ld_byte4_table[i].next_table_high = 11;
arm_thumb32_ld_byte4_table[i].next_table_low = 11;
}
arm_thumb32_ld_byte5_table[1].next_table = arm_thumb32_ld_byte6_table;
arm_thumb32_ld_byte5_table[1].next_table_high = 10;
arm_thumb32_ld_byte5_table[1].next_table_low = 8;
/* Load Halfword Table */
arm_thumb32_asm_lv7_table[1].next_table = arm_thumb32_asm_lv9_table;
arm_thumb32_asm_lv7_table[1].next_table_high = 22;
arm_thumb32_asm_lv7_table[1].next_table_low = 20;
arm_thumb32_asm_lv9_table[3].next_table = arm_thumb32_ld_hfword_table;
arm_thumb32_asm_lv9_table[3].next_table_high = 24;
arm_thumb32_asm_lv9_table[3].next_table_low = 23;
arm_thumb32_asm_lv8_table[3].next_table = arm_thumb32_ld_hfword_table;
arm_thumb32_asm_lv8_table[3].next_table_high = 24;
arm_thumb32_asm_lv8_table[3].next_table_low = 23;
arm_thumb32_ld_hfword_table[0].next_table = arm_thumb32_ld_hfword1_table;
arm_thumb32_ld_hfword_table[0].next_table_high = 11;
arm_thumb32_ld_hfword_table[0].next_table_low = 11;
arm_thumb32_ld_hfword_table[2].next_table = arm_thumb32_ld_hfword2_table;
arm_thumb32_ld_hfword_table[2].next_table_high = 11;
arm_thumb32_ld_hfword_table[2].next_table_low = 11;
/* Load Word Table */
arm_thumb32_asm_lv7_table[1].next_table = arm_thumb32_asm_lv9_table;
arm_thumb32_asm_lv7_table[1].next_table_high = 22;
arm_thumb32_asm_lv7_table[1].next_table_low = 20;
arm_thumb32_asm_lv9_table[5].next_table = arm_thumb32_ld_word_table;
arm_thumb32_asm_lv9_table[5].next_table_high = 24;
arm_thumb32_asm_lv9_table[5].next_table_low = 23;
arm_thumb32_asm_lv8_table[5].next_table = arm_thumb32_ld_word_table;
arm_thumb32_asm_lv8_table[5].next_table_high = 24;
arm_thumb32_asm_lv8_table[5].next_table_low = 23;
arm_thumb32_ld_word_table[0].next_table = arm_thumb32_ld_word1_table;
arm_thumb32_ld_word_table[0].next_table_high = 11;
arm_thumb32_ld_word_table[0].next_table_low = 11;
/* Data Processing Register Based Table */
arm_thumb32_asm_lv7_table[2].next_table = arm_thumb32_dproc_reg_table;
arm_thumb32_asm_lv7_table[2].next_table_high = 23;
arm_thumb32_asm_lv7_table[2].next_table_low = 20;
arm_thumb32_dproc_reg_table[0].next_table = arm_thumb32_dproc_reg1_table;
arm_thumb32_dproc_reg_table[0].next_table_high = 7;
arm_thumb32_dproc_reg_table[0].next_table_low = 7;
arm_thumb32_dproc_reg_table[1].next_table = arm_thumb32_dproc_reg2_table;
arm_thumb32_dproc_reg_table[1].next_table_high = 7;
arm_thumb32_dproc_reg_table[1].next_table_low = 7;
arm_thumb32_dproc_reg2_table[1].next_table = arm_thumb32_dproc_reg3_table;
arm_thumb32_dproc_reg2_table[1].next_table_high = 19;
arm_thumb32_dproc_reg2_table[1].next_table_low = 16;
arm_thumb32_dproc_reg_table[2].next_table = arm_thumb32_dproc_reg4_table;
arm_thumb32_dproc_reg_table[2].next_table_high = 7;
arm_thumb32_dproc_reg_table[2].next_table_low = 7;
arm_thumb32_dproc_reg_table[3].next_table = arm_thumb32_dproc_reg5_table;
arm_thumb32_dproc_reg_table[3].next_table_high = 7;
arm_thumb32_dproc_reg_table[3].next_table_low = 7;
arm_thumb32_dproc_reg_table[4].next_table = arm_thumb32_dproc_reg6_table;
arm_thumb32_dproc_reg_table[4].next_table_high = 7;
arm_thumb32_dproc_reg_table[4].next_table_low = 7;
arm_thumb32_dproc_reg_table[5].next_table = arm_thumb32_dproc_reg7_table;
arm_thumb32_dproc_reg_table[5].next_table_high = 7;
arm_thumb32_dproc_reg_table[5].next_table_low = 7;
arm_thumb32_dproc_reg_table[8].next_table = arm_thumb32_dproc_misc_table;
arm_thumb32_dproc_reg_table[8].next_table_high = 7;
arm_thumb32_dproc_reg_table[8].next_table_low = 6;
arm_thumb32_dproc_misc_table[2].next_table = arm_thumb32_dproc_misc1_table;
arm_thumb32_dproc_misc_table[2].next_table_high = 21;
arm_thumb32_dproc_misc_table[2].next_table_low = 20;
/* Multiply Tables */
arm_thumb32_asm_lv7_table[3].next_table = arm_thumb32_asm_lv10_table;
arm_thumb32_asm_lv7_table[3].next_table_high = 23;
arm_thumb32_asm_lv7_table[3].next_table_low = 23;
arm_thumb32_asm_lv10_table[0].next_table = arm_thumb32_mult_table;
arm_thumb32_asm_lv10_table[0].next_table_high = 5;
arm_thumb32_asm_lv10_table[0].next_table_low = 4;
arm_thumb32_mult_table[0].next_table = arm_thumb32_mult1_table;
arm_thumb32_mult_table[0].next_table_high = 15;
arm_thumb32_mult_table[0].next_table_low = 12;
/* Multiply Long Tables */
arm_thumb32_asm_lv10_table[1].next_table = arm_thumb32_mult_long_table;
arm_thumb32_asm_lv10_table[1].next_table_high = 22;
arm_thumb32_asm_lv10_table[1].next_table_low = 20;
#define DEFINST(_name,_fmt_str,_cat,_op1,_op2,_op3,_op4,_op5,_op6,_op7,_op8) \
arm_thumb32_setup_table(#_name, _fmt_str, ARM_THUMB32_CAT_##_cat, _op1, _op2,\
_op3, _op4, _op5, _op6, _op7, _op8, ARM_THUMB32_INST_##_name);
#include "asm-thumb32.dat"
#undef DEFINST
}
void arm_thumb32_setup_table(char* name , char* fmt_str ,
enum arm_thumb32_cat_enum cat32 , int op1 , int op2 , int op3 ,
int op4 , int op5 , int op6, int op7, int op8, enum arm_thumb32_inst_enum inst_name)
{
struct arm_thumb32_inst_info_t *current_table;
/* We initially start with the first table arm_asm_table, with the opcode field as argument */
current_table = arm_thumb32_asm_table;
int op[8];
int i;
op[0] = op1;
op[1] = op2;
op[2] = op3;
op[3] = op4;
op[4] = op5;
op[5] = op6;
op[6] = op7;
op[7] = op8;
i = 0;
while(1)
{
if(current_table[op[i]].next_table && (op[i] >= 0))
{
current_table = current_table[op[i]].next_table;
i++;
}
else
{
current_table[op[i]].name = name;
current_table[op[i]].fmt_str = fmt_str;
current_table[op[i]].cat32 = cat32;
current_table[op[i]].size = 4;
current_table[op[i]].inst_32 = inst_name;
break;
}
}
}
void arm_thumb16_disasm_init()
{
//int op[6];
int i = 0;
arm_thumb16_asm_table = xcalloc(8, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_shft_ins_table = xcalloc(16, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_shft_ins_lv2_table = xcalloc(16, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv1_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv2_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv3_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv4_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv5_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv6_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv7_table = xcalloc(64, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv8_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_asm_lv9_table = xcalloc(64, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_data_proc_table = xcalloc(32, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_spcl_data_brex_table = xcalloc(32, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_spcl_data_brex_lv1_table = xcalloc(4, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_ld_st_table = xcalloc(64, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_ld_st_lv1_table = xcalloc(64, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_ld_st_lv2_table = xcalloc(64, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_misc_table = xcalloc(128, sizeof(struct arm_thumb16_inst_info_t));
arm_thumb16_it_table = xcalloc(256, sizeof(struct arm_thumb16_inst_info_t));
/* Directing to Shift Instructions */
arm_thumb16_asm_table[0].next_table = arm_thumb16_shft_ins_table;
arm_thumb16_asm_table[0].next_table_high= 13;
arm_thumb16_asm_table[0].next_table_low = 11;
arm_thumb16_shft_ins_table[3].next_table = arm_thumb16_shft_ins_lv2_table;
arm_thumb16_shft_ins_table[3].next_table_high = 10;
arm_thumb16_shft_ins_table[3].next_table_low = 9;
/* Directing to Data Processing Instructions */
arm_thumb16_asm_table[1].next_table = arm_thumb16_asm_lv1_table;
arm_thumb16_asm_table[1].next_table_high= 13;
arm_thumb16_asm_table[1].next_table_low = 13;
arm_thumb16_asm_lv1_table[0].next_table = arm_thumb16_asm_lv2_table;
arm_thumb16_asm_lv1_table[0].next_table_high = 12;
arm_thumb16_asm_lv1_table[0].next_table_low = 12;
arm_thumb16_asm_lv2_table[0].next_table = arm_thumb16_asm_lv3_table;
arm_thumb16_asm_lv2_table[0].next_table_high = 11;
arm_thumb16_asm_lv2_table[0].next_table_low = 10;
arm_thumb16_asm_lv3_table[0].next_table = arm_thumb16_data_proc_table;
arm_thumb16_asm_lv3_table[0].next_table_high = 9;
arm_thumb16_asm_lv3_table[0].next_table_low = 6;
/* Directing to LD/ST Instructions */
arm_thumb16_asm_lv1_table[1].next_table = arm_thumb16_ld_st_table;
arm_thumb16_asm_lv1_table[1].next_table_high = 15;
arm_thumb16_asm_lv1_table[1].next_table_low = 11;
arm_thumb16_asm_lv2_table[1].next_table = arm_thumb16_ld_st_table;
arm_thumb16_asm_lv2_table[1].next_table_high = 15;
arm_thumb16_asm_lv2_table[1].next_table_low = 11;
arm_thumb16_asm_lv4_table[0].next_table = arm_thumb16_ld_st_table;
arm_thumb16_asm_lv4_table[0].next_table_high = 15;
arm_thumb16_asm_lv4_table[0].next_table_low = 11;
arm_thumb16_ld_st_table[10].next_table = arm_thumb16_ld_st_lv1_table;
arm_thumb16_ld_st_table[10].next_table_high = 10;
arm_thumb16_ld_st_table[10].next_table_low = 9;
arm_thumb16_ld_st_table[11].next_table = arm_thumb16_ld_st_lv2_table;
arm_thumb16_ld_st_table[11].next_table_high = 10;
arm_thumb16_ld_st_table[11].next_table_low = 9;
/* Directing to Special data Instructions and B&EX instructions*/
arm_thumb16_asm_lv3_table[1].next_table = arm_thumb16_spcl_data_brex_table;
arm_thumb16_asm_lv3_table[1].next_table_high = 9;
arm_thumb16_asm_lv3_table[1].next_table_low = 7;
arm_thumb16_spcl_data_brex_table[0].next_table = arm_thumb16_spcl_data_brex_lv1_table;
arm_thumb16_spcl_data_brex_table[0].next_table_high = 6;
arm_thumb16_spcl_data_brex_table[0].next_table_low = 6;
/* Directing to Misellaneous 16 bit thumb2 instructions */
arm_thumb16_asm_table[2].next_table = arm_thumb16_asm_lv4_table;
arm_thumb16_asm_table[2].next_table_high = 13;
arm_thumb16_asm_table[2].next_table_low = 13;
arm_thumb16_asm_lv4_table[1].next_table = arm_thumb16_asm_lv5_table;
arm_thumb16_asm_lv4_table[1].next_table_high = 12;
arm_thumb16_asm_lv4_table[1].next_table_low = 12;
arm_thumb16_asm_lv5_table[1].next_table = arm_thumb16_misc_table;
arm_thumb16_asm_lv5_table[1].next_table_high = 11;
arm_thumb16_asm_lv5_table[1].next_table_low = 5;
for(i = 0; i < 8; i++)
{
arm_thumb16_misc_table[(0x78 + i)].next_table = arm_thumb16_it_table;
arm_thumb16_misc_table[(0x78 + i)].next_table_high = 3;
arm_thumb16_misc_table[(0x78 + i)].next_table_low = 0;
}
/* Directing to PC and SP relative instructions */
arm_thumb16_asm_lv5_table[0].next_table = arm_thumb16_asm_lv6_table;
arm_thumb16_asm_lv5_table[0].next_table_high = 11;
arm_thumb16_asm_lv5_table[0].next_table_low = 11;
arm_thumb16_asm_table[3].next_table = arm_thumb16_asm_lv7_table;
arm_thumb16_asm_table[3].next_table_high = 13;
arm_thumb16_asm_table[3].next_table_low = 12;
/* Directing to Software interrupt instructions */
arm_thumb16_asm_lv7_table[0].next_table = arm_thumb16_asm_lv8_table;
arm_thumb16_asm_lv7_table[0].next_table_high = 11;
arm_thumb16_asm_lv7_table[0].next_table_low = 11;
/* Directing to unconditional branch instructions */
arm_thumb16_asm_lv7_table[1].next_table = arm_thumb16_asm_lv9_table; // entries [0 to 0xe] of lv9 are inst B //
arm_thumb16_asm_lv7_table[1].next_table_high = 11;
arm_thumb16_asm_lv7_table[1].next_table_low = 8;
#define DEFINST(_name,_fmt_str,_cat,_op1,_op2,_op3,_op4,_op5,_op6) \
arm_thumb16_setup_table(#_name, _fmt_str, ARM_THUMB16_CAT_##_cat, _op1, _op2,\
_op3, _op4, _op5, _op6, ARM_THUMB16_INST_##_name);
#include "asm-thumb.dat"
#undef DEFINST
}
void arm_thumb16_setup_table(char* name , char* fmt_str ,
enum arm_thumb16_cat_enum cat16 , int op1 , int op2 , int op3 ,
int op4 , int op5 , int op6, enum arm_thumb16_inst_enum inst_name)
{
struct arm_thumb16_inst_info_t *current_table;
/* We initially start with the first table arm_asm_table, with the opcode field as argument */
current_table = arm_thumb16_asm_table;
int op[6];
int i;
op[0] = op1;
op[1] = op2;
op[2] = op3;
op[3] = op4;
op[4] = op5;
op[5] = op6;
i = 0;
while(1)
{
if(current_table[op[i]].next_table && (op[i] >= 0))
{
current_table = current_table[op[i]].next_table;
i++;
}
else
{
current_table[op[i]].name = name;
current_table[op[i]].fmt_str = fmt_str;
current_table[op[i]].cat16 = cat16;
current_table[op[i]].size = 2;
current_table[op[i]].inst_16 = inst_name;
break;
}
}
}
static int arm_token_comp(char *fmt_str, char *token_str, int *token_len)
{
*token_len = strlen(token_str);
return !strncmp(fmt_str, token_str, *token_len) &&
!isalnum(fmt_str[*token_len]);
}
void arm_thumb16_inst_dump(FILE *f , char *str , int inst_str_size , void *inst_ptr ,
unsigned int inst_index, unsigned int inst_addr)
{
struct arm_thumb16_inst_t inst;
int byte_index;
char *inst_str;
char **inst_str_ptr;
char *fmt_str;
int token_len;
inst.addr = inst_index;
for (byte_index = 0; byte_index < 2; ++byte_index)
inst.dword.bytes[byte_index] = *(unsigned char *) (inst_ptr
+ byte_index);
arm_thumb16_inst_decode(&inst); // Change to thumb2
inst_str = str;
inst_str_ptr = &str;
fmt_str = inst.info->fmt_str;
if (fmt_str)
{
while (*fmt_str)
{
if (*fmt_str != '%')
{
if (!(*fmt_str == ' ' && *inst_str_ptr == inst_str))
str_printf(inst_str_ptr, &inst_str_size, "%c",
*fmt_str);
++fmt_str;
continue;
}
++fmt_str;
if (arm_token_comp(fmt_str, "rd", &token_len))
arm_thumb16_inst_dump_RD(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else if (arm_token_comp(fmt_str, "rm", &token_len))
arm_thumb16_inst_dump_RM(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else if (arm_token_comp(fmt_str, "rn", &token_len))
arm_thumb16_inst_dump_RN(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else if (arm_token_comp(fmt_str, "immd8", &token_len))
arm_thumb16_inst_dump_IMMD8(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16, inst_addr);
else if (arm_token_comp(fmt_str, "immd5", &token_len))
arm_thumb16_inst_dump_IMMD5(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16, inst_addr);
else if (arm_token_comp(fmt_str, "immd3", &token_len))
arm_thumb16_inst_dump_IMMD3(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else if (arm_token_comp(fmt_str, "cond", &token_len))
arm_thumb16_inst_dump_COND(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else if (arm_token_comp(fmt_str, "regs", &token_len))
arm_thumb16_inst_dump_REGS(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else if (arm_token_comp(fmt_str, "x", &token_len))
arm_thumb16_inst_dump_it_eq_x(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat16);
else
fatal("%s: token not recognized\n", fmt_str);
fmt_str += token_len;
}
fprintf(f, "%s\n", inst_str);
}
else
{
fprintf (f,"???\n");
}
}
void arm_thumb16_inst_dump_RD(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int rd;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
rd = inst->dword.movshift_reg_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_ADDSUB)
rd = inst->dword.addsub_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
rd = inst->dword.immd_oprs_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_DPR_INS)
rd = inst->dword.dpr_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
rd = ((inst->dword.high_oprs_ins.h1 << 3) | inst->dword.high_oprs_ins.reg_rd);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
rd = inst->dword.pcldr_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
rd = inst->dword.ldstr_reg_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
rd = inst->dword.ldstr_exts_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
rd = inst->dword.ldstr_immd_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
rd = inst->dword.ldstr_hfwrd_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
rd = inst->dword.sp_immd_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
rd = inst->dword.addsp_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_MISC_REV)
rd = inst->dword.rev_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_CMP_T2)
rd = (inst->dword.cmp_t2.N << 3 | inst->dword.cmp_t2.reg_rn);
else
fatal("%d: rd fmt not recognized", cat);
switch (rd)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rd);
break;
}
}
void arm_thumb16_inst_dump_RM(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int rm;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
rm = inst->dword.movshift_reg_ins.reg_rs;
else if (cat == ARM_THUMB16_CAT_ADDSUB)
rm = inst->dword.addsub_ins.reg_rs;
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_DPR_INS)
rm = inst->dword.dpr_ins.reg_rs;
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
rm = inst->dword.high_oprs_ins.reg_rs;
else if (cat == ARM_THUMB16_CAT_PC_LDR)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
rm = inst->dword.ldstr_reg_ins.reg_ro;
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
rm = inst->dword.ldstr_exts_ins.reg_rb;
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_REV)
rm = inst->dword.rev_ins.reg_rm;
else if (cat == ARM_THUMB16_CAT_CMP_T2)
rm = inst->dword.cmp_t2.reg_rm;
else
fatal("%d: rm fmt not recognized", cat);
switch (rm)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rm);
break;
}
}
void arm_thumb16_inst_dump_RN(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int rn;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_ADDSUB)
rn = inst->dword.addsub_ins.reg_rs;
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
rn = inst->dword.immd_oprs_ins.reg_rd;
else if (cat == ARM_THUMB16_CAT_DPR_INS)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
rn = inst->dword.ldstr_reg_ins.reg_rb;
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
rn = inst->dword.ldstr_exts_ins.reg_rb;
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
rn = inst->dword.ldstr_immd_ins.reg_rb;
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
rn = inst->dword.ldstr_hfwrd_ins.reg_rb;
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
rn = inst->dword.ldm_stm_ins.reg_rb;
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_CBNZ)
rn = inst->dword.cbnz_ins.reg_rn;
else
fatal("%d: rn fmt not recognized", cat);
switch (rn)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rn);
break;
}
}
void arm_thumb16_inst_dump_IMMD8(char **inst_str_ptr , int *inst_str_size ,
struct arm_thumb16_inst_t *inst , enum arm_thumb16_cat_enum cat ,
unsigned int inst_addr)
{
unsigned int immd8;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_ADDSUB)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
immd8 = inst->dword.immd_oprs_ins.offset8;
else if (cat == ARM_THUMB16_CAT_DPR_INS)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
immd8 =(inst->dword.pcldr_ins.immd_8 << 2);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
immd8 = 4 * inst->dword.sp_immd_ins.immd_8;
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
fatal("%d: immd8 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
immd8 = 4 * inst->dword.addsp_ins.immd_8;
else if (cat == ARM_THUMB16_CAT_MISC_SUBSP_INS)
immd8 = 4 * inst->dword.sub_sp_ins.immd_8;
else if (cat == ARM_THUMB16_CAT_MISC_BR)
immd8 = inst->dword.cond_br_ins.s_offset;
else if (cat == ARM_THUMB16_CAT_MISC_UCBR)
immd8 = inst->dword.br_ins.immd11;
else if (cat == ARM_THUMB16_CAT_MISC_SVC_INS)
immd8 = inst->dword.svc_ins.value;
else
fatal("%d: immd8 fmt not recognized", cat);
if(cat == ARM_THUMB16_CAT_MISC_BR)
{
if((immd8 >> 7))
{
immd8 = ((inst_addr + 4) + ((immd8 << 1) | 0xffffff00));
}
else
{
immd8 = (inst_addr + 4) + (immd8 << 1);
}
str_printf(inst_str_ptr, inst_str_size, "%x",immd8);
}
else if(cat == ARM_THUMB16_CAT_MISC_UCBR)
{
immd8 = immd8 << 1;
immd8 = SEXT32(immd8, 12);
immd8 = inst_addr + 4 + immd8;
str_printf(inst_str_ptr, inst_str_size, "%x",immd8);
}
else
str_printf(inst_str_ptr, inst_str_size, "#%d",immd8);
}
void arm_thumb16_inst_dump_IMMD3(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int immd3;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_ADDSUB)
immd3 = inst->dword.addsub_ins.rn_imm;
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_DPR_INS)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_SUBSP_INS)
fatal("%d: immd3 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_BR)
fatal("%d: immd3 fmt not recognized", cat);
else
fatal("%d: immd3 fmt not recognized", cat);
str_printf(inst_str_ptr, inst_str_size, "#%d",immd3);
}
void arm_thumb16_inst_dump_IMMD5(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat,
unsigned int inst_addr)
{
unsigned int immd5;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
immd5 = inst->dword.movshift_reg_ins.offset;
else if (cat == ARM_THUMB16_CAT_ADDSUB)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_DPR_INS)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
immd5 = inst->dword.ldstr_immd_ins.offset << 2;
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
immd5 = inst->dword.ldstr_hfwrd_ins.offset;
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_SUBSP_INS)
fatal("%d: immd5 fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_CBNZ)
immd5 = inst->dword.cbnz_ins.immd_5;
else
fatal("%d: immd5 fmt not recognized", cat);
if(cat == ARM_THUMB16_CAT_MISC_CBNZ)
{
if((inst_addr + 2) % 4)
immd5 = (inst_addr + 4) + (immd5 << 1);
else
immd5 = (inst_addr + 2) + (immd5 << 1);
str_printf(inst_str_ptr, inst_str_size, "%x",immd5);
}
else
str_printf(inst_str_ptr, inst_str_size, "#%d",immd5);
}
void arm_thumb16_inst_dump_COND(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int cond;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_ADDSUB)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_DPR_INS)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IF_THEN)
cond = inst->dword.if_eq_ins.first_cond;
else if (cat == ARM_THUMB16_CAT_LDM_STM)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_SUBSP_INS)
fatal("%d: cond fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_BR)
cond = inst->dword.cond_br_ins.cond;
else if (cat == ARM_THUMB16_CAT_IF_THEN)
cond = inst->dword.if_eq_ins.first_cond;
else
fatal("%d: rm fmt not recognized", cat);
switch (cond)
{
case (EQ):
str_printf(inst_str_ptr, inst_str_size, "eq");
break;
case (NE):
str_printf(inst_str_ptr, inst_str_size, "ne");
break;
case (CS):
str_printf(inst_str_ptr, inst_str_size, "cs");
break;
case (CC):
str_printf(inst_str_ptr, inst_str_size, "cc");
break;
case (MI):
str_printf(inst_str_ptr, inst_str_size, "mi");
break;
case (PL):
str_printf(inst_str_ptr, inst_str_size, "pl");
break;
case (VS):
str_printf(inst_str_ptr, inst_str_size, "vs");
break;
case (VC):
str_printf(inst_str_ptr, inst_str_size, "vc");
break;
case (HI):
str_printf(inst_str_ptr, inst_str_size, "hi");
break;
case (LS):
str_printf(inst_str_ptr, inst_str_size, "ls");
break;
case (GE):
str_printf(inst_str_ptr, inst_str_size, "ge");
break;
case (LT):
str_printf(inst_str_ptr, inst_str_size, "lt");
break;
case (GT):
str_printf(inst_str_ptr, inst_str_size, "gt");
break;
case (LE):
str_printf(inst_str_ptr, inst_str_size, "le");
break;
case (AL):
str_printf(inst_str_ptr, inst_str_size, " ");
break;
}
}
void arm_thumb16_inst_dump_REGS(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int regs;
unsigned int i;
if (cat == ARM_THUMB16_CAT_MOVSHIFT_REG)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_ADDSUB)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IMMD_OPRS)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_DPR_INS)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_HI_REG_OPRS)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_PC_LDR)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_REG)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_EXTS)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_IMMD)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_HFWRD)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDSTR_SP_IMMD)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_IF_THEN)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_LDM_STM)
regs = inst->dword.ldm_stm_ins.reg_list;
else if (cat == ARM_THUMB16_CAT_MISC_ADDSP_INS)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_SUBSP_INS)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_BR)
fatal("%d: regs fmt not recognized", cat);
else if (cat == ARM_THUMB16_CAT_MISC_PUSH_POP)
regs = inst->dword.push_pop_ins.reg_list;
else
fatal("%d: regs fmt not recognized", cat);
regs = (inst->dword.push_pop_ins.m_ext << 14) | regs;
str_printf(inst_str_ptr, inst_str_size, "{");
for (i = 1; i < 65536; i *= 2)
{
if(regs & (i))
{
str_printf(inst_str_ptr, inst_str_size, "r%d ", log_base2(i));
}
}
str_printf(inst_str_ptr, inst_str_size, "}");
}
void arm_thumb16_inst_dump_it_eq_x(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb16_inst_t *inst, enum arm_thumb16_cat_enum cat)
{
unsigned int first_cond;
unsigned int mask;
if (cat == ARM_THUMB16_CAT_IF_THEN)
{
mask = inst->dword.if_eq_ins.mask;
first_cond = inst->dword.if_eq_ins.first_cond;
}
else
fatal("%d: x fmt not recognized", cat);
if((mask != 0x8))
{
if((mask >> 3) ^ (first_cond & 1))
str_printf(inst_str_ptr, inst_str_size, "e");
else
str_printf(inst_str_ptr, inst_str_size, "t");
}
}
void arm_thumb32_inst_dump(FILE *f , char *str , int inst_str_size , void *inst_ptr ,
unsigned int inst_index, unsigned int inst_addr)
{
struct arm_thumb32_inst_t inst;
int byte_index;
char *inst_str;
char **inst_str_ptr;
char *fmt_str;
int token_len;
inst.addr = inst_index;
for (byte_index = 0; byte_index < 4; ++byte_index)
inst.dword.bytes[byte_index] = *(unsigned char *) (inst_ptr
+ ((byte_index + 2) % 4));
arm_thumb32_inst_decode(&inst); // Change to thumb2
inst_str = str;
inst_str_ptr = &str;
fmt_str = inst.info->fmt_str;
if (fmt_str)
{
while (*fmt_str)
{
if (*fmt_str != '%')
{
if (!(*fmt_str == ' ' && *inst_str_ptr == inst_str))
str_printf(inst_str_ptr, &inst_str_size, "%c",
*fmt_str);
++fmt_str;
continue;
}
++fmt_str;
if (arm_token_comp(fmt_str, "rd", &token_len))
arm_thumb32_inst_dump_RD(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "rn", &token_len))
arm_thumb32_inst_dump_RN(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "rm", &token_len))
arm_thumb32_inst_dump_RM(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "rt", &token_len))
arm_thumb32_inst_dump_RT(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "rt2", &token_len))
arm_thumb32_inst_dump_RT2(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "ra", &token_len))
arm_thumb32_inst_dump_RA(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "rdlo", &token_len))
arm_thumb32_inst_dump_RDLO(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "rdhi", &token_len))
arm_thumb32_inst_dump_RDHI(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "imm12", &token_len))
arm_thumb32_inst_dump_IMM12(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "imm8", &token_len))
arm_thumb32_inst_dump_IMM12(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "imm2", &token_len))
arm_thumb32_inst_dump_IMM2(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "immd8", &token_len))
arm_thumb32_inst_dump_IMMD8(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "immd12", &token_len))
arm_thumb32_inst_dump_IMMD12(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "immd16", &token_len))
arm_thumb32_inst_dump_IMMD16(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "addr", &token_len))
arm_thumb32_inst_dump_ADDR(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32, inst_addr);
else if (arm_token_comp(fmt_str, "regs", &token_len))
arm_thumb32_inst_dump_REGS(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "shft", &token_len))
arm_thumb32_inst_dump_SHFT_REG(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "S", &token_len))
arm_thumb32_inst_dump_S(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "lsb", &token_len))
arm_thumb32_inst_dump_LSB(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "wid", &token_len))
arm_thumb32_inst_dump_WID(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else if (arm_token_comp(fmt_str, "cond", &token_len))
arm_thumb32_inst_dump_COND(inst_str_ptr, &inst_str_size, &inst,
inst.info->cat32);
else
fatal("%s: token not recognized\n", fmt_str);
fmt_str += token_len;
}
fprintf(f, "%s\n", inst_str);
}
else
{
fprintf (f,"???\n");
}
}
void arm_thumb32_inst_dump_RD(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rd;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_PUSH_POP)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_TABLE_BRNCH)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_DPR_SHFTREG)
rd = inst->dword.data_proc_shftreg.rd;
else if (cat == ARM_THUMB32_CAT_DPR_IMM)
rd = inst->dword.data_proc_immd.rd;
else if (cat == ARM_THUMB32_CAT_DPR_BIN_IMM)
rd = inst->dword.data_proc_immd.rd;
else if (cat == ARM_THUMB32_CAT_BRANCH)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LDSTR_BYTE)
rd = inst->dword.ldstr_reg.rd;
else if (cat == ARM_THUMB32_CAT_LDSTR_REG)
rd = inst->dword.ldstr_reg.rd;
else if (cat == ARM_THUMB32_CAT_LDSTR_IMMD)
rd = inst->dword.ldstr_imm.rd;
else if (cat == ARM_THUMB32_CAT_DPR_REG)
rd = inst->dword.dproc_reg.rd;
else if (cat == ARM_THUMB32_CAT_MULT)
rd = inst->dword.mult.rd;
else if (cat == ARM_THUMB32_CAT_MULT_LONG)
fatal("%d: rd fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_BIT_FIELD)
rd = inst->dword.bit_field.rd;
else
fatal("%d: rd fmt not recognized", cat);
switch (rd)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rd);
break;
}
}
void arm_thumb32_inst_dump_RN(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rn;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
rn = inst->dword.ld_st_mult.rn;
else if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
rn = inst->dword.ld_st_double.rn;
else if (cat == ARM_THUMB32_CAT_PUSH_POP)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_TABLE_BRNCH)
rn = inst->dword.table_branch.rn;
else if (cat == ARM_THUMB32_CAT_DPR_SHFTREG)
rn = inst->dword.data_proc_shftreg.rn;
else if (cat == ARM_THUMB32_CAT_DPR_IMM)
rn = inst->dword.data_proc_immd.rn;
else if (cat == ARM_THUMB32_CAT_DPR_BIN_IMM)
rn = inst->dword.data_proc_immd.rn;
else if (cat == ARM_THUMB32_CAT_BRANCH)
fatal("%d: rn fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LDSTR_BYTE)
rn = inst->dword.ldstr_reg.rn;
else if (cat == ARM_THUMB32_CAT_LDSTR_REG)
rn = inst->dword.ldstr_reg.rn;
else if (cat == ARM_THUMB32_CAT_LDSTR_IMMD)
rn = inst->dword.ldstr_imm.rn;
else if (cat == ARM_THUMB32_CAT_DPR_REG)
rn = inst->dword.dproc_reg.rn;
else if (cat == ARM_THUMB32_CAT_MULT)
rn = inst->dword.mult.rn;
else if (cat == ARM_THUMB32_CAT_MULT_LONG)
rn = inst->dword.mult_long.rn;
else if (cat == ARM_THUMB32_CAT_BIT_FIELD)
rn = inst->dword.bit_field.rn;
else
fatal("%d: rn fmt not recognized", cat);
switch (rn)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rn);
break;
}
}
void arm_thumb32_inst_dump_RM(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rm;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_PUSH_POP)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_TABLE_BRNCH)
rm = inst->dword.table_branch.rm;
else if (cat == ARM_THUMB32_CAT_DPR_SHFTREG)
rm = inst->dword.data_proc_shftreg.rm;
else if (cat == ARM_THUMB32_CAT_DPR_IMM)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_DPR_BIN_IMM)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_BRANCH)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LDSTR_BYTE)
rm = inst->dword.ldstr_reg.rm;
else if (cat == ARM_THUMB32_CAT_LDSTR_REG)
rm = inst->dword.ldstr_reg.rm;
else if (cat == ARM_THUMB32_CAT_LDSTR_IMMD)
fatal("%d: rm fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_DPR_REG)
rm = inst->dword.dproc_reg.rm;
else if (cat == ARM_THUMB32_CAT_MULT)
rm = inst->dword.mult.rm;
else if (cat == ARM_THUMB32_CAT_MULT_LONG)
rm = inst->dword.mult_long.rm;
else if (cat == ARM_THUMB32_CAT_BIT_FIELD)
fatal("%d: rm fmt not recognized", cat);
else
fatal("%d: rm fmt not recognized", cat);
switch (rm)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rm);
break;
}
}
void arm_thumb32_inst_dump_RT(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rt;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
fatal("%d: rt fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
rt = inst->dword.ld_st_double.rt;
else
fatal("%d: rt fmt not recognized", cat);
switch (rt)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rt);
break;
}
}
void arm_thumb32_inst_dump_RT2(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rt2;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
fatal("%d: rt fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
rt2 = inst->dword.ld_st_double.rt2;
else
fatal("%d: rt2 fmt not recognized", cat);
switch (rt2)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rt2);
break;
}
}
void arm_thumb32_inst_dump_RA(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int ra;
if (cat == ARM_THUMB32_CAT_MULT)
ra = inst->dword.mult.ra;
else
fatal("%d: ra fmt not recognized", cat);
switch (ra)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", ra);
break;
}
}
void arm_thumb32_inst_dump_RDLO(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rdlo;
if (cat == ARM_THUMB32_CAT_MULT_LONG)
rdlo = inst->dword.mult_long.rdlo;
else
fatal("%d: rdlo fmt not recognized", cat);
switch (rdlo)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rdlo);
break;
}
}
void arm_thumb32_inst_dump_RDHI(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int rdhi;
if (cat == ARM_THUMB32_CAT_MULT_LONG)
rdhi = inst->dword.mult_long.rdhi;
else
fatal("%d: rdhi fmt not recognized", cat);
switch (rdhi)
{
case (r13):
str_printf(inst_str_ptr, inst_str_size, "sp");
break;
case (r14):
str_printf(inst_str_ptr, inst_str_size, "lr");
break;
case (r15):
str_printf(inst_str_ptr, inst_str_size, "pc");
break;
default:
str_printf(inst_str_ptr, inst_str_size, "r%d", rdhi);
break;
}
}
void arm_thumb32_inst_dump_S(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int sign;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_PUSH_POP)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_TABLE_BRNCH)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_DPR_SHFTREG)
sign = inst->dword.data_proc_shftreg.sign;
else if (cat == ARM_THUMB32_CAT_DPR_IMM)
sign = inst->dword.data_proc_immd.sign;
else if (cat == ARM_THUMB32_CAT_DPR_BIN_IMM)
sign = inst->dword.data_proc_immd.sign;
else if (cat == ARM_THUMB32_CAT_BRANCH)
sign = inst->dword.branch.sign;
else if (cat == ARM_THUMB32_CAT_LDSTR_BYTE)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LDSTR_REG)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_LDSTR_IMMD)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_DPR_REG)
sign = inst->dword.dproc_reg.sign;
else if (cat == ARM_THUMB32_CAT_MULT)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_MULT_LONG)
fatal("%d: S fmt not recognized", cat);
else if (cat == ARM_THUMB32_CAT_BIT_FIELD)
fatal("%d: sign fmt not recognized", cat);
else
fatal("%d: sign fmt not recognized", cat);
if(sign)
str_printf(inst_str_ptr, inst_str_size, "s");
}
void arm_thumb32_inst_dump_REGS(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int regs;
unsigned int i;
if (cat == ARM_THUMB32_CAT_LD_ST_MULT)
regs = inst->dword.ld_st_mult.reglist;
else if (cat == ARM_THUMB32_CAT_PUSH_POP)
regs = inst->dword.push_pop.reglist;
else
fatal("%d: regs fmt not recognized", cat);
str_printf(inst_str_ptr, inst_str_size, "{");
for (i = 1; i < 65536; i *= 2)
{
if(regs & (i))
{
str_printf(inst_str_ptr, inst_str_size, "r%d ", log_base2(i));
}
}
str_printf(inst_str_ptr, inst_str_size, "}");
}
void arm_thumb32_inst_dump_SHFT_REG(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int shift;
unsigned int type;
if (cat == ARM_THUMB32_CAT_DPR_SHFTREG)
{
type = inst->dword.data_proc_shftreg.type;
shift = (inst->dword.data_proc_shftreg.imm3 << 2) | (inst->dword.data_proc_shftreg.imm2);
}
else
fatal("%d: shft fmt not recognized", cat);
if(shift)
{
switch(type)
{
case (ARM_OPTR_LSL):
str_printf(inst_str_ptr, inst_str_size, "{lsl #%d}", shift);
break;
case (ARM_OPTR_LSR):
str_printf(inst_str_ptr, inst_str_size, "{lsr #%d}", shift);
break;
case (ARM_OPTR_ASR):
str_printf(inst_str_ptr, inst_str_size, "{asr #%d}", shift);
break;
case (ARM_OPTR_ROR):
str_printf(inst_str_ptr, inst_str_size, "{ror #%d}", shift);
break;
}
}
}
void arm_thumb32_inst_dump_IMM12(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int immd12;
unsigned int idx;
unsigned int wback;
unsigned int add;
if (cat == ARM_THUMB32_CAT_LDSTR_IMMD)
immd12 = inst->dword.ldstr_imm.immd12;
else if (cat == ARM_THUMB32_CAT_LDSTR_BYTE)
immd12 = inst->dword.ldstr_imm.immd12;
else
fatal("%d: imm12 fmt not recognized", cat);
if(inst->dword.ldstr_imm.add)
str_printf(inst_str_ptr, inst_str_size, "#%d",immd12);
else
{
idx = (immd12 & 0x00000400) >> 10;
add = (immd12 & 0x00000200) >> 9;
wback = (immd12 & 0x00000100) >> 8;
if(add)
{
if(idx == 1 && wback == 0)
str_printf(inst_str_ptr, inst_str_size, "[#%d]",(immd12 & 0x000000ff));
else if (idx == 1 && wback == 1)
str_printf(inst_str_ptr, inst_str_size, "[#%d]!",(immd12 & 0x000000ff));
else if (idx == 0 && wback == 1)
str_printf(inst_str_ptr, inst_str_size, "#%d",(immd12 & 0x000000ff));
}
else
{
if(idx == 1 && wback == 0)
str_printf(inst_str_ptr, inst_str_size, "[#-%d]",(immd12 & 0x000000ff));
else if (idx == 1 && wback == 1)
str_printf(inst_str_ptr, inst_str_size, "[#-%d]!",(immd12 & 0x000000ff));
else if (idx == 0 && wback == 1)
str_printf(inst_str_ptr, inst_str_size, "#-%d",(immd12 & 0x000000ff));
}
}
}
void arm_thumb32_inst_dump_IMMD12(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int immd8;
unsigned int immd3;
unsigned int i;
unsigned int imm4;
unsigned int imm5;
unsigned int shft;
unsigned int const_val;
if (cat == ARM_THUMB32_CAT_DPR_IMM)
{
immd8 = inst->dword.data_proc_immd.immd8;
immd3 = inst->dword.data_proc_immd.immd3;
i = inst->dword.data_proc_immd.i_flag;
}
else if (cat == ARM_THUMB32_CAT_DPR_BIN_IMM)
{
immd8 = inst->dword.data_proc_immd.immd8;
immd3 = inst->dword.data_proc_immd.immd3;
i = inst->dword.data_proc_immd.i_flag;
}
else
fatal("%d: immd12 fmt not recognized", cat);
imm4 = (i << 3) | (immd3);
if(imm4 < 4)
{
switch(imm4)
{
case(0) :
const_val = immd8;
break;
case(1) :
const_val = (immd8 << 16) | immd8;
break;
case(2) :
const_val = (immd8 << 24) | (immd8 << 8);
break;
case(3) :
const_val = (immd8 << 24) | (immd8 << 16) | (immd8 << 8) | immd8;
break;
}
}
else
{
imm5 = (imm4 << 1) | ((0x00000008 & immd8) >> 8);
const_val = (immd8 << 24) | 0x10000000;
shft = (imm5 - 8);
const_val = (const_val >> shft);
}
str_printf(inst_str_ptr, inst_str_size, "#%d", const_val);
}
void arm_thumb32_inst_dump_IMMD8(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int immd8;
if (cat == ARM_THUMB32_CAT_LD_ST_DOUBLE)
immd8 = (inst->dword.ld_st_double.immd8 << 2);
else
fatal("%d: immd12 fmt not recognized", cat);
if(immd8)
{
if(inst->dword.ld_st_double.add_sub)
{
if(inst->dword.ld_st_double.index == 1 && inst->dword.ld_st_double.wback == 0)
str_printf(inst_str_ptr, inst_str_size, "#%d",(immd8));
else if (inst->dword.ld_st_double.index == 1 && inst->dword.ld_st_double.wback == 1)
str_printf(inst_str_ptr, inst_str_size, "#%d!",(immd8));
else if (inst->dword.ld_st_double.index == 0 && inst->dword.ld_st_double.wback == 0)
str_printf(inst_str_ptr, inst_str_size, "#%d",(immd8));
}
else
{
if(inst->dword.ld_st_double.index == 1 && inst->dword.ld_st_double.wback == 0)
str_printf(inst_str_ptr, inst_str_size, "#-%d",(immd8));
else if (inst->dword.ld_st_double.index == 1 && inst->dword.ld_st_double.wback == 1)
str_printf(inst_str_ptr, inst_str_size, "#-%d!",(immd8));
else if (inst->dword.ld_st_double.index == 0 && inst->dword.ld_st_double.wback == 1)
str_printf(inst_str_ptr, inst_str_size, "#-%d",(immd8));
}
}
}
void arm_thumb32_inst_dump_IMM2(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int immd2;
if (cat == ARM_THUMB32_CAT_LDSTR_BYTE)
{
immd2 = inst->dword.ldstr_reg.immd2;
}
else if (cat == ARM_THUMB32_CAT_LDSTR_REG)
{
immd2 = inst->dword.ldstr_reg.immd2;
}
else
fatal("%d: imm2 fmt not recognized", cat);
str_printf(inst_str_ptr, inst_str_size, "#%d", immd2);
}
void arm_thumb32_inst_dump_COND(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int cond;
if (cat == ARM_THUMB32_CAT_BRANCH_COND)
{
cond = inst->dword.branch.cond;
}
else
fatal("%d: cond fmt not recognized", cat);
switch (cond)
{
case (EQ):
str_printf(inst_str_ptr, inst_str_size, "eq");
break;
case (NE):
str_printf(inst_str_ptr, inst_str_size, "ne");
break;
case (CS):
str_printf(inst_str_ptr, inst_str_size, "cs");
break;
case (CC):
str_printf(inst_str_ptr, inst_str_size, "cc");
break;
case (MI):
str_printf(inst_str_ptr, inst_str_size, "mi");
break;
case (PL):
str_printf(inst_str_ptr, inst_str_size, "pl");
break;
case (VS):
str_printf(inst_str_ptr, inst_str_size, "vs");
break;
case (VC):
str_printf(inst_str_ptr, inst_str_size, "vc");
break;
case (HI):
str_printf(inst_str_ptr, inst_str_size, "hi");
break;
case (LS):
str_printf(inst_str_ptr, inst_str_size, "ls");
break;
case (GE):
str_printf(inst_str_ptr, inst_str_size, "ge");
break;
case (LT):
str_printf(inst_str_ptr, inst_str_size, "lt");
break;
case (GT):
str_printf(inst_str_ptr, inst_str_size, "gt");
break;
case (LE):
str_printf(inst_str_ptr, inst_str_size, "le");
break;
case (AL):
str_printf(inst_str_ptr, inst_str_size, " ");
break;
}
}
void arm_thumb32_inst_dump_LSB(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int immd2;
unsigned int immd3;
if (cat == ARM_THUMB32_CAT_BIT_FIELD)
{
immd2 = inst->dword.bit_field.immd2;
immd3 = inst->dword.bit_field.immd3;
}
else
fatal("%d: imm2 fmt not recognized", cat);
str_printf(inst_str_ptr, inst_str_size, "#%d", ((immd3 << 2) | immd2));
}
void arm_thumb32_inst_dump_WID(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int msb;
unsigned int immd2;
unsigned int immd3;
unsigned int lsb;
if (cat == ARM_THUMB32_CAT_BIT_FIELD)
{
msb = inst->dword.bit_field.msb;
immd2 = inst->dword.bit_field.immd2;
immd3 = inst->dword.bit_field.immd3;
}
else
fatal("%d: imm2 fmt not recognized", cat);
lsb = (immd3 << 2) | immd2;
str_printf(inst_str_ptr, inst_str_size, "#%d", (msb - lsb + 1));
}
void arm_thumb32_inst_dump_IMMD16(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat)
{
unsigned int immd16;
unsigned int immd8;
unsigned int immd3;
unsigned int i;
unsigned int immd4;
if (cat == ARM_THUMB32_CAT_DPR_BIN_IMM)
{
immd8 = inst->dword.data_proc_immd.immd8;
immd3 = inst->dword.data_proc_immd.immd3;
i = inst->dword.data_proc_immd.i_flag;
immd4 = inst->dword.data_proc_immd.rn;
}
else
fatal("%d: immd16 fmt not recognized", cat);
immd16 = (immd4 << 12) | (i << 11) | (immd3 << 8) | immd8;
str_printf(inst_str_ptr, inst_str_size, "#%d ; 0x%x", immd16, immd16);
}
void arm_thumb32_inst_dump_ADDR(char **inst_str_ptr, int *inst_str_size,
struct arm_thumb32_inst_t *inst, enum arm_thumb32_cat_enum cat,
unsigned int inst_addr)
{
unsigned int addr;
addr = 0;
if (cat == ARM_THUMB32_CAT_BRANCH)
{
addr = (inst->dword.branch_link.sign << 24)
| ((!(inst->dword.branch.j1 ^ inst->dword.branch_link.sign)) << 23)
| ((!(inst->dword.branch.j2 ^ inst->dword.branch_link.sign)) << 22)
| (inst->dword.branch_link.immd10 << 12)
| (inst->dword.branch_link.immd11 << 1);
addr = SEXT32(addr,25);
}
else if (cat == ARM_THUMB32_CAT_BRANCH_LX)
{
addr = (inst->dword.branch_link.sign << 24)
| ((!(inst->dword.branch.j1 ^ inst->dword.branch_link.sign)) << 23)
| ((!(inst->dword.branch.j2 ^ inst->dword.branch_link.sign)) << 22)
| (inst->dword.branch_link.immd10 << 12)
| ((inst->dword.branch_link.immd11 & 0xfffffffe) << 1);
addr = SEXT32(addr,25);
}
else if (cat == ARM_THUMB32_CAT_BRANCH_COND)
{
addr = (inst->dword.branch.sign << 20)
| (((inst->dword.branch.j2)) << 19)
| (((inst->dword.branch.j1)) << 18)
| (inst->dword.branch.immd6 << 12)
| (inst->dword.branch.immd11 << 1);
addr = SEXT32(addr,21);
}
else
fatal("%d: addr fmt not recognized", cat);
/* FIXME : Changed from +4 to +2 */
addr = (inst_addr + 2) + (addr);
str_printf(inst_str_ptr, inst_str_size, "#%d ; 0x%x", addr, addr);
}
void arm_thumb32_inst_decode(struct arm_thumb32_inst_t *inst)
{
struct arm_thumb32_inst_info_t *current_table;
/* We initially start with the first table mips_asm_table, with the opcode field as argument */
current_table = arm_thumb32_asm_table;
int current_table_low = 27;
int current_table_high = 28;
unsigned int thumb32_table_arg;
int loop_iteration = 0;
thumb32_table_arg = BITS32(*(unsigned int*)inst->dword.bytes, current_table_high, current_table_low);
/* Find next tables if the instruction belongs to another table */
while (1) {
if (current_table[thumb32_table_arg].next_table && loop_iteration < 8) {
current_table_high = current_table[thumb32_table_arg].next_table_high;
current_table_low = current_table[thumb32_table_arg].next_table_low;
current_table = current_table[thumb32_table_arg].next_table;
thumb32_table_arg = BITS32(*(unsigned int*)inst->dword.bytes, current_table_high, current_table_low);
loop_iteration++;
}
else if (loop_iteration > 8) {
fatal("Can not find the correct table containing the instruction\n");
}
else
break;
}
inst->info = ¤t_table[thumb32_table_arg];
}
void arm_thumb16_inst_decode(struct arm_thumb16_inst_t *inst)
{
struct arm_thumb16_inst_info_t *current_table;
/* We initially start with the first table mips_asm_table, with the opcode field as argument */
current_table = arm_thumb16_asm_table;
int current_table_low = 14;
int current_table_high = 15;
unsigned int thumb16_table_arg;
int loop_iteration = 0;
thumb16_table_arg = BITS16(*(unsigned short*)inst->dword.bytes, current_table_high, current_table_low);
/* Find next tables if the instruction belongs to another table */
while (1) {
if (current_table[thumb16_table_arg].next_table && loop_iteration < 6) {
current_table_high = current_table[thumb16_table_arg].next_table_high;
current_table_low = current_table[thumb16_table_arg].next_table_low;
current_table = current_table[thumb16_table_arg].next_table;
thumb16_table_arg = BITS16(*(unsigned short*)inst->dword.bytes, current_table_high, current_table_low);
loop_iteration++;
}
else if (loop_iteration > 6) {
fatal("Can not find the correct table containing the instruction\n");
}
else
break;
}
inst->info = ¤t_table[thumb16_table_arg];
}
void arm_disasm_done()
{
/* Thumb 16 tables */
free(arm_thumb16_asm_table);
free(arm_thumb16_shft_ins_table);
free(arm_thumb16_shft_ins_lv2_table);
free(arm_thumb16_asm_lv1_table);
free(arm_thumb16_asm_lv2_table);
free(arm_thumb16_asm_lv3_table);
free(arm_thumb16_asm_lv4_table);
free(arm_thumb16_asm_lv5_table);
free(arm_thumb16_asm_lv6_table);
free(arm_thumb16_asm_lv7_table);
free(arm_thumb16_asm_lv8_table);
free(arm_thumb16_asm_lv9_table);
free(arm_thumb16_data_proc_table);
free(arm_thumb16_spcl_data_brex_table);
free(arm_thumb16_spcl_data_brex_lv1_table);
free(arm_thumb16_ld_st_table);
free(arm_thumb16_ld_st_lv1_table);
free(arm_thumb16_ld_st_lv2_table);
free(arm_thumb16_misc_table);
free(arm_thumb16_it_table);
/* Thumb 32 tables */
free(arm_thumb32_asm_table);
free(arm_thumb32_asm_lv1_table);
free(arm_thumb32_asm_lv2_table);
free(arm_thumb32_asm_lv3_table);
free(arm_thumb32_asm_lv4_table);
free(arm_thumb32_asm_lv5_table);
free(arm_thumb32_asm_lv6_table);
free(arm_thumb32_asm_lv7_table);
free(arm_thumb32_asm_lv8_table);
free(arm_thumb32_asm_lv9_table);
free(arm_thumb32_asm_lv10_table);
free(arm_thumb32_asm_lv11_table);
free(arm_thumb32_asm_lv12_table);
free(arm_thumb32_asm_lv13_table);
free(arm_thumb32_asm_lv14_table);
free(arm_thumb32_asm_lv15_table);
free(arm_thumb32_asm_ldst_mul_table);
free(arm_thumb32_asm_ldst_mul1_table);
free(arm_thumb32_asm_ldst_mul2_table);
free(arm_thumb32_asm_ldst_mul3_table);
free(arm_thumb32_asm_ldst_mul4_table);
free(arm_thumb32_asm_ldst_mul5_table);
free(arm_thumb32_asm_ldst_mul6_table);
free(arm_thumb32_asm_ldst_dual_table);
free(arm_thumb32_asm_ldst1_dual_table);
free(arm_thumb32_asm_ldst2_dual_table);
free(arm_thumb32_asm_ldst3_dual_table);
free(arm_thumb32_dproc_shft_reg_table);
free(arm_thumb32_dproc_shft_reg1_table);
free(arm_thumb32_dproc_shft_reg2_table);
free(arm_thumb32_dproc_shft_reg3_table);
free(arm_thumb32_dproc_shft_reg4_table);
free(arm_thumb32_dproc_shft_reg5_table);
free(arm_thumb32_dproc_shft_reg6_table);
free(arm_thumb32_dproc_imm_table);
free(arm_thumb32_dproc_imm1_table);
free(arm_thumb32_dproc_imm2_table);
free(arm_thumb32_dproc_imm3_table);
free(arm_thumb32_dproc_imm4_table);
free(arm_thumb32_dproc_imm5_table);
free(arm_thumb32_dproc_imm6_table);
free(arm_thumb32_dproc_reg_table);
free(arm_thumb32_dproc_reg1_table);
free(arm_thumb32_dproc_reg2_table);
free(arm_thumb32_dproc_reg3_table);
free(arm_thumb32_dproc_reg4_table);
free(arm_thumb32_dproc_reg5_table);
free(arm_thumb32_dproc_reg6_table);
free(arm_thumb32_dproc_reg7_table);
free(arm_thumb32_dproc_misc_table);
free(arm_thumb32_dproc_misc1_table);
free(arm_thumb32_st_single_table);
free(arm_thumb32_st_single1_table);
free(arm_thumb32_st_single2_table);
free(arm_thumb32_st_single3_table);
free(arm_thumb32_st_single4_table);
free(arm_thumb32_st_single5_table);
free(arm_thumb32_st_single6_table);
free(arm_thumb32_ld_byte_table);
free(arm_thumb32_ld_byte1_table);
free(arm_thumb32_ld_byte2_table);
free(arm_thumb32_ld_byte3_table);
free(arm_thumb32_ld_byte4_table);
free(arm_thumb32_ld_byte5_table);
free(arm_thumb32_ld_byte6_table);
free(arm_thumb32_ld_hfword_table);
free(arm_thumb32_ld_hfword1_table);
free(arm_thumb32_ld_hfword2_table);
free(arm_thumb32_ld_word_table);
free(arm_thumb32_ld_word1_table);
free(arm_thumb32_mult_table);
free(arm_thumb32_mult1_table);
free(arm_thumb32_dproc_bin_imm_table);
free(arm_thumb32_dproc_bin_imm1_table);
free(arm_thumb32_dproc_bin_imm2_table);
free(arm_thumb32_dproc_bin_imm3_table);
free(arm_thumb32_mult_long_table);
free(arm_thumb32_mov_table);
free(arm_thumb32_mov1_table);
free(arm_thumb32_brnch_ctrl_table);
free(arm_thumb32_brnch_ctrl1_table);
}
| gpl-3.0 |
df8oe/UHSDR | mchf-eclipse/basesw/ovi40/Drivers/CMSIS/DSP_Lib/Source/FilteringFunctions/arm_fir_lattice_init_f32.c | 279 | 3047 | /*-----------------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_fir_lattice_init_f32.c
*
* Description: Floating-point FIR Lattice filter initialization function.
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* - Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* - Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* - Neither the name of ARM LIMITED nor the names of its contributors
* may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
* ---------------------------------------------------------------------------*/
#include "arm_math.h"
/**
* @ingroup groupFilters
*/
/**
* @addtogroup FIR_Lattice
* @{
*/
/**
* @brief Initialization function for the floating-point FIR lattice filter.
* @param[in] *S points to an instance of the floating-point FIR lattice structure.
* @param[in] numStages number of filter stages.
* @param[in] *pCoeffs points to the coefficient buffer. The array is of length numStages.
* @param[in] *pState points to the state buffer. The array is of length numStages.
* @return none.
*/
void arm_fir_lattice_init_f32(
arm_fir_lattice_instance_f32 * S,
uint16_t numStages,
float32_t * pCoeffs,
float32_t * pState)
{
/* Assign filter taps */
S->numStages = numStages;
/* Assign coefficient pointer */
S->pCoeffs = pCoeffs;
/* Clear state buffer and size is always numStages */
memset(pState, 0, (numStages) * sizeof(float32_t));
/* Assign state pointer */
S->pState = pState;
}
/**
* @} end of FIR_Lattice group
*/
| gpl-3.0 |
SandclockStudios/SandClock-Engine | Libraries/Geolib/include/Geometry/Line.cpp | 26 | 10485 | /* Copyright Jukka Jylänki
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License. */
/** @file Line.cpp
@author Jukka Jylänki
@brief Implementation for the Line geometry object. */
#include "Line.h"
#include "Ray.h"
#include "LineSegment.h"
#include "../Math/float3x3.h"
#include "../Math/float3x4.h"
#include "../Math/float4x4.h"
#include "OBB.h"
#include "../Math/Quat.h"
#include "Frustum.h"
#include "Triangle.h"
#include "Plane.h"
#include "Polygon.h"
#include "Polyhedron.h"
#include "Sphere.h"
#include "AABB.h"
#include "Capsule.h"
#include "Circle.h"
#include "../Math/MathFunc.h"
#ifdef MATH_ENABLE_STL_SUPPORT
#include <iostream>
#endif
MATH_BEGIN_NAMESPACE
/// Computes the closest point pair on two lines.
/** The first line is specified by two points start0 and end0. The second line is specified by
two points start1 and end1.
The implementation of this function follows http://paulbourke.net/geometry/lineline3d/ .
@param v0 The starting point of the first line.
@param v10 The direction vector of the first line. This can be unnormalized.
@param v2 The starting point of the second line.
@param v32 The direction vector of the second line. This can be unnormalized.
@param d [out] Receives the normalized distance of the closest point along the first line.
@param d2 [out] Receives the normalized distance of the closest point along the second line.
@return Returns the closest point on line start0<->end0 to the second line.
@note This is a low-level utility function. You probably want to use ClosestPoint() or Distance() instead.
@see ClosestPoint(), Distance(). */
void Line::ClosestPointLineLine(const vec &v0, const vec &v10, const vec &v2, const vec &v32, float &d, float &d2)
{
assume(!v10.IsZero());
assume(!v32.IsZero());
vec v02 = v0 - v2;
float d0232 = v02.Dot(v32);
float d3210 = v32.Dot(v10);
float d3232 = v32.Dot(v32);
assume(d3232 != 0.f); // Don't call with a zero direction vector.
float d0210 = v02.Dot(v10);
float d1010 = v10.Dot(v10);
float denom = d1010*d3232 - d3210*d3210;
if (denom != 0.f)
d = (d0232*d3210 - d0210*d3232) / denom;
else
d = 0.f;
d2 = (d0232 + d * d3210) / d3232;
}
Line::Line(const vec &pos_, const vec &dir_)
:pos(pos_), dir(dir_)
{
assume2(dir.IsNormalized(), dir, dir.LengthSq());
}
Line::Line(const Ray &ray)
:pos(ray.pos), dir(ray.dir)
{
assume2(dir.IsNormalized(), dir, dir.LengthSq());
}
Line::Line(const LineSegment &lineSegment)
:pos(lineSegment.a), dir(lineSegment.Dir())
{
}
bool Line::IsFinite() const
{
return pos.IsFinite() && dir.IsFinite();
}
vec Line::GetPoint(float d) const
{
assume2(dir.IsNormalized(), dir, dir.LengthSq());
return pos + d * dir;
}
void Line::Translate(const vec &offset)
{
pos += offset;
}
void Line::Transform(const float3x3 &transform)
{
pos = transform.Transform(pos);
dir = transform.Transform(dir);
}
void Line::Transform(const float3x4 &transform)
{
pos = transform.MulPos(pos);
dir = transform.MulDir(dir);
}
void Line::Transform(const float4x4 &transform)
{
pos = transform.MulPos(pos);
dir = transform.MulDir(dir);
}
void Line::Transform(const Quat &transform)
{
pos = transform.Transform(pos);
dir = transform.Transform(dir);
}
bool Line::Contains(const vec &point, float distanceThreshold) const
{
return ClosestPoint(point).DistanceSq(point) <= distanceThreshold;
}
bool Line::Contains(const Ray &ray, float epsilon) const
{
return Contains(ray.pos, epsilon) && dir.Equals(ray.dir, epsilon);
}
bool Line::Contains(const LineSegment &lineSegment, float epsilon) const
{
return Contains(lineSegment.a, epsilon) && Contains(lineSegment.b, epsilon);
}
bool Line::Equals(const Line &line, float epsilon) const
{
assume2(dir.IsNormalized(), dir, dir.LengthSq());
assume2(line.dir.IsNormalized(), line.dir, line.dir.LengthSq());
// If the point of the other line is on this line, and the two lines point to the same, or exactly reverse directions,
// they must be equal.
return Contains(line.pos, epsilon) && EqualAbs(Abs(dir.Dot(line.dir)), 1.f, epsilon);
}
float Line::Distance(const vec &point, float &d) const
{
return ClosestPoint(point, d).Distance(point);
}
float Line::Distance(const Ray &other, float &d, float &d2) const
{
vec c = ClosestPoint(other, d, d2);
return c.Distance(other.GetPoint(d2));
}
float Line::Distance(const Line &other, float &d, float &d2) const
{
vec c = ClosestPoint(other, d, d2);
return c.Distance(other.GetPoint(d2));
}
float Line::Distance(const LineSegment &other, float &d, float &d2) const
{
vec c = ClosestPoint(other, d, d2);
mathassert(d2 >= 0.f);
mathassert(d2 <= 1.f);
return c.Distance(other.GetPoint(d2));
}
float Line::Distance(const Sphere &other) const
{
return Max(0.f, Distance(other.pos) - other.r);
}
float Line::Distance(const Capsule &other) const
{
return Max(0.f, Distance(other.l) - other.r);
}
bool Line::Intersects(const Triangle &triangle, float *d, vec *intersectionPoint) const
{
return triangle.Intersects(*this, d, intersectionPoint);
}
bool Line::Intersects(const Plane &plane, float *d) const
{
return plane.Intersects(*this, d);
}
bool Line::Intersects(const Sphere &s, vec *intersectionPoint, vec *intersectionNormal, float *d) const
{
return s.Intersects(*this, intersectionPoint, intersectionNormal, d) > 0;
}
bool Line::Intersects(const AABB &aabb) const
{
return aabb.Intersects(*this);
}
bool Line::Intersects(const AABB &aabb, float &dNear, float &dFar) const
{
return aabb.Intersects(*this, dNear, dFar);
}
bool Line::Intersects(const OBB &obb) const
{
return obb.Intersects(*this);
}
bool Line::Intersects(const OBB &obb, float &dNear, float &dFar) const
{
return obb.Intersects(*this, dNear, dFar);
}
bool Line::Intersects(const Capsule &capsule) const
{
return capsule.Intersects(*this);
}
bool Line::Intersects(const Polygon &polygon) const
{
return polygon.Intersects(*this);
}
bool Line::Intersects(const Frustum &frustum) const
{
return frustum.Intersects(*this);
}
bool Line::Intersects(const Polyhedron &polyhedron) const
{
return polyhedron.Intersects(*this);
}
bool Line::IntersectsDisc(const Circle &disc) const
{
return disc.IntersectsDisc(*this);
}
vec Line::ClosestPoint(const vec &targetPoint, float &d) const
{
d = Dot(targetPoint - pos, dir);
return GetPoint(d);
}
vec Line::ClosestPoint(const Ray &other, float &d, float &d2) const
{
ClosestPointLineLine(pos, dir, other.pos, other.dir, d, d2);
if (d2 >= 0.f)
return GetPoint(d);
else
{
d2 = 0.f;
return ClosestPoint(other.pos, d);
}
}
vec Line::ClosestPoint(const Line &other, float &d, float &d2) const
{
ClosestPointLineLine(pos, dir, other.pos, other.dir, d, d2);
return GetPoint(d);
}
vec Line::ClosestPoint(const LineSegment &other, float &d, float &d2) const
{
ClosestPointLineLine(pos, dir, other.a, other.b - other.a, d, d2);
if (d2 < 0.f)
{
d2 = 0.f;
return ClosestPoint(other.a, d);
}
else if (d2 > 1.f)
{
d2 = 1.f;
return ClosestPoint(other.b, d);
}
else
return GetPoint(d);
}
vec Line::ClosestPoint(const Triangle &triangle, float &d) const
{
vec closestPointTriangle = triangle.ClosestPoint(*this);
return ClosestPoint(closestPointTriangle, d);
}
vec Line::ClosestPoint(const Triangle &triangle, float &d, float2 &outBarycentricUV) const
{
vec closestPointTriangle = triangle.ClosestPoint(*this);
outBarycentricUV = triangle.BarycentricUV(closestPointTriangle);
return ClosestPoint(closestPointTriangle, d);
}
bool Line::AreCollinear(const vec &p1, const vec &p2, const vec &p3, float epsilon)
{
return vec::AreCollinear(p1, p2, p3, epsilon);
}
Ray Line::ToRay() const
{
return Ray(pos, dir);
}
LineSegment Line::ToLineSegment(float d) const
{
return LineSegment(pos, GetPoint(d));
}
void Line::ProjectToAxis(const vec &direction, float &outMin, float &outMax) const
{
// Most of the time, the projection of a line spans the whole 1D axis.
// As a special case, if the line is perpendicular to the direction vector in question,
// then the projection interval of this line is a single point.
if (dir.IsPerpendicular(direction))
outMin = outMax = Dot(direction, pos);
else
{
outMin = -FLOAT_INF;
outMax = FLOAT_INF;
}
}
LineSegment Line::ToLineSegment(float dStart, float dEnd) const
{
return LineSegment(GetPoint(dStart), GetPoint(dEnd));
}
Line operator *(const float3x3 &transform, const Line &l)
{
return Line(transform * l.pos, transform * l.dir);
}
Line operator *(const float3x4 &transform, const Line &l)
{
return Line(transform.MulPos(l.pos), transform.MulDir(l.dir));
}
Line operator *(const float4x4 &transform, const Line &l)
{
return Line(transform.MulPos(l.pos), transform.MulDir(l.dir));
}
Line operator *(const Quat &transform, const Line &l)
{
return Line(transform * l.pos, transform * l.dir);
}
#ifdef MATH_ENABLE_STL_SUPPORT
std::string Line::ToString() const
{
char str[256];
sprintf(str, "Line(Pos:(%.2f, %.2f, %.2f) Dir:(%.3f, %.3f, %.3f))", pos.x, pos.y, pos.z, dir.x, dir.y, dir.z);
return str;
}
std::string Line::SerializeToString() const
{
char str[256];
char *s = SerializeFloat(pos.x, str); *s = ','; ++s;
s = SerializeFloat(pos.y, s); *s = ','; ++s;
s = SerializeFloat(pos.z, s); *s = ','; ++s;
s = SerializeFloat(dir.x, s); *s = ','; ++s;
s = SerializeFloat(dir.y, s); *s = ','; ++s;
s = SerializeFloat(dir.z, s);
assert(s+1 - str < 256);
MARK_UNUSED(s);
return str;
}
std::string Line::SerializeToCodeString() const
{
return "Line(" + pos.SerializeToCodeString() + "," + dir.SerializeToCodeString() + ")";
}
std::ostream &operator <<(std::ostream &o, const Line &line)
{
o << line.ToString();
return o;
}
#endif
Line Line::FromString(const char *str, const char **outEndStr)
{
assume(str);
if (!str)
return Line(vec::nan, vec::nan);
Line l;
MATH_SKIP_WORD(str, "Line(");
MATH_SKIP_WORD(str, "Pos:(");
l.pos = PointVecFromString(str, &str);
MATH_SKIP_WORD(str, " Dir:(");
l.dir = DirVecFromString(str, &str);
if (outEndStr)
*outEndStr = str;
return l;
}
MATH_END_NAMESPACE
| gpl-3.0 |
crodrigues96/mtasa-blue | MTA10_Server/mods/deathmatch/logic/packets/CResourceClientScriptsPacket.cpp | 28 | 1596 | /*****************************************************************************
*
* PROJECT: Multi Theft Auto v1.3
* LICENSE: See LICENSE in the top level directory
* FILE: mods/deathmatch/logic/packets/CResourceClientScriptsPacket.cpp
* PURPOSE: Resource client-side scripts packet class
* DEVELOPERS: Alberto Alonso <rydencillo@gmail.com>
*
* Multi Theft Auto is available from http://www.multitheftauto.com/
*
*****************************************************************************/
#include "StdInc.h"
CResourceClientScriptsPacket::CResourceClientScriptsPacket ( CResource* pResource )
: m_pResource ( pResource )
{}
void CResourceClientScriptsPacket::AddItem ( CResourceClientScriptItem* pItem )
{
m_vecItems.push_back ( pItem );
}
bool CResourceClientScriptsPacket::Write ( NetBitStreamInterface& BitStream ) const
{
if ( m_vecItems.size() == 0 )
return false;
BitStream.Write ( m_pResource->GetNetID() );
unsigned short usItemCount = m_vecItems.size();
BitStream.Write ( usItemCount );
for ( std::vector<CResourceClientScriptItem*>::const_iterator iter = m_vecItems.begin ();
iter != m_vecItems.end();
++iter )
{
if ( BitStream.Version() >= 0x50 )
BitStream.WriteString( ConformResourcePath( (*iter)->GetFullName() ) );
const SString& data = (*iter)->GetSourceCode ();
unsigned int len = data.length ();
BitStream.Write ( len );
BitStream.Write ( data.c_str(), len );
}
return true;
}
| gpl-3.0 |
loele/samba | source3/winbindd/wb_gettoken.c | 29 | 6366 | /*
Unix SMB/CIFS implementation.
async gettoken
Copyright (C) Volker Lendecke 2009
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "includes.h"
#include "winbindd.h"
#include "librpc/gen_ndr/ndr_winbind_c.h"
#include "../libcli/security/security.h"
#include "passdb/machine_sid.h"
struct wb_gettoken_state {
struct tevent_context *ev;
struct dom_sid usersid;
int num_sids;
struct dom_sid *sids;
};
static bool wb_add_rids_to_sids(TALLOC_CTX *mem_ctx,
int *pnum_sids, struct dom_sid **psids,
const struct dom_sid *domain_sid,
int num_rids, uint32_t *rids);
static void wb_gettoken_gotgroups(struct tevent_req *subreq);
static void wb_gettoken_gotlocalgroups(struct tevent_req *subreq);
static void wb_gettoken_gotbuiltins(struct tevent_req *subreq);
struct tevent_req *wb_gettoken_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
const struct dom_sid *sid)
{
struct tevent_req *req, *subreq;
struct wb_gettoken_state *state;
struct winbindd_domain *domain;
req = tevent_req_create(mem_ctx, &state, struct wb_gettoken_state);
if (req == NULL) {
return NULL;
}
sid_copy(&state->usersid, sid);
state->ev = ev;
domain = find_domain_from_sid_noinit(sid);
if (domain == NULL) {
DEBUG(5, ("Could not find domain from SID %s\n",
sid_string_dbg(sid)));
tevent_req_nterror(req, NT_STATUS_NO_SUCH_USER);
return tevent_req_post(req, ev);
}
if (lp_winbind_trusted_domains_only() && domain->primary) {
DEBUG(7, ("wb_gettoken: My domain -- rejecting getgroups() "
"for %s.\n", sid_string_tos(sid)));
tevent_req_nterror(req, NT_STATUS_NO_SUCH_USER);
return tevent_req_post(req, ev);
}
subreq = wb_lookupusergroups_send(state, ev, domain, &state->usersid);
if (tevent_req_nomem(subreq, req)) {
return tevent_req_post(req, ev);
}
tevent_req_set_callback(subreq, wb_gettoken_gotgroups, req);
return req;
}
static void wb_gettoken_gotgroups(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
struct wb_gettoken_state *state = tevent_req_data(
req, struct wb_gettoken_state);
struct dom_sid *sids;
struct winbindd_domain *domain;
NTSTATUS status;
status = wb_lookupusergroups_recv(subreq, state, &state->num_sids,
&state->sids);
TALLOC_FREE(subreq);
if (tevent_req_nterror(req, status)) {
return;
}
sids = talloc_realloc(state, state->sids, struct dom_sid,
state->num_sids + 1);
if (tevent_req_nomem(sids, req)) {
return;
}
memmove(&sids[1], &sids[0], state->num_sids * sizeof(sids[0]));
sid_copy(&sids[0], &state->usersid);
state->num_sids += 1;
state->sids = sids;
/*
* Expand our domain's aliases
*/
domain = find_domain_from_sid_noinit(get_global_sam_sid());
if (domain == NULL) {
tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
return;
}
subreq = wb_lookupuseraliases_send(state, state->ev, domain,
state->num_sids, state->sids);
if (tevent_req_nomem(subreq, req)) {
return;
}
tevent_req_set_callback(subreq, wb_gettoken_gotlocalgroups, req);
}
static void wb_gettoken_gotlocalgroups(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
struct wb_gettoken_state *state = tevent_req_data(
req, struct wb_gettoken_state);
uint32_t num_rids;
uint32_t *rids;
struct winbindd_domain *domain;
NTSTATUS status;
status = wb_lookupuseraliases_recv(subreq, state, &num_rids, &rids);
TALLOC_FREE(subreq);
if (tevent_req_nterror(req, status)) {
return;
}
domain = find_domain_from_sid_noinit(get_global_sam_sid());
if (domain == NULL) {
tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
return;
}
if (!wb_add_rids_to_sids(state, &state->num_sids, &state->sids,
&domain->sid, num_rids, rids)) {
tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
return;
}
TALLOC_FREE(rids);
/*
* Now expand the builtin groups
*/
domain = find_builtin_domain();
if (domain == NULL) {
tevent_req_nterror(req, NT_STATUS_INTERNAL_ERROR);
return;
}
subreq = wb_lookupuseraliases_send(state, state->ev, domain,
state->num_sids, state->sids);
if (tevent_req_nomem(subreq, req)) {
return;
}
tevent_req_set_callback(subreq, wb_gettoken_gotbuiltins, req);
}
static void wb_gettoken_gotbuiltins(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
struct wb_gettoken_state *state = tevent_req_data(
req, struct wb_gettoken_state);
uint32_t num_rids;
uint32_t *rids;
NTSTATUS status;
status = wb_lookupuseraliases_recv(subreq, state, &num_rids, &rids);
TALLOC_FREE(subreq);
if (tevent_req_nterror(req, status)) {
return;
}
if (!wb_add_rids_to_sids(state, &state->num_sids, &state->sids,
&global_sid_Builtin, num_rids, rids)) {
tevent_req_nterror(req, NT_STATUS_NO_MEMORY);
return;
}
tevent_req_done(req);
}
NTSTATUS wb_gettoken_recv(struct tevent_req *req, TALLOC_CTX *mem_ctx,
int *num_sids, struct dom_sid **sids)
{
struct wb_gettoken_state *state = tevent_req_data(
req, struct wb_gettoken_state);
NTSTATUS status;
if (tevent_req_is_nterror(req, &status)) {
return status;
}
*num_sids = state->num_sids;
*sids = talloc_move(mem_ctx, &state->sids);
return NT_STATUS_OK;
}
static bool wb_add_rids_to_sids(TALLOC_CTX *mem_ctx,
int *pnum_sids, struct dom_sid **psids,
const struct dom_sid *domain_sid,
int num_rids, uint32_t *rids)
{
struct dom_sid *sids;
int i;
sids = talloc_realloc(mem_ctx, *psids, struct dom_sid,
*pnum_sids + num_rids);
if (sids == NULL) {
return false;
}
for (i=0; i<num_rids; i++) {
sid_compose(&sids[i+*pnum_sids], domain_sid, rids[i]);
}
*pnum_sids += num_rids;
*psids = sids;
return true;
}
| gpl-3.0 |
youssef-emad/shogun | src/shogun/preprocessor/SumOne.cpp | 31 | 2146 | /*
* 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.
*
* Written (W) 2012 Sergey Lisitsyn
* Copyright (C) 2012 Sergey Lisitsyn
*/
#include <shogun/preprocessor/SumOne.h>
#include <shogun/preprocessor/DensePreprocessor.h>
#include <shogun/mathematics/Math.h>
#include <shogun/features/Features.h>
using namespace shogun;
CSumOne::CSumOne()
: CDensePreprocessor<float64_t>()
{
}
CSumOne::~CSumOne()
{
}
/// initialize preprocessor from features
bool CSumOne::init(CFeatures* features)
{
ASSERT(features->get_feature_class()==C_DENSE)
ASSERT(features->get_feature_type()==F_DREAL)
return true;
}
/// clean up allocated memory
void CSumOne::cleanup()
{
}
/// initialize preprocessor from file
bool CSumOne::load(FILE* f)
{
SG_SET_LOCALE_C;
SG_RESET_LOCALE;
return false;
}
/// save preprocessor init-data to file
bool CSumOne::save(FILE* f)
{
SG_SET_LOCALE_C;
SG_RESET_LOCALE;
return false;
}
/// apply preproc on feature matrix
/// result in feature matrix
/// return pointer to feature_matrix, i.e. f->get_feature_matrix();
SGMatrix<float64_t> CSumOne::apply_to_feature_matrix(CFeatures* features)
{
SGMatrix<float64_t> feature_matrix=((CDenseFeatures<float64_t>*)features)->get_feature_matrix();
for (int32_t i=0; i<feature_matrix.num_cols; i++)
{
float64_t* vec= &(feature_matrix.matrix[i*feature_matrix.num_rows]);
float64_t sum = SGVector<float64_t>::sum(vec,feature_matrix.num_rows);
SGVector<float64_t>::scale_vector(1.0/sum, vec, feature_matrix.num_rows);
}
return feature_matrix;
}
/// apply preproc on single feature vector
/// result in feature matrix
SGVector<float64_t> CSumOne::apply_to_feature_vector(SGVector<float64_t> vector)
{
float64_t* normed_vec = SG_MALLOC(float64_t, vector.vlen);
float64_t sum = SGVector<float64_t>::sum(vector.vector, vector.vlen);
for (int32_t i=0; i<vector.vlen; i++)
normed_vec[i]=vector.vector[i]/sum;
return SGVector<float64_t>(normed_vec,vector.vlen);
}
| gpl-3.0 |
r2t2sdr/r2t2 | linux/trunk/linux-4.0-adi/drivers/gpu/drm/udl/udl_fb.c | 543 | 16678 | /*
* Copyright (C) 2012 Red Hat
*
* based in parts on udlfb.c:
* Copyright (C) 2009 Roberto De Ioris <roberto@unbit.it>
* Copyright (C) 2009 Jaya Kumar <jayakumar.lkml@gmail.com>
* Copyright (C) 2009 Bernie Thompson <bernie@plugable.com>
*
* This file is subject to the terms and conditions of the GNU General Public
* License v2. See the file COPYING in the main directory of this archive for
* more details.
*/
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/fb.h>
#include <linux/dma-buf.h>
#include <drm/drmP.h>
#include <drm/drm_crtc.h>
#include <drm/drm_crtc_helper.h>
#include "udl_drv.h"
#include <drm/drm_fb_helper.h>
#define DL_DEFIO_WRITE_DELAY (HZ/20) /* fb_deferred_io.delay in jiffies */
static int fb_defio = 0; /* Optionally enable experimental fb_defio mmap support */
static int fb_bpp = 16;
module_param(fb_bpp, int, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP);
module_param(fb_defio, int, S_IWUSR | S_IRUSR | S_IWGRP | S_IRGRP);
struct udl_fbdev {
struct drm_fb_helper helper;
struct udl_framebuffer ufb;
struct list_head fbdev_list;
int fb_count;
};
#define DL_ALIGN_UP(x, a) ALIGN(x, a)
#define DL_ALIGN_DOWN(x, a) ALIGN(x-(a-1), a)
/** Read the red component (0..255) of a 32 bpp colour. */
#define DLO_RGB_GETRED(col) (uint8_t)((col) & 0xFF)
/** Read the green component (0..255) of a 32 bpp colour. */
#define DLO_RGB_GETGRN(col) (uint8_t)(((col) >> 8) & 0xFF)
/** Read the blue component (0..255) of a 32 bpp colour. */
#define DLO_RGB_GETBLU(col) (uint8_t)(((col) >> 16) & 0xFF)
/** Return red/green component of a 16 bpp colour number. */
#define DLO_RG16(red, grn) (uint8_t)((((red) & 0xF8) | ((grn) >> 5)) & 0xFF)
/** Return green/blue component of a 16 bpp colour number. */
#define DLO_GB16(grn, blu) (uint8_t)(((((grn) & 0x1C) << 3) | ((blu) >> 3)) & 0xFF)
/** Return 8 bpp colour number from red, green and blue components. */
#define DLO_RGB8(red, grn, blu) ((((red) << 5) | (((grn) & 3) << 3) | ((blu) & 7)) & 0xFF)
#if 0
static uint8_t rgb8(uint32_t col)
{
uint8_t red = DLO_RGB_GETRED(col);
uint8_t grn = DLO_RGB_GETGRN(col);
uint8_t blu = DLO_RGB_GETBLU(col);
return DLO_RGB8(red, grn, blu);
}
static uint16_t rgb16(uint32_t col)
{
uint8_t red = DLO_RGB_GETRED(col);
uint8_t grn = DLO_RGB_GETGRN(col);
uint8_t blu = DLO_RGB_GETBLU(col);
return (DLO_RG16(red, grn) << 8) + DLO_GB16(grn, blu);
}
#endif
/*
* NOTE: fb_defio.c is holding info->fbdefio.mutex
* Touching ANY framebuffer memory that triggers a page fault
* in fb_defio will cause a deadlock, when it also tries to
* grab the same mutex.
*/
static void udlfb_dpy_deferred_io(struct fb_info *info,
struct list_head *pagelist)
{
struct page *cur;
struct fb_deferred_io *fbdefio = info->fbdefio;
struct udl_fbdev *ufbdev = info->par;
struct drm_device *dev = ufbdev->ufb.base.dev;
struct udl_device *udl = dev->dev_private;
struct urb *urb;
char *cmd;
cycles_t start_cycles, end_cycles;
int bytes_sent = 0;
int bytes_identical = 0;
int bytes_rendered = 0;
if (!fb_defio)
return;
start_cycles = get_cycles();
urb = udl_get_urb(dev);
if (!urb)
return;
cmd = urb->transfer_buffer;
/* walk the written page list and render each to device */
list_for_each_entry(cur, &fbdefio->pagelist, lru) {
if (udl_render_hline(dev, (ufbdev->ufb.base.bits_per_pixel / 8),
&urb, (char *) info->fix.smem_start,
&cmd, cur->index << PAGE_SHIFT,
cur->index << PAGE_SHIFT,
PAGE_SIZE, &bytes_identical, &bytes_sent))
goto error;
bytes_rendered += PAGE_SIZE;
}
if (cmd > (char *) urb->transfer_buffer) {
/* Send partial buffer remaining before exiting */
int len = cmd - (char *) urb->transfer_buffer;
udl_submit_urb(dev, urb, len);
bytes_sent += len;
} else
udl_urb_completion(urb);
error:
atomic_add(bytes_sent, &udl->bytes_sent);
atomic_add(bytes_identical, &udl->bytes_identical);
atomic_add(bytes_rendered, &udl->bytes_rendered);
end_cycles = get_cycles();
atomic_add(((unsigned int) ((end_cycles - start_cycles)
>> 10)), /* Kcycles */
&udl->cpu_kcycles_used);
}
int udl_handle_damage(struct udl_framebuffer *fb, int x, int y,
int width, int height)
{
struct drm_device *dev = fb->base.dev;
struct udl_device *udl = dev->dev_private;
int i, ret;
char *cmd;
cycles_t start_cycles, end_cycles;
int bytes_sent = 0;
int bytes_identical = 0;
struct urb *urb;
int aligned_x;
int bpp = (fb->base.bits_per_pixel / 8);
int x2, y2;
bool store_for_later = false;
unsigned long flags;
if (!fb->active_16)
return 0;
if (!fb->obj->vmapping) {
ret = udl_gem_vmap(fb->obj);
if (ret == -ENOMEM) {
DRM_ERROR("failed to vmap fb\n");
return 0;
}
if (!fb->obj->vmapping) {
DRM_ERROR("failed to vmapping\n");
return 0;
}
}
aligned_x = DL_ALIGN_DOWN(x, sizeof(unsigned long));
width = DL_ALIGN_UP(width + (x-aligned_x), sizeof(unsigned long));
x = aligned_x;
if ((width <= 0) ||
(x + width > fb->base.width) ||
(y + height > fb->base.height))
return -EINVAL;
/* if we are in atomic just store the info
can't test inside spin lock */
if (in_atomic())
store_for_later = true;
x2 = x + width - 1;
y2 = y + height - 1;
spin_lock_irqsave(&fb->dirty_lock, flags);
if (fb->y1 < y)
y = fb->y1;
if (fb->y2 > y2)
y2 = fb->y2;
if (fb->x1 < x)
x = fb->x1;
if (fb->x2 > x2)
x2 = fb->x2;
if (store_for_later) {
fb->x1 = x;
fb->x2 = x2;
fb->y1 = y;
fb->y2 = y2;
spin_unlock_irqrestore(&fb->dirty_lock, flags);
return 0;
}
fb->x1 = fb->y1 = INT_MAX;
fb->x2 = fb->y2 = 0;
spin_unlock_irqrestore(&fb->dirty_lock, flags);
start_cycles = get_cycles();
urb = udl_get_urb(dev);
if (!urb)
return 0;
cmd = urb->transfer_buffer;
for (i = y; i <= y2 ; i++) {
const int line_offset = fb->base.pitches[0] * i;
const int byte_offset = line_offset + (x * bpp);
const int dev_byte_offset = (fb->base.width * bpp * i) + (x * bpp);
if (udl_render_hline(dev, bpp, &urb,
(char *) fb->obj->vmapping,
&cmd, byte_offset, dev_byte_offset,
(x2 - x + 1) * bpp,
&bytes_identical, &bytes_sent))
goto error;
}
if (cmd > (char *) urb->transfer_buffer) {
/* Send partial buffer remaining before exiting */
int len = cmd - (char *) urb->transfer_buffer;
ret = udl_submit_urb(dev, urb, len);
bytes_sent += len;
} else
udl_urb_completion(urb);
error:
atomic_add(bytes_sent, &udl->bytes_sent);
atomic_add(bytes_identical, &udl->bytes_identical);
atomic_add(width*height*bpp, &udl->bytes_rendered);
end_cycles = get_cycles();
atomic_add(((unsigned int) ((end_cycles - start_cycles)
>> 10)), /* Kcycles */
&udl->cpu_kcycles_used);
return 0;
}
static int udl_fb_mmap(struct fb_info *info, struct vm_area_struct *vma)
{
unsigned long start = vma->vm_start;
unsigned long size = vma->vm_end - vma->vm_start;
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
unsigned long page, pos;
if (offset + size > info->fix.smem_len)
return -EINVAL;
pos = (unsigned long)info->fix.smem_start + offset;
pr_notice("mmap() framebuffer addr:%lu size:%lu\n",
pos, size);
while (size > 0) {
page = vmalloc_to_pfn((void *)pos);
if (remap_pfn_range(vma, start, page, PAGE_SIZE, PAGE_SHARED))
return -EAGAIN;
start += PAGE_SIZE;
pos += PAGE_SIZE;
if (size > PAGE_SIZE)
size -= PAGE_SIZE;
else
size = 0;
}
/* VM_IO | VM_DONTEXPAND | VM_DONTDUMP are set by remap_pfn_range() */
return 0;
}
static void udl_fb_fillrect(struct fb_info *info, const struct fb_fillrect *rect)
{
struct udl_fbdev *ufbdev = info->par;
sys_fillrect(info, rect);
udl_handle_damage(&ufbdev->ufb, rect->dx, rect->dy, rect->width,
rect->height);
}
static void udl_fb_copyarea(struct fb_info *info, const struct fb_copyarea *region)
{
struct udl_fbdev *ufbdev = info->par;
sys_copyarea(info, region);
udl_handle_damage(&ufbdev->ufb, region->dx, region->dy, region->width,
region->height);
}
static void udl_fb_imageblit(struct fb_info *info, const struct fb_image *image)
{
struct udl_fbdev *ufbdev = info->par;
sys_imageblit(info, image);
udl_handle_damage(&ufbdev->ufb, image->dx, image->dy, image->width,
image->height);
}
/*
* It's common for several clients to have framebuffer open simultaneously.
* e.g. both fbcon and X. Makes things interesting.
* Assumes caller is holding info->lock (for open and release at least)
*/
static int udl_fb_open(struct fb_info *info, int user)
{
struct udl_fbdev *ufbdev = info->par;
struct drm_device *dev = ufbdev->ufb.base.dev;
struct udl_device *udl = dev->dev_private;
/* If the USB device is gone, we don't accept new opens */
if (drm_device_is_unplugged(udl->ddev))
return -ENODEV;
ufbdev->fb_count++;
if (fb_defio && (info->fbdefio == NULL)) {
/* enable defio at last moment if not disabled by client */
struct fb_deferred_io *fbdefio;
fbdefio = kmalloc(sizeof(struct fb_deferred_io), GFP_KERNEL);
if (fbdefio) {
fbdefio->delay = DL_DEFIO_WRITE_DELAY;
fbdefio->deferred_io = udlfb_dpy_deferred_io;
}
info->fbdefio = fbdefio;
fb_deferred_io_init(info);
}
pr_notice("open /dev/fb%d user=%d fb_info=%p count=%d\n",
info->node, user, info, ufbdev->fb_count);
return 0;
}
/*
* Assumes caller is holding info->lock mutex (for open and release at least)
*/
static int udl_fb_release(struct fb_info *info, int user)
{
struct udl_fbdev *ufbdev = info->par;
ufbdev->fb_count--;
if ((ufbdev->fb_count == 0) && (info->fbdefio)) {
fb_deferred_io_cleanup(info);
kfree(info->fbdefio);
info->fbdefio = NULL;
info->fbops->fb_mmap = udl_fb_mmap;
}
pr_warn("released /dev/fb%d user=%d count=%d\n",
info->node, user, ufbdev->fb_count);
return 0;
}
static struct fb_ops udlfb_ops = {
.owner = THIS_MODULE,
.fb_check_var = drm_fb_helper_check_var,
.fb_set_par = drm_fb_helper_set_par,
.fb_fillrect = udl_fb_fillrect,
.fb_copyarea = udl_fb_copyarea,
.fb_imageblit = udl_fb_imageblit,
.fb_pan_display = drm_fb_helper_pan_display,
.fb_blank = drm_fb_helper_blank,
.fb_setcmap = drm_fb_helper_setcmap,
.fb_debug_enter = drm_fb_helper_debug_enter,
.fb_debug_leave = drm_fb_helper_debug_leave,
.fb_mmap = udl_fb_mmap,
.fb_open = udl_fb_open,
.fb_release = udl_fb_release,
};
static int udl_user_framebuffer_dirty(struct drm_framebuffer *fb,
struct drm_file *file,
unsigned flags, unsigned color,
struct drm_clip_rect *clips,
unsigned num_clips)
{
struct udl_framebuffer *ufb = to_udl_fb(fb);
int i;
int ret = 0;
drm_modeset_lock_all(fb->dev);
if (!ufb->active_16)
goto unlock;
if (ufb->obj->base.import_attach) {
ret = dma_buf_begin_cpu_access(ufb->obj->base.import_attach->dmabuf,
0, ufb->obj->base.size,
DMA_FROM_DEVICE);
if (ret)
goto unlock;
}
for (i = 0; i < num_clips; i++) {
ret = udl_handle_damage(ufb, clips[i].x1, clips[i].y1,
clips[i].x2 - clips[i].x1,
clips[i].y2 - clips[i].y1);
if (ret)
break;
}
if (ufb->obj->base.import_attach) {
dma_buf_end_cpu_access(ufb->obj->base.import_attach->dmabuf,
0, ufb->obj->base.size,
DMA_FROM_DEVICE);
}
unlock:
drm_modeset_unlock_all(fb->dev);
return ret;
}
static void udl_user_framebuffer_destroy(struct drm_framebuffer *fb)
{
struct udl_framebuffer *ufb = to_udl_fb(fb);
if (ufb->obj)
drm_gem_object_unreference_unlocked(&ufb->obj->base);
drm_framebuffer_cleanup(fb);
kfree(ufb);
}
static const struct drm_framebuffer_funcs udlfb_funcs = {
.destroy = udl_user_framebuffer_destroy,
.dirty = udl_user_framebuffer_dirty,
};
static int
udl_framebuffer_init(struct drm_device *dev,
struct udl_framebuffer *ufb,
struct drm_mode_fb_cmd2 *mode_cmd,
struct udl_gem_object *obj)
{
int ret;
spin_lock_init(&ufb->dirty_lock);
ufb->obj = obj;
drm_helper_mode_fill_fb_struct(&ufb->base, mode_cmd);
ret = drm_framebuffer_init(dev, &ufb->base, &udlfb_funcs);
return ret;
}
static int udlfb_create(struct drm_fb_helper *helper,
struct drm_fb_helper_surface_size *sizes)
{
struct udl_fbdev *ufbdev =
container_of(helper, struct udl_fbdev, helper);
struct drm_device *dev = ufbdev->helper.dev;
struct fb_info *info;
struct device *device = dev->dev;
struct drm_framebuffer *fb;
struct drm_mode_fb_cmd2 mode_cmd;
struct udl_gem_object *obj;
uint32_t size;
int ret = 0;
if (sizes->surface_bpp == 24)
sizes->surface_bpp = 32;
mode_cmd.width = sizes->surface_width;
mode_cmd.height = sizes->surface_height;
mode_cmd.pitches[0] = mode_cmd.width * ((sizes->surface_bpp + 7) / 8);
mode_cmd.pixel_format = drm_mode_legacy_fb_format(sizes->surface_bpp,
sizes->surface_depth);
size = mode_cmd.pitches[0] * mode_cmd.height;
size = ALIGN(size, PAGE_SIZE);
obj = udl_gem_alloc_object(dev, size);
if (!obj)
goto out;
ret = udl_gem_vmap(obj);
if (ret) {
DRM_ERROR("failed to vmap fb\n");
goto out_gfree;
}
info = framebuffer_alloc(0, device);
if (!info) {
ret = -ENOMEM;
goto out_gfree;
}
info->par = ufbdev;
ret = udl_framebuffer_init(dev, &ufbdev->ufb, &mode_cmd, obj);
if (ret)
goto out_gfree;
fb = &ufbdev->ufb.base;
ufbdev->helper.fb = fb;
ufbdev->helper.fbdev = info;
strcpy(info->fix.id, "udldrmfb");
info->screen_base = ufbdev->ufb.obj->vmapping;
info->fix.smem_len = size;
info->fix.smem_start = (unsigned long)ufbdev->ufb.obj->vmapping;
info->flags = FBINFO_DEFAULT | FBINFO_CAN_FORCE_OUTPUT;
info->fbops = &udlfb_ops;
drm_fb_helper_fill_fix(info, fb->pitches[0], fb->depth);
drm_fb_helper_fill_var(info, &ufbdev->helper, sizes->fb_width, sizes->fb_height);
ret = fb_alloc_cmap(&info->cmap, 256, 0);
if (ret) {
ret = -ENOMEM;
goto out_gfree;
}
DRM_DEBUG_KMS("allocated %dx%d vmal %p\n",
fb->width, fb->height,
ufbdev->ufb.obj->vmapping);
return ret;
out_gfree:
drm_gem_object_unreference(&ufbdev->ufb.obj->base);
out:
return ret;
}
static const struct drm_fb_helper_funcs udl_fb_helper_funcs = {
.fb_probe = udlfb_create,
};
static void udl_fbdev_destroy(struct drm_device *dev,
struct udl_fbdev *ufbdev)
{
struct fb_info *info;
if (ufbdev->helper.fbdev) {
info = ufbdev->helper.fbdev;
unregister_framebuffer(info);
if (info->cmap.len)
fb_dealloc_cmap(&info->cmap);
framebuffer_release(info);
}
drm_fb_helper_fini(&ufbdev->helper);
drm_framebuffer_unregister_private(&ufbdev->ufb.base);
drm_framebuffer_cleanup(&ufbdev->ufb.base);
drm_gem_object_unreference_unlocked(&ufbdev->ufb.obj->base);
}
int udl_fbdev_init(struct drm_device *dev)
{
struct udl_device *udl = dev->dev_private;
int bpp_sel = fb_bpp;
struct udl_fbdev *ufbdev;
int ret;
ufbdev = kzalloc(sizeof(struct udl_fbdev), GFP_KERNEL);
if (!ufbdev)
return -ENOMEM;
udl->fbdev = ufbdev;
drm_fb_helper_prepare(dev, &ufbdev->helper, &udl_fb_helper_funcs);
ret = drm_fb_helper_init(dev, &ufbdev->helper,
1, 1);
if (ret)
goto free;
ret = drm_fb_helper_single_add_all_connectors(&ufbdev->helper);
if (ret)
goto fini;
/* disable all the possible outputs/crtcs before entering KMS mode */
drm_helper_disable_unused_functions(dev);
ret = drm_fb_helper_initial_config(&ufbdev->helper, bpp_sel);
if (ret)
goto fini;
return 0;
fini:
drm_fb_helper_fini(&ufbdev->helper);
free:
kfree(ufbdev);
return ret;
}
void udl_fbdev_cleanup(struct drm_device *dev)
{
struct udl_device *udl = dev->dev_private;
if (!udl->fbdev)
return;
udl_fbdev_destroy(dev, udl->fbdev);
kfree(udl->fbdev);
udl->fbdev = NULL;
}
void udl_fbdev_unplug(struct drm_device *dev)
{
struct udl_device *udl = dev->dev_private;
struct udl_fbdev *ufbdev;
if (!udl->fbdev)
return;
ufbdev = udl->fbdev;
if (ufbdev->helper.fbdev) {
struct fb_info *info;
info = ufbdev->helper.fbdev;
unlink_framebuffer(info);
}
}
struct drm_framebuffer *
udl_fb_user_fb_create(struct drm_device *dev,
struct drm_file *file,
struct drm_mode_fb_cmd2 *mode_cmd)
{
struct drm_gem_object *obj;
struct udl_framebuffer *ufb;
int ret;
uint32_t size;
obj = drm_gem_object_lookup(dev, file, mode_cmd->handles[0]);
if (obj == NULL)
return ERR_PTR(-ENOENT);
size = mode_cmd->pitches[0] * mode_cmd->height;
size = ALIGN(size, PAGE_SIZE);
if (size > obj->size) {
DRM_ERROR("object size not sufficient for fb %d %zu %d %d\n", size, obj->size, mode_cmd->pitches[0], mode_cmd->height);
return ERR_PTR(-ENOMEM);
}
ufb = kzalloc(sizeof(*ufb), GFP_KERNEL);
if (ufb == NULL)
return ERR_PTR(-ENOMEM);
ret = udl_framebuffer_init(dev, ufb, mode_cmd, to_udl_bo(obj));
if (ret) {
kfree(ufb);
return ERR_PTR(-EINVAL);
}
return &ufb->base;
}
| gpl-3.0 |
sonico67/ArdupilotST-JD_3_1_1 | libraries/AP_HAL_FLYMAPLE/AnalogSource.cpp | 32 | 4922 | /// -*- tab-width: 4; Mode: C++; c-basic-offset: 4; indent-tabs-mode: nil -*-
/*
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/>.
*/
/*
Flymaple port by Mike McCauley
*/
#include <AP_HAL.h>
#if CONFIG_HAL_BOARD == HAL_BOARD_FLYMAPLE
#include "FlymapleWirish.h"
#include "AnalogIn.h"
using namespace AP_HAL_FLYMAPLE_NS;
extern const AP_HAL::HAL& hal;
FLYMAPLEAnalogSource::FLYMAPLEAnalogSource(uint8_t pin) :
_sum_count(0),
_sum(0),
_last_average(0),
_pin(ANALOG_INPUT_NONE),
_stop_pin(ANALOG_INPUT_NONE),
_settle_time_ms(0)
{
set_pin(pin);
}
float FLYMAPLEAnalogSource::read_average() {
return _read_average();
}
float FLYMAPLEAnalogSource::read_latest() {
noInterrupts();
uint16_t latest = _latest;
interrupts();
return latest;
}
/*
return voltage from 0.0 to 3.3V, scaled to Vcc
*/
float FLYMAPLEAnalogSource::voltage_average(void)
{
return voltage_average_ratiometric();
}
float FLYMAPLEAnalogSource::voltage_latest(void)
{
float v = read_latest();
return v * (3.3f / 4095.0f);
}
/*
return voltage from 0.0 to 3.3V, assuming a ratiometric sensor. This
means the result is really a pseudo-voltage, that assumes the supply
voltage is exactly 3.3V.
*/
float FLYMAPLEAnalogSource::voltage_average_ratiometric(void)
{
float v = read_average();
return v * (3.3f / 4095.0f);
}
void FLYMAPLEAnalogSource::set_pin(uint8_t pin) {
if (pin != _pin) {
// ensure the pin is marked as an INPUT pin
if (pin != ANALOG_INPUT_NONE && pin != ANALOG_INPUT_BOARD_VCC) {
int8_t dpin = hal.gpio->analogPinToDigitalPin(pin);
if (dpin != -1) {
pinMode(dpin, INPUT_ANALOG);
}
}
noInterrupts();
_sum = 0;
_sum_count = 0;
_last_average = 0;
_latest = 0;
_pin = pin;
interrupts();
}
}
void FLYMAPLEAnalogSource::set_stop_pin(uint8_t pin) {
_stop_pin = pin;
}
void FLYMAPLEAnalogSource::set_settle_time(uint16_t settle_time_ms)
{
_settle_time_ms = settle_time_ms;
}
/* read_average is called from the normal thread (not an interrupt). */
float FLYMAPLEAnalogSource::_read_average()
{
uint16_t sum;
uint8_t sum_count;
if (_sum_count == 0) {
// avoid blocking waiting for new samples
return _last_average;
}
/* Read and clear in a critical section */
noInterrupts();
sum = _sum;
sum_count = _sum_count;
_sum = 0;
_sum_count = 0;
interrupts();
float avg = sum / (float) sum_count;
_last_average = avg;
return avg;
}
void FLYMAPLEAnalogSource::setup_read() {
if (_stop_pin != ANALOG_INPUT_NONE) {
uint8_t digital_pin = hal.gpio->analogPinToDigitalPin(_stop_pin);
hal.gpio->pinMode(digital_pin, GPIO_OUTPUT);
hal.gpio->write(digital_pin, 1);
}
if (_settle_time_ms != 0) {
_read_start_time_ms = hal.scheduler->millis();
}
adc_reg_map *regs = ADC1->regs;
adc_set_reg_seqlen(ADC1, 1);
uint8 channel = 0;
if (_pin == ANALOG_INPUT_BOARD_VCC)
channel = PIN_MAP[FLYMAPLE_VCC_ANALOG_IN_PIN].adc_channel;
else if (_pin == ANALOG_INPUT_NONE)
; // NOOP
else
channel = PIN_MAP[_pin].adc_channel;
regs->SQR3 = channel;
}
void FLYMAPLEAnalogSource::stop_read() {
if (_stop_pin != ANALOG_INPUT_NONE) {
uint8_t digital_pin = hal.gpio->analogPinToDigitalPin(_stop_pin);
hal.gpio->pinMode(digital_pin, GPIO_OUTPUT);
hal.gpio->write(digital_pin, 0);
}
}
bool FLYMAPLEAnalogSource::reading_settled()
{
if (_settle_time_ms != 0 && (hal.scheduler->millis() - _read_start_time_ms) < _settle_time_ms) {
return false;
}
return true;
}
/* new_sample is called from an interrupt. It always has access to
* _sum and _sum_count. Lock out the interrupts briefly with
* noInterrupts()/interrupts() to read these variables from outside an interrupt. */
void FLYMAPLEAnalogSource::new_sample(uint16_t sample) {
_sum += sample;
_latest = sample;
// Copied from AVR code in ArduPlane-2.74b, but AVR code is wrong!
if (_sum_count >= 15) { // Flymaple has a 12 bit ADC, so can only sum 16 in a uint16_t
_sum >>= 1;
_sum_count = 8;
} else {
_sum_count++;
}
}
#endif
| gpl-3.0 |
CognetTestbed/COGNET_CODE | KERNEL_SOURCE_CODE/grouper/drivers/media/dvb/frontends/mt312.c | 3104 | 18520 | /*
Driver for Zarlink VP310/MT312/ZL10313 Satellite Channel Decoder
Copyright (C) 2003 Andreas Oberritter <obi@linuxtv.org>
Copyright (C) 2008 Matthias Schwarzott <zzam@gentoo.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., 675 Mass Ave, Cambridge, MA 02139, USA.
References:
http://products.zarlink.com/product_profiles/MT312.htm
http://products.zarlink.com/product_profiles/SL1935.htm
*/
#include <linux/delay.h>
#include <linux/errno.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/string.h>
#include <linux/slab.h>
#include "dvb_frontend.h"
#include "mt312_priv.h"
#include "mt312.h"
struct mt312_state {
struct i2c_adapter *i2c;
/* configuration settings */
const struct mt312_config *config;
struct dvb_frontend frontend;
u8 id;
unsigned long xtal;
u8 freq_mult;
};
static int debug;
#define dprintk(args...) \
do { \
if (debug) \
printk(KERN_DEBUG "mt312: " args); \
} while (0)
#define MT312_PLL_CLK 10000000UL /* 10 MHz */
#define MT312_PLL_CLK_10_111 10111000UL /* 10.111 MHz */
static int mt312_read(struct mt312_state *state, const enum mt312_reg_addr reg,
u8 *buf, const size_t count)
{
int ret;
struct i2c_msg msg[2];
u8 regbuf[1] = { reg };
msg[0].addr = state->config->demod_address;
msg[0].flags = 0;
msg[0].buf = regbuf;
msg[0].len = 1;
msg[1].addr = state->config->demod_address;
msg[1].flags = I2C_M_RD;
msg[1].buf = buf;
msg[1].len = count;
ret = i2c_transfer(state->i2c, msg, 2);
if (ret != 2) {
printk(KERN_DEBUG "%s: ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
if (debug) {
int i;
dprintk("R(%d):", reg & 0x7f);
for (i = 0; i < count; i++)
printk(KERN_CONT " %02x", buf[i]);
printk("\n");
}
return 0;
}
static int mt312_write(struct mt312_state *state, const enum mt312_reg_addr reg,
const u8 *src, const size_t count)
{
int ret;
u8 buf[count + 1];
struct i2c_msg msg;
if (debug) {
int i;
dprintk("W(%d):", reg & 0x7f);
for (i = 0; i < count; i++)
printk(KERN_CONT " %02x", src[i]);
printk("\n");
}
buf[0] = reg;
memcpy(&buf[1], src, count);
msg.addr = state->config->demod_address;
msg.flags = 0;
msg.buf = buf;
msg.len = count + 1;
ret = i2c_transfer(state->i2c, &msg, 1);
if (ret != 1) {
dprintk("%s: ret == %d\n", __func__, ret);
return -EREMOTEIO;
}
return 0;
}
static inline int mt312_readreg(struct mt312_state *state,
const enum mt312_reg_addr reg, u8 *val)
{
return mt312_read(state, reg, val, 1);
}
static inline int mt312_writereg(struct mt312_state *state,
const enum mt312_reg_addr reg, const u8 val)
{
return mt312_write(state, reg, &val, 1);
}
static inline u32 mt312_div(u32 a, u32 b)
{
return (a + (b / 2)) / b;
}
static int mt312_reset(struct mt312_state *state, const u8 full)
{
return mt312_writereg(state, RESET, full ? 0x80 : 0x40);
}
static int mt312_get_inversion(struct mt312_state *state,
fe_spectral_inversion_t *i)
{
int ret;
u8 vit_mode;
ret = mt312_readreg(state, VIT_MODE, &vit_mode);
if (ret < 0)
return ret;
if (vit_mode & 0x80) /* auto inversion was used */
*i = (vit_mode & 0x40) ? INVERSION_ON : INVERSION_OFF;
return 0;
}
static int mt312_get_symbol_rate(struct mt312_state *state, u32 *sr)
{
int ret;
u8 sym_rate_h;
u8 dec_ratio;
u16 sym_rat_op;
u16 monitor;
u8 buf[2];
ret = mt312_readreg(state, SYM_RATE_H, &sym_rate_h);
if (ret < 0)
return ret;
if (sym_rate_h & 0x80) {
/* symbol rate search was used */
ret = mt312_writereg(state, MON_CTRL, 0x03);
if (ret < 0)
return ret;
ret = mt312_read(state, MONITOR_H, buf, sizeof(buf));
if (ret < 0)
return ret;
monitor = (buf[0] << 8) | buf[1];
dprintk("sr(auto) = %u\n",
mt312_div(monitor * 15625, 4));
} else {
ret = mt312_writereg(state, MON_CTRL, 0x05);
if (ret < 0)
return ret;
ret = mt312_read(state, MONITOR_H, buf, sizeof(buf));
if (ret < 0)
return ret;
dec_ratio = ((buf[0] >> 5) & 0x07) * 32;
ret = mt312_read(state, SYM_RAT_OP_H, buf, sizeof(buf));
if (ret < 0)
return ret;
sym_rat_op = (buf[0] << 8) | buf[1];
dprintk("sym_rat_op=%d dec_ratio=%d\n",
sym_rat_op, dec_ratio);
dprintk("*sr(manual) = %lu\n",
(((state->xtal * 8192) / (sym_rat_op + 8192)) *
2) - dec_ratio);
}
return 0;
}
static int mt312_get_code_rate(struct mt312_state *state, fe_code_rate_t *cr)
{
const fe_code_rate_t fec_tab[8] =
{ FEC_1_2, FEC_2_3, FEC_3_4, FEC_5_6, FEC_6_7, FEC_7_8,
FEC_AUTO, FEC_AUTO };
int ret;
u8 fec_status;
ret = mt312_readreg(state, FEC_STATUS, &fec_status);
if (ret < 0)
return ret;
*cr = fec_tab[(fec_status >> 4) & 0x07];
return 0;
}
static int mt312_initfe(struct dvb_frontend *fe)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 buf[2];
/* wake up */
ret = mt312_writereg(state, CONFIG,
(state->freq_mult == 6 ? 0x88 : 0x8c));
if (ret < 0)
return ret;
/* wait at least 150 usec */
udelay(150);
/* full reset */
ret = mt312_reset(state, 1);
if (ret < 0)
return ret;
/* Per datasheet, write correct values. 09/28/03 ACCJr.
* If we don't do this, we won't get FE_HAS_VITERBI in the VP310. */
{
u8 buf_def[8] = { 0x14, 0x12, 0x03, 0x02,
0x01, 0x00, 0x00, 0x00 };
ret = mt312_write(state, VIT_SETUP, buf_def, sizeof(buf_def));
if (ret < 0)
return ret;
}
switch (state->id) {
case ID_ZL10313:
/* enable ADC */
ret = mt312_writereg(state, GPP_CTRL, 0x80);
if (ret < 0)
return ret;
/* configure ZL10313 for optimal ADC performance */
buf[0] = 0x80;
buf[1] = 0xB0;
ret = mt312_write(state, HW_CTRL, buf, 2);
if (ret < 0)
return ret;
/* enable MPEG output and ADCs */
ret = mt312_writereg(state, HW_CTRL, 0x00);
if (ret < 0)
return ret;
ret = mt312_writereg(state, MPEG_CTRL, 0x00);
if (ret < 0)
return ret;
break;
}
/* SYS_CLK */
buf[0] = mt312_div(state->xtal * state->freq_mult * 2, 1000000);
/* DISEQC_RATIO */
buf[1] = mt312_div(state->xtal, 22000 * 4);
ret = mt312_write(state, SYS_CLK, buf, sizeof(buf));
if (ret < 0)
return ret;
ret = mt312_writereg(state, SNR_THS_HIGH, 0x32);
if (ret < 0)
return ret;
/* different MOCLK polarity */
switch (state->id) {
case ID_ZL10313:
buf[0] = 0x33;
break;
default:
buf[0] = 0x53;
break;
}
ret = mt312_writereg(state, OP_CTRL, buf[0]);
if (ret < 0)
return ret;
/* TS_SW_LIM */
buf[0] = 0x8c;
buf[1] = 0x98;
ret = mt312_write(state, TS_SW_LIM_L, buf, sizeof(buf));
if (ret < 0)
return ret;
ret = mt312_writereg(state, CS_SW_LIM, 0x69);
if (ret < 0)
return ret;
return 0;
}
static int mt312_send_master_cmd(struct dvb_frontend *fe,
struct dvb_diseqc_master_cmd *c)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 diseqc_mode;
if ((c->msg_len == 0) || (c->msg_len > sizeof(c->msg)))
return -EINVAL;
ret = mt312_readreg(state, DISEQC_MODE, &diseqc_mode);
if (ret < 0)
return ret;
ret = mt312_write(state, (0x80 | DISEQC_INSTR), c->msg, c->msg_len);
if (ret < 0)
return ret;
ret = mt312_writereg(state, DISEQC_MODE,
(diseqc_mode & 0x40) | ((c->msg_len - 1) << 3)
| 0x04);
if (ret < 0)
return ret;
/* is there a better way to wait for message to be transmitted */
msleep(100);
/* set DISEQC_MODE[2:0] to zero if a return message is expected */
if (c->msg[0] & 0x02) {
ret = mt312_writereg(state, DISEQC_MODE, (diseqc_mode & 0x40));
if (ret < 0)
return ret;
}
return 0;
}
static int mt312_send_burst(struct dvb_frontend *fe, const fe_sec_mini_cmd_t c)
{
struct mt312_state *state = fe->demodulator_priv;
const u8 mini_tab[2] = { 0x02, 0x03 };
int ret;
u8 diseqc_mode;
if (c > SEC_MINI_B)
return -EINVAL;
ret = mt312_readreg(state, DISEQC_MODE, &diseqc_mode);
if (ret < 0)
return ret;
ret = mt312_writereg(state, DISEQC_MODE,
(diseqc_mode & 0x40) | mini_tab[c]);
if (ret < 0)
return ret;
return 0;
}
static int mt312_set_tone(struct dvb_frontend *fe, const fe_sec_tone_mode_t t)
{
struct mt312_state *state = fe->demodulator_priv;
const u8 tone_tab[2] = { 0x01, 0x00 };
int ret;
u8 diseqc_mode;
if (t > SEC_TONE_OFF)
return -EINVAL;
ret = mt312_readreg(state, DISEQC_MODE, &diseqc_mode);
if (ret < 0)
return ret;
ret = mt312_writereg(state, DISEQC_MODE,
(diseqc_mode & 0x40) | tone_tab[t]);
if (ret < 0)
return ret;
return 0;
}
static int mt312_set_voltage(struct dvb_frontend *fe, const fe_sec_voltage_t v)
{
struct mt312_state *state = fe->demodulator_priv;
const u8 volt_tab[3] = { 0x00, 0x40, 0x00 };
u8 val;
if (v > SEC_VOLTAGE_OFF)
return -EINVAL;
val = volt_tab[v];
if (state->config->voltage_inverted)
val ^= 0x40;
return mt312_writereg(state, DISEQC_MODE, val);
}
static int mt312_read_status(struct dvb_frontend *fe, fe_status_t *s)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 status[3];
*s = 0;
ret = mt312_read(state, QPSK_STAT_H, status, sizeof(status));
if (ret < 0)
return ret;
dprintk("QPSK_STAT_H: 0x%02x, QPSK_STAT_L: 0x%02x,"
" FEC_STATUS: 0x%02x\n", status[0], status[1], status[2]);
if (status[0] & 0xc0)
*s |= FE_HAS_SIGNAL; /* signal noise ratio */
if (status[0] & 0x04)
*s |= FE_HAS_CARRIER; /* qpsk carrier lock */
if (status[2] & 0x02)
*s |= FE_HAS_VITERBI; /* viterbi lock */
if (status[2] & 0x04)
*s |= FE_HAS_SYNC; /* byte align lock */
if (status[0] & 0x01)
*s |= FE_HAS_LOCK; /* qpsk lock */
return 0;
}
static int mt312_read_ber(struct dvb_frontend *fe, u32 *ber)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 buf[3];
ret = mt312_read(state, RS_BERCNT_H, buf, 3);
if (ret < 0)
return ret;
*ber = ((buf[0] << 16) | (buf[1] << 8) | buf[2]) * 64;
return 0;
}
static int mt312_read_signal_strength(struct dvb_frontend *fe,
u16 *signal_strength)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 buf[3];
u16 agc;
s16 err_db;
ret = mt312_read(state, AGC_H, buf, sizeof(buf));
if (ret < 0)
return ret;
agc = (buf[0] << 6) | (buf[1] >> 2);
err_db = (s16) (((buf[1] & 0x03) << 14) | buf[2] << 6) >> 6;
*signal_strength = agc;
dprintk("agc=%08x err_db=%hd\n", agc, err_db);
return 0;
}
static int mt312_read_snr(struct dvb_frontend *fe, u16 *snr)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 buf[2];
ret = mt312_read(state, M_SNR_H, buf, sizeof(buf));
if (ret < 0)
return ret;
*snr = 0xFFFF - ((((buf[0] & 0x7f) << 8) | buf[1]) << 1);
return 0;
}
static int mt312_read_ucblocks(struct dvb_frontend *fe, u32 *ubc)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 buf[2];
ret = mt312_read(state, RS_UBC_H, buf, sizeof(buf));
if (ret < 0)
return ret;
*ubc = (buf[0] << 8) | buf[1];
return 0;
}
static int mt312_set_frontend(struct dvb_frontend *fe,
struct dvb_frontend_parameters *p)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 buf[5], config_val;
u16 sr;
const u8 fec_tab[10] =
{ 0x00, 0x01, 0x02, 0x04, 0x3f, 0x08, 0x10, 0x20, 0x3f, 0x3f };
const u8 inv_tab[3] = { 0x00, 0x40, 0x80 };
dprintk("%s: Freq %d\n", __func__, p->frequency);
if ((p->frequency < fe->ops.info.frequency_min)
|| (p->frequency > fe->ops.info.frequency_max))
return -EINVAL;
if ((p->inversion < INVERSION_OFF)
|| (p->inversion > INVERSION_ON))
return -EINVAL;
if ((p->u.qpsk.symbol_rate < fe->ops.info.symbol_rate_min)
|| (p->u.qpsk.symbol_rate > fe->ops.info.symbol_rate_max))
return -EINVAL;
if ((p->u.qpsk.fec_inner < FEC_NONE)
|| (p->u.qpsk.fec_inner > FEC_AUTO))
return -EINVAL;
if ((p->u.qpsk.fec_inner == FEC_4_5)
|| (p->u.qpsk.fec_inner == FEC_8_9))
return -EINVAL;
switch (state->id) {
case ID_VP310:
/* For now we will do this only for the VP310.
* It should be better for the mt312 as well,
* but tuning will be slower. ACCJr 09/29/03
*/
ret = mt312_readreg(state, CONFIG, &config_val);
if (ret < 0)
return ret;
if (p->u.qpsk.symbol_rate >= 30000000) {
/* Note that 30MS/s should use 90MHz */
if (state->freq_mult == 6) {
/* We are running 60MHz */
state->freq_mult = 9;
ret = mt312_initfe(fe);
if (ret < 0)
return ret;
}
} else {
if (state->freq_mult == 9) {
/* We are running 90MHz */
state->freq_mult = 6;
ret = mt312_initfe(fe);
if (ret < 0)
return ret;
}
}
break;
case ID_MT312:
case ID_ZL10313:
break;
default:
return -EINVAL;
}
if (fe->ops.tuner_ops.set_params) {
fe->ops.tuner_ops.set_params(fe, p);
if (fe->ops.i2c_gate_ctrl)
fe->ops.i2c_gate_ctrl(fe, 0);
}
/* sr = (u16)(sr * 256.0 / 1000000.0) */
sr = mt312_div(p->u.qpsk.symbol_rate * 4, 15625);
/* SYM_RATE */
buf[0] = (sr >> 8) & 0x3f;
buf[1] = (sr >> 0) & 0xff;
/* VIT_MODE */
buf[2] = inv_tab[p->inversion] | fec_tab[p->u.qpsk.fec_inner];
/* QPSK_CTRL */
buf[3] = 0x40; /* swap I and Q before QPSK demodulation */
if (p->u.qpsk.symbol_rate < 10000000)
buf[3] |= 0x04; /* use afc mode */
/* GO */
buf[4] = 0x01;
ret = mt312_write(state, SYM_RATE_H, buf, sizeof(buf));
if (ret < 0)
return ret;
mt312_reset(state, 0);
return 0;
}
static int mt312_get_frontend(struct dvb_frontend *fe,
struct dvb_frontend_parameters *p)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
ret = mt312_get_inversion(state, &p->inversion);
if (ret < 0)
return ret;
ret = mt312_get_symbol_rate(state, &p->u.qpsk.symbol_rate);
if (ret < 0)
return ret;
ret = mt312_get_code_rate(state, &p->u.qpsk.fec_inner);
if (ret < 0)
return ret;
return 0;
}
static int mt312_i2c_gate_ctrl(struct dvb_frontend *fe, int enable)
{
struct mt312_state *state = fe->demodulator_priv;
u8 val = 0x00;
int ret;
switch (state->id) {
case ID_ZL10313:
ret = mt312_readreg(state, GPP_CTRL, &val);
if (ret < 0)
goto error;
/* preserve this bit to not accidentally shutdown ADC */
val &= 0x80;
break;
}
if (enable)
val |= 0x40;
else
val &= ~0x40;
ret = mt312_writereg(state, GPP_CTRL, val);
error:
return ret;
}
static int mt312_sleep(struct dvb_frontend *fe)
{
struct mt312_state *state = fe->demodulator_priv;
int ret;
u8 config;
/* reset all registers to defaults */
ret = mt312_reset(state, 1);
if (ret < 0)
return ret;
if (state->id == ID_ZL10313) {
/* reset ADC */
ret = mt312_writereg(state, GPP_CTRL, 0x00);
if (ret < 0)
return ret;
/* full shutdown of ADCs, mpeg bus tristated */
ret = mt312_writereg(state, HW_CTRL, 0x0d);
if (ret < 0)
return ret;
}
ret = mt312_readreg(state, CONFIG, &config);
if (ret < 0)
return ret;
/* enter standby */
ret = mt312_writereg(state, CONFIG, config & 0x7f);
if (ret < 0)
return ret;
return 0;
}
static int mt312_get_tune_settings(struct dvb_frontend *fe,
struct dvb_frontend_tune_settings *fesettings)
{
fesettings->min_delay_ms = 50;
fesettings->step_size = 0;
fesettings->max_drift = 0;
return 0;
}
static void mt312_release(struct dvb_frontend *fe)
{
struct mt312_state *state = fe->demodulator_priv;
kfree(state);
}
#define MT312_SYS_CLK 90000000UL /* 90 MHz */
static struct dvb_frontend_ops mt312_ops = {
.info = {
.name = "Zarlink ???? DVB-S",
.type = FE_QPSK,
.frequency_min = 950000,
.frequency_max = 2150000,
/* FIXME: adjust freq to real used xtal */
.frequency_stepsize = (MT312_PLL_CLK / 1000) / 128,
.symbol_rate_min = MT312_SYS_CLK / 128, /* FIXME as above */
.symbol_rate_max = MT312_SYS_CLK / 2,
.caps =
FE_CAN_FEC_1_2 | FE_CAN_FEC_2_3 |
FE_CAN_FEC_3_4 | FE_CAN_FEC_5_6 | FE_CAN_FEC_7_8 |
FE_CAN_FEC_AUTO | FE_CAN_QPSK | FE_CAN_MUTE_TS |
FE_CAN_RECOVER
},
.release = mt312_release,
.init = mt312_initfe,
.sleep = mt312_sleep,
.i2c_gate_ctrl = mt312_i2c_gate_ctrl,
.set_frontend = mt312_set_frontend,
.get_frontend = mt312_get_frontend,
.get_tune_settings = mt312_get_tune_settings,
.read_status = mt312_read_status,
.read_ber = mt312_read_ber,
.read_signal_strength = mt312_read_signal_strength,
.read_snr = mt312_read_snr,
.read_ucblocks = mt312_read_ucblocks,
.diseqc_send_master_cmd = mt312_send_master_cmd,
.diseqc_send_burst = mt312_send_burst,
.set_tone = mt312_set_tone,
.set_voltage = mt312_set_voltage,
};
struct dvb_frontend *mt312_attach(const struct mt312_config *config,
struct i2c_adapter *i2c)
{
struct mt312_state *state = NULL;
/* allocate memory for the internal state */
state = kzalloc(sizeof(struct mt312_state), GFP_KERNEL);
if (state == NULL)
goto error;
/* setup the state */
state->config = config;
state->i2c = i2c;
/* check if the demod is there */
if (mt312_readreg(state, ID, &state->id) < 0)
goto error;
/* create dvb_frontend */
memcpy(&state->frontend.ops, &mt312_ops,
sizeof(struct dvb_frontend_ops));
state->frontend.demodulator_priv = state;
switch (state->id) {
case ID_VP310:
strcpy(state->frontend.ops.info.name, "Zarlink VP310 DVB-S");
state->xtal = MT312_PLL_CLK;
state->freq_mult = 9;
break;
case ID_MT312:
strcpy(state->frontend.ops.info.name, "Zarlink MT312 DVB-S");
state->xtal = MT312_PLL_CLK;
state->freq_mult = 6;
break;
case ID_ZL10313:
strcpy(state->frontend.ops.info.name, "Zarlink ZL10313 DVB-S");
state->xtal = MT312_PLL_CLK_10_111;
state->freq_mult = 9;
break;
default:
printk(KERN_WARNING "Only Zarlink VP310/MT312/ZL10313"
" are supported chips.\n");
goto error;
}
return &state->frontend;
error:
kfree(state);
return NULL;
}
EXPORT_SYMBOL(mt312_attach);
module_param(debug, int, 0644);
MODULE_PARM_DESC(debug, "Turn on/off frontend debugging (default:off).");
MODULE_DESCRIPTION("Zarlink VP310/MT312/ZL10313 DVB-S Demodulator driver");
MODULE_AUTHOR("Andreas Oberritter <obi@linuxtv.org>");
MODULE_AUTHOR("Matthias Schwarzott <zzam@gentoo.org>");
MODULE_LICENSE("GPL");
| gpl-3.0 |
dachziegel/Sigil | src/tidyLib/tags.c | 34 | 49302 | /* tags.c -- recognize HTML tags
(c) 1998-2008 (W3C) MIT, ERCIM, Keio University
See tidy.h for the copyright notice.
CVS Info :
$Author: hoehrmann $
$Date: 2008/08/09 11:55:27 $
$Revision: 1.71 $
The HTML tags are stored as 8 bit ASCII strings.
*/
#include "tidy-int.h"
#include "message.h"
#include "tmbstr.h"
/* Attribute checking methods */
static CheckAttribs CheckIMG;
static CheckAttribs CheckLINK;
static CheckAttribs CheckAREA;
static CheckAttribs CheckTABLE;
static CheckAttribs CheckCaption;
static CheckAttribs CheckSCRIPT;
static CheckAttribs CheckSTYLE;
static CheckAttribs CheckHTML;
static CheckAttribs CheckFORM;
static CheckAttribs CheckMETA;
#define VERS_ELEM_A (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_ABBR (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_ACRONYM (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_ADDRESS (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_APPLET (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_AREA (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_B (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_BASE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_BASEFONT (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_BDO (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_BIG (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_BLOCKQUOTE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_BODY (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_BR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_BUTTON (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_CAPTION (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_CENTER (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_CITE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_CODE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_COL (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_COLGROUP (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_DD (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_DEL (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_DFN (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_DIR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_DIV (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_DL (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_DT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_EM (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_FIELDSET (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_FONT (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_FORM (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_FRAME (xxxx|xxxx|xxxx|xxxx|xxxx|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_FRAMESET (xxxx|xxxx|xxxx|xxxx|xxxx|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_H1 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_H2 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_H3 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_H4 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_H5 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_H6 (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_HEAD (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_HR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_HTML (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_I (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_IFRAME (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_IMG (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_INPUT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_INS (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_ISINDEX (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_KBD (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_LABEL (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_LEGEND (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_LI (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_LINK (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_LISTING (HT20|HT32|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_MAP (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_MENU (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_META (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_NEXTID (HT20|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_NOFRAMES (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_NOSCRIPT (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_OBJECT (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_OL (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_OPTGROUP (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_OPTION (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_P (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_PARAM (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_PLAINTEXT (HT20|HT32|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_PRE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_Q (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_RB (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx)
#define VERS_ELEM_RBC (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx)
#define VERS_ELEM_RP (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx)
#define VERS_ELEM_RT (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx)
#define VERS_ELEM_RTC (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx)
#define VERS_ELEM_RUBY (xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|XH11|xxxx)
#define VERS_ELEM_S (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_SAMP (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_SCRIPT (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_SELECT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_SMALL (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_SPAN (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_STRIKE (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_STRONG (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_STYLE (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_SUB (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_SUP (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_TABLE (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_TBODY (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_TD (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_TEXTAREA (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_TFOOT (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_TH (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_THEAD (xxxx|xxxx|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_TITLE (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_TR (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_TT (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|xxxx)
#define VERS_ELEM_U (xxxx|HT32|H40T|H41T|X10T|H40F|H41F|X10F|xxxx|xxxx|xxxx|xxxx|xxxx)
#define VERS_ELEM_UL (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_VAR (HT20|HT32|H40T|H41T|X10T|H40F|H41F|X10F|H40S|H41S|X10S|XH11|XB10)
#define VERS_ELEM_XMP (HT20|HT32|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx|xxxx)
static const Dict tag_defs[] =
{
{ TidyTag_UNKNOWN, "unknown!", VERS_UNKNOWN, NULL, (0), NULL, NULL },
/* W3C defined elements */
{ TidyTag_A, "a", VERS_ELEM_A, &TY_(W3CAttrsFor_A)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_ABBR, "abbr", VERS_ELEM_ABBR, &TY_(W3CAttrsFor_ABBR)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_ACRONYM, "acronym", VERS_ELEM_ACRONYM, &TY_(W3CAttrsFor_ACRONYM)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_ADDRESS, "address", VERS_ELEM_ADDRESS, &TY_(W3CAttrsFor_ADDRESS)[0], (CM_BLOCK), TY_(ParseInline), NULL },
{ TidyTag_APPLET, "applet", VERS_ELEM_APPLET, &TY_(W3CAttrsFor_APPLET)[0], (CM_OBJECT|CM_IMG|CM_INLINE|CM_PARAM), TY_(ParseBlock), NULL },
{ TidyTag_AREA, "area", VERS_ELEM_AREA, &TY_(W3CAttrsFor_AREA)[0], (CM_BLOCK|CM_EMPTY), TY_(ParseEmpty), CheckAREA },
{ TidyTag_B, "b", VERS_ELEM_B, &TY_(W3CAttrsFor_B)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_BASE, "base", VERS_ELEM_BASE, &TY_(W3CAttrsFor_BASE)[0], (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_BASEFONT, "basefont", VERS_ELEM_BASEFONT, &TY_(W3CAttrsFor_BASEFONT)[0], (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_BDO, "bdo", VERS_ELEM_BDO, &TY_(W3CAttrsFor_BDO)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_BIG, "big", VERS_ELEM_BIG, &TY_(W3CAttrsFor_BIG)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_BLOCKQUOTE, "blockquote", VERS_ELEM_BLOCKQUOTE, &TY_(W3CAttrsFor_BLOCKQUOTE)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_BODY, "body", VERS_ELEM_BODY, &TY_(W3CAttrsFor_BODY)[0], (CM_HTML|CM_OPT|CM_OMITST), TY_(ParseBody), NULL },
{ TidyTag_BR, "br", VERS_ELEM_BR, &TY_(W3CAttrsFor_BR)[0], (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_BUTTON, "button", VERS_ELEM_BUTTON, &TY_(W3CAttrsFor_BUTTON)[0], (CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_CAPTION, "caption", VERS_ELEM_CAPTION, &TY_(W3CAttrsFor_CAPTION)[0], (CM_TABLE), TY_(ParseInline), CheckCaption },
{ TidyTag_CENTER, "center", VERS_ELEM_CENTER, &TY_(W3CAttrsFor_CENTER)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_CITE, "cite", VERS_ELEM_CITE, &TY_(W3CAttrsFor_CITE)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_CODE, "code", VERS_ELEM_CODE, &TY_(W3CAttrsFor_CODE)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_COL, "col", VERS_ELEM_COL, &TY_(W3CAttrsFor_COL)[0], (CM_TABLE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_COLGROUP, "colgroup", VERS_ELEM_COLGROUP, &TY_(W3CAttrsFor_COLGROUP)[0], (CM_TABLE|CM_OPT), TY_(ParseColGroup), NULL },
{ TidyTag_DD, "dd", VERS_ELEM_DD, &TY_(W3CAttrsFor_DD)[0], (CM_DEFLIST|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_DEL, "del", VERS_ELEM_DEL, &TY_(W3CAttrsFor_DEL)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseInline), NULL },
{ TidyTag_DFN, "dfn", VERS_ELEM_DFN, &TY_(W3CAttrsFor_DFN)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_DIR, "dir", VERS_ELEM_DIR, &TY_(W3CAttrsFor_DIR)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParseList), NULL },
{ TidyTag_DIV, "div", VERS_ELEM_DIV, &TY_(W3CAttrsFor_DIV)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_DL, "dl", VERS_ELEM_DL, &TY_(W3CAttrsFor_DL)[0], (CM_BLOCK), TY_(ParseDefList), NULL },
{ TidyTag_DT, "dt", VERS_ELEM_DT, &TY_(W3CAttrsFor_DT)[0], (CM_DEFLIST|CM_OPT|CM_NO_INDENT), TY_(ParseInline), NULL },
{ TidyTag_EM, "em", VERS_ELEM_EM, &TY_(W3CAttrsFor_EM)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_FIELDSET, "fieldset", VERS_ELEM_FIELDSET, &TY_(W3CAttrsFor_FIELDSET)[0], (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_FONT, "font", VERS_ELEM_FONT, &TY_(W3CAttrsFor_FONT)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_FORM, "form", VERS_ELEM_FORM, &TY_(W3CAttrsFor_FORM)[0], (CM_BLOCK), TY_(ParseBlock), CheckFORM },
{ TidyTag_FRAME, "frame", VERS_ELEM_FRAME, &TY_(W3CAttrsFor_FRAME)[0], (CM_FRAMES|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_FRAMESET, "frameset", VERS_ELEM_FRAMESET, &TY_(W3CAttrsFor_FRAMESET)[0], (CM_HTML|CM_FRAMES), TY_(ParseFrameSet), NULL },
{ TidyTag_H1, "h1", VERS_ELEM_H1, &TY_(W3CAttrsFor_H1)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H2, "h2", VERS_ELEM_H2, &TY_(W3CAttrsFor_H2)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H3, "h3", VERS_ELEM_H3, &TY_(W3CAttrsFor_H3)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H4, "h4", VERS_ELEM_H4, &TY_(W3CAttrsFor_H4)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H5, "h5", VERS_ELEM_H5, &TY_(W3CAttrsFor_H5)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_H6, "h6", VERS_ELEM_H6, &TY_(W3CAttrsFor_H6)[0], (CM_BLOCK|CM_HEADING), TY_(ParseInline), NULL },
{ TidyTag_HEAD, "head", VERS_ELEM_HEAD, &TY_(W3CAttrsFor_HEAD)[0], (CM_HTML|CM_OPT|CM_OMITST), TY_(ParseHead), NULL },
{ TidyTag_HR, "hr", VERS_ELEM_HR, &TY_(W3CAttrsFor_HR)[0], (CM_BLOCK|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_HTML, "html", VERS_ELEM_HTML, &TY_(W3CAttrsFor_HTML)[0], (CM_HTML|CM_OPT|CM_OMITST), TY_(ParseHTML), CheckHTML },
{ TidyTag_I, "i", VERS_ELEM_I, &TY_(W3CAttrsFor_I)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_IFRAME, "iframe", VERS_ELEM_IFRAME, &TY_(W3CAttrsFor_IFRAME)[0], (CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_IMG, "img", VERS_ELEM_IMG, &TY_(W3CAttrsFor_IMG)[0], (CM_INLINE|CM_IMG|CM_EMPTY), TY_(ParseEmpty), CheckIMG },
{ TidyTag_INPUT, "input", VERS_ELEM_INPUT, &TY_(W3CAttrsFor_INPUT)[0], (CM_INLINE|CM_IMG|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_INS, "ins", VERS_ELEM_INS, &TY_(W3CAttrsFor_INS)[0], (CM_INLINE|CM_BLOCK|CM_MIXED), TY_(ParseInline), NULL },
{ TidyTag_ISINDEX, "isindex", VERS_ELEM_ISINDEX, &TY_(W3CAttrsFor_ISINDEX)[0], (CM_BLOCK|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_KBD, "kbd", VERS_ELEM_KBD, &TY_(W3CAttrsFor_KBD)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LABEL, "label", VERS_ELEM_LABEL, &TY_(W3CAttrsFor_LABEL)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LEGEND, "legend", VERS_ELEM_LEGEND, &TY_(W3CAttrsFor_LEGEND)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_LI, "li", VERS_ELEM_LI, &TY_(W3CAttrsFor_LI)[0], (CM_LIST|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_LINK, "link", VERS_ELEM_LINK, &TY_(W3CAttrsFor_LINK)[0], (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), CheckLINK },
{ TidyTag_LISTING, "listing", VERS_ELEM_LISTING, &TY_(W3CAttrsFor_LISTING)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParsePre), NULL },
{ TidyTag_MAP, "map", VERS_ELEM_MAP, &TY_(W3CAttrsFor_MAP)[0], (CM_INLINE), TY_(ParseBlock), NULL },
{ TidyTag_MENU, "menu", VERS_ELEM_MENU, &TY_(W3CAttrsFor_MENU)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParseList), NULL },
{ TidyTag_META, "meta", VERS_ELEM_META, &TY_(W3CAttrsFor_META)[0], (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), CheckMETA },
{ TidyTag_NOFRAMES, "noframes", VERS_ELEM_NOFRAMES, &TY_(W3CAttrsFor_NOFRAMES)[0], (CM_BLOCK|CM_FRAMES), TY_(ParseNoFrames), NULL },
{ TidyTag_NOSCRIPT, "noscript", VERS_ELEM_NOSCRIPT, &TY_(W3CAttrsFor_NOSCRIPT)[0], (CM_BLOCK|CM_INLINE|CM_MIXED), TY_(ParseBlock), NULL },
{ TidyTag_OBJECT, "object", VERS_ELEM_OBJECT, &TY_(W3CAttrsFor_OBJECT)[0], (CM_OBJECT|CM_HEAD|CM_IMG|CM_INLINE|CM_PARAM), TY_(ParseBlock), NULL },
{ TidyTag_OL, "ol", VERS_ELEM_OL, &TY_(W3CAttrsFor_OL)[0], (CM_BLOCK), TY_(ParseList), NULL },
{ TidyTag_OPTGROUP, "optgroup", VERS_ELEM_OPTGROUP, &TY_(W3CAttrsFor_OPTGROUP)[0], (CM_FIELD|CM_OPT), TY_(ParseOptGroup), NULL },
{ TidyTag_OPTION, "option", VERS_ELEM_OPTION, &TY_(W3CAttrsFor_OPTION)[0], (CM_FIELD|CM_OPT), TY_(ParseText), NULL },
{ TidyTag_P, "p", VERS_ELEM_P, &TY_(W3CAttrsFor_P)[0], (CM_BLOCK|CM_OPT), TY_(ParseInline), NULL },
{ TidyTag_PARAM, "param", VERS_ELEM_PARAM, &TY_(W3CAttrsFor_PARAM)[0], (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_PLAINTEXT, "plaintext", VERS_ELEM_PLAINTEXT, &TY_(W3CAttrsFor_PLAINTEXT)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParsePre), NULL },
{ TidyTag_PRE, "pre", VERS_ELEM_PRE, &TY_(W3CAttrsFor_PRE)[0], (CM_BLOCK), TY_(ParsePre), NULL },
{ TidyTag_Q, "q", VERS_ELEM_Q, &TY_(W3CAttrsFor_Q)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RB, "rb", VERS_ELEM_RB, &TY_(W3CAttrsFor_RB)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RBC, "rbc", VERS_ELEM_RBC, &TY_(W3CAttrsFor_RBC)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RP, "rp", VERS_ELEM_RP, &TY_(W3CAttrsFor_RP)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RT, "rt", VERS_ELEM_RT, &TY_(W3CAttrsFor_RT)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RTC, "rtc", VERS_ELEM_RTC, &TY_(W3CAttrsFor_RTC)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_RUBY, "ruby", VERS_ELEM_RUBY, &TY_(W3CAttrsFor_RUBY)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_S, "s", VERS_ELEM_S, &TY_(W3CAttrsFor_S)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SAMP, "samp", VERS_ELEM_SAMP, &TY_(W3CAttrsFor_SAMP)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SCRIPT, "script", VERS_ELEM_SCRIPT, &TY_(W3CAttrsFor_SCRIPT)[0], (CM_HEAD|CM_MIXED|CM_BLOCK|CM_INLINE), TY_(ParseScript), CheckSCRIPT },
{ TidyTag_SELECT, "select", VERS_ELEM_SELECT, &TY_(W3CAttrsFor_SELECT)[0], (CM_INLINE|CM_FIELD), TY_(ParseSelect), NULL },
{ TidyTag_SMALL, "small", VERS_ELEM_SMALL, &TY_(W3CAttrsFor_SMALL)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SPAN, "span", VERS_ELEM_SPAN, &TY_(W3CAttrsFor_SPAN)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_STRIKE, "strike", VERS_ELEM_STRIKE, &TY_(W3CAttrsFor_STRIKE)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_STRONG, "strong", VERS_ELEM_STRONG, &TY_(W3CAttrsFor_STRONG)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_STYLE, "style", VERS_ELEM_STYLE, &TY_(W3CAttrsFor_STYLE)[0], (CM_HEAD), TY_(ParseScript), CheckSTYLE },
{ TidyTag_SUB, "sub", VERS_ELEM_SUB, &TY_(W3CAttrsFor_SUB)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_SUP, "sup", VERS_ELEM_SUP, &TY_(W3CAttrsFor_SUP)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_TABLE, "table", VERS_ELEM_TABLE, &TY_(W3CAttrsFor_TABLE)[0], (CM_BLOCK), TY_(ParseTableTag), CheckTABLE },
{ TidyTag_TBODY, "tbody", VERS_ELEM_TBODY, &TY_(W3CAttrsFor_TBODY)[0], (CM_TABLE|CM_ROWGRP|CM_OPT), TY_(ParseRowGroup), NULL },
{ TidyTag_TD, "td", VERS_ELEM_TD, &TY_(W3CAttrsFor_TD)[0], (CM_ROW|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_TEXTAREA, "textarea", VERS_ELEM_TEXTAREA, &TY_(W3CAttrsFor_TEXTAREA)[0], (CM_INLINE|CM_FIELD), TY_(ParseText), NULL },
{ TidyTag_TFOOT, "tfoot", VERS_ELEM_TFOOT, &TY_(W3CAttrsFor_TFOOT)[0], (CM_TABLE|CM_ROWGRP|CM_OPT), TY_(ParseRowGroup), NULL },
{ TidyTag_TH, "th", VERS_ELEM_TH, &TY_(W3CAttrsFor_TH)[0], (CM_ROW|CM_OPT|CM_NO_INDENT), TY_(ParseBlock), NULL },
{ TidyTag_THEAD, "thead", VERS_ELEM_THEAD, &TY_(W3CAttrsFor_THEAD)[0], (CM_TABLE|CM_ROWGRP|CM_OPT), TY_(ParseRowGroup), NULL },
{ TidyTag_TITLE, "title", VERS_ELEM_TITLE, &TY_(W3CAttrsFor_TITLE)[0], (CM_HEAD), TY_(ParseTitle), NULL },
{ TidyTag_TR, "tr", VERS_ELEM_TR, &TY_(W3CAttrsFor_TR)[0], (CM_TABLE|CM_OPT), TY_(ParseRow), NULL },
{ TidyTag_TT, "tt", VERS_ELEM_TT, &TY_(W3CAttrsFor_TT)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_U, "u", VERS_ELEM_U, &TY_(W3CAttrsFor_U)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_UL, "ul", VERS_ELEM_UL, &TY_(W3CAttrsFor_UL)[0], (CM_BLOCK), TY_(ParseList), NULL },
{ TidyTag_VAR, "var", VERS_ELEM_VAR, &TY_(W3CAttrsFor_VAR)[0], (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_XMP, "xmp", VERS_ELEM_XMP, &TY_(W3CAttrsFor_XMP)[0], (CM_BLOCK|CM_OBSOLETE), TY_(ParsePre), NULL },
{ TidyTag_NEXTID, "nextid", VERS_ELEM_NEXTID, &TY_(W3CAttrsFor_NEXTID)[0], (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), NULL },
/* proprietary elements */
{ TidyTag_ALIGN, "align", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_BGSOUND, "bgsound", VERS_MICROSOFT, NULL, (CM_HEAD|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_BLINK, "blink", VERS_PROPRIETARY, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_COMMENT, "comment", VERS_MICROSOFT, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_EMBED, "embed", VERS_NETSCAPE, NULL, (CM_INLINE|CM_IMG|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_ILAYER, "ilayer", VERS_NETSCAPE, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_KEYGEN, "keygen", VERS_NETSCAPE, NULL, (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_LAYER, "layer", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_MARQUEE, "marquee", VERS_MICROSOFT, NULL, (CM_INLINE|CM_OPT), TY_(ParseInline), NULL },
{ TidyTag_MULTICOL, "multicol", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_NOBR, "nobr", VERS_PROPRIETARY, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_NOEMBED, "noembed", VERS_NETSCAPE, NULL, (CM_INLINE), TY_(ParseInline), NULL },
{ TidyTag_NOLAYER, "nolayer", VERS_NETSCAPE, NULL, (CM_BLOCK|CM_INLINE|CM_MIXED), TY_(ParseBlock), NULL },
{ TidyTag_NOSAVE, "nosave", VERS_NETSCAPE, NULL, (CM_BLOCK), TY_(ParseBlock), NULL },
{ TidyTag_SERVER, "server", VERS_NETSCAPE, NULL, (CM_HEAD|CM_MIXED|CM_BLOCK|CM_INLINE), TY_(ParseScript), NULL },
{ TidyTag_SERVLET, "servlet", VERS_SUN, NULL, (CM_OBJECT|CM_IMG|CM_INLINE|CM_PARAM), TY_(ParseBlock), NULL },
{ TidyTag_SPACER, "spacer", VERS_NETSCAPE, NULL, (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
{ TidyTag_WBR, "wbr", VERS_PROPRIETARY, NULL, (CM_INLINE|CM_EMPTY), TY_(ParseEmpty), NULL },
/* this must be the final entry */
{ (TidyTagId)0, NULL, 0, NULL, (0), NULL, NULL }
};
#if ELEMENT_HASH_LOOKUP
static uint tagsHash(ctmbstr s)
{
uint hashval;
for (hashval = 0; *s != '\0'; s++)
hashval = *s + 31*hashval;
return hashval % ELEMENT_HASH_SIZE;
}
static const Dict *tagsInstall(TidyDocImpl* doc, TidyTagImpl* tags, const Dict* old)
{
DictHash *np;
uint hashval;
if (old)
{
np = (DictHash *)TidyDocAlloc(doc, sizeof(*np));
np->tag = old;
hashval = tagsHash(old->name);
np->next = tags->hashtab[hashval];
tags->hashtab[hashval] = np;
}
return old;
}
static void tagsRemoveFromHash( TidyDocImpl* doc, TidyTagImpl* tags, ctmbstr s )
{
uint h = tagsHash(s);
DictHash *p, *prev = NULL;
for (p = tags->hashtab[h]; p && p->tag; p = p->next)
{
if (TY_(tmbstrcmp)(s, p->tag->name) == 0)
{
DictHash* next = p->next;
if ( prev )
prev->next = next;
else
tags->hashtab[h] = next;
TidyDocFree(doc, p);
return;
}
prev = p;
}
}
static void tagsEmptyHash( TidyDocImpl* doc, TidyTagImpl* tags )
{
uint i;
DictHash *prev, *next;
for (i = 0; i < ELEMENT_HASH_SIZE; ++i)
{
prev = NULL;
next = tags->hashtab[i];
while(next)
{
prev = next->next;
TidyDocFree(doc, next);
next = prev;
}
tags->hashtab[i] = NULL;
}
}
#endif /* ELEMENT_HASH_LOOKUP */
static const Dict* tagsLookup( TidyDocImpl* doc, TidyTagImpl* tags, ctmbstr s )
{
const Dict *np;
#if ELEMENT_HASH_LOOKUP
const DictHash* p;
#endif
if (!s)
return NULL;
#if ELEMENT_HASH_LOOKUP
/* this breaks if declared elements get changed between two */
/* parser runs since Tidy would use the cached version rather */
/* than the new one. */
/* However, as FreeDeclaredTags() correctly cleans the hash */
/* this should not be true anymore. */
for (p = tags->hashtab[tagsHash(s)]; p && p->tag; p = p->next)
if (TY_(tmbstrcmp)(s, p->tag->name) == 0)
return p->tag;
for (np = tag_defs + 1; np < tag_defs + N_TIDY_TAGS; ++np)
if (TY_(tmbstrcmp)(s, np->name) == 0)
return tagsInstall(doc, tags, np);
for (np = tags->declared_tag_list; np; np = np->next)
if (TY_(tmbstrcmp)(s, np->name) == 0)
return tagsInstall(doc, tags, np);
#else
for (np = tag_defs + 1; np < tag_defs + N_TIDY_TAGS; ++np)
if (TY_(tmbstrcmp)(s, np->name) == 0)
return np;
for (np = tags->declared_tag_list; np; np = np->next)
if (TY_(tmbstrcmp)(s, np->name) == 0)
return np;
#endif /* ELEMENT_HASH_LOOKUP */
return NULL;
}
static Dict* NewDict( TidyDocImpl* doc, ctmbstr name )
{
Dict *np = (Dict*) TidyDocAlloc( doc, sizeof(Dict) );
np->id = TidyTag_UNKNOWN;
np->name = name ? TY_(tmbstrdup)( doc->allocator, name ) : NULL;
np->versions = VERS_UNKNOWN;
np->attrvers = NULL;
np->model = CM_UNKNOWN;
np->parser = 0;
np->chkattrs = 0;
np->next = NULL;
return np;
}
static void FreeDict( TidyDocImpl* doc, Dict *d )
{
if ( d )
TidyDocFree( doc, d->name );
TidyDocFree( doc, d );
}
static void declare( TidyDocImpl* doc, TidyTagImpl* tags,
ctmbstr name, uint versions, uint model,
Parser *parser, CheckAttribs *chkattrs )
{
if ( name )
{
Dict* np = (Dict*) tagsLookup( doc, tags, name );
if ( np == NULL )
{
np = NewDict( doc, name );
np->next = tags->declared_tag_list;
tags->declared_tag_list = np;
}
/* Make sure we are not over-writing predefined tags */
if ( np->id == TidyTag_UNKNOWN )
{
np->versions = versions;
np->model |= model;
np->parser = parser;
np->chkattrs = chkattrs;
np->attrvers = NULL;
}
}
}
/* public interface for finding tag by name */
Bool TY_(FindTag)( TidyDocImpl* doc, Node *node )
{
const Dict *np = NULL;
if ( cfgBool(doc, TidyXmlTags) )
{
node->tag = doc->tags.xml_tags;
return yes;
}
if ( node->element && (np = tagsLookup(doc, &doc->tags, node->element)) )
{
node->tag = np;
return yes;
}
return no;
}
const Dict* TY_(LookupTagDef)( TidyTagId tid )
{
const Dict *np;
for (np = tag_defs + 1; np < tag_defs + N_TIDY_TAGS; ++np )
if (np->id == tid)
return np;
return NULL;
}
Parser* TY_(FindParser)( TidyDocImpl* doc, Node *node )
{
const Dict* np = tagsLookup( doc, &doc->tags, node->element );
if ( np )
return np->parser;
return NULL;
}
void TY_(DefineTag)( TidyDocImpl* doc, UserTagType tagType, ctmbstr name )
{
Parser* parser = 0;
uint cm = CM_UNKNOWN;
uint vers = VERS_PROPRIETARY;
switch (tagType)
{
case tagtype_empty:
cm = CM_EMPTY|CM_NO_INDENT|CM_NEW;
parser = TY_(ParseBlock);
break;
case tagtype_inline:
cm = CM_INLINE|CM_NO_INDENT|CM_NEW;
parser = TY_(ParseInline);
break;
case tagtype_block:
cm = CM_BLOCK|CM_NO_INDENT|CM_NEW;
parser = TY_(ParseBlock);
break;
case tagtype_pre:
cm = CM_BLOCK|CM_NO_INDENT|CM_NEW;
parser = TY_(ParsePre);
break;
case tagtype_null:
break;
}
if ( cm && parser )
declare( doc, &doc->tags, name, vers, cm, parser, 0 );
}
TidyIterator TY_(GetDeclaredTagList)( TidyDocImpl* doc )
{
return (TidyIterator) doc->tags.declared_tag_list;
}
ctmbstr TY_(GetNextDeclaredTag)( TidyDocImpl* ARG_UNUSED(doc),
UserTagType tagType, TidyIterator* iter )
{
ctmbstr name = NULL;
Dict* curr;
for ( curr = (Dict*) *iter; name == NULL && curr != NULL; curr = curr->next )
{
switch ( tagType )
{
case tagtype_empty:
if ( (curr->model & CM_EMPTY) != 0 )
name = curr->name;
break;
case tagtype_inline:
if ( (curr->model & CM_INLINE) != 0 )
name = curr->name;
break;
case tagtype_block:
if ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParseBlock) )
name = curr->name;
break;
case tagtype_pre:
if ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParsePre) )
name = curr->name;
break;
case tagtype_null:
break;
}
}
*iter = (TidyIterator) curr;
return name;
}
void TY_(InitTags)( TidyDocImpl* doc )
{
Dict* xml;
TidyTagImpl* tags = &doc->tags;
TidyClearMemory( tags, sizeof(TidyTagImpl) );
/* create dummy entry for all xml tags */
xml = NewDict( doc, NULL );
xml->versions = VERS_XML;
xml->model = CM_BLOCK;
xml->parser = 0;
xml->chkattrs = 0;
xml->attrvers = NULL;
tags->xml_tags = xml;
}
/* By default, zap all of them. But allow
** an single type to be specified.
*/
void TY_(FreeDeclaredTags)( TidyDocImpl* doc, UserTagType tagType )
{
TidyTagImpl* tags = &doc->tags;
Dict *curr, *next = NULL, *prev = NULL;
for ( curr=tags->declared_tag_list; curr; curr = next )
{
Bool deleteIt = yes;
next = curr->next;
switch ( tagType )
{
case tagtype_empty:
deleteIt = ( curr->model & CM_EMPTY ) != 0;
break;
case tagtype_inline:
deleteIt = ( curr->model & CM_INLINE ) != 0;
break;
case tagtype_block:
deleteIt = ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParseBlock) );
break;
case tagtype_pre:
deleteIt = ( (curr->model & CM_BLOCK) != 0 &&
curr->parser == TY_(ParsePre) );
break;
case tagtype_null:
break;
}
if ( deleteIt )
{
#if ELEMENT_HASH_LOOKUP
tagsRemoveFromHash( doc, &doc->tags, curr->name );
#endif
FreeDict( doc, curr );
if ( prev )
prev->next = next;
else
tags->declared_tag_list = next;
}
else
prev = curr;
}
}
void TY_(FreeTags)( TidyDocImpl* doc )
{
TidyTagImpl* tags = &doc->tags;
#if ELEMENT_HASH_LOOKUP
tagsEmptyHash( doc, tags );
#endif
TY_(FreeDeclaredTags)( doc, tagtype_null );
FreeDict( doc, tags->xml_tags );
/* get rid of dangling tag references */
TidyClearMemory( tags, sizeof(TidyTagImpl) );
}
/* default method for checking an element's attributes */
void TY_(CheckAttributes)( TidyDocImpl* doc, Node *node )
{
AttVal *next, *attval = node->attributes;
while (attval)
{
next = attval->next;
TY_(CheckAttribute)( doc, node, attval );
attval = next;
}
}
/* methods for checking attributes for specific elements */
void CheckIMG( TidyDocImpl* doc, Node *node )
{
Bool HasAlt = TY_(AttrGetById)(node, TidyAttr_ALT) != NULL;
Bool HasSrc = TY_(AttrGetById)(node, TidyAttr_SRC) != NULL;
Bool HasUseMap = TY_(AttrGetById)(node, TidyAttr_USEMAP) != NULL;
Bool HasIsMap = TY_(AttrGetById)(node, TidyAttr_ISMAP) != NULL;
Bool HasDataFld = TY_(AttrGetById)(node, TidyAttr_DATAFLD) != NULL;
TY_(CheckAttributes)(doc, node);
if ( !HasAlt )
{
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
doc->badAccess |= BA_MISSING_IMAGE_ALT;
TY_(ReportMissingAttr)( doc, node, "alt" );
}
if ( cfgStr(doc, TidyAltText) )
TY_(AddAttribute)( doc, node, "alt", cfgStr(doc, TidyAltText) );
}
if ( !HasSrc && !HasDataFld )
TY_(ReportMissingAttr)( doc, node, "src" );
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
if ( HasIsMap && !HasUseMap )
TY_(ReportAttrError)( doc, node, NULL, MISSING_IMAGEMAP);
}
}
void CheckCaption(TidyDocImpl* doc, Node *node)
{
AttVal *attval;
TY_(CheckAttributes)(doc, node);
attval = TY_(AttrGetById)(node, TidyAttr_ALIGN);
if (!AttrHasValue(attval))
return;
if (AttrValueIs(attval, "left") || AttrValueIs(attval, "right"))
TY_(ConstrainVersion)(doc, VERS_HTML40_LOOSE);
else if (AttrValueIs(attval, "top") || AttrValueIs(attval, "bottom"))
TY_(ConstrainVersion)(doc, ~(VERS_HTML20|VERS_HTML32));
else
TY_(ReportAttrError)(doc, node, attval, BAD_ATTRIBUTE_VALUE);
}
void CheckHTML( TidyDocImpl* doc, Node *node )
{
TY_(CheckAttributes)(doc, node);
}
void CheckAREA( TidyDocImpl* doc, Node *node )
{
Bool HasAlt = TY_(AttrGetById)(node, TidyAttr_ALT) != NULL;
Bool HasHref = TY_(AttrGetById)(node, TidyAttr_HREF) != NULL;
Bool HasNohref = TY_(AttrGetById)(node, TidyAttr_NOHREF) != NULL;
TY_(CheckAttributes)(doc, node);
if ( !HasAlt )
{
if ( cfg(doc, TidyAccessibilityCheckLevel) == 0 )
{
doc->badAccess |= BA_MISSING_LINK_ALT;
TY_(ReportMissingAttr)( doc, node, "alt" );
}
}
if ( !HasHref && !HasNohref )
TY_(ReportMissingAttr)( doc, node, "href" );
}
void CheckTABLE( TidyDocImpl* doc, Node *node )
{
AttVal* attval;
Bool HasSummary = TY_(AttrGetById)(node, TidyAttr_SUMMARY) != NULL;
TY_(CheckAttributes)(doc, node);
/* a missing summary attribute is bad accessibility, no matter
what HTML version is involved; a document without is valid */
if (cfg(doc, TidyAccessibilityCheckLevel) == 0)
{
if (!HasSummary)
{
doc->badAccess |= BA_MISSING_SUMMARY;
TY_(ReportMissingAttr)( doc, node, "summary");
}
}
/* convert <table border> to <table border="1"> */
if ( cfgBool(doc, TidyXmlOut) && (attval = TY_(AttrGetById)(node, TidyAttr_BORDER)) )
{
if (attval->value == NULL)
attval->value = TY_(tmbstrdup)(doc->allocator, "1");
}
}
/* add missing type attribute when appropriate */
void CheckSCRIPT( TidyDocImpl* doc, Node *node )
{
AttVal *lang, *type;
char buf[16];
TY_(CheckAttributes)(doc, node);
lang = TY_(AttrGetById)(node, TidyAttr_LANGUAGE);
type = TY_(AttrGetById)(node, TidyAttr_TYPE);
if (!type)
{
/* check for javascript */
if (lang)
{
/* Test #696799. lang->value can be NULL. */
buf[0] = '\0';
TY_(tmbstrncpy)(buf, lang->value, sizeof(buf));
buf[10] = '\0';
if (TY_(tmbstrncasecmp)(buf, "javascript", 10) == 0 ||
TY_(tmbstrncasecmp)(buf, "jscript", 7) == 0)
{
TY_(AddAttribute)(doc, node, "type", "text/javascript");
}
else if (TY_(tmbstrcasecmp)(buf, "vbscript") == 0)
{
/* per Randy Waki 8/6/01 */
TY_(AddAttribute)(doc, node, "type", "text/vbscript");
}
}
else
{
TY_(AddAttribute)(doc, node, "type", "text/javascript");
}
type = TY_(AttrGetById)(node, TidyAttr_TYPE);
if (type != NULL)
{
TY_(ReportAttrError)(doc, node, type, INSERTING_ATTRIBUTE);
}
else
{
TY_(ReportMissingAttr)(doc, node, "type");
}
}
}
/* add missing type attribute when appropriate */
void CheckSTYLE( TidyDocImpl* doc, Node *node )
{
AttVal *type = TY_(AttrGetById)(node, TidyAttr_TYPE);
TY_(CheckAttributes)( doc, node );
if ( !type || !type->value || !TY_(tmbstrlen)(type->value) )
{
type = TY_(RepairAttrValue)(doc, node, "type", "text/css");
TY_(ReportAttrError)( doc, node, type, INSERTING_ATTRIBUTE );
}
}
/* add missing type attribute when appropriate */
void CheckLINK( TidyDocImpl* doc, Node *node )
{
AttVal *rel = TY_(AttrGetById)(node, TidyAttr_REL);
TY_(CheckAttributes)( doc, node );
/* todo: <link rel="alternate stylesheet"> */
if (AttrValueIs(rel, "stylesheet"))
{
AttVal *type = TY_(AttrGetById)(node, TidyAttr_TYPE);
if (!type)
{
TY_(AddAttribute)( doc, node, "type", "text/css" );
type = TY_(AttrGetById)(node, TidyAttr_TYPE);
TY_(ReportAttrError)( doc, node, type, INSERTING_ATTRIBUTE );
}
}
}
/* reports missing action attribute */
void CheckFORM( TidyDocImpl* doc, Node *node )
{
AttVal *action = TY_(AttrGetById)(node, TidyAttr_ACTION);
TY_(CheckAttributes)(doc, node);
if (!action)
TY_(ReportMissingAttr)(doc, node, "action");
}
/* reports missing content attribute */
void CheckMETA( TidyDocImpl* doc, Node *node )
{
AttVal *content = TY_(AttrGetById)(node, TidyAttr_CONTENT);
TY_(CheckAttributes)(doc, node);
if (!content)
TY_(ReportMissingAttr)( doc, node, "content" );
/* name or http-equiv attribute must also be set */
}
Bool TY_(nodeIsText)( Node* node )
{
return ( node && node->type == TextNode );
}
Bool TY_(nodeHasText)( TidyDocImpl* doc, Node* node )
{
if ( doc && node )
{
uint ix;
Lexer* lexer = doc->lexer;
for ( ix = node->start; ix < node->end; ++ix )
{
/* whitespace */
if ( !TY_(IsWhite)( lexer->lexbuf[ix] ) )
return yes;
}
}
return no;
}
Bool TY_(nodeIsElement)( Node* node )
{
return ( node &&
(node->type == StartTag || node->type == StartEndTag) );
}
#if 0
/* Compare & result to operand. If equal, then all bits
** requested are set.
*/
Bool nodeMatchCM( Node* node, uint contentModel )
{
return ( node && node->tag &&
(node->tag->model & contentModel) == contentModel );
}
#endif
/* True if any of the bits requested are set.
*/
Bool TY_(nodeHasCM)( Node* node, uint contentModel )
{
return ( node && node->tag &&
(node->tag->model & contentModel) != 0 );
}
Bool TY_(nodeCMIsBlock)( Node* node )
{
return TY_(nodeHasCM)( node, CM_BLOCK );
}
Bool TY_(nodeCMIsInline)( Node* node )
{
return TY_(nodeHasCM)( node, CM_INLINE );
}
Bool TY_(nodeCMIsEmpty)( Node* node )
{
return TY_(nodeHasCM)( node, CM_EMPTY );
}
Bool TY_(nodeIsHeader)( Node* node )
{
TidyTagId tid = TagId( node );
return ( tid && (
tid == TidyTag_H1 ||
tid == TidyTag_H2 ||
tid == TidyTag_H3 ||
tid == TidyTag_H4 ||
tid == TidyTag_H5 ||
tid == TidyTag_H6 ));
}
uint TY_(nodeHeaderLevel)( Node* node )
{
TidyTagId tid = TagId( node );
switch ( tid )
{
case TidyTag_H1:
return 1;
case TidyTag_H2:
return 2;
case TidyTag_H3:
return 3;
case TidyTag_H4:
return 4;
case TidyTag_H5:
return 5;
case TidyTag_H6:
return 6;
default:
{
/* fall through */
}
}
return 0;
}
/*
* local variables:
* mode: c
* indent-tabs-mode: nil
* c-basic-offset: 4
* eval: (c-set-offset 'substatement-open 0)
* end:
*/
| gpl-3.0 |
redFrik/supercollider | external_libraries/portmidi/pm_win/pmwin.c | 37 | 3741 | /* pmwin.c -- PortMidi os-dependent code */
/* This file only needs to implement:
pm_init(), which calls various routines to register the
available midi devices,
Pm_GetDefaultInputDeviceID(), and
Pm_GetDefaultOutputDeviceID().
This file must
be separate from the main portmidi.c file because it is system
dependent, and it is separate from, say, pmwinmm.c, because it
might need to register devices for winmm, directx, and others.
*/
#include "stdlib.h"
#include "portmidi.h"
#include "pmutil.h"
#include "pminternal.h"
#include "pmwinmm.h"
#ifdef DEBUG
#include "stdio.h"
#endif
#include <windows.h>
/* pm_exit is called when the program exits.
It calls pm_term to make sure PortMidi is properly closed.
If DEBUG is on, we prompt for input to avoid losing error messages.
*/
static void pm_exit(void) {
pm_term();
#ifdef DEBUG
#define STRING_MAX 80
{
char line[STRING_MAX];
printf("Type ENTER...\n");
/* note, w/o this prompting, client console application can not see one
of its errors before closing. */
fgets(line, STRING_MAX, stdin);
}
#endif
}
/* pm_init is the windows-dependent initialization.*/
void pm_init(void)
{
atexit(pm_exit);
#ifdef DEBUG
printf("registered pm_exit with atexit()\n");
#endif
pm_winmm_init();
/* initialize other APIs (DirectX?) here */
}
void pm_term(void) {
pm_winmm_term();
}
static PmDeviceID pm_get_default_device_id(int is_input, char *key) {
HKEY hkey;
#define PATTERN_MAX 256
char pattern[PATTERN_MAX];
long pattern_max = PATTERN_MAX;
DWORD dwType;
/* Find first input or device -- this is the default. */
PmDeviceID id = pmNoDevice;
int i, j;
Pm_Initialize(); /* make sure descriptors exist! */
for (i = 0; i < pm_descriptor_index; i++) {
if (descriptors[i].pub.input == is_input) {
id = i;
break;
}
}
/* Look in registry for a default device name pattern. */
if (RegOpenKeyEx(HKEY_CURRENT_USER, "Software", 0, KEY_READ, &hkey) !=
ERROR_SUCCESS) {
return id;
}
if (RegOpenKeyEx(hkey, "JavaSoft", 0, KEY_READ, &hkey) !=
ERROR_SUCCESS) {
return id;
}
if (RegOpenKeyEx(hkey, "Prefs", 0, KEY_READ, &hkey) !=
ERROR_SUCCESS) {
return id;
}
if (RegOpenKeyEx(hkey, "/Port/Midi", 0, KEY_READ, &hkey) !=
ERROR_SUCCESS) {
return id;
}
if (RegQueryValueEx(hkey, key, NULL, &dwType, (BYTE *) pattern,
(DWORD *) &pattern_max) !=
ERROR_SUCCESS) {
return id;
}
/* decode pattern: upper case encoded with "/" prefix */
i = j = 0;
while (pattern[i]) {
if (pattern[i] == '/' && pattern[i + 1]) {
pattern[j++] = toupper(pattern[++i]);
} else {
pattern[j++] = tolower(pattern[i]);
}
i++;
}
pattern[j] = 0; /* end of string */
/* now pattern is the string from the registry; search for match */
i = pm_find_default_device(pattern, is_input);
if (i != pmNoDevice) {
id = i;
}
return id;
}
PmDeviceID Pm_GetDefaultInputDeviceID() {
return pm_get_default_device_id(TRUE,
"/P/M_/R/E/C/O/M/M/E/N/D/E/D_/I/N/P/U/T_/D/E/V/I/C/E");
}
PmDeviceID Pm_GetDefaultOutputDeviceID() {
return pm_get_default_device_id(FALSE,
"/P/M_/R/E/C/O/M/M/E/N/D/E/D_/O/U/T/P/U/T_/D/E/V/I/C/E");
}
#include "stdio.h"
void *pm_alloc(size_t s) {
return malloc(s);
}
void pm_free(void *ptr) {
free(ptr);
}
| gpl-3.0 |
hasanalom/tdesktop | Telegram/SourceFiles/_other/msmain.cpp | 37 | 2435 | /*
This file is part of Telegram Desktop,
the official desktop version of Telegram messaging app, see https://telegram.org
Telegram Desktop 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.
It is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
Full license: https://github.com/telegramdesktop/tdesktop/blob/master/LICENSE
Copyright (c) 2014 John Preston, https://desktop.telegram.org
*/
#include "msmain.h"
#include <QtCore/QDir>
int main(int argc, char *argv[]) {
QString classes_in("style_classes.txt"), classes_out("style_classes.h"), styles_in("style.txt"), styles_out("style_auto.h"), path_to_sprites("./SourceFiles/art/");
for (int i = 0; i < argc; ++i) {
if (string("-classes_in") == argv[i]) {
if (++i < argc) classes_in = argv[i];
} else if (string("-classes_out") == argv[i]) {
if (++i < argc) classes_out = argv[i];
} else if (string("-styles_in") == argv[i]) {
if (++i < argc) styles_in = argv[i];
} else if (string("-styles_out") == argv[i]) {
if (++i < argc) styles_out = argv[i];
} else if (string("-path_to_sprites") == argv[i]) {
if (++i < argc) path_to_sprites = argv[i];
}
}
#ifdef Q_OS_MAC
if (QDir(QString()).absolutePath() == "/") {
QString first = argc ? QString::fromLocal8Bit(argv[0]) : QString();
if (!first.isEmpty()) {
QFileInfo info(first);
if (info.exists()) {
QDir result(info.absolutePath() + "/../../..");
QString basePath = result.absolutePath() + '/';
classes_in = basePath + classes_in;
classes_out = basePath + classes_out;
styles_in = basePath + styles_in;
styles_out = basePath + styles_out;
path_to_sprites = basePath + path_to_sprites;
}
}
}
#endif
QObject *taskImpl = new GenStyles(classes_in, classes_out, styles_in, styles_out, path_to_sprites);
QGuiApplication a(argc, argv);
QObject::connect(taskImpl, SIGNAL(finished()), &a, SLOT(quit()));
QTimer::singleShot(0, taskImpl, SLOT(run()));
return a.exec();
}
| gpl-3.0 |
danialbehzadi/Nokia-RM-1013-2.0.0.11 | kernel/drivers/gpu/drm/gma500/mdfld_tmd_vid.c | 10278 | 7236 | /*
* Copyright © 2010 Intel Corporation
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice (including the next
* paragraph) shall be included in all copies or substantial portions of the
* Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
* Authors:
* Jim Liu <jim.liu@intel.com>
* Jackie Li<yaodong.li@intel.com>
* Gideon Eaton <eaton.
* Scott Rowe <scott.m.rowe@intel.com>
*/
#include "mdfld_dsi_dpi.h"
#include "mdfld_dsi_pkg_sender.h"
static struct drm_display_mode *tmd_vid_get_config_mode(struct drm_device *dev)
{
struct drm_display_mode *mode;
struct drm_psb_private *dev_priv = dev->dev_private;
struct oaktrail_timing_info *ti = &dev_priv->gct_data.DTD;
bool use_gct = false; /*Disable GCT for now*/
mode = kzalloc(sizeof(*mode), GFP_KERNEL);
if (!mode)
return NULL;
if (use_gct) {
mode->hdisplay = (ti->hactive_hi << 8) | ti->hactive_lo;
mode->vdisplay = (ti->vactive_hi << 8) | ti->vactive_lo;
mode->hsync_start = mode->hdisplay + \
((ti->hsync_offset_hi << 8) | \
ti->hsync_offset_lo);
mode->hsync_end = mode->hsync_start + \
((ti->hsync_pulse_width_hi << 8) | \
ti->hsync_pulse_width_lo);
mode->htotal = mode->hdisplay + ((ti->hblank_hi << 8) | \
ti->hblank_lo);
mode->vsync_start = \
mode->vdisplay + ((ti->vsync_offset_hi << 8) | \
ti->vsync_offset_lo);
mode->vsync_end = \
mode->vsync_start + ((ti->vsync_pulse_width_hi << 8) | \
ti->vsync_pulse_width_lo);
mode->vtotal = mode->vdisplay + \
((ti->vblank_hi << 8) | ti->vblank_lo);
mode->clock = ti->pixel_clock * 10;
dev_dbg(dev->dev, "hdisplay is %d\n", mode->hdisplay);
dev_dbg(dev->dev, "vdisplay is %d\n", mode->vdisplay);
dev_dbg(dev->dev, "HSS is %d\n", mode->hsync_start);
dev_dbg(dev->dev, "HSE is %d\n", mode->hsync_end);
dev_dbg(dev->dev, "htotal is %d\n", mode->htotal);
dev_dbg(dev->dev, "VSS is %d\n", mode->vsync_start);
dev_dbg(dev->dev, "VSE is %d\n", mode->vsync_end);
dev_dbg(dev->dev, "vtotal is %d\n", mode->vtotal);
dev_dbg(dev->dev, "clock is %d\n", mode->clock);
} else {
mode->hdisplay = 480;
mode->vdisplay = 854;
mode->hsync_start = 487;
mode->hsync_end = 490;
mode->htotal = 499;
mode->vsync_start = 861;
mode->vsync_end = 865;
mode->vtotal = 873;
mode->clock = 33264;
}
drm_mode_set_name(mode);
drm_mode_set_crtcinfo(mode, 0);
mode->type |= DRM_MODE_TYPE_PREFERRED;
return mode;
}
static int tmd_vid_get_panel_info(struct drm_device *dev,
int pipe,
struct panel_info *pi)
{
if (!dev || !pi)
return -EINVAL;
pi->width_mm = TMD_PANEL_WIDTH;
pi->height_mm = TMD_PANEL_HEIGHT;
return 0;
}
/* ************************************************************************* *\
* FUNCTION: mdfld_init_TMD_MIPI
*
* DESCRIPTION: This function is called only by mrst_dsi_mode_set and
* restore_display_registers. since this function does not
* acquire the mutex, it is important that the calling function
* does!
\* ************************************************************************* */
/* FIXME: make the below data u8 instead of u32; note byte order! */
static u32 tmd_cmd_mcap_off[] = {0x000000b2};
static u32 tmd_cmd_enable_lane_switch[] = {0x000101ef};
static u32 tmd_cmd_set_lane_num[] = {0x006360ef};
static u32 tmd_cmd_pushing_clock0[] = {0x00cc2fef};
static u32 tmd_cmd_pushing_clock1[] = {0x00dd6eef};
static u32 tmd_cmd_set_mode[] = {0x000000b3};
static u32 tmd_cmd_set_sync_pulse_mode[] = {0x000961ef};
static u32 tmd_cmd_set_column[] = {0x0100002a, 0x000000df};
static u32 tmd_cmd_set_page[] = {0x0300002b, 0x00000055};
static u32 tmd_cmd_set_video_mode[] = {0x00000153};
/*no auto_bl,need add in furture*/
static u32 tmd_cmd_enable_backlight[] = {0x00005ab4};
static u32 tmd_cmd_set_backlight_dimming[] = {0x00000ebd};
static void mdfld_dsi_tmd_drv_ic_init(struct mdfld_dsi_config *dsi_config,
int pipe)
{
struct mdfld_dsi_pkg_sender *sender
= mdfld_dsi_get_pkg_sender(dsi_config);
DRM_INFO("Enter mdfld init TMD MIPI display.\n");
if (!sender) {
DRM_ERROR("Cannot get sender\n");
return;
}
if (dsi_config->dvr_ic_inited)
return;
msleep(3);
/* FIXME: make the below data u8 instead of u32; note byte order! */
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_mcap_off,
sizeof(tmd_cmd_mcap_off), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_enable_lane_switch,
sizeof(tmd_cmd_enable_lane_switch), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_lane_num,
sizeof(tmd_cmd_set_lane_num), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_pushing_clock0,
sizeof(tmd_cmd_pushing_clock0), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_pushing_clock1,
sizeof(tmd_cmd_pushing_clock1), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_mode,
sizeof(tmd_cmd_set_mode), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_sync_pulse_mode,
sizeof(tmd_cmd_set_sync_pulse_mode), false);
mdfld_dsi_send_mcs_long(sender, (u8 *) tmd_cmd_set_column,
sizeof(tmd_cmd_set_column), false);
mdfld_dsi_send_mcs_long(sender, (u8 *) tmd_cmd_set_page,
sizeof(tmd_cmd_set_page), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_video_mode,
sizeof(tmd_cmd_set_video_mode), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_enable_backlight,
sizeof(tmd_cmd_enable_backlight), false);
mdfld_dsi_send_gen_long(sender, (u8 *) tmd_cmd_set_backlight_dimming,
sizeof(tmd_cmd_set_backlight_dimming), false);
dsi_config->dvr_ic_inited = 1;
}
/*TPO DPI encoder helper funcs*/
static const struct drm_encoder_helper_funcs
mdfld_tpo_dpi_encoder_helper_funcs = {
.dpms = mdfld_dsi_dpi_dpms,
.mode_fixup = mdfld_dsi_dpi_mode_fixup,
.prepare = mdfld_dsi_dpi_prepare,
.mode_set = mdfld_dsi_dpi_mode_set,
.commit = mdfld_dsi_dpi_commit,
};
/*TPO DPI encoder funcs*/
static const struct drm_encoder_funcs mdfld_tpo_dpi_encoder_funcs = {
.destroy = drm_encoder_cleanup,
};
const struct panel_funcs mdfld_tmd_vid_funcs = {
.encoder_funcs = &mdfld_tpo_dpi_encoder_funcs,
.encoder_helper_funcs = &mdfld_tpo_dpi_encoder_helper_funcs,
.get_config_mode = &tmd_vid_get_config_mode,
.get_panel_info = tmd_vid_get_panel_info,
.reset = mdfld_dsi_panel_reset,
.drv_ic_init = mdfld_dsi_tmd_drv_ic_init,
};
| gpl-3.0 |
geminy/aidear | oss/linux/linux-4.7/kernel/signal.c | 42 | 96412 | /*
* linux/kernel/signal.c
*
* Copyright (C) 1991, 1992 Linus Torvalds
*
* 1997-11-02 Modified for POSIX.1b signals by Richard Henderson
*
* 2003-06-02 Jim Houston - Concurrent Computer Corp.
* Changes to use preallocated sigqueue structures
* to allow signals to be sent reliably.
*/
#include <linux/slab.h>
#include <linux/export.h>
#include <linux/init.h>
#include <linux/sched.h>
#include <linux/fs.h>
#include <linux/tty.h>
#include <linux/binfmts.h>
#include <linux/coredump.h>
#include <linux/security.h>
#include <linux/syscalls.h>
#include <linux/ptrace.h>
#include <linux/signal.h>
#include <linux/signalfd.h>
#include <linux/ratelimit.h>
#include <linux/tracehook.h>
#include <linux/capability.h>
#include <linux/freezer.h>
#include <linux/pid_namespace.h>
#include <linux/nsproxy.h>
#include <linux/user_namespace.h>
#include <linux/uprobes.h>
#include <linux/compat.h>
#include <linux/cn_proc.h>
#include <linux/compiler.h>
#define CREATE_TRACE_POINTS
#include <trace/events/signal.h>
#include <asm/param.h>
#include <asm/uaccess.h>
#include <asm/unistd.h>
#include <asm/siginfo.h>
#include <asm/cacheflush.h>
#include "audit.h" /* audit_signal_info() */
/*
* SLAB caches for signal bits.
*/
static struct kmem_cache *sigqueue_cachep;
int print_fatal_signals __read_mostly;
static void __user *sig_handler(struct task_struct *t, int sig)
{
return t->sighand->action[sig - 1].sa.sa_handler;
}
static int sig_handler_ignored(void __user *handler, int sig)
{
/* Is it explicitly or implicitly ignored? */
return handler == SIG_IGN ||
(handler == SIG_DFL && sig_kernel_ignore(sig));
}
static int sig_task_ignored(struct task_struct *t, int sig, bool force)
{
void __user *handler;
handler = sig_handler(t, sig);
if (unlikely(t->signal->flags & SIGNAL_UNKILLABLE) &&
handler == SIG_DFL && !force)
return 1;
return sig_handler_ignored(handler, sig);
}
static int sig_ignored(struct task_struct *t, int sig, bool force)
{
/*
* Blocked signals are never ignored, since the
* signal handler may change by the time it is
* unblocked.
*/
if (sigismember(&t->blocked, sig) || sigismember(&t->real_blocked, sig))
return 0;
if (!sig_task_ignored(t, sig, force))
return 0;
/*
* Tracers may want to know about even ignored signals.
*/
return !t->ptrace;
}
/*
* Re-calculate pending state from the set of locally pending
* signals, globally pending signals, and blocked signals.
*/
static inline int has_pending_signals(sigset_t *signal, sigset_t *blocked)
{
unsigned long ready;
long i;
switch (_NSIG_WORDS) {
default:
for (i = _NSIG_WORDS, ready = 0; --i >= 0 ;)
ready |= signal->sig[i] &~ blocked->sig[i];
break;
case 4: ready = signal->sig[3] &~ blocked->sig[3];
ready |= signal->sig[2] &~ blocked->sig[2];
ready |= signal->sig[1] &~ blocked->sig[1];
ready |= signal->sig[0] &~ blocked->sig[0];
break;
case 2: ready = signal->sig[1] &~ blocked->sig[1];
ready |= signal->sig[0] &~ blocked->sig[0];
break;
case 1: ready = signal->sig[0] &~ blocked->sig[0];
}
return ready != 0;
}
#define PENDING(p,b) has_pending_signals(&(p)->signal, (b))
static int recalc_sigpending_tsk(struct task_struct *t)
{
if ((t->jobctl & JOBCTL_PENDING_MASK) ||
PENDING(&t->pending, &t->blocked) ||
PENDING(&t->signal->shared_pending, &t->blocked)) {
set_tsk_thread_flag(t, TIF_SIGPENDING);
return 1;
}
/*
* We must never clear the flag in another thread, or in current
* when it's possible the current syscall is returning -ERESTART*.
* So we don't clear it here, and only callers who know they should do.
*/
return 0;
}
/*
* After recalculating TIF_SIGPENDING, we need to make sure the task wakes up.
* This is superfluous when called on current, the wakeup is a harmless no-op.
*/
void recalc_sigpending_and_wake(struct task_struct *t)
{
if (recalc_sigpending_tsk(t))
signal_wake_up(t, 0);
}
void recalc_sigpending(void)
{
if (!recalc_sigpending_tsk(current) && !freezing(current))
clear_thread_flag(TIF_SIGPENDING);
}
/* Given the mask, find the first available signal that should be serviced. */
#define SYNCHRONOUS_MASK \
(sigmask(SIGSEGV) | sigmask(SIGBUS) | sigmask(SIGILL) | \
sigmask(SIGTRAP) | sigmask(SIGFPE) | sigmask(SIGSYS))
int next_signal(struct sigpending *pending, sigset_t *mask)
{
unsigned long i, *s, *m, x;
int sig = 0;
s = pending->signal.sig;
m = mask->sig;
/*
* Handle the first word specially: it contains the
* synchronous signals that need to be dequeued first.
*/
x = *s &~ *m;
if (x) {
if (x & SYNCHRONOUS_MASK)
x &= SYNCHRONOUS_MASK;
sig = ffz(~x) + 1;
return sig;
}
switch (_NSIG_WORDS) {
default:
for (i = 1; i < _NSIG_WORDS; ++i) {
x = *++s &~ *++m;
if (!x)
continue;
sig = ffz(~x) + i*_NSIG_BPW + 1;
break;
}
break;
case 2:
x = s[1] &~ m[1];
if (!x)
break;
sig = ffz(~x) + _NSIG_BPW + 1;
break;
case 1:
/* Nothing to do */
break;
}
return sig;
}
static inline void print_dropped_signal(int sig)
{
static DEFINE_RATELIMIT_STATE(ratelimit_state, 5 * HZ, 10);
if (!print_fatal_signals)
return;
if (!__ratelimit(&ratelimit_state))
return;
pr_info("%s/%d: reached RLIMIT_SIGPENDING, dropped signal %d\n",
current->comm, current->pid, sig);
}
/**
* task_set_jobctl_pending - set jobctl pending bits
* @task: target task
* @mask: pending bits to set
*
* Clear @mask from @task->jobctl. @mask must be subset of
* %JOBCTL_PENDING_MASK | %JOBCTL_STOP_CONSUME | %JOBCTL_STOP_SIGMASK |
* %JOBCTL_TRAPPING. If stop signo is being set, the existing signo is
* cleared. If @task is already being killed or exiting, this function
* becomes noop.
*
* CONTEXT:
* Must be called with @task->sighand->siglock held.
*
* RETURNS:
* %true if @mask is set, %false if made noop because @task was dying.
*/
bool task_set_jobctl_pending(struct task_struct *task, unsigned long mask)
{
BUG_ON(mask & ~(JOBCTL_PENDING_MASK | JOBCTL_STOP_CONSUME |
JOBCTL_STOP_SIGMASK | JOBCTL_TRAPPING));
BUG_ON((mask & JOBCTL_TRAPPING) && !(mask & JOBCTL_PENDING_MASK));
if (unlikely(fatal_signal_pending(task) || (task->flags & PF_EXITING)))
return false;
if (mask & JOBCTL_STOP_SIGMASK)
task->jobctl &= ~JOBCTL_STOP_SIGMASK;
task->jobctl |= mask;
return true;
}
/**
* task_clear_jobctl_trapping - clear jobctl trapping bit
* @task: target task
*
* If JOBCTL_TRAPPING is set, a ptracer is waiting for us to enter TRACED.
* Clear it and wake up the ptracer. Note that we don't need any further
* locking. @task->siglock guarantees that @task->parent points to the
* ptracer.
*
* CONTEXT:
* Must be called with @task->sighand->siglock held.
*/
void task_clear_jobctl_trapping(struct task_struct *task)
{
if (unlikely(task->jobctl & JOBCTL_TRAPPING)) {
task->jobctl &= ~JOBCTL_TRAPPING;
smp_mb(); /* advised by wake_up_bit() */
wake_up_bit(&task->jobctl, JOBCTL_TRAPPING_BIT);
}
}
/**
* task_clear_jobctl_pending - clear jobctl pending bits
* @task: target task
* @mask: pending bits to clear
*
* Clear @mask from @task->jobctl. @mask must be subset of
* %JOBCTL_PENDING_MASK. If %JOBCTL_STOP_PENDING is being cleared, other
* STOP bits are cleared together.
*
* If clearing of @mask leaves no stop or trap pending, this function calls
* task_clear_jobctl_trapping().
*
* CONTEXT:
* Must be called with @task->sighand->siglock held.
*/
void task_clear_jobctl_pending(struct task_struct *task, unsigned long mask)
{
BUG_ON(mask & ~JOBCTL_PENDING_MASK);
if (mask & JOBCTL_STOP_PENDING)
mask |= JOBCTL_STOP_CONSUME | JOBCTL_STOP_DEQUEUED;
task->jobctl &= ~mask;
if (!(task->jobctl & JOBCTL_PENDING_MASK))
task_clear_jobctl_trapping(task);
}
/**
* task_participate_group_stop - participate in a group stop
* @task: task participating in a group stop
*
* @task has %JOBCTL_STOP_PENDING set and is participating in a group stop.
* Group stop states are cleared and the group stop count is consumed if
* %JOBCTL_STOP_CONSUME was set. If the consumption completes the group
* stop, the appropriate %SIGNAL_* flags are set.
*
* CONTEXT:
* Must be called with @task->sighand->siglock held.
*
* RETURNS:
* %true if group stop completion should be notified to the parent, %false
* otherwise.
*/
static bool task_participate_group_stop(struct task_struct *task)
{
struct signal_struct *sig = task->signal;
bool consume = task->jobctl & JOBCTL_STOP_CONSUME;
WARN_ON_ONCE(!(task->jobctl & JOBCTL_STOP_PENDING));
task_clear_jobctl_pending(task, JOBCTL_STOP_PENDING);
if (!consume)
return false;
if (!WARN_ON_ONCE(sig->group_stop_count == 0))
sig->group_stop_count--;
/*
* Tell the caller to notify completion iff we are entering into a
* fresh group stop. Read comment in do_signal_stop() for details.
*/
if (!sig->group_stop_count && !(sig->flags & SIGNAL_STOP_STOPPED)) {
sig->flags = SIGNAL_STOP_STOPPED;
return true;
}
return false;
}
/*
* allocate a new signal queue record
* - this may be called without locks if and only if t == current, otherwise an
* appropriate lock must be held to stop the target task from exiting
*/
static struct sigqueue *
__sigqueue_alloc(int sig, struct task_struct *t, gfp_t flags, int override_rlimit)
{
struct sigqueue *q = NULL;
struct user_struct *user;
/*
* Protect access to @t credentials. This can go away when all
* callers hold rcu read lock.
*/
rcu_read_lock();
user = get_uid(__task_cred(t)->user);
atomic_inc(&user->sigpending);
rcu_read_unlock();
if (override_rlimit ||
atomic_read(&user->sigpending) <=
task_rlimit(t, RLIMIT_SIGPENDING)) {
q = kmem_cache_alloc(sigqueue_cachep, flags);
} else {
print_dropped_signal(sig);
}
if (unlikely(q == NULL)) {
atomic_dec(&user->sigpending);
free_uid(user);
} else {
INIT_LIST_HEAD(&q->list);
q->flags = 0;
q->user = user;
}
return q;
}
static void __sigqueue_free(struct sigqueue *q)
{
if (q->flags & SIGQUEUE_PREALLOC)
return;
atomic_dec(&q->user->sigpending);
free_uid(q->user);
kmem_cache_free(sigqueue_cachep, q);
}
void flush_sigqueue(struct sigpending *queue)
{
struct sigqueue *q;
sigemptyset(&queue->signal);
while (!list_empty(&queue->list)) {
q = list_entry(queue->list.next, struct sigqueue , list);
list_del_init(&q->list);
__sigqueue_free(q);
}
}
/*
* Flush all pending signals for this kthread.
*/
void flush_signals(struct task_struct *t)
{
unsigned long flags;
spin_lock_irqsave(&t->sighand->siglock, flags);
clear_tsk_thread_flag(t, TIF_SIGPENDING);
flush_sigqueue(&t->pending);
flush_sigqueue(&t->signal->shared_pending);
spin_unlock_irqrestore(&t->sighand->siglock, flags);
}
static void __flush_itimer_signals(struct sigpending *pending)
{
sigset_t signal, retain;
struct sigqueue *q, *n;
signal = pending->signal;
sigemptyset(&retain);
list_for_each_entry_safe(q, n, &pending->list, list) {
int sig = q->info.si_signo;
if (likely(q->info.si_code != SI_TIMER)) {
sigaddset(&retain, sig);
} else {
sigdelset(&signal, sig);
list_del_init(&q->list);
__sigqueue_free(q);
}
}
sigorsets(&pending->signal, &signal, &retain);
}
void flush_itimer_signals(void)
{
struct task_struct *tsk = current;
unsigned long flags;
spin_lock_irqsave(&tsk->sighand->siglock, flags);
__flush_itimer_signals(&tsk->pending);
__flush_itimer_signals(&tsk->signal->shared_pending);
spin_unlock_irqrestore(&tsk->sighand->siglock, flags);
}
void ignore_signals(struct task_struct *t)
{
int i;
for (i = 0; i < _NSIG; ++i)
t->sighand->action[i].sa.sa_handler = SIG_IGN;
flush_signals(t);
}
/*
* Flush all handlers for a task.
*/
void
flush_signal_handlers(struct task_struct *t, int force_default)
{
int i;
struct k_sigaction *ka = &t->sighand->action[0];
for (i = _NSIG ; i != 0 ; i--) {
if (force_default || ka->sa.sa_handler != SIG_IGN)
ka->sa.sa_handler = SIG_DFL;
ka->sa.sa_flags = 0;
#ifdef __ARCH_HAS_SA_RESTORER
ka->sa.sa_restorer = NULL;
#endif
sigemptyset(&ka->sa.sa_mask);
ka++;
}
}
int unhandled_signal(struct task_struct *tsk, int sig)
{
void __user *handler = tsk->sighand->action[sig-1].sa.sa_handler;
if (is_global_init(tsk))
return 1;
if (handler != SIG_IGN && handler != SIG_DFL)
return 0;
/* if ptraced, let the tracer determine */
return !tsk->ptrace;
}
static void collect_signal(int sig, struct sigpending *list, siginfo_t *info)
{
struct sigqueue *q, *first = NULL;
/*
* Collect the siginfo appropriate to this signal. Check if
* there is another siginfo for the same signal.
*/
list_for_each_entry(q, &list->list, list) {
if (q->info.si_signo == sig) {
if (first)
goto still_pending;
first = q;
}
}
sigdelset(&list->signal, sig);
if (first) {
still_pending:
list_del_init(&first->list);
copy_siginfo(info, &first->info);
__sigqueue_free(first);
} else {
/*
* Ok, it wasn't in the queue. This must be
* a fast-pathed signal or we must have been
* out of queue space. So zero out the info.
*/
info->si_signo = sig;
info->si_errno = 0;
info->si_code = SI_USER;
info->si_pid = 0;
info->si_uid = 0;
}
}
static int __dequeue_signal(struct sigpending *pending, sigset_t *mask,
siginfo_t *info)
{
int sig = next_signal(pending, mask);
if (sig)
collect_signal(sig, pending, info);
return sig;
}
/*
* Dequeue a signal and return the element to the caller, which is
* expected to free it.
*
* All callers have to hold the siglock.
*/
int dequeue_signal(struct task_struct *tsk, sigset_t *mask, siginfo_t *info)
{
int signr;
/* We only dequeue private signals from ourselves, we don't let
* signalfd steal them
*/
signr = __dequeue_signal(&tsk->pending, mask, info);
if (!signr) {
signr = __dequeue_signal(&tsk->signal->shared_pending,
mask, info);
/*
* itimer signal ?
*
* itimers are process shared and we restart periodic
* itimers in the signal delivery path to prevent DoS
* attacks in the high resolution timer case. This is
* compliant with the old way of self-restarting
* itimers, as the SIGALRM is a legacy signal and only
* queued once. Changing the restart behaviour to
* restart the timer in the signal dequeue path is
* reducing the timer noise on heavy loaded !highres
* systems too.
*/
if (unlikely(signr == SIGALRM)) {
struct hrtimer *tmr = &tsk->signal->real_timer;
if (!hrtimer_is_queued(tmr) &&
tsk->signal->it_real_incr.tv64 != 0) {
hrtimer_forward(tmr, tmr->base->get_time(),
tsk->signal->it_real_incr);
hrtimer_restart(tmr);
}
}
}
recalc_sigpending();
if (!signr)
return 0;
if (unlikely(sig_kernel_stop(signr))) {
/*
* Set a marker that we have dequeued a stop signal. Our
* caller might release the siglock and then the pending
* stop signal it is about to process is no longer in the
* pending bitmasks, but must still be cleared by a SIGCONT
* (and overruled by a SIGKILL). So those cases clear this
* shared flag after we've set it. Note that this flag may
* remain set after the signal we return is ignored or
* handled. That doesn't matter because its only purpose
* is to alert stop-signal processing code when another
* processor has come along and cleared the flag.
*/
current->jobctl |= JOBCTL_STOP_DEQUEUED;
}
if ((info->si_code & __SI_MASK) == __SI_TIMER && info->si_sys_private) {
/*
* Release the siglock to ensure proper locking order
* of timer locks outside of siglocks. Note, we leave
* irqs disabled here, since the posix-timers code is
* about to disable them again anyway.
*/
spin_unlock(&tsk->sighand->siglock);
do_schedule_next_timer(info);
spin_lock(&tsk->sighand->siglock);
}
return signr;
}
/*
* Tell a process that it has a new active signal..
*
* NOTE! we rely on the previous spin_lock to
* lock interrupts for us! We can only be called with
* "siglock" held, and the local interrupt must
* have been disabled when that got acquired!
*
* No need to set need_resched since signal event passing
* goes through ->blocked
*/
void signal_wake_up_state(struct task_struct *t, unsigned int state)
{
set_tsk_thread_flag(t, TIF_SIGPENDING);
/*
* TASK_WAKEKILL also means wake it up in the stopped/traced/killable
* case. We don't check t->state here because there is a race with it
* executing another processor and just now entering stopped state.
* By using wake_up_state, we ensure the process will wake up and
* handle its death signal.
*/
if (!wake_up_state(t, state | TASK_INTERRUPTIBLE))
kick_process(t);
}
/*
* Remove signals in mask from the pending set and queue.
* Returns 1 if any signals were found.
*
* All callers must be holding the siglock.
*/
static int flush_sigqueue_mask(sigset_t *mask, struct sigpending *s)
{
struct sigqueue *q, *n;
sigset_t m;
sigandsets(&m, mask, &s->signal);
if (sigisemptyset(&m))
return 0;
sigandnsets(&s->signal, &s->signal, mask);
list_for_each_entry_safe(q, n, &s->list, list) {
if (sigismember(mask, q->info.si_signo)) {
list_del_init(&q->list);
__sigqueue_free(q);
}
}
return 1;
}
static inline int is_si_special(const struct siginfo *info)
{
return info <= SEND_SIG_FORCED;
}
static inline bool si_fromuser(const struct siginfo *info)
{
return info == SEND_SIG_NOINFO ||
(!is_si_special(info) && SI_FROMUSER(info));
}
/*
* called with RCU read lock from check_kill_permission()
*/
static int kill_ok_by_cred(struct task_struct *t)
{
const struct cred *cred = current_cred();
const struct cred *tcred = __task_cred(t);
if (uid_eq(cred->euid, tcred->suid) ||
uid_eq(cred->euid, tcred->uid) ||
uid_eq(cred->uid, tcred->suid) ||
uid_eq(cred->uid, tcred->uid))
return 1;
if (ns_capable(tcred->user_ns, CAP_KILL))
return 1;
return 0;
}
/*
* Bad permissions for sending the signal
* - the caller must hold the RCU read lock
*/
static int check_kill_permission(int sig, struct siginfo *info,
struct task_struct *t)
{
struct pid *sid;
int error;
if (!valid_signal(sig))
return -EINVAL;
if (!si_fromuser(info))
return 0;
error = audit_signal_info(sig, t); /* Let audit system see the signal */
if (error)
return error;
if (!same_thread_group(current, t) &&
!kill_ok_by_cred(t)) {
switch (sig) {
case SIGCONT:
sid = task_session(t);
/*
* We don't return the error if sid == NULL. The
* task was unhashed, the caller must notice this.
*/
if (!sid || sid == task_session(current))
break;
default:
return -EPERM;
}
}
return security_task_kill(t, info, sig, 0);
}
/**
* ptrace_trap_notify - schedule trap to notify ptracer
* @t: tracee wanting to notify tracer
*
* This function schedules sticky ptrace trap which is cleared on the next
* TRAP_STOP to notify ptracer of an event. @t must have been seized by
* ptracer.
*
* If @t is running, STOP trap will be taken. If trapped for STOP and
* ptracer is listening for events, tracee is woken up so that it can
* re-trap for the new event. If trapped otherwise, STOP trap will be
* eventually taken without returning to userland after the existing traps
* are finished by PTRACE_CONT.
*
* CONTEXT:
* Must be called with @task->sighand->siglock held.
*/
static void ptrace_trap_notify(struct task_struct *t)
{
WARN_ON_ONCE(!(t->ptrace & PT_SEIZED));
assert_spin_locked(&t->sighand->siglock);
task_set_jobctl_pending(t, JOBCTL_TRAP_NOTIFY);
ptrace_signal_wake_up(t, t->jobctl & JOBCTL_LISTENING);
}
/*
* Handle magic process-wide effects of stop/continue signals. Unlike
* the signal actions, these happen immediately at signal-generation
* time regardless of blocking, ignoring, or handling. This does the
* actual continuing for SIGCONT, but not the actual stopping for stop
* signals. The process stop is done as a signal action for SIG_DFL.
*
* Returns true if the signal should be actually delivered, otherwise
* it should be dropped.
*/
static bool prepare_signal(int sig, struct task_struct *p, bool force)
{
struct signal_struct *signal = p->signal;
struct task_struct *t;
sigset_t flush;
if (signal->flags & (SIGNAL_GROUP_EXIT | SIGNAL_GROUP_COREDUMP)) {
if (!(signal->flags & SIGNAL_GROUP_EXIT))
return sig == SIGKILL;
/*
* The process is in the middle of dying, nothing to do.
*/
} else if (sig_kernel_stop(sig)) {
/*
* This is a stop signal. Remove SIGCONT from all queues.
*/
siginitset(&flush, sigmask(SIGCONT));
flush_sigqueue_mask(&flush, &signal->shared_pending);
for_each_thread(p, t)
flush_sigqueue_mask(&flush, &t->pending);
} else if (sig == SIGCONT) {
unsigned int why;
/*
* Remove all stop signals from all queues, wake all threads.
*/
siginitset(&flush, SIG_KERNEL_STOP_MASK);
flush_sigqueue_mask(&flush, &signal->shared_pending);
for_each_thread(p, t) {
flush_sigqueue_mask(&flush, &t->pending);
task_clear_jobctl_pending(t, JOBCTL_STOP_PENDING);
if (likely(!(t->ptrace & PT_SEIZED)))
wake_up_state(t, __TASK_STOPPED);
else
ptrace_trap_notify(t);
}
/*
* Notify the parent with CLD_CONTINUED if we were stopped.
*
* If we were in the middle of a group stop, we pretend it
* was already finished, and then continued. Since SIGCHLD
* doesn't queue we report only CLD_STOPPED, as if the next
* CLD_CONTINUED was dropped.
*/
why = 0;
if (signal->flags & SIGNAL_STOP_STOPPED)
why |= SIGNAL_CLD_CONTINUED;
else if (signal->group_stop_count)
why |= SIGNAL_CLD_STOPPED;
if (why) {
/*
* The first thread which returns from do_signal_stop()
* will take ->siglock, notice SIGNAL_CLD_MASK, and
* notify its parent. See get_signal_to_deliver().
*/
signal->flags = why | SIGNAL_STOP_CONTINUED;
signal->group_stop_count = 0;
signal->group_exit_code = 0;
}
}
return !sig_ignored(p, sig, force);
}
/*
* Test if P wants to take SIG. After we've checked all threads with this,
* it's equivalent to finding no threads not blocking SIG. Any threads not
* blocking SIG were ruled out because they are not running and already
* have pending signals. Such threads will dequeue from the shared queue
* as soon as they're available, so putting the signal on the shared queue
* will be equivalent to sending it to one such thread.
*/
static inline int wants_signal(int sig, struct task_struct *p)
{
if (sigismember(&p->blocked, sig))
return 0;
if (p->flags & PF_EXITING)
return 0;
if (sig == SIGKILL)
return 1;
if (task_is_stopped_or_traced(p))
return 0;
return task_curr(p) || !signal_pending(p);
}
static void complete_signal(int sig, struct task_struct *p, int group)
{
struct signal_struct *signal = p->signal;
struct task_struct *t;
/*
* Now find a thread we can wake up to take the signal off the queue.
*
* If the main thread wants the signal, it gets first crack.
* Probably the least surprising to the average bear.
*/
if (wants_signal(sig, p))
t = p;
else if (!group || thread_group_empty(p))
/*
* There is just one thread and it does not need to be woken.
* It will dequeue unblocked signals before it runs again.
*/
return;
else {
/*
* Otherwise try to find a suitable thread.
*/
t = signal->curr_target;
while (!wants_signal(sig, t)) {
t = next_thread(t);
if (t == signal->curr_target)
/*
* No thread needs to be woken.
* Any eligible threads will see
* the signal in the queue soon.
*/
return;
}
signal->curr_target = t;
}
/*
* Found a killable thread. If the signal will be fatal,
* then start taking the whole group down immediately.
*/
if (sig_fatal(p, sig) &&
!(signal->flags & (SIGNAL_UNKILLABLE | SIGNAL_GROUP_EXIT)) &&
!sigismember(&t->real_blocked, sig) &&
(sig == SIGKILL || !t->ptrace)) {
/*
* This signal will be fatal to the whole group.
*/
if (!sig_kernel_coredump(sig)) {
/*
* Start a group exit and wake everybody up.
* This way we don't have other threads
* running and doing things after a slower
* thread has the fatal signal pending.
*/
signal->flags = SIGNAL_GROUP_EXIT;
signal->group_exit_code = sig;
signal->group_stop_count = 0;
t = p;
do {
task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
sigaddset(&t->pending.signal, SIGKILL);
signal_wake_up(t, 1);
} while_each_thread(p, t);
return;
}
}
/*
* The signal is already in the shared-pending queue.
* Tell the chosen thread to wake up and dequeue it.
*/
signal_wake_up(t, sig == SIGKILL);
return;
}
static inline int legacy_queue(struct sigpending *signals, int sig)
{
return (sig < SIGRTMIN) && sigismember(&signals->signal, sig);
}
#ifdef CONFIG_USER_NS
static inline void userns_fixup_signal_uid(struct siginfo *info, struct task_struct *t)
{
if (current_user_ns() == task_cred_xxx(t, user_ns))
return;
if (SI_FROMKERNEL(info))
return;
rcu_read_lock();
info->si_uid = from_kuid_munged(task_cred_xxx(t, user_ns),
make_kuid(current_user_ns(), info->si_uid));
rcu_read_unlock();
}
#else
static inline void userns_fixup_signal_uid(struct siginfo *info, struct task_struct *t)
{
return;
}
#endif
static int __send_signal(int sig, struct siginfo *info, struct task_struct *t,
int group, int from_ancestor_ns)
{
struct sigpending *pending;
struct sigqueue *q;
int override_rlimit;
int ret = 0, result;
assert_spin_locked(&t->sighand->siglock);
result = TRACE_SIGNAL_IGNORED;
if (!prepare_signal(sig, t,
from_ancestor_ns || (info == SEND_SIG_FORCED)))
goto ret;
pending = group ? &t->signal->shared_pending : &t->pending;
/*
* Short-circuit ignored signals and support queuing
* exactly one non-rt signal, so that we can get more
* detailed information about the cause of the signal.
*/
result = TRACE_SIGNAL_ALREADY_PENDING;
if (legacy_queue(pending, sig))
goto ret;
result = TRACE_SIGNAL_DELIVERED;
/*
* fast-pathed signals for kernel-internal things like SIGSTOP
* or SIGKILL.
*/
if (info == SEND_SIG_FORCED)
goto out_set;
/*
* Real-time signals must be queued if sent by sigqueue, or
* some other real-time mechanism. It is implementation
* defined whether kill() does so. We attempt to do so, on
* the principle of least surprise, but since kill is not
* allowed to fail with EAGAIN when low on memory we just
* make sure at least one signal gets delivered and don't
* pass on the info struct.
*/
if (sig < SIGRTMIN)
override_rlimit = (is_si_special(info) || info->si_code >= 0);
else
override_rlimit = 0;
q = __sigqueue_alloc(sig, t, GFP_ATOMIC | __GFP_NOTRACK_FALSE_POSITIVE,
override_rlimit);
if (q) {
list_add_tail(&q->list, &pending->list);
switch ((unsigned long) info) {
case (unsigned long) SEND_SIG_NOINFO:
q->info.si_signo = sig;
q->info.si_errno = 0;
q->info.si_code = SI_USER;
q->info.si_pid = task_tgid_nr_ns(current,
task_active_pid_ns(t));
q->info.si_uid = from_kuid_munged(current_user_ns(), current_uid());
break;
case (unsigned long) SEND_SIG_PRIV:
q->info.si_signo = sig;
q->info.si_errno = 0;
q->info.si_code = SI_KERNEL;
q->info.si_pid = 0;
q->info.si_uid = 0;
break;
default:
copy_siginfo(&q->info, info);
if (from_ancestor_ns)
q->info.si_pid = 0;
break;
}
userns_fixup_signal_uid(&q->info, t);
} else if (!is_si_special(info)) {
if (sig >= SIGRTMIN && info->si_code != SI_USER) {
/*
* Queue overflow, abort. We may abort if the
* signal was rt and sent by user using something
* other than kill().
*/
result = TRACE_SIGNAL_OVERFLOW_FAIL;
ret = -EAGAIN;
goto ret;
} else {
/*
* This is a silent loss of information. We still
* send the signal, but the *info bits are lost.
*/
result = TRACE_SIGNAL_LOSE_INFO;
}
}
out_set:
signalfd_notify(t, sig);
sigaddset(&pending->signal, sig);
complete_signal(sig, t, group);
ret:
trace_signal_generate(sig, info, t, group, result);
return ret;
}
static int send_signal(int sig, struct siginfo *info, struct task_struct *t,
int group)
{
int from_ancestor_ns = 0;
#ifdef CONFIG_PID_NS
from_ancestor_ns = si_fromuser(info) &&
!task_pid_nr_ns(current, task_active_pid_ns(t));
#endif
return __send_signal(sig, info, t, group, from_ancestor_ns);
}
static void print_fatal_signal(int signr)
{
struct pt_regs *regs = signal_pt_regs();
pr_info("potentially unexpected fatal signal %d.\n", signr);
#if defined(__i386__) && !defined(__arch_um__)
pr_info("code at %08lx: ", regs->ip);
{
int i;
for (i = 0; i < 16; i++) {
unsigned char insn;
if (get_user(insn, (unsigned char *)(regs->ip + i)))
break;
pr_cont("%02x ", insn);
}
}
pr_cont("\n");
#endif
preempt_disable();
show_regs(regs);
preempt_enable();
}
static int __init setup_print_fatal_signals(char *str)
{
get_option (&str, &print_fatal_signals);
return 1;
}
__setup("print-fatal-signals=", setup_print_fatal_signals);
int
__group_send_sig_info(int sig, struct siginfo *info, struct task_struct *p)
{
return send_signal(sig, info, p, 1);
}
static int
specific_send_sig_info(int sig, struct siginfo *info, struct task_struct *t)
{
return send_signal(sig, info, t, 0);
}
int do_send_sig_info(int sig, struct siginfo *info, struct task_struct *p,
bool group)
{
unsigned long flags;
int ret = -ESRCH;
if (lock_task_sighand(p, &flags)) {
ret = send_signal(sig, info, p, group);
unlock_task_sighand(p, &flags);
}
return ret;
}
/*
* Force a signal that the process can't ignore: if necessary
* we unblock the signal and change any SIG_IGN to SIG_DFL.
*
* Note: If we unblock the signal, we always reset it to SIG_DFL,
* since we do not want to have a signal handler that was blocked
* be invoked when user space had explicitly blocked it.
*
* We don't want to have recursive SIGSEGV's etc, for example,
* that is why we also clear SIGNAL_UNKILLABLE.
*/
int
force_sig_info(int sig, struct siginfo *info, struct task_struct *t)
{
unsigned long int flags;
int ret, blocked, ignored;
struct k_sigaction *action;
spin_lock_irqsave(&t->sighand->siglock, flags);
action = &t->sighand->action[sig-1];
ignored = action->sa.sa_handler == SIG_IGN;
blocked = sigismember(&t->blocked, sig);
if (blocked || ignored) {
action->sa.sa_handler = SIG_DFL;
if (blocked) {
sigdelset(&t->blocked, sig);
recalc_sigpending_and_wake(t);
}
}
if (action->sa.sa_handler == SIG_DFL)
t->signal->flags &= ~SIGNAL_UNKILLABLE;
ret = specific_send_sig_info(sig, info, t);
spin_unlock_irqrestore(&t->sighand->siglock, flags);
return ret;
}
/*
* Nuke all other threads in the group.
*/
int zap_other_threads(struct task_struct *p)
{
struct task_struct *t = p;
int count = 0;
p->signal->group_stop_count = 0;
while_each_thread(p, t) {
task_clear_jobctl_pending(t, JOBCTL_PENDING_MASK);
count++;
/* Don't bother with already dead threads */
if (t->exit_state)
continue;
sigaddset(&t->pending.signal, SIGKILL);
signal_wake_up(t, 1);
}
return count;
}
struct sighand_struct *__lock_task_sighand(struct task_struct *tsk,
unsigned long *flags)
{
struct sighand_struct *sighand;
for (;;) {
/*
* Disable interrupts early to avoid deadlocks.
* See rcu_read_unlock() comment header for details.
*/
local_irq_save(*flags);
rcu_read_lock();
sighand = rcu_dereference(tsk->sighand);
if (unlikely(sighand == NULL)) {
rcu_read_unlock();
local_irq_restore(*flags);
break;
}
/*
* This sighand can be already freed and even reused, but
* we rely on SLAB_DESTROY_BY_RCU and sighand_ctor() which
* initializes ->siglock: this slab can't go away, it has
* the same object type, ->siglock can't be reinitialized.
*
* We need to ensure that tsk->sighand is still the same
* after we take the lock, we can race with de_thread() or
* __exit_signal(). In the latter case the next iteration
* must see ->sighand == NULL.
*/
spin_lock(&sighand->siglock);
if (likely(sighand == tsk->sighand)) {
rcu_read_unlock();
break;
}
spin_unlock(&sighand->siglock);
rcu_read_unlock();
local_irq_restore(*flags);
}
return sighand;
}
/*
* send signal info to all the members of a group
*/
int group_send_sig_info(int sig, struct siginfo *info, struct task_struct *p)
{
int ret;
rcu_read_lock();
ret = check_kill_permission(sig, info, p);
rcu_read_unlock();
if (!ret && sig)
ret = do_send_sig_info(sig, info, p, true);
return ret;
}
/*
* __kill_pgrp_info() sends a signal to a process group: this is what the tty
* control characters do (^C, ^Z etc)
* - the caller must hold at least a readlock on tasklist_lock
*/
int __kill_pgrp_info(int sig, struct siginfo *info, struct pid *pgrp)
{
struct task_struct *p = NULL;
int retval, success;
success = 0;
retval = -ESRCH;
do_each_pid_task(pgrp, PIDTYPE_PGID, p) {
int err = group_send_sig_info(sig, info, p);
success |= !err;
retval = err;
} while_each_pid_task(pgrp, PIDTYPE_PGID, p);
return success ? 0 : retval;
}
int kill_pid_info(int sig, struct siginfo *info, struct pid *pid)
{
int error = -ESRCH;
struct task_struct *p;
for (;;) {
rcu_read_lock();
p = pid_task(pid, PIDTYPE_PID);
if (p)
error = group_send_sig_info(sig, info, p);
rcu_read_unlock();
if (likely(!p || error != -ESRCH))
return error;
/*
* The task was unhashed in between, try again. If it
* is dead, pid_task() will return NULL, if we race with
* de_thread() it will find the new leader.
*/
}
}
int kill_proc_info(int sig, struct siginfo *info, pid_t pid)
{
int error;
rcu_read_lock();
error = kill_pid_info(sig, info, find_vpid(pid));
rcu_read_unlock();
return error;
}
static int kill_as_cred_perm(const struct cred *cred,
struct task_struct *target)
{
const struct cred *pcred = __task_cred(target);
if (!uid_eq(cred->euid, pcred->suid) && !uid_eq(cred->euid, pcred->uid) &&
!uid_eq(cred->uid, pcred->suid) && !uid_eq(cred->uid, pcred->uid))
return 0;
return 1;
}
/* like kill_pid_info(), but doesn't use uid/euid of "current" */
int kill_pid_info_as_cred(int sig, struct siginfo *info, struct pid *pid,
const struct cred *cred, u32 secid)
{
int ret = -EINVAL;
struct task_struct *p;
unsigned long flags;
if (!valid_signal(sig))
return ret;
rcu_read_lock();
p = pid_task(pid, PIDTYPE_PID);
if (!p) {
ret = -ESRCH;
goto out_unlock;
}
if (si_fromuser(info) && !kill_as_cred_perm(cred, p)) {
ret = -EPERM;
goto out_unlock;
}
ret = security_task_kill(p, info, sig, secid);
if (ret)
goto out_unlock;
if (sig) {
if (lock_task_sighand(p, &flags)) {
ret = __send_signal(sig, info, p, 1, 0);
unlock_task_sighand(p, &flags);
} else
ret = -ESRCH;
}
out_unlock:
rcu_read_unlock();
return ret;
}
EXPORT_SYMBOL_GPL(kill_pid_info_as_cred);
/*
* kill_something_info() interprets pid in interesting ways just like kill(2).
*
* POSIX specifies that kill(-1,sig) is unspecified, but what we have
* is probably wrong. Should make it like BSD or SYSV.
*/
static int kill_something_info(int sig, struct siginfo *info, pid_t pid)
{
int ret;
if (pid > 0) {
rcu_read_lock();
ret = kill_pid_info(sig, info, find_vpid(pid));
rcu_read_unlock();
return ret;
}
read_lock(&tasklist_lock);
if (pid != -1) {
ret = __kill_pgrp_info(sig, info,
pid ? find_vpid(-pid) : task_pgrp(current));
} else {
int retval = 0, count = 0;
struct task_struct * p;
for_each_process(p) {
if (task_pid_vnr(p) > 1 &&
!same_thread_group(p, current)) {
int err = group_send_sig_info(sig, info, p);
++count;
if (err != -EPERM)
retval = err;
}
}
ret = count ? retval : -ESRCH;
}
read_unlock(&tasklist_lock);
return ret;
}
/*
* These are for backward compatibility with the rest of the kernel source.
*/
int send_sig_info(int sig, struct siginfo *info, struct task_struct *p)
{
/*
* Make sure legacy kernel users don't send in bad values
* (normal paths check this in check_kill_permission).
*/
if (!valid_signal(sig))
return -EINVAL;
return do_send_sig_info(sig, info, p, false);
}
#define __si_special(priv) \
((priv) ? SEND_SIG_PRIV : SEND_SIG_NOINFO)
int
send_sig(int sig, struct task_struct *p, int priv)
{
return send_sig_info(sig, __si_special(priv), p);
}
void
force_sig(int sig, struct task_struct *p)
{
force_sig_info(sig, SEND_SIG_PRIV, p);
}
/*
* When things go south during signal handling, we
* will force a SIGSEGV. And if the signal that caused
* the problem was already a SIGSEGV, we'll want to
* make sure we don't even try to deliver the signal..
*/
int
force_sigsegv(int sig, struct task_struct *p)
{
if (sig == SIGSEGV) {
unsigned long flags;
spin_lock_irqsave(&p->sighand->siglock, flags);
p->sighand->action[sig - 1].sa.sa_handler = SIG_DFL;
spin_unlock_irqrestore(&p->sighand->siglock, flags);
}
force_sig(SIGSEGV, p);
return 0;
}
int kill_pgrp(struct pid *pid, int sig, int priv)
{
int ret;
read_lock(&tasklist_lock);
ret = __kill_pgrp_info(sig, __si_special(priv), pid);
read_unlock(&tasklist_lock);
return ret;
}
EXPORT_SYMBOL(kill_pgrp);
int kill_pid(struct pid *pid, int sig, int priv)
{
return kill_pid_info(sig, __si_special(priv), pid);
}
EXPORT_SYMBOL(kill_pid);
/*
* These functions support sending signals using preallocated sigqueue
* structures. This is needed "because realtime applications cannot
* afford to lose notifications of asynchronous events, like timer
* expirations or I/O completions". In the case of POSIX Timers
* we allocate the sigqueue structure from the timer_create. If this
* allocation fails we are able to report the failure to the application
* with an EAGAIN error.
*/
struct sigqueue *sigqueue_alloc(void)
{
struct sigqueue *q = __sigqueue_alloc(-1, current, GFP_KERNEL, 0);
if (q)
q->flags |= SIGQUEUE_PREALLOC;
return q;
}
void sigqueue_free(struct sigqueue *q)
{
unsigned long flags;
spinlock_t *lock = ¤t->sighand->siglock;
BUG_ON(!(q->flags & SIGQUEUE_PREALLOC));
/*
* We must hold ->siglock while testing q->list
* to serialize with collect_signal() or with
* __exit_signal()->flush_sigqueue().
*/
spin_lock_irqsave(lock, flags);
q->flags &= ~SIGQUEUE_PREALLOC;
/*
* If it is queued it will be freed when dequeued,
* like the "regular" sigqueue.
*/
if (!list_empty(&q->list))
q = NULL;
spin_unlock_irqrestore(lock, flags);
if (q)
__sigqueue_free(q);
}
int send_sigqueue(struct sigqueue *q, struct task_struct *t, int group)
{
int sig = q->info.si_signo;
struct sigpending *pending;
unsigned long flags;
int ret, result;
BUG_ON(!(q->flags & SIGQUEUE_PREALLOC));
ret = -1;
if (!likely(lock_task_sighand(t, &flags)))
goto ret;
ret = 1; /* the signal is ignored */
result = TRACE_SIGNAL_IGNORED;
if (!prepare_signal(sig, t, false))
goto out;
ret = 0;
if (unlikely(!list_empty(&q->list))) {
/*
* If an SI_TIMER entry is already queue just increment
* the overrun count.
*/
BUG_ON(q->info.si_code != SI_TIMER);
q->info.si_overrun++;
result = TRACE_SIGNAL_ALREADY_PENDING;
goto out;
}
q->info.si_overrun = 0;
signalfd_notify(t, sig);
pending = group ? &t->signal->shared_pending : &t->pending;
list_add_tail(&q->list, &pending->list);
sigaddset(&pending->signal, sig);
complete_signal(sig, t, group);
result = TRACE_SIGNAL_DELIVERED;
out:
trace_signal_generate(sig, &q->info, t, group, result);
unlock_task_sighand(t, &flags);
ret:
return ret;
}
/*
* Let a parent know about the death of a child.
* For a stopped/continued status change, use do_notify_parent_cldstop instead.
*
* Returns true if our parent ignored us and so we've switched to
* self-reaping.
*/
bool do_notify_parent(struct task_struct *tsk, int sig)
{
struct siginfo info;
unsigned long flags;
struct sighand_struct *psig;
bool autoreap = false;
cputime_t utime, stime;
BUG_ON(sig == -1);
/* do_notify_parent_cldstop should have been called instead. */
BUG_ON(task_is_stopped_or_traced(tsk));
BUG_ON(!tsk->ptrace &&
(tsk->group_leader != tsk || !thread_group_empty(tsk)));
if (sig != SIGCHLD) {
/*
* This is only possible if parent == real_parent.
* Check if it has changed security domain.
*/
if (tsk->parent_exec_id != tsk->parent->self_exec_id)
sig = SIGCHLD;
}
info.si_signo = sig;
info.si_errno = 0;
/*
* We are under tasklist_lock here so our parent is tied to
* us and cannot change.
*
* task_active_pid_ns will always return the same pid namespace
* until a task passes through release_task.
*
* write_lock() currently calls preempt_disable() which is the
* same as rcu_read_lock(), but according to Oleg, this is not
* correct to rely on this
*/
rcu_read_lock();
info.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(tsk->parent));
info.si_uid = from_kuid_munged(task_cred_xxx(tsk->parent, user_ns),
task_uid(tsk));
rcu_read_unlock();
task_cputime(tsk, &utime, &stime);
info.si_utime = cputime_to_clock_t(utime + tsk->signal->utime);
info.si_stime = cputime_to_clock_t(stime + tsk->signal->stime);
info.si_status = tsk->exit_code & 0x7f;
if (tsk->exit_code & 0x80)
info.si_code = CLD_DUMPED;
else if (tsk->exit_code & 0x7f)
info.si_code = CLD_KILLED;
else {
info.si_code = CLD_EXITED;
info.si_status = tsk->exit_code >> 8;
}
psig = tsk->parent->sighand;
spin_lock_irqsave(&psig->siglock, flags);
if (!tsk->ptrace && sig == SIGCHLD &&
(psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN ||
(psig->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDWAIT))) {
/*
* We are exiting and our parent doesn't care. POSIX.1
* defines special semantics for setting SIGCHLD to SIG_IGN
* or setting the SA_NOCLDWAIT flag: we should be reaped
* automatically and not left for our parent's wait4 call.
* Rather than having the parent do it as a magic kind of
* signal handler, we just set this to tell do_exit that we
* can be cleaned up without becoming a zombie. Note that
* we still call __wake_up_parent in this case, because a
* blocked sys_wait4 might now return -ECHILD.
*
* Whether we send SIGCHLD or not for SA_NOCLDWAIT
* is implementation-defined: we do (if you don't want
* it, just use SIG_IGN instead).
*/
autoreap = true;
if (psig->action[SIGCHLD-1].sa.sa_handler == SIG_IGN)
sig = 0;
}
if (valid_signal(sig) && sig)
__group_send_sig_info(sig, &info, tsk->parent);
__wake_up_parent(tsk, tsk->parent);
spin_unlock_irqrestore(&psig->siglock, flags);
return autoreap;
}
/**
* do_notify_parent_cldstop - notify parent of stopped/continued state change
* @tsk: task reporting the state change
* @for_ptracer: the notification is for ptracer
* @why: CLD_{CONTINUED|STOPPED|TRAPPED} to report
*
* Notify @tsk's parent that the stopped/continued state has changed. If
* @for_ptracer is %false, @tsk's group leader notifies to its real parent.
* If %true, @tsk reports to @tsk->parent which should be the ptracer.
*
* CONTEXT:
* Must be called with tasklist_lock at least read locked.
*/
static void do_notify_parent_cldstop(struct task_struct *tsk,
bool for_ptracer, int why)
{
struct siginfo info;
unsigned long flags;
struct task_struct *parent;
struct sighand_struct *sighand;
cputime_t utime, stime;
if (for_ptracer) {
parent = tsk->parent;
} else {
tsk = tsk->group_leader;
parent = tsk->real_parent;
}
info.si_signo = SIGCHLD;
info.si_errno = 0;
/*
* see comment in do_notify_parent() about the following 4 lines
*/
rcu_read_lock();
info.si_pid = task_pid_nr_ns(tsk, task_active_pid_ns(parent));
info.si_uid = from_kuid_munged(task_cred_xxx(parent, user_ns), task_uid(tsk));
rcu_read_unlock();
task_cputime(tsk, &utime, &stime);
info.si_utime = cputime_to_clock_t(utime);
info.si_stime = cputime_to_clock_t(stime);
info.si_code = why;
switch (why) {
case CLD_CONTINUED:
info.si_status = SIGCONT;
break;
case CLD_STOPPED:
info.si_status = tsk->signal->group_exit_code & 0x7f;
break;
case CLD_TRAPPED:
info.si_status = tsk->exit_code & 0x7f;
break;
default:
BUG();
}
sighand = parent->sighand;
spin_lock_irqsave(&sighand->siglock, flags);
if (sighand->action[SIGCHLD-1].sa.sa_handler != SIG_IGN &&
!(sighand->action[SIGCHLD-1].sa.sa_flags & SA_NOCLDSTOP))
__group_send_sig_info(SIGCHLD, &info, parent);
/*
* Even if SIGCHLD is not generated, we must wake up wait4 calls.
*/
__wake_up_parent(tsk, parent);
spin_unlock_irqrestore(&sighand->siglock, flags);
}
static inline int may_ptrace_stop(void)
{
if (!likely(current->ptrace))
return 0;
/*
* Are we in the middle of do_coredump?
* If so and our tracer is also part of the coredump stopping
* is a deadlock situation, and pointless because our tracer
* is dead so don't allow us to stop.
* If SIGKILL was already sent before the caller unlocked
* ->siglock we must see ->core_state != NULL. Otherwise it
* is safe to enter schedule().
*
* This is almost outdated, a task with the pending SIGKILL can't
* block in TASK_TRACED. But PTRACE_EVENT_EXIT can be reported
* after SIGKILL was already dequeued.
*/
if (unlikely(current->mm->core_state) &&
unlikely(current->mm == current->parent->mm))
return 0;
return 1;
}
/*
* Return non-zero if there is a SIGKILL that should be waking us up.
* Called with the siglock held.
*/
static int sigkill_pending(struct task_struct *tsk)
{
return sigismember(&tsk->pending.signal, SIGKILL) ||
sigismember(&tsk->signal->shared_pending.signal, SIGKILL);
}
/*
* This must be called with current->sighand->siglock held.
*
* This should be the path for all ptrace stops.
* We always set current->last_siginfo while stopped here.
* That makes it a way to test a stopped process for
* being ptrace-stopped vs being job-control-stopped.
*
* If we actually decide not to stop at all because the tracer
* is gone, we keep current->exit_code unless clear_code.
*/
static void ptrace_stop(int exit_code, int why, int clear_code, siginfo_t *info)
__releases(¤t->sighand->siglock)
__acquires(¤t->sighand->siglock)
{
bool gstop_done = false;
if (arch_ptrace_stop_needed(exit_code, info)) {
/*
* The arch code has something special to do before a
* ptrace stop. This is allowed to block, e.g. for faults
* on user stack pages. We can't keep the siglock while
* calling arch_ptrace_stop, so we must release it now.
* To preserve proper semantics, we must do this before
* any signal bookkeeping like checking group_stop_count.
* Meanwhile, a SIGKILL could come in before we retake the
* siglock. That must prevent us from sleeping in TASK_TRACED.
* So after regaining the lock, we must check for SIGKILL.
*/
spin_unlock_irq(¤t->sighand->siglock);
arch_ptrace_stop(exit_code, info);
spin_lock_irq(¤t->sighand->siglock);
if (sigkill_pending(current))
return;
}
/*
* We're committing to trapping. TRACED should be visible before
* TRAPPING is cleared; otherwise, the tracer might fail do_wait().
* Also, transition to TRACED and updates to ->jobctl should be
* atomic with respect to siglock and should be done after the arch
* hook as siglock is released and regrabbed across it.
*/
set_current_state(TASK_TRACED);
current->last_siginfo = info;
current->exit_code = exit_code;
/*
* If @why is CLD_STOPPED, we're trapping to participate in a group
* stop. Do the bookkeeping. Note that if SIGCONT was delievered
* across siglock relocks since INTERRUPT was scheduled, PENDING
* could be clear now. We act as if SIGCONT is received after
* TASK_TRACED is entered - ignore it.
*/
if (why == CLD_STOPPED && (current->jobctl & JOBCTL_STOP_PENDING))
gstop_done = task_participate_group_stop(current);
/* any trap clears pending STOP trap, STOP trap clears NOTIFY */
task_clear_jobctl_pending(current, JOBCTL_TRAP_STOP);
if (info && info->si_code >> 8 == PTRACE_EVENT_STOP)
task_clear_jobctl_pending(current, JOBCTL_TRAP_NOTIFY);
/* entering a trap, clear TRAPPING */
task_clear_jobctl_trapping(current);
spin_unlock_irq(¤t->sighand->siglock);
read_lock(&tasklist_lock);
if (may_ptrace_stop()) {
/*
* Notify parents of the stop.
*
* While ptraced, there are two parents - the ptracer and
* the real_parent of the group_leader. The ptracer should
* know about every stop while the real parent is only
* interested in the completion of group stop. The states
* for the two don't interact with each other. Notify
* separately unless they're gonna be duplicates.
*/
do_notify_parent_cldstop(current, true, why);
if (gstop_done && ptrace_reparented(current))
do_notify_parent_cldstop(current, false, why);
/*
* Don't want to allow preemption here, because
* sys_ptrace() needs this task to be inactive.
*
* XXX: implement read_unlock_no_resched().
*/
preempt_disable();
read_unlock(&tasklist_lock);
preempt_enable_no_resched();
freezable_schedule();
} else {
/*
* By the time we got the lock, our tracer went away.
* Don't drop the lock yet, another tracer may come.
*
* If @gstop_done, the ptracer went away between group stop
* completion and here. During detach, it would have set
* JOBCTL_STOP_PENDING on us and we'll re-enter
* TASK_STOPPED in do_signal_stop() on return, so notifying
* the real parent of the group stop completion is enough.
*/
if (gstop_done)
do_notify_parent_cldstop(current, false, why);
/* tasklist protects us from ptrace_freeze_traced() */
__set_current_state(TASK_RUNNING);
if (clear_code)
current->exit_code = 0;
read_unlock(&tasklist_lock);
}
/*
* We are back. Now reacquire the siglock before touching
* last_siginfo, so that we are sure to have synchronized with
* any signal-sending on another CPU that wants to examine it.
*/
spin_lock_irq(¤t->sighand->siglock);
current->last_siginfo = NULL;
/* LISTENING can be set only during STOP traps, clear it */
current->jobctl &= ~JOBCTL_LISTENING;
/*
* Queued signals ignored us while we were stopped for tracing.
* So check for any that we should take before resuming user mode.
* This sets TIF_SIGPENDING, but never clears it.
*/
recalc_sigpending_tsk(current);
}
static void ptrace_do_notify(int signr, int exit_code, int why)
{
siginfo_t info;
memset(&info, 0, sizeof info);
info.si_signo = signr;
info.si_code = exit_code;
info.si_pid = task_pid_vnr(current);
info.si_uid = from_kuid_munged(current_user_ns(), current_uid());
/* Let the debugger run. */
ptrace_stop(exit_code, why, 1, &info);
}
void ptrace_notify(int exit_code)
{
BUG_ON((exit_code & (0x7f | ~0xffff)) != SIGTRAP);
if (unlikely(current->task_works))
task_work_run();
spin_lock_irq(¤t->sighand->siglock);
ptrace_do_notify(SIGTRAP, exit_code, CLD_TRAPPED);
spin_unlock_irq(¤t->sighand->siglock);
}
/**
* do_signal_stop - handle group stop for SIGSTOP and other stop signals
* @signr: signr causing group stop if initiating
*
* If %JOBCTL_STOP_PENDING is not set yet, initiate group stop with @signr
* and participate in it. If already set, participate in the existing
* group stop. If participated in a group stop (and thus slept), %true is
* returned with siglock released.
*
* If ptraced, this function doesn't handle stop itself. Instead,
* %JOBCTL_TRAP_STOP is scheduled and %false is returned with siglock
* untouched. The caller must ensure that INTERRUPT trap handling takes
* places afterwards.
*
* CONTEXT:
* Must be called with @current->sighand->siglock held, which is released
* on %true return.
*
* RETURNS:
* %false if group stop is already cancelled or ptrace trap is scheduled.
* %true if participated in group stop.
*/
static bool do_signal_stop(int signr)
__releases(¤t->sighand->siglock)
{
struct signal_struct *sig = current->signal;
if (!(current->jobctl & JOBCTL_STOP_PENDING)) {
unsigned long gstop = JOBCTL_STOP_PENDING | JOBCTL_STOP_CONSUME;
struct task_struct *t;
/* signr will be recorded in task->jobctl for retries */
WARN_ON_ONCE(signr & ~JOBCTL_STOP_SIGMASK);
if (!likely(current->jobctl & JOBCTL_STOP_DEQUEUED) ||
unlikely(signal_group_exit(sig)))
return false;
/*
* There is no group stop already in progress. We must
* initiate one now.
*
* While ptraced, a task may be resumed while group stop is
* still in effect and then receive a stop signal and
* initiate another group stop. This deviates from the
* usual behavior as two consecutive stop signals can't
* cause two group stops when !ptraced. That is why we
* also check !task_is_stopped(t) below.
*
* The condition can be distinguished by testing whether
* SIGNAL_STOP_STOPPED is already set. Don't generate
* group_exit_code in such case.
*
* This is not necessary for SIGNAL_STOP_CONTINUED because
* an intervening stop signal is required to cause two
* continued events regardless of ptrace.
*/
if (!(sig->flags & SIGNAL_STOP_STOPPED))
sig->group_exit_code = signr;
sig->group_stop_count = 0;
if (task_set_jobctl_pending(current, signr | gstop))
sig->group_stop_count++;
t = current;
while_each_thread(current, t) {
/*
* Setting state to TASK_STOPPED for a group
* stop is always done with the siglock held,
* so this check has no races.
*/
if (!task_is_stopped(t) &&
task_set_jobctl_pending(t, signr | gstop)) {
sig->group_stop_count++;
if (likely(!(t->ptrace & PT_SEIZED)))
signal_wake_up(t, 0);
else
ptrace_trap_notify(t);
}
}
}
if (likely(!current->ptrace)) {
int notify = 0;
/*
* If there are no other threads in the group, or if there
* is a group stop in progress and we are the last to stop,
* report to the parent.
*/
if (task_participate_group_stop(current))
notify = CLD_STOPPED;
__set_current_state(TASK_STOPPED);
spin_unlock_irq(¤t->sighand->siglock);
/*
* Notify the parent of the group stop completion. Because
* we're not holding either the siglock or tasklist_lock
* here, ptracer may attach inbetween; however, this is for
* group stop and should always be delivered to the real
* parent of the group leader. The new ptracer will get
* its notification when this task transitions into
* TASK_TRACED.
*/
if (notify) {
read_lock(&tasklist_lock);
do_notify_parent_cldstop(current, false, notify);
read_unlock(&tasklist_lock);
}
/* Now we don't run again until woken by SIGCONT or SIGKILL */
freezable_schedule();
return true;
} else {
/*
* While ptraced, group stop is handled by STOP trap.
* Schedule it and let the caller deal with it.
*/
task_set_jobctl_pending(current, JOBCTL_TRAP_STOP);
return false;
}
}
/**
* do_jobctl_trap - take care of ptrace jobctl traps
*
* When PT_SEIZED, it's used for both group stop and explicit
* SEIZE/INTERRUPT traps. Both generate PTRACE_EVENT_STOP trap with
* accompanying siginfo. If stopped, lower eight bits of exit_code contain
* the stop signal; otherwise, %SIGTRAP.
*
* When !PT_SEIZED, it's used only for group stop trap with stop signal
* number as exit_code and no siginfo.
*
* CONTEXT:
* Must be called with @current->sighand->siglock held, which may be
* released and re-acquired before returning with intervening sleep.
*/
static void do_jobctl_trap(void)
{
struct signal_struct *signal = current->signal;
int signr = current->jobctl & JOBCTL_STOP_SIGMASK;
if (current->ptrace & PT_SEIZED) {
if (!signal->group_stop_count &&
!(signal->flags & SIGNAL_STOP_STOPPED))
signr = SIGTRAP;
WARN_ON_ONCE(!signr);
ptrace_do_notify(signr, signr | (PTRACE_EVENT_STOP << 8),
CLD_STOPPED);
} else {
WARN_ON_ONCE(!signr);
ptrace_stop(signr, CLD_STOPPED, 0, NULL);
current->exit_code = 0;
}
}
static int ptrace_signal(int signr, siginfo_t *info)
{
ptrace_signal_deliver();
/*
* We do not check sig_kernel_stop(signr) but set this marker
* unconditionally because we do not know whether debugger will
* change signr. This flag has no meaning unless we are going
* to stop after return from ptrace_stop(). In this case it will
* be checked in do_signal_stop(), we should only stop if it was
* not cleared by SIGCONT while we were sleeping. See also the
* comment in dequeue_signal().
*/
current->jobctl |= JOBCTL_STOP_DEQUEUED;
ptrace_stop(signr, CLD_TRAPPED, 0, info);
/* We're back. Did the debugger cancel the sig? */
signr = current->exit_code;
if (signr == 0)
return signr;
current->exit_code = 0;
/*
* Update the siginfo structure if the signal has
* changed. If the debugger wanted something
* specific in the siginfo structure then it should
* have updated *info via PTRACE_SETSIGINFO.
*/
if (signr != info->si_signo) {
info->si_signo = signr;
info->si_errno = 0;
info->si_code = SI_USER;
rcu_read_lock();
info->si_pid = task_pid_vnr(current->parent);
info->si_uid = from_kuid_munged(current_user_ns(),
task_uid(current->parent));
rcu_read_unlock();
}
/* If the (new) signal is now blocked, requeue it. */
if (sigismember(¤t->blocked, signr)) {
specific_send_sig_info(signr, info, current);
signr = 0;
}
return signr;
}
int get_signal(struct ksignal *ksig)
{
struct sighand_struct *sighand = current->sighand;
struct signal_struct *signal = current->signal;
int signr;
if (unlikely(current->task_works))
task_work_run();
if (unlikely(uprobe_deny_signal()))
return 0;
/*
* Do this once, we can't return to user-mode if freezing() == T.
* do_signal_stop() and ptrace_stop() do freezable_schedule() and
* thus do not need another check after return.
*/
try_to_freeze();
relock:
spin_lock_irq(&sighand->siglock);
/*
* Every stopped thread goes here after wakeup. Check to see if
* we should notify the parent, prepare_signal(SIGCONT) encodes
* the CLD_ si_code into SIGNAL_CLD_MASK bits.
*/
if (unlikely(signal->flags & SIGNAL_CLD_MASK)) {
int why;
if (signal->flags & SIGNAL_CLD_CONTINUED)
why = CLD_CONTINUED;
else
why = CLD_STOPPED;
signal->flags &= ~SIGNAL_CLD_MASK;
spin_unlock_irq(&sighand->siglock);
/*
* Notify the parent that we're continuing. This event is
* always per-process and doesn't make whole lot of sense
* for ptracers, who shouldn't consume the state via
* wait(2) either, but, for backward compatibility, notify
* the ptracer of the group leader too unless it's gonna be
* a duplicate.
*/
read_lock(&tasklist_lock);
do_notify_parent_cldstop(current, false, why);
if (ptrace_reparented(current->group_leader))
do_notify_parent_cldstop(current->group_leader,
true, why);
read_unlock(&tasklist_lock);
goto relock;
}
for (;;) {
struct k_sigaction *ka;
if (unlikely(current->jobctl & JOBCTL_STOP_PENDING) &&
do_signal_stop(0))
goto relock;
if (unlikely(current->jobctl & JOBCTL_TRAP_MASK)) {
do_jobctl_trap();
spin_unlock_irq(&sighand->siglock);
goto relock;
}
signr = dequeue_signal(current, ¤t->blocked, &ksig->info);
if (!signr)
break; /* will return 0 */
if (unlikely(current->ptrace) && signr != SIGKILL) {
signr = ptrace_signal(signr, &ksig->info);
if (!signr)
continue;
}
ka = &sighand->action[signr-1];
/* Trace actually delivered signals. */
trace_signal_deliver(signr, &ksig->info, ka);
if (ka->sa.sa_handler == SIG_IGN) /* Do nothing. */
continue;
if (ka->sa.sa_handler != SIG_DFL) {
/* Run the handler. */
ksig->ka = *ka;
if (ka->sa.sa_flags & SA_ONESHOT)
ka->sa.sa_handler = SIG_DFL;
break; /* will return non-zero "signr" value */
}
/*
* Now we are doing the default action for this signal.
*/
if (sig_kernel_ignore(signr)) /* Default is nothing. */
continue;
/*
* Global init gets no signals it doesn't want.
* Container-init gets no signals it doesn't want from same
* container.
*
* Note that if global/container-init sees a sig_kernel_only()
* signal here, the signal must have been generated internally
* or must have come from an ancestor namespace. In either
* case, the signal cannot be dropped.
*/
if (unlikely(signal->flags & SIGNAL_UNKILLABLE) &&
!sig_kernel_only(signr))
continue;
if (sig_kernel_stop(signr)) {
/*
* The default action is to stop all threads in
* the thread group. The job control signals
* do nothing in an orphaned pgrp, but SIGSTOP
* always works. Note that siglock needs to be
* dropped during the call to is_orphaned_pgrp()
* because of lock ordering with tasklist_lock.
* This allows an intervening SIGCONT to be posted.
* We need to check for that and bail out if necessary.
*/
if (signr != SIGSTOP) {
spin_unlock_irq(&sighand->siglock);
/* signals can be posted during this window */
if (is_current_pgrp_orphaned())
goto relock;
spin_lock_irq(&sighand->siglock);
}
if (likely(do_signal_stop(ksig->info.si_signo))) {
/* It released the siglock. */
goto relock;
}
/*
* We didn't actually stop, due to a race
* with SIGCONT or something like that.
*/
continue;
}
spin_unlock_irq(&sighand->siglock);
/*
* Anything else is fatal, maybe with a core dump.
*/
current->flags |= PF_SIGNALED;
if (sig_kernel_coredump(signr)) {
if (print_fatal_signals)
print_fatal_signal(ksig->info.si_signo);
proc_coredump_connector(current);
/*
* If it was able to dump core, this kills all
* other threads in the group and synchronizes with
* their demise. If we lost the race with another
* thread getting here, it set group_exit_code
* first and our do_group_exit call below will use
* that value and ignore the one we pass it.
*/
do_coredump(&ksig->info);
}
/*
* Death signals, no core dump.
*/
do_group_exit(ksig->info.si_signo);
/* NOTREACHED */
}
spin_unlock_irq(&sighand->siglock);
ksig->sig = signr;
return ksig->sig > 0;
}
/**
* signal_delivered -
* @ksig: kernel signal struct
* @stepping: nonzero if debugger single-step or block-step in use
*
* This function should be called when a signal has successfully been
* delivered. It updates the blocked signals accordingly (@ksig->ka.sa.sa_mask
* is always blocked, and the signal itself is blocked unless %SA_NODEFER
* is set in @ksig->ka.sa.sa_flags. Tracing is notified.
*/
static void signal_delivered(struct ksignal *ksig, int stepping)
{
sigset_t blocked;
/* A signal was successfully delivered, and the
saved sigmask was stored on the signal frame,
and will be restored by sigreturn. So we can
simply clear the restore sigmask flag. */
clear_restore_sigmask();
sigorsets(&blocked, ¤t->blocked, &ksig->ka.sa.sa_mask);
if (!(ksig->ka.sa.sa_flags & SA_NODEFER))
sigaddset(&blocked, ksig->sig);
set_current_blocked(&blocked);
tracehook_signal_handler(stepping);
}
void signal_setup_done(int failed, struct ksignal *ksig, int stepping)
{
if (failed)
force_sigsegv(ksig->sig, current);
else
signal_delivered(ksig, stepping);
}
/*
* It could be that complete_signal() picked us to notify about the
* group-wide signal. Other threads should be notified now to take
* the shared signals in @which since we will not.
*/
static void retarget_shared_pending(struct task_struct *tsk, sigset_t *which)
{
sigset_t retarget;
struct task_struct *t;
sigandsets(&retarget, &tsk->signal->shared_pending.signal, which);
if (sigisemptyset(&retarget))
return;
t = tsk;
while_each_thread(tsk, t) {
if (t->flags & PF_EXITING)
continue;
if (!has_pending_signals(&retarget, &t->blocked))
continue;
/* Remove the signals this thread can handle. */
sigandsets(&retarget, &retarget, &t->blocked);
if (!signal_pending(t))
signal_wake_up(t, 0);
if (sigisemptyset(&retarget))
break;
}
}
void exit_signals(struct task_struct *tsk)
{
int group_stop = 0;
sigset_t unblocked;
/*
* @tsk is about to have PF_EXITING set - lock out users which
* expect stable threadgroup.
*/
threadgroup_change_begin(tsk);
if (thread_group_empty(tsk) || signal_group_exit(tsk->signal)) {
tsk->flags |= PF_EXITING;
threadgroup_change_end(tsk);
return;
}
spin_lock_irq(&tsk->sighand->siglock);
/*
* From now this task is not visible for group-wide signals,
* see wants_signal(), do_signal_stop().
*/
tsk->flags |= PF_EXITING;
threadgroup_change_end(tsk);
if (!signal_pending(tsk))
goto out;
unblocked = tsk->blocked;
signotset(&unblocked);
retarget_shared_pending(tsk, &unblocked);
if (unlikely(tsk->jobctl & JOBCTL_STOP_PENDING) &&
task_participate_group_stop(tsk))
group_stop = CLD_STOPPED;
out:
spin_unlock_irq(&tsk->sighand->siglock);
/*
* If group stop has completed, deliver the notification. This
* should always go to the real parent of the group leader.
*/
if (unlikely(group_stop)) {
read_lock(&tasklist_lock);
do_notify_parent_cldstop(tsk, false, group_stop);
read_unlock(&tasklist_lock);
}
}
EXPORT_SYMBOL(recalc_sigpending);
EXPORT_SYMBOL_GPL(dequeue_signal);
EXPORT_SYMBOL(flush_signals);
EXPORT_SYMBOL(force_sig);
EXPORT_SYMBOL(send_sig);
EXPORT_SYMBOL(send_sig_info);
EXPORT_SYMBOL(sigprocmask);
/*
* System call entry points.
*/
/**
* sys_restart_syscall - restart a system call
*/
SYSCALL_DEFINE0(restart_syscall)
{
struct restart_block *restart = ¤t->restart_block;
return restart->fn(restart);
}
long do_no_restart_syscall(struct restart_block *param)
{
return -EINTR;
}
static void __set_task_blocked(struct task_struct *tsk, const sigset_t *newset)
{
if (signal_pending(tsk) && !thread_group_empty(tsk)) {
sigset_t newblocked;
/* A set of now blocked but previously unblocked signals. */
sigandnsets(&newblocked, newset, ¤t->blocked);
retarget_shared_pending(tsk, &newblocked);
}
tsk->blocked = *newset;
recalc_sigpending();
}
/**
* set_current_blocked - change current->blocked mask
* @newset: new mask
*
* It is wrong to change ->blocked directly, this helper should be used
* to ensure the process can't miss a shared signal we are going to block.
*/
void set_current_blocked(sigset_t *newset)
{
sigdelsetmask(newset, sigmask(SIGKILL) | sigmask(SIGSTOP));
__set_current_blocked(newset);
}
void __set_current_blocked(const sigset_t *newset)
{
struct task_struct *tsk = current;
spin_lock_irq(&tsk->sighand->siglock);
__set_task_blocked(tsk, newset);
spin_unlock_irq(&tsk->sighand->siglock);
}
/*
* This is also useful for kernel threads that want to temporarily
* (or permanently) block certain signals.
*
* NOTE! Unlike the user-mode sys_sigprocmask(), the kernel
* interface happily blocks "unblockable" signals like SIGKILL
* and friends.
*/
int sigprocmask(int how, sigset_t *set, sigset_t *oldset)
{
struct task_struct *tsk = current;
sigset_t newset;
/* Lockless, only current can change ->blocked, never from irq */
if (oldset)
*oldset = tsk->blocked;
switch (how) {
case SIG_BLOCK:
sigorsets(&newset, &tsk->blocked, set);
break;
case SIG_UNBLOCK:
sigandnsets(&newset, &tsk->blocked, set);
break;
case SIG_SETMASK:
newset = *set;
break;
default:
return -EINVAL;
}
__set_current_blocked(&newset);
return 0;
}
/**
* sys_rt_sigprocmask - change the list of currently blocked signals
* @how: whether to add, remove, or set signals
* @nset: stores pending signals
* @oset: previous value of signal mask if non-null
* @sigsetsize: size of sigset_t type
*/
SYSCALL_DEFINE4(rt_sigprocmask, int, how, sigset_t __user *, nset,
sigset_t __user *, oset, size_t, sigsetsize)
{
sigset_t old_set, new_set;
int error;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
old_set = current->blocked;
if (nset) {
if (copy_from_user(&new_set, nset, sizeof(sigset_t)))
return -EFAULT;
sigdelsetmask(&new_set, sigmask(SIGKILL)|sigmask(SIGSTOP));
error = sigprocmask(how, &new_set, NULL);
if (error)
return error;
}
if (oset) {
if (copy_to_user(oset, &old_set, sizeof(sigset_t)))
return -EFAULT;
}
return 0;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(rt_sigprocmask, int, how, compat_sigset_t __user *, nset,
compat_sigset_t __user *, oset, compat_size_t, sigsetsize)
{
#ifdef __BIG_ENDIAN
sigset_t old_set = current->blocked;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (nset) {
compat_sigset_t new32;
sigset_t new_set;
int error;
if (copy_from_user(&new32, nset, sizeof(compat_sigset_t)))
return -EFAULT;
sigset_from_compat(&new_set, &new32);
sigdelsetmask(&new_set, sigmask(SIGKILL)|sigmask(SIGSTOP));
error = sigprocmask(how, &new_set, NULL);
if (error)
return error;
}
if (oset) {
compat_sigset_t old32;
sigset_to_compat(&old32, &old_set);
if (copy_to_user(oset, &old32, sizeof(compat_sigset_t)))
return -EFAULT;
}
return 0;
#else
return sys_rt_sigprocmask(how, (sigset_t __user *)nset,
(sigset_t __user *)oset, sigsetsize);
#endif
}
#endif
static int do_sigpending(void *set, unsigned long sigsetsize)
{
if (sigsetsize > sizeof(sigset_t))
return -EINVAL;
spin_lock_irq(¤t->sighand->siglock);
sigorsets(set, ¤t->pending.signal,
¤t->signal->shared_pending.signal);
spin_unlock_irq(¤t->sighand->siglock);
/* Outside the lock because only this thread touches it. */
sigandsets(set, ¤t->blocked, set);
return 0;
}
/**
* sys_rt_sigpending - examine a pending signal that has been raised
* while blocked
* @uset: stores pending signals
* @sigsetsize: size of sigset_t type or larger
*/
SYSCALL_DEFINE2(rt_sigpending, sigset_t __user *, uset, size_t, sigsetsize)
{
sigset_t set;
int err = do_sigpending(&set, sigsetsize);
if (!err && copy_to_user(uset, &set, sigsetsize))
err = -EFAULT;
return err;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(rt_sigpending, compat_sigset_t __user *, uset,
compat_size_t, sigsetsize)
{
#ifdef __BIG_ENDIAN
sigset_t set;
int err = do_sigpending(&set, sigsetsize);
if (!err) {
compat_sigset_t set32;
sigset_to_compat(&set32, &set);
/* we can get here only if sigsetsize <= sizeof(set) */
if (copy_to_user(uset, &set32, sigsetsize))
err = -EFAULT;
}
return err;
#else
return sys_rt_sigpending((sigset_t __user *)uset, sigsetsize);
#endif
}
#endif
#ifndef HAVE_ARCH_COPY_SIGINFO_TO_USER
int copy_siginfo_to_user(siginfo_t __user *to, const siginfo_t *from)
{
int err;
if (!access_ok (VERIFY_WRITE, to, sizeof(siginfo_t)))
return -EFAULT;
if (from->si_code < 0)
return __copy_to_user(to, from, sizeof(siginfo_t))
? -EFAULT : 0;
/*
* If you change siginfo_t structure, please be sure
* this code is fixed accordingly.
* Please remember to update the signalfd_copyinfo() function
* inside fs/signalfd.c too, in case siginfo_t changes.
* It should never copy any pad contained in the structure
* to avoid security leaks, but must copy the generic
* 3 ints plus the relevant union member.
*/
err = __put_user(from->si_signo, &to->si_signo);
err |= __put_user(from->si_errno, &to->si_errno);
err |= __put_user((short)from->si_code, &to->si_code);
switch (from->si_code & __SI_MASK) {
case __SI_KILL:
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
break;
case __SI_TIMER:
err |= __put_user(from->si_tid, &to->si_tid);
err |= __put_user(from->si_overrun, &to->si_overrun);
err |= __put_user(from->si_ptr, &to->si_ptr);
break;
case __SI_POLL:
err |= __put_user(from->si_band, &to->si_band);
err |= __put_user(from->si_fd, &to->si_fd);
break;
case __SI_FAULT:
err |= __put_user(from->si_addr, &to->si_addr);
#ifdef __ARCH_SI_TRAPNO
err |= __put_user(from->si_trapno, &to->si_trapno);
#endif
#ifdef BUS_MCEERR_AO
/*
* Other callers might not initialize the si_lsb field,
* so check explicitly for the right codes here.
*/
if (from->si_signo == SIGBUS &&
(from->si_code == BUS_MCEERR_AR || from->si_code == BUS_MCEERR_AO))
err |= __put_user(from->si_addr_lsb, &to->si_addr_lsb);
#endif
#ifdef SEGV_BNDERR
if (from->si_signo == SIGSEGV && from->si_code == SEGV_BNDERR) {
err |= __put_user(from->si_lower, &to->si_lower);
err |= __put_user(from->si_upper, &to->si_upper);
}
#endif
#ifdef SEGV_PKUERR
if (from->si_signo == SIGSEGV && from->si_code == SEGV_PKUERR)
err |= __put_user(from->si_pkey, &to->si_pkey);
#endif
break;
case __SI_CHLD:
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
err |= __put_user(from->si_status, &to->si_status);
err |= __put_user(from->si_utime, &to->si_utime);
err |= __put_user(from->si_stime, &to->si_stime);
break;
case __SI_RT: /* This is not generated by the kernel as of now. */
case __SI_MESGQ: /* But this is */
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
err |= __put_user(from->si_ptr, &to->si_ptr);
break;
#ifdef __ARCH_SIGSYS
case __SI_SYS:
err |= __put_user(from->si_call_addr, &to->si_call_addr);
err |= __put_user(from->si_syscall, &to->si_syscall);
err |= __put_user(from->si_arch, &to->si_arch);
break;
#endif
default: /* this is just in case for now ... */
err |= __put_user(from->si_pid, &to->si_pid);
err |= __put_user(from->si_uid, &to->si_uid);
break;
}
return err;
}
#endif
/**
* do_sigtimedwait - wait for queued signals specified in @which
* @which: queued signals to wait for
* @info: if non-null, the signal's siginfo is returned here
* @ts: upper bound on process time suspension
*/
int do_sigtimedwait(const sigset_t *which, siginfo_t *info,
const struct timespec *ts)
{
struct task_struct *tsk = current;
long timeout = MAX_SCHEDULE_TIMEOUT;
sigset_t mask = *which;
int sig;
if (ts) {
if (!timespec_valid(ts))
return -EINVAL;
timeout = timespec_to_jiffies(ts);
/*
* We can be close to the next tick, add another one
* to ensure we will wait at least the time asked for.
*/
if (ts->tv_sec || ts->tv_nsec)
timeout++;
}
/*
* Invert the set of allowed signals to get those we want to block.
*/
sigdelsetmask(&mask, sigmask(SIGKILL) | sigmask(SIGSTOP));
signotset(&mask);
spin_lock_irq(&tsk->sighand->siglock);
sig = dequeue_signal(tsk, &mask, info);
if (!sig && timeout) {
/*
* None ready, temporarily unblock those we're interested
* while we are sleeping in so that we'll be awakened when
* they arrive. Unblocking is always fine, we can avoid
* set_current_blocked().
*/
tsk->real_blocked = tsk->blocked;
sigandsets(&tsk->blocked, &tsk->blocked, &mask);
recalc_sigpending();
spin_unlock_irq(&tsk->sighand->siglock);
timeout = freezable_schedule_timeout_interruptible(timeout);
spin_lock_irq(&tsk->sighand->siglock);
__set_task_blocked(tsk, &tsk->real_blocked);
sigemptyset(&tsk->real_blocked);
sig = dequeue_signal(tsk, &mask, info);
}
spin_unlock_irq(&tsk->sighand->siglock);
if (sig)
return sig;
return timeout ? -EINTR : -EAGAIN;
}
/**
* sys_rt_sigtimedwait - synchronously wait for queued signals specified
* in @uthese
* @uthese: queued signals to wait for
* @uinfo: if non-null, the signal's siginfo is returned here
* @uts: upper bound on process time suspension
* @sigsetsize: size of sigset_t type
*/
SYSCALL_DEFINE4(rt_sigtimedwait, const sigset_t __user *, uthese,
siginfo_t __user *, uinfo, const struct timespec __user *, uts,
size_t, sigsetsize)
{
sigset_t these;
struct timespec ts;
siginfo_t info;
int ret;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (copy_from_user(&these, uthese, sizeof(these)))
return -EFAULT;
if (uts) {
if (copy_from_user(&ts, uts, sizeof(ts)))
return -EFAULT;
}
ret = do_sigtimedwait(&these, &info, uts ? &ts : NULL);
if (ret > 0 && uinfo) {
if (copy_siginfo_to_user(uinfo, &info))
ret = -EFAULT;
}
return ret;
}
/**
* sys_kill - send a signal to a process
* @pid: the PID of the process
* @sig: signal to be sent
*/
SYSCALL_DEFINE2(kill, pid_t, pid, int, sig)
{
struct siginfo info;
info.si_signo = sig;
info.si_errno = 0;
info.si_code = SI_USER;
info.si_pid = task_tgid_vnr(current);
info.si_uid = from_kuid_munged(current_user_ns(), current_uid());
return kill_something_info(sig, &info, pid);
}
static int
do_send_specific(pid_t tgid, pid_t pid, int sig, struct siginfo *info)
{
struct task_struct *p;
int error = -ESRCH;
rcu_read_lock();
p = find_task_by_vpid(pid);
if (p && (tgid <= 0 || task_tgid_vnr(p) == tgid)) {
error = check_kill_permission(sig, info, p);
/*
* The null signal is a permissions and process existence
* probe. No signal is actually delivered.
*/
if (!error && sig) {
error = do_send_sig_info(sig, info, p, false);
/*
* If lock_task_sighand() failed we pretend the task
* dies after receiving the signal. The window is tiny,
* and the signal is private anyway.
*/
if (unlikely(error == -ESRCH))
error = 0;
}
}
rcu_read_unlock();
return error;
}
static int do_tkill(pid_t tgid, pid_t pid, int sig)
{
struct siginfo info = {};
info.si_signo = sig;
info.si_errno = 0;
info.si_code = SI_TKILL;
info.si_pid = task_tgid_vnr(current);
info.si_uid = from_kuid_munged(current_user_ns(), current_uid());
return do_send_specific(tgid, pid, sig, &info);
}
/**
* sys_tgkill - send signal to one specific thread
* @tgid: the thread group ID of the thread
* @pid: the PID of the thread
* @sig: signal to be sent
*
* This syscall also checks the @tgid and returns -ESRCH even if the PID
* exists but it's not belonging to the target process anymore. This
* method solves the problem of threads exiting and PIDs getting reused.
*/
SYSCALL_DEFINE3(tgkill, pid_t, tgid, pid_t, pid, int, sig)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
return do_tkill(tgid, pid, sig);
}
/**
* sys_tkill - send signal to one specific task
* @pid: the PID of the task
* @sig: signal to be sent
*
* Send a signal to only one task, even if it's a CLONE_THREAD task.
*/
SYSCALL_DEFINE2(tkill, pid_t, pid, int, sig)
{
/* This is only valid for single tasks */
if (pid <= 0)
return -EINVAL;
return do_tkill(0, pid, sig);
}
static int do_rt_sigqueueinfo(pid_t pid, int sig, siginfo_t *info)
{
/* Not even root can pretend to send signals from the kernel.
* Nor can they impersonate a kill()/tgkill(), which adds source info.
*/
if ((info->si_code >= 0 || info->si_code == SI_TKILL) &&
(task_pid_vnr(current) != pid))
return -EPERM;
info->si_signo = sig;
/* POSIX.1b doesn't mention process groups. */
return kill_proc_info(sig, info, pid);
}
/**
* sys_rt_sigqueueinfo - send signal information to a signal
* @pid: the PID of the thread
* @sig: signal to be sent
* @uinfo: signal info to be sent
*/
SYSCALL_DEFINE3(rt_sigqueueinfo, pid_t, pid, int, sig,
siginfo_t __user *, uinfo)
{
siginfo_t info;
if (copy_from_user(&info, uinfo, sizeof(siginfo_t)))
return -EFAULT;
return do_rt_sigqueueinfo(pid, sig, &info);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE3(rt_sigqueueinfo,
compat_pid_t, pid,
int, sig,
struct compat_siginfo __user *, uinfo)
{
siginfo_t info = {};
int ret = copy_siginfo_from_user32(&info, uinfo);
if (unlikely(ret))
return ret;
return do_rt_sigqueueinfo(pid, sig, &info);
}
#endif
static int do_rt_tgsigqueueinfo(pid_t tgid, pid_t pid, int sig, siginfo_t *info)
{
/* This is only valid for single tasks */
if (pid <= 0 || tgid <= 0)
return -EINVAL;
/* Not even root can pretend to send signals from the kernel.
* Nor can they impersonate a kill()/tgkill(), which adds source info.
*/
if ((info->si_code >= 0 || info->si_code == SI_TKILL) &&
(task_pid_vnr(current) != pid))
return -EPERM;
info->si_signo = sig;
return do_send_specific(tgid, pid, sig, info);
}
SYSCALL_DEFINE4(rt_tgsigqueueinfo, pid_t, tgid, pid_t, pid, int, sig,
siginfo_t __user *, uinfo)
{
siginfo_t info;
if (copy_from_user(&info, uinfo, sizeof(siginfo_t)))
return -EFAULT;
return do_rt_tgsigqueueinfo(tgid, pid, sig, &info);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(rt_tgsigqueueinfo,
compat_pid_t, tgid,
compat_pid_t, pid,
int, sig,
struct compat_siginfo __user *, uinfo)
{
siginfo_t info = {};
if (copy_siginfo_from_user32(&info, uinfo))
return -EFAULT;
return do_rt_tgsigqueueinfo(tgid, pid, sig, &info);
}
#endif
/*
* For kthreads only, must not be used if cloned with CLONE_SIGHAND
*/
void kernel_sigaction(int sig, __sighandler_t action)
{
spin_lock_irq(¤t->sighand->siglock);
current->sighand->action[sig - 1].sa.sa_handler = action;
if (action == SIG_IGN) {
sigset_t mask;
sigemptyset(&mask);
sigaddset(&mask, sig);
flush_sigqueue_mask(&mask, ¤t->signal->shared_pending);
flush_sigqueue_mask(&mask, ¤t->pending);
recalc_sigpending();
}
spin_unlock_irq(¤t->sighand->siglock);
}
EXPORT_SYMBOL(kernel_sigaction);
int do_sigaction(int sig, struct k_sigaction *act, struct k_sigaction *oact)
{
struct task_struct *p = current, *t;
struct k_sigaction *k;
sigset_t mask;
if (!valid_signal(sig) || sig < 1 || (act && sig_kernel_only(sig)))
return -EINVAL;
k = &p->sighand->action[sig-1];
spin_lock_irq(&p->sighand->siglock);
if (oact)
*oact = *k;
if (act) {
sigdelsetmask(&act->sa.sa_mask,
sigmask(SIGKILL) | sigmask(SIGSTOP));
*k = *act;
/*
* POSIX 3.3.1.3:
* "Setting a signal action to SIG_IGN for a signal that is
* pending shall cause the pending signal to be discarded,
* whether or not it is blocked."
*
* "Setting a signal action to SIG_DFL for a signal that is
* pending and whose default action is to ignore the signal
* (for example, SIGCHLD), shall cause the pending signal to
* be discarded, whether or not it is blocked"
*/
if (sig_handler_ignored(sig_handler(p, sig), sig)) {
sigemptyset(&mask);
sigaddset(&mask, sig);
flush_sigqueue_mask(&mask, &p->signal->shared_pending);
for_each_thread(p, t)
flush_sigqueue_mask(&mask, &t->pending);
}
}
spin_unlock_irq(&p->sighand->siglock);
return 0;
}
static int
do_sigaltstack (const stack_t __user *uss, stack_t __user *uoss, unsigned long sp)
{
stack_t oss;
int error;
oss.ss_sp = (void __user *) current->sas_ss_sp;
oss.ss_size = current->sas_ss_size;
oss.ss_flags = sas_ss_flags(sp) |
(current->sas_ss_flags & SS_FLAG_BITS);
if (uss) {
void __user *ss_sp;
size_t ss_size;
unsigned ss_flags;
int ss_mode;
error = -EFAULT;
if (!access_ok(VERIFY_READ, uss, sizeof(*uss)))
goto out;
error = __get_user(ss_sp, &uss->ss_sp) |
__get_user(ss_flags, &uss->ss_flags) |
__get_user(ss_size, &uss->ss_size);
if (error)
goto out;
error = -EPERM;
if (on_sig_stack(sp))
goto out;
ss_mode = ss_flags & ~SS_FLAG_BITS;
error = -EINVAL;
if (ss_mode != SS_DISABLE && ss_mode != SS_ONSTACK &&
ss_mode != 0)
goto out;
if (ss_mode == SS_DISABLE) {
ss_size = 0;
ss_sp = NULL;
} else {
error = -ENOMEM;
if (ss_size < MINSIGSTKSZ)
goto out;
}
current->sas_ss_sp = (unsigned long) ss_sp;
current->sas_ss_size = ss_size;
current->sas_ss_flags = ss_flags;
}
error = 0;
if (uoss) {
error = -EFAULT;
if (!access_ok(VERIFY_WRITE, uoss, sizeof(*uoss)))
goto out;
error = __put_user(oss.ss_sp, &uoss->ss_sp) |
__put_user(oss.ss_size, &uoss->ss_size) |
__put_user(oss.ss_flags, &uoss->ss_flags);
}
out:
return error;
}
SYSCALL_DEFINE2(sigaltstack,const stack_t __user *,uss, stack_t __user *,uoss)
{
return do_sigaltstack(uss, uoss, current_user_stack_pointer());
}
int restore_altstack(const stack_t __user *uss)
{
int err = do_sigaltstack(uss, NULL, current_user_stack_pointer());
/* squash all but EFAULT for now */
return err == -EFAULT ? err : 0;
}
int __save_altstack(stack_t __user *uss, unsigned long sp)
{
struct task_struct *t = current;
int err = __put_user((void __user *)t->sas_ss_sp, &uss->ss_sp) |
__put_user(t->sas_ss_flags, &uss->ss_flags) |
__put_user(t->sas_ss_size, &uss->ss_size);
if (err)
return err;
if (t->sas_ss_flags & SS_AUTODISARM)
sas_ss_reset(t);
return 0;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(sigaltstack,
const compat_stack_t __user *, uss_ptr,
compat_stack_t __user *, uoss_ptr)
{
stack_t uss, uoss;
int ret;
mm_segment_t seg;
if (uss_ptr) {
compat_stack_t uss32;
memset(&uss, 0, sizeof(stack_t));
if (copy_from_user(&uss32, uss_ptr, sizeof(compat_stack_t)))
return -EFAULT;
uss.ss_sp = compat_ptr(uss32.ss_sp);
uss.ss_flags = uss32.ss_flags;
uss.ss_size = uss32.ss_size;
}
seg = get_fs();
set_fs(KERNEL_DS);
ret = do_sigaltstack((stack_t __force __user *) (uss_ptr ? &uss : NULL),
(stack_t __force __user *) &uoss,
compat_user_stack_pointer());
set_fs(seg);
if (ret >= 0 && uoss_ptr) {
if (!access_ok(VERIFY_WRITE, uoss_ptr, sizeof(compat_stack_t)) ||
__put_user(ptr_to_compat(uoss.ss_sp), &uoss_ptr->ss_sp) ||
__put_user(uoss.ss_flags, &uoss_ptr->ss_flags) ||
__put_user(uoss.ss_size, &uoss_ptr->ss_size))
ret = -EFAULT;
}
return ret;
}
int compat_restore_altstack(const compat_stack_t __user *uss)
{
int err = compat_sys_sigaltstack(uss, NULL);
/* squash all but -EFAULT for now */
return err == -EFAULT ? err : 0;
}
int __compat_save_altstack(compat_stack_t __user *uss, unsigned long sp)
{
struct task_struct *t = current;
return __put_user(ptr_to_compat((void __user *)t->sas_ss_sp), &uss->ss_sp) |
__put_user(sas_ss_flags(sp), &uss->ss_flags) |
__put_user(t->sas_ss_size, &uss->ss_size);
}
#endif
#ifdef __ARCH_WANT_SYS_SIGPENDING
/**
* sys_sigpending - examine pending signals
* @set: where mask of pending signal is returned
*/
SYSCALL_DEFINE1(sigpending, old_sigset_t __user *, set)
{
return sys_rt_sigpending((sigset_t __user *)set, sizeof(old_sigset_t));
}
#endif
#ifdef __ARCH_WANT_SYS_SIGPROCMASK
/**
* sys_sigprocmask - examine and change blocked signals
* @how: whether to add, remove, or set signals
* @nset: signals to add or remove (if non-null)
* @oset: previous value of signal mask if non-null
*
* Some platforms have their own version with special arguments;
* others support only sys_rt_sigprocmask.
*/
SYSCALL_DEFINE3(sigprocmask, int, how, old_sigset_t __user *, nset,
old_sigset_t __user *, oset)
{
old_sigset_t old_set, new_set;
sigset_t new_blocked;
old_set = current->blocked.sig[0];
if (nset) {
if (copy_from_user(&new_set, nset, sizeof(*nset)))
return -EFAULT;
new_blocked = current->blocked;
switch (how) {
case SIG_BLOCK:
sigaddsetmask(&new_blocked, new_set);
break;
case SIG_UNBLOCK:
sigdelsetmask(&new_blocked, new_set);
break;
case SIG_SETMASK:
new_blocked.sig[0] = new_set;
break;
default:
return -EINVAL;
}
set_current_blocked(&new_blocked);
}
if (oset) {
if (copy_to_user(oset, &old_set, sizeof(*oset)))
return -EFAULT;
}
return 0;
}
#endif /* __ARCH_WANT_SYS_SIGPROCMASK */
#ifndef CONFIG_ODD_RT_SIGACTION
/**
* sys_rt_sigaction - alter an action taken by a process
* @sig: signal to be sent
* @act: new sigaction
* @oact: used to save the previous sigaction
* @sigsetsize: size of sigset_t type
*/
SYSCALL_DEFINE4(rt_sigaction, int, sig,
const struct sigaction __user *, act,
struct sigaction __user *, oact,
size_t, sigsetsize)
{
struct k_sigaction new_sa, old_sa;
int ret = -EINVAL;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
goto out;
if (act) {
if (copy_from_user(&new_sa.sa, act, sizeof(new_sa.sa)))
return -EFAULT;
}
ret = do_sigaction(sig, act ? &new_sa : NULL, oact ? &old_sa : NULL);
if (!ret && oact) {
if (copy_to_user(oact, &old_sa.sa, sizeof(old_sa.sa)))
return -EFAULT;
}
out:
return ret;
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE4(rt_sigaction, int, sig,
const struct compat_sigaction __user *, act,
struct compat_sigaction __user *, oact,
compat_size_t, sigsetsize)
{
struct k_sigaction new_ka, old_ka;
compat_sigset_t mask;
#ifdef __ARCH_HAS_SA_RESTORER
compat_uptr_t restorer;
#endif
int ret;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(compat_sigset_t))
return -EINVAL;
if (act) {
compat_uptr_t handler;
ret = get_user(handler, &act->sa_handler);
new_ka.sa.sa_handler = compat_ptr(handler);
#ifdef __ARCH_HAS_SA_RESTORER
ret |= get_user(restorer, &act->sa_restorer);
new_ka.sa.sa_restorer = compat_ptr(restorer);
#endif
ret |= copy_from_user(&mask, &act->sa_mask, sizeof(mask));
ret |= get_user(new_ka.sa.sa_flags, &act->sa_flags);
if (ret)
return -EFAULT;
sigset_from_compat(&new_ka.sa.sa_mask, &mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
sigset_to_compat(&mask, &old_ka.sa.sa_mask);
ret = put_user(ptr_to_compat(old_ka.sa.sa_handler),
&oact->sa_handler);
ret |= copy_to_user(&oact->sa_mask, &mask, sizeof(mask));
ret |= put_user(old_ka.sa.sa_flags, &oact->sa_flags);
#ifdef __ARCH_HAS_SA_RESTORER
ret |= put_user(ptr_to_compat(old_ka.sa.sa_restorer),
&oact->sa_restorer);
#endif
}
return ret;
}
#endif
#endif /* !CONFIG_ODD_RT_SIGACTION */
#ifdef CONFIG_OLD_SIGACTION
SYSCALL_DEFINE3(sigaction, int, sig,
const struct old_sigaction __user *, act,
struct old_sigaction __user *, oact)
{
struct k_sigaction new_ka, old_ka;
int ret;
if (act) {
old_sigset_t mask;
if (!access_ok(VERIFY_READ, act, sizeof(*act)) ||
__get_user(new_ka.sa.sa_handler, &act->sa_handler) ||
__get_user(new_ka.sa.sa_restorer, &act->sa_restorer) ||
__get_user(new_ka.sa.sa_flags, &act->sa_flags) ||
__get_user(mask, &act->sa_mask))
return -EFAULT;
#ifdef __ARCH_HAS_KA_RESTORER
new_ka.ka_restorer = NULL;
#endif
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)) ||
__put_user(old_ka.sa.sa_handler, &oact->sa_handler) ||
__put_user(old_ka.sa.sa_restorer, &oact->sa_restorer) ||
__put_user(old_ka.sa.sa_flags, &oact->sa_flags) ||
__put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask))
return -EFAULT;
}
return ret;
}
#endif
#ifdef CONFIG_COMPAT_OLD_SIGACTION
COMPAT_SYSCALL_DEFINE3(sigaction, int, sig,
const struct compat_old_sigaction __user *, act,
struct compat_old_sigaction __user *, oact)
{
struct k_sigaction new_ka, old_ka;
int ret;
compat_old_sigset_t mask;
compat_uptr_t handler, restorer;
if (act) {
if (!access_ok(VERIFY_READ, act, sizeof(*act)) ||
__get_user(handler, &act->sa_handler) ||
__get_user(restorer, &act->sa_restorer) ||
__get_user(new_ka.sa.sa_flags, &act->sa_flags) ||
__get_user(mask, &act->sa_mask))
return -EFAULT;
#ifdef __ARCH_HAS_KA_RESTORER
new_ka.ka_restorer = NULL;
#endif
new_ka.sa.sa_handler = compat_ptr(handler);
new_ka.sa.sa_restorer = compat_ptr(restorer);
siginitset(&new_ka.sa.sa_mask, mask);
}
ret = do_sigaction(sig, act ? &new_ka : NULL, oact ? &old_ka : NULL);
if (!ret && oact) {
if (!access_ok(VERIFY_WRITE, oact, sizeof(*oact)) ||
__put_user(ptr_to_compat(old_ka.sa.sa_handler),
&oact->sa_handler) ||
__put_user(ptr_to_compat(old_ka.sa.sa_restorer),
&oact->sa_restorer) ||
__put_user(old_ka.sa.sa_flags, &oact->sa_flags) ||
__put_user(old_ka.sa.sa_mask.sig[0], &oact->sa_mask))
return -EFAULT;
}
return ret;
}
#endif
#ifdef CONFIG_SGETMASK_SYSCALL
/*
* For backwards compatibility. Functionality superseded by sigprocmask.
*/
SYSCALL_DEFINE0(sgetmask)
{
/* SMP safe */
return current->blocked.sig[0];
}
SYSCALL_DEFINE1(ssetmask, int, newmask)
{
int old = current->blocked.sig[0];
sigset_t newset;
siginitset(&newset, newmask);
set_current_blocked(&newset);
return old;
}
#endif /* CONFIG_SGETMASK_SYSCALL */
#ifdef __ARCH_WANT_SYS_SIGNAL
/*
* For backwards compatibility. Functionality superseded by sigaction.
*/
SYSCALL_DEFINE2(signal, int, sig, __sighandler_t, handler)
{
struct k_sigaction new_sa, old_sa;
int ret;
new_sa.sa.sa_handler = handler;
new_sa.sa.sa_flags = SA_ONESHOT | SA_NOMASK;
sigemptyset(&new_sa.sa.sa_mask);
ret = do_sigaction(sig, &new_sa, &old_sa);
return ret ? ret : (unsigned long)old_sa.sa.sa_handler;
}
#endif /* __ARCH_WANT_SYS_SIGNAL */
#ifdef __ARCH_WANT_SYS_PAUSE
SYSCALL_DEFINE0(pause)
{
while (!signal_pending(current)) {
__set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
return -ERESTARTNOHAND;
}
#endif
static int sigsuspend(sigset_t *set)
{
current->saved_sigmask = current->blocked;
set_current_blocked(set);
while (!signal_pending(current)) {
__set_current_state(TASK_INTERRUPTIBLE);
schedule();
}
set_restore_sigmask();
return -ERESTARTNOHAND;
}
/**
* sys_rt_sigsuspend - replace the signal mask for a value with the
* @unewset value until a signal is received
* @unewset: new signal mask value
* @sigsetsize: size of sigset_t type
*/
SYSCALL_DEFINE2(rt_sigsuspend, sigset_t __user *, unewset, size_t, sigsetsize)
{
sigset_t newset;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (copy_from_user(&newset, unewset, sizeof(newset)))
return -EFAULT;
return sigsuspend(&newset);
}
#ifdef CONFIG_COMPAT
COMPAT_SYSCALL_DEFINE2(rt_sigsuspend, compat_sigset_t __user *, unewset, compat_size_t, sigsetsize)
{
#ifdef __BIG_ENDIAN
sigset_t newset;
compat_sigset_t newset32;
/* XXX: Don't preclude handling different sized sigset_t's. */
if (sigsetsize != sizeof(sigset_t))
return -EINVAL;
if (copy_from_user(&newset32, unewset, sizeof(compat_sigset_t)))
return -EFAULT;
sigset_from_compat(&newset, &newset32);
return sigsuspend(&newset);
#else
/* on little-endian bitmaps don't care about granularity */
return sys_rt_sigsuspend((sigset_t __user *)unewset, sigsetsize);
#endif
}
#endif
#ifdef CONFIG_OLD_SIGSUSPEND
SYSCALL_DEFINE1(sigsuspend, old_sigset_t, mask)
{
sigset_t blocked;
siginitset(&blocked, mask);
return sigsuspend(&blocked);
}
#endif
#ifdef CONFIG_OLD_SIGSUSPEND3
SYSCALL_DEFINE3(sigsuspend, int, unused1, int, unused2, old_sigset_t, mask)
{
sigset_t blocked;
siginitset(&blocked, mask);
return sigsuspend(&blocked);
}
#endif
__weak const char *arch_vma_name(struct vm_area_struct *vma)
{
return NULL;
}
void __init signals_init(void)
{
/* If this check fails, the __ARCH_SI_PREAMBLE_SIZE value is wrong! */
BUILD_BUG_ON(__ARCH_SI_PREAMBLE_SIZE
!= offsetof(struct siginfo, _sifields._pad));
sigqueue_cachep = KMEM_CACHE(sigqueue, SLAB_PANIC);
}
#ifdef CONFIG_KGDB_KDB
#include <linux/kdb.h>
/*
* kdb_send_sig_info - Allows kdb to send signals without exposing
* signal internals. This function checks if the required locks are
* available before calling the main signal code, to avoid kdb
* deadlocks.
*/
void
kdb_send_sig_info(struct task_struct *t, struct siginfo *info)
{
static struct task_struct *kdb_prev_t;
int sig, new_t;
if (!spin_trylock(&t->sighand->siglock)) {
kdb_printf("Can't do kill command now.\n"
"The sigmask lock is held somewhere else in "
"kernel, try again later\n");
return;
}
spin_unlock(&t->sighand->siglock);
new_t = kdb_prev_t != t;
kdb_prev_t = t;
if (t->state != TASK_RUNNING && new_t) {
kdb_printf("Process is not RUNNING, sending a signal from "
"kdb risks deadlock\n"
"on the run queue locks. "
"The signal has _not_ been sent.\n"
"Reissue the kill command if you want to risk "
"the deadlock.\n");
return;
}
sig = info->si_signo;
if (send_sig_info(sig, info, t))
kdb_printf("Fail to deliver Signal %d to process %d.\n",
sig, t->pid);
else
kdb_printf("Signal %d is sent to process %d.\n", sig, t->pid);
}
#endif /* CONFIG_KGDB_KDB */
| gpl-3.0 |
Cellrox/android_external_bash | examples/loadables/finfo.c | 47 | 11627 | /*
* finfo - print file info
*
* Chet Ramey
* chet@po.cwru.edu
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <sys/types.h>
#include "posixstat.h"
#include <stdio.h>
#include <pwd.h>
#include <grp.h>
#include <errno.h>
#include "posixtime.h"
#include "bashansi.h"
#include "shell.h"
#include "builtins.h"
#include "common.h"
#ifndef errno
extern int errno;
#endif
extern char **make_builtin_argv ();
static int printst();
static int printsome();
static int printfinfo();
static int finfo_main();
extern int sh_optind;
extern char *sh_optarg;
extern char *this_command_name;
static char *prog;
static int pmask;
#define OPT_UID 0x00001
#define OPT_GID 0x00002
#define OPT_DEV 0x00004
#define OPT_INO 0x00008
#define OPT_PERM 0x00010
#define OPT_LNKNAM 0x00020
#define OPT_FID 0x00040
#define OPT_NLINK 0x00080
#define OPT_RDEV 0x00100
#define OPT_SIZE 0x00200
#define OPT_ATIME 0x00400
#define OPT_MTIME 0x00800
#define OPT_CTIME 0x01000
#define OPT_BLKSIZE 0x02000
#define OPT_BLKS 0x04000
#define OPT_FTYPE 0x08000
#define OPT_PMASK 0x10000
#define OPT_OPERM 0x20000
#define OPT_ASCII 0x1000000
#define OPTIONS "acdgiflmnopsuACGMP:U"
static int
octal(s)
char *s;
{
int r;
r = *s - '0';
while (*++s >= '0' && *s <= '7')
r = (r * 8) + (*s - '0');
return r;
}
static int
finfo_main(argc, argv)
int argc;
char **argv;
{
register int i;
int mode, flags, opt;
sh_optind = 0; /* XXX */
prog = base_pathname(argv[0]);
if (argc == 1) {
builtin_usage();
return(1);
}
flags = 0;
while ((opt = sh_getopt(argc, argv, OPTIONS)) != EOF) {
switch(opt) {
case 'a': flags |= OPT_ATIME; break;
case 'A': flags |= OPT_ATIME|OPT_ASCII; break;
case 'c': flags |= OPT_CTIME; break;
case 'C': flags |= OPT_CTIME|OPT_ASCII; break;
case 'd': flags |= OPT_DEV; break;
case 'i': flags |= OPT_INO; break;
case 'f': flags |= OPT_FID; break;
case 'g': flags |= OPT_GID; break;
case 'G': flags |= OPT_GID|OPT_ASCII; break;
case 'l': flags |= OPT_LNKNAM; break;
case 'm': flags |= OPT_MTIME; break;
case 'M': flags |= OPT_MTIME|OPT_ASCII; break;
case 'n': flags |= OPT_NLINK; break;
case 'o': flags |= OPT_OPERM; break;
case 'p': flags |= OPT_PERM; break;
case 'P': flags |= OPT_PMASK; pmask = octal(sh_optarg); break;
case 's': flags |= OPT_SIZE; break;
case 'u': flags |= OPT_UID; break;
case 'U': flags |= OPT_UID|OPT_ASCII; break;
default: builtin_usage (); return(1);
}
}
argc -= sh_optind;
argv += sh_optind;
if (argc == 0) {
builtin_usage();
return(1);
}
for (i = 0; i < argc; i++)
opt = flags ? printsome (argv[i], flags) : printfinfo(argv[i]);
return(opt);
}
static struct stat *
getstat(f)
char *f;
{
static struct stat st;
int fd, r;
intmax_t lfd;
if (strncmp(f, "/dev/fd/", 8) == 0) {
if ((legal_number(f + 8, &lfd) == 0) || (int)lfd != lfd) {
builtin_error("%s: invalid fd", f + 8);
return ((struct stat *)0);
}
fd = lfd;
r = fstat(fd, &st);
} else
#ifdef HAVE_LSTAT
r = lstat(f, &st);
#else
r = stat(f, &st);
#endif
if (r < 0) {
builtin_error("%s: cannot stat: %s", f, strerror(errno));
return ((struct stat *)0);
}
return (&st);
}
static int
printfinfo(f)
char *f;
{
struct stat *st;
st = getstat(f);
return (st ? printst(st) : 1);
}
static int
getperm(m)
int m;
{
return (m & (S_IRWXU|S_IRWXG|S_IRWXO|S_ISUID|S_ISGID));
}
static int
perms(m)
int m;
{
char ubits[4], gbits[4], obits[4]; /* u=rwx,g=rwx,o=rwx */
int i;
i = 0;
if (m & S_IRUSR)
ubits[i++] = 'r';
if (m & S_IWUSR)
ubits[i++] = 'w';
if (m & S_IXUSR)
ubits[i++] = 'x';
ubits[i] = '\0';
i = 0;
if (m & S_IRGRP)
gbits[i++] = 'r';
if (m & S_IWGRP)
gbits[i++] = 'w';
if (m & S_IXGRP)
gbits[i++] = 'x';
gbits[i] = '\0';
i = 0;
if (m & S_IROTH)
obits[i++] = 'r';
if (m & S_IWOTH)
obits[i++] = 'w';
if (m & S_IXOTH)
obits[i++] = 'x';
obits[i] = '\0';
if (m & S_ISUID)
ubits[2] = (m & S_IXUSR) ? 's' : 'S';
if (m & S_ISGID)
gbits[2] = (m & S_IXGRP) ? 's' : 'S';
if (m & S_ISVTX)
obits[2] = (m & S_IXOTH) ? 't' : 'T';
printf ("u=%s,g=%s,o=%s", ubits, gbits, obits);
}
static int
printmode(mode)
int mode;
{
if (S_ISBLK(mode))
printf("S_IFBLK ");
if (S_ISCHR(mode))
printf("S_IFCHR ");
if (S_ISDIR(mode))
printf("S_IFDIR ");
if (S_ISREG(mode))
printf("S_IFREG ");
if (S_ISFIFO(mode))
printf("S_IFIFO ");
if (S_ISLNK(mode))
printf("S_IFLNK ");
if (S_ISSOCK(mode))
printf("S_IFSOCK ");
#ifdef S_ISWHT
if (S_ISWHT(mode))
printf("S_ISWHT ");
#endif
perms(getperm(mode));
printf("\n");
}
static int
printst(st)
struct stat *st;
{
struct passwd *pw;
struct group *gr;
char *owner;
int ma, mi, d;
ma = major (st->st_rdev);
mi = minor (st->st_rdev);
#if defined (makedev)
d = makedev (ma, mi);
#else
d = st->st_rdev & 0xFF;
#endif
printf("Device (major/minor): %d (%d/%d)\n", d, ma, mi);
printf("Inode: %d\n", (int) st->st_ino);
printf("Mode: (%o) ", (int) st->st_mode);
printmode((int) st->st_mode);
printf("Link count: %d\n", (int) st->st_nlink);
pw = getpwuid(st->st_uid);
owner = pw ? pw->pw_name : "unknown";
printf("Uid of owner: %d (%s)\n", (int) st->st_uid, owner);
gr = getgrgid(st->st_gid);
owner = gr ? gr->gr_name : "unknown";
printf("Gid of owner: %d (%s)\n", (int) st->st_gid, owner);
printf("Device type: %d\n", (int) st->st_rdev);
printf("File size: %ld\n", (long) st->st_size);
printf("File last access time: %s", ctime (&st->st_atime));
printf("File last modify time: %s", ctime (&st->st_mtime));
printf("File last status change time: %s", ctime (&st->st_ctime));
fflush(stdout);
return(0);
}
static int
printsome(f, flags)
char *f;
int flags;
{
struct stat *st;
struct passwd *pw;
struct group *gr;
int p;
char *b;
st = getstat(f);
if (st == NULL)
return (1);
/* Print requested info */
if (flags & OPT_ATIME) {
if (flags & OPT_ASCII)
printf("%s", ctime(&st->st_atime));
else
printf("%ld\n", st->st_atime);
} else if (flags & OPT_MTIME) {
if (flags & OPT_ASCII)
printf("%s", ctime(&st->st_mtime));
else
printf("%ld\n", st->st_mtime);
} else if (flags & OPT_CTIME) {
if (flags & OPT_ASCII)
printf("%s", ctime(&st->st_ctime));
else
printf("%ld\n", st->st_ctime);
} else if (flags & OPT_DEV)
printf("%d\n", st->st_dev);
else if (flags & OPT_INO)
printf("%d\n", st->st_ino);
else if (flags & OPT_FID)
printf("%d:%ld\n", st->st_dev, st->st_ino);
else if (flags & OPT_NLINK)
printf("%d\n", st->st_nlink);
else if (flags & OPT_LNKNAM) {
#ifdef S_ISLNK
b = xmalloc(4096);
p = readlink(f, b, 4096);
if (p >= 0 && p < 4096)
b[p] = '\0';
else {
p = errno;
strcpy(b, prog);
strcat(b, ": ");
strcat(b, strerror(p));
}
printf("%s\n", b);
free(b);
#else
printf("%s\n", f);
#endif
} else if (flags & OPT_PERM) {
perms(st->st_mode);
printf("\n");
} else if (flags & OPT_OPERM)
printf("%o\n", getperm(st->st_mode));
else if (flags & OPT_PMASK)
printf("%o\n", getperm(st->st_mode) & pmask);
else if (flags & OPT_UID) {
pw = getpwuid(st->st_uid);
if (flags & OPT_ASCII)
printf("%s\n", pw ? pw->pw_name : "unknown");
else
printf("%d\n", st->st_uid);
} else if (flags & OPT_GID) {
gr = getgrgid(st->st_gid);
if (flags & OPT_ASCII)
printf("%s\n", gr ? gr->gr_name : "unknown");
else
printf("%d\n", st->st_gid);
} else if (flags & OPT_SIZE)
printf("%ld\n", (long) st->st_size);
return (0);
}
#ifndef NOBUILTIN
int
finfo_builtin(list)
WORD_LIST *list;
{
int c, r;
char **v;
WORD_LIST *l;
v = make_builtin_argv (list, &c);
r = finfo_main (c, v);
free (v);
return r;
}
static char *finfo_doc[] = {
"Display information about file attributes.",
"",
"Display information about each FILE. Only single operators should",
"be supplied. If no options are supplied, a summary of the info",
"available about each FILE is printed. If FILE is of the form",
"/dev/fd/XX, file descriptor XX is described. Operators, if supplied,",
"have the following meanings:",
"",
" -a last file access time",
" -A last file access time in ctime format",
" -c last file status change time",
" -C last file status change time in ctime format",
" -m last file modification time",
" -M last file modification time in ctime format",
" -d device",
" -i inode",
" -f composite file identifier (device:inode)",
" -g gid of owner",
" -G group name of owner",
" -l name of file pointed to by symlink",
" -n link count",
" -o permissions in octal",
" -p permissions in ascii",
" -P mask permissions ANDed with MASK (like with umask)",
" -s file size in bytes",
" -u uid of owner",
" -U user name of owner",
(char *)0
};
struct builtin finfo_struct = {
"finfo",
finfo_builtin,
BUILTIN_ENABLED,
finfo_doc,
"finfo [-acdgiflmnopsuACGMPU] file [file...]",
0
};
#endif
#ifdef NOBUILTIN
#if defined (PREFER_STDARG)
# include <stdarg.h>
#else
# if defined (PREFER_VARARGS)
# include <varargs.h>
# endif
#endif
char *this_command_name;
main(argc, argv)
int argc;
char **argv;
{
this_command_name = argv[0];
exit(finfo_main(argc, argv));
}
void
builtin_usage()
{
fprintf(stderr, "%s: usage: %s [-%s] [file ...]\n", prog, OPTIONS);
}
#ifndef HAVE_STRERROR
char *
strerror(e)
int e;
{
static char ebuf[40];
extern int sys_nerr;
extern char *sys_errlist[];
if (e < 0 || e > sys_nerr) {
sprintf(ebuf,"Unknown error code %d", e);
return (&ebuf[0]);
}
return (sys_errlist[e]);
}
#endif
char *
xmalloc(s)
size_t s;
{
char *ret;
extern char *malloc();
ret = malloc(s);
if (ret)
return (ret);
fprintf(stderr, "%s: cannot malloc %d bytes\n", prog, s);
exit(1);
}
char *
base_pathname(p)
char *p;
{
char *t;
if (t = strrchr(p, '/'))
return(++t);
return(p);
}
int
legal_number (string, result)
char *string;
long *result;
{
int sign;
long value;
sign = 1;
value = 0;
if (result)
*result = 0;
/* Skip leading whitespace characters. */
while (whitespace (*string))
string++;
if (!*string)
return (0);
/* We allow leading `-' or `+'. */
if (*string == '-' || *string == '+')
{
if (!digit (string[1]))
return (0);
if (*string == '-')
sign = -1;
string++;
}
while (digit (*string))
{
if (result)
value = (value * 10) + digit_value (*string);
string++;
}
/* Skip trailing whitespace, if any. */
while (whitespace (*string))
string++;
/* Error if not at end of string. */
if (*string)
return (0);
if (result)
*result = value * sign;
return (1);
}
int sh_optind;
char *sh_optarg;
int sh_opterr;
extern int optind;
extern char *optarg;
int
sh_getopt(c, v, o)
int c;
char **v, *o;
{
int r;
r = getopt(c, v, o);
sh_optind = optind;
sh_optarg = optarg;
return r;
}
#if defined (USE_VARARGS)
void
#if defined (PREFER_STDARG)
builtin_error (const char *format, ...)
#else
builtin_error (format, va_alist)
const char *format;
va_dcl
#endif
{
va_list args;
if (this_command_name && *this_command_name)
fprintf (stderr, "%s: ", this_command_name);
#if defined (PREFER_STDARG)
va_start (args, format);
#else
va_start (args);
#endif
vfprintf (stderr, format, args);
va_end (args);
fprintf (stderr, "\n");
}
#else
void
builtin_error (format, arg1, arg2, arg3, arg4, arg5)
char *format, *arg1, *arg2, *arg3, *arg4, *arg5;
{
if (this_command_name && *this_command_name)
fprintf (stderr, "%s: ", this_command_name);
fprintf (stderr, format, arg1, arg2, arg3, arg4, arg5);
fprintf (stderr, "\n");
fflush (stderr);
}
#endif /* !USE_VARARGS */
#endif
| gpl-3.0 |
daodewang/DECAF | decaf/hw/lm32_boards.c | 48 | 10233 | /*
* QEMU models for LatticeMico32 uclinux and evr32 boards.
*
* Copyright (c) 2010 Michael Walle <michael@walle.cc>
*
* 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, see <http://www.gnu.org/licenses/>.
*/
#include "sysbus.h"
#include "hw.h"
#include "net.h"
#include "flash.h"
#include "devices.h"
#include "boards.h"
#include "loader.h"
#include "blockdev.h"
#include "elf.h"
#include "lm32_hwsetup.h"
#include "lm32.h"
#include "exec-memory.h"
typedef struct {
CPUState *env;
target_phys_addr_t bootstrap_pc;
target_phys_addr_t flash_base;
target_phys_addr_t hwsetup_base;
target_phys_addr_t initrd_base;
size_t initrd_size;
target_phys_addr_t cmdline_base;
} ResetInfo;
static void cpu_irq_handler(void *opaque, int irq, int level)
{
CPUState *env = opaque;
if (level) {
cpu_interrupt(env, CPU_INTERRUPT_HARD);
} else {
cpu_reset_interrupt(env, CPU_INTERRUPT_HARD);
}
}
static void main_cpu_reset(void *opaque)
{
ResetInfo *reset_info = opaque;
CPUState *env = reset_info->env;
cpu_reset(env);
/* init defaults */
env->pc = (uint32_t)reset_info->bootstrap_pc;
env->regs[R_R1] = (uint32_t)reset_info->hwsetup_base;
env->regs[R_R2] = (uint32_t)reset_info->cmdline_base;
env->regs[R_R3] = (uint32_t)reset_info->initrd_base;
env->regs[R_R4] = (uint32_t)(reset_info->initrd_base +
reset_info->initrd_size);
env->eba = reset_info->flash_base;
env->deba = reset_info->flash_base;
}
static void lm32_evr_init(ram_addr_t ram_size_not_used,
const char *boot_device,
const char *kernel_filename,
const char *kernel_cmdline,
const char *initrd_filename, const char *cpu_model)
{
CPUState *env;
DriveInfo *dinfo;
MemoryRegion *address_space_mem = get_system_memory();
MemoryRegion *phys_ram = g_new(MemoryRegion, 1);
qemu_irq *cpu_irq, irq[32];
ResetInfo *reset_info;
int i;
/* memory map */
target_phys_addr_t flash_base = 0x04000000;
size_t flash_sector_size = 256 * 1024;
size_t flash_size = 32 * 1024 * 1024;
target_phys_addr_t ram_base = 0x08000000;
size_t ram_size = 64 * 1024 * 1024;
target_phys_addr_t timer0_base = 0x80002000;
target_phys_addr_t uart0_base = 0x80006000;
target_phys_addr_t timer1_base = 0x8000a000;
int uart0_irq = 0;
int timer0_irq = 1;
int timer1_irq = 3;
reset_info = g_malloc0(sizeof(ResetInfo));
if (cpu_model == NULL) {
cpu_model = "lm32-full";
}
env = cpu_init(cpu_model);
reset_info->env = env;
reset_info->flash_base = flash_base;
memory_region_init_ram(phys_ram, NULL, "lm32_evr.sdram", ram_size);
memory_region_add_subregion(address_space_mem, ram_base, phys_ram);
dinfo = drive_get(IF_PFLASH, 0, 0);
/* Spansion S29NS128P */
pflash_cfi02_register(flash_base, NULL, "lm32_evr.flash", flash_size,
dinfo ? dinfo->bdrv : NULL, flash_sector_size,
flash_size / flash_sector_size, 1, 2,
0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
/* create irq lines */
cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);
env->pic_state = lm32_pic_init(*cpu_irq);
for (i = 0; i < 32; i++) {
irq[i] = qdev_get_gpio_in(env->pic_state, i);
}
sysbus_create_simple("lm32-uart", uart0_base, irq[uart0_irq]);
sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);
sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);
/* make sure juart isn't the first chardev */
env->juart_state = lm32_juart_init();
reset_info->bootstrap_pc = flash_base;
if (kernel_filename) {
uint64_t entry;
int kernel_size;
kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,
1, ELF_MACHINE, 0);
reset_info->bootstrap_pc = entry;
if (kernel_size < 0) {
kernel_size = load_image_targphys(kernel_filename, ram_base,
ram_size);
reset_info->bootstrap_pc = ram_base;
}
if (kernel_size < 0) {
fprintf(stderr, "qemu: could not load kernel '%s'\n",
kernel_filename);
exit(1);
}
}
qemu_register_reset(main_cpu_reset, reset_info);
}
static void lm32_uclinux_init(ram_addr_t ram_size_not_used,
const char *boot_device,
const char *kernel_filename,
const char *kernel_cmdline,
const char *initrd_filename, const char *cpu_model)
{
CPUState *env;
DriveInfo *dinfo;
MemoryRegion *address_space_mem = get_system_memory();
MemoryRegion *phys_ram = g_new(MemoryRegion, 1);
qemu_irq *cpu_irq, irq[32];
HWSetup *hw;
ResetInfo *reset_info;
int i;
/* memory map */
target_phys_addr_t flash_base = 0x04000000;
size_t flash_sector_size = 256 * 1024;
size_t flash_size = 32 * 1024 * 1024;
target_phys_addr_t ram_base = 0x08000000;
size_t ram_size = 64 * 1024 * 1024;
target_phys_addr_t uart0_base = 0x80000000;
target_phys_addr_t timer0_base = 0x80002000;
target_phys_addr_t timer1_base = 0x80010000;
target_phys_addr_t timer2_base = 0x80012000;
int uart0_irq = 0;
int timer0_irq = 1;
int timer1_irq = 20;
int timer2_irq = 21;
target_phys_addr_t hwsetup_base = 0x0bffe000;
target_phys_addr_t cmdline_base = 0x0bfff000;
target_phys_addr_t initrd_base = 0x08400000;
size_t initrd_max = 0x01000000;
reset_info = g_malloc0(sizeof(ResetInfo));
if (cpu_model == NULL) {
cpu_model = "lm32-full";
}
env = cpu_init(cpu_model);
reset_info->env = env;
reset_info->flash_base = flash_base;
memory_region_init_ram(phys_ram, NULL, "lm32_uclinux.sdram", ram_size);
memory_region_add_subregion(address_space_mem, ram_base, phys_ram);
dinfo = drive_get(IF_PFLASH, 0, 0);
/* Spansion S29NS128P */
pflash_cfi02_register(flash_base, NULL, "lm32_uclinux.flash", flash_size,
dinfo ? dinfo->bdrv : NULL, flash_sector_size,
flash_size / flash_sector_size, 1, 2,
0x01, 0x7e, 0x43, 0x00, 0x555, 0x2aa, 1);
/* create irq lines */
cpu_irq = qemu_allocate_irqs(cpu_irq_handler, env, 1);
env->pic_state = lm32_pic_init(*cpu_irq);
for (i = 0; i < 32; i++) {
irq[i] = qdev_get_gpio_in(env->pic_state, i);
}
sysbus_create_simple("lm32-uart", uart0_base, irq[uart0_irq]);
sysbus_create_simple("lm32-timer", timer0_base, irq[timer0_irq]);
sysbus_create_simple("lm32-timer", timer1_base, irq[timer1_irq]);
sysbus_create_simple("lm32-timer", timer2_base, irq[timer2_irq]);
/* make sure juart isn't the first chardev */
env->juart_state = lm32_juart_init();
reset_info->bootstrap_pc = flash_base;
if (kernel_filename) {
uint64_t entry;
int kernel_size;
kernel_size = load_elf(kernel_filename, NULL, NULL, &entry, NULL, NULL,
1, ELF_MACHINE, 0);
reset_info->bootstrap_pc = entry;
if (kernel_size < 0) {
kernel_size = load_image_targphys(kernel_filename, ram_base,
ram_size);
reset_info->bootstrap_pc = ram_base;
}
if (kernel_size < 0) {
fprintf(stderr, "qemu: could not load kernel '%s'\n",
kernel_filename);
exit(1);
}
}
/* generate a rom with the hardware description */
hw = hwsetup_init();
hwsetup_add_cpu(hw, "LM32", 75000000);
hwsetup_add_flash(hw, "flash", flash_base, flash_size);
hwsetup_add_ddr_sdram(hw, "ddr_sdram", ram_base, ram_size);
hwsetup_add_timer(hw, "timer0", timer0_base, timer0_irq);
hwsetup_add_timer(hw, "timer1_dev_only", timer1_base, timer1_irq);
hwsetup_add_timer(hw, "timer2_dev_only", timer2_base, timer2_irq);
hwsetup_add_uart(hw, "uart", uart0_base, uart0_irq);
hwsetup_add_trailer(hw);
hwsetup_create_rom(hw, hwsetup_base);
hwsetup_free(hw);
reset_info->hwsetup_base = hwsetup_base;
if (kernel_cmdline && strlen(kernel_cmdline)) {
pstrcpy_targphys("cmdline", cmdline_base, TARGET_PAGE_SIZE,
kernel_cmdline);
reset_info->cmdline_base = cmdline_base;
}
if (initrd_filename) {
size_t initrd_size;
initrd_size = load_image_targphys(initrd_filename, initrd_base,
initrd_max);
reset_info->initrd_base = initrd_base;
reset_info->initrd_size = initrd_size;
}
qemu_register_reset(main_cpu_reset, reset_info);
}
static QEMUMachine lm32_evr_machine = {
.name = "lm32-evr",
.desc = "LatticeMico32 EVR32 eval system",
.init = lm32_evr_init,
.is_default = 1
};
static QEMUMachine lm32_uclinux_machine = {
.name = "lm32-uclinux",
.desc = "lm32 platform for uClinux and u-boot by Theobroma Systems",
.init = lm32_uclinux_init,
.is_default = 0
};
static void lm32_machine_init(void)
{
qemu_register_machine(&lm32_uclinux_machine);
qemu_register_machine(&lm32_evr_machine);
}
machine_init(lm32_machine_init);
| gpl-3.0 |
nevelis/rAthena | 3rdparty/libconfig/scanctx.c | 49 | 4649 | /* ----------------------------------------------------------------------------
libconfig - A library for processing structured configuration files
Copyright (C) 2005-2010 Mark A Lindner
This file is part of libconfig.
This library is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 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 General Public License for more details.
You should have received a copy of the GNU General Public License
along with this library. If not, see <http://www.gnu.org/licenses/>.
----------------------------------------------------------------------------
*/
#include "scanctx.h"
#include "wincompat.h"
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#define STRING_BLOCK_SIZE 64
#define CHUNK_SIZE 32
/* ------------------------------------------------------------------------- */
static const char *err_bad_include = "cannot open include file";
static const char *err_include_too_deep = "include file nesting too deep";
/* ------------------------------------------------------------------------- */
static const char *__scanctx_add_filename(struct scan_context *ctx,
const char *filename)
{
unsigned int count = ctx->num_filenames;
const char **f;
for(f = ctx->filenames; count > 0; ++f, --count)
{
if(!strcmp(*f, filename))
{
free((void *)filename);
return(*f); /* already in list */
}
}
if((ctx->num_filenames % CHUNK_SIZE) == 0)
{
ctx->filenames = (const char **)realloc(
(void *)ctx->filenames,
(ctx->num_filenames + CHUNK_SIZE) * sizeof(const char *));
}
ctx->filenames[ctx->num_filenames] = filename;
++ctx->num_filenames;
return(filename);
}
/* ------------------------------------------------------------------------- */
void scanctx_init(struct scan_context *ctx, const char *top_filename)
{
memset(ctx, 0, sizeof(struct scan_context));
if(top_filename)
ctx->top_filename = __scanctx_add_filename(ctx, strdup(top_filename));
}
/* ------------------------------------------------------------------------- */
const char **scanctx_cleanup(struct scan_context *ctx,
unsigned int *num_filenames)
{
int i;
for(i = 0; i < ctx->depth; ++i)
fclose(ctx->streams[i]);
free((void *)(strbuf_release(&(ctx->string))));
*num_filenames = ctx->num_filenames;
return(ctx->filenames);
}
/* ------------------------------------------------------------------------- */
FILE *scanctx_push_include(struct scan_context *ctx, void *buffer,
const char **error)
{
FILE *fp = NULL;
const char *file;
char *full_file = NULL;
*error = NULL;
if(ctx->depth == MAX_INCLUDE_DEPTH)
{
*error = err_include_too_deep;
return(NULL);
}
file = scanctx_take_string(ctx);
if(ctx->config->include_dir)
{
full_file = (char *)malloc(strlen(ctx->config->include_dir) + strlen(file)
+ 2);
strcpy(full_file, ctx->config->include_dir);
strcat(full_file, FILE_SEPARATOR);
strcat(full_file, file);
}
fp = fopen(full_file ? full_file : file, "rt");
free((void *)full_file);
if(fp)
{
ctx->streams[ctx->depth] = fp;
ctx->files[ctx->depth] = __scanctx_add_filename(ctx, file);
ctx->buffers[ctx->depth] = buffer;
++(ctx->depth);
}
else
{
free((void *)file);
*error = err_bad_include;
}
return(fp);
}
/* ------------------------------------------------------------------------- */
void *scanctx_pop_include(struct scan_context *ctx)
{
void *buffer;
if(ctx->depth == 0)
return(NULL); /* stack underflow */
--(ctx->depth);
buffer = ctx->buffers[ctx->depth];
fclose(ctx->streams[ctx->depth]);
return(buffer);
}
/* ------------------------------------------------------------------------- */
char *scanctx_take_string(struct scan_context *ctx)
{
char *r = strbuf_release(&(ctx->string));
return(r ? r : strdup(""));
}
/* ------------------------------------------------------------------------- */
const char *scanctx_current_filename(struct scan_context *ctx)
{
return((ctx->depth == 0) ? ctx->top_filename : ctx->files[ctx->depth - 1]);
}
/* ------------------------------------------------------------------------- */
/* eof */
| gpl-3.0 |
ArkBriar/shadowsocks-android | src/main/jni/openssl/crypto/ripemd/rmd160.c | 819 | 4224 | /* crypto/ripemd/rmd160.c */
/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
* All rights reserved.
*
* This package is an SSL implementation written
* by Eric Young (eay@cryptsoft.com).
* The implementation was written so as to conform with Netscapes SSL.
*
* This library is free for commercial and non-commercial use as long as
* the following conditions are aheared to. The following conditions
* apply to all code found in this distribution, be it the RC4, RSA,
* lhash, DES, etc., code; not just the SSL code. The SSL documentation
* included with this distribution is covered by the same copyright terms
* except that the holder is Tim Hudson (tjh@cryptsoft.com).
*
* Copyright remains Eric Young's, and as such any Copyright notices in
* the code are not to be removed.
* If this package is used in a product, Eric Young should be given attribution
* as the author of the parts of the library used.
* This can be in the form of a textual message at program startup or
* in documentation (online or textual) provided with the package.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* "This product includes cryptographic software written by
* Eric Young (eay@cryptsoft.com)"
* The word 'cryptographic' can be left out if the rouines from the library
* being used are not cryptographic related :-).
* 4. If you include any Windows specific code (or a derivative thereof) from
* the apps directory (application code) you must include an acknowledgement:
* "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
*
* THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*
* The licence and distribution terms for any publically available version or
* derivative of this code cannot be changed. i.e. this code cannot simply be
* copied and put under another distribution licence
* [including the GNU Public Licence.]
*/
#include <stdio.h>
#include <stdlib.h>
#include <openssl/ripemd.h>
#define BUFSIZE 1024*16
void do_fp(FILE *f);
void pt(unsigned char *md);
#if !defined(_OSD_POSIX) && !defined(__DJGPP__)
int read(int, void *, unsigned int);
#endif
int main(int argc, char **argv)
{
int i,err=0;
FILE *IN;
if (argc == 1)
{
do_fp(stdin);
}
else
{
for (i=1; i<argc; i++)
{
IN=fopen(argv[i],"r");
if (IN == NULL)
{
perror(argv[i]);
err++;
continue;
}
printf("RIPEMD160(%s)= ",argv[i]);
do_fp(IN);
fclose(IN);
}
}
exit(err);
}
void do_fp(FILE *f)
{
RIPEMD160_CTX c;
unsigned char md[RIPEMD160_DIGEST_LENGTH];
int fd;
int i;
static unsigned char buf[BUFSIZE];
fd=fileno(f);
RIPEMD160_Init(&c);
for (;;)
{
i=read(fd,buf,BUFSIZE);
if (i <= 0) break;
RIPEMD160_Update(&c,buf,(unsigned long)i);
}
RIPEMD160_Final(&(md[0]),&c);
pt(md);
}
void pt(unsigned char *md)
{
int i;
for (i=0; i<RIPEMD160_DIGEST_LENGTH; i++)
printf("%02x",md[i]);
printf("\n");
}
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.