repo_name
string | path
string | copies
string | size
string | content
string | license
string |
---|---|---|---|---|---|
hirano/koblo_software
|
SDK/trunk/AudioCompress/codecs/libvorbis/lib/vorbisfile.c
|
11
|
62478
|
/********************************************************************
* *
* THIS FILE IS PART OF THE OggVorbis SOFTWARE CODEC SOURCE CODE. *
* USE, DISTRIBUTION AND REPRODUCTION OF THIS LIBRARY SOURCE IS *
* GOVERNED BY A BSD-STYLE SOURCE LICENSE INCLUDED WITH THIS SOURCE *
* IN 'COPYING'. PLEASE READ THESE TERMS BEFORE DISTRIBUTING. *
* *
* THE OggVorbis SOURCE CODE IS (C) COPYRIGHT 1994-2007 *
* by the Xiph.Org Foundation http://www.xiph.org/ *
* *
********************************************************************
function: stdio-based convenience library for opening/seeking/decoding
last mod: $Id: vorbisfile.c 13294 2007-07-24 01:08:23Z xiphmont $
********************************************************************/
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <math.h>
#include "vorbis/codec.h"
#include "vorbis/vorbisfile.h"
#include "os.h"
#include "misc.h"
/* A 'chained bitstream' is a Vorbis bitstream that contains more than
one logical bitstream arranged end to end (the only form of Ogg
multiplexing allowed in a Vorbis bitstream; grouping [parallel
multiplexing] is not allowed in Vorbis) */
/* A Vorbis file can be played beginning to end (streamed) without
worrying ahead of time about chaining (see decoder_example.c). If
we have the whole file, however, and want random access
(seeking/scrubbing) or desire to know the total length/time of a
file, we need to account for the possibility of chaining. */
/* We can handle things a number of ways; we can determine the entire
bitstream structure right off the bat, or find pieces on demand.
This example determines and caches structure for the entire
bitstream, but builds a virtual decoder on the fly when moving
between links in the chain. */
/* There are also different ways to implement seeking. Enough
information exists in an Ogg bitstream to seek to
sample-granularity positions in the output. Or, one can seek by
picking some portion of the stream roughly in the desired area if
we only want coarse navigation through the stream. */
/*************************************************************************
* Many, many internal helpers. The intention is not to be confusing;
* rampant duplication and monolithic function implementation would be
* harder to understand anyway. The high level functions are last. Begin
* grokking near the end of the file */
/* read a little more data from the file/pipe into the ogg_sync framer
*/
#define CHUNKSIZE 65536
static long _get_data(OggVorbis_File *vf){
errno=0;
if(!(vf->callbacks.read_func))return(-1);
if(vf->datasource){
char *buffer=ogg_sync_buffer(&vf->oy,CHUNKSIZE);
long bytes=(vf->callbacks.read_func)(buffer,1,CHUNKSIZE,vf->datasource);
if(bytes>0)ogg_sync_wrote(&vf->oy,bytes);
if(bytes==0 && errno)return(-1);
return(bytes);
}else
return(0);
}
/* save a tiny smidge of verbosity to make the code more readable */
static int _seek_helper(OggVorbis_File *vf,ogg_int64_t offset){
if(vf->datasource){
if(!(vf->callbacks.seek_func)||
(vf->callbacks.seek_func)(vf->datasource, offset, SEEK_SET) == -1)
return OV_EREAD;
vf->offset=offset;
ogg_sync_reset(&vf->oy);
}else{
/* shouldn't happen unless someone writes a broken callback */
return OV_EFAULT;
}
return 0;
}
/* The read/seek functions track absolute position within the stream */
/* from the head of the stream, get the next page. boundary specifies
if the function is allowed to fetch more data from the stream (and
how much) or only use internally buffered data.
boundary: -1) unbounded search
0) read no additional data; use cached only
n) search for a new page beginning for n bytes
return: <0) did not find a page (OV_FALSE, OV_EOF, OV_EREAD)
n) found a page at absolute offset n */
static ogg_int64_t _get_next_page(OggVorbis_File *vf,ogg_page *og,
ogg_int64_t boundary){
if(boundary>0)boundary+=vf->offset;
while(1){
long more;
if(boundary>0 && vf->offset>=boundary)return(OV_FALSE);
more=ogg_sync_pageseek(&vf->oy,og);
if(more<0){
/* skipped n bytes */
vf->offset-=more;
}else{
if(more==0){
/* send more paramedics */
if(!boundary)return(OV_FALSE);
{
long ret=_get_data(vf);
if(ret==0)return(OV_EOF);
if(ret<0)return(OV_EREAD);
}
}else{
/* got a page. Return the offset at the page beginning,
advance the internal offset past the page end */
ogg_int64_t ret=vf->offset;
vf->offset+=more;
return(ret);
}
}
}
}
/* find the latest page beginning before the current stream cursor
position. Much dirtier than the above as Ogg doesn't have any
backward search linkage. no 'readp' as it will certainly have to
read. */
/* returns offset or OV_EREAD, OV_FAULT */
static ogg_int64_t _get_prev_page(OggVorbis_File *vf,ogg_page *og){
ogg_int64_t begin=vf->offset;
ogg_int64_t end=begin;
ogg_int64_t ret;
ogg_int64_t offset=-1;
while(offset==-1){
begin-=CHUNKSIZE;
if(begin<0)
begin=0;
ret=_seek_helper(vf,begin);
if(ret)return(ret);
while(vf->offset<end){
ret=_get_next_page(vf,og,end-vf->offset);
if(ret==OV_EREAD)return(OV_EREAD);
if(ret<0){
break;
}else{
offset=ret;
}
}
}
/* we have the offset. Actually snork and hold the page now */
ret=_seek_helper(vf,offset);
if(ret)return(ret);
ret=_get_next_page(vf,og,CHUNKSIZE);
if(ret<0)
/* this shouldn't be possible */
return(OV_EFAULT);
return(offset);
}
static void _add_serialno(ogg_page *og,long **serialno_list, int *n){
long s = ogg_page_serialno(og);
(*n)++;
if(serialno_list){
*serialno_list = _ogg_realloc(*serialno_list, sizeof(*serialno_list)*(*n));
}else{
*serialno_list = _ogg_malloc(sizeof(**serialno_list));
}
(*serialno_list)[(*n)-1] = s;
}
/* returns nonzero if found */
static int _lookup_serialno(ogg_page *og, long *serialno_list, int n){
long s = ogg_page_serialno(og);
if(serialno_list){
while(n--){
if(*serialno_list == s) return 1;
serialno_list++;
}
}
return 0;
}
/* start parsing pages at current offset, remembering all serial
numbers. Stop logging at first non-bos page */
static int _get_serialnos(OggVorbis_File *vf, long **s, int *n){
ogg_page og;
*s=NULL;
*n=0;
while(1){
ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
if(llret==OV_EOF)return(0);
if(llret<0)return(llret);
if(!ogg_page_bos(&og)) return 0;
/* look for duplicate serialnos; add this one if unique */
if(_lookup_serialno(&og,*s,*n)){
if(*s)_ogg_free(*s);
*s=0;
*n=0;
return(OV_EBADHEADER);
}
_add_serialno(&og,s,n);
}
}
/* finds each bitstream link one at a time using a bisection search
(has to begin by knowing the offset of the lb's initial page).
Recurses for each link so it can alloc the link storage after
finding them all, then unroll and fill the cache at the same time */
static int _bisect_forward_serialno(OggVorbis_File *vf,
ogg_int64_t begin,
ogg_int64_t searched,
ogg_int64_t end,
long *currentno_list,
int currentnos,
long m){
ogg_int64_t endsearched=end;
ogg_int64_t next=end;
ogg_page og;
ogg_int64_t ret;
/* the below guards against garbage seperating the last and
first pages of two links. */
while(searched<endsearched){
ogg_int64_t bisect;
if(endsearched-searched<CHUNKSIZE){
bisect=searched;
}else{
bisect=(searched+endsearched)/2;
}
ret=_seek_helper(vf,bisect);
if(ret)return(ret);
ret=_get_next_page(vf,&og,-1);
if(ret==OV_EREAD)return(OV_EREAD);
if(ret<0 || !_lookup_serialno(&og,currentno_list,currentnos)){
endsearched=bisect;
if(ret>=0)next=ret;
}else{
searched=ret+og.header_len+og.body_len;
}
}
{
long *next_serialno_list=NULL;
int next_serialnos=0;
ret=_seek_helper(vf,next);
if(ret)return(ret);
ret=_get_serialnos(vf,&next_serialno_list,&next_serialnos);
if(ret)return(ret);
if(searched>=end || next_serialnos==0){
vf->links=m+1;
vf->offsets=_ogg_malloc((vf->links+1)*sizeof(*vf->offsets));
vf->offsets[m+1]=searched;
}else{
ret=_bisect_forward_serialno(vf,next,vf->offset,
end,next_serialno_list,next_serialnos,m+1);
if(ret)return(ret);
}
if(next_serialno_list)_ogg_free(next_serialno_list);
}
vf->offsets[m]=begin;
return(0);
}
/* uses the local ogg_stream storage in vf; this is important for
non-streaming input sources */
static int _fetch_headers(OggVorbis_File *vf,vorbis_info *vi,vorbis_comment *vc,
long *serialno,ogg_page *og_ptr){
ogg_page og;
ogg_packet op;
int i,ret;
int allbos=0;
if(!og_ptr){
ogg_int64_t llret=_get_next_page(vf,&og,CHUNKSIZE);
if(llret==OV_EREAD)return(OV_EREAD);
if(llret<0)return(OV_ENOTVORBIS);
og_ptr=&og;
}
vorbis_info_init(vi);
vorbis_comment_init(vc);
/* extract the first set of vorbis headers we see in the headerset */
while(1){
/* if we're past the ID headers, we won't be finding a Vorbis
stream in this link */
if(!ogg_page_bos(og_ptr)){
ret = OV_ENOTVORBIS;
goto bail_header;
}
/* prospective stream setup; we need a stream to get packets */
ogg_stream_reset_serialno(&vf->os,ogg_page_serialno(og_ptr));
ogg_stream_pagein(&vf->os,og_ptr);
if(ogg_stream_packetout(&vf->os,&op) > 0 &&
vorbis_synthesis_idheader(&op)){
/* continue Vorbis header load; past this point, any error will
render this link useless (we won't continue looking for more
Vorbis streams */
if(serialno)*serialno=vf->os.serialno;
vf->ready_state=STREAMSET;
if((ret=vorbis_synthesis_headerin(vi,vc,&op)))
goto bail_header;
i=0;
while(i<2){ /* get a page loop */
while(i<2){ /* get a packet loop */
int result=ogg_stream_packetout(&vf->os,&op);
if(result==0)break;
if(result==-1){
ret=OV_EBADHEADER;
goto bail_header;
}
if((ret=vorbis_synthesis_headerin(vi,vc,&op)))
goto bail_header;
i++;
}
while(i<2){
if(_get_next_page(vf,og_ptr,CHUNKSIZE)<0){
ret=OV_EBADHEADER;
goto bail_header;
}
/* if this page belongs to the correct stream, go parse it */
if(vf->os.serialno == ogg_page_serialno(og_ptr)){
ogg_stream_pagein(&vf->os,og_ptr);
break;
}
/* if we never see the final vorbis headers before the link
ends, abort */
if(ogg_page_bos(og_ptr)){
if(allbos){
ret = OV_EBADHEADER;
goto bail_header;
}else
allbos=1;
}
/* otherwise, keep looking */
}
}
return 0;
}
/* this wasn't vorbis, get next page, try again */
{
ogg_int64_t llret=_get_next_page(vf,og_ptr,CHUNKSIZE);
if(llret==OV_EREAD)return(OV_EREAD);
if(llret<0)return(OV_ENOTVORBIS);
}
}
bail_header:
vorbis_info_clear(vi);
vorbis_comment_clear(vc);
vf->ready_state=OPENED;
return ret;
}
/* last step of the OggVorbis_File initialization; get all the
vorbis_info structs and PCM positions. Only called by the seekable
initialization (local stream storage is hacked slightly; pay
attention to how that's done) */
/* this is void and does not propogate errors up because we want to be
able to open and use damaged bitstreams as well as we can. Just
watch out for missing information for links in the OggVorbis_File
struct */
static void _prefetch_all_headers(OggVorbis_File *vf, ogg_int64_t dataoffset){
ogg_page og;
int i;
ogg_int64_t ret;
vf->vi=_ogg_realloc(vf->vi,vf->links*sizeof(*vf->vi));
vf->vc=_ogg_realloc(vf->vc,vf->links*sizeof(*vf->vc));
vf->serialnos=_ogg_malloc(vf->links*sizeof(*vf->serialnos));
vf->dataoffsets=_ogg_malloc(vf->links*sizeof(*vf->dataoffsets));
vf->pcmlengths=_ogg_malloc(vf->links*2*sizeof(*vf->pcmlengths));
for(i=0;i<vf->links;i++){
if(i==0){
/* we already grabbed the initial header earlier. Just set the offset */
vf->serialnos[i]=vf->current_serialno;
vf->dataoffsets[i]=dataoffset;
ret=_seek_helper(vf,dataoffset);
if(ret)
vf->dataoffsets[i]=-1;
}else{
/* seek to the location of the initial header */
ret=_seek_helper(vf,vf->offsets[i]);
if(ret){
vf->dataoffsets[i]=-1;
}else{
if(_fetch_headers(vf,vf->vi+i,vf->vc+i,vf->serialnos+i,NULL)<0){
vf->dataoffsets[i]=-1;
}else{
vf->dataoffsets[i]=vf->offset;
}
}
}
/* fetch beginning PCM offset */
if(vf->dataoffsets[i]!=-1){
ogg_int64_t accumulated=0;
long lastblock=-1;
int result;
ogg_stream_reset_serialno(&vf->os,vf->serialnos[i]);
while(1){
ogg_packet op;
ret=_get_next_page(vf,&og,-1);
if(ret<0)
/* this should not be possible unless the file is
truncated/mangled */
break;
if(ogg_page_bos(&og)) break;
if(ogg_page_serialno(&og)!=vf->serialnos[i])
continue;
/* count blocksizes of all frames in the page */
ogg_stream_pagein(&vf->os,&og);
while((result=ogg_stream_packetout(&vf->os,&op))){
if(result>0){ /* ignore holes */
long thisblock=vorbis_packet_blocksize(vf->vi+i,&op);
if(lastblock!=-1)
accumulated+=(lastblock+thisblock)>>2;
lastblock=thisblock;
}
}
if(ogg_page_granulepos(&og)!=-1){
/* pcm offset of last packet on the first audio page */
accumulated= ogg_page_granulepos(&og)-accumulated;
break;
}
}
/* less than zero? This is a stream with samples trimmed off
the beginning, a normal occurrence; set the offset to zero */
if(accumulated<0)accumulated=0;
vf->pcmlengths[i*2]=accumulated;
}
/* get the PCM length of this link. To do this,
get the last page of the stream */
{
ogg_int64_t end=vf->offsets[i+1];
ret=_seek_helper(vf,end);
if(ret){
/* this should not be possible */
vorbis_info_clear(vf->vi+i);
vorbis_comment_clear(vf->vc+i);
}else{
while(1){
ret=_get_prev_page(vf,&og);
if(ret<0){
/* this should not be possible */
vorbis_info_clear(vf->vi+i);
vorbis_comment_clear(vf->vc+i);
break;
}
if(ogg_page_serialno(&og)==vf->serialnos[i]){
if(ogg_page_granulepos(&og)!=-1){
vf->pcmlengths[i*2+1]=ogg_page_granulepos(&og)-vf->pcmlengths[i*2];
break;
}
}
vf->offset=ret;
}
}
}
}
}
static int _make_decode_ready(OggVorbis_File *vf){
if(vf->ready_state>STREAMSET)return 0;
if(vf->ready_state<STREAMSET)return OV_EFAULT;
if(vf->seekable){
if(vorbis_synthesis_init(&vf->vd,vf->vi+vf->current_link))
return OV_EBADLINK;
}else{
if(vorbis_synthesis_init(&vf->vd,vf->vi))
return OV_EBADLINK;
}
vorbis_block_init(&vf->vd,&vf->vb);
vf->ready_state=INITSET;
vf->bittrack=0.f;
vf->samptrack=0.f;
return 0;
}
static int _open_seekable2(OggVorbis_File *vf){
ogg_int64_t dataoffset=vf->offset,end;
long *serialno_list=NULL;
int serialnos=0;
int ret;
ogg_page og;
/* we're partially open and have a first link header state in
storage in vf */
/* we can seek, so set out learning all about this file */
if(vf->callbacks.seek_func && vf->callbacks.tell_func){
(vf->callbacks.seek_func)(vf->datasource,0,SEEK_END);
vf->offset=vf->end=(vf->callbacks.tell_func)(vf->datasource);
}else{
vf->offset=vf->end=-1;
}
/* If seek_func is implemented, tell_func must also be implemented */
if(vf->end==-1) return(OV_EINVAL);
/* We get the offset for the last page of the physical bitstream.
Most OggVorbis files will contain a single logical bitstream */
end=_get_prev_page(vf,&og);
if(end<0)return(end);
/* back to beginning, learn all serialnos of first link */
ret=_seek_helper(vf,0);
if(ret)return(ret);
ret=_get_serialnos(vf,&serialno_list,&serialnos);
if(ret)return(ret);
/* now determine bitstream structure recursively */
if(_bisect_forward_serialno(vf,0,0,end+1,serialno_list,serialnos,0)<0)return(OV_EREAD);
if(serialno_list)_ogg_free(serialno_list);
/* the initial header memory is referenced by vf after; don't free it */
_prefetch_all_headers(vf,dataoffset);
return(ov_raw_seek(vf,0));
}
/* clear out the current logical bitstream decoder */
static void _decode_clear(OggVorbis_File *vf){
vorbis_dsp_clear(&vf->vd);
vorbis_block_clear(&vf->vb);
vf->ready_state=OPENED;
}
/* fetch and process a packet. Handles the case where we're at a
bitstream boundary and dumps the decoding machine. If the decoding
machine is unloaded, it loads it. It also keeps pcm_offset up to
date (seek and read both use this. seek uses a special hack with
readp).
return: <0) error, OV_HOLE (lost packet) or OV_EOF
0) need more data (only if readp==0)
1) got a packet
*/
static int _fetch_and_process_packet(OggVorbis_File *vf,
ogg_packet *op_in,
int readp,
int spanp){
ogg_page og;
/* handle one packet. Try to fetch it from current stream state */
/* extract packets from page */
while(1){
/* process a packet if we can. If the machine isn't loaded,
neither is a page */
if(vf->ready_state==INITSET){
while(1) {
ogg_packet op;
ogg_packet *op_ptr=(op_in?op_in:&op);
int result=ogg_stream_packetout(&vf->os,op_ptr);
ogg_int64_t granulepos;
op_in=NULL;
if(result==-1)return(OV_HOLE); /* hole in the data. */
if(result>0){
/* got a packet. process it */
granulepos=op_ptr->granulepos;
if(!vorbis_synthesis(&vf->vb,op_ptr)){ /* lazy check for lazy
header handling. The
header packets aren't
audio, so if/when we
submit them,
vorbis_synthesis will
reject them */
/* suck in the synthesis data and track bitrate */
{
int oldsamples=vorbis_synthesis_pcmout(&vf->vd,NULL);
/* for proper use of libvorbis within libvorbisfile,
oldsamples will always be zero. */
if(oldsamples)return(OV_EFAULT);
vorbis_synthesis_blockin(&vf->vd,&vf->vb);
vf->samptrack+=vorbis_synthesis_pcmout(&vf->vd,NULL)-oldsamples;
vf->bittrack+=op_ptr->bytes*8;
}
/* update the pcm offset. */
if(granulepos!=-1 && !op_ptr->e_o_s){
int link=(vf->seekable?vf->current_link:0);
int i,samples;
/* this packet has a pcm_offset on it (the last packet
completed on a page carries the offset) After processing
(above), we know the pcm position of the *last* sample
ready to be returned. Find the offset of the *first*
As an aside, this trick is inaccurate if we begin
reading anew right at the last page; the end-of-stream
granulepos declares the last frame in the stream, and the
last packet of the last page may be a partial frame.
So, we need a previous granulepos from an in-sequence page
to have a reference point. Thus the !op_ptr->e_o_s clause
above */
if(vf->seekable && link>0)
granulepos-=vf->pcmlengths[link*2];
if(granulepos<0)granulepos=0; /* actually, this
shouldn't be possible
here unless the stream
is very broken */
samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
granulepos-=samples;
for(i=0;i<link;i++)
granulepos+=vf->pcmlengths[i*2+1];
vf->pcm_offset=granulepos;
}
return(1);
}
}
else
break;
}
}
if(vf->ready_state>=OPENED){
ogg_int64_t ret;
while(1){
/* the loop is not strictly necessary, but there's no sense in
doing the extra checks of the larger loop for the common
case in a multiplexed bistream where the page is simply
part of a different logical bitstream; keep reading until
we get one with the correct serialno */
if(!readp)return(0);
if((ret=_get_next_page(vf,&og,-1))<0){
return(OV_EOF); /* eof. leave unitialized */
}
/* bitrate tracking; add the header's bytes here, the body bytes
are done by packet above */
vf->bittrack+=og.header_len*8;
if(vf->ready_state==INITSET){
if(vf->current_serialno!=ogg_page_serialno(&og)){
/* two possibilities:
1) our decoding just traversed a bitstream boundary
2) another stream is multiplexed into this logical section? */
if(ogg_page_bos(&og)){
/* boundary case */
if(!spanp)
return(OV_EOF);
_decode_clear(vf);
if(!vf->seekable){
vorbis_info_clear(vf->vi);
vorbis_comment_clear(vf->vc);
}
break;
}else
continue; /* possibility #2 */
}
}
break;
}
}
/* Do we need to load a new machine before submitting the page? */
/* This is different in the seekable and non-seekable cases.
In the seekable case, we already have all the header
information loaded and cached; we just initialize the machine
with it and continue on our merry way.
In the non-seekable (streaming) case, we'll only be at a
boundary if we just left the previous logical bitstream and
we're now nominally at the header of the next bitstream
*/
if(vf->ready_state!=INITSET){
int link;
if(vf->ready_state<STREAMSET){
if(vf->seekable){
long serialno = ogg_page_serialno(&og);
/* match the serialno to bitstream section. We use this rather than
offset positions to avoid problems near logical bitstream
boundaries */
for(link=0;link<vf->links;link++)
if(vf->serialnos[link]==serialno)break;
if(link==vf->links) continue; /* not the desired Vorbis
bitstream section; keep
trying */
vf->current_serialno=serialno;
vf->current_link=link;
ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
vf->ready_state=STREAMSET;
}else{
/* we're streaming */
/* fetch the three header packets, build the info struct */
int ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,&og);
if(ret)return(ret);
vf->current_link++;
link=0;
}
}
{
int ret=_make_decode_ready(vf);
if(ret<0)return ret;
}
}
/* the buffered page is the data we want, and we're ready for it;
add it to the stream state */
ogg_stream_pagein(&vf->os,&og);
}
}
/* if, eg, 64 bit stdio is configured by default, this will build with
fseek64 */
static int _fseek64_wrap(FILE *f,ogg_int64_t off,int whence){
if(f==NULL)return(-1);
return fseek(f,off,whence);
}
static int _ov_open1(void *f,OggVorbis_File *vf,char *initial,
long ibytes, ov_callbacks callbacks){
int offsettest=((f && callbacks.seek_func)?callbacks.seek_func(f,0,SEEK_CUR):-1);
int ret;
memset(vf,0,sizeof(*vf));
vf->datasource=f;
vf->callbacks = callbacks;
/* init the framing state */
ogg_sync_init(&vf->oy);
/* perhaps some data was previously read into a buffer for testing
against other stream types. Allow initialization from this
previously read data (as we may be reading from a non-seekable
stream) */
if(initial){
char *buffer=ogg_sync_buffer(&vf->oy,ibytes);
memcpy(buffer,initial,ibytes);
ogg_sync_wrote(&vf->oy,ibytes);
}
/* can we seek? Stevens suggests the seek test was portable */
if(offsettest!=-1)vf->seekable=1;
/* No seeking yet; Set up a 'single' (current) logical bitstream
entry for partial open */
vf->links=1;
vf->vi=_ogg_calloc(vf->links,sizeof(*vf->vi));
vf->vc=_ogg_calloc(vf->links,sizeof(*vf->vc));
ogg_stream_init(&vf->os,-1); /* fill in the serialno later */
/* Try to fetch the headers, maintaining all the storage */
if((ret=_fetch_headers(vf,vf->vi,vf->vc,&vf->current_serialno,NULL))<0){
vf->datasource=NULL;
ov_clear(vf);
}else
vf->ready_state=PARTOPEN;
return(ret);
}
static int _ov_open2(OggVorbis_File *vf){
if(vf->ready_state != PARTOPEN) return OV_EINVAL;
vf->ready_state=OPENED;
if(vf->seekable){
int ret=_open_seekable2(vf);
if(ret){
vf->datasource=NULL;
ov_clear(vf);
}
return(ret);
}else
vf->ready_state=STREAMSET;
return 0;
}
/* clear out the OggVorbis_File struct */
int ov_clear(OggVorbis_File *vf){
if(vf){
vorbis_block_clear(&vf->vb);
vorbis_dsp_clear(&vf->vd);
ogg_stream_clear(&vf->os);
if(vf->vi && vf->links){
int i;
for(i=0;i<vf->links;i++){
vorbis_info_clear(vf->vi+i);
vorbis_comment_clear(vf->vc+i);
}
_ogg_free(vf->vi);
_ogg_free(vf->vc);
}
if(vf->dataoffsets)_ogg_free(vf->dataoffsets);
if(vf->pcmlengths)_ogg_free(vf->pcmlengths);
if(vf->serialnos)_ogg_free(vf->serialnos);
if(vf->offsets)_ogg_free(vf->offsets);
ogg_sync_clear(&vf->oy);
if(vf->datasource && vf->callbacks.close_func)
(vf->callbacks.close_func)(vf->datasource);
memset(vf,0,sizeof(*vf));
}
#ifdef DEBUG_LEAKS
_VDBG_dump();
#endif
return(0);
}
/* inspects the OggVorbis file and finds/documents all the logical
bitstreams contained in it. Tries to be tolerant of logical
bitstream sections that are truncated/woogie.
return: -1) error
0) OK
*/
int ov_open_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
ov_callbacks callbacks){
int ret=_ov_open1(f,vf,initial,ibytes,callbacks);
if(ret)return ret;
return _ov_open2(vf);
}
int ov_open(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
ov_callbacks callbacks = {
(size_t (*)(void *, size_t, size_t, void *)) fread,
(int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
(int (*)(void *)) fclose,
(long (*)(void *)) ftell
};
return ov_open_callbacks((void *)f, vf, initial, ibytes, callbacks);
}
int ov_fopen(char *path,OggVorbis_File *vf){
int ret;
FILE *f = fopen(path,"rb");
if(!f) return -1;
ret = ov_open(f,vf,NULL,0);
if(ret) fclose(f);
return ret;
}
/* cheap hack for game usage where downsampling is desirable; there's
no need for SRC as we can just do it cheaply in libvorbis. */
int ov_halfrate(OggVorbis_File *vf,int flag){
int i;
if(vf->vi==NULL)return OV_EINVAL;
if(!vf->seekable)return OV_EINVAL;
if(vf->ready_state>=STREAMSET)
_decode_clear(vf); /* clear out stream state; later on libvorbis
will be able to swap this on the fly, but
for now dumping the decode machine is needed
to reinit the MDCT lookups. 1.1 libvorbis
is planned to be able to switch on the fly */
for(i=0;i<vf->links;i++){
if(vorbis_synthesis_halfrate(vf->vi+i,flag)){
ov_halfrate(vf,0);
return OV_EINVAL;
}
}
return 0;
}
int ov_halfrate_p(OggVorbis_File *vf){
if(vf->vi==NULL)return OV_EINVAL;
return vorbis_synthesis_halfrate_p(vf->vi);
}
/* Only partially open the vorbis file; test for Vorbisness, and load
the headers for the first chain. Do not seek (although test for
seekability). Use ov_test_open to finish opening the file, else
ov_clear to close/free it. Same return codes as open. */
int ov_test_callbacks(void *f,OggVorbis_File *vf,char *initial,long ibytes,
ov_callbacks callbacks)
{
return _ov_open1(f,vf,initial,ibytes,callbacks);
}
int ov_test(FILE *f,OggVorbis_File *vf,char *initial,long ibytes){
ov_callbacks callbacks = {
(size_t (*)(void *, size_t, size_t, void *)) fread,
(int (*)(void *, ogg_int64_t, int)) _fseek64_wrap,
(int (*)(void *)) fclose,
(long (*)(void *)) ftell
};
return ov_test_callbacks((void *)f, vf, initial, ibytes, callbacks);
}
int ov_test_open(OggVorbis_File *vf){
if(vf->ready_state!=PARTOPEN)return(OV_EINVAL);
return _ov_open2(vf);
}
/* How many logical bitstreams in this physical bitstream? */
long ov_streams(OggVorbis_File *vf){
return vf->links;
}
/* Is the FILE * associated with vf seekable? */
long ov_seekable(OggVorbis_File *vf){
return vf->seekable;
}
/* returns the bitrate for a given logical bitstream or the entire
physical bitstream. If the file is open for random access, it will
find the *actual* average bitrate. If the file is streaming, it
returns the nominal bitrate (if set) else the average of the
upper/lower bounds (if set) else -1 (unset).
If you want the actual bitrate field settings, get them from the
vorbis_info structs */
long ov_bitrate(OggVorbis_File *vf,int i){
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(i>=vf->links)return(OV_EINVAL);
if(!vf->seekable && i!=0)return(ov_bitrate(vf,0));
if(i<0){
ogg_int64_t bits=0;
int i;
float br;
for(i=0;i<vf->links;i++)
bits+=(vf->offsets[i+1]-vf->dataoffsets[i])*8;
/* This once read: return(rint(bits/ov_time_total(vf,-1)));
* gcc 3.x on x86 miscompiled this at optimisation level 2 and above,
* so this is slightly transformed to make it work.
*/
br = bits/ov_time_total(vf,-1);
return(rint(br));
}else{
if(vf->seekable){
/* return the actual bitrate */
return(rint((vf->offsets[i+1]-vf->dataoffsets[i])*8/ov_time_total(vf,i)));
}else{
/* return nominal if set */
if(vf->vi[i].bitrate_nominal>0){
return vf->vi[i].bitrate_nominal;
}else{
if(vf->vi[i].bitrate_upper>0){
if(vf->vi[i].bitrate_lower>0){
return (vf->vi[i].bitrate_upper+vf->vi[i].bitrate_lower)/2;
}else{
return vf->vi[i].bitrate_upper;
}
}
return(OV_FALSE);
}
}
}
}
/* returns the actual bitrate since last call. returns -1 if no
additional data to offer since last call (or at beginning of stream),
EINVAL if stream is only partially open
*/
long ov_bitrate_instant(OggVorbis_File *vf){
int link=(vf->seekable?vf->current_link:0);
long ret;
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(vf->samptrack==0)return(OV_FALSE);
ret=vf->bittrack/vf->samptrack*vf->vi[link].rate+.5;
vf->bittrack=0.f;
vf->samptrack=0.f;
return(ret);
}
/* Guess */
long ov_serialnumber(OggVorbis_File *vf,int i){
if(i>=vf->links)return(ov_serialnumber(vf,vf->links-1));
if(!vf->seekable && i>=0)return(ov_serialnumber(vf,-1));
if(i<0){
return(vf->current_serialno);
}else{
return(vf->serialnos[i]);
}
}
/* returns: total raw (compressed) length of content if i==-1
raw (compressed) length of that logical bitstream for i==0 to n
OV_EINVAL if the stream is not seekable (we can't know the length)
or if stream is only partially open
*/
ogg_int64_t ov_raw_total(OggVorbis_File *vf,int i){
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
if(i<0){
ogg_int64_t acc=0;
int i;
for(i=0;i<vf->links;i++)
acc+=ov_raw_total(vf,i);
return(acc);
}else{
return(vf->offsets[i+1]-vf->offsets[i]);
}
}
/* returns: total PCM length (samples) of content if i==-1 PCM length
(samples) of that logical bitstream for i==0 to n
OV_EINVAL if the stream is not seekable (we can't know the
length) or only partially open
*/
ogg_int64_t ov_pcm_total(OggVorbis_File *vf,int i){
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
if(i<0){
ogg_int64_t acc=0;
int i;
for(i=0;i<vf->links;i++)
acc+=ov_pcm_total(vf,i);
return(acc);
}else{
return(vf->pcmlengths[i*2+1]);
}
}
/* returns: total seconds of content if i==-1
seconds in that logical bitstream for i==0 to n
OV_EINVAL if the stream is not seekable (we can't know the
length) or only partially open
*/
double ov_time_total(OggVorbis_File *vf,int i){
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable || i>=vf->links)return(OV_EINVAL);
if(i<0){
double acc=0;
int i;
for(i=0;i<vf->links;i++)
acc+=ov_time_total(vf,i);
return(acc);
}else{
return((double)(vf->pcmlengths[i*2+1])/vf->vi[i].rate);
}
}
/* seek to an offset relative to the *compressed* data. This also
scans packets to update the PCM cursor. It will cross a logical
bitstream boundary, but only if it can't get any packets out of the
tail of the bitstream we seek to (so no surprises).
returns zero on success, nonzero on failure */
int ov_raw_seek(OggVorbis_File *vf,ogg_int64_t pos){
ogg_stream_state work_os;
int ret;
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable)
return(OV_ENOSEEK); /* don't dump machine if we can't seek */
if(pos<0 || pos>vf->end)return(OV_EINVAL);
/* don't yet clear out decoding machine (if it's initialized), in
the case we're in the same link. Restart the decode lapping, and
let _fetch_and_process_packet deal with a potential bitstream
boundary */
vf->pcm_offset=-1;
ogg_stream_reset_serialno(&vf->os,
vf->current_serialno); /* must set serialno */
vorbis_synthesis_restart(&vf->vd);
ret=_seek_helper(vf,pos);
if(ret)goto seek_error;
/* we need to make sure the pcm_offset is set, but we don't want to
advance the raw cursor past good packets just to get to the first
with a granulepos. That's not equivalent behavior to beginning
decoding as immediately after the seek position as possible.
So, a hack. We use two stream states; a local scratch state and
the shared vf->os stream state. We use the local state to
scan, and the shared state as a buffer for later decode.
Unfortuantely, on the last page we still advance to last packet
because the granulepos on the last page is not necessarily on a
packet boundary, and we need to make sure the granpos is
correct.
*/
{
ogg_page og;
ogg_packet op;
int lastblock=0;
int accblock=0;
int thisblock=0;
int eosflag=0;
ogg_stream_init(&work_os,vf->current_serialno); /* get the memory ready */
ogg_stream_reset(&work_os); /* eliminate the spurious OV_HOLE
return from not necessarily
starting from the beginning */
while(1){
if(vf->ready_state>=STREAMSET){
/* snarf/scan a packet if we can */
int result=ogg_stream_packetout(&work_os,&op);
if(result>0){
if(vf->vi[vf->current_link].codec_setup){
thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
if(thisblock<0){
ogg_stream_packetout(&vf->os,NULL);
thisblock=0;
}else{
if(eosflag)
ogg_stream_packetout(&vf->os,NULL);
else
if(lastblock)accblock+=(lastblock+thisblock)>>2;
}
if(op.granulepos!=-1){
int i,link=vf->current_link;
ogg_int64_t granulepos=op.granulepos-vf->pcmlengths[link*2];
if(granulepos<0)granulepos=0;
for(i=0;i<link;i++)
granulepos+=vf->pcmlengths[i*2+1];
vf->pcm_offset=granulepos-accblock;
break;
}
lastblock=thisblock;
continue;
}else
ogg_stream_packetout(&vf->os,NULL);
}
}
if(!lastblock){
if(_get_next_page(vf,&og,-1)<0){
vf->pcm_offset=ov_pcm_total(vf,-1);
break;
}
}else{
/* huh? Bogus stream with packets but no granulepos */
vf->pcm_offset=-1;
break;
}
/* has our decoding just traversed a bitstream boundary? */
if(vf->ready_state>=STREAMSET){
if(vf->current_serialno!=ogg_page_serialno(&og)){
/* two possibilities:
1) our decoding just traversed a bitstream boundary
2) another stream is multiplexed into this logical section? */
if(ogg_page_bos(&og)){
/* we traversed */
_decode_clear(vf); /* clear out stream state */
ogg_stream_clear(&work_os);
} /* else, do nothing; next loop will scoop another page */
}
}
if(vf->ready_state<STREAMSET){
int link;
long serialno = ogg_page_serialno(&og);
for(link=0;link<vf->links;link++)
if(vf->serialnos[link]==serialno)break;
if(link==vf->links) continue; /* not the desired Vorbis
bitstream section; keep
trying */
vf->current_link=link;
vf->current_serialno=serialno;
ogg_stream_reset_serialno(&vf->os,serialno);
ogg_stream_reset_serialno(&work_os,serialno);
vf->ready_state=STREAMSET;
}
ogg_stream_pagein(&vf->os,&og);
ogg_stream_pagein(&work_os,&og);
eosflag=ogg_page_eos(&og);
}
}
ogg_stream_clear(&work_os);
vf->bittrack=0.f;
vf->samptrack=0.f;
return(0);
seek_error:
/* dump the machine so we're in a known state */
vf->pcm_offset=-1;
ogg_stream_clear(&work_os);
_decode_clear(vf);
return OV_EBADLINK;
}
/* Page granularity seek (faster than sample granularity because we
don't do the last bit of decode to find a specific sample).
Seek to the last [granule marked] page preceeding the specified pos
location, such that decoding past the returned point will quickly
arrive at the requested position. */
int ov_pcm_seek_page(OggVorbis_File *vf,ogg_int64_t pos){
int link=-1;
ogg_int64_t result=0;
ogg_int64_t total=ov_pcm_total(vf,-1);
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable)return(OV_ENOSEEK);
if(pos<0 || pos>total)return(OV_EINVAL);
/* which bitstream section does this pcm offset occur in? */
for(link=vf->links-1;link>=0;link--){
total-=vf->pcmlengths[link*2+1];
if(pos>=total)break;
}
/* search within the logical bitstream for the page with the highest
pcm_pos preceeding (or equal to) pos. There is a danger here;
missing pages or incorrect frame number information in the
bitstream could make our task impossible. Account for that (it
would be an error condition) */
/* new search algorithm by HB (Nicholas Vinen) */
{
ogg_int64_t end=vf->offsets[link+1];
ogg_int64_t begin=vf->offsets[link];
ogg_int64_t begintime = vf->pcmlengths[link*2];
ogg_int64_t endtime = vf->pcmlengths[link*2+1]+begintime;
ogg_int64_t target=pos-total+begintime;
ogg_int64_t best=begin;
ogg_page og;
while(begin<end){
ogg_int64_t bisect;
if(end-begin<CHUNKSIZE){
bisect=begin;
}else{
/* take a (pretty decent) guess. */
bisect=begin +
(target-begintime)*(end-begin)/(endtime-begintime) - CHUNKSIZE;
if(bisect<=begin)
bisect=begin+1;
}
result=_seek_helper(vf,bisect);
if(result) goto seek_error;
while(begin<end){
result=_get_next_page(vf,&og,end-vf->offset);
if(result==OV_EREAD) goto seek_error;
if(result<0){
if(bisect<=begin+1)
end=begin; /* found it */
else{
if(bisect==0) goto seek_error;
bisect-=CHUNKSIZE;
if(bisect<=begin)bisect=begin+1;
result=_seek_helper(vf,bisect);
if(result) goto seek_error;
}
}else{
ogg_int64_t granulepos;
if(ogg_page_serialno(&og)!=vf->serialnos[link])
continue;
granulepos=ogg_page_granulepos(&og);
if(granulepos==-1)continue;
if(granulepos<target){
best=result; /* raw offset of packet with granulepos */
begin=vf->offset; /* raw offset of next page */
begintime=granulepos;
if(target-begintime>44100)break;
bisect=begin; /* *not* begin + 1 */
}else{
if(bisect<=begin+1)
end=begin; /* found it */
else{
if(end==vf->offset){ /* we're pretty close - we'd be stuck in */
end=result;
bisect-=CHUNKSIZE; /* an endless loop otherwise. */
if(bisect<=begin)bisect=begin+1;
result=_seek_helper(vf,bisect);
if(result) goto seek_error;
}else{
end=bisect;
endtime=granulepos;
break;
}
}
}
}
}
}
/* found our page. seek to it, update pcm offset. Easier case than
raw_seek, don't keep packets preceeding granulepos. */
{
ogg_page og;
ogg_packet op;
/* seek */
result=_seek_helper(vf,best);
vf->pcm_offset=-1;
if(result) goto seek_error;
result=_get_next_page(vf,&og,-1);
if(result<0) goto seek_error;
if(link!=vf->current_link){
/* Different link; dump entire decode machine */
_decode_clear(vf);
vf->current_link=link;
vf->current_serialno=vf->serialnos[link];
vf->ready_state=STREAMSET;
}else{
vorbis_synthesis_restart(&vf->vd);
}
ogg_stream_reset_serialno(&vf->os,vf->current_serialno);
ogg_stream_pagein(&vf->os,&og);
/* pull out all but last packet; the one with granulepos */
while(1){
result=ogg_stream_packetpeek(&vf->os,&op);
if(result==0){
/* !!! the packet finishing this page originated on a
preceeding page. Keep fetching previous pages until we
get one with a granulepos or without the 'continued' flag
set. Then just use raw_seek for simplicity. */
result=_seek_helper(vf,best);
if(result<0) goto seek_error;
while(1){
result=_get_prev_page(vf,&og);
if(result<0) goto seek_error;
if(ogg_page_serialno(&og)==vf->current_serialno &&
(ogg_page_granulepos(&og)>-1 ||
!ogg_page_continued(&og))){
return ov_raw_seek(vf,result);
}
vf->offset=result;
}
}
if(result<0){
result = OV_EBADPACKET;
goto seek_error;
}
if(op.granulepos!=-1){
vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
if(vf->pcm_offset<0)vf->pcm_offset=0;
vf->pcm_offset+=total;
break;
}else
result=ogg_stream_packetout(&vf->os,NULL);
}
}
}
/* verify result */
if(vf->pcm_offset>pos || pos>ov_pcm_total(vf,-1)){
result=OV_EFAULT;
goto seek_error;
}
vf->bittrack=0.f;
vf->samptrack=0.f;
return(0);
seek_error:
/* dump machine so we're in a known state */
vf->pcm_offset=-1;
_decode_clear(vf);
return (int)result;
}
/* seek to a sample offset relative to the decompressed pcm stream
returns zero on success, nonzero on failure */
int ov_pcm_seek(OggVorbis_File *vf,ogg_int64_t pos){
int thisblock,lastblock=0;
int ret=ov_pcm_seek_page(vf,pos);
if(ret<0)return(ret);
if((ret=_make_decode_ready(vf)))return ret;
/* discard leading packets we don't need for the lapping of the
position we want; don't decode them */
while(1){
ogg_packet op;
ogg_page og;
int ret=ogg_stream_packetpeek(&vf->os,&op);
if(ret>0){
thisblock=vorbis_packet_blocksize(vf->vi+vf->current_link,&op);
if(thisblock<0){
ogg_stream_packetout(&vf->os,NULL);
continue; /* non audio packet */
}
if(lastblock)vf->pcm_offset+=(lastblock+thisblock)>>2;
if(vf->pcm_offset+((thisblock+
vorbis_info_blocksize(vf->vi,1))>>2)>=pos)break;
/* remove the packet from packet queue and track its granulepos */
ogg_stream_packetout(&vf->os,NULL);
vorbis_synthesis_trackonly(&vf->vb,&op); /* set up a vb with
only tracking, no
pcm_decode */
vorbis_synthesis_blockin(&vf->vd,&vf->vb);
/* end of logical stream case is hard, especially with exact
length positioning. */
if(op.granulepos>-1){
int i;
/* always believe the stream markers */
vf->pcm_offset=op.granulepos-vf->pcmlengths[vf->current_link*2];
if(vf->pcm_offset<0)vf->pcm_offset=0;
for(i=0;i<vf->current_link;i++)
vf->pcm_offset+=vf->pcmlengths[i*2+1];
}
lastblock=thisblock;
}else{
if(ret<0 && ret!=OV_HOLE)break;
/* suck in a new page */
if(_get_next_page(vf,&og,-1)<0)break;
if(ogg_page_bos(&og))_decode_clear(vf);
if(vf->ready_state<STREAMSET){
long serialno=ogg_page_serialno(&og);
int link;
for(link=0;link<vf->links;link++)
if(vf->serialnos[link]==serialno)break;
if(link==vf->links) continue;
vf->current_link=link;
vf->ready_state=STREAMSET;
vf->current_serialno=ogg_page_serialno(&og);
ogg_stream_reset_serialno(&vf->os,serialno);
ret=_make_decode_ready(vf);
if(ret)return ret;
lastblock=0;
}
ogg_stream_pagein(&vf->os,&og);
}
}
vf->bittrack=0.f;
vf->samptrack=0.f;
/* discard samples until we reach the desired position. Crossing a
logical bitstream boundary with abandon is OK. */
while(vf->pcm_offset<pos){
ogg_int64_t target=pos-vf->pcm_offset;
long samples=vorbis_synthesis_pcmout(&vf->vd,NULL);
if(samples>target)samples=target;
vorbis_synthesis_read(&vf->vd,samples);
vf->pcm_offset+=samples;
if(samples<target)
if(_fetch_and_process_packet(vf,NULL,1,1)<=0)
vf->pcm_offset=ov_pcm_total(vf,-1); /* eof */
}
return 0;
}
/* seek to a playback time relative to the decompressed pcm stream
returns zero on success, nonzero on failure */
int ov_time_seek(OggVorbis_File *vf,double seconds){
/* translate time to PCM position and call ov_pcm_seek */
int link=-1;
ogg_int64_t pcm_total=0;
double time_total=0.;
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable)return(OV_ENOSEEK);
if(seconds<0)return(OV_EINVAL);
/* which bitstream section does this time offset occur in? */
for(link=0;link<vf->links;link++){
double addsec = ov_time_total(vf,link);
if(seconds<time_total+addsec)break;
time_total+=addsec;
pcm_total+=vf->pcmlengths[link*2+1];
}
if(link==vf->links)return(OV_EINVAL);
/* enough information to convert time offset to pcm offset */
{
ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
return(ov_pcm_seek(vf,target));
}
}
/* page-granularity version of ov_time_seek
returns zero on success, nonzero on failure */
int ov_time_seek_page(OggVorbis_File *vf,double seconds){
/* translate time to PCM position and call ov_pcm_seek */
int link=-1;
ogg_int64_t pcm_total=0;
double time_total=0.;
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(!vf->seekable)return(OV_ENOSEEK);
if(seconds<0)return(OV_EINVAL);
/* which bitstream section does this time offset occur in? */
for(link=0;link<vf->links;link++){
double addsec = ov_time_total(vf,link);
if(seconds<time_total+addsec)break;
time_total+=addsec;
pcm_total+=vf->pcmlengths[link*2+1];
}
if(link==vf->links)return(OV_EINVAL);
/* enough information to convert time offset to pcm offset */
{
ogg_int64_t target=pcm_total+(seconds-time_total)*vf->vi[link].rate;
return(ov_pcm_seek_page(vf,target));
}
}
/* tell the current stream offset cursor. Note that seek followed by
tell will likely not give the set offset due to caching */
ogg_int64_t ov_raw_tell(OggVorbis_File *vf){
if(vf->ready_state<OPENED)return(OV_EINVAL);
return(vf->offset);
}
/* return PCM offset (sample) of next PCM sample to be read */
ogg_int64_t ov_pcm_tell(OggVorbis_File *vf){
if(vf->ready_state<OPENED)return(OV_EINVAL);
return(vf->pcm_offset);
}
/* return time offset (seconds) of next PCM sample to be read */
double ov_time_tell(OggVorbis_File *vf){
int link=0;
ogg_int64_t pcm_total=0;
double time_total=0.f;
if(vf->ready_state<OPENED)return(OV_EINVAL);
if(vf->seekable){
pcm_total=ov_pcm_total(vf,-1);
time_total=ov_time_total(vf,-1);
/* which bitstream section does this time offset occur in? */
for(link=vf->links-1;link>=0;link--){
pcm_total-=vf->pcmlengths[link*2+1];
time_total-=ov_time_total(vf,link);
if(vf->pcm_offset>=pcm_total)break;
}
}
return((double)time_total+(double)(vf->pcm_offset-pcm_total)/vf->vi[link].rate);
}
/* link: -1) return the vorbis_info struct for the bitstream section
currently being decoded
0-n) to request information for a specific bitstream section
In the case of a non-seekable bitstream, any call returns the
current bitstream. NULL in the case that the machine is not
initialized */
vorbis_info *ov_info(OggVorbis_File *vf,int link){
if(vf->seekable){
if(link<0)
if(vf->ready_state>=STREAMSET)
return vf->vi+vf->current_link;
else
return vf->vi;
else
if(link>=vf->links)
return NULL;
else
return vf->vi+link;
}else{
return vf->vi;
}
}
/* grr, strong typing, grr, no templates/inheritence, grr */
vorbis_comment *ov_comment(OggVorbis_File *vf,int link){
if(vf->seekable){
if(link<0)
if(vf->ready_state>=STREAMSET)
return vf->vc+vf->current_link;
else
return vf->vc;
else
if(link>=vf->links)
return NULL;
else
return vf->vc+link;
}else{
return vf->vc;
}
}
static int host_is_big_endian() {
ogg_int32_t pattern = 0xfeedface; /* deadbeef */
unsigned char *bytewise = (unsigned char *)&pattern;
if (bytewise[0] == 0xfe) return 1;
return 0;
}
/* up to this point, everything could more or less hide the multiple
logical bitstream nature of chaining from the toplevel application
if the toplevel application didn't particularly care. However, at
the point that we actually read audio back, the multiple-section
nature must surface: Multiple bitstream sections do not necessarily
have to have the same number of channels or sampling rate.
ov_read returns the sequential logical bitstream number currently
being decoded along with the PCM data in order that the toplevel
application can take action on channel/sample rate changes. This
number will be incremented even for streamed (non-seekable) streams
(for seekable streams, it represents the actual logical bitstream
index within the physical bitstream. Note that the accessor
functions above are aware of this dichotomy).
input values: buffer) a buffer to hold packed PCM data for return
length) the byte length requested to be placed into buffer
bigendianp) should the data be packed LSB first (0) or
MSB first (1)
word) word size for output. currently 1 (byte) or
2 (16 bit short)
return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
0) EOF
n) number of bytes of PCM actually returned. The
below works on a packet-by-packet basis, so the
return length is not related to the 'length' passed
in, just guaranteed to fit.
*section) set to the logical bitstream number */
long ov_read(OggVorbis_File *vf,char *buffer,int length,
int bigendianp,int word,int sgned,int *bitstream){
int i,j;
int host_endian = host_is_big_endian();
float **pcm;
long samples;
if(vf->ready_state<OPENED)return(OV_EINVAL);
while(1){
if(vf->ready_state==INITSET){
samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
if(samples)break;
}
/* suck in another packet */
{
int ret=_fetch_and_process_packet(vf,NULL,1,1);
if(ret==OV_EOF)
return(0);
if(ret<=0)
return(ret);
}
}
if(samples>0){
/* yay! proceed to pack data into the byte buffer */
long channels=ov_info(vf,-1)->channels;
long bytespersample=word * channels;
vorbis_fpu_control fpu;
if(samples>length/bytespersample)samples=length/bytespersample;
if(samples <= 0)
return OV_EINVAL;
/* a tight loop to pack each size */
{
int val;
if(word==1){
int off=(sgned?0:128);
vorbis_fpu_setround(&fpu);
for(j=0;j<samples;j++)
for(i=0;i<channels;i++){
val=vorbis_ftoi(pcm[i][j]*128.f);
if(val>127)val=127;
else if(val<-128)val=-128;
*buffer++=val+off;
}
vorbis_fpu_restore(fpu);
}else{
int off=(sgned?0:32768);
if(host_endian==bigendianp){
if(sgned){
vorbis_fpu_setround(&fpu);
for(i=0;i<channels;i++) { /* It's faster in this order */
float *src=pcm[i];
short *dest=((short *)buffer)+i;
for(j=0;j<samples;j++) {
val=vorbis_ftoi(src[j]*32768.f);
if(val>32767)val=32767;
else if(val<-32768)val=-32768;
*dest=val;
dest+=channels;
}
}
vorbis_fpu_restore(fpu);
}else{
vorbis_fpu_setround(&fpu);
for(i=0;i<channels;i++) {
float *src=pcm[i];
short *dest=((short *)buffer)+i;
for(j=0;j<samples;j++) {
val=vorbis_ftoi(src[j]*32768.f);
if(val>32767)val=32767;
else if(val<-32768)val=-32768;
*dest=val+off;
dest+=channels;
}
}
vorbis_fpu_restore(fpu);
}
}else if(bigendianp){
vorbis_fpu_setround(&fpu);
for(j=0;j<samples;j++)
for(i=0;i<channels;i++){
val=vorbis_ftoi(pcm[i][j]*32768.f);
if(val>32767)val=32767;
else if(val<-32768)val=-32768;
val+=off;
*buffer++=(val>>8);
*buffer++=(val&0xff);
}
vorbis_fpu_restore(fpu);
}else{
int val;
vorbis_fpu_setround(&fpu);
for(j=0;j<samples;j++)
for(i=0;i<channels;i++){
val=vorbis_ftoi(pcm[i][j]*32768.f);
if(val>32767)val=32767;
else if(val<-32768)val=-32768;
val+=off;
*buffer++=(val&0xff);
*buffer++=(val>>8);
}
vorbis_fpu_restore(fpu);
}
}
}
vorbis_synthesis_read(&vf->vd,samples);
vf->pcm_offset+=samples;
if(bitstream)*bitstream=vf->current_link;
return(samples*bytespersample);
}else{
return(samples);
}
}
/* input values: pcm_channels) a float vector per channel of output
length) the sample length being read by the app
return values: <0) error/hole in data (OV_HOLE), partial open (OV_EINVAL)
0) EOF
n) number of samples of PCM actually returned. The
below works on a packet-by-packet basis, so the
return length is not related to the 'length' passed
in, just guaranteed to fit.
*section) set to the logical bitstream number */
long ov_read_float(OggVorbis_File *vf,float ***pcm_channels,int length,
int *bitstream){
if(vf->ready_state<OPENED)return(OV_EINVAL);
while(1){
if(vf->ready_state==INITSET){
float **pcm;
long samples=vorbis_synthesis_pcmout(&vf->vd,&pcm);
if(samples){
if(pcm_channels)*pcm_channels=pcm;
if(samples>length)samples=length;
vorbis_synthesis_read(&vf->vd,samples);
vf->pcm_offset+=samples;
if(bitstream)*bitstream=vf->current_link;
return samples;
}
}
/* suck in another packet */
{
int ret=_fetch_and_process_packet(vf,NULL,1,1);
if(ret==OV_EOF)return(0);
if(ret<=0)return(ret);
}
}
}
extern float *vorbis_window(vorbis_dsp_state *v,int W);
extern void _analysis_output_always(char *base,int i,float *v,int n,int bark,int dB,
ogg_int64_t off);
static void _ov_splice(float **pcm,float **lappcm,
int n1, int n2,
int ch1, int ch2,
float *w1, float *w2){
int i,j;
float *w=w1;
int n=n1;
if(n1>n2){
n=n2;
w=w2;
}
/* splice */
for(j=0;j<ch1 && j<ch2;j++){
float *s=lappcm[j];
float *d=pcm[j];
for(i=0;i<n;i++){
float wd=w[i]*w[i];
float ws=1.-wd;
d[i]=d[i]*wd + s[i]*ws;
}
}
/* window from zero */
for(;j<ch2;j++){
float *d=pcm[j];
for(i=0;i<n;i++){
float wd=w[i]*w[i];
d[i]=d[i]*wd;
}
}
}
/* make sure vf is INITSET */
static int _ov_initset(OggVorbis_File *vf){
while(1){
if(vf->ready_state==INITSET)break;
/* suck in another packet */
{
int ret=_fetch_and_process_packet(vf,NULL,1,0);
if(ret<0 && ret!=OV_HOLE)return(ret);
}
}
return 0;
}
/* make sure vf is INITSET and that we have a primed buffer; if
we're crosslapping at a stream section boundary, this also makes
sure we're sanity checking against the right stream information */
static int _ov_initprime(OggVorbis_File *vf){
vorbis_dsp_state *vd=&vf->vd;
while(1){
if(vf->ready_state==INITSET)
if(vorbis_synthesis_pcmout(vd,NULL))break;
/* suck in another packet */
{
int ret=_fetch_and_process_packet(vf,NULL,1,0);
if(ret<0 && ret!=OV_HOLE)return(ret);
}
}
return 0;
}
/* grab enough data for lapping from vf; this may be in the form of
unreturned, already-decoded pcm, remaining PCM we will need to
decode, or synthetic postextrapolation from last packets. */
static void _ov_getlap(OggVorbis_File *vf,vorbis_info *vi,vorbis_dsp_state *vd,
float **lappcm,int lapsize){
int lapcount=0,i;
float **pcm;
/* try first to decode the lapping data */
while(lapcount<lapsize){
int samples=vorbis_synthesis_pcmout(vd,&pcm);
if(samples){
if(samples>lapsize-lapcount)samples=lapsize-lapcount;
for(i=0;i<vi->channels;i++)
memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
lapcount+=samples;
vorbis_synthesis_read(vd,samples);
}else{
/* suck in another packet */
int ret=_fetch_and_process_packet(vf,NULL,1,0); /* do *not* span */
if(ret==OV_EOF)break;
}
}
if(lapcount<lapsize){
/* failed to get lapping data from normal decode; pry it from the
postextrapolation buffering, or the second half of the MDCT
from the last packet */
int samples=vorbis_synthesis_lapout(&vf->vd,&pcm);
if(samples==0){
for(i=0;i<vi->channels;i++)
memset(lappcm[i]+lapcount,0,sizeof(**pcm)*lapsize-lapcount);
lapcount=lapsize;
}else{
if(samples>lapsize-lapcount)samples=lapsize-lapcount;
for(i=0;i<vi->channels;i++)
memcpy(lappcm[i]+lapcount,pcm[i],sizeof(**pcm)*samples);
lapcount+=samples;
}
}
}
/* this sets up crosslapping of a sample by using trailing data from
sample 1 and lapping it into the windowing buffer of sample 2 */
int ov_crosslap(OggVorbis_File *vf1, OggVorbis_File *vf2){
vorbis_info *vi1,*vi2;
float **lappcm;
float **pcm;
float *w1,*w2;
int n1,n2,i,ret,hs1,hs2;
if(vf1==vf2)return(0); /* degenerate case */
if(vf1->ready_state<OPENED)return(OV_EINVAL);
if(vf2->ready_state<OPENED)return(OV_EINVAL);
/* the relevant overlap buffers must be pre-checked and pre-primed
before looking at settings in the event that priming would cross
a bitstream boundary. So, do it now */
ret=_ov_initset(vf1);
if(ret)return(ret);
ret=_ov_initprime(vf2);
if(ret)return(ret);
vi1=ov_info(vf1,-1);
vi2=ov_info(vf2,-1);
hs1=ov_halfrate_p(vf1);
hs2=ov_halfrate_p(vf2);
lappcm=alloca(sizeof(*lappcm)*vi1->channels);
n1=vorbis_info_blocksize(vi1,0)>>(1+hs1);
n2=vorbis_info_blocksize(vi2,0)>>(1+hs2);
w1=vorbis_window(&vf1->vd,0);
w2=vorbis_window(&vf2->vd,0);
for(i=0;i<vi1->channels;i++)
lappcm[i]=alloca(sizeof(**lappcm)*n1);
_ov_getlap(vf1,vi1,&vf1->vd,lappcm,n1);
/* have a lapping buffer from vf1; now to splice it into the lapping
buffer of vf2 */
/* consolidate and expose the buffer. */
vorbis_synthesis_lapout(&vf2->vd,&pcm);
_analysis_output_always("pcmL",0,pcm[0],n1*2,0,0,0);
_analysis_output_always("pcmR",0,pcm[1],n1*2,0,0,0);
/* splice */
_ov_splice(pcm,lappcm,n1,n2,vi1->channels,vi2->channels,w1,w2);
/* done */
return(0);
}
static int _ov_64_seek_lap(OggVorbis_File *vf,ogg_int64_t pos,
int (*localseek)(OggVorbis_File *,ogg_int64_t)){
vorbis_info *vi;
float **lappcm;
float **pcm;
float *w1,*w2;
int n1,n2,ch1,ch2,hs;
int i,ret;
if(vf->ready_state<OPENED)return(OV_EINVAL);
ret=_ov_initset(vf);
if(ret)return(ret);
vi=ov_info(vf,-1);
hs=ov_halfrate_p(vf);
ch1=vi->channels;
n1=vorbis_info_blocksize(vi,0)>>(1+hs);
w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
persistent; even if the decode state
from this link gets dumped, this
window array continues to exist */
lappcm=alloca(sizeof(*lappcm)*ch1);
for(i=0;i<ch1;i++)
lappcm[i]=alloca(sizeof(**lappcm)*n1);
_ov_getlap(vf,vi,&vf->vd,lappcm,n1);
/* have lapping data; seek and prime the buffer */
ret=localseek(vf,pos);
if(ret)return ret;
ret=_ov_initprime(vf);
if(ret)return(ret);
/* Guard against cross-link changes; they're perfectly legal */
vi=ov_info(vf,-1);
ch2=vi->channels;
n2=vorbis_info_blocksize(vi,0)>>(1+hs);
w2=vorbis_window(&vf->vd,0);
/* consolidate and expose the buffer. */
vorbis_synthesis_lapout(&vf->vd,&pcm);
/* splice */
_ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
/* done */
return(0);
}
int ov_raw_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
return _ov_64_seek_lap(vf,pos,ov_raw_seek);
}
int ov_pcm_seek_lap(OggVorbis_File *vf,ogg_int64_t pos){
return _ov_64_seek_lap(vf,pos,ov_pcm_seek);
}
int ov_pcm_seek_page_lap(OggVorbis_File *vf,ogg_int64_t pos){
return _ov_64_seek_lap(vf,pos,ov_pcm_seek_page);
}
static int _ov_d_seek_lap(OggVorbis_File *vf,double pos,
int (*localseek)(OggVorbis_File *,double)){
vorbis_info *vi;
float **lappcm;
float **pcm;
float *w1,*w2;
int n1,n2,ch1,ch2,hs;
int i,ret;
if(vf->ready_state<OPENED)return(OV_EINVAL);
ret=_ov_initset(vf);
if(ret)return(ret);
vi=ov_info(vf,-1);
hs=ov_halfrate_p(vf);
ch1=vi->channels;
n1=vorbis_info_blocksize(vi,0)>>(1+hs);
w1=vorbis_window(&vf->vd,0); /* window arrays from libvorbis are
persistent; even if the decode state
from this link gets dumped, this
window array continues to exist */
lappcm=alloca(sizeof(*lappcm)*ch1);
for(i=0;i<ch1;i++)
lappcm[i]=alloca(sizeof(**lappcm)*n1);
_ov_getlap(vf,vi,&vf->vd,lappcm,n1);
/* have lapping data; seek and prime the buffer */
ret=localseek(vf,pos);
if(ret)return ret;
ret=_ov_initprime(vf);
if(ret)return(ret);
/* Guard against cross-link changes; they're perfectly legal */
vi=ov_info(vf,-1);
ch2=vi->channels;
n2=vorbis_info_blocksize(vi,0)>>(1+hs);
w2=vorbis_window(&vf->vd,0);
/* consolidate and expose the buffer. */
vorbis_synthesis_lapout(&vf->vd,&pcm);
/* splice */
_ov_splice(pcm,lappcm,n1,n2,ch1,ch2,w1,w2);
/* done */
return(0);
}
int ov_time_seek_lap(OggVorbis_File *vf,double pos){
return _ov_d_seek_lap(vf,pos,ov_time_seek);
}
int ov_time_seek_page_lap(OggVorbis_File *vf,double pos){
return _ov_d_seek_lap(vf,pos,ov_time_seek_page);
}
|
gpl-3.0
|
rsn8887/scummvm
|
engines/titanic/carry/vision_centre.cpp
|
11
|
1837
|
/* 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/carry/vision_centre.h"
namespace Titanic {
BEGIN_MESSAGE_MAP(CVisionCentre, CBrain)
ON_MESSAGE(PuzzleSolvedMsg)
ON_MESSAGE(MouseButtonDownMsg)
ON_MESSAGE(MouseDragStartMsg)
END_MESSAGE_MAP()
void CVisionCentre::save(SimpleFile *file, int indent) {
file->writeNumberLine(1, indent);
CBrain::save(file, indent);
}
void CVisionCentre::load(SimpleFile *file) {
file->readNumber();
CBrain::load(file);
}
bool CVisionCentre::PuzzleSolvedMsg(CPuzzleSolvedMsg *msg) {
_canTake = true;
return true;
}
bool CVisionCentre::MouseButtonDownMsg(CMouseButtonDownMsg *msg) {
if (_canTake) {
return CBrain::MouseButtonDownMsg(msg);
} else {
petDisplayMessage(1, NICE_IF_TAKE_BUT_CANT);
return true;
}
}
bool CVisionCentre::MouseDragStartMsg(CMouseDragStartMsg *msg) {
if (_canTake) {
return CBrain::MouseDragStartMsg(msg);
} else {
petDisplayMessage(1, NICE_IF_TAKE_BUT_CANT);
return true;
}
}
} // End of namespace Titanic
|
gpl-3.0
|
AlienCowEatCake/ImageViewer
|
src/ThirdParty/Zstandard/zstd-1.5.2/contrib/pzstd/utils/test/RangeTest.cpp
|
13
|
2033
|
/*
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under both the BSD-style license (found in the
* LICENSE file in the root directory of this source tree) and the GPLv2 (found
* in the COPYING file in the root directory of this source tree).
*/
#include "utils/Range.h"
#include <gtest/gtest.h>
#include <string>
using namespace pzstd;
// Range is directly copied from folly.
// Just some sanity tests to make sure everything seems to work.
TEST(Range, Constructors) {
StringPiece empty;
EXPECT_TRUE(empty.empty());
EXPECT_EQ(0, empty.size());
std::string str = "hello";
{
Range<std::string::const_iterator> piece(str.begin(), str.end());
EXPECT_EQ(5, piece.size());
EXPECT_EQ('h', *piece.data());
EXPECT_EQ('o', *(piece.end() - 1));
}
{
StringPiece piece(str.data(), str.size());
EXPECT_EQ(5, piece.size());
EXPECT_EQ('h', *piece.data());
EXPECT_EQ('o', *(piece.end() - 1));
}
{
StringPiece piece(str);
EXPECT_EQ(5, piece.size());
EXPECT_EQ('h', *piece.data());
EXPECT_EQ('o', *(piece.end() - 1));
}
{
StringPiece piece(str.c_str());
EXPECT_EQ(5, piece.size());
EXPECT_EQ('h', *piece.data());
EXPECT_EQ('o', *(piece.end() - 1));
}
}
TEST(Range, Modifiers) {
StringPiece range("hello world");
ASSERT_EQ(11, range.size());
{
auto hello = range.subpiece(0, 5);
EXPECT_EQ(5, hello.size());
EXPECT_EQ('h', *hello.data());
EXPECT_EQ('o', *(hello.end() - 1));
}
{
auto hello = range;
hello.subtract(6);
EXPECT_EQ(5, hello.size());
EXPECT_EQ('h', *hello.data());
EXPECT_EQ('o', *(hello.end() - 1));
}
{
auto world = range;
world.advance(6);
EXPECT_EQ(5, world.size());
EXPECT_EQ('w', *world.data());
EXPECT_EQ('d', *(world.end() - 1));
}
std::string expected = "hello world";
EXPECT_EQ(expected, std::string(range.begin(), range.end()));
EXPECT_EQ(expected, std::string(range.data(), range.size()));
}
|
gpl-3.0
|
geminy/aidear
|
oss/linux/linux-4.7/drivers/media/pci/zoran/zoran_driver.c
|
527
|
75422
|
/*
* Zoran zr36057/zr36067 PCI controller driver, for the
* Pinnacle/Miro DC10/DC10+/DC30/DC30+, Iomega Buz, Linux
* Media Labs LML33/LML33R10.
*
* Copyright (C) 2000 Serguei Miridonov <mirsev@cicese.mx>
*
* Changes for BUZ by Wolfgang Scherr <scherr@net4you.net>
*
* Changes for DC10/DC30 by Laurent Pinchart <laurent.pinchart@skynet.be>
*
* Changes for LML33R10 by Maxim Yevtyushkin <max@linuxmedialabs.com>
*
* Changes for videodev2/v4l2 by Ronald Bultje <rbultje@ronald.bitfreak.net>
*
* Based on
*
* Miro DC10 driver
* Copyright (C) 1999 Wolfgang Scherr <scherr@net4you.net>
*
* Iomega Buz driver version 1.0
* Copyright (C) 1999 Rainer Johanni <Rainer@Johanni.de>
*
* buz.0.0.3
* Copyright (C) 1998 Dave Perks <dperks@ibm.net>
*
* bttv - Bt848 frame grabber driver
* Copyright (C) 1996,97,98 Ralph Metzler (rjkm@thp.uni-koeln.de)
* & Marcus Metzler (mocm@thp.uni-koeln.de)
*
*
* 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.
*/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/slab.h>
#include <linux/pci.h>
#include <linux/vmalloc.h>
#include <linux/wait.h>
#include <linux/interrupt.h>
#include <linux/i2c.h>
#include <linux/i2c-algo-bit.h>
#include <linux/spinlock.h>
#include <linux/videodev2.h>
#include <media/v4l2-common.h>
#include <media/v4l2-ioctl.h>
#include <media/v4l2-event.h>
#include "videocodec.h"
#include <asm/byteorder.h>
#include <asm/io.h>
#include <asm/uaccess.h>
#include <linux/proc_fs.h>
#include <linux/mutex.h>
#include "zoran.h"
#include "zoran_device.h"
#include "zoran_card.h"
const struct zoran_format zoran_formats[] = {
{
.name = "15-bit RGB LE",
.fourcc = V4L2_PIX_FMT_RGB555,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 15,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB555|ZR36057_VFESPFR_ErrDif|
ZR36057_VFESPFR_LittleEndian,
}, {
.name = "15-bit RGB BE",
.fourcc = V4L2_PIX_FMT_RGB555X,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 15,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB555|ZR36057_VFESPFR_ErrDif,
}, {
.name = "16-bit RGB LE",
.fourcc = V4L2_PIX_FMT_RGB565,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB565|ZR36057_VFESPFR_ErrDif|
ZR36057_VFESPFR_LittleEndian,
}, {
.name = "16-bit RGB BE",
.fourcc = V4L2_PIX_FMT_RGB565X,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB565|ZR36057_VFESPFR_ErrDif,
}, {
.name = "24-bit RGB",
.fourcc = V4L2_PIX_FMT_BGR24,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 24,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB888|ZR36057_VFESPFR_Pack24,
}, {
.name = "32-bit RGB LE",
.fourcc = V4L2_PIX_FMT_BGR32,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 32,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB888|ZR36057_VFESPFR_LittleEndian,
}, {
.name = "32-bit RGB BE",
.fourcc = V4L2_PIX_FMT_RGB32,
.colorspace = V4L2_COLORSPACE_SRGB,
.depth = 32,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_RGB888,
}, {
.name = "4:2:2, packed, YUYV",
.fourcc = V4L2_PIX_FMT_YUYV,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_YUV422,
}, {
.name = "4:2:2, packed, UYVY",
.fourcc = V4L2_PIX_FMT_UYVY,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.depth = 16,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_OVERLAY,
.vfespfr = ZR36057_VFESPFR_YUV422|ZR36057_VFESPFR_LittleEndian,
}, {
.name = "Hardware-encoded Motion-JPEG",
.fourcc = V4L2_PIX_FMT_MJPEG,
.colorspace = V4L2_COLORSPACE_SMPTE170M,
.depth = 0,
.flags = ZORAN_FORMAT_CAPTURE |
ZORAN_FORMAT_PLAYBACK |
ZORAN_FORMAT_COMPRESSED,
}
};
#define NUM_FORMATS ARRAY_SIZE(zoran_formats)
/* small helper function for calculating buffersizes for v4l2
* we calculate the nearest higher power-of-two, which
* will be the recommended buffersize */
static __u32
zoran_v4l2_calc_bufsize (struct zoran_jpg_settings *settings)
{
__u8 div = settings->VerDcm * settings->HorDcm * settings->TmpDcm;
__u32 num = (1024 * 512) / (div);
__u32 result = 2;
num--;
while (num) {
num >>= 1;
result <<= 1;
}
if (result > jpg_bufsize)
return jpg_bufsize;
if (result < 8192)
return 8192;
return result;
}
/* forward references */
static void v4l_fbuffer_free(struct zoran_fh *fh);
static void jpg_fbuffer_free(struct zoran_fh *fh);
/* Set mapping mode */
static void map_mode_raw(struct zoran_fh *fh)
{
fh->map_mode = ZORAN_MAP_MODE_RAW;
fh->buffers.buffer_size = v4l_bufsize;
fh->buffers.num_buffers = v4l_nbufs;
}
static void map_mode_jpg(struct zoran_fh *fh, int play)
{
fh->map_mode = play ? ZORAN_MAP_MODE_JPG_PLAY : ZORAN_MAP_MODE_JPG_REC;
fh->buffers.buffer_size = jpg_bufsize;
fh->buffers.num_buffers = jpg_nbufs;
}
static inline const char *mode_name(enum zoran_map_mode mode)
{
return mode == ZORAN_MAP_MODE_RAW ? "V4L" : "JPG";
}
/*
* Allocate the V4L grab buffers
*
* These have to be pysically contiguous.
*/
static int v4l_fbuffer_alloc(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, off;
unsigned char *mem;
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].v4l.fbuffer)
dprintk(2,
KERN_WARNING
"%s: %s - buffer %d already allocated!?\n",
ZR_DEVNAME(zr), __func__, i);
//udelay(20);
mem = kmalloc(fh->buffers.buffer_size,
GFP_KERNEL | __GFP_NOWARN);
if (!mem) {
dprintk(1,
KERN_ERR
"%s: %s - kmalloc for V4L buf %d failed\n",
ZR_DEVNAME(zr), __func__, i);
v4l_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].v4l.fbuffer = mem;
fh->buffers.buffer[i].v4l.fbuffer_phys = virt_to_phys(mem);
fh->buffers.buffer[i].v4l.fbuffer_bus = virt_to_bus(mem);
for (off = 0; off < fh->buffers.buffer_size;
off += PAGE_SIZE)
SetPageReserved(virt_to_page(mem + off));
dprintk(4,
KERN_INFO
"%s: %s - V4L frame %d mem 0x%lx (bus: 0x%llx)\n",
ZR_DEVNAME(zr), __func__, i, (unsigned long) mem,
(unsigned long long)virt_to_bus(mem));
}
fh->buffers.allocated = 1;
return 0;
}
/* free the V4L grab buffers */
static void v4l_fbuffer_free(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, off;
unsigned char *mem;
dprintk(4, KERN_INFO "%s: %s\n", ZR_DEVNAME(zr), __func__);
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (!fh->buffers.buffer[i].v4l.fbuffer)
continue;
mem = fh->buffers.buffer[i].v4l.fbuffer;
for (off = 0; off < fh->buffers.buffer_size;
off += PAGE_SIZE)
ClearPageReserved(virt_to_page(mem + off));
kfree(fh->buffers.buffer[i].v4l.fbuffer);
fh->buffers.buffer[i].v4l.fbuffer = NULL;
}
fh->buffers.allocated = 0;
}
/*
* Allocate the MJPEG grab buffers.
*
* If a Natoma chipset is present and this is a revision 1 zr36057,
* each MJPEG buffer needs to be physically contiguous.
* (RJ: This statement is from Dave Perks' original driver,
* I could never check it because I have a zr36067)
*
* RJ: The contents grab buffers needs never be accessed in the driver.
* Therefore there is no need to allocate them with vmalloc in order
* to get a contiguous virtual memory space.
* I don't understand why many other drivers first allocate them with
* vmalloc (which uses internally also get_zeroed_page, but delivers you
* virtual addresses) and then again have to make a lot of efforts
* to get the physical address.
*
* Ben Capper:
* On big-endian architectures (such as ppc) some extra steps
* are needed. When reading and writing to the stat_com array
* and fragment buffers, the device expects to see little-
* endian values. The use of cpu_to_le32() and le32_to_cpu()
* in this function (and one or two others in zoran_device.c)
* ensure that these values are always stored in little-endian
* form, regardless of architecture. The zr36057 does Very Bad
* Things on big endian architectures if the stat_com array
* and fragment buffers are not little-endian.
*/
static int jpg_fbuffer_alloc(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, j, off;
u8 *mem;
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].jpg.frag_tab)
dprintk(2,
KERN_WARNING
"%s: %s - buffer %d already allocated!?\n",
ZR_DEVNAME(zr), __func__, i);
/* Allocate fragment table for this buffer */
mem = (void *)get_zeroed_page(GFP_KERNEL);
if (!mem) {
dprintk(1,
KERN_ERR
"%s: %s - get_zeroed_page (frag_tab) failed for buffer %d\n",
ZR_DEVNAME(zr), __func__, i);
jpg_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].jpg.frag_tab = (__le32 *)mem;
fh->buffers.buffer[i].jpg.frag_tab_bus = virt_to_bus(mem);
if (fh->buffers.need_contiguous) {
mem = kmalloc(fh->buffers.buffer_size, GFP_KERNEL);
if (mem == NULL) {
dprintk(1,
KERN_ERR
"%s: %s - kmalloc failed for buffer %d\n",
ZR_DEVNAME(zr), __func__, i);
jpg_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].jpg.frag_tab[0] =
cpu_to_le32(virt_to_bus(mem));
fh->buffers.buffer[i].jpg.frag_tab[1] =
cpu_to_le32((fh->buffers.buffer_size >> 1) | 1);
for (off = 0; off < fh->buffers.buffer_size; off += PAGE_SIZE)
SetPageReserved(virt_to_page(mem + off));
} else {
/* jpg_bufsize is already page aligned */
for (j = 0; j < fh->buffers.buffer_size / PAGE_SIZE; j++) {
mem = (void *)get_zeroed_page(GFP_KERNEL);
if (mem == NULL) {
dprintk(1,
KERN_ERR
"%s: %s - get_zeroed_page failed for buffer %d\n",
ZR_DEVNAME(zr), __func__, i);
jpg_fbuffer_free(fh);
return -ENOBUFS;
}
fh->buffers.buffer[i].jpg.frag_tab[2 * j] =
cpu_to_le32(virt_to_bus(mem));
fh->buffers.buffer[i].jpg.frag_tab[2 * j + 1] =
cpu_to_le32((PAGE_SIZE >> 2) << 1);
SetPageReserved(virt_to_page(mem));
}
fh->buffers.buffer[i].jpg.frag_tab[2 * j - 1] |= cpu_to_le32(1);
}
}
dprintk(4,
KERN_DEBUG "%s: %s - %d KB allocated\n",
ZR_DEVNAME(zr), __func__,
(fh->buffers.num_buffers * fh->buffers.buffer_size) >> 10);
fh->buffers.allocated = 1;
return 0;
}
/* free the MJPEG grab buffers */
static void jpg_fbuffer_free(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
int i, j, off;
unsigned char *mem;
__le32 frag_tab;
struct zoran_buffer *buffer;
dprintk(4, KERN_DEBUG "%s: %s\n", ZR_DEVNAME(zr), __func__);
for (i = 0, buffer = &fh->buffers.buffer[0];
i < fh->buffers.num_buffers; i++, buffer++) {
if (!buffer->jpg.frag_tab)
continue;
if (fh->buffers.need_contiguous) {
frag_tab = buffer->jpg.frag_tab[0];
if (frag_tab) {
mem = bus_to_virt(le32_to_cpu(frag_tab));
for (off = 0; off < fh->buffers.buffer_size; off += PAGE_SIZE)
ClearPageReserved(virt_to_page(mem + off));
kfree(mem);
buffer->jpg.frag_tab[0] = 0;
buffer->jpg.frag_tab[1] = 0;
}
} else {
for (j = 0; j < fh->buffers.buffer_size / PAGE_SIZE; j++) {
frag_tab = buffer->jpg.frag_tab[2 * j];
if (!frag_tab)
break;
ClearPageReserved(virt_to_page(bus_to_virt(le32_to_cpu(frag_tab))));
free_page((unsigned long)bus_to_virt(le32_to_cpu(frag_tab)));
buffer->jpg.frag_tab[2 * j] = 0;
buffer->jpg.frag_tab[2 * j + 1] = 0;
}
}
free_page((unsigned long)buffer->jpg.frag_tab);
buffer->jpg.frag_tab = NULL;
}
fh->buffers.allocated = 0;
}
/*
* V4L Buffer grabbing
*/
static int
zoran_v4l_set_format (struct zoran_fh *fh,
int width,
int height,
const struct zoran_format *format)
{
struct zoran *zr = fh->zr;
int bpp;
/* Check size and format of the grab wanted */
if (height < BUZ_MIN_HEIGHT || width < BUZ_MIN_WIDTH ||
height > BUZ_MAX_HEIGHT || width > BUZ_MAX_WIDTH) {
dprintk(1,
KERN_ERR
"%s: %s - wrong frame size (%dx%d)\n",
ZR_DEVNAME(zr), __func__, width, height);
return -EINVAL;
}
bpp = (format->depth + 7) / 8;
/* Check against available buffer size */
if (height * width * bpp > fh->buffers.buffer_size) {
dprintk(1,
KERN_ERR
"%s: %s - video buffer size (%d kB) is too small\n",
ZR_DEVNAME(zr), __func__, fh->buffers.buffer_size >> 10);
return -EINVAL;
}
/* The video front end needs 4-byte alinged line sizes */
if ((bpp == 2 && (width & 1)) || (bpp == 3 && (width & 3))) {
dprintk(1,
KERN_ERR
"%s: %s - wrong frame alignment\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
fh->v4l_settings.width = width;
fh->v4l_settings.height = height;
fh->v4l_settings.format = format;
fh->v4l_settings.bytesperline = bpp * fh->v4l_settings.width;
return 0;
}
static int zoran_v4l_queue_frame(struct zoran_fh *fh, int num)
{
struct zoran *zr = fh->zr;
unsigned long flags;
int res = 0;
if (!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - buffers not yet allocated\n",
ZR_DEVNAME(zr), __func__);
res = -ENOMEM;
}
/* No grabbing outside the buffer range! */
if (num >= fh->buffers.num_buffers || num < 0) {
dprintk(1,
KERN_ERR
"%s: %s - buffer %d is out of range\n",
ZR_DEVNAME(zr), __func__, num);
res = -EINVAL;
}
spin_lock_irqsave(&zr->spinlock, flags);
if (fh->buffers.active == ZORAN_FREE) {
if (zr->v4l_buffers.active == ZORAN_FREE) {
zr->v4l_buffers = fh->buffers;
fh->buffers.active = ZORAN_ACTIVE;
} else {
dprintk(1,
KERN_ERR
"%s: %s - another session is already capturing\n",
ZR_DEVNAME(zr), __func__);
res = -EBUSY;
}
}
/* make sure a grab isn't going on currently with this buffer */
if (!res) {
switch (zr->v4l_buffers.buffer[num].state) {
default:
case BUZ_STATE_PEND:
if (zr->v4l_buffers.active == ZORAN_FREE) {
fh->buffers.active = ZORAN_FREE;
zr->v4l_buffers.allocated = 0;
}
res = -EBUSY; /* what are you doing? */
break;
case BUZ_STATE_DONE:
dprintk(2,
KERN_WARNING
"%s: %s - queueing buffer %d in state DONE!?\n",
ZR_DEVNAME(zr), __func__, num);
case BUZ_STATE_USER:
/* since there is at least one unused buffer there's room for at least
* one more pend[] entry */
zr->v4l_pend[zr->v4l_pend_head++ & V4L_MASK_FRAME] = num;
zr->v4l_buffers.buffer[num].state = BUZ_STATE_PEND;
zr->v4l_buffers.buffer[num].bs.length =
fh->v4l_settings.bytesperline *
zr->v4l_settings.height;
fh->buffers.buffer[num] = zr->v4l_buffers.buffer[num];
break;
}
}
spin_unlock_irqrestore(&zr->spinlock, flags);
if (!res && zr->v4l_buffers.active == ZORAN_FREE)
zr->v4l_buffers.active = fh->buffers.active;
return res;
}
/*
* Sync on a V4L buffer
*/
static int v4l_sync(struct zoran_fh *fh, int frame)
{
struct zoran *zr = fh->zr;
unsigned long flags;
if (fh->buffers.active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - no grab active for this session\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
/* check passed-in frame number */
if (frame >= fh->buffers.num_buffers || frame < 0) {
dprintk(1,
KERN_ERR "%s: %s - frame %d is invalid\n",
ZR_DEVNAME(zr), __func__, frame);
return -EINVAL;
}
/* Check if is buffer was queued at all */
if (zr->v4l_buffers.buffer[frame].state == BUZ_STATE_USER) {
dprintk(1,
KERN_ERR
"%s: %s - attempt to sync on a buffer which was not queued?\n",
ZR_DEVNAME(zr), __func__);
return -EPROTO;
}
mutex_unlock(&zr->lock);
/* wait on this buffer to get ready */
if (!wait_event_interruptible_timeout(zr->v4l_capq,
(zr->v4l_buffers.buffer[frame].state != BUZ_STATE_PEND), 10*HZ)) {
mutex_lock(&zr->lock);
return -ETIME;
}
mutex_lock(&zr->lock);
if (signal_pending(current))
return -ERESTARTSYS;
/* buffer should now be in BUZ_STATE_DONE */
if (zr->v4l_buffers.buffer[frame].state != BUZ_STATE_DONE)
dprintk(2,
KERN_ERR "%s: %s - internal state error\n",
ZR_DEVNAME(zr), __func__);
zr->v4l_buffers.buffer[frame].state = BUZ_STATE_USER;
fh->buffers.buffer[frame] = zr->v4l_buffers.buffer[frame];
spin_lock_irqsave(&zr->spinlock, flags);
/* Check if streaming capture has finished */
if (zr->v4l_pend_tail == zr->v4l_pend_head) {
zr36057_set_memgrab(zr, 0);
if (zr->v4l_buffers.active == ZORAN_ACTIVE) {
fh->buffers.active = zr->v4l_buffers.active = ZORAN_FREE;
zr->v4l_buffers.allocated = 0;
}
}
spin_unlock_irqrestore(&zr->spinlock, flags);
return 0;
}
/*
* Queue a MJPEG buffer for capture/playback
*/
static int zoran_jpg_queue_frame(struct zoran_fh *fh, int num,
enum zoran_codec_mode mode)
{
struct zoran *zr = fh->zr;
unsigned long flags;
int res = 0;
/* Check if buffers are allocated */
if (!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - buffers not yet allocated\n",
ZR_DEVNAME(zr), __func__);
return -ENOMEM;
}
/* No grabbing outside the buffer range! */
if (num >= fh->buffers.num_buffers || num < 0) {
dprintk(1,
KERN_ERR
"%s: %s - buffer %d out of range\n",
ZR_DEVNAME(zr), __func__, num);
return -EINVAL;
}
/* what is the codec mode right now? */
if (zr->codec_mode == BUZ_MODE_IDLE) {
zr->jpg_settings = fh->jpg_settings;
} else if (zr->codec_mode != mode) {
/* wrong codec mode active - invalid */
dprintk(1,
KERN_ERR
"%s: %s - codec in wrong mode\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (fh->buffers.active == ZORAN_FREE) {
if (zr->jpg_buffers.active == ZORAN_FREE) {
zr->jpg_buffers = fh->buffers;
fh->buffers.active = ZORAN_ACTIVE;
} else {
dprintk(1,
KERN_ERR
"%s: %s - another session is already capturing\n",
ZR_DEVNAME(zr), __func__);
res = -EBUSY;
}
}
if (!res && zr->codec_mode == BUZ_MODE_IDLE) {
/* Ok load up the jpeg codec */
zr36057_enable_jpg(zr, mode);
}
spin_lock_irqsave(&zr->spinlock, flags);
if (!res) {
switch (zr->jpg_buffers.buffer[num].state) {
case BUZ_STATE_DONE:
dprintk(2,
KERN_WARNING
"%s: %s - queing frame in BUZ_STATE_DONE state!?\n",
ZR_DEVNAME(zr), __func__);
case BUZ_STATE_USER:
/* since there is at least one unused buffer there's room for at
*least one more pend[] entry */
zr->jpg_pend[zr->jpg_que_head++ & BUZ_MASK_FRAME] = num;
zr->jpg_buffers.buffer[num].state = BUZ_STATE_PEND;
fh->buffers.buffer[num] = zr->jpg_buffers.buffer[num];
zoran_feed_stat_com(zr);
break;
default:
case BUZ_STATE_DMA:
case BUZ_STATE_PEND:
if (zr->jpg_buffers.active == ZORAN_FREE) {
fh->buffers.active = ZORAN_FREE;
zr->jpg_buffers.allocated = 0;
}
res = -EBUSY; /* what are you doing? */
break;
}
}
spin_unlock_irqrestore(&zr->spinlock, flags);
if (!res && zr->jpg_buffers.active == ZORAN_FREE)
zr->jpg_buffers.active = fh->buffers.active;
return res;
}
static int jpg_qbuf(struct zoran_fh *fh, int frame, enum zoran_codec_mode mode)
{
struct zoran *zr = fh->zr;
int res = 0;
/* Does the user want to stop streaming? */
if (frame < 0) {
if (zr->codec_mode == mode) {
if (fh->buffers.active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s(-1) - session not active\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
fh->buffers.active = zr->jpg_buffers.active = ZORAN_FREE;
zr->jpg_buffers.allocated = 0;
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
return 0;
} else {
dprintk(1,
KERN_ERR
"%s: %s - stop streaming but not in streaming mode\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
}
if ((res = zoran_jpg_queue_frame(fh, frame, mode)))
return res;
/* Start the jpeg codec when the first frame is queued */
if (!res && zr->jpg_que_head == 1)
jpeg_start(zr);
return res;
}
/*
* Sync on a MJPEG buffer
*/
static int jpg_sync(struct zoran_fh *fh, struct zoran_sync *bs)
{
struct zoran *zr = fh->zr;
unsigned long flags;
int frame;
if (fh->buffers.active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - capture is not currently active\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (zr->codec_mode != BUZ_MODE_MOTION_DECOMPRESS &&
zr->codec_mode != BUZ_MODE_MOTION_COMPRESS) {
dprintk(1,
KERN_ERR
"%s: %s - codec not in streaming mode\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
mutex_unlock(&zr->lock);
if (!wait_event_interruptible_timeout(zr->jpg_capq,
(zr->jpg_que_tail != zr->jpg_dma_tail ||
zr->jpg_dma_tail == zr->jpg_dma_head),
10*HZ)) {
int isr;
btand(~ZR36057_JMC_Go_en, ZR36057_JMC);
udelay(1);
zr->codec->control(zr->codec, CODEC_G_STATUS,
sizeof(isr), &isr);
mutex_lock(&zr->lock);
dprintk(1,
KERN_ERR
"%s: %s - timeout: codec isr=0x%02x\n",
ZR_DEVNAME(zr), __func__, isr);
return -ETIME;
}
mutex_lock(&zr->lock);
if (signal_pending(current))
return -ERESTARTSYS;
spin_lock_irqsave(&zr->spinlock, flags);
if (zr->jpg_dma_tail != zr->jpg_dma_head)
frame = zr->jpg_pend[zr->jpg_que_tail++ & BUZ_MASK_FRAME];
else
frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
/* buffer should now be in BUZ_STATE_DONE */
if (zr->jpg_buffers.buffer[frame].state != BUZ_STATE_DONE)
dprintk(2,
KERN_ERR "%s: %s - internal state error\n",
ZR_DEVNAME(zr), __func__);
*bs = zr->jpg_buffers.buffer[frame].bs;
bs->frame = frame;
zr->jpg_buffers.buffer[frame].state = BUZ_STATE_USER;
fh->buffers.buffer[frame] = zr->jpg_buffers.buffer[frame];
spin_unlock_irqrestore(&zr->spinlock, flags);
return 0;
}
static void zoran_open_init_session(struct zoran_fh *fh)
{
int i;
struct zoran *zr = fh->zr;
/* Per default, map the V4L Buffers */
map_mode_raw(fh);
/* take over the card's current settings */
fh->overlay_settings = zr->overlay_settings;
fh->overlay_settings.is_set = 0;
fh->overlay_settings.format = zr->overlay_settings.format;
fh->overlay_active = ZORAN_FREE;
/* v4l settings */
fh->v4l_settings = zr->v4l_settings;
/* jpg settings */
fh->jpg_settings = zr->jpg_settings;
/* buffers */
memset(&fh->buffers, 0, sizeof(fh->buffers));
for (i = 0; i < MAX_FRAME; i++) {
fh->buffers.buffer[i].state = BUZ_STATE_USER; /* nothing going on */
fh->buffers.buffer[i].bs.frame = i;
}
fh->buffers.allocated = 0;
fh->buffers.active = ZORAN_FREE;
}
static void zoran_close_end_session(struct zoran_fh *fh)
{
struct zoran *zr = fh->zr;
/* overlay */
if (fh->overlay_active != ZORAN_FREE) {
fh->overlay_active = zr->overlay_active = ZORAN_FREE;
zr->v4l_overlay_active = 0;
if (!zr->v4l_memgrab_active)
zr36057_overlay(zr, 0);
zr->overlay_mask = NULL;
}
if (fh->map_mode == ZORAN_MAP_MODE_RAW) {
/* v4l capture */
if (fh->buffers.active != ZORAN_FREE) {
unsigned long flags;
spin_lock_irqsave(&zr->spinlock, flags);
zr36057_set_memgrab(zr, 0);
zr->v4l_buffers.allocated = 0;
zr->v4l_buffers.active = fh->buffers.active = ZORAN_FREE;
spin_unlock_irqrestore(&zr->spinlock, flags);
}
/* v4l buffers */
if (fh->buffers.allocated)
v4l_fbuffer_free(fh);
} else {
/* jpg capture */
if (fh->buffers.active != ZORAN_FREE) {
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
zr->jpg_buffers.allocated = 0;
zr->jpg_buffers.active = fh->buffers.active = ZORAN_FREE;
}
/* jpg buffers */
if (fh->buffers.allocated)
jpg_fbuffer_free(fh);
}
}
/*
* Open a zoran card. Right now the flags stuff is just playing
*/
static int zoran_open(struct file *file)
{
struct zoran *zr = video_drvdata(file);
struct zoran_fh *fh;
int res, first_open = 0;
dprintk(2, KERN_INFO "%s: %s(%s, pid=[%d]), users(-)=%d\n",
ZR_DEVNAME(zr), __func__, current->comm, task_pid_nr(current), zr->user + 1);
mutex_lock(&zr->lock);
if (zr->user >= 2048) {
dprintk(1, KERN_ERR "%s: too many users (%d) on device\n",
ZR_DEVNAME(zr), zr->user);
res = -EBUSY;
goto fail_unlock;
}
/* now, create the open()-specific file_ops struct */
fh = kzalloc(sizeof(struct zoran_fh), GFP_KERNEL);
if (!fh) {
dprintk(1,
KERN_ERR
"%s: %s - allocation of zoran_fh failed\n",
ZR_DEVNAME(zr), __func__);
res = -ENOMEM;
goto fail_unlock;
}
v4l2_fh_init(&fh->fh, video_devdata(file));
/* used to be BUZ_MAX_WIDTH/HEIGHT, but that gives overflows
* on norm-change! */
fh->overlay_mask =
kmalloc(((768 + 31) / 32) * 576 * 4, GFP_KERNEL);
if (!fh->overlay_mask) {
dprintk(1,
KERN_ERR
"%s: %s - allocation of overlay_mask failed\n",
ZR_DEVNAME(zr), __func__);
res = -ENOMEM;
goto fail_fh;
}
if (zr->user++ == 0)
first_open = 1;
/* default setup - TODO: look at flags */
if (first_open) { /* First device open */
zr36057_restart(zr);
zoran_open_init_params(zr);
zoran_init_hardware(zr);
btor(ZR36057_ICR_IntPinEn, ZR36057_ICR);
}
/* set file_ops stuff */
file->private_data = fh;
fh->zr = zr;
zoran_open_init_session(fh);
v4l2_fh_add(&fh->fh);
mutex_unlock(&zr->lock);
return 0;
fail_fh:
kfree(fh);
fail_unlock:
mutex_unlock(&zr->lock);
dprintk(2, KERN_INFO "%s: open failed (%d), users(-)=%d\n",
ZR_DEVNAME(zr), res, zr->user);
return res;
}
static int
zoran_close(struct file *file)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
dprintk(2, KERN_INFO "%s: %s(%s, pid=[%d]), users(+)=%d\n",
ZR_DEVNAME(zr), __func__, current->comm, task_pid_nr(current), zr->user - 1);
/* kernel locks (fs/device.c), so don't do that ourselves
* (prevents deadlocks) */
mutex_lock(&zr->lock);
zoran_close_end_session(fh);
if (zr->user-- == 1) { /* Last process */
/* Clean up JPEG process */
wake_up_interruptible(&zr->jpg_capq);
zr36057_enable_jpg(zr, BUZ_MODE_IDLE);
zr->jpg_buffers.allocated = 0;
zr->jpg_buffers.active = ZORAN_FREE;
/* disable interrupts */
btand(~ZR36057_ICR_IntPinEn, ZR36057_ICR);
if (zr36067_debug > 1)
print_interrupts(zr);
/* Overlay off */
zr->v4l_overlay_active = 0;
zr36057_overlay(zr, 0);
zr->overlay_mask = NULL;
/* capture off */
wake_up_interruptible(&zr->v4l_capq);
zr36057_set_memgrab(zr, 0);
zr->v4l_buffers.allocated = 0;
zr->v4l_buffers.active = ZORAN_FREE;
zoran_set_pci_master(zr, 0);
if (!pass_through) { /* Switch to color bar */
decoder_call(zr, video, s_stream, 0);
encoder_call(zr, video, s_routing, 2, 0, 0);
}
}
mutex_unlock(&zr->lock);
v4l2_fh_del(&fh->fh);
v4l2_fh_exit(&fh->fh);
kfree(fh->overlay_mask);
kfree(fh);
dprintk(4, KERN_INFO "%s: %s done\n", ZR_DEVNAME(zr), __func__);
return 0;
}
static int setup_fbuffer(struct zoran_fh *fh,
void *base,
const struct zoran_format *fmt,
int width,
int height,
int bytesperline)
{
struct zoran *zr = fh->zr;
/* (Ronald) v4l/v4l2 guidelines */
if (!capable(CAP_SYS_ADMIN) && !capable(CAP_SYS_RAWIO))
return -EPERM;
/* Don't allow frame buffer overlay if PCI or AGP is buggy, or on
ALi Magik (that needs very low latency while the card needs a
higher value always) */
if (pci_pci_problems & (PCIPCI_FAIL | PCIAGP_FAIL | PCIPCI_ALIMAGIK))
return -ENXIO;
/* we need a bytesperline value, even if not given */
if (!bytesperline)
bytesperline = width * ((fmt->depth + 7) & ~7) / 8;
#if 0
if (zr->overlay_active) {
/* dzjee... stupid users... don't even bother to turn off
* overlay before changing the memory location...
* normally, we would return errors here. However, one of
* the tools that does this is... xawtv! and since xawtv
* is used by +/- 99% of the users, we'd rather be user-
* friendly and silently do as if nothing went wrong */
dprintk(3,
KERN_ERR
"%s: %s - forced overlay turnoff because framebuffer changed\n",
ZR_DEVNAME(zr), __func__);
zr36057_overlay(zr, 0);
}
#endif
if (!(fmt->flags & ZORAN_FORMAT_OVERLAY)) {
dprintk(1,
KERN_ERR
"%s: %s - no valid overlay format given\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (height <= 0 || width <= 0 || bytesperline <= 0) {
dprintk(1,
KERN_ERR
"%s: %s - invalid height/width/bpl value (%d|%d|%d)\n",
ZR_DEVNAME(zr), __func__, width, height, bytesperline);
return -EINVAL;
}
if (bytesperline & 3) {
dprintk(1,
KERN_ERR
"%s: %s - bytesperline (%d) must be 4-byte aligned\n",
ZR_DEVNAME(zr), __func__, bytesperline);
return -EINVAL;
}
zr->vbuf_base = (void *) ((unsigned long) base & ~3);
zr->vbuf_height = height;
zr->vbuf_width = width;
zr->vbuf_depth = fmt->depth;
zr->overlay_settings.format = fmt;
zr->vbuf_bytesperline = bytesperline;
/* The user should set new window parameters */
zr->overlay_settings.is_set = 0;
return 0;
}
static int setup_window(struct zoran_fh *fh,
int x,
int y,
int width,
int height,
struct v4l2_clip __user *clips,
unsigned int clipcount,
void __user *bitmap)
{
struct zoran *zr = fh->zr;
struct v4l2_clip *vcp = NULL;
int on, end;
if (!zr->vbuf_base) {
dprintk(1,
KERN_ERR
"%s: %s - frame buffer has to be set first\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (!fh->overlay_settings.format) {
dprintk(1,
KERN_ERR
"%s: %s - no overlay format set\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (clipcount > 2048) {
dprintk(1,
KERN_ERR
"%s: %s - invalid clipcount\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
/*
* The video front end needs 4-byte alinged line sizes, we correct that
* silently here if necessary
*/
if (zr->vbuf_depth == 15 || zr->vbuf_depth == 16) {
end = (x + width) & ~1; /* round down */
x = (x + 1) & ~1; /* round up */
width = end - x;
}
if (zr->vbuf_depth == 24) {
end = (x + width) & ~3; /* round down */
x = (x + 3) & ~3; /* round up */
width = end - x;
}
if (width > BUZ_MAX_WIDTH)
width = BUZ_MAX_WIDTH;
if (height > BUZ_MAX_HEIGHT)
height = BUZ_MAX_HEIGHT;
/* Check for invalid parameters */
if (width < BUZ_MIN_WIDTH || height < BUZ_MIN_HEIGHT ||
width > BUZ_MAX_WIDTH || height > BUZ_MAX_HEIGHT) {
dprintk(1,
KERN_ERR
"%s: %s - width = %d or height = %d invalid\n",
ZR_DEVNAME(zr), __func__, width, height);
return -EINVAL;
}
fh->overlay_settings.x = x;
fh->overlay_settings.y = y;
fh->overlay_settings.width = width;
fh->overlay_settings.height = height;
fh->overlay_settings.clipcount = clipcount;
/*
* If an overlay is running, we have to switch it off
* and switch it on again in order to get the new settings in effect.
*
* We also want to avoid that the overlay mask is written
* when an overlay is running.
*/
on = zr->v4l_overlay_active && !zr->v4l_memgrab_active &&
zr->overlay_active != ZORAN_FREE &&
fh->overlay_active != ZORAN_FREE;
if (on)
zr36057_overlay(zr, 0);
/*
* Write the overlay mask if clips are wanted.
* We prefer a bitmap.
*/
if (bitmap) {
/* fake value - it just means we want clips */
fh->overlay_settings.clipcount = 1;
if (copy_from_user(fh->overlay_mask, bitmap,
(width * height + 7) / 8)) {
return -EFAULT;
}
} else if (clipcount) {
/* write our own bitmap from the clips */
vcp = vmalloc(sizeof(struct v4l2_clip) * (clipcount + 4));
if (vcp == NULL) {
dprintk(1,
KERN_ERR
"%s: %s - Alloc of clip mask failed\n",
ZR_DEVNAME(zr), __func__);
return -ENOMEM;
}
if (copy_from_user
(vcp, clips, sizeof(struct v4l2_clip) * clipcount)) {
vfree(vcp);
return -EFAULT;
}
write_overlay_mask(fh, vcp, clipcount);
vfree(vcp);
}
fh->overlay_settings.is_set = 1;
if (fh->overlay_active != ZORAN_FREE &&
zr->overlay_active != ZORAN_FREE)
zr->overlay_settings = fh->overlay_settings;
if (on)
zr36057_overlay(zr, 1);
/* Make sure the changes come into effect */
return wait_grab_pending(zr);
}
static int setup_overlay(struct zoran_fh *fh, int on)
{
struct zoran *zr = fh->zr;
/* If there is nothing to do, return immediately */
if ((on && fh->overlay_active != ZORAN_FREE) ||
(!on && fh->overlay_active == ZORAN_FREE))
return 0;
/* check whether we're touching someone else's overlay */
if (on && zr->overlay_active != ZORAN_FREE &&
fh->overlay_active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - overlay is already active for another session\n",
ZR_DEVNAME(zr), __func__);
return -EBUSY;
}
if (!on && zr->overlay_active != ZORAN_FREE &&
fh->overlay_active == ZORAN_FREE) {
dprintk(1,
KERN_ERR
"%s: %s - you cannot cancel someone else's session\n",
ZR_DEVNAME(zr), __func__);
return -EPERM;
}
if (on == 0) {
zr->overlay_active = fh->overlay_active = ZORAN_FREE;
zr->v4l_overlay_active = 0;
/* When a grab is running, the video simply
* won't be switched on any more */
if (!zr->v4l_memgrab_active)
zr36057_overlay(zr, 0);
zr->overlay_mask = NULL;
} else {
if (!zr->vbuf_base || !fh->overlay_settings.is_set) {
dprintk(1,
KERN_ERR
"%s: %s - buffer or window not set\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (!fh->overlay_settings.format) {
dprintk(1,
KERN_ERR
"%s: %s - no overlay format set\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
zr->overlay_active = fh->overlay_active = ZORAN_LOCKED;
zr->v4l_overlay_active = 1;
zr->overlay_mask = fh->overlay_mask;
zr->overlay_settings = fh->overlay_settings;
if (!zr->v4l_memgrab_active)
zr36057_overlay(zr, 1);
/* When a grab is running, the video will be
* switched on when grab is finished */
}
/* Make sure the changes come into effect */
return wait_grab_pending(zr);
}
/* get the status of a buffer in the clients buffer queue */
static int zoran_v4l2_buffer_status(struct zoran_fh *fh,
struct v4l2_buffer *buf, int num)
{
struct zoran *zr = fh->zr;
unsigned long flags;
buf->flags = V4L2_BUF_FLAG_MAPPED | V4L2_BUF_FLAG_TIMESTAMP_MONOTONIC;
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
/* check range */
if (num < 0 || num >= fh->buffers.num_buffers ||
!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - wrong number or buffers not allocated\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
spin_lock_irqsave(&zr->spinlock, flags);
dprintk(3,
KERN_DEBUG
"%s: %s() - raw active=%c, buffer %d: state=%c, map=%c\n",
ZR_DEVNAME(zr), __func__,
"FAL"[fh->buffers.active], num,
"UPMD"[zr->v4l_buffers.buffer[num].state],
fh->buffers.buffer[num].map ? 'Y' : 'N');
spin_unlock_irqrestore(&zr->spinlock, flags);
buf->type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf->length = fh->buffers.buffer_size;
/* get buffer */
buf->bytesused = fh->buffers.buffer[num].bs.length;
if (fh->buffers.buffer[num].state == BUZ_STATE_DONE ||
fh->buffers.buffer[num].state == BUZ_STATE_USER) {
buf->sequence = fh->buffers.buffer[num].bs.seq;
buf->flags |= V4L2_BUF_FLAG_DONE;
buf->timestamp = fh->buffers.buffer[num].bs.timestamp;
} else {
buf->flags |= V4L2_BUF_FLAG_QUEUED;
}
if (fh->v4l_settings.height <= BUZ_MAX_HEIGHT / 2)
buf->field = V4L2_FIELD_TOP;
else
buf->field = V4L2_FIELD_INTERLACED;
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
/* check range */
if (num < 0 || num >= fh->buffers.num_buffers ||
!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s - wrong number or buffers not allocated\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
buf->type = (fh->map_mode == ZORAN_MAP_MODE_JPG_REC) ?
V4L2_BUF_TYPE_VIDEO_CAPTURE :
V4L2_BUF_TYPE_VIDEO_OUTPUT;
buf->length = fh->buffers.buffer_size;
/* these variables are only written after frame has been captured */
if (fh->buffers.buffer[num].state == BUZ_STATE_DONE ||
fh->buffers.buffer[num].state == BUZ_STATE_USER) {
buf->sequence = fh->buffers.buffer[num].bs.seq;
buf->timestamp = fh->buffers.buffer[num].bs.timestamp;
buf->bytesused = fh->buffers.buffer[num].bs.length;
buf->flags |= V4L2_BUF_FLAG_DONE;
} else {
buf->flags |= V4L2_BUF_FLAG_QUEUED;
}
/* which fields are these? */
if (fh->jpg_settings.TmpDcm != 1)
buf->field = fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM;
else
buf->field = fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT;
break;
default:
dprintk(5,
KERN_ERR
"%s: %s - invalid buffer type|map_mode (%d|%d)\n",
ZR_DEVNAME(zr), __func__, buf->type, fh->map_mode);
return -EINVAL;
}
buf->memory = V4L2_MEMORY_MMAP;
buf->index = num;
buf->m.offset = buf->length * num;
return 0;
}
static int
zoran_set_norm (struct zoran *zr,
v4l2_std_id norm)
{
int on;
if (zr->v4l_buffers.active != ZORAN_FREE ||
zr->jpg_buffers.active != ZORAN_FREE) {
dprintk(1,
KERN_WARNING
"%s: %s called while in playback/capture mode\n",
ZR_DEVNAME(zr), __func__);
return -EBUSY;
}
if (!(norm & zr->card.norms)) {
dprintk(1,
KERN_ERR "%s: %s - unsupported norm %llx\n",
ZR_DEVNAME(zr), __func__, norm);
return -EINVAL;
}
if (norm & V4L2_STD_SECAM)
zr->timing = zr->card.tvn[2];
else if (norm & V4L2_STD_NTSC)
zr->timing = zr->card.tvn[1];
else
zr->timing = zr->card.tvn[0];
/* We switch overlay off and on since a change in the
* norm needs different VFE settings */
on = zr->overlay_active && !zr->v4l_memgrab_active;
if (on)
zr36057_overlay(zr, 0);
decoder_call(zr, video, s_std, norm);
encoder_call(zr, video, s_std_output, norm);
if (on)
zr36057_overlay(zr, 1);
/* Make sure the changes come into effect */
zr->norm = norm;
return 0;
}
static int
zoran_set_input (struct zoran *zr,
int input)
{
if (input == zr->input) {
return 0;
}
if (zr->v4l_buffers.active != ZORAN_FREE ||
zr->jpg_buffers.active != ZORAN_FREE) {
dprintk(1,
KERN_WARNING
"%s: %s called while in playback/capture mode\n",
ZR_DEVNAME(zr), __func__);
return -EBUSY;
}
if (input < 0 || input >= zr->card.inputs) {
dprintk(1,
KERN_ERR
"%s: %s - unnsupported input %d\n",
ZR_DEVNAME(zr), __func__, input);
return -EINVAL;
}
zr->input = input;
decoder_call(zr, video, s_routing,
zr->card.input[input].muxsel, 0, 0);
return 0;
}
/*
* ioctl routine
*/
static int zoran_querycap(struct file *file, void *__fh, struct v4l2_capability *cap)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
strncpy(cap->card, ZR_DEVNAME(zr), sizeof(cap->card)-1);
strncpy(cap->driver, "zoran", sizeof(cap->driver)-1);
snprintf(cap->bus_info, sizeof(cap->bus_info), "PCI:%s",
pci_name(zr->pci_dev));
cap->device_caps = V4L2_CAP_STREAMING | V4L2_CAP_VIDEO_CAPTURE |
V4L2_CAP_VIDEO_OUTPUT | V4L2_CAP_VIDEO_OVERLAY;
cap->capabilities = cap->device_caps | V4L2_CAP_DEVICE_CAPS;
return 0;
}
static int zoran_enum_fmt(struct zoran *zr, struct v4l2_fmtdesc *fmt, int flag)
{
unsigned int num, i;
for (num = i = 0; i < NUM_FORMATS; i++) {
if (zoran_formats[i].flags & flag && num++ == fmt->index) {
strncpy(fmt->description, zoran_formats[i].name,
sizeof(fmt->description) - 1);
/* fmt struct pre-zeroed, so adding '\0' not needed */
fmt->pixelformat = zoran_formats[i].fourcc;
if (zoran_formats[i].flags & ZORAN_FORMAT_COMPRESSED)
fmt->flags |= V4L2_FMT_FLAG_COMPRESSED;
return 0;
}
}
return -EINVAL;
}
static int zoran_enum_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_fmtdesc *f)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
return zoran_enum_fmt(zr, f, ZORAN_FORMAT_CAPTURE);
}
static int zoran_enum_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_fmtdesc *f)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
return zoran_enum_fmt(zr, f, ZORAN_FORMAT_PLAYBACK);
}
static int zoran_enum_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_fmtdesc *f)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
return zoran_enum_fmt(zr, f, ZORAN_FORMAT_OVERLAY);
}
static int zoran_g_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
fmt->fmt.pix.width = fh->jpg_settings.img_width / fh->jpg_settings.HorDcm;
fmt->fmt.pix.height = fh->jpg_settings.img_height * 2 /
(fh->jpg_settings.VerDcm * fh->jpg_settings.TmpDcm);
fmt->fmt.pix.sizeimage = zoran_v4l2_calc_bufsize(&fh->jpg_settings);
fmt->fmt.pix.pixelformat = V4L2_PIX_FMT_MJPEG;
if (fh->jpg_settings.TmpDcm == 1)
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT);
else
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM);
fmt->fmt.pix.bytesperline = 0;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return 0;
}
static int zoran_g_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
if (fh->map_mode != ZORAN_MAP_MODE_RAW)
return zoran_g_fmt_vid_out(file, fh, fmt);
fmt->fmt.pix.width = fh->v4l_settings.width;
fmt->fmt.pix.height = fh->v4l_settings.height;
fmt->fmt.pix.sizeimage = fh->v4l_settings.bytesperline *
fh->v4l_settings.height;
fmt->fmt.pix.pixelformat = fh->v4l_settings.format->fourcc;
fmt->fmt.pix.colorspace = fh->v4l_settings.format->colorspace;
fmt->fmt.pix.bytesperline = fh->v4l_settings.bytesperline;
if (BUZ_MAX_HEIGHT < (fh->v4l_settings.height * 2))
fmt->fmt.pix.field = V4L2_FIELD_INTERLACED;
else
fmt->fmt.pix.field = V4L2_FIELD_TOP;
return 0;
}
static int zoran_g_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
fmt->fmt.win.w.left = fh->overlay_settings.x;
fmt->fmt.win.w.top = fh->overlay_settings.y;
fmt->fmt.win.w.width = fh->overlay_settings.width;
fmt->fmt.win.w.height = fh->overlay_settings.height;
if (fh->overlay_settings.width * 2 > BUZ_MAX_HEIGHT)
fmt->fmt.win.field = V4L2_FIELD_INTERLACED;
else
fmt->fmt.win.field = V4L2_FIELD_TOP;
return 0;
}
static int zoran_try_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
if (fmt->fmt.win.w.width > BUZ_MAX_WIDTH)
fmt->fmt.win.w.width = BUZ_MAX_WIDTH;
if (fmt->fmt.win.w.width < BUZ_MIN_WIDTH)
fmt->fmt.win.w.width = BUZ_MIN_WIDTH;
if (fmt->fmt.win.w.height > BUZ_MAX_HEIGHT)
fmt->fmt.win.w.height = BUZ_MAX_HEIGHT;
if (fmt->fmt.win.w.height < BUZ_MIN_HEIGHT)
fmt->fmt.win.w.height = BUZ_MIN_HEIGHT;
return 0;
}
static int zoran_try_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
struct zoran_jpg_settings settings;
int res = 0;
if (fmt->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG)
return -EINVAL;
settings = fh->jpg_settings;
/* we actually need to set 'real' parameters now */
if ((fmt->fmt.pix.height * 2) > BUZ_MAX_HEIGHT)
settings.TmpDcm = 1;
else
settings.TmpDcm = 2;
settings.decimation = 0;
if (fmt->fmt.pix.height <= fh->jpg_settings.img_height / 2)
settings.VerDcm = 2;
else
settings.VerDcm = 1;
if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 4)
settings.HorDcm = 4;
else if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 2)
settings.HorDcm = 2;
else
settings.HorDcm = 1;
if (settings.TmpDcm == 1)
settings.field_per_buff = 2;
else
settings.field_per_buff = 1;
if (settings.HorDcm > 1) {
settings.img_x = (BUZ_MAX_WIDTH == 720) ? 8 : 0;
settings.img_width = (BUZ_MAX_WIDTH == 720) ? 704 : BUZ_MAX_WIDTH;
} else {
settings.img_x = 0;
settings.img_width = BUZ_MAX_WIDTH;
}
/* check */
res = zoran_check_jpg_settings(zr, &settings, 1);
if (res)
return res;
/* tell the user what we actually did */
fmt->fmt.pix.width = settings.img_width / settings.HorDcm;
fmt->fmt.pix.height = settings.img_height * 2 /
(settings.TmpDcm * settings.VerDcm);
if (settings.TmpDcm == 1)
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT);
else
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM);
fmt->fmt.pix.sizeimage = zoran_v4l2_calc_bufsize(&settings);
fmt->fmt.pix.bytesperline = 0;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return res;
}
static int zoran_try_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int bpp;
int i;
if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG)
return zoran_try_fmt_vid_out(file, fh, fmt);
for (i = 0; i < NUM_FORMATS; i++)
if (zoran_formats[i].fourcc == fmt->fmt.pix.pixelformat)
break;
if (i == NUM_FORMATS)
return -EINVAL;
bpp = DIV_ROUND_UP(zoran_formats[i].depth, 8);
v4l_bound_align_image(
&fmt->fmt.pix.width, BUZ_MIN_WIDTH, BUZ_MAX_WIDTH, bpp == 2 ? 1 : 2,
&fmt->fmt.pix.height, BUZ_MIN_HEIGHT, BUZ_MAX_HEIGHT, 0, 0);
return 0;
}
static int zoran_s_fmt_vid_overlay(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
int res;
dprintk(3, "x=%d, y=%d, w=%d, h=%d, cnt=%d, map=0x%p\n",
fmt->fmt.win.w.left, fmt->fmt.win.w.top,
fmt->fmt.win.w.width,
fmt->fmt.win.w.height,
fmt->fmt.win.clipcount,
fmt->fmt.win.bitmap);
res = setup_window(fh, fmt->fmt.win.w.left, fmt->fmt.win.w.top,
fmt->fmt.win.w.width, fmt->fmt.win.w.height,
(struct v4l2_clip __user *)fmt->fmt.win.clips,
fmt->fmt.win.clipcount, fmt->fmt.win.bitmap);
return res;
}
static int zoran_s_fmt_vid_out(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
__le32 printformat = __cpu_to_le32(fmt->fmt.pix.pixelformat);
struct zoran_jpg_settings settings;
int res = 0;
dprintk(3, "size=%dx%d, fmt=0x%x (%4.4s)\n",
fmt->fmt.pix.width, fmt->fmt.pix.height,
fmt->fmt.pix.pixelformat,
(char *) &printformat);
if (fmt->fmt.pix.pixelformat != V4L2_PIX_FMT_MJPEG)
return -EINVAL;
if (fh->buffers.allocated) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FMT - cannot change capture mode\n",
ZR_DEVNAME(zr));
res = -EBUSY;
return res;
}
settings = fh->jpg_settings;
/* we actually need to set 'real' parameters now */
if (fmt->fmt.pix.height * 2 > BUZ_MAX_HEIGHT)
settings.TmpDcm = 1;
else
settings.TmpDcm = 2;
settings.decimation = 0;
if (fmt->fmt.pix.height <= fh->jpg_settings.img_height / 2)
settings.VerDcm = 2;
else
settings.VerDcm = 1;
if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 4)
settings.HorDcm = 4;
else if (fmt->fmt.pix.width <= fh->jpg_settings.img_width / 2)
settings.HorDcm = 2;
else
settings.HorDcm = 1;
if (settings.TmpDcm == 1)
settings.field_per_buff = 2;
else
settings.field_per_buff = 1;
if (settings.HorDcm > 1) {
settings.img_x = (BUZ_MAX_WIDTH == 720) ? 8 : 0;
settings.img_width = (BUZ_MAX_WIDTH == 720) ? 704 : BUZ_MAX_WIDTH;
} else {
settings.img_x = 0;
settings.img_width = BUZ_MAX_WIDTH;
}
/* check */
res = zoran_check_jpg_settings(zr, &settings, 0);
if (res)
return res;
/* it's ok, so set them */
fh->jpg_settings = settings;
map_mode_jpg(fh, fmt->type == V4L2_BUF_TYPE_VIDEO_OUTPUT);
fh->buffers.buffer_size = zoran_v4l2_calc_bufsize(&fh->jpg_settings);
/* tell the user what we actually did */
fmt->fmt.pix.width = settings.img_width / settings.HorDcm;
fmt->fmt.pix.height = settings.img_height * 2 /
(settings.TmpDcm * settings.VerDcm);
if (settings.TmpDcm == 1)
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_SEQ_TB : V4L2_FIELD_SEQ_BT);
else
fmt->fmt.pix.field = (fh->jpg_settings.odd_even ?
V4L2_FIELD_TOP : V4L2_FIELD_BOTTOM);
fmt->fmt.pix.bytesperline = 0;
fmt->fmt.pix.sizeimage = fh->buffers.buffer_size;
fmt->fmt.pix.colorspace = V4L2_COLORSPACE_SMPTE170M;
return res;
}
static int zoran_s_fmt_vid_cap(struct file *file, void *__fh,
struct v4l2_format *fmt)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int i;
int res = 0;
if (fmt->fmt.pix.pixelformat == V4L2_PIX_FMT_MJPEG)
return zoran_s_fmt_vid_out(file, fh, fmt);
for (i = 0; i < NUM_FORMATS; i++)
if (fmt->fmt.pix.pixelformat == zoran_formats[i].fourcc)
break;
if (i == NUM_FORMATS) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FMT - unknown/unsupported format 0x%x\n",
ZR_DEVNAME(zr), fmt->fmt.pix.pixelformat);
return -EINVAL;
}
if ((fh->map_mode != ZORAN_MAP_MODE_RAW && fh->buffers.allocated) ||
fh->buffers.active != ZORAN_FREE) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FMT - cannot change capture mode\n",
ZR_DEVNAME(zr));
res = -EBUSY;
return res;
}
if (fmt->fmt.pix.height > BUZ_MAX_HEIGHT)
fmt->fmt.pix.height = BUZ_MAX_HEIGHT;
if (fmt->fmt.pix.width > BUZ_MAX_WIDTH)
fmt->fmt.pix.width = BUZ_MAX_WIDTH;
map_mode_raw(fh);
res = zoran_v4l_set_format(fh, fmt->fmt.pix.width, fmt->fmt.pix.height,
&zoran_formats[i]);
if (res)
return res;
/* tell the user the results/missing stuff */
fmt->fmt.pix.bytesperline = fh->v4l_settings.bytesperline;
fmt->fmt.pix.sizeimage = fh->v4l_settings.height * fh->v4l_settings.bytesperline;
fmt->fmt.pix.colorspace = fh->v4l_settings.format->colorspace;
if (BUZ_MAX_HEIGHT < (fh->v4l_settings.height * 2))
fmt->fmt.pix.field = V4L2_FIELD_INTERLACED;
else
fmt->fmt.pix.field = V4L2_FIELD_TOP;
return res;
}
static int zoran_g_fbuf(struct file *file, void *__fh,
struct v4l2_framebuffer *fb)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
memset(fb, 0, sizeof(*fb));
fb->base = zr->vbuf_base;
fb->fmt.width = zr->vbuf_width;
fb->fmt.height = zr->vbuf_height;
if (zr->overlay_settings.format)
fb->fmt.pixelformat = fh->overlay_settings.format->fourcc;
fb->fmt.bytesperline = zr->vbuf_bytesperline;
fb->fmt.colorspace = V4L2_COLORSPACE_SRGB;
fb->fmt.field = V4L2_FIELD_INTERLACED;
fb->capability = V4L2_FBUF_CAP_LIST_CLIPPING;
return 0;
}
static int zoran_s_fbuf(struct file *file, void *__fh,
const struct v4l2_framebuffer *fb)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int i, res = 0;
__le32 printformat = __cpu_to_le32(fb->fmt.pixelformat);
for (i = 0; i < NUM_FORMATS; i++)
if (zoran_formats[i].fourcc == fb->fmt.pixelformat)
break;
if (i == NUM_FORMATS) {
dprintk(1, KERN_ERR "%s: VIDIOC_S_FBUF - format=0x%x (%4.4s) not allowed\n",
ZR_DEVNAME(zr), fb->fmt.pixelformat,
(char *)&printformat);
return -EINVAL;
}
res = setup_fbuffer(fh, fb->base, &zoran_formats[i], fb->fmt.width,
fb->fmt.height, fb->fmt.bytesperline);
return res;
}
static int zoran_overlay(struct file *file, void *__fh, unsigned int on)
{
struct zoran_fh *fh = __fh;
int res;
res = setup_overlay(fh, on);
return res;
}
static int zoran_streamoff(struct file *file, void *__fh, enum v4l2_buf_type type);
static int zoran_reqbufs(struct file *file, void *__fh, struct v4l2_requestbuffers *req)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
if (req->memory != V4L2_MEMORY_MMAP) {
dprintk(2,
KERN_ERR
"%s: only MEMORY_MMAP capture is supported, not %d\n",
ZR_DEVNAME(zr), req->memory);
return -EINVAL;
}
if (req->count == 0)
return zoran_streamoff(file, fh, req->type);
if (fh->buffers.allocated) {
dprintk(2,
KERN_ERR
"%s: VIDIOC_REQBUFS - buffers already allocated\n",
ZR_DEVNAME(zr));
res = -EBUSY;
return res;
}
if (fh->map_mode == ZORAN_MAP_MODE_RAW &&
req->type == V4L2_BUF_TYPE_VIDEO_CAPTURE) {
/* control user input */
if (req->count < 2)
req->count = 2;
if (req->count > v4l_nbufs)
req->count = v4l_nbufs;
/* The next mmap will map the V4L buffers */
map_mode_raw(fh);
fh->buffers.num_buffers = req->count;
if (v4l_fbuffer_alloc(fh)) {
res = -ENOMEM;
return res;
}
} else if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC ||
fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
/* we need to calculate size ourselves now */
if (req->count < 4)
req->count = 4;
if (req->count > jpg_nbufs)
req->count = jpg_nbufs;
/* The next mmap will map the MJPEG buffers */
map_mode_jpg(fh, req->type == V4L2_BUF_TYPE_VIDEO_OUTPUT);
fh->buffers.num_buffers = req->count;
fh->buffers.buffer_size = zoran_v4l2_calc_bufsize(&fh->jpg_settings);
if (jpg_fbuffer_alloc(fh)) {
res = -ENOMEM;
return res;
}
} else {
dprintk(1,
KERN_ERR
"%s: VIDIOC_REQBUFS - unknown type %d\n",
ZR_DEVNAME(zr), req->type);
res = -EINVAL;
return res;
}
return res;
}
static int zoran_querybuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct zoran_fh *fh = __fh;
int res;
res = zoran_v4l2_buffer_status(fh, buf, buf->index);
return res;
}
static int zoran_qbuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0, codec_mode, buf_type;
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
return res;
}
res = zoran_v4l_queue_frame(fh, buf->index);
if (res)
return res;
if (!zr->v4l_memgrab_active && fh->buffers.active == ZORAN_LOCKED)
zr36057_set_memgrab(zr, 1);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY) {
buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
codec_mode = BUZ_MODE_MOTION_DECOMPRESS;
} else {
buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
codec_mode = BUZ_MODE_MOTION_COMPRESS;
}
if (buf->type != buf_type) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
return res;
}
res = zoran_jpg_queue_frame(fh, buf->index, codec_mode);
if (res != 0)
return res;
if (zr->codec_mode == BUZ_MODE_IDLE &&
fh->buffers.active == ZORAN_LOCKED)
zr36057_enable_jpg(zr, codec_mode);
break;
default:
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - unsupported type %d\n",
ZR_DEVNAME(zr), buf->type);
res = -EINVAL;
break;
}
return res;
}
static int zoran_dqbuf(struct file *file, void *__fh, struct v4l2_buffer *buf)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0, buf_type, num = -1; /* compiler borks here (?) */
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
if (buf->type != V4L2_BUF_TYPE_VIDEO_CAPTURE) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
return res;
}
num = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
if (file->f_flags & O_NONBLOCK &&
zr->v4l_buffers.buffer[num].state != BUZ_STATE_DONE) {
res = -EAGAIN;
return res;
}
res = v4l_sync(fh, num);
if (res)
return res;
zr->v4l_sync_tail++;
res = zoran_v4l2_buffer_status(fh, buf, num);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
{
struct zoran_sync bs;
if (fh->map_mode == ZORAN_MAP_MODE_JPG_PLAY)
buf_type = V4L2_BUF_TYPE_VIDEO_OUTPUT;
else
buf_type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (buf->type != buf_type) {
dprintk(1, KERN_ERR
"%s: VIDIOC_QBUF - invalid buf->type=%d for map_mode=%d\n",
ZR_DEVNAME(zr), buf->type, fh->map_mode);
res = -EINVAL;
return res;
}
num = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
if (file->f_flags & O_NONBLOCK &&
zr->jpg_buffers.buffer[num].state != BUZ_STATE_DONE) {
res = -EAGAIN;
return res;
}
bs.frame = 0; /* suppress compiler warning */
res = jpg_sync(fh, &bs);
if (res)
return res;
res = zoran_v4l2_buffer_status(fh, buf, bs.frame);
break;
}
default:
dprintk(1, KERN_ERR
"%s: VIDIOC_DQBUF - unsupported type %d\n",
ZR_DEVNAME(zr), buf->type);
res = -EINVAL;
break;
}
return res;
}
static int zoran_streamon(struct file *file, void *__fh, enum v4l2_buf_type type)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW: /* raw capture */
if (zr->v4l_buffers.active != ZORAN_ACTIVE ||
fh->buffers.active != ZORAN_ACTIVE) {
res = -EBUSY;
return res;
}
zr->v4l_buffers.active = fh->buffers.active = ZORAN_LOCKED;
zr->v4l_settings = fh->v4l_settings;
zr->v4l_sync_tail = zr->v4l_pend_tail;
if (!zr->v4l_memgrab_active &&
zr->v4l_pend_head != zr->v4l_pend_tail) {
zr36057_set_memgrab(zr, 1);
}
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
/* what is the codec mode right now? */
if (zr->jpg_buffers.active != ZORAN_ACTIVE ||
fh->buffers.active != ZORAN_ACTIVE) {
res = -EBUSY;
return res;
}
zr->jpg_buffers.active = fh->buffers.active = ZORAN_LOCKED;
if (zr->jpg_que_head != zr->jpg_que_tail) {
/* Start the jpeg codec when the first frame is queued */
jpeg_start(zr);
}
break;
default:
dprintk(1,
KERN_ERR
"%s: VIDIOC_STREAMON - invalid map mode %d\n",
ZR_DEVNAME(zr), fh->map_mode);
res = -EINVAL;
break;
}
return res;
}
static int zoran_streamoff(struct file *file, void *__fh, enum v4l2_buf_type type)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int i, res = 0;
unsigned long flags;
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW: /* raw capture */
if (fh->buffers.active == ZORAN_FREE &&
zr->v4l_buffers.active != ZORAN_FREE) {
res = -EPERM; /* stay off other's settings! */
return res;
}
if (zr->v4l_buffers.active == ZORAN_FREE)
return res;
spin_lock_irqsave(&zr->spinlock, flags);
/* unload capture */
if (zr->v4l_memgrab_active) {
zr36057_set_memgrab(zr, 0);
}
for (i = 0; i < fh->buffers.num_buffers; i++)
zr->v4l_buffers.buffer[i].state = BUZ_STATE_USER;
fh->buffers = zr->v4l_buffers;
zr->v4l_buffers.active = fh->buffers.active = ZORAN_FREE;
zr->v4l_grab_seq = 0;
zr->v4l_pend_head = zr->v4l_pend_tail = 0;
zr->v4l_sync_tail = 0;
spin_unlock_irqrestore(&zr->spinlock, flags);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
if (fh->buffers.active == ZORAN_FREE &&
zr->jpg_buffers.active != ZORAN_FREE) {
res = -EPERM; /* stay off other's settings! */
return res;
}
if (zr->jpg_buffers.active == ZORAN_FREE)
return res;
res = jpg_qbuf(fh, -1,
(fh->map_mode == ZORAN_MAP_MODE_JPG_REC) ?
BUZ_MODE_MOTION_COMPRESS :
BUZ_MODE_MOTION_DECOMPRESS);
if (res)
return res;
break;
default:
dprintk(1, KERN_ERR
"%s: VIDIOC_STREAMOFF - invalid map mode %d\n",
ZR_DEVNAME(zr), fh->map_mode);
res = -EINVAL;
break;
}
return res;
}
static int zoran_g_std(struct file *file, void *__fh, v4l2_std_id *std)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
*std = zr->norm;
return 0;
}
static int zoran_s_std(struct file *file, void *__fh, v4l2_std_id std)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
res = zoran_set_norm(zr, std);
if (res)
return res;
res = wait_grab_pending(zr);
return res;
}
static int zoran_enum_input(struct file *file, void *__fh,
struct v4l2_input *inp)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
if (inp->index >= zr->card.inputs)
return -EINVAL;
strncpy(inp->name, zr->card.input[inp->index].name,
sizeof(inp->name) - 1);
inp->type = V4L2_INPUT_TYPE_CAMERA;
inp->std = V4L2_STD_ALL;
/* Get status of video decoder */
decoder_call(zr, video, g_input_status, &inp->status);
return 0;
}
static int zoran_g_input(struct file *file, void *__fh, unsigned int *input)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
*input = zr->input;
return 0;
}
static int zoran_s_input(struct file *file, void *__fh, unsigned int input)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res;
res = zoran_set_input(zr, input);
if (res)
return res;
/* Make sure the changes come into effect */
res = wait_grab_pending(zr);
return res;
}
static int zoran_enum_output(struct file *file, void *__fh,
struct v4l2_output *outp)
{
if (outp->index != 0)
return -EINVAL;
outp->index = 0;
outp->type = V4L2_OUTPUT_TYPE_ANALOGVGAOVERLAY;
strncpy(outp->name, "Autodetect", sizeof(outp->name)-1);
return 0;
}
static int zoran_g_output(struct file *file, void *__fh, unsigned int *output)
{
*output = 0;
return 0;
}
static int zoran_s_output(struct file *file, void *__fh, unsigned int output)
{
if (output != 0)
return -EINVAL;
return 0;
}
/* cropping (sub-frame capture) */
static int zoran_cropcap(struct file *file, void *__fh,
struct v4l2_cropcap *cropcap)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int type = cropcap->type, res = 0;
memset(cropcap, 0, sizeof(*cropcap));
cropcap->type = type;
if (cropcap->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(cropcap->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
fh->map_mode == ZORAN_MAP_MODE_RAW)) {
dprintk(1, KERN_ERR
"%s: VIDIOC_CROPCAP - subcapture only supported for compressed capture\n",
ZR_DEVNAME(zr));
res = -EINVAL;
return res;
}
cropcap->bounds.top = cropcap->bounds.left = 0;
cropcap->bounds.width = BUZ_MAX_WIDTH;
cropcap->bounds.height = BUZ_MAX_HEIGHT;
cropcap->defrect.top = cropcap->defrect.left = 0;
cropcap->defrect.width = BUZ_MIN_WIDTH;
cropcap->defrect.height = BUZ_MIN_HEIGHT;
return res;
}
static int zoran_g_crop(struct file *file, void *__fh, struct v4l2_crop *crop)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int type = crop->type, res = 0;
memset(crop, 0, sizeof(*crop));
crop->type = type;
if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
fh->map_mode == ZORAN_MAP_MODE_RAW)) {
dprintk(1,
KERN_ERR
"%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
ZR_DEVNAME(zr));
res = -EINVAL;
return res;
}
crop->c.top = fh->jpg_settings.img_y;
crop->c.left = fh->jpg_settings.img_x;
crop->c.width = fh->jpg_settings.img_width;
crop->c.height = fh->jpg_settings.img_height;
return res;
}
static int zoran_s_crop(struct file *file, void *__fh, const struct v4l2_crop *crop)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
struct zoran_jpg_settings settings;
settings = fh->jpg_settings;
if (fh->buffers.allocated) {
dprintk(1, KERN_ERR
"%s: VIDIOC_S_CROP - cannot change settings while active\n",
ZR_DEVNAME(zr));
res = -EBUSY;
return res;
}
if (crop->type != V4L2_BUF_TYPE_VIDEO_OUTPUT &&
(crop->type != V4L2_BUF_TYPE_VIDEO_CAPTURE ||
fh->map_mode == ZORAN_MAP_MODE_RAW)) {
dprintk(1, KERN_ERR
"%s: VIDIOC_G_CROP - subcapture only supported for compressed capture\n",
ZR_DEVNAME(zr));
res = -EINVAL;
return res;
}
/* move into a form that we understand */
settings.img_x = crop->c.left;
settings.img_y = crop->c.top;
settings.img_width = crop->c.width;
settings.img_height = crop->c.height;
/* check validity */
res = zoran_check_jpg_settings(zr, &settings, 0);
if (res)
return res;
/* accept */
fh->jpg_settings = settings;
return res;
}
static int zoran_g_jpegcomp(struct file *file, void *__fh,
struct v4l2_jpegcompression *params)
{
struct zoran_fh *fh = __fh;
memset(params, 0, sizeof(*params));
params->quality = fh->jpg_settings.jpg_comp.quality;
params->APPn = fh->jpg_settings.jpg_comp.APPn;
memcpy(params->APP_data,
fh->jpg_settings.jpg_comp.APP_data,
fh->jpg_settings.jpg_comp.APP_len);
params->APP_len = fh->jpg_settings.jpg_comp.APP_len;
memcpy(params->COM_data,
fh->jpg_settings.jpg_comp.COM_data,
fh->jpg_settings.jpg_comp.COM_len);
params->COM_len = fh->jpg_settings.jpg_comp.COM_len;
params->jpeg_markers =
fh->jpg_settings.jpg_comp.jpeg_markers;
return 0;
}
static int zoran_s_jpegcomp(struct file *file, void *__fh,
const struct v4l2_jpegcompression *params)
{
struct zoran_fh *fh = __fh;
struct zoran *zr = fh->zr;
int res = 0;
struct zoran_jpg_settings settings;
settings = fh->jpg_settings;
settings.jpg_comp = *params;
if (fh->buffers.active != ZORAN_FREE) {
dprintk(1, KERN_WARNING
"%s: VIDIOC_S_JPEGCOMP called while in playback/capture mode\n",
ZR_DEVNAME(zr));
res = -EBUSY;
return res;
}
res = zoran_check_jpg_settings(zr, &settings, 0);
if (res)
return res;
if (!fh->buffers.allocated)
fh->buffers.buffer_size =
zoran_v4l2_calc_bufsize(&fh->jpg_settings);
fh->jpg_settings.jpg_comp = settings.jpg_comp;
return res;
}
static unsigned int
zoran_poll (struct file *file,
poll_table *wait)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
int res = v4l2_ctrl_poll(file, wait);
int frame;
unsigned long flags;
/* we should check whether buffers are ready to be synced on
* (w/o waits - O_NONBLOCK) here
* if ready for read (sync), return POLLIN|POLLRDNORM,
* if ready for write (sync), return POLLOUT|POLLWRNORM,
* if error, return POLLERR,
* if no buffers queued or so, return POLLNVAL
*/
switch (fh->map_mode) {
case ZORAN_MAP_MODE_RAW:
poll_wait(file, &zr->v4l_capq, wait);
frame = zr->v4l_pend[zr->v4l_sync_tail & V4L_MASK_FRAME];
spin_lock_irqsave(&zr->spinlock, flags);
dprintk(3,
KERN_DEBUG
"%s: %s() raw - active=%c, sync_tail=%lu/%c, pend_tail=%lu, pend_head=%lu\n",
ZR_DEVNAME(zr), __func__,
"FAL"[fh->buffers.active], zr->v4l_sync_tail,
"UPMD"[zr->v4l_buffers.buffer[frame].state],
zr->v4l_pend_tail, zr->v4l_pend_head);
/* Process is the one capturing? */
if (fh->buffers.active != ZORAN_FREE &&
/* Buffer ready to DQBUF? */
zr->v4l_buffers.buffer[frame].state == BUZ_STATE_DONE)
res |= POLLIN | POLLRDNORM;
spin_unlock_irqrestore(&zr->spinlock, flags);
break;
case ZORAN_MAP_MODE_JPG_REC:
case ZORAN_MAP_MODE_JPG_PLAY:
poll_wait(file, &zr->jpg_capq, wait);
frame = zr->jpg_pend[zr->jpg_que_tail & BUZ_MASK_FRAME];
spin_lock_irqsave(&zr->spinlock, flags);
dprintk(3,
KERN_DEBUG
"%s: %s() jpg - active=%c, que_tail=%lu/%c, que_head=%lu, dma=%lu/%lu\n",
ZR_DEVNAME(zr), __func__,
"FAL"[fh->buffers.active], zr->jpg_que_tail,
"UPMD"[zr->jpg_buffers.buffer[frame].state],
zr->jpg_que_head, zr->jpg_dma_tail, zr->jpg_dma_head);
if (fh->buffers.active != ZORAN_FREE &&
zr->jpg_buffers.buffer[frame].state == BUZ_STATE_DONE) {
if (fh->map_mode == ZORAN_MAP_MODE_JPG_REC)
res |= POLLIN | POLLRDNORM;
else
res |= POLLOUT | POLLWRNORM;
}
spin_unlock_irqrestore(&zr->spinlock, flags);
break;
default:
dprintk(1,
KERN_ERR
"%s: %s - internal error, unknown map_mode=%d\n",
ZR_DEVNAME(zr), __func__, fh->map_mode);
res |= POLLERR;
}
return res;
}
/*
* This maps the buffers to user space.
*
* Depending on the state of fh->map_mode
* the V4L or the MJPEG buffers are mapped
* per buffer or all together
*
* Note that we need to connect to some
* unmap signal event to unmap the de-allocate
* the buffer accordingly (zoran_vm_close())
*/
static void
zoran_vm_open (struct vm_area_struct *vma)
{
struct zoran_mapping *map = vma->vm_private_data;
atomic_inc(&map->count);
}
static void
zoran_vm_close (struct vm_area_struct *vma)
{
struct zoran_mapping *map = vma->vm_private_data;
struct zoran_fh *fh = map->fh;
struct zoran *zr = fh->zr;
int i;
dprintk(3, KERN_INFO "%s: %s - munmap(%s)\n", ZR_DEVNAME(zr),
__func__, mode_name(fh->map_mode));
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].map == map)
fh->buffers.buffer[i].map = NULL;
}
kfree(map);
/* Any buffers still mapped? */
for (i = 0; i < fh->buffers.num_buffers; i++) {
if (fh->buffers.buffer[i].map) {
return;
}
}
dprintk(3, KERN_INFO "%s: %s - free %s buffers\n", ZR_DEVNAME(zr),
__func__, mode_name(fh->map_mode));
if (fh->map_mode == ZORAN_MAP_MODE_RAW) {
if (fh->buffers.active != ZORAN_FREE) {
unsigned long flags;
spin_lock_irqsave(&zr->spinlock, flags);
zr36057_set_memgrab(zr, 0);
zr->v4l_buffers.allocated = 0;
zr->v4l_buffers.active = fh->buffers.active = ZORAN_FREE;
spin_unlock_irqrestore(&zr->spinlock, flags);
}
v4l_fbuffer_free(fh);
} else {
if (fh->buffers.active != ZORAN_FREE) {
jpg_qbuf(fh, -1, zr->codec_mode);
zr->jpg_buffers.allocated = 0;
zr->jpg_buffers.active = fh->buffers.active = ZORAN_FREE;
}
jpg_fbuffer_free(fh);
}
}
static const struct vm_operations_struct zoran_vm_ops = {
.open = zoran_vm_open,
.close = zoran_vm_close,
};
static int
zoran_mmap (struct file *file,
struct vm_area_struct *vma)
{
struct zoran_fh *fh = file->private_data;
struct zoran *zr = fh->zr;
unsigned long size = (vma->vm_end - vma->vm_start);
unsigned long offset = vma->vm_pgoff << PAGE_SHIFT;
int i, j;
unsigned long page, start = vma->vm_start, todo, pos, fraglen;
int first, last;
struct zoran_mapping *map;
int res = 0;
dprintk(3,
KERN_INFO "%s: %s(%s) of 0x%08lx-0x%08lx (size=%lu)\n",
ZR_DEVNAME(zr), __func__,
mode_name(fh->map_mode), vma->vm_start, vma->vm_end, size);
if (!(vma->vm_flags & VM_SHARED) || !(vma->vm_flags & VM_READ) ||
!(vma->vm_flags & VM_WRITE)) {
dprintk(1,
KERN_ERR
"%s: %s - no MAP_SHARED/PROT_{READ,WRITE} given\n",
ZR_DEVNAME(zr), __func__);
return -EINVAL;
}
if (!fh->buffers.allocated) {
dprintk(1,
KERN_ERR
"%s: %s(%s) - buffers not yet allocated\n",
ZR_DEVNAME(zr), __func__, mode_name(fh->map_mode));
res = -ENOMEM;
return res;
}
first = offset / fh->buffers.buffer_size;
last = first - 1 + size / fh->buffers.buffer_size;
if (offset % fh->buffers.buffer_size != 0 ||
size % fh->buffers.buffer_size != 0 || first < 0 ||
last < 0 || first >= fh->buffers.num_buffers ||
last >= fh->buffers.buffer_size) {
dprintk(1,
KERN_ERR
"%s: %s(%s) - offset=%lu or size=%lu invalid for bufsize=%d and numbufs=%d\n",
ZR_DEVNAME(zr), __func__, mode_name(fh->map_mode), offset, size,
fh->buffers.buffer_size,
fh->buffers.num_buffers);
res = -EINVAL;
return res;
}
/* Check if any buffers are already mapped */
for (i = first; i <= last; i++) {
if (fh->buffers.buffer[i].map) {
dprintk(1,
KERN_ERR
"%s: %s(%s) - buffer %d already mapped\n",
ZR_DEVNAME(zr), __func__, mode_name(fh->map_mode), i);
res = -EBUSY;
return res;
}
}
/* map these buffers */
map = kmalloc(sizeof(struct zoran_mapping), GFP_KERNEL);
if (!map) {
res = -ENOMEM;
return res;
}
map->fh = fh;
atomic_set(&map->count, 1);
vma->vm_ops = &zoran_vm_ops;
vma->vm_flags |= VM_DONTEXPAND;
vma->vm_private_data = map;
if (fh->map_mode == ZORAN_MAP_MODE_RAW) {
for (i = first; i <= last; i++) {
todo = size;
if (todo > fh->buffers.buffer_size)
todo = fh->buffers.buffer_size;
page = fh->buffers.buffer[i].v4l.fbuffer_phys;
if (remap_pfn_range(vma, start, page >> PAGE_SHIFT,
todo, PAGE_SHARED)) {
dprintk(1,
KERN_ERR
"%s: %s(V4L) - remap_pfn_range failed\n",
ZR_DEVNAME(zr), __func__);
res = -EAGAIN;
return res;
}
size -= todo;
start += todo;
fh->buffers.buffer[i].map = map;
if (size == 0)
break;
}
} else {
for (i = first; i <= last; i++) {
for (j = 0;
j < fh->buffers.buffer_size / PAGE_SIZE;
j++) {
fraglen =
(le32_to_cpu(fh->buffers.buffer[i].jpg.
frag_tab[2 * j + 1]) & ~1) << 1;
todo = size;
if (todo > fraglen)
todo = fraglen;
pos =
le32_to_cpu(fh->buffers.
buffer[i].jpg.frag_tab[2 * j]);
/* should just be pos on i386 */
page = virt_to_phys(bus_to_virt(pos))
>> PAGE_SHIFT;
if (remap_pfn_range(vma, start, page,
todo, PAGE_SHARED)) {
dprintk(1,
KERN_ERR
"%s: %s(V4L) - remap_pfn_range failed\n",
ZR_DEVNAME(zr), __func__);
res = -EAGAIN;
return res;
}
size -= todo;
start += todo;
if (size == 0)
break;
if (le32_to_cpu(fh->buffers.buffer[i].jpg.
frag_tab[2 * j + 1]) & 1)
break; /* was last fragment */
}
fh->buffers.buffer[i].map = map;
if (size == 0)
break;
}
}
return res;
}
static const struct v4l2_ioctl_ops zoran_ioctl_ops = {
.vidioc_querycap = zoran_querycap,
.vidioc_cropcap = zoran_cropcap,
.vidioc_s_crop = zoran_s_crop,
.vidioc_g_crop = zoran_g_crop,
.vidioc_enum_input = zoran_enum_input,
.vidioc_g_input = zoran_g_input,
.vidioc_s_input = zoran_s_input,
.vidioc_enum_output = zoran_enum_output,
.vidioc_g_output = zoran_g_output,
.vidioc_s_output = zoran_s_output,
.vidioc_g_fbuf = zoran_g_fbuf,
.vidioc_s_fbuf = zoran_s_fbuf,
.vidioc_g_std = zoran_g_std,
.vidioc_s_std = zoran_s_std,
.vidioc_g_jpegcomp = zoran_g_jpegcomp,
.vidioc_s_jpegcomp = zoran_s_jpegcomp,
.vidioc_overlay = zoran_overlay,
.vidioc_reqbufs = zoran_reqbufs,
.vidioc_querybuf = zoran_querybuf,
.vidioc_qbuf = zoran_qbuf,
.vidioc_dqbuf = zoran_dqbuf,
.vidioc_streamon = zoran_streamon,
.vidioc_streamoff = zoran_streamoff,
.vidioc_enum_fmt_vid_cap = zoran_enum_fmt_vid_cap,
.vidioc_enum_fmt_vid_out = zoran_enum_fmt_vid_out,
.vidioc_enum_fmt_vid_overlay = zoran_enum_fmt_vid_overlay,
.vidioc_g_fmt_vid_cap = zoran_g_fmt_vid_cap,
.vidioc_g_fmt_vid_out = zoran_g_fmt_vid_out,
.vidioc_g_fmt_vid_overlay = zoran_g_fmt_vid_overlay,
.vidioc_s_fmt_vid_cap = zoran_s_fmt_vid_cap,
.vidioc_s_fmt_vid_out = zoran_s_fmt_vid_out,
.vidioc_s_fmt_vid_overlay = zoran_s_fmt_vid_overlay,
.vidioc_try_fmt_vid_cap = zoran_try_fmt_vid_cap,
.vidioc_try_fmt_vid_out = zoran_try_fmt_vid_out,
.vidioc_try_fmt_vid_overlay = zoran_try_fmt_vid_overlay,
.vidioc_subscribe_event = v4l2_ctrl_subscribe_event,
.vidioc_unsubscribe_event = v4l2_event_unsubscribe,
};
static const struct v4l2_file_operations zoran_fops = {
.owner = THIS_MODULE,
.open = zoran_open,
.release = zoran_close,
.unlocked_ioctl = video_ioctl2,
.mmap = zoran_mmap,
.poll = zoran_poll,
};
struct video_device zoran_template = {
.name = ZORAN_NAME,
.fops = &zoran_fops,
.ioctl_ops = &zoran_ioctl_ops,
.release = &zoran_vdev_release,
.tvnorms = V4L2_STD_NTSC | V4L2_STD_PAL | V4L2_STD_SECAM,
};
|
gpl-3.0
|
sbx320/mtasa-blue
|
vendor/jpeg-9d/jdmarker.c
|
16
|
45824
|
/*
* jdmarker.c
*
* Copyright (C) 1991-1998, Thomas G. Lane.
* Modified 2009-2019 by Guido Vollbeding.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains routines to decode JPEG datastream markers.
* Most of the complexity arises from our desire to support input
* suspension: if not all of the data for a marker is available,
* we must exit back to the application. On resumption, we reprocess
* the marker.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
typedef enum { /* JPEG marker codes */
M_SOF0 = 0xc0,
M_SOF1 = 0xc1,
M_SOF2 = 0xc2,
M_SOF3 = 0xc3,
M_SOF5 = 0xc5,
M_SOF6 = 0xc6,
M_SOF7 = 0xc7,
M_JPG = 0xc8,
M_SOF9 = 0xc9,
M_SOF10 = 0xca,
M_SOF11 = 0xcb,
M_SOF13 = 0xcd,
M_SOF14 = 0xce,
M_SOF15 = 0xcf,
M_DHT = 0xc4,
M_DAC = 0xcc,
M_RST0 = 0xd0,
M_RST1 = 0xd1,
M_RST2 = 0xd2,
M_RST3 = 0xd3,
M_RST4 = 0xd4,
M_RST5 = 0xd5,
M_RST6 = 0xd6,
M_RST7 = 0xd7,
M_SOI = 0xd8,
M_EOI = 0xd9,
M_SOS = 0xda,
M_DQT = 0xdb,
M_DNL = 0xdc,
M_DRI = 0xdd,
M_DHP = 0xde,
M_EXP = 0xdf,
M_APP0 = 0xe0,
M_APP1 = 0xe1,
M_APP2 = 0xe2,
M_APP3 = 0xe3,
M_APP4 = 0xe4,
M_APP5 = 0xe5,
M_APP6 = 0xe6,
M_APP7 = 0xe7,
M_APP8 = 0xe8,
M_APP9 = 0xe9,
M_APP10 = 0xea,
M_APP11 = 0xeb,
M_APP12 = 0xec,
M_APP13 = 0xed,
M_APP14 = 0xee,
M_APP15 = 0xef,
M_JPG0 = 0xf0,
M_JPG8 = 0xf8,
M_JPG13 = 0xfd,
M_COM = 0xfe,
M_TEM = 0x01,
M_ERROR = 0x100
} JPEG_MARKER;
/* Private state */
typedef struct {
struct jpeg_marker_reader pub; /* public fields */
/* Application-overridable marker processing methods */
jpeg_marker_parser_method process_COM;
jpeg_marker_parser_method process_APPn[16];
/* Limit on marker data length to save for each marker type */
unsigned int length_limit_COM;
unsigned int length_limit_APPn[16];
/* Status of COM/APPn marker saving */
jpeg_saved_marker_ptr cur_marker; /* NULL if not processing a marker */
unsigned int bytes_read; /* data bytes read so far in marker */
/* Note: cur_marker is not linked into marker_list until it's all read. */
} my_marker_reader;
typedef my_marker_reader * my_marker_ptr;
/*
* Macros for fetching data from the data source module.
*
* At all times, cinfo->src->next_input_byte and ->bytes_in_buffer reflect
* the current restart point; we update them only when we have reached a
* suitable place to restart if a suspension occurs.
*/
/* Declare and initialize local copies of input pointer/count */
#define INPUT_VARS(cinfo) \
struct jpeg_source_mgr * datasrc = (cinfo)->src; \
const JOCTET * next_input_byte = datasrc->next_input_byte; \
size_t bytes_in_buffer = datasrc->bytes_in_buffer
/* Unload the local copies --- do this only at a restart boundary */
#define INPUT_SYNC(cinfo) \
( datasrc->next_input_byte = next_input_byte, \
datasrc->bytes_in_buffer = bytes_in_buffer )
/* Reload the local copies --- used only in MAKE_BYTE_AVAIL */
#define INPUT_RELOAD(cinfo) \
( next_input_byte = datasrc->next_input_byte, \
bytes_in_buffer = datasrc->bytes_in_buffer )
/* Internal macro for INPUT_BYTE and INPUT_2BYTES: make a byte available.
* Note we do *not* do INPUT_SYNC before calling fill_input_buffer,
* but we must reload the local copies after a successful fill.
*/
#define MAKE_BYTE_AVAIL(cinfo,action) \
if (bytes_in_buffer == 0) { \
if (! (*datasrc->fill_input_buffer) (cinfo)) \
{ action; } \
INPUT_RELOAD(cinfo); \
}
/* Read a byte into variable V.
* If must suspend, take the specified action (typically "return FALSE").
*/
#define INPUT_BYTE(cinfo,V,action) \
MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
bytes_in_buffer--; \
V = GETJOCTET(*next_input_byte++); )
/* As above, but read two bytes interpreted as an unsigned 16-bit integer.
* V should be declared unsigned int or perhaps INT32.
*/
#define INPUT_2BYTES(cinfo,V,action) \
MAKESTMT( MAKE_BYTE_AVAIL(cinfo,action); \
bytes_in_buffer--; \
V = ((unsigned int) GETJOCTET(*next_input_byte++)) << 8; \
MAKE_BYTE_AVAIL(cinfo,action); \
bytes_in_buffer--; \
V += GETJOCTET(*next_input_byte++); )
/*
* Routines to process JPEG markers.
*
* Entry condition: JPEG marker itself has been read and its code saved
* in cinfo->unread_marker; input restart point is just after the marker.
*
* Exit: if return TRUE, have read and processed any parameters, and have
* updated the restart point to point after the parameters.
* If return FALSE, was forced to suspend before reaching end of
* marker parameters; restart point has not been moved. Same routine
* will be called again after application supplies more input data.
*
* This approach to suspension assumes that all of a marker's parameters
* can fit into a single input bufferload. This should hold for "normal"
* markers. Some COM/APPn markers might have large parameter segments
* that might not fit. If we are simply dropping such a marker, we use
* skip_input_data to get past it, and thereby put the problem on the
* source manager's shoulders. If we are saving the marker's contents
* into memory, we use a slightly different convention: when forced to
* suspend, the marker processor updates the restart point to the end of
* what it's consumed (ie, the end of the buffer) before returning FALSE.
* On resumption, cinfo->unread_marker still contains the marker code,
* but the data source will point to the next chunk of marker data.
* The marker processor must retain internal state to deal with this.
*
* Note that we don't bother to avoid duplicate trace messages if a
* suspension occurs within marker parameters. Other side effects
* require more care.
*/
LOCAL(boolean)
get_soi (j_decompress_ptr cinfo)
/* Process an SOI marker */
{
int i;
TRACEMS(cinfo, 1, JTRC_SOI);
if (cinfo->marker->saw_SOI)
ERREXIT(cinfo, JERR_SOI_DUPLICATE);
/* Reset all parameters that are defined to be reset by SOI */
for (i = 0; i < NUM_ARITH_TBLS; i++) {
cinfo->arith_dc_L[i] = 0;
cinfo->arith_dc_U[i] = 1;
cinfo->arith_ac_K[i] = 5;
}
cinfo->restart_interval = 0;
/* Set initial assumptions for colorspace etc */
cinfo->jpeg_color_space = JCS_UNKNOWN;
cinfo->color_transform = JCT_NONE;
cinfo->CCIR601_sampling = FALSE; /* Assume non-CCIR sampling??? */
cinfo->saw_JFIF_marker = FALSE;
cinfo->JFIF_major_version = 1; /* set default JFIF APP0 values */
cinfo->JFIF_minor_version = 1;
cinfo->density_unit = 0;
cinfo->X_density = 1;
cinfo->Y_density = 1;
cinfo->saw_Adobe_marker = FALSE;
cinfo->Adobe_transform = 0;
cinfo->marker->saw_SOI = TRUE;
return TRUE;
}
LOCAL(boolean)
get_sof (j_decompress_ptr cinfo, boolean is_baseline, boolean is_prog,
boolean is_arith)
/* Process a SOFn marker */
{
INT32 length;
int c, ci, i;
jpeg_component_info * compptr;
INPUT_VARS(cinfo);
cinfo->is_baseline = is_baseline;
cinfo->progressive_mode = is_prog;
cinfo->arith_code = is_arith;
INPUT_2BYTES(cinfo, length, return FALSE);
INPUT_BYTE(cinfo, cinfo->data_precision, return FALSE);
INPUT_2BYTES(cinfo, cinfo->image_height, return FALSE);
INPUT_2BYTES(cinfo, cinfo->image_width, return FALSE);
INPUT_BYTE(cinfo, cinfo->num_components, return FALSE);
length -= 8;
TRACEMS4(cinfo, 1, JTRC_SOF, cinfo->unread_marker,
(int) cinfo->image_width, (int) cinfo->image_height,
cinfo->num_components);
if (cinfo->marker->saw_SOF)
ERREXIT(cinfo, JERR_SOF_DUPLICATE);
/* We don't support files in which the image height is initially specified */
/* as 0 and is later redefined by DNL. As long as we have to check that, */
/* might as well have a general sanity check. */
if (cinfo->image_height <= 0 || cinfo->image_width <= 0 ||
cinfo->num_components <= 0)
ERREXIT(cinfo, JERR_EMPTY_IMAGE);
if (length != (cinfo->num_components * 3))
ERREXIT(cinfo, JERR_BAD_LENGTH);
if (cinfo->comp_info == NULL) /* do only once, even if suspend */
cinfo->comp_info = (jpeg_component_info *) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_IMAGE,
cinfo->num_components * SIZEOF(jpeg_component_info));
for (ci = 0; ci < cinfo->num_components; ci++) {
INPUT_BYTE(cinfo, c, return FALSE);
/* Check to see whether component id has already been seen */
/* (in violation of the spec, but unfortunately seen in some */
/* files). If so, create "fake" component id equal to the */
/* max id seen so far + 1. */
for (i = 0, compptr = cinfo->comp_info; i < ci; i++, compptr++) {
if (c == compptr->component_id) {
compptr = cinfo->comp_info;
c = compptr->component_id;
compptr++;
for (i = 1; i < ci; i++, compptr++) {
if (compptr->component_id > c) c = compptr->component_id;
}
c++;
break;
}
}
compptr->component_id = c;
compptr->component_index = ci;
INPUT_BYTE(cinfo, c, return FALSE);
compptr->h_samp_factor = (c >> 4) & 15;
compptr->v_samp_factor = (c ) & 15;
INPUT_BYTE(cinfo, compptr->quant_tbl_no, return FALSE);
TRACEMS4(cinfo, 1, JTRC_SOF_COMPONENT,
compptr->component_id, compptr->h_samp_factor,
compptr->v_samp_factor, compptr->quant_tbl_no);
}
cinfo->marker->saw_SOF = TRUE;
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_sos (j_decompress_ptr cinfo)
/* Process a SOS marker */
{
INT32 length;
int c, ci, i, n;
jpeg_component_info * compptr;
INPUT_VARS(cinfo);
if (! cinfo->marker->saw_SOF)
ERREXITS(cinfo, JERR_SOF_BEFORE, "SOS");
INPUT_2BYTES(cinfo, length, return FALSE);
INPUT_BYTE(cinfo, n, return FALSE); /* Number of components */
TRACEMS1(cinfo, 1, JTRC_SOS, n);
if (length != (n * 2 + 6) || n > MAX_COMPS_IN_SCAN ||
(n == 0 && !cinfo->progressive_mode))
/* pseudo SOS marker only allowed in progressive mode */
ERREXIT(cinfo, JERR_BAD_LENGTH);
cinfo->comps_in_scan = n;
/* Collect the component-spec parameters */
for (i = 0; i < n; i++) {
INPUT_BYTE(cinfo, c, return FALSE);
/* Detect the case where component id's are not unique, and, if so, */
/* create a fake component id using the same logic as in get_sof. */
/* Note: This also ensures that all of the SOF components are */
/* referenced in the single scan case, which prevents access to */
/* uninitialized memory in later decoding stages. */
for (ci = 0; ci < i; ci++) {
if (c == cinfo->cur_comp_info[ci]->component_id) {
c = cinfo->cur_comp_info[0]->component_id;
for (ci = 1; ci < i; ci++) {
compptr = cinfo->cur_comp_info[ci];
if (compptr->component_id > c) c = compptr->component_id;
}
c++;
break;
}
}
for (ci = 0, compptr = cinfo->comp_info; ci < cinfo->num_components;
ci++, compptr++) {
if (c == compptr->component_id)
goto id_found;
}
ERREXIT1(cinfo, JERR_BAD_COMPONENT_ID, c);
id_found:
cinfo->cur_comp_info[i] = compptr;
INPUT_BYTE(cinfo, c, return FALSE);
compptr->dc_tbl_no = (c >> 4) & 15;
compptr->ac_tbl_no = (c ) & 15;
TRACEMS3(cinfo, 1, JTRC_SOS_COMPONENT, compptr->component_id,
compptr->dc_tbl_no, compptr->ac_tbl_no);
}
/* Collect the additional scan parameters Ss, Se, Ah/Al. */
INPUT_BYTE(cinfo, c, return FALSE);
cinfo->Ss = c;
INPUT_BYTE(cinfo, c, return FALSE);
cinfo->Se = c;
INPUT_BYTE(cinfo, c, return FALSE);
cinfo->Ah = (c >> 4) & 15;
cinfo->Al = (c ) & 15;
TRACEMS4(cinfo, 1, JTRC_SOS_PARAMS, cinfo->Ss, cinfo->Se,
cinfo->Ah, cinfo->Al);
/* Prepare to scan data & restart markers */
cinfo->marker->next_restart_num = 0;
/* Count another (non-pseudo) SOS marker */
if (n) cinfo->input_scan_number++;
INPUT_SYNC(cinfo);
return TRUE;
}
#ifdef D_ARITH_CODING_SUPPORTED
LOCAL(boolean)
get_dac (j_decompress_ptr cinfo)
/* Process a DAC marker */
{
INT32 length;
int index, val;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
while (length > 0) {
INPUT_BYTE(cinfo, index, return FALSE);
INPUT_BYTE(cinfo, val, return FALSE);
length -= 2;
TRACEMS2(cinfo, 1, JTRC_DAC, index, val);
if (index < 0 || index >= (2*NUM_ARITH_TBLS))
ERREXIT1(cinfo, JERR_DAC_INDEX, index);
if (index >= NUM_ARITH_TBLS) { /* define AC table */
cinfo->arith_ac_K[index-NUM_ARITH_TBLS] = (UINT8) val;
} else { /* define DC table */
cinfo->arith_dc_L[index] = (UINT8) (val & 0x0F);
cinfo->arith_dc_U[index] = (UINT8) (val >> 4);
if (cinfo->arith_dc_L[index] > cinfo->arith_dc_U[index])
ERREXIT1(cinfo, JERR_DAC_VALUE, val);
}
}
if (length != 0)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_SYNC(cinfo);
return TRUE;
}
#else /* ! D_ARITH_CODING_SUPPORTED */
#define get_dac(cinfo) skip_variable(cinfo)
#endif /* D_ARITH_CODING_SUPPORTED */
LOCAL(boolean)
get_dht (j_decompress_ptr cinfo)
/* Process a DHT marker */
{
INT32 length;
UINT8 bits[17];
UINT8 huffval[256];
int i, index, count;
JHUFF_TBL **htblptr;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
while (length > 16) {
INPUT_BYTE(cinfo, index, return FALSE);
TRACEMS1(cinfo, 1, JTRC_DHT, index);
bits[0] = 0;
count = 0;
for (i = 1; i <= 16; i++) {
INPUT_BYTE(cinfo, bits[i], return FALSE);
count += bits[i];
}
length -= 1 + 16;
TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
bits[1], bits[2], bits[3], bits[4],
bits[5], bits[6], bits[7], bits[8]);
TRACEMS8(cinfo, 2, JTRC_HUFFBITS,
bits[9], bits[10], bits[11], bits[12],
bits[13], bits[14], bits[15], bits[16]);
/* Here we just do minimal validation of the counts to avoid walking
* off the end of our table space. jdhuff.c will check more carefully.
*/
if (count > 256 || ((INT32) count) > length)
ERREXIT(cinfo, JERR_BAD_HUFF_TABLE);
for (i = 0; i < count; i++)
INPUT_BYTE(cinfo, huffval[i], return FALSE);
length -= count;
if (index & 0x10) { /* AC table definition */
index -= 0x10;
htblptr = &cinfo->ac_huff_tbl_ptrs[index];
} else { /* DC table definition */
htblptr = &cinfo->dc_huff_tbl_ptrs[index];
}
if (index < 0 || index >= NUM_HUFF_TBLS)
ERREXIT1(cinfo, JERR_DHT_INDEX, index);
if (*htblptr == NULL)
*htblptr = jpeg_alloc_huff_table((j_common_ptr) cinfo);
MEMCOPY((*htblptr)->bits, bits, SIZEOF((*htblptr)->bits));
if (count > 0)
MEMCOPY((*htblptr)->huffval, huffval, count * SIZEOF(UINT8));
}
if (length != 0)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_dqt (j_decompress_ptr cinfo)
/* Process a DQT marker */
{
INT32 length, count, i;
int n, prec;
unsigned int tmp;
JQUANT_TBL *quant_ptr;
const int *natural_order;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
while (length > 0) {
length--;
INPUT_BYTE(cinfo, n, return FALSE);
prec = n >> 4;
n &= 0x0F;
TRACEMS2(cinfo, 1, JTRC_DQT, n, prec);
if (n >= NUM_QUANT_TBLS)
ERREXIT1(cinfo, JERR_DQT_INDEX, n);
if (cinfo->quant_tbl_ptrs[n] == NULL)
cinfo->quant_tbl_ptrs[n] = jpeg_alloc_quant_table((j_common_ptr) cinfo);
quant_ptr = cinfo->quant_tbl_ptrs[n];
if (prec) {
if (length < DCTSIZE2 * 2) {
/* Initialize full table for safety. */
for (i = 0; i < DCTSIZE2; i++) {
quant_ptr->quantval[i] = 1;
}
count = length >> 1;
} else
count = DCTSIZE2;
} else {
if (length < DCTSIZE2) {
/* Initialize full table for safety. */
for (i = 0; i < DCTSIZE2; i++) {
quant_ptr->quantval[i] = 1;
}
count = length;
} else
count = DCTSIZE2;
}
switch ((int) count) {
case (2*2): natural_order = jpeg_natural_order2; break;
case (3*3): natural_order = jpeg_natural_order3; break;
case (4*4): natural_order = jpeg_natural_order4; break;
case (5*5): natural_order = jpeg_natural_order5; break;
case (6*6): natural_order = jpeg_natural_order6; break;
case (7*7): natural_order = jpeg_natural_order7; break;
default: natural_order = jpeg_natural_order;
}
for (i = 0; i < count; i++) {
if (prec)
INPUT_2BYTES(cinfo, tmp, return FALSE);
else
INPUT_BYTE(cinfo, tmp, return FALSE);
/* We convert the zigzag-order table to natural array order. */
quant_ptr->quantval[natural_order[i]] = (UINT16) tmp;
}
if (cinfo->err->trace_level >= 2) {
for (i = 0; i < DCTSIZE2; i += 8) {
TRACEMS8(cinfo, 2, JTRC_QUANTVALS,
quant_ptr->quantval[i], quant_ptr->quantval[i+1],
quant_ptr->quantval[i+2], quant_ptr->quantval[i+3],
quant_ptr->quantval[i+4], quant_ptr->quantval[i+5],
quant_ptr->quantval[i+6], quant_ptr->quantval[i+7]);
}
}
length -= count;
if (prec) length -= count;
}
if (length != 0)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_dri (j_decompress_ptr cinfo)
/* Process a DRI marker */
{
INT32 length;
unsigned int tmp;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
if (length != 4)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_2BYTES(cinfo, tmp, return FALSE);
TRACEMS1(cinfo, 1, JTRC_DRI, tmp);
cinfo->restart_interval = tmp;
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
get_lse (j_decompress_ptr cinfo)
/* Process an LSE marker */
{
INT32 length;
unsigned int tmp;
int cid;
INPUT_VARS(cinfo);
if (! cinfo->marker->saw_SOF)
ERREXITS(cinfo, JERR_SOF_BEFORE, "LSE");
if (cinfo->num_components < 3) goto bad;
INPUT_2BYTES(cinfo, length, return FALSE);
if (length != 24)
ERREXIT(cinfo, JERR_BAD_LENGTH);
INPUT_BYTE(cinfo, tmp, return FALSE);
if (tmp != 0x0D) /* ID inverse transform specification */
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != MAXJSAMPLE) goto bad; /* MAXTRANS */
INPUT_BYTE(cinfo, tmp, return FALSE);
if (tmp != 3) goto bad; /* Nt=3 */
INPUT_BYTE(cinfo, cid, return FALSE);
if (cid != cinfo->comp_info[1].component_id) goto bad;
INPUT_BYTE(cinfo, cid, return FALSE);
if (cid != cinfo->comp_info[0].component_id) goto bad;
INPUT_BYTE(cinfo, cid, return FALSE);
if (cid != cinfo->comp_info[2].component_id) goto bad;
INPUT_BYTE(cinfo, tmp, return FALSE);
if (tmp != 0x80) goto bad; /* F1: CENTER1=1, NORM1=0 */
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != 0) goto bad; /* A(1,1)=0 */
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != 0) goto bad; /* A(1,2)=0 */
INPUT_BYTE(cinfo, tmp, return FALSE);
if (tmp != 0) goto bad; /* F2: CENTER2=0, NORM2=0 */
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != 1) goto bad; /* A(2,1)=1 */
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != 0) goto bad; /* A(2,2)=0 */
INPUT_BYTE(cinfo, tmp, return FALSE);
if (tmp != 0) goto bad; /* F3: CENTER3=0, NORM3=0 */
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != 1) goto bad; /* A(3,1)=1 */
INPUT_2BYTES(cinfo, tmp, return FALSE);
if (tmp != 0) { /* A(3,2)=0 */
bad:
ERREXIT(cinfo, JERR_CONVERSION_NOTIMPL);
}
/* OK, valid transform that we can handle. */
cinfo->color_transform = JCT_SUBTRACT_GREEN;
INPUT_SYNC(cinfo);
return TRUE;
}
/*
* Routines for processing APPn and COM markers.
* These are either saved in memory or discarded, per application request.
* APP0 and APP14 are specially checked to see if they are
* JFIF and Adobe markers, respectively.
*/
#define APP0_DATA_LEN 14 /* Length of interesting data in APP0 */
#define APP14_DATA_LEN 12 /* Length of interesting data in APP14 */
#define APPN_DATA_LEN 14 /* Must be the largest of the above!! */
LOCAL(void)
examine_app0 (j_decompress_ptr cinfo, JOCTET FAR * data,
unsigned int datalen, INT32 remaining)
/* Examine first few bytes from an APP0.
* Take appropriate action if it is a JFIF marker.
* datalen is # of bytes at data[], remaining is length of rest of marker data.
*/
{
INT32 totallen = (INT32) datalen + remaining;
if (datalen >= APP0_DATA_LEN &&
GETJOCTET(data[0]) == 0x4A &&
GETJOCTET(data[1]) == 0x46 &&
GETJOCTET(data[2]) == 0x49 &&
GETJOCTET(data[3]) == 0x46 &&
GETJOCTET(data[4]) == 0) {
/* Found JFIF APP0 marker: save info */
cinfo->saw_JFIF_marker = TRUE;
cinfo->JFIF_major_version = GETJOCTET(data[5]);
cinfo->JFIF_minor_version = GETJOCTET(data[6]);
cinfo->density_unit = GETJOCTET(data[7]);
cinfo->X_density = (GETJOCTET(data[8]) << 8) + GETJOCTET(data[9]);
cinfo->Y_density = (GETJOCTET(data[10]) << 8) + GETJOCTET(data[11]);
/* Check version.
* Major version must be 1 or 2, anything else signals an incompatible
* change.
* (We used to treat this as an error, but now it's a nonfatal warning,
* because some bozo at Hijaak couldn't read the spec.)
* Minor version should be 0..2, but process anyway if newer.
*/
if (cinfo->JFIF_major_version != 1 && cinfo->JFIF_major_version != 2)
WARNMS2(cinfo, JWRN_JFIF_MAJOR,
cinfo->JFIF_major_version, cinfo->JFIF_minor_version);
/* Generate trace messages */
TRACEMS5(cinfo, 1, JTRC_JFIF,
cinfo->JFIF_major_version, cinfo->JFIF_minor_version,
cinfo->X_density, cinfo->Y_density, cinfo->density_unit);
/* Validate thumbnail dimensions and issue appropriate messages */
if (GETJOCTET(data[12]) | GETJOCTET(data[13]))
TRACEMS2(cinfo, 1, JTRC_JFIF_THUMBNAIL,
GETJOCTET(data[12]), GETJOCTET(data[13]));
totallen -= APP0_DATA_LEN;
if (totallen !=
((INT32)GETJOCTET(data[12]) * (INT32)GETJOCTET(data[13]) * (INT32) 3))
TRACEMS1(cinfo, 1, JTRC_JFIF_BADTHUMBNAILSIZE, (int) totallen);
} else if (datalen >= 6 &&
GETJOCTET(data[0]) == 0x4A &&
GETJOCTET(data[1]) == 0x46 &&
GETJOCTET(data[2]) == 0x58 &&
GETJOCTET(data[3]) == 0x58 &&
GETJOCTET(data[4]) == 0) {
/* Found JFIF "JFXX" extension APP0 marker */
/* The library doesn't actually do anything with these,
* but we try to produce a helpful trace message.
*/
switch (GETJOCTET(data[5])) {
case 0x10:
TRACEMS1(cinfo, 1, JTRC_THUMB_JPEG, (int) totallen);
break;
case 0x11:
TRACEMS1(cinfo, 1, JTRC_THUMB_PALETTE, (int) totallen);
break;
case 0x13:
TRACEMS1(cinfo, 1, JTRC_THUMB_RGB, (int) totallen);
break;
default:
TRACEMS2(cinfo, 1, JTRC_JFIF_EXTENSION,
GETJOCTET(data[5]), (int) totallen);
}
} else {
/* Start of APP0 does not match "JFIF" or "JFXX", or too short */
TRACEMS1(cinfo, 1, JTRC_APP0, (int) totallen);
}
}
LOCAL(void)
examine_app14 (j_decompress_ptr cinfo, JOCTET FAR * data,
unsigned int datalen, INT32 remaining)
/* Examine first few bytes from an APP14.
* Take appropriate action if it is an Adobe marker.
* datalen is # of bytes at data[], remaining is length of rest of marker data.
*/
{
unsigned int version, flags0, flags1, transform;
if (datalen >= APP14_DATA_LEN &&
GETJOCTET(data[0]) == 0x41 &&
GETJOCTET(data[1]) == 0x64 &&
GETJOCTET(data[2]) == 0x6F &&
GETJOCTET(data[3]) == 0x62 &&
GETJOCTET(data[4]) == 0x65) {
/* Found Adobe APP14 marker */
version = (GETJOCTET(data[5]) << 8) + GETJOCTET(data[6]);
flags0 = (GETJOCTET(data[7]) << 8) + GETJOCTET(data[8]);
flags1 = (GETJOCTET(data[9]) << 8) + GETJOCTET(data[10]);
transform = GETJOCTET(data[11]);
TRACEMS4(cinfo, 1, JTRC_ADOBE, version, flags0, flags1, transform);
cinfo->saw_Adobe_marker = TRUE;
cinfo->Adobe_transform = (UINT8) transform;
} else {
/* Start of APP14 does not match "Adobe", or too short */
TRACEMS1(cinfo, 1, JTRC_APP14, (int) (datalen + remaining));
}
}
METHODDEF(boolean)
get_interesting_appn (j_decompress_ptr cinfo)
/* Process an APP0 or APP14 marker without saving it */
{
INT32 length;
JOCTET b[APPN_DATA_LEN];
unsigned int i, numtoread;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
/* get the interesting part of the marker data */
if (length >= APPN_DATA_LEN)
numtoread = APPN_DATA_LEN;
else if (length > 0)
numtoread = (unsigned int) length;
else
numtoread = 0;
for (i = 0; i < numtoread; i++)
INPUT_BYTE(cinfo, b[i], return FALSE);
length -= numtoread;
/* process it */
switch (cinfo->unread_marker) {
case M_APP0:
examine_app0(cinfo, (JOCTET FAR *) b, numtoread, length);
break;
case M_APP14:
examine_app14(cinfo, (JOCTET FAR *) b, numtoread, length);
break;
default:
/* can't get here unless jpeg_save_markers chooses wrong processor */
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
}
/* skip any remaining data -- could be lots */
INPUT_SYNC(cinfo);
if (length > 0)
(*cinfo->src->skip_input_data) (cinfo, (long) length);
return TRUE;
}
#ifdef SAVE_MARKERS_SUPPORTED
METHODDEF(boolean)
save_marker (j_decompress_ptr cinfo)
/* Save an APPn or COM marker into the marker list */
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
jpeg_saved_marker_ptr cur_marker = marker->cur_marker;
unsigned int bytes_read, data_length;
JOCTET FAR * data;
INT32 length = 0;
INPUT_VARS(cinfo);
if (cur_marker == NULL) {
/* begin reading a marker */
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
if (length >= 0) { /* watch out for bogus length word */
/* figure out how much we want to save */
unsigned int limit;
if (cinfo->unread_marker == (int) M_COM)
limit = marker->length_limit_COM;
else
limit = marker->length_limit_APPn[cinfo->unread_marker - (int) M_APP0];
if ((unsigned int) length < limit)
limit = (unsigned int) length;
/* allocate and initialize the marker item */
cur_marker = (jpeg_saved_marker_ptr)
(*cinfo->mem->alloc_large) ((j_common_ptr) cinfo, JPOOL_IMAGE,
SIZEOF(struct jpeg_marker_struct) + limit);
cur_marker->next = NULL;
cur_marker->marker = (UINT8) cinfo->unread_marker;
cur_marker->original_length = (unsigned int) length;
cur_marker->data_length = limit;
/* data area is just beyond the jpeg_marker_struct */
data = cur_marker->data = (JOCTET FAR *) (cur_marker + 1);
marker->cur_marker = cur_marker;
marker->bytes_read = 0;
bytes_read = 0;
data_length = limit;
} else {
/* deal with bogus length word */
bytes_read = data_length = 0;
data = NULL;
}
} else {
/* resume reading a marker */
bytes_read = marker->bytes_read;
data_length = cur_marker->data_length;
data = cur_marker->data + bytes_read;
}
while (bytes_read < data_length) {
INPUT_SYNC(cinfo); /* move the restart point to here */
marker->bytes_read = bytes_read;
/* If there's not at least one byte in buffer, suspend */
MAKE_BYTE_AVAIL(cinfo, return FALSE);
/* Copy bytes with reasonable rapidity */
while (bytes_read < data_length && bytes_in_buffer > 0) {
*data++ = *next_input_byte++;
bytes_in_buffer--;
bytes_read++;
}
}
/* Done reading what we want to read */
if (cur_marker != NULL) { /* will be NULL if bogus length word */
/* Add new marker to end of list */
if (cinfo->marker_list == NULL) {
cinfo->marker_list = cur_marker;
} else {
jpeg_saved_marker_ptr prev = cinfo->marker_list;
while (prev->next != NULL)
prev = prev->next;
prev->next = cur_marker;
}
/* Reset pointer & calc remaining data length */
data = cur_marker->data;
length = cur_marker->original_length - data_length;
}
/* Reset to initial state for next marker */
marker->cur_marker = NULL;
/* Process the marker if interesting; else just make a generic trace msg */
switch (cinfo->unread_marker) {
case M_APP0:
examine_app0(cinfo, data, data_length, length);
break;
case M_APP14:
examine_app14(cinfo, data, data_length, length);
break;
default:
TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker,
(int) (data_length + length));
}
/* skip any remaining data -- could be lots */
INPUT_SYNC(cinfo); /* do before skip_input_data */
if (length > 0)
(*cinfo->src->skip_input_data) (cinfo, (long) length);
return TRUE;
}
#endif /* SAVE_MARKERS_SUPPORTED */
METHODDEF(boolean)
skip_variable (j_decompress_ptr cinfo)
/* Skip over an unknown or uninteresting variable-length marker */
{
INT32 length;
INPUT_VARS(cinfo);
INPUT_2BYTES(cinfo, length, return FALSE);
length -= 2;
TRACEMS2(cinfo, 1, JTRC_MISC_MARKER, cinfo->unread_marker, (int) length);
INPUT_SYNC(cinfo); /* do before skip_input_data */
if (length > 0)
(*cinfo->src->skip_input_data) (cinfo, (long) length);
return TRUE;
}
/*
* Find the next JPEG marker, save it in cinfo->unread_marker.
* Returns FALSE if had to suspend before reaching a marker;
* in that case cinfo->unread_marker is unchanged.
*
* Note that the result might not be a valid marker code,
* but it will never be 0 or FF.
*/
LOCAL(boolean)
next_marker (j_decompress_ptr cinfo)
{
int c;
INPUT_VARS(cinfo);
for (;;) {
INPUT_BYTE(cinfo, c, return FALSE);
/* Skip any non-FF bytes.
* This may look a bit inefficient, but it will not occur in a valid file.
* We sync after each discarded byte so that a suspending data source
* can discard the byte from its buffer.
*/
while (c != 0xFF) {
cinfo->marker->discarded_bytes++;
INPUT_SYNC(cinfo);
INPUT_BYTE(cinfo, c, return FALSE);
}
/* This loop swallows any duplicate FF bytes. Extra FFs are legal as
* pad bytes, so don't count them in discarded_bytes. We assume there
* will not be so many consecutive FF bytes as to overflow a suspending
* data source's input buffer.
*/
do {
INPUT_BYTE(cinfo, c, return FALSE);
} while (c == 0xFF);
if (c != 0)
break; /* found a valid marker, exit loop */
/* Reach here if we found a stuffed-zero data sequence (FF/00).
* Discard it and loop back to try again.
*/
cinfo->marker->discarded_bytes += 2;
INPUT_SYNC(cinfo);
}
if (cinfo->marker->discarded_bytes != 0) {
WARNMS2(cinfo, JWRN_EXTRANEOUS_DATA, cinfo->marker->discarded_bytes, c);
cinfo->marker->discarded_bytes = 0;
}
cinfo->unread_marker = c;
INPUT_SYNC(cinfo);
return TRUE;
}
LOCAL(boolean)
first_marker (j_decompress_ptr cinfo)
/* Like next_marker, but used to obtain the initial SOI marker. */
/* For this marker, we do not allow preceding garbage or fill; otherwise,
* we might well scan an entire input file before realizing it ain't JPEG.
* If an application wants to process non-JFIF files, it must seek to the
* SOI before calling the JPEG library.
*/
{
int c, c2;
INPUT_VARS(cinfo);
INPUT_BYTE(cinfo, c, return FALSE);
INPUT_BYTE(cinfo, c2, return FALSE);
if (c != 0xFF || c2 != (int) M_SOI)
ERREXIT2(cinfo, JERR_NO_SOI, c, c2);
cinfo->unread_marker = c2;
INPUT_SYNC(cinfo);
return TRUE;
}
/*
* Read markers until SOS or EOI.
*
* Returns same codes as are defined for jpeg_consume_input:
* JPEG_SUSPENDED, JPEG_REACHED_SOS, or JPEG_REACHED_EOI.
*
* Note: This function may return a pseudo SOS marker (with zero
* component number) for treat by input controller's consume_input.
* consume_input itself should filter out (skip) the pseudo marker
* after processing for the caller.
*/
METHODDEF(int)
read_markers (j_decompress_ptr cinfo)
{
/* Outer loop repeats once for each marker. */
for (;;) {
/* Collect the marker proper, unless we already did. */
/* NB: first_marker() enforces the requirement that SOI appear first. */
if (cinfo->unread_marker == 0) {
if (! cinfo->marker->saw_SOI) {
if (! first_marker(cinfo))
return JPEG_SUSPENDED;
} else {
if (! next_marker(cinfo))
return JPEG_SUSPENDED;
}
}
/* At this point cinfo->unread_marker contains the marker code and the
* input point is just past the marker proper, but before any parameters.
* A suspension will cause us to return with this state still true.
*/
switch (cinfo->unread_marker) {
case M_SOI:
if (! get_soi(cinfo))
return JPEG_SUSPENDED;
break;
case M_SOF0: /* Baseline */
if (! get_sof(cinfo, TRUE, FALSE, FALSE))
return JPEG_SUSPENDED;
break;
case M_SOF1: /* Extended sequential, Huffman */
if (! get_sof(cinfo, FALSE, FALSE, FALSE))
return JPEG_SUSPENDED;
break;
case M_SOF2: /* Progressive, Huffman */
if (! get_sof(cinfo, FALSE, TRUE, FALSE))
return JPEG_SUSPENDED;
break;
case M_SOF9: /* Extended sequential, arithmetic */
if (! get_sof(cinfo, FALSE, FALSE, TRUE))
return JPEG_SUSPENDED;
break;
case M_SOF10: /* Progressive, arithmetic */
if (! get_sof(cinfo, FALSE, TRUE, TRUE))
return JPEG_SUSPENDED;
break;
/* Currently unsupported SOFn types */
case M_SOF3: /* Lossless, Huffman */
case M_SOF5: /* Differential sequential, Huffman */
case M_SOF6: /* Differential progressive, Huffman */
case M_SOF7: /* Differential lossless, Huffman */
case M_JPG: /* Reserved for JPEG extensions */
case M_SOF11: /* Lossless, arithmetic */
case M_SOF13: /* Differential sequential, arithmetic */
case M_SOF14: /* Differential progressive, arithmetic */
case M_SOF15: /* Differential lossless, arithmetic */
ERREXIT1(cinfo, JERR_SOF_UNSUPPORTED, cinfo->unread_marker);
break;
case M_SOS:
if (! get_sos(cinfo))
return JPEG_SUSPENDED;
cinfo->unread_marker = 0; /* processed the marker */
return JPEG_REACHED_SOS;
case M_EOI:
TRACEMS(cinfo, 1, JTRC_EOI);
cinfo->unread_marker = 0; /* processed the marker */
return JPEG_REACHED_EOI;
case M_DAC:
if (! get_dac(cinfo))
return JPEG_SUSPENDED;
break;
case M_DHT:
if (! get_dht(cinfo))
return JPEG_SUSPENDED;
break;
case M_DQT:
if (! get_dqt(cinfo))
return JPEG_SUSPENDED;
break;
case M_DRI:
if (! get_dri(cinfo))
return JPEG_SUSPENDED;
break;
case M_JPG8:
if (! get_lse(cinfo))
return JPEG_SUSPENDED;
break;
case M_APP0:
case M_APP1:
case M_APP2:
case M_APP3:
case M_APP4:
case M_APP5:
case M_APP6:
case M_APP7:
case M_APP8:
case M_APP9:
case M_APP10:
case M_APP11:
case M_APP12:
case M_APP13:
case M_APP14:
case M_APP15:
if (! (*((my_marker_ptr) cinfo->marker)->process_APPn[
cinfo->unread_marker - (int) M_APP0]) (cinfo))
return JPEG_SUSPENDED;
break;
case M_COM:
if (! (*((my_marker_ptr) cinfo->marker)->process_COM) (cinfo))
return JPEG_SUSPENDED;
break;
case M_RST0: /* these are all parameterless */
case M_RST1:
case M_RST2:
case M_RST3:
case M_RST4:
case M_RST5:
case M_RST6:
case M_RST7:
case M_TEM:
TRACEMS1(cinfo, 1, JTRC_PARMLESS_MARKER, cinfo->unread_marker);
break;
case M_DNL: /* Ignore DNL ... perhaps the wrong thing */
if (! skip_variable(cinfo))
return JPEG_SUSPENDED;
break;
default: /* must be DHP, EXP, JPGn, or RESn */
/* For now, we treat the reserved markers as fatal errors since they are
* likely to be used to signal incompatible JPEG Part 3 extensions.
* Once the JPEG 3 version-number marker is well defined, this code
* ought to change!
*/
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, cinfo->unread_marker);
}
/* Successfully processed marker, so reset state variable */
cinfo->unread_marker = 0;
} /* end loop */
}
/*
* Read a restart marker, which is expected to appear next in the datastream;
* if the marker is not there, take appropriate recovery action.
* Returns FALSE if suspension is required.
*
* This is called by the entropy decoder after it has read an appropriate
* number of MCUs. cinfo->unread_marker may be nonzero if the entropy decoder
* has already read a marker from the data source. Under normal conditions
* cinfo->unread_marker will be reset to 0 before returning; if not reset,
* it holds a marker which the decoder will be unable to read past.
*/
METHODDEF(boolean)
read_restart_marker (j_decompress_ptr cinfo)
{
/* Obtain a marker unless we already did. */
/* Note that next_marker will complain if it skips any data. */
if (cinfo->unread_marker == 0) {
if (! next_marker(cinfo))
return FALSE;
}
if (cinfo->unread_marker ==
((int) M_RST0 + cinfo->marker->next_restart_num)) {
/* Normal case --- swallow the marker and let entropy decoder continue */
TRACEMS1(cinfo, 3, JTRC_RST, cinfo->marker->next_restart_num);
cinfo->unread_marker = 0;
} else {
/* Uh-oh, the restart markers have been messed up. */
/* Let the data source manager determine how to resync. */
if (! (*cinfo->src->resync_to_restart) (cinfo,
cinfo->marker->next_restart_num))
return FALSE;
}
/* Update next-restart state */
cinfo->marker->next_restart_num = (cinfo->marker->next_restart_num + 1) & 7;
return TRUE;
}
/*
* This is the default resync_to_restart method for data source managers
* to use if they don't have any better approach. Some data source managers
* may be able to back up, or may have additional knowledge about the data
* which permits a more intelligent recovery strategy; such managers would
* presumably supply their own resync method.
*
* read_restart_marker calls resync_to_restart if it finds a marker other than
* the restart marker it was expecting. (This code is *not* used unless
* a nonzero restart interval has been declared.) cinfo->unread_marker is
* the marker code actually found (might be anything, except 0 or FF).
* The desired restart marker number (0..7) is passed as a parameter.
* This routine is supposed to apply whatever error recovery strategy seems
* appropriate in order to position the input stream to the next data segment.
* Note that cinfo->unread_marker is treated as a marker appearing before
* the current data-source input point; usually it should be reset to zero
* before returning.
* Returns FALSE if suspension is required.
*
* This implementation is substantially constrained by wanting to treat the
* input as a data stream; this means we can't back up. Therefore, we have
* only the following actions to work with:
* 1. Simply discard the marker and let the entropy decoder resume at next
* byte of file.
* 2. Read forward until we find another marker, discarding intervening
* data. (In theory we could look ahead within the current bufferload,
* without having to discard data if we don't find the desired marker.
* This idea is not implemented here, in part because it makes behavior
* dependent on buffer size and chance buffer-boundary positions.)
* 3. Leave the marker unread (by failing to zero cinfo->unread_marker).
* This will cause the entropy decoder to process an empty data segment,
* inserting dummy zeroes, and then we will reprocess the marker.
*
* #2 is appropriate if we think the desired marker lies ahead, while #3 is
* appropriate if the found marker is a future restart marker (indicating
* that we have missed the desired restart marker, probably because it got
* corrupted).
* We apply #2 or #3 if the found marker is a restart marker no more than
* two counts behind or ahead of the expected one. We also apply #2 if the
* found marker is not a legal JPEG marker code (it's certainly bogus data).
* If the found marker is a restart marker more than 2 counts away, we do #1
* (too much risk that the marker is erroneous; with luck we will be able to
* resync at some future point).
* For any valid non-restart JPEG marker, we apply #3. This keeps us from
* overrunning the end of a scan. An implementation limited to single-scan
* files might find it better to apply #2 for markers other than EOI, since
* any other marker would have to be bogus data in that case.
*/
GLOBAL(boolean)
jpeg_resync_to_restart (j_decompress_ptr cinfo, int desired)
{
int marker = cinfo->unread_marker;
int action = 1;
/* Always put up a warning. */
WARNMS2(cinfo, JWRN_MUST_RESYNC, marker, desired);
/* Outer loop handles repeated decision after scanning forward. */
for (;;) {
if (marker < (int) M_SOF0)
action = 2; /* invalid marker */
else if (marker < (int) M_RST0 || marker > (int) M_RST7)
action = 3; /* valid non-restart marker */
else {
if (marker == ((int) M_RST0 + ((desired+1) & 7)) ||
marker == ((int) M_RST0 + ((desired+2) & 7)))
action = 3; /* one of the next two expected restarts */
else if (marker == ((int) M_RST0 + ((desired-1) & 7)) ||
marker == ((int) M_RST0 + ((desired-2) & 7)))
action = 2; /* a prior restart, so advance */
else
action = 1; /* desired restart or too far away */
}
TRACEMS2(cinfo, 4, JTRC_RECOVERY_ACTION, marker, action);
switch (action) {
case 1:
/* Discard marker and let entropy decoder resume processing. */
cinfo->unread_marker = 0;
return TRUE;
case 2:
/* Scan to the next marker, and repeat the decision loop. */
if (! next_marker(cinfo))
return FALSE;
marker = cinfo->unread_marker;
break;
case 3:
/* Return without advancing past this marker. */
/* Entropy decoder will be forced to process an empty segment. */
return TRUE;
}
} /* end loop */
}
/*
* Reset marker processing state to begin a fresh datastream.
*/
METHODDEF(void)
reset_marker_reader (j_decompress_ptr cinfo)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
cinfo->comp_info = NULL; /* until allocated by get_sof */
cinfo->input_scan_number = 0; /* no SOS seen yet */
cinfo->unread_marker = 0; /* no pending marker */
marker->pub.saw_SOI = FALSE; /* set internal state too */
marker->pub.saw_SOF = FALSE;
marker->pub.discarded_bytes = 0;
marker->cur_marker = NULL;
}
/*
* Initialize the marker reader module.
* This is called only once, when the decompression object is created.
*/
GLOBAL(void)
jinit_marker_reader (j_decompress_ptr cinfo)
{
my_marker_ptr marker;
int i;
/* Create subobject in permanent pool */
marker = (my_marker_ptr) (*cinfo->mem->alloc_small)
((j_common_ptr) cinfo, JPOOL_PERMANENT, SIZEOF(my_marker_reader));
cinfo->marker = &marker->pub;
/* Initialize public method pointers */
marker->pub.reset_marker_reader = reset_marker_reader;
marker->pub.read_markers = read_markers;
marker->pub.read_restart_marker = read_restart_marker;
/* Initialize COM/APPn processing.
* By default, we examine and then discard APP0 and APP14,
* but simply discard COM and all other APPn.
*/
marker->process_COM = skip_variable;
marker->length_limit_COM = 0;
for (i = 0; i < 16; i++) {
marker->process_APPn[i] = skip_variable;
marker->length_limit_APPn[i] = 0;
}
marker->process_APPn[0] = get_interesting_appn;
marker->process_APPn[14] = get_interesting_appn;
/* Reset marker processing state */
reset_marker_reader(cinfo);
}
/*
* Control saving of COM and APPn markers into marker_list.
*/
#ifdef SAVE_MARKERS_SUPPORTED
GLOBAL(void)
jpeg_save_markers (j_decompress_ptr cinfo, int marker_code,
unsigned int length_limit)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
long maxlength;
jpeg_marker_parser_method processor;
/* Length limit mustn't be larger than what we can allocate
* (should only be a concern in a 16-bit environment).
*/
maxlength = cinfo->mem->max_alloc_chunk - SIZEOF(struct jpeg_marker_struct);
if (((long) length_limit) > maxlength)
length_limit = (unsigned int) maxlength;
/* Choose processor routine to use.
* APP0/APP14 have special requirements.
*/
if (length_limit) {
processor = save_marker;
/* If saving APP0/APP14, save at least enough for our internal use. */
if (marker_code == (int) M_APP0 && length_limit < APP0_DATA_LEN)
length_limit = APP0_DATA_LEN;
else if (marker_code == (int) M_APP14 && length_limit < APP14_DATA_LEN)
length_limit = APP14_DATA_LEN;
} else {
processor = skip_variable;
/* If discarding APP0/APP14, use our regular on-the-fly processor. */
if (marker_code == (int) M_APP0 || marker_code == (int) M_APP14)
processor = get_interesting_appn;
}
if (marker_code == (int) M_COM) {
marker->process_COM = processor;
marker->length_limit_COM = length_limit;
} else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15) {
marker->process_APPn[marker_code - (int) M_APP0] = processor;
marker->length_limit_APPn[marker_code - (int) M_APP0] = length_limit;
} else
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
}
#endif /* SAVE_MARKERS_SUPPORTED */
/*
* Install a special processing method for COM or APPn markers.
*/
GLOBAL(void)
jpeg_set_marker_processor (j_decompress_ptr cinfo, int marker_code,
jpeg_marker_parser_method routine)
{
my_marker_ptr marker = (my_marker_ptr) cinfo->marker;
if (marker_code == (int) M_COM)
marker->process_COM = routine;
else if (marker_code >= (int) M_APP0 && marker_code <= (int) M_APP15)
marker->process_APPn[marker_code - (int) M_APP0] = routine;
else
ERREXIT1(cinfo, JERR_UNKNOWN_MARKER, marker_code);
}
|
gpl-3.0
|
jqk6/robomongo
|
src/third-party/qscintilla/Qt3/qscilexerhtml.cpp
|
16
|
31781
|
// This module implements the QsciLexerHTML class.
//
// Copyright (c) 2014 Riverbank Computing Limited <info@riverbankcomputing.com>
//
// This file is part of QScintilla.
//
// 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 files LICENSE.GPL2 and LICENSE.GPL3
// included in the packaging of this file. Alternatively you may (at
// your option) use any later version of the GNU General Public
// License if such license has been publicly approved by Riverbank
// Computing Limited (or its successors, if any) and the KDE Free Qt
// Foundation. In addition, as a special exception, Riverbank gives you
// certain additional rights. These rights are described in the Riverbank
// GPL Exception version 1.1, which can be found in the file
// GPL_EXCEPTION.txt in this package.
//
// If you are unsure which license is appropriate for your use, please
// contact the sales department at sales@riverbankcomputing.com.
//
// 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 "Qsci/qscilexerhtml.h"
#include <qcolor.h>
#include <qfont.h>
#include <qsettings.h>
#include "Qsci/qscilexerjavascript.h"
#include "Qsci/qscilexerpython.h"
// The ctor.
QsciLexerHTML::QsciLexerHTML(QObject *parent, const char *name)
: QsciLexer(parent, name),
fold_compact(true), fold_preproc(true), case_sens_tags(false),
fold_script_comments(false), fold_script_heredocs(false),
django_templates(false), mako_templates(false)
{
}
// The dtor.
QsciLexerHTML::~QsciLexerHTML()
{
}
// Returns the language name.
const char *QsciLexerHTML::language() const
{
return "HTML";
}
// Returns the lexer name.
const char *QsciLexerHTML::lexer() const
{
return "hypertext";
}
// Return the auto-completion fillup characters.
const char *QsciLexerHTML::autoCompletionFillups() const
{
return "/>";
}
// Return the string of characters that comprise a word.
const char *QsciLexerHTML::wordCharacters() const
{
return "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-";
}
// Returns the foreground colour of the text for a style.
QColor QsciLexerHTML::defaultColor(int style) const
{
switch (style)
{
case Default:
case JavaScriptDefault:
case JavaScriptWord:
case JavaScriptSymbol:
case ASPJavaScriptDefault:
case ASPJavaScriptWord:
case ASPJavaScriptSymbol:
case VBScriptDefault:
case ASPVBScriptDefault:
case PHPOperator:
return QColor(0x00,0x00,0x00);
case Tag:
case XMLTagEnd:
case Script:
case SGMLDefault:
case SGMLCommand:
case VBScriptKeyword:
case VBScriptIdentifier:
case VBScriptUnclosedString:
case ASPVBScriptKeyword:
case ASPVBScriptIdentifier:
case ASPVBScriptUnclosedString:
return QColor(0x00,0x00,0x80);
case UnknownTag:
case UnknownAttribute:
return QColor(0xff,0x00,0x00);
case Attribute:
case VBScriptNumber:
case ASPVBScriptNumber:
return QColor(0x00,0x80,0x80);
case HTMLNumber:
case JavaScriptNumber:
case ASPJavaScriptNumber:
case PythonNumber:
case PythonFunctionMethodName:
case ASPPythonNumber:
case ASPPythonFunctionMethodName:
return QColor(0x00,0x7f,0x7f);
case HTMLDoubleQuotedString:
case HTMLSingleQuotedString:
case JavaScriptDoubleQuotedString:
case JavaScriptSingleQuotedString:
case ASPJavaScriptDoubleQuotedString:
case ASPJavaScriptSingleQuotedString:
case PythonDoubleQuotedString:
case PythonSingleQuotedString:
case ASPPythonDoubleQuotedString:
case ASPPythonSingleQuotedString:
case PHPKeyword:
return QColor(0x7f,0x00,0x7f);
case OtherInTag:
case Entity:
case VBScriptString:
case ASPVBScriptString:
return QColor(0x80,0x00,0x80);
case HTMLComment:
case SGMLComment:
return QColor(0x80,0x80,0x00);
case XMLStart:
case XMLEnd:
case PHPStart:
case PythonClassName:
case ASPPythonClassName:
return QColor(0x00,0x00,0xff);
case HTMLValue:
return QColor(0xff,0x00,0xff);
case SGMLParameter:
return QColor(0x00,0x66,0x00);
case SGMLDoubleQuotedString:
case SGMLError:
return QColor(0x80,0x00,0x00);
case SGMLSingleQuotedString:
return QColor(0x99,0x33,0x00);
case SGMLSpecial:
return QColor(0x33,0x66,0xff);
case SGMLEntity:
return QColor(0x33,0x33,0x33);
case SGMLBlockDefault:
return QColor(0x00,0x00,0x66);
case JavaScriptStart:
case ASPJavaScriptStart:
return QColor(0x7f,0x7f,0x00);
case JavaScriptComment:
case JavaScriptCommentLine:
case ASPJavaScriptComment:
case ASPJavaScriptCommentLine:
case PythonComment:
case ASPPythonComment:
case PHPDoubleQuotedString:
return QColor(0x00,0x7f,0x00);
case JavaScriptCommentDoc:
return QColor(0x3f,0x70,0x3f);
case JavaScriptKeyword:
case ASPJavaScriptKeyword:
case PythonKeyword:
case ASPPythonKeyword:
case PHPVariable:
case PHPDoubleQuotedVariable:
return QColor(0x00,0x00,0x7f);
case ASPJavaScriptCommentDoc:
return QColor(0x7f,0x7f,0x7f);
case VBScriptComment:
case ASPVBScriptComment:
return QColor(0x00,0x80,0x00);
case PythonStart:
case PythonDefault:
case ASPPythonStart:
case ASPPythonDefault:
return QColor(0x80,0x80,0x80);
case PythonTripleSingleQuotedString:
case PythonTripleDoubleQuotedString:
case ASPPythonTripleSingleQuotedString:
case ASPPythonTripleDoubleQuotedString:
return QColor(0x7f,0x00,0x00);
case PHPDefault:
return QColor(0x00,0x00,0x33);
case PHPSingleQuotedString:
return QColor(0x00,0x9f,0x00);
case PHPNumber:
return QColor(0xcc,0x99,0x00);
case PHPComment:
return QColor(0x99,0x99,0x99);
case PHPCommentLine:
return QColor(0x66,0x66,0x66);
}
return QsciLexer::defaultColor(style);
}
// Returns the end-of-line fill for a style.
bool QsciLexerHTML::defaultEolFill(int style) const
{
switch (style)
{
case JavaScriptDefault:
case JavaScriptComment:
case JavaScriptCommentDoc:
case JavaScriptUnclosedString:
case ASPJavaScriptDefault:
case ASPJavaScriptComment:
case ASPJavaScriptCommentDoc:
case ASPJavaScriptUnclosedString:
case VBScriptDefault:
case VBScriptComment:
case VBScriptNumber:
case VBScriptKeyword:
case VBScriptString:
case VBScriptIdentifier:
case VBScriptUnclosedString:
case ASPVBScriptDefault:
case ASPVBScriptComment:
case ASPVBScriptNumber:
case ASPVBScriptKeyword:
case ASPVBScriptString:
case ASPVBScriptIdentifier:
case ASPVBScriptUnclosedString:
case PythonDefault:
case PythonComment:
case PythonNumber:
case PythonDoubleQuotedString:
case PythonSingleQuotedString:
case PythonKeyword:
case PythonTripleSingleQuotedString:
case PythonTripleDoubleQuotedString:
case PythonClassName:
case PythonFunctionMethodName:
case PythonOperator:
case PythonIdentifier:
case ASPPythonDefault:
case ASPPythonComment:
case ASPPythonNumber:
case ASPPythonDoubleQuotedString:
case ASPPythonSingleQuotedString:
case ASPPythonKeyword:
case ASPPythonTripleSingleQuotedString:
case ASPPythonTripleDoubleQuotedString:
case ASPPythonClassName:
case ASPPythonFunctionMethodName:
case ASPPythonOperator:
case ASPPythonIdentifier:
case PHPDefault:
return true;
}
return QsciLexer::defaultEolFill(style);
}
// Returns the font of the text for a style.
QFont QsciLexerHTML::defaultFont(int style) const
{
QFont f;
switch (style)
{
case Default:
case Entity:
#if defined(Q_OS_WIN)
f = QFont("Times New Roman",11);
#elif defined(Q_OS_MAC)
f = QFont("Times New Roman", 12);
#else
f = QFont("Bitstream Charter",10);
#endif
break;
case HTMLComment:
#if defined(Q_OS_WIN)
f = QFont("Verdana",9);
#elif defined(Q_OS_MAC)
f = QFont("Verdana", 12);
#else
f = QFont("Bitstream Vera Sans",8);
#endif
break;
case SGMLCommand:
case PythonKeyword:
case PythonClassName:
case PythonFunctionMethodName:
case PythonOperator:
case ASPPythonKeyword:
case ASPPythonClassName:
case ASPPythonFunctionMethodName:
case ASPPythonOperator:
f = QsciLexer::defaultFont(style);
f.setBold(true);
break;
case JavaScriptDefault:
case JavaScriptCommentDoc:
case JavaScriptKeyword:
case JavaScriptSymbol:
case ASPJavaScriptDefault:
case ASPJavaScriptCommentDoc:
case ASPJavaScriptKeyword:
case ASPJavaScriptSymbol:
#if defined(Q_OS_WIN)
f = QFont("Comic Sans MS",9);
#elif defined(Q_OS_MAC)
f = QFont("Comic Sans MS", 12);
#else
f = QFont("Bitstream Vera Serif",9);
#endif
f.setBold(true);
break;
case JavaScriptComment:
case JavaScriptCommentLine:
case JavaScriptNumber:
case JavaScriptWord:
case JavaScriptDoubleQuotedString:
case JavaScriptSingleQuotedString:
case ASPJavaScriptComment:
case ASPJavaScriptCommentLine:
case ASPJavaScriptNumber:
case ASPJavaScriptWord:
case ASPJavaScriptDoubleQuotedString:
case ASPJavaScriptSingleQuotedString:
case VBScriptComment:
case ASPVBScriptComment:
case PythonComment:
case ASPPythonComment:
case PHPComment:
#if defined(Q_OS_WIN)
f = QFont("Comic Sans MS",9);
#elif defined(Q_OS_MAC)
f = QFont("Comic Sans MS", 12);
#else
f = QFont("Bitstream Vera Serif",9);
#endif
break;
case VBScriptDefault:
case VBScriptNumber:
case VBScriptString:
case VBScriptIdentifier:
case VBScriptUnclosedString:
case ASPVBScriptDefault:
case ASPVBScriptNumber:
case ASPVBScriptString:
case ASPVBScriptIdentifier:
case ASPVBScriptUnclosedString:
#if defined(Q_OS_WIN)
f = QFont("Lucida Sans Unicode",9);
#elif defined(Q_OS_MAC)
f = QFont("Lucida Grande", 12);
#else
f = QFont("Bitstream Vera Serif",9);
#endif
break;
case VBScriptKeyword:
case ASPVBScriptKeyword:
#if defined(Q_OS_WIN)
f = QFont("Lucida Sans Unicode",9);
#elif defined(Q_OS_MAC)
f = QFont("Lucida Grande", 12);
#else
f = QFont("Bitstream Vera Serif",9);
#endif
f.setBold(true);
break;
case PythonDoubleQuotedString:
case PythonSingleQuotedString:
case ASPPythonDoubleQuotedString:
case ASPPythonSingleQuotedString:
#if defined(Q_OS_WIN)
f = QFont("Courier New",10);
#elif defined(Q_OS_MAC)
f = QFont("Courier New", 12);
#else
f = QFont("Bitstream Vera Sans Mono",9);
#endif
break;
case PHPKeyword:
case PHPVariable:
case PHPDoubleQuotedVariable:
f = QsciLexer::defaultFont(style);
f.setItalic(true);
break;
case PHPCommentLine:
#if defined(Q_OS_WIN)
f = QFont("Comic Sans MS",9);
#elif defined(Q_OS_MAC)
f = QFont("Comic Sans MS", 12);
#else
f = QFont("Bitstream Vera Serif",9);
#endif
f.setItalic(true);
break;
default:
f = QsciLexer::defaultFont(style);
}
return f;
}
// Returns the set of keywords.
const char *QsciLexerHTML::keywords(int set) const
{
if (set == 1)
return
"a abbr acronym address applet area "
"b base basefont bdo big blockquote body br button "
"caption center cite code col colgroup "
"dd del dfn dir div dl dt "
"em "
"fieldset font form frame frameset "
"h1 h2 h3 h4 h5 h6 head hr html "
"i iframe img input ins isindex "
"kbd "
"label legend li link "
"map menu meta "
"noframes noscript "
"object ol optgroup option "
"p param pre "
"q "
"s samp script select small span strike strong style "
"sub sup "
"table tbody td textarea tfoot th thead title tr tt "
"u ul "
"var "
"xml xmlns "
"abbr accept-charset accept accesskey action align "
"alink alt archive axis "
"background bgcolor border "
"cellpadding cellspacing char charoff charset checked "
"cite class classid clear codebase codetype color "
"cols colspan compact content coords "
"data datafld dataformatas datapagesize datasrc "
"datetime declare defer dir disabled "
"enctype event "
"face for frame frameborder "
"headers height href hreflang hspace http-equiv "
"id ismap label lang language leftmargin link "
"longdesc "
"marginwidth marginheight maxlength media method "
"multiple "
"name nohref noresize noshade nowrap "
"object onblur onchange onclick ondblclick onfocus "
"onkeydown onkeypress onkeyup onload onmousedown "
"onmousemove onmouseover onmouseout onmouseup onreset "
"onselect onsubmit onunload "
"profile prompt "
"readonly rel rev rows rowspan rules "
"scheme scope selected shape size span src standby "
"start style summary "
"tabindex target text title topmargin type "
"usemap "
"valign value valuetype version vlink vspace "
"width "
"text password checkbox radio submit reset file "
"hidden image "
"public !doctype";
if (set == 2)
return QsciLexerJavaScript::keywordClass;
if (set == 3)
return
// Move these to QsciLexerVisualBasic when we
// get round to implementing it.
"and begin case call continue do each else elseif end "
"erase error event exit false for function get gosub "
"goto if implement in load loop lset me mid new next "
"not nothing on or property raiseevent rem resume "
"return rset select set stop sub then to true unload "
"until wend while with withevents attribute alias as "
"boolean byref byte byval const compare currency date "
"declare dim double enum explicit friend global "
"integer let lib long module object option optional "
"preserve private property public redim single static "
"string type variant";
if (set == 4)
return QsciLexerPython::keywordClass;
if (set == 5)
return
"and argv as argc break case cfunction class continue "
"declare default do die "
"echo else elseif empty enddeclare endfor endforeach "
"endif endswitch endwhile e_all e_parse e_error "
"e_warning eval exit extends "
"false for foreach function global "
"http_cookie_vars http_get_vars http_post_vars "
"http_post_files http_env_vars http_server_vars "
"if include include_once list new not null "
"old_function or "
"parent php_os php_self php_version print "
"require require_once return "
"static switch stdclass this true var xor virtual "
"while "
"__file__ __line__ __sleep __wakeup";
if (set == 6)
return "ELEMENT DOCTYPE ATTLIST ENTITY NOTATION";
return 0;
}
// Returns the user name of a style.
QString QsciLexerHTML::description(int style) const
{
switch (style)
{
case Default:
return tr("HTML default");
case Tag:
return tr("Tag");
case UnknownTag:
return tr("Unknown tag");
case Attribute:
return tr("Attribute");
case UnknownAttribute:
return tr("Unknown attribute");
case HTMLNumber:
return tr("HTML number");
case HTMLDoubleQuotedString:
return tr("HTML double-quoted string");
case HTMLSingleQuotedString:
return tr("HTML single-quoted string");
case OtherInTag:
return tr("Other text in a tag");
case HTMLComment:
return tr("HTML comment");
case Entity:
return tr("Entity");
case XMLTagEnd:
return tr("End of a tag");
case XMLStart:
return tr("Start of an XML fragment");
case XMLEnd:
return tr("End of an XML fragment");
case Script:
return tr("Script tag");
case ASPAtStart:
return tr("Start of an ASP fragment with @");
case ASPStart:
return tr("Start of an ASP fragment");
case CDATA:
return tr("CDATA");
case PHPStart:
return tr("Start of a PHP fragment");
case HTMLValue:
return tr("Unquoted HTML value");
case ASPXCComment:
return tr("ASP X-Code comment");
case SGMLDefault:
return tr("SGML default");
case SGMLCommand:
return tr("SGML command");
case SGMLParameter:
return tr("First parameter of an SGML command");
case SGMLDoubleQuotedString:
return tr("SGML double-quoted string");
case SGMLSingleQuotedString:
return tr("SGML single-quoted string");
case SGMLError:
return tr("SGML error");
case SGMLSpecial:
return tr("SGML special entity");
case SGMLComment:
return tr("SGML comment");
case SGMLParameterComment:
return tr("First parameter comment of an SGML command");
case SGMLBlockDefault:
return tr("SGML block default");
case JavaScriptStart:
return tr("Start of a JavaScript fragment");
case JavaScriptDefault:
return tr("JavaScript default");
case JavaScriptComment:
return tr("JavaScript comment");
case JavaScriptCommentLine:
return tr("JavaScript line comment");
case JavaScriptCommentDoc:
return tr("JavaDoc style JavaScript comment");
case JavaScriptNumber:
return tr("JavaScript number");
case JavaScriptWord:
return tr("JavaScript word");
case JavaScriptKeyword:
return tr("JavaScript keyword");
case JavaScriptDoubleQuotedString:
return tr("JavaScript double-quoted string");
case JavaScriptSingleQuotedString:
return tr("JavaScript single-quoted string");
case JavaScriptSymbol:
return tr("JavaScript symbol");
case JavaScriptUnclosedString:
return tr("JavaScript unclosed string");
case JavaScriptRegex:
return tr("JavaScript regular expression");
case ASPJavaScriptStart:
return tr("Start of an ASP JavaScript fragment");
case ASPJavaScriptDefault:
return tr("ASP JavaScript default");
case ASPJavaScriptComment:
return tr("ASP JavaScript comment");
case ASPJavaScriptCommentLine:
return tr("ASP JavaScript line comment");
case ASPJavaScriptCommentDoc:
return tr("JavaDoc style ASP JavaScript comment");
case ASPJavaScriptNumber:
return tr("ASP JavaScript number");
case ASPJavaScriptWord:
return tr("ASP JavaScript word");
case ASPJavaScriptKeyword:
return tr("ASP JavaScript keyword");
case ASPJavaScriptDoubleQuotedString:
return tr("ASP JavaScript double-quoted string");
case ASPJavaScriptSingleQuotedString:
return tr("ASP JavaScript single-quoted string");
case ASPJavaScriptSymbol:
return tr("ASP JavaScript symbol");
case ASPJavaScriptUnclosedString:
return tr("ASP JavaScript unclosed string");
case ASPJavaScriptRegex:
return tr("ASP JavaScript regular expression");
case VBScriptStart:
return tr("Start of a VBScript fragment");
case VBScriptDefault:
return tr("VBScript default");
case VBScriptComment:
return tr("VBScript comment");
case VBScriptNumber:
return tr("VBScript number");
case VBScriptKeyword:
return tr("VBScript keyword");
case VBScriptString:
return tr("VBScript string");
case VBScriptIdentifier:
return tr("VBScript identifier");
case VBScriptUnclosedString:
return tr("VBScript unclosed string");
case ASPVBScriptStart:
return tr("Start of an ASP VBScript fragment");
case ASPVBScriptDefault:
return tr("ASP VBScript default");
case ASPVBScriptComment:
return tr("ASP VBScript comment");
case ASPVBScriptNumber:
return tr("ASP VBScript number");
case ASPVBScriptKeyword:
return tr("ASP VBScript keyword");
case ASPVBScriptString:
return tr("ASP VBScript string");
case ASPVBScriptIdentifier:
return tr("ASP VBScript identifier");
case ASPVBScriptUnclosedString:
return tr("ASP VBScript unclosed string");
case PythonStart:
return tr("Start of a Python fragment");
case PythonDefault:
return tr("Python default");
case PythonComment:
return tr("Python comment");
case PythonNumber:
return tr("Python number");
case PythonDoubleQuotedString:
return tr("Python double-quoted string");
case PythonSingleQuotedString:
return tr("Python single-quoted string");
case PythonKeyword:
return tr("Python keyword");
case PythonTripleDoubleQuotedString:
return tr("Python triple double-quoted string");
case PythonTripleSingleQuotedString:
return tr("Python triple single-quoted string");
case PythonClassName:
return tr("Python class name");
case PythonFunctionMethodName:
return tr("Python function or method name");
case PythonOperator:
return tr("Python operator");
case PythonIdentifier:
return tr("Python identifier");
case ASPPythonStart:
return tr("Start of an ASP Python fragment");
case ASPPythonDefault:
return tr("ASP Python default");
case ASPPythonComment:
return tr("ASP Python comment");
case ASPPythonNumber:
return tr("ASP Python number");
case ASPPythonDoubleQuotedString:
return tr("ASP Python double-quoted string");
case ASPPythonSingleQuotedString:
return tr("ASP Python single-quoted string");
case ASPPythonKeyword:
return tr("ASP Python keyword");
case ASPPythonTripleDoubleQuotedString:
return tr("ASP Python triple double-quoted string");
case ASPPythonTripleSingleQuotedString:
return tr("ASP Python triple single-quoted string");
case ASPPythonClassName:
return tr("ASP Python class name");
case ASPPythonFunctionMethodName:
return tr("ASP Python function or method name");
case ASPPythonOperator:
return tr("ASP Python operator");
case ASPPythonIdentifier:
return tr("ASP Python identifier");
case PHPDefault:
return tr("PHP default");
case PHPDoubleQuotedString:
return tr("PHP double-quoted string");
case PHPSingleQuotedString:
return tr("PHP single-quoted string");
case PHPKeyword:
return tr("PHP keyword");
case PHPNumber:
return tr("PHP number");
case PHPVariable:
return tr("PHP variable");
case PHPComment:
return tr("PHP comment");
case PHPCommentLine:
return tr("PHP line comment");
case PHPDoubleQuotedVariable:
return tr("PHP double-quoted variable");
case PHPOperator:
return tr("PHP operator");
}
return QString();
}
// Returns the background colour of the text for a style.
QColor QsciLexerHTML::defaultPaper(int style) const
{
switch (style)
{
case ASPAtStart:
return QColor(0xff,0xff,0x00);
case ASPStart:
case CDATA:
return QColor(0xff,0xdf,0x00);
case PHPStart:
return QColor(0xff,0xef,0xbf);
case HTMLValue:
return QColor(0xff,0xef,0xff);
case SGMLDefault:
case SGMLCommand:
case SGMLParameter:
case SGMLDoubleQuotedString:
case SGMLSingleQuotedString:
case SGMLSpecial:
case SGMLEntity:
case SGMLComment:
return QColor(0xef,0xef,0xff);
case SGMLError:
return QColor(0xff,0x66,0x66);
case SGMLBlockDefault:
return QColor(0xcc,0xcc,0xe0);
case JavaScriptDefault:
case JavaScriptComment:
case JavaScriptCommentLine:
case JavaScriptCommentDoc:
case JavaScriptNumber:
case JavaScriptWord:
case JavaScriptKeyword:
case JavaScriptDoubleQuotedString:
case JavaScriptSingleQuotedString:
case JavaScriptSymbol:
return QColor(0xf0,0xf0,0xff);
case JavaScriptUnclosedString:
case ASPJavaScriptUnclosedString:
return QColor(0xbf,0xbb,0xb0);
case JavaScriptRegex:
case ASPJavaScriptRegex:
return QColor(0xff,0xbb,0xb0);
case ASPJavaScriptDefault:
case ASPJavaScriptComment:
case ASPJavaScriptCommentLine:
case ASPJavaScriptCommentDoc:
case ASPJavaScriptNumber:
case ASPJavaScriptWord:
case ASPJavaScriptKeyword:
case ASPJavaScriptDoubleQuotedString:
case ASPJavaScriptSingleQuotedString:
case ASPJavaScriptSymbol:
return QColor(0xdf,0xdf,0x7f);
case VBScriptDefault:
case VBScriptComment:
case VBScriptNumber:
case VBScriptKeyword:
case VBScriptString:
case VBScriptIdentifier:
return QColor(0xef,0xef,0xff);
case VBScriptUnclosedString:
case ASPVBScriptUnclosedString:
return QColor(0x7f,0x7f,0xff);
case ASPVBScriptDefault:
case ASPVBScriptComment:
case ASPVBScriptNumber:
case ASPVBScriptKeyword:
case ASPVBScriptString:
case ASPVBScriptIdentifier:
return QColor(0xcf,0xcf,0xef);
case PythonDefault:
case PythonComment:
case PythonNumber:
case PythonDoubleQuotedString:
case PythonSingleQuotedString:
case PythonKeyword:
case PythonTripleSingleQuotedString:
case PythonTripleDoubleQuotedString:
case PythonClassName:
case PythonFunctionMethodName:
case PythonOperator:
case PythonIdentifier:
return QColor(0xef,0xff,0xef);
case ASPPythonDefault:
case ASPPythonComment:
case ASPPythonNumber:
case ASPPythonDoubleQuotedString:
case ASPPythonSingleQuotedString:
case ASPPythonKeyword:
case ASPPythonTripleSingleQuotedString:
case ASPPythonTripleDoubleQuotedString:
case ASPPythonClassName:
case ASPPythonFunctionMethodName:
case ASPPythonOperator:
case ASPPythonIdentifier:
return QColor(0xcf,0xef,0xcf);
case PHPDefault:
case PHPDoubleQuotedString:
case PHPSingleQuotedString:
case PHPKeyword:
case PHPNumber:
case PHPVariable:
case PHPComment:
case PHPCommentLine:
case PHPDoubleQuotedVariable:
case PHPOperator:
return QColor(0xff,0xf8,0xf8);
}
return QsciLexer::defaultPaper(style);
}
// Refresh all properties.
void QsciLexerHTML::refreshProperties()
{
setCompactProp();
setPreprocProp();
setCaseSensTagsProp();
setScriptCommentsProp();
setScriptHeredocsProp();
setDjangoProp();
setMakoProp();
}
// Read properties from the settings.
bool QsciLexerHTML::readProperties(QSettings &qs,const QString &prefix)
{
int rc = true;
bool ok, flag;
flag = qs.readBoolEntry(prefix + "foldcompact", true, &ok);
if (ok)
fold_compact = flag;
else
rc = false;
flag = qs.readBoolEntry(prefix + "foldpreprocessor", false, &ok);
if (ok)
fold_preproc = flag;
else
rc = false;
flag = qs.readBoolEntry(prefix + "casesensitivetags", false, &ok);
if (ok)
case_sens_tags = flag;
else
rc = false;
flag = qs.readBoolEntry(prefix + "foldscriptcomments", false, &ok);
if (ok)
fold_script_comments = flag;
else
rc = false;
flag = qs.readBoolEntry(prefix + "foldscriptheredocs", false, &ok);
if (ok)
fold_script_heredocs = flag;
else
rc = false;
flag = qs.readBoolEntry(prefix + "djangotemplates", false, &ok);
if (ok)
django_templates = flag;
else
rc = false;
flag = qs.readBoolEntry(prefix + "makotemplates", false, &ok);
if (ok)
mako_templates = flag;
else
rc = false;
return rc;
}
// Write properties to the settings.
bool QsciLexerHTML::writeProperties(QSettings &qs,const QString &prefix) const
{
int rc = true;
if (!qs.writeEntry(prefix + "foldcompact", fold_compact))
rc = false;
if (!qs.writeEntry(prefix + "foldpreprocessor", fold_preproc))
rc = false;
if (!qs.writeEntry(prefix + "casesensitivetags", case_sens_tags))
rc = false;
if (!qs.writeEntry(prefix + "foldscriptcomments", fold_script_comments))
rc = false;
if (!qs.writeEntry(prefix + "foldscriptheredocs", fold_script_heredocs))
rc = false;
if (!qs.writeEntry(prefix + "djangotemplates", django_templates))
rc = false;
if (!qs.writeEntry(prefix + "makotemplates", mako_templates))
rc = false;
return rc;
}
// Set if tags are case sensitive.
void QsciLexerHTML::setCaseSensitiveTags(bool sens)
{
case_sens_tags = sens;
setCaseSensTagsProp();
}
// Set the "html.tags.case.sensitive" property.
void QsciLexerHTML::setCaseSensTagsProp()
{
emit propertyChanged("html.tags.case.sensitive",(case_sens_tags ? "1" : "0"));
}
// Set if folds are compact
void QsciLexerHTML::setFoldCompact(bool fold)
{
fold_compact = fold;
setCompactProp();
}
// Set the "fold.compact" property.
void QsciLexerHTML::setCompactProp()
{
emit propertyChanged("fold.compact",(fold_compact ? "1" : "0"));
}
// Set if preprocessor blocks can be folded.
void QsciLexerHTML::setFoldPreprocessor(bool fold)
{
fold_preproc = fold;
setPreprocProp();
}
// Set the "fold.html.preprocessor" property.
void QsciLexerHTML::setPreprocProp()
{
emit propertyChanged("fold.html.preprocessor",(fold_preproc ? "1" : "0"));
}
// Set if script comments can be folded.
void QsciLexerHTML::setFoldScriptComments(bool fold)
{
fold_script_comments = fold;
setScriptCommentsProp();
}
// Set the "fold.hypertext.comment" property.
void QsciLexerHTML::setScriptCommentsProp()
{
emit propertyChanged("fold.hypertext.comment",(fold_script_comments ? "1" : "0"));
}
// Set if script heredocs can be folded.
void QsciLexerHTML::setFoldScriptHeredocs(bool fold)
{
fold_script_heredocs = fold;
setScriptHeredocsProp();
}
// Set the "fold.hypertext.heredoc" property.
void QsciLexerHTML::setScriptHeredocsProp()
{
emit propertyChanged("fold.hypertext.heredoc",(fold_script_heredocs ? "1" : "0"));
}
// Set if Django templates are supported.
void QsciLexerHTML::setDjangoTemplates(bool enable)
{
django_templates = enable;
setDjangoProp();
}
// Set the "lexer.html.django" property.
void QsciLexerHTML::setDjangoProp()
{
emit propertyChanged("lexer.html.django", (django_templates ? "1" : "0"));
}
// Set if Mako templates are supported.
void QsciLexerHTML::setMakoTemplates(bool enable)
{
mako_templates = enable;
setMakoProp();
}
// Set the "lexer.html.mako" property.
void QsciLexerHTML::setMakoProp()
{
emit propertyChanged("lexer.html.mako", (mako_templates ? "1" : "0"));
}
|
gpl-3.0
|
gamvrosi/scrubber
|
linux-2.6.35/arch/x86/kernel/cpu/perf_event_p6.c
|
1040
|
3507
|
#ifdef CONFIG_CPU_SUP_INTEL
/*
* Not sure about some of these
*/
static const u64 p6_perfmon_event_map[] =
{
[PERF_COUNT_HW_CPU_CYCLES] = 0x0079,
[PERF_COUNT_HW_INSTRUCTIONS] = 0x00c0,
[PERF_COUNT_HW_CACHE_REFERENCES] = 0x0f2e,
[PERF_COUNT_HW_CACHE_MISSES] = 0x012e,
[PERF_COUNT_HW_BRANCH_INSTRUCTIONS] = 0x00c4,
[PERF_COUNT_HW_BRANCH_MISSES] = 0x00c5,
[PERF_COUNT_HW_BUS_CYCLES] = 0x0062,
};
static u64 p6_pmu_event_map(int hw_event)
{
return p6_perfmon_event_map[hw_event];
}
/*
* Event setting that is specified not to count anything.
* We use this to effectively disable a counter.
*
* L2_RQSTS with 0 MESI unit mask.
*/
#define P6_NOP_EVENT 0x0000002EULL
static struct event_constraint p6_event_constraints[] =
{
INTEL_EVENT_CONSTRAINT(0xc1, 0x1), /* FLOPS */
INTEL_EVENT_CONSTRAINT(0x10, 0x1), /* FP_COMP_OPS_EXE */
INTEL_EVENT_CONSTRAINT(0x11, 0x1), /* FP_ASSIST */
INTEL_EVENT_CONSTRAINT(0x12, 0x2), /* MUL */
INTEL_EVENT_CONSTRAINT(0x13, 0x2), /* DIV */
INTEL_EVENT_CONSTRAINT(0x14, 0x1), /* CYCLES_DIV_BUSY */
EVENT_CONSTRAINT_END
};
static void p6_pmu_disable_all(void)
{
u64 val;
/* p6 only has one enable register */
rdmsrl(MSR_P6_EVNTSEL0, val);
val &= ~ARCH_PERFMON_EVENTSEL_ENABLE;
wrmsrl(MSR_P6_EVNTSEL0, val);
}
static void p6_pmu_enable_all(int added)
{
unsigned long val;
/* p6 only has one enable register */
rdmsrl(MSR_P6_EVNTSEL0, val);
val |= ARCH_PERFMON_EVENTSEL_ENABLE;
wrmsrl(MSR_P6_EVNTSEL0, val);
}
static inline void
p6_pmu_disable_event(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct hw_perf_event *hwc = &event->hw;
u64 val = P6_NOP_EVENT;
if (cpuc->enabled)
val |= ARCH_PERFMON_EVENTSEL_ENABLE;
(void)checking_wrmsrl(hwc->config_base + hwc->idx, val);
}
static void p6_pmu_enable_event(struct perf_event *event)
{
struct cpu_hw_events *cpuc = &__get_cpu_var(cpu_hw_events);
struct hw_perf_event *hwc = &event->hw;
u64 val;
val = hwc->config;
if (cpuc->enabled)
val |= ARCH_PERFMON_EVENTSEL_ENABLE;
(void)checking_wrmsrl(hwc->config_base + hwc->idx, val);
}
static __initconst const struct x86_pmu p6_pmu = {
.name = "p6",
.handle_irq = x86_pmu_handle_irq,
.disable_all = p6_pmu_disable_all,
.enable_all = p6_pmu_enable_all,
.enable = p6_pmu_enable_event,
.disable = p6_pmu_disable_event,
.hw_config = x86_pmu_hw_config,
.schedule_events = x86_schedule_events,
.eventsel = MSR_P6_EVNTSEL0,
.perfctr = MSR_P6_PERFCTR0,
.event_map = p6_pmu_event_map,
.max_events = ARRAY_SIZE(p6_perfmon_event_map),
.apic = 1,
.max_period = (1ULL << 31) - 1,
.version = 0,
.num_counters = 2,
/*
* Events have 40 bits implemented. However they are designed such
* that bits [32-39] are sign extensions of bit 31. As such the
* effective width of a event for P6-like PMU is 32 bits only.
*
* See IA-32 Intel Architecture Software developer manual Vol 3B
*/
.cntval_bits = 32,
.cntval_mask = (1ULL << 32) - 1,
.get_event_constraints = x86_get_event_constraints,
.event_constraints = p6_event_constraints,
};
static __init int p6_pmu_init(void)
{
switch (boot_cpu_data.x86_model) {
case 1:
case 3: /* Pentium Pro */
case 5:
case 6: /* Pentium II */
case 7:
case 8:
case 11: /* Pentium III */
case 9:
case 13:
/* Pentium M */
break;
default:
pr_cont("unsupported p6 CPU model %d ",
boot_cpu_data.x86_model);
return -ENODEV;
}
x86_pmu = p6_pmu;
return 0;
}
#endif /* CONFIG_CPU_SUP_INTEL */
|
gpl-3.0
|
Edgarins29/Doom3
|
neo/tools/particle/DialogParticleEditor.cpp
|
17
|
43185
|
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code ("Doom 3 Source Code").
Doom 3 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.
Doom 3 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 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 Doom 3 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.
===========================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "../../game/game.h"
#include "../../sys/win32/win_local.h"
#include "../../sys/win32/rc/common_resource.h"
#include "../../sys/win32/rc/Radiant_resource.h"
#include "../../sys/win32/rc/ParticleEditor_resource.h"
#include "../comafx/DialogName.h"
#include "../comafx/VectorCtl.h"
#include "../comafx/DialogColorPicker.h"
#include "../radiant/GLWidget.h"
#include "../radiant/PreviewDlg.h"
#include "DialogParticleEditor.h"
#ifdef ID_DEBUG_MEMORY
#undef new
#undef DEBUG_NEW
#define DEBUG_NEW new
#endif
const int StageEnableID[] = {
IDC_EDIT_MATERIAL,
IDC_BUTTON_BROWSEMATERIAL,
IDC_EDIT_ANIMFRAMES,
IDC_EDIT_ANIMRATE,
IDC_EDIT_COLOR,
IDC_BUTTON_BROWSECOLOR,
IDC_EDIT_FADECOLOR,
IDC_BUTTON_BROWSEFADECOLOR,
IDC_EDIT_FADEIN,
IDC_SLIDER_FADEIN,
IDC_EDIT_FADEOUT,
IDC_EDIT_FADEFRACTION,
IDC_SLIDER_FADEOUT,
IDC_SLIDER_FADEFRACTION,
IDC_EDIT_BUNCHING,
IDC_SLIDER_BUNCHING,
IDC_EDIT_COUNT,
IDC_SLIDER_COUNT,
IDC_EDIT_TIME,
IDC_SLIDER_TIME,
IDC_EDIT_CYCLES,
IDC_EDIT_TIMEOFFSET,
IDC_EDIT_DEADTIME,
IDC_CHECK_WORLDGRAVITY,
IDC_EDIT_GRAVITY,
IDC_SLIDER_GRAVITY,
IDC_RADIO_RECT,
IDC_RADIO_CYLINDER,
IDC_RADIO_SPHERE,
IDC_EDIT_OFFSET,
IDC_EDIT_XSIZE,
IDC_EDIT_YSIZE,
IDC_EDIT_ZSIZE,
IDC_EDIT_RINGOFFSET,
IDC_RADIO_CONE,
IDC_RADIO_OUTWARD,
IDC_EDIT_DIRECTIONPARM,
IDC_RADIO_AIMED,
IDC_RADIO_VIEW,
IDC_RADIO_X,
IDC_RADIO_Y,
IDC_RADIO_Z,
IDC_EDIT_ORIENTATIONPARM1,
IDC_EDIT_ORIENTATIONPARM2,
IDC_SLIDER_SPEEDFROM,
IDC_EDIT_SPEEDFROM,
IDC_EDIT_SPEEDTO,
IDC_SLIDER_SPEEDTO,
IDC_SLIDER_ROTATIONFROM,
IDC_EDIT_ROTATIONFROM,
IDC_EDIT_ROTATIONTO,
IDC_SLIDER_ROTATIONTO,
IDC_SLIDER_SIZEFROM,
IDC_EDIT_SIZEFROM,
IDC_EDIT_SIZETO,
IDC_SLIDER_SIZETO,
IDC_SLIDER_ASPECTFROM,
IDC_EDIT_ASPECTFROM,
IDC_EDIT_ASPECTTO,
IDC_SLIDER_ASPECTTO,
IDC_COMBO_CUSTOMPATH,
IDC_CHECK_ENTITYCOLOR,
};
const int StageIDCount = sizeof( StageEnableID ) / sizeof ( const int );
const int EditEnableID[] = {
IDC_BUTTON_XDN,
IDC_BUTTON_XUP,
IDC_BUTTON_YUP,
IDC_BUTTON_YDN,
IDC_BUTTON_ZUP,
IDC_BUTTON_ZDN,
IDC_BUTTON_DROPEMITTER,
IDC_BUTTON_VECTOR,
IDC_BUTTON_BROWSECOLOR_ENTITY
};
const int EditIDCount = sizeof ( EditEnableID ) / sizeof ( const int );
CDialogParticleEditor *g_ParticleDialog = NULL;
/*
================
ParticleEditorInit
================
*/
void ParticleEditorInit( const idDict *spawnArgs ) {
if ( renderSystem->IsFullScreen() ) {
common->Printf( "Cannot run the particle editor in fullscreen mode.\n"
"Set r_fullscreen to 0 and vid_restart.\n" );
return;
}
if ( g_ParticleDialog == NULL ) {
InitAfx();
g_ParticleDialog = new CDialogParticleEditor();
}
if ( g_ParticleDialog->GetSafeHwnd() == NULL) {
g_ParticleDialog->Create( IDD_DIALOG_PARTICLE_EDITOR );
/*
// FIXME: restore position
CRect rct;
g_AFDialog->SetWindowPos( NULL, rct.left, rct.top, 0, 0, SWP_NOSIZE );
*/
}
idKeyInput::ClearStates();
g_ParticleDialog->ShowWindow( SW_SHOW );
g_ParticleDialog->SetFocus();
if ( spawnArgs ) {
idStr str = spawnArgs->GetString( "model" );
str.StripFileExtension();
g_ParticleDialog->SelectParticle( str );
g_ParticleDialog->SetParticleVisualization( static_cast<int>( CDialogParticleEditor::SELECTED ) );
}
cvarSystem->SetCVarBool( "r_useCachedDynamicModels", false );
}
/*
================
ParticleEditorRun
================
*/
void ParticleEditorRun( void ) {
#if _MSC_VER >= 1300
MSG *msg = AfxGetCurrentMessage(); // TODO Robert fix me!!
#else
MSG *msg = &m_msgCur;
#endif
while( ::PeekMessage(msg, NULL, NULL, NULL, PM_NOREMOVE) ) {
// pump message
if ( !AfxGetApp()->PumpMessage() ) {
}
}
}
/*
================
ParticleEditorShutdown
================
*/
void ParticleEditorShutdown( void ) {
delete g_ParticleDialog;
g_ParticleDialog = NULL;
}
// CDialogParticleEditor dialog
IMPLEMENT_DYNAMIC(CDialogParticleEditor, CDialog)
CDialogParticleEditor::CDialogParticleEditor(CWnd* pParent /*=NULL*/)
: CDialog(CDialogParticleEditor::IDD, pParent)
, matName(_T(""))
, animFrames(_T(""))
, animRate(_T(""))
, color(_T(""))
, fadeColor(_T(""))
, fadeIn(_T(""))
, fadeOut(_T(""))
, fadeFraction(_T(""))
, count(_T(""))
, time(_T(""))
, timeOffset(_T(""))
, deadTime(_T(""))
, gravity(_T(""))
, bunching(_T(""))
, offset(_T(""))
, xSize(_T(""))
, ySize(_T(""))
, zSize(_T(""))
, ringOffset(_T(""))
, directionParm(_T(""))
, direction(0)
, orientation(0)
, distribution(0)
, viewOrigin(_T(""))
, speedFrom(_T(""))
, speedTo(_T(""))
, rotationFrom(_T(""))
, rotationTo(_T(""))
, sizeFrom(_T(""))
, sizeTo(_T(""))
, aspectFrom(_T(""))
, aspectTo(_T(""))
, customPath(_T(""))
, customParms(_T(""))
, trails(_T(""))
, trailTime(_T(""))
, worldGravity(TRUE)
, entityColor(TRUE)
, randomDistribution(TRUE)
, initialAngle(_T(""))
, boundsExpansion(_T(""))
, customDesc(_T(""))
, particleMode(FALSE)
{
visualization = TESTMODEL;
mapModified = false;
}
CDialogParticleEditor::~CDialogParticleEditor() {
}
void CDialogParticleEditor::DoDataExchange(CDataExchange* pDX) {
CDialog::DoDataExchange(pDX);
DDX_Text(pDX, IDC_EDIT_DEPTHHACK, depthHack);
DDX_Check(pDX, IDC_CHECK_WORLDGRAVITY, worldGravity);
DDX_Check(pDX, IDC_CHECK_ENTITYCOLOR, entityColor);
DDX_Control(pDX, IDC_COMBO_PARTICLES, comboParticle);
DDX_Control(pDX, IDC_LIST_STAGES, listStages);
DDX_Text(pDX, IDC_COMBO_CUSTOMPATH, customPath );
DDX_Text(pDX, IDC_EDIT_CUSTOMPARMS, customParms );
DDX_Text(pDX, IDC_EDIT_MATERIAL, matName);
DDX_Text(pDX, IDC_EDIT_ANIMFRAMES, animFrames);
DDX_Text(pDX, IDC_EDIT_ANIMRATE, animRate);
DDX_Text(pDX, IDC_EDIT_COLOR, color);
DDX_Text(pDX, IDC_EDIT_FADECOLOR, fadeColor);
DDX_Text(pDX, IDC_EDIT_FADEIN, fadeIn);
DDX_Text(pDX, IDC_EDIT_FADEOUT, fadeOut);
DDX_Text(pDX, IDC_EDIT_FADEFRACTION, fadeFraction);
DDX_Text(pDX, IDC_EDIT_COUNT, count);
DDX_Text(pDX, IDC_EDIT_TIME, time);
DDX_Text(pDX, IDC_EDIT_TIMEOFFSET, timeOffset);
DDX_Text(pDX, IDC_EDIT_DEADTIME, deadTime);
DDX_Text(pDX, IDC_EDIT_GRAVITY, gravity);
DDX_Text(pDX, IDC_EDIT_BUNCHING, bunching);
DDX_Text(pDX, IDC_EDIT_OFFSET, offset);
DDX_Text(pDX, IDC_EDIT_XSIZE, xSize);
DDX_Text(pDX, IDC_EDIT_YSIZE, ySize);
DDX_Text(pDX, IDC_EDIT_ZSIZE, zSize);
DDX_Text(pDX, IDC_EDIT_RINGOFFSET, ringOffset);
DDX_Text(pDX, IDC_EDIT_CYCLES, cycles);
DDX_Control(pDX, IDC_STATIC_DIRPARM, staticDirectionParm);
DDX_Text(pDX, IDC_EDIT_DIRECTIONPARM, directionParm);
DDX_Text(pDX, IDC_EDIT_SPEEDFROM, speedFrom);
DDX_Text(pDX, IDC_EDIT_SPEEDTO, speedTo);
DDX_Text(pDX, IDC_EDIT_ROTATIONFROM, rotationFrom);
DDX_Text(pDX, IDC_EDIT_ROTATIONTO, rotationTo);
DDX_Text(pDX, IDC_EDIT_SIZEFROM, sizeFrom);
DDX_Text(pDX, IDC_EDIT_SIZETO, sizeTo);
DDX_Text(pDX, IDC_EDIT_ASPECTFROM, aspectFrom);
DDX_Text(pDX, IDC_EDIT_ASPECTTO, aspectTo);
DDX_Text(pDX, IDC_EDIT_ORIENTATIONPARM1, trails);
DDX_Text(pDX, IDC_EDIT_ORIENTATIONPARM2, trailTime);
DDX_Check(pDX, IDC_CHECK_RANDOMDISTRIBUTION, randomDistribution);
DDX_Text(pDX, IDC_EDIT_INITIALANGLE, initialAngle);
DDX_Text(pDX, IDC_EDIT_BOUNDSEXPANSION, boundsExpansion);
DDX_Text(pDX, IDC_STATIC_DESC, customDesc);
DDX_Control(pDX, IDC_EDIT_RINGOFFSET, editRingOffset);
DDX_Radio(pDX, IDC_RADIO_RECT, distribution);
DDX_Radio(pDX, IDC_RADIO_CONE, direction);
DDX_Radio(pDX, IDC_RADIO_VIEW, orientation);
DDX_Control(pDX, IDC_SLIDER_BUNCHING, sliderBunching);
DDX_Control(pDX, IDC_SLIDER_FADEIN, sliderFadeIn);
DDX_Control(pDX, IDC_SLIDER_FADEOUT, sliderFadeOut);
DDX_Control(pDX, IDC_SLIDER_FADEFRACTION, sliderFadeFraction);
DDX_Control(pDX, IDC_SLIDER_COUNT, sliderCount);
DDX_Control(pDX, IDC_SLIDER_TIME, sliderTime);
DDX_Control(pDX, IDC_SLIDER_GRAVITY, sliderGravity);
DDX_Control(pDX, IDC_SLIDER_SPEEDFROM, sliderSpeedFrom);
DDX_Control(pDX, IDC_SLIDER_SPEEDTO, sliderSpeedTo);
DDX_Control(pDX, IDC_SLIDER_ROTATIONFROM, sliderRotationFrom);
DDX_Control(pDX, IDC_SLIDER_ROTATIONTO, sliderRotationTo);
DDX_Control(pDX, IDC_SLIDER_SIZEFROM, sliderSizeFrom);
DDX_Control(pDX, IDC_SLIDER_SIZETO, sliderSizeTo);
DDX_Control(pDX, IDC_SLIDER_ASPECTFROM, sliderAspectFrom);
DDX_Control(pDX, IDC_SLIDER_ASPECTTO, sliderAspectTo);
DDX_Control(pDX, IDC_BUTTON_VECTOR, vectorControl);
}
BEGIN_MESSAGE_MAP(CDialogParticleEditor, CDialog)
ON_BN_CLICKED(IDC_BUTTON_ADDSTAGE, OnBnClickedButtonAddstage)
ON_BN_CLICKED(IDC_BUTTON_REMOVESTAGE, OnBnClickedButtonRemovestage)
ON_BN_CLICKED(IDC_BUTTON_BROWSEMATERIAL, OnBnClickedButtonBrowsematerial)
ON_BN_CLICKED(IDC_BUTTON_BROWSECOLOR, OnBnClickedButtonBrowsecolor)
ON_BN_CLICKED(IDC_BUTTON_BROWSEFADECOLOR, OnBnClickedButtonBrowsefadecolor)
ON_BN_CLICKED(IDC_BUTTON_BROWSECOLOR_ENTITY, OnBnClickedButtonBrowseEntitycolor)
ON_BN_CLICKED(IDC_BUTTON_UPDATE, OnBnClickedButtonUpdate)
ON_CBN_SELCHANGE(IDC_COMBO_PARTICLES, OnCbnSelchangeComboParticles)
ON_CBN_SELCHANGE(IDC_COMBO_CUSTOMPATH, OnCbnSelchangeComboPath)
ON_BN_CLICKED(IDC_RADIO_RECT, OnBnClickedRadioRect)
ON_BN_CLICKED(IDC_RADIO_SPHERE, OnBnClickedRadioSphere)
ON_BN_CLICKED(IDC_RADIO_CYLINDER, OnBnClickedRadioCylinder)
ON_BN_CLICKED(IDC_RADIO_CONE, OnBnClickedRadioCone)
ON_BN_CLICKED(IDC_RADIO_OUTWARD, OnBnClickedRadioOutward)
ON_BN_CLICKED(IDC_RADIO_VIEW, OnBnClickedRadioView)
ON_BN_CLICKED(IDC_RADIO_AIMED, OnBnClickedRadioAimed)
ON_BN_CLICKED(IDC_RADIO_X, OnBnClickedRadioX)
ON_BN_CLICKED(IDC_RADIO_Y, OnBnClickedRadioY)
ON_BN_CLICKED(IDC_RADIO_Z, OnBnClickedRadioZ)
ON_BN_CLICKED(IDC_BUTTON_HIDESTAGE, OnBnClickedButtonHidestage)
ON_BN_CLICKED(IDC_BUTTON_SHOWSTAGE, OnBnClickedButtonShowstage)
ON_BN_CLICKED(IDC_CHECK_WORLDGRAVITY, OnBnClickedWorldGravity)
ON_BN_CLICKED(IDC_CHECK_ENTITYCOLOR, OnBnClickedEntityColor)
ON_LBN_SELCHANGE(IDC_LIST_STAGES, OnLbnSelchangeListStages)
ON_BN_CLICKED(IDC_BUTTON_NEW, OnBnClickedButtonNew)
ON_BN_CLICKED(IDC_BUTTON_SAVE_PARTICLE, OnBnClickedButtonSave)
ON_BN_CLICKED(IDC_BUTTON_SAVE_PARTICLE_AS, OnBnClickedButtonSaveAs)
ON_BN_CLICKED(IDC_BUTTON_SAVE_PARTICLEENTITIES, OnBnClickedButtonSaveParticles)
ON_BN_CLICKED(IDC_BUTTON_TESTMODEL, OnBnClickedTestModel)
ON_BN_CLICKED(IDC_BUTTON_IMPACT, OnBnClickedImpact)
ON_BN_CLICKED(IDC_BUTTON_MUZZLE, OnBnClickedMuzzle)
ON_BN_CLICKED(IDC_BUTTON_FLIGHT, OnBnClickedFlight)
ON_BN_CLICKED(IDC_BUTTON_SELECTED, OnBnClickedSelected)
ON_BN_CLICKED(IDC_BUTTON_DOOM, OnBnClickedDoom)
ON_BN_CLICKED(IDC_CHECK_EDITPARTICLEMODE, OnBnClickedParticleMode)
ON_BN_CLICKED(IDC_BUTTON_DROPEMITTER, OnBtnDrop)
ON_BN_CLICKED(IDC_BUTTON_YUP, OnBtnYup)
ON_BN_CLICKED(IDC_BUTTON_YDN, OnBtnYdn)
ON_BN_CLICKED(IDC_BUTTON_XDN, OnBtnXdn)
ON_BN_CLICKED(IDC_BUTTON_XUP, OnBtnXup)
ON_BN_CLICKED(IDC_BUTTON_ZUP, OnBtnZup)
ON_BN_CLICKED(IDC_BUTTON_ZDN, OnBtnZdn)
ON_WM_HSCROLL()
END_MESSAGE_MAP()
// CDialogParticleEditor message handlers
void CDialogParticleEditor::OnBnClickedParticleMode() {
particleMode = !particleMode;
cvarSystem->SetCVarInteger( "g_editEntityMode", ( particleMode ) ? 4 : 0 );
EnableEditControls();
}
void CDialogParticleEditor::OnBnClickedButtonSaveAs() {
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
DialogName dlg("New Particle");
if (dlg.DoModal() == IDOK) {
if ( declManager->FindType( DECL_PARTICLE, dlg.m_strName, false ) ) {
MessageBox( "Particle already exists!", "Particle exists", MB_OK );
return;
}
CFileDialog dlgSave( TRUE, "prt", NULL, OFN_CREATEPROMPT, "Particle Files (*.prt)|*.prt||All Files (*.*)|*.*||", AfxGetMainWnd() );
if ( dlgSave.DoModal() == IDOK ) {
idStr fileName;
fileName = fileSystem->OSPathToRelativePath( dlgSave.m_ofn.lpstrFile );
idDeclParticle *decl = dynamic_cast<idDeclParticle*>( declManager->CreateNewDecl( DECL_PARTICLE, dlg.m_strName, fileName ) );
if ( decl ) {
decl->stages.DeleteContents( true );
decl->depthHack = idp->depthHack;
for ( int i = 0; i < idp->stages.Num(); i++ ) {
idParticleStage *stage = new idParticleStage();
*stage = *idp->stages[i];
decl->stages.Append( stage );
}
EnumParticles();
int index = comboParticle.FindStringExact( -1, dlg.m_strName );
if ( index >= 0 ) {
comboParticle.SetCurSel( index );
}
OnBnClickedButtonSave();
OnCbnSelchangeComboParticles();
OnBnClickedButtonUpdate();
}
}
}
}
void CDialogParticleEditor::OnBnClickedButtonSaveParticles() {
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "saveParticles" );
CWnd *wnd = GetDlgItem( IDC_BUTTON_SAVE_PARTICLEENTITIES );
if ( wnd ) {
wnd->EnableWindow( FALSE );
}
}
void CDialogParticleEditor::OnBnClickedButtonAddstage() {
AddStage();
}
void CDialogParticleEditor::OnBnClickedButtonRemovestage() {
RemoveStage();
}
void CDialogParticleEditor::OnBnClickedButtonBrowsematerial() {
CPreviewDlg matDlg( this );
matDlg.SetMode(CPreviewDlg::MATERIALS, "particles" );
matDlg.SetDisablePreview( true );
if ( matDlg.DoModal() == IDOK ) {
matName = matDlg.mediaName;
DlgVarsToCurStage();
CurStageToDlgVars();
}
}
void CDialogParticleEditor::OnBnClickedButtonBrowsecolor() {
int r, g, b;
float ob;
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
r = ps->color.x * 255.0f;
g = ps->color.y * 255.0f;
b = ps->color.z * 255.0f;
ob = 1.0f;
if ( DoNewColor( &r, &g, &b, &ob ) ) {
color.Format( "%f %f %f %f", (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f, 1.0f );
DlgVarsToCurStage();
CurStageToDlgVars();
}
}
void CDialogParticleEditor::OnBnClickedButtonBrowseEntitycolor() {
int r, g, b;
float ob;
idList<idEntity*> list;
idDict dict2;
idStr str;
list.SetNum( 128 );
int count = gameEdit->GetSelectedEntities( list.Ptr(), list.Num() );
list.SetNum( count );
if ( count ) {
const idDict *dict = gameEdit->EntityGetSpawnArgs( list[0] );
if ( dict ) {
idVec3 clr = dict->GetVector( "_color", "1 1 1" );
r = clr.x * 255.0f;
g = clr.y * 255.0f;
b = clr.z * 255.0f;
ob = 1.0f;
if ( DoNewColor( &r, &g, &b, &ob ) ) {
for ( int i = 0; i < count; i++ ) {
dict = gameEdit->EntityGetSpawnArgs( list[i] );
const char *name = dict->GetString( "name" );
idEntity *ent = gameEdit->FindEntity( name );
if ( ent ) {
gameEdit->EntitySetColor( ent, idVec3( (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f ) );
str = va( "%f %f %f", (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f );
dict2.Clear();
dict2.Set( "_color", str );
gameEdit->EntityChangeSpawnArgs( ent, &dict2 );
gameEdit->MapSetEntityKeyVal( name, "_color", str );
}
}
}
}
CWnd *wnd = GetDlgItem( IDC_BUTTON_SAVE_PARTICLEENTITIES );
if ( wnd ) {
wnd->EnableWindow( TRUE );
}
}
}
void CDialogParticleEditor::OnBnClickedButtonBrowsefadecolor() {
int r, g, b;
float ob;
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
r = ps->fadeColor.x * 255.0f;
g = ps->fadeColor.y * 255.0f;
b = ps->fadeColor.z * 255.0f;
ob = 1.0f;
if ( DoNewColor( &r, &g, &b, &ob ) ) {
fadeColor.Format( "%f %f %f %f", (float)r / 255.0f, (float)g / 255.0f, (float)b / 255.0f, 1.0f );
DlgVarsToCurStage();
CurStageToDlgVars();
}
}
void CDialogParticleEditor::OnBnClickedButtonUpdate() {
UpdateData( TRUE );
DlgVarsToCurStage();
CurStageToDlgVars();
}
void CDialogParticleEditor::SelectParticle( const char *name ) {
int index = comboParticle.FindString( 0, name );
if ( index >= 0 ) {
comboParticle.SetCurSel( index );
UpdateParticleData();
}
}
idDeclParticle *CDialogParticleEditor::GetCurParticle() {
int sel = comboParticle.GetCurSel();
if ( sel == CB_ERR ) {
return NULL;
}
int index = comboParticle.GetItemData( sel );
return static_cast<idDeclParticle *>( const_cast<idDecl *>( declManager->DeclByIndex( DECL_PARTICLE, index ) ) );
}
void CDialogParticleEditor::UpdateParticleData() {
listStages.ResetContent();
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
for ( int i = 0; i < idp->stages.Num(); i++ ) {
int index = listStages.AddString( va( "stage %i", i ) );
if ( index >= 0 ) {
listStages.SetItemData( index, i );
}
}
listStages.SetCurSel( 0 );
OnLbnSelchangeListStages();
CWnd *wnd = GetDlgItem( IDC_STATIC_INFILE );
if ( wnd ) {
wnd->SetWindowText( va( "Particle file: %s", idp->GetFileName() ) );
}
SetParticleView();
}
void CDialogParticleEditor::OnCbnSelchangeComboParticles() {
UpdateParticleData();
}
void CDialogParticleEditor::OnCbnSelchangeComboPath() {
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::UpdateControlInfo() {
CWnd *wnd = GetDlgItem( IDC_EDIT_RINGOFFSET );
if ( wnd ) {
wnd->EnableWindow( distribution == 2 );
}
wnd = GetDlgItem( IDC_STATIC_DIRPARM );
if ( wnd ) {
wnd->SetWindowText( (direction == 0 ) ? "Angle" : "Upward Bias" );
}
wnd = GetDlgItem( IDC_EDIT_ORIENTATIONPARM1 );
if ( wnd ) {
wnd->EnableWindow( orientation == 1 );
}
wnd = GetDlgItem( IDC_EDIT_ORIENTATIONPARM2 );
if ( wnd ) {
wnd->EnableWindow( orientation == 1 );
}
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
sliderBunching.SetValuePos( ps->spawnBunching );
sliderFadeIn.SetValuePos( ps->fadeInFraction );
sliderFadeOut.SetValuePos( ps->fadeOutFraction );
sliderFadeFraction.SetValuePos( ps->fadeIndexFraction );
sliderCount.SetValuePos( ps->totalParticles );
sliderTime.SetValuePos( ps->particleLife );
sliderGravity.SetValuePos( ps->gravity );
sliderSpeedFrom.SetValuePos( ps->speed.from );
sliderSpeedTo.SetValuePos( ps->speed.to );
sliderRotationFrom.SetValuePos( ps->rotationSpeed.from );
sliderRotationTo.SetValuePos( ps->rotationSpeed.to );
sliderSizeFrom.SetValuePos( ps->size.from );
sliderSizeTo.SetValuePos( ps->size.to );
sliderAspectFrom.SetValuePos( ps->aspect.from );
sliderAspectTo.SetValuePos( ps->aspect.to );
}
void CDialogParticleEditor::OnBnClickedRadioRect() {
distribution = 0;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioSphere() {
distribution = 2;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioCylinder() {
distribution = 1;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioCone() {
direction = 0;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioOutward() {
direction = 1;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioView() {
orientation = 0;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioAimed() {
orientation = 1;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioX() {
orientation = 2;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioY() {
orientation = 3;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedRadioZ() {
orientation = 4;
DlgVarsToCurStage();
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnBnClickedDoom() {
::SetFocus(win32.hWnd);
}
void CDialogParticleEditor::OnBnClickedTestModel() {
visualization = TESTMODEL;
SetParticleView();
}
void CDialogParticleEditor::OnBnClickedImpact() {
visualization = IMPACT;
SetParticleView();
}
void CDialogParticleEditor::OnBnClickedMuzzle(){
visualization = MUZZLE;
SetParticleView();
}
void CDialogParticleEditor::OnBnClickedFlight() {
visualization = FLIGHT;
SetParticleView();
}
void CDialogParticleEditor::OnBnClickedSelected() {
visualization = SELECTED;
SetParticleView();
}
void CDialogParticleEditor::SetParticleVisualization( int i ) {
visualization = i;
SetParticleView();
}
void CDialogParticleEditor::SetParticleView() {
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
cmdSystem->BufferCommandText( CMD_EXEC_NOW, "testmodel" );
idStr str;
switch ( visualization ) {
case TESTMODEL :
str = idp->GetName();
str.SetFileExtension( ".prt" );
cmdSystem->BufferCommandText( CMD_EXEC_NOW, va("testmodel %s\n", str.c_str() ) );
break;
case IMPACT :
str = idp->GetName();
str.SetFileExtension( ".prt" );
cvarSystem->SetCVarInteger( "g_testParticle", TEST_PARTICLE_IMPACT );
cvarSystem->SetCVarString( "g_testParticleName", str );
break;
case MUZZLE :
str = idp->GetName();
str.SetFileExtension( ".prt" );
cvarSystem->SetCVarInteger( "g_testParticle", TEST_PARTICLE_MUZZLE );
cvarSystem->SetCVarString( "g_testParticleName", str );
break;
case FLIGHT :
str = idp->GetName();
str.SetFileExtension( ".prt" );
cvarSystem->SetCVarInteger( "g_testParticle", TEST_PARTICLE_FLIGHT );
cvarSystem->SetCVarString( "g_testParticleName", str );
break;
case SELECTED :
str = idp->GetName();
str.SetFileExtension( ".prt" );
cvarSystem->SetCVarInteger( "g_testParticle", TEST_PARTICLE_FLIGHT );
SetSelectedModel( str );
break;
}
}
void CDialogParticleEditor::SetSelectedModel( const char *val ) {
idList<idEntity*> list;
idMat3 axis;
list.SetNum( 128 );
int count = gameEdit->GetSelectedEntities( list.Ptr(), list.Num() );
list.SetNum( count );
if ( count ) {
for ( int i = 0; i < count; i++ ) {
const idDict *dict = gameEdit->EntityGetSpawnArgs( list[i] );
if ( dict == NULL ) {
continue;
}
const char *name = dict->GetString( "name" );
gameEdit->EntitySetModel( list[i], val );
gameEdit->EntityUpdateVisuals( list[i] );
gameEdit->EntityGetAxis( list[i], axis );
vectorControl.SetidAxis( axis );
gameEdit->MapSetEntityKeyVal( name, "model", val );
}
CWnd *wnd = GetDlgItem( IDC_BUTTON_SAVE_PARTICLEENTITIES );
if ( wnd ) {
wnd->EnableWindow( TRUE );
}
}
}
void CDialogParticleEditor::OnBnClickedButtonHidestage() {
HideStage();
}
void CDialogParticleEditor::OnBnClickedButtonShowstage() {
ShowStage();
}
void CDialogParticleEditor::OnBnClickedWorldGravity() {
worldGravity = !worldGravity;
DlgVarsToCurStage();
CurStageToDlgVars();
}
void CDialogParticleEditor::OnBnClickedEntityColor() {
entityColor = !entityColor;
DlgVarsToCurStage();
CurStageToDlgVars();
}
void CDialogParticleEditor::AddStage() {
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
idParticleStage *stage = new idParticleStage;
if ((GetAsyncKeyState(VK_CONTROL) & 0x8000)) {
idParticleStage *source = GetCurStage();
if ( source == NULL ) {
delete stage;
return;
}
*stage = *source;
} else {
stage->Default();
}
int newIndex = idp->stages.Append( stage );
int index = listStages.AddString( va( "stage %i", newIndex ) );
listStages.SetCurSel( index );
listStages.SetItemData( index, newIndex );
ShowCurrentStage();
EnableStageControls();
}
void CDialogParticleEditor::RemoveStage() {
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
if ( MessageBox( "Are you sure you want to remove this stage?", "Remove Stage", MB_YESNO | MB_ICONQUESTION ) != IDYES ) {
return;
}
int index = listStages.GetCurSel();
if ( index >= 0 ) {
int newIndex = listStages.GetItemData( index );
if ( newIndex >= 0 && newIndex < idp->stages.Num() ) {
idp->stages.RemoveIndex( newIndex );
index += ( index >= 1 ) ? -1 : 1;
newIndex = comboParticle.FindStringExact( -1, idp->GetName() );
EnumParticles();
if ( newIndex >= 0 ) {
comboParticle.SetCurSel( newIndex );
}
OnCbnSelchangeComboParticles();
listStages.SetCurSel( index );
ShowCurrentStage();
}
}
EnableStageControls();
}
void CDialogParticleEditor::ShowStage() {
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
ps->hidden = false;
int index = listStages.GetCurSel();
int newIndex = listStages.GetItemData( index );
listStages.DeleteString ( index );
listStages.InsertString( index, va("stage %i", index ) );
listStages.SetItemData( index, newIndex );
listStages.SetCurSel( index );
EnableStageControls();
}
void CDialogParticleEditor::HideStage() {
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
ps->hidden = true;
int index = listStages.GetCurSel();
int newIndex = listStages.GetItemData( index );
listStages.DeleteString ( index );
listStages.InsertString( index, va("stage %i (H) ", index ) );
listStages.SetItemData( index, newIndex );
listStages.SetCurSel( index );
EnableStageControls();
}
idParticleStage *CDialogParticleEditor::GetCurStage() {
idDeclParticle *idp = GetCurParticle();
int sel = listStages.GetCurSel();
int index = listStages.GetItemData( sel );
if ( idp == NULL || sel == LB_ERR || index >= idp->stages.Num() ) {
return NULL;
}
return idp->stages[index];
}
void CDialogParticleEditor::ClearDlgVars() {
matName = "";
animFrames = "";
animRate = "";
color = "";
fadeColor = "";
fadeIn = "";
fadeOut = "";
fadeFraction = "";
count = "";
time = "";
timeOffset = "";
deadTime = "";
gravity = "";
bunching = "";
offset = "";
xSize = "";
ySize = "";
zSize = "";
ringOffset = "";
directionParm = "";
direction = 1;
orientation = 1;
distribution = 1;
speedFrom = "";
speedTo = "";
rotationFrom = "";
rotationTo = "";
sizeFrom = "";
sizeTo = "";
aspectFrom = "";
aspectTo = "";
customPath = "";
customParms = "";
trails = "";
trailTime = "";
worldGravity = FALSE;
entityColor = FALSE;
randomDistribution = TRUE;
initialAngle = "";
customDesc = "";
UpdateData( FALSE );
}
void CDialogParticleEditor::CurStageToDlgVars() {
// go ahead and get the two system vars too
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
depthHack = va( "%.3f", idp->depthHack );
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
matName = ps->material->GetName();
animFrames = va( "%i", ps->animationFrames );
animRate = va( "%i", ps->animationRate );
color = ps->color.ToString();
fadeColor = ps->fadeColor.ToString();
fadeIn = va( "%.3f", ps->fadeInFraction );
fadeOut = va( "%.3f", ps->fadeOutFraction );
fadeFraction = va( "%.3f", ps->fadeIndexFraction );
count = va( "%i", ps->totalParticles );
time = va( "%.3f", ps->particleLife );
timeOffset = va( "%.3f", ps->timeOffset );
deadTime = va( "%.3f", ps->deadTime );
gravity = va( "%.3f", ps->gravity );
bunching = va( "%.3f", ps->spawnBunching );
offset = ps->offset.ToString( 0 );
xSize = va( "%.3f", ps->distributionParms[0] );
ySize = va( "%.3f", ps->distributionParms[1] );
zSize = va( "%.3f", ps->distributionParms[2] );
ringOffset = va( "%.3f", ps->distributionParms[3] );
directionParm = va( "%.3f", ps->directionParms[0] );
direction = ps->directionType;
orientation = ps->orientation;
distribution = ps->distributionType;
speedFrom = va( "%.3f", ps->speed.from );
speedTo = va( "%.3f", ps->speed.to );
rotationFrom = va( "%.3f", ps->rotationSpeed.from );
rotationTo = va( "%.3f", ps->rotationSpeed.to );
sizeFrom = va( "%.3f", ps->size.from );
sizeTo = va( "%.3f", ps->size.to );
aspectFrom = va( "%.3f", ps->aspect.from );
aspectTo = va( "%.3f", ps->aspect.to );
trails = va( "%f", ps->orientationParms[0] );
trailTime = va( "%.3f", ps->orientationParms[1] );
cycles = va( "%.3f", ps->cycles );
customPath = ps->GetCustomPathName();
customParms = "";
customDesc = ps->GetCustomPathDesc();
if ( ps->customPathType != PPATH_STANDARD ) {
for ( int i = 0; i < ps->NumCustomPathParms(); i++ ) {
customParms += va( "%.1f ", ps->customPathParms[i] );
}
}
worldGravity = ps->worldGravity;
initialAngle = va( "%.3f", ps->initialAngle );
boundsExpansion = va( "%.3f", ps->boundsExpansion );
randomDistribution = ps->randomDistribution;
entityColor = ps->entityColor;
UpdateData( FALSE );
}
void CDialogParticleEditor::DlgVarsToCurStage() {
// go ahead and set the two system vars too
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
idp->depthHack = atof( depthHack );
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
ps->material = declManager->FindMaterial( matName );
ps->animationFrames = atoi( animFrames );
ps->animationRate = atoi( animRate );
sscanf( color, "%f %f %f %f", &ps->color.x, &ps->color.y, &ps->color.z, &ps->color.w );
sscanf( fadeColor, "%f %f %f %f", &ps->fadeColor.x, &ps->fadeColor.y, &ps->fadeColor.z, &ps->fadeColor.w );
ps->fadeInFraction = atof( fadeIn );
ps->fadeOutFraction = atof( fadeOut );
ps->fadeIndexFraction = atof( fadeFraction );
ps->totalParticles = atoi( count );
ps->particleLife = atof( time );
ps->timeOffset = atof( timeOffset );
ps->deadTime = atof( deadTime );
ps->gravity = atof( gravity );
ps->spawnBunching = atof( bunching );
sscanf( offset, "%f %f %f", &ps->offset.x, &ps->offset.y, &ps->offset.z );
ps->distributionParms[0] = atof( xSize );
ps->distributionParms[1] = atof( ySize );
ps->distributionParms[2] = atof( zSize );
ps->distributionParms[3] = atof( ringOffset );
ps->directionParms[0] = atof( directionParm );
ps->directionType = static_cast<prtDirection_t>( direction );
ps->orientation = static_cast<prtOrientation_t>( orientation );
ps->distributionType = static_cast<prtDistribution_t>( distribution );
ps->speed.from = atof( speedFrom );
ps->speed.to = atof( speedTo );
ps->rotationSpeed.from = atof( rotationFrom );
ps->rotationSpeed.to = atof( rotationTo );
ps->size.from = atof( sizeFrom );
ps->size.to = atof( sizeTo );
ps->aspect.from = atof( aspectFrom );
ps->aspect.to = atof( aspectTo );
ps->orientationParms[0] = atof( trails );
ps->orientationParms[1] = atof( trailTime );
ps->worldGravity = ( worldGravity == TRUE );
ps->cycles = atof( cycles );
ps->cycleMsec = ( ps->particleLife + ps->deadTime ) * 1000;
sscanf( customParms, "%f %f %f %f %f %f %f %f", &ps->customPathParms[0], &ps->customPathParms[1], &ps->customPathParms[2],
&ps->customPathParms[3], &ps->customPathParms[4], &ps->customPathParms[5],
&ps->customPathParms[6], &ps->customPathParms[7] );
ps->SetCustomPathType( customPath );
ps->initialAngle = atof( initialAngle );
ps->boundsExpansion = atof( boundsExpansion );
ps->randomDistribution = ( randomDistribution != FALSE );
ps->entityColor = ( entityColor == TRUE );
}
void CDialogParticleEditor::ShowCurrentStage() {
ClearDlgVars();
idParticleStage *ps = GetCurStage();
if ( ps == NULL ) {
return;
}
CurStageToDlgVars();
UpdateControlInfo();
}
void CDialogParticleEditor::OnLbnSelchangeListStages() {
ShowCurrentStage();
EnableStageControls();
}
void CDialogParticleEditor::OnBnClickedButtonNew() {
DialogName dlg("New Particle");
if (dlg.DoModal() == IDOK) {
CFileDialog dlgSave( TRUE, "prt", NULL, OFN_CREATEPROMPT, "Particle Files (*.prt)|*.prt||All Files (*.*)|*.*||", AfxGetMainWnd() );
if ( dlgSave.DoModal() == IDOK ) {
if ( declManager->FindType( DECL_PARTICLE, dlg.m_strName, false ) ) {
MessageBox( "Particle already exists!", "Particle exists", MB_OK );
return;
}
idStr fileName;
fileName = fileSystem->OSPathToRelativePath( dlgSave.m_ofn.lpstrFile );
idDecl *decl = declManager->CreateNewDecl( DECL_PARTICLE, dlg.m_strName, fileName );
if ( decl ) {
if ( MessageBox( "Copy current particle?", "Copy current", MB_YESNO | MB_ICONQUESTION ) == IDYES ) {
MessageBox( "Copy current particle not implemented yet.. Stay tuned" );
}
EnumParticles();
int index = comboParticle.FindStringExact( -1, dlg.m_strName );
if ( index >= 0 ) {
comboParticle.SetCurSel( index );
}
OnBnClickedButtonSave();
OnCbnSelchangeComboParticles();
}
}
}
}
void CDialogParticleEditor::OnBnClickedButtonSave() {
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
if ( strstr( idp->GetFileName(), "implicit" ) ) {
// defaulted, need to choose a file
CFileDialog dlgSave( FALSE, "prt", NULL, OFN_OVERWRITEPROMPT, "Particle Files (*.prt)|*.prt||All Files (*.*)|*.*||", AfxGetMainWnd() );
if ( dlgSave.DoModal() == IDOK ) {
idStr fileName;
fileName = fileSystem->OSPathToRelativePath( dlgSave.m_ofn.lpstrFile );
idp->Save( fileName );
EnumParticles();
}
} else {
idp->Save();
}
}
void CDialogParticleEditor::EnumParticles() {
CWaitCursor cursor;
comboParticle.ResetContent();
for ( int i = 0; i < declManager->GetNumDecls( DECL_PARTICLE ); i++ ) {
const idDecl *idp = declManager->DeclByIndex( DECL_PARTICLE, i );
int index = comboParticle.AddString( idp->GetName() );
if ( index >= 0 ) {
comboParticle.SetItemData( index, i );
}
}
comboParticle.SetCurSel( 0 );
OnCbnSelchangeComboParticles();
}
void CDialogParticleEditor::OnDestroy() {
com_editors &= ~EDITOR_PARTICLE;
return CDialog::OnDestroy();
}
void VectorCallBack( idQuat rotation ) {
if ( g_ParticleDialog && g_ParticleDialog->GetSafeHwnd() ) {
g_ParticleDialog->SetVectorControlUpdate( rotation );
}
}
void CDialogParticleEditor::SetVectorControlUpdate( idQuat rotation ) {
if ( particleMode ) {
idList<idEntity*> list;
list.SetNum( 128 );
int count = gameEdit->GetSelectedEntities( list.Ptr(), list.Num() );
list.SetNum( count );
if ( count ) {
for ( int i = 0; i < count; i++ ) {
const idDict *dict = gameEdit->EntityGetSpawnArgs( list[i] );
if ( dict == NULL ) {
continue;
}
const char *name = dict->GetString( "name" );
gameEdit->EntitySetAxis( list[i], rotation.ToMat3() );
gameEdit->EntityUpdateVisuals( list[i] );
gameEdit->MapSetEntityKeyVal( name, "rotation", rotation.ToMat3().ToString() );
}
CWnd *wnd = GetDlgItem( IDC_BUTTON_SAVE_PARTICLEENTITIES );
if ( wnd ) {
wnd->EnableWindow( TRUE );
}
}
}
}
BOOL CDialogParticleEditor::OnInitDialog() {
com_editors |= EDITOR_PARTICLE;
particleMode = ( cvarSystem->GetCVarInteger( "g_editEntityMode" ) == 4 );
mapModified = false;
CDialog::OnInitDialog();
sliderBunching.SetRange( 0, 20 );
sliderBunching.SetValueRange( 0.0f, 1.0f );
sliderFadeIn.SetRange( 0, 20 );
sliderFadeIn.SetValueRange( 0.0f, 1.0f );
sliderFadeOut.SetRange( 0, 20 );
sliderFadeOut.SetValueRange( 0.0f, 1.0f );
sliderCount.SetRange( 0, 1024 );
sliderCount.SetValueRange( 0, 4096 );
sliderTime.SetRange( 0, 200 );
sliderTime.SetValueRange( 0.0f, 10.0f );
sliderGravity.SetRange( 0, 600 );
sliderGravity.SetValueRange( -300.0f, 300.0f );
sliderSpeedFrom.SetRange( 0, 600 );
sliderSpeedFrom.SetValueRange( -300.0f, 300.0f );
sliderSpeedTo.SetRange( 0, 600 );
sliderSpeedTo.SetValueRange( -300.0f, 300.0f );
sliderRotationFrom.SetRange( 0, 100 );
sliderRotationFrom.SetValueRange( 0.0f, 100.0f );
sliderRotationTo.SetRange( 0, 100 );
sliderRotationTo.SetValueRange( 0.0f, 100.0f );
sliderSizeFrom.SetRange( 0, 256 );
sliderSizeFrom.SetValueRange( 0.0f, 128.0f );
sliderSizeTo.SetRange( 0, 256 );
sliderSizeTo.SetValueRange( 0.0f, 128.0f );
sliderAspectFrom.SetRange( 0, 256 );
sliderAspectFrom.SetValueRange( 0.0f, 128.0f );
sliderAspectTo.SetRange( 0, 256 );
sliderAspectTo.SetValueRange( 0.0f, 128.0f );
sliderFadeFraction.SetRange( 0, 20 );
sliderFadeFraction.SetValueRange( 0.0f, 1.0f );
EnumParticles();
SetParticleView();
toolTipCtrl.Create( this );
toolTipCtrl.Activate( TRUE );
CWnd* wnd = GetWindow( GW_CHILD );
CString str;
while ( wnd ) {
if ( str.LoadString( wnd->GetDlgCtrlID() ) ) {
toolTipCtrl.AddTool( wnd, str );
}
wnd = wnd->GetWindow( GW_HWNDNEXT );
}
wnd = GetDlgItem( IDC_BUTTON_SAVE_PARTICLEENTITIES );
if ( wnd ) {
wnd->EnableWindow( FALSE );
}
EnableEditControls();
vectorControl.SetVectorChangingCallback( VectorCallBack );
return TRUE; // return TRUE unless you set the focus to a control
// EXCEPTION: OCX Property Pages should return FALSE
}
void CDialogParticleEditor::OnHScroll( UINT nSBCode, UINT nPos, CScrollBar* pScrollBar ) {
CDialog::OnHScroll( nSBCode, nPos, pScrollBar );
CSliderCtrl *ctrl = dynamic_cast< CSliderCtrl* >( pScrollBar );
if ( !ctrl ) {
return;
}
if ( ctrl == &sliderBunching ) {
// handle bunching
bunching = va( "%.3f", sliderBunching.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderFadeIn ) {
fadeIn = va( "%.3f", sliderFadeIn.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderFadeOut ) {
fadeOut = va( "%.3f", sliderFadeOut.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderFadeFraction ) {
fadeFraction = va( "%.3f", sliderFadeFraction.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderCount ) {
count = va( "%i", (int)sliderCount.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderTime ) {
time = va( "%.3f", sliderTime.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderGravity ) {
gravity = va( "%.3f", sliderGravity.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderSpeedFrom ) {
speedFrom = va( "%.3f", sliderSpeedFrom.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderSpeedTo ) {
speedTo = va( "%.3f", sliderSpeedTo.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderRotationFrom ) {
rotationFrom = va( "%.3f", sliderRotationFrom.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderRotationTo ) {
rotationTo = va( "%.3f", sliderRotationTo.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderSizeFrom ) {
sizeFrom = va( "%.3f", sliderSizeFrom.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderSizeTo ) {
sizeTo = va( "%.3f", sliderSizeTo.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderAspectFrom ) {
aspectFrom = va( "%.3f", sliderAspectFrom.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
} else if ( ctrl == &sliderAspectTo ) {
aspectTo = va( "%.3f", sliderAspectTo.GetValue() );
DlgVarsToCurStage();
CurStageToDlgVars();
}
}
BOOL CDialogParticleEditor::PreTranslateMessage(MSG *pMsg) {
if ( pMsg->message >= WM_MOUSEFIRST && pMsg->message <= WM_MOUSELAST ) {
toolTipCtrl.RelayEvent( pMsg );
}
return CDialog::PreTranslateMessage(pMsg);
}
void CDialogParticleEditor::EnableStageControls() {
idParticleStage *stage = GetCurStage();
bool b = ( stage && stage->hidden ) ? false : true;
for ( int i = 0; i < StageIDCount; i++ ) {
CWnd *wnd = GetDlgItem( StageEnableID[ i ] );
if ( wnd ) {
wnd->EnableWindow( b );
}
}
}
void CDialogParticleEditor::EnableEditControls() {
for ( int i = 0; i < EditIDCount; i++ ) {
CWnd *wnd = GetDlgItem( EditEnableID[ i ] );
if ( wnd ) {
wnd->EnableWindow( particleMode );
}
}
}
void CDialogParticleEditor::UpdateSelectedOrigin( float x, float y, float z ) {
idList<idEntity*> list;
idVec3 origin;
idVec3 vec(x, y, z);
list.SetNum( 128 );
int count = gameEdit->GetSelectedEntities( list.Ptr(), list.Num() );
list.SetNum( count );
if ( count ) {
for ( int i = 0; i < count; i++ ) {
const idDict *dict = gameEdit->EntityGetSpawnArgs( list[i] );
if ( dict == NULL ) {
continue;
}
const char *name = dict->GetString( "name" );
gameEdit->EntityTranslate( list[i], vec );
gameEdit->EntityUpdateVisuals( list[i] );
gameEdit->MapEntityTranslate( name, vec );
}
CWnd *wnd = GetDlgItem( IDC_BUTTON_SAVE_PARTICLEENTITIES );
if ( wnd ) {
wnd->EnableWindow( TRUE );
}
}
}
void CDialogParticleEditor::OnBtnYup()
{
UpdateSelectedOrigin(0, 8, 0);
}
void CDialogParticleEditor::OnBtnYdn()
{
UpdateSelectedOrigin(0, -8, 0);
}
void CDialogParticleEditor::OnBtnXdn()
{
UpdateSelectedOrigin(-8, 0, 0);
}
void CDialogParticleEditor::OnBtnXup()
{
UpdateSelectedOrigin(8, 0, 0);
}
void CDialogParticleEditor::OnBtnZup()
{
UpdateSelectedOrigin(0, 0, 8);
}
void CDialogParticleEditor::OnBtnZdn()
{
UpdateSelectedOrigin(0, 0, -8);
}
void CDialogParticleEditor::OnBtnDrop()
{
idStr classname;
idStr key;
idStr value;
idVec3 org;
idDict args;
idAngles viewAngles;
if ( !gameEdit->PlayerIsValid() ) {
return;
}
gameEdit->PlayerGetViewAngles( viewAngles );
gameEdit->PlayerGetEyePosition( org );
org += idAngles( 0, viewAngles.yaw, 0 ).ToForward() * 80 + idVec3( 0, 0, 1 );
args.Set("origin", org.ToString());
args.Set("classname", "func_emitter");
args.Set("angle", va( "%f", viewAngles.yaw + 180 ));
idDeclParticle *idp = GetCurParticle();
if ( idp == NULL ) {
return;
}
idStr str = idp->GetName();
str.SetFileExtension( ".prt" );
args.Set("model", str);
idStr name = gameEdit->GetUniqueEntityName( "func_emitter" );
bool nameValid = false;
while (!nameValid) {
DialogName dlg("Name Particle", this);
dlg.m_strName = name;
if (dlg.DoModal() == IDOK) {
idEntity *gameEnt = gameEdit->FindEntity( dlg.m_strName );
if (gameEnt) {
if (MessageBox("Please choose another name", "Duplicate Entity Name!", MB_OKCANCEL) == IDCANCEL) {
return;
}
} else {
nameValid = true;
name = dlg.m_strName;
}
}
}
args.Set("name", name.c_str());
idEntity *ent = NULL;
gameEdit->SpawnEntityDef( args, &ent );
if (ent) {
gameEdit->EntityUpdateChangeableSpawnArgs( ent, NULL );
gameEdit->ClearEntitySelection();
gameEdit->AddSelectedEntity( ent );
}
gameEdit->MapAddEntity( &args );
}
void CDialogParticleEditor::OnOK()
{
// never return on OK as windows will map this at times when you don't want
// ENTER closing the dialog
// CDialog::OnOK();
}
|
gpl-3.0
|
rac146/firmware
|
hal/src/photon/tls_stub.c
|
20
|
1069
|
#include "wiced.h"
wiced_result_t wiced_tcp_start_tls( wiced_tcp_socket_t* socket, wiced_tls_endpoint_type_t type, wiced_tls_certificate_verification_t verification )
{
return WICED_SUCCESS;
}
wiced_result_t wiced_tls_close_notify( wiced_tcp_socket_t* socket )
{
return WICED_SUCCESS;
}
wiced_result_t wiced_tls_deinit_context( wiced_tls_simple_context_t* tls_context )
{
return WICED_SUCCESS;
}
wiced_result_t wiced_tls_calculate_overhead( wiced_tls_context_t* context, uint16_t content_length, uint16_t* header, uint16_t* footer )
{
return WICED_SUCCESS;
}
wiced_result_t wiced_tls_encrypt_packet( wiced_tls_context_t* context, wiced_packet_t* packet )
{
return WICED_SUCCESS;
}
wiced_result_t wiced_tls_receive_packet( wiced_tcp_socket_t* socket, wiced_packet_t** packet, uint32_t timeout )
{
return WICED_SUCCESS;
}
wiced_result_t wiced_tls_reset_context( wiced_tls_simple_context_t* tls_context )
{
return WICED_SUCCESS;
}
void host_network_process_eapol_data( /*@only@*/ wiced_buffer_t buffer, wwd_interface_t interface )
{
}
|
gpl-3.0
|
ranqingfa/ardupilot
|
libraries/AP_Compass/AP_Compass_Calibration.cpp
|
21
|
9311
|
#include <AP_HAL/AP_HAL.h>
#include <AP_Notify/AP_Notify.h>
#include <GCS_MAVLink/GCS.h>
#include "AP_Compass.h"
extern AP_HAL::HAL& hal;
void
Compass::compass_cal_update()
{
bool running = false;
for (uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
bool failure;
_calibrator[i].update(failure);
if (failure) {
AP_Notify::events.compass_cal_failed = 1;
}
if (_calibrator[i].check_for_timeout()) {
AP_Notify::events.compass_cal_failed = 1;
cancel_calibration_all();
}
if (_calibrator[i].running()) {
running = true;
} else if (_cal_autosave && !_cal_saved[i] && _calibrator[i].get_status() == COMPASS_CAL_SUCCESS) {
_accept_calibration(i);
}
}
AP_Notify::flags.compass_cal_running = running;
if (is_calibrating()) {
_cal_has_run = true;
return;
} else if (_cal_has_run && _auto_reboot()) {
hal.scheduler->delay(1000);
hal.scheduler->reboot(false);
}
}
bool
Compass::_start_calibration(uint8_t i, bool retry, float delay)
{
if (!healthy(i)) {
return false;
}
if (!use_for_yaw(i)) {
return false;
}
if (!is_calibrating()) {
AP_Notify::events.initiated_compass_cal = 1;
}
if (i == get_primary() && _state[i].external != 0) {
_calibrator[i].set_tolerance(_calibration_threshold);
} else {
// internal compasses or secondary compasses get twice the
// threshold. This is because internal compasses tend to be a
// lot noisier
_calibrator[i].set_tolerance(_calibration_threshold*2);
}
_cal_saved[i] = false;
_calibrator[i].start(retry, delay, get_offsets_max());
// disable compass learning both for calibration and after completion
_learn.set_and_save(0);
return true;
}
bool
Compass::_start_calibration_mask(uint8_t mask, bool retry, bool autosave, float delay, bool autoreboot)
{
_cal_autosave = autosave;
_compass_cal_autoreboot = autoreboot;
for (uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
if ((1<<i) & mask) {
if (!_start_calibration(i,retry,delay)) {
_cancel_calibration_mask(mask);
return false;
}
}
}
return true;
}
void
Compass::start_calibration_all(bool retry, bool autosave, float delay, bool autoreboot)
{
_cal_autosave = autosave;
_compass_cal_autoreboot = autoreboot;
for (uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
// ignore any compasses that fail to start calibrating
// start all should only calibrate compasses that are being used
_start_calibration(i,retry,delay);
}
}
void
Compass::_cancel_calibration(uint8_t i)
{
AP_Notify::events.initiated_compass_cal = 0;
if (_calibrator[i].running() || _calibrator[i].get_status() == COMPASS_CAL_WAITING_TO_START) {
AP_Notify::events.compass_cal_canceled = 1;
}
_cal_saved[i] = false;
_calibrator[i].clear();
}
void
Compass::_cancel_calibration_mask(uint8_t mask)
{
for(uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
if((1<<i) & mask) {
_cancel_calibration(i);
}
}
}
void
Compass::cancel_calibration_all()
{
_cancel_calibration_mask(0xFF);
}
bool
Compass::_accept_calibration(uint8_t i)
{
CompassCalibrator& cal = _calibrator[i];
uint8_t cal_status = cal.get_status();
if (_cal_saved[i] || cal_status == COMPASS_CAL_NOT_STARTED) {
return true;
} else if (cal_status == COMPASS_CAL_SUCCESS) {
_cal_complete_requires_reboot = true;
_cal_saved[i] = true;
Vector3f ofs, diag, offdiag;
cal.get_calibration(ofs, diag, offdiag);
set_and_save_offsets(i, ofs);
set_and_save_diagonals(i,diag);
set_and_save_offdiagonals(i,offdiag);
if (!is_calibrating()) {
AP_Notify::events.compass_cal_saved = 1;
}
return true;
} else {
return false;
}
}
bool
Compass::_accept_calibration_mask(uint8_t mask)
{
bool success = true;
for (uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
if ((1<<i) & mask) {
if (!_accept_calibration(i)) {
success = false;
}
_calibrator[i].clear();
}
}
return success;
}
void
Compass::send_mag_cal_progress(mavlink_channel_t chan)
{
uint8_t cal_mask = _get_cal_mask();
for (uint8_t compass_id=0; compass_id<COMPASS_MAX_INSTANCES; compass_id++) {
// ensure we don't try to send with no space available
if (!HAVE_PAYLOAD_SPACE(chan, MAG_CAL_PROGRESS)) {
return;
}
auto& calibrator = _calibrator[compass_id];
uint8_t cal_status = calibrator.get_status();
if (cal_status == COMPASS_CAL_WAITING_TO_START ||
cal_status == COMPASS_CAL_RUNNING_STEP_ONE ||
cal_status == COMPASS_CAL_RUNNING_STEP_TWO) {
uint8_t completion_pct = calibrator.get_completion_percent();
auto& completion_mask = calibrator.get_completion_mask();
Vector3f direction(0.0f,0.0f,0.0f);
uint8_t attempt = _calibrator[compass_id].get_attempt();
mavlink_msg_mag_cal_progress_send(
chan,
compass_id, cal_mask,
cal_status, attempt, completion_pct, completion_mask,
direction.x, direction.y, direction.z
);
}
}
}
void Compass::send_mag_cal_report(mavlink_channel_t chan)
{
uint8_t cal_mask = _get_cal_mask();
for (uint8_t compass_id=0; compass_id<COMPASS_MAX_INSTANCES; compass_id++) {
// ensure we don't try to send with no space available
if (!HAVE_PAYLOAD_SPACE(chan, MAG_CAL_REPORT)) {
return;
}
uint8_t cal_status = _calibrator[compass_id].get_status();
if ((cal_status == COMPASS_CAL_SUCCESS ||
cal_status == COMPASS_CAL_FAILED)) {
float fitness = _calibrator[compass_id].get_fitness();
Vector3f ofs, diag, offdiag;
_calibrator[compass_id].get_calibration(ofs, diag, offdiag);
uint8_t autosaved = _cal_saved[compass_id];
mavlink_msg_mag_cal_report_send(
chan,
compass_id, cal_mask,
cal_status, autosaved,
fitness,
ofs.x, ofs.y, ofs.z,
diag.x, diag.y, diag.z,
offdiag.x, offdiag.y, offdiag.z
);
}
}
}
bool
Compass::is_calibrating() const
{
for (uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
switch(_calibrator[i].get_status()) {
case COMPASS_CAL_NOT_STARTED:
case COMPASS_CAL_SUCCESS:
case COMPASS_CAL_FAILED:
break;
default:
return true;
}
}
return false;
}
uint8_t
Compass::_get_cal_mask() const
{
uint8_t cal_mask = 0;
for (uint8_t i=0; i<COMPASS_MAX_INSTANCES; i++) {
if (_calibrator[i].get_status() != COMPASS_CAL_NOT_STARTED) {
cal_mask |= 1 << i;
}
}
return cal_mask;
}
/*
handle an incoming MAG_CAL command
*/
MAV_RESULT Compass::handle_mag_cal_command(const mavlink_command_long_t &packet)
{
MAV_RESULT result = MAV_RESULT_FAILED;
switch (packet.command) {
case MAV_CMD_DO_START_MAG_CAL: {
result = MAV_RESULT_ACCEPTED;
if (hal.util->get_soft_armed()) {
hal.console->printf("Disarm for compass calibration\n");
result = MAV_RESULT_FAILED;
break;
}
if (packet.param1 < 0 || packet.param1 > 255) {
result = MAV_RESULT_FAILED;
break;
}
uint8_t mag_mask = packet.param1;
bool retry = !is_zero(packet.param2);
bool autosave = !is_zero(packet.param3);
float delay = packet.param4;
bool autoreboot = !is_zero(packet.param5);
if (mag_mask == 0) { // 0 means all
start_calibration_all(retry, autosave, delay, autoreboot);
} else {
if (!_start_calibration_mask(mag_mask, retry, autosave, delay, autoreboot)) {
result = MAV_RESULT_FAILED;
}
}
break;
}
case MAV_CMD_DO_ACCEPT_MAG_CAL: {
result = MAV_RESULT_ACCEPTED;
if(packet.param1 < 0 || packet.param1 > 255) {
result = MAV_RESULT_FAILED;
break;
}
uint8_t mag_mask = packet.param1;
if (mag_mask == 0) { // 0 means all
mag_mask = 0xFF;
}
if(!_accept_calibration_mask(mag_mask)) {
result = MAV_RESULT_FAILED;
}
break;
}
case MAV_CMD_DO_CANCEL_MAG_CAL: {
result = MAV_RESULT_ACCEPTED;
if(packet.param1 < 0 || packet.param1 > 255) {
result = MAV_RESULT_FAILED;
break;
}
uint8_t mag_mask = packet.param1;
if (mag_mask == 0) { // 0 means all
cancel_calibration_all();
break;
}
_cancel_calibration_mask(mag_mask);
break;
}
}
return result;
}
|
gpl-3.0
|
obnoxxx/samba
|
source3/smbd/aio.c
|
21
|
28407
|
/*
Unix SMB/Netbios implementation.
Version 3.0
async_io read handling using POSIX async io.
Copyright (C) Jeremy Allison 2005.
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 "smbd/smbd.h"
#include "smbd/globals.h"
#include "../lib/util/tevent_ntstatus.h"
#include "../lib/util/tevent_unix.h"
#include "lib/tevent_wait.h"
/****************************************************************************
The buffer we keep around whilst an aio request is in process.
*****************************************************************************/
struct aio_extra {
files_struct *fsp;
struct smb_request *smbreq;
DATA_BLOB outbuf;
struct lock_struct lock;
size_t nbyte;
off_t offset;
bool write_through;
};
/****************************************************************************
Accessor function to return write_through state.
*****************************************************************************/
bool aio_write_through_requested(struct aio_extra *aio_ex)
{
return aio_ex->write_through;
}
static int aio_extra_destructor(struct aio_extra *aio_ex)
{
outstanding_aio_calls--;
return 0;
}
/****************************************************************************
Create the extended aio struct we must keep around for the lifetime
of the aio call.
*****************************************************************************/
static struct aio_extra *create_aio_extra(TALLOC_CTX *mem_ctx,
files_struct *fsp,
size_t buflen)
{
struct aio_extra *aio_ex = talloc_zero(mem_ctx, struct aio_extra);
if (!aio_ex) {
return NULL;
}
/* The output buffer stored in the aio_ex is the start of
the smb return buffer. The buffer used in the acb
is the start of the reply data portion of that buffer. */
if (buflen) {
aio_ex->outbuf = data_blob_talloc(aio_ex, NULL, buflen);
if (!aio_ex->outbuf.data) {
TALLOC_FREE(aio_ex);
return NULL;
}
}
talloc_set_destructor(aio_ex, aio_extra_destructor);
aio_ex->fsp = fsp;
outstanding_aio_calls++;
return aio_ex;
}
struct aio_req_fsp_link {
files_struct *fsp;
struct tevent_req *req;
};
static int aio_del_req_from_fsp(struct aio_req_fsp_link *lnk)
{
unsigned i;
files_struct *fsp = lnk->fsp;
struct tevent_req *req = lnk->req;
for (i=0; i<fsp->num_aio_requests; i++) {
if (fsp->aio_requests[i] == req) {
break;
}
}
if (i == fsp->num_aio_requests) {
DEBUG(1, ("req %p not found in fsp %p\n", req, fsp));
return 0;
}
fsp->num_aio_requests -= 1;
fsp->aio_requests[i] = fsp->aio_requests[fsp->num_aio_requests];
if (fsp->num_aio_requests == 0) {
tevent_wait_done(fsp->deferred_close);
}
return 0;
}
bool aio_add_req_to_fsp(files_struct *fsp, struct tevent_req *req)
{
size_t array_len;
struct aio_req_fsp_link *lnk;
lnk = talloc(req, struct aio_req_fsp_link);
if (lnk == NULL) {
return false;
}
array_len = talloc_array_length(fsp->aio_requests);
if (array_len <= fsp->num_aio_requests) {
struct tevent_req **tmp;
tmp = talloc_realloc(
fsp, fsp->aio_requests, struct tevent_req *,
fsp->num_aio_requests+1);
if (tmp == NULL) {
TALLOC_FREE(lnk);
return false;
}
fsp->aio_requests = tmp;
}
fsp->aio_requests[fsp->num_aio_requests] = req;
fsp->num_aio_requests += 1;
lnk->fsp = fsp;
lnk->req = req;
talloc_set_destructor(lnk, aio_del_req_from_fsp);
return true;
}
static void aio_pread_smb1_done(struct tevent_req *req);
/****************************************************************************
Set up an aio request from a SMBreadX call.
*****************************************************************************/
NTSTATUS schedule_aio_read_and_X(connection_struct *conn,
struct smb_request *smbreq,
files_struct *fsp, off_t startpos,
size_t smb_maxcnt)
{
struct aio_extra *aio_ex;
size_t bufsize;
size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
struct tevent_req *req;
if (fsp->base_fsp != NULL) {
/* No AIO on streams yet */
DEBUG(10, ("AIO on streams not yet supported\n"));
return NT_STATUS_RETRY;
}
if ((!min_aio_read_size || (smb_maxcnt < min_aio_read_size))
&& !SMB_VFS_AIO_FORCE(fsp)) {
/* Too small a read for aio request. */
DEBUG(10,("schedule_aio_read_and_X: read size (%u) too small "
"for minimum aio_read of %u\n",
(unsigned int)smb_maxcnt,
(unsigned int)min_aio_read_size ));
return NT_STATUS_RETRY;
}
/* Only do this on non-chained and non-chaining reads not using the
* write cache. */
if (req_is_in_chain(smbreq) || (lp_write_cache_size(SNUM(conn)) != 0)) {
return NT_STATUS_RETRY;
}
if (outstanding_aio_calls >= aio_pending_size) {
DEBUG(10,("schedule_aio_read_and_X: Already have %d aio "
"activities outstanding.\n",
outstanding_aio_calls ));
return NT_STATUS_RETRY;
}
/* The following is safe from integer wrap as we've already checked
smb_maxcnt is 128k or less. Wct is 12 for read replies */
bufsize = smb_size + 12 * 2 + smb_maxcnt + 1 /* padding byte */;
if ((aio_ex = create_aio_extra(NULL, fsp, bufsize)) == NULL) {
DEBUG(10,("schedule_aio_read_and_X: malloc fail.\n"));
return NT_STATUS_NO_MEMORY;
}
construct_reply_common_req(smbreq, (char *)aio_ex->outbuf.data);
srv_set_message((char *)aio_ex->outbuf.data, 12, 0, True);
SCVAL(aio_ex->outbuf.data,smb_vwv0,0xFF); /* Never a chained reply. */
SCVAL(smb_buf(aio_ex->outbuf.data), 0, 0); /* padding byte */
init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
(uint64_t)startpos, (uint64_t)smb_maxcnt, READ_LOCK,
&aio_ex->lock);
/* Take the lock until the AIO completes. */
if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
TALLOC_FREE(aio_ex);
return NT_STATUS_FILE_LOCK_CONFLICT;
}
aio_ex->nbyte = smb_maxcnt;
aio_ex->offset = startpos;
req = SMB_VFS_PREAD_SEND(aio_ex, fsp->conn->sconn->ev_ctx,
fsp,
smb_buf(aio_ex->outbuf.data) + 1 /* pad */,
smb_maxcnt, startpos);
if (req == NULL) {
DEBUG(0,("schedule_aio_read_and_X: aio_read failed. "
"Error %s\n", strerror(errno) ));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
tevent_req_set_callback(req, aio_pread_smb1_done, aio_ex);
if (!aio_add_req_to_fsp(fsp, req)) {
DEBUG(1, ("Could not add req to fsp\n"));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
aio_ex->smbreq = talloc_move(aio_ex, &smbreq);
DEBUG(10,("schedule_aio_read_and_X: scheduled aio_read for file %s, "
"offset %.0f, len = %u (mid = %u)\n",
fsp_str_dbg(fsp), (double)startpos, (unsigned int)smb_maxcnt,
(unsigned int)aio_ex->smbreq->mid ));
return NT_STATUS_OK;
}
static void aio_pread_smb1_done(struct tevent_req *req)
{
struct aio_extra *aio_ex = tevent_req_callback_data(
req, struct aio_extra);
files_struct *fsp = aio_ex->fsp;
int outsize;
char *outbuf = (char *)aio_ex->outbuf.data;
char *data = smb_buf(outbuf) + 1 /* padding byte */;
ssize_t nread;
int err;
nread = SMB_VFS_PREAD_RECV(req, &err);
TALLOC_FREE(req);
DEBUG(10, ("pread_recv returned %d, err = %s\n", (int)nread,
(nread == -1) ? strerror(err) : "no error"));
if (fsp == NULL) {
DEBUG( 3, ("aio_pread_smb1_done: file closed whilst "
"aio outstanding (mid[%llu]).\n",
(unsigned long long)aio_ex->smbreq->mid));
TALLOC_FREE(aio_ex);
return;
}
/* Unlock now we're done. */
SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
if (nread < 0) {
DEBUG( 3, ("handle_aio_read_complete: file %s nread == %d. "
"Error = %s\n", fsp_str_dbg(fsp), (int)nread,
strerror(err)));
ERROR_NT(map_nt_error_from_unix(err));
outsize = srv_set_message(outbuf,0,0,true);
} else {
outsize = srv_set_message(outbuf, 12,
nread + 1 /* padding byte */, false);
SSVAL(outbuf,smb_vwv2, 0xFFFF); /* Remaining - must be * -1. */
SSVAL(outbuf,smb_vwv5, nread);
SSVAL(outbuf,smb_vwv6, smb_offset(data,outbuf));
SSVAL(outbuf,smb_vwv7, ((nread >> 16) & 1));
SSVAL(smb_buf(outbuf), -2, nread);
aio_ex->fsp->fh->pos = aio_ex->offset + nread;
aio_ex->fsp->fh->position_information = aio_ex->fsp->fh->pos;
DEBUG( 3, ("handle_aio_read_complete file %s max=%d "
"nread=%d\n", fsp_str_dbg(fsp),
(int)aio_ex->nbyte, (int)nread ) );
}
smb_setlen(outbuf, outsize - 4);
show_msg(outbuf);
if (!srv_send_smb(aio_ex->smbreq->xconn, outbuf,
true, aio_ex->smbreq->seqnum+1,
IS_CONN_ENCRYPTED(fsp->conn), NULL)) {
exit_server_cleanly("handle_aio_read_complete: srv_send_smb "
"failed.");
}
DEBUG(10, ("handle_aio_read_complete: scheduled aio_read completed "
"for file %s, offset %.0f, len = %u\n",
fsp_str_dbg(fsp), (double)aio_ex->offset,
(unsigned int)nread));
TALLOC_FREE(aio_ex);
}
struct pwrite_fsync_state {
struct tevent_context *ev;
files_struct *fsp;
bool write_through;
ssize_t nwritten;
};
static void pwrite_fsync_write_done(struct tevent_req *subreq);
static void pwrite_fsync_sync_done(struct tevent_req *subreq);
static struct tevent_req *pwrite_fsync_send(TALLOC_CTX *mem_ctx,
struct tevent_context *ev,
struct files_struct *fsp,
const void *data,
size_t n, off_t offset,
bool write_through)
{
struct tevent_req *req, *subreq;
struct pwrite_fsync_state *state;
req = tevent_req_create(mem_ctx, &state, struct pwrite_fsync_state);
if (req == NULL) {
return NULL;
}
state->ev = ev;
state->fsp = fsp;
state->write_through = write_through;
subreq = SMB_VFS_PWRITE_SEND(state, ev, fsp, data, n, offset);
if (tevent_req_nomem(subreq, req)) {
return tevent_req_post(req, ev);
}
tevent_req_set_callback(subreq, pwrite_fsync_write_done, req);
return req;
}
static void pwrite_fsync_write_done(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
struct pwrite_fsync_state *state = tevent_req_data(
req, struct pwrite_fsync_state);
connection_struct *conn = state->fsp->conn;
int err;
bool do_sync;
state->nwritten = SMB_VFS_PWRITE_RECV(subreq, &err);
TALLOC_FREE(subreq);
if (state->nwritten == -1) {
tevent_req_error(req, err);
return;
}
do_sync = (lp_strict_sync(SNUM(conn)) &&
(lp_sync_always(SNUM(conn)) || state->write_through));
if (!do_sync) {
tevent_req_done(req);
return;
}
subreq = SMB_VFS_FSYNC_SEND(state, state->ev, state->fsp);
if (tevent_req_nomem(subreq, req)) {
return;
}
tevent_req_set_callback(subreq, pwrite_fsync_sync_done, req);
}
static void pwrite_fsync_sync_done(struct tevent_req *subreq)
{
struct tevent_req *req = tevent_req_callback_data(
subreq, struct tevent_req);
int ret, err;
ret = SMB_VFS_FSYNC_RECV(subreq, &err);
TALLOC_FREE(subreq);
if (ret == -1) {
tevent_req_error(req, err);
return;
}
tevent_req_done(req);
}
static ssize_t pwrite_fsync_recv(struct tevent_req *req, int *perr)
{
struct pwrite_fsync_state *state = tevent_req_data(
req, struct pwrite_fsync_state);
if (tevent_req_is_unix_error(req, perr)) {
return -1;
}
return state->nwritten;
}
static void aio_pwrite_smb1_done(struct tevent_req *req);
/****************************************************************************
Set up an aio request from a SMBwriteX call.
*****************************************************************************/
NTSTATUS schedule_aio_write_and_X(connection_struct *conn,
struct smb_request *smbreq,
files_struct *fsp, const char *data,
off_t startpos,
size_t numtowrite)
{
struct aio_extra *aio_ex;
size_t bufsize;
size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
struct tevent_req *req;
if (fsp->base_fsp != NULL) {
/* No AIO on streams yet */
DEBUG(10, ("AIO on streams not yet supported\n"));
return NT_STATUS_RETRY;
}
if ((!min_aio_write_size || (numtowrite < min_aio_write_size))
&& !SMB_VFS_AIO_FORCE(fsp)) {
/* Too small a write for aio request. */
DEBUG(10,("schedule_aio_write_and_X: write size (%u) too "
"small for minimum aio_write of %u\n",
(unsigned int)numtowrite,
(unsigned int)min_aio_write_size ));
return NT_STATUS_RETRY;
}
/* Only do this on non-chained and non-chaining writes not using the
* write cache. */
if (req_is_in_chain(smbreq) || (lp_write_cache_size(SNUM(conn)) != 0)) {
return NT_STATUS_RETRY;
}
if (outstanding_aio_calls >= aio_pending_size) {
DEBUG(3,("schedule_aio_write_and_X: Already have %d aio "
"activities outstanding.\n",
outstanding_aio_calls ));
DEBUG(10,("schedule_aio_write_and_X: failed to schedule "
"aio_write for file %s, offset %.0f, len = %u "
"(mid = %u)\n",
fsp_str_dbg(fsp), (double)startpos,
(unsigned int)numtowrite,
(unsigned int)smbreq->mid ));
return NT_STATUS_RETRY;
}
bufsize = smb_size + 6*2;
if (!(aio_ex = create_aio_extra(NULL, fsp, bufsize))) {
DEBUG(0,("schedule_aio_write_and_X: malloc fail.\n"));
return NT_STATUS_NO_MEMORY;
}
aio_ex->write_through = BITSETW(smbreq->vwv+7,0);
construct_reply_common_req(smbreq, (char *)aio_ex->outbuf.data);
srv_set_message((char *)aio_ex->outbuf.data, 6, 0, True);
SCVAL(aio_ex->outbuf.data,smb_vwv0,0xFF); /* Never a chained reply. */
init_strict_lock_struct(fsp, (uint64_t)smbreq->smbpid,
(uint64_t)startpos, (uint64_t)numtowrite, WRITE_LOCK,
&aio_ex->lock);
/* Take the lock until the AIO completes. */
if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
TALLOC_FREE(aio_ex);
return NT_STATUS_FILE_LOCK_CONFLICT;
}
aio_ex->nbyte = numtowrite;
aio_ex->offset = startpos;
req = pwrite_fsync_send(aio_ex, fsp->conn->sconn->ev_ctx, fsp,
data, numtowrite, startpos,
aio_ex->write_through);
if (req == NULL) {
DEBUG(3,("schedule_aio_wrote_and_X: aio_write failed. "
"Error %s\n", strerror(errno) ));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
tevent_req_set_callback(req, aio_pwrite_smb1_done, aio_ex);
if (!aio_add_req_to_fsp(fsp, req)) {
DEBUG(1, ("Could not add req to fsp\n"));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
aio_ex->smbreq = talloc_move(aio_ex, &smbreq);
/* This should actually be improved to span the write. */
contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);
if (!aio_ex->write_through && !lp_sync_always(SNUM(fsp->conn))
&& fsp->aio_write_behind) {
/* Lie to the client and immediately claim we finished the
* write. */
SSVAL(aio_ex->outbuf.data,smb_vwv2,numtowrite);
SSVAL(aio_ex->outbuf.data,smb_vwv4,(numtowrite>>16)&1);
show_msg((char *)aio_ex->outbuf.data);
if (!srv_send_smb(aio_ex->smbreq->xconn,
(char *)aio_ex->outbuf.data,
true, aio_ex->smbreq->seqnum+1,
IS_CONN_ENCRYPTED(fsp->conn),
&aio_ex->smbreq->pcd)) {
exit_server_cleanly("schedule_aio_write_and_X: "
"srv_send_smb failed.");
}
DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write "
"behind for file %s\n", fsp_str_dbg(fsp)));
}
DEBUG(10,("schedule_aio_write_and_X: scheduled aio_write for file "
"%s, offset %.0f, len = %u (mid = %u) "
"outstanding_aio_calls = %d\n",
fsp_str_dbg(fsp), (double)startpos, (unsigned int)numtowrite,
(unsigned int)aio_ex->smbreq->mid, outstanding_aio_calls ));
return NT_STATUS_OK;
}
static void aio_pwrite_smb1_done(struct tevent_req *req)
{
struct aio_extra *aio_ex = tevent_req_callback_data(
req, struct aio_extra);
files_struct *fsp = aio_ex->fsp;
char *outbuf = (char *)aio_ex->outbuf.data;
ssize_t numtowrite = aio_ex->nbyte;
ssize_t nwritten;
int err;
nwritten = pwrite_fsync_recv(req, &err);
TALLOC_FREE(req);
DEBUG(10, ("pwrite_recv returned %d, err = %s\n", (int)nwritten,
(nwritten == -1) ? strerror(err) : "no error"));
if (fsp == NULL) {
DEBUG( 3, ("aio_pwrite_smb1_done: file closed whilst "
"aio outstanding (mid[%llu]).\n",
(unsigned long long)aio_ex->smbreq->mid));
TALLOC_FREE(aio_ex);
return;
}
/* Unlock now we're done. */
SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
mark_file_modified(fsp);
if (fsp->aio_write_behind) {
if (nwritten != numtowrite) {
if (nwritten == -1) {
DEBUG(5,("handle_aio_write_complete: "
"aio_write_behind failed ! File %s "
"is corrupt ! Error %s\n",
fsp_str_dbg(fsp), strerror(err)));
} else {
DEBUG(0,("handle_aio_write_complete: "
"aio_write_behind failed ! File %s "
"is corrupt ! Wanted %u bytes but "
"only wrote %d\n", fsp_str_dbg(fsp),
(unsigned int)numtowrite,
(int)nwritten ));
}
} else {
DEBUG(10,("handle_aio_write_complete: "
"aio_write_behind completed for file %s\n",
fsp_str_dbg(fsp)));
}
/* TODO: should no return success in case of an error !!! */
TALLOC_FREE(aio_ex);
return;
}
/* We don't need outsize or set_message here as we've already set the
fixed size length when we set up the aio call. */
if (nwritten == -1) {
DEBUG(3, ("handle_aio_write: file %s wanted %u bytes. "
"nwritten == %d. Error = %s\n",
fsp_str_dbg(fsp), (unsigned int)numtowrite,
(int)nwritten, strerror(err)));
ERROR_NT(map_nt_error_from_unix(err));
srv_set_message(outbuf,0,0,true);
} else {
SSVAL(outbuf,smb_vwv2,nwritten);
SSVAL(outbuf,smb_vwv4,(nwritten>>16)&1);
if (nwritten < (ssize_t)numtowrite) {
SCVAL(outbuf,smb_rcls,ERRHRD);
SSVAL(outbuf,smb_err,ERRdiskfull);
}
DEBUG(3,("handle_aio_write: %s, num=%d wrote=%d\n",
fsp_fnum_dbg(fsp), (int)numtowrite, (int)nwritten));
aio_ex->fsp->fh->pos = aio_ex->offset + nwritten;
}
show_msg(outbuf);
if (!srv_send_smb(aio_ex->smbreq->xconn, outbuf,
true, aio_ex->smbreq->seqnum+1,
IS_CONN_ENCRYPTED(fsp->conn),
NULL)) {
exit_server_cleanly("handle_aio_write_complete: "
"srv_send_smb failed.");
}
DEBUG(10, ("handle_aio_write_complete: scheduled aio_write completed "
"for file %s, offset %.0f, requested %u, written = %u\n",
fsp_str_dbg(fsp), (double)aio_ex->offset,
(unsigned int)numtowrite, (unsigned int)nwritten));
TALLOC_FREE(aio_ex);
}
bool cancel_smb2_aio(struct smb_request *smbreq)
{
struct smbd_smb2_request *smb2req = smbreq->smb2req;
struct aio_extra *aio_ex = NULL;
if (smb2req) {
aio_ex = talloc_get_type(smbreq->async_priv,
struct aio_extra);
}
if (aio_ex == NULL) {
return false;
}
if (aio_ex->fsp == NULL) {
return false;
}
/*
* We let the aio request run. Setting fsp to NULL has the
* effect that the _done routines don't send anything out.
*/
aio_ex->fsp = NULL;
return true;
}
static void aio_pread_smb2_done(struct tevent_req *req);
/****************************************************************************
Set up an aio request from a SMB2 read call.
*****************************************************************************/
NTSTATUS schedule_smb2_aio_read(connection_struct *conn,
struct smb_request *smbreq,
files_struct *fsp,
TALLOC_CTX *ctx,
DATA_BLOB *preadbuf,
off_t startpos,
size_t smb_maxcnt)
{
struct aio_extra *aio_ex;
size_t min_aio_read_size = lp_aio_read_size(SNUM(conn));
struct tevent_req *req;
if (fsp->base_fsp != NULL) {
/* No AIO on streams yet */
DEBUG(10, ("AIO on streams not yet supported\n"));
return NT_STATUS_RETRY;
}
if (fsp->op == NULL) {
/* No AIO on internal opens. */
return NT_STATUS_RETRY;
}
if ((!min_aio_read_size || (smb_maxcnt < min_aio_read_size))
&& !SMB_VFS_AIO_FORCE(fsp)) {
/* Too small a read for aio request. */
DEBUG(10,("smb2: read size (%u) too small "
"for minimum aio_read of %u\n",
(unsigned int)smb_maxcnt,
(unsigned int)min_aio_read_size ));
return NT_STATUS_RETRY;
}
/* Only do this on reads not using the write cache. */
if (lp_write_cache_size(SNUM(conn)) != 0) {
return NT_STATUS_RETRY;
}
if (outstanding_aio_calls >= aio_pending_size) {
DEBUG(10,("smb2: Already have %d aio "
"activities outstanding.\n",
outstanding_aio_calls ));
return NT_STATUS_RETRY;
}
/* Create the out buffer. */
*preadbuf = data_blob_talloc(ctx, NULL, smb_maxcnt);
if (preadbuf->data == NULL) {
return NT_STATUS_NO_MEMORY;
}
if (!(aio_ex = create_aio_extra(smbreq->smb2req, fsp, 0))) {
return NT_STATUS_NO_MEMORY;
}
init_strict_lock_struct(fsp, fsp->op->global->open_persistent_id,
(uint64_t)startpos, (uint64_t)smb_maxcnt, READ_LOCK,
&aio_ex->lock);
/* Take the lock until the AIO completes. */
if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
TALLOC_FREE(aio_ex);
return NT_STATUS_FILE_LOCK_CONFLICT;
}
aio_ex->nbyte = smb_maxcnt;
aio_ex->offset = startpos;
req = SMB_VFS_PREAD_SEND(aio_ex, fsp->conn->sconn->ev_ctx, fsp,
preadbuf->data, smb_maxcnt, startpos);
if (req == NULL) {
DEBUG(0, ("smb2: SMB_VFS_PREAD_SEND failed. "
"Error %s\n", strerror(errno)));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
tevent_req_set_callback(req, aio_pread_smb2_done, aio_ex);
if (!aio_add_req_to_fsp(fsp, req)) {
DEBUG(1, ("Could not add req to fsp\n"));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
/* We don't need talloc_move here as both aio_ex and
* smbreq are children of smbreq->smb2req. */
aio_ex->smbreq = smbreq;
smbreq->async_priv = aio_ex;
DEBUG(10,("smb2: scheduled aio_read for file %s, "
"offset %.0f, len = %u (mid = %u)\n",
fsp_str_dbg(fsp), (double)startpos, (unsigned int)smb_maxcnt,
(unsigned int)aio_ex->smbreq->mid ));
return NT_STATUS_OK;
}
static void aio_pread_smb2_done(struct tevent_req *req)
{
struct aio_extra *aio_ex = tevent_req_callback_data(
req, struct aio_extra);
struct tevent_req *subreq = aio_ex->smbreq->smb2req->subreq;
files_struct *fsp = aio_ex->fsp;
NTSTATUS status;
ssize_t nread;
int err = 0;
nread = SMB_VFS_PREAD_RECV(req, &err);
TALLOC_FREE(req);
DEBUG(10, ("pread_recv returned %d, err = %s\n", (int)nread,
(nread == -1) ? strerror(err) : "no error"));
if (fsp == NULL) {
DEBUG(3, ("%s: request cancelled (mid[%ju])\n",
__func__, (uintmax_t)aio_ex->smbreq->mid));
TALLOC_FREE(aio_ex);
tevent_req_nterror(subreq, NT_STATUS_INTERNAL_ERROR);
return;
}
/* Unlock now we're done. */
SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
/* Common error or success code processing for async or sync
read returns. */
status = smb2_read_complete(subreq, nread, err);
if (nread > 0) {
fsp->fh->pos = aio_ex->offset + nread;
fsp->fh->position_information = fsp->fh->pos;
}
DEBUG(10, ("smb2: scheduled aio_read completed "
"for file %s, offset %.0f, len = %u "
"(errcode = %d, NTSTATUS = %s)\n",
fsp_str_dbg(aio_ex->fsp),
(double)aio_ex->offset,
(unsigned int)nread,
err, nt_errstr(status)));
if (!NT_STATUS_IS_OK(status)) {
tevent_req_nterror(subreq, status);
return;
}
tevent_req_done(subreq);
}
static void aio_pwrite_smb2_done(struct tevent_req *req);
/****************************************************************************
Set up an aio request from a SMB2write call.
*****************************************************************************/
NTSTATUS schedule_aio_smb2_write(connection_struct *conn,
struct smb_request *smbreq,
files_struct *fsp,
uint64_t in_offset,
DATA_BLOB in_data,
bool write_through)
{
struct aio_extra *aio_ex = NULL;
size_t min_aio_write_size = lp_aio_write_size(SNUM(conn));
struct tevent_req *req;
if (fsp->base_fsp != NULL) {
/* No AIO on streams yet */
DEBUG(10, ("AIO on streams not yet supported\n"));
return NT_STATUS_RETRY;
}
if (fsp->op == NULL) {
/* No AIO on internal opens. */
return NT_STATUS_RETRY;
}
if ((!min_aio_write_size || (in_data.length < min_aio_write_size))
&& !SMB_VFS_AIO_FORCE(fsp)) {
/* Too small a write for aio request. */
DEBUG(10,("smb2: write size (%u) too "
"small for minimum aio_write of %u\n",
(unsigned int)in_data.length,
(unsigned int)min_aio_write_size ));
return NT_STATUS_RETRY;
}
/* Only do this on writes not using the write cache. */
if (lp_write_cache_size(SNUM(conn)) != 0) {
return NT_STATUS_RETRY;
}
if (outstanding_aio_calls >= aio_pending_size) {
DEBUG(3,("smb2: Already have %d aio "
"activities outstanding.\n",
outstanding_aio_calls ));
return NT_STATUS_RETRY;
}
if (smbreq->unread_bytes) {
/* Can't do async with recvfile. */
return NT_STATUS_RETRY;
}
if (!(aio_ex = create_aio_extra(smbreq->smb2req, fsp, 0))) {
return NT_STATUS_NO_MEMORY;
}
aio_ex->write_through = write_through;
init_strict_lock_struct(fsp, fsp->op->global->open_persistent_id,
in_offset, (uint64_t)in_data.length, WRITE_LOCK,
&aio_ex->lock);
/* Take the lock until the AIO completes. */
if (!SMB_VFS_STRICT_LOCK(conn, fsp, &aio_ex->lock)) {
TALLOC_FREE(aio_ex);
return NT_STATUS_FILE_LOCK_CONFLICT;
}
aio_ex->nbyte = in_data.length;
aio_ex->offset = in_offset;
req = pwrite_fsync_send(aio_ex, fsp->conn->sconn->ev_ctx, fsp,
in_data.data, in_data.length, in_offset,
write_through);
if (req == NULL) {
DEBUG(3, ("smb2: SMB_VFS_PWRITE_SEND failed. "
"Error %s\n", strerror(errno)));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
tevent_req_set_callback(req, aio_pwrite_smb2_done, aio_ex);
if (!aio_add_req_to_fsp(fsp, req)) {
DEBUG(1, ("Could not add req to fsp\n"));
SMB_VFS_STRICT_UNLOCK(conn, fsp, &aio_ex->lock);
TALLOC_FREE(aio_ex);
return NT_STATUS_RETRY;
}
/* We don't need talloc_move here as both aio_ex and
* smbreq are children of smbreq->smb2req. */
aio_ex->smbreq = smbreq;
smbreq->async_priv = aio_ex;
/* This should actually be improved to span the write. */
contend_level2_oplocks_begin(fsp, LEVEL2_CONTEND_WRITE);
contend_level2_oplocks_end(fsp, LEVEL2_CONTEND_WRITE);
/*
* We don't want to do write behind due to ownership
* issues of the request structs. Maybe add it if I
* figure those out. JRA.
*/
DEBUG(10,("smb2: scheduled aio_write for file "
"%s, offset %.0f, len = %u (mid = %u) "
"outstanding_aio_calls = %d\n",
fsp_str_dbg(fsp),
(double)in_offset,
(unsigned int)in_data.length,
(unsigned int)aio_ex->smbreq->mid,
outstanding_aio_calls ));
return NT_STATUS_OK;
}
static void aio_pwrite_smb2_done(struct tevent_req *req)
{
struct aio_extra *aio_ex = tevent_req_callback_data(
req, struct aio_extra);
ssize_t numtowrite = aio_ex->nbyte;
struct tevent_req *subreq = aio_ex->smbreq->smb2req->subreq;
files_struct *fsp = aio_ex->fsp;
NTSTATUS status;
ssize_t nwritten;
int err = 0;
nwritten = pwrite_fsync_recv(req, &err);
TALLOC_FREE(req);
DEBUG(10, ("pwrite_recv returned %d, err = %s\n", (int)nwritten,
(nwritten == -1) ? strerror(err) : "no error"));
if (fsp == NULL) {
DEBUG(3, ("%s: request cancelled (mid[%ju])\n",
__func__, (uintmax_t)aio_ex->smbreq->mid));
TALLOC_FREE(aio_ex);
tevent_req_nterror(subreq, NT_STATUS_INTERNAL_ERROR);
return;
}
/* Unlock now we're done. */
SMB_VFS_STRICT_UNLOCK(fsp->conn, fsp, &aio_ex->lock);
mark_file_modified(fsp);
status = smb2_write_complete_nosync(subreq, nwritten, err);
DEBUG(10, ("smb2: scheduled aio_write completed "
"for file %s, offset %.0f, requested %u, "
"written = %u (errcode = %d, NTSTATUS = %s)\n",
fsp_str_dbg(fsp),
(double)aio_ex->offset,
(unsigned int)numtowrite,
(unsigned int)nwritten,
err, nt_errstr(status)));
if (!NT_STATUS_IS_OK(status)) {
tevent_req_nterror(subreq, status);
return;
}
tevent_req_done(subreq);
}
|
gpl-3.0
|
victorzhao/miniblink49
|
third_party/WebKit/Source/web/DragClientImpl.cpp
|
21
|
3541
|
/*
* Copyright (C) 2009 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* 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 "config.h"
#include "web/DragClientImpl.h"
#include "core/clipboard/DataObject.h"
#include "core/clipboard/DataTransfer.h"
#include "core/frame/LocalFrame.h"
#include "platform/DragImage.h"
#include "platform/geometry/IntSize.h"
#include "public/platform/WebCommon.h"
#include "public/platform/WebDragData.h"
#include "public/platform/WebImage.h"
#include "public/platform/WebPoint.h"
#include "public/web/WebDragOperation.h"
#include "public/web/WebViewClient.h"
#include "web/WebViewImpl.h"
#include "wtf/Assertions.h"
#include "wtf/RefPtr.h"
namespace blink {
DragDestinationAction DragClientImpl::actionMaskForDrag(DragData*)
{
if (m_webView->client() && m_webView->client()->acceptsLoadDrops())
return DragDestinationActionAny;
return static_cast<DragDestinationAction>(
DragDestinationActionDHTML | DragDestinationActionEdit);
}
void DragClientImpl::startDrag(DragImage* dragImage, const IntPoint& dragImageOrigin, const IntPoint& eventPos, DataTransfer* dataTransfer, LocalFrame* frame, bool isLinkDrag)
{
// Add a ref to the frame just in case a load occurs mid-drag.
RefPtrWillBeRawPtr<LocalFrame> frameProtector(frame);
WebDragData dragData = dataTransfer->dataObject()->toWebDragData();
WebDragOperationsMask dragOperationMask = static_cast<WebDragOperationsMask>(dataTransfer->sourceOperation());
WebImage image;
IntSize offsetSize(eventPos - dragImageOrigin);
WebPoint offsetPoint(offsetSize.width(), offsetSize.height());
if (dragImage) {
float resolutionScale = dragImage->resolutionScale();
if (m_webView->deviceScaleFactor() != resolutionScale) {
ASSERT(resolutionScale > 0);
float scale = m_webView->deviceScaleFactor() / resolutionScale;
dragImage->scale(scale, scale);
}
image = dragImage->bitmap();
}
m_webView->startDragging(frame, dragData, dragOperationMask, image, offsetPoint);
}
} // namespace blink
|
gpl-3.0
|
valascus/android_p8000_kernel_nougat
|
drivers/misc/mediatek/gpu/ged/src/ged_monitor_3D_fence.c
|
21
|
4143
|
#include <linux/version.h>
#include <linux/workqueue.h>
#include <linux/sched.h>
#include <asm/atomic.h>
#include <linux/module.h>
#if (LINUX_VERSION_CODE < KERNEL_VERSION(3,10,0))
#include <linux/sync.h>
#else
#include <../drivers/staging/android/sync.h>
#endif
#include <linux/mtk_gpu_utility.h>
#include <trace/events/gpu.h>
#include "ged_monitor_3D_fence.h"
#include "ged_log.h"
#include "ged_base.h"
static atomic_t g_i32Count = ATOMIC_INIT(0);
static unsigned int ged_monitor_3D_fence_debug = 0;
static unsigned int ged_monitor_3D_fence_disable = 0;
static unsigned int ged_monitor_3D_fence_systrace = 0;
#ifdef GED_DEBUG_MONITOR_3D_FENCE
extern GED_LOG_BUF_HANDLE ghLogBuf_GED;
#endif
typedef struct GED_MONITOR_3D_FENCE_TAG
{
struct sync_fence_waiter sSyncWaiter;
struct work_struct sWork;
struct sync_fence* psSyncFence;
} GED_MONITOR_3D_FENCE;
static void ged_sync_cb(struct sync_fence *fence, struct sync_fence_waiter *waiter)
{
GED_MONITOR_3D_FENCE *psMonitor;
psMonitor = GED_CONTAINER_OF(waiter, GED_MONITOR_3D_FENCE, sSyncWaiter);
schedule_work(&psMonitor->sWork);
}
static void ged_monitor_3D_fence_work_cb(struct work_struct *psWork)
{
GED_MONITOR_3D_FENCE *psMonitor;
if (atomic_sub_return(1, &g_i32Count) < 1)
{
if (0 == ged_monitor_3D_fence_disable)
{
//unsigned int uiFreqLevelID;
//if (mtk_get_bottom_gpu_freq(&uiFreqLevelID))
{
//if (uiFreqLevelID > 0)
{
mtk_set_bottom_gpu_freq(0);
#ifdef CONFIG_GPU_TRACEPOINTS
if (ged_monitor_3D_fence_systrace)
{
unsigned long long t = cpu_clock(smp_processor_id());
trace_gpu_sched_switch("Smart Boost", t, 0, 0, 1);
}
#endif
}
}
}
}
if (ged_monitor_3D_fence_debug > 0)
{
GED_LOGI("[-]3D fences count = %d\n", atomic_read(&g_i32Count));
}
psMonitor = GED_CONTAINER_OF(psWork, GED_MONITOR_3D_FENCE, sWork);
sync_fence_put(psMonitor->psSyncFence);
ged_free(psMonitor, sizeof(GED_MONITOR_3D_FENCE));
}
GED_ERROR ged_monitor_3D_fence_add(int fence_fd)
{
int err;
GED_MONITOR_3D_FENCE* psMonitor;
psMonitor = (GED_MONITOR_3D_FENCE*)ged_alloc(sizeof(GED_MONITOR_3D_FENCE));
if (!psMonitor)
{
return GED_ERROR_OOM;
}
sync_fence_waiter_init(&psMonitor->sSyncWaiter, ged_sync_cb);
INIT_WORK(&psMonitor->sWork, ged_monitor_3D_fence_work_cb);
psMonitor->psSyncFence = sync_fence_fdget(fence_fd);
if (NULL == psMonitor->psSyncFence)
{
ged_free(psMonitor, sizeof(GED_MONITOR_3D_FENCE));
return GED_ERROR_INVALID_PARAMS;
}
err = sync_fence_wait_async(psMonitor->psSyncFence, &psMonitor->sSyncWaiter);
if ((1 == err) || (0 > err))
{
sync_fence_put(psMonitor->psSyncFence);
ged_free(psMonitor, sizeof(GED_MONITOR_3D_FENCE));
}
else if (0 == err)
{
int iCount = atomic_add_return(1, &g_i32Count);
if (iCount > 1)
{
if (0 == ged_monitor_3D_fence_disable)
{
//unsigned int uiFreqLevelID;
//if (mtk_get_bottom_gpu_freq(&uiFreqLevelID))
{
//if (uiFreqLevelID != 4)
{
#ifdef CONFIG_GPU_TRACEPOINTS
if (ged_monitor_3D_fence_systrace)
{
unsigned long long t = cpu_clock(smp_processor_id());
trace_gpu_sched_switch("Smart Boost", t, 1, 0, 1);
}
#endif
mtk_set_bottom_gpu_freq(4);
}
}
}
}
}
if (ged_monitor_3D_fence_debug > 0)
{
GED_LOGI("[+]3D fences count = %d\n", atomic_read(&g_i32Count));
}
return GED_OK;
}
module_param(ged_monitor_3D_fence_debug, uint, 0644);
module_param(ged_monitor_3D_fence_disable, uint, 0644);
module_param(ged_monitor_3D_fence_systrace, uint, 0644);
|
gpl-3.0
|
flymperopoulos/SoftwareSystems
|
lecture23/semaphore.c
|
23
|
2098
|
/* Example code for Software Systems at Olin College.
Copyright 2012 Allen Downey
License: Creative Commons Attribution-ShareAlike 3.0
*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include "semaphore.h"
// UTILITY CODE
void perror_exit (char *s)
{
perror (s); exit (-1);
}
void *check_malloc(int size)
{
void *p = malloc (size);
if (p == NULL) perror_exit ("malloc failed");
return p;
}
// MUTEX WRAPPER
Mutex *make_mutex ()
{
Mutex *mutex = check_malloc (sizeof(Mutex));
int n = pthread_mutex_init (mutex, NULL);
if (n != 0) perror_exit ("make_lock failed");
return mutex;
}
void mutex_lock (Mutex *mutex)
{
int n = pthread_mutex_lock (mutex);
if (n != 0) perror_exit ("lock failed");
}
void mutex_unlock (Mutex *mutex)
{
int n = pthread_mutex_unlock (mutex);
if (n != 0) perror_exit ("unlock failed");
}
// COND WRAPPER
Cond *make_cond ()
{
Cond *cond = check_malloc (sizeof(Cond));
int n = pthread_cond_init (cond, NULL);
if (n != 0) perror_exit ("make_cond failed");
return cond;
}
void cond_wait (Cond *cond, Mutex *mutex)
{
int n = pthread_cond_wait (cond, mutex);
if (n != 0) perror_exit ("cond_wait failed");
}
void cond_signal (Cond *cond)
{
int n = pthread_cond_signal (cond);
if (n != 0) perror_exit ("cond_signal failed");
}
// SEMAPHORE
Semaphore *make_semaphore (int value)
{
Semaphore *semaphore = check_malloc (sizeof(Semaphore));
semaphore->value = value;
semaphore->wakeups = 0;
semaphore->mutex = make_mutex ();
semaphore->cond = make_cond ();
return semaphore;
}
void sem_wait (Semaphore *semaphore)
{
mutex_lock (semaphore->mutex);
semaphore->value--;
if (semaphore->value < 0) {
do {
cond_wait (semaphore->cond, semaphore->mutex);
} while (semaphore->wakeups < 1);
semaphore->wakeups--;
}
mutex_unlock (semaphore->mutex);
}
void sem_signal (Semaphore *semaphore)
{
mutex_lock (semaphore->mutex);
semaphore->value++;
if (semaphore->value <= 0) {
semaphore->wakeups++;
cond_signal (semaphore->cond);
}
mutex_unlock (semaphore->mutex);
}
|
gpl-3.0
|
syntheticpp/metashell
|
3rd/templight/llvm/lib/Target/AMDGPU/R600ControlFlowFinalizer.cpp
|
24
|
22513
|
//===-- R600ControlFlowFinalizer.cpp - Finalize Control Flow Inst----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
/// \file
/// This pass compute turns all control flow pseudo instructions into native one
/// computing their address on the fly ; it also sets STACK_SIZE info.
//===----------------------------------------------------------------------===//
#include "llvm/Support/Debug.h"
#include "AMDGPU.h"
#include "AMDGPUSubtarget.h"
#include "R600Defines.h"
#include "R600InstrInfo.h"
#include "R600MachineFunctionInfo.h"
#include "R600RegisterInfo.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/Support/raw_ostream.h"
using namespace llvm;
#define DEBUG_TYPE "r600cf"
namespace {
struct CFStack {
enum StackItem {
ENTRY = 0,
SUB_ENTRY = 1,
FIRST_NON_WQM_PUSH = 2,
FIRST_NON_WQM_PUSH_W_FULL_ENTRY = 3
};
const AMDGPUSubtarget *ST;
std::vector<StackItem> BranchStack;
std::vector<StackItem> LoopStack;
unsigned MaxStackSize;
unsigned CurrentEntries;
unsigned CurrentSubEntries;
CFStack(const AMDGPUSubtarget *st, unsigned ShaderType) : ST(st),
// We need to reserve a stack entry for CALL_FS in vertex shaders.
MaxStackSize(ShaderType == ShaderType::VERTEX ? 1 : 0),
CurrentEntries(0), CurrentSubEntries(0) { }
unsigned getLoopDepth();
bool branchStackContains(CFStack::StackItem);
bool requiresWorkAroundForInst(unsigned Opcode);
unsigned getSubEntrySize(CFStack::StackItem Item);
void updateMaxStackSize();
void pushBranch(unsigned Opcode, bool isWQM = false);
void pushLoop();
void popBranch();
void popLoop();
};
unsigned CFStack::getLoopDepth() {
return LoopStack.size();
}
bool CFStack::branchStackContains(CFStack::StackItem Item) {
for (std::vector<CFStack::StackItem>::const_iterator I = BranchStack.begin(),
E = BranchStack.end(); I != E; ++I) {
if (*I == Item)
return true;
}
return false;
}
bool CFStack::requiresWorkAroundForInst(unsigned Opcode) {
if (Opcode == AMDGPU::CF_ALU_PUSH_BEFORE && ST->hasCaymanISA() &&
getLoopDepth() > 1)
return true;
if (!ST->hasCFAluBug())
return false;
switch(Opcode) {
default: return false;
case AMDGPU::CF_ALU_PUSH_BEFORE:
case AMDGPU::CF_ALU_ELSE_AFTER:
case AMDGPU::CF_ALU_BREAK:
case AMDGPU::CF_ALU_CONTINUE:
if (CurrentSubEntries == 0)
return false;
if (ST->getWavefrontSize() == 64) {
// We are being conservative here. We only require this work-around if
// CurrentSubEntries > 3 &&
// (CurrentSubEntries % 4 == 3 || CurrentSubEntries % 4 == 0)
//
// We have to be conservative, because we don't know for certain that
// our stack allocation algorithm for Evergreen/NI is correct. Applying this
// work-around when CurrentSubEntries > 3 allows us to over-allocate stack
// resources without any problems.
return CurrentSubEntries > 3;
} else {
assert(ST->getWavefrontSize() == 32);
// We are being conservative here. We only require the work-around if
// CurrentSubEntries > 7 &&
// (CurrentSubEntries % 8 == 7 || CurrentSubEntries % 8 == 0)
// See the comment on the wavefront size == 64 case for why we are
// being conservative.
return CurrentSubEntries > 7;
}
}
}
unsigned CFStack::getSubEntrySize(CFStack::StackItem Item) {
switch(Item) {
default:
return 0;
case CFStack::FIRST_NON_WQM_PUSH:
assert(!ST->hasCaymanISA());
if (ST->getGeneration() <= AMDGPUSubtarget::R700) {
// +1 For the push operation.
// +2 Extra space required.
return 3;
} else {
// Some documentation says that this is not necessary on Evergreen,
// but experimentation has show that we need to allocate 1 extra
// sub-entry for the first non-WQM push.
// +1 For the push operation.
// +1 Extra space required.
return 2;
}
case CFStack::FIRST_NON_WQM_PUSH_W_FULL_ENTRY:
assert(ST->getGeneration() >= AMDGPUSubtarget::EVERGREEN);
// +1 For the push operation.
// +1 Extra space required.
return 2;
case CFStack::SUB_ENTRY:
return 1;
}
}
void CFStack::updateMaxStackSize() {
unsigned CurrentStackSize = CurrentEntries +
(RoundUpToAlignment(CurrentSubEntries, 4) / 4);
MaxStackSize = std::max(CurrentStackSize, MaxStackSize);
}
void CFStack::pushBranch(unsigned Opcode, bool isWQM) {
CFStack::StackItem Item = CFStack::ENTRY;
switch(Opcode) {
case AMDGPU::CF_PUSH_EG:
case AMDGPU::CF_ALU_PUSH_BEFORE:
if (!isWQM) {
if (!ST->hasCaymanISA() &&
!branchStackContains(CFStack::FIRST_NON_WQM_PUSH))
Item = CFStack::FIRST_NON_WQM_PUSH; // May not be required on Evergreen/NI
// See comment in
// CFStack::getSubEntrySize()
else if (CurrentEntries > 0 &&
ST->getGeneration() > AMDGPUSubtarget::EVERGREEN &&
!ST->hasCaymanISA() &&
!branchStackContains(CFStack::FIRST_NON_WQM_PUSH_W_FULL_ENTRY))
Item = CFStack::FIRST_NON_WQM_PUSH_W_FULL_ENTRY;
else
Item = CFStack::SUB_ENTRY;
} else
Item = CFStack::ENTRY;
break;
}
BranchStack.push_back(Item);
if (Item == CFStack::ENTRY)
CurrentEntries++;
else
CurrentSubEntries += getSubEntrySize(Item);
updateMaxStackSize();
}
void CFStack::pushLoop() {
LoopStack.push_back(CFStack::ENTRY);
CurrentEntries++;
updateMaxStackSize();
}
void CFStack::popBranch() {
CFStack::StackItem Top = BranchStack.back();
if (Top == CFStack::ENTRY)
CurrentEntries--;
else
CurrentSubEntries-= getSubEntrySize(Top);
BranchStack.pop_back();
}
void CFStack::popLoop() {
CurrentEntries--;
LoopStack.pop_back();
}
class R600ControlFlowFinalizer : public MachineFunctionPass {
private:
typedef std::pair<MachineInstr *, std::vector<MachineInstr *> > ClauseFile;
enum ControlFlowInstruction {
CF_TC,
CF_VC,
CF_CALL_FS,
CF_WHILE_LOOP,
CF_END_LOOP,
CF_LOOP_BREAK,
CF_LOOP_CONTINUE,
CF_JUMP,
CF_ELSE,
CF_POP,
CF_END
};
static char ID;
const R600InstrInfo *TII;
const R600RegisterInfo *TRI;
unsigned MaxFetchInst;
const AMDGPUSubtarget *ST;
bool IsTrivialInst(MachineInstr *MI) const {
switch (MI->getOpcode()) {
case AMDGPU::KILL:
case AMDGPU::RETURN:
return true;
default:
return false;
}
}
const MCInstrDesc &getHWInstrDesc(ControlFlowInstruction CFI) const {
unsigned Opcode = 0;
bool isEg = (ST->getGeneration() >= AMDGPUSubtarget::EVERGREEN);
switch (CFI) {
case CF_TC:
Opcode = isEg ? AMDGPU::CF_TC_EG : AMDGPU::CF_TC_R600;
break;
case CF_VC:
Opcode = isEg ? AMDGPU::CF_VC_EG : AMDGPU::CF_VC_R600;
break;
case CF_CALL_FS:
Opcode = isEg ? AMDGPU::CF_CALL_FS_EG : AMDGPU::CF_CALL_FS_R600;
break;
case CF_WHILE_LOOP:
Opcode = isEg ? AMDGPU::WHILE_LOOP_EG : AMDGPU::WHILE_LOOP_R600;
break;
case CF_END_LOOP:
Opcode = isEg ? AMDGPU::END_LOOP_EG : AMDGPU::END_LOOP_R600;
break;
case CF_LOOP_BREAK:
Opcode = isEg ? AMDGPU::LOOP_BREAK_EG : AMDGPU::LOOP_BREAK_R600;
break;
case CF_LOOP_CONTINUE:
Opcode = isEg ? AMDGPU::CF_CONTINUE_EG : AMDGPU::CF_CONTINUE_R600;
break;
case CF_JUMP:
Opcode = isEg ? AMDGPU::CF_JUMP_EG : AMDGPU::CF_JUMP_R600;
break;
case CF_ELSE:
Opcode = isEg ? AMDGPU::CF_ELSE_EG : AMDGPU::CF_ELSE_R600;
break;
case CF_POP:
Opcode = isEg ? AMDGPU::POP_EG : AMDGPU::POP_R600;
break;
case CF_END:
if (ST->hasCaymanISA()) {
Opcode = AMDGPU::CF_END_CM;
break;
}
Opcode = isEg ? AMDGPU::CF_END_EG : AMDGPU::CF_END_R600;
break;
}
assert (Opcode && "No opcode selected");
return TII->get(Opcode);
}
bool isCompatibleWithClause(const MachineInstr *MI,
std::set<unsigned> &DstRegs) const {
unsigned DstMI, SrcMI;
for (MachineInstr::const_mop_iterator I = MI->operands_begin(),
E = MI->operands_end(); I != E; ++I) {
const MachineOperand &MO = *I;
if (!MO.isReg())
continue;
if (MO.isDef()) {
unsigned Reg = MO.getReg();
if (AMDGPU::R600_Reg128RegClass.contains(Reg))
DstMI = Reg;
else
DstMI = TRI->getMatchingSuperReg(Reg,
TRI->getSubRegFromChannel(TRI->getHWRegChan(Reg)),
&AMDGPU::R600_Reg128RegClass);
}
if (MO.isUse()) {
unsigned Reg = MO.getReg();
if (AMDGPU::R600_Reg128RegClass.contains(Reg))
SrcMI = Reg;
else
SrcMI = TRI->getMatchingSuperReg(Reg,
TRI->getSubRegFromChannel(TRI->getHWRegChan(Reg)),
&AMDGPU::R600_Reg128RegClass);
}
}
if ((DstRegs.find(SrcMI) == DstRegs.end())) {
DstRegs.insert(DstMI);
return true;
} else
return false;
}
ClauseFile
MakeFetchClause(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I)
const {
MachineBasicBlock::iterator ClauseHead = I;
std::vector<MachineInstr *> ClauseContent;
unsigned AluInstCount = 0;
bool IsTex = TII->usesTextureCache(ClauseHead);
std::set<unsigned> DstRegs;
for (MachineBasicBlock::iterator E = MBB.end(); I != E; ++I) {
if (IsTrivialInst(I))
continue;
if (AluInstCount >= MaxFetchInst)
break;
if ((IsTex && !TII->usesTextureCache(I)) ||
(!IsTex && !TII->usesVertexCache(I)))
break;
if (!isCompatibleWithClause(I, DstRegs))
break;
AluInstCount ++;
ClauseContent.push_back(I);
}
MachineInstr *MIb = BuildMI(MBB, ClauseHead, MBB.findDebugLoc(ClauseHead),
getHWInstrDesc(IsTex?CF_TC:CF_VC))
.addImm(0) // ADDR
.addImm(AluInstCount - 1); // COUNT
return ClauseFile(MIb, std::move(ClauseContent));
}
void getLiteral(MachineInstr *MI, std::vector<int64_t> &Lits) const {
static const unsigned LiteralRegs[] = {
AMDGPU::ALU_LITERAL_X,
AMDGPU::ALU_LITERAL_Y,
AMDGPU::ALU_LITERAL_Z,
AMDGPU::ALU_LITERAL_W
};
const SmallVector<std::pair<MachineOperand *, int64_t>, 3 > Srcs =
TII->getSrcs(MI);
for (unsigned i = 0, e = Srcs.size(); i < e; ++i) {
if (Srcs[i].first->getReg() != AMDGPU::ALU_LITERAL_X)
continue;
int64_t Imm = Srcs[i].second;
std::vector<int64_t>::iterator It =
std::find(Lits.begin(), Lits.end(), Imm);
if (It != Lits.end()) {
unsigned Index = It - Lits.begin();
Srcs[i].first->setReg(LiteralRegs[Index]);
} else {
assert(Lits.size() < 4 && "Too many literals in Instruction Group");
Srcs[i].first->setReg(LiteralRegs[Lits.size()]);
Lits.push_back(Imm);
}
}
}
MachineBasicBlock::iterator insertLiterals(
MachineBasicBlock::iterator InsertPos,
const std::vector<unsigned> &Literals) const {
MachineBasicBlock *MBB = InsertPos->getParent();
for (unsigned i = 0, e = Literals.size(); i < e; i+=2) {
unsigned LiteralPair0 = Literals[i];
unsigned LiteralPair1 = (i + 1 < e)?Literals[i + 1]:0;
InsertPos = BuildMI(MBB, InsertPos->getDebugLoc(),
TII->get(AMDGPU::LITERALS))
.addImm(LiteralPair0)
.addImm(LiteralPair1);
}
return InsertPos;
}
ClauseFile
MakeALUClause(MachineBasicBlock &MBB, MachineBasicBlock::iterator &I)
const {
MachineBasicBlock::iterator ClauseHead = I;
std::vector<MachineInstr *> ClauseContent;
I++;
for (MachineBasicBlock::instr_iterator E = MBB.instr_end(); I != E;) {
if (IsTrivialInst(I)) {
++I;
continue;
}
if (!I->isBundle() && !TII->isALUInstr(I->getOpcode()))
break;
std::vector<int64_t> Literals;
if (I->isBundle()) {
MachineInstr *DeleteMI = I;
MachineBasicBlock::instr_iterator BI = I.getInstrIterator();
while (++BI != E && BI->isBundledWithPred()) {
BI->unbundleFromPred();
for (unsigned i = 0, e = BI->getNumOperands(); i != e; ++i) {
MachineOperand &MO = BI->getOperand(i);
if (MO.isReg() && MO.isInternalRead())
MO.setIsInternalRead(false);
}
getLiteral(BI, Literals);
ClauseContent.push_back(BI);
}
I = BI;
DeleteMI->eraseFromParent();
} else {
getLiteral(I, Literals);
ClauseContent.push_back(I);
I++;
}
for (unsigned i = 0, e = Literals.size(); i < e; i+=2) {
unsigned literal0 = Literals[i];
unsigned literal2 = (i + 1 < e)?Literals[i + 1]:0;
MachineInstr *MILit = BuildMI(MBB, I, I->getDebugLoc(),
TII->get(AMDGPU::LITERALS))
.addImm(literal0)
.addImm(literal2);
ClauseContent.push_back(MILit);
}
}
assert(ClauseContent.size() < 128 && "ALU clause is too big");
ClauseHead->getOperand(7).setImm(ClauseContent.size() - 1);
return ClauseFile(ClauseHead, std::move(ClauseContent));
}
void
EmitFetchClause(MachineBasicBlock::iterator InsertPos, ClauseFile &Clause,
unsigned &CfCount) {
CounterPropagateAddr(Clause.first, CfCount);
MachineBasicBlock *BB = Clause.first->getParent();
BuildMI(BB, InsertPos->getDebugLoc(), TII->get(AMDGPU::FETCH_CLAUSE))
.addImm(CfCount);
for (unsigned i = 0, e = Clause.second.size(); i < e; ++i) {
BB->splice(InsertPos, BB, Clause.second[i]);
}
CfCount += 2 * Clause.second.size();
}
void
EmitALUClause(MachineBasicBlock::iterator InsertPos, ClauseFile &Clause,
unsigned &CfCount) {
Clause.first->getOperand(0).setImm(0);
CounterPropagateAddr(Clause.first, CfCount);
MachineBasicBlock *BB = Clause.first->getParent();
BuildMI(BB, InsertPos->getDebugLoc(), TII->get(AMDGPU::ALU_CLAUSE))
.addImm(CfCount);
for (unsigned i = 0, e = Clause.second.size(); i < e; ++i) {
BB->splice(InsertPos, BB, Clause.second[i]);
}
CfCount += Clause.second.size();
}
void CounterPropagateAddr(MachineInstr *MI, unsigned Addr) const {
MI->getOperand(0).setImm(Addr + MI->getOperand(0).getImm());
}
void CounterPropagateAddr(const std::set<MachineInstr *> &MIs,
unsigned Addr) const {
for (MachineInstr *MI : MIs) {
CounterPropagateAddr(MI, Addr);
}
}
public:
R600ControlFlowFinalizer(TargetMachine &tm)
: MachineFunctionPass(ID), TII(nullptr), TRI(nullptr), ST(nullptr) {}
bool runOnMachineFunction(MachineFunction &MF) override {
ST = &MF.getSubtarget<AMDGPUSubtarget>();
MaxFetchInst = ST->getTexVTXClauseSize();
TII = static_cast<const R600InstrInfo *>(ST->getInstrInfo());
TRI = static_cast<const R600RegisterInfo *>(ST->getRegisterInfo());
R600MachineFunctionInfo *MFI = MF.getInfo<R600MachineFunctionInfo>();
CFStack CFStack(ST, MFI->getShaderType());
for (MachineFunction::iterator MB = MF.begin(), ME = MF.end(); MB != ME;
++MB) {
MachineBasicBlock &MBB = *MB;
unsigned CfCount = 0;
std::vector<std::pair<unsigned, std::set<MachineInstr *> > > LoopStack;
std::vector<MachineInstr * > IfThenElseStack;
if (MFI->getShaderType() == ShaderType::VERTEX) {
BuildMI(MBB, MBB.begin(), MBB.findDebugLoc(MBB.begin()),
getHWInstrDesc(CF_CALL_FS));
CfCount++;
}
std::vector<ClauseFile> FetchClauses, AluClauses;
std::vector<MachineInstr *> LastAlu(1);
std::vector<MachineInstr *> ToPopAfter;
for (MachineBasicBlock::iterator I = MBB.begin(), E = MBB.end();
I != E;) {
if (TII->usesTextureCache(I) || TII->usesVertexCache(I)) {
DEBUG(dbgs() << CfCount << ":"; I->dump(););
FetchClauses.push_back(MakeFetchClause(MBB, I));
CfCount++;
LastAlu.back() = nullptr;
continue;
}
MachineBasicBlock::iterator MI = I;
if (MI->getOpcode() != AMDGPU::ENDIF)
LastAlu.back() = nullptr;
if (MI->getOpcode() == AMDGPU::CF_ALU)
LastAlu.back() = MI;
I++;
bool RequiresWorkAround =
CFStack.requiresWorkAroundForInst(MI->getOpcode());
switch (MI->getOpcode()) {
case AMDGPU::CF_ALU_PUSH_BEFORE:
if (RequiresWorkAround) {
DEBUG(dbgs() << "Applying bug work-around for ALU_PUSH_BEFORE\n");
BuildMI(MBB, MI, MBB.findDebugLoc(MI), TII->get(AMDGPU::CF_PUSH_EG))
.addImm(CfCount + 1)
.addImm(1);
MI->setDesc(TII->get(AMDGPU::CF_ALU));
CfCount++;
CFStack.pushBranch(AMDGPU::CF_PUSH_EG);
} else
CFStack.pushBranch(AMDGPU::CF_ALU_PUSH_BEFORE);
case AMDGPU::CF_ALU:
I = MI;
AluClauses.push_back(MakeALUClause(MBB, I));
DEBUG(dbgs() << CfCount << ":"; MI->dump(););
CfCount++;
break;
case AMDGPU::WHILELOOP: {
CFStack.pushLoop();
MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
getHWInstrDesc(CF_WHILE_LOOP))
.addImm(1);
std::pair<unsigned, std::set<MachineInstr *> > Pair(CfCount,
std::set<MachineInstr *>());
Pair.second.insert(MIb);
LoopStack.push_back(std::move(Pair));
MI->eraseFromParent();
CfCount++;
break;
}
case AMDGPU::ENDLOOP: {
CFStack.popLoop();
std::pair<unsigned, std::set<MachineInstr *> > Pair =
std::move(LoopStack.back());
LoopStack.pop_back();
CounterPropagateAddr(Pair.second, CfCount);
BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_END_LOOP))
.addImm(Pair.first + 1);
MI->eraseFromParent();
CfCount++;
break;
}
case AMDGPU::IF_PREDICATE_SET: {
LastAlu.push_back(nullptr);
MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
getHWInstrDesc(CF_JUMP))
.addImm(0)
.addImm(0);
IfThenElseStack.push_back(MIb);
DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
MI->eraseFromParent();
CfCount++;
break;
}
case AMDGPU::ELSE: {
MachineInstr * JumpInst = IfThenElseStack.back();
IfThenElseStack.pop_back();
CounterPropagateAddr(JumpInst, CfCount);
MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
getHWInstrDesc(CF_ELSE))
.addImm(0)
.addImm(0);
DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
IfThenElseStack.push_back(MIb);
MI->eraseFromParent();
CfCount++;
break;
}
case AMDGPU::ENDIF: {
CFStack.popBranch();
if (LastAlu.back()) {
ToPopAfter.push_back(LastAlu.back());
} else {
MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
getHWInstrDesc(CF_POP))
.addImm(CfCount + 1)
.addImm(1);
(void)MIb;
DEBUG(dbgs() << CfCount << ":"; MIb->dump(););
CfCount++;
}
MachineInstr *IfOrElseInst = IfThenElseStack.back();
IfThenElseStack.pop_back();
CounterPropagateAddr(IfOrElseInst, CfCount);
IfOrElseInst->getOperand(1).setImm(1);
LastAlu.pop_back();
MI->eraseFromParent();
break;
}
case AMDGPU::BREAK: {
CfCount ++;
MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
getHWInstrDesc(CF_LOOP_BREAK))
.addImm(0);
LoopStack.back().second.insert(MIb);
MI->eraseFromParent();
break;
}
case AMDGPU::CONTINUE: {
MachineInstr *MIb = BuildMI(MBB, MI, MBB.findDebugLoc(MI),
getHWInstrDesc(CF_LOOP_CONTINUE))
.addImm(0);
LoopStack.back().second.insert(MIb);
MI->eraseFromParent();
CfCount++;
break;
}
case AMDGPU::RETURN: {
BuildMI(MBB, MI, MBB.findDebugLoc(MI), getHWInstrDesc(CF_END));
CfCount++;
MI->eraseFromParent();
if (CfCount % 2) {
BuildMI(MBB, I, MBB.findDebugLoc(MI), TII->get(AMDGPU::PAD));
CfCount++;
}
for (unsigned i = 0, e = FetchClauses.size(); i < e; i++)
EmitFetchClause(I, FetchClauses[i], CfCount);
for (unsigned i = 0, e = AluClauses.size(); i < e; i++)
EmitALUClause(I, AluClauses[i], CfCount);
}
default:
if (TII->isExport(MI->getOpcode())) {
DEBUG(dbgs() << CfCount << ":"; MI->dump(););
CfCount++;
}
break;
}
}
for (unsigned i = 0, e = ToPopAfter.size(); i < e; ++i) {
MachineInstr *Alu = ToPopAfter[i];
BuildMI(MBB, Alu, MBB.findDebugLoc((MachineBasicBlock::iterator)Alu),
TII->get(AMDGPU::CF_ALU_POP_AFTER))
.addImm(Alu->getOperand(0).getImm())
.addImm(Alu->getOperand(1).getImm())
.addImm(Alu->getOperand(2).getImm())
.addImm(Alu->getOperand(3).getImm())
.addImm(Alu->getOperand(4).getImm())
.addImm(Alu->getOperand(5).getImm())
.addImm(Alu->getOperand(6).getImm())
.addImm(Alu->getOperand(7).getImm())
.addImm(Alu->getOperand(8).getImm());
Alu->eraseFromParent();
}
MFI->StackSize = CFStack.MaxStackSize;
}
return false;
}
const char *getPassName() const override {
return "R600 Control Flow Finalizer Pass";
}
};
char R600ControlFlowFinalizer::ID = 0;
} // end anonymous namespace
llvm::FunctionPass *llvm::createR600ControlFlowFinalizer(TargetMachine &TM) {
return new R600ControlFlowFinalizer(TM);
}
|
gpl-3.0
|
Fdepraetre/Handmouse
|
Software/Handmouse_STM/Lib_DL/STM32Cube_FW_F0_V1.8.0/Drivers/CMSIS/DSP_Lib/Source/FilteringFunctions/arm_correlate_fast_q15.c
|
280
|
37364
|
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_correlate_fast_q15.c
*
* Description: Fast Q15 Correlation.
*
* Target Processor: Cortex-M4/Cortex-M3
*
* 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 Corr
* @{
*/
/**
* @brief Correlation of Q15 sequences (fast version) for Cortex-M3 and Cortex-M4.
* @param[in] *pSrcA points to the first input sequence.
* @param[in] srcALen length of the first input sequence.
* @param[in] *pSrcB points to the second input sequence.
* @param[in] srcBLen length of the second input sequence.
* @param[out] *pDst points to the location where the output result is written. Length 2 * max(srcALen, srcBLen) - 1.
* @return none.
*
* <b>Scaling and Overflow Behavior:</b>
*
* \par
* This fast version uses a 32-bit accumulator with 2.30 format.
* The accumulator maintains full precision of the intermediate multiplication results but provides only a single guard bit.
* There is no saturation on intermediate additions.
* Thus, if the accumulator overflows it wraps around and distorts the result.
* The input signals should be scaled down to avoid intermediate overflows.
* Scale down one of the inputs by 1/min(srcALen, srcBLen) to avoid overflow since a
* maximum of min(srcALen, srcBLen) number of additions is carried internally.
* The 2.30 accumulator is right shifted by 15 bits and then saturated to 1.15 format to yield the final result.
*
* \par
* See <code>arm_correlate_q15()</code> for a slower implementation of this function which uses a 64-bit accumulator to avoid wrap around distortion.
*/
void arm_correlate_fast_q15(
q15_t * pSrcA,
uint32_t srcALen,
q15_t * pSrcB,
uint32_t srcBLen,
q15_t * pDst)
{
#ifndef UNALIGNED_SUPPORT_DISABLE
q15_t *pIn1; /* inputA pointer */
q15_t *pIn2; /* inputB pointer */
q15_t *pOut = pDst; /* output pointer */
q31_t sum, acc0, acc1, acc2, acc3; /* Accumulators */
q15_t *px; /* Intermediate inputA pointer */
q15_t *py; /* Intermediate inputB pointer */
q15_t *pSrc1; /* Intermediate pointers */
q31_t x0, x1, x2, x3, c0; /* temporary variables for holding input and coefficient values */
uint32_t j, k = 0u, count, blkCnt, outBlockSize, blockSize1, blockSize2, blockSize3; /* loop counter */
int32_t inc = 1; /* Destination address modifier */
/* The algorithm implementation is based on the lengths of the inputs. */
/* srcB is always made to slide across srcA. */
/* So srcBLen is always considered as shorter or equal to srcALen */
/* But CORR(x, y) is reverse of CORR(y, x) */
/* So, when srcBLen > srcALen, output pointer is made to point to the end of the output buffer */
/* and the destination pointer modifier, inc is set to -1 */
/* If srcALen > srcBLen, zero pad has to be done to srcB to make the two inputs of same length */
/* But to improve the performance,
* we include zeroes in the output instead of zero padding either of the the inputs*/
/* If srcALen > srcBLen,
* (srcALen - srcBLen) zeroes has to included in the starting of the output buffer */
/* If srcALen < srcBLen,
* (srcALen - srcBLen) zeroes has to included in the ending of the output buffer */
if(srcALen >= srcBLen)
{
/* Initialization of inputA pointer */
pIn1 = (pSrcA);
/* Initialization of inputB pointer */
pIn2 = (pSrcB);
/* Number of output samples is calculated */
outBlockSize = (2u * srcALen) - 1u;
/* When srcALen > srcBLen, zero padding is done to srcB
* to make their lengths equal.
* Instead, (outBlockSize - (srcALen + srcBLen - 1))
* number of output samples are made zero */
j = outBlockSize - (srcALen + (srcBLen - 1u));
/* Updating the pointer position to non zero value */
pOut += j;
}
else
{
/* Initialization of inputA pointer */
pIn1 = (pSrcB);
/* Initialization of inputB pointer */
pIn2 = (pSrcA);
/* srcBLen is always considered as shorter or equal to srcALen */
j = srcBLen;
srcBLen = srcALen;
srcALen = j;
/* CORR(x, y) = Reverse order(CORR(y, x)) */
/* Hence set the destination pointer to point to the last output sample */
pOut = pDst + ((srcALen + srcBLen) - 2u);
/* Destination address modifier is set to -1 */
inc = -1;
}
/* The function is internally
* divided into three parts according to the number of multiplications that has to be
* taken place between inputA samples and inputB samples. In the first part of the
* algorithm, the multiplications increase by one for every iteration.
* In the second part of the algorithm, srcBLen number of multiplications are done.
* In the third part of the algorithm, the multiplications decrease by one
* for every iteration.*/
/* The algorithm is implemented in three stages.
* The loop counters of each stage is initiated here. */
blockSize1 = srcBLen - 1u;
blockSize2 = srcALen - (srcBLen - 1u);
blockSize3 = blockSize1;
/* --------------------------
* Initializations of stage1
* -------------------------*/
/* sum = x[0] * y[srcBlen - 1]
* sum = x[0] * y[srcBlen - 2] + x[1] * y[srcBlen - 1]
* ....
* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen - 1] * y[srcBLen - 1]
*/
/* In this stage the MAC operations are increased by 1 for every iteration.
The count variable holds the number of MAC operations performed */
count = 1u;
/* Working pointer of inputA */
px = pIn1;
/* Working pointer of inputB */
pSrc1 = pIn2 + (srcBLen - 1u);
py = pSrc1;
/* ------------------------
* Stage1 process
* ----------------------*/
/* The first loop starts here */
while(blockSize1 > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = count >> 2;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* x[0] * y[srcBLen - 4] , x[1] * y[srcBLen - 3] */
sum = __SMLAD(*__SIMD32(px)++, *__SIMD32(py)++, sum);
/* x[3] * y[srcBLen - 1] , x[2] * y[srcBLen - 2] */
sum = __SMLAD(*__SIMD32(px)++, *__SIMD32(py)++, sum);
/* Decrement the loop counter */
k--;
}
/* If the count is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = count % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
/* x[0] * y[srcBLen - 1] */
sum = __SMLAD(*px++, *py++, sum);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
py = pSrc1 - count;
px = pIn1;
/* Increment the MAC count */
count++;
/* Decrement the loop counter */
blockSize1--;
}
/* --------------------------
* Initializations of stage2
* ------------------------*/
/* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen-1] * y[srcBLen-1]
* sum = x[1] * y[0] + x[2] * y[1] +...+ x[srcBLen] * y[srcBLen-1]
* ....
* sum = x[srcALen-srcBLen-2] * y[0] + x[srcALen-srcBLen-1] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
*/
/* Working pointer of inputA */
px = pIn1;
/* Working pointer of inputB */
py = pIn2;
/* count is index by which the pointer pIn1 to be incremented */
count = 0u;
/* -------------------
* Stage2 process
* ------------------*/
/* Stage2 depends on srcBLen as in this stage srcBLen number of MACS are performed.
* So, to loop unroll over blockSize2,
* srcBLen should be greater than or equal to 4, to loop unroll the srcBLen loop */
if(srcBLen >= 4u)
{
/* Loop unroll over blockSize2, by 4 */
blkCnt = blockSize2 >> 2u;
while(blkCnt > 0u)
{
/* Set all accumulators to zero */
acc0 = 0;
acc1 = 0;
acc2 = 0;
acc3 = 0;
/* read x[0], x[1] samples */
x0 = *__SIMD32(px);
/* read x[1], x[2] samples */
x1 = _SIMD32_OFFSET(px + 1);
px += 2u;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = srcBLen >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
do
{
/* Read the first two inputB samples using SIMD:
* y[0] and y[1] */
c0 = *__SIMD32(py)++;
/* acc0 += x[0] * y[0] + x[1] * y[1] */
acc0 = __SMLAD(x0, c0, acc0);
/* acc1 += x[1] * y[0] + x[2] * y[1] */
acc1 = __SMLAD(x1, c0, acc1);
/* Read x[2], x[3] */
x2 = *__SIMD32(px);
/* Read x[3], x[4] */
x3 = _SIMD32_OFFSET(px + 1);
/* acc2 += x[2] * y[0] + x[3] * y[1] */
acc2 = __SMLAD(x2, c0, acc2);
/* acc3 += x[3] * y[0] + x[4] * y[1] */
acc3 = __SMLAD(x3, c0, acc3);
/* Read y[2] and y[3] */
c0 = *__SIMD32(py)++;
/* acc0 += x[2] * y[2] + x[3] * y[3] */
acc0 = __SMLAD(x2, c0, acc0);
/* acc1 += x[3] * y[2] + x[4] * y[3] */
acc1 = __SMLAD(x3, c0, acc1);
/* Read x[4], x[5] */
x0 = _SIMD32_OFFSET(px + 2);
/* Read x[5], x[6] */
x1 = _SIMD32_OFFSET(px + 3);
px += 4u;
/* acc2 += x[4] * y[2] + x[5] * y[3] */
acc2 = __SMLAD(x0, c0, acc2);
/* acc3 += x[5] * y[2] + x[6] * y[3] */
acc3 = __SMLAD(x1, c0, acc3);
} while(--k);
/* For the next MAC operations, SIMD is not used
* So, the 16 bit pointer if inputB, py is updated */
/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = srcBLen % 0x4u;
if(k == 1u)
{
/* Read y[4] */
c0 = *py;
#ifdef ARM_MATH_BIG_ENDIAN
c0 = c0 << 16u;
#else
c0 = c0 & 0x0000FFFF;
#endif /* #ifdef ARM_MATH_BIG_ENDIAN */
/* Read x[7] */
x3 = *__SIMD32(px);
px++;
/* Perform the multiply-accumulates */
acc0 = __SMLAD(x0, c0, acc0);
acc1 = __SMLAD(x1, c0, acc1);
acc2 = __SMLADX(x1, c0, acc2);
acc3 = __SMLADX(x3, c0, acc3);
}
if(k == 2u)
{
/* Read y[4], y[5] */
c0 = *__SIMD32(py);
/* Read x[7], x[8] */
x3 = *__SIMD32(px);
/* Read x[9] */
x2 = _SIMD32_OFFSET(px + 1);
px += 2u;
/* Perform the multiply-accumulates */
acc0 = __SMLAD(x0, c0, acc0);
acc1 = __SMLAD(x1, c0, acc1);
acc2 = __SMLAD(x3, c0, acc2);
acc3 = __SMLAD(x2, c0, acc3);
}
if(k == 3u)
{
/* Read y[4], y[5] */
c0 = *__SIMD32(py)++;
/* Read x[7], x[8] */
x3 = *__SIMD32(px);
/* Read x[9] */
x2 = _SIMD32_OFFSET(px + 1);
/* Perform the multiply-accumulates */
acc0 = __SMLAD(x0, c0, acc0);
acc1 = __SMLAD(x1, c0, acc1);
acc2 = __SMLAD(x3, c0, acc2);
acc3 = __SMLAD(x2, c0, acc3);
c0 = (*py);
/* Read y[6] */
#ifdef ARM_MATH_BIG_ENDIAN
c0 = c0 << 16u;
#else
c0 = c0 & 0x0000FFFF;
#endif /* #ifdef ARM_MATH_BIG_ENDIAN */
/* Read x[10] */
x3 = _SIMD32_OFFSET(px + 2);
px += 3u;
/* Perform the multiply-accumulates */
acc0 = __SMLADX(x1, c0, acc0);
acc1 = __SMLAD(x2, c0, acc1);
acc2 = __SMLADX(x2, c0, acc2);
acc3 = __SMLADX(x3, c0, acc3);
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (acc0 >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
*pOut = (q15_t) (acc1 >> 15);
pOut += inc;
*pOut = (q15_t) (acc2 >> 15);
pOut += inc;
*pOut = (q15_t) (acc3 >> 15);
pOut += inc;
/* Increment the pointer pIn1 index, count by 1 */
count += 4u;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize2 is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize2 % 0x4u;
while(blkCnt > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = srcBLen >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = srcBLen % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Increment the pointer pIn1 index, count by 1 */
count++;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Decrement the loop counter */
blkCnt--;
}
}
else
{
/* If the srcBLen is not a multiple of 4,
* the blockSize2 loop cannot be unrolled by 4 */
blkCnt = blockSize2;
while(blkCnt > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Loop over srcBLen */
k = srcBLen;
while(k > 0u)
{
/* Perform the multiply-accumulate */
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Increment the MAC count */
count++;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Decrement the loop counter */
blkCnt--;
}
}
/* --------------------------
* Initializations of stage3
* -------------------------*/
/* sum += x[srcALen-srcBLen+1] * y[0] + x[srcALen-srcBLen+2] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
* sum += x[srcALen-srcBLen+2] * y[0] + x[srcALen-srcBLen+3] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
* ....
* sum += x[srcALen-2] * y[0] + x[srcALen-1] * y[1]
* sum += x[srcALen-1] * y[0]
*/
/* In this stage the MAC operations are decreased by 1 for every iteration.
The count variable holds the number of MAC operations performed */
count = srcBLen - 1u;
/* Working pointer of inputA */
pSrc1 = (pIn1 + srcALen) - (srcBLen - 1u);
px = pSrc1;
/* Working pointer of inputB */
py = pIn2;
/* -------------------
* Stage3 process
* ------------------*/
while(blockSize3 > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = count >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* Perform the multiply-accumulates */
/* sum += x[srcALen - srcBLen + 4] * y[3] , sum += x[srcALen - srcBLen + 3] * y[2] */
sum = __SMLAD(*__SIMD32(px)++, *__SIMD32(py)++, sum);
/* sum += x[srcALen - srcBLen + 2] * y[1] , sum += x[srcALen - srcBLen + 1] * y[0] */
sum = __SMLAD(*__SIMD32(px)++, *__SIMD32(py)++, sum);
/* Decrement the loop counter */
k--;
}
/* If the count is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = count % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum = __SMLAD(*px++, *py++, sum);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
px = ++pSrc1;
py = pIn2;
/* Decrement the MAC count */
count--;
/* Decrement the loop counter */
blockSize3--;
}
#else
q15_t *pIn1; /* inputA pointer */
q15_t *pIn2; /* inputB pointer */
q15_t *pOut = pDst; /* output pointer */
q31_t sum, acc0, acc1, acc2, acc3; /* Accumulators */
q15_t *px; /* Intermediate inputA pointer */
q15_t *py; /* Intermediate inputB pointer */
q15_t *pSrc1; /* Intermediate pointers */
q31_t x0, x1, x2, x3, c0; /* temporary variables for holding input and coefficient values */
uint32_t j, k = 0u, count, blkCnt, outBlockSize, blockSize1, blockSize2, blockSize3; /* loop counter */
int32_t inc = 1; /* Destination address modifier */
q15_t a, b;
/* The algorithm implementation is based on the lengths of the inputs. */
/* srcB is always made to slide across srcA. */
/* So srcBLen is always considered as shorter or equal to srcALen */
/* But CORR(x, y) is reverse of CORR(y, x) */
/* So, when srcBLen > srcALen, output pointer is made to point to the end of the output buffer */
/* and the destination pointer modifier, inc is set to -1 */
/* If srcALen > srcBLen, zero pad has to be done to srcB to make the two inputs of same length */
/* But to improve the performance,
* we include zeroes in the output instead of zero padding either of the the inputs*/
/* If srcALen > srcBLen,
* (srcALen - srcBLen) zeroes has to included in the starting of the output buffer */
/* If srcALen < srcBLen,
* (srcALen - srcBLen) zeroes has to included in the ending of the output buffer */
if(srcALen >= srcBLen)
{
/* Initialization of inputA pointer */
pIn1 = (pSrcA);
/* Initialization of inputB pointer */
pIn2 = (pSrcB);
/* Number of output samples is calculated */
outBlockSize = (2u * srcALen) - 1u;
/* When srcALen > srcBLen, zero padding is done to srcB
* to make their lengths equal.
* Instead, (outBlockSize - (srcALen + srcBLen - 1))
* number of output samples are made zero */
j = outBlockSize - (srcALen + (srcBLen - 1u));
/* Updating the pointer position to non zero value */
pOut += j;
}
else
{
/* Initialization of inputA pointer */
pIn1 = (pSrcB);
/* Initialization of inputB pointer */
pIn2 = (pSrcA);
/* srcBLen is always considered as shorter or equal to srcALen */
j = srcBLen;
srcBLen = srcALen;
srcALen = j;
/* CORR(x, y) = Reverse order(CORR(y, x)) */
/* Hence set the destination pointer to point to the last output sample */
pOut = pDst + ((srcALen + srcBLen) - 2u);
/* Destination address modifier is set to -1 */
inc = -1;
}
/* The function is internally
* divided into three parts according to the number of multiplications that has to be
* taken place between inputA samples and inputB samples. In the first part of the
* algorithm, the multiplications increase by one for every iteration.
* In the second part of the algorithm, srcBLen number of multiplications are done.
* In the third part of the algorithm, the multiplications decrease by one
* for every iteration.*/
/* The algorithm is implemented in three stages.
* The loop counters of each stage is initiated here. */
blockSize1 = srcBLen - 1u;
blockSize2 = srcALen - (srcBLen - 1u);
blockSize3 = blockSize1;
/* --------------------------
* Initializations of stage1
* -------------------------*/
/* sum = x[0] * y[srcBlen - 1]
* sum = x[0] * y[srcBlen - 2] + x[1] * y[srcBlen - 1]
* ....
* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen - 1] * y[srcBLen - 1]
*/
/* In this stage the MAC operations are increased by 1 for every iteration.
The count variable holds the number of MAC operations performed */
count = 1u;
/* Working pointer of inputA */
px = pIn1;
/* Working pointer of inputB */
pSrc1 = pIn2 + (srcBLen - 1u);
py = pSrc1;
/* ------------------------
* Stage1 process
* ----------------------*/
/* The first loop starts here */
while(blockSize1 > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = count >> 2;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* x[0] * y[srcBLen - 4] , x[1] * y[srcBLen - 3] */
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* If the count is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = count % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
/* x[0] * y[srcBLen - 1] */
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
py = pSrc1 - count;
px = pIn1;
/* Increment the MAC count */
count++;
/* Decrement the loop counter */
blockSize1--;
}
/* --------------------------
* Initializations of stage2
* ------------------------*/
/* sum = x[0] * y[0] + x[1] * y[1] +...+ x[srcBLen-1] * y[srcBLen-1]
* sum = x[1] * y[0] + x[2] * y[1] +...+ x[srcBLen] * y[srcBLen-1]
* ....
* sum = x[srcALen-srcBLen-2] * y[0] + x[srcALen-srcBLen-1] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
*/
/* Working pointer of inputA */
px = pIn1;
/* Working pointer of inputB */
py = pIn2;
/* count is index by which the pointer pIn1 to be incremented */
count = 0u;
/* -------------------
* Stage2 process
* ------------------*/
/* Stage2 depends on srcBLen as in this stage srcBLen number of MACS are performed.
* So, to loop unroll over blockSize2,
* srcBLen should be greater than or equal to 4, to loop unroll the srcBLen loop */
if(srcBLen >= 4u)
{
/* Loop unroll over blockSize2, by 4 */
blkCnt = blockSize2 >> 2u;
while(blkCnt > 0u)
{
/* Set all accumulators to zero */
acc0 = 0;
acc1 = 0;
acc2 = 0;
acc3 = 0;
/* read x[0], x[1], x[2] samples */
a = *px;
b = *(px + 1);
#ifndef ARM_MATH_BIG_ENDIAN
x0 = __PKHBT(a, b, 16);
a = *(px + 2);
x1 = __PKHBT(b, a, 16);
#else
x0 = __PKHBT(b, a, 16);
a = *(px + 2);
x1 = __PKHBT(a, b, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
px += 2u;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = srcBLen >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
do
{
/* Read the first two inputB samples using SIMD:
* y[0] and y[1] */
a = *py;
b = *(py + 1);
#ifndef ARM_MATH_BIG_ENDIAN
c0 = __PKHBT(a, b, 16);
#else
c0 = __PKHBT(b, a, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
/* acc0 += x[0] * y[0] + x[1] * y[1] */
acc0 = __SMLAD(x0, c0, acc0);
/* acc1 += x[1] * y[0] + x[2] * y[1] */
acc1 = __SMLAD(x1, c0, acc1);
/* Read x[2], x[3], x[4] */
a = *px;
b = *(px + 1);
#ifndef ARM_MATH_BIG_ENDIAN
x2 = __PKHBT(a, b, 16);
a = *(px + 2);
x3 = __PKHBT(b, a, 16);
#else
x2 = __PKHBT(b, a, 16);
a = *(px + 2);
x3 = __PKHBT(a, b, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
/* acc2 += x[2] * y[0] + x[3] * y[1] */
acc2 = __SMLAD(x2, c0, acc2);
/* acc3 += x[3] * y[0] + x[4] * y[1] */
acc3 = __SMLAD(x3, c0, acc3);
/* Read y[2] and y[3] */
a = *(py + 2);
b = *(py + 3);
py += 4u;
#ifndef ARM_MATH_BIG_ENDIAN
c0 = __PKHBT(a, b, 16);
#else
c0 = __PKHBT(b, a, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
/* acc0 += x[2] * y[2] + x[3] * y[3] */
acc0 = __SMLAD(x2, c0, acc0);
/* acc1 += x[3] * y[2] + x[4] * y[3] */
acc1 = __SMLAD(x3, c0, acc1);
/* Read x[4], x[5], x[6] */
a = *(px + 2);
b = *(px + 3);
#ifndef ARM_MATH_BIG_ENDIAN
x0 = __PKHBT(a, b, 16);
a = *(px + 4);
x1 = __PKHBT(b, a, 16);
#else
x0 = __PKHBT(b, a, 16);
a = *(px + 4);
x1 = __PKHBT(a, b, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
px += 4u;
/* acc2 += x[4] * y[2] + x[5] * y[3] */
acc2 = __SMLAD(x0, c0, acc2);
/* acc3 += x[5] * y[2] + x[6] * y[3] */
acc3 = __SMLAD(x1, c0, acc3);
} while(--k);
/* For the next MAC operations, SIMD is not used
* So, the 16 bit pointer if inputB, py is updated */
/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = srcBLen % 0x4u;
if(k == 1u)
{
/* Read y[4] */
c0 = *py;
#ifdef ARM_MATH_BIG_ENDIAN
c0 = c0 << 16u;
#else
c0 = c0 & 0x0000FFFF;
#endif /* #ifdef ARM_MATH_BIG_ENDIAN */
/* Read x[7] */
a = *px;
b = *(px + 1);
px++;;
#ifndef ARM_MATH_BIG_ENDIAN
x3 = __PKHBT(a, b, 16);
#else
x3 = __PKHBT(b, a, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
px++;
/* Perform the multiply-accumulates */
acc0 = __SMLAD(x0, c0, acc0);
acc1 = __SMLAD(x1, c0, acc1);
acc2 = __SMLADX(x1, c0, acc2);
acc3 = __SMLADX(x3, c0, acc3);
}
if(k == 2u)
{
/* Read y[4], y[5] */
a = *py;
b = *(py + 1);
#ifndef ARM_MATH_BIG_ENDIAN
c0 = __PKHBT(a, b, 16);
#else
c0 = __PKHBT(b, a, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
/* Read x[7], x[8], x[9] */
a = *px;
b = *(px + 1);
#ifndef ARM_MATH_BIG_ENDIAN
x3 = __PKHBT(a, b, 16);
a = *(px + 2);
x2 = __PKHBT(b, a, 16);
#else
x3 = __PKHBT(b, a, 16);
a = *(px + 2);
x2 = __PKHBT(a, b, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
px += 2u;
/* Perform the multiply-accumulates */
acc0 = __SMLAD(x0, c0, acc0);
acc1 = __SMLAD(x1, c0, acc1);
acc2 = __SMLAD(x3, c0, acc2);
acc3 = __SMLAD(x2, c0, acc3);
}
if(k == 3u)
{
/* Read y[4], y[5] */
a = *py;
b = *(py + 1);
#ifndef ARM_MATH_BIG_ENDIAN
c0 = __PKHBT(a, b, 16);
#else
c0 = __PKHBT(b, a, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
py += 2u;
/* Read x[7], x[8], x[9] */
a = *px;
b = *(px + 1);
#ifndef ARM_MATH_BIG_ENDIAN
x3 = __PKHBT(a, b, 16);
a = *(px + 2);
x2 = __PKHBT(b, a, 16);
#else
x3 = __PKHBT(b, a, 16);
a = *(px + 2);
x2 = __PKHBT(a, b, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
/* Perform the multiply-accumulates */
acc0 = __SMLAD(x0, c0, acc0);
acc1 = __SMLAD(x1, c0, acc1);
acc2 = __SMLAD(x3, c0, acc2);
acc3 = __SMLAD(x2, c0, acc3);
c0 = (*py);
/* Read y[6] */
#ifdef ARM_MATH_BIG_ENDIAN
c0 = c0 << 16u;
#else
c0 = c0 & 0x0000FFFF;
#endif /* #ifdef ARM_MATH_BIG_ENDIAN */
/* Read x[10] */
b = *(px + 3);
#ifndef ARM_MATH_BIG_ENDIAN
x3 = __PKHBT(a, b, 16);
#else
x3 = __PKHBT(b, a, 16);
#endif /* #ifndef ARM_MATH_BIG_ENDIAN */
px += 3u;
/* Perform the multiply-accumulates */
acc0 = __SMLADX(x1, c0, acc0);
acc1 = __SMLAD(x2, c0, acc1);
acc2 = __SMLADX(x2, c0, acc2);
acc3 = __SMLADX(x3, c0, acc3);
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (acc0 >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
*pOut = (q15_t) (acc1 >> 15);
pOut += inc;
*pOut = (q15_t) (acc2 >> 15);
pOut += inc;
*pOut = (q15_t) (acc3 >> 15);
pOut += inc;
/* Increment the pointer pIn1 index, count by 1 */
count += 4u;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize2 is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize2 % 0x4u;
while(blkCnt > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = srcBLen >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* If the srcBLen is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = srcBLen % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Increment the pointer pIn1 index, count by 1 */
count++;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Decrement the loop counter */
blkCnt--;
}
}
else
{
/* If the srcBLen is not a multiple of 4,
* the blockSize2 loop cannot be unrolled by 4 */
blkCnt = blockSize2;
while(blkCnt > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Loop over srcBLen */
k = srcBLen;
while(k > 0u)
{
/* Perform the multiply-accumulate */
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Increment the MAC count */
count++;
/* Update the inputA and inputB pointers for next MAC calculation */
px = pIn1 + count;
py = pIn2;
/* Decrement the loop counter */
blkCnt--;
}
}
/* --------------------------
* Initializations of stage3
* -------------------------*/
/* sum += x[srcALen-srcBLen+1] * y[0] + x[srcALen-srcBLen+2] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
* sum += x[srcALen-srcBLen+2] * y[0] + x[srcALen-srcBLen+3] * y[1] +...+ x[srcALen-1] * y[srcBLen-1]
* ....
* sum += x[srcALen-2] * y[0] + x[srcALen-1] * y[1]
* sum += x[srcALen-1] * y[0]
*/
/* In this stage the MAC operations are decreased by 1 for every iteration.
The count variable holds the number of MAC operations performed */
count = srcBLen - 1u;
/* Working pointer of inputA */
pSrc1 = (pIn1 + srcALen) - (srcBLen - 1u);
px = pSrc1;
/* Working pointer of inputB */
py = pIn2;
/* -------------------
* Stage3 process
* ------------------*/
while(blockSize3 > 0u)
{
/* Accumulator is made zero for every iteration */
sum = 0;
/* Apply loop unrolling and compute 4 MACs simultaneously. */
k = count >> 2u;
/* First part of the processing with loop unrolling. Compute 4 MACs at a time.
** a second loop below computes MACs for the remaining 1 to 3 samples. */
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* If the count is not a multiple of 4, compute any remaining MACs here.
** No loop unrolling is used. */
k = count % 0x4u;
while(k > 0u)
{
/* Perform the multiply-accumulates */
sum += ((q31_t) * px++ * *py++);
/* Decrement the loop counter */
k--;
}
/* Store the result in the accumulator in the destination buffer. */
*pOut = (q15_t) (sum >> 15);
/* Destination pointer is updated according to the address modifier, inc */
pOut += inc;
/* Update the inputA and inputB pointers for next MAC calculation */
px = ++pSrc1;
py = pIn2;
/* Decrement the MAC count */
count--;
/* Decrement the loop counter */
blockSize3--;
}
#endif /* #ifndef UNALIGNED_SUPPORT_DISABLE */
}
/**
* @} end of Corr group
*/
|
gpl-3.0
|
qyqx/Sigil
|
src/FlightCrew/Schemas/AsSources/ContainerXsd.cpp
|
25
|
10538
|
/************************************************************************
**
** Copyright (C) 2010 Strahinja Markovic
**
** This file is part of FlightCrew.
**
** FlightCrew 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.
**
** FlightCrew 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 FlightCrew. If not, see <http://www.gnu.org/licenses/>.
**
*************************************************************************/
#include <stdafx.h>
/*
OCF META-INF/container.xml, XSD
Specification: http://www.idpf.org/doc_library/epub/OCF_2.0.1_draft.doc
Namespace: urn:oasis:names:tc:opendocument:xmlns:container
Created by hand.
*/
namespace FlightCrew
{
const char* CONTAINER_XSD_NS = "urn:oasis:names:tc:opendocument:xmlns:container";
const char* CONTAINER_XSD_ID = "container.xsd";
const unsigned int CONTAINER_XSD_LEN = 1437;
const unsigned char CONTAINER_XSD[] = {
0x3c, 0x3f, 0x78, 0x6d, 0x6c, 0x20, 0x76, 0x65, 0x72, 0x73, 0x69, 0x6f,
0x6e, 0x3d, 0x22, 0x31, 0x2e, 0x30, 0x22, 0x20, 0x65, 0x6e, 0x63, 0x6f,
0x64, 0x69, 0x6e, 0x67, 0x3d, 0x22, 0x55, 0x54, 0x46, 0x2d, 0x38, 0x22,
0x3f, 0x3e, 0x0d, 0x0a, 0x3c, 0x78, 0x73, 0x3a, 0x73, 0x63, 0x68, 0x65,
0x6d, 0x61, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x78, 0x73, 0x3d,
0x22, 0x68, 0x74, 0x74, 0x70, 0x3a, 0x2f, 0x2f, 0x77, 0x77, 0x77, 0x2e,
0x77, 0x33, 0x2e, 0x6f, 0x72, 0x67, 0x2f, 0x32, 0x30, 0x30, 0x31, 0x2f,
0x58, 0x4d, 0x4c, 0x53, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x22, 0x20, 0x65,
0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x46, 0x6f, 0x72, 0x6d, 0x44, 0x65,
0x66, 0x61, 0x75, 0x6c, 0x74, 0x3d, 0x22, 0x71, 0x75, 0x61, 0x6c, 0x69,
0x66, 0x69, 0x65, 0x64, 0x22, 0x0d, 0x0a, 0x20, 0x20, 0x74, 0x61, 0x72,
0x67, 0x65, 0x74, 0x4e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65,
0x3d, 0x22, 0x75, 0x72, 0x6e, 0x3a, 0x6f, 0x61, 0x73, 0x69, 0x73, 0x3a,
0x6e, 0x61, 0x6d, 0x65, 0x73, 0x3a, 0x74, 0x63, 0x3a, 0x6f, 0x70, 0x65,
0x6e, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74, 0x3a, 0x78, 0x6d,
0x6c, 0x6e, 0x73, 0x3a, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69, 0x6e, 0x65,
0x72, 0x22, 0x0d, 0x0a, 0x20, 0x20, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a,
0x63, 0x6f, 0x6e, 0x3d, 0x22, 0x75, 0x72, 0x6e, 0x3a, 0x6f, 0x61, 0x73,
0x69, 0x73, 0x3a, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x3a, 0x74, 0x63, 0x3a,
0x6f, 0x70, 0x65, 0x6e, 0x64, 0x6f, 0x63, 0x75, 0x6d, 0x65, 0x6e, 0x74,
0x3a, 0x78, 0x6d, 0x6c, 0x6e, 0x73, 0x3a, 0x63, 0x6f, 0x6e, 0x74, 0x61,
0x69, 0x6e, 0x65, 0x72, 0x22, 0x3e, 0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20,
0x3c, 0x78, 0x73, 0x3a, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20,
0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x74, 0x61, 0x69,
0x6e, 0x65, 0x72, 0x22, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c,
0x78, 0x73, 0x3a, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78, 0x54, 0x79,
0x70, 0x65, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c,
0x78, 0x73, 0x3a, 0x63, 0x68, 0x6f, 0x69, 0x63, 0x65, 0x20, 0x6d, 0x61,
0x78, 0x4f, 0x63, 0x63, 0x75, 0x72, 0x73, 0x3d, 0x22, 0x75, 0x6e, 0x62,
0x6f, 0x75, 0x6e, 0x64, 0x65, 0x64, 0x22, 0x3e, 0x0d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x65, 0x6c,
0x65, 0x6d, 0x65, 0x6e, 0x74, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22,
0x72, 0x6f, 0x6f, 0x74, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x22, 0x20, 0x74,
0x79, 0x70, 0x65, 0x3d, 0x22, 0x63, 0x6f, 0x6e, 0x3a, 0x72, 0x6f, 0x6f,
0x74, 0x66, 0x69, 0x6c, 0x65, 0x73, 0x22, 0x2f, 0x3e, 0x0d, 0x0a, 0x20,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x61,
0x6e, 0x79, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x43, 0x6f,
0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x3d, 0x22, 0x6c, 0x61, 0x78, 0x22,
0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3d, 0x22,
0x23, 0x23, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x22, 0x20, 0x6d, 0x69, 0x6e,
0x4f, 0x63, 0x63, 0x75, 0x72, 0x73, 0x3d, 0x22, 0x30, 0x22, 0x20, 0x6d,
0x61, 0x78, 0x4f, 0x63, 0x63, 0x75, 0x72, 0x73, 0x3d, 0x22, 0x75, 0x6e,
0x62, 0x6f, 0x75, 0x6e, 0x64, 0x65, 0x64, 0x22, 0x2f, 0x3e, 0x0d, 0x0a,
0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x78, 0x73, 0x3a, 0x63,
0x68, 0x6f, 0x69, 0x63, 0x65, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62,
0x75, 0x74, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22, 0x76, 0x65,
0x72, 0x73, 0x69, 0x6f, 0x6e, 0x22, 0x20, 0x75, 0x73, 0x65, 0x3d, 0x22,
0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x22, 0x2f, 0x3e, 0x0d,
0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x61,
0x6e, 0x79, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20,
0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x65,
0x6e, 0x74, 0x73, 0x3d, 0x22, 0x6c, 0x61, 0x78, 0x22, 0x20, 0x6e, 0x61,
0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3d, 0x22, 0x23, 0x23, 0x6f,
0x74, 0x68, 0x65, 0x72, 0x22, 0x20, 0x2f, 0x3e, 0x0d, 0x0a, 0x20, 0x20,
0x20, 0x20, 0x3c, 0x2f, 0x78, 0x73, 0x3a, 0x63, 0x6f, 0x6d, 0x70, 0x6c,
0x65, 0x78, 0x54, 0x79, 0x70, 0x65, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x3c,
0x2f, 0x78, 0x73, 0x3a, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e, 0x74, 0x3e,
0x0d, 0x0a, 0x0d, 0x0a, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x63, 0x6f,
0x6d, 0x70, 0x6c, 0x65, 0x78, 0x54, 0x79, 0x70, 0x65, 0x20, 0x6e, 0x61,
0x6d, 0x65, 0x3d, 0x22, 0x72, 0x6f, 0x6f, 0x74, 0x66, 0x69, 0x6c, 0x65,
0x73, 0x22, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73,
0x3a, 0x63, 0x68, 0x6f, 0x69, 0x63, 0x65, 0x20, 0x6d, 0x61, 0x78, 0x4f,
0x63, 0x63, 0x75, 0x72, 0x73, 0x3d, 0x22, 0x75, 0x6e, 0x62, 0x6f, 0x75,
0x6e, 0x64, 0x65, 0x64, 0x22, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x65, 0x6c, 0x65, 0x6d, 0x65, 0x6e,
0x74, 0x20, 0x6d, 0x61, 0x78, 0x4f, 0x63, 0x63, 0x75, 0x72, 0x73, 0x3d,
0x22, 0x75, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x65, 0x64, 0x22, 0x20,
0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22, 0x72, 0x6f, 0x6f, 0x74, 0x66, 0x69,
0x6c, 0x65, 0x22, 0x20, 0x74, 0x79, 0x70, 0x65, 0x3d, 0x22, 0x63, 0x6f,
0x6e, 0x3a, 0x72, 0x6f, 0x6f, 0x74, 0x66, 0x69, 0x6c, 0x65, 0x22, 0x2f,
0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73,
0x3a, 0x61, 0x6e, 0x79, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73,
0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x3d, 0x22, 0x6c, 0x61,
0x78, 0x22, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65,
0x3d, 0x22, 0x23, 0x23, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x22, 0x20, 0x6d,
0x69, 0x6e, 0x4f, 0x63, 0x63, 0x75, 0x72, 0x73, 0x3d, 0x22, 0x30, 0x22,
0x20, 0x6d, 0x61, 0x78, 0x4f, 0x63, 0x63, 0x75, 0x72, 0x73, 0x3d, 0x22,
0x75, 0x6e, 0x62, 0x6f, 0x75, 0x6e, 0x64, 0x65, 0x64, 0x22, 0x2f, 0x3e,
0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x2f, 0x78, 0x73, 0x3a, 0x63,
0x68, 0x6f, 0x69, 0x63, 0x65, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x3c, 0x78, 0x73, 0x3a, 0x61, 0x6e, 0x79, 0x41, 0x74, 0x74, 0x72, 0x69,
0x62, 0x75, 0x74, 0x65, 0x20, 0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73,
0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e, 0x74, 0x73, 0x3d, 0x22, 0x6c, 0x61,
0x78, 0x22, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65,
0x3d, 0x22, 0x23, 0x23, 0x6f, 0x74, 0x68, 0x65, 0x72, 0x22, 0x20, 0x2f,
0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x3c, 0x2f, 0x78, 0x73, 0x3a, 0x63, 0x6f,
0x6d, 0x70, 0x6c, 0x65, 0x78, 0x54, 0x79, 0x70, 0x65, 0x3e, 0x0d, 0x0a,
0x0d, 0x0a, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x63, 0x6f, 0x6d, 0x70,
0x6c, 0x65, 0x78, 0x54, 0x79, 0x70, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65,
0x3d, 0x22, 0x72, 0x6f, 0x6f, 0x74, 0x66, 0x69, 0x6c, 0x65, 0x22, 0x3e,
0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x73, 0x65,
0x71, 0x75, 0x65, 0x6e, 0x63, 0x65, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x61, 0x6e, 0x79, 0x20, 0x70,
0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x65, 0x6e,
0x74, 0x73, 0x3d, 0x22, 0x6c, 0x61, 0x78, 0x22, 0x20, 0x6e, 0x61, 0x6d,
0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3d, 0x22, 0x23, 0x23, 0x6f, 0x74,
0x68, 0x65, 0x72, 0x22, 0x20, 0x6d, 0x69, 0x6e, 0x4f, 0x63, 0x63, 0x75,
0x72, 0x73, 0x3d, 0x22, 0x30, 0x22, 0x20, 0x6d, 0x61, 0x78, 0x4f, 0x63,
0x63, 0x75, 0x72, 0x73, 0x3d, 0x22, 0x75, 0x6e, 0x62, 0x6f, 0x75, 0x6e,
0x64, 0x65, 0x64, 0x22, 0x2f, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20,
0x3c, 0x2f, 0x78, 0x73, 0x3a, 0x73, 0x65, 0x71, 0x75, 0x65, 0x6e, 0x63,
0x65, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a,
0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20, 0x6e, 0x61,
0x6d, 0x65, 0x3d, 0x22, 0x66, 0x75, 0x6c, 0x6c, 0x2d, 0x70, 0x61, 0x74,
0x68, 0x22, 0x20, 0x75, 0x73, 0x65, 0x3d, 0x22, 0x72, 0x65, 0x71, 0x75,
0x69, 0x72, 0x65, 0x64, 0x22, 0x2f, 0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20,
0x20, 0x3c, 0x78, 0x73, 0x3a, 0x61, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75,
0x74, 0x65, 0x20, 0x6e, 0x61, 0x6d, 0x65, 0x3d, 0x22, 0x6d, 0x65, 0x64,
0x69, 0x61, 0x2d, 0x74, 0x79, 0x70, 0x65, 0x22, 0x20, 0x75, 0x73, 0x65,
0x3d, 0x22, 0x72, 0x65, 0x71, 0x75, 0x69, 0x72, 0x65, 0x64, 0x22, 0x2f,
0x3e, 0x0d, 0x0a, 0x20, 0x20, 0x20, 0x20, 0x3c, 0x78, 0x73, 0x3a, 0x61,
0x6e, 0x79, 0x41, 0x74, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x65, 0x20,
0x70, 0x72, 0x6f, 0x63, 0x65, 0x73, 0x73, 0x43, 0x6f, 0x6e, 0x74, 0x65,
0x6e, 0x74, 0x73, 0x3d, 0x22, 0x6c, 0x61, 0x78, 0x22, 0x20, 0x6e, 0x61,
0x6d, 0x65, 0x73, 0x70, 0x61, 0x63, 0x65, 0x3d, 0x22, 0x23, 0x23, 0x6f,
0x74, 0x68, 0x65, 0x72, 0x22, 0x20, 0x2f, 0x3e, 0x0d, 0x0a, 0x20, 0x20,
0x3c, 0x2f, 0x78, 0x73, 0x3a, 0x63, 0x6f, 0x6d, 0x70, 0x6c, 0x65, 0x78,
0x54, 0x79, 0x70, 0x65, 0x3e, 0x0d, 0x0a, 0x3c, 0x2f, 0x78, 0x73, 0x3a,
0x73, 0x63, 0x68, 0x65, 0x6d, 0x61, 0x3e, 0x0d, 0x0a
};
} //namespace FlightCrew
|
gpl-3.0
|
Zouyiran/shadowsocks-android
|
src/main/jni/openssl/crypto/whrlpool/wp_block.c
|
537
|
25828
|
/**
* The Whirlpool hashing function.
*
* <P>
* <b>References</b>
*
* <P>
* The Whirlpool algorithm was developed by
* <a href="mailto:pbarreto@scopus.com.br">Paulo S. L. M. Barreto</a> and
* <a href="mailto:vincent.rijmen@cryptomathic.com">Vincent Rijmen</a>.
*
* See
* P.S.L.M. Barreto, V. Rijmen,
* ``The Whirlpool hashing function,''
* NESSIE submission, 2000 (tweaked version, 2001),
* <https://www.cosic.esat.kuleuven.ac.be/nessie/workshop/submissions/whirlpool.zip>
*
* Based on "@version 3.0 (2003.03.12)" by Paulo S.L.M. Barreto and
* Vincent Rijmen. Lookup "reference implementations" on
* <http://planeta.terra.com.br/informatica/paulobarreto/>
*
* =============================================================================
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ''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 AUTHORS 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 "wp_locl.h"
#include <string.h>
typedef unsigned char u8;
#if (defined(_WIN32) || defined(_WIN64)) && !defined(__MINGW32)
typedef unsigned __int64 u64;
#elif defined(__arch64__)
typedef unsigned long u64;
#else
typedef unsigned long long u64;
#endif
#define ROUNDS 10
#define STRICT_ALIGNMENT
#if defined(__i386) || defined(__i386__) || \
defined(__x86_64) || defined(__x86_64__) || \
defined(_M_IX86) || defined(_M_AMD64) || defined(_M_X64)
/* Well, formally there're couple of other architectures, which permit
* unaligned loads, specifically those not crossing cache lines, IA-64
* and PowerPC... */
# undef STRICT_ALIGNMENT
#endif
#undef SMALL_REGISTER_BANK
#if defined(__i386) || defined(__i386__) || defined(_M_IX86)
# define SMALL_REGISTER_BANK
# if defined(WHIRLPOOL_ASM)
# ifndef OPENSSL_SMALL_FOOTPRINT
# define OPENSSL_SMALL_FOOTPRINT /* it appears that for elder non-MMX
CPUs this is actually faster! */
# endif
# define GO_FOR_MMX(ctx,inp,num) do { \
extern unsigned int OPENSSL_ia32cap_P[]; \
void whirlpool_block_mmx(void *,const void *,size_t); \
if (!(OPENSSL_ia32cap_P[0] & (1<<23))) break; \
whirlpool_block_mmx(ctx->H.c,inp,num); return; \
} while (0)
# endif
#endif
#undef ROTATE
#if defined(_MSC_VER)
# if defined(_WIN64) /* applies to both IA-64 and AMD64 */
# pragma intrinsic(_rotl64)
# define ROTATE(a,n) _rotl64((a),n)
# endif
#elif defined(__GNUC__) && __GNUC__>=2
# if defined(__x86_64) || defined(__x86_64__)
# if defined(L_ENDIAN)
# define ROTATE(a,n) ({ u64 ret; asm ("rolq %1,%0" \
: "=r"(ret) : "J"(n),"0"(a) : "cc"); ret; })
# elif defined(B_ENDIAN)
/* Most will argue that x86_64 is always little-endian. Well,
* yes, but then we have stratus.com who has modified gcc to
* "emulate" big-endian on x86. Is there evidence that they
* [or somebody else] won't do same for x86_64? Naturally no.
* And this line is waiting ready for that brave soul:-) */
# define ROTATE(a,n) ({ u64 ret; asm ("rorq %1,%0" \
: "=r"(ret) : "J"(n),"0"(a) : "cc"); ret; })
# endif
# elif defined(__ia64) || defined(__ia64__)
# if defined(L_ENDIAN)
# define ROTATE(a,n) ({ u64 ret; asm ("shrp %0=%1,%1,%2" \
: "=r"(ret) : "r"(a),"M"(64-(n))); ret; })
# elif defined(B_ENDIAN)
# define ROTATE(a,n) ({ u64 ret; asm ("shrp %0=%1,%1,%2" \
: "=r"(ret) : "r"(a),"M"(n)); ret; })
# endif
# endif
#endif
#if defined(OPENSSL_SMALL_FOOTPRINT)
# if !defined(ROTATE)
# if defined(L_ENDIAN) /* little-endians have to rotate left */
# define ROTATE(i,n) ((i)<<(n) ^ (i)>>(64-n))
# elif defined(B_ENDIAN) /* big-endians have to rotate right */
# define ROTATE(i,n) ((i)>>(n) ^ (i)<<(64-n))
# endif
# endif
# if defined(ROTATE) && !defined(STRICT_ALIGNMENT)
# define STRICT_ALIGNMENT /* ensure smallest table size */
# endif
#endif
/*
* Table size depends on STRICT_ALIGNMENT and whether or not endian-
* specific ROTATE macro is defined. If STRICT_ALIGNMENT is not
* defined, which is normally the case on x86[_64] CPUs, the table is
* 4KB large unconditionally. Otherwise if ROTATE is defined, the
* table is 2KB large, and otherwise - 16KB. 2KB table requires a
* whole bunch of additional rotations, but I'm willing to "trade,"
* because 16KB table certainly trashes L1 cache. I wish all CPUs
* could handle unaligned load as 4KB table doesn't trash the cache,
* nor does it require additional rotations.
*/
/*
* Note that every Cn macro expands as two loads: one byte load and
* one quadword load. One can argue that that many single-byte loads
* is too excessive, as one could load a quadword and "milk" it for
* eight 8-bit values instead. Well, yes, but in order to do so *and*
* avoid excessive loads you have to accomodate a handful of 64-bit
* values in the register bank and issue a bunch of shifts and mask.
* It's a tradeoff: loads vs. shift and mask in big register bank[!].
* On most CPUs eight single-byte loads are faster and I let other
* ones to depend on smart compiler to fold byte loads if beneficial.
* Hand-coded assembler would be another alternative:-)
*/
#ifdef STRICT_ALIGNMENT
# if defined(ROTATE)
# define N 1
# define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7
# define C0(K,i) (Cx.q[K.c[(i)*8+0]])
# define C1(K,i) ROTATE(Cx.q[K.c[(i)*8+1]],8)
# define C2(K,i) ROTATE(Cx.q[K.c[(i)*8+2]],16)
# define C3(K,i) ROTATE(Cx.q[K.c[(i)*8+3]],24)
# define C4(K,i) ROTATE(Cx.q[K.c[(i)*8+4]],32)
# define C5(K,i) ROTATE(Cx.q[K.c[(i)*8+5]],40)
# define C6(K,i) ROTATE(Cx.q[K.c[(i)*8+6]],48)
# define C7(K,i) ROTATE(Cx.q[K.c[(i)*8+7]],56)
# else
# define N 8
# define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7, \
c7,c0,c1,c2,c3,c4,c5,c6, \
c6,c7,c0,c1,c2,c3,c4,c5, \
c5,c6,c7,c0,c1,c2,c3,c4, \
c4,c5,c6,c7,c0,c1,c2,c3, \
c3,c4,c5,c6,c7,c0,c1,c2, \
c2,c3,c4,c5,c6,c7,c0,c1, \
c1,c2,c3,c4,c5,c6,c7,c0
# define C0(K,i) (Cx.q[0+8*K.c[(i)*8+0]])
# define C1(K,i) (Cx.q[1+8*K.c[(i)*8+1]])
# define C2(K,i) (Cx.q[2+8*K.c[(i)*8+2]])
# define C3(K,i) (Cx.q[3+8*K.c[(i)*8+3]])
# define C4(K,i) (Cx.q[4+8*K.c[(i)*8+4]])
# define C5(K,i) (Cx.q[5+8*K.c[(i)*8+5]])
# define C6(K,i) (Cx.q[6+8*K.c[(i)*8+6]])
# define C7(K,i) (Cx.q[7+8*K.c[(i)*8+7]])
# endif
#else
# define N 2
# define LL(c0,c1,c2,c3,c4,c5,c6,c7) c0,c1,c2,c3,c4,c5,c6,c7, \
c0,c1,c2,c3,c4,c5,c6,c7
# define C0(K,i) (((u64*)(Cx.c+0))[2*K.c[(i)*8+0]])
# define C1(K,i) (((u64*)(Cx.c+7))[2*K.c[(i)*8+1]])
# define C2(K,i) (((u64*)(Cx.c+6))[2*K.c[(i)*8+2]])
# define C3(K,i) (((u64*)(Cx.c+5))[2*K.c[(i)*8+3]])
# define C4(K,i) (((u64*)(Cx.c+4))[2*K.c[(i)*8+4]])
# define C5(K,i) (((u64*)(Cx.c+3))[2*K.c[(i)*8+5]])
# define C6(K,i) (((u64*)(Cx.c+2))[2*K.c[(i)*8+6]])
# define C7(K,i) (((u64*)(Cx.c+1))[2*K.c[(i)*8+7]])
#endif
static const
union {
u8 c[(256*N+ROUNDS)*sizeof(u64)];
u64 q[(256*N+ROUNDS)];
} Cx = { {
/* Note endian-neutral representation:-) */
LL(0x18,0x18,0x60,0x18,0xc0,0x78,0x30,0xd8),
LL(0x23,0x23,0x8c,0x23,0x05,0xaf,0x46,0x26),
LL(0xc6,0xc6,0x3f,0xc6,0x7e,0xf9,0x91,0xb8),
LL(0xe8,0xe8,0x87,0xe8,0x13,0x6f,0xcd,0xfb),
LL(0x87,0x87,0x26,0x87,0x4c,0xa1,0x13,0xcb),
LL(0xb8,0xb8,0xda,0xb8,0xa9,0x62,0x6d,0x11),
LL(0x01,0x01,0x04,0x01,0x08,0x05,0x02,0x09),
LL(0x4f,0x4f,0x21,0x4f,0x42,0x6e,0x9e,0x0d),
LL(0x36,0x36,0xd8,0x36,0xad,0xee,0x6c,0x9b),
LL(0xa6,0xa6,0xa2,0xa6,0x59,0x04,0x51,0xff),
LL(0xd2,0xd2,0x6f,0xd2,0xde,0xbd,0xb9,0x0c),
LL(0xf5,0xf5,0xf3,0xf5,0xfb,0x06,0xf7,0x0e),
LL(0x79,0x79,0xf9,0x79,0xef,0x80,0xf2,0x96),
LL(0x6f,0x6f,0xa1,0x6f,0x5f,0xce,0xde,0x30),
LL(0x91,0x91,0x7e,0x91,0xfc,0xef,0x3f,0x6d),
LL(0x52,0x52,0x55,0x52,0xaa,0x07,0xa4,0xf8),
LL(0x60,0x60,0x9d,0x60,0x27,0xfd,0xc0,0x47),
LL(0xbc,0xbc,0xca,0xbc,0x89,0x76,0x65,0x35),
LL(0x9b,0x9b,0x56,0x9b,0xac,0xcd,0x2b,0x37),
LL(0x8e,0x8e,0x02,0x8e,0x04,0x8c,0x01,0x8a),
LL(0xa3,0xa3,0xb6,0xa3,0x71,0x15,0x5b,0xd2),
LL(0x0c,0x0c,0x30,0x0c,0x60,0x3c,0x18,0x6c),
LL(0x7b,0x7b,0xf1,0x7b,0xff,0x8a,0xf6,0x84),
LL(0x35,0x35,0xd4,0x35,0xb5,0xe1,0x6a,0x80),
LL(0x1d,0x1d,0x74,0x1d,0xe8,0x69,0x3a,0xf5),
LL(0xe0,0xe0,0xa7,0xe0,0x53,0x47,0xdd,0xb3),
LL(0xd7,0xd7,0x7b,0xd7,0xf6,0xac,0xb3,0x21),
LL(0xc2,0xc2,0x2f,0xc2,0x5e,0xed,0x99,0x9c),
LL(0x2e,0x2e,0xb8,0x2e,0x6d,0x96,0x5c,0x43),
LL(0x4b,0x4b,0x31,0x4b,0x62,0x7a,0x96,0x29),
LL(0xfe,0xfe,0xdf,0xfe,0xa3,0x21,0xe1,0x5d),
LL(0x57,0x57,0x41,0x57,0x82,0x16,0xae,0xd5),
LL(0x15,0x15,0x54,0x15,0xa8,0x41,0x2a,0xbd),
LL(0x77,0x77,0xc1,0x77,0x9f,0xb6,0xee,0xe8),
LL(0x37,0x37,0xdc,0x37,0xa5,0xeb,0x6e,0x92),
LL(0xe5,0xe5,0xb3,0xe5,0x7b,0x56,0xd7,0x9e),
LL(0x9f,0x9f,0x46,0x9f,0x8c,0xd9,0x23,0x13),
LL(0xf0,0xf0,0xe7,0xf0,0xd3,0x17,0xfd,0x23),
LL(0x4a,0x4a,0x35,0x4a,0x6a,0x7f,0x94,0x20),
LL(0xda,0xda,0x4f,0xda,0x9e,0x95,0xa9,0x44),
LL(0x58,0x58,0x7d,0x58,0xfa,0x25,0xb0,0xa2),
LL(0xc9,0xc9,0x03,0xc9,0x06,0xca,0x8f,0xcf),
LL(0x29,0x29,0xa4,0x29,0x55,0x8d,0x52,0x7c),
LL(0x0a,0x0a,0x28,0x0a,0x50,0x22,0x14,0x5a),
LL(0xb1,0xb1,0xfe,0xb1,0xe1,0x4f,0x7f,0x50),
LL(0xa0,0xa0,0xba,0xa0,0x69,0x1a,0x5d,0xc9),
LL(0x6b,0x6b,0xb1,0x6b,0x7f,0xda,0xd6,0x14),
LL(0x85,0x85,0x2e,0x85,0x5c,0xab,0x17,0xd9),
LL(0xbd,0xbd,0xce,0xbd,0x81,0x73,0x67,0x3c),
LL(0x5d,0x5d,0x69,0x5d,0xd2,0x34,0xba,0x8f),
LL(0x10,0x10,0x40,0x10,0x80,0x50,0x20,0x90),
LL(0xf4,0xf4,0xf7,0xf4,0xf3,0x03,0xf5,0x07),
LL(0xcb,0xcb,0x0b,0xcb,0x16,0xc0,0x8b,0xdd),
LL(0x3e,0x3e,0xf8,0x3e,0xed,0xc6,0x7c,0xd3),
LL(0x05,0x05,0x14,0x05,0x28,0x11,0x0a,0x2d),
LL(0x67,0x67,0x81,0x67,0x1f,0xe6,0xce,0x78),
LL(0xe4,0xe4,0xb7,0xe4,0x73,0x53,0xd5,0x97),
LL(0x27,0x27,0x9c,0x27,0x25,0xbb,0x4e,0x02),
LL(0x41,0x41,0x19,0x41,0x32,0x58,0x82,0x73),
LL(0x8b,0x8b,0x16,0x8b,0x2c,0x9d,0x0b,0xa7),
LL(0xa7,0xa7,0xa6,0xa7,0x51,0x01,0x53,0xf6),
LL(0x7d,0x7d,0xe9,0x7d,0xcf,0x94,0xfa,0xb2),
LL(0x95,0x95,0x6e,0x95,0xdc,0xfb,0x37,0x49),
LL(0xd8,0xd8,0x47,0xd8,0x8e,0x9f,0xad,0x56),
LL(0xfb,0xfb,0xcb,0xfb,0x8b,0x30,0xeb,0x70),
LL(0xee,0xee,0x9f,0xee,0x23,0x71,0xc1,0xcd),
LL(0x7c,0x7c,0xed,0x7c,0xc7,0x91,0xf8,0xbb),
LL(0x66,0x66,0x85,0x66,0x17,0xe3,0xcc,0x71),
LL(0xdd,0xdd,0x53,0xdd,0xa6,0x8e,0xa7,0x7b),
LL(0x17,0x17,0x5c,0x17,0xb8,0x4b,0x2e,0xaf),
LL(0x47,0x47,0x01,0x47,0x02,0x46,0x8e,0x45),
LL(0x9e,0x9e,0x42,0x9e,0x84,0xdc,0x21,0x1a),
LL(0xca,0xca,0x0f,0xca,0x1e,0xc5,0x89,0xd4),
LL(0x2d,0x2d,0xb4,0x2d,0x75,0x99,0x5a,0x58),
LL(0xbf,0xbf,0xc6,0xbf,0x91,0x79,0x63,0x2e),
LL(0x07,0x07,0x1c,0x07,0x38,0x1b,0x0e,0x3f),
LL(0xad,0xad,0x8e,0xad,0x01,0x23,0x47,0xac),
LL(0x5a,0x5a,0x75,0x5a,0xea,0x2f,0xb4,0xb0),
LL(0x83,0x83,0x36,0x83,0x6c,0xb5,0x1b,0xef),
LL(0x33,0x33,0xcc,0x33,0x85,0xff,0x66,0xb6),
LL(0x63,0x63,0x91,0x63,0x3f,0xf2,0xc6,0x5c),
LL(0x02,0x02,0x08,0x02,0x10,0x0a,0x04,0x12),
LL(0xaa,0xaa,0x92,0xaa,0x39,0x38,0x49,0x93),
LL(0x71,0x71,0xd9,0x71,0xaf,0xa8,0xe2,0xde),
LL(0xc8,0xc8,0x07,0xc8,0x0e,0xcf,0x8d,0xc6),
LL(0x19,0x19,0x64,0x19,0xc8,0x7d,0x32,0xd1),
LL(0x49,0x49,0x39,0x49,0x72,0x70,0x92,0x3b),
LL(0xd9,0xd9,0x43,0xd9,0x86,0x9a,0xaf,0x5f),
LL(0xf2,0xf2,0xef,0xf2,0xc3,0x1d,0xf9,0x31),
LL(0xe3,0xe3,0xab,0xe3,0x4b,0x48,0xdb,0xa8),
LL(0x5b,0x5b,0x71,0x5b,0xe2,0x2a,0xb6,0xb9),
LL(0x88,0x88,0x1a,0x88,0x34,0x92,0x0d,0xbc),
LL(0x9a,0x9a,0x52,0x9a,0xa4,0xc8,0x29,0x3e),
LL(0x26,0x26,0x98,0x26,0x2d,0xbe,0x4c,0x0b),
LL(0x32,0x32,0xc8,0x32,0x8d,0xfa,0x64,0xbf),
LL(0xb0,0xb0,0xfa,0xb0,0xe9,0x4a,0x7d,0x59),
LL(0xe9,0xe9,0x83,0xe9,0x1b,0x6a,0xcf,0xf2),
LL(0x0f,0x0f,0x3c,0x0f,0x78,0x33,0x1e,0x77),
LL(0xd5,0xd5,0x73,0xd5,0xe6,0xa6,0xb7,0x33),
LL(0x80,0x80,0x3a,0x80,0x74,0xba,0x1d,0xf4),
LL(0xbe,0xbe,0xc2,0xbe,0x99,0x7c,0x61,0x27),
LL(0xcd,0xcd,0x13,0xcd,0x26,0xde,0x87,0xeb),
LL(0x34,0x34,0xd0,0x34,0xbd,0xe4,0x68,0x89),
LL(0x48,0x48,0x3d,0x48,0x7a,0x75,0x90,0x32),
LL(0xff,0xff,0xdb,0xff,0xab,0x24,0xe3,0x54),
LL(0x7a,0x7a,0xf5,0x7a,0xf7,0x8f,0xf4,0x8d),
LL(0x90,0x90,0x7a,0x90,0xf4,0xea,0x3d,0x64),
LL(0x5f,0x5f,0x61,0x5f,0xc2,0x3e,0xbe,0x9d),
LL(0x20,0x20,0x80,0x20,0x1d,0xa0,0x40,0x3d),
LL(0x68,0x68,0xbd,0x68,0x67,0xd5,0xd0,0x0f),
LL(0x1a,0x1a,0x68,0x1a,0xd0,0x72,0x34,0xca),
LL(0xae,0xae,0x82,0xae,0x19,0x2c,0x41,0xb7),
LL(0xb4,0xb4,0xea,0xb4,0xc9,0x5e,0x75,0x7d),
LL(0x54,0x54,0x4d,0x54,0x9a,0x19,0xa8,0xce),
LL(0x93,0x93,0x76,0x93,0xec,0xe5,0x3b,0x7f),
LL(0x22,0x22,0x88,0x22,0x0d,0xaa,0x44,0x2f),
LL(0x64,0x64,0x8d,0x64,0x07,0xe9,0xc8,0x63),
LL(0xf1,0xf1,0xe3,0xf1,0xdb,0x12,0xff,0x2a),
LL(0x73,0x73,0xd1,0x73,0xbf,0xa2,0xe6,0xcc),
LL(0x12,0x12,0x48,0x12,0x90,0x5a,0x24,0x82),
LL(0x40,0x40,0x1d,0x40,0x3a,0x5d,0x80,0x7a),
LL(0x08,0x08,0x20,0x08,0x40,0x28,0x10,0x48),
LL(0xc3,0xc3,0x2b,0xc3,0x56,0xe8,0x9b,0x95),
LL(0xec,0xec,0x97,0xec,0x33,0x7b,0xc5,0xdf),
LL(0xdb,0xdb,0x4b,0xdb,0x96,0x90,0xab,0x4d),
LL(0xa1,0xa1,0xbe,0xa1,0x61,0x1f,0x5f,0xc0),
LL(0x8d,0x8d,0x0e,0x8d,0x1c,0x83,0x07,0x91),
LL(0x3d,0x3d,0xf4,0x3d,0xf5,0xc9,0x7a,0xc8),
LL(0x97,0x97,0x66,0x97,0xcc,0xf1,0x33,0x5b),
LL(0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00),
LL(0xcf,0xcf,0x1b,0xcf,0x36,0xd4,0x83,0xf9),
LL(0x2b,0x2b,0xac,0x2b,0x45,0x87,0x56,0x6e),
LL(0x76,0x76,0xc5,0x76,0x97,0xb3,0xec,0xe1),
LL(0x82,0x82,0x32,0x82,0x64,0xb0,0x19,0xe6),
LL(0xd6,0xd6,0x7f,0xd6,0xfe,0xa9,0xb1,0x28),
LL(0x1b,0x1b,0x6c,0x1b,0xd8,0x77,0x36,0xc3),
LL(0xb5,0xb5,0xee,0xb5,0xc1,0x5b,0x77,0x74),
LL(0xaf,0xaf,0x86,0xaf,0x11,0x29,0x43,0xbe),
LL(0x6a,0x6a,0xb5,0x6a,0x77,0xdf,0xd4,0x1d),
LL(0x50,0x50,0x5d,0x50,0xba,0x0d,0xa0,0xea),
LL(0x45,0x45,0x09,0x45,0x12,0x4c,0x8a,0x57),
LL(0xf3,0xf3,0xeb,0xf3,0xcb,0x18,0xfb,0x38),
LL(0x30,0x30,0xc0,0x30,0x9d,0xf0,0x60,0xad),
LL(0xef,0xef,0x9b,0xef,0x2b,0x74,0xc3,0xc4),
LL(0x3f,0x3f,0xfc,0x3f,0xe5,0xc3,0x7e,0xda),
LL(0x55,0x55,0x49,0x55,0x92,0x1c,0xaa,0xc7),
LL(0xa2,0xa2,0xb2,0xa2,0x79,0x10,0x59,0xdb),
LL(0xea,0xea,0x8f,0xea,0x03,0x65,0xc9,0xe9),
LL(0x65,0x65,0x89,0x65,0x0f,0xec,0xca,0x6a),
LL(0xba,0xba,0xd2,0xba,0xb9,0x68,0x69,0x03),
LL(0x2f,0x2f,0xbc,0x2f,0x65,0x93,0x5e,0x4a),
LL(0xc0,0xc0,0x27,0xc0,0x4e,0xe7,0x9d,0x8e),
LL(0xde,0xde,0x5f,0xde,0xbe,0x81,0xa1,0x60),
LL(0x1c,0x1c,0x70,0x1c,0xe0,0x6c,0x38,0xfc),
LL(0xfd,0xfd,0xd3,0xfd,0xbb,0x2e,0xe7,0x46),
LL(0x4d,0x4d,0x29,0x4d,0x52,0x64,0x9a,0x1f),
LL(0x92,0x92,0x72,0x92,0xe4,0xe0,0x39,0x76),
LL(0x75,0x75,0xc9,0x75,0x8f,0xbc,0xea,0xfa),
LL(0x06,0x06,0x18,0x06,0x30,0x1e,0x0c,0x36),
LL(0x8a,0x8a,0x12,0x8a,0x24,0x98,0x09,0xae),
LL(0xb2,0xb2,0xf2,0xb2,0xf9,0x40,0x79,0x4b),
LL(0xe6,0xe6,0xbf,0xe6,0x63,0x59,0xd1,0x85),
LL(0x0e,0x0e,0x38,0x0e,0x70,0x36,0x1c,0x7e),
LL(0x1f,0x1f,0x7c,0x1f,0xf8,0x63,0x3e,0xe7),
LL(0x62,0x62,0x95,0x62,0x37,0xf7,0xc4,0x55),
LL(0xd4,0xd4,0x77,0xd4,0xee,0xa3,0xb5,0x3a),
LL(0xa8,0xa8,0x9a,0xa8,0x29,0x32,0x4d,0x81),
LL(0x96,0x96,0x62,0x96,0xc4,0xf4,0x31,0x52),
LL(0xf9,0xf9,0xc3,0xf9,0x9b,0x3a,0xef,0x62),
LL(0xc5,0xc5,0x33,0xc5,0x66,0xf6,0x97,0xa3),
LL(0x25,0x25,0x94,0x25,0x35,0xb1,0x4a,0x10),
LL(0x59,0x59,0x79,0x59,0xf2,0x20,0xb2,0xab),
LL(0x84,0x84,0x2a,0x84,0x54,0xae,0x15,0xd0),
LL(0x72,0x72,0xd5,0x72,0xb7,0xa7,0xe4,0xc5),
LL(0x39,0x39,0xe4,0x39,0xd5,0xdd,0x72,0xec),
LL(0x4c,0x4c,0x2d,0x4c,0x5a,0x61,0x98,0x16),
LL(0x5e,0x5e,0x65,0x5e,0xca,0x3b,0xbc,0x94),
LL(0x78,0x78,0xfd,0x78,0xe7,0x85,0xf0,0x9f),
LL(0x38,0x38,0xe0,0x38,0xdd,0xd8,0x70,0xe5),
LL(0x8c,0x8c,0x0a,0x8c,0x14,0x86,0x05,0x98),
LL(0xd1,0xd1,0x63,0xd1,0xc6,0xb2,0xbf,0x17),
LL(0xa5,0xa5,0xae,0xa5,0x41,0x0b,0x57,0xe4),
LL(0xe2,0xe2,0xaf,0xe2,0x43,0x4d,0xd9,0xa1),
LL(0x61,0x61,0x99,0x61,0x2f,0xf8,0xc2,0x4e),
LL(0xb3,0xb3,0xf6,0xb3,0xf1,0x45,0x7b,0x42),
LL(0x21,0x21,0x84,0x21,0x15,0xa5,0x42,0x34),
LL(0x9c,0x9c,0x4a,0x9c,0x94,0xd6,0x25,0x08),
LL(0x1e,0x1e,0x78,0x1e,0xf0,0x66,0x3c,0xee),
LL(0x43,0x43,0x11,0x43,0x22,0x52,0x86,0x61),
LL(0xc7,0xc7,0x3b,0xc7,0x76,0xfc,0x93,0xb1),
LL(0xfc,0xfc,0xd7,0xfc,0xb3,0x2b,0xe5,0x4f),
LL(0x04,0x04,0x10,0x04,0x20,0x14,0x08,0x24),
LL(0x51,0x51,0x59,0x51,0xb2,0x08,0xa2,0xe3),
LL(0x99,0x99,0x5e,0x99,0xbc,0xc7,0x2f,0x25),
LL(0x6d,0x6d,0xa9,0x6d,0x4f,0xc4,0xda,0x22),
LL(0x0d,0x0d,0x34,0x0d,0x68,0x39,0x1a,0x65),
LL(0xfa,0xfa,0xcf,0xfa,0x83,0x35,0xe9,0x79),
LL(0xdf,0xdf,0x5b,0xdf,0xb6,0x84,0xa3,0x69),
LL(0x7e,0x7e,0xe5,0x7e,0xd7,0x9b,0xfc,0xa9),
LL(0x24,0x24,0x90,0x24,0x3d,0xb4,0x48,0x19),
LL(0x3b,0x3b,0xec,0x3b,0xc5,0xd7,0x76,0xfe),
LL(0xab,0xab,0x96,0xab,0x31,0x3d,0x4b,0x9a),
LL(0xce,0xce,0x1f,0xce,0x3e,0xd1,0x81,0xf0),
LL(0x11,0x11,0x44,0x11,0x88,0x55,0x22,0x99),
LL(0x8f,0x8f,0x06,0x8f,0x0c,0x89,0x03,0x83),
LL(0x4e,0x4e,0x25,0x4e,0x4a,0x6b,0x9c,0x04),
LL(0xb7,0xb7,0xe6,0xb7,0xd1,0x51,0x73,0x66),
LL(0xeb,0xeb,0x8b,0xeb,0x0b,0x60,0xcb,0xe0),
LL(0x3c,0x3c,0xf0,0x3c,0xfd,0xcc,0x78,0xc1),
LL(0x81,0x81,0x3e,0x81,0x7c,0xbf,0x1f,0xfd),
LL(0x94,0x94,0x6a,0x94,0xd4,0xfe,0x35,0x40),
LL(0xf7,0xf7,0xfb,0xf7,0xeb,0x0c,0xf3,0x1c),
LL(0xb9,0xb9,0xde,0xb9,0xa1,0x67,0x6f,0x18),
LL(0x13,0x13,0x4c,0x13,0x98,0x5f,0x26,0x8b),
LL(0x2c,0x2c,0xb0,0x2c,0x7d,0x9c,0x58,0x51),
LL(0xd3,0xd3,0x6b,0xd3,0xd6,0xb8,0xbb,0x05),
LL(0xe7,0xe7,0xbb,0xe7,0x6b,0x5c,0xd3,0x8c),
LL(0x6e,0x6e,0xa5,0x6e,0x57,0xcb,0xdc,0x39),
LL(0xc4,0xc4,0x37,0xc4,0x6e,0xf3,0x95,0xaa),
LL(0x03,0x03,0x0c,0x03,0x18,0x0f,0x06,0x1b),
LL(0x56,0x56,0x45,0x56,0x8a,0x13,0xac,0xdc),
LL(0x44,0x44,0x0d,0x44,0x1a,0x49,0x88,0x5e),
LL(0x7f,0x7f,0xe1,0x7f,0xdf,0x9e,0xfe,0xa0),
LL(0xa9,0xa9,0x9e,0xa9,0x21,0x37,0x4f,0x88),
LL(0x2a,0x2a,0xa8,0x2a,0x4d,0x82,0x54,0x67),
LL(0xbb,0xbb,0xd6,0xbb,0xb1,0x6d,0x6b,0x0a),
LL(0xc1,0xc1,0x23,0xc1,0x46,0xe2,0x9f,0x87),
LL(0x53,0x53,0x51,0x53,0xa2,0x02,0xa6,0xf1),
LL(0xdc,0xdc,0x57,0xdc,0xae,0x8b,0xa5,0x72),
LL(0x0b,0x0b,0x2c,0x0b,0x58,0x27,0x16,0x53),
LL(0x9d,0x9d,0x4e,0x9d,0x9c,0xd3,0x27,0x01),
LL(0x6c,0x6c,0xad,0x6c,0x47,0xc1,0xd8,0x2b),
LL(0x31,0x31,0xc4,0x31,0x95,0xf5,0x62,0xa4),
LL(0x74,0x74,0xcd,0x74,0x87,0xb9,0xe8,0xf3),
LL(0xf6,0xf6,0xff,0xf6,0xe3,0x09,0xf1,0x15),
LL(0x46,0x46,0x05,0x46,0x0a,0x43,0x8c,0x4c),
LL(0xac,0xac,0x8a,0xac,0x09,0x26,0x45,0xa5),
LL(0x89,0x89,0x1e,0x89,0x3c,0x97,0x0f,0xb5),
LL(0x14,0x14,0x50,0x14,0xa0,0x44,0x28,0xb4),
LL(0xe1,0xe1,0xa3,0xe1,0x5b,0x42,0xdf,0xba),
LL(0x16,0x16,0x58,0x16,0xb0,0x4e,0x2c,0xa6),
LL(0x3a,0x3a,0xe8,0x3a,0xcd,0xd2,0x74,0xf7),
LL(0x69,0x69,0xb9,0x69,0x6f,0xd0,0xd2,0x06),
LL(0x09,0x09,0x24,0x09,0x48,0x2d,0x12,0x41),
LL(0x70,0x70,0xdd,0x70,0xa7,0xad,0xe0,0xd7),
LL(0xb6,0xb6,0xe2,0xb6,0xd9,0x54,0x71,0x6f),
LL(0xd0,0xd0,0x67,0xd0,0xce,0xb7,0xbd,0x1e),
LL(0xed,0xed,0x93,0xed,0x3b,0x7e,0xc7,0xd6),
LL(0xcc,0xcc,0x17,0xcc,0x2e,0xdb,0x85,0xe2),
LL(0x42,0x42,0x15,0x42,0x2a,0x57,0x84,0x68),
LL(0x98,0x98,0x5a,0x98,0xb4,0xc2,0x2d,0x2c),
LL(0xa4,0xa4,0xaa,0xa4,0x49,0x0e,0x55,0xed),
LL(0x28,0x28,0xa0,0x28,0x5d,0x88,0x50,0x75),
LL(0x5c,0x5c,0x6d,0x5c,0xda,0x31,0xb8,0x86),
LL(0xf8,0xf8,0xc7,0xf8,0x93,0x3f,0xed,0x6b),
LL(0x86,0x86,0x22,0x86,0x44,0xa4,0x11,0xc2),
#define RC (&(Cx.q[256*N]))
0x18,0x23,0xc6,0xe8,0x87,0xb8,0x01,0x4f, /* rc[ROUNDS] */
0x36,0xa6,0xd2,0xf5,0x79,0x6f,0x91,0x52,
0x60,0xbc,0x9b,0x8e,0xa3,0x0c,0x7b,0x35,
0x1d,0xe0,0xd7,0xc2,0x2e,0x4b,0xfe,0x57,
0x15,0x77,0x37,0xe5,0x9f,0xf0,0x4a,0xda,
0x58,0xc9,0x29,0x0a,0xb1,0xa0,0x6b,0x85,
0xbd,0x5d,0x10,0xf4,0xcb,0x3e,0x05,0x67,
0xe4,0x27,0x41,0x8b,0xa7,0x7d,0x95,0xd8,
0xfb,0xee,0x7c,0x66,0xdd,0x17,0x47,0x9e,
0xca,0x2d,0xbf,0x07,0xad,0x5a,0x83,0x33
}
};
void whirlpool_block(WHIRLPOOL_CTX *ctx,const void *inp,size_t n)
{
int r;
const u8 *p=inp;
union { u64 q[8]; u8 c[64]; } S,K,*H=(void *)ctx->H.q;
#ifdef GO_FOR_MMX
GO_FOR_MMX(ctx,inp,n);
#endif
do {
#ifdef OPENSSL_SMALL_FOOTPRINT
u64 L[8];
int i;
for (i=0;i<64;i++) S.c[i] = (K.c[i] = H->c[i]) ^ p[i];
for (r=0;r<ROUNDS;r++)
{
for (i=0;i<8;i++)
{
L[i] = i ? 0 : RC[r];
L[i] ^= C0(K,i) ^ C1(K,(i-1)&7) ^
C2(K,(i-2)&7) ^ C3(K,(i-3)&7) ^
C4(K,(i-4)&7) ^ C5(K,(i-5)&7) ^
C6(K,(i-6)&7) ^ C7(K,(i-7)&7);
}
memcpy (K.q,L,64);
for (i=0;i<8;i++)
{
L[i] ^= C0(S,i) ^ C1(S,(i-1)&7) ^
C2(S,(i-2)&7) ^ C3(S,(i-3)&7) ^
C4(S,(i-4)&7) ^ C5(S,(i-5)&7) ^
C6(S,(i-6)&7) ^ C7(S,(i-7)&7);
}
memcpy (S.q,L,64);
}
for (i=0;i<64;i++) H->c[i] ^= S.c[i] ^ p[i];
#else
u64 L0,L1,L2,L3,L4,L5,L6,L7;
#ifdef STRICT_ALIGNMENT
if ((size_t)p & 7)
{
memcpy (S.c,p,64);
S.q[0] ^= (K.q[0] = H->q[0]);
S.q[1] ^= (K.q[1] = H->q[1]);
S.q[2] ^= (K.q[2] = H->q[2]);
S.q[3] ^= (K.q[3] = H->q[3]);
S.q[4] ^= (K.q[4] = H->q[4]);
S.q[5] ^= (K.q[5] = H->q[5]);
S.q[6] ^= (K.q[6] = H->q[6]);
S.q[7] ^= (K.q[7] = H->q[7]);
}
else
#endif
{
const u64 *pa = (const u64*)p;
S.q[0] = (K.q[0] = H->q[0]) ^ pa[0];
S.q[1] = (K.q[1] = H->q[1]) ^ pa[1];
S.q[2] = (K.q[2] = H->q[2]) ^ pa[2];
S.q[3] = (K.q[3] = H->q[3]) ^ pa[3];
S.q[4] = (K.q[4] = H->q[4]) ^ pa[4];
S.q[5] = (K.q[5] = H->q[5]) ^ pa[5];
S.q[6] = (K.q[6] = H->q[6]) ^ pa[6];
S.q[7] = (K.q[7] = H->q[7]) ^ pa[7];
}
for(r=0;r<ROUNDS;r++)
{
#ifdef SMALL_REGISTER_BANK
L0 = C0(K,0) ^ C1(K,7) ^ C2(K,6) ^ C3(K,5) ^
C4(K,4) ^ C5(K,3) ^ C6(K,2) ^ C7(K,1) ^ RC[r];
L1 = C0(K,1) ^ C1(K,0) ^ C2(K,7) ^ C3(K,6) ^
C4(K,5) ^ C5(K,4) ^ C6(K,3) ^ C7(K,2);
L2 = C0(K,2) ^ C1(K,1) ^ C2(K,0) ^ C3(K,7) ^
C4(K,6) ^ C5(K,5) ^ C6(K,4) ^ C7(K,3);
L3 = C0(K,3) ^ C1(K,2) ^ C2(K,1) ^ C3(K,0) ^
C4(K,7) ^ C5(K,6) ^ C6(K,5) ^ C7(K,4);
L4 = C0(K,4) ^ C1(K,3) ^ C2(K,2) ^ C3(K,1) ^
C4(K,0) ^ C5(K,7) ^ C6(K,6) ^ C7(K,5);
L5 = C0(K,5) ^ C1(K,4) ^ C2(K,3) ^ C3(K,2) ^
C4(K,1) ^ C5(K,0) ^ C6(K,7) ^ C7(K,6);
L6 = C0(K,6) ^ C1(K,5) ^ C2(K,4) ^ C3(K,3) ^
C4(K,2) ^ C5(K,1) ^ C6(K,0) ^ C7(K,7);
L7 = C0(K,7) ^ C1(K,6) ^ C2(K,5) ^ C3(K,4) ^
C4(K,3) ^ C5(K,2) ^ C6(K,1) ^ C7(K,0);
K.q[0] = L0; K.q[1] = L1; K.q[2] = L2; K.q[3] = L3;
K.q[4] = L4; K.q[5] = L5; K.q[6] = L6; K.q[7] = L7;
L0 ^= C0(S,0) ^ C1(S,7) ^ C2(S,6) ^ C3(S,5) ^
C4(S,4) ^ C5(S,3) ^ C6(S,2) ^ C7(S,1);
L1 ^= C0(S,1) ^ C1(S,0) ^ C2(S,7) ^ C3(S,6) ^
C4(S,5) ^ C5(S,4) ^ C6(S,3) ^ C7(S,2);
L2 ^= C0(S,2) ^ C1(S,1) ^ C2(S,0) ^ C3(S,7) ^
C4(S,6) ^ C5(S,5) ^ C6(S,4) ^ C7(S,3);
L3 ^= C0(S,3) ^ C1(S,2) ^ C2(S,1) ^ C3(S,0) ^
C4(S,7) ^ C5(S,6) ^ C6(S,5) ^ C7(S,4);
L4 ^= C0(S,4) ^ C1(S,3) ^ C2(S,2) ^ C3(S,1) ^
C4(S,0) ^ C5(S,7) ^ C6(S,6) ^ C7(S,5);
L5 ^= C0(S,5) ^ C1(S,4) ^ C2(S,3) ^ C3(S,2) ^
C4(S,1) ^ C5(S,0) ^ C6(S,7) ^ C7(S,6);
L6 ^= C0(S,6) ^ C1(S,5) ^ C2(S,4) ^ C3(S,3) ^
C4(S,2) ^ C5(S,1) ^ C6(S,0) ^ C7(S,7);
L7 ^= C0(S,7) ^ C1(S,6) ^ C2(S,5) ^ C3(S,4) ^
C4(S,3) ^ C5(S,2) ^ C6(S,1) ^ C7(S,0);
S.q[0] = L0; S.q[1] = L1; S.q[2] = L2; S.q[3] = L3;
S.q[4] = L4; S.q[5] = L5; S.q[6] = L6; S.q[7] = L7;
#else
L0 = C0(K,0); L1 = C1(K,0); L2 = C2(K,0); L3 = C3(K,0);
L4 = C4(K,0); L5 = C5(K,0); L6 = C6(K,0); L7 = C7(K,0);
L0 ^= RC[r];
L1 ^= C0(K,1); L2 ^= C1(K,1); L3 ^= C2(K,1); L4 ^= C3(K,1);
L5 ^= C4(K,1); L6 ^= C5(K,1); L7 ^= C6(K,1); L0 ^= C7(K,1);
L2 ^= C0(K,2); L3 ^= C1(K,2); L4 ^= C2(K,2); L5 ^= C3(K,2);
L6 ^= C4(K,2); L7 ^= C5(K,2); L0 ^= C6(K,2); L1 ^= C7(K,2);
L3 ^= C0(K,3); L4 ^= C1(K,3); L5 ^= C2(K,3); L6 ^= C3(K,3);
L7 ^= C4(K,3); L0 ^= C5(K,3); L1 ^= C6(K,3); L2 ^= C7(K,3);
L4 ^= C0(K,4); L5 ^= C1(K,4); L6 ^= C2(K,4); L7 ^= C3(K,4);
L0 ^= C4(K,4); L1 ^= C5(K,4); L2 ^= C6(K,4); L3 ^= C7(K,4);
L5 ^= C0(K,5); L6 ^= C1(K,5); L7 ^= C2(K,5); L0 ^= C3(K,5);
L1 ^= C4(K,5); L2 ^= C5(K,5); L3 ^= C6(K,5); L4 ^= C7(K,5);
L6 ^= C0(K,6); L7 ^= C1(K,6); L0 ^= C2(K,6); L1 ^= C3(K,6);
L2 ^= C4(K,6); L3 ^= C5(K,6); L4 ^= C6(K,6); L5 ^= C7(K,6);
L7 ^= C0(K,7); L0 ^= C1(K,7); L1 ^= C2(K,7); L2 ^= C3(K,7);
L3 ^= C4(K,7); L4 ^= C5(K,7); L5 ^= C6(K,7); L6 ^= C7(K,7);
K.q[0] = L0; K.q[1] = L1; K.q[2] = L2; K.q[3] = L3;
K.q[4] = L4; K.q[5] = L5; K.q[6] = L6; K.q[7] = L7;
L0 ^= C0(S,0); L1 ^= C1(S,0); L2 ^= C2(S,0); L3 ^= C3(S,0);
L4 ^= C4(S,0); L5 ^= C5(S,0); L6 ^= C6(S,0); L7 ^= C7(S,0);
L1 ^= C0(S,1); L2 ^= C1(S,1); L3 ^= C2(S,1); L4 ^= C3(S,1);
L5 ^= C4(S,1); L6 ^= C5(S,1); L7 ^= C6(S,1); L0 ^= C7(S,1);
L2 ^= C0(S,2); L3 ^= C1(S,2); L4 ^= C2(S,2); L5 ^= C3(S,2);
L6 ^= C4(S,2); L7 ^= C5(S,2); L0 ^= C6(S,2); L1 ^= C7(S,2);
L3 ^= C0(S,3); L4 ^= C1(S,3); L5 ^= C2(S,3); L6 ^= C3(S,3);
L7 ^= C4(S,3); L0 ^= C5(S,3); L1 ^= C6(S,3); L2 ^= C7(S,3);
L4 ^= C0(S,4); L5 ^= C1(S,4); L6 ^= C2(S,4); L7 ^= C3(S,4);
L0 ^= C4(S,4); L1 ^= C5(S,4); L2 ^= C6(S,4); L3 ^= C7(S,4);
L5 ^= C0(S,5); L6 ^= C1(S,5); L7 ^= C2(S,5); L0 ^= C3(S,5);
L1 ^= C4(S,5); L2 ^= C5(S,5); L3 ^= C6(S,5); L4 ^= C7(S,5);
L6 ^= C0(S,6); L7 ^= C1(S,6); L0 ^= C2(S,6); L1 ^= C3(S,6);
L2 ^= C4(S,6); L3 ^= C5(S,6); L4 ^= C6(S,6); L5 ^= C7(S,6);
L7 ^= C0(S,7); L0 ^= C1(S,7); L1 ^= C2(S,7); L2 ^= C3(S,7);
L3 ^= C4(S,7); L4 ^= C5(S,7); L5 ^= C6(S,7); L6 ^= C7(S,7);
S.q[0] = L0; S.q[1] = L1; S.q[2] = L2; S.q[3] = L3;
S.q[4] = L4; S.q[5] = L5; S.q[6] = L6; S.q[7] = L7;
#endif
}
#ifdef STRICT_ALIGNMENT
if ((size_t)p & 7)
{
int i;
for(i=0;i<64;i++) H->c[i] ^= S.c[i] ^ p[i];
}
else
#endif
{
const u64 *pa=(const u64 *)p;
H->q[0] ^= S.q[0] ^ pa[0];
H->q[1] ^= S.q[1] ^ pa[1];
H->q[2] ^= S.q[2] ^ pa[2];
H->q[3] ^= S.q[3] ^ pa[3];
H->q[4] ^= S.q[4] ^ pa[4];
H->q[5] ^= S.q[5] ^ pa[5];
H->q[6] ^= S.q[6] ^ pa[6];
H->q[7] ^= S.q[7] ^ pa[7];
}
#endif
p += 64;
} while(--n);
}
|
gpl-3.0
|
gzzhanghao/shadowsocks-android
|
src/main/jni/openssl/crypto/evp/m_sha.c
|
538
|
3996
|
/* crypto/evp/m_sha.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 "cryptlib.h"
#if !defined(OPENSSL_NO_SHA) && !defined(OPENSSL_NO_SHA0)
#include <openssl/evp.h>
#include <openssl/objects.h>
#include <openssl/x509.h>
#ifndef OPENSSL_NO_RSA
#include <openssl/rsa.h>
#endif
#include "evp_locl.h"
static int init(EVP_MD_CTX *ctx)
{ return SHA_Init(ctx->md_data); }
static int update(EVP_MD_CTX *ctx,const void *data,size_t count)
{ return SHA_Update(ctx->md_data,data,count); }
static int final(EVP_MD_CTX *ctx,unsigned char *md)
{ return SHA_Final(md,ctx->md_data); }
static const EVP_MD sha_md=
{
NID_sha,
NID_shaWithRSAEncryption,
SHA_DIGEST_LENGTH,
0,
init,
update,
final,
NULL,
NULL,
EVP_PKEY_RSA_method,
SHA_CBLOCK,
sizeof(EVP_MD *)+sizeof(SHA_CTX),
};
const EVP_MD *EVP_sha(void)
{
return(&sha_md);
}
#endif
|
gpl-3.0
|
jguille2/SA5
|
ArduinoFiles/libraries/IRremote/ir_Sanyo.cpp
|
33
|
2698
|
#include "IRremote.h"
#include "IRremoteInt.h"
//==============================================================================
// SSSS AAA N N Y Y OOO
// S A A NN N Y Y O O
// SSS AAAAA N N N Y O O
// S A A N NN Y O O
// SSSS A A N N Y OOO
//==============================================================================
// I think this is a Sanyo decoder: Serial = SA 8650B
// Looks like Sony except for timings, 48 chars of data and time/space different
#define SANYO_BITS 12
#define SANYO_HDR_MARK 3500 // seen range 3500
#define SANYO_HDR_SPACE 950 // seen 950
#define SANYO_ONE_MARK 2400 // seen 2400
#define SANYO_ZERO_MARK 700 // seen 700
#define SANYO_DOUBLE_SPACE_USECS 800 // usually ssee 713 - not using ticks as get number wrapround
#define SANYO_RPT_LENGTH 45000
//+=============================================================================
#if DECODE_SANYO
bool IRrecv::decodeSanyo (decode_results *results)
{
long data = 0;
int offset = 0; // Skip first space <-- CHECK THIS!
if (irparams.rawlen < (2 * SANYO_BITS) + 2) return false ;
#if 0
// Put this back in for debugging - note can't use #DEBUG as if Debug on we don't see the repeat cos of the delay
Serial.print("IR Gap: ");
Serial.println( results->rawbuf[offset]);
Serial.println( "test against:");
Serial.println(results->rawbuf[offset]);
#endif
// Initial space
if (results->rawbuf[offset] < SANYO_DOUBLE_SPACE_USECS) {
//Serial.print("IR Gap found: ");
results->bits = 0;
results->value = REPEAT;
results->decode_type = SANYO;
return true;
}
offset++;
// Initial mark
if (!MATCH_MARK(results->rawbuf[offset++], SANYO_HDR_MARK)) return false ;
// Skip Second Mark
if (!MATCH_MARK(results->rawbuf[offset++], SANYO_HDR_MARK)) return false ;
while (offset + 1 < irparams.rawlen) {
if (!MATCH_SPACE(results->rawbuf[offset++], SANYO_HDR_SPACE)) break ;
if (MATCH_MARK(results->rawbuf[offset], SANYO_ONE_MARK)) data = (data << 1) | 1 ;
else if (MATCH_MARK(results->rawbuf[offset], SANYO_ZERO_MARK)) data = (data << 1) | 0 ;
else return false ;
offset++;
}
// Success
results->bits = (offset - 1) / 2;
if (results->bits < 12) {
results->bits = 0;
return false;
}
results->value = data;
results->decode_type = SANYO;
return true;
}
#endif
|
gpl-3.0
|
javierag/samba
|
lib/tdb/test/run-check.c
|
40
|
1672
|
#include "../common/tdb_private.h"
#include "../common/io.c"
#include "../common/tdb.c"
#include "../common/lock.c"
#include "../common/freelist.c"
#include "../common/traverse.c"
#include "../common/transaction.c"
#include "../common/error.c"
#include "../common/open.c"
#include "../common/check.c"
#include "../common/hash.c"
#include "../common/mutex.c"
#include "tap-interface.h"
#include <stdlib.h>
#include "logging.h"
int main(int argc, char *argv[])
{
struct tdb_context *tdb;
TDB_DATA key, data;
plan_tests(13);
tdb = tdb_open_ex("run-check.tdb", 1, TDB_CLEAR_IF_FIRST,
O_CREAT|O_TRUNC|O_RDWR, 0600, &taplogctx, NULL);
ok1(tdb);
ok1(tdb_check(tdb, NULL, NULL) == 0);
key.dsize = strlen("hi");
key.dptr = discard_const_p(uint8_t, "hi");
data.dsize = strlen("world");
data.dptr = discard_const_p(uint8_t, "world");
ok1(tdb_store(tdb, key, data, TDB_INSERT) == 0);
ok1(tdb_check(tdb, NULL, NULL) == 0);
tdb_close(tdb);
tdb = tdb_open_ex("run-check.tdb", 1024, 0, O_RDWR, 0,
&taplogctx, NULL);
ok1(tdb);
ok1(tdb_check(tdb, NULL, NULL) == 0);
tdb_close(tdb);
tdb = tdb_open_ex("test/tdb.corrupt", 1024, 0, O_RDWR, 0,
&taplogctx, NULL);
ok1(tdb);
ok1(tdb_check(tdb, NULL, NULL) == -1);
ok1(tdb_error(tdb) == TDB_ERR_CORRUPT);
tdb_close(tdb);
/* Big and little endian should work! */
tdb = tdb_open_ex("test/old-nohash-le.tdb", 1024, 0, O_RDWR, 0,
&taplogctx, NULL);
ok1(tdb);
ok1(tdb_check(tdb, NULL, NULL) == 0);
tdb_close(tdb);
tdb = tdb_open_ex("test/old-nohash-be.tdb", 1024, 0, O_RDWR, 0,
&taplogctx, NULL);
ok1(tdb);
ok1(tdb_check(tdb, NULL, NULL) == 0);
tdb_close(tdb);
return exit_status();
}
|
gpl-3.0
|
vedderb/nrf24l01plus_stm32f100_chibios
|
ChibiOS_2.6.6/testhal/STM32L1xx/ADC/main.c
|
41
|
4570
|
/*
ChibiOS/RT - Copyright (C) 2006-2013 Giovanni Di Sirio
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "ch.h"
#include "hal.h"
#define ADC_GRP1_NUM_CHANNELS 1
#define ADC_GRP1_BUF_DEPTH 8
#define ADC_GRP2_NUM_CHANNELS 8
#define ADC_GRP2_BUF_DEPTH 16
static adcsample_t samples1[ADC_GRP1_NUM_CHANNELS * ADC_GRP1_BUF_DEPTH];
static adcsample_t samples2[ADC_GRP2_NUM_CHANNELS * ADC_GRP2_BUF_DEPTH];
/*
* ADC streaming callback.
*/
size_t nx = 0, ny = 0;
static void adccallback(ADCDriver *adcp, adcsample_t *buffer, size_t n) {
(void)adcp;
if (samples2 == buffer) {
nx += n;
}
else {
ny += n;
}
}
static void adcerrorcallback(ADCDriver *adcp, adcerror_t err) {
(void)adcp;
(void)err;
}
/*
* ADC conversion group.
* Mode: Linear buffer, 8 samples of 1 channel, SW triggered.
* Channels: IN10.
*/
static const ADCConversionGroup adcgrpcfg1 = {
FALSE,
ADC_GRP1_NUM_CHANNELS,
NULL,
adcerrorcallback,
0, /* CR1 */
ADC_CR2_SWSTART, /* CR2 */
0, /* SMPR1 */
ADC_SMPR2_SMP_AN10(ADC_SAMPLE_4),
0, /* SMPR3 */
ADC_SQR1_NUM_CH(ADC_GRP1_NUM_CHANNELS),
0, 0, 0, /* SQR2, SQR3, SQR4 */
ADC_SQR5_SQ1_N(ADC_CHANNEL_IN10)
};
/*
* ADC conversion group.
* Mode: Continuous, 16 samples of 8 channels, SW triggered.
* Channels: IN10, IN11, IN10, IN11, IN10, IN11, Sensor, VRef.
*/
static const ADCConversionGroup adcgrpcfg2 = {
TRUE,
ADC_GRP2_NUM_CHANNELS,
adccallback,
adcerrorcallback,
0, /* CR1 */
ADC_CR2_SWSTART, /* CR2 */
0, /* SMPR1 */
ADC_SMPR2_SMP_AN11(ADC_SAMPLE_48) | ADC_SMPR2_SMP_AN10(ADC_SAMPLE_48) |
ADC_SMPR2_SMP_SENSOR(ADC_SAMPLE_192) | ADC_SMPR2_SMP_VREF(ADC_SAMPLE_192),
0, /* SMPR3 */
ADC_SQR1_NUM_CH(ADC_GRP2_NUM_CHANNELS),
0, 0, /* SQR2, SQR3 */
ADC_SQR4_SQ8_N(ADC_CHANNEL_SENSOR) | ADC_SQR4_SQ7_N(ADC_CHANNEL_VREFINT),
ADC_SQR5_SQ6_N(ADC_CHANNEL_IN11) | ADC_SQR5_SQ5_N(ADC_CHANNEL_IN10) |
ADC_SQR5_SQ4_N(ADC_CHANNEL_IN11) | ADC_SQR5_SQ3_N(ADC_CHANNEL_IN10) |
ADC_SQR5_SQ2_N(ADC_CHANNEL_IN11) | ADC_SQR5_SQ1_N(ADC_CHANNEL_IN10)
};
/*
* Red LEDs blinker thread, times are in milliseconds.
*/
static WORKING_AREA(waThread1, 128);
static msg_t Thread1(void *arg) {
(void)arg;
chRegSetThreadName("blinker");
while (TRUE) {
palSetPad(GPIOB, GPIOB_LED4);
chThdSleepMilliseconds(500);
palClearPad(GPIOB, GPIOB_LED4);
chThdSleepMilliseconds(500);
}
}
/*
* Application entry point.
*/
int main(void) {
/*
* System initializations.
* - HAL initialization, this also initializes the configured device drivers
* and performs the board-specific initializations.
* - Kernel initialization, the main() function becomes a thread and the
* RTOS is active.
*/
halInit();
chSysInit();
/*
* Setting up analog inputs used by the demo.
*/
palSetGroupMode(GPIOC, PAL_PORT_BIT(0) | PAL_PORT_BIT(1),
0, PAL_MODE_INPUT_ANALOG);
/*
* Creates the blinker thread.
*/
chThdCreateStatic(waThread1, sizeof(waThread1), NORMALPRIO, Thread1, NULL);
/*
* Activates the ADC1 driver and the temperature sensor.
*/
adcStart(&ADCD1, NULL);
adcSTM32EnableTSVREFE();
/*
* Linear conversion.
*/
adcConvert(&ADCD1, &adcgrpcfg1, samples1, ADC_GRP1_BUF_DEPTH);
chThdSleepMilliseconds(1000);
/*
* Starts an ADC continuous conversion.
*/
adcStartConversion(&ADCD1, &adcgrpcfg2, samples2, ADC_GRP2_BUF_DEPTH);
/*
* Normal main() thread activity, in this demo it does nothing.
*/
while (TRUE) {
if (palReadPad(GPIOA, GPIOA_BUTTON)) {
adcStopConversion(&ADCD1);
adcSTM32DisableTSVREFE();
}
chThdSleepMilliseconds(500);
}
}
|
gpl-3.0
|
queglay/Marlin
|
ArduinoAddons/Arduino_1.0.x/hardware/Sanguino/bootloaders/atmega/ATmegaBOOT_168.c
|
303
|
30998
|
/**********************************************************/
/* Serial Bootloader for Atmel megaAVR Controllers */
/* */
/* tested with ATmega8, ATmega128 and ATmega168 */
/* should work with other mega's, see code for details */
/* */
/* ATmegaBOOT.c */
/* */
/* */
/* 20090308: integrated Mega changes into main bootloader */
/* source by D. Mellis */
/* 20080930: hacked for Arduino Mega (with the 1280 */
/* processor, backwards compatible) */
/* by D. Cuartielles */
/* 20070626: hacked for Arduino Diecimila (which auto- */
/* resets when a USB connection is made to it) */
/* by D. Mellis */
/* 20060802: hacked for Arduino by D. Cuartielles */
/* based on a previous hack by D. Mellis */
/* and D. Cuartielles */
/* */
/* Monitor and debug functions were added to the original */
/* code by Dr. Erik Lins, chip45.com. (See below) */
/* */
/* Thanks to Karl Pitrich for fixing a bootloader pin */
/* problem and more informative LED blinking! */
/* */
/* For the latest version see: */
/* http://www.chip45.com/ */
/* */
/* ------------------------------------------------------ */
/* */
/* based on stk500boot.c */
/* Copyright (c) 2003, Jason P. Kyle */
/* All rights reserved. */
/* see avr1.org for original file and information */
/* */
/* 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 */
/* */
/* Licence can be viewed at */
/* http://www.fsf.org/licenses/gpl.txt */
/* */
/* Target = Atmel AVR m128,m64,m32,m16,m8,m162,m163,m169, */
/* m8515,m8535. ATmega161 has a very small boot block so */
/* isn't supported. */
/* */
/* Tested with m168 */
/**********************************************************/
/* $Id$ */
/* some includes */
#include <inttypes.h>
#include <avr/io.h>
#include <avr/pgmspace.h>
#include <avr/interrupt.h>
#include <avr/wdt.h>
#include <util/delay.h>
/* the current avr-libc eeprom functions do not support the ATmega168 */
/* own eeprom write/read functions are used instead */
#if !defined(__AVR_ATmega168__) || !defined(__AVR_ATmega328P__)
#include <avr/eeprom.h>
#endif
/* Use the F_CPU defined in Makefile */
/* 20060803: hacked by DojoCorp */
/* 20070626: hacked by David A. Mellis to decrease waiting time for auto-reset */
/* set the waiting time for the bootloader */
/* get this from the Makefile instead */
/* #define MAX_TIME_COUNT (F_CPU>>4) */
/* 20070707: hacked by David A. Mellis - after this many errors give up and launch application */
#define MAX_ERROR_COUNT 5
/* set the UART baud rate */
/* 20060803: hacked by DojoCorp */
//#define BAUD_RATE 115200
#ifndef BAUD_RATE
#define BAUD_RATE 19200
#endif
/* SW_MAJOR and MINOR needs to be updated from time to time to avoid warning message from AVR Studio */
/* never allow AVR Studio to do an update !!!! */
#define HW_VER 0x02
#define SW_MAJOR 0x01
#define SW_MINOR 0x10
/* Adjust to suit whatever pin your hardware uses to enter the bootloader */
/* ATmega128 has two UARTS so two pins are used to enter bootloader and select UART */
/* ATmega1280 has four UARTS, but for Arduino Mega, we will only use RXD0 to get code */
/* BL0... means UART0, BL1... means UART1 */
#ifdef __AVR_ATmega128__
#define BL_DDR DDRF
#define BL_PORT PORTF
#define BL_PIN PINF
#define BL0 PINF7
#define BL1 PINF6
#elif defined __AVR_ATmega1280__
/* we just don't do anything for the MEGA and enter bootloader on reset anyway*/
#elif defined __AVR_ATmega1284P_ || defined __AVR_ATmega644P__
#else
/* other ATmegas have only one UART, so only one pin is defined to enter bootloader */
#define BL_DDR DDRD
#define BL_PORT PORTD
#define BL_PIN PIND
#define BL PIND6
#endif
/* onboard LED is used to indicate, that the bootloader was entered (3x flashing) */
/* if monitor functions are included, LED goes on after monitor was entered */
#if defined __AVR_ATmega128__ || defined __AVR_ATmega1280__
/* Onboard LED is connected to pin PB7 (e.g. Crumb128, PROBOmega128, Savvy128, Arduino Mega) */
#define LED_DDR DDRB
#define LED_PORT PORTB
#define LED_PIN PINB
#define LED PINB7
#elif defined __AVR_ATmega1284P__ || defined __AVR_ATmega644P__
#define LED_DDR DDRB
#define LED_PORT PORTB
#define LED_PIN PINB
#define LED PINB0
#else
/* Onboard LED is connected to pin PB5 in Arduino NG, Diecimila, and Duomilanuove */
/* other boards like e.g. Crumb8, Crumb168 are using PB2 */
#define LED_DDR DDRB
#define LED_PORT PORTB
#define LED_PIN PINB
#define LED PINB5
#endif
/* monitor functions will only be compiled when using ATmega128, due to bootblock size constraints */
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__)
#define MONITOR 1
#endif
/* define various device id's */
/* manufacturer byte is always the same */
#define SIG1 0x1E // Yep, Atmel is the only manufacturer of AVR micros. Single source :(
#if defined __AVR_ATmega1280__
#define SIG2 0x97
#define SIG3 0x03
#define PAGE_SIZE 0x80U //128 words
#elif defined __AVR_ATmega1284P__
#define SIG2 0x97
#define SIG3 0x05
#define PAGE_SIZE 0x080U //128 words
#elif defined __AVR_ATmega1281__
#define SIG2 0x97
#define SIG3 0x04
#define PAGE_SIZE 0x80U //128 words
#elif defined __AVR_ATmega644P__
#define SIG2 0x96
#define SIG3 0x0A
#define PAGE_SIZE 0x080U //128 words
#elif defined __AVR_ATmega128__
#define SIG2 0x97
#define SIG3 0x02
#define PAGE_SIZE 0x80U //128 words
#elif defined __AVR_ATmega64__
#define SIG2 0x96
#define SIG3 0x02
#define PAGE_SIZE 0x80U //128 words
#elif defined __AVR_ATmega32__
#define SIG2 0x95
#define SIG3 0x02
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega16__
#define SIG2 0x94
#define SIG3 0x03
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega8__
#define SIG2 0x93
#define SIG3 0x07
#define PAGE_SIZE 0x20U //32 words
#elif defined __AVR_ATmega88__
#define SIG2 0x93
#define SIG3 0x0a
#define PAGE_SIZE 0x20U //32 words
#elif defined __AVR_ATmega168__
#define SIG2 0x94
#define SIG3 0x06
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega328P__
#define SIG2 0x95
#define SIG3 0x0F
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega162__
#define SIG2 0x94
#define SIG3 0x04
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega163__
#define SIG2 0x94
#define SIG3 0x02
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega169__
#define SIG2 0x94
#define SIG3 0x05
#define PAGE_SIZE 0x40U //64 words
#elif defined __AVR_ATmega8515__
#define SIG2 0x93
#define SIG3 0x06
#define PAGE_SIZE 0x20U //32 words
#elif defined __AVR_ATmega8535__
#define SIG2 0x93
#define SIG3 0x08
#define PAGE_SIZE 0x20U //32 words
#endif
/* function prototypes */
void putch(char);
char getch(void);
void getNch(uint8_t);
void byte_response(uint8_t);
void nothing_response(void);
char gethex(void);
void puthex(char);
void flash_led(uint8_t);
/* some variables */
union address_union {
uint16_t word;
uint8_t byte[2];
} address;
union length_union {
uint16_t word;
uint8_t byte[2];
} length;
struct flags_struct {
unsigned eeprom : 1;
unsigned rampz : 1;
} flags;
uint8_t buff[256];
uint8_t address_high;
uint8_t pagesz=0x80;
uint8_t i;
uint8_t bootuart = 0;
uint8_t error_count = 0;
void (*app_start)(void) = 0x0000;
/* main program starts here */
int main(void)
{
uint8_t ch,ch2;
uint16_t w;
#ifdef WATCHDOG_MODS
ch = MCUSR;
MCUSR = 0;
WDTCSR |= _BV(WDCE) | _BV(WDE);
WDTCSR = 0;
// Check if the WDT was used to reset, in which case we dont bootload and skip straight to the code. woot.
if (! (ch & _BV(EXTRF))) // if it's a not an external reset...
app_start(); // skip bootloader
#else
asm volatile("nop\n\t");
#endif
/* set pin direction for bootloader pin and enable pullup */
/* for ATmega128, two pins need to be initialized */
#ifdef __AVR_ATmega128__
BL_DDR &= ~_BV(BL0);
BL_DDR &= ~_BV(BL1);
BL_PORT |= _BV(BL0);
BL_PORT |= _BV(BL1);
#else
/* We run the bootloader regardless of the state of this pin. Thus, don't
put it in a different state than the other pins. --DAM, 070709
This also applies to Arduino Mega -- DC, 080930
BL_DDR &= ~_BV(BL);
BL_PORT |= _BV(BL);
*/
#endif
#ifdef __AVR_ATmega128__
/* check which UART should be used for booting */
if(bit_is_clear(BL_PIN, BL0)) {
bootuart = 1;
}
else if(bit_is_clear(BL_PIN, BL1)) {
bootuart = 2;
}
#endif
#if defined __AVR_ATmega1280__ || defined __AVR_ATmega1284P__ || defined __AVR_ATmega644P__
/* the mega1280 chip has four serial ports ... we could eventually use any of them, or not? */
/* however, we don't wanna confuse people, to avoid making a mess, we will stick to RXD0, TXD0 */
bootuart = 1;
#endif
/* check if flash is programmed already, if not start bootloader anyway */
if(pgm_read_byte_near(0x0000) != 0xFF) {
#ifdef __AVR_ATmega128__
/* no UART was selected, start application */
if(!bootuart) {
app_start();
}
#else
/* check if bootloader pin is set low */
/* we don't start this part neither for the m8, nor m168 */
//if(bit_is_set(BL_PIN, BL)) {
// app_start();
// }
#endif
}
#ifdef __AVR_ATmega128__
/* no bootuart was selected, default to uart 0 */
if(!bootuart) {
bootuart = 1;
}
#endif
/* initialize UART(s) depending on CPU defined */
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
if(bootuart == 1) {
UBRR0L = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
UBRR0H = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
UCSR0A = 0x00;
UCSR0C = 0x06;
UCSR0B = _BV(TXEN0)|_BV(RXEN0);
}
if(bootuart == 2) {
UBRR1L = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
UBRR1H = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
UCSR1A = 0x00;
UCSR1C = 0x06;
UCSR1B = _BV(TXEN1)|_BV(RXEN1);
}
#elif defined __AVR_ATmega163__
UBRR = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
UBRRHI = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
UCSRA = 0x00;
UCSRB = _BV(TXEN)|_BV(RXEN);
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
#ifdef DOUBLE_SPEED
UCSR0A = (1<<U2X0); //Double speed mode USART0
UBRR0L = (uint8_t)(F_CPU/(BAUD_RATE*8L)-1);
UBRR0H = (F_CPU/(BAUD_RATE*8L)-1) >> 8;
#else
UBRR0L = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
UBRR0H = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
#endif
UCSR0B = (1<<RXEN0) | (1<<TXEN0);
UCSR0C = (1<<UCSZ00) | (1<<UCSZ01);
/* Enable internal pull-up resistor on pin D0 (RX), in order
to supress line noise that prevents the bootloader from
timing out (DAM: 20070509) */
DDRD &= ~_BV(PIND0);
PORTD |= _BV(PIND0);
#elif defined __AVR_ATmega8__
/* m8 */
UBRRH = (((F_CPU/BAUD_RATE)/16)-1)>>8; // set baud rate
UBRRL = (((F_CPU/BAUD_RATE)/16)-1);
UCSRB = (1<<RXEN)|(1<<TXEN); // enable Rx & Tx
UCSRC = (1<<URSEL)|(1<<UCSZ1)|(1<<UCSZ0); // config USART; 8N1
#else
/* m16,m32,m169,m8515,m8535 */
UBRRL = (uint8_t)(F_CPU/(BAUD_RATE*16L)-1);
UBRRH = (F_CPU/(BAUD_RATE*16L)-1) >> 8;
UCSRA = 0x00;
UCSRC = 0x06;
UCSRB = _BV(TXEN)|_BV(RXEN);
#endif
#if defined __AVR_ATmega1280__
/* Enable internal pull-up resistor on pin D0 (RX), in order
to supress line noise that prevents the bootloader from
timing out (DAM: 20070509) */
/* feature added to the Arduino Mega --DC: 080930 */
DDRE &= ~_BV(PINE0);
PORTE |= _BV(PINE0);
#endif
/* set LED pin as output */
LED_DDR |= _BV(LED);
/* flash onboard LED to signal entering of bootloader */
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
// 4x for UART0, 5x for UART1
flash_led(NUM_LED_FLASHES + bootuart);
#else
flash_led(NUM_LED_FLASHES);
#endif
/* 20050803: by DojoCorp, this is one of the parts provoking the
system to stop listening, cancelled from the original */
//putch('\0');
/* forever loop */
for (;;) {
/* get character from UART */
ch = getch();
/* A bunch of if...else if... gives smaller code than switch...case ! */
/* Hello is anyone home ? */
if(ch=='0') {
nothing_response();
}
/* Request programmer ID */
/* Not using PROGMEM string due to boot block in m128 being beyond 64kB boundry */
/* Would need to selectively manipulate RAMPZ, and it's only 9 characters anyway so who cares. */
else if(ch=='1') {
if (getch() == ' ') {
putch(0x14);
putch('A');
putch('V');
putch('R');
putch(' ');
putch('I');
putch('S');
putch('P');
putch(0x10);
} else {
if (++error_count == MAX_ERROR_COUNT)
app_start();
}
}
/* AVR ISP/STK500 board commands DON'T CARE so default nothing_response */
else if(ch=='@') {
ch2 = getch();
if (ch2>0x85) getch();
nothing_response();
}
/* AVR ISP/STK500 board requests */
else if(ch=='A') {
ch2 = getch();
if(ch2==0x80) byte_response(HW_VER); // Hardware version
else if(ch2==0x81) byte_response(SW_MAJOR); // Software major version
else if(ch2==0x82) byte_response(SW_MINOR); // Software minor version
else if(ch2==0x98) byte_response(0x03); // Unknown but seems to be required by avr studio 3.56
else byte_response(0x00); // Covers various unnecessary responses we don't care about
}
/* Device Parameters DON'T CARE, DEVICE IS FIXED */
else if(ch=='B') {
getNch(20);
nothing_response();
}
/* Parallel programming stuff DON'T CARE */
else if(ch=='E') {
getNch(5);
nothing_response();
}
/* P: Enter programming mode */
/* R: Erase device, don't care as we will erase one page at a time anyway. */
else if(ch=='P' || ch=='R') {
nothing_response();
}
/* Leave programming mode */
else if(ch=='Q') {
nothing_response();
#ifdef WATCHDOG_MODS
// autoreset via watchdog (sneaky!)
WDTCSR = _BV(WDE);
while (1); // 16 ms
#endif
}
/* Set address, little endian. EEPROM in bytes, FLASH in words */
/* Perhaps extra address bytes may be added in future to support > 128kB FLASH. */
/* This might explain why little endian was used here, big endian used everywhere else. */
else if(ch=='U') {
address.byte[0] = getch();
address.byte[1] = getch();
nothing_response();
}
/* Universal SPI programming command, disabled. Would be used for fuses and lock bits. */
else if(ch=='V') {
if (getch() == 0x30) {
getch();
ch = getch();
getch();
if (ch == 0) {
byte_response(SIG1);
} else if (ch == 1) {
byte_response(SIG2);
} else {
byte_response(SIG3);
}
} else {
getNch(3);
byte_response(0x00);
}
}
/* Write memory, length is big endian and is in bytes */
else if(ch=='d') {
length.byte[1] = getch();
length.byte[0] = getch();
flags.eeprom = 0;
if (getch() == 'E') flags.eeprom = 1;
for (w=0;w<length.word;w++) {
buff[w] = getch(); // Store data in buffer, can't keep up with serial data stream whilst programming pages
}
if (getch() == ' ') {
if (flags.eeprom) { //Write to EEPROM one byte at a time
address.word <<= 1;
for(w=0;w<length.word;w++) {
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
while(EECR & (1<<EEPE));
EEAR = (uint16_t)(void *)address.word;
EEDR = buff[w];
EECR |= (1<<EEMPE);
EECR |= (1<<EEPE);
#else
eeprom_write_byte((void *)address.word,buff[w]);
#endif
address.word++;
}
}
else { //Write to FLASH one page at a time
if (address.byte[1]>127) address_high = 0x01; //Only possible with m128, m256 will need 3rd address byte. FIXME
else address_high = 0x00;
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega1284P__)
RAMPZ = address_high;
#endif
address.word = address.word << 1; //address * 2 -> byte location
/* if ((length.byte[0] & 0x01) == 0x01) length.word++; //Even up an odd number of bytes */
if ((length.byte[0] & 0x01)) length.word++; //Even up an odd number of bytes
cli(); //Disable interrupts, just to be sure
#if defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1281__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
while(bit_is_set(EECR,EEPE)); //Wait for previous EEPROM writes to complete
#else
while(bit_is_set(EECR,EEWE)); //Wait for previous EEPROM writes to complete
#endif
asm volatile(
"clr r17 \n\t" //page_word_count
"lds r30,address \n\t" //Address of FLASH location (in bytes)
"lds r31,address+1 \n\t"
"ldi r28,lo8(buff) \n\t" //Start of buffer array in RAM
"ldi r29,hi8(buff) \n\t"
"lds r24,length \n\t" //Length of data to be written (in bytes)
"lds r25,length+1 \n\t"
"length_loop: \n\t" //Main loop, repeat for number of words in block
"cpi r17,0x00 \n\t" //If page_word_count=0 then erase page
"brne no_page_erase \n\t"
"wait_spm1: \n\t"
"lds r16,%0 \n\t" //Wait for previous spm to complete
"andi r16,1 \n\t"
"cpi r16,1 \n\t"
"breq wait_spm1 \n\t"
"ldi r16,0x03 \n\t" //Erase page pointed to by Z
"sts %0,r16 \n\t"
"spm \n\t"
#ifdef __AVR_ATmega163__
".word 0xFFFF \n\t"
"nop \n\t"
#endif
"wait_spm2: \n\t"
"lds r16,%0 \n\t" //Wait for previous spm to complete
"andi r16,1 \n\t"
"cpi r16,1 \n\t"
"breq wait_spm2 \n\t"
"ldi r16,0x11 \n\t" //Re-enable RWW section
"sts %0,r16 \n\t"
"spm \n\t"
#ifdef __AVR_ATmega163__
".word 0xFFFF \n\t"
"nop \n\t"
#endif
"no_page_erase: \n\t"
"ld r0,Y+ \n\t" //Write 2 bytes into page buffer
"ld r1,Y+ \n\t"
"wait_spm3: \n\t"
"lds r16,%0 \n\t" //Wait for previous spm to complete
"andi r16,1 \n\t"
"cpi r16,1 \n\t"
"breq wait_spm3 \n\t"
"ldi r16,0x01 \n\t" //Load r0,r1 into FLASH page buffer
"sts %0,r16 \n\t"
"spm \n\t"
"inc r17 \n\t" //page_word_count++
"cpi r17,%1 \n\t"
"brlo same_page \n\t" //Still same page in FLASH
"write_page: \n\t"
"clr r17 \n\t" //New page, write current one first
"wait_spm4: \n\t"
"lds r16,%0 \n\t" //Wait for previous spm to complete
"andi r16,1 \n\t"
"cpi r16,1 \n\t"
"breq wait_spm4 \n\t"
#ifdef __AVR_ATmega163__
"andi r30,0x80 \n\t" // m163 requires Z6:Z1 to be zero during page write
#endif
"ldi r16,0x05 \n\t" //Write page pointed to by Z
"sts %0,r16 \n\t"
"spm \n\t"
#ifdef __AVR_ATmega163__
".word 0xFFFF \n\t"
"nop \n\t"
"ori r30,0x7E \n\t" // recover Z6:Z1 state after page write (had to be zero during write)
#endif
"wait_spm5: \n\t"
"lds r16,%0 \n\t" //Wait for previous spm to complete
"andi r16,1 \n\t"
"cpi r16,1 \n\t"
"breq wait_spm5 \n\t"
"ldi r16,0x11 \n\t" //Re-enable RWW section
"sts %0,r16 \n\t"
"spm \n\t"
#ifdef __AVR_ATmega163__
".word 0xFFFF \n\t"
"nop \n\t"
#endif
"same_page: \n\t"
"adiw r30,2 \n\t" //Next word in FLASH
"sbiw r24,2 \n\t" //length-2
"breq final_write \n\t" //Finished
"rjmp length_loop \n\t"
"final_write: \n\t"
"cpi r17,0 \n\t"
"breq block_done \n\t"
"adiw r24,2 \n\t" //length+2, fool above check on length after short page write
"rjmp write_page \n\t"
"block_done: \n\t"
"clr __zero_reg__ \n\t" //restore zero register
#if defined __AVR_ATmega168__ || __AVR_ATmega328P__ || __AVR_ATmega128__ || __AVR_ATmega1280__ || __AVR_ATmega1281__ || __AVR_ATmega1284P__ || __AVR_ATmega644P__
: "=m" (SPMCSR) : "M" (PAGE_SIZE) : "r0","r16","r17","r24","r25","r28","r29","r30","r31"
#else
: "=m" (SPMCR) : "M" (PAGE_SIZE) : "r0","r16","r17","r24","r25","r28","r29","r30","r31"
#endif
);
/* Should really add a wait for RWW section to be enabled, don't actually need it since we never */
/* exit the bootloader without a power cycle anyhow */
}
putch(0x14);
putch(0x10);
} else {
if (++error_count == MAX_ERROR_COUNT)
app_start();
}
}
/* Read memory block mode, length is big endian. */
else if(ch=='t') {
length.byte[1] = getch();
length.byte[0] = getch();
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
if (address.word>0x7FFF) flags.rampz = 1; // No go with m256, FIXME
else flags.rampz = 0;
#endif
address.word = address.word << 1; // address * 2 -> byte location
if (getch() == 'E') flags.eeprom = 1;
else flags.eeprom = 0;
if (getch() == ' ') { // Command terminator
putch(0x14);
for (w=0;w < length.word;w++) { // Can handle odd and even lengths okay
if (flags.eeprom) { // Byte access EEPROM read
#if defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
while(EECR & (1<<EEPE));
EEAR = (uint16_t)(void *)address.word;
EECR |= (1<<EERE);
putch(EEDR);
#else
putch(eeprom_read_byte((void *)address.word));
#endif
address.word++;
}
else {
if (!flags.rampz) putch(pgm_read_byte_near(address.word));
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__)
else putch(pgm_read_byte_far(address.word + 0x10000));
// Hmmmm, yuck FIXME when m256 arrvies
#endif
address.word++;
}
}
putch(0x10);
}
}
/* Get device signature bytes */
else if(ch=='u') {
if (getch() == ' ') {
putch(0x14);
putch(SIG1);
putch(SIG2);
putch(SIG3);
putch(0x10);
} else {
if (++error_count == MAX_ERROR_COUNT)
app_start();
}
}
/* Read oscillator calibration byte */
else if(ch=='v') {
byte_response(0x00);
}
#if defined MONITOR
/* here come the extended monitor commands by Erik Lins */
/* check for three times exclamation mark pressed */
else if(ch=='!') {
ch = getch();
if(ch=='!') {
ch = getch();
if(ch=='!') {
PGM_P welcome = "";
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__)
uint16_t extaddr;
#endif
uint8_t addrl, addrh;
#ifdef CRUMB128
welcome = "ATmegaBOOT / Crumb128 - (C) J.P.Kyle, E.Lins - 050815\n\r";
#elif defined PROBOMEGA128
welcome = "ATmegaBOOT / PROBOmega128 - (C) J.P.Kyle, E.Lins - 050815\n\r";
#elif defined SAVVY128
welcome = "ATmegaBOOT / Savvy128 - (C) J.P.Kyle, E.Lins - 050815\n\r";
#elif defined __AVR_ATmega1280__
welcome = "ATmegaBOOT / Arduino Mega - (C) Arduino LLC - 090930\n\r";
#endif
/* turn on LED */
LED_DDR |= _BV(LED);
LED_PORT &= ~_BV(LED);
/* print a welcome message and command overview */
for(i=0; welcome[i] != '\0'; ++i) {
putch(welcome[i]);
}
/* test for valid commands */
for(;;) {
putch('\n');
putch('\r');
putch(':');
putch(' ');
ch = getch();
putch(ch);
/* toggle LED */
if(ch == 't') {
if(bit_is_set(LED_PIN,LED)) {
LED_PORT &= ~_BV(LED);
putch('1');
} else {
LED_PORT |= _BV(LED);
putch('0');
}
}
/* read byte from address */
else if(ch == 'r') {
ch = getch(); putch(ch);
addrh = gethex();
addrl = gethex();
putch('=');
ch = *(uint8_t *)((addrh << 8) + addrl);
puthex(ch);
}
/* write a byte to address */
else if(ch == 'w') {
ch = getch(); putch(ch);
addrh = gethex();
addrl = gethex();
ch = getch(); putch(ch);
ch = gethex();
*(uint8_t *)((addrh << 8) + addrl) = ch;
}
/* read from uart and echo back */
else if(ch == 'u') {
for(;;) {
putch(getch());
}
}
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__)
/* external bus loop */
else if(ch == 'b') {
putch('b');
putch('u');
putch('s');
MCUCR = 0x80;
XMCRA = 0;
XMCRB = 0;
extaddr = 0x1100;
for(;;) {
ch = *(volatile uint8_t *)extaddr;
if(++extaddr == 0) {
extaddr = 0x1100;
}
}
}
#endif
else if(ch == 'j') {
app_start();
}
} /* end of monitor functions */
}
}
}
/* end of monitor */
#endif
else if (++error_count == MAX_ERROR_COUNT) {
app_start();
}
} /* end of forever loop */
}
char gethexnib(void) {
char a;
a = getch(); putch(a);
if(a >= 'a') {
return (a - 'a' + 0x0a);
} else if(a >= '0') {
return(a - '0');
}
return a;
}
char gethex(void) {
return (gethexnib() << 4) + gethexnib();
}
void puthex(char ch) {
char ah;
ah = ch >> 4;
if(ah >= 0x0a) {
ah = ah - 0x0a + 'a';
} else {
ah += '0';
}
ch &= 0x0f;
if(ch >= 0x0a) {
ch = ch - 0x0a + 'a';
} else {
ch += '0';
}
putch(ah);
putch(ch);
}
void putch(char ch)
{
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
if(bootuart == 1) {
while (!(UCSR0A & _BV(UDRE0)));
UDR0 = ch;
}
else if (bootuart == 2) {
while (!(UCSR1A & _BV(UDRE1)));
UDR1 = ch;
}
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
while (!(UCSR0A & _BV(UDRE0)));
UDR0 = ch;
#else
/* m8,16,32,169,8515,8535,163 */
while (!(UCSRA & _BV(UDRE)));
UDR = ch;
#endif
}
char getch(void)
{
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
uint32_t count = 0;
if(bootuart == 1) {
while(!(UCSR0A & _BV(RXC0))) {
/* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/
/* HACKME:: here is a good place to count times*/
count++;
if (count > MAX_TIME_COUNT)
app_start();
}
return UDR0;
}
else if(bootuart == 2) {
while(!(UCSR1A & _BV(RXC1))) {
/* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/
/* HACKME:: here is a good place to count times*/
count++;
if (count > MAX_TIME_COUNT)
app_start();
}
return UDR1;
}
return 0;
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
uint32_t count = 0;
while(!(UCSR0A & _BV(RXC0))){
/* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/
/* HACKME:: here is a good place to count times*/
count++;
if (count > MAX_TIME_COUNT)
app_start();
}
return UDR0;
#else
/* m8,16,32,169,8515,8535,163 */
uint32_t count = 0;
while(!(UCSRA & _BV(RXC))){
/* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/
/* HACKME:: here is a good place to count times*/
count++;
if (count > MAX_TIME_COUNT)
app_start();
}
return UDR;
#endif
}
void getNch(uint8_t count)
{
while(count--) {
#if defined(__AVR_ATmega128__) || defined(__AVR_ATmega1280__) || defined(__AVR_ATmega1284P__) || defined(__AVR_ATmega644P__)
if(bootuart == 1) {
while(!(UCSR0A & _BV(RXC0)));
UDR0;
}
else if(bootuart == 2) {
while(!(UCSR1A & _BV(RXC1)));
UDR1;
}
#elif defined(__AVR_ATmega168__) || defined(__AVR_ATmega328P__)
getch();
#else
/* m8,16,32,169,8515,8535,163 */
/* 20060803 DojoCorp:: Addon coming from the previous Bootloader*/
//while(!(UCSRA & _BV(RXC)));
//UDR;
getch(); // need to handle time out
#endif
}
}
void byte_response(uint8_t val)
{
if (getch() == ' ') {
putch(0x14);
putch(val);
putch(0x10);
} else {
if (++error_count == MAX_ERROR_COUNT)
app_start();
}
}
void nothing_response(void)
{
if (getch() == ' ') {
putch(0x14);
putch(0x10);
} else {
if (++error_count == MAX_ERROR_COUNT)
app_start();
}
}
void flash_led(uint8_t count)
{
while (count--) {
LED_PORT |= _BV(LED);
_delay_ms(100);
LED_PORT &= ~_BV(LED);
_delay_ms(100);
}
}
/* end of file ATmegaBOOT.c */
|
gpl-3.0
|
lastcolour/GraphicsDemo
|
extern/libs/glm-0.9.7.4/test/gtc/gtc_round.cpp
|
49
|
8743
|
///////////////////////////////////////////////////////////////////////////////////
/// OpenGL Mathematics (glm.g-truc.net)
///
/// Copyright (c) 2005 - 2015 G-Truc Creation (www.g-truc.net)
/// Permission is hereby granted, free of charge, to any person obtaining a copy
/// of this software and associated documentation files (the "Software"), to deal
/// in the Software without restriction, including without limitation the rights
/// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
/// copies of the Software, and to permit persons to whom the Software is
/// furnished to do so, subject to the following conditions:
///
/// The above copyright notice and this permission notice shall be included in
/// all copies or substantial portions of the Software.
///
/// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
/// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
/// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
/// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
/// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
/// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
/// THE SOFTWARE.
///
/// @file test/gtc/gtc_round.cpp
/// @date 2014-11-03 / 2014-11-03
/// @author Christophe Riccio
///
/// @see core (dependence)
/// @see gtc_round (dependence)
///////////////////////////////////////////////////////////////////////////////////
#include <glm/gtc/round.hpp>
#include <glm/gtc/type_precision.hpp>
#include <glm/gtc/vec1.hpp>
#include <glm/gtc/epsilon.hpp>
#include <vector>
#include <ctime>
#include <cstdio>
namespace isPowerOfTwo
{
template <typename genType>
struct type
{
genType Value;
bool Return;
};
int test_int16()
{
type<glm::int16> const Data[] =
{
{0x0001, true},
{0x0002, true},
{0x0004, true},
{0x0080, true},
{0x0000, true},
{0x0003, false}
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::int16>); i < n; ++i)
{
bool Result = glm::isPowerOfTwo(Data[i].Value);
Error += Data[i].Return == Result ? 0 : 1;
}
return Error;
}
int test_uint16()
{
type<glm::uint16> const Data[] =
{
{0x0001, true},
{0x0002, true},
{0x0004, true},
{0x0000, true},
{0x0000, true},
{0x0003, false}
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::uint16>); i < n; ++i)
{
bool Result = glm::isPowerOfTwo(Data[i].Value);
Error += Data[i].Return == Result ? 0 : 1;
}
return Error;
}
int test_int32()
{
type<int> const Data[] =
{
{0x00000001, true},
{0x00000002, true},
{0x00000004, true},
{0x0000000f, false},
{0x00000000, true},
{0x00000003, false}
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<int>); i < n; ++i)
{
bool Result = glm::isPowerOfTwo(Data[i].Value);
Error += Data[i].Return == Result ? 0 : 1;
}
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<int>); i < n; ++i)
{
glm::bvec1 Result = glm::isPowerOfTwo(glm::ivec1(Data[i].Value));
Error += glm::all(glm::equal(glm::bvec1(Data[i].Return), Result)) ? 0 : 1;
}
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<int>); i < n; ++i)
{
glm::bvec2 Result = glm::isPowerOfTwo(glm::ivec2(Data[i].Value));
Error += glm::all(glm::equal(glm::bvec2(Data[i].Return), Result)) ? 0 : 1;
}
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<int>); i < n; ++i)
{
glm::bvec3 Result = glm::isPowerOfTwo(glm::ivec3(Data[i].Value));
Error += glm::all(glm::equal(glm::bvec3(Data[i].Return), Result)) ? 0 : 1;
}
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<int>); i < n; ++i)
{
glm::bvec4 Result = glm::isPowerOfTwo(glm::ivec4(Data[i].Value));
Error += glm::all(glm::equal(glm::bvec4(Data[i].Return), Result)) ? 0 : 1;
}
return Error;
}
int test_uint32()
{
type<glm::uint> const Data[] =
{
{0x00000001, true},
{0x00000002, true},
{0x00000004, true},
{0x80000000, true},
{0x00000000, true},
{0x00000003, false}
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::uint>); i < n; ++i)
{
bool Result = glm::isPowerOfTwo(Data[i].Value);
Error += Data[i].Return == Result ? 0 : 1;
}
return Error;
}
int test()
{
int Error(0);
Error += test_int16();
Error += test_uint16();
Error += test_int32();
Error += test_uint32();
return Error;
}
}//isPowerOfTwo
namespace ceilPowerOfTwo
{
template <typename genIUType>
GLM_FUNC_QUALIFIER genIUType highestBitValue(genIUType Value)
{
genIUType tmp = Value;
genIUType result = genIUType(0);
while(tmp)
{
result = (tmp & (~tmp + 1)); // grab lowest bit
tmp &= ~result; // clear lowest bit
}
return result;
}
template <typename genType>
GLM_FUNC_QUALIFIER genType ceilPowerOfTwo_loop(genType value)
{
return glm::isPowerOfTwo(value) ? value : highestBitValue(value) << 1;
}
template <typename genType>
struct type
{
genType Value;
genType Return;
};
int test_int32()
{
type<glm::int32> const Data[] =
{
{0x0000ffff, 0x00010000},
{-3, -4},
{-8, -8},
{0x00000001, 0x00000001},
{0x00000002, 0x00000002},
{0x00000004, 0x00000004},
{0x00000007, 0x00000008},
{0x0000fff0, 0x00010000},
{0x0000f000, 0x00010000},
{0x08000000, 0x08000000},
{0x00000000, 0x00000000},
{0x00000003, 0x00000004}
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::int32>); i < n; ++i)
{
glm::int32 Result = glm::ceilPowerOfTwo(Data[i].Value);
Error += Data[i].Return == Result ? 0 : 1;
}
return Error;
}
int test_uint32()
{
type<glm::uint32> const Data[] =
{
{0x00000001, 0x00000001},
{0x00000002, 0x00000002},
{0x00000004, 0x00000004},
{0x00000007, 0x00000008},
{0x0000ffff, 0x00010000},
{0x0000fff0, 0x00010000},
{0x0000f000, 0x00010000},
{0x80000000, 0x80000000},
{0x00000000, 0x00000000},
{0x00000003, 0x00000004}
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::uint32>); i < n; ++i)
{
glm::uint32 Result = glm::ceilPowerOfTwo(Data[i].Value);
Error += Data[i].Return == Result ? 0 : 1;
}
return Error;
}
int perf()
{
int Error(0);
std::vector<glm::uint> v;
v.resize(100000000);
std::clock_t Timestramp0 = std::clock();
for(glm::uint32 i = 0, n = static_cast<glm::uint>(v.size()); i < n; ++i)
v[i] = ceilPowerOfTwo_loop(i);
std::clock_t Timestramp1 = std::clock();
for(glm::uint32 i = 0, n = static_cast<glm::uint>(v.size()); i < n; ++i)
v[i] = glm::ceilPowerOfTwo(i);
std::clock_t Timestramp2 = std::clock();
std::printf("ceilPowerOfTwo_loop: %d clocks\n", static_cast<unsigned int>(Timestramp1 - Timestramp0));
std::printf("glm::ceilPowerOfTwo: %d clocks\n", static_cast<unsigned int>(Timestramp2 - Timestramp1));
return Error;
}
int test()
{
int Error(0);
Error += test_int32();
Error += test_uint32();
return Error;
}
}//namespace ceilPowerOfTwo
namespace floorMultiple
{
template <typename genType>
struct type
{
genType Source;
genType Multiple;
genType Return;
genType Epsilon;
};
int test_float()
{
type<glm::float64> const Data[] =
{
{3.4, 0.3, 3.3, 0.0001},
{-1.4, 0.3, -1.5, 0.0001},
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::float64>); i < n; ++i)
{
glm::float64 Result = glm::floorMultiple(Data[i].Source, Data[i].Multiple);
Error += glm::epsilonEqual(Data[i].Return, Result, Data[i].Epsilon) ? 0 : 1;
}
return Error;
}
int test()
{
int Error(0);
Error += test_float();
return Error;
}
}//namespace floorMultiple
namespace ceilMultiple
{
template <typename genType>
struct type
{
genType Source;
genType Multiple;
genType Return;
genType Epsilon;
};
int test_float()
{
type<glm::float64> const Data[] =
{
{3.4, 0.3, 3.6, 0.0001},
{-1.4, 0.3, -1.2, 0.0001},
};
int Error(0);
for(std::size_t i = 0, n = sizeof(Data) / sizeof(type<glm::float64>); i < n; ++i)
{
glm::float64 Result = glm::ceilMultiple(Data[i].Source, Data[i].Multiple);
Error += glm::epsilonEqual(Data[i].Return, Result, Data[i].Epsilon) ? 0 : 1;
}
return Error;
}
int test()
{
int Error(0);
Error += test_float();
return Error;
}
}//namespace ceilMultiple
int main()
{
int Error(0);
Error += isPowerOfTwo::test();
Error += ceilPowerOfTwo::test();
# ifdef NDEBUG
Error += ceilPowerOfTwo::perf();
# endif//NDEBUG
Error += floorMultiple::test();
Error += ceilMultiple::test();
return Error;
}
|
gpl-3.0
|
yukuilong/Avplayer-old
|
libtorrent/bindings/python/src/datetime.cpp
|
50
|
1932
|
// Copyright Daniel Wallin 2006. Use, modification and distribution is
// subject to the Boost Software License, Version 1.0. (See accompanying
// file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
#include <boost/python.hpp>
#include <boost/date_time/posix_time/posix_time_types.hpp>
#include "optional.hpp"
#include <boost/version.hpp>
using namespace boost::python;
#if BOOST_VERSION < 103400
// From Boost 1.34
object import(str name)
{
// should be 'char const *' but older python versions don't use 'const' yet.
char *n = extract<char *>(name);
handle<> module(borrowed(PyImport_ImportModule(n)));
return object(module);
}
#endif
object datetime_timedelta;
object datetime_datetime;
struct time_duration_to_python
{
static PyObject* convert(boost::posix_time::time_duration const& d)
{
object result = datetime_timedelta(
0 // days
, 0 // seconds
, d.total_microseconds()
);
return incref(result.ptr());
}
};
struct ptime_to_python
{
static PyObject* convert(boost::posix_time::ptime const& pt)
{
boost::gregorian::date date = pt.date();
boost::posix_time::time_duration td = pt.time_of_day();
object result = datetime_datetime(
(int)date.year()
, (int)date.month()
, (int)date.day()
, td.hours()
, td.minutes()
, td.seconds()
);
return incref(result.ptr());
}
};
void bind_datetime()
{
object datetime = import("datetime").attr("__dict__");
datetime_timedelta = datetime["timedelta"];
datetime_datetime = datetime["datetime"];
to_python_converter<
boost::posix_time::time_duration
, time_duration_to_python
>();
to_python_converter<
boost::posix_time::ptime
, ptime_to_python
>();
optional_to_python<boost::posix_time::ptime>();
}
|
gpl-3.0
|
shlevy/grub
|
grub-core/commands/i386/cpuid.c
|
54
|
3252
|
/* cpuid.c - test for CPU features */
/*
* GRUB -- GRand Unified Bootloader
* Copyright (C) 2006, 2007, 2009 Free Software Foundation, Inc.
* Based on gcc/gcc/config/i386/driver-i386.c
*
* GRUB 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.
*
* GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>.
*/
#include <grub/dl.h>
#include <grub/misc.h>
#include <grub/mm.h>
#include <grub/env.h>
#include <grub/command.h>
#include <grub/extcmd.h>
#include <grub/i386/cpuid.h>
#include <grub/i18n.h>
GRUB_MOD_LICENSE ("GPLv3+");
static const struct grub_arg_option options[] =
{
/* TRANSLATORS: "(default)" at the end means that this option is used if
no argument is specified. */
{"long-mode", 'l', 0, N_("Check if CPU supports 64-bit (long) mode (default)."), 0, 0},
{"pae", 'p', 0, N_("Check if CPU supports Physical Address Extension."), 0, 0},
{0, 0, 0, 0, 0, 0}
};
enum
{
MODE_LM = 0,
MODE_PAE = 1
};
enum
{
bit_PAE = (1 << 6),
};
enum
{
bit_LM = (1 << 29)
};
unsigned char grub_cpuid_has_longmode = 0, grub_cpuid_has_pae = 0;
static grub_err_t
grub_cmd_cpuid (grub_extcmd_context_t ctxt,
int argc __attribute__ ((unused)),
char **args __attribute__ ((unused)))
{
int val = 0;
if (ctxt->state[MODE_PAE].set)
val = grub_cpuid_has_pae;
else
val = grub_cpuid_has_longmode;
return val ? GRUB_ERR_NONE
/* TRANSLATORS: it's a standalone boolean value,
opposite of "true". */
: grub_error (GRUB_ERR_TEST_FAILURE, N_("false"));
}
static grub_extcmd_t cmd;
GRUB_MOD_INIT(cpuid)
{
#ifdef __x86_64__
/* grub-emu */
grub_cpuid_has_longmode = 1;
grub_cpuid_has_pae = 1;
#else
unsigned int eax, ebx, ecx, edx;
unsigned int max_level;
unsigned int ext_level;
/* See if we can use cpuid. */
asm volatile ("pushfl; pushfl; popl %0; movl %0,%1; xorl %2,%0;"
"pushl %0; popfl; pushfl; popl %0; popfl"
: "=&r" (eax), "=&r" (ebx)
: "i" (0x00200000));
if (((eax ^ ebx) & 0x00200000) == 0)
goto done;
/* Check the highest input value for eax. */
grub_cpuid (0, eax, ebx, ecx, edx);
/* We only look at the first four characters. */
max_level = eax;
if (max_level == 0)
goto done;
if (max_level >= 1)
{
grub_cpuid (1, eax, ebx, ecx, edx);
grub_cpuid_has_pae = !!(edx & bit_PAE);
}
grub_cpuid (0x80000000, eax, ebx, ecx, edx);
ext_level = eax;
if (ext_level < 0x80000000)
goto done;
grub_cpuid (0x80000001, eax, ebx, ecx, edx);
grub_cpuid_has_longmode = !!(edx & bit_LM);
done:
#endif
cmd = grub_register_extcmd ("cpuid", grub_cmd_cpuid, 0,
"[-l]", N_("Check for CPU features."), options);
}
GRUB_MOD_FINI(cpuid)
{
grub_unregister_extcmd (cmd);
}
|
gpl-3.0
|
donnerluetjen/ardupilot
|
Tools/ArduPPM/ATMega32U2/LUFA/Drivers/USB/Class/Device/MassStorage.c
|
310
|
7456
|
/*
LUFA Library
Copyright (C) Dean Camera, 2010.
dean [at] fourwalledcubicle [dot] com
www.fourwalledcubicle.com
*/
/*
Copyright 2010 Dean Camera (dean [at] fourwalledcubicle [dot] com)
Permission to use, copy, modify, distribute, and sell this
software and its documentation for any purpose is hereby granted
without fee, provided that the above copyright notice appear in
all copies and that both that the copyright notice and this
permission notice and warranty disclaimer appear in supporting
documentation, and that the name of the author not be used in
advertising or publicity pertaining to distribution of the
software without specific, written prior permission.
The author disclaim all warranties with regard to this
software, including all implied warranties of merchantability
and fitness. In no event shall the author be liable for any
special, indirect or consequential damages or any damages
whatsoever resulting from loss of use, data or profits, whether
in an action of contract, negligence or other tortious action,
arising out of or in connection with the use or performance of
this software.
*/
#define __INCLUDE_FROM_USB_DRIVER
#include "../../HighLevel/USBMode.h"
#if defined(USB_CAN_BE_DEVICE)
#define __INCLUDE_FROM_MS_CLASS_DEVICE_C
#define __INCLUDE_FROM_MS_DRIVER
#include "MassStorage.h"
static volatile bool* CallbackIsResetSource;
void MS_Device_ProcessControlRequest(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
{
if (!(Endpoint_IsSETUPReceived()))
return;
if (USB_ControlRequest.wIndex != MSInterfaceInfo->Config.InterfaceNumber)
return;
switch (USB_ControlRequest.bRequest)
{
case REQ_MassStorageReset:
if (USB_ControlRequest.bmRequestType == (REQDIR_HOSTTODEVICE | REQTYPE_CLASS | REQREC_INTERFACE))
{
Endpoint_ClearSETUP();
MSInterfaceInfo->State.IsMassStoreReset = true;
Endpoint_ClearStatusStage();
}
break;
case REQ_GetMaxLUN:
if (USB_ControlRequest.bmRequestType == (REQDIR_DEVICETOHOST | REQTYPE_CLASS | REQREC_INTERFACE))
{
Endpoint_ClearSETUP();
Endpoint_Write_Byte(MSInterfaceInfo->Config.TotalLUNs - 1);
Endpoint_ClearIN();
Endpoint_ClearStatusStage();
}
break;
}
}
bool MS_Device_ConfigureEndpoints(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
{
memset(&MSInterfaceInfo->State, 0x00, sizeof(MSInterfaceInfo->State));
if (!(Endpoint_ConfigureEndpoint(MSInterfaceInfo->Config.DataINEndpointNumber, EP_TYPE_BULK,
ENDPOINT_DIR_IN, MSInterfaceInfo->Config.DataINEndpointSize,
MSInterfaceInfo->Config.DataINEndpointDoubleBank ? ENDPOINT_BANK_DOUBLE : ENDPOINT_BANK_SINGLE)))
{
return false;
}
if (!(Endpoint_ConfigureEndpoint(MSInterfaceInfo->Config.DataOUTEndpointNumber, EP_TYPE_BULK,
ENDPOINT_DIR_OUT, MSInterfaceInfo->Config.DataOUTEndpointSize,
MSInterfaceInfo->Config.DataOUTEndpointDoubleBank ? ENDPOINT_BANK_DOUBLE : ENDPOINT_BANK_SINGLE)))
{
return false;
}
return true;
}
void MS_Device_USBTask(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
{
if (USB_DeviceState != DEVICE_STATE_Configured)
return;
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpointNumber);
if (Endpoint_IsReadWriteAllowed())
{
if (MS_Device_ReadInCommandBlock(MSInterfaceInfo))
{
if (MSInterfaceInfo->State.CommandBlock.Flags & MS_COMMAND_DIR_DATA_IN)
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpointNumber);
MSInterfaceInfo->State.CommandStatus.Status = CALLBACK_MS_Device_SCSICommandReceived(MSInterfaceInfo) ?
SCSI_Command_Pass : SCSI_Command_Fail;
MSInterfaceInfo->State.CommandStatus.Signature = MS_CSW_SIGNATURE;
MSInterfaceInfo->State.CommandStatus.Tag = MSInterfaceInfo->State.CommandBlock.Tag;
MSInterfaceInfo->State.CommandStatus.DataTransferResidue = MSInterfaceInfo->State.CommandBlock.DataTransferLength;
if ((MSInterfaceInfo->State.CommandStatus.Status == SCSI_Command_Fail) &&
(MSInterfaceInfo->State.CommandStatus.DataTransferResidue))
{
Endpoint_StallTransaction();
}
MS_Device_ReturnCommandStatus(MSInterfaceInfo);
}
}
if (MSInterfaceInfo->State.IsMassStoreReset)
{
Endpoint_ResetFIFO(MSInterfaceInfo->Config.DataOUTEndpointNumber);
Endpoint_ResetFIFO(MSInterfaceInfo->Config.DataINEndpointNumber);
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpointNumber);
Endpoint_ClearStall();
Endpoint_ResetDataToggle();
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpointNumber);
Endpoint_ClearStall();
Endpoint_ResetDataToggle();
MSInterfaceInfo->State.IsMassStoreReset = false;
}
}
static bool MS_Device_ReadInCommandBlock(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
{
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpointNumber);
CallbackIsResetSource = &MSInterfaceInfo->State.IsMassStoreReset;
if (Endpoint_Read_Stream_LE(&MSInterfaceInfo->State.CommandBlock,
(sizeof(MS_CommandBlockWrapper_t) - 16),
StreamCallback_MS_Device_AbortOnMassStoreReset))
{
return false;
}
if ((MSInterfaceInfo->State.CommandBlock.Signature != MS_CBW_SIGNATURE) ||
(MSInterfaceInfo->State.CommandBlock.LUN >= MSInterfaceInfo->Config.TotalLUNs) ||
(MSInterfaceInfo->State.CommandBlock.Flags & 0x1F) ||
(MSInterfaceInfo->State.CommandBlock.SCSICommandLength == 0) ||
(MSInterfaceInfo->State.CommandBlock.SCSICommandLength > 16))
{
Endpoint_StallTransaction();
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpointNumber);
Endpoint_StallTransaction();
return false;
}
CallbackIsResetSource = &MSInterfaceInfo->State.IsMassStoreReset;
if (Endpoint_Read_Stream_LE(&MSInterfaceInfo->State.CommandBlock.SCSICommandData,
MSInterfaceInfo->State.CommandBlock.SCSICommandLength,
StreamCallback_MS_Device_AbortOnMassStoreReset))
{
return false;
}
Endpoint_ClearOUT();
return true;
}
static void MS_Device_ReturnCommandStatus(USB_ClassInfo_MS_Device_t* const MSInterfaceInfo)
{
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataOUTEndpointNumber);
while (Endpoint_IsStalled())
{
#if !defined(INTERRUPT_CONTROL_ENDPOINT)
USB_USBTask();
#endif
if (MSInterfaceInfo->State.IsMassStoreReset)
return;
}
Endpoint_SelectEndpoint(MSInterfaceInfo->Config.DataINEndpointNumber);
while (Endpoint_IsStalled())
{
#if !defined(INTERRUPT_CONTROL_ENDPOINT)
USB_USBTask();
#endif
if (MSInterfaceInfo->State.IsMassStoreReset)
return;
}
CallbackIsResetSource = &MSInterfaceInfo->State.IsMassStoreReset;
if (Endpoint_Write_Stream_LE(&MSInterfaceInfo->State.CommandStatus, sizeof(MS_CommandStatusWrapper_t),
StreamCallback_MS_Device_AbortOnMassStoreReset))
{
return;
}
Endpoint_ClearIN();
}
static uint8_t StreamCallback_MS_Device_AbortOnMassStoreReset(void)
{
#if !defined(INTERRUPT_CONTROL_ENDPOINT)
USB_USBTask();
#endif
if (*CallbackIsResetSource)
return STREAMCALLBACK_Abort;
else
return STREAMCALLBACK_Continue;
}
#endif
|
gpl-3.0
|
MyComputableRomance/DOOM-3
|
neo/sys/osx/PickMonitor.cpp
|
55
|
16292
|
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 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.
Doom 3 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 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 Doom 3 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.
===========================================================================
*/
#include "../../idlib/precompiled.h"
#include <Carbon/Carbon.h>
#include "PickMonitor.h"
//====================================================================================
// CONSTANTS
//====================================================================================
#define kMaxMonitors 16
//====================================================================================
// TYPES
//====================================================================================
typedef struct
{
GDHandle device;
Rect origRect;
Rect scaledRect;
int isMain;
}
Monitor;
//====================================================================================
// GLOBALS
//====================================================================================
static GDHandle sSelectedDevice;
static int sNumMonitors;
static Monitor sMonitors[kMaxMonitors];
static RGBColor rgbBlack = { 0x0000, 0x0000, 0x0000 };
static RGBColor rgbWhite = { 0xffff, 0xffff, 0xffff };
static RGBColor rgbGray = { 0x5252, 0x8A8A, 0xCCCC }; // this is the blue used in the Displays control panel
//====================================================================================
// MACROS
//====================================================================================
#undef PtInRect
#undef OffsetRect
#undef InsetRect
#undef EraseRect
#undef MoveTo
#undef LineTo
//====================================================================================
// IMPLEMENTATION
//====================================================================================
//-----------------------------------------------------------------------------
// SetupUserPaneProcs
//-----------------------------------------------------------------------------
// Call this to initialize the specified user pane control before displaying
// the dialog window. Pass NULL for any user pane procs you don't need to install.
OSErr SetupUserPaneProcs( ControlRef inUserPane,
ControlUserPaneDrawProcPtr inDrawProc,
ControlUserPaneHitTestProcPtr inHitTestProc,
ControlUserPaneTrackingProcPtr inTrackingProc)
{
OSErr err = noErr;
ControlUserPaneDrawUPP drawUPP;
ControlUserPaneHitTestUPP hitTestUPP;
ControlUserPaneTrackingUPP trackingUPP;
if (0 == inUserPane) return paramErr;
if (inDrawProc && noErr == err)
{
drawUPP = NewControlUserPaneDrawUPP(inDrawProc);
if (0 == drawUPP)
err = memFullErr;
else
err = SetControlData( inUserPane,
kControlEntireControl,
kControlUserPaneDrawProcTag,
sizeof(ControlUserPaneDrawUPP),
(Ptr)&drawUPP);
}
if (inHitTestProc && noErr == err)
{
hitTestUPP = NewControlUserPaneHitTestUPP(inHitTestProc);
if (0 == hitTestUPP)
err = memFullErr;
else
err = SetControlData( inUserPane,
kControlEntireControl,
kControlUserPaneHitTestProcTag,
sizeof(ControlUserPaneHitTestUPP),
(Ptr)&hitTestUPP);
}
if (inTrackingProc && noErr == err)
{
trackingUPP = NewControlUserPaneTrackingUPP(inTrackingProc);
if (0 == trackingUPP)
err = memFullErr;
else
err = SetControlData( inUserPane,
kControlEntireControl,
kControlUserPaneTrackingProcTag,
sizeof(ControlUserPaneTrackingUPP),
(Ptr)&trackingUPP);
}
return err;
}
//-----------------------------------------------------------------------------
// DisposeUserPaneProcs
//-----------------------------------------------------------------------------
// Call this to clean up when you're done with the specified user pane control.
OSErr DisposeUserPaneProcs(ControlRef inUserPane)
{
ControlUserPaneDrawUPP drawUPP;
ControlUserPaneHitTestUPP hitTestUPP;
ControlUserPaneTrackingUPP trackingUPP;
Size actualSize;
OSErr err;
err = GetControlData(inUserPane, kControlEntireControl, kControlUserPaneDrawProcTag, sizeof(ControlUserPaneDrawUPP), (Ptr)&drawUPP, &actualSize);
if (err == noErr) DisposeControlUserPaneDrawUPP(drawUPP);
err = GetControlData(inUserPane, kControlEntireControl, kControlUserPaneHitTestProcTag, sizeof(ControlUserPaneHitTestUPP), (Ptr)&hitTestUPP, &actualSize);
if (err == noErr) DisposeControlUserPaneHitTestUPP(hitTestUPP);
err = GetControlData(inUserPane, kControlEntireControl, kControlUserPaneTrackingProcTag, sizeof(ControlUserPaneTrackingUPP), (Ptr)&trackingUPP, &actualSize);
if (err == noErr) DisposeControlUserPaneTrackingUPP(trackingUPP);
return noErr;
}
#pragma mark -
//-----------------------------------------------------------------------------
// drawProc
//-----------------------------------------------------------------------------
// Custom drawProc for our UserPane control.
static pascal void drawProc(ControlRef inControl, SInt16 inPart)
{
#pragma unused(inControl, inPart)
int i;
RGBColor saveForeColor;
RGBColor saveBackColor;
PenState savePenState;
GetForeColor(&saveForeColor);
GetBackColor(&saveBackColor);
GetPenState(&savePenState);
RGBForeColor(&rgbBlack);
RGBBackColor(&rgbWhite);
PenNormal();
for (i = 0; i < sNumMonitors; i++)
{
RGBForeColor(&rgbGray);
PaintRect(&sMonitors[i].scaledRect);
if (sMonitors[i].isMain)
{
Rect r = sMonitors[i].scaledRect;
InsetRect(&r, 1, 1);
r.bottom = r.top + 6;
RGBForeColor(&rgbWhite);
PaintRect(&r);
RGBForeColor(&rgbBlack);
PenSize(1,1);
MoveTo(r.left, r.bottom);
LineTo(r.right, r.bottom);
}
if (sMonitors[i].device == sSelectedDevice)
{
PenSize(3,3);
RGBForeColor(&rgbBlack);
FrameRect(&sMonitors[i].scaledRect);
}
else
{
PenSize(1,1);
RGBForeColor(&rgbBlack);
FrameRect(&sMonitors[i].scaledRect);
}
}
// restore the original pen state and colors
RGBForeColor(&saveForeColor);
RGBBackColor(&saveBackColor);
SetPenState(&savePenState);
}
//-----------------------------------------------------------------------------
// hitTestProc
//-----------------------------------------------------------------------------
// Custom hitTestProc for our UserPane control.
// This allows FindControlUnderMouse() to locate our control, which allows
// ModalDialog() to call TrackControl() or HandleControlClick() for our control.
static pascal ControlPartCode hitTestProc(ControlRef inControl, Point inWhere)
{
// return a valid part code so HandleControlClick() will be called
return kControlButtonPart;
}
//-----------------------------------------------------------------------------
// trackingProc
//-----------------------------------------------------------------------------
// Custom trackingProc for our UserPane control.
// This won't be called for our control unless the kControlHandlesTracking feature
// bit is specified when the userPane is created.
static pascal ControlPartCode trackingProc (
ControlRef inControl,
Point inStartPt,
ControlActionUPP inActionProc)
{
#pragma unused (inControl, inStartPt, inActionProc)
int i;
for (i = 0; i < sNumMonitors; i++)
{
if (PtInRect(inStartPt, &sMonitors[i].scaledRect))
{
if (sMonitors[i].device != sSelectedDevice)
{
sSelectedDevice = sMonitors[i].device;
DrawOneControl(inControl);
}
break;
}
}
return kControlNoPart;
}
#pragma mark -
//-----------------------------------------------------------------------------
// SetupPickMonitorPane
//-----------------------------------------------------------------------------
// Call this to initialize the user pane control that is the Pick Monitor
// control. Pass the ControlRef of the user pane control and a display ID
// for the monitor you want selected by default (pass 0 for the main monitor).
// Call this function before displaying the dialog window.
OSErr SetupPickMonitorPane(ControlRef inPane, DisplayIDType inDefaultMonitor)
{
GDHandle dev = GetDeviceList();
OSErr err = noErr;
// make the default monitor the selected device
if (inDefaultMonitor)
DMGetGDeviceByDisplayID(inDefaultMonitor, &sSelectedDevice, true);
else
sSelectedDevice = GetMainDevice();
// build the list of monitors
sNumMonitors = 0;
while (dev && sNumMonitors < kMaxMonitors)
{
if (TestDeviceAttribute(dev, screenDevice) && TestDeviceAttribute(dev, screenActive))
{
sMonitors[sNumMonitors].device = dev;
sMonitors[sNumMonitors].origRect = (**dev).gdRect;
sMonitors[sNumMonitors].isMain = (dev == GetMainDevice());
sNumMonitors++;
}
dev = GetNextDevice(dev);
}
// calculate scaled rects
if (sNumMonitors)
{
Rect origPaneRect, paneRect;
Rect origGrayRect, grayRect, scaledGrayRect;
float srcAspect, dstAspect, scale;
int i;
GetControlBounds(inPane, &origPaneRect);
paneRect = origPaneRect;
OffsetRect(&paneRect, -paneRect.left, -paneRect.top);
GetRegionBounds(GetGrayRgn(), &origGrayRect);
grayRect = origGrayRect;
OffsetRect(&grayRect, -grayRect.left, -grayRect.top);
srcAspect = (float)grayRect.right / (float)grayRect.bottom;
dstAspect = (float)paneRect.right / (float)paneRect.bottom;
scaledGrayRect = paneRect;
if (srcAspect < dstAspect)
{
scaledGrayRect.right = (float)paneRect.bottom * srcAspect;
scale = (float)scaledGrayRect.right / grayRect.right;
}
else
{
scaledGrayRect.bottom = (float)paneRect.right / srcAspect;
scale = (float)scaledGrayRect.bottom / grayRect.bottom;
}
for (i = 0; i < sNumMonitors; i++)
{
Rect r = sMonitors[i].origRect;
Rect r2 = r;
// normalize rect and scale
OffsetRect(&r, -r.left, -r.top);
r.bottom = (float)r.bottom * scale;
r.right = (float)r.right * scale;
// offset rect wrt gray region
OffsetRect(&r, (float)(r2.left - origGrayRect.left) * scale,
(float)(r2.top - origGrayRect.top) * scale);
sMonitors[i].scaledRect = r;
}
// center scaledGrayRect in the pane
OffsetRect(&scaledGrayRect, (paneRect.right - scaledGrayRect.right) / 2,
(paneRect.bottom - scaledGrayRect.bottom) / 2);
// offset monitors to match
for (i = 0; i < sNumMonitors; i++)
OffsetRect(&sMonitors[i].scaledRect, scaledGrayRect.left, scaledGrayRect.top);
}
else
return paramErr;
// setup the procs for the pick monitor user pane
err = SetupUserPaneProcs(inPane, drawProc, hitTestProc, trackingProc);
return err;
}
//-----------------------------------------------------------------------------
// TearDownPickMonitorPane
//-----------------------------------------------------------------------------
// Disposes of everything associated with the Pick Monitor pane. You should
// call this when disposing the dialog.
OSErr TearDownPickMonitorPane(ControlRef inPane)
{
OSErr err;
err = DisposeUserPaneProcs(inPane);
sNumMonitors = 0;
return err;
}
#pragma mark -
//------------------------------------------------------------------------------------
// ¥ PickMonitorHandler
//------------------------------------------------------------------------------------
// Our command handler for the PickMonitor dialog.
static pascal OSStatus PickMonitorHandler( EventHandlerCallRef inHandler, EventRef inEvent, void* inUserData )
{
#pragma unused( inHandler )
HICommand cmd;
OSStatus result = eventNotHandledErr;
WindowRef theWindow = (WindowRef)inUserData;
// The direct object for a 'process commmand' event is the HICommand.
// Extract it here and switch off the command ID.
GetEventParameter( inEvent, kEventParamDirectObject, typeHICommand, NULL, sizeof( cmd ), NULL, &cmd );
switch ( cmd.commandID )
{
case kHICommandOK:
QuitAppModalLoopForWindow( theWindow );
result = noErr;
break;
case kHICommandCancel:
// Setting sSelectedDevice to zero will signal that the user cancelled.
sSelectedDevice = 0;
QuitAppModalLoopForWindow( theWindow );
result = noErr;
break;
}
return result;
}
#pragma mark -
//-----------------------------------------------------------------------------
// CanUserPickMonitor
//-----------------------------------------------------------------------------
// Returns true if more than one monitor is available to choose from.
Boolean CanUserPickMonitor (void)
{
GDHandle dev = GetDeviceList();
OSErr err = noErr;
int numMonitors;
// build the list of monitors
numMonitors = 0;
while (dev && numMonitors < kMaxMonitors)
{
if (TestDeviceAttribute(dev, screenDevice) && TestDeviceAttribute(dev, screenActive))
{
numMonitors++;
}
dev = GetNextDevice(dev);
}
if (numMonitors > 1) return true;
else return false;
}
//-----------------------------------------------------------------------------
// PickMonitor
//-----------------------------------------------------------------------------
// Prompts for a monitor. Returns userCanceledErr if the user cancelled.
OSStatus PickMonitor (DisplayIDType *inOutDisplayID, WindowRef parentWindow)
{
WindowRef theWindow;
OSStatus status = noErr;
static const ControlID kUserPane = { 'MONI', 1 };
// Fetch the dialog
IBNibRef aslNib;
CFBundleRef theBundle = CFBundleGetMainBundle();
status = CreateNibReferenceWithCFBundle(theBundle, CFSTR("ASLCore"), &aslNib);
status = ::CreateWindowFromNib(aslNib, CFSTR( "Pick Monitor" ), &theWindow );
if (status != noErr)
{
assert(false);
return userCanceledErr;
}
#if 0
// Put game name in window title. By default the title includes the token <<<kGameName>>>.
Str255 windowTitle;
GetWTitle(theWindow, windowTitle);
FormatPStringWithGameName(windowTitle);
SetWTitle(theWindow, windowTitle);
#endif
// Set up the controls
ControlRef monitorPane;
GetControlByID( theWindow, &kUserPane, &monitorPane );
assert(monitorPane);
SetupPickMonitorPane(monitorPane, *inOutDisplayID);
// Create our UPP and install the handler.
EventTypeSpec cmdEvent = { kEventClassCommand, kEventCommandProcess };
EventHandlerUPP handler = NewEventHandlerUPP( PickMonitorHandler );
InstallWindowEventHandler( theWindow, handler, 1, &cmdEvent, theWindow, NULL );
// Show the window
if (parentWindow)
ShowSheetWindow( theWindow, parentWindow );
else
ShowWindow( theWindow );
// Now we run modally. We will remain here until the PrefHandler
// calls QuitAppModalLoopForWindow if the user clicks OK or
// Cancel.
RunAppModalLoopForWindow( theWindow );
// OK, we're done. Dispose of our window and our UPP.
// We do the UPP last because DisposeWindow can send out
// CarbonEvents, and we haven't explicitly removed our
// handler. If we disposed the UPP, the Toolbox might try
// to call it. That would be bad.
TearDownPickMonitorPane(monitorPane);
if (parentWindow)
HideSheetWindow( theWindow );
DisposeWindow( theWindow );
DisposeEventHandlerUPP( handler );
// Return settings to caller
if (sSelectedDevice != 0)
{
// Read back the controls
DMGetDisplayIDByGDevice (sSelectedDevice, &*inOutDisplayID, true);
return noErr;
}
else
return userCanceledErr;
}
|
gpl-3.0
|
Nargesf/Sumatrapdf
|
ext/lzma/C/Threads.c
|
55
|
2712
|
/* Threads.c -- multithreading library
2009-09-20 : Igor Pavlov : Public domain */
#ifndef _WIN32_WCE
#include <process.h>
#endif
#include "Threads.h"
static WRes GetError()
{
DWORD res = GetLastError();
return (res) ? (WRes)(res) : 1;
}
WRes HandleToWRes(HANDLE h) { return (h != 0) ? 0 : GetError(); }
WRes BOOLToWRes(BOOL v) { return v ? 0 : GetError(); }
WRes HandlePtr_Close(HANDLE *p)
{
if (*p != NULL)
if (!CloseHandle(*p))
return GetError();
*p = NULL;
return 0;
}
WRes Handle_WaitObject(HANDLE h) { return (WRes)WaitForSingleObject(h, INFINITE); }
WRes Thread_Create(CThread *p, THREAD_FUNC_TYPE func, LPVOID param)
{
unsigned threadId; /* Windows Me/98/95: threadId parameter may not be NULL in _beginthreadex/CreateThread functions */
*p =
#ifdef UNDER_CE
CreateThread(0, 0, func, param, 0, &threadId);
#else
(HANDLE)_beginthreadex(NULL, 0, func, param, 0, &threadId);
#endif
/* maybe we must use errno here, but probably GetLastError() is also OK. */
return HandleToWRes(*p);
}
WRes Event_Create(CEvent *p, BOOL manualReset, int signaled)
{
*p = CreateEvent(NULL, manualReset, (signaled ? TRUE : FALSE), NULL);
return HandleToWRes(*p);
}
WRes Event_Set(CEvent *p) { return BOOLToWRes(SetEvent(*p)); }
WRes Event_Reset(CEvent *p) { return BOOLToWRes(ResetEvent(*p)); }
WRes ManualResetEvent_Create(CManualResetEvent *p, int signaled) { return Event_Create(p, TRUE, signaled); }
WRes AutoResetEvent_Create(CAutoResetEvent *p, int signaled) { return Event_Create(p, FALSE, signaled); }
WRes ManualResetEvent_CreateNotSignaled(CManualResetEvent *p) { return ManualResetEvent_Create(p, 0); }
WRes AutoResetEvent_CreateNotSignaled(CAutoResetEvent *p) { return AutoResetEvent_Create(p, 0); }
WRes Semaphore_Create(CSemaphore *p, UInt32 initCount, UInt32 maxCount)
{
*p = CreateSemaphore(NULL, (LONG)initCount, (LONG)maxCount, NULL);
return HandleToWRes(*p);
}
static WRes Semaphore_Release(CSemaphore *p, LONG releaseCount, LONG *previousCount)
{ return BOOLToWRes(ReleaseSemaphore(*p, releaseCount, previousCount)); }
WRes Semaphore_ReleaseN(CSemaphore *p, UInt32 num)
{ return Semaphore_Release(p, (LONG)num, NULL); }
WRes Semaphore_Release1(CSemaphore *p) { return Semaphore_ReleaseN(p, 1); }
WRes CriticalSection_Init(CCriticalSection *p)
{
/* InitializeCriticalSection can raise only STATUS_NO_MEMORY exception */
#ifdef _MSC_VER
__try
#endif
{
InitializeCriticalSection(p);
/* InitializeCriticalSectionAndSpinCount(p, 0); */
}
#ifdef _MSC_VER
__except (EXCEPTION_EXECUTE_HANDLER) { return 1; }
#endif
return 0;
}
|
gpl-3.0
|
bowlofstew/Doom3-for-MacOSX-
|
neo/tools/radiant/DlgEvent.cpp
|
57
|
2448
|
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 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.
Doom 3 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 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 Doom 3 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.
===========================================================================
*/
#include "../../idlib/precompiled.h"
#pragma hdrstop
#include "qe3.h"
#include "DlgEvent.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgEvent dialog
CDlgEvent::CDlgEvent(CWnd* pParent /*=NULL*/)
: CDialog(CDlgEvent::IDD, pParent)
{
//{{AFX_DATA_INIT(CDlgEvent)
m_strParm = _T("");
m_event = 0;
//}}AFX_DATA_INIT
}
void CDlgEvent::DoDataExchange(CDataExchange* pDX)
{
CDialog::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgEvent)
DDX_Text(pDX, IDC_EDIT_PARAM, m_strParm);
DDX_Radio(pDX, IDC_RADIO_EVENT, m_event);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgEvent, CDialog)
//{{AFX_MSG_MAP(CDlgEvent)
// NOTE: the ClassWizard will add message map macros here
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgEvent message handlers
|
gpl-3.0
|
Perpixel/Doom3
|
neo/ui/GuiScript.cpp
|
58
|
15802
|
/*
===========================================================================
Doom 3 GPL Source Code
Copyright (C) 1999-2011 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 GPL Source Code (?Doom 3 Source Code?).
Doom 3 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.
Doom 3 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 Doom 3 Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 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 Doom 3 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.
===========================================================================
*/
#include "../idlib/precompiled.h"
#pragma hdrstop
#include "Window.h"
#include "Winvar.h"
#include "GuiScript.h"
#include "UserInterfaceLocal.h"
/*
=========================
Script_Set
=========================
*/
void Script_Set(idWindow *window, idList<idGSWinVar> *src) {
idStr key, val;
idWinStr *dest = dynamic_cast<idWinStr*>((*src)[0].var);
if (dest) {
if (idStr::Icmp(*dest, "cmd") == 0) {
dest = dynamic_cast<idWinStr*>((*src)[1].var);
int parmCount = src->Num();
if (parmCount > 2) {
val = dest->c_str();
int i = 2;
while (i < parmCount) {
val += " \"";
val += (*src)[i].var->c_str();
val += "\"";
i++;
}
window->AddCommand(val);
} else {
window->AddCommand(*dest);
}
return;
}
}
(*src)[0].var->Set((*src)[1].var->c_str());
(*src)[0].var->SetEval(false);
}
/*
=========================
Script_SetFocus
=========================
*/
void Script_SetFocus(idWindow *window, idList<idGSWinVar> *src) {
idWinStr *parm = dynamic_cast<idWinStr*>((*src)[0].var);
if (parm) {
drawWin_t *win = window->GetGui()->GetDesktop()->FindChildByName(*parm);
if (win && win->win) {
window->SetFocus(win->win);
}
}
}
/*
=========================
Script_ShowCursor
=========================
*/
void Script_ShowCursor(idWindow *window, idList<idGSWinVar> *src) {
idWinStr *parm = dynamic_cast<idWinStr*>((*src)[0].var);
if ( parm ) {
if ( atoi( *parm ) ) {
window->GetGui()->GetDesktop()->ClearFlag( WIN_NOCURSOR );
} else {
window->GetGui()->GetDesktop()->SetFlag( WIN_NOCURSOR );
}
}
}
/*
=========================
Script_RunScript
run scripts must come after any set cmd set's in the script
=========================
*/
void Script_RunScript(idWindow *window, idList<idGSWinVar> *src) {
idWinStr *parm = dynamic_cast<idWinStr*>((*src)[0].var);
if (parm) {
idStr str = window->cmd;
str += " ; runScript ";
str += parm->c_str();
window->cmd = str;
}
}
/*
=========================
Script_LocalSound
=========================
*/
void Script_LocalSound(idWindow *window, idList<idGSWinVar> *src) {
idWinStr *parm = dynamic_cast<idWinStr*>((*src)[0].var);
if (parm) {
session->sw->PlayShaderDirectly(*parm);
}
}
/*
=========================
Script_EvalRegs
=========================
*/
void Script_EvalRegs(idWindow *window, idList<idGSWinVar> *src) {
window->EvalRegs(-1, true);
}
/*
=========================
Script_EndGame
=========================
*/
void Script_EndGame( idWindow *window, idList<idGSWinVar> *src ) {
cvarSystem->SetCVarBool( "g_nightmare", true );
cmdSystem->BufferCommandText( CMD_EXEC_APPEND, "disconnect\n" );
}
/*
=========================
Script_ResetTime
=========================
*/
void Script_ResetTime(idWindow *window, idList<idGSWinVar> *src) {
idWinStr *parm = dynamic_cast<idWinStr*>((*src)[0].var);
drawWin_t *win = NULL;
if (parm && src->Num() > 1) {
win = window->GetGui()->GetDesktop()->FindChildByName(*parm);
parm = dynamic_cast<idWinStr*>((*src)[1].var);
}
if (win && win->win) {
win->win->ResetTime(atoi(*parm));
win->win->EvalRegs(-1, true);
} else {
window->ResetTime(atoi(*parm));
window->EvalRegs(-1, true);
}
}
/*
=========================
Script_ResetCinematics
=========================
*/
void Script_ResetCinematics(idWindow *window, idList<idGSWinVar> *src) {
window->ResetCinematics();
}
/*
=========================
Script_Transition
=========================
*/
void Script_Transition(idWindow *window, idList<idGSWinVar> *src) {
// transitions always affect rect or vec4 vars
if (src->Num() >= 4) {
idWinRectangle *rect = NULL;
idWinVec4 *vec4 = dynamic_cast<idWinVec4*>((*src)[0].var);
//
// added float variable
idWinFloat* val = NULL;
//
if (vec4 == NULL) {
rect = dynamic_cast<idWinRectangle*>((*src)[0].var);
//
// added float variable
if ( NULL == rect ) {
val = dynamic_cast<idWinFloat*>((*src)[0].var);
}
//
}
idWinVec4 *from = dynamic_cast<idWinVec4*>((*src)[1].var);
idWinVec4 *to = dynamic_cast<idWinVec4*>((*src)[2].var);
idWinStr *timeStr = dynamic_cast<idWinStr*>((*src)[3].var);
//
// added float variable
if (!((vec4 || rect || val) && from && to && timeStr)) {
//
common->Warning("Bad transition in gui %s in window %s\n", window->GetGui()->GetSourceFile(), window->GetName());
return;
}
int time = atoi(*timeStr);
float ac = 0.0f;
float dc = 0.0f;
if (src->Num() > 4) {
idWinStr *acv = dynamic_cast<idWinStr*>((*src)[4].var);
idWinStr *dcv = dynamic_cast<idWinStr*>((*src)[5].var);
assert(acv && dcv);
ac = atof(*acv);
dc = atof(*dcv);
}
if (vec4) {
vec4->SetEval(false);
window->AddTransition(vec4, *from, *to, time, ac, dc);
//
// added float variable
} else if ( val ) {
val->SetEval ( false );
window->AddTransition(val, *from, *to, time, ac, dc);
//
} else {
rect->SetEval(false);
window->AddTransition(rect, *from, *to, time, ac, dc);
}
window->StartTransition();
}
}
typedef struct {
const char *name;
void (*handler) (idWindow *window, idList<idGSWinVar> *src);
int mMinParms;
int mMaxParms;
} guiCommandDef_t;
guiCommandDef_t commandList[] = {
{ "set", Script_Set, 2, 999 },
{ "setFocus", Script_SetFocus, 1, 1 },
{ "endGame", Script_EndGame, 0, 0 },
{ "resetTime", Script_ResetTime, 0, 2 },
{ "showCursor", Script_ShowCursor, 1, 1 },
{ "resetCinematics", Script_ResetCinematics, 0, 2 },
{ "transition", Script_Transition, 4, 6 },
{ "localSound", Script_LocalSound, 1, 1 },
{ "runScript", Script_RunScript, 1, 1 },
{ "evalRegs", Script_EvalRegs, 0, 0 }
};
int scriptCommandCount = sizeof(commandList) / sizeof(guiCommandDef_t);
/*
=========================
idGuiScript::idGuiScript
=========================
*/
idGuiScript::idGuiScript() {
ifList = NULL;
elseList = NULL;
conditionReg = -1;
handler = NULL;
parms.SetGranularity( 2 );
}
/*
=========================
idGuiScript::~idGuiScript
=========================
*/
idGuiScript::~idGuiScript() {
delete ifList;
delete elseList;
int c = parms.Num();
for ( int i = 0; i < c; i++ ) {
if ( parms[i].own ) {
delete parms[i].var;
}
}
}
/*
=========================
idGuiScript::WriteToSaveGame
=========================
*/
void idGuiScript::WriteToSaveGame( idFile *savefile ) {
int i;
if ( ifList ) {
ifList->WriteToSaveGame( savefile );
}
if ( elseList ) {
elseList->WriteToSaveGame( savefile );
}
savefile->Write( &conditionReg, sizeof( conditionReg ) );
for ( i = 0; i < parms.Num(); i++ ) {
if ( parms[i].own ) {
parms[i].var->WriteToSaveGame( savefile );
}
}
}
/*
=========================
idGuiScript::ReadFromSaveGame
=========================
*/
void idGuiScript::ReadFromSaveGame( idFile *savefile ) {
int i;
if ( ifList ) {
ifList->ReadFromSaveGame( savefile );
}
if ( elseList ) {
elseList->ReadFromSaveGame( savefile );
}
savefile->Read( &conditionReg, sizeof( conditionReg ) );
for ( i = 0; i < parms.Num(); i++ ) {
if ( parms[i].own ) {
parms[i].var->ReadFromSaveGame( savefile );
}
}
}
/*
=========================
idGuiScript::Parse
=========================
*/
bool idGuiScript::Parse(idParser *src) {
int i;
// first token should be function call
// then a potentially variable set of parms
// ended with a ;
idToken token;
if ( !src->ReadToken(&token) ) {
src->Error( "Unexpected end of file" );
return false;
}
handler = NULL;
for ( i = 0; i < scriptCommandCount ; i++ ) {
if ( idStr::Icmp(token, commandList[i].name) == 0 ) {
handler = commandList[i].handler;
break;
}
}
if (handler == NULL) {
src->Error("Uknown script call %s", token.c_str());
}
// now read parms til ;
// all parms are read as idWinStr's but will be fixed up later
// to be proper types
while (1) {
if ( !src->ReadToken(&token) ) {
src->Error( "Unexpected end of file" );
return false;
}
if (idStr::Icmp(token, ";") == 0) {
break;
}
if (idStr::Icmp(token, "}") == 0) {
src->UnreadToken(&token);
break;
}
idWinStr *str = new idWinStr();
*str = token;
idGSWinVar wv;
wv.own = true;
wv.var = str;
parms.Append( wv );
}
//
// verify min/max params
if ( handler && (parms.Num() < commandList[i].mMinParms || parms.Num() > commandList[i].mMaxParms ) ) {
src->Error("incorrect number of parameters for script %s", commandList[i].name );
}
//
return true;
}
/*
=========================
idGuiScriptList::Execute
=========================
*/
void idGuiScriptList::Execute(idWindow *win) {
int c = list.Num();
for (int i = 0; i < c; i++) {
idGuiScript *gs = list[i];
assert(gs);
if (gs->conditionReg >= 0) {
if (win->HasOps()) {
float f = win->EvalRegs(gs->conditionReg);
if (f) {
if (gs->ifList) {
win->RunScriptList(gs->ifList);
}
} else if (gs->elseList) {
win->RunScriptList(gs->elseList);
}
}
}
gs->Execute(win);
}
}
/*
=========================
idGuiScriptList::FixupParms
=========================
*/
void idGuiScript::FixupParms(idWindow *win) {
if (handler == &Script_Set) {
bool precacheBackground = false;
bool precacheSounds = false;
idWinStr *str = dynamic_cast<idWinStr*>(parms[0].var);
assert(str);
idWinVar *dest = win->GetWinVarByName(*str, true);
if (dest) {
delete parms[0].var;
parms[0].var = dest;
parms[0].own = false;
if ( dynamic_cast<idWinBackground *>(dest) != NULL ) {
precacheBackground = true;
}
} else if ( idStr::Icmp( str->c_str(), "cmd" ) == 0 ) {
precacheSounds = true;
}
int parmCount = parms.Num();
for (int i = 1; i < parmCount; i++) {
idWinStr *str = dynamic_cast<idWinStr*>(parms[i].var);
if (idStr::Icmpn(*str, "gui::", 5) == 0) {
// always use a string here, no point using a float if it is one
// FIXME: This creates duplicate variables, while not technically a problem since they
// are all bound to the same guiDict, it does consume extra memory and is generally a bad thing
idWinStr* defvar = new idWinStr();
defvar->Init ( *str, win );
win->AddDefinedVar ( defvar );
delete parms[i].var;
parms[i].var = defvar;
parms[i].own = false;
//dest = win->GetWinVarByName(*str, true);
//if (dest) {
// delete parms[i].var;
// parms[i].var = dest;
// parms[i].own = false;
//}
//
} else if ((*str[0]) == '$') {
//
// dont include the $ when asking for variable
dest = win->GetGui()->GetDesktop()->GetWinVarByName((const char*)(*str) + 1, true);
//
if (dest) {
delete parms[i].var;
parms[i].var = dest;
parms[i].own = false;
}
} else if ( idStr::Cmpn( str->c_str(), STRTABLE_ID, STRTABLE_ID_LENGTH ) == 0 ) {
str->Set( common->GetLanguageDict()->GetString( str->c_str() ) );
} else if ( precacheBackground ) {
const idMaterial *mat = declManager->FindMaterial( str->c_str() );
mat->SetSort( SS_GUI );
} else if ( precacheSounds ) {
// Search for "play <...>"
idToken token;
idParser parser( LEXFL_NOSTRINGCONCAT | LEXFL_ALLOWMULTICHARLITERALS | LEXFL_ALLOWBACKSLASHSTRINGCONCAT );
parser.LoadMemory(str->c_str(), str->Length(), "command");
while ( parser.ReadToken(&token) ) {
if ( token.Icmp("play") == 0 ) {
if ( parser.ReadToken(&token) && ( token != "" ) ) {
declManager->FindSound( token.c_str() );
}
}
}
}
}
} else if (handler == &Script_Transition) {
if (parms.Num() < 4) {
common->Warning("Window %s in gui %s has a bad transition definition", win->GetName(), win->GetGui()->GetSourceFile());
}
idWinStr *str = dynamic_cast<idWinStr*>(parms[0].var);
assert(str);
//
drawWin_t *destowner;
idWinVar *dest = win->GetWinVarByName(*str, true, &destowner );
//
if (dest) {
delete parms[0].var;
parms[0].var = dest;
parms[0].own = false;
} else {
common->Warning("Window %s in gui %s: a transition does not have a valid destination var %s", win->GetName(), win->GetGui()->GetSourceFile(),str->c_str());
}
//
// support variables as parameters
int c;
for ( c = 1; c < 3; c ++ ) {
str = dynamic_cast<idWinStr*>(parms[c].var);
idWinVec4 *v4 = new idWinVec4;
parms[c].var = v4;
parms[c].own = true;
drawWin_t* owner;
if ( (*str[0]) == '$' ) {
dest = win->GetWinVarByName ( (const char*)(*str) + 1, true, &owner );
} else {
dest = NULL;
}
if ( dest ) {
idWindow* ownerparent;
idWindow* destparent;
if ( owner ) {
ownerparent = owner->simp?owner->simp->GetParent():owner->win->GetParent();
destparent = destowner->simp?destowner->simp->GetParent():destowner->win->GetParent();
// If its the rectangle they are referencing then adjust it
if ( ownerparent && destparent &&
(dest == (owner->simp?owner->simp->GetWinVarByName ( "rect" ):owner->win->GetWinVarByName ( "rect" ) ) ) )
{
idRectangle rect;
rect = *(dynamic_cast<idWinRectangle*>(dest));
ownerparent->ClientToScreen ( &rect );
destparent->ScreenToClient ( &rect );
*v4 = rect.ToVec4 ( );
} else {
v4->Set ( dest->c_str ( ) );
}
} else {
v4->Set ( dest->c_str ( ) );
}
} else {
v4->Set(*str);
}
delete str;
}
//
} else {
int c = parms.Num();
for (int i = 0; i < c; i++) {
parms[i].var->Init(parms[i].var->c_str(), win);
}
}
}
/*
=========================
idGuiScriptList::FixupParms
=========================
*/
void idGuiScriptList::FixupParms(idWindow *win) {
int c = list.Num();
for (int i = 0; i < c; i++) {
idGuiScript *gs = list[i];
gs->FixupParms(win);
if (gs->ifList) {
gs->ifList->FixupParms(win);
}
if (gs->elseList) {
gs->elseList->FixupParms(win);
}
}
}
/*
=========================
idGuiScriptList::WriteToSaveGame
=========================
*/
void idGuiScriptList::WriteToSaveGame( idFile *savefile ) {
int i;
for ( i = 0; i < list.Num(); i++ ) {
list[i]->WriteToSaveGame( savefile );
}
}
/*
=========================
idGuiScriptList::ReadFromSaveGame
=========================
*/
void idGuiScriptList::ReadFromSaveGame( idFile *savefile ) {
int i;
for ( i = 0; i < list.Num(); i++ ) {
list[i]->ReadFromSaveGame( savefile );
}
}
|
gpl-3.0
|
tsunli/shadowsocks-android
|
src/main/jni/openssl/crypto/x509/x509spki.c
|
828
|
4379
|
/* x509spki.c */
/* Written by Dr Stephen N Henson (steve@openssl.org) for the OpenSSL
* project 1999.
*/
/* ====================================================================
* Copyright (c) 1999 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* licensing@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/x509.h>
int NETSCAPE_SPKI_set_pubkey(NETSCAPE_SPKI *x, EVP_PKEY *pkey)
{
if ((x == NULL) || (x->spkac == NULL)) return(0);
return(X509_PUBKEY_set(&(x->spkac->pubkey),pkey));
}
EVP_PKEY *NETSCAPE_SPKI_get_pubkey(NETSCAPE_SPKI *x)
{
if ((x == NULL) || (x->spkac == NULL))
return(NULL);
return(X509_PUBKEY_get(x->spkac->pubkey));
}
/* Load a Netscape SPKI from a base64 encoded string */
NETSCAPE_SPKI * NETSCAPE_SPKI_b64_decode(const char *str, int len)
{
unsigned char *spki_der;
const unsigned char *p;
int spki_len;
NETSCAPE_SPKI *spki;
if(len <= 0) len = strlen(str);
if (!(spki_der = OPENSSL_malloc(len + 1))) {
X509err(X509_F_NETSCAPE_SPKI_B64_DECODE, ERR_R_MALLOC_FAILURE);
return NULL;
}
spki_len = EVP_DecodeBlock(spki_der, (const unsigned char *)str, len);
if(spki_len < 0) {
X509err(X509_F_NETSCAPE_SPKI_B64_DECODE,
X509_R_BASE64_DECODE_ERROR);
OPENSSL_free(spki_der);
return NULL;
}
p = spki_der;
spki = d2i_NETSCAPE_SPKI(NULL, &p, spki_len);
OPENSSL_free(spki_der);
return spki;
}
/* Generate a base64 encoded string from an SPKI */
char * NETSCAPE_SPKI_b64_encode(NETSCAPE_SPKI *spki)
{
unsigned char *der_spki, *p;
char *b64_str;
int der_len;
der_len = i2d_NETSCAPE_SPKI(spki, NULL);
der_spki = OPENSSL_malloc(der_len);
b64_str = OPENSSL_malloc(der_len * 2);
if(!der_spki || !b64_str) {
X509err(X509_F_NETSCAPE_SPKI_B64_ENCODE, ERR_R_MALLOC_FAILURE);
return NULL;
}
p = der_spki;
i2d_NETSCAPE_SPKI(spki, &p);
EVP_EncodeBlock((unsigned char *)b64_str, der_spki, der_len);
OPENSSL_free(der_spki);
return b64_str;
}
|
gpl-3.0
|
xinyue/shadowsocks-libev
|
libsodium/test/default/box.c
|
345
|
3764
|
#define TEST_NAME "box"
#include "cmptest.h"
unsigned char alicesk[32]
= { 0x77, 0x07, 0x6d, 0x0a, 0x73, 0x18, 0xa5, 0x7d, 0x3c, 0x16, 0xc1,
0x72, 0x51, 0xb2, 0x66, 0x45, 0xdf, 0x4c, 0x2f, 0x87, 0xeb, 0xc0,
0x99, 0x2a, 0xb1, 0x77, 0xfb, 0xa5, 0x1d, 0xb9, 0x2c, 0x2a };
unsigned char bobpk[32]
= { 0xde, 0x9e, 0xdb, 0x7d, 0x7b, 0x7d, 0xc1, 0xb4, 0xd3, 0x5b, 0x61,
0xc2, 0xec, 0xe4, 0x35, 0x37, 0x3f, 0x83, 0x43, 0xc8, 0x5b, 0x78,
0x67, 0x4d, 0xad, 0xfc, 0x7e, 0x14, 0x6f, 0x88, 0x2b, 0x4f };
unsigned char nonce[24] = { 0x69, 0x69, 0x6e, 0xe9, 0x55, 0xb6, 0x2b, 0x73,
0xcd, 0x62, 0xbd, 0xa8, 0x75, 0xfc, 0x73, 0xd6,
0x82, 0x19, 0xe0, 0x03, 0x6b, 0x7a, 0x0b, 0x37 };
// API requires first 32 bytes to be 0
unsigned char m[163]
= { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0xbe, 0x07, 0x5f, 0xc5,
0x3c, 0x81, 0xf2, 0xd5, 0xcf, 0x14, 0x13, 0x16, 0xeb, 0xeb, 0x0c, 0x7b,
0x52, 0x28, 0xc5, 0x2a, 0x4c, 0x62, 0xcb, 0xd4, 0x4b, 0x66, 0x84, 0x9b,
0x64, 0x24, 0x4f, 0xfc, 0xe5, 0xec, 0xba, 0xaf, 0x33, 0xbd, 0x75, 0x1a,
0x1a, 0xc7, 0x28, 0xd4, 0x5e, 0x6c, 0x61, 0x29, 0x6c, 0xdc, 0x3c, 0x01,
0x23, 0x35, 0x61, 0xf4, 0x1d, 0xb6, 0x6c, 0xce, 0x31, 0x4a, 0xdb, 0x31,
0x0e, 0x3b, 0xe8, 0x25, 0x0c, 0x46, 0xf0, 0x6d, 0xce, 0xea, 0x3a, 0x7f,
0xa1, 0x34, 0x80, 0x57, 0xe2, 0xf6, 0x55, 0x6a, 0xd6, 0xb1, 0x31, 0x8a,
0x02, 0x4a, 0x83, 0x8f, 0x21, 0xaf, 0x1f, 0xde, 0x04, 0x89, 0x77, 0xeb,
0x48, 0xf5, 0x9f, 0xfd, 0x49, 0x24, 0xca, 0x1c, 0x60, 0x90, 0x2e, 0x52,
0xf0, 0xa0, 0x89, 0xbc, 0x76, 0x89, 0x70, 0x40, 0xe0, 0x82, 0xf9, 0x37,
0x76, 0x38, 0x48, 0x64, 0x5e, 0x07, 0x05 };
unsigned char c[163];
int main(void)
{
unsigned char k[crypto_box_BEFORENMBYTES];
int i;
crypto_box(c, m, 163, nonce, bobpk, alicesk);
for (i = 16; i < 163; ++i) {
printf(",0x%02x", (unsigned int)c[i]);
if (i % 8 == 7)
printf("\n");
}
printf("\n");
memset(c, 0, sizeof c);
crypto_box_beforenm(k, bobpk, alicesk);
crypto_box_afternm(c, m, 163, nonce, k);
for (i = 16; i < 163; ++i) {
printf(",0x%02x", (unsigned int)c[i]);
if (i % 8 == 7)
printf("\n");
}
printf("\n");
assert(crypto_box_seedbytes() > 0U);
assert(crypto_box_publickeybytes() > 0U);
assert(crypto_box_secretkeybytes() > 0U);
assert(crypto_box_beforenmbytes() > 0U);
assert(crypto_box_noncebytes() > 0U);
assert(crypto_box_zerobytes() > 0U);
assert(crypto_box_boxzerobytes() > 0U);
assert(crypto_box_macbytes() > 0U);
assert(strcmp(crypto_box_primitive(), "curve25519xsalsa20poly1305") == 0);
assert(crypto_box_curve25519xsalsa20poly1305_seedbytes()
== crypto_box_seedbytes());
assert(crypto_box_curve25519xsalsa20poly1305_publickeybytes()
== crypto_box_publickeybytes());
assert(crypto_box_curve25519xsalsa20poly1305_secretkeybytes()
== crypto_box_secretkeybytes());
assert(crypto_box_curve25519xsalsa20poly1305_beforenmbytes()
== crypto_box_beforenmbytes());
assert(crypto_box_curve25519xsalsa20poly1305_noncebytes()
== crypto_box_noncebytes());
assert(crypto_box_curve25519xsalsa20poly1305_zerobytes()
== crypto_box_zerobytes());
assert(crypto_box_curve25519xsalsa20poly1305_boxzerobytes()
== crypto_box_boxzerobytes());
assert(crypto_box_curve25519xsalsa20poly1305_macbytes()
== crypto_box_macbytes());
return 0;
}
|
gpl-3.0
|
sureshkwarrier/Sipdroid
|
jni/bx16_fixedp/bv16/coarptch.c
|
98
|
19975
|
/*****************************************************************************/
/* BroadVoice(R)16 (BV16) Fixed-Point ANSI-C Source Code */
/* Revision Date: November 13, 2009 */
/* Version 1.1 */
/*****************************************************************************/
/*****************************************************************************/
/* Copyright 2000-2009 Broadcom Corporation */
/* */
/* This software is provided under the GNU Lesser General Public License, */
/* version 2.1, as published by the Free Software Foundation ("LGPL"). */
/* This program is distributed in the hope that it will be useful, but */
/* WITHOUT ANY SUPPORT OR WARRANTY; without even the implied warranty of */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the LGPL for */
/* more details. A copy of the LGPL is available at */
/* http://www.broadcom.com/licenses/LGPLv2.1.php, */
/* or by writing to the Free Software Foundation, Inc., */
/* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
/*****************************************************************************/
/*****************************************************************************
coarptch.c: Coarse pitch search
$Log$
******************************************************************************/
#include "typedef.h"
#include "bvcommon.h"
#include "bv16cnst.h"
#include "bv16strct.h"
#include "bv16externs.h"
#include "basop32.h"
Word16 coarsepitch(
Word16 *xw, /* (i) (normalized) weighted signal */
struct BV16_Encoder_State *cstate) /* (i/o) Coder State */
{
Word16 s; /* Q2 */
Word16 a, b;
Word16 im;
Word16 maxdev, flag, mpflag;
Word32 eni, deltae;
Word32 cc;
Word16 ah,al, bh, bl;
Word32 a0, a1, a2, a3;
Word32 *lp0;
Word16 exp, new_exp;
Word16 *fp0, *fp1, *fp2, *fp3, *sp;
Word16 *fp1_h, *fp1_l, *fp2_h, *fp2_l;
Word16 cor2max, cor2max_exp;
Word16 cor2m, cor2m_exp;
Word16 s0, t0, t1, exp0, exp1, e2, e3;
Word16 threshold;
Word16 mplth; /* Q2 */
Word16 i, j, k, n, npeaks, imax, idx[MAXPPD-MINPPD+1];
Word16 cpp;
Word16 plag[HMAXPPD], cor2[MAXPPD1], cor2_exp[MAXPPD1];
Word16 cor2i[HMAXPPD], cor2i_exp[HMAXPPD], xwd[LXD];
Word16 tmp_h[DFO+FRSZ], tmp_l[DFO+FRSZ]; /* DPF Q7 */
Word32 cor[MAXPPD1], energy[MAXPPD1], lxwd[FRSZD];
Word16 energy_man[MAXPPD1], energy_exp[MAXPPD1];
Word16 energyi_man[HMAXPPD], energyi_exp[HMAXPPD];
Word16 energym_man, energym_exp;
Word16 energymax_man, energymax_exp;
/* Lowpass filter xw() to 800 hz; shift & output into xwd() */
/* AP and AZ filtering and decimation */
fp1_h = tmp_h + DFO;
fp1_l = tmp_l + DFO;
sp = xw;
a1 = 1;
for (i=0;i<DFO;i++) tmp_h[i] = cstate->dfm_h[2*i+1];
for (i=0;i<DFO;i++) tmp_l[i] = cstate->dfm_h[2*i];
lp0 = lxwd;
for (i=0;i<FRSZD;i++) {
for (k=0;k<DECF;k++) {
a0 = L_shr(L_deposit_h(*sp++),10);
fp2_h = fp1_h-1;
fp2_l = fp1_l-1;
for (j=0;j<DFO;j++)
a0=L_sub(a0,Mpy_32(*fp2_h--,*fp2_l--,adf_h[j+1],adf_l[j+1]));
a0 = L_shl(a0, 2); /* adf Q13 */
L_Extract(a0, fp1_h++, fp1_l++);
}
fp2_h = fp1_h-1;
fp2_l = fp1_l-1;
a0 = Mpy_32_16(*fp2_h--, *fp2_l--, bdf[0]);
for (j=0;j<DFO;j++)
a0=L_add(a0,Mpy_32_16(*fp2_h--,*fp2_l--,bdf[j+1]));
*lp0++ = a0;
a0 = L_abs(a0);
if (a1 < a0)
a1 = a0;
}
/* copy temp buffer to memory */
fp1_h -= DFO;
fp1_l -= DFO;
for (i=0;i<DFO;i++) {
cstate->dfm_h[2*i+1] = fp1_h[i];
cstate->dfm_h[2*i] = fp1_l[i];
}
lp0 = lxwd;
new_exp = sub(norm_l(a1), 3); /* headroom to avoid overflow */
exp = sub(cstate->xwd_exp,new_exp); /* increase in bit-resolution */
if (exp < 0) { /* Descending signal level */
new_exp = cstate->xwd_exp;
exp = 0;
}
for (i=0;i<XDOFF;i++)
xwd[i] = shr(cstate->xwd[i], exp);
/* fill-in new exponent */
fp0 = xwd + XDOFF;
for (i=0;i<FRSZD;i++)
fp0[i] = intround(L_shl(lp0[i],new_exp));
/* update signal memory for next frame */
exp0 = 1;
for (i=0;i<XDOFF;i++) {
exp1 = abs_s(xwd[FRSZD+i]);
if (exp1 > exp0)
exp0 = exp1;
}
exp0 = sub(norm_s(exp0),3); /* extra exponent for next frame */
exp = sub(exp0, exp);
if (exp >=0)
{
for (i=0;i<XDOFF-FRSZD;i++)
cstate->xwd[i] = shl(cstate->xwd[i+FRSZD], exp);
}
else
{
exp = -exp;
if (exp >=15)
exp = 15;
for (i=0;i<XDOFF-FRSZD;i++)
cstate->xwd[i] = shr(cstate->xwd[i+FRSZD], exp);
}
for (;i<XDOFF;i++)
cstate->xwd[i] = shl(xwd[FRSZD+i],exp0);
cstate->xwd_exp = add(new_exp, exp0);
/* Compute correlation & energy of prediction basis vector */
/* reset local buffers */
for (i=0;i<MAXPPD1;i++)
cor[i] = energy[i] = 0;
fp0 = xwd+MAXPPD1;
fp1 = xwd+MAXPPD1-M1;
a0 = a1 = 0;
for (i=0;i<(LXD-MAXPPD1);i++) {
a0 = L_mac0(a0, *fp1, *fp1);
a1 = L_mac0(a1, *fp0++, *fp1++);
}
cor[M1-1] = a1;
energy[M1-1] = a0;
energy_exp[M1-1] = norm_l(energy[M1-1]);
energy_man[M1-1] = extract_h(L_shl(energy[M1-1], energy_exp[M1-1]));
s0 = cor2_exp[M1-1] = norm_l(a1);
t0 = extract_h(L_shl(a1, s0));
cor2[M1-1] = extract_h(L_mult(t0, t0));
if (a1 < 0)
cor2[M1-1] = negate(cor2[M1-1]);
fp2 = xwd+LXD-M1-1;
fp3 = xwd+MAXPPD1-M1-1;
for (i=M1;i<M2;i++) {
fp0 = xwd+MAXPPD1;
fp1 = xwd+MAXPPD1-i-1;
a1 = 0;
for (j=0;j<(LXD-MAXPPD1);j++)
a1 = L_mac0(a1,*fp0++,*fp1++);
cor[i] = a1;
a0 = L_msu0(a0, *fp2, *fp2);
a0 = L_mac0(a0, *fp3, *fp3);
fp2--; fp3--;
energy[i] = a0;
energy_exp[i] = norm_l(energy[i]);
energy_man[i] = extract_h(L_shl(energy[i], energy_exp[i]));
s0 = cor2_exp[i] = norm_l(a1);
t0 = extract_h(L_shl(a1, s0));
cor2[i] = extract_h(L_mult(t0, t0));
if (a1 < 0)
cor2[i] = negate(cor2[i]);
}
/* Find positive correlation peaks */
/* Find maximum of cor*cor/energy among positive correlation peaks */
npeaks = 0;
n = MINPPD-1;
while ((npeaks < MAX_NPEAKS) && (n<MAXPPD)) {
if (cor[n]>0) {
a0 = L_mult(energy_man[n-1],cor2[n]);
a1 = L_mult(energy_man[n], cor2[n-1]);
exp0 = shl(sub(cor2_exp[n], cor2_exp[n-1]),1);
exp0 = add(exp0, energy_exp[n-1]);
exp0 = sub(exp0, energy_exp[n]);
if (exp0>=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
a0 = L_mult(energy_man[n+1],cor2[n]);
a1 = L_mult(energy_man[n], cor2[n+1]);
exp0 = shl(sub(cor2_exp[n], cor2_exp[n+1]),1);
exp0 = add(exp0, energy_exp[n+1]);
exp0 = sub(exp0, energy_exp[n]);
if (exp0>=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
idx[npeaks] = n;
npeaks++;
}
}
}
n++;
}
/* Return early if there is no peak or only one peak */
if (npeaks == 0){ /* if there are no positive peak, */
return MINPPD*DECF; /* return minimum pitch period in decimated domain */
}
if (npeaks == 1){ /* if there is exactly one peak, */
return (idx[0]+1)*DECF; /* return the time lag for this single peak */
}
/* If program proceeds to here, there are 2 or more peaks */
cor2max=(Word16) 0x8000;
cor2max_exp= (Word16) 0;
energymax_man=1;
energymax_exp=0;
imax=0;
for (i=0; i < npeaks; i++) {
/* Use quadratic interpolation to find the interpolated cor[] and
energy[] corresponding to interpolated peak of cor2[]/energy[] */
/* first calculate coefficients of y(x)=ax^2+bx+c; */
n=idx[i];
a0=L_sub(L_shr(L_add(cor[n+1],cor[n-1]),1),cor[n]);
L_Extract(a0, &ah, &al);
a0=L_shr(L_sub(cor[n+1],cor[n-1]),1);
L_Extract(a0, &bh, &bl);
cc=cor[n];
/* Initialize variables before searching for interpolated peak */
im=0;
cor2m_exp = cor2_exp[n];
cor2m = cor2[n];
energym_exp = energy_exp[n];
energym_man = energy_man[n];
eni=energy[n];
/* Determine which side the interpolated peak falls in, then
do the search in the appropriate range */
a0 = L_mult(energy_man[n-1],cor2[n+1]);
a1 = L_mult(energy_man[n+1], cor2[n-1]);
exp0 = shl(sub(cor2_exp[n+1], cor2_exp[n-1]),1);
exp0 = add(exp0, energy_exp[n-1]);
exp0 = sub(exp0, energy_exp[n+1]);
if (exp0>=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) { /* if right side */
deltae = L_shr(L_sub(energy[n+1], eni), 2);
for (k = 0; k < HDECF; k++) {
a0=L_add(L_add(Mpy_32_16(ah,al,x2[k]),Mpy_32_16(bh,bl,x[k])),cc);
eni = L_add(eni, deltae);
a1 = eni;
exp0 = norm_l(a0);
s0 = extract_h(L_shl(a0, exp0));
s0 = extract_h(L_mult(s0, s0));
e2 = energym_exp;
t0 = energym_man;
a2 = L_mult(t0, s0);
e3 = norm_l(a1);
t1 = extract_h(L_shl(a1, e3));
a3 = L_mult(t1, cor2m);
exp1 = shl(sub(exp0, cor2m_exp),1);
exp1 = add(exp1, e2);
exp1 = sub(exp1, e3);
if (exp1>=0)
a2 = L_shr(a2, exp1);
else
a3 = L_shl(a3, exp1);
if (a2 > a3) {
im = k+1;
cor2m = s0;
cor2m_exp = exp0;
energym_exp = e3;
energym_man = t1;
}
}
} else { /* if interpolated peak is on the left side */
deltae = L_shr(L_sub(energy[n-1], eni), 2);
for (k = 0; k < HDECF; k++) {
a0=L_add(L_sub(Mpy_32_16(ah,al,x2[k]),Mpy_32_16(bh,bl,x[k])),cc);
eni = L_add(eni, deltae);
a1=eni;
exp0 = norm_l(a0);
s0 = extract_h(L_shl(a0, exp0));
s0 = extract_h(L_mult(s0, s0));
e2 = energym_exp;
t0 = energym_man;
a2 = L_mult(t0, s0);
e3 = norm_l(a1);
t1 = extract_h(L_shl(a1, e3));
a3 = L_mult(t1, cor2m);
exp1 = shl(sub(exp0, cor2m_exp),1);
exp1 = add(exp1, e2);
exp1 = sub(exp1, e3);
if (exp1>=0)
a2 = L_shr(a2, exp1);
else
a3 = L_shl(a3, exp1);
if (a2 > a3) {
im = -k-1;
cor2m = s0;
cor2m_exp = exp0;
energym_exp = e3;
energym_man = t1;
}
}
}
/* Search done; assign cor2[] and energy[] corresponding to
interpolated peak */
plag[i]=add(shl(add(idx[i],1),2),im); /* lag of interp. peak */
cor2i[i]=cor2m;
cor2i_exp[i]=cor2m_exp;
/* interpolated energy[] of i-th interpolated peak */
energyi_exp[i] = energym_exp;
energyi_man[i] = energym_man;
/* Search for global maximum of interpolated cor2[]/energy[] peak */
a0 = L_mult(cor2m,energymax_man);
a1 = L_mult(cor2max, energyi_man[i]);
exp0 = shl(sub(cor2m_exp, cor2max_exp),1);
exp0 = add(exp0, energymax_exp);
exp0 = sub(exp0, energyi_exp[i]);
if (exp0 >=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
imax=i;
cor2max=cor2m;
cor2max_exp=cor2m_exp;
energymax_exp = energyi_exp[i];
energymax_man = energyi_man[i];
}
}
cpp=plag[imax]; /* first candidate for coarse pitch period */
mplth=plag[npeaks-1]; /* set mplth to the lag of last peak */
/* Find the largest peak (if there is any) around the last pitch */
maxdev= shr(cstate->cpplast,2); /* maximum deviation from last pitch */
im = -1;
cor2m=(Word16) 0x8000;
cor2m_exp= (Word16) 0;
energym_man = 1;
energym_exp = 0;
for (i=0;i<npeaks;i++) { /* loop thru the peaks before the largest peak */
if (abs_s(sub(plag[i],cstate->cpplast)) <= maxdev) {
a0 = L_mult(cor2i[i],energym_man);
a1 = L_mult(cor2m, energyi_man[i]);
exp0 = shl(sub(cor2i_exp[i], cor2m_exp),1);
exp0 = add(exp0, energym_exp);
exp0 = sub(exp0, energyi_exp[i]);
if (exp0 >=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
im=i;
cor2m=cor2i[i];
cor2m_exp=cor2i_exp[i];
energym_man = energyi_man[i];
energym_exp = energyi_exp[i];
}
}
} /* if there is no peaks around last pitch, then im is still -1 */
/* Now see if we should pick any alternatice peak */
/* first, search first half of pitch range, see if any qualified peak
has large enough peaks at every multiple of its lag */
i=0;
while (2*plag[i] < mplth) {
/* Determine the appropriate threshold for this peak */
if (i != im) { /* if not around last pitch, */
threshold = TH1; /* use a higher threshold */
} else { /* if around last pitch */
threshold = TH2; /* use a lower threshold */
}
/* If threshold exceeded, test peaks at multiples of this lag */
a0 = L_mult(cor2i[i],energymax_man);
t1 = extract_h(L_mult(energyi_man[i], threshold));
a1 = L_mult(cor2max, t1);
exp0 = shl(sub(cor2i_exp[i], cor2max_exp),1);
exp0 = add(exp0, energymax_exp);
exp0 = sub(exp0, energyi_exp[i]);
if (exp0 >=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
flag=1;
j=i+1;
k=0;
s=shl(plag[i],1); /* initialize t to twice the current lag */
while (s<=mplth) { /* loop thru all multiple lag <= mplth */
mpflag=0; /* initialize multiple pitch flag to 0 */
t0 = mult_r(s,MPDTH);
a=sub(s, t0); /* multiple pitch range lower bound */
b=add(s, t0); /* multiple pitch range upper bound */
while (j < npeaks) { /* loop thru peaks with larger lags */
if (plag[j] > b) { /* if range exceeded, */
break; /* break the innermost while loop */
} /* if didn't break, then plag[j] <= b */
if (plag[j] > a) { /* if current peak lag within range, */
/* then check if peak value large enough */
a0 = L_mult(cor2i[j],energymax_man);
if (k<4)
t1 = MPTH[k];
else
t1 = MPTH4;
t1 = extract_h(L_mult(t1, energyi_man[j]));
a1 = L_mult(cor2max, t1);
exp0 = shl(sub(cor2i_exp[j], cor2max_exp),1);
exp0 = add(exp0, energymax_exp);
exp0 = sub(exp0, energyi_exp[j]);
if (exp0 >=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
mpflag=1; /* if peak large enough, set mpflag, */
break; /* and break the innermost while loop */
}
}
j++;
}
/* if no qualified peak found at this multiple lag */
if (mpflag == 0) {
flag=0; /* disqualify the lag plag[i] */
break; /* and break the while (s<=mplth) loop */
}
k++;
s = add(s, plag[i]); /* update s to the next multiple pitch lag */
}
/* if there is a qualified peak at every multiple of plag[i], */
if (flag == 1) {
cpp = plag[i]; /* then accept this as final pitch */
return cpp; /* and return to calling function */
}
}
i++;
if (i == npeaks)
break; /* to avoid out of array bound error */
}
/* If program proceeds to here, none of the peaks with lags < 0.5*mplth
qualifies as the final pitch. in this case, check if
there is any peak large enough around last pitch. if so, use its
lag as the final pitch. */
if (im != -1) { /* if there is at least one peak around last pitch */
if (im == imax) { /* if this peak is also the global maximum, */
return cpp; /* return first pitch candidate at global max */
}
if (im < imax) { /* if lag of this peak < lag of global max, */
a0 = L_mult(cor2m,energymax_man);
t1 = extract_h(L_mult(energym_man, LPTH2));
a1 = L_mult(cor2max, t1);
exp0 = shl(sub(cor2m_exp, cor2max_exp),1);
exp0 = add(exp0, energymax_exp);
exp0 = sub(exp0, energym_exp);
if (exp0 >=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
if (plag[im] > HMAXPPD*DECF) {
cpp=plag[im];
return cpp;
}
for (k=2; k<=5;k++) { /* check if current candidate pitch */
s=mult(plag[imax],invk[k-2]); /* is a sub-multiple of */
t0 = mult_r(s,SMDTH);
a=sub(s, t0); /* the time lag of */
b=add(s, t0); /* the global maximum peak */
if (plag[im]>a && plag[im]<b) { /* if so, */
cpp=plag[im]; /* accept this peak, */
return cpp; /* and return as pitch */
}
}
}
} else { /* if lag of this peak > lag of global max, */
a0 = L_mult(cor2m,energymax_man);
t1 = extract_h(L_mult(energym_man, LPTH1));
a1 = L_mult(cor2max, t1);
exp0 = shl(sub(cor2m_exp, cor2max_exp),1);
exp0 = add(exp0, energymax_exp);
exp0 = sub(exp0, energym_exp);
if (exp0 >=0)
a0 = L_shr(a0, exp0);
else
a1 = L_shl(a1, exp0);
if (a0 > a1) {
cpp = plag[im]; /* if this peak is large enough, */
return cpp; /* accept its lag */
}
}
}
/* If program proceeds to here, we have no choice but to accept the
lag of the global maximum */
return cpp;
}
|
gpl-3.0
|
autc04/Retro68
|
gcc/gcc/testsuite/gcc.target/i386/avx512f-vunpckhps-2.c
|
99
|
1225
|
/* { dg-do run } */
/* { dg-options "-O2 -mavx512f" } */
/* { dg-require-effective-target avx512f } */
#define AVX512F
#include "avx512f-helper.h"
#define SIZE (AVX512F_LEN / 32)
#include "avx512f-mask-type.h"
void static
CALC (float *s1, float *s2, float *r)
{
int i;
for (i = 0; i < SIZE / 4; i++)
{
r[4 * i] = s1[4 * i + 2];
r[4 * i + 1] = s2[4 * i + 2];
r[4 * i + 2] = s1[4 * i + 3];
r[4 * i + 3] = s2[4 * i + 3];
}
}
void
TEST (void)
{
UNION_TYPE (AVX512F_LEN, ) s1, s2, res1, res2, res3;
MASK_TYPE mask = MASK_VALUE;
float res_ref[SIZE];
int i;
for (i = 0; i < SIZE; i++)
{
s1.a[i] = i * 123.2 + 32.6;
s2.a[i] = i + 2.5;
res2.a[i] = DEFAULT_VALUE;
}
res1.x = INTRINSIC (_unpackhi_ps) (s1.x, s2.x);
res2.x = INTRINSIC (_mask_unpackhi_ps) (res2.x, mask, s1.x, s2.x);
res3.x = INTRINSIC (_maskz_unpackhi_ps) (mask, s1.x, s2.x);
CALC (s1.a, s2.a, res_ref);
if (UNION_CHECK (AVX512F_LEN, ) (res1, res_ref))
abort ();
MASK_MERGE () (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, ) (res2, res_ref))
abort ();
MASK_ZERO () (res_ref, mask, SIZE);
if (UNION_CHECK (AVX512F_LEN, ) (res3, res_ref))
abort ();
}
|
gpl-3.0
|
LaiDong/sipdroid
|
jni/silk/src/SKP_Silk_tables_NLSF_CB0_10.c
|
99
|
31418
|
/***********************************************************************
Copyright (c) 2006-2010, Skype Limited. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, (subject to the limitations in the disclaimer below)
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 Skype Limited, nor the names of specific
contributors, may be used to endorse or promote products derived from
this software without specific prior written permission.
NO EXPRESS OR IMPLIED LICENSES TO ANY PARTY'S PATENT RIGHTS ARE GRANTED
BY THIS LICENSE. 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.
***********************************************************************/
/**********************************************/
/* This file has been automatically generated */
/* */
/* ROM usage: 138+1331 Words */
/**********************************************/
#include "SKP_Silk_structs.h"
#include "SKP_Silk_tables_NLSF_CB0_10.h"
const SKP_uint16 SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ NLSF_MSVQ_CB0_10_VECTORS + NLSF_MSVQ_CB0_10_STAGES ] =
{
0,
2658,
4420,
6107,
7757,
9408,
10955,
12502,
13983,
15432,
16882,
18331,
19750,
21108,
22409,
23709,
25010,
26256,
27501,
28747,
29965,
31158,
32351,
33544,
34736,
35904,
36997,
38091,
39185,
40232,
41280,
42327,
43308,
44290,
45271,
46232,
47192,
48132,
49032,
49913,
50775,
51618,
52462,
53287,
54095,
54885,
55675,
56449,
57222,
57979,
58688,
59382,
60076,
60726,
61363,
61946,
62505,
63052,
63543,
63983,
64396,
64766,
65023,
65279,
65535,
0,
4977,
9542,
14106,
18671,
23041,
27319,
31596,
35873,
39969,
43891,
47813,
51652,
55490,
59009,
62307,
65535,
0,
8571,
17142,
25529,
33917,
42124,
49984,
57844,
65535,
0,
8732,
17463,
25825,
34007,
42189,
50196,
58032,
65535,
0,
8948,
17704,
25733,
33762,
41791,
49821,
57678,
65535,
0,
4374,
8655,
12936,
17125,
21313,
25413,
29512,
33611,
37710,
41809,
45820,
49832,
53843,
57768,
61694,
65535
};
const SKP_uint16 * const SKP_Silk_NLSF_MSVQ_CB0_10_CDF_start_ptr[ NLSF_MSVQ_CB0_10_STAGES ] =
{
&SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 0 ],
&SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 65 ],
&SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 82 ],
&SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 91 ],
&SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 100 ],
&SKP_Silk_NLSF_MSVQ_CB0_10_CDF[ 109 ]
};
const SKP_int SKP_Silk_NLSF_MSVQ_CB0_10_CDF_middle_idx[ NLSF_MSVQ_CB0_10_STAGES ] =
{
23,
8,
5,
5,
5,
9
};
const SKP_int16 SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ NLSF_MSVQ_CB0_10_VECTORS ] =
{
148, 167,
169, 170,
170, 173,
173, 175,
176, 176,
176, 177,
179, 181,
181, 181,
183, 183,
183, 184,
185, 185,
185, 185,
186, 189,
189, 189,
191, 191,
191, 194,
194, 194,
195, 195,
196, 198,
199, 200,
201, 201,
202, 203,
204, 204,
205, 205,
206, 209,
210, 210,
213, 214,
218, 220,
221, 226,
231, 234,
239, 256,
256, 256,
119, 123,
123, 123,
125, 126,
126, 126,
128, 130,
130, 131,
131, 135,
138, 139,
94, 94,
95, 95,
96, 98,
98, 99,
93, 93,
95, 96,
96, 97,
98, 100,
92, 93,
97, 97,
97, 97,
98, 98,
125, 126,
126, 127,
127, 128,
128, 128,
128, 128,
129, 129,
129, 130,
130, 131
};
const SKP_int SKP_Silk_NLSF_MSVQ_CB0_10_ndelta_min_Q15[ 10 + 1 ] =
{
563,
3,
22,
20,
3,
3,
132,
119,
358,
86,
964
};
const SKP_int16 SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * NLSF_MSVQ_CB0_10_VECTORS ] =
{
2210, 4023,
6981, 9260,
12573, 15687,
19207, 22383,
25981, 29142,
3285, 4172,
6116, 10856,
15289, 16826,
19701, 22010,
24721, 29313,
1554, 2511,
6577, 10337,
13837, 16511,
20086, 23214,
26480, 29464,
3062, 4017,
5771, 10037,
13365, 14952,
20140, 22891,
25229, 29603,
2085, 3457,
5934, 8718,
11501, 13670,
17997, 21817,
24935, 28745,
2776, 4093,
6421, 10413,
15111, 16806,
20825, 23826,
26308, 29411,
2717, 4034,
5697, 8463,
14301, 16354,
19007, 23413,
25812, 28506,
2872, 3702,
5881, 11034,
17141, 18879,
21146, 23451,
25817, 29600,
2999, 4015,
7357, 11219,
12866, 17307,
20081, 22644,
26774, 29107,
2942, 3866,
5918, 11915,
13909, 16072,
20453, 22279,
27310, 29826,
2271, 3527,
6606, 9729,
12943, 17382,
20224, 22345,
24602, 28290,
2207, 3310,
5844, 9339,
11141, 15651,
18576, 21177,
25551, 28228,
3963, 4975,
6901, 11588,
13466, 15577,
19231, 21368,
25510, 27759,
2749, 3549,
6966, 13808,
15653, 17645,
20090, 22599,
26467, 28537,
2126, 3504,
5109, 9954,
12550, 14620,
19703, 21687,
26457, 29106,
3966, 5745,
7442, 9757,
14468, 16404,
19135, 23048,
25375, 28391,
3197, 4751,
6451, 9298,
13038, 14874,
17962, 20627,
23835, 28464,
3195, 4081,
6499, 12252,
14289, 16040,
18357, 20730,
26980, 29309,
1533, 2471,
4486, 7796,
12332, 15758,
19567, 22298,
25673, 29051,
2002, 2971,
4985, 8083,
13181, 15435,
18237, 21517,
24595, 28351,
3808, 4925,
6710, 10201,
12011, 14300,
18457, 20391,
26525, 28956,
2281, 3418,
4979, 8726,
15964, 18104,
20250, 22771,
25286, 28954,
3051, 5479,
7290, 9848,
12744, 14503,
18665, 23684,
26065, 28947,
2364, 3565,
5502, 9621,
14922, 16621,
19005, 20996,
26310, 29302,
4093, 5212,
6833, 9880,
16303, 18286,
20571, 23614,
26067, 29128,
2941, 3996,
6038, 10638,
12668, 14451,
16798, 19392,
26051, 28517,
3863, 5212,
7019, 9468,
11039, 13214,
19942, 22344,
25126, 29539,
4615, 6172,
7853, 10252,
12611, 14445,
19719, 22441,
24922, 29341,
3566, 4512,
6985, 8684,
10544, 16097,
18058, 22475,
26066, 28167,
4481, 5489,
7432, 11414,
13191, 15225,
20161, 22258,
26484, 29716,
3320, 4320,
6621, 9867,
11581, 14034,
21168, 23210,
26588, 29903,
3794, 4689,
6916, 8655,
10143, 16144,
19568, 21588,
27557, 29593,
2446, 3276,
5918, 12643,
16601, 18013,
21126, 23175,
27300, 29634,
2450, 3522,
5437, 8560,
15285, 19911,
21826, 24097,
26567, 29078,
2580, 3796,
5580, 8338,
9969, 12675,
18907, 22753,
25450, 29292,
3325, 4312,
6241, 7709,
9164, 14452,
21665, 23797,
27096, 29857,
3338, 4163,
7738, 11114,
12668, 14753,
16931, 22736,
25671, 28093,
3840, 4755,
7755, 13471,
15338, 17180,
20077, 22353,
27181, 29743,
2504, 4079,
8351, 12118,
15046, 18595,
21684, 24704,
27519, 29937,
5234, 6342,
8267, 11821,
15155, 16760,
20667, 23488,
25949, 29307,
2681, 3562,
6028, 10827,
18458, 20458,
22303, 24701,
26912, 29956,
3374, 4528,
6230, 8256,
9513, 12730,
18666, 20720,
26007, 28425,
2731, 3629,
8320, 12450,
14112, 16431,
18548, 22098,
25329, 27718,
3481, 4401,
7321, 9319,
11062, 13093,
15121, 22315,
26331, 28740,
3577, 4945,
6669, 8792,
10299, 12645,
19505, 24766,
26996, 29634,
4058, 5060,
7288, 10190,
11724, 13936,
15849, 18539,
26701, 29845,
4262, 5390,
7057, 8982,
10187, 15264,
20480, 22340,
25958, 28072,
3404, 4329,
6629, 7946,
10121, 17165,
19640, 22244,
25062, 27472,
3157, 4168,
6195, 9319,
10771, 13325,
15416, 19816,
24672, 27634,
2503, 3473,
5130, 6767,
8571, 14902,
19033, 21926,
26065, 28728,
4133, 5102,
7553, 10054,
11757, 14924,
17435, 20186,
23987, 26272,
4972, 6139,
7894, 9633,
11320, 14295,
21737, 24306,
26919, 29907,
2958, 3816,
6851, 9204,
10895, 18052,
20791, 23338,
27556, 29609,
5234, 6028,
8034, 10154,
11242, 14789,
18948, 20966,
26585, 29127,
5241, 6838,
10526, 12819,
14681, 17328,
19928, 22336,
26193, 28697,
3412, 4251,
5988, 7094,
9907, 18243,
21669, 23777,
26969, 29087,
2470, 3217,
7797, 15296,
17365, 19135,
21979, 24256,
27322, 29442,
4939, 5804,
8145, 11809,
13873, 15598,
17234, 19423,
26476, 29645,
5051, 6167,
8223, 9655,
12159, 17995,
20464, 22832,
26616, 28462,
4987, 5907,
9319, 11245,
13132, 15024,
17485, 22687,
26011, 28273,
5137, 6884,
11025, 14950,
17191, 19425,
21807, 24393,
26938, 29288,
7057, 7884,
9528, 10483,
10960, 14811,
19070, 21675,
25645, 28019,
6759, 7160,
8546, 11779,
12295, 13023,
16627, 21099,
24697, 28287,
3863, 9762,
11068, 11445,
12049, 13960,
18085, 21507,
25224, 28997,
397, 335,
651, 1168,
640, 765,
465, 331,
214, -194,
-578, -647,
-657, 750,
564, 613,
549, 630,
304, -52,
828, 922,
443, 111,
138, 124,
169, 14,
144, 83,
132, 58,
-413, -752,
869, 336,
385, 69,
56, 830,
-227, -266,
-368, -440,
-1195, 163,
126, -228,
802, 156,
188, 120,
376, 59,
-358, -558,
-1326, -254,
-202, -789,
296, 92,
-70, -129,
-718, -1135,
292, -29,
-631, 487,
-157, -153,
-279, 2,
-419, -342,
-34, -514,
-799, -1571,
-687, -609,
-546, -130,
-215, -252,
-446, -574,
-1337, 207,
-72, 32,
103, -642,
942, 733,
187, 29,
-211, -814,
143, 225,
20, 24,
-268, -377,
1623, 1133,
667, 164,
307, 366,
187, 34,
62, -313,
-832, -1482,
-1181, 483,
-42, -39,
-450, -1406,
-587, -52,
-760, 334,
98, -60,
-500, -488,
-1058, 299,
131, -250,
-251, -703,
1037, 568,
-413, -265,
1687, 573,
345, 323,
98, 61,
-102, 31,
135, 149,
617, 365,
-39, 34,
-611, 1201,
1421, 736,
-414, -393,
-492, -343,
-316, -532,
528, 172,
90, 322,
-294, -319,
-541, 503,
639, 401,
1, -149,
-73, -167,
150, 118,
308, 218,
121, 195,
-143, -261,
-1013, -802,
387, 436,
130, -427,
-448, -681,
123, -87,
-251, -113,
274, 310,
445, 501,
354, 272,
141, -285,
569, 656,
37, -49,
251, -386,
-263, 1122,
604, 606,
336, 95,
34, 0,
85, 180,
207, -367,
-622, 1070,
-6, -79,
-160, -92,
-137, -276,
-323, -371,
-696, -1036,
407, 102,
-86, -214,
-482, -647,
-28, -291,
-97, -180,
-250, -435,
-18, -76,
-332, 410,
407, 168,
539, 411,
254, 111,
58, -145,
200, 30,
187, 116,
131, -367,
-475, 781,
-559, 561,
195, -115,
8, -168,
30, 55,
-122, 131,
82, -5,
-273, -50,
-632, 668,
4, 32,
-26, -279,
315, 165,
197, 377,
155, -41,
-138, -324,
-109, -617,
360, 98,
-53, -319,
-114, -245,
-82, 507,
468, 263,
-137, -389,
652, 354,
-18, -227,
-462, -135,
317, 53,
-16, 66,
-72, -126,
-356, -347,
-328, -72,
-337, 324,
152, 349,
169, -196,
179, 254,
260, 325,
-74, -80,
75, -31,
270, 275,
87, 278,
-446, -301,
309, 71,
-25, -242,
516, 161,
-162, -83,
329, 230,
-311, -259,
177, -26,
-462, 89,
257, 6,
-130, -93,
-456, -317,
-221, -206,
-417, -182,
-74, 234,
48, 261,
359, 231,
258, 85,
-282, 252,
-147, -222,
251, -207,
443, 123,
-417, -36,
273, -241,
240, -112,
44, -167,
126, -124,
-77, 58,
-401, 333,
-118, 82,
126, 151,
-433, 359,
-130, -102,
131, -244,
86, 85,
-462, 414,
-240, 16,
145, 28,
-205, -481,
373, 293,
-72, -174,
62, 259,
-8, -18,
362, 233,
185, 43,
278, 27,
193, 570,
-248, 189,
92, 31,
-275, -3,
243, 176,
438, 209,
206, -51,
79, 109,
168, -185,
-308, -68,
-618, 385,
-310, -108,
-164, 165,
61, -152,
-101, -412,
-268, -257,
-40, -20,
-28, -158,
-301, 271,
380, -338,
-367, -132,
64, 114,
-131, -225,
-156, -260,
-63, -116,
155, -586,
-202, 254,
-287, 178,
227, -106,
-294, 164,
298, -100,
185, 317,
193, -45,
28, 80,
-87, -433,
22, -48,
48, -237,
-229, -139,
120, -364,
268, -136,
396, 125,
130, -89,
-272, 118,
-256, -68,
-451, 488,
143, -165,
-48, -190,
106, 219,
47, 435,
245, 97,
75, -418,
121, -187,
570, -200,
-351, 225,
-21, -217,
234, -111,
194, 14,
242, 118,
140, -397,
355, 361,
-45, -195
};
const SKP_Silk_NLSF_CBS SKP_Silk_NLSF_CB0_10_Stage_info[ NLSF_MSVQ_CB0_10_STAGES ] =
{
{ 64, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 0 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 0 ] },
{ 16, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 64 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 64 ] },
{ 8, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 80 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 80 ] },
{ 8, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 88 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 88 ] },
{ 8, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 96 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 96 ] },
{ 16, &SKP_Silk_NLSF_MSVQ_CB0_10_Q15[ 10 * 104 ], &SKP_Silk_NLSF_MSVQ_CB0_10_rates_Q5[ 104 ] }
};
const SKP_Silk_NLSF_CB_struct SKP_Silk_NLSF_CB0_10 =
{
NLSF_MSVQ_CB0_10_STAGES,
SKP_Silk_NLSF_CB0_10_Stage_info,
SKP_Silk_NLSF_MSVQ_CB0_10_ndelta_min_Q15,
SKP_Silk_NLSF_MSVQ_CB0_10_CDF,
SKP_Silk_NLSF_MSVQ_CB0_10_CDF_start_ptr,
SKP_Silk_NLSF_MSVQ_CB0_10_CDF_middle_idx
};
|
gpl-3.0
|
Darkitty/applistage
|
fuel/packages/pdf/lib/dompdf/lib/ttf2ufm/src/app/netscape/nsfix.c
|
102
|
11355
|
/*
* Fix the Netscape executable for specified font widths
*
* (c) 1999 Copyright by Sergey Babkin
* see COPYRIGHT
*/
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <locale.h>
#include <unistd.h>
/************************** DEFINES *************************/
#undef DEBUG
/* we can handle at most this many fonts */
#define MAXFONTS 20
/* maximal line buffer size */
#define MAXLINE 512
/* there may be multiple strings with the same contents */
#define MAXDUPS 10
/* file read buffer size */
#define FILEBF 40960
/* bits in the hardware page offset */
#define BITSPERPAGE 12
/* size of page in bytes */
#define PAGESIZE (1<<BITSPERPAGE)
/* mask of the in-page offset */
#define PAGEMASK (PAGESIZE-1)
/* this is machine-dependent! */
typedef short t2b; /* 2-byte type */
typedef int t4b; /* 4-byte type */
typedef int tptr; /* integer type with the same size as pointer */
struct bbox { /* bounding box */
t2b llx; /* lower-left-x */
t2b lly;
t2b urx;
t2b ury; /* upper-right-y */
};
struct glyphmetrics { /* metrics of one glyph */
t2b width;
t2b unknown;
struct bbox bbox;
};
struct fontmetrics { /* metrics of the wholefont */
tptr name;
struct bbox bbox;
t2b underlinepos;
t2b underlinethick;
struct glyphmetrics glyphs[256];
};
struct font {
char nsname[MAXLINE]; /* name in the Netscape binary */
char afmname[MAXLINE]; /* name of the .afm file */
char pfaname[MAXLINE]; /* name of the .pfa (or .pfb) file */
struct fontmetrics metrics;
off_t binoff; /* offset in the binary */
};
#define SCONST(x) (x), ((sizeof (x))-1)
/************************** GLOBALS *************************/
struct font font[MAXFONTS];
int nfonts=0;
char msg[MAXLINE];
/*************************** PROTOTYPES **********************/
void usage(void);
void readconfig( char *fn);
void readmetrics(void);
void replacefonts( char *fn);
/************************** main ****************************/
main(ac, av)
int ac;
char **av;
{
setlocale(LC_ALL, "");
if(ac!=3) {
usage(); exit(1);
}
readconfig(av[2]);
readmetrics();
replacefonts( av[1]);
}
/************************** usage ***************************/
void
usage(void)
{
fprintf(stderr,"Use:\n");
fprintf(stderr," nsfix <netscape.bin> <config-file>\n");
}
/************************** readconfig **********************/
void
readconfig(fn)
char *fn;
{
char s[MAXLINE];
char afmsuffix[MAXLINE], pfasuffix[MAXLINE];
int lineno=0;
FILE *f;
if(( f=fopen(fn, "r") )==NULL) {
sprintf(msg,"nsfix: open %s",fn);
perror(msg);
exit(1);
}
while( fgets(s, MAXLINE, f) ) {
lineno++;
if(s[0]=='#' || s[0]=='\n')
continue;
if(nfonts>=MAXFONTS) {
fprintf(stderr, "nsfix: only %d fonts are supported at once\n",
MAXFONTS);
exit(1);
}
if( sscanf(s, "%s %s %s %s", font[nfonts].nsname,
font[nfonts].afmname, afmsuffix, pfasuffix) != 4 ) {
fprintf(stderr, "nsfix: syntax error at line %d of %s\n",
lineno, fn);
exit(1);
}
strcpy(font[nfonts].pfaname, font[nfonts].afmname);
strcat(font[nfonts].afmname, afmsuffix);
strcat(font[nfonts].pfaname, pfasuffix);
nfonts++;
}
if(nfonts==0) {
fprintf(stderr, "nsfix: no fonts are defined in %s\n", fn);
exit(1);
}
fclose(f);
}
/************************** readmetrics *********************/
void
readmetrics(void)
{
int i;
char s[MAXLINE];
FILE *f;
int n;
int lineno;
int code, width, llx, lly, urx, ury;
char gn[MAXLINE];
struct glyphmetrics *gm;
for(i=0; i<nfonts; i++) {
if(( f=fopen(font[i].afmname, "r") )==NULL) {
sprintf(msg,"nsfix: open %s", font[i].afmname);
perror(msg);
exit(1);
}
lineno=0;
while( fgets(s, MAXLINE, f) ) {
lineno++;
if( !strncmp(s, SCONST("UnderlineThickness ")) ) {
if( sscanf(s, "UnderlineThickness %d", &n) <1) {
fprintf(stderr, "nsfix: weird UnderlineThickness at line %d in %s\n",
lineno, font[i].afmname);
exit(1);
}
font[i].metrics.underlinethick=n;
} else if( !strncmp(s, SCONST("UnderlinePosition ")) ) {
if( sscanf(s, "UnderlinePosition %d", &n) <1) {
fprintf(stderr, "nsfix: weird UnderlinePosition at line %d in %s\n",
lineno, font[i].afmname);
exit(1);
}
font[i].metrics.underlinepos=n;
} else if( !strncmp(s, SCONST("FontBBox ")) ) {
if( sscanf(s, "FontBBox %d %d %d %d", &llx, &lly, &urx, &ury) <4) {
fprintf(stderr, "nsfix: weird FontBBox at line %d in %s\n",
lineno, font[i].afmname);
exit(1);
}
font[i].metrics.bbox.llx=llx;
font[i].metrics.bbox.lly=lly;
font[i].metrics.bbox.urx=urx;
font[i].metrics.bbox.ury=ury;
} else if( !strncmp(s, SCONST("C ")) ) {
if( sscanf(s, "C %d ; WX %d ; N %s ; B %d %d %d %d",
&code, &width, &gn, &llx, &lly, &urx, &ury) <7)
{
fprintf(stderr, "nsfix: weird metrics at line %d in %s\n",
lineno, font[i].afmname);
exit(1);
}
if(code>=32 && code<=255) {
font[i].metrics.glyphs[code].width=width;
font[i].metrics.glyphs[code].bbox.llx=llx;
font[i].metrics.glyphs[code].bbox.lly=lly;
font[i].metrics.glyphs[code].bbox.urx=urx;
font[i].metrics.glyphs[code].bbox.ury=ury;
}
}
}
fclose(f);
}
#ifdef DEBUG
for(i=0; i<nfonts; i++) {
printf("Font %s\n", font[i].nsname);
for(n=0; n<256; n++) {
gm= &font[i].metrics.glyphs[n];
printf(" %d w=%4d [%4d %4d %4d %4d]", n, gm->width,
gm->bbox.llx, gm->bbox.lly, gm->bbox.urx, gm->bbox.ury);
printf(" w=0x%04x [0x%04x 0x%04x 0x%04x 0x%04x]\n", gm->width & 0xffff,
gm->bbox.llx & 0xffff, gm->bbox.lly & 0xffff, gm->bbox.urx & 0xffff, gm->bbox.ury & 0xffff);
}
}
exit(0);
#endif
}
/************************** replacefonts ********************/
void
replacefonts(fn)
char *fn;
{
int f; /* don't use stdio */
char bf[FILEBF];
char *bfend, *p;
int len;
off_t pos;
off_t zerooff[MAXFONTS*MAXDUPS]; /* offset of zero strings */
tptr nameaddr[MAXFONTS*MAXDUPS]; /* name pointers before these zero strings */
int zeroid[MAXFONTS*MAXDUPS]; /* font number for this zero block */
int nzeroes;
short matched[MAXFONTS]; /* counters how many matches we have for each requested font */
struct fontmetrics *fp;
struct {
int noff;
int nz;
off_t off[MAXDUPS]; /* there may be multiple strings with the same contents */
} o[MAXFONTS];
int maxnlen;
int i, j, k, n;
static struct glyphmetrics gm[32]; /* 0-initialized */
if(( f=open(fn, O_RDWR) )<0) {
sprintf(msg,"nsfix: open %s",fn);
perror(msg);
exit(1);
}
/* get the maximal font name length */
maxnlen=0;
for(i=0; i<nfonts; i++) {
o[i].noff=o[i].nz=0;
matched[i]=0;
len=strlen(font[i].nsname)+1;
if(len>maxnlen)
maxnlen=len;
}
/* fprintf(stderr,"maxnlen= 0x%x\n", maxnlen); /* */
/* try to find the literal strings of the font names */
pos=0; bfend=bf;
while(( len=read(f, bfend, FILEBF-(bfend-bf)) )>=0 ) {
/* fprintf(stderr,"looking at 0x%lx\n", (long)pos); /* */
/* the last position to check */
if(len>=maxnlen)
/* leave the rest with the next block */
bfend+= len-maxnlen;
else {
/* we are very near to the end of file, check
* up to the very last byte */
bfend+= len-2;
memset(bfend+2, 0, maxnlen);
}
for(p=bf; p<=bfend; p++)
for(i=0; i<nfonts; i++)
if(!strcmp(font[i].nsname, p) && o[i].noff<MAXDUPS) {
o[i].off[ o[i].noff++ ] = pos + (p-bf);
fprintf(stderr,"found %s at 0x%lx\n", font[i].nsname, (long)pos + (p-bf));
}
if(len==0)
break;
memmove(bf, bfend, maxnlen);
pos+= (bfend-bf);
bfend= (bf+maxnlen);
}
if(len<0) {
sprintf(msg,"nsfix: read %s",fn);
perror(msg);
exit(1);
}
fprintf(stderr,"---\n");
/* if there are any dups try to resolve them */
for(i=0; i<nfonts; i++) {
if(o[i].noff==0) {
fprintf(stderr, "nsfix: font %s (%d of %d) is missing in %s\n",
font[i].nsname, i, nfonts, fn);
exit(1);
}
if(o[i].noff!=1)
continue;
/* good, only one entry */
fprintf(stderr,"found unique %s at 0x%lx\n", font[i].nsname, (long)o[i].off[0] );
/* if any dupped entry is right after this one then it's good */
/* if it's farther than PAGESIZE/2 then it's bad */
pos=o[i].off[0]+strlen(font[i].nsname)+1;
for(j=0; j<MAXFONTS; j++) {
if(o[j].noff<=1)
continue;
for(k=0; k<o[j].noff; k++) {
if(o[j].off[k]==pos) { /* good */
fprintf(stderr,"got unique %s at 0x%lx\n", font[j].nsname, (long)pos );
o[j].off[0]=pos;
o[j].noff=1;
break;
}
if(o[j].off[k] < pos - PAGESIZE/2
|| o[j].off[k] > pos + PAGESIZE/2) { /* bad */
fprintf(stderr, "eliminated %s at 0x%lx\n", font[j].nsname, (long)o[j].off[k] );
for(n=k+1; n<o[j].noff; n++)
o[j].off[n-1]=o[j].off[n];
o[j].noff--;
k--;
}
}
if(o[j].noff==1 && j<i) { /* have to revisit this font */
i=j-1; /* compensate for i++ */
break;
}
}
}
/* try to find the metric tables in the executable */
if(lseek(f, (off_t)0, SEEK_SET)<0) {
sprintf(msg,"nsfix: rewind %s",fn);
perror(msg);
exit(1);
}
/*
* search for the zeroes in place of the metrics for the codes 0-31:
* 4-byte aligned strings of (32*sizeof(struct glyphmetrics)) zero bytes
*/
maxnlen=sizeof(struct fontmetrics);
pos=0; bfend=bf; nzeroes=0;
while(( len=read(f, bfend, FILEBF-(bfend-bf)) )>=0 ) {
/* fprintf(stderr,"looking at 0x%lx\n", (long)pos); /* */
/* the last position to check */
bfend+= len-maxnlen; /* don't look beyond the EOF */
for(p=bf; p<=bfend; p+=4 /* 4-byte aligned */ ) {
fp=(struct fontmetrics *)p;
if(fp->name==0)
continue;
if( memcmp(gm, fp->glyphs, sizeof gm) )
continue;
/* OK, looks like it, see if we can match it to any name */
n= fp->name & PAGEMASK;
for(i=0; i<nfonts; i++) {
for(j=0; j<o[i].noff; j++)
if( n==(o[i].off[j] & PAGEMASK) ) {
zerooff[nzeroes]= pos + (p-bf);
nameaddr[nzeroes]= fp->name;
zeroid[nzeroes]=i;
o[i].nz++;
fprintf(stderr, "matched %s at 0x%lx\n",
font[i].nsname, (long) zerooff[nzeroes]);
nzeroes++;
matched[i]++;
break;
}
}
}
if(len==0)
break;
memmove(bf, bfend, maxnlen);
pos+= (bfend-bf);
bfend= (bf+maxnlen);
}
if(len<0) {
sprintf(msg,"nsfix: read %s",fn);
perror(msg);
exit(1);
}
fprintf(stderr,"---\n");
/* make sure that all the fonts got one match */
k=0; /* flag: have non-matched fonts */ n=0; /* flag: have ambiguities */
for(i=0; i<nfonts; i++)
if(matched[i]==0)
k=1;
else if(matched[i]>1)
n=1;
if(k) {
fprintf(stderr,"nsfix: can't find match for some of the fonts\n");
fprintf(stderr,"nsfix: maybe wrong byte order, aborting\n");
exit(1);
}
if(n) {
fprintf(stderr,"nsfix: got multiple matches for some of the fonts\n");
fprintf(stderr,"nsfix: can't resolve, aborting\n");
exit(1);
}
/* now finally write the updated tables */
for(i=0; i<nzeroes; i++) {
j=zeroid[i];
fprintf(stderr, "nsfix: writing table for %s at 0x%lx\n", font[j].nsname,
(long)zerooff[i]);
font[j].metrics.name=nameaddr[i];
if( lseek(f, zerooff[i], SEEK_SET)<0 ) {
sprintf(msg,"nsfix: seek %s to 0x%lx",fn, (long)zerooff[i] );
perror(msg);
exit(1);
}
if( write(f, &font[j].metrics, sizeof font[j].metrics) != sizeof font[j].metrics ) {
sprintf(msg,"nsfix: write to %s",fn );
perror(msg);
exit(1);
}
}
close(f);
}
|
gpl-3.0
|
azraelrabbit/shadowsocks-android
|
src/main/jni/badvpn/ncd/modules/ondemand.c
|
360
|
11061
|
/**
* @file ondemand.c
* @author Ambroz Bizjak <ambrop7@gmail.com>
*
* @section LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author 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 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.
*
* @section DESCRIPTION
*
* On-demand process manager.
*
* Synopsis:
* ondemand(string template_name, list args)
*
* Description:
* Manages an on-demand template process using a process template named
* template_name.
* On deinitialization, if the process is running, reqests its termination
* and waits for it to terminate.
*
* Synopsis:
* ondemand::demand()
*
* Description:
* Demands the availability of an on-demand template process.
* This statement is in UP state if and only if the template process of the
* corresponding ondemand object is completely up.
*
* Variables:
* Exposes variables and objects from the template process corresponding to
* the ondemand object.
*/
#include <stdlib.h>
#include <string.h>
#include <misc/offset.h>
#include <misc/debug.h>
#include <structure/LinkedList1.h>
#include <ncd/NCDModule.h>
#include <generated/blog_channel_ncd_ondemand.h>
#define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
struct ondemand {
NCDModuleInst *i;
NCDValRef template_name;
NCDValRef args;
LinkedList1 demands_list;
int dying;
int have_process;
NCDModuleProcess process;
int process_terminating;
int process_up;
};
struct demand {
NCDModuleInst *i;
struct ondemand *od;
LinkedList1Node demands_list_node;
};
static int ondemand_start_process (struct ondemand *o);
static void ondemand_terminate_process (struct ondemand *o);
static void ondemand_process_handler (NCDModuleProcess *process, int event);
static void ondemand_free (struct ondemand *o);
static void demand_free (struct demand *o, int is_error);
static int ondemand_start_process (struct ondemand *o)
{
ASSERT(!o->dying)
ASSERT(!o->have_process)
// start process
if (!NCDModuleProcess_InitValue(&o->process, o->i, o->template_name, o->args, ondemand_process_handler)) {
ModuleLog(o->i, BLOG_ERROR, "NCDModuleProcess_Init failed");
goto fail0;
}
// set have process
o->have_process = 1;
// set process not terminating
o->process_terminating = 0;
// set process not up
o->process_up = 0;
return 1;
fail0:
return 0;
}
static void ondemand_terminate_process (struct ondemand *o)
{
ASSERT(o->have_process)
ASSERT(!o->process_terminating)
// request termination
NCDModuleProcess_Terminate(&o->process);
// set process terminating
o->process_terminating = 1;
if (o->process_up) {
// set process down
o->process_up = 0;
// signal demands down
for (LinkedList1Node *n = LinkedList1_GetFirst(&o->demands_list); n; n = LinkedList1Node_Next(n)) {
struct demand *demand = UPPER_OBJECT(n, struct demand, demands_list_node);
ASSERT(demand->od == o)
NCDModuleInst_Backend_Down(demand->i);
}
}
}
static void ondemand_process_handler (NCDModuleProcess *process, int event)
{
struct ondemand *o = UPPER_OBJECT(process, struct ondemand, process);
ASSERT(o->have_process)
switch (event) {
case NCDMODULEPROCESS_EVENT_UP: {
ASSERT(!o->process_terminating)
ASSERT(!o->process_up)
// set process up
o->process_up = 1;
// signal demands up
for (LinkedList1Node *n = LinkedList1_GetFirst(&o->demands_list); n; n = LinkedList1Node_Next(n)) {
struct demand *demand = UPPER_OBJECT(n, struct demand, demands_list_node);
ASSERT(demand->od == o)
NCDModuleInst_Backend_Up(demand->i);
}
} break;
case NCDMODULEPROCESS_EVENT_DOWN: {
ASSERT(!o->process_terminating)
ASSERT(o->process_up)
// continue process
NCDModuleProcess_Continue(&o->process);
// set process down
o->process_up = 0;
// signal demands down
for (LinkedList1Node *n = LinkedList1_GetFirst(&o->demands_list); n; n = LinkedList1Node_Next(n)) {
struct demand *demand = UPPER_OBJECT(n, struct demand, demands_list_node);
ASSERT(demand->od == o)
NCDModuleInst_Backend_Down(demand->i);
}
} break;
case NCDMODULEPROCESS_EVENT_TERMINATED: {
ASSERT(o->process_terminating)
ASSERT(!o->process_up)
// free process
NCDModuleProcess_Free(&o->process);
// set have no process
o->have_process = 0;
// if dying, die finally
if (o->dying) {
ondemand_free(o);
return;
}
// if demands arrivied, restart process
if (!LinkedList1_IsEmpty(&o->demands_list)) {
if (!ondemand_start_process(o)) {
// error demands
while (!LinkedList1_IsEmpty(&o->demands_list)) {
struct demand *demand = UPPER_OBJECT(LinkedList1_GetFirst(&o->demands_list), struct demand, demands_list_node);
ASSERT(demand->od == o)
demand_free(demand, 1);
}
}
}
} break;
}
}
static void ondemand_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
struct ondemand *o = vo;
o->i = i;
// read arguments
NCDValRef arg_template_name;
NCDValRef arg_args;
if (!NCDVal_ListRead(params->args, 2, &arg_template_name, &arg_args)) {
ModuleLog(i, BLOG_ERROR, "wrong arity");
goto fail0;
}
if (!NCDVal_IsString(arg_template_name) || !NCDVal_IsList(arg_args)) {
ModuleLog(i, BLOG_ERROR, "wrong type");
goto fail0;
}
o->template_name = arg_template_name;
o->args = arg_args;
// init demands list
LinkedList1_Init(&o->demands_list);
// set not dying
o->dying = 0;
// set have no process
o->have_process = 0;
// signal up
NCDModuleInst_Backend_Up(i);
return;
fail0:
NCDModuleInst_Backend_DeadError(i);
}
static void ondemand_free (struct ondemand *o)
{
ASSERT(!o->have_process)
// die demands
while (!LinkedList1_IsEmpty(&o->demands_list)) {
struct demand *demand = UPPER_OBJECT(LinkedList1_GetFirst(&o->demands_list), struct demand, demands_list_node);
ASSERT(demand->od == o)
demand_free(demand, 0);
}
NCDModuleInst_Backend_Dead(o->i);
}
static void ondemand_func_die (void *vo)
{
struct ondemand *o = vo;
ASSERT(!o->dying)
// if not have process, die right away
if (!o->have_process) {
ondemand_free(o);
return;
}
// set dying
o->dying = 1;
// request process termination if not already
if (!o->process_terminating) {
ondemand_terminate_process(o);
}
}
static void demand_func_new (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
struct demand *o = vo;
o->i = i;
// read arguments
if (!NCDVal_ListRead(params->args, 0)) {
ModuleLog(i, BLOG_ERROR, "wrong arity");
goto fail0;
}
// set ondemand
o->od = NCDModuleInst_Backend_GetUser((NCDModuleInst *)params->method_user);
// add to ondemand's demands list
LinkedList1_Append(&o->od->demands_list, &o->demands_list_node);
// start process if needed
if (!o->od->have_process) {
ASSERT(!o->od->dying)
if (!ondemand_start_process(o->od)) {
goto fail1;
}
}
// if process is up, signal up
if (o->od->process_up) {
NCDModuleInst_Backend_Up(i);
}
return;
fail1:
LinkedList1_Remove(&o->od->demands_list, &o->demands_list_node);
fail0:
NCDModuleInst_Backend_DeadError(i);
}
static void demand_free (struct demand *o, int is_error)
{
// remove from ondemand's demands list
LinkedList1_Remove(&o->od->demands_list, &o->demands_list_node);
// request process termination if no longer needed
if (o->od->have_process && !o->od->process_terminating && LinkedList1_IsEmpty(&o->od->demands_list)) {
ondemand_terminate_process(o->od);
}
if (is_error) {
NCDModuleInst_Backend_DeadError(o->i);
} else {
NCDModuleInst_Backend_Dead(o->i);
}
}
static void demand_func_die (void *vo)
{
struct demand *o = vo;
demand_free(o, 0);
}
static int demand_func_getobj (void *vo, NCD_string_id_t objname, NCDObject *out_object)
{
struct demand *o = vo;
ASSERT(o->od->have_process)
ASSERT(o->od->process_up)
return NCDModuleProcess_GetObj(&o->od->process, objname, out_object);
}
static struct NCDModule modules[] = {
{
.type = "ondemand",
.func_new2 = ondemand_func_new,
.func_die = ondemand_func_die,
.alloc_size = sizeof(struct ondemand)
}, {
.type = "ondemand::demand",
.func_new2 = demand_func_new,
.func_die = demand_func_die,
.func_getobj = demand_func_getobj,
.alloc_size = sizeof(struct demand)
}, {
.type = NULL
}
};
const struct NCDModuleGroup ncdmodule_ondemand = {
.modules = modules
};
|
gpl-3.0
|
Sandeep85Das/pathgrind
|
valgrind-r12356/perf/many-loss-records.c
|
105
|
5380
|
// Performance test for the leak checker from bug #191182.
// Nb: it must be run with --leak-resolution=high to show the quadratic
// behaviour caused by the large number of loss records.
// By Philippe Waroquiers.
//
// On my machine, before being fixed, building the loss record list took about
// 36 seconds, and sorting + printing it took about 20 seconds. After being
// fixed it took about 2 seconds, and the leak checking was only a small
// fraction of that. --njn
#include <stdlib.h>
#include <strings.h>
#include <stdio.h>
#include <math.h>
/* parameters */
/* we will create stack_fan_out ^ stack_depth different call stacks */
int stack_fan_out = 15;
int stack_depth = 4;
/* for each call stack, allocate malloc_fan blocks */
int malloc_fan = 4;
/* for each call stack, allocate data structures having malloc_depth
indirection at each malloc-ed level */
int malloc_depth = 2;
/* in addition to the pointer needed to maintain the levels; some more
bytes are allocated simulating the data stored in the data structure */
int malloc_data = 5;
/* every n top blocks, 1 block and all its children will be freed instead of
being kept */
int free_every_n = 2;
/* every n release block operation, 1 block and its children will be leaked */
int leak_every_n = 250;
struct Chunk {
struct Chunk* child;
char s[];
};
struct Chunk** topblocks;
int freetop = 0;
/* statistics */
long total_malloced = 0;
int blocknr = 0;
int blockfreed = 0;
int blockleaked = 0;
int total_stacks = 0;
int releaseop = 0;
void free_chunks (struct Chunk ** mem)
{
if (*mem == 0)
return;
free_chunks ((&(*mem)->child));
blockfreed++;
free (*mem);
*mem = 0;
}
void release (struct Chunk ** mem)
{
releaseop++;
if (releaseop % leak_every_n == 0) {
blockleaked++;
*mem = 0; // lose the pointer without free-ing the blocks
} else {
free_chunks (mem);
}
}
void call_stack (int level)
{
int call_fan_out = 1;
if (level == stack_depth) {
int sz = sizeof(struct Chunk*) + malloc_data;
int d;
int f;
for (f = 0; f < malloc_fan; f++) {
struct Chunk *new = NULL; // shut gcc up
struct Chunk *prev = NULL;
for (d = 0; d < malloc_depth; d++) {
new = malloc (sz);
total_malloced += sz;
blocknr++;
new->child = prev;
prev = new;
}
topblocks[freetop] = new;
if (freetop % free_every_n == 0) {
release (&topblocks[freetop]);
}
freetop++;
}
total_stacks++;
} else {
/* Nb: don't common these up into a loop! We need different code
locations to exercise the problem. */
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
call_stack (level + 1);
if (call_fan_out == stack_fan_out) return;
call_fan_out++;
printf ("maximum stack_fan_out exceeded\n");
}
}
int main()
{
int d;
int stacks = 1;
for (d = 0; d < stack_depth; d++)
stacks *= stack_fan_out;
printf ("will generate %d different stacks\n", stacks);
topblocks = malloc(sizeof(struct Chunk*) * stacks * malloc_fan);
call_stack (0);
printf ("total stacks %d\n", total_stacks);
printf ("total bytes malloc-ed: %ld\n", total_malloced);
printf ("total blocks malloc-ed: %d\n", blocknr);
printf ("total blocks free-ed: %d\n", blockfreed);
printf ("total blocks leak-ed: %d\n", blockleaked);
return 0;
}
|
gpl-3.0
|
laborautonomo/bitmask_android
|
app/openssl/crypto/asn1/x_spki.c
|
877
|
3914
|
/* crypto/asn1/x_spki.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.]
*/
/* This module was send to me my Pat Richards <patr@x509.com> who
* wrote it. It is under my Copyright with his permission
*/
#include <stdio.h>
#include "cryptlib.h"
#include <openssl/x509.h>
#include <openssl/asn1t.h>
ASN1_SEQUENCE(NETSCAPE_SPKAC) = {
ASN1_SIMPLE(NETSCAPE_SPKAC, pubkey, X509_PUBKEY),
ASN1_SIMPLE(NETSCAPE_SPKAC, challenge, ASN1_IA5STRING)
} ASN1_SEQUENCE_END(NETSCAPE_SPKAC)
IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_SPKAC)
ASN1_SEQUENCE(NETSCAPE_SPKI) = {
ASN1_SIMPLE(NETSCAPE_SPKI, spkac, NETSCAPE_SPKAC),
ASN1_SIMPLE(NETSCAPE_SPKI, sig_algor, X509_ALGOR),
ASN1_SIMPLE(NETSCAPE_SPKI, signature, ASN1_BIT_STRING)
} ASN1_SEQUENCE_END(NETSCAPE_SPKI)
IMPLEMENT_ASN1_FUNCTIONS(NETSCAPE_SPKI)
|
gpl-3.0
|
iAugux/shadowsocks-android
|
src/main/jni/badvpn/lwip/test/unit/dhcp/test_dhcp.c
|
366
|
33620
|
#include "test_dhcp.h"
#include "lwip/netif.h"
#include "lwip/dhcp.h"
#include "netif/etharp.h"
struct netif net_test;
static const u8_t broadcast[6] = { 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF };
static const u8_t magic_cookie[] = { 0x63, 0x82, 0x53, 0x63 };
static u8_t dhcp_offer[] = {
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* To unit */
0x00, 0x0F, 0xEE, 0x30, 0xAB, 0x22, /* From Remote host */
0x08, 0x00, /* Protocol: IP */
0x45, 0x10, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x36, 0xcc, 0xc3, 0xaa, 0xbd, 0xab, 0xc3, 0xaa, 0xbd, 0xc8, /* IP header */
0x00, 0x43, 0x00, 0x44, 0x01, 0x34, 0x00, 0x00, /* UDP header */
0x02, /* Type == Boot reply */
0x01, 0x06, /* Hw Ethernet, 6 bytes addrlen */
0x00, /* 0 hops */
0xAA, 0xAA, 0xAA, 0xAA, /* Transaction id, will be overwritten */
0x00, 0x00, /* 0 seconds elapsed */
0x00, 0x00, /* Flags (unicast) */
0x00, 0x00, 0x00, 0x00, /* Client ip */
0xc3, 0xaa, 0xbd, 0xc8, /* Your IP */
0xc3, 0xaa, 0xbd, 0xab, /* DHCP server ip */
0x00, 0x00, 0x00, 0x00, /* relay agent */
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* MAC addr + padding */
/* Empty server name and boot file name */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x63, 0x82, 0x53, 0x63, /* Magic cookie */
0x35, 0x01, 0x02, /* Message type: Offer */
0x36, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Server identifier (IP) */
0x33, 0x04, 0x00, 0x00, 0x00, 0x78, /* Lease time 2 minutes */
0x03, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Router IP */
0x01, 0x04, 0xff, 0xff, 0xff, 0x00, /* Subnet mask */
0xff, /* End option */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Padding */
};
static u8_t dhcp_ack[] = {
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* To unit */
0x00, 0x0f, 0xEE, 0x30, 0xAB, 0x22, /* From remote host */
0x08, 0x00, /* Proto IP */
0x45, 0x10, 0x01, 0x48, 0x00, 0x00, 0x00, 0x00, 0x80, 0x11, 0x36, 0xcc, 0xc3, 0xaa, 0xbd, 0xab, 0xc3, 0xaa, 0xbd, 0xc8, /* IP header */
0x00, 0x43, 0x00, 0x44, 0x01, 0x34, 0x00, 0x00, /* UDP header */
0x02, /* Bootp reply */
0x01, 0x06, /* Hw type Eth, len 6 */
0x00, /* 0 hops */
0xAA, 0xAA, 0xAA, 0xAA,
0x00, 0x00, /* 0 seconds elapsed */
0x00, 0x00, /* Flags (unicast) */
0x00, 0x00, 0x00, 0x00, /* Client IP */
0xc3, 0xaa, 0xbd, 0xc8, /* Your IP */
0xc3, 0xaa, 0xbd, 0xab, /* DHCP server IP */
0x00, 0x00, 0x00, 0x00, /* Relay agent */
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Macaddr + padding */
/* Empty server name and boot file name */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00,
0x63, 0x82, 0x53, 0x63, /* Magic cookie */
0x35, 0x01, 0x05, /* Dhcp message type ack */
0x36, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* DHCP server identifier */
0x33, 0x04, 0x00, 0x00, 0x00, 0x78, /* Lease time 2 minutes */
0x03, 0x04, 0xc3, 0xaa, 0xbd, 0xab, /* Router IP */
0x01, 0x04, 0xff, 0xff, 0xff, 0x00, /* Netmask */
0xff, /* End marker */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, /* Padding */
};
static const u8_t arpreply[] = {
0x00, 0x23, 0xC1, 0xDE, 0xD0, 0x0D, /* dst mac */
0x00, 0x32, 0x44, 0x20, 0x01, 0x02, /* src mac */
0x08, 0x06, /* proto arp */
0x00, 0x01, /* hw eth */
0x08, 0x00, /* proto ip */
0x06, /* hw addr len 6 */
0x04, /* proto addr len 4 */
0x00, 0x02, /* arp reply */
0x00, 0x32, 0x44, 0x20, 0x01, 0x02, /* sender mac */
0xc3, 0xaa, 0xbd, 0xc8, /* sender ip */
0x00, 0x23, 0xC1, 0xDE, 0xD0, 0x0D, /* target mac */
0x00, 0x00, 0x00, 0x00, /* target ip */
};
static int txpacket;
static enum tcase {
TEST_LWIP_DHCP,
TEST_LWIP_DHCP_NAK,
TEST_LWIP_DHCP_RELAY,
TEST_LWIP_DHCP_NAK_NO_ENDMARKER,
} tcase;
static int debug = 0;
static void setdebug(int a) {debug = a;}
static int tick = 0;
static void tick_lwip(void)
{
tick++;
if (tick % 5 == 0) {
dhcp_fine_tmr();
}
if (tick % 600 == 0) {
dhcp_coarse_tmr();
}
}
static void send_pkt(struct netif *netif, const u8_t *data, u32_t len)
{
struct pbuf *p = pbuf_alloc(PBUF_RAW, len, PBUF_POOL);
struct pbuf *q;
if (debug) {
/* Dump data */
u32_t i;
printf("RX data (len %d)", p->tot_len);
for (i = 0; i < len; i++) {
printf(" %02X", data[i]);
}
printf("\n");
}
fail_unless(p != NULL);
for(q = p; q != NULL; q = q->next) {
memcpy(q->payload, data, q->len);
data += q->len;
}
netif->input(p, netif);
}
static err_t lwip_tx_func(struct netif *netif, struct pbuf *p);
static err_t testif_init(struct netif *netif)
{
netif->name[0] = 'c';
netif->name[1] = 'h';
netif->output = etharp_output;
netif->linkoutput = lwip_tx_func;
netif->mtu = 1500;
netif->hwaddr_len = 6;
netif->flags = NETIF_FLAG_BROADCAST | NETIF_FLAG_ETHARP;
netif->hwaddr[0] = 0x00;
netif->hwaddr[1] = 0x23;
netif->hwaddr[2] = 0xC1;
netif->hwaddr[3] = 0xDE;
netif->hwaddr[4] = 0xD0;
netif->hwaddr[5] = 0x0D;
return ERR_OK;
}
static void dhcp_setup(void)
{
txpacket = 0;
}
static void dhcp_teardown(void)
{
}
static void check_pkt(struct pbuf *p, u32_t pos, const u8_t *mem, u32_t len)
{
u8_t *data;
fail_if((pos + len) > p->tot_len);
while (pos > p->len && p->next) {
pos -= p->len;
p = p->next;
}
fail_if(p == NULL);
fail_unless(pos + len <= p->len); /* All data we seek within same pbuf */
data = p->payload;
fail_if(memcmp(&data[pos], mem, len), "data at pos %d, len %d in packet %d did not match", pos, len, txpacket);
}
static void check_pkt_fuzzy(struct pbuf *p, u32_t startpos, const u8_t *mem, u32_t len)
{
int found;
u32_t i;
u8_t *data;
fail_if((startpos + len) > p->tot_len);
while (startpos > p->len && p->next) {
startpos -= p->len;
p = p->next;
}
fail_if(p == NULL);
fail_unless(startpos + len <= p->len); /* All data we seek within same pbuf */
found = 0;
data = p->payload;
for (i = startpos; i <= (p->len - len); i++) {
if (memcmp(&data[i], mem, len) == 0) {
found = 1;
break;
}
}
fail_unless(found);
}
static err_t lwip_tx_func(struct netif *netif, struct pbuf *p)
{
fail_unless(netif == &net_test);
txpacket++;
if (debug) {
struct pbuf *pp = p;
/* Dump data */
printf("TX data (pkt %d, len %d, tick %d)", txpacket, p->tot_len, tick);
do {
int i;
for (i = 0; i < pp->len; i++) {
printf(" %02X", ((u8_t *) pp->payload)[i]);
}
if (pp->next) {
pp = pp->next;
}
} while (pp->next);
printf("\n");
}
switch (tcase) {
case TEST_LWIP_DHCP:
switch (txpacket) {
case 1:
case 2:
{
const u8_t ipproto[] = { 0x08, 0x00 };
const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */
const u8_t ipaddrs[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */
check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */
check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */
check_pkt(p, 42, bootp_start, sizeof(bootp_start));
check_pkt(p, 53, ipaddrs, sizeof(ipaddrs));
check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */
check_pkt(p, 278, magic_cookie, sizeof(magic_cookie));
/* Check dchp message type, can be at different positions */
if (txpacket == 1) {
u8_t dhcp_discover_opt[] = { 0x35, 0x01, 0x01 };
check_pkt_fuzzy(p, 282, dhcp_discover_opt, sizeof(dhcp_discover_opt));
} else if (txpacket == 2) {
u8_t dhcp_request_opt[] = { 0x35, 0x01, 0x03 };
u8_t requested_ipaddr[] = { 0x32, 0x04, 0xc3, 0xaa, 0xbd, 0xc8 }; /* Ask for offered IP */
check_pkt_fuzzy(p, 282, dhcp_request_opt, sizeof(dhcp_request_opt));
check_pkt_fuzzy(p, 282, requested_ipaddr, sizeof(requested_ipaddr));
}
break;
}
case 3:
case 4:
case 5:
{
const u8_t arpproto[] = { 0x08, 0x06 };
check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */
check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */
check_pkt(p, 12, arpproto, sizeof(arpproto)); /* eth level proto: ip */
break;
}
}
break;
case TEST_LWIP_DHCP_NAK:
{
const u8_t ipproto[] = { 0x08, 0x00 };
const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */
const u8_t ipaddrs[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
const u8_t dhcp_nak_opt[] = { 0x35, 0x01, 0x04 };
const u8_t requested_ipaddr[] = { 0x32, 0x04, 0xc3, 0xaa, 0xbd, 0xc8 }; /* offered IP */
fail_unless(txpacket == 4);
check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */
check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */
check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */
check_pkt(p, 42, bootp_start, sizeof(bootp_start));
check_pkt(p, 53, ipaddrs, sizeof(ipaddrs));
check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */
check_pkt(p, 278, magic_cookie, sizeof(magic_cookie));
check_pkt_fuzzy(p, 282, dhcp_nak_opt, sizeof(dhcp_nak_opt)); /* NAK the ack */
check_pkt_fuzzy(p, 282, requested_ipaddr, sizeof(requested_ipaddr));
break;
}
case TEST_LWIP_DHCP_RELAY:
switch (txpacket) {
case 1:
case 2:
{
const u8_t ipproto[] = { 0x08, 0x00 };
const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */
const u8_t ipaddrs[] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */
check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */
check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */
check_pkt(p, 42, bootp_start, sizeof(bootp_start));
check_pkt(p, 53, ipaddrs, sizeof(ipaddrs));
check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */
check_pkt(p, 278, magic_cookie, sizeof(magic_cookie));
/* Check dchp message type, can be at different positions */
if (txpacket == 1) {
u8_t dhcp_discover_opt[] = { 0x35, 0x01, 0x01 };
check_pkt_fuzzy(p, 282, dhcp_discover_opt, sizeof(dhcp_discover_opt));
} else if (txpacket == 2) {
u8_t dhcp_request_opt[] = { 0x35, 0x01, 0x03 };
u8_t requested_ipaddr[] = { 0x32, 0x04, 0x4f, 0x8a, 0x33, 0x05 }; /* Ask for offered IP */
check_pkt_fuzzy(p, 282, dhcp_request_opt, sizeof(dhcp_request_opt));
check_pkt_fuzzy(p, 282, requested_ipaddr, sizeof(requested_ipaddr));
}
break;
}
case 3:
case 4:
case 5:
case 6:
{
const u8_t arpproto[] = { 0x08, 0x06 };
check_pkt(p, 0, broadcast, 6); /* eth level dest: broadcast */
check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */
check_pkt(p, 12, arpproto, sizeof(arpproto)); /* eth level proto: ip */
break;
}
case 7:
{
const u8_t fake_arp[6] = { 0x12, 0x34, 0x56, 0x78, 0x9a, 0xab };
const u8_t ipproto[] = { 0x08, 0x00 };
const u8_t bootp_start[] = { 0x01, 0x01, 0x06, 0x00}; /* bootp request, eth, hwaddr len 6, 0 hops */
const u8_t ipaddrs[] = { 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
const u8_t dhcp_request_opt[] = { 0x35, 0x01, 0x03 };
check_pkt(p, 0, fake_arp, 6); /* eth level dest: broadcast */
check_pkt(p, 6, netif->hwaddr, 6); /* eth level src: unit mac */
check_pkt(p, 12, ipproto, sizeof(ipproto)); /* eth level proto: ip */
check_pkt(p, 42, bootp_start, sizeof(bootp_start));
check_pkt(p, 53, ipaddrs, sizeof(ipaddrs));
check_pkt(p, 70, netif->hwaddr, 6); /* mac addr inside bootp */
check_pkt(p, 278, magic_cookie, sizeof(magic_cookie));
/* Check dchp message type, can be at different positions */
check_pkt_fuzzy(p, 282, dhcp_request_opt, sizeof(dhcp_request_opt));
break;
}
}
break;
default:
break;
}
return ERR_OK;
}
/*
* Test basic happy flow DHCP session.
* Validate that xid is checked.
*/
START_TEST(test_dhcp)
{
struct ip_addr addr;
struct ip_addr netmask;
struct ip_addr gw;
int i;
u32_t xid;
LWIP_UNUSED_ARG(_i);
tcase = TEST_LWIP_DHCP;
setdebug(0);
IP4_ADDR(&addr, 0, 0, 0, 0);
IP4_ADDR(&netmask, 0, 0, 0, 0);
IP4_ADDR(&gw, 0, 0, 0, 0);
netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input);
dhcp_start(&net_test);
fail_unless(txpacket == 1); /* DHCP discover sent */
xid = net_test.dhcp->xid; /* Write bad xid, not using htonl! */
memcpy(&dhcp_offer[46], &xid, 4);
send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer));
/* Interface down */
fail_if(netif_is_up(&net_test));
/* IP addresses should be zero */
fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(struct ip_addr)));
fail_if(memcmp(&netmask, &net_test.netmask, sizeof(struct ip_addr)));
fail_if(memcmp(&gw, &net_test.gw, sizeof(struct ip_addr)));
fail_unless(txpacket == 1, "TX %d packets, expected 1", txpacket); /* Nothing more sent */
xid = htonl(net_test.dhcp->xid);
memcpy(&dhcp_offer[46], &xid, 4); /* insert correct transaction id */
send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer));
fail_unless(txpacket == 2, "TX %d packets, expected 2", txpacket); /* DHCP request sent */
xid = net_test.dhcp->xid; /* Write bad xid, not using htonl! */
memcpy(&dhcp_ack[46], &xid, 4);
send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack));
fail_unless(txpacket == 2, "TX %d packets, still expected 2", txpacket); /* No more sent */
xid = htonl(net_test.dhcp->xid); /* xid updated */
memcpy(&dhcp_ack[46], &xid, 4); /* insert transaction id */
send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack));
for (i = 0; i < 20; i++) {
tick_lwip();
}
fail_unless(txpacket == 4, "TX %d packets, expected 4", txpacket); /* ARP requests sent */
/* Interface up */
fail_unless(netif_is_up(&net_test));
/* Now it should have taken the IP */
IP4_ADDR(&addr, 195, 170, 189, 200);
IP4_ADDR(&netmask, 255, 255, 255, 0);
IP4_ADDR(&gw, 195, 170, 189, 171);
fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(struct ip_addr)));
fail_if(memcmp(&netmask, &net_test.netmask, sizeof(struct ip_addr)));
fail_if(memcmp(&gw, &net_test.gw, sizeof(struct ip_addr)));
netif_remove(&net_test);
}
END_TEST
/*
* Test that IP address is not taken and NAK is sent if someone
* replies to ARP requests for the offered address.
*/
START_TEST(test_dhcp_nak)
{
struct ip_addr addr;
struct ip_addr netmask;
struct ip_addr gw;
u32_t xid;
LWIP_UNUSED_ARG(_i);
tcase = TEST_LWIP_DHCP;
setdebug(0);
IP4_ADDR(&addr, 0, 0, 0, 0);
IP4_ADDR(&netmask, 0, 0, 0, 0);
IP4_ADDR(&gw, 0, 0, 0, 0);
netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input);
dhcp_start(&net_test);
fail_unless(txpacket == 1); /* DHCP discover sent */
xid = net_test.dhcp->xid; /* Write bad xid, not using htonl! */
memcpy(&dhcp_offer[46], &xid, 4);
send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer));
/* Interface down */
fail_if(netif_is_up(&net_test));
/* IP addresses should be zero */
fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(struct ip_addr)));
fail_if(memcmp(&netmask, &net_test.netmask, sizeof(struct ip_addr)));
fail_if(memcmp(&gw, &net_test.gw, sizeof(struct ip_addr)));
fail_unless(txpacket == 1); /* Nothing more sent */
xid = htonl(net_test.dhcp->xid);
memcpy(&dhcp_offer[46], &xid, 4); /* insert correct transaction id */
send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer));
fail_unless(txpacket == 2); /* DHCP request sent */
xid = net_test.dhcp->xid; /* Write bad xid, not using htonl! */
memcpy(&dhcp_ack[46], &xid, 4);
send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack));
fail_unless(txpacket == 2); /* No more sent */
xid = htonl(net_test.dhcp->xid); /* xid updated */
memcpy(&dhcp_ack[46], &xid, 4); /* insert transaction id */
send_pkt(&net_test, dhcp_ack, sizeof(dhcp_ack));
fail_unless(txpacket == 3); /* ARP request sent */
tcase = TEST_LWIP_DHCP_NAK; /* Switch testcase */
/* Send arp reply, mark offered IP as taken */
send_pkt(&net_test, arpreply, sizeof(arpreply));
fail_unless(txpacket == 4); /* DHCP nak sent */
netif_remove(&net_test);
}
END_TEST
/*
* Test case based on captured data where
* replies are sent from a different IP than the
* one the client unicasted to.
*/
START_TEST(test_dhcp_relayed)
{
const u8_t relay_offer[] = {
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d,
0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60,
0x08, 0x00, 0x45, 0x00,
0x01, 0x38, 0xfd, 0x53, 0x00, 0x00, 0x40, 0x11,
0x78, 0x46, 0x4f, 0x8a, 0x32, 0x02, 0x4f, 0x8a,
0x33, 0x05, 0x00, 0x43, 0x00, 0x44, 0x01, 0x24,
0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x51, 0x35,
0xb6, 0xa0, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xb5, 0x04, 0x01, 0x00, 0x23,
0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82,
0x53, 0x63, 0x01, 0x04, 0xff, 0xff, 0xfe, 0x00,
0x03, 0x04, 0x4f, 0x8a, 0x32, 0x01, 0x06, 0x08,
0x4f, 0x8a, 0x00, 0xb4, 0x55, 0x08, 0x1f, 0xd1,
0x1c, 0x04, 0x4f, 0x8a, 0x33, 0xff, 0x33, 0x04,
0x00, 0x00, 0x54, 0x49, 0x35, 0x01, 0x02, 0x36,
0x04, 0x0a, 0xb5, 0x04, 0x01, 0xff
};
const u8_t relay_ack1[] = {
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x22,
0x93, 0x5a, 0xf7, 0x60, 0x08, 0x00, 0x45, 0x00,
0x01, 0x38, 0xfd, 0x55, 0x00, 0x00, 0x40, 0x11,
0x78, 0x44, 0x4f, 0x8a, 0x32, 0x02, 0x4f, 0x8a,
0x33, 0x05, 0x00, 0x43, 0x00, 0x44, 0x01, 0x24,
0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x51, 0x35,
0xb6, 0xa1, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xb5, 0x04, 0x01, 0x00, 0x23,
0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82,
0x53, 0x63, 0x01, 0x04, 0xff, 0xff, 0xfe, 0x00,
0x03, 0x04, 0x4f, 0x8a, 0x32, 0x01, 0x06, 0x08,
0x4f, 0x8a, 0x00, 0xb4, 0x55, 0x08, 0x1f, 0xd1,
0x1c, 0x04, 0x4f, 0x8a, 0x33, 0xff, 0x33, 0x04,
0x00, 0x00, 0x54, 0x49, 0x35, 0x01, 0x05, 0x36,
0x04, 0x0a, 0xb5, 0x04, 0x01, 0xff
};
const u8_t relay_ack2[] = {
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d,
0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60,
0x08, 0x00, 0x45, 0x00,
0x01, 0x38, 0xfa, 0x18, 0x00, 0x00, 0x40, 0x11,
0x7b, 0x81, 0x4f, 0x8a, 0x32, 0x02, 0x4f, 0x8a,
0x33, 0x05, 0x00, 0x43, 0x00, 0x44, 0x01, 0x24,
0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x49, 0x8b,
0x6e, 0xab, 0x00, 0x00, 0x00, 0x00, 0x4f, 0x8a,
0x33, 0x05, 0x4f, 0x8a, 0x33, 0x05, 0x00, 0x00,
0x00, 0x00, 0x0a, 0xb5, 0x04, 0x01, 0x00, 0x23,
0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82,
0x53, 0x63, 0x01, 0x04, 0xff, 0xff, 0xfe, 0x00,
0x03, 0x04, 0x4f, 0x8a, 0x32, 0x01, 0x06, 0x08,
0x4f, 0x8a, 0x00, 0xb4, 0x55, 0x08, 0x1f, 0xd1,
0x1c, 0x04, 0x4f, 0x8a, 0x33, 0xff, 0x33, 0x04,
0x00, 0x00, 0x54, 0x60, 0x35, 0x01, 0x05, 0x36,
0x04, 0x0a, 0xb5, 0x04, 0x01, 0xff };
const u8_t arp_resp[] = {
0x00, 0x23, 0xc1, 0xde, 0xd0, 0x0d, /* DEST */
0x00, 0x22, 0x93, 0x5a, 0xf7, 0x60, /* SRC */
0x08, 0x06, /* Type: ARP */
0x00, 0x01, /* HW: Ethernet */
0x08, 0x00, /* PROTO: IP */
0x06, /* HW size */
0x04, /* PROTO size */
0x00, 0x02, /* OPCODE: Reply */
0x12, 0x34, 0x56, 0x78, 0x9a, 0xab, /* Target MAC */
0x4f, 0x8a, 0x32, 0x01, /* Target IP */
0x00, 0x23, 0xc1, 0x00, 0x06, 0x50, /* src mac */
0x4f, 0x8a, 0x33, 0x05, /* src ip */
/* Padding follows.. */
0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00 };
struct ip_addr addr;
struct ip_addr netmask;
struct ip_addr gw;
int i;
u32_t xid;
LWIP_UNUSED_ARG(_i);
tcase = TEST_LWIP_DHCP_RELAY;
setdebug(0);
IP4_ADDR(&addr, 0, 0, 0, 0);
IP4_ADDR(&netmask, 0, 0, 0, 0);
IP4_ADDR(&gw, 0, 0, 0, 0);
netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input);
dhcp_start(&net_test);
fail_unless(txpacket == 1); /* DHCP discover sent */
/* Interface down */
fail_if(netif_is_up(&net_test));
/* IP addresses should be zero */
fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(struct ip_addr)));
fail_if(memcmp(&netmask, &net_test.netmask, sizeof(struct ip_addr)));
fail_if(memcmp(&gw, &net_test.gw, sizeof(struct ip_addr)));
fail_unless(txpacket == 1); /* Nothing more sent */
xid = htonl(net_test.dhcp->xid);
memcpy(&relay_offer[46], &xid, 4); /* insert correct transaction id */
send_pkt(&net_test, relay_offer, sizeof(relay_offer));
/* request sent? */
fail_unless(txpacket == 2, "txpkt = %d, should be 2", txpacket);
xid = htonl(net_test.dhcp->xid); /* xid updated */
memcpy(&relay_ack1[46], &xid, 4); /* insert transaction id */
send_pkt(&net_test, relay_ack1, sizeof(relay_ack1));
for (i = 0; i < 25; i++) {
tick_lwip();
}
fail_unless(txpacket == 4, "txpkt should be 5, is %d", txpacket); /* ARP requests sent */
/* Interface up */
fail_unless(netif_is_up(&net_test));
/* Now it should have taken the IP */
IP4_ADDR(&addr, 79, 138, 51, 5);
IP4_ADDR(&netmask, 255, 255, 254, 0);
IP4_ADDR(&gw, 79, 138, 50, 1);
fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(struct ip_addr)));
fail_if(memcmp(&netmask, &net_test.netmask, sizeof(struct ip_addr)));
fail_if(memcmp(&gw, &net_test.gw, sizeof(struct ip_addr)));
fail_unless(txpacket == 4, "txpacket = %d", txpacket);
for (i = 0; i < 108000 - 25; i++) {
tick_lwip();
}
fail_unless(netif_is_up(&net_test));
fail_unless(txpacket == 6, "txpacket = %d", txpacket);
/* We need to send arp response here.. */
send_pkt(&net_test, arp_resp, sizeof(arp_resp));
fail_unless(txpacket == 7, "txpacket = %d", txpacket);
fail_unless(netif_is_up(&net_test));
xid = htonl(net_test.dhcp->xid); /* xid updated */
memcpy(&relay_ack2[46], &xid, 4); /* insert transaction id */
send_pkt(&net_test, relay_ack2, sizeof(relay_ack2));
for (i = 0; i < 100000; i++) {
tick_lwip();
}
fail_unless(txpacket == 7, "txpacket = %d", txpacket);
netif_remove(&net_test);
}
END_TEST
START_TEST(test_dhcp_nak_no_endmarker)
{
struct ip_addr addr;
struct ip_addr netmask;
struct ip_addr gw;
u8_t dhcp_nack_no_endmarker[] = {
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x54, 0x75,
0xd0, 0x26, 0xd0, 0x0d, 0x08, 0x00, 0x45, 0x00,
0x01, 0x15, 0x38, 0x86, 0x00, 0x00, 0xff, 0x11,
0xc0, 0xa8, 0xc0, 0xa8, 0x01, 0x01, 0xff, 0xff,
0xff, 0xff, 0x00, 0x43, 0x00, 0x44, 0x01, 0x01,
0x00, 0x00, 0x02, 0x01, 0x06, 0x00, 0x7a, 0xcb,
0xba, 0xf2, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x23,
0xc1, 0xde, 0xd0, 0x0d, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x63, 0x82,
0x53, 0x63, 0x35, 0x01, 0x06, 0x36, 0x04, 0xc0,
0xa8, 0x01, 0x01, 0x31, 0xef, 0xad, 0x72, 0x31,
0x43, 0x4e, 0x44, 0x30, 0x32, 0x35, 0x30, 0x43,
0x52, 0x47, 0x44, 0x38, 0x35, 0x36, 0x3c, 0x08,
0x4d, 0x53, 0x46, 0x54, 0x20, 0x35, 0x2e, 0x30,
0x37, 0x0d, 0x01, 0x0f, 0x03, 0x06, 0x2c, 0x2e,
0x2f, 0x1f, 0x21, 0x79, 0xf9, 0x2b, 0xfc, 0xff,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xe2, 0x71,
0xf3, 0x5b, 0xe2, 0x71, 0x2e, 0x01, 0x08, 0x03,
0x04, 0xc0, 0xa8, 0x01, 0x01, 0xff, 0xeb, 0x1e,
0x44, 0xec, 0xeb, 0x1e, 0x30, 0x37, 0x0c, 0x01,
0x0f, 0x03, 0x06, 0x2c, 0x2e, 0x2f, 0x1f, 0x21,
0x79, 0xf9, 0x2b, 0xff, 0x25, 0xc0, 0x09, 0xd6,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
u32_t xid;
LWIP_UNUSED_ARG(_i);
tcase = TEST_LWIP_DHCP_NAK_NO_ENDMARKER;
setdebug(0);
IP4_ADDR(&addr, 0, 0, 0, 0);
IP4_ADDR(&netmask, 0, 0, 0, 0);
IP4_ADDR(&gw, 0, 0, 0, 0);
netif_add(&net_test, &addr, &netmask, &gw, &net_test, testif_init, ethernet_input);
dhcp_start(&net_test);
fail_unless(txpacket == 1); /* DHCP discover sent */
xid = net_test.dhcp->xid; /* Write bad xid, not using htonl! */
memcpy(&dhcp_offer[46], &xid, 4);
send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer));
/* Interface down */
fail_if(netif_is_up(&net_test));
/* IP addresses should be zero */
fail_if(memcmp(&addr, &net_test.ip_addr, sizeof(struct ip_addr)));
fail_if(memcmp(&netmask, &net_test.netmask, sizeof(struct ip_addr)));
fail_if(memcmp(&gw, &net_test.gw, sizeof(struct ip_addr)));
fail_unless(txpacket == 1); /* Nothing more sent */
xid = htonl(net_test.dhcp->xid);
memcpy(&dhcp_offer[46], &xid, 4); /* insert correct transaction id */
send_pkt(&net_test, dhcp_offer, sizeof(dhcp_offer));
fail_unless(net_test.dhcp->state == DHCP_REQUESTING);
fail_unless(txpacket == 2); /* No more sent */
xid = htonl(net_test.dhcp->xid); /* xid updated */
memcpy(&dhcp_nack_no_endmarker[46], &xid, 4); /* insert transaction id */
send_pkt(&net_test, dhcp_nack_no_endmarker, sizeof(dhcp_nack_no_endmarker));
/* NAK should put us in another state for a while, no other way detecting it */
fail_unless(net_test.dhcp->state != DHCP_REQUESTING);
netif_remove(&net_test);
}
END_TEST
/** Create the suite including all tests for this module */
Suite *
dhcp_suite(void)
{
TFun tests[] = {
test_dhcp,
test_dhcp_nak,
test_dhcp_relayed,
test_dhcp_nak_no_endmarker
};
return create_suite("DHCP", tests, sizeof(tests)/sizeof(TFun), dhcp_setup, dhcp_teardown);
}
|
gpl-3.0
|
Team-Huawei/android_kernel_huawei_msm8909
|
drivers/mtd/nand/orion_nand.c
|
2158
|
5332
|
/*
* drivers/mtd/nand/orion_nand.c
*
* NAND support for Marvell Orion SoC platforms
*
* Tzachi Perelstein <tzachi@marvell.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/of.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/nand.h>
#include <linux/mtd/partitions.h>
#include <linux/clk.h>
#include <linux/err.h>
#include <asm/io.h>
#include <asm/sizes.h>
#include <linux/platform_data/mtd-orion_nand.h>
static void orion_nand_cmd_ctrl(struct mtd_info *mtd, int cmd, unsigned int ctrl)
{
struct nand_chip *nc = mtd->priv;
struct orion_nand_data *board = nc->priv;
u32 offs;
if (cmd == NAND_CMD_NONE)
return;
if (ctrl & NAND_CLE)
offs = (1 << board->cle);
else if (ctrl & NAND_ALE)
offs = (1 << board->ale);
else
return;
if (nc->options & NAND_BUSWIDTH_16)
offs <<= 1;
writeb(cmd, nc->IO_ADDR_W + offs);
}
static void orion_nand_read_buf(struct mtd_info *mtd, uint8_t *buf, int len)
{
struct nand_chip *chip = mtd->priv;
void __iomem *io_base = chip->IO_ADDR_R;
uint64_t *buf64;
int i = 0;
while (len && (unsigned long)buf & 7) {
*buf++ = readb(io_base);
len--;
}
buf64 = (uint64_t *)buf;
while (i < len/8) {
/*
* Since GCC has no proper constraint (PR 43518)
* force x variable to r2/r3 registers as ldrd instruction
* requires first register to be even.
*/
register uint64_t x asm ("r2");
asm volatile ("ldrd\t%0, [%1]" : "=&r" (x) : "r" (io_base));
buf64[i++] = x;
}
i *= 8;
while (i < len)
buf[i++] = readb(io_base);
}
static int __init orion_nand_probe(struct platform_device *pdev)
{
struct mtd_info *mtd;
struct mtd_part_parser_data ppdata = {};
struct nand_chip *nc;
struct orion_nand_data *board;
struct resource *res;
struct clk *clk;
void __iomem *io_base;
int ret = 0;
u32 val = 0;
nc = kzalloc(sizeof(struct nand_chip) + sizeof(struct mtd_info), GFP_KERNEL);
if (!nc) {
printk(KERN_ERR "orion_nand: failed to allocate device structure.\n");
ret = -ENOMEM;
goto no_res;
}
mtd = (struct mtd_info *)(nc + 1);
res = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!res) {
ret = -ENODEV;
goto no_res;
}
io_base = ioremap(res->start, resource_size(res));
if (!io_base) {
printk(KERN_ERR "orion_nand: ioremap failed\n");
ret = -EIO;
goto no_res;
}
if (pdev->dev.of_node) {
board = devm_kzalloc(&pdev->dev, sizeof(struct orion_nand_data),
GFP_KERNEL);
if (!board) {
printk(KERN_ERR "orion_nand: failed to allocate board structure.\n");
ret = -ENOMEM;
goto no_res;
}
if (!of_property_read_u32(pdev->dev.of_node, "cle", &val))
board->cle = (u8)val;
else
board->cle = 0;
if (!of_property_read_u32(pdev->dev.of_node, "ale", &val))
board->ale = (u8)val;
else
board->ale = 1;
if (!of_property_read_u32(pdev->dev.of_node,
"bank-width", &val))
board->width = (u8)val * 8;
else
board->width = 8;
if (!of_property_read_u32(pdev->dev.of_node,
"chip-delay", &val))
board->chip_delay = (u8)val;
} else
board = pdev->dev.platform_data;
mtd->priv = nc;
mtd->owner = THIS_MODULE;
nc->priv = board;
nc->IO_ADDR_R = nc->IO_ADDR_W = io_base;
nc->cmd_ctrl = orion_nand_cmd_ctrl;
nc->read_buf = orion_nand_read_buf;
nc->ecc.mode = NAND_ECC_SOFT;
if (board->chip_delay)
nc->chip_delay = board->chip_delay;
WARN(board->width > 16,
"%d bit bus width out of range",
board->width);
if (board->width == 16)
nc->options |= NAND_BUSWIDTH_16;
if (board->dev_ready)
nc->dev_ready = board->dev_ready;
platform_set_drvdata(pdev, mtd);
/* Not all platforms can gate the clock, so it is not
an error if the clock does not exists. */
clk = clk_get(&pdev->dev, NULL);
if (!IS_ERR(clk)) {
clk_prepare_enable(clk);
clk_put(clk);
}
if (nand_scan(mtd, 1)) {
ret = -ENXIO;
goto no_dev;
}
mtd->name = "orion_nand";
ppdata.of_node = pdev->dev.of_node;
ret = mtd_device_parse_register(mtd, NULL, &ppdata,
board->parts, board->nr_parts);
if (ret) {
nand_release(mtd);
goto no_dev;
}
return 0;
no_dev:
if (!IS_ERR(clk)) {
clk_disable_unprepare(clk);
clk_put(clk);
}
platform_set_drvdata(pdev, NULL);
iounmap(io_base);
no_res:
kfree(nc);
return ret;
}
static int orion_nand_remove(struct platform_device *pdev)
{
struct mtd_info *mtd = platform_get_drvdata(pdev);
struct nand_chip *nc = mtd->priv;
struct clk *clk;
nand_release(mtd);
iounmap(nc->IO_ADDR_W);
kfree(nc);
clk = clk_get(&pdev->dev, NULL);
if (!IS_ERR(clk)) {
clk_disable_unprepare(clk);
clk_put(clk);
}
return 0;
}
#ifdef CONFIG_OF
static struct of_device_id orion_nand_of_match_table[] = {
{ .compatible = "marvell,orion-nand", },
{},
};
#endif
static struct platform_driver orion_nand_driver = {
.remove = orion_nand_remove,
.driver = {
.name = "orion_nand",
.owner = THIS_MODULE,
.of_match_table = of_match_ptr(orion_nand_of_match_table),
},
};
module_platform_driver_probe(orion_nand_driver, orion_nand_probe);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Tzachi Perelstein");
MODULE_DESCRIPTION("NAND glue for Orion platforms");
MODULE_ALIAS("platform:orion_nand");
|
gpl-3.0
|
hanx11/shadowsocks-android
|
src/main/jni/badvpn/examples/bprocess_example.c
|
369
|
4146
|
/**
* @file bprocess_example.c
* @author Ambroz Bizjak <ambrop7@gmail.com>
*
* @section LICENSE
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the author 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 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.
*/
#include <stddef.h>
#include <unistd.h>
#include <misc/debug.h>
#include <base/DebugObject.h>
#include <base/BLog.h>
#include <system/BReactor.h>
#include <system/BUnixSignal.h>
#include <system/BTime.h>
#include <system/BProcess.h>
BReactor reactor;
BUnixSignal unixsignal;
BProcessManager manager;
BProcess process;
static void unixsignal_handler (void *user, int signo);
static void process_handler (void *user, int normally, uint8_t normally_exit_status);
int main (int argc, char **argv)
{
if (argc <= 0) {
return 1;
}
int ret = 1;
if (argc < 2) {
printf("Usage: %s <program> [argument ...]\n", argv[0]);
goto fail0;
}
char *program = argv[1];
// init time
BTime_Init();
// init logger
BLog_InitStdout();
// init reactor (event loop)
if (!BReactor_Init(&reactor)) {
DEBUG("BReactor_Init failed");
goto fail1;
}
// choose signals to catch
sigset_t set;
sigemptyset(&set);
sigaddset(&set, SIGINT);
sigaddset(&set, SIGTERM);
// init BUnixSignal for catching signals
if (!BUnixSignal_Init(&unixsignal, &reactor, set, unixsignal_handler, NULL)) {
DEBUG("BUnixSignal_Init failed");
goto fail2;
}
// init process manager
if (!BProcessManager_Init(&manager, &reactor)) {
DEBUG("BProcessManager_Init failed");
goto fail3;
}
char **p_argv = argv + 1;
// map fds 0, 1, 2 in child to fds 0, 1, 2 in parent
int fds[] = { 0, 1, 2, -1 };
int fds_map[] = { 0, 1, 2 };
// start child process
if (!BProcess_InitWithFds(&process, &manager, process_handler, NULL, program, p_argv, NULL, fds, fds_map)) {
DEBUG("BProcess_Init failed");
goto fail4;
}
// enter event loop
ret = BReactor_Exec(&reactor);
BProcess_Free(&process);
fail4:
BProcessManager_Free(&manager);
fail3:
BUnixSignal_Free(&unixsignal, 0);
fail2:
BReactor_Free(&reactor);
fail1:
BLog_Free();
fail0:
DebugObjectGlobal_Finish();
return ret;
}
void unixsignal_handler (void *user, int signo)
{
DEBUG("received %s, terminating child", (signo == SIGINT ? "SIGINT" : "SIGTERM"));
// send SIGTERM to child
BProcess_Terminate(&process);
}
void process_handler (void *user, int normally, uint8_t normally_exit_status)
{
DEBUG("process terminated");
int ret = (normally ? normally_exit_status : 1);
// return from event loop
BReactor_Quit(&reactor, ret);
}
|
gpl-3.0
|
shlyakpavel/s720-w832-KK-kernel
|
kernel/drivers/hid/hid-lg3ff.c
|
1394
|
4512
|
/*
* Force feedback support for Logitech Flight System G940
*
* Copyright (c) 2009 Gary Stein <LordCnidarian@gmail.com>
*/
/*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/input.h>
#include <linux/usb.h>
#include <linux/hid.h>
#include "usbhid/usbhid.h"
#include "hid-lg.h"
/*
* G940 Theory of Operation (from experimentation)
*
* There are 63 fields (only 3 of them currently used)
* 0 - seems to be command field
* 1 - 30 deal with the x axis
* 31 -60 deal with the y axis
*
* Field 1 is x axis constant force
* Field 31 is y axis constant force
*
* other interesting fields 1,2,3,4 on x axis
* (same for 31,32,33,34 on y axis)
*
* 0 0 127 127 makes the joystick autocenter hard
*
* 127 0 127 127 makes the joystick loose on the right,
* but stops all movemnt left
*
* -127 0 -127 -127 makes the joystick loose on the left,
* but stops all movement right
*
* 0 0 -127 -127 makes the joystick rattle very hard
*
* I'm sure these are effects that I don't know enough about them
*/
struct lg3ff_device {
struct hid_report *report;
};
static int hid_lg3ff_play(struct input_dev *dev, void *data,
struct ff_effect *effect)
{
struct hid_device *hid = input_get_drvdata(dev);
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
int x, y;
/*
* Available values in the field should always be 63, but we only use up to
* 35. Instead, clear the entire area, however big it is.
*/
memset(report->field[0]->value, 0,
sizeof(__s32) * report->field[0]->report_count);
switch (effect->type) {
case FF_CONSTANT:
/*
* Already clamped in ff_memless
* 0 is center (different then other logitech)
*/
x = effect->u.ramp.start_level;
y = effect->u.ramp.end_level;
/* send command byte */
report->field[0]->value[0] = 0x51;
/*
* Sign backwards from other Force3d pro
* which get recast here in two's complement 8 bits
*/
report->field[0]->value[1] = (unsigned char)(-x);
report->field[0]->value[31] = (unsigned char)(-y);
usbhid_submit_report(hid, report, USB_DIR_OUT);
break;
}
return 0;
}
static void hid_lg3ff_set_autocenter(struct input_dev *dev, u16 magnitude)
{
struct hid_device *hid = input_get_drvdata(dev);
struct list_head *report_list = &hid->report_enum[HID_OUTPUT_REPORT].report_list;
struct hid_report *report = list_entry(report_list->next, struct hid_report, list);
/*
* Auto Centering probed from device
* NOTE: deadman's switch on G940 must be covered
* for effects to work
*/
report->field[0]->value[0] = 0x51;
report->field[0]->value[1] = 0x00;
report->field[0]->value[2] = 0x00;
report->field[0]->value[3] = 0x7F;
report->field[0]->value[4] = 0x7F;
report->field[0]->value[31] = 0x00;
report->field[0]->value[32] = 0x00;
report->field[0]->value[33] = 0x7F;
report->field[0]->value[34] = 0x7F;
usbhid_submit_report(hid, report, USB_DIR_OUT);
}
static const signed short ff3_joystick_ac[] = {
FF_CONSTANT,
FF_AUTOCENTER,
-1
};
int lg3ff_init(struct hid_device *hid)
{
struct hid_input *hidinput = list_entry(hid->inputs.next, struct hid_input, list);
struct input_dev *dev = hidinput->input;
const signed short *ff_bits = ff3_joystick_ac;
int error;
int i;
/* Check that the report looks ok */
if (!hid_validate_values(hid, HID_OUTPUT_REPORT, 0, 0, 35))
return -ENODEV;
/* Assume single fixed device G940 */
for (i = 0; ff_bits[i] >= 0; i++)
set_bit(ff_bits[i], dev->ffbit);
error = input_ff_create_memless(dev, NULL, hid_lg3ff_play);
if (error)
return error;
if (test_bit(FF_AUTOCENTER, dev->ffbit))
dev->ff->set_autocenter = hid_lg3ff_set_autocenter;
hid_info(hid, "Force feedback for Logitech Flight System G940 by Gary Stein <LordCnidarian@gmail.com>\n");
return 0;
}
|
gpl-3.0
|
r2t2sdr/r2t2
|
linux/trunk/linux-4.0-adi/drivers/cpufreq/omap-cpufreq.c
|
1140
|
5141
|
/*
* CPU frequency scaling for OMAP using OPP information
*
* Copyright (C) 2005 Nokia Corporation
* Written by Tony Lindgren <tony@atomide.com>
*
* Based on cpu-sa1110.c, Copyright (C) 2001 Russell King
*
* Copyright (C) 2007-2011 Texas Instruments, Inc.
* - OMAP3/4 support by Rajendra Nayak, Santosh Shilimkar
*
* 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/types.h>
#include <linux/kernel.h>
#include <linux/sched.h>
#include <linux/cpufreq.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/err.h>
#include <linux/clk.h>
#include <linux/io.h>
#include <linux/pm_opp.h>
#include <linux/cpu.h>
#include <linux/module.h>
#include <linux/platform_device.h>
#include <linux/regulator/consumer.h>
#include <asm/smp_plat.h>
#include <asm/cpu.h>
/* OPP tolerance in percentage */
#define OPP_TOLERANCE 4
static struct cpufreq_frequency_table *freq_table;
static atomic_t freq_table_users = ATOMIC_INIT(0);
static struct device *mpu_dev;
static struct regulator *mpu_reg;
static int omap_target(struct cpufreq_policy *policy, unsigned int index)
{
int r, ret;
struct dev_pm_opp *opp;
unsigned long freq, volt = 0, volt_old = 0, tol = 0;
unsigned int old_freq, new_freq;
old_freq = policy->cur;
new_freq = freq_table[index].frequency;
freq = new_freq * 1000;
ret = clk_round_rate(policy->clk, freq);
if (IS_ERR_VALUE(ret)) {
dev_warn(mpu_dev,
"CPUfreq: Cannot find matching frequency for %lu\n",
freq);
return ret;
}
freq = ret;
if (mpu_reg) {
rcu_read_lock();
opp = dev_pm_opp_find_freq_ceil(mpu_dev, &freq);
if (IS_ERR(opp)) {
rcu_read_unlock();
dev_err(mpu_dev, "%s: unable to find MPU OPP for %d\n",
__func__, new_freq);
return -EINVAL;
}
volt = dev_pm_opp_get_voltage(opp);
rcu_read_unlock();
tol = volt * OPP_TOLERANCE / 100;
volt_old = regulator_get_voltage(mpu_reg);
}
dev_dbg(mpu_dev, "cpufreq-omap: %u MHz, %ld mV --> %u MHz, %ld mV\n",
old_freq / 1000, volt_old ? volt_old / 1000 : -1,
new_freq / 1000, volt ? volt / 1000 : -1);
/* scaling up? scale voltage before frequency */
if (mpu_reg && (new_freq > old_freq)) {
r = regulator_set_voltage(mpu_reg, volt - tol, volt + tol);
if (r < 0) {
dev_warn(mpu_dev, "%s: unable to scale voltage up.\n",
__func__);
return r;
}
}
ret = clk_set_rate(policy->clk, new_freq * 1000);
/* scaling down? scale voltage after frequency */
if (mpu_reg && (new_freq < old_freq)) {
r = regulator_set_voltage(mpu_reg, volt - tol, volt + tol);
if (r < 0) {
dev_warn(mpu_dev, "%s: unable to scale voltage down.\n",
__func__);
clk_set_rate(policy->clk, old_freq * 1000);
return r;
}
}
return ret;
}
static inline void freq_table_free(void)
{
if (atomic_dec_and_test(&freq_table_users))
dev_pm_opp_free_cpufreq_table(mpu_dev, &freq_table);
}
static int omap_cpu_init(struct cpufreq_policy *policy)
{
int result;
policy->clk = clk_get(NULL, "cpufreq_ck");
if (IS_ERR(policy->clk))
return PTR_ERR(policy->clk);
if (!freq_table) {
result = dev_pm_opp_init_cpufreq_table(mpu_dev, &freq_table);
if (result) {
dev_err(mpu_dev,
"%s: cpu%d: failed creating freq table[%d]\n",
__func__, policy->cpu, result);
goto fail;
}
}
atomic_inc_return(&freq_table_users);
/* FIXME: what's the actual transition time? */
result = cpufreq_generic_init(policy, freq_table, 300 * 1000);
if (!result)
return 0;
freq_table_free();
fail:
clk_put(policy->clk);
return result;
}
static int omap_cpu_exit(struct cpufreq_policy *policy)
{
freq_table_free();
clk_put(policy->clk);
return 0;
}
static struct cpufreq_driver omap_driver = {
.flags = CPUFREQ_STICKY | CPUFREQ_NEED_INITIAL_FREQ_CHECK,
.verify = cpufreq_generic_frequency_table_verify,
.target_index = omap_target,
.get = cpufreq_generic_get,
.init = omap_cpu_init,
.exit = omap_cpu_exit,
.name = "omap",
.attr = cpufreq_generic_attr,
};
static int omap_cpufreq_probe(struct platform_device *pdev)
{
mpu_dev = get_cpu_device(0);
if (!mpu_dev) {
pr_warning("%s: unable to get the mpu device\n", __func__);
return -EINVAL;
}
mpu_reg = regulator_get(mpu_dev, "vcc");
if (IS_ERR(mpu_reg)) {
pr_warning("%s: unable to get MPU regulator\n", __func__);
mpu_reg = NULL;
} else {
/*
* Ensure physical regulator is present.
* (e.g. could be dummy regulator.)
*/
if (regulator_get_voltage(mpu_reg) < 0) {
pr_warn("%s: physical regulator not present for MPU\n",
__func__);
regulator_put(mpu_reg);
mpu_reg = NULL;
}
}
return cpufreq_register_driver(&omap_driver);
}
static int omap_cpufreq_remove(struct platform_device *pdev)
{
return cpufreq_unregister_driver(&omap_driver);
}
static struct platform_driver omap_cpufreq_platdrv = {
.driver = {
.name = "omap-cpufreq",
},
.probe = omap_cpufreq_probe,
.remove = omap_cpufreq_remove,
};
module_platform_driver(omap_cpufreq_platdrv);
MODULE_DESCRIPTION("cpufreq driver for OMAP SoCs");
MODULE_LICENSE("GPL");
|
gpl-3.0
|
zuoyanyouwu/shadowsocks-android
|
src/main/jni/badvpn/lwip/src/api/api_lib.c
|
382
|
24670
|
/**
* @file
* Sequential API External module
*
*/
/*
* Copyright (c) 2001-2004 Swedish Institute of Computer Science.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
* SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
* IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY
* OF SUCH DAMAGE.
*
* This file is part of the lwIP TCP/IP stack.
*
* Author: Adam Dunkels <adam@sics.se>
*
*/
/* This is the part of the API that is linked with
the application */
#include "lwip/opt.h"
#if LWIP_NETCONN /* don't build if not configured for use in lwipopts.h */
#include "lwip/api.h"
#include "lwip/tcpip.h"
#include "lwip/memp.h"
#include "lwip/ip.h"
#include "lwip/raw.h"
#include "lwip/udp.h"
#include "lwip/tcp.h"
#include <string.h>
/**
* Create a new netconn (of a specific type) that has a callback function.
* The corresponding pcb is also created.
*
* @param t the type of 'connection' to create (@see enum netconn_type)
* @param proto the IP protocol for RAW IP pcbs
* @param callback a function to call on status changes (RX available, TX'ed)
* @return a newly allocated struct netconn or
* NULL on memory error
*/
struct netconn*
netconn_new_with_proto_and_callback(enum netconn_type t, u8_t proto, netconn_callback callback)
{
struct netconn *conn;
struct api_msg msg;
conn = netconn_alloc(t, callback);
if (conn != NULL) {
err_t err;
msg.msg.msg.n.proto = proto;
msg.msg.conn = conn;
TCPIP_APIMSG((&msg), lwip_netconn_do_newconn, err);
if (err != ERR_OK) {
LWIP_ASSERT("freeing conn without freeing pcb", conn->pcb.tcp == NULL);
LWIP_ASSERT("conn has no op_completed", sys_sem_valid(&conn->op_completed));
LWIP_ASSERT("conn has no recvmbox", sys_mbox_valid(&conn->recvmbox));
#if LWIP_TCP
LWIP_ASSERT("conn->acceptmbox shouldn't exist", !sys_mbox_valid(&conn->acceptmbox));
#endif /* LWIP_TCP */
sys_sem_free(&conn->op_completed);
sys_mbox_free(&conn->recvmbox);
memp_free(MEMP_NETCONN, conn);
return NULL;
}
}
return conn;
}
/**
* Close a netconn 'connection' and free its resources.
* UDP and RAW connection are completely closed, TCP pcbs might still be in a waitstate
* after this returns.
*
* @param conn the netconn to delete
* @return ERR_OK if the connection was deleted
*/
err_t
netconn_delete(struct netconn *conn)
{
struct api_msg msg;
/* No ASSERT here because possible to get a (conn == NULL) if we got an accept error */
if (conn == NULL) {
return ERR_OK;
}
msg.function = lwip_netconn_do_delconn;
msg.msg.conn = conn;
tcpip_apimsg(&msg);
netconn_free(conn);
/* don't care for return value of lwip_netconn_do_delconn since it only calls void functions */
return ERR_OK;
}
/**
* Get the local or remote IP address and port of a netconn.
* For RAW netconns, this returns the protocol instead of a port!
*
* @param conn the netconn to query
* @param addr a pointer to which to save the IP address
* @param port a pointer to which to save the port (or protocol for RAW)
* @param local 1 to get the local IP address, 0 to get the remote one
* @return ERR_CONN for invalid connections
* ERR_OK if the information was retrieved
*/
err_t
netconn_getaddr(struct netconn *conn, ip_addr_t *addr, u16_t *port, u8_t local)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_getaddr: invalid conn", (conn != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_getaddr: invalid addr", (addr != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_getaddr: invalid port", (port != NULL), return ERR_ARG;);
msg.msg.conn = conn;
msg.msg.msg.ad.ipaddr = ip_2_ipX(addr);
msg.msg.msg.ad.port = port;
msg.msg.msg.ad.local = local;
TCPIP_APIMSG(&msg, lwip_netconn_do_getaddr, err);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Bind a netconn to a specific local IP address and port.
* Binding one netconn twice might not always be checked correctly!
*
* @param conn the netconn to bind
* @param addr the local IP address to bind the netconn to (use IP_ADDR_ANY
* to bind to all addresses)
* @param port the local port to bind the netconn to (not used for RAW)
* @return ERR_OK if bound, any other err_t on failure
*/
err_t
netconn_bind(struct netconn *conn, ip_addr_t *addr, u16_t port)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_bind: invalid conn", (conn != NULL), return ERR_ARG;);
msg.msg.conn = conn;
msg.msg.msg.bc.ipaddr = addr;
msg.msg.msg.bc.port = port;
TCPIP_APIMSG(&msg, lwip_netconn_do_bind, err);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Connect a netconn to a specific remote IP address and port.
*
* @param conn the netconn to connect
* @param addr the remote IP address to connect to
* @param port the remote port to connect to (no used for RAW)
* @return ERR_OK if connected, return value of tcp_/udp_/raw_connect otherwise
*/
err_t
netconn_connect(struct netconn *conn, ip_addr_t *addr, u16_t port)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_connect: invalid conn", (conn != NULL), return ERR_ARG;);
msg.msg.conn = conn;
msg.msg.msg.bc.ipaddr = addr;
msg.msg.msg.bc.port = port;
#if LWIP_TCP
#if (LWIP_UDP || LWIP_RAW)
if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP)
#endif /* (LWIP_UDP || LWIP_RAW) */
{
/* The TCP version waits for the connect to succeed,
so always needs to use message passing. */
msg.function = lwip_netconn_do_connect;
err = tcpip_apimsg(&msg);
}
#endif /* LWIP_TCP */
#if (LWIP_UDP || LWIP_RAW) && LWIP_TCP
else
#endif /* (LWIP_UDP || LWIP_RAW) && LWIP_TCP */
#if (LWIP_UDP || LWIP_RAW)
{
/* UDP and RAW only set flags, so we can use core-locking. */
TCPIP_APIMSG(&msg, lwip_netconn_do_connect, err);
}
#endif /* (LWIP_UDP || LWIP_RAW) */
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Disconnect a netconn from its current peer (only valid for UDP netconns).
*
* @param conn the netconn to disconnect
* @return TODO: return value is not set here...
*/
err_t
netconn_disconnect(struct netconn *conn)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_disconnect: invalid conn", (conn != NULL), return ERR_ARG;);
msg.msg.conn = conn;
TCPIP_APIMSG(&msg, lwip_netconn_do_disconnect, err);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Set a TCP netconn into listen mode
*
* @param conn the tcp netconn to set to listen mode
* @param backlog the listen backlog, only used if TCP_LISTEN_BACKLOG==1
* @return ERR_OK if the netconn was set to listen (UDP and RAW netconns
* don't return any error (yet?))
*/
err_t
netconn_listen_with_backlog(struct netconn *conn, u8_t backlog)
{
#if LWIP_TCP
struct api_msg msg;
err_t err;
/* This does no harm. If TCP_LISTEN_BACKLOG is off, backlog is unused. */
LWIP_UNUSED_ARG(backlog);
LWIP_ERROR("netconn_listen: invalid conn", (conn != NULL), return ERR_ARG;);
msg.msg.conn = conn;
#if TCP_LISTEN_BACKLOG
msg.msg.msg.lb.backlog = backlog;
#endif /* TCP_LISTEN_BACKLOG */
TCPIP_APIMSG(&msg, lwip_netconn_do_listen, err);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
#else /* LWIP_TCP */
LWIP_UNUSED_ARG(conn);
LWIP_UNUSED_ARG(backlog);
return ERR_ARG;
#endif /* LWIP_TCP */
}
/**
* Accept a new connection on a TCP listening netconn.
*
* @param conn the TCP listen netconn
* @param new_conn pointer where the new connection is stored
* @return ERR_OK if a new connection has been received or an error
* code otherwise
*/
err_t
netconn_accept(struct netconn *conn, struct netconn **new_conn)
{
#if LWIP_TCP
struct netconn *newconn;
err_t err;
#if TCP_LISTEN_BACKLOG
struct api_msg msg;
#endif /* TCP_LISTEN_BACKLOG */
LWIP_ERROR("netconn_accept: invalid pointer", (new_conn != NULL), return ERR_ARG;);
*new_conn = NULL;
LWIP_ERROR("netconn_accept: invalid conn", (conn != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_accept: invalid acceptmbox", sys_mbox_valid(&conn->acceptmbox), return ERR_ARG;);
err = conn->last_err;
if (ERR_IS_FATAL(err)) {
/* don't recv on fatal errors: this might block the application task
waiting on acceptmbox forever! */
return err;
}
#if LWIP_SO_RCVTIMEO
if (sys_arch_mbox_fetch(&conn->acceptmbox, (void **)&newconn, conn->recv_timeout) == SYS_ARCH_TIMEOUT) {
NETCONN_SET_SAFE_ERR(conn, ERR_TIMEOUT);
return ERR_TIMEOUT;
}
#else
sys_arch_mbox_fetch(&conn->acceptmbox, (void **)&newconn, 0);
#endif /* LWIP_SO_RCVTIMEO*/
/* Register event with callback */
API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0);
if (newconn == NULL) {
/* connection has been aborted */
NETCONN_SET_SAFE_ERR(conn, ERR_ABRT);
return ERR_ABRT;
}
#if TCP_LISTEN_BACKLOG
/* Let the stack know that we have accepted the connection. */
msg.msg.conn = conn;
/* don't care for the return value of lwip_netconn_do_recv */
TCPIP_APIMSG_NOERR(&msg, lwip_netconn_do_recv);
#endif /* TCP_LISTEN_BACKLOG */
*new_conn = newconn;
/* don't set conn->last_err: it's only ERR_OK, anyway */
return ERR_OK;
#else /* LWIP_TCP */
LWIP_UNUSED_ARG(conn);
LWIP_UNUSED_ARG(new_conn);
return ERR_ARG;
#endif /* LWIP_TCP */
}
/**
* Receive data: actual implementation that doesn't care whether pbuf or netbuf
* is received
*
* @param conn the netconn from which to receive data
* @param new_buf pointer where a new pbuf/netbuf is stored when received data
* @return ERR_OK if data has been received, an error code otherwise (timeout,
* memory error or another error)
*/
static err_t
netconn_recv_data(struct netconn *conn, void **new_buf)
{
void *buf = NULL;
u16_t len;
err_t err;
#if LWIP_TCP
struct api_msg msg;
#endif /* LWIP_TCP */
LWIP_ERROR("netconn_recv: invalid pointer", (new_buf != NULL), return ERR_ARG;);
*new_buf = NULL;
LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_accept: invalid recvmbox", sys_mbox_valid(&conn->recvmbox), return ERR_CONN;);
err = conn->last_err;
if (ERR_IS_FATAL(err)) {
/* don't recv on fatal errors: this might block the application task
waiting on recvmbox forever! */
/* @todo: this does not allow us to fetch data that has been put into recvmbox
before the fatal error occurred - is that a problem? */
return err;
}
#if LWIP_SO_RCVTIMEO
if (sys_arch_mbox_fetch(&conn->recvmbox, &buf, conn->recv_timeout) == SYS_ARCH_TIMEOUT) {
NETCONN_SET_SAFE_ERR(conn, ERR_TIMEOUT);
return ERR_TIMEOUT;
}
#else
sys_arch_mbox_fetch(&conn->recvmbox, &buf, 0);
#endif /* LWIP_SO_RCVTIMEO*/
#if LWIP_TCP
#if (LWIP_UDP || LWIP_RAW)
if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP)
#endif /* (LWIP_UDP || LWIP_RAW) */
{
if (!netconn_get_noautorecved(conn) || (buf == NULL)) {
/* Let the stack know that we have taken the data. */
/* TODO: Speedup: Don't block and wait for the answer here
(to prevent multiple thread-switches). */
msg.msg.conn = conn;
if (buf != NULL) {
msg.msg.msg.r.len = ((struct pbuf *)buf)->tot_len;
} else {
msg.msg.msg.r.len = 1;
}
/* don't care for the return value of lwip_netconn_do_recv */
TCPIP_APIMSG_NOERR(&msg, lwip_netconn_do_recv);
}
/* If we are closed, we indicate that we no longer wish to use the socket */
if (buf == NULL) {
API_EVENT(conn, NETCONN_EVT_RCVMINUS, 0);
/* Avoid to lose any previous error code */
NETCONN_SET_SAFE_ERR(conn, ERR_CLSD);
return ERR_CLSD;
}
len = ((struct pbuf *)buf)->tot_len;
}
#endif /* LWIP_TCP */
#if LWIP_TCP && (LWIP_UDP || LWIP_RAW)
else
#endif /* LWIP_TCP && (LWIP_UDP || LWIP_RAW) */
#if (LWIP_UDP || LWIP_RAW)
{
LWIP_ASSERT("buf != NULL", buf != NULL);
len = netbuf_len((struct netbuf *)buf);
}
#endif /* (LWIP_UDP || LWIP_RAW) */
#if LWIP_SO_RCVBUF
SYS_ARCH_DEC(conn->recv_avail, len);
#endif /* LWIP_SO_RCVBUF */
/* Register event with callback */
API_EVENT(conn, NETCONN_EVT_RCVMINUS, len);
LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_recv_data: received %p, len=%"U16_F"\n", buf, len));
*new_buf = buf;
/* don't set conn->last_err: it's only ERR_OK, anyway */
return ERR_OK;
}
/**
* Receive data (in form of a pbuf) from a TCP netconn
*
* @param conn the netconn from which to receive data
* @param new_buf pointer where a new pbuf is stored when received data
* @return ERR_OK if data has been received, an error code otherwise (timeout,
* memory error or another error)
* ERR_ARG if conn is not a TCP netconn
*/
err_t
netconn_recv_tcp_pbuf(struct netconn *conn, struct pbuf **new_buf)
{
LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL) &&
NETCONNTYPE_GROUP(netconn_type(conn)) == NETCONN_TCP, return ERR_ARG;);
return netconn_recv_data(conn, (void **)new_buf);
}
/**
* Receive data (in form of a netbuf containing a packet buffer) from a netconn
*
* @param conn the netconn from which to receive data
* @param new_buf pointer where a new netbuf is stored when received data
* @return ERR_OK if data has been received, an error code otherwise (timeout,
* memory error or another error)
*/
err_t
netconn_recv(struct netconn *conn, struct netbuf **new_buf)
{
#if LWIP_TCP
struct netbuf *buf = NULL;
err_t err;
#endif /* LWIP_TCP */
LWIP_ERROR("netconn_recv: invalid pointer", (new_buf != NULL), return ERR_ARG;);
*new_buf = NULL;
LWIP_ERROR("netconn_recv: invalid conn", (conn != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_accept: invalid recvmbox", sys_mbox_valid(&conn->recvmbox), return ERR_CONN;);
#if LWIP_TCP
#if (LWIP_UDP || LWIP_RAW)
if (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP)
#endif /* (LWIP_UDP || LWIP_RAW) */
{
struct pbuf *p = NULL;
/* This is not a listening netconn, since recvmbox is set */
buf = (struct netbuf *)memp_malloc(MEMP_NETBUF);
if (buf == NULL) {
NETCONN_SET_SAFE_ERR(conn, ERR_MEM);
return ERR_MEM;
}
err = netconn_recv_data(conn, (void **)&p);
if (err != ERR_OK) {
memp_free(MEMP_NETBUF, buf);
return err;
}
LWIP_ASSERT("p != NULL", p != NULL);
buf->p = p;
buf->ptr = p;
buf->port = 0;
ipX_addr_set_any(LWIP_IPV6, &buf->addr);
*new_buf = buf;
/* don't set conn->last_err: it's only ERR_OK, anyway */
return ERR_OK;
}
#endif /* LWIP_TCP */
#if LWIP_TCP && (LWIP_UDP || LWIP_RAW)
else
#endif /* LWIP_TCP && (LWIP_UDP || LWIP_RAW) */
{
#if (LWIP_UDP || LWIP_RAW)
return netconn_recv_data(conn, (void **)new_buf);
#endif /* (LWIP_UDP || LWIP_RAW) */
}
}
/**
* TCP: update the receive window: by calling this, the application
* tells the stack that it has processed data and is able to accept
* new data.
* ATTENTION: use with care, this is mainly used for sockets!
* Can only be used when calling netconn_set_noautorecved(conn, 1) before.
*
* @param conn the netconn for which to update the receive window
* @param length amount of data processed (ATTENTION: this must be accurate!)
*/
void
netconn_recved(struct netconn *conn, u32_t length)
{
#if LWIP_TCP
if ((conn != NULL) && (NETCONNTYPE_GROUP(conn->type) == NETCONN_TCP) &&
(netconn_get_noautorecved(conn))) {
struct api_msg msg;
/* Let the stack know that we have taken the data. */
/* TODO: Speedup: Don't block and wait for the answer here
(to prevent multiple thread-switches). */
msg.msg.conn = conn;
msg.msg.msg.r.len = length;
/* don't care for the return value of lwip_netconn_do_recv */
TCPIP_APIMSG_NOERR(&msg, lwip_netconn_do_recv);
}
#else /* LWIP_TCP */
LWIP_UNUSED_ARG(conn);
LWIP_UNUSED_ARG(length);
#endif /* LWIP_TCP */
}
/**
* Send data (in form of a netbuf) to a specific remote IP address and port.
* Only to be used for UDP and RAW netconns (not TCP).
*
* @param conn the netconn over which to send data
* @param buf a netbuf containing the data to send
* @param addr the remote IP address to which to send the data
* @param port the remote port to which to send the data
* @return ERR_OK if data was sent, any other err_t on error
*/
err_t
netconn_sendto(struct netconn *conn, struct netbuf *buf, ip_addr_t *addr, u16_t port)
{
if (buf != NULL) {
ipX_addr_set_ipaddr(PCB_ISIPV6(conn->pcb.ip), &buf->addr, addr);
buf->port = port;
return netconn_send(conn, buf);
}
return ERR_VAL;
}
/**
* Send data over a UDP or RAW netconn (that is already connected).
*
* @param conn the UDP or RAW netconn over which to send data
* @param buf a netbuf containing the data to send
* @return ERR_OK if data was sent, any other err_t on error
*/
err_t
netconn_send(struct netconn *conn, struct netbuf *buf)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_send: invalid conn", (conn != NULL), return ERR_ARG;);
LWIP_DEBUGF(API_LIB_DEBUG, ("netconn_send: sending %"U16_F" bytes\n", buf->p->tot_len));
msg.msg.conn = conn;
msg.msg.msg.b = buf;
TCPIP_APIMSG(&msg, lwip_netconn_do_send, err);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Send data over a TCP netconn.
*
* @param conn the TCP netconn over which to send data
* @param dataptr pointer to the application buffer that contains the data to send
* @param size size of the application data to send
* @param apiflags combination of following flags :
* - NETCONN_COPY: data will be copied into memory belonging to the stack
* - NETCONN_MORE: for TCP connection, PSH flag will be set on last segment sent
* - NETCONN_DONTBLOCK: only write the data if all dat can be written at once
* @param bytes_written pointer to a location that receives the number of written bytes
* @return ERR_OK if data was sent, any other err_t on error
*/
err_t
netconn_write_partly(struct netconn *conn, const void *dataptr, size_t size,
u8_t apiflags, size_t *bytes_written)
{
struct api_msg msg;
err_t err;
u8_t dontblock;
LWIP_ERROR("netconn_write: invalid conn", (conn != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_write: invalid conn->type", (NETCONNTYPE_GROUP(conn->type)== NETCONN_TCP), return ERR_VAL;);
if (size == 0) {
return ERR_OK;
}
dontblock = netconn_is_nonblocking(conn) || (apiflags & NETCONN_DONTBLOCK);
if (dontblock && !bytes_written) {
/* This implies netconn_write() cannot be used for non-blocking send, since
it has no way to return the number of bytes written. */
return ERR_VAL;
}
/* non-blocking write sends as much */
msg.msg.conn = conn;
msg.msg.msg.w.dataptr = dataptr;
msg.msg.msg.w.apiflags = apiflags;
msg.msg.msg.w.len = size;
#if LWIP_SO_SNDTIMEO
if (conn->send_timeout != 0) {
/* get the time we started, which is later compared to
sys_now() + conn->send_timeout */
msg.msg.msg.w.time_started = sys_now();
} else {
msg.msg.msg.w.time_started = 0;
}
#endif /* LWIP_SO_SNDTIMEO */
/* For locking the core: this _can_ be delayed on low memory/low send buffer,
but if it is, this is done inside api_msg.c:do_write(), so we can use the
non-blocking version here. */
TCPIP_APIMSG(&msg, lwip_netconn_do_write, err);
if ((err == ERR_OK) && (bytes_written != NULL)) {
if (dontblock
#if LWIP_SO_SNDTIMEO
|| (conn->send_timeout != 0)
#endif /* LWIP_SO_SNDTIMEO */
) {
/* nonblocking write: maybe the data has been sent partly */
*bytes_written = msg.msg.msg.w.len;
} else {
/* blocking call succeeded: all data has been sent if it */
*bytes_written = size;
}
}
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Close ot shutdown a TCP netconn (doesn't delete it).
*
* @param conn the TCP netconn to close or shutdown
* @param how fully close or only shutdown one side?
* @return ERR_OK if the netconn was closed, any other err_t on error
*/
static err_t
netconn_close_shutdown(struct netconn *conn, u8_t how)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_close: invalid conn", (conn != NULL), return ERR_ARG;);
msg.function = lwip_netconn_do_close;
msg.msg.conn = conn;
/* shutting down both ends is the same as closing */
msg.msg.msg.sd.shut = how;
/* because of the LWIP_TCPIP_CORE_LOCKING implementation of lwip_netconn_do_close,
don't use TCPIP_APIMSG here */
err = tcpip_apimsg(&msg);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
/**
* Close a TCP netconn (doesn't delete it).
*
* @param conn the TCP netconn to close
* @return ERR_OK if the netconn was closed, any other err_t on error
*/
err_t
netconn_close(struct netconn *conn)
{
/* shutting down both ends is the same as closing */
return netconn_close_shutdown(conn, NETCONN_SHUT_RDWR);
}
/**
* Shut down one or both sides of a TCP netconn (doesn't delete it).
*
* @param conn the TCP netconn to shut down
* @return ERR_OK if the netconn was closed, any other err_t on error
*/
err_t
netconn_shutdown(struct netconn *conn, u8_t shut_rx, u8_t shut_tx)
{
return netconn_close_shutdown(conn, (shut_rx ? NETCONN_SHUT_RD : 0) | (shut_tx ? NETCONN_SHUT_WR : 0));
}
#if LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD)
/**
* Join multicast groups for UDP netconns.
*
* @param conn the UDP netconn for which to change multicast addresses
* @param multiaddr IP address of the multicast group to join or leave
* @param netif_addr the IP address of the network interface on which to send
* the igmp message
* @param join_or_leave flag whether to send a join- or leave-message
* @return ERR_OK if the action was taken, any err_t on error
*/
err_t
netconn_join_leave_group(struct netconn *conn,
ip_addr_t *multiaddr,
ip_addr_t *netif_addr,
enum netconn_igmp join_or_leave)
{
struct api_msg msg;
err_t err;
LWIP_ERROR("netconn_join_leave_group: invalid conn", (conn != NULL), return ERR_ARG;);
msg.msg.conn = conn;
msg.msg.msg.jl.multiaddr = ip_2_ipX(multiaddr);
msg.msg.msg.jl.netif_addr = ip_2_ipX(netif_addr);
msg.msg.msg.jl.join_or_leave = join_or_leave;
TCPIP_APIMSG(&msg, lwip_netconn_do_join_leave_group, err);
NETCONN_SET_SAFE_ERR(conn, err);
return err;
}
#endif /* LWIP_IGMP || (LWIP_IPV6 && LWIP_IPV6_MLD) */
#if LWIP_DNS
/**
* Execute a DNS query, only one IP address is returned
*
* @param name a string representation of the DNS host name to query
* @param addr a preallocated ip_addr_t where to store the resolved IP address
* @return ERR_OK: resolving succeeded
* ERR_MEM: memory error, try again later
* ERR_ARG: dns client not initialized or invalid hostname
* ERR_VAL: dns server response was invalid
*/
err_t
netconn_gethostbyname(const char *name, ip_addr_t *addr)
{
struct dns_api_msg msg;
err_t err;
sys_sem_t sem;
LWIP_ERROR("netconn_gethostbyname: invalid name", (name != NULL), return ERR_ARG;);
LWIP_ERROR("netconn_gethostbyname: invalid addr", (addr != NULL), return ERR_ARG;);
err = sys_sem_new(&sem, 0);
if (err != ERR_OK) {
return err;
}
msg.name = name;
msg.addr = addr;
msg.err = &err;
msg.sem = &sem;
tcpip_callback(lwip_netconn_do_gethostbyname, &msg);
sys_sem_wait(&sem);
sys_sem_free(&sem);
return err;
}
#endif /* LWIP_DNS*/
#endif /* LWIP_NETCONN */
|
gpl-3.0
|
venj/shadowsocks-android
|
src/main/jni/openssl/crypto/bio/bss_dgram.c
|
388
|
46315
|
/* crypto/bio/bio_dgram.c */
/*
* DTLS implementation written by Nagendra Modadugu
* (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
*/
/* ====================================================================
* Copyright (c) 1999-2005 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.OpenSSL.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@OpenSSL.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.OpenSSL.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include <stdio.h>
#include <errno.h>
#define USE_SOCKETS
#include "cryptlib.h"
#include <openssl/bio.h>
#ifndef OPENSSL_NO_DGRAM
#if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VMS)
#include <sys/timeb.h>
#endif
#ifndef OPENSSL_NO_SCTP
#include <netinet/sctp.h>
#include <fcntl.h>
#define OPENSSL_SCTP_DATA_CHUNK_TYPE 0x00
#define OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE 0xc0
#endif
#ifdef OPENSSL_SYS_LINUX
#define IP_MTU 14 /* linux is lame */
#endif
#ifdef WATT32
#define sock_write SockWrite /* Watt-32 uses same names */
#define sock_read SockRead
#define sock_puts SockPuts
#endif
static int dgram_write(BIO *h, const char *buf, int num);
static int dgram_read(BIO *h, char *buf, int size);
static int dgram_puts(BIO *h, const char *str);
static long dgram_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int dgram_new(BIO *h);
static int dgram_free(BIO *data);
static int dgram_clear(BIO *bio);
#ifndef OPENSSL_NO_SCTP
static int dgram_sctp_write(BIO *h, const char *buf, int num);
static int dgram_sctp_read(BIO *h, char *buf, int size);
static int dgram_sctp_puts(BIO *h, const char *str);
static long dgram_sctp_ctrl(BIO *h, int cmd, long arg1, void *arg2);
static int dgram_sctp_new(BIO *h);
static int dgram_sctp_free(BIO *data);
#ifdef SCTP_AUTHENTICATION_EVENT
static void dgram_sctp_handle_auth_free_key_event(BIO *b, union sctp_notification *snp);
#endif
#endif
static int BIO_dgram_should_retry(int s);
static void get_current_time(struct timeval *t);
static BIO_METHOD methods_dgramp=
{
BIO_TYPE_DGRAM,
"datagram socket",
dgram_write,
dgram_read,
dgram_puts,
NULL, /* dgram_gets, */
dgram_ctrl,
dgram_new,
dgram_free,
NULL,
};
#ifndef OPENSSL_NO_SCTP
static BIO_METHOD methods_dgramp_sctp=
{
BIO_TYPE_DGRAM_SCTP,
"datagram sctp socket",
dgram_sctp_write,
dgram_sctp_read,
dgram_sctp_puts,
NULL, /* dgram_gets, */
dgram_sctp_ctrl,
dgram_sctp_new,
dgram_sctp_free,
NULL,
};
#endif
typedef struct bio_dgram_data_st
{
union {
struct sockaddr sa;
struct sockaddr_in sa_in;
#if OPENSSL_USE_IPV6
struct sockaddr_in6 sa_in6;
#endif
} peer;
unsigned int connected;
unsigned int _errno;
unsigned int mtu;
struct timeval next_timeout;
struct timeval socket_timeout;
} bio_dgram_data;
#ifndef OPENSSL_NO_SCTP
typedef struct bio_dgram_sctp_save_message_st
{
BIO *bio;
char *data;
int length;
} bio_dgram_sctp_save_message;
typedef struct bio_dgram_sctp_data_st
{
union {
struct sockaddr sa;
struct sockaddr_in sa_in;
#if OPENSSL_USE_IPV6
struct sockaddr_in6 sa_in6;
#endif
} peer;
unsigned int connected;
unsigned int _errno;
unsigned int mtu;
struct bio_dgram_sctp_sndinfo sndinfo;
struct bio_dgram_sctp_rcvinfo rcvinfo;
struct bio_dgram_sctp_prinfo prinfo;
void (*handle_notifications)(BIO *bio, void *context, void *buf);
void* notification_context;
int in_handshake;
int ccs_rcvd;
int ccs_sent;
int save_shutdown;
int peer_auth_tested;
bio_dgram_sctp_save_message saved_message;
} bio_dgram_sctp_data;
#endif
BIO_METHOD *BIO_s_datagram(void)
{
return(&methods_dgramp);
}
BIO *BIO_new_dgram(int fd, int close_flag)
{
BIO *ret;
ret=BIO_new(BIO_s_datagram());
if (ret == NULL) return(NULL);
BIO_set_fd(ret,fd,close_flag);
return(ret);
}
static int dgram_new(BIO *bi)
{
bio_dgram_data *data = NULL;
bi->init=0;
bi->num=0;
data = OPENSSL_malloc(sizeof(bio_dgram_data));
if (data == NULL)
return 0;
memset(data, 0x00, sizeof(bio_dgram_data));
bi->ptr = data;
bi->flags=0;
return(1);
}
static int dgram_free(BIO *a)
{
bio_dgram_data *data;
if (a == NULL) return(0);
if ( ! dgram_clear(a))
return 0;
data = (bio_dgram_data *)a->ptr;
if(data != NULL) OPENSSL_free(data);
return(1);
}
static int dgram_clear(BIO *a)
{
if (a == NULL) return(0);
if (a->shutdown)
{
if (a->init)
{
SHUTDOWN2(a->num);
}
a->init=0;
a->flags=0;
}
return(1);
}
static void dgram_adjust_rcv_timeout(BIO *b)
{
#if defined(SO_RCVTIMEO)
bio_dgram_data *data = (bio_dgram_data *)b->ptr;
int sz = sizeof(int);
/* Is a timer active? */
if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0)
{
struct timeval timenow, timeleft;
/* Read current socket timeout */
#ifdef OPENSSL_SYS_WINDOWS
int timeout;
if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
(void*)&timeout, &sz) < 0)
{ perror("getsockopt"); }
else
{
data->socket_timeout.tv_sec = timeout / 1000;
data->socket_timeout.tv_usec = (timeout % 1000) * 1000;
}
#else
if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
&(data->socket_timeout), (void *)&sz) < 0)
{ perror("getsockopt"); }
#endif
/* Get current time */
get_current_time(&timenow);
/* Calculate time left until timer expires */
memcpy(&timeleft, &(data->next_timeout), sizeof(struct timeval));
timeleft.tv_sec -= timenow.tv_sec;
timeleft.tv_usec -= timenow.tv_usec;
if (timeleft.tv_usec < 0)
{
timeleft.tv_sec--;
timeleft.tv_usec += 1000000;
}
if (timeleft.tv_sec < 0)
{
timeleft.tv_sec = 0;
timeleft.tv_usec = 1;
}
/* Adjust socket timeout if next handhake message timer
* will expire earlier.
*/
if ((data->socket_timeout.tv_sec == 0 && data->socket_timeout.tv_usec == 0) ||
(data->socket_timeout.tv_sec > timeleft.tv_sec) ||
(data->socket_timeout.tv_sec == timeleft.tv_sec &&
data->socket_timeout.tv_usec >= timeleft.tv_usec))
{
#ifdef OPENSSL_SYS_WINDOWS
timeout = timeleft.tv_sec * 1000 + timeleft.tv_usec / 1000;
if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
(void*)&timeout, sizeof(timeout)) < 0)
{ perror("setsockopt"); }
#else
if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &timeleft,
sizeof(struct timeval)) < 0)
{ perror("setsockopt"); }
#endif
}
}
#endif
}
static void dgram_reset_rcv_timeout(BIO *b)
{
#if defined(SO_RCVTIMEO)
bio_dgram_data *data = (bio_dgram_data *)b->ptr;
/* Is a timer active? */
if (data->next_timeout.tv_sec > 0 || data->next_timeout.tv_usec > 0)
{
#ifdef OPENSSL_SYS_WINDOWS
int timeout = data->socket_timeout.tv_sec * 1000 +
data->socket_timeout.tv_usec / 1000;
if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
(void*)&timeout, sizeof(timeout)) < 0)
{ perror("setsockopt"); }
#else
if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, &(data->socket_timeout),
sizeof(struct timeval)) < 0)
{ perror("setsockopt"); }
#endif
}
#endif
}
static int dgram_read(BIO *b, char *out, int outl)
{
int ret=0;
bio_dgram_data *data = (bio_dgram_data *)b->ptr;
struct {
/*
* See commentary in b_sock.c. <appro>
*/
union { size_t s; int i; } len;
union {
struct sockaddr sa;
struct sockaddr_in sa_in;
#if OPENSSL_USE_IPV6
struct sockaddr_in6 sa_in6;
#endif
} peer;
} sa;
sa.len.s=0;
sa.len.i=sizeof(sa.peer);
if (out != NULL)
{
clear_socket_error();
memset(&sa.peer, 0x00, sizeof(sa.peer));
dgram_adjust_rcv_timeout(b);
ret=recvfrom(b->num,out,outl,0,&sa.peer.sa,(void *)&sa.len);
if (sizeof(sa.len.i)!=sizeof(sa.len.s) && sa.len.i==0)
{
OPENSSL_assert(sa.len.s<=sizeof(sa.peer));
sa.len.i = (int)sa.len.s;
}
if ( ! data->connected && ret >= 0)
BIO_ctrl(b, BIO_CTRL_DGRAM_SET_PEER, 0, &sa.peer);
BIO_clear_retry_flags(b);
if (ret < 0)
{
if (BIO_dgram_should_retry(ret))
{
BIO_set_retry_read(b);
data->_errno = get_last_socket_error();
}
}
dgram_reset_rcv_timeout(b);
}
return(ret);
}
static int dgram_write(BIO *b, const char *in, int inl)
{
int ret;
bio_dgram_data *data = (bio_dgram_data *)b->ptr;
clear_socket_error();
if ( data->connected )
ret=writesocket(b->num,in,inl);
else
{
int peerlen = sizeof(data->peer);
if (data->peer.sa.sa_family == AF_INET)
peerlen = sizeof(data->peer.sa_in);
#if OPENSSL_USE_IPV6
else if (data->peer.sa.sa_family == AF_INET6)
peerlen = sizeof(data->peer.sa_in6);
#endif
#if defined(NETWARE_CLIB) && defined(NETWARE_BSDSOCK)
ret=sendto(b->num, (char *)in, inl, 0, &data->peer.sa, peerlen);
#else
ret=sendto(b->num, in, inl, 0, &data->peer.sa, peerlen);
#endif
}
BIO_clear_retry_flags(b);
if (ret <= 0)
{
if (BIO_dgram_should_retry(ret))
{
BIO_set_retry_write(b);
data->_errno = get_last_socket_error();
#if 0 /* higher layers are responsible for querying MTU, if necessary */
if ( data->_errno == EMSGSIZE)
/* retrieve the new MTU */
BIO_ctrl(b, BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
#endif
}
}
return(ret);
}
static long dgram_ctrl(BIO *b, int cmd, long num, void *ptr)
{
long ret=1;
int *ip;
struct sockaddr *to = NULL;
bio_dgram_data *data = NULL;
#if defined(IP_MTU_DISCOVER) || defined(IP_MTU)
long sockopt_val = 0;
unsigned int sockopt_len = 0;
#endif
#ifdef OPENSSL_SYS_LINUX
socklen_t addr_len;
union {
struct sockaddr sa;
struct sockaddr_in s4;
#if OPENSSL_USE_IPV6
struct sockaddr_in6 s6;
#endif
} addr;
#endif
data = (bio_dgram_data *)b->ptr;
switch (cmd)
{
case BIO_CTRL_RESET:
num=0;
case BIO_C_FILE_SEEK:
ret=0;
break;
case BIO_C_FILE_TELL:
case BIO_CTRL_INFO:
ret=0;
break;
case BIO_C_SET_FD:
dgram_clear(b);
b->num= *((int *)ptr);
b->shutdown=(int)num;
b->init=1;
break;
case BIO_C_GET_FD:
if (b->init)
{
ip=(int *)ptr;
if (ip != NULL) *ip=b->num;
ret=b->num;
}
else
ret= -1;
break;
case BIO_CTRL_GET_CLOSE:
ret=b->shutdown;
break;
case BIO_CTRL_SET_CLOSE:
b->shutdown=(int)num;
break;
case BIO_CTRL_PENDING:
case BIO_CTRL_WPENDING:
ret=0;
break;
case BIO_CTRL_DUP:
case BIO_CTRL_FLUSH:
ret=1;
break;
case BIO_CTRL_DGRAM_CONNECT:
to = (struct sockaddr *)ptr;
#if 0
if (connect(b->num, to, sizeof(struct sockaddr)) < 0)
{ perror("connect"); ret = 0; }
else
{
#endif
switch (to->sa_family)
{
case AF_INET:
memcpy(&data->peer,to,sizeof(data->peer.sa_in));
break;
#if OPENSSL_USE_IPV6
case AF_INET6:
memcpy(&data->peer,to,sizeof(data->peer.sa_in6));
break;
#endif
default:
memcpy(&data->peer,to,sizeof(data->peer.sa));
break;
}
#if 0
}
#endif
break;
/* (Linux)kernel sets DF bit on outgoing IP packets */
case BIO_CTRL_DGRAM_MTU_DISCOVER:
#ifdef OPENSSL_SYS_LINUX
addr_len = (socklen_t)sizeof(addr);
memset((void *)&addr, 0, sizeof(addr));
if (getsockname(b->num, &addr.sa, &addr_len) < 0)
{
ret = 0;
break;
}
sockopt_len = sizeof(sockopt_val);
switch (addr.sa.sa_family)
{
case AF_INET:
sockopt_val = IP_PMTUDISC_DO;
if ((ret = setsockopt(b->num, IPPROTO_IP, IP_MTU_DISCOVER,
&sockopt_val, sizeof(sockopt_val))) < 0)
perror("setsockopt");
break;
#if OPENSSL_USE_IPV6 && defined(IPV6_MTU_DISCOVER)
case AF_INET6:
sockopt_val = IPV6_PMTUDISC_DO;
if ((ret = setsockopt(b->num, IPPROTO_IPV6, IPV6_MTU_DISCOVER,
&sockopt_val, sizeof(sockopt_val))) < 0)
perror("setsockopt");
break;
#endif
default:
ret = -1;
break;
}
ret = -1;
#else
break;
#endif
case BIO_CTRL_DGRAM_QUERY_MTU:
#ifdef OPENSSL_SYS_LINUX
addr_len = (socklen_t)sizeof(addr);
memset((void *)&addr, 0, sizeof(addr));
if (getsockname(b->num, &addr.sa, &addr_len) < 0)
{
ret = 0;
break;
}
sockopt_len = sizeof(sockopt_val);
switch (addr.sa.sa_family)
{
case AF_INET:
if ((ret = getsockopt(b->num, IPPROTO_IP, IP_MTU, (void *)&sockopt_val,
&sockopt_len)) < 0 || sockopt_val < 0)
{
ret = 0;
}
else
{
/* we assume that the transport protocol is UDP and no
* IP options are used.
*/
data->mtu = sockopt_val - 8 - 20;
ret = data->mtu;
}
break;
#if OPENSSL_USE_IPV6 && defined(IPV6_MTU)
case AF_INET6:
if ((ret = getsockopt(b->num, IPPROTO_IPV6, IPV6_MTU, (void *)&sockopt_val,
&sockopt_len)) < 0 || sockopt_val < 0)
{
ret = 0;
}
else
{
/* we assume that the transport protocol is UDP and no
* IPV6 options are used.
*/
data->mtu = sockopt_val - 8 - 40;
ret = data->mtu;
}
break;
#endif
default:
ret = 0;
break;
}
#else
ret = 0;
#endif
break;
case BIO_CTRL_DGRAM_GET_FALLBACK_MTU:
switch (data->peer.sa.sa_family)
{
case AF_INET:
ret = 576 - 20 - 8;
break;
#if OPENSSL_USE_IPV6
case AF_INET6:
#ifdef IN6_IS_ADDR_V4MAPPED
if (IN6_IS_ADDR_V4MAPPED(&data->peer.sa_in6.sin6_addr))
ret = 576 - 20 - 8;
else
#endif
ret = 1280 - 40 - 8;
break;
#endif
default:
ret = 576 - 20 - 8;
break;
}
break;
case BIO_CTRL_DGRAM_GET_MTU:
return data->mtu;
break;
case BIO_CTRL_DGRAM_SET_MTU:
data->mtu = num;
ret = num;
break;
case BIO_CTRL_DGRAM_SET_CONNECTED:
to = (struct sockaddr *)ptr;
if ( to != NULL)
{
data->connected = 1;
switch (to->sa_family)
{
case AF_INET:
memcpy(&data->peer,to,sizeof(data->peer.sa_in));
break;
#if OPENSSL_USE_IPV6
case AF_INET6:
memcpy(&data->peer,to,sizeof(data->peer.sa_in6));
break;
#endif
default:
memcpy(&data->peer,to,sizeof(data->peer.sa));
break;
}
}
else
{
data->connected = 0;
memset(&(data->peer), 0x00, sizeof(data->peer));
}
break;
case BIO_CTRL_DGRAM_GET_PEER:
switch (data->peer.sa.sa_family)
{
case AF_INET:
ret=sizeof(data->peer.sa_in);
break;
#if OPENSSL_USE_IPV6
case AF_INET6:
ret=sizeof(data->peer.sa_in6);
break;
#endif
default:
ret=sizeof(data->peer.sa);
break;
}
if (num==0 || num>ret)
num=ret;
memcpy(ptr,&data->peer,(ret=num));
break;
case BIO_CTRL_DGRAM_SET_PEER:
to = (struct sockaddr *) ptr;
switch (to->sa_family)
{
case AF_INET:
memcpy(&data->peer,to,sizeof(data->peer.sa_in));
break;
#if OPENSSL_USE_IPV6
case AF_INET6:
memcpy(&data->peer,to,sizeof(data->peer.sa_in6));
break;
#endif
default:
memcpy(&data->peer,to,sizeof(data->peer.sa));
break;
}
break;
case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
memcpy(&(data->next_timeout), ptr, sizeof(struct timeval));
break;
#if defined(SO_RCVTIMEO)
case BIO_CTRL_DGRAM_SET_RECV_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
{
struct timeval *tv = (struct timeval *)ptr;
int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
if (setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
(void*)&timeout, sizeof(timeout)) < 0)
{ perror("setsockopt"); ret = -1; }
}
#else
if ( setsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO, ptr,
sizeof(struct timeval)) < 0)
{ perror("setsockopt"); ret = -1; }
#endif
break;
case BIO_CTRL_DGRAM_GET_RECV_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
{
int timeout, sz = sizeof(timeout);
struct timeval *tv = (struct timeval *)ptr;
if (getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
(void*)&timeout, &sz) < 0)
{ perror("getsockopt"); ret = -1; }
else
{
tv->tv_sec = timeout / 1000;
tv->tv_usec = (timeout % 1000) * 1000;
ret = sizeof(*tv);
}
}
#else
if ( getsockopt(b->num, SOL_SOCKET, SO_RCVTIMEO,
ptr, (void *)&ret) < 0)
{ perror("getsockopt"); ret = -1; }
#endif
break;
#endif
#if defined(SO_SNDTIMEO)
case BIO_CTRL_DGRAM_SET_SEND_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
{
struct timeval *tv = (struct timeval *)ptr;
int timeout = tv->tv_sec * 1000 + tv->tv_usec/1000;
if (setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
(void*)&timeout, sizeof(timeout)) < 0)
{ perror("setsockopt"); ret = -1; }
}
#else
if ( setsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO, ptr,
sizeof(struct timeval)) < 0)
{ perror("setsockopt"); ret = -1; }
#endif
break;
case BIO_CTRL_DGRAM_GET_SEND_TIMEOUT:
#ifdef OPENSSL_SYS_WINDOWS
{
int timeout, sz = sizeof(timeout);
struct timeval *tv = (struct timeval *)ptr;
if (getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
(void*)&timeout, &sz) < 0)
{ perror("getsockopt"); ret = -1; }
else
{
tv->tv_sec = timeout / 1000;
tv->tv_usec = (timeout % 1000) * 1000;
ret = sizeof(*tv);
}
}
#else
if ( getsockopt(b->num, SOL_SOCKET, SO_SNDTIMEO,
ptr, (void *)&ret) < 0)
{ perror("getsockopt"); ret = -1; }
#endif
break;
#endif
case BIO_CTRL_DGRAM_GET_SEND_TIMER_EXP:
/* fall-through */
case BIO_CTRL_DGRAM_GET_RECV_TIMER_EXP:
#ifdef OPENSSL_SYS_WINDOWS
if ( data->_errno == WSAETIMEDOUT)
#else
if ( data->_errno == EAGAIN)
#endif
{
ret = 1;
data->_errno = 0;
}
else
ret = 0;
break;
#ifdef EMSGSIZE
case BIO_CTRL_DGRAM_MTU_EXCEEDED:
if ( data->_errno == EMSGSIZE)
{
ret = 1;
data->_errno = 0;
}
else
ret = 0;
break;
#endif
default:
ret=0;
break;
}
return(ret);
}
static int dgram_puts(BIO *bp, const char *str)
{
int n,ret;
n=strlen(str);
ret=dgram_write(bp,str,n);
return(ret);
}
#ifndef OPENSSL_NO_SCTP
BIO_METHOD *BIO_s_datagram_sctp(void)
{
return(&methods_dgramp_sctp);
}
BIO *BIO_new_dgram_sctp(int fd, int close_flag)
{
BIO *bio;
int ret, optval = 20000;
int auth_data = 0, auth_forward = 0;
unsigned char *p;
struct sctp_authchunk auth;
struct sctp_authchunks *authchunks;
socklen_t sockopt_len;
#ifdef SCTP_AUTHENTICATION_EVENT
#ifdef SCTP_EVENT
struct sctp_event event;
#else
struct sctp_event_subscribe event;
#endif
#endif
bio=BIO_new(BIO_s_datagram_sctp());
if (bio == NULL) return(NULL);
BIO_set_fd(bio,fd,close_flag);
/* Activate SCTP-AUTH for DATA and FORWARD-TSN chunks */
auth.sauth_chunk = OPENSSL_SCTP_DATA_CHUNK_TYPE;
ret = setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth, sizeof(struct sctp_authchunk));
OPENSSL_assert(ret >= 0);
auth.sauth_chunk = OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE;
ret = setsockopt(fd, IPPROTO_SCTP, SCTP_AUTH_CHUNK, &auth, sizeof(struct sctp_authchunk));
OPENSSL_assert(ret >= 0);
/* Test if activation was successful. When using accept(),
* SCTP-AUTH has to be activated for the listening socket
* already, otherwise the connected socket won't use it. */
sockopt_len = (socklen_t)(sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
authchunks = OPENSSL_malloc(sockopt_len);
memset(authchunks, 0, sizeof(sockopt_len));
ret = getsockopt(fd, IPPROTO_SCTP, SCTP_LOCAL_AUTH_CHUNKS, authchunks, &sockopt_len);
OPENSSL_assert(ret >= 0);
for (p = (unsigned char*) authchunks + sizeof(sctp_assoc_t);
p < (unsigned char*) authchunks + sockopt_len;
p += sizeof(uint8_t))
{
if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE) auth_data = 1;
if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE) auth_forward = 1;
}
OPENSSL_free(authchunks);
OPENSSL_assert(auth_data);
OPENSSL_assert(auth_forward);
#ifdef SCTP_AUTHENTICATION_EVENT
#ifdef SCTP_EVENT
memset(&event, 0, sizeof(struct sctp_event));
event.se_assoc_id = 0;
event.se_type = SCTP_AUTHENTICATION_EVENT;
event.se_on = 1;
ret = setsockopt(fd, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
OPENSSL_assert(ret >= 0);
#else
sockopt_len = (socklen_t) sizeof(struct sctp_event_subscribe);
ret = getsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, &sockopt_len);
OPENSSL_assert(ret >= 0);
event.sctp_authentication_event = 1;
ret = setsockopt(fd, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
OPENSSL_assert(ret >= 0);
#endif
#endif
/* Disable partial delivery by setting the min size
* larger than the max record size of 2^14 + 2048 + 13
*/
ret = setsockopt(fd, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT, &optval, sizeof(optval));
OPENSSL_assert(ret >= 0);
return(bio);
}
int BIO_dgram_is_sctp(BIO *bio)
{
return (BIO_method_type(bio) == BIO_TYPE_DGRAM_SCTP);
}
static int dgram_sctp_new(BIO *bi)
{
bio_dgram_sctp_data *data = NULL;
bi->init=0;
bi->num=0;
data = OPENSSL_malloc(sizeof(bio_dgram_sctp_data));
if (data == NULL)
return 0;
memset(data, 0x00, sizeof(bio_dgram_sctp_data));
#ifdef SCTP_PR_SCTP_NONE
data->prinfo.pr_policy = SCTP_PR_SCTP_NONE;
#endif
bi->ptr = data;
bi->flags=0;
return(1);
}
static int dgram_sctp_free(BIO *a)
{
bio_dgram_sctp_data *data;
if (a == NULL) return(0);
if ( ! dgram_clear(a))
return 0;
data = (bio_dgram_sctp_data *)a->ptr;
if(data != NULL) OPENSSL_free(data);
return(1);
}
#ifdef SCTP_AUTHENTICATION_EVENT
void dgram_sctp_handle_auth_free_key_event(BIO *b, union sctp_notification *snp)
{
unsigned int sockopt_len = 0;
int ret;
struct sctp_authkey_event* authkeyevent = &snp->sn_auth_event;
if (authkeyevent->auth_indication == SCTP_AUTH_FREE_KEY)
{
struct sctp_authkeyid authkeyid;
/* delete key */
authkeyid.scact_keynumber = authkeyevent->auth_keynumber;
sockopt_len = sizeof(struct sctp_authkeyid);
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
&authkeyid, sockopt_len);
}
}
#endif
static int dgram_sctp_read(BIO *b, char *out, int outl)
{
int ret = 0, n = 0, i, optval;
socklen_t optlen;
bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
union sctp_notification *snp;
struct msghdr msg;
struct iovec iov;
struct cmsghdr *cmsg;
char cmsgbuf[512];
if (out != NULL)
{
clear_socket_error();
do
{
memset(&data->rcvinfo, 0x00, sizeof(struct bio_dgram_sctp_rcvinfo));
iov.iov_base = out;
iov.iov_len = outl;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = cmsgbuf;
msg.msg_controllen = 512;
msg.msg_flags = 0;
n = recvmsg(b->num, &msg, 0);
if (msg.msg_controllen > 0)
{
for (cmsg = CMSG_FIRSTHDR(&msg); cmsg; cmsg = CMSG_NXTHDR(&msg, cmsg))
{
if (cmsg->cmsg_level != IPPROTO_SCTP)
continue;
#ifdef SCTP_RCVINFO
if (cmsg->cmsg_type == SCTP_RCVINFO)
{
struct sctp_rcvinfo *rcvinfo;
rcvinfo = (struct sctp_rcvinfo *)CMSG_DATA(cmsg);
data->rcvinfo.rcv_sid = rcvinfo->rcv_sid;
data->rcvinfo.rcv_ssn = rcvinfo->rcv_ssn;
data->rcvinfo.rcv_flags = rcvinfo->rcv_flags;
data->rcvinfo.rcv_ppid = rcvinfo->rcv_ppid;
data->rcvinfo.rcv_tsn = rcvinfo->rcv_tsn;
data->rcvinfo.rcv_cumtsn = rcvinfo->rcv_cumtsn;
data->rcvinfo.rcv_context = rcvinfo->rcv_context;
}
#endif
#ifdef SCTP_SNDRCV
if (cmsg->cmsg_type == SCTP_SNDRCV)
{
struct sctp_sndrcvinfo *sndrcvinfo;
sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
data->rcvinfo.rcv_sid = sndrcvinfo->sinfo_stream;
data->rcvinfo.rcv_ssn = sndrcvinfo->sinfo_ssn;
data->rcvinfo.rcv_flags = sndrcvinfo->sinfo_flags;
data->rcvinfo.rcv_ppid = sndrcvinfo->sinfo_ppid;
data->rcvinfo.rcv_tsn = sndrcvinfo->sinfo_tsn;
data->rcvinfo.rcv_cumtsn = sndrcvinfo->sinfo_cumtsn;
data->rcvinfo.rcv_context = sndrcvinfo->sinfo_context;
}
#endif
}
}
if (n <= 0)
{
if (n < 0)
ret = n;
break;
}
if (msg.msg_flags & MSG_NOTIFICATION)
{
snp = (union sctp_notification*) out;
if (snp->sn_header.sn_type == SCTP_SENDER_DRY_EVENT)
{
#ifdef SCTP_EVENT
struct sctp_event event;
#else
struct sctp_event_subscribe event;
socklen_t eventsize;
#endif
/* If a message has been delayed until the socket
* is dry, it can be sent now.
*/
if (data->saved_message.length > 0)
{
dgram_sctp_write(data->saved_message.bio, data->saved_message.data,
data->saved_message.length);
OPENSSL_free(data->saved_message.data);
data->saved_message.length = 0;
}
/* disable sender dry event */
#ifdef SCTP_EVENT
memset(&event, 0, sizeof(struct sctp_event));
event.se_assoc_id = 0;
event.se_type = SCTP_SENDER_DRY_EVENT;
event.se_on = 0;
i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
OPENSSL_assert(i >= 0);
#else
eventsize = sizeof(struct sctp_event_subscribe);
i = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
OPENSSL_assert(i >= 0);
event.sctp_sender_dry_event = 0;
i = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
OPENSSL_assert(i >= 0);
#endif
}
#ifdef SCTP_AUTHENTICATION_EVENT
if (snp->sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
dgram_sctp_handle_auth_free_key_event(b, snp);
#endif
if (data->handle_notifications != NULL)
data->handle_notifications(b, data->notification_context, (void*) out);
memset(out, 0, outl);
}
else
ret += n;
}
while ((msg.msg_flags & MSG_NOTIFICATION) && (msg.msg_flags & MSG_EOR) && (ret < outl));
if (ret > 0 && !(msg.msg_flags & MSG_EOR))
{
/* Partial message read, this should never happen! */
/* The buffer was too small, this means the peer sent
* a message that was larger than allowed. */
if (ret == outl)
return -1;
/* Test if socket buffer can handle max record
* size (2^14 + 2048 + 13)
*/
optlen = (socklen_t) sizeof(int);
ret = getsockopt(b->num, SOL_SOCKET, SO_RCVBUF, &optval, &optlen);
OPENSSL_assert(ret >= 0);
OPENSSL_assert(optval >= 18445);
/* Test if SCTP doesn't partially deliver below
* max record size (2^14 + 2048 + 13)
*/
optlen = (socklen_t) sizeof(int);
ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_PARTIAL_DELIVERY_POINT,
&optval, &optlen);
OPENSSL_assert(ret >= 0);
OPENSSL_assert(optval >= 18445);
/* Partially delivered notification??? Probably a bug.... */
OPENSSL_assert(!(msg.msg_flags & MSG_NOTIFICATION));
/* Everything seems ok till now, so it's most likely
* a message dropped by PR-SCTP.
*/
memset(out, 0, outl);
BIO_set_retry_read(b);
return -1;
}
BIO_clear_retry_flags(b);
if (ret < 0)
{
if (BIO_dgram_should_retry(ret))
{
BIO_set_retry_read(b);
data->_errno = get_last_socket_error();
}
}
/* Test if peer uses SCTP-AUTH before continuing */
if (!data->peer_auth_tested)
{
int ii, auth_data = 0, auth_forward = 0;
unsigned char *p;
struct sctp_authchunks *authchunks;
optlen = (socklen_t)(sizeof(sctp_assoc_t) + 256 * sizeof(uint8_t));
authchunks = OPENSSL_malloc(optlen);
memset(authchunks, 0, sizeof(optlen));
ii = getsockopt(b->num, IPPROTO_SCTP, SCTP_PEER_AUTH_CHUNKS, authchunks, &optlen);
OPENSSL_assert(ii >= 0);
for (p = (unsigned char*) authchunks + sizeof(sctp_assoc_t);
p < (unsigned char*) authchunks + optlen;
p += sizeof(uint8_t))
{
if (*p == OPENSSL_SCTP_DATA_CHUNK_TYPE) auth_data = 1;
if (*p == OPENSSL_SCTP_FORWARD_CUM_TSN_CHUNK_TYPE) auth_forward = 1;
}
OPENSSL_free(authchunks);
if (!auth_data || !auth_forward)
{
BIOerr(BIO_F_DGRAM_SCTP_READ,BIO_R_CONNECT_ERROR);
return -1;
}
data->peer_auth_tested = 1;
}
}
return(ret);
}
static int dgram_sctp_write(BIO *b, const char *in, int inl)
{
int ret;
bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
struct bio_dgram_sctp_sndinfo *sinfo = &(data->sndinfo);
struct bio_dgram_sctp_prinfo *pinfo = &(data->prinfo);
struct bio_dgram_sctp_sndinfo handshake_sinfo;
struct iovec iov[1];
struct msghdr msg;
struct cmsghdr *cmsg;
#if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo)) + CMSG_SPACE(sizeof(struct sctp_prinfo))];
struct sctp_sndinfo *sndinfo;
struct sctp_prinfo *prinfo;
#else
char cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndrcvinfo))];
struct sctp_sndrcvinfo *sndrcvinfo;
#endif
clear_socket_error();
/* If we're send anything else than application data,
* disable all user parameters and flags.
*/
if (in[0] != 23) {
memset(&handshake_sinfo, 0x00, sizeof(struct bio_dgram_sctp_sndinfo));
#ifdef SCTP_SACK_IMMEDIATELY
handshake_sinfo.snd_flags = SCTP_SACK_IMMEDIATELY;
#endif
sinfo = &handshake_sinfo;
}
/* If we have to send a shutdown alert message and the
* socket is not dry yet, we have to save it and send it
* as soon as the socket gets dry.
*/
if (data->save_shutdown && !BIO_dgram_sctp_wait_for_dry(b))
{
data->saved_message.bio = b;
data->saved_message.length = inl;
data->saved_message.data = OPENSSL_malloc(inl);
memcpy(data->saved_message.data, in, inl);
return inl;
}
iov[0].iov_base = (char *)in;
iov[0].iov_len = inl;
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = iov;
msg.msg_iovlen = 1;
msg.msg_control = (caddr_t)cmsgbuf;
msg.msg_controllen = 0;
msg.msg_flags = 0;
#if defined(SCTP_SNDINFO) && defined(SCTP_PRINFO)
cmsg = (struct cmsghdr *)cmsgbuf;
cmsg->cmsg_level = IPPROTO_SCTP;
cmsg->cmsg_type = SCTP_SNDINFO;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndinfo));
sndinfo = (struct sctp_sndinfo *)CMSG_DATA(cmsg);
memset(sndinfo, 0, sizeof(struct sctp_sndinfo));
sndinfo->snd_sid = sinfo->snd_sid;
sndinfo->snd_flags = sinfo->snd_flags;
sndinfo->snd_ppid = sinfo->snd_ppid;
sndinfo->snd_context = sinfo->snd_context;
msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndinfo));
cmsg = (struct cmsghdr *)&cmsgbuf[CMSG_SPACE(sizeof(struct sctp_sndinfo))];
cmsg->cmsg_level = IPPROTO_SCTP;
cmsg->cmsg_type = SCTP_PRINFO;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_prinfo));
prinfo = (struct sctp_prinfo *)CMSG_DATA(cmsg);
memset(prinfo, 0, sizeof(struct sctp_prinfo));
prinfo->pr_policy = pinfo->pr_policy;
prinfo->pr_value = pinfo->pr_value;
msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_prinfo));
#else
cmsg = (struct cmsghdr *)cmsgbuf;
cmsg->cmsg_level = IPPROTO_SCTP;
cmsg->cmsg_type = SCTP_SNDRCV;
cmsg->cmsg_len = CMSG_LEN(sizeof(struct sctp_sndrcvinfo));
sndrcvinfo = (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
memset(sndrcvinfo, 0, sizeof(struct sctp_sndrcvinfo));
sndrcvinfo->sinfo_stream = sinfo->snd_sid;
sndrcvinfo->sinfo_flags = sinfo->snd_flags;
#ifdef __FreeBSD__
sndrcvinfo->sinfo_flags |= pinfo->pr_policy;
#endif
sndrcvinfo->sinfo_ppid = sinfo->snd_ppid;
sndrcvinfo->sinfo_context = sinfo->snd_context;
sndrcvinfo->sinfo_timetolive = pinfo->pr_value;
msg.msg_controllen += CMSG_SPACE(sizeof(struct sctp_sndrcvinfo));
#endif
ret = sendmsg(b->num, &msg, 0);
BIO_clear_retry_flags(b);
if (ret <= 0)
{
if (BIO_dgram_should_retry(ret))
{
BIO_set_retry_write(b);
data->_errno = get_last_socket_error();
}
}
return(ret);
}
static long dgram_sctp_ctrl(BIO *b, int cmd, long num, void *ptr)
{
long ret=1;
bio_dgram_sctp_data *data = NULL;
unsigned int sockopt_len = 0;
struct sctp_authkeyid authkeyid;
struct sctp_authkey *authkey;
data = (bio_dgram_sctp_data *)b->ptr;
switch (cmd)
{
case BIO_CTRL_DGRAM_QUERY_MTU:
/* Set to maximum (2^14)
* and ignore user input to enable transport
* protocol fragmentation.
* Returns always 2^14.
*/
data->mtu = 16384;
ret = data->mtu;
break;
case BIO_CTRL_DGRAM_SET_MTU:
/* Set to maximum (2^14)
* and ignore input to enable transport
* protocol fragmentation.
* Returns always 2^14.
*/
data->mtu = 16384;
ret = data->mtu;
break;
case BIO_CTRL_DGRAM_SET_CONNECTED:
case BIO_CTRL_DGRAM_CONNECT:
/* Returns always -1. */
ret = -1;
break;
case BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT:
/* SCTP doesn't need the DTLS timer
* Returns always 1.
*/
break;
case BIO_CTRL_DGRAM_SCTP_SET_IN_HANDSHAKE:
if (num > 0)
data->in_handshake = 1;
else
data->in_handshake = 0;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_NODELAY, &data->in_handshake, sizeof(int));
break;
case BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY:
/* New shared key for SCTP AUTH.
* Returns 0 on success, -1 otherwise.
*/
/* Get active key */
sockopt_len = sizeof(struct sctp_authkeyid);
ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid, &sockopt_len);
if (ret < 0) break;
/* Add new key */
sockopt_len = sizeof(struct sctp_authkey) + 64 * sizeof(uint8_t);
authkey = OPENSSL_malloc(sockopt_len);
memset(authkey, 0x00, sockopt_len);
authkey->sca_keynumber = authkeyid.scact_keynumber + 1;
#ifndef __FreeBSD__
/* This field is missing in FreeBSD 8.2 and earlier,
* and FreeBSD 8.3 and higher work without it.
*/
authkey->sca_keylength = 64;
#endif
memcpy(&authkey->sca_key[0], ptr, 64 * sizeof(uint8_t));
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_KEY, authkey, sockopt_len);
if (ret < 0) break;
/* Reset active key */
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
&authkeyid, sizeof(struct sctp_authkeyid));
if (ret < 0) break;
break;
case BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY:
/* Returns 0 on success, -1 otherwise. */
/* Get active key */
sockopt_len = sizeof(struct sctp_authkeyid);
ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid, &sockopt_len);
if (ret < 0) break;
/* Set active key */
authkeyid.scact_keynumber = authkeyid.scact_keynumber + 1;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY,
&authkeyid, sizeof(struct sctp_authkeyid));
if (ret < 0) break;
/* CCS has been sent, so remember that and fall through
* to check if we need to deactivate an old key
*/
data->ccs_sent = 1;
case BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD:
/* Returns 0 on success, -1 otherwise. */
/* Has this command really been called or is this just a fall-through? */
if (cmd == BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD)
data->ccs_rcvd = 1;
/* CSS has been both, received and sent, so deactivate an old key */
if (data->ccs_rcvd == 1 && data->ccs_sent == 1)
{
/* Get active key */
sockopt_len = sizeof(struct sctp_authkeyid);
ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_ACTIVE_KEY, &authkeyid, &sockopt_len);
if (ret < 0) break;
/* Deactivate key or delete second last key if
* SCTP_AUTHENTICATION_EVENT is not available.
*/
authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
#ifdef SCTP_AUTH_DEACTIVATE_KEY
sockopt_len = sizeof(struct sctp_authkeyid);
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DEACTIVATE_KEY,
&authkeyid, sockopt_len);
if (ret < 0) break;
#endif
#ifndef SCTP_AUTHENTICATION_EVENT
if (authkeyid.scact_keynumber > 0)
{
authkeyid.scact_keynumber = authkeyid.scact_keynumber - 1;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_AUTH_DELETE_KEY,
&authkeyid, sizeof(struct sctp_authkeyid));
if (ret < 0) break;
}
#endif
data->ccs_rcvd = 0;
data->ccs_sent = 0;
}
break;
case BIO_CTRL_DGRAM_SCTP_GET_SNDINFO:
/* Returns the size of the copied struct. */
if (num > (long) sizeof(struct bio_dgram_sctp_sndinfo))
num = sizeof(struct bio_dgram_sctp_sndinfo);
memcpy(ptr, &(data->sndinfo), num);
ret = num;
break;
case BIO_CTRL_DGRAM_SCTP_SET_SNDINFO:
/* Returns the size of the copied struct. */
if (num > (long) sizeof(struct bio_dgram_sctp_sndinfo))
num = sizeof(struct bio_dgram_sctp_sndinfo);
memcpy(&(data->sndinfo), ptr, num);
break;
case BIO_CTRL_DGRAM_SCTP_GET_RCVINFO:
/* Returns the size of the copied struct. */
if (num > (long) sizeof(struct bio_dgram_sctp_rcvinfo))
num = sizeof(struct bio_dgram_sctp_rcvinfo);
memcpy(ptr, &data->rcvinfo, num);
ret = num;
break;
case BIO_CTRL_DGRAM_SCTP_SET_RCVINFO:
/* Returns the size of the copied struct. */
if (num > (long) sizeof(struct bio_dgram_sctp_rcvinfo))
num = sizeof(struct bio_dgram_sctp_rcvinfo);
memcpy(&(data->rcvinfo), ptr, num);
break;
case BIO_CTRL_DGRAM_SCTP_GET_PRINFO:
/* Returns the size of the copied struct. */
if (num > (long) sizeof(struct bio_dgram_sctp_prinfo))
num = sizeof(struct bio_dgram_sctp_prinfo);
memcpy(ptr, &(data->prinfo), num);
ret = num;
break;
case BIO_CTRL_DGRAM_SCTP_SET_PRINFO:
/* Returns the size of the copied struct. */
if (num > (long) sizeof(struct bio_dgram_sctp_prinfo))
num = sizeof(struct bio_dgram_sctp_prinfo);
memcpy(&(data->prinfo), ptr, num);
break;
case BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN:
/* Returns always 1. */
if (num > 0)
data->save_shutdown = 1;
else
data->save_shutdown = 0;
break;
default:
/* Pass to default ctrl function to
* process SCTP unspecific commands
*/
ret=dgram_ctrl(b, cmd, num, ptr);
break;
}
return(ret);
}
int BIO_dgram_sctp_notification_cb(BIO *b,
void (*handle_notifications)(BIO *bio, void *context, void *buf),
void *context)
{
bio_dgram_sctp_data *data = (bio_dgram_sctp_data *) b->ptr;
if (handle_notifications != NULL)
{
data->handle_notifications = handle_notifications;
data->notification_context = context;
}
else
return -1;
return 0;
}
int BIO_dgram_sctp_wait_for_dry(BIO *b)
{
int is_dry = 0;
int n, sockflags, ret;
union sctp_notification snp;
struct msghdr msg;
struct iovec iov;
#ifdef SCTP_EVENT
struct sctp_event event;
#else
struct sctp_event_subscribe event;
socklen_t eventsize;
#endif
bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
/* set sender dry event */
#ifdef SCTP_EVENT
memset(&event, 0, sizeof(struct sctp_event));
event.se_assoc_id = 0;
event.se_type = SCTP_SENDER_DRY_EVENT;
event.se_on = 1;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
#else
eventsize = sizeof(struct sctp_event_subscribe);
ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
if (ret < 0)
return -1;
event.sctp_sender_dry_event = 1;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
#endif
if (ret < 0)
return -1;
/* peek for notification */
memset(&snp, 0x00, sizeof(union sctp_notification));
iov.iov_base = (char *)&snp;
iov.iov_len = sizeof(union sctp_notification);
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
n = recvmsg(b->num, &msg, MSG_PEEK);
if (n <= 0)
{
if ((n < 0) && (get_last_socket_error() != EAGAIN) && (get_last_socket_error() != EWOULDBLOCK))
return -1;
else
return 0;
}
/* if we find a notification, process it and try again if necessary */
while (msg.msg_flags & MSG_NOTIFICATION)
{
memset(&snp, 0x00, sizeof(union sctp_notification));
iov.iov_base = (char *)&snp;
iov.iov_len = sizeof(union sctp_notification);
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
n = recvmsg(b->num, &msg, 0);
if (n <= 0)
{
if ((n < 0) && (get_last_socket_error() != EAGAIN) && (get_last_socket_error() != EWOULDBLOCK))
return -1;
else
return is_dry;
}
if (snp.sn_header.sn_type == SCTP_SENDER_DRY_EVENT)
{
is_dry = 1;
/* disable sender dry event */
#ifdef SCTP_EVENT
memset(&event, 0, sizeof(struct sctp_event));
event.se_assoc_id = 0;
event.se_type = SCTP_SENDER_DRY_EVENT;
event.se_on = 0;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENT, &event, sizeof(struct sctp_event));
#else
eventsize = (socklen_t) sizeof(struct sctp_event_subscribe);
ret = getsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, &eventsize);
if (ret < 0)
return -1;
event.sctp_sender_dry_event = 0;
ret = setsockopt(b->num, IPPROTO_SCTP, SCTP_EVENTS, &event, sizeof(struct sctp_event_subscribe));
#endif
if (ret < 0)
return -1;
}
#ifdef SCTP_AUTHENTICATION_EVENT
if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
dgram_sctp_handle_auth_free_key_event(b, &snp);
#endif
if (data->handle_notifications != NULL)
data->handle_notifications(b, data->notification_context, (void*) &snp);
/* found notification, peek again */
memset(&snp, 0x00, sizeof(union sctp_notification));
iov.iov_base = (char *)&snp;
iov.iov_len = sizeof(union sctp_notification);
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
/* if we have seen the dry already, don't wait */
if (is_dry)
{
sockflags = fcntl(b->num, F_GETFL, 0);
fcntl(b->num, F_SETFL, O_NONBLOCK);
}
n = recvmsg(b->num, &msg, MSG_PEEK);
if (is_dry)
{
fcntl(b->num, F_SETFL, sockflags);
}
if (n <= 0)
{
if ((n < 0) && (get_last_socket_error() != EAGAIN) && (get_last_socket_error() != EWOULDBLOCK))
return -1;
else
return is_dry;
}
}
/* read anything else */
return is_dry;
}
int BIO_dgram_sctp_msg_waiting(BIO *b)
{
int n, sockflags;
union sctp_notification snp;
struct msghdr msg;
struct iovec iov;
bio_dgram_sctp_data *data = (bio_dgram_sctp_data *)b->ptr;
/* Check if there are any messages waiting to be read */
do
{
memset(&snp, 0x00, sizeof(union sctp_notification));
iov.iov_base = (char *)&snp;
iov.iov_len = sizeof(union sctp_notification);
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
sockflags = fcntl(b->num, F_GETFL, 0);
fcntl(b->num, F_SETFL, O_NONBLOCK);
n = recvmsg(b->num, &msg, MSG_PEEK);
fcntl(b->num, F_SETFL, sockflags);
/* if notification, process and try again */
if (n > 0 && (msg.msg_flags & MSG_NOTIFICATION))
{
#ifdef SCTP_AUTHENTICATION_EVENT
if (snp.sn_header.sn_type == SCTP_AUTHENTICATION_EVENT)
dgram_sctp_handle_auth_free_key_event(b, &snp);
#endif
memset(&snp, 0x00, sizeof(union sctp_notification));
iov.iov_base = (char *)&snp;
iov.iov_len = sizeof(union sctp_notification);
msg.msg_name = NULL;
msg.msg_namelen = 0;
msg.msg_iov = &iov;
msg.msg_iovlen = 1;
msg.msg_control = NULL;
msg.msg_controllen = 0;
msg.msg_flags = 0;
n = recvmsg(b->num, &msg, 0);
if (data->handle_notifications != NULL)
data->handle_notifications(b, data->notification_context, (void*) &snp);
}
} while (n > 0 && (msg.msg_flags & MSG_NOTIFICATION));
/* Return 1 if there is a message to be read, return 0 otherwise. */
if (n > 0)
return 1;
else
return 0;
}
static int dgram_sctp_puts(BIO *bp, const char *str)
{
int n,ret;
n=strlen(str);
ret=dgram_sctp_write(bp,str,n);
return(ret);
}
#endif
static int BIO_dgram_should_retry(int i)
{
int err;
if ((i == 0) || (i == -1))
{
err=get_last_socket_error();
#if defined(OPENSSL_SYS_WINDOWS)
/* If the socket return value (i) is -1
* and err is unexpectedly 0 at this point,
* the error code was overwritten by
* another system call before this error
* handling is called.
*/
#endif
return(BIO_dgram_non_fatal_error(err));
}
return(0);
}
int BIO_dgram_non_fatal_error(int err)
{
switch (err)
{
#if defined(OPENSSL_SYS_WINDOWS)
# if defined(WSAEWOULDBLOCK)
case WSAEWOULDBLOCK:
# endif
# if 0 /* This appears to always be an error */
# if defined(WSAENOTCONN)
case WSAENOTCONN:
# endif
# endif
#endif
#ifdef EWOULDBLOCK
# ifdef WSAEWOULDBLOCK
# if WSAEWOULDBLOCK != EWOULDBLOCK
case EWOULDBLOCK:
# endif
# else
case EWOULDBLOCK:
# endif
#endif
#ifdef EINTR
case EINTR:
#endif
#ifdef EAGAIN
#if EWOULDBLOCK != EAGAIN
case EAGAIN:
# endif
#endif
#ifdef EPROTO
case EPROTO:
#endif
#ifdef EINPROGRESS
case EINPROGRESS:
#endif
#ifdef EALREADY
case EALREADY:
#endif
return(1);
/* break; */
default:
break;
}
return(0);
}
static void get_current_time(struct timeval *t)
{
#ifdef OPENSSL_SYS_WIN32
struct _timeb tb;
_ftime(&tb);
t->tv_sec = (long)tb.time;
t->tv_usec = (long)tb.millitm * 1000;
#elif defined(OPENSSL_SYS_VMS)
struct timeb tb;
ftime(&tb);
t->tv_sec = (long)tb.time;
t->tv_usec = (long)tb.millitm * 1000;
#else
gettimeofday(t, NULL);
#endif
}
#endif
|
gpl-3.0
|
fffonion/shadowsocks-libev
|
libsodium/src/libsodium/crypto_onetimeauth/poly1305/onetimeauth_poly1305.c
|
399
|
1719
|
#include "crypto_onetimeauth_poly1305.h"
#include "donna/poly1305_donna.h"
/* LCOV_EXCL_START */
static const crypto_onetimeauth_poly1305_implementation *implementation =
&crypto_onetimeauth_poly1305_donna_implementation;
int
crypto_onetimeauth_poly1305_set_implementation(crypto_onetimeauth_poly1305_implementation *impl)
{
implementation = impl;
return 0;
}
const char *
crypto_onetimeauth_poly1305_implementation_name(void)
{
return implementation->implementation_name();
}
/* LCOV_EXCL_STOP */
int
crypto_onetimeauth_poly1305(unsigned char *out, const unsigned char *in,
unsigned long long inlen, const unsigned char *k)
{
return implementation->onetimeauth(out, in, inlen, k);
}
int
crypto_onetimeauth_poly1305_verify(const unsigned char *h,
const unsigned char *in,
unsigned long long inlen,
const unsigned char *k)
{
return implementation->onetimeauth_verify(h, in, inlen, k);
}
int
crypto_onetimeauth_poly1305_init(crypto_onetimeauth_poly1305_state *state,
const unsigned char *key)
{
return implementation->onetimeauth_init(state, key);
}
int
crypto_onetimeauth_poly1305_update(crypto_onetimeauth_poly1305_state *state,
const unsigned char *in,
unsigned long long inlen)
{
return implementation->onetimeauth_update(state, in, inlen);
}
int
crypto_onetimeauth_poly1305_final(crypto_onetimeauth_poly1305_state *state,
unsigned char *out)
{
return implementation->onetimeauth_final(state, out);
}
|
gpl-3.0
|
CatTail/shadowsocks-android
|
src/main/jni/openssl/crypto/jpake/jpake.c
|
657
|
11830
|
#include "jpake.h"
#include <openssl/crypto.h>
#include <openssl/sha.h>
#include <openssl/err.h>
#include <memory.h>
/*
* In the definition, (xa, xb, xc, xd) are Alice's (x1, x2, x3, x4) or
* Bob's (x3, x4, x1, x2). If you see what I mean.
*/
typedef struct
{
char *name; /* Must be unique */
char *peer_name;
BIGNUM *p;
BIGNUM *g;
BIGNUM *q;
BIGNUM *gxc; /* Alice's g^{x3} or Bob's g^{x1} */
BIGNUM *gxd; /* Alice's g^{x4} or Bob's g^{x2} */
} JPAKE_CTX_PUBLIC;
struct JPAKE_CTX
{
JPAKE_CTX_PUBLIC p;
BIGNUM *secret; /* The shared secret */
BN_CTX *ctx;
BIGNUM *xa; /* Alice's x1 or Bob's x3 */
BIGNUM *xb; /* Alice's x2 or Bob's x4 */
BIGNUM *key; /* The calculated (shared) key */
};
static void JPAKE_ZKP_init(JPAKE_ZKP *zkp)
{
zkp->gr = BN_new();
zkp->b = BN_new();
}
static void JPAKE_ZKP_release(JPAKE_ZKP *zkp)
{
BN_free(zkp->b);
BN_free(zkp->gr);
}
/* Two birds with one stone - make the global name as expected */
#define JPAKE_STEP_PART_init JPAKE_STEP2_init
#define JPAKE_STEP_PART_release JPAKE_STEP2_release
void JPAKE_STEP_PART_init(JPAKE_STEP_PART *p)
{
p->gx = BN_new();
JPAKE_ZKP_init(&p->zkpx);
}
void JPAKE_STEP_PART_release(JPAKE_STEP_PART *p)
{
JPAKE_ZKP_release(&p->zkpx);
BN_free(p->gx);
}
void JPAKE_STEP1_init(JPAKE_STEP1 *s1)
{
JPAKE_STEP_PART_init(&s1->p1);
JPAKE_STEP_PART_init(&s1->p2);
}
void JPAKE_STEP1_release(JPAKE_STEP1 *s1)
{
JPAKE_STEP_PART_release(&s1->p2);
JPAKE_STEP_PART_release(&s1->p1);
}
static void JPAKE_CTX_init(JPAKE_CTX *ctx, const char *name,
const char *peer_name, const BIGNUM *p,
const BIGNUM *g, const BIGNUM *q,
const BIGNUM *secret)
{
ctx->p.name = OPENSSL_strdup(name);
ctx->p.peer_name = OPENSSL_strdup(peer_name);
ctx->p.p = BN_dup(p);
ctx->p.g = BN_dup(g);
ctx->p.q = BN_dup(q);
ctx->secret = BN_dup(secret);
ctx->p.gxc = BN_new();
ctx->p.gxd = BN_new();
ctx->xa = BN_new();
ctx->xb = BN_new();
ctx->key = BN_new();
ctx->ctx = BN_CTX_new();
}
static void JPAKE_CTX_release(JPAKE_CTX *ctx)
{
BN_CTX_free(ctx->ctx);
BN_clear_free(ctx->key);
BN_clear_free(ctx->xb);
BN_clear_free(ctx->xa);
BN_free(ctx->p.gxd);
BN_free(ctx->p.gxc);
BN_clear_free(ctx->secret);
BN_free(ctx->p.q);
BN_free(ctx->p.g);
BN_free(ctx->p.p);
OPENSSL_free(ctx->p.peer_name);
OPENSSL_free(ctx->p.name);
memset(ctx, '\0', sizeof *ctx);
}
JPAKE_CTX *JPAKE_CTX_new(const char *name, const char *peer_name,
const BIGNUM *p, const BIGNUM *g, const BIGNUM *q,
const BIGNUM *secret)
{
JPAKE_CTX *ctx = OPENSSL_malloc(sizeof *ctx);
JPAKE_CTX_init(ctx, name, peer_name, p, g, q, secret);
return ctx;
}
void JPAKE_CTX_free(JPAKE_CTX *ctx)
{
JPAKE_CTX_release(ctx);
OPENSSL_free(ctx);
}
static void hashlength(SHA_CTX *sha, size_t l)
{
unsigned char b[2];
OPENSSL_assert(l <= 0xffff);
b[0] = l >> 8;
b[1] = l&0xff;
SHA1_Update(sha, b, 2);
}
static void hashstring(SHA_CTX *sha, const char *string)
{
size_t l = strlen(string);
hashlength(sha, l);
SHA1_Update(sha, string, l);
}
static void hashbn(SHA_CTX *sha, const BIGNUM *bn)
{
size_t l = BN_num_bytes(bn);
unsigned char *bin = OPENSSL_malloc(l);
hashlength(sha, l);
BN_bn2bin(bn, bin);
SHA1_Update(sha, bin, l);
OPENSSL_free(bin);
}
/* h=hash(g, g^r, g^x, name) */
static void zkp_hash(BIGNUM *h, const BIGNUM *zkpg, const JPAKE_STEP_PART *p,
const char *proof_name)
{
unsigned char md[SHA_DIGEST_LENGTH];
SHA_CTX sha;
/*
* XXX: hash should not allow moving of the boundaries - Java code
* is flawed in this respect. Length encoding seems simplest.
*/
SHA1_Init(&sha);
hashbn(&sha, zkpg);
OPENSSL_assert(!BN_is_zero(p->zkpx.gr));
hashbn(&sha, p->zkpx.gr);
hashbn(&sha, p->gx);
hashstring(&sha, proof_name);
SHA1_Final(md, &sha);
BN_bin2bn(md, SHA_DIGEST_LENGTH, h);
}
/*
* Prove knowledge of x
* Note that p->gx has already been calculated
*/
static void generate_zkp(JPAKE_STEP_PART *p, const BIGNUM *x,
const BIGNUM *zkpg, JPAKE_CTX *ctx)
{
BIGNUM *r = BN_new();
BIGNUM *h = BN_new();
BIGNUM *t = BN_new();
/*
* r in [0,q)
* XXX: Java chooses r in [0, 2^160) - i.e. distribution not uniform
*/
BN_rand_range(r, ctx->p.q);
/* g^r */
BN_mod_exp(p->zkpx.gr, zkpg, r, ctx->p.p, ctx->ctx);
/* h=hash... */
zkp_hash(h, zkpg, p, ctx->p.name);
/* b = r - x*h */
BN_mod_mul(t, x, h, ctx->p.q, ctx->ctx);
BN_mod_sub(p->zkpx.b, r, t, ctx->p.q, ctx->ctx);
/* cleanup */
BN_free(t);
BN_free(h);
BN_free(r);
}
static int verify_zkp(const JPAKE_STEP_PART *p, const BIGNUM *zkpg,
JPAKE_CTX *ctx)
{
BIGNUM *h = BN_new();
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
int ret = 0;
zkp_hash(h, zkpg, p, ctx->p.peer_name);
/* t1 = g^b */
BN_mod_exp(t1, zkpg, p->zkpx.b, ctx->p.p, ctx->ctx);
/* t2 = (g^x)^h = g^{hx} */
BN_mod_exp(t2, p->gx, h, ctx->p.p, ctx->ctx);
/* t3 = t1 * t2 = g^{hx} * g^b = g^{hx+b} = g^r (allegedly) */
BN_mod_mul(t3, t1, t2, ctx->p.p, ctx->ctx);
/* verify t3 == g^r */
if(BN_cmp(t3, p->zkpx.gr) == 0)
ret = 1;
else
JPAKEerr(JPAKE_F_VERIFY_ZKP, JPAKE_R_ZKP_VERIFY_FAILED);
/* cleanup */
BN_free(t3);
BN_free(t2);
BN_free(t1);
BN_free(h);
return ret;
}
static void generate_step_part(JPAKE_STEP_PART *p, const BIGNUM *x,
const BIGNUM *g, JPAKE_CTX *ctx)
{
BN_mod_exp(p->gx, g, x, ctx->p.p, ctx->ctx);
generate_zkp(p, x, g, ctx);
}
/* Generate each party's random numbers. xa is in [0, q), xb is in [1, q). */
static void genrand(JPAKE_CTX *ctx)
{
BIGNUM *qm1;
/* xa in [0, q) */
BN_rand_range(ctx->xa, ctx->p.q);
/* q-1 */
qm1 = BN_new();
BN_copy(qm1, ctx->p.q);
BN_sub_word(qm1, 1);
/* ... and xb in [0, q-1) */
BN_rand_range(ctx->xb, qm1);
/* [1, q) */
BN_add_word(ctx->xb, 1);
/* cleanup */
BN_free(qm1);
}
int JPAKE_STEP1_generate(JPAKE_STEP1 *send, JPAKE_CTX *ctx)
{
genrand(ctx);
generate_step_part(&send->p1, ctx->xa, ctx->p.g, ctx);
generate_step_part(&send->p2, ctx->xb, ctx->p.g, ctx);
return 1;
}
/* g^x is a legal value */
static int is_legal(const BIGNUM *gx, const JPAKE_CTX *ctx)
{
BIGNUM *t;
int res;
if(BN_is_negative(gx) || BN_is_zero(gx) || BN_cmp(gx, ctx->p.p) >= 0)
return 0;
t = BN_new();
BN_mod_exp(t, gx, ctx->p.q, ctx->p.p, ctx->ctx);
res = BN_is_one(t);
BN_free(t);
return res;
}
int JPAKE_STEP1_process(JPAKE_CTX *ctx, const JPAKE_STEP1 *received)
{
if(!is_legal(received->p1.gx, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X3_IS_NOT_LEGAL);
return 0;
}
if(!is_legal(received->p2.gx, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_NOT_LEGAL);
return 0;
}
/* verify their ZKP(xc) */
if(!verify_zkp(&received->p1, ctx->p.g, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X3_FAILED);
return 0;
}
/* verify their ZKP(xd) */
if(!verify_zkp(&received->p2, ctx->p.g, ctx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_VERIFY_X4_FAILED);
return 0;
}
/* g^xd != 1 */
if(BN_is_one(received->p2.gx))
{
JPAKEerr(JPAKE_F_JPAKE_STEP1_PROCESS, JPAKE_R_G_TO_THE_X4_IS_ONE);
return 0;
}
/* Save the bits we need for later */
BN_copy(ctx->p.gxc, received->p1.gx);
BN_copy(ctx->p.gxd, received->p2.gx);
return 1;
}
int JPAKE_STEP2_generate(JPAKE_STEP2 *send, JPAKE_CTX *ctx)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
/*
* X = g^{(xa + xc + xd) * xb * s}
* t1 = g^xa
*/
BN_mod_exp(t1, ctx->p.g, ctx->xa, ctx->p.p, ctx->ctx);
/* t2 = t1 * g^{xc} = g^{xa} * g^{xc} = g^{xa + xc} */
BN_mod_mul(t2, t1, ctx->p.gxc, ctx->p.p, ctx->ctx);
/* t1 = t2 * g^{xd} = g^{xa + xc + xd} */
BN_mod_mul(t1, t2, ctx->p.gxd, ctx->p.p, ctx->ctx);
/* t2 = xb * s */
BN_mod_mul(t2, ctx->xb, ctx->secret, ctx->p.q, ctx->ctx);
/*
* ZKP(xb * s)
* XXX: this is kinda funky, because we're using
*
* g' = g^{xa + xc + xd}
*
* as the generator, which means X is g'^{xb * s}
* X = t1^{t2} = t1^{xb * s} = g^{(xa + xc + xd) * xb * s}
*/
generate_step_part(send, t2, t1, ctx);
/* cleanup */
BN_free(t1);
BN_free(t2);
return 1;
}
/* gx = g^{xc + xa + xb} * xd * s */
static int compute_key(JPAKE_CTX *ctx, const BIGNUM *gx)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
BIGNUM *t3 = BN_new();
/*
* K = (gx/g^{xb * xd * s})^{xb}
* = (g^{(xc + xa + xb) * xd * s - xb * xd *s})^{xb}
* = (g^{(xa + xc) * xd * s})^{xb}
* = g^{(xa + xc) * xb * xd * s}
* [which is the same regardless of who calculates it]
*/
/* t1 = (g^{xd})^{xb} = g^{xb * xd} */
BN_mod_exp(t1, ctx->p.gxd, ctx->xb, ctx->p.p, ctx->ctx);
/* t2 = -s = q-s */
BN_sub(t2, ctx->p.q, ctx->secret);
/* t3 = t1^t2 = g^{-xb * xd * s} */
BN_mod_exp(t3, t1, t2, ctx->p.p, ctx->ctx);
/* t1 = gx * t3 = X/g^{xb * xd * s} */
BN_mod_mul(t1, gx, t3, ctx->p.p, ctx->ctx);
/* K = t1^{xb} */
BN_mod_exp(ctx->key, t1, ctx->xb, ctx->p.p, ctx->ctx);
/* cleanup */
BN_free(t3);
BN_free(t2);
BN_free(t1);
return 1;
}
int JPAKE_STEP2_process(JPAKE_CTX *ctx, const JPAKE_STEP2 *received)
{
BIGNUM *t1 = BN_new();
BIGNUM *t2 = BN_new();
int ret = 0;
/*
* g' = g^{xc + xa + xb} [from our POV]
* t1 = xa + xb
*/
BN_mod_add(t1, ctx->xa, ctx->xb, ctx->p.q, ctx->ctx);
/* t2 = g^{t1} = g^{xa+xb} */
BN_mod_exp(t2, ctx->p.g, t1, ctx->p.p, ctx->ctx);
/* t1 = g^{xc} * t2 = g^{xc + xa + xb} */
BN_mod_mul(t1, ctx->p.gxc, t2, ctx->p.p, ctx->ctx);
if(verify_zkp(received, t1, ctx))
ret = 1;
else
JPAKEerr(JPAKE_F_JPAKE_STEP2_PROCESS, JPAKE_R_VERIFY_B_FAILED);
compute_key(ctx, received->gx);
/* cleanup */
BN_free(t2);
BN_free(t1);
return ret;
}
static void quickhashbn(unsigned char *md, const BIGNUM *bn)
{
SHA_CTX sha;
SHA1_Init(&sha);
hashbn(&sha, bn);
SHA1_Final(md, &sha);
}
void JPAKE_STEP3A_init(JPAKE_STEP3A *s3a)
{}
int JPAKE_STEP3A_generate(JPAKE_STEP3A *send, JPAKE_CTX *ctx)
{
quickhashbn(send->hhk, ctx->key);
SHA1(send->hhk, sizeof send->hhk, send->hhk);
return 1;
}
int JPAKE_STEP3A_process(JPAKE_CTX *ctx, const JPAKE_STEP3A *received)
{
unsigned char hhk[SHA_DIGEST_LENGTH];
quickhashbn(hhk, ctx->key);
SHA1(hhk, sizeof hhk, hhk);
if(memcmp(hhk, received->hhk, sizeof hhk))
{
JPAKEerr(JPAKE_F_JPAKE_STEP3A_PROCESS, JPAKE_R_HASH_OF_HASH_OF_KEY_MISMATCH);
return 0;
}
return 1;
}
void JPAKE_STEP3A_release(JPAKE_STEP3A *s3a)
{}
void JPAKE_STEP3B_init(JPAKE_STEP3B *s3b)
{}
int JPAKE_STEP3B_generate(JPAKE_STEP3B *send, JPAKE_CTX *ctx)
{
quickhashbn(send->hk, ctx->key);
return 1;
}
int JPAKE_STEP3B_process(JPAKE_CTX *ctx, const JPAKE_STEP3B *received)
{
unsigned char hk[SHA_DIGEST_LENGTH];
quickhashbn(hk, ctx->key);
if(memcmp(hk, received->hk, sizeof hk))
{
JPAKEerr(JPAKE_F_JPAKE_STEP3B_PROCESS, JPAKE_R_HASH_OF_KEY_MISMATCH);
return 0;
}
return 1;
}
void JPAKE_STEP3B_release(JPAKE_STEP3B *s3b)
{}
const BIGNUM *JPAKE_get_shared_key(JPAKE_CTX *ctx)
{
return ctx->key;
}
|
gpl-3.0
|
Syun0929/shadowsocks-android
|
src/main/jni/openssl/crypto/rc5/rc5test.c
|
657
|
13112
|
/* crypto/rc5/rc5test.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.]
*/
/* This has been a quickly hacked 'ideatest.c'. When I add tests for other
* RC5 modes, more of the code will be uncommented. */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "../e_os.h"
#ifdef OPENSSL_NO_RC5
int main(int argc, char *argv[])
{
printf("No RC5 support\n");
return(0);
}
#else
#include <openssl/rc5.h>
static unsigned char RC5key[5][16]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,
0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x91,0x5f,0x46,0x19,0xbe,0x41,0xb2,0x51,
0x63,0x55,0xa5,0x01,0x10,0xa9,0xce,0x91},
{0x78,0x33,0x48,0xe7,0x5a,0xeb,0x0f,0x2f,
0xd7,0xb1,0x69,0xbb,0x8d,0xc1,0x67,0x87},
{0xdc,0x49,0xdb,0x13,0x75,0xa5,0x58,0x4f,
0x64,0x85,0xb4,0x13,0xb5,0xf1,0x2b,0xaf},
{0x52,0x69,0xf1,0x49,0xd4,0x1b,0xa0,0x15,
0x24,0x97,0x57,0x4d,0x7f,0x15,0x31,0x25},
};
static unsigned char RC5plain[5][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x21,0xA5,0xDB,0xEE,0x15,0x4B,0x8F,0x6D},
{0xF7,0xC0,0x13,0xAC,0x5B,0x2B,0x89,0x52},
{0x2F,0x42,0xB3,0xB7,0x03,0x69,0xFC,0x92},
{0x65,0xC1,0x78,0xB2,0x84,0xD1,0x97,0xCC},
};
static unsigned char RC5cipher[5][8]={
{0x21,0xA5,0xDB,0xEE,0x15,0x4B,0x8F,0x6D},
{0xF7,0xC0,0x13,0xAC,0x5B,0x2B,0x89,0x52},
{0x2F,0x42,0xB3,0xB7,0x03,0x69,0xFC,0x92},
{0x65,0xC1,0x78,0xB2,0x84,0xD1,0x97,0xCC},
{0xEB,0x44,0xE4,0x15,0xDA,0x31,0x98,0x24},
};
#define RC5_CBC_NUM 27
static unsigned char rc5_cbc_cipher[RC5_CBC_NUM][8]={
{0x7a,0x7b,0xba,0x4d,0x79,0x11,0x1d,0x1e},
{0x79,0x7b,0xba,0x4d,0x78,0x11,0x1d,0x1e},
{0x7a,0x7b,0xba,0x4d,0x79,0x11,0x1d,0x1f},
{0x7a,0x7b,0xba,0x4d,0x79,0x11,0x1d,0x1f},
{0x8b,0x9d,0xed,0x91,0xce,0x77,0x94,0xa6},
{0x2f,0x75,0x9f,0xe7,0xad,0x86,0xa3,0x78},
{0xdc,0xa2,0x69,0x4b,0xf4,0x0e,0x07,0x88},
{0xdc,0xa2,0x69,0x4b,0xf4,0x0e,0x07,0x88},
{0xdc,0xfe,0x09,0x85,0x77,0xec,0xa5,0xff},
{0x96,0x46,0xfb,0x77,0x63,0x8f,0x9c,0xa8},
{0xb2,0xb3,0x20,0x9d,0xb6,0x59,0x4d,0xa4},
{0x54,0x5f,0x7f,0x32,0xa5,0xfc,0x38,0x36},
{0x82,0x85,0xe7,0xc1,0xb5,0xbc,0x74,0x02},
{0xfc,0x58,0x6f,0x92,0xf7,0x08,0x09,0x34},
{0xcf,0x27,0x0e,0xf9,0x71,0x7f,0xf7,0xc4},
{0xe4,0x93,0xf1,0xc1,0xbb,0x4d,0x6e,0x8c},
{0x5c,0x4c,0x04,0x1e,0x0f,0x21,0x7a,0xc3},
{0x92,0x1f,0x12,0x48,0x53,0x73,0xb4,0xf7},
{0x5b,0xa0,0xca,0x6b,0xbe,0x7f,0x5f,0xad},
{0xc5,0x33,0x77,0x1c,0xd0,0x11,0x0e,0x63},
{0x29,0x4d,0xdb,0x46,0xb3,0x27,0x8d,0x60},
{0xda,0xd6,0xbd,0xa9,0xdf,0xe8,0xf7,0xe8},
{0x97,0xe0,0x78,0x78,0x37,0xed,0x31,0x7f},
{0x78,0x75,0xdb,0xf6,0x73,0x8c,0x64,0x78},
{0x8f,0x34,0xc3,0xc6,0x81,0xc9,0x96,0x95},
{0x7c,0xb3,0xf1,0xdf,0x34,0xf9,0x48,0x11},
{0x7f,0xd1,0xa0,0x23,0xa5,0xbb,0xa2,0x17},
};
static unsigned char rc5_cbc_key[RC5_CBC_NUM][17]={
{ 1,0x00},
{ 1,0x00},
{ 1,0x00},
{ 1,0x00},
{ 1,0x00},
{ 1,0x11},
{ 1,0x00},
{ 4,0x00,0x00,0x00,0x00},
{ 1,0x00},
{ 1,0x00},
{ 1,0x00},
{ 1,0x00},
{ 4,0x01,0x02,0x03,0x04},
{ 4,0x01,0x02,0x03,0x04},
{ 4,0x01,0x02,0x03,0x04},
{ 8,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{ 8,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{ 8,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{ 8,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{16,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{16,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{16,0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08,
0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{ 5,0x01,0x02,0x03,0x04,0x05},
{ 5,0x01,0x02,0x03,0x04,0x05},
{ 5,0x01,0x02,0x03,0x04,0x05},
{ 5,0x01,0x02,0x03,0x04,0x05},
{ 5,0x01,0x02,0x03,0x04,0x05},
};
static unsigned char rc5_cbc_plain[RC5_CBC_NUM][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0x10,0x20,0x30,0x40,0x50,0x60,0x70,0x80},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0xff,0xff,0xff,0xff,0xff,0xff,0xff,0xff},
{0x08,0x08,0x08,0x08,0x08,0x08,0x08,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x11,0x22,0x33,0x44,0x55,0x66,0x77,0x01},
};
static int rc5_cbc_rounds[RC5_CBC_NUM]={
0, 0, 0, 0, 0, 1, 2, 2,
8, 8,12,16, 8,12,16,12,
8,12,16, 8,12,16,12, 8,
8, 8, 8,
};
static unsigned char rc5_cbc_iv[RC5_CBC_NUM][8]={
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x01,0x02,0x03,0x04,0x05,0x06,0x07,0x08},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x78,0x75,0xdb,0xf6,0x73,0x8c,0x64,0x78},
{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00},
{0x7c,0xb3,0xf1,0xdf,0x34,0xf9,0x48,0x11},
};
int main(int argc, char *argv[])
{
int i,n,err=0;
RC5_32_KEY key;
unsigned char buf[8],buf2[8],ivb[8];
for (n=0; n<5; n++)
{
RC5_32_set_key(&key,16,&(RC5key[n][0]),12);
RC5_32_ecb_encrypt(&(RC5plain[n][0]),buf,&key,RC5_ENCRYPT);
if (memcmp(&(RC5cipher[n][0]),buf,8) != 0)
{
printf("ecb RC5 error encrypting (%d)\n",n+1);
printf("got :");
for (i=0; i<8; i++)
printf("%02X ",buf[i]);
printf("\n");
printf("expected:");
for (i=0; i<8; i++)
printf("%02X ",RC5cipher[n][i]);
err=20;
printf("\n");
}
RC5_32_ecb_encrypt(buf,buf2,&key,RC5_DECRYPT);
if (memcmp(&(RC5plain[n][0]),buf2,8) != 0)
{
printf("ecb RC5 error decrypting (%d)\n",n+1);
printf("got :");
for (i=0; i<8; i++)
printf("%02X ",buf2[i]);
printf("\n");
printf("expected:");
for (i=0; i<8; i++)
printf("%02X ",RC5plain[n][i]);
printf("\n");
err=3;
}
}
if (err == 0) printf("ecb RC5 ok\n");
for (n=0; n<RC5_CBC_NUM; n++)
{
i=rc5_cbc_rounds[n];
if (i < 8) continue;
RC5_32_set_key(&key,rc5_cbc_key[n][0],&(rc5_cbc_key[n][1]),i);
memcpy(ivb,&(rc5_cbc_iv[n][0]),8);
RC5_32_cbc_encrypt(&(rc5_cbc_plain[n][0]),buf,8,
&key,&(ivb[0]),RC5_ENCRYPT);
if (memcmp(&(rc5_cbc_cipher[n][0]),buf,8) != 0)
{
printf("cbc RC5 error encrypting (%d)\n",n+1);
printf("got :");
for (i=0; i<8; i++)
printf("%02X ",buf[i]);
printf("\n");
printf("expected:");
for (i=0; i<8; i++)
printf("%02X ",rc5_cbc_cipher[n][i]);
err=30;
printf("\n");
}
memcpy(ivb,&(rc5_cbc_iv[n][0]),8);
RC5_32_cbc_encrypt(buf,buf2,8,
&key,&(ivb[0]),RC5_DECRYPT);
if (memcmp(&(rc5_cbc_plain[n][0]),buf2,8) != 0)
{
printf("cbc RC5 error decrypting (%d)\n",n+1);
printf("got :");
for (i=0; i<8; i++)
printf("%02X ",buf2[i]);
printf("\n");
printf("expected:");
for (i=0; i<8; i++)
printf("%02X ",rc5_cbc_plain[n][i]);
printf("\n");
err=3;
}
}
if (err == 0) printf("cbc RC5 ok\n");
EXIT(err);
return(err);
}
#ifdef undef
static int cfb64_test(unsigned char *cfb_cipher)
{
IDEA_KEY_SCHEDULE eks,dks;
int err=0,i,n;
idea_set_encrypt_key(cfb_key,&eks);
idea_set_decrypt_key(&eks,&dks);
memcpy(cfb_tmp,cfb_iv,8);
n=0;
idea_cfb64_encrypt(plain,cfb_buf1,(long)12,&eks,
cfb_tmp,&n,IDEA_ENCRYPT);
idea_cfb64_encrypt(&(plain[12]),&(cfb_buf1[12]),
(long)CFB_TEST_SIZE-12,&eks,
cfb_tmp,&n,IDEA_ENCRYPT);
if (memcmp(cfb_cipher,cfb_buf1,CFB_TEST_SIZE) != 0)
{
err=1;
printf("idea_cfb64_encrypt encrypt error\n");
for (i=0; i<CFB_TEST_SIZE; i+=8)
printf("%s\n",pt(&(cfb_buf1[i])));
}
memcpy(cfb_tmp,cfb_iv,8);
n=0;
idea_cfb64_encrypt(cfb_buf1,cfb_buf2,(long)17,&eks,
cfb_tmp,&n,IDEA_DECRYPT);
idea_cfb64_encrypt(&(cfb_buf1[17]),&(cfb_buf2[17]),
(long)CFB_TEST_SIZE-17,&dks,
cfb_tmp,&n,IDEA_DECRYPT);
if (memcmp(plain,cfb_buf2,CFB_TEST_SIZE) != 0)
{
err=1;
printf("idea_cfb_encrypt decrypt error\n");
for (i=0; i<24; i+=8)
printf("%s\n",pt(&(cfb_buf2[i])));
}
return(err);
}
static char *pt(unsigned char *p)
{
static char bufs[10][20];
static int bnum=0;
char *ret;
int i;
static char *f="0123456789ABCDEF";
ret= &(bufs[bnum++][0]);
bnum%=10;
for (i=0; i<8; i++)
{
ret[i*2]=f[(p[i]>>4)&0xf];
ret[i*2+1]=f[p[i]&0xf];
}
ret[16]='\0';
return(ret);
}
#endif
#endif
|
gpl-3.0
|
slfl/HUAWEI89_WE_KK_700
|
kernel/arch/powerpc/boot/treeboot-iss4xx.c
|
9366
|
2023
|
/*
* Copyright 2010 Ben. Herrenschmidt, IBM Corporation.
*
* Based on earlier code:
* Copyright (C) Paul Mackerras 1997.
*
* Matt Porter <mporter@kernel.crashing.org>
* Copyright 2002-2005 MontaVista Software Inc.
*
* Eugene Surovegin <eugene.surovegin@zultys.com> or <ebs@ebshome.net>
* Copyright (c) 2003, 2004 Zultys Technologies
*
* Copyright 2007 David Gibson, IBM Corporation.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <stdarg.h>
#include <stddef.h>
#include "types.h"
#include "elf.h"
#include "string.h"
#include "stdio.h"
#include "page.h"
#include "ops.h"
#include "reg.h"
#include "io.h"
#include "dcr.h"
#include "4xx.h"
#include "44x.h"
#include "libfdt.h"
BSS_STACK(4096);
static u32 ibm4xx_memstart;
static void iss_4xx_fixups(void)
{
void *memory;
u32 reg[3];
memory = finddevice("/memory");
if (!memory)
fatal("Can't find memory node\n");
/* This assumes #address-cells = 2, #size-cells =1 and that */
getprop(memory, "reg", reg, sizeof(reg));
if (reg[2])
/* If the device tree specifies the memory range, use it */
ibm4xx_memstart = reg[1];
else
/* othersize, read it from the SDRAM controller */
ibm4xx_sdram_fixup_memsize();
}
static void *iss_4xx_vmlinux_alloc(unsigned long size)
{
return (void *)ibm4xx_memstart;
}
#define SPRN_PIR 0x11E /* Processor Indentification Register */
void platform_init(void)
{
unsigned long end_of_ram = 0x08000000;
unsigned long avail_ram = end_of_ram - (unsigned long)_end;
u32 pir_reg;
simple_alloc_init(_end, avail_ram, 128, 64);
platform_ops.fixups = iss_4xx_fixups;
platform_ops.vmlinux_alloc = iss_4xx_vmlinux_alloc;
platform_ops.exit = ibm44x_dbcr_reset;
pir_reg = mfspr(SPRN_PIR);
fdt_set_boot_cpuid_phys(_dtb_start, pir_reg);
fdt_init(_dtb_start);
serial_console_init();
}
|
gpl-3.0
|
CognetTestbed/COGNET_CODE
|
KERNEL_SOURCE_CODE/linux-source-3.8.11-voyage/drivers/scsi/ultrastor.c
|
9381
|
36980
|
/*
* ultrastor.c Copyright (C) 1992 David B. Gentzel
* Low-level SCSI driver for UltraStor 14F, 24F, and 34F
* by David B. Gentzel, Whitfield Software Services, Carnegie, PA
* (gentzel@nova.enet.dec.com)
* scatter/gather added by Scott Taylor (n217cg@tamuts.tamu.edu)
* 24F and multiple command support by John F. Carr (jfc@athena.mit.edu)
* John's work modified by Caleb Epstein (cae@jpmorgan.com) and
* Eric Youngdale (ericy@cais.com).
* Thanks to UltraStor for providing the necessary documentation
*
* This is an old driver, for the 14F and 34F you should be using the
* u14-34f driver instead.
*/
/*
* TODO:
* 1. Find out why scatter/gather is limited to 16 requests per command.
* This is fixed, at least on the 24F, as of version 1.12 - CAE.
* 2. Look at command linking (mscp.command_link and
* mscp.command_link_id). (Does not work with many disks,
* and no performance increase. ERY).
* 3. Allow multiple adapters.
*/
/*
* NOTES:
* The UltraStor 14F, 24F, and 34F are a family of intelligent, high
* performance SCSI-2 host adapters. They all support command queueing
* and scatter/gather I/O. Some of them can also emulate the standard
* WD1003 interface for use with OS's which don't support SCSI. Here
* is the scoop on the various models:
* 14F - ISA first-party DMA HA with floppy support and WD1003 emulation.
* 14N - ISA HA with floppy support. I think that this is a non-DMA
* HA. Nothing further known.
* 24F - EISA Bus Master HA with floppy support and WD1003 emulation.
* 34F - VL-Bus Bus Master HA with floppy support (no WD1003 emulation).
*
* The 14F, 24F, and 34F are supported by this driver.
*
* Places flagged with a triple question-mark are things which are either
* unfinished, questionable, or wrong.
*/
/* Changes from version 1.11 alpha to 1.12
*
* Increased the size of the scatter-gather list to 33 entries for
* the 24F adapter (it was 16). I don't have the specs for the 14F
* or the 34F, so they may support larger s-g lists as well.
*
* Caleb Epstein <cae@jpmorgan.com>
*/
/* Changes from version 1.9 to 1.11
*
* Patches to bring this driver up to speed with the default kernel
* driver which supports only the 14F and 34F adapters. This version
* should compile cleanly into 0.99.13, 0.99.12 and probably 0.99.11.
*
* Fixes from Eric Youngdale to fix a few possible race conditions and
* several problems with bit testing operations (insufficient
* parentheses).
*
* Removed the ultrastor_abort() and ultrastor_reset() functions
* (enclosed them in #if 0 / #endif). These functions, at least on
* the 24F, cause the SCSI bus to do odd things and generally lead to
* kernel panics and machine hangs. This is like the Adaptec code.
*
* Use check/snarf_region for 14f, 34f to avoid I/O space address conflicts.
*/
/* Changes from version 1.8 to version 1.9
*
* 0.99.11 patches (cae@jpmorgan.com) */
/* Changes from version 1.7 to version 1.8
*
* Better error reporting.
*/
/* Changes from version 1.6 to version 1.7
*
* Removed CSIR command code.
*
* Better race condition avoidance (xchgb function added).
*
* Set ICM and OGM status to zero at probe (24F)
*
* reset sends soft reset to UltraStor adapter
*
* reset adapter if adapter interrupts with an invalid MSCP address
*
* handle aborted command interrupt (24F)
*
*/
/* Changes from version 1.5 to version 1.6:
*
* Read MSCP address from ICM _before_ clearing the interrupt flag.
* This fixes a race condition.
*/
/* Changes from version 1.4 to version 1.5:
*
* Abort now calls done when multiple commands are enabled.
*
* Clear busy when aborted command finishes, not when abort is called.
*
* More debugging messages for aborts.
*/
/* Changes from version 1.3 to version 1.4:
*
* Enable automatic request of sense data on error (requires newer version
* of scsi.c to be useful).
*
* Fix PORT_OVERRIDE for 14F.
*
* Fix abort and reset to work properly (config.aborted wasn't cleared
* after it was tested, so after a command abort no further commands would
* work).
*
* Boot time test to enable SCSI bus reset (defaults to not allowing reset).
*
* Fix test for OGM busy -- the busy bit is in different places on the 24F.
*
* Release ICM slot by clearing first byte on 24F.
*/
#include <linux/module.h>
#include <linux/blkdev.h>
#include <linux/interrupt.h>
#include <linux/stddef.h>
#include <linux/string.h>
#include <linux/kernel.h>
#include <linux/ioport.h>
#include <linux/proc_fs.h>
#include <linux/spinlock.h>
#include <linux/stat.h>
#include <linux/bitops.h>
#include <linux/delay.h>
#include <asm/io.h>
#include <asm/dma.h>
#define ULTRASTOR_PRIVATE /* Get the private stuff from ultrastor.h */
#include "scsi.h"
#include <scsi/scsi_host.h>
#include "ultrastor.h"
#define FALSE 0
#define TRUE 1
#ifndef ULTRASTOR_DEBUG
#define ULTRASTOR_DEBUG (UD_ABORT|UD_CSIR|UD_RESET)
#endif
#define VERSION "1.12"
#define PACKED __attribute__((packed))
#define ALIGNED(x) __attribute__((aligned(x)))
/* The 14F uses an array of 4-byte ints for its scatter/gather list.
The data can be unaligned, but need not be. It's easier to give
the list normal alignment since it doesn't need to fit into a
packed structure. */
typedef struct {
u32 address;
u32 num_bytes;
} ultrastor_sg_list;
/* MailBox SCSI Command Packet. Basic command structure for communicating
with controller. */
struct mscp {
unsigned char opcode: 3; /* type of command */
unsigned char xdir: 2; /* data transfer direction */
unsigned char dcn: 1; /* disable disconnect */
unsigned char ca: 1; /* use cache (if available) */
unsigned char sg: 1; /* scatter/gather operation */
unsigned char target_id: 3; /* target SCSI id */
unsigned char ch_no: 2; /* SCSI channel (always 0 for 14f) */
unsigned char lun: 3; /* logical unit number */
unsigned int transfer_data PACKED; /* transfer data pointer */
unsigned int transfer_data_length PACKED; /* length in bytes */
unsigned int command_link PACKED; /* for linking command chains */
unsigned char scsi_command_link_id; /* identifies command in chain */
unsigned char number_of_sg_list; /* (if sg is set) 8 bytes per list */
unsigned char length_of_sense_byte;
unsigned char length_of_scsi_cdbs; /* 6, 10, or 12 */
unsigned char scsi_cdbs[12]; /* SCSI commands */
unsigned char adapter_status; /* non-zero indicates HA error */
unsigned char target_status; /* non-zero indicates target error */
u32 sense_data PACKED;
/* The following fields are for software only. They are included in
the MSCP structure because they are associated with SCSI requests. */
void (*done) (struct scsi_cmnd *);
struct scsi_cmnd *SCint;
ultrastor_sg_list sglist[ULTRASTOR_24F_MAX_SG]; /* use larger size for 24F */
};
/* Port addresses (relative to the base address) */
#define U14F_PRODUCT_ID(port) ((port) + 0x4)
#define CONFIG(port) ((port) + 0x6)
/* Port addresses relative to the doorbell base address. */
#define LCL_DOORBELL_MASK(port) ((port) + 0x0)
#define LCL_DOORBELL_INTR(port) ((port) + 0x1)
#define SYS_DOORBELL_MASK(port) ((port) + 0x2)
#define SYS_DOORBELL_INTR(port) ((port) + 0x3)
/* Used to store configuration info read from config i/o registers. Most of
this is not used yet, but might as well save it.
This structure also holds port addresses that are not at the same offset
on the 14F and 24F.
This structure holds all data that must be duplicated to support multiple
adapters. */
static struct ultrastor_config
{
unsigned short port_address; /* base address of card */
unsigned short doorbell_address; /* base address of doorbell CSRs */
unsigned short ogm_address; /* base address of OGM */
unsigned short icm_address; /* base address of ICM */
const void *bios_segment;
unsigned char interrupt: 4;
unsigned char dma_channel: 3;
unsigned char bios_drive_number: 1;
unsigned char heads;
unsigned char sectors;
unsigned char ha_scsi_id: 3;
unsigned char subversion: 4;
unsigned char revision;
/* The slot number is used to distinguish the 24F (slot != 0) from
the 14F and 34F (slot == 0). */
unsigned char slot;
#ifdef PRINT_U24F_VERSION
volatile int csir_done;
#endif
/* A pool of MSCP structures for this adapter, and a bitmask of
busy structures. (If ULTRASTOR_14F_MAX_CMDS == 1, a 1 byte
busy flag is used instead.) */
#if ULTRASTOR_MAX_CMDS == 1
unsigned char mscp_busy;
#else
unsigned long mscp_free;
#endif
volatile unsigned char aborted[ULTRASTOR_MAX_CMDS];
struct mscp mscp[ULTRASTOR_MAX_CMDS];
} config = {0};
/* Set this to 1 to reset the SCSI bus on error. */
static int ultrastor_bus_reset;
/* Allowed BIOS base addresses (NULL indicates reserved) */
static const void *const bios_segment_table[8] = {
NULL, (void *)0xC4000, (void *)0xC8000, (void *)0xCC000,
(void *)0xD0000, (void *)0xD4000, (void *)0xD8000, (void *)0xDC000,
};
/* Allowed IRQs for 14f */
static const unsigned char interrupt_table_14f[4] = { 15, 14, 11, 10 };
/* Allowed DMA channels for 14f (0 indicates reserved) */
static const unsigned char dma_channel_table_14f[4] = { 5, 6, 7, 0 };
/* Head/sector mappings allowed by 14f */
static const struct {
unsigned char heads;
unsigned char sectors;
} mapping_table[4] = { { 16, 63 }, { 64, 32 }, { 64, 63 }, { 64, 32 } };
#ifndef PORT_OVERRIDE
/* ??? A probe of address 0x310 screws up NE2000 cards */
static const unsigned short ultrastor_ports_14f[] = {
0x330, 0x340, /*0x310,*/ 0x230, 0x240, 0x210, 0x130, 0x140,
};
#endif
static void ultrastor_interrupt(void *);
static irqreturn_t do_ultrastor_interrupt(int, void *);
static inline void build_sg_list(struct mscp *, struct scsi_cmnd *SCpnt);
/* Always called with host lock held */
static inline int find_and_clear_bit_16(unsigned long *field)
{
int rv;
if (*field == 0)
panic("No free mscp");
asm volatile (
"xorl %0,%0\n\t"
"0: bsfw %1,%w0\n\t"
"btr %0,%1\n\t"
"jnc 0b"
: "=&r" (rv), "+m" (*field) :);
return rv;
}
/* This has been re-implemented with the help of Richard Earnshaw,
<rwe@pegasus.esprit.ec.org> and works with gcc-2.5.8 and gcc-2.6.0.
The instability noted by jfc below appears to be a bug in
gcc-2.5.x when compiling w/o optimization. --Caleb
This asm is fragile: it doesn't work without the casts and it may
not work without optimization. Maybe I should add a swap builtin
to gcc. --jfc */
static inline unsigned char xchgb(unsigned char reg,
volatile unsigned char *mem)
{
__asm__ ("xchgb %0,%1" : "=q" (reg), "=m" (*mem) : "0" (reg));
return reg;
}
#if ULTRASTOR_DEBUG & (UD_COMMAND | UD_ABORT)
/* Always called with the host lock held */
static void log_ultrastor_abort(struct ultrastor_config *config,
int command)
{
static char fmt[80] = "abort %d (%x); MSCP free pool: %x;";
int i;
for (i = 0; i < ULTRASTOR_MAX_CMDS; i++)
{
fmt[20 + i*2] = ' ';
if (! (config->mscp_free & (1 << i)))
fmt[21 + i*2] = '0' + config->mscp[i].target_id;
else
fmt[21 + i*2] = '-';
}
fmt[20 + ULTRASTOR_MAX_CMDS * 2] = '\n';
fmt[21 + ULTRASTOR_MAX_CMDS * 2] = 0;
printk(fmt, command, &config->mscp[command], config->mscp_free);
}
#endif
static int ultrastor_14f_detect(struct scsi_host_template * tpnt)
{
size_t i;
unsigned char in_byte, version_byte = 0;
struct config_1 {
unsigned char bios_segment: 3;
unsigned char removable_disks_as_fixed: 1;
unsigned char interrupt: 2;
unsigned char dma_channel: 2;
} config_1;
struct config_2 {
unsigned char ha_scsi_id: 3;
unsigned char mapping_mode: 2;
unsigned char bios_drive_number: 1;
unsigned char tfr_port: 2;
} config_2;
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: called\n");
#endif
/* If a 24F has already been configured, don't look for a 14F. */
if (config.bios_segment)
return FALSE;
#ifdef PORT_OVERRIDE
if(!request_region(PORT_OVERRIDE, 0xc, "ultrastor")) {
printk("Ultrastor I/O space already in use\n");
return FALSE;
};
config.port_address = PORT_OVERRIDE;
#else
for (i = 0; i < ARRAY_SIZE(ultrastor_ports_14f); i++) {
if(!request_region(ultrastor_ports_14f[i], 0x0c, "ultrastor")) continue;
config.port_address = ultrastor_ports_14f[i];
#endif
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: testing port address %03X\n", config.port_address);
#endif
in_byte = inb(U14F_PRODUCT_ID(config.port_address));
if (in_byte != US14F_PRODUCT_ID_0) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
# ifdef PORT_OVERRIDE
printk("US14F: detect: wrong product ID 0 - %02X\n", in_byte);
# else
printk("US14F: detect: no adapter at port %03X\n", config.port_address);
# endif
#endif
#ifdef PORT_OVERRIDE
goto out_release_port;
#else
release_region(config.port_address, 0x0c);
continue;
#endif
}
in_byte = inb(U14F_PRODUCT_ID(config.port_address) + 1);
/* Only upper nibble is significant for Product ID 1 */
if ((in_byte & 0xF0) != US14F_PRODUCT_ID_1) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
# ifdef PORT_OVERRIDE
printk("US14F: detect: wrong product ID 1 - %02X\n", in_byte);
# else
printk("US14F: detect: no adapter at port %03X\n", config.port_address);
# endif
#endif
#ifdef PORT_OVERRIDE
goto out_release_port;
#else
release_region(config.port_address, 0x0c);
continue;
#endif
}
version_byte = in_byte;
#ifndef PORT_OVERRIDE
break;
}
if (i == ARRAY_SIZE(ultrastor_ports_14f)) {
# if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: no port address found!\n");
# endif
/* all ports probed already released - we can just go straight out */
return FALSE;
}
#endif
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: adapter found at port address %03X\n",
config.port_address);
#endif
/* Set local doorbell mask to disallow bus reset unless
ultrastor_bus_reset is true. */
outb(ultrastor_bus_reset ? 0xc2 : 0x82, LCL_DOORBELL_MASK(config.port_address));
/* All above tests passed, must be the right thing. Get some useful
info. */
/* Register the I/O space that we use */
*(char *)&config_1 = inb(CONFIG(config.port_address + 0));
*(char *)&config_2 = inb(CONFIG(config.port_address + 1));
config.bios_segment = bios_segment_table[config_1.bios_segment];
config.doorbell_address = config.port_address;
config.ogm_address = config.port_address + 0x8;
config.icm_address = config.port_address + 0xC;
config.interrupt = interrupt_table_14f[config_1.interrupt];
config.ha_scsi_id = config_2.ha_scsi_id;
config.heads = mapping_table[config_2.mapping_mode].heads;
config.sectors = mapping_table[config_2.mapping_mode].sectors;
config.bios_drive_number = config_2.bios_drive_number;
config.subversion = (version_byte & 0x0F);
if (config.subversion == U34F)
config.dma_channel = 0;
else
config.dma_channel = dma_channel_table_14f[config_1.dma_channel];
if (!config.bios_segment) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: not detected.\n");
#endif
goto out_release_port;
}
/* Final consistency check, verify previous info. */
if (config.subversion != U34F)
if (!config.dma_channel || !(config_2.tfr_port & 0x2)) {
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: consistency check failed\n");
#endif
goto out_release_port;
}
/* If we were TRULY paranoid, we could issue a host adapter inquiry
command here and verify the data returned. But frankly, I'm
exhausted! */
/* Finally! Now I'm satisfied... */
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US14F: detect: detect succeeded\n"
" Port address: %03X\n"
" BIOS segment: %05X\n"
" Interrupt: %u\n"
" DMA channel: %u\n"
" H/A SCSI ID: %u\n"
" Subversion: %u\n",
config.port_address, config.bios_segment, config.interrupt,
config.dma_channel, config.ha_scsi_id, config.subversion);
#endif
tpnt->this_id = config.ha_scsi_id;
tpnt->unchecked_isa_dma = (config.subversion != U34F);
#if ULTRASTOR_MAX_CMDS > 1
config.mscp_free = ~0;
#endif
/*
* Brrr, &config.mscp[0].SCint->host) it is something magical....
* XXX and FIXME
*/
if (request_irq(config.interrupt, do_ultrastor_interrupt, 0, "Ultrastor", &config.mscp[0].SCint->device->host)) {
printk("Unable to allocate IRQ%u for UltraStor controller.\n",
config.interrupt);
goto out_release_port;
}
if (config.dma_channel && request_dma(config.dma_channel,"Ultrastor")) {
printk("Unable to allocate DMA channel %u for UltraStor controller.\n",
config.dma_channel);
free_irq(config.interrupt, NULL);
goto out_release_port;
}
tpnt->sg_tablesize = ULTRASTOR_14F_MAX_SG;
printk("UltraStor driver version" VERSION ". Using %d SG lists.\n",
ULTRASTOR_14F_MAX_SG);
return TRUE;
out_release_port:
release_region(config.port_address, 0x0c);
return FALSE;
}
static int ultrastor_24f_detect(struct scsi_host_template * tpnt)
{
int i;
struct Scsi_Host * shpnt = NULL;
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US24F: detect");
#endif
/* probe each EISA slot at slot address C80 */
for (i = 1; i < 15; i++)
{
unsigned char config_1, config_2;
unsigned short addr = (i << 12) | ULTRASTOR_24F_PORT;
if (inb(addr) != US24F_PRODUCT_ID_0 &&
inb(addr+1) != US24F_PRODUCT_ID_1 &&
inb(addr+2) != US24F_PRODUCT_ID_2)
continue;
config.revision = inb(addr+3);
config.slot = i;
if (! (inb(addr+4) & 1))
{
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("U24F: found disabled card in slot %u\n", i);
#endif
continue;
}
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("U24F: found card in slot %u\n", i);
#endif
config_1 = inb(addr + 5);
config.bios_segment = bios_segment_table[config_1 & 7];
switch(config_1 >> 4)
{
case 1:
config.interrupt = 15;
break;
case 2:
config.interrupt = 14;
break;
case 4:
config.interrupt = 11;
break;
case 8:
config.interrupt = 10;
break;
default:
printk("U24F: invalid IRQ\n");
return FALSE;
}
/* BIOS addr set */
/* base port set */
config.port_address = addr;
config.doorbell_address = addr + 12;
config.ogm_address = addr + 0x17;
config.icm_address = addr + 0x1C;
config_2 = inb(addr + 7);
config.ha_scsi_id = config_2 & 7;
config.heads = mapping_table[(config_2 >> 3) & 3].heads;
config.sectors = mapping_table[(config_2 >> 3) & 3].sectors;
#if (ULTRASTOR_DEBUG & UD_DETECT)
printk("US24F: detect: detect succeeded\n"
" Port address: %03X\n"
" BIOS segment: %05X\n"
" Interrupt: %u\n"
" H/A SCSI ID: %u\n",
config.port_address, config.bios_segment,
config.interrupt, config.ha_scsi_id);
#endif
tpnt->this_id = config.ha_scsi_id;
tpnt->unchecked_isa_dma = 0;
tpnt->sg_tablesize = ULTRASTOR_24F_MAX_SG;
shpnt = scsi_register(tpnt, 0);
if (!shpnt) {
printk(KERN_WARNING "(ultrastor:) Could not register scsi device. Aborting registration.\n");
free_irq(config.interrupt, do_ultrastor_interrupt);
return FALSE;
}
if (request_irq(config.interrupt, do_ultrastor_interrupt, 0, "Ultrastor", shpnt))
{
printk("Unable to allocate IRQ%u for UltraStor controller.\n",
config.interrupt);
return FALSE;
}
shpnt->irq = config.interrupt;
shpnt->dma_channel = config.dma_channel;
shpnt->io_port = config.port_address;
#if ULTRASTOR_MAX_CMDS > 1
config.mscp_free = ~0;
#endif
/* Mark ICM and OGM free */
outb(0, addr + 0x16);
outb(0, addr + 0x1B);
/* Set local doorbell mask to disallow bus reset unless
ultrastor_bus_reset is true. */
outb(ultrastor_bus_reset ? 0xc2 : 0x82, LCL_DOORBELL_MASK(addr+12));
outb(0x02, SYS_DOORBELL_MASK(addr+12));
printk("UltraStor driver version " VERSION ". Using %d SG lists.\n",
tpnt->sg_tablesize);
return TRUE;
}
return FALSE;
}
static int ultrastor_detect(struct scsi_host_template * tpnt)
{
tpnt->proc_name = "ultrastor";
return ultrastor_14f_detect(tpnt) || ultrastor_24f_detect(tpnt);
}
static int ultrastor_release(struct Scsi_Host *shost)
{
if (shost->irq)
free_irq(shost->irq, NULL);
if (shost->dma_channel != 0xff)
free_dma(shost->dma_channel);
if (shost->io_port && shost->n_io_port)
release_region(shost->io_port, shost->n_io_port);
scsi_unregister(shost);
return 0;
}
static const char *ultrastor_info(struct Scsi_Host * shpnt)
{
static char buf[64];
if (config.slot)
sprintf(buf, "UltraStor 24F SCSI @ Slot %u IRQ%u",
config.slot, config.interrupt);
else if (config.subversion)
sprintf(buf, "UltraStor 34F SCSI @ Port %03X BIOS %05X IRQ%u",
config.port_address, (int)config.bios_segment,
config.interrupt);
else
sprintf(buf, "UltraStor 14F SCSI @ Port %03X BIOS %05X IRQ%u DMA%u",
config.port_address, (int)config.bios_segment,
config.interrupt, config.dma_channel);
return buf;
}
static inline void build_sg_list(struct mscp *mscp, struct scsi_cmnd *SCpnt)
{
struct scatterlist *sg;
long transfer_length = 0;
int i, max;
max = scsi_sg_count(SCpnt);
scsi_for_each_sg(SCpnt, sg, max, i) {
mscp->sglist[i].address = isa_page_to_bus(sg_page(sg)) + sg->offset;
mscp->sglist[i].num_bytes = sg->length;
transfer_length += sg->length;
}
mscp->number_of_sg_list = max;
mscp->transfer_data = isa_virt_to_bus(mscp->sglist);
/* ??? May not be necessary. Docs are unclear as to whether transfer
length field is ignored or whether it should be set to the total
number of bytes of the transfer. */
mscp->transfer_data_length = transfer_length;
}
static int ultrastor_queuecommand_lck(struct scsi_cmnd *SCpnt,
void (*done) (struct scsi_cmnd *))
{
struct mscp *my_mscp;
#if ULTRASTOR_MAX_CMDS > 1
int mscp_index;
#endif
unsigned int status;
/* Next test is for debugging; "can't happen" */
if ((config.mscp_free & ((1U << ULTRASTOR_MAX_CMDS) - 1)) == 0)
panic("ultrastor_queuecommand: no free MSCP\n");
mscp_index = find_and_clear_bit_16(&config.mscp_free);
/* Has the command been aborted? */
if (xchgb(0xff, &config.aborted[mscp_index]) != 0)
{
status = DID_ABORT << 16;
goto aborted;
}
my_mscp = &config.mscp[mscp_index];
*(unsigned char *)my_mscp = OP_SCSI | (DTD_SCSI << 3);
/* Tape drives don't work properly if the cache is used. The SCSI
READ command for a tape doesn't have a block offset, and the adapter
incorrectly assumes that all reads from the tape read the same
blocks. Results will depend on read buffer size and other disk
activity.
??? Which other device types should never use the cache? */
my_mscp->ca = SCpnt->device->type != TYPE_TAPE;
my_mscp->target_id = SCpnt->device->id;
my_mscp->ch_no = 0;
my_mscp->lun = SCpnt->device->lun;
if (scsi_sg_count(SCpnt)) {
/* Set scatter/gather flag in SCSI command packet */
my_mscp->sg = TRUE;
build_sg_list(my_mscp, SCpnt);
} else {
/* Unset scatter/gather flag in SCSI command packet */
my_mscp->sg = FALSE;
my_mscp->transfer_data = isa_virt_to_bus(scsi_sglist(SCpnt));
my_mscp->transfer_data_length = scsi_bufflen(SCpnt);
}
my_mscp->command_link = 0; /*???*/
my_mscp->scsi_command_link_id = 0; /*???*/
my_mscp->length_of_sense_byte = SCSI_SENSE_BUFFERSIZE;
my_mscp->length_of_scsi_cdbs = SCpnt->cmd_len;
memcpy(my_mscp->scsi_cdbs, SCpnt->cmnd, my_mscp->length_of_scsi_cdbs);
my_mscp->adapter_status = 0;
my_mscp->target_status = 0;
my_mscp->sense_data = isa_virt_to_bus(&SCpnt->sense_buffer);
my_mscp->done = done;
my_mscp->SCint = SCpnt;
SCpnt->host_scribble = (unsigned char *)my_mscp;
/* Find free OGM slot. On 24F, look for OGM status byte == 0.
On 14F and 34F, wait for local interrupt pending flag to clear.
FIXME: now we are using new_eh we should punt here and let the
midlayer sort it out */
retry:
if (config.slot)
while (inb(config.ogm_address - 1) != 0 && config.aborted[mscp_index] == 0xff)
barrier();
/* else??? */
while ((inb(LCL_DOORBELL_INTR(config.doorbell_address)) & (config.slot ? 2 : 1)) && config.aborted[mscp_index] == 0xff)
barrier();
/* To avoid race conditions, keep the code to write to the adapter
atomic. This simplifies the abort code. Right now the
scsi mid layer has the host_lock already held
*/
if (inb(LCL_DOORBELL_INTR(config.doorbell_address)) & (config.slot ? 2 : 1))
goto retry;
status = xchgb(0, &config.aborted[mscp_index]);
if (status != 0xff) {
#if ULTRASTOR_DEBUG & (UD_COMMAND | UD_ABORT)
printk("USx4F: queuecommand: aborted\n");
#if ULTRASTOR_MAX_CMDS > 1
log_ultrastor_abort(&config, mscp_index);
#endif
#endif
status <<= 16;
aborted:
set_bit(mscp_index, &config.mscp_free);
/* If the driver queues commands, call the done proc here. Otherwise
return an error. */
#if ULTRASTOR_MAX_CMDS > 1
SCpnt->result = status;
done(SCpnt);
return 0;
#else
return status;
#endif
}
/* Store pointer in OGM address bytes */
outl(isa_virt_to_bus(my_mscp), config.ogm_address);
/* Issue OGM interrupt */
if (config.slot) {
/* Write OGM command register on 24F */
outb(1, config.ogm_address - 1);
outb(0x2, LCL_DOORBELL_INTR(config.doorbell_address));
} else {
outb(0x1, LCL_DOORBELL_INTR(config.doorbell_address));
}
#if (ULTRASTOR_DEBUG & UD_COMMAND)
printk("USx4F: queuecommand: returning\n");
#endif
return 0;
}
static DEF_SCSI_QCMD(ultrastor_queuecommand)
/* This code must deal with 2 cases:
1. The command has not been written to the OGM. In this case, set
the abort flag and return.
2. The command has been written to the OGM and is stuck somewhere in
the adapter.
2a. On a 24F, ask the adapter to abort the command. It will interrupt
when it does.
2b. Call the command's done procedure.
*/
static int ultrastor_abort(struct scsi_cmnd *SCpnt)
{
#if ULTRASTOR_DEBUG & UD_ABORT
char out[108];
unsigned char icm_status = 0, ogm_status = 0;
unsigned int icm_addr = 0, ogm_addr = 0;
#endif
unsigned int mscp_index;
unsigned char old_aborted;
unsigned long flags;
void (*done)(struct scsi_cmnd *);
struct Scsi_Host *host = SCpnt->device->host;
if(config.slot)
return FAILED; /* Do not attempt an abort for the 24f */
/* Simple consistency checking */
if(!SCpnt->host_scribble)
return FAILED;
mscp_index = ((struct mscp *)SCpnt->host_scribble) - config.mscp;
if (mscp_index >= ULTRASTOR_MAX_CMDS)
panic("Ux4F aborting invalid MSCP");
#if ULTRASTOR_DEBUG & UD_ABORT
if (config.slot)
{
int port0 = (config.slot << 12) | 0xc80;
int i;
unsigned long flags;
spin_lock_irqsave(host->host_lock, flags);
strcpy(out, "OGM %d:%x ICM %d:%x ports: ");
for (i = 0; i < 16; i++)
{
unsigned char p = inb(port0 + i);
out[28 + i * 3] = "0123456789abcdef"[p >> 4];
out[29 + i * 3] = "0123456789abcdef"[p & 15];
out[30 + i * 3] = ' ';
}
out[28 + i * 3] = '\n';
out[29 + i * 3] = 0;
ogm_status = inb(port0 + 22);
ogm_addr = (unsigned int)isa_bus_to_virt(inl(port0 + 23));
icm_status = inb(port0 + 27);
icm_addr = (unsigned int)isa_bus_to_virt(inl(port0 + 28));
spin_unlock_irqrestore(host->host_lock, flags);
}
/* First check to see if an interrupt is pending. I suspect the SiS
chipset loses interrupts. (I also suspect is mangles data, but
one bug at a time... */
if (config.slot ? inb(config.icm_address - 1) == 2 :
(inb(SYS_DOORBELL_INTR(config.doorbell_address)) & 1))
{
printk("Ux4F: abort while completed command pending\n");
spin_lock_irqsave(host->host_lock, flags);
/* FIXME: Ewww... need to think about passing host around properly */
ultrastor_interrupt(NULL);
spin_unlock_irqrestore(host->host_lock, flags);
return SUCCESS;
}
#endif
old_aborted = xchgb(DID_ABORT, &config.aborted[mscp_index]);
/* aborted == 0xff is the signal that queuecommand has not yet sent
the command. It will notice the new abort flag and fail. */
if (old_aborted == 0xff)
return SUCCESS;
/* On 24F, send an abort MSCP request. The adapter will interrupt
and the interrupt handler will call done. */
if (config.slot && inb(config.ogm_address - 1) == 0)
{
unsigned long flags;
spin_lock_irqsave(host->host_lock, flags);
outl(isa_virt_to_bus(&config.mscp[mscp_index]), config.ogm_address);
udelay(8);
outb(0x80, config.ogm_address - 1);
outb(0x2, LCL_DOORBELL_INTR(config.doorbell_address));
#if ULTRASTOR_DEBUG & UD_ABORT
log_ultrastor_abort(&config, mscp_index);
printk(out, ogm_status, ogm_addr, icm_status, icm_addr);
#endif
spin_unlock_irqrestore(host->host_lock, flags);
/* FIXME: add a wait for the abort to complete */
return SUCCESS;
}
#if ULTRASTOR_DEBUG & UD_ABORT
log_ultrastor_abort(&config, mscp_index);
#endif
/* Can't request a graceful abort. Either this is not a 24F or
the OGM is busy. Don't free the command -- the adapter might
still be using it. Setting SCint = 0 causes the interrupt
handler to ignore the command. */
/* FIXME - devices that implement soft resets will still be running
the command after a bus reset. We would probably rather leave
the command in the queue. The upper level code will automatically
leave the command in the active state instead of requeueing it. ERY */
#if ULTRASTOR_DEBUG & UD_ABORT
if (config.mscp[mscp_index].SCint != SCpnt)
printk("abort: command mismatch, %p != %p\n",
config.mscp[mscp_index].SCint, SCpnt);
#endif
if (config.mscp[mscp_index].SCint == NULL)
return FAILED;
if (config.mscp[mscp_index].SCint != SCpnt) panic("Bad abort");
config.mscp[mscp_index].SCint = NULL;
done = config.mscp[mscp_index].done;
config.mscp[mscp_index].done = NULL;
SCpnt->result = DID_ABORT << 16;
/* Take the host lock to guard against scsi layer re-entry */
done(SCpnt);
/* Need to set a timeout here in case command never completes. */
return SUCCESS;
}
static int ultrastor_host_reset(struct scsi_cmnd * SCpnt)
{
unsigned long flags;
int i;
struct Scsi_Host *host = SCpnt->device->host;
#if (ULTRASTOR_DEBUG & UD_RESET)
printk("US14F: reset: called\n");
#endif
if(config.slot)
return FAILED;
spin_lock_irqsave(host->host_lock, flags);
/* Reset the adapter and SCSI bus. The SCSI bus reset can be
inhibited by clearing ultrastor_bus_reset before probe. */
outb(0xc0, LCL_DOORBELL_INTR(config.doorbell_address));
if (config.slot)
{
outb(0, config.ogm_address - 1);
outb(0, config.icm_address - 1);
}
#if ULTRASTOR_MAX_CMDS == 1
if (config.mscp_busy && config.mscp->done && config.mscp->SCint)
{
config.mscp->SCint->result = DID_RESET << 16;
config.mscp->done(config.mscp->SCint);
}
config.mscp->SCint = 0;
#else
for (i = 0; i < ULTRASTOR_MAX_CMDS; i++)
{
if (! (config.mscp_free & (1 << i)) &&
config.mscp[i].done && config.mscp[i].SCint)
{
config.mscp[i].SCint->result = DID_RESET << 16;
config.mscp[i].done(config.mscp[i].SCint);
config.mscp[i].done = NULL;
}
config.mscp[i].SCint = NULL;
}
#endif
/* FIXME - if the device implements soft resets, then the command
will still be running. ERY
Even bigger deal with new_eh!
*/
memset((unsigned char *)config.aborted, 0, sizeof config.aborted);
#if ULTRASTOR_MAX_CMDS == 1
config.mscp_busy = 0;
#else
config.mscp_free = ~0;
#endif
spin_unlock_irqrestore(host->host_lock, flags);
return SUCCESS;
}
int ultrastor_biosparam(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int * dkinfo)
{
int size = capacity;
unsigned int s = config.heads * config.sectors;
dkinfo[0] = config.heads;
dkinfo[1] = config.sectors;
dkinfo[2] = size / s; /* Ignore partial cylinders */
#if 0
if (dkinfo[2] > 1024)
dkinfo[2] = 1024;
#endif
return 0;
}
static void ultrastor_interrupt(void *dev_id)
{
unsigned int status;
#if ULTRASTOR_MAX_CMDS > 1
unsigned int mscp_index;
#endif
struct mscp *mscp;
void (*done) (struct scsi_cmnd *);
struct scsi_cmnd *SCtmp;
#if ULTRASTOR_MAX_CMDS == 1
mscp = &config.mscp[0];
#else
mscp = (struct mscp *)isa_bus_to_virt(inl(config.icm_address));
mscp_index = mscp - config.mscp;
if (mscp_index >= ULTRASTOR_MAX_CMDS) {
printk("Ux4F interrupt: bad MSCP address %x\n", (unsigned int) mscp);
/* A command has been lost. Reset and report an error
for all commands. */
ultrastor_host_reset(dev_id);
return;
}
#endif
/* Clean ICM slot (set ICMINT bit to 0) */
if (config.slot) {
unsigned char icm_status = inb(config.icm_address - 1);
#if ULTRASTOR_DEBUG & (UD_INTERRUPT|UD_ERROR|UD_ABORT)
if (icm_status != 1 && icm_status != 2)
printk("US24F: ICM status %x for MSCP %d (%x)\n", icm_status,
mscp_index, (unsigned int) mscp);
#endif
/* The manual says clear interrupt then write 0 to ICM status.
This seems backwards, but I'll do it anyway. --jfc */
outb(2, SYS_DOORBELL_INTR(config.doorbell_address));
outb(0, config.icm_address - 1);
if (icm_status == 4) {
printk("UltraStor abort command failed\n");
return;
}
if (icm_status == 3) {
void (*done)(struct scsi_cmnd *) = mscp->done;
if (done) {
mscp->done = NULL;
mscp->SCint->result = DID_ABORT << 16;
done(mscp->SCint);
}
return;
}
} else {
outb(1, SYS_DOORBELL_INTR(config.doorbell_address));
}
SCtmp = mscp->SCint;
mscp->SCint = NULL;
if (!SCtmp)
{
#if ULTRASTOR_DEBUG & (UD_ABORT|UD_INTERRUPT)
printk("MSCP %d (%x): no command\n", mscp_index, (unsigned int) mscp);
#endif
#if ULTRASTOR_MAX_CMDS == 1
config.mscp_busy = FALSE;
#else
set_bit(mscp_index, &config.mscp_free);
#endif
config.aborted[mscp_index] = 0;
return;
}
/* Save done locally and zero before calling. This is needed as
once we call done, we may get another command queued before this
interrupt service routine can return. */
done = mscp->done;
mscp->done = NULL;
/* Let the higher levels know that we're done */
switch (mscp->adapter_status)
{
case 0:
status = DID_OK << 16;
break;
case 0x01: /* invalid command */
case 0x02: /* invalid parameters */
case 0x03: /* invalid data list */
default:
status = DID_ERROR << 16;
break;
case 0x84: /* SCSI bus abort */
status = DID_ABORT << 16;
break;
case 0x91:
status = DID_TIME_OUT << 16;
break;
}
SCtmp->result = status | mscp->target_status;
SCtmp->host_scribble = NULL;
/* Free up mscp block for next command */
#if ULTRASTOR_MAX_CMDS == 1
config.mscp_busy = FALSE;
#else
set_bit(mscp_index, &config.mscp_free);
#endif
#if ULTRASTOR_DEBUG & (UD_ABORT|UD_INTERRUPT)
if (config.aborted[mscp_index])
printk("Ux4 interrupt: MSCP %d (%x) aborted = %d\n",
mscp_index, (unsigned int) mscp, config.aborted[mscp_index]);
#endif
config.aborted[mscp_index] = 0;
if (done)
done(SCtmp);
else
printk("US14F: interrupt: unexpected interrupt\n");
if (config.slot ? inb(config.icm_address - 1) :
(inb(SYS_DOORBELL_INTR(config.doorbell_address)) & 1))
#if (ULTRASTOR_DEBUG & UD_MULTI_CMD)
printk("Ux4F: multiple commands completed\n");
#else
;
#endif
#if (ULTRASTOR_DEBUG & UD_INTERRUPT)
printk("USx4F: interrupt: returning\n");
#endif
}
static irqreturn_t do_ultrastor_interrupt(int irq, void *dev_id)
{
unsigned long flags;
struct Scsi_Host *dev = dev_id;
spin_lock_irqsave(dev->host_lock, flags);
ultrastor_interrupt(dev_id);
spin_unlock_irqrestore(dev->host_lock, flags);
return IRQ_HANDLED;
}
MODULE_LICENSE("GPL");
static struct scsi_host_template driver_template = {
.name = "UltraStor 14F/24F/34F",
.detect = ultrastor_detect,
.release = ultrastor_release,
.info = ultrastor_info,
.queuecommand = ultrastor_queuecommand,
.eh_abort_handler = ultrastor_abort,
.eh_host_reset_handler = ultrastor_host_reset,
.bios_param = ultrastor_biosparam,
.can_queue = ULTRASTOR_MAX_CMDS,
.sg_tablesize = ULTRASTOR_14F_MAX_SG,
.cmd_per_lun = ULTRASTOR_MAX_CMDS_PER_LUN,
.unchecked_isa_dma = 1,
.use_clustering = ENABLE_CLUSTERING,
};
#include "scsi_module.c"
|
gpl-3.0
|
n5047c/android_kernel_chagall
|
arch/mips/pmc-sierra/msp71xx/msp_irq_cic.c
|
2986
|
5172
|
/*
* Copyright 2010 PMC-Sierra, Inc, derived from irq_cpu.c
*
* This file define the irq handler for MSP CIC subsystem interrupts.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*/
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/bitops.h>
#include <linux/irq.h>
#include <asm/mipsregs.h>
#include <asm/system.h>
#include <msp_cic_int.h>
#include <msp_regs.h>
/*
* External API
*/
extern void msp_per_irq_init(void);
extern void msp_per_irq_dispatch(void);
/*
* Convenience Macro. Should be somewhere generic.
*/
#define get_current_vpe() \
((read_c0_tcbind() >> TCBIND_CURVPE_SHIFT) & TCBIND_CURVPE)
#ifdef CONFIG_SMP
#define LOCK_VPE(flags, mtflags) \
do { \
local_irq_save(flags); \
mtflags = dmt(); \
} while (0)
#define UNLOCK_VPE(flags, mtflags) \
do { \
emt(mtflags); \
local_irq_restore(flags);\
} while (0)
#define LOCK_CORE(flags, mtflags) \
do { \
local_irq_save(flags); \
mtflags = dvpe(); \
} while (0)
#define UNLOCK_CORE(flags, mtflags) \
do { \
evpe(mtflags); \
local_irq_restore(flags);\
} while (0)
#else
#define LOCK_VPE(flags, mtflags)
#define UNLOCK_VPE(flags, mtflags)
#endif
/* ensure writes to cic are completed */
static inline void cic_wmb(void)
{
const volatile void __iomem *cic_mem = CIC_VPE0_MSK_REG;
volatile u32 dummy_read;
wmb();
dummy_read = __raw_readl(cic_mem);
dummy_read++;
}
static void unmask_cic_irq(struct irq_data *d)
{
volatile u32 *cic_msk_reg = CIC_VPE0_MSK_REG;
int vpe;
#ifdef CONFIG_SMP
unsigned int mtflags;
unsigned long flags;
/*
* Make sure we have IRQ affinity. It may have changed while
* we were processing the IRQ.
*/
if (!cpumask_test_cpu(smp_processor_id(), d->affinity))
return;
#endif
vpe = get_current_vpe();
LOCK_VPE(flags, mtflags);
cic_msk_reg[vpe] |= (1 << (d->irq - MSP_CIC_INTBASE));
UNLOCK_VPE(flags, mtflags);
cic_wmb();
}
static void mask_cic_irq(struct irq_data *d)
{
volatile u32 *cic_msk_reg = CIC_VPE0_MSK_REG;
int vpe = get_current_vpe();
#ifdef CONFIG_SMP
unsigned long flags, mtflags;
#endif
LOCK_VPE(flags, mtflags);
cic_msk_reg[vpe] &= ~(1 << (d->irq - MSP_CIC_INTBASE));
UNLOCK_VPE(flags, mtflags);
cic_wmb();
}
static void msp_cic_irq_ack(struct irq_data *d)
{
mask_cic_irq(d);
/*
* Only really necessary for 18, 16-14 and sometimes 3:0
* (since these can be edge sensitive) but it doesn't
* hurt for the others
*/
*CIC_STS_REG = (1 << (d->irq - MSP_CIC_INTBASE));
smtc_im_ack_irq(d->irq);
}
/*Note: Limiting to VSMP . Not tested in SMTC */
#ifdef CONFIG_MIPS_MT_SMP
static int msp_cic_irq_set_affinity(struct irq_data *d,
const struct cpumask *cpumask, bool force)
{
int cpu;
unsigned long flags;
unsigned int mtflags;
unsigned long imask = (1 << (irq - MSP_CIC_INTBASE));
volatile u32 *cic_mask = (volatile u32 *)CIC_VPE0_MSK_REG;
/* timer balancing should be disabled in kernel code */
BUG_ON(irq == MSP_INT_VPE0_TIMER || irq == MSP_INT_VPE1_TIMER);
LOCK_CORE(flags, mtflags);
/* enable if any of each VPE's TCs require this IRQ */
for_each_online_cpu(cpu) {
if (cpumask_test_cpu(cpu, cpumask))
cic_mask[cpu] |= imask;
else
cic_mask[cpu] &= ~imask;
}
UNLOCK_CORE(flags, mtflags);
return 0;
}
#endif
static struct irq_chip msp_cic_irq_controller = {
.name = "MSP_CIC",
.irq_mask = mask_cic_irq,
.irq_mask_ack = msp_cic_irq_ack,
.irq_unmask = unmask_cic_irq,
.irq_ack = msp_cic_irq_ack,
#ifdef CONFIG_MIPS_MT_SMP
.irq_set_affinity = msp_cic_irq_set_affinity,
#endif
};
void __init msp_cic_irq_init(void)
{
int i;
/* Mask/clear interrupts. */
*CIC_VPE0_MSK_REG = 0x00000000;
*CIC_VPE1_MSK_REG = 0x00000000;
*CIC_STS_REG = 0xFFFFFFFF;
/*
* The MSP7120 RG and EVBD boards use IRQ[6:4] for PCI.
* These inputs map to EXT_INT_POL[6:4] inside the CIC.
* They are to be active low, level sensitive.
*/
*CIC_EXT_CFG_REG &= 0xFFFF8F8F;
/* initialize all the IRQ descriptors */
for (i = MSP_CIC_INTBASE ; i < MSP_CIC_INTBASE + 32 ; i++) {
irq_set_chip_and_handler(i, &msp_cic_irq_controller,
handle_level_irq);
#ifdef CONFIG_MIPS_MT_SMTC
/* Mask of CIC interrupt */
irq_hwmask[i] = C_IRQ4;
#endif
}
/* Initialize the PER interrupt sub-system */
msp_per_irq_init();
}
/* CIC masked by CIC vector processing before dispatch called */
void msp_cic_irq_dispatch(void)
{
volatile u32 *cic_msk_reg = (volatile u32 *)CIC_VPE0_MSK_REG;
u32 cic_mask;
u32 pending;
int cic_status = *CIC_STS_REG;
cic_mask = cic_msk_reg[get_current_vpe()];
pending = cic_status & cic_mask;
if (pending & (1 << (MSP_INT_VPE0_TIMER - MSP_CIC_INTBASE))) {
do_IRQ(MSP_INT_VPE0_TIMER);
} else if (pending & (1 << (MSP_INT_VPE1_TIMER - MSP_CIC_INTBASE))) {
do_IRQ(MSP_INT_VPE1_TIMER);
} else if (pending & (1 << (MSP_INT_PER - MSP_CIC_INTBASE))) {
msp_per_irq_dispatch();
} else if (pending) {
do_IRQ(ffs(pending) + MSP_CIC_INTBASE - 1);
} else{
spurious_interrupt();
}
}
|
gpl-3.0
|
marcusrogerio/RedPhone
|
jni/openssl/crypto/rand/randfile.c
|
187
|
9941
|
/* crypto/rand/randfile.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.]
*/
/* We need to define this to get macros like S_IFBLK and S_IFCHR */
#if !defined(OPENSSL_SYS_VXWORKS)
#define _XOPEN_SOURCE 500
#endif
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "e_os.h"
#include <openssl/crypto.h>
#include <openssl/rand.h>
#include <openssl/buffer.h>
#ifdef OPENSSL_SYS_VMS
#include <unixio.h>
#endif
#ifndef NO_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifndef OPENSSL_NO_POSIX_IO
# include <sys/stat.h>
#endif
#ifdef _WIN32
#define stat _stat
#define chmod _chmod
#define open _open
#define fdopen _fdopen
#endif
#undef BUFSIZE
#define BUFSIZE 1024
#define RAND_DATA 1024
#ifdef OPENSSL_SYS_VMS
/* This declaration is a nasty hack to get around vms' extension to fopen
* for passing in sharing options being disabled by our /STANDARD=ANSI89 */
static FILE *(*const vms_fopen)(const char *, const char *, ...) =
(FILE *(*)(const char *, const char *, ...))fopen;
#define VMS_OPEN_ATTRS "shr=get,put,upd,del","ctx=bin,stm","rfm=stm","rat=none","mrs=0"
#endif
/* #define RFILE ".rnd" - defined in ../../e_os.h */
/* Note that these functions are intended for seed files only.
* Entropy devices and EGD sockets are handled in rand_unix.c */
int RAND_load_file(const char *file, long bytes)
{
/* If bytes >= 0, read up to 'bytes' bytes.
* if bytes == -1, read complete file. */
MS_STATIC unsigned char buf[BUFSIZE];
#ifndef OPENSSL_NO_POSIX_IO
struct stat sb;
#endif
int i,ret=0,n;
FILE *in;
if (file == NULL) return(0);
#ifndef OPENSSL_NO_POSIX_IO
#ifdef PURIFY
/* struct stat can have padding and unused fields that may not be
* initialized in the call to stat(). We need to clear the entire
* structure before calling RAND_add() to avoid complaints from
* applications such as Valgrind.
*/
memset(&sb, 0, sizeof(sb));
#endif
if (stat(file,&sb) < 0) return(0);
RAND_add(&sb,sizeof(sb),0.0);
#endif
if (bytes == 0) return(ret);
#ifdef OPENSSL_SYS_VMS
in=vms_fopen(file,"rb",VMS_OPEN_ATTRS);
#else
in=fopen(file,"rb");
#endif
if (in == NULL) goto err;
#if defined(S_IFBLK) && defined(S_IFCHR) && !defined(OPENSSL_NO_POSIX_IO)
if (sb.st_mode & (S_IFBLK | S_IFCHR)) {
/* this file is a device. we don't want read an infinite number
* of bytes from a random device, nor do we want to use buffered
* I/O because we will waste system entropy.
*/
bytes = (bytes == -1) ? 2048 : bytes; /* ok, is 2048 enough? */
#ifndef OPENSSL_NO_SETVBUF_IONBF
setvbuf(in, NULL, _IONBF, 0); /* don't do buffered reads */
#endif /* ndef OPENSSL_NO_SETVBUF_IONBF */
}
#endif
for (;;)
{
if (bytes > 0)
n = (bytes < BUFSIZE)?(int)bytes:BUFSIZE;
else
n = BUFSIZE;
i=fread(buf,1,n,in);
if (i <= 0) break;
#ifdef PURIFY
RAND_add(buf,i,(double)i);
#else
/* even if n != i, use the full array */
RAND_add(buf,n,(double)i);
#endif
ret+=i;
if (bytes > 0)
{
bytes-=n;
if (bytes <= 0) break;
}
}
fclose(in);
OPENSSL_cleanse(buf,BUFSIZE);
err:
return(ret);
}
int RAND_write_file(const char *file)
{
unsigned char buf[BUFSIZE];
int i,ret=0,rand_err=0;
FILE *out = NULL;
int n;
#ifndef OPENSSL_NO_POSIX_IO
struct stat sb;
i=stat(file,&sb);
if (i != -1) {
#if defined(S_ISBLK) && defined(S_ISCHR)
if (S_ISBLK(sb.st_mode) || S_ISCHR(sb.st_mode)) {
/* this file is a device. we don't write back to it.
* we "succeed" on the assumption this is some sort
* of random device. Otherwise attempting to write to
* and chmod the device causes problems.
*/
return(1);
}
#endif
}
#endif
#if defined(O_CREAT) && !defined(OPENSSL_NO_POSIX_IO) && !defined(OPENSSL_SYS_VMS)
{
#ifndef O_BINARY
#define O_BINARY 0
#endif
/* chmod(..., 0600) is too late to protect the file,
* permissions should be restrictive from the start */
int fd = open(file, O_WRONLY|O_CREAT|O_BINARY, 0600);
if (fd != -1)
out = fdopen(fd, "wb");
}
#endif
#ifdef OPENSSL_SYS_VMS
/* VMS NOTE: Prior versions of this routine created a _new_
* version of the rand file for each call into this routine, then
* deleted all existing versions named ;-1, and finally renamed
* the current version as ';1'. Under concurrent usage, this
* resulted in an RMS race condition in rename() which could
* orphan files (see vms message help for RMS$_REENT). With the
* fopen() calls below, openssl/VMS now shares the top-level
* version of the rand file. Note that there may still be
* conditions where the top-level rand file is locked. If so, this
* code will then create a new version of the rand file. Without
* the delete and rename code, this can result in ascending file
* versions that stop at version 32767, and this routine will then
* return an error. The remedy for this is to recode the calling
* application to avoid concurrent use of the rand file, or
* synchronize usage at the application level. Also consider
* whether or not you NEED a persistent rand file in a concurrent
* use situation.
*/
out = vms_fopen(file,"rb+",VMS_OPEN_ATTRS);
if (out == NULL)
out = vms_fopen(file,"wb",VMS_OPEN_ATTRS);
#else
if (out == NULL)
out = fopen(file,"wb");
#endif
if (out == NULL) goto err;
#ifndef NO_CHMOD
chmod(file,0600);
#endif
n=RAND_DATA;
for (;;)
{
i=(n > BUFSIZE)?BUFSIZE:n;
n-=BUFSIZE;
if (RAND_bytes(buf,i) <= 0)
rand_err=1;
i=fwrite(buf,1,i,out);
if (i <= 0)
{
ret=0;
break;
}
ret+=i;
if (n <= 0) break;
}
fclose(out);
OPENSSL_cleanse(buf,BUFSIZE);
err:
return (rand_err ? -1 : ret);
}
const char *RAND_file_name(char *buf, size_t size)
{
char *s=NULL;
#ifdef __OpenBSD__
struct stat sb;
#endif
if (OPENSSL_issetugid() == 0)
s=getenv("RANDFILE");
if (s != NULL && *s && strlen(s) + 1 < size)
{
if (BUF_strlcpy(buf,s,size) >= size)
return NULL;
}
else
{
if (OPENSSL_issetugid() == 0)
s=getenv("HOME");
#ifdef DEFAULT_HOME
if (s == NULL)
{
s = DEFAULT_HOME;
}
#endif
if (s && *s && strlen(s)+strlen(RFILE)+2 < size)
{
BUF_strlcpy(buf,s,size);
#ifndef OPENSSL_SYS_VMS
BUF_strlcat(buf,"/",size);
#endif
BUF_strlcat(buf,RFILE,size);
}
else
buf[0] = '\0'; /* no file name */
}
#ifdef __OpenBSD__
/* given that all random loads just fail if the file can't be
* seen on a stat, we stat the file we're returning, if it
* fails, use /dev/arandom instead. this allows the user to
* use their own source for good random data, but defaults
* to something hopefully decent if that isn't available.
*/
if (!buf[0])
if (BUF_strlcpy(buf,"/dev/arandom",size) >= size) {
return(NULL);
}
if (stat(buf,&sb) == -1)
if (BUF_strlcpy(buf,"/dev/arandom",size) >= size) {
return(NULL);
}
#endif
return(buf);
}
|
gpl-3.0
|
monkbroc/firmware
|
communication/lib/mbedtls/library/padlock.c
|
453
|
4804
|
/*
* VIA PadLock support functions
*
* Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
* SPDX-License-Identifier: Apache-2.0
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* This file is part of mbed TLS (https://tls.mbed.org)
*/
/*
* This implementation is based on the VIA PadLock Programming Guide:
*
* http://www.via.com.tw/en/downloads/whitepapers/initiatives/padlock/
* programming_guide.pdf
*/
#if !defined(MBEDTLS_CONFIG_FILE)
#include "mbedtls/config.h"
#else
#include MBEDTLS_CONFIG_FILE
#endif
#if defined(MBEDTLS_PADLOCK_C)
#include "mbedtls/padlock.h"
#include <string.h>
#ifndef asm
#define asm __asm
#endif
#if defined(MBEDTLS_HAVE_X86)
/*
* PadLock detection routine
*/
int mbedtls_padlock_has_support( int feature )
{
static int flags = -1;
int ebx = 0, edx = 0;
if( flags == -1 )
{
asm( "movl %%ebx, %0 \n\t"
"movl $0xC0000000, %%eax \n\t"
"cpuid \n\t"
"cmpl $0xC0000001, %%eax \n\t"
"movl $0, %%edx \n\t"
"jb unsupported \n\t"
"movl $0xC0000001, %%eax \n\t"
"cpuid \n\t"
"unsupported: \n\t"
"movl %%edx, %1 \n\t"
"movl %2, %%ebx \n\t"
: "=m" (ebx), "=m" (edx)
: "m" (ebx)
: "eax", "ecx", "edx" );
flags = edx;
}
return( flags & feature );
}
/*
* PadLock AES-ECB block en(de)cryption
*/
int mbedtls_padlock_xcryptecb( mbedtls_aes_context *ctx,
int mode,
const unsigned char input[16],
unsigned char output[16] )
{
int ebx = 0;
uint32_t *rk;
uint32_t *blk;
uint32_t *ctrl;
unsigned char buf[256];
rk = ctx->rk;
blk = MBEDTLS_PADLOCK_ALIGN16( buf );
memcpy( blk, input, 16 );
ctrl = blk + 4;
*ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode^1 ) - 10 ) << 9 );
asm( "pushfl \n\t"
"popfl \n\t"
"movl %%ebx, %0 \n\t"
"movl $1, %%ecx \n\t"
"movl %2, %%edx \n\t"
"movl %3, %%ebx \n\t"
"movl %4, %%esi \n\t"
"movl %4, %%edi \n\t"
".byte 0xf3,0x0f,0xa7,0xc8 \n\t"
"movl %1, %%ebx \n\t"
: "=m" (ebx)
: "m" (ebx), "m" (ctrl), "m" (rk), "m" (blk)
: "memory", "ecx", "edx", "esi", "edi" );
memcpy( output, blk, 16 );
return( 0 );
}
/*
* PadLock AES-CBC buffer en(de)cryption
*/
int mbedtls_padlock_xcryptcbc( mbedtls_aes_context *ctx,
int mode,
size_t length,
unsigned char iv[16],
const unsigned char *input,
unsigned char *output )
{
int ebx = 0;
size_t count;
uint32_t *rk;
uint32_t *iw;
uint32_t *ctrl;
unsigned char buf[256];
if( ( (long) input & 15 ) != 0 ||
( (long) output & 15 ) != 0 )
return( MBEDTLS_ERR_PADLOCK_DATA_MISALIGNED );
rk = ctx->rk;
iw = MBEDTLS_PADLOCK_ALIGN16( buf );
memcpy( iw, iv, 16 );
ctrl = iw + 4;
*ctrl = 0x80 | ctx->nr | ( ( ctx->nr + ( mode ^ 1 ) - 10 ) << 9 );
count = ( length + 15 ) >> 4;
asm( "pushfl \n\t"
"popfl \n\t"
"movl %%ebx, %0 \n\t"
"movl %2, %%ecx \n\t"
"movl %3, %%edx \n\t"
"movl %4, %%ebx \n\t"
"movl %5, %%esi \n\t"
"movl %6, %%edi \n\t"
"movl %7, %%eax \n\t"
".byte 0xf3,0x0f,0xa7,0xd0 \n\t"
"movl %1, %%ebx \n\t"
: "=m" (ebx)
: "m" (ebx), "m" (count), "m" (ctrl),
"m" (rk), "m" (input), "m" (output), "m" (iw)
: "memory", "eax", "ecx", "edx", "esi", "edi" );
memcpy( iv, iw, 16 );
return( 0 );
}
#endif /* MBEDTLS_HAVE_X86 */
#endif /* MBEDTLS_PADLOCK_C */
|
gpl-3.0
|
pokowaka/atreus-firmware
|
tmk/tmk_core/tool/mbed/mbed-sdk/libraries/USBDevice/USBDevice/TARGET_RENESAS/TARGET_RZ_A1H/usb0/src/function/usb0_function_sub.c
|
200
|
17531
|
/*******************************************************************************
* DISCLAIMER
* This software is supplied by Renesas Electronics Corporation and is only
* intended for use with Renesas products. No other uses are authorized. This
* software is owned by Renesas Electronics Corporation and is protected under
* all applicable laws, including copyright laws.
* THIS SOFTWARE IS PROVIDED "AS IS" AND RENESAS MAKES NO WARRANTIES REGARDING
* THIS SOFTWARE, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING BUT NOT
* LIMITED TO WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE
* AND NON-INFRINGEMENT. ALL SUCH WARRANTIES ARE EXPRESSLY DISCLAIMED.
* TO THE MAXIMUM EXTENT PERMITTED NOT PROHIBITED BY LAW, NEITHER RENESAS
* ELECTRONICS CORPORATION NOR ANY OF ITS AFFILIATED COMPANIES SHALL BE LIABLE
* FOR ANY DIRECT, INDIRECT, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES FOR
* ANY REASON RELATED TO THIS SOFTWARE, EVEN IF RENESAS OR ITS AFFILIATES HAVE
* BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
* Renesas reserves the right, without notice, to make changes to this software
* and to discontinue the availability of this software. By using this software,
* you agree to the additional terms and conditions found by accessing the
* following link:
* http://www.renesas.com/disclaimer
* Copyright (C) 2012 - 2014 Renesas Electronics Corporation. All rights reserved.
*******************************************************************************/
/*******************************************************************************
* File Name : usb0_function_sub.c
* $Rev: 1116 $
* $Date:: 2014-07-09 16:29:19 +0900#$
* Device(s) : RZ/A1H
* Tool-Chain :
* OS : None
* H/W Platform :
* Description : RZ/A1H R7S72100 USB Sample Program
* Operation :
* Limitations :
*******************************************************************************/
/*******************************************************************************
Includes <System Includes> , "Project Includes"
*******************************************************************************/
#include "usb0_function.h"
/*******************************************************************************
Typedef definitions
*******************************************************************************/
/*******************************************************************************
Macro definitions
*******************************************************************************/
/*******************************************************************************
Imported global variables and functions (from other files)
*******************************************************************************/
#if 0
extern const uint16_t *g_usb0_function_EndPntPtr[];
extern uint8_t g_usb0_function_DeviceDescriptor[];
extern uint8_t *g_usb0_function_ConfigurationPtr[];
#endif
/*******************************************************************************
Exported global variables and functions (to be accessed by other files)
*******************************************************************************/
/*******************************************************************************
Private global variables and functions
*******************************************************************************/
/*******************************************************************************
* Function Name: usb0_function_ResetDCP
* Description : Initializes the default control pipe(DCP).
* Outline : Reset default control pipe
* Arguments : none
* Return Value : none
*******************************************************************************/
void usb0_function_ResetDCP (void)
{
USB200.DCPCFG = 0;
#if 0
USB200.DCPMAXP = g_usb0_function_DeviceDescriptor[7];
#else
USB200.DCPMAXP = 64;
#endif
USB200.CFIFOSEL = (uint16_t)(USB_FUNCTION_BITMBW_8 | USB_FUNCTION_BITBYTE_LITTLE);
USB200.D0FIFOSEL = (uint16_t)(USB_FUNCTION_BITMBW_8 | USB_FUNCTION_BITBYTE_LITTLE);
USB200.D1FIFOSEL = (uint16_t)(USB_FUNCTION_BITMBW_8 | USB_FUNCTION_BITBYTE_LITTLE);
}
/*******************************************************************************
* Function Name: usb0_function_ResetEP
* Description : Initializes the end point.
* Arguments : uint16_t num ; Configuration Number
* Return Value : none
*******************************************************************************/
#if 0
void usb0_function_ResetEP (uint16_t num)
{
uint16_t pipe;
uint16_t ep;
uint16_t index;
uint16_t buf;
uint16_t * tbl;
tbl = (uint16_t *)(g_usb0_function_EndPntPtr[num - 1]);
for (ep = 1; ep <= USB_FUNCTION_MAX_EP_NO; ++ep)
{
if (g_usb0_function_EPTableIndex[ep] != USB_FUNCTION_EP_ERROR)
{
index = (uint16_t)(USB_FUNCTION_EPTABLE_LENGTH * g_usb0_function_EPTableIndex[ep]);
pipe = (uint16_t)(tbl[index + 0] & USB_FUNCTION_BITCURPIPE);
g_usb0_function_PipeTbl[pipe] = (uint16_t)( ((tbl[index + 1] & USB_FUNCTION_DIRFIELD) << 3) |
ep |
(tbl[index + 0] & USB_FUNCTION_FIFO_USE) );
if ((tbl[index + 1] & USB_FUNCTION_DIRFIELD) == USB_FUNCTION_DIR_P_OUT)
{
tbl[index + 1] |= USB_FUNCTION_SHTNAKON;
#ifdef __USB_DMA_BFRE_ENABLE__
/* this routine cannnot be perfomred if read operation is executed in buffer size */
if (((tbl[index + 0] & USB_FUNCTION_FIFO_USE) == USB_FUNCTION_D0FIFO_DMA) ||
((tbl[index + 0] & USB_FUNCTION_FIFO_USE) == USB_FUNCTION_D1FIFO_DMA))
{
tbl[index + 1] |= USB_FUNCTION_BFREON;
}
#endif
}
/* Interrupt Disable */
buf = USB200.BRDYENB;
buf &= (uint16_t)~g_usb0_function_bit_set[pipe];
USB200.BRDYENB = buf;
buf = USB200.NRDYENB;
buf &= (uint16_t)~g_usb0_function_bit_set[pipe];
USB200.NRDYENB = buf;
buf = USB200.BEMPENB;
buf &= (uint16_t)~g_usb0_function_bit_set[pipe];
USB200.BEMPENB = buf;
usb0_function_set_pid_nak(pipe);
/* CurrentPIPE Clear */
if (RZA_IO_RegRead_16(&USB200.CFIFOSEL,
USB_CFIFOSEL_CURPIPE_SHIFT,
USB_CFIFOSEL_CURPIPE) == pipe)
{
RZA_IO_RegWrite_16(&USB200.CFIFOSEL,
0,
USB_CFIFOSEL_CURPIPE_SHIFT,
USB_CFIFOSEL_CURPIPE);
}
if (RZA_IO_RegRead_16(&USB200.D0FIFOSEL,
USB_DnFIFOSEL_CURPIPE_SHIFT,
USB_DnFIFOSEL_CURPIPE) == pipe)
{
RZA_IO_RegWrite_16(&USB200.D0FIFOSEL,
0,
USB_DnFIFOSEL_CURPIPE_SHIFT,
USB_DnFIFOSEL_CURPIPE);
}
if (RZA_IO_RegRead_16(&USB200.D1FIFOSEL,
USB_DnFIFOSEL_CURPIPE_SHIFT,
USB_DnFIFOSEL_CURPIPE) == pipe)
{
RZA_IO_RegWrite_16(&USB200.D1FIFOSEL,
0,
USB_DnFIFOSEL_CURPIPE_SHIFT,
USB_DnFIFOSEL_CURPIPE);
}
/* PIPE Configuration */
USB200.PIPESEL = pipe;
USB200.PIPECFG = tbl[index + 1];
USB200.PIPEBUF = tbl[index + 2];
USB200.PIPEMAXP = tbl[index + 3];
USB200.PIPEPERI = tbl[index + 4];
g_usb0_function_pipecfg[pipe] = tbl[index + 1];
g_usb0_function_pipebuf[pipe] = tbl[index + 2];
g_usb0_function_pipemaxp[pipe] = tbl[index + 3];
g_usb0_function_pipeperi[pipe] = tbl[index + 4];
/* Buffer Clear */
usb0_function_set_sqclr(pipe);
usb0_function_aclrm(pipe);
/* init Global */
g_usb0_function_pipe_status[pipe] = DEVDRV_USBF_PIPE_IDLE;
g_usb0_function_PipeDataSize[pipe] = 0;
}
}
}
#endif
/*******************************************************************************
* Function Name: usb0_function_EpToPipe
* Description : Returns the pipe which end point specified by the argument is
* : allocated to.
* Arguments : uint16_t ep ; Direction + Endpoint Number
* Return Value : USB_FUNCTION_EP_ERROR : Error
* : Others : Pipe Number
*******************************************************************************/
uint16_t usb0_function_EpToPipe (uint16_t ep)
{
uint16_t pipe;
for (pipe = 1; pipe <= USB_FUNCTION_MAX_PIPE_NO; pipe++)
{
if ((g_usb0_function_PipeTbl[pipe] & 0x00ff) == ep)
{
return pipe;
}
}
return USB_FUNCTION_EP_ERROR;
}
/*******************************************************************************
* Function Name: usb0_function_InitEPTable
* Description : Sets the end point by the Alternate setting value of the
* : configuration number and the interface number specified by the
* : argument.
* Arguments : uint16_t Con_Num ; Configuration Number
* : uint16_t Int_Num ; Interface Number
* : uint16_t Alt_Num ; Alternate Setting
* Return Value : none
*******************************************************************************/
#if 0
void usb0_function_InitEPTable (uint16_t Con_Num, uint16_t Int_Num, uint16_t Alt_Num)
{
uint8_t * ptr;
uint16_t point_interface;
uint16_t point_endpoint;
uint16_t length;
uint16_t start;
uint16_t numbers;
uint16_t endpoint;
ptr = (uint8_t *)g_usb0_function_ConfigurationPtr[Con_Num - 1];
point_interface = *ptr;
length = (uint16_t)((uint16_t)*(ptr + 3) << 8 | (uint16_t)*(ptr + 2));
ptr += *ptr;
start = 0;
numbers = 0;
point_endpoint = 0;
for (; point_interface < length;)
{
switch (*(ptr + 1)) /* Descriptor Type ? */
{
case USB_FUNCTION_DT_INTERFACE: /* Interface */
if ((*(ptr + 2) == Int_Num) && (*(ptr + 3) == Alt_Num))
{
numbers = *(ptr + 4);
}
else
{
start += *(ptr + 4);
}
point_interface += *ptr;
ptr += *ptr;
break;
case USB_FUNCTION_DT_ENDPOINT: /* Endpoint */
if (point_endpoint < numbers)
{
endpoint = (uint16_t)(*(ptr + 2) & 0x0f);
g_usb0_function_EPTableIndex[endpoint] = (uint16_t)(start + point_endpoint);
++point_endpoint;
}
point_interface += *ptr;
ptr += *ptr;
break;
case USB_FUNCTION_DT_DEVICE: /* Device */
case USB_FUNCTION_DT_CONFIGURATION: /* Configuration */
case USB_FUNCTION_DT_STRING: /* String */
default: /* Class, Vendor, else */
point_interface += *ptr;
ptr += *ptr;
break;
}
}
}
#endif
/*******************************************************************************
* Function Name: usb0_function_GetConfigNum
* Description : Returns the number of configuration referring to the number of
* : configuration described in the device descriptor.
* Arguments : none
* Return Value : Number of possible configurations (bNumConfigurations).
*******************************************************************************/
#if 0
uint16_t usb0_function_GetConfigNum (void)
{
return (uint16_t)g_usb0_function_DeviceDescriptor[17];
}
#endif
/*******************************************************************************
* Function Name: usb0_function_GetInterfaceNum
* Description : Returns the number of interface referring to the number of
* : interface described in the configuration descriptor.
* Arguments : uint16_t num ; Configuration Number
* Return Value : Number of this interface (bNumInterfaces).
*******************************************************************************/
#if 0
uint16_t usb0_function_GetInterfaceNum (uint16_t num)
{
return (uint16_t)(*(g_usb0_function_ConfigurationPtr[num - 1] + 4));
}
#endif
/*******************************************************************************
* Function Name: usb0_function_GetAltNum
* Description : Returns the Alternate setting value of the configuration number
* : and the interface number specified by the argument.
* Arguments : uint16_t Con_Num ; Configuration Number
* : uint16_t Int_Num ; Interface Number
* Return Value : Value used to select this alternate setting(bAlternateSetting).
*******************************************************************************/
#if 0
uint16_t usb0_function_GetAltNum (uint16_t Con_Num, uint16_t Int_Num)
{
uint8_t * ptr;
uint16_t point;
uint16_t alt_num = 0;
uint16_t length;
ptr = (uint8_t *)(g_usb0_function_ConfigurationPtr[Con_Num - 1]);
point = ptr[0];
ptr += ptr[0]; /* InterfaceDescriptor[0] */
length = (uint16_t)(*(g_usb0_function_ConfigurationPtr[Con_Num - 1] + 2));
length |= (uint16_t)((uint16_t)(*(g_usb0_function_ConfigurationPtr[Con_Num - 1] + 3)) << 8);
for (; point < length;) /* Search Descriptor Table size */
{
switch (ptr[1]) /* Descriptor Type ? */
{
case USB_FUNCTION_DT_INTERFACE: /* Interface */
if (Int_Num == ptr[2])
{
alt_num = (uint16_t)ptr[3]; /* Alternate Number count */
}
point += ptr[0];
ptr += ptr[0];
break;
case USB_FUNCTION_DT_DEVICE: /* Device */
case USB_FUNCTION_DT_CONFIGURATION: /* Configuration */
case USB_FUNCTION_DT_STRING: /* String */
case USB_FUNCTION_DT_ENDPOINT: /* Endpoint */
default: /* Class, Vendor, else */
point += ptr[0];
ptr += ptr[0];
break;
}
}
return alt_num;
}
#endif
/*******************************************************************************
* Function Name: usb0_function_CheckRemoteWakeup
* Description : Returns the result of the remote wake up function is supported
* : or not referring to the configuration descriptor.
* Arguments : none
* Return Value : DEVDRV_USBF_ON : Support Remote Wakeup
* : DEVDRV_USBF_OFF : not Support Remote Wakeup
*******************************************************************************/
#if 0
uint16_t usb0_function_CheckRemoteWakeup (void)
{
uint8_t atr;
if (g_usb0_function_ConfigNum == 0)
{
return DEVDRV_USBF_OFF;
}
atr = *(g_usb0_function_ConfigurationPtr[g_usb0_function_ConfigNum - 1] + 7);
if (atr & USB_FUNCTION_CF_RWUP)
{
return DEVDRV_USBF_ON;
}
return DEVDRV_USBF_OFF;
}
#endif
/*******************************************************************************
* Function Name: usb0_function_clear_alt
* Description : Initializes the Alternate setting area.
* Arguments : none
* Return Value : none
*******************************************************************************/
#if 0
void usb0_function_clear_alt (void)
{
int i;
for (i = 0; i < USB_FUNCTION_ALT_NO; ++i)
{
g_usb0_function_Alternate[i] = 0; /* Alternate */
}
}
#endif
/*******************************************************************************
* Function Name: usb0_function_clear_pipe_tbl
* Description : Initializes pipe definition table.
* Arguments : none
* Return Value : none
*******************************************************************************/
void usb0_function_clear_pipe_tbl (void)
{
int pipe;
for (pipe = 0; pipe < (USB_FUNCTION_MAX_PIPE_NO + 1); ++pipe)
{
g_usb0_function_PipeTbl[pipe] = 0;
}
}
/*******************************************************************************
* Function Name: usb0_function_clear_ep_table_index
* Description : Initializes the end point table index.
* Arguments : none
* Return Value : none
*******************************************************************************/
#if 0
void usb0_function_clear_ep_table_index (void)
{
int ep;
for (ep = 0; ep <= USB_FUNCTION_MAX_EP_NO; ++ep)
{
g_usb0_function_EPTableIndex[ep] = USB_FUNCTION_EP_ERROR;
}
}
#endif
/* End of File */
|
gpl-3.0
|
awid777/android_kernel_htc_k2-CM
|
drivers/net/wireless/brcm80211/brcmfmac/dhd_cdc.c
|
4818
|
12735
|
/*
* Copyright (c) 2010 Broadcom Corporation
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
/*******************************************************************************
* Communicates with the dongle by using dcmd codes.
* For certain dcmd codes, the dongle interprets string data from the host.
******************************************************************************/
#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
#include <linux/types.h>
#include <linux/netdevice.h>
#include <linux/sched.h>
#include <defs.h>
#include <brcmu_utils.h>
#include <brcmu_wifi.h>
#include "dhd.h"
#include "dhd_proto.h"
#include "dhd_bus.h"
#include "dhd_dbg.h"
struct brcmf_proto_cdc_dcmd {
__le32 cmd; /* dongle command value */
__le32 len; /* lower 16: output buflen;
* upper 16: input buflen (excludes header) */
__le32 flags; /* flag defns given below */
__le32 status; /* status code returned from the device */
};
/* Max valid buffer size that can be sent to the dongle */
#define CDC_MAX_MSG_SIZE (ETH_FRAME_LEN+ETH_FCS_LEN)
/* CDC flag definitions */
#define CDC_DCMD_ERROR 0x01 /* 1=cmd failed */
#define CDC_DCMD_SET 0x02 /* 0=get, 1=set cmd */
#define CDC_DCMD_IF_MASK 0xF000 /* I/F index */
#define CDC_DCMD_IF_SHIFT 12
#define CDC_DCMD_ID_MASK 0xFFFF0000 /* id an cmd pairing */
#define CDC_DCMD_ID_SHIFT 16 /* ID Mask shift bits */
#define CDC_DCMD_ID(flags) \
(((flags) & CDC_DCMD_ID_MASK) >> CDC_DCMD_ID_SHIFT)
/*
* BDC header - Broadcom specific extension of CDC.
* Used on data packets to convey priority across USB.
*/
#define BDC_HEADER_LEN 4
#define BDC_PROTO_VER 2 /* Protocol version */
#define BDC_FLAG_VER_MASK 0xf0 /* Protocol version mask */
#define BDC_FLAG_VER_SHIFT 4 /* Protocol version shift */
#define BDC_FLAG_SUM_GOOD 0x04 /* Good RX checksums */
#define BDC_FLAG_SUM_NEEDED 0x08 /* Dongle needs to do TX checksums */
#define BDC_PRIORITY_MASK 0x7
#define BDC_FLAG2_IF_MASK 0x0f /* packet rx interface in APSTA */
#define BDC_FLAG2_IF_SHIFT 0
#define BDC_GET_IF_IDX(hdr) \
((int)((((hdr)->flags2) & BDC_FLAG2_IF_MASK) >> BDC_FLAG2_IF_SHIFT))
#define BDC_SET_IF_IDX(hdr, idx) \
((hdr)->flags2 = (((hdr)->flags2 & ~BDC_FLAG2_IF_MASK) | \
((idx) << BDC_FLAG2_IF_SHIFT)))
struct brcmf_proto_bdc_header {
u8 flags;
u8 priority; /* 802.1d Priority, 4:7 flow control info for usb */
u8 flags2;
u8 data_offset;
};
#define RETRIES 2 /* # of retries to retrieve matching dcmd response */
#define BUS_HEADER_LEN (16+64) /* Must be atleast SDPCM_RESERVE
* (amount of header tha might be added)
* plus any space that might be needed
* for bus alignment padding.
*/
#define ROUND_UP_MARGIN 2048 /* Biggest bus block size possible for
* round off at the end of buffer
* Currently is SDIO
*/
struct brcmf_proto {
u16 reqid;
u8 pending;
u32 lastcmd;
u8 bus_header[BUS_HEADER_LEN];
struct brcmf_proto_cdc_dcmd msg;
unsigned char buf[BRCMF_DCMD_MAXLEN + ROUND_UP_MARGIN];
};
static int brcmf_proto_cdc_msg(struct brcmf_pub *drvr)
{
struct brcmf_proto *prot = drvr->prot;
int len = le32_to_cpu(prot->msg.len) +
sizeof(struct brcmf_proto_cdc_dcmd);
brcmf_dbg(TRACE, "Enter\n");
/* NOTE : cdc->msg.len holds the desired length of the buffer to be
* returned. Only up to CDC_MAX_MSG_SIZE of this buffer area
* is actually sent to the dongle
*/
if (len > CDC_MAX_MSG_SIZE)
len = CDC_MAX_MSG_SIZE;
/* Send request */
return drvr->bus_if->brcmf_bus_txctl(drvr->dev,
(unsigned char *)&prot->msg,
len);
}
static int brcmf_proto_cdc_cmplt(struct brcmf_pub *drvr, u32 id, u32 len)
{
int ret;
struct brcmf_proto *prot = drvr->prot;
brcmf_dbg(TRACE, "Enter\n");
do {
ret = drvr->bus_if->brcmf_bus_rxctl(drvr->dev,
(unsigned char *)&prot->msg,
len + sizeof(struct brcmf_proto_cdc_dcmd));
if (ret < 0)
break;
} while (CDC_DCMD_ID(le32_to_cpu(prot->msg.flags)) != id);
return ret;
}
int
brcmf_proto_cdc_query_dcmd(struct brcmf_pub *drvr, int ifidx, uint cmd,
void *buf, uint len)
{
struct brcmf_proto *prot = drvr->prot;
struct brcmf_proto_cdc_dcmd *msg = &prot->msg;
void *info;
int ret = 0, retries = 0;
u32 id, flags;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CTL, "cmd %d len %d\n", cmd, len);
/* Respond "bcmerror" and "bcmerrorstr" with local cache */
if (cmd == BRCMF_C_GET_VAR && buf) {
if (!strcmp((char *)buf, "bcmerrorstr")) {
strncpy((char *)buf, "bcm_error",
BCME_STRLEN);
goto done;
} else if (!strcmp((char *)buf, "bcmerror")) {
*(int *)buf = drvr->dongle_error;
goto done;
}
}
memset(msg, 0, sizeof(struct brcmf_proto_cdc_dcmd));
msg->cmd = cpu_to_le32(cmd);
msg->len = cpu_to_le32(len);
flags = (++prot->reqid << CDC_DCMD_ID_SHIFT);
flags = (flags & ~CDC_DCMD_IF_MASK) |
(ifidx << CDC_DCMD_IF_SHIFT);
msg->flags = cpu_to_le32(flags);
if (buf)
memcpy(prot->buf, buf, len);
ret = brcmf_proto_cdc_msg(drvr);
if (ret < 0) {
brcmf_dbg(ERROR, "brcmf_proto_cdc_msg failed w/status %d\n",
ret);
goto done;
}
retry:
/* wait for interrupt and get first fragment */
ret = brcmf_proto_cdc_cmplt(drvr, prot->reqid, len);
if (ret < 0)
goto done;
flags = le32_to_cpu(msg->flags);
id = (flags & CDC_DCMD_ID_MASK) >> CDC_DCMD_ID_SHIFT;
if ((id < prot->reqid) && (++retries < RETRIES))
goto retry;
if (id != prot->reqid) {
brcmf_dbg(ERROR, "%s: unexpected request id %d (expected %d)\n",
brcmf_ifname(drvr, ifidx), id, prot->reqid);
ret = -EINVAL;
goto done;
}
/* Check info buffer */
info = (void *)&msg[1];
/* Copy info buffer */
if (buf) {
if (ret < (int)len)
len = ret;
memcpy(buf, info, len);
}
/* Check the ERROR flag */
if (flags & CDC_DCMD_ERROR) {
ret = le32_to_cpu(msg->status);
/* Cache error from dongle */
drvr->dongle_error = ret;
}
done:
return ret;
}
int brcmf_proto_cdc_set_dcmd(struct brcmf_pub *drvr, int ifidx, uint cmd,
void *buf, uint len)
{
struct brcmf_proto *prot = drvr->prot;
struct brcmf_proto_cdc_dcmd *msg = &prot->msg;
int ret = 0;
u32 flags, id;
brcmf_dbg(TRACE, "Enter\n");
brcmf_dbg(CTL, "cmd %d len %d\n", cmd, len);
memset(msg, 0, sizeof(struct brcmf_proto_cdc_dcmd));
msg->cmd = cpu_to_le32(cmd);
msg->len = cpu_to_le32(len);
flags = (++prot->reqid << CDC_DCMD_ID_SHIFT) | CDC_DCMD_SET;
flags = (flags & ~CDC_DCMD_IF_MASK) |
(ifidx << CDC_DCMD_IF_SHIFT);
msg->flags = cpu_to_le32(flags);
if (buf)
memcpy(prot->buf, buf, len);
ret = brcmf_proto_cdc_msg(drvr);
if (ret < 0)
goto done;
ret = brcmf_proto_cdc_cmplt(drvr, prot->reqid, len);
if (ret < 0)
goto done;
flags = le32_to_cpu(msg->flags);
id = (flags & CDC_DCMD_ID_MASK) >> CDC_DCMD_ID_SHIFT;
if (id != prot->reqid) {
brcmf_dbg(ERROR, "%s: unexpected request id %d (expected %d)\n",
brcmf_ifname(drvr, ifidx), id, prot->reqid);
ret = -EINVAL;
goto done;
}
/* Check the ERROR flag */
if (flags & CDC_DCMD_ERROR) {
ret = le32_to_cpu(msg->status);
/* Cache error from dongle */
drvr->dongle_error = ret;
}
done:
return ret;
}
int
brcmf_proto_dcmd(struct brcmf_pub *drvr, int ifidx, struct brcmf_dcmd *dcmd,
int len)
{
struct brcmf_proto *prot = drvr->prot;
int ret = -1;
if (drvr->bus_if->state == BRCMF_BUS_DOWN) {
brcmf_dbg(ERROR, "bus is down. we have nothing to do.\n");
return ret;
}
mutex_lock(&drvr->proto_block);
brcmf_dbg(TRACE, "Enter\n");
if (len > BRCMF_DCMD_MAXLEN)
goto done;
if (prot->pending == true) {
brcmf_dbg(TRACE, "CDC packet is pending!!!! cmd=0x%x (%lu) lastcmd=0x%x (%lu)\n",
dcmd->cmd, (unsigned long)dcmd->cmd, prot->lastcmd,
(unsigned long)prot->lastcmd);
if (dcmd->cmd == BRCMF_C_SET_VAR ||
dcmd->cmd == BRCMF_C_GET_VAR)
brcmf_dbg(TRACE, "iovar cmd=%s\n", (char *)dcmd->buf);
goto done;
}
prot->pending = true;
prot->lastcmd = dcmd->cmd;
if (dcmd->set)
ret = brcmf_proto_cdc_set_dcmd(drvr, ifidx, dcmd->cmd,
dcmd->buf, len);
else {
ret = brcmf_proto_cdc_query_dcmd(drvr, ifidx, dcmd->cmd,
dcmd->buf, len);
if (ret > 0)
dcmd->used = ret -
sizeof(struct brcmf_proto_cdc_dcmd);
}
if (ret >= 0)
ret = 0;
else {
struct brcmf_proto_cdc_dcmd *msg = &prot->msg;
/* len == needed when set/query fails from dongle */
dcmd->needed = le32_to_cpu(msg->len);
}
/* Intercept the wme_dp dongle cmd here */
if (!ret && dcmd->cmd == BRCMF_C_SET_VAR &&
!strcmp(dcmd->buf, "wme_dp")) {
int slen;
__le32 val = 0;
slen = strlen("wme_dp") + 1;
if (len >= (int)(slen + sizeof(int)))
memcpy(&val, (char *)dcmd->buf + slen, sizeof(int));
drvr->wme_dp = (u8) le32_to_cpu(val);
}
prot->pending = false;
done:
mutex_unlock(&drvr->proto_block);
return ret;
}
static bool pkt_sum_needed(struct sk_buff *skb)
{
return skb->ip_summed == CHECKSUM_PARTIAL;
}
static void pkt_set_sum_good(struct sk_buff *skb, bool x)
{
skb->ip_summed = (x ? CHECKSUM_UNNECESSARY : CHECKSUM_NONE);
}
void brcmf_proto_hdrpush(struct brcmf_pub *drvr, int ifidx,
struct sk_buff *pktbuf)
{
struct brcmf_proto_bdc_header *h;
brcmf_dbg(TRACE, "Enter\n");
/* Push BDC header used to convey priority for buses that don't */
skb_push(pktbuf, BDC_HEADER_LEN);
h = (struct brcmf_proto_bdc_header *)(pktbuf->data);
h->flags = (BDC_PROTO_VER << BDC_FLAG_VER_SHIFT);
if (pkt_sum_needed(pktbuf))
h->flags |= BDC_FLAG_SUM_NEEDED;
h->priority = (pktbuf->priority & BDC_PRIORITY_MASK);
h->flags2 = 0;
h->data_offset = 0;
BDC_SET_IF_IDX(h, ifidx);
}
int brcmf_proto_hdrpull(struct device *dev, int *ifidx,
struct sk_buff *pktbuf)
{
struct brcmf_proto_bdc_header *h;
struct brcmf_bus *bus_if = dev_get_drvdata(dev);
struct brcmf_pub *drvr = bus_if->drvr;
brcmf_dbg(TRACE, "Enter\n");
/* Pop BDC header used to convey priority for buses that don't */
if (pktbuf->len < BDC_HEADER_LEN) {
brcmf_dbg(ERROR, "rx data too short (%d < %d)\n",
pktbuf->len, BDC_HEADER_LEN);
return -EBADE;
}
h = (struct brcmf_proto_bdc_header *)(pktbuf->data);
*ifidx = BDC_GET_IF_IDX(h);
if (*ifidx >= BRCMF_MAX_IFS) {
brcmf_dbg(ERROR, "rx data ifnum out of range (%d)\n", *ifidx);
return -EBADE;
}
if (((h->flags & BDC_FLAG_VER_MASK) >> BDC_FLAG_VER_SHIFT) !=
BDC_PROTO_VER) {
brcmf_dbg(ERROR, "%s: non-BDC packet received, flags 0x%x\n",
brcmf_ifname(drvr, *ifidx), h->flags);
return -EBADE;
}
if (h->flags & BDC_FLAG_SUM_GOOD) {
brcmf_dbg(INFO, "%s: BDC packet received with good rx-csum, flags 0x%x\n",
brcmf_ifname(drvr, *ifidx), h->flags);
pkt_set_sum_good(pktbuf, true);
}
pktbuf->priority = h->priority & BDC_PRIORITY_MASK;
skb_pull(pktbuf, BDC_HEADER_LEN);
return 0;
}
int brcmf_proto_attach(struct brcmf_pub *drvr)
{
struct brcmf_proto *cdc;
cdc = kzalloc(sizeof(struct brcmf_proto), GFP_ATOMIC);
if (!cdc)
goto fail;
/* ensure that the msg buf directly follows the cdc msg struct */
if ((unsigned long)(&cdc->msg + 1) != (unsigned long)cdc->buf) {
brcmf_dbg(ERROR, "struct brcmf_proto is not correctly defined\n");
goto fail;
}
drvr->prot = cdc;
drvr->hdrlen += BDC_HEADER_LEN;
drvr->bus_if->maxctl = BRCMF_DCMD_MAXLEN +
sizeof(struct brcmf_proto_cdc_dcmd) + ROUND_UP_MARGIN;
return 0;
fail:
kfree(cdc);
return -ENOMEM;
}
/* ~NOTE~ What if another thread is waiting on the semaphore? Holding it? */
void brcmf_proto_detach(struct brcmf_pub *drvr)
{
kfree(drvr->prot);
drvr->prot = NULL;
}
int brcmf_proto_init(struct brcmf_pub *drvr)
{
int ret = 0;
char buf[128];
brcmf_dbg(TRACE, "Enter\n");
mutex_lock(&drvr->proto_block);
/* Get the device MAC address */
strcpy(buf, "cur_etheraddr");
ret = brcmf_proto_cdc_query_dcmd(drvr, 0, BRCMF_C_GET_VAR,
buf, sizeof(buf));
if (ret < 0) {
mutex_unlock(&drvr->proto_block);
return ret;
}
memcpy(drvr->mac, buf, ETH_ALEN);
mutex_unlock(&drvr->proto_block);
ret = brcmf_c_preinit_dcmds(drvr);
/* Always assumes wl for now */
drvr->iswl = true;
return ret;
}
void brcmf_proto_stop(struct brcmf_pub *drvr)
{
/* Nothing to do for CDC */
}
|
gpl-3.0
|
db4ple/mchf-github
|
mchf-eclipse/basesw/ovi40/Drivers/CMSIS/DSP_Lib/Source/BasicMathFunctions/arm_abs_q7.c
|
217
|
4933
|
/* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_abs_q7.c
*
* Description: Q7 vector absolute value.
*
* 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 groupMath
*/
/**
* @addtogroup BasicAbs
* @{
*/
/**
* @brief Q7 vector absolute value.
* @param[in] *pSrc points to the input buffer
* @param[out] *pDst points to the output buffer
* @param[in] blockSize number of samples in each vector
* @return none.
*
* \par Conditions for optimum performance
* Input and output buffers should be aligned by 32-bit
*
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function uses saturating arithmetic.
* The Q7 value -1 (0x80) will be saturated to the maximum allowable positive value 0x7F.
*/
void arm_abs_q7(
q7_t * pSrc,
q7_t * pDst,
uint32_t blockSize)
{
uint32_t blkCnt; /* loop counter */
q7_t in; /* Input value1 */
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
q31_t in1, in2, in3, in4; /* temporary input variables */
q31_t out1, out2, out3, out4; /* temporary output variables */
/*loop Unrolling */
blkCnt = blockSize >> 2u;
/* First part of the processing with loop unrolling. Compute 4 outputs at a time.
** a second loop below computes the remaining 1 to 3 samples. */
while(blkCnt > 0u)
{
/* C = |A| */
/* Read inputs */
in1 = (q31_t) * pSrc;
in2 = (q31_t) * (pSrc + 1);
in3 = (q31_t) * (pSrc + 2);
/* find absolute value */
out1 = (in1 > 0) ? in1 : (q31_t)__QSUB8(0, in1);
/* read input */
in4 = (q31_t) * (pSrc + 3);
/* find absolute value */
out2 = (in2 > 0) ? in2 : (q31_t)__QSUB8(0, in2);
/* store result to destination */
*pDst = (q7_t) out1;
/* find absolute value */
out3 = (in3 > 0) ? in3 : (q31_t)__QSUB8(0, in3);
/* find absolute value */
out4 = (in4 > 0) ? in4 : (q31_t)__QSUB8(0, in4);
/* store result to destination */
*(pDst + 1) = (q7_t) out2;
/* store result to destination */
*(pDst + 2) = (q7_t) out3;
/* store result to destination */
*(pDst + 3) = (q7_t) out4;
/* update pointers to process next samples */
pSrc += 4u;
pDst += 4u;
/* Decrement the loop counter */
blkCnt--;
}
/* If the blockSize is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = blockSize % 0x4u;
#else
/* Run the below code for Cortex-M0 */
blkCnt = blockSize;
#endif /* #define ARM_MATH_CM0_FAMILY */
while(blkCnt > 0u)
{
/* C = |A| */
/* Read the input */
in = *pSrc++;
/* Store the Absolute result in the destination buffer */
*pDst++ = (in > 0) ? in : ((in == (q7_t) 0x80) ? 0x7f : -in);
/* Decrement the loop counter */
blkCnt--;
}
}
/**
* @} end of BasicAbs group
*/
|
gpl-3.0
|
loganmc10/mupen64plus-ae
|
ndkLibs/freetype/src/pshinter/pshalgo.c
|
219
|
61747
|
/***************************************************************************/
/* */
/* pshalgo.c */
/* */
/* PostScript hinting algorithm (body). */
/* */
/* Copyright 2001-2010, 2012-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 <ft2build.h>
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_DEBUG_H
#include FT_INTERNAL_CALC_H
#include "pshalgo.h"
#include "pshnterr.h"
#undef FT_COMPONENT
#define FT_COMPONENT trace_pshalgo2
#ifdef DEBUG_HINTER
PSH_Hint_Table ps_debug_hint_table = 0;
PSH_HintFunc ps_debug_hint_func = 0;
PSH_Glyph ps_debug_glyph = 0;
#endif
#define COMPUTE_INFLEXS /* compute inflection points to optimize `S' */
/* and similar glyphs */
#define STRONGER /* slightly increase the contrast of smooth */
/* hinting */
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** BASIC HINTS RECORDINGS *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
/* return true if two stem hints overlap */
static FT_Int
psh_hint_overlap( PSH_Hint hint1,
PSH_Hint hint2 )
{
return hint1->org_pos + hint1->org_len >= hint2->org_pos &&
hint2->org_pos + hint2->org_len >= hint1->org_pos;
}
/* destroy hints table */
static void
psh_hint_table_done( PSH_Hint_Table table,
FT_Memory memory )
{
FT_FREE( table->zones );
table->num_zones = 0;
table->zone = 0;
FT_FREE( table->sort );
FT_FREE( table->hints );
table->num_hints = 0;
table->max_hints = 0;
table->sort_global = 0;
}
/* deactivate all hints in a table */
static void
psh_hint_table_deactivate( PSH_Hint_Table table )
{
FT_UInt count = table->max_hints;
PSH_Hint hint = table->hints;
for ( ; count > 0; count--, hint++ )
{
psh_hint_deactivate( hint );
hint->order = -1;
}
}
/* internal function to record a new hint */
static void
psh_hint_table_record( PSH_Hint_Table table,
FT_UInt idx )
{
PSH_Hint hint = table->hints + idx;
if ( idx >= table->max_hints )
{
FT_TRACE0(( "psh_hint_table_record: invalid hint index %d\n", idx ));
return;
}
/* ignore active hints */
if ( psh_hint_is_active( hint ) )
return;
psh_hint_activate( hint );
/* now scan the current active hint set to check */
/* whether `hint' overlaps with another hint */
{
PSH_Hint* sorted = table->sort_global;
FT_UInt count = table->num_hints;
PSH_Hint hint2;
hint->parent = 0;
for ( ; count > 0; count--, sorted++ )
{
hint2 = sorted[0];
if ( psh_hint_overlap( hint, hint2 ) )
{
hint->parent = hint2;
break;
}
}
}
if ( table->num_hints < table->max_hints )
table->sort_global[table->num_hints++] = hint;
else
FT_TRACE0(( "psh_hint_table_record: too many sorted hints! BUG!\n" ));
}
static void
psh_hint_table_record_mask( PSH_Hint_Table table,
PS_Mask hint_mask )
{
FT_Int mask = 0, val = 0;
FT_Byte* cursor = hint_mask->bytes;
FT_UInt idx, limit;
limit = hint_mask->num_bits;
for ( idx = 0; idx < limit; idx++ )
{
if ( mask == 0 )
{
val = *cursor++;
mask = 0x80;
}
if ( val & mask )
psh_hint_table_record( table, idx );
mask >>= 1;
}
}
/* create hints table */
static FT_Error
psh_hint_table_init( PSH_Hint_Table table,
PS_Hint_Table hints,
PS_Mask_Table hint_masks,
PS_Mask_Table counter_masks,
FT_Memory memory )
{
FT_UInt count;
FT_Error error;
FT_UNUSED( counter_masks );
count = hints->num_hints;
/* allocate our tables */
if ( FT_NEW_ARRAY( table->sort, 2 * count ) ||
FT_NEW_ARRAY( table->hints, count ) ||
FT_NEW_ARRAY( table->zones, 2 * count + 1 ) )
goto Exit;
table->max_hints = count;
table->sort_global = table->sort + count;
table->num_hints = 0;
table->num_zones = 0;
table->zone = 0;
/* initialize the `table->hints' array */
{
PSH_Hint write = table->hints;
PS_Hint read = hints->hints;
for ( ; count > 0; count--, write++, read++ )
{
write->org_pos = read->pos;
write->org_len = read->len;
write->flags = read->flags;
}
}
/* we now need to determine the initial `parent' stems; first */
/* activate the hints that are given by the initial hint masks */
if ( hint_masks )
{
PS_Mask mask = hint_masks->masks;
count = hint_masks->num_masks;
table->hint_masks = hint_masks;
for ( ; count > 0; count--, mask++ )
psh_hint_table_record_mask( table, mask );
}
/* finally, do a linear parse in case some hints were left alone */
if ( table->num_hints != table->max_hints )
{
FT_UInt idx;
FT_TRACE0(( "psh_hint_table_init: missing/incorrect hint masks\n" ));
count = table->max_hints;
for ( idx = 0; idx < count; idx++ )
psh_hint_table_record( table, idx );
}
Exit:
return error;
}
static void
psh_hint_table_activate_mask( PSH_Hint_Table table,
PS_Mask hint_mask )
{
FT_Int mask = 0, val = 0;
FT_Byte* cursor = hint_mask->bytes;
FT_UInt idx, limit, count;
limit = hint_mask->num_bits;
count = 0;
psh_hint_table_deactivate( table );
for ( idx = 0; idx < limit; idx++ )
{
if ( mask == 0 )
{
val = *cursor++;
mask = 0x80;
}
if ( val & mask )
{
PSH_Hint hint = &table->hints[idx];
if ( !psh_hint_is_active( hint ) )
{
FT_UInt count2;
#if 0
PSH_Hint* sort = table->sort;
PSH_Hint hint2;
for ( count2 = count; count2 > 0; count2--, sort++ )
{
hint2 = sort[0];
if ( psh_hint_overlap( hint, hint2 ) )
FT_TRACE0(( "psh_hint_table_activate_mask:"
" found overlapping hints\n" ))
}
#else
count2 = 0;
#endif
if ( count2 == 0 )
{
psh_hint_activate( hint );
if ( count < table->max_hints )
table->sort[count++] = hint;
else
FT_TRACE0(( "psh_hint_tableactivate_mask:"
" too many active hints\n" ));
}
}
}
mask >>= 1;
}
table->num_hints = count;
/* now, sort the hints; they are guaranteed to not overlap */
/* so we can compare their "org_pos" field directly */
{
FT_Int i1, i2;
PSH_Hint hint1, hint2;
PSH_Hint* sort = table->sort;
/* a simple bubble sort will do, since in 99% of cases, the hints */
/* will be already sorted -- and the sort will be linear */
for ( i1 = 1; i1 < (FT_Int)count; i1++ )
{
hint1 = sort[i1];
for ( i2 = i1 - 1; i2 >= 0; i2-- )
{
hint2 = sort[i2];
if ( hint2->org_pos < hint1->org_pos )
break;
sort[i2 + 1] = hint2;
sort[i2] = hint1;
}
}
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** HINTS GRID-FITTING AND OPTIMIZATION *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#if 1
static FT_Pos
psh_dimension_quantize_len( PSH_Dimension dim,
FT_Pos len,
FT_Bool do_snapping )
{
if ( len <= 64 )
len = 64;
else
{
FT_Pos delta = len - dim->stdw.widths[0].cur;
if ( delta < 0 )
delta = -delta;
if ( delta < 40 )
{
len = dim->stdw.widths[0].cur;
if ( len < 48 )
len = 48;
}
if ( len < 3 * 64 )
{
delta = ( len & 63 );
len &= -64;
if ( delta < 10 )
len += delta;
else if ( delta < 32 )
len += 10;
else if ( delta < 54 )
len += 54;
else
len += delta;
}
else
len = FT_PIX_ROUND( len );
}
if ( do_snapping )
len = FT_PIX_ROUND( len );
return len;
}
#endif /* 0 */
#ifdef DEBUG_HINTER
static void
ps_simple_scale( PSH_Hint_Table table,
FT_Fixed scale,
FT_Fixed delta,
FT_Int dimension )
{
FT_UInt count;
for ( count = 0; count < table->max_hints; count++ )
{
PSH_Hint hint = table->hints + count;
hint->cur_pos = FT_MulFix( hint->org_pos, scale ) + delta;
hint->cur_len = FT_MulFix( hint->org_len, scale );
if ( ps_debug_hint_func )
ps_debug_hint_func( hint, dimension );
}
}
#endif /* DEBUG_HINTER */
static FT_Fixed
psh_hint_snap_stem_side_delta( FT_Fixed pos,
FT_Fixed len )
{
FT_Fixed delta1 = FT_PIX_ROUND( pos ) - pos;
FT_Fixed delta2 = FT_PIX_ROUND( pos + len ) - pos - len;
if ( FT_ABS( delta1 ) <= FT_ABS( delta2 ) )
return delta1;
else
return delta2;
}
static void
psh_hint_align( PSH_Hint hint,
PSH_Globals globals,
FT_Int dimension,
PSH_Glyph glyph )
{
PSH_Dimension dim = &globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
if ( !psh_hint_is_fitted( hint ) )
{
FT_Pos pos = FT_MulFix( hint->org_pos, scale ) + delta;
FT_Pos len = FT_MulFix( hint->org_len, scale );
FT_Int do_snapping;
FT_Pos fit_len;
PSH_AlignmentRec align;
/* ignore stem alignments when requested through the hint flags */
if ( ( dimension == 0 && !glyph->do_horz_hints ) ||
( dimension == 1 && !glyph->do_vert_hints ) )
{
hint->cur_pos = pos;
hint->cur_len = len;
psh_hint_set_fitted( hint );
return;
}
/* perform stem snapping when requested - this is necessary
* for monochrome and LCD hinting modes only
*/
do_snapping = ( dimension == 0 && glyph->do_horz_snapping ) ||
( dimension == 1 && glyph->do_vert_snapping );
hint->cur_len = fit_len = len;
/* check blue zones for horizontal stems */
align.align = PSH_BLUE_ALIGN_NONE;
align.align_bot = align.align_top = 0;
if ( dimension == 1 )
psh_blues_snap_stem( &globals->blues,
hint->org_pos + hint->org_len,
hint->org_pos,
&align );
switch ( align.align )
{
case PSH_BLUE_ALIGN_TOP:
/* the top of the stem is aligned against a blue zone */
hint->cur_pos = align.align_top - fit_len;
break;
case PSH_BLUE_ALIGN_BOT:
/* the bottom of the stem is aligned against a blue zone */
hint->cur_pos = align.align_bot;
break;
case PSH_BLUE_ALIGN_TOP | PSH_BLUE_ALIGN_BOT:
/* both edges of the stem are aligned against blue zones */
hint->cur_pos = align.align_bot;
hint->cur_len = align.align_top - align.align_bot;
break;
default:
{
PSH_Hint parent = hint->parent;
if ( parent )
{
FT_Pos par_org_center, par_cur_center;
FT_Pos cur_org_center, cur_delta;
/* ensure that parent is already fitted */
if ( !psh_hint_is_fitted( parent ) )
psh_hint_align( parent, globals, dimension, glyph );
/* keep original relation between hints, this is, use the */
/* scaled distance between the centers of the hints to */
/* compute the new position */
par_org_center = parent->org_pos + ( parent->org_len >> 1 );
par_cur_center = parent->cur_pos + ( parent->cur_len >> 1 );
cur_org_center = hint->org_pos + ( hint->org_len >> 1 );
cur_delta = FT_MulFix( cur_org_center - par_org_center, scale );
pos = par_cur_center + cur_delta - ( len >> 1 );
}
hint->cur_pos = pos;
hint->cur_len = fit_len;
/* Stem adjustment tries to snap stem widths to standard
* ones. This is important to prevent unpleasant rounding
* artefacts.
*/
if ( glyph->do_stem_adjust )
{
if ( len <= 64 )
{
/* the stem is less than one pixel; we will center it
* around the nearest pixel center
*/
if ( len >= 32 )
{
/* This is a special case where we also widen the stem
* and align it to the pixel grid.
*
* stem_center = pos + (len/2)
* nearest_pixel_center = FT_ROUND(stem_center-32)+32
* new_pos = nearest_pixel_center-32
* = FT_ROUND(stem_center-32)
* = FT_FLOOR(stem_center-32+32)
* = FT_FLOOR(stem_center)
* new_len = 64
*/
pos = FT_PIX_FLOOR( pos + ( len >> 1 ) );
len = 64;
}
else if ( len > 0 )
{
/* This is a very small stem; we simply align it to the
* pixel grid, trying to find the minimum displacement.
*
* left = pos
* right = pos + len
* left_nearest_edge = ROUND(pos)
* right_nearest_edge = ROUND(right)
*
* if ( ABS(left_nearest_edge - left) <=
* ABS(right_nearest_edge - right) )
* new_pos = left
* else
* new_pos = right
*/
FT_Pos left_nearest = FT_PIX_ROUND( pos );
FT_Pos right_nearest = FT_PIX_ROUND( pos + len );
FT_Pos left_disp = left_nearest - pos;
FT_Pos right_disp = right_nearest - ( pos + len );
if ( left_disp < 0 )
left_disp = -left_disp;
if ( right_disp < 0 )
right_disp = -right_disp;
if ( left_disp <= right_disp )
pos = left_nearest;
else
pos = right_nearest;
}
else
{
/* this is a ghost stem; we simply round it */
pos = FT_PIX_ROUND( pos );
}
}
else
{
len = psh_dimension_quantize_len( dim, len, 0 );
}
}
/* now that we have a good hinted stem width, try to position */
/* the stem along a pixel grid integer coordinate */
hint->cur_pos = pos + psh_hint_snap_stem_side_delta( pos, len );
hint->cur_len = len;
}
}
if ( do_snapping )
{
pos = hint->cur_pos;
len = hint->cur_len;
if ( len < 64 )
len = 64;
else
len = FT_PIX_ROUND( len );
switch ( align.align )
{
case PSH_BLUE_ALIGN_TOP:
hint->cur_pos = align.align_top - len;
hint->cur_len = len;
break;
case PSH_BLUE_ALIGN_BOT:
hint->cur_len = len;
break;
case PSH_BLUE_ALIGN_BOT | PSH_BLUE_ALIGN_TOP:
/* don't touch */
break;
default:
hint->cur_len = len;
if ( len & 64 )
pos = FT_PIX_FLOOR( pos + ( len >> 1 ) ) + 32;
else
pos = FT_PIX_ROUND( pos + ( len >> 1 ) );
hint->cur_pos = pos - ( len >> 1 );
hint->cur_len = len;
}
}
psh_hint_set_fitted( hint );
#ifdef DEBUG_HINTER
if ( ps_debug_hint_func )
ps_debug_hint_func( hint, dimension );
#endif
}
}
#if 0 /* not used for now, experimental */
/*
* A variant to perform "light" hinting (i.e. FT_RENDER_MODE_LIGHT)
* of stems
*/
static void
psh_hint_align_light( PSH_Hint hint,
PSH_Globals globals,
FT_Int dimension,
PSH_Glyph glyph )
{
PSH_Dimension dim = &globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
if ( !psh_hint_is_fitted( hint ) )
{
FT_Pos pos = FT_MulFix( hint->org_pos, scale ) + delta;
FT_Pos len = FT_MulFix( hint->org_len, scale );
FT_Pos fit_len;
PSH_AlignmentRec align;
/* ignore stem alignments when requested through the hint flags */
if ( ( dimension == 0 && !glyph->do_horz_hints ) ||
( dimension == 1 && !glyph->do_vert_hints ) )
{
hint->cur_pos = pos;
hint->cur_len = len;
psh_hint_set_fitted( hint );
return;
}
fit_len = len;
hint->cur_len = fit_len;
/* check blue zones for horizontal stems */
align.align = PSH_BLUE_ALIGN_NONE;
align.align_bot = align.align_top = 0;
if ( dimension == 1 )
psh_blues_snap_stem( &globals->blues,
hint->org_pos + hint->org_len,
hint->org_pos,
&align );
switch ( align.align )
{
case PSH_BLUE_ALIGN_TOP:
/* the top of the stem is aligned against a blue zone */
hint->cur_pos = align.align_top - fit_len;
break;
case PSH_BLUE_ALIGN_BOT:
/* the bottom of the stem is aligned against a blue zone */
hint->cur_pos = align.align_bot;
break;
case PSH_BLUE_ALIGN_TOP | PSH_BLUE_ALIGN_BOT:
/* both edges of the stem are aligned against blue zones */
hint->cur_pos = align.align_bot;
hint->cur_len = align.align_top - align.align_bot;
break;
default:
{
PSH_Hint parent = hint->parent;
if ( parent )
{
FT_Pos par_org_center, par_cur_center;
FT_Pos cur_org_center, cur_delta;
/* ensure that parent is already fitted */
if ( !psh_hint_is_fitted( parent ) )
psh_hint_align_light( parent, globals, dimension, glyph );
par_org_center = parent->org_pos + ( parent->org_len / 2 );
par_cur_center = parent->cur_pos + ( parent->cur_len / 2 );
cur_org_center = hint->org_pos + ( hint->org_len / 2 );
cur_delta = FT_MulFix( cur_org_center - par_org_center, scale );
pos = par_cur_center + cur_delta - ( len >> 1 );
}
/* Stems less than one pixel wide are easy -- we want to
* make them as dark as possible, so they must fall within
* one pixel. If the stem is split between two pixels
* then snap the edge that is nearer to the pixel boundary
* to the pixel boundary.
*/
if ( len <= 64 )
{
if ( ( pos + len + 63 ) / 64 != pos / 64 + 1 )
pos += psh_hint_snap_stem_side_delta ( pos, len );
}
/* Position stems other to minimize the amount of mid-grays.
* There are, in general, two positions that do this,
* illustrated as A) and B) below.
*
* + + + +
*
* A) |--------------------------------|
* B) |--------------------------------|
* C) |--------------------------------|
*
* Position A) (split the excess stem equally) should be better
* for stems of width N + f where f < 0.5.
*
* Position B) (split the deficiency equally) should be better
* for stems of width N + f where f > 0.5.
*
* It turns out though that minimizing the total number of lit
* pixels is also important, so position C), with one edge
* aligned with a pixel boundary is actually preferable
* to A). There are also more possibile positions for C) than
* for A) or B), so it involves less distortion of the overall
* character shape.
*/
else /* len > 64 */
{
FT_Fixed frac_len = len & 63;
FT_Fixed center = pos + ( len >> 1 );
FT_Fixed delta_a, delta_b;
if ( ( len / 64 ) & 1 )
{
delta_a = FT_PIX_FLOOR( center ) + 32 - center;
delta_b = FT_PIX_ROUND( center ) - center;
}
else
{
delta_a = FT_PIX_ROUND( center ) - center;
delta_b = FT_PIX_FLOOR( center ) + 32 - center;
}
/* We choose between B) and C) above based on the amount
* of fractinal stem width; for small amounts, choose
* C) always, for large amounts, B) always, and inbetween,
* pick whichever one involves less stem movement.
*/
if ( frac_len < 32 )
{
pos += psh_hint_snap_stem_side_delta ( pos, len );
}
else if ( frac_len < 48 )
{
FT_Fixed side_delta = psh_hint_snap_stem_side_delta ( pos,
len );
if ( FT_ABS( side_delta ) < FT_ABS( delta_b ) )
pos += side_delta;
else
pos += delta_b;
}
else
{
pos += delta_b;
}
}
hint->cur_pos = pos;
}
} /* switch */
psh_hint_set_fitted( hint );
#ifdef DEBUG_HINTER
if ( ps_debug_hint_func )
ps_debug_hint_func( hint, dimension );
#endif
}
}
#endif /* 0 */
static void
psh_hint_table_align_hints( PSH_Hint_Table table,
PSH_Globals globals,
FT_Int dimension,
PSH_Glyph glyph )
{
PSH_Hint hint;
FT_UInt count;
#ifdef DEBUG_HINTER
PSH_Dimension dim = &globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
if ( ps_debug_no_vert_hints && dimension == 0 )
{
ps_simple_scale( table, scale, delta, dimension );
return;
}
if ( ps_debug_no_horz_hints && dimension == 1 )
{
ps_simple_scale( table, scale, delta, dimension );
return;
}
#endif /* DEBUG_HINTER*/
hint = table->hints;
count = table->max_hints;
for ( ; count > 0; count--, hint++ )
psh_hint_align( hint, globals, dimension, glyph );
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** POINTS INTERPOLATION ROUTINES *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#define PSH_ZONE_MIN -3200000L
#define PSH_ZONE_MAX +3200000L
#define xxDEBUG_ZONES
#ifdef DEBUG_ZONES
#include FT_CONFIG_STANDARD_LIBRARY_H
static void
psh_print_zone( PSH_Zone zone )
{
printf( "zone [scale,delta,min,max] = [%.3f,%.3f,%d,%d]\n",
zone->scale / 65536.0,
zone->delta / 64.0,
zone->min,
zone->max );
}
#else
#define psh_print_zone( x ) do { } while ( 0 )
#endif /* DEBUG_ZONES */
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** HINTER GLYPH MANAGEMENT *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
#if 1
#define psh_corner_is_flat ft_corner_is_flat
#define psh_corner_orientation ft_corner_orientation
#else
FT_LOCAL_DEF( FT_Int )
psh_corner_is_flat( FT_Pos x_in,
FT_Pos y_in,
FT_Pos x_out,
FT_Pos y_out )
{
FT_Pos ax = x_in;
FT_Pos ay = y_in;
FT_Pos d_in, d_out, d_corner;
if ( ax < 0 )
ax = -ax;
if ( ay < 0 )
ay = -ay;
d_in = ax + ay;
ax = x_out;
if ( ax < 0 )
ax = -ax;
ay = y_out;
if ( ay < 0 )
ay = -ay;
d_out = ax + ay;
ax = x_out + x_in;
if ( ax < 0 )
ax = -ax;
ay = y_out + y_in;
if ( ay < 0 )
ay = -ay;
d_corner = ax + ay;
return ( d_in + d_out - d_corner ) < ( d_corner >> 4 );
}
static FT_Int
psh_corner_orientation( FT_Pos in_x,
FT_Pos in_y,
FT_Pos out_x,
FT_Pos out_y )
{
FT_Int result;
/* deal with the trivial cases quickly */
if ( in_y == 0 )
{
if ( in_x >= 0 )
result = out_y;
else
result = -out_y;
}
else if ( in_x == 0 )
{
if ( in_y >= 0 )
result = -out_x;
else
result = out_x;
}
else if ( out_y == 0 )
{
if ( out_x >= 0 )
result = in_y;
else
result = -in_y;
}
else if ( out_x == 0 )
{
if ( out_y >= 0 )
result = -in_x;
else
result = in_x;
}
else /* general case */
{
long long delta = (long long)in_x * out_y - (long long)in_y * out_x;
if ( delta == 0 )
result = 0;
else
result = 1 - 2 * ( delta < 0 );
}
return result;
}
#endif /* !1 */
#ifdef COMPUTE_INFLEXS
/* compute all inflex points in a given glyph */
static void
psh_glyph_compute_inflections( PSH_Glyph glyph )
{
FT_UInt n;
for ( n = 0; n < glyph->num_contours; n++ )
{
PSH_Point first, start, end, before, after;
FT_Pos in_x, in_y, out_x, out_y;
FT_Int orient_prev, orient_cur;
FT_Int finished = 0;
/* we need at least 4 points to create an inflection point */
if ( glyph->contours[n].count < 4 )
continue;
/* compute first segment in contour */
first = glyph->contours[n].start;
start = end = first;
do
{
end = end->next;
if ( end == first )
goto Skip;
in_x = end->org_u - start->org_u;
in_y = end->org_v - start->org_v;
} while ( in_x == 0 && in_y == 0 );
/* extend the segment start whenever possible */
before = start;
do
{
do
{
start = before;
before = before->prev;
if ( before == first )
goto Skip;
out_x = start->org_u - before->org_u;
out_y = start->org_v - before->org_v;
} while ( out_x == 0 && out_y == 0 );
orient_prev = psh_corner_orientation( in_x, in_y, out_x, out_y );
} while ( orient_prev == 0 );
first = start;
in_x = out_x;
in_y = out_y;
/* now, process all segments in the contour */
do
{
/* first, extend current segment's end whenever possible */
after = end;
do
{
do
{
end = after;
after = after->next;
if ( after == first )
finished = 1;
out_x = after->org_u - end->org_u;
out_y = after->org_v - end->org_v;
} while ( out_x == 0 && out_y == 0 );
orient_cur = psh_corner_orientation( in_x, in_y, out_x, out_y );
} while ( orient_cur == 0 );
if ( ( orient_cur ^ orient_prev ) < 0 )
{
do
{
psh_point_set_inflex( start );
start = start->next;
}
while ( start != end );
psh_point_set_inflex( start );
}
start = end;
end = after;
orient_prev = orient_cur;
in_x = out_x;
in_y = out_y;
} while ( !finished );
Skip:
;
}
}
#endif /* COMPUTE_INFLEXS */
static void
psh_glyph_done( PSH_Glyph glyph )
{
FT_Memory memory = glyph->memory;
psh_hint_table_done( &glyph->hint_tables[1], memory );
psh_hint_table_done( &glyph->hint_tables[0], memory );
FT_FREE( glyph->points );
FT_FREE( glyph->contours );
glyph->num_points = 0;
glyph->num_contours = 0;
glyph->memory = 0;
}
static int
psh_compute_dir( FT_Pos dx,
FT_Pos dy )
{
FT_Pos ax, ay;
int result = PSH_DIR_NONE;
ax = FT_ABS( dx );
ay = FT_ABS( dy );
if ( ay * 12 < ax )
{
/* |dy| <<< |dx| means a near-horizontal segment */
result = ( dx >= 0 ) ? PSH_DIR_RIGHT : PSH_DIR_LEFT;
}
else if ( ax * 12 < ay )
{
/* |dx| <<< |dy| means a near-vertical segment */
result = ( dy >= 0 ) ? PSH_DIR_UP : PSH_DIR_DOWN;
}
return result;
}
/* load outline point coordinates into hinter glyph */
static void
psh_glyph_load_points( PSH_Glyph glyph,
FT_Int dimension )
{
FT_Vector* vec = glyph->outline->points;
PSH_Point point = glyph->points;
FT_UInt count = glyph->num_points;
for ( ; count > 0; count--, point++, vec++ )
{
point->flags2 = 0;
point->hint = NULL;
if ( dimension == 0 )
{
point->org_u = vec->x;
point->org_v = vec->y;
}
else
{
point->org_u = vec->y;
point->org_v = vec->x;
}
#ifdef DEBUG_HINTER
point->org_x = vec->x;
point->org_y = vec->y;
#endif
}
}
/* save hinted point coordinates back to outline */
static void
psh_glyph_save_points( PSH_Glyph glyph,
FT_Int dimension )
{
FT_UInt n;
PSH_Point point = glyph->points;
FT_Vector* vec = glyph->outline->points;
char* tags = glyph->outline->tags;
for ( n = 0; n < glyph->num_points; n++ )
{
if ( dimension == 0 )
vec[n].x = point->cur_u;
else
vec[n].y = point->cur_u;
if ( psh_point_is_strong( point ) )
tags[n] |= (char)( ( dimension == 0 ) ? 32 : 64 );
#ifdef DEBUG_HINTER
if ( dimension == 0 )
{
point->cur_x = point->cur_u;
point->flags_x = point->flags2 | point->flags;
}
else
{
point->cur_y = point->cur_u;
point->flags_y = point->flags2 | point->flags;
}
#endif
point++;
}
}
static FT_Error
psh_glyph_init( PSH_Glyph glyph,
FT_Outline* outline,
PS_Hints ps_hints,
PSH_Globals globals )
{
FT_Error error;
FT_Memory memory;
/* clear all fields */
FT_MEM_ZERO( glyph, sizeof ( *glyph ) );
memory = glyph->memory = globals->memory;
/* allocate and setup points + contours arrays */
if ( FT_NEW_ARRAY( glyph->points, outline->n_points ) ||
FT_NEW_ARRAY( glyph->contours, outline->n_contours ) )
goto Exit;
glyph->num_points = outline->n_points;
glyph->num_contours = outline->n_contours;
{
FT_UInt first = 0, next, n;
PSH_Point points = glyph->points;
PSH_Contour contour = glyph->contours;
for ( n = 0; n < glyph->num_contours; n++ )
{
FT_Int count;
PSH_Point point;
next = outline->contours[n] + 1;
count = next - first;
contour->start = points + first;
contour->count = (FT_UInt)count;
if ( count > 0 )
{
point = points + first;
point->prev = points + next - 1;
point->contour = contour;
for ( ; count > 1; count-- )
{
point[0].next = point + 1;
point[1].prev = point;
point++;
point->contour = contour;
}
point->next = points + first;
}
contour++;
first = next;
}
}
{
PSH_Point points = glyph->points;
PSH_Point point = points;
FT_Vector* vec = outline->points;
FT_UInt n;
for ( n = 0; n < glyph->num_points; n++, point++ )
{
FT_Int n_prev = (FT_Int)( point->prev - points );
FT_Int n_next = (FT_Int)( point->next - points );
FT_Pos dxi, dyi, dxo, dyo;
if ( !( outline->tags[n] & FT_CURVE_TAG_ON ) )
point->flags = PSH_POINT_OFF;
dxi = vec[n].x - vec[n_prev].x;
dyi = vec[n].y - vec[n_prev].y;
point->dir_in = (FT_Char)psh_compute_dir( dxi, dyi );
dxo = vec[n_next].x - vec[n].x;
dyo = vec[n_next].y - vec[n].y;
point->dir_out = (FT_Char)psh_compute_dir( dxo, dyo );
/* detect smooth points */
if ( point->flags & PSH_POINT_OFF )
point->flags |= PSH_POINT_SMOOTH;
else if ( point->dir_in == point->dir_out )
{
if ( point->dir_out != PSH_DIR_NONE ||
psh_corner_is_flat( dxi, dyi, dxo, dyo ) )
point->flags |= PSH_POINT_SMOOTH;
}
}
}
glyph->outline = outline;
glyph->globals = globals;
#ifdef COMPUTE_INFLEXS
psh_glyph_load_points( glyph, 0 );
psh_glyph_compute_inflections( glyph );
#endif /* COMPUTE_INFLEXS */
/* now deal with hints tables */
error = psh_hint_table_init( &glyph->hint_tables [0],
&ps_hints->dimension[0].hints,
&ps_hints->dimension[0].masks,
&ps_hints->dimension[0].counters,
memory );
if ( error )
goto Exit;
error = psh_hint_table_init( &glyph->hint_tables [1],
&ps_hints->dimension[1].hints,
&ps_hints->dimension[1].masks,
&ps_hints->dimension[1].counters,
memory );
if ( error )
goto Exit;
Exit:
return error;
}
/* compute all extrema in a glyph for a given dimension */
static void
psh_glyph_compute_extrema( PSH_Glyph glyph )
{
FT_UInt n;
/* first of all, compute all local extrema */
for ( n = 0; n < glyph->num_contours; n++ )
{
PSH_Point first = glyph->contours[n].start;
PSH_Point point, before, after;
if ( glyph->contours[n].count == 0 )
continue;
point = first;
before = point;
do
{
before = before->prev;
if ( before == first )
goto Skip;
} while ( before->org_u == point->org_u );
first = point = before->next;
for (;;)
{
after = point;
do
{
after = after->next;
if ( after == first )
goto Next;
} while ( after->org_u == point->org_u );
if ( before->org_u < point->org_u )
{
if ( after->org_u < point->org_u )
{
/* local maximum */
goto Extremum;
}
}
else /* before->org_u > point->org_u */
{
if ( after->org_u > point->org_u )
{
/* local minimum */
Extremum:
do
{
psh_point_set_extremum( point );
point = point->next;
} while ( point != after );
}
}
before = after->prev;
point = after;
} /* for */
Next:
;
}
/* for each extremum, determine its direction along the */
/* orthogonal axis */
for ( n = 0; n < glyph->num_points; n++ )
{
PSH_Point point, before, after;
point = &glyph->points[n];
before = point;
after = point;
if ( psh_point_is_extremum( point ) )
{
do
{
before = before->prev;
if ( before == point )
goto Skip;
} while ( before->org_v == point->org_v );
do
{
after = after->next;
if ( after == point )
goto Skip;
} while ( after->org_v == point->org_v );
}
if ( before->org_v < point->org_v &&
after->org_v > point->org_v )
{
psh_point_set_positive( point );
}
else if ( before->org_v > point->org_v &&
after->org_v < point->org_v )
{
psh_point_set_negative( point );
}
Skip:
;
}
}
/* major_dir is the direction for points on the bottom/left of the stem; */
/* Points on the top/right of the stem will have a direction of */
/* -major_dir. */
static void
psh_hint_table_find_strong_points( PSH_Hint_Table table,
PSH_Point point,
FT_UInt count,
FT_Int threshold,
FT_Int major_dir )
{
PSH_Hint* sort = table->sort;
FT_UInt num_hints = table->num_hints;
for ( ; count > 0; count--, point++ )
{
FT_Int point_dir = 0;
FT_Pos org_u = point->org_u;
if ( psh_point_is_strong( point ) )
continue;
if ( PSH_DIR_COMPARE( point->dir_in, major_dir ) )
point_dir = point->dir_in;
else if ( PSH_DIR_COMPARE( point->dir_out, major_dir ) )
point_dir = point->dir_out;
if ( point_dir )
{
if ( point_dir == major_dir )
{
FT_UInt nn;
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos;
if ( d < threshold && -d < threshold )
{
psh_point_set_strong( point );
point->flags2 |= PSH_POINT_EDGE_MIN;
point->hint = hint;
break;
}
}
}
else if ( point_dir == -major_dir )
{
FT_UInt nn;
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos - hint->org_len;
if ( d < threshold && -d < threshold )
{
psh_point_set_strong( point );
point->flags2 |= PSH_POINT_EDGE_MAX;
point->hint = hint;
break;
}
}
}
}
#if 1
else if ( psh_point_is_extremum( point ) )
{
/* treat extrema as special cases for stem edge alignment */
FT_UInt nn, min_flag, max_flag;
if ( major_dir == PSH_DIR_HORIZONTAL )
{
min_flag = PSH_POINT_POSITIVE;
max_flag = PSH_POINT_NEGATIVE;
}
else
{
min_flag = PSH_POINT_NEGATIVE;
max_flag = PSH_POINT_POSITIVE;
}
if ( point->flags2 & min_flag )
{
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos;
if ( d < threshold && -d < threshold )
{
point->flags2 |= PSH_POINT_EDGE_MIN;
point->hint = hint;
psh_point_set_strong( point );
break;
}
}
}
else if ( point->flags2 & max_flag )
{
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
FT_Pos d = org_u - hint->org_pos - hint->org_len;
if ( d < threshold && -d < threshold )
{
point->flags2 |= PSH_POINT_EDGE_MAX;
point->hint = hint;
psh_point_set_strong( point );
break;
}
}
}
if ( point->hint == NULL )
{
for ( nn = 0; nn < num_hints; nn++ )
{
PSH_Hint hint = sort[nn];
if ( org_u >= hint->org_pos &&
org_u <= hint->org_pos + hint->org_len )
{
point->hint = hint;
break;
}
}
}
}
#endif /* 1 */
}
}
/* the accepted shift for strong points in fractional pixels */
#define PSH_STRONG_THRESHOLD 32
/* the maximum shift value in font units */
#define PSH_STRONG_THRESHOLD_MAXIMUM 30
/* find strong points in a glyph */
static void
psh_glyph_find_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
/* a point is `strong' if it is located on a stem edge and */
/* has an `in' or `out' tangent parallel to the hint's direction */
PSH_Hint_Table table = &glyph->hint_tables[dimension];
PS_Mask mask = table->hint_masks->masks;
FT_UInt num_masks = table->hint_masks->num_masks;
FT_UInt first = 0;
FT_Int major_dir = dimension == 0 ? PSH_DIR_VERTICAL
: PSH_DIR_HORIZONTAL;
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Int threshold;
threshold = (FT_Int)FT_DivFix( PSH_STRONG_THRESHOLD, scale );
if ( threshold > PSH_STRONG_THRESHOLD_MAXIMUM )
threshold = PSH_STRONG_THRESHOLD_MAXIMUM;
/* process secondary hints to `selected' points */
if ( num_masks > 1 && glyph->num_points > 0 )
{
/* the `endchar' op can reduce the number of points */
first = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
mask++;
for ( ; num_masks > 1; num_masks--, mask++ )
{
FT_UInt next;
FT_Int count;
next = mask->end_point > glyph->num_points
? glyph->num_points
: mask->end_point;
count = next - first;
if ( count > 0 )
{
PSH_Point point = glyph->points + first;
psh_hint_table_activate_mask( table, mask );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
first = next;
}
}
/* process primary hints for all points */
if ( num_masks == 1 )
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
psh_hint_table_activate_mask( table, table->hint_masks->masks );
psh_hint_table_find_strong_points( table, point, count,
threshold, major_dir );
}
/* now, certain points may have been attached to a hint and */
/* not marked as strong; update their flags then */
{
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
if ( point->hint && !psh_point_is_strong( point ) )
psh_point_set_strong( point );
}
}
/* find points in a glyph which are in a blue zone and have `in' or */
/* `out' tangents parallel to the horizontal axis */
static void
psh_glyph_find_blue_points( PSH_Blues blues,
PSH_Glyph glyph )
{
PSH_Blue_Table table;
PSH_Blue_Zone zone;
FT_UInt glyph_count = glyph->num_points;
FT_UInt blue_count;
PSH_Point point = glyph->points;
for ( ; glyph_count > 0; glyph_count--, point++ )
{
FT_Pos y;
/* check tangents */
if ( !PSH_DIR_COMPARE( point->dir_in, PSH_DIR_HORIZONTAL ) &&
!PSH_DIR_COMPARE( point->dir_out, PSH_DIR_HORIZONTAL ) )
continue;
/* skip strong points */
if ( psh_point_is_strong( point ) )
continue;
y = point->org_u;
/* look up top zones */
table = &blues->normal_top;
blue_count = table->count;
zone = table->zones;
for ( ; blue_count > 0; blue_count--, zone++ )
{
FT_Pos delta = y - zone->org_bottom;
if ( delta < -blues->blue_fuzz )
break;
if ( y <= zone->org_top + blues->blue_fuzz )
if ( blues->no_overshoots || delta <= blues->blue_threshold )
{
point->cur_u = zone->cur_bottom;
psh_point_set_strong( point );
psh_point_set_fitted( point );
}
}
/* look up bottom zones */
table = &blues->normal_bottom;
blue_count = table->count;
zone = table->zones + blue_count - 1;
for ( ; blue_count > 0; blue_count--, zone-- )
{
FT_Pos delta = zone->org_top - y;
if ( delta < -blues->blue_fuzz )
break;
if ( y >= zone->org_bottom - blues->blue_fuzz )
if ( blues->no_overshoots || delta < blues->blue_threshold )
{
point->cur_u = zone->cur_top;
psh_point_set_strong( point );
psh_point_set_fitted( point );
}
}
}
}
/* interpolate strong points with the help of hinted coordinates */
static void
psh_glyph_interpolate_strong_points( PSH_Glyph glyph,
FT_Int dimension )
{
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_UInt count = glyph->num_points;
PSH_Point point = glyph->points;
for ( ; count > 0; count--, point++ )
{
PSH_Hint hint = point->hint;
if ( hint )
{
FT_Pos delta;
if ( psh_point_is_edge_min( point ) )
point->cur_u = hint->cur_pos;
else if ( psh_point_is_edge_max( point ) )
point->cur_u = hint->cur_pos + hint->cur_len;
else
{
delta = point->org_u - hint->org_pos;
if ( delta <= 0 )
point->cur_u = hint->cur_pos + FT_MulFix( delta, scale );
else if ( delta >= hint->org_len )
point->cur_u = hint->cur_pos + hint->cur_len +
FT_MulFix( delta - hint->org_len, scale );
else /* hint->org_len > 0 */
point->cur_u = hint->cur_pos +
FT_MulDiv( delta, hint->cur_len,
hint->org_len );
}
psh_point_set_fitted( point );
}
}
}
#define PSH_MAX_STRONG_INTERNAL 16
static void
psh_glyph_interpolate_normal_points( PSH_Glyph glyph,
FT_Int dimension )
{
#if 1
/* first technique: a point is strong if it is a local extremum */
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Memory memory = glyph->memory;
PSH_Point* strongs = NULL;
PSH_Point strongs_0[PSH_MAX_STRONG_INTERNAL];
FT_UInt num_strongs = 0;
PSH_Point points = glyph->points;
PSH_Point points_end = points + glyph->num_points;
PSH_Point point;
/* first count the number of strong points */
for ( point = points; point < points_end; point++ )
{
if ( psh_point_is_strong( point ) )
num_strongs++;
}
if ( num_strongs == 0 ) /* nothing to do here */
return;
/* allocate an array to store a list of points, */
/* stored in increasing org_u order */
if ( num_strongs <= PSH_MAX_STRONG_INTERNAL )
strongs = strongs_0;
else
{
FT_Error error;
if ( FT_NEW_ARRAY( strongs, num_strongs ) )
return;
}
num_strongs = 0;
for ( point = points; point < points_end; point++ )
{
PSH_Point* insert;
if ( !psh_point_is_strong( point ) )
continue;
for ( insert = strongs + num_strongs; insert > strongs; insert-- )
{
if ( insert[-1]->org_u <= point->org_u )
break;
insert[0] = insert[-1];
}
insert[0] = point;
num_strongs++;
}
/* now try to interpolate all normal points */
for ( point = points; point < points_end; point++ )
{
if ( psh_point_is_strong( point ) )
continue;
/* sometimes, some local extrema are smooth points */
if ( psh_point_is_smooth( point ) )
{
if ( point->dir_in == PSH_DIR_NONE ||
point->dir_in != point->dir_out )
continue;
if ( !psh_point_is_extremum( point ) &&
!psh_point_is_inflex( point ) )
continue;
point->flags &= ~PSH_POINT_SMOOTH;
}
/* find best enclosing point coordinates then interpolate */
{
PSH_Point before, after;
FT_UInt nn;
for ( nn = 0; nn < num_strongs; nn++ )
if ( strongs[nn]->org_u > point->org_u )
break;
if ( nn == 0 ) /* point before the first strong point */
{
after = strongs[0];
point->cur_u = after->cur_u +
FT_MulFix( point->org_u - after->org_u,
scale );
}
else
{
before = strongs[nn - 1];
for ( nn = num_strongs; nn > 0; nn-- )
if ( strongs[nn - 1]->org_u < point->org_u )
break;
if ( nn == num_strongs ) /* point is after last strong point */
{
before = strongs[nn - 1];
point->cur_u = before->cur_u +
FT_MulFix( point->org_u - before->org_u,
scale );
}
else
{
FT_Pos u;
after = strongs[nn];
/* now interpolate point between before and after */
u = point->org_u;
if ( u == before->org_u )
point->cur_u = before->cur_u;
else if ( u == after->org_u )
point->cur_u = after->cur_u;
else
point->cur_u = before->cur_u +
FT_MulDiv( u - before->org_u,
after->cur_u - before->cur_u,
after->org_u - before->org_u );
}
}
psh_point_set_fitted( point );
}
}
if ( strongs != strongs_0 )
FT_FREE( strongs );
#endif /* 1 */
}
/* interpolate other points */
static void
psh_glyph_interpolate_other_points( PSH_Glyph glyph,
FT_Int dimension )
{
PSH_Dimension dim = &glyph->globals->dimension[dimension];
FT_Fixed scale = dim->scale_mult;
FT_Fixed delta = dim->scale_delta;
PSH_Contour contour = glyph->contours;
FT_UInt num_contours = glyph->num_contours;
for ( ; num_contours > 0; num_contours--, contour++ )
{
PSH_Point start = contour->start;
PSH_Point first, next, point;
FT_UInt fit_count;
/* count the number of strong points in this contour */
next = start + contour->count;
fit_count = 0;
first = 0;
for ( point = start; point < next; point++ )
if ( psh_point_is_fitted( point ) )
{
if ( !first )
first = point;
fit_count++;
}
/* if there are less than 2 fitted points in the contour, we */
/* simply scale and eventually translate the contour points */
if ( fit_count < 2 )
{
if ( fit_count == 1 )
delta = first->cur_u - FT_MulFix( first->org_u, scale );
for ( point = start; point < next; point++ )
if ( point != first )
point->cur_u = FT_MulFix( point->org_u, scale ) + delta;
goto Next_Contour;
}
/* there are more than 2 strong points in this contour; we */
/* need to interpolate weak points between them */
start = first;
do
{
/* skip consecutive fitted points */
for (;;)
{
next = first->next;
if ( next == start )
goto Next_Contour;
if ( !psh_point_is_fitted( next ) )
break;
first = next;
}
/* find next fitted point after unfitted one */
for (;;)
{
next = next->next;
if ( psh_point_is_fitted( next ) )
break;
}
/* now interpolate between them */
{
FT_Pos org_a, org_ab, cur_a, cur_ab;
FT_Pos org_c, org_ac, cur_c;
FT_Fixed scale_ab;
if ( first->org_u <= next->org_u )
{
org_a = first->org_u;
cur_a = first->cur_u;
org_ab = next->org_u - org_a;
cur_ab = next->cur_u - cur_a;
}
else
{
org_a = next->org_u;
cur_a = next->cur_u;
org_ab = first->org_u - org_a;
cur_ab = first->cur_u - cur_a;
}
scale_ab = 0x10000L;
if ( org_ab > 0 )
scale_ab = FT_DivFix( cur_ab, org_ab );
point = first->next;
do
{
org_c = point->org_u;
org_ac = org_c - org_a;
if ( org_ac <= 0 )
{
/* on the left of the interpolation zone */
cur_c = cur_a + FT_MulFix( org_ac, scale );
}
else if ( org_ac >= org_ab )
{
/* on the right on the interpolation zone */
cur_c = cur_a + cur_ab + FT_MulFix( org_ac - org_ab, scale );
}
else
{
/* within the interpolation zone */
cur_c = cur_a + FT_MulFix( org_ac, scale_ab );
}
point->cur_u = cur_c;
point = point->next;
} while ( point != next );
}
/* keep going until all points in the contours have been processed */
first = next;
} while ( first != start );
Next_Contour:
;
}
}
/*************************************************************************/
/*************************************************************************/
/***** *****/
/***** HIGH-LEVEL INTERFACE *****/
/***** *****/
/*************************************************************************/
/*************************************************************************/
FT_Error
ps_hints_apply( PS_Hints ps_hints,
FT_Outline* outline,
PSH_Globals globals,
FT_Render_Mode hint_mode )
{
PSH_GlyphRec glyphrec;
PSH_Glyph glyph = &glyphrec;
FT_Error error;
#ifdef DEBUG_HINTER
FT_Memory memory;
#endif
FT_Int dimension;
/* something to do? */
if ( outline->n_points == 0 || outline->n_contours == 0 )
return FT_Err_Ok;
#ifdef DEBUG_HINTER
memory = globals->memory;
if ( ps_debug_glyph )
{
psh_glyph_done( ps_debug_glyph );
FT_FREE( ps_debug_glyph );
}
if ( FT_NEW( glyph ) )
return error;
ps_debug_glyph = glyph;
#endif /* DEBUG_HINTER */
error = psh_glyph_init( glyph, outline, ps_hints, globals );
if ( error )
goto Exit;
/* try to optimize the y_scale so that the top of non-capital letters
* is aligned on a pixel boundary whenever possible
*/
{
PSH_Dimension dim_x = &glyph->globals->dimension[0];
PSH_Dimension dim_y = &glyph->globals->dimension[1];
FT_Fixed x_scale = dim_x->scale_mult;
FT_Fixed y_scale = dim_y->scale_mult;
FT_Fixed old_x_scale = x_scale;
FT_Fixed old_y_scale = y_scale;
FT_Fixed scaled;
FT_Fixed fitted;
FT_Bool rescale = FALSE;
scaled = FT_MulFix( globals->blues.normal_top.zones->org_ref, y_scale );
fitted = FT_PIX_ROUND( scaled );
if ( fitted != 0 && scaled != fitted )
{
rescale = TRUE;
y_scale = FT_MulDiv( y_scale, fitted, scaled );
if ( fitted < scaled )
x_scale -= x_scale / 50;
psh_globals_set_scale( glyph->globals, x_scale, y_scale, 0, 0 );
}
glyph->do_horz_hints = 1;
glyph->do_vert_hints = 1;
glyph->do_horz_snapping = FT_BOOL( hint_mode == FT_RENDER_MODE_MONO ||
hint_mode == FT_RENDER_MODE_LCD );
glyph->do_vert_snapping = FT_BOOL( hint_mode == FT_RENDER_MODE_MONO ||
hint_mode == FT_RENDER_MODE_LCD_V );
glyph->do_stem_adjust = FT_BOOL( hint_mode != FT_RENDER_MODE_LIGHT );
for ( dimension = 0; dimension < 2; dimension++ )
{
/* load outline coordinates into glyph */
psh_glyph_load_points( glyph, dimension );
/* compute local extrema */
psh_glyph_compute_extrema( glyph );
/* compute aligned stem/hints positions */
psh_hint_table_align_hints( &glyph->hint_tables[dimension],
glyph->globals,
dimension,
glyph );
/* find strong points, align them, then interpolate others */
psh_glyph_find_strong_points( glyph, dimension );
if ( dimension == 1 )
psh_glyph_find_blue_points( &globals->blues, glyph );
psh_glyph_interpolate_strong_points( glyph, dimension );
psh_glyph_interpolate_normal_points( glyph, dimension );
psh_glyph_interpolate_other_points( glyph, dimension );
/* save hinted coordinates back to outline */
psh_glyph_save_points( glyph, dimension );
if ( rescale )
psh_globals_set_scale( glyph->globals,
old_x_scale, old_y_scale, 0, 0 );
}
}
Exit:
#ifndef DEBUG_HINTER
psh_glyph_done( glyph );
#endif
return error;
}
/* END */
|
gpl-3.0
|
histech/shadowsocks-android
|
src/main/jni/openssl/crypto/ex_data.c
|
731
|
21405
|
/* crypto/ex_data.c */
/*
* Overhaul notes;
*
* This code is now *mostly* thread-safe. It is now easier to understand in what
* ways it is safe and in what ways it is not, which is an improvement. Firstly,
* all per-class stacks and index-counters for ex_data are stored in the same
* global LHASH table (keyed by class). This hash table uses locking for all
* access with the exception of CRYPTO_cleanup_all_ex_data(), which must only be
* called when no other threads can possibly race against it (even if it was
* locked, the race would mean it's possible the hash table might have been
* recreated after the cleanup). As classes can only be added to the hash table,
* and within each class, the stack of methods can only be incremented, the
* locking mechanics are simpler than they would otherwise be. For example, the
* new/dup/free ex_data functions will lock the hash table, copy the method
* pointers it needs from the relevant class, then unlock the hash table before
* actually applying those method pointers to the task of the new/dup/free
* operations. As they can't be removed from the method-stack, only
* supplemented, there's no race conditions associated with using them outside
* the lock. The get/set_ex_data functions are not locked because they do not
* involve this global state at all - they operate directly with a previously
* obtained per-class method index and a particular "ex_data" variable. These
* variables are usually instantiated per-context (eg. each RSA structure has
* one) so locking on read/write access to that variable can be locked locally
* if required (eg. using the "RSA" lock to synchronise access to a
* per-RSA-structure ex_data variable if required).
* [Geoff]
*/
/* 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.]
*/
/* ====================================================================
* Copyright (c) 1998-2001 The OpenSSL Project. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. All advertising materials mentioning features or use of this
* software must display the following acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
*
* 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
* endorse or promote products derived from this software without
* prior written permission. For written permission, please contact
* openssl-core@openssl.org.
*
* 5. Products derived from this software may not be called "OpenSSL"
* nor may "OpenSSL" appear in their names without prior written
* permission of the OpenSSL Project.
*
* 6. Redistributions of any form whatsoever must retain the following
* acknowledgment:
* "This product includes software developed by the OpenSSL Project
* for use in the OpenSSL Toolkit (http://www.openssl.org/)"
*
* THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
* EXPRESSED 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 OpenSSL PROJECT OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
* ====================================================================
*
* This product includes cryptographic software written by Eric Young
* (eay@cryptsoft.com). This product includes software written by Tim
* Hudson (tjh@cryptsoft.com).
*
*/
#include "cryptlib.h"
#include <openssl/lhash.h>
/* What an "implementation of ex_data functionality" looks like */
struct st_CRYPTO_EX_DATA_IMPL
{
/*********************/
/* GLOBAL OPERATIONS */
/* Return a new class index */
int (*cb_new_class)(void);
/* Cleanup all state used by the implementation */
void (*cb_cleanup)(void);
/************************/
/* PER-CLASS OPERATIONS */
/* Get a new method index within a class */
int (*cb_get_new_index)(int class_index, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
/* Initialise a new CRYPTO_EX_DATA of a given class */
int (*cb_new_ex_data)(int class_index, void *obj,
CRYPTO_EX_DATA *ad);
/* Duplicate a CRYPTO_EX_DATA of a given class onto a copy */
int (*cb_dup_ex_data)(int class_index, CRYPTO_EX_DATA *to,
CRYPTO_EX_DATA *from);
/* Cleanup a CRYPTO_EX_DATA of a given class */
void (*cb_free_ex_data)(int class_index, void *obj,
CRYPTO_EX_DATA *ad);
};
/* The implementation we use at run-time */
static const CRYPTO_EX_DATA_IMPL *impl = NULL;
/* To call "impl" functions, use this macro rather than referring to 'impl' directly, eg.
* EX_IMPL(get_new_index)(...); */
#define EX_IMPL(a) impl->cb_##a
/* Predeclare the "default" ex_data implementation */
static int int_new_class(void);
static void int_cleanup(void);
static int int_get_new_index(int class_index, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func);
static int int_new_ex_data(int class_index, void *obj,
CRYPTO_EX_DATA *ad);
static int int_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
CRYPTO_EX_DATA *from);
static void int_free_ex_data(int class_index, void *obj,
CRYPTO_EX_DATA *ad);
static CRYPTO_EX_DATA_IMPL impl_default =
{
int_new_class,
int_cleanup,
int_get_new_index,
int_new_ex_data,
int_dup_ex_data,
int_free_ex_data
};
/* Internal function that checks whether "impl" is set and if not, sets it to
* the default. */
static void impl_check(void)
{
CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
if(!impl)
impl = &impl_default;
CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
}
/* A macro wrapper for impl_check that first uses a non-locked test before
* invoking the function (which checks again inside a lock). */
#define IMPL_CHECK if(!impl) impl_check();
/* API functions to get/set the "ex_data" implementation */
const CRYPTO_EX_DATA_IMPL *CRYPTO_get_ex_data_implementation(void)
{
IMPL_CHECK
return impl;
}
int CRYPTO_set_ex_data_implementation(const CRYPTO_EX_DATA_IMPL *i)
{
int toret = 0;
CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
if(!impl)
{
impl = i;
toret = 1;
}
CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
return toret;
}
/****************************************************************************/
/* Interal (default) implementation of "ex_data" support. API functions are
* further down. */
/* The type that represents what each "class" used to implement locally. A STACK
* of CRYPTO_EX_DATA_FUNCS plus a index-counter. The 'class_index' is the global
* value representing the class that is used to distinguish these items. */
typedef struct st_ex_class_item {
int class_index;
STACK_OF(CRYPTO_EX_DATA_FUNCS) *meth;
int meth_num;
} EX_CLASS_ITEM;
/* When assigning new class indexes, this is our counter */
static int ex_class = CRYPTO_EX_INDEX_USER;
/* The global hash table of EX_CLASS_ITEM items */
DECLARE_LHASH_OF(EX_CLASS_ITEM);
static LHASH_OF(EX_CLASS_ITEM) *ex_data = NULL;
/* The callbacks required in the "ex_data" hash table */
static unsigned long ex_class_item_hash(const EX_CLASS_ITEM *a)
{
return a->class_index;
}
static IMPLEMENT_LHASH_HASH_FN(ex_class_item, EX_CLASS_ITEM)
static int ex_class_item_cmp(const EX_CLASS_ITEM *a, const EX_CLASS_ITEM *b)
{
return a->class_index - b->class_index;
}
static IMPLEMENT_LHASH_COMP_FN(ex_class_item, EX_CLASS_ITEM)
/* Internal functions used by the "impl_default" implementation to access the
* state */
static int ex_data_check(void)
{
int toret = 1;
CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
if(!ex_data
&& (ex_data = lh_EX_CLASS_ITEM_new()) == NULL)
toret = 0;
CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
return toret;
}
/* This macros helps reduce the locking from repeated checks because the
* ex_data_check() function checks ex_data again inside a lock. */
#define EX_DATA_CHECK(iffail) if(!ex_data && !ex_data_check()) {iffail}
/* This "inner" callback is used by the callback function that follows it */
static void def_cleanup_util_cb(CRYPTO_EX_DATA_FUNCS *funcs)
{
OPENSSL_free(funcs);
}
/* This callback is used in lh_doall to destroy all EX_CLASS_ITEM values from
* "ex_data" prior to the ex_data hash table being itself destroyed. Doesn't do
* any locking. */
static void def_cleanup_cb(void *a_void)
{
EX_CLASS_ITEM *item = (EX_CLASS_ITEM *)a_void;
sk_CRYPTO_EX_DATA_FUNCS_pop_free(item->meth, def_cleanup_util_cb);
OPENSSL_free(item);
}
/* Return the EX_CLASS_ITEM from the "ex_data" hash table that corresponds to a
* given class. Handles locking. */
static EX_CLASS_ITEM *def_get_class(int class_index)
{
EX_CLASS_ITEM d, *p, *gen;
EX_DATA_CHECK(return NULL;)
d.class_index = class_index;
CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
p = lh_EX_CLASS_ITEM_retrieve(ex_data, &d);
if(!p)
{
gen = OPENSSL_malloc(sizeof(EX_CLASS_ITEM));
if(gen)
{
gen->class_index = class_index;
gen->meth_num = 0;
gen->meth = sk_CRYPTO_EX_DATA_FUNCS_new_null();
if(!gen->meth)
OPENSSL_free(gen);
else
{
/* Because we're inside the ex_data lock, the
* return value from the insert will be NULL */
(void)lh_EX_CLASS_ITEM_insert(ex_data, gen);
p = gen;
}
}
}
CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
if(!p)
CRYPTOerr(CRYPTO_F_DEF_GET_CLASS,ERR_R_MALLOC_FAILURE);
return p;
}
/* Add a new method to the given EX_CLASS_ITEM and return the corresponding
* index (or -1 for error). Handles locking. */
static int def_add_index(EX_CLASS_ITEM *item, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
int toret = -1;
CRYPTO_EX_DATA_FUNCS *a = (CRYPTO_EX_DATA_FUNCS *)OPENSSL_malloc(
sizeof(CRYPTO_EX_DATA_FUNCS));
if(!a)
{
CRYPTOerr(CRYPTO_F_DEF_ADD_INDEX,ERR_R_MALLOC_FAILURE);
return -1;
}
a->argl=argl;
a->argp=argp;
a->new_func=new_func;
a->dup_func=dup_func;
a->free_func=free_func;
CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
while (sk_CRYPTO_EX_DATA_FUNCS_num(item->meth) <= item->meth_num)
{
if (!sk_CRYPTO_EX_DATA_FUNCS_push(item->meth, NULL))
{
CRYPTOerr(CRYPTO_F_DEF_ADD_INDEX,ERR_R_MALLOC_FAILURE);
OPENSSL_free(a);
goto err;
}
}
toret = item->meth_num++;
(void)sk_CRYPTO_EX_DATA_FUNCS_set(item->meth, toret, a);
err:
CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
return toret;
}
/**************************************************************/
/* The functions in the default CRYPTO_EX_DATA_IMPL structure */
static int int_new_class(void)
{
int toret;
CRYPTO_w_lock(CRYPTO_LOCK_EX_DATA);
toret = ex_class++;
CRYPTO_w_unlock(CRYPTO_LOCK_EX_DATA);
return toret;
}
static void int_cleanup(void)
{
EX_DATA_CHECK(return;)
lh_EX_CLASS_ITEM_doall(ex_data, def_cleanup_cb);
lh_EX_CLASS_ITEM_free(ex_data);
ex_data = NULL;
impl = NULL;
}
static int int_get_new_index(int class_index, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
EX_CLASS_ITEM *item = def_get_class(class_index);
if(!item)
return -1;
return def_add_index(item, argl, argp, new_func, dup_func, free_func);
}
/* Thread-safe by copying a class's array of "CRYPTO_EX_DATA_FUNCS" entries in
* the lock, then using them outside the lock. NB: Thread-safety only applies to
* the global "ex_data" state (ie. class definitions), not thread-safe on 'ad'
* itself. */
static int int_new_ex_data(int class_index, void *obj,
CRYPTO_EX_DATA *ad)
{
int mx,i;
void *ptr;
CRYPTO_EX_DATA_FUNCS **storage = NULL;
EX_CLASS_ITEM *item = def_get_class(class_index);
if(!item)
/* error is already set */
return 0;
ad->sk = NULL;
CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
mx = sk_CRYPTO_EX_DATA_FUNCS_num(item->meth);
if(mx > 0)
{
storage = OPENSSL_malloc(mx * sizeof(CRYPTO_EX_DATA_FUNCS*));
if(!storage)
goto skip;
for(i = 0; i < mx; i++)
storage[i] = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth,i);
}
skip:
CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
if((mx > 0) && !storage)
{
CRYPTOerr(CRYPTO_F_INT_NEW_EX_DATA,ERR_R_MALLOC_FAILURE);
return 0;
}
for(i = 0; i < mx; i++)
{
if(storage[i] && storage[i]->new_func)
{
ptr = CRYPTO_get_ex_data(ad, i);
storage[i]->new_func(obj,ptr,ad,i,
storage[i]->argl,storage[i]->argp);
}
}
if(storage)
OPENSSL_free(storage);
return 1;
}
/* Same thread-safety notes as for "int_new_ex_data" */
static int int_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
CRYPTO_EX_DATA *from)
{
int mx, j, i;
char *ptr;
CRYPTO_EX_DATA_FUNCS **storage = NULL;
EX_CLASS_ITEM *item;
if(!from->sk)
/* 'to' should be "blank" which *is* just like 'from' */
return 1;
if((item = def_get_class(class_index)) == NULL)
return 0;
CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
mx = sk_CRYPTO_EX_DATA_FUNCS_num(item->meth);
j = sk_void_num(from->sk);
if(j < mx)
mx = j;
if(mx > 0)
{
storage = OPENSSL_malloc(mx * sizeof(CRYPTO_EX_DATA_FUNCS*));
if(!storage)
goto skip;
for(i = 0; i < mx; i++)
storage[i] = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth,i);
}
skip:
CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
if((mx > 0) && !storage)
{
CRYPTOerr(CRYPTO_F_INT_DUP_EX_DATA,ERR_R_MALLOC_FAILURE);
return 0;
}
for(i = 0; i < mx; i++)
{
ptr = CRYPTO_get_ex_data(from, i);
if(storage[i] && storage[i]->dup_func)
storage[i]->dup_func(to,from,&ptr,i,
storage[i]->argl,storage[i]->argp);
CRYPTO_set_ex_data(to,i,ptr);
}
if(storage)
OPENSSL_free(storage);
return 1;
}
/* Same thread-safety notes as for "int_new_ex_data" */
static void int_free_ex_data(int class_index, void *obj,
CRYPTO_EX_DATA *ad)
{
int mx,i;
EX_CLASS_ITEM *item;
void *ptr;
CRYPTO_EX_DATA_FUNCS **storage = NULL;
if((item = def_get_class(class_index)) == NULL)
return;
CRYPTO_r_lock(CRYPTO_LOCK_EX_DATA);
mx = sk_CRYPTO_EX_DATA_FUNCS_num(item->meth);
if(mx > 0)
{
storage = OPENSSL_malloc(mx * sizeof(CRYPTO_EX_DATA_FUNCS*));
if(!storage)
goto skip;
for(i = 0; i < mx; i++)
storage[i] = sk_CRYPTO_EX_DATA_FUNCS_value(item->meth,i);
}
skip:
CRYPTO_r_unlock(CRYPTO_LOCK_EX_DATA);
if((mx > 0) && !storage)
{
CRYPTOerr(CRYPTO_F_INT_FREE_EX_DATA,ERR_R_MALLOC_FAILURE);
return;
}
for(i = 0; i < mx; i++)
{
if(storage[i] && storage[i]->free_func)
{
ptr = CRYPTO_get_ex_data(ad,i);
storage[i]->free_func(obj,ptr,ad,i,
storage[i]->argl,storage[i]->argp);
}
}
if(storage)
OPENSSL_free(storage);
if(ad->sk)
{
sk_void_free(ad->sk);
ad->sk=NULL;
}
}
/********************************************************************/
/* API functions that defer all "state" operations to the "ex_data"
* implementation we have set. */
/* Obtain an index for a new class (not the same as getting a new index within
* an existing class - this is actually getting a new *class*) */
int CRYPTO_ex_data_new_class(void)
{
IMPL_CHECK
return EX_IMPL(new_class)();
}
/* Release all "ex_data" state to prevent memory leaks. This can't be made
* thread-safe without overhauling a lot of stuff, and shouldn't really be
* called under potential race-conditions anyway (it's for program shutdown
* after all). */
void CRYPTO_cleanup_all_ex_data(void)
{
IMPL_CHECK
EX_IMPL(cleanup)();
}
/* Inside an existing class, get/register a new index. */
int CRYPTO_get_ex_new_index(int class_index, long argl, void *argp,
CRYPTO_EX_new *new_func, CRYPTO_EX_dup *dup_func,
CRYPTO_EX_free *free_func)
{
int ret = -1;
IMPL_CHECK
ret = EX_IMPL(get_new_index)(class_index,
argl, argp, new_func, dup_func, free_func);
return ret;
}
/* Initialise a new CRYPTO_EX_DATA for use in a particular class - including
* calling new() callbacks for each index in the class used by this variable */
int CRYPTO_new_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
{
IMPL_CHECK
return EX_IMPL(new_ex_data)(class_index, obj, ad);
}
/* Duplicate a CRYPTO_EX_DATA variable - including calling dup() callbacks for
* each index in the class used by this variable */
int CRYPTO_dup_ex_data(int class_index, CRYPTO_EX_DATA *to,
CRYPTO_EX_DATA *from)
{
IMPL_CHECK
return EX_IMPL(dup_ex_data)(class_index, to, from);
}
/* Cleanup a CRYPTO_EX_DATA variable - including calling free() callbacks for
* each index in the class used by this variable */
void CRYPTO_free_ex_data(int class_index, void *obj, CRYPTO_EX_DATA *ad)
{
IMPL_CHECK
EX_IMPL(free_ex_data)(class_index, obj, ad);
}
/* For a given CRYPTO_EX_DATA variable, set the value corresponding to a
* particular index in the class used by this variable */
int CRYPTO_set_ex_data(CRYPTO_EX_DATA *ad, int idx, void *val)
{
int i;
if (ad->sk == NULL)
{
if ((ad->sk=sk_void_new_null()) == NULL)
{
CRYPTOerr(CRYPTO_F_CRYPTO_SET_EX_DATA,ERR_R_MALLOC_FAILURE);
return(0);
}
}
i=sk_void_num(ad->sk);
while (i <= idx)
{
if (!sk_void_push(ad->sk,NULL))
{
CRYPTOerr(CRYPTO_F_CRYPTO_SET_EX_DATA,ERR_R_MALLOC_FAILURE);
return(0);
}
i++;
}
sk_void_set(ad->sk,idx,val);
return(1);
}
/* For a given CRYPTO_EX_DATA_ variable, get the value corresponding to a
* particular index in the class used by this variable */
void *CRYPTO_get_ex_data(const CRYPTO_EX_DATA *ad, int idx)
{
if (ad->sk == NULL)
return(0);
else if (idx >= sk_void_num(ad->sk))
return(0);
else
return(sk_void_value(ad->sk,idx));
}
IMPLEMENT_STACK_OF(CRYPTO_EX_DATA_FUNCS)
|
gpl-3.0
|
CognetTestbed/COGNET_CODE
|
KERNEL_SOURCE_CODE/grouper/drivers/staging/altera-stapl/altera-lpt.c
|
13020
|
1747
|
/*
* altera-lpt.c
*
* altera FPGA driver
*
* Copyright (C) Altera Corporation 1998-2001
* Copyright (C) 2010 NetUP Inc.
* Copyright (C) 2010 Abylay Ospan <aospan@netup.ru>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
*
* GNU General Public License for more details.
*
* 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 "altera-exprt.h"
static int lpt_hardware_initialized;
static void byteblaster_write(int port, int data)
{
outb((u8)data, (u16)(port + 0x378));
};
static int byteblaster_read(int port)
{
int data = 0;
data = inb((u16)(port + 0x378));
return data & 0xff;
};
int netup_jtag_io_lpt(void *device, int tms, int tdi, int read_tdo)
{
int data = 0;
int tdo = 0;
int initial_lpt_ctrl = 0;
if (!lpt_hardware_initialized) {
initial_lpt_ctrl = byteblaster_read(2);
byteblaster_write(2, (initial_lpt_ctrl | 0x02) & 0xdf);
lpt_hardware_initialized = 1;
}
data = ((tdi ? 0x40 : 0) | (tms ? 0x02 : 0));
byteblaster_write(0, data);
if (read_tdo) {
tdo = byteblaster_read(1);
tdo = ((tdo & 0x80) ? 0 : 1);
}
byteblaster_write(0, data | 0x01);
byteblaster_write(0, data);
return tdo;
}
|
gpl-3.0
|
AKuHAK/xcover3ltexx_custom_kernel
|
drivers/net/wireless/rtlwifi/rtl8723ae/led.c
|
2783
|
4450
|
/******************************************************************************
*
* Copyright(c) 2009-2012 Realtek Corporation.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of version 2 of the GNU General Public License as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110, USA
*
* The full GNU General Public License is included in this distribution in the
* file called LICENSE.
*
* Contact Information:
* wlanfae <wlanfae@realtek.com>
* Realtek Corporation, No. 2, Innovation Road II, Hsinchu Science Park,
* Hsinchu 300, Taiwan.
*
* Larry Finger <Larry.Finger@lwfinger.net>
*
*****************************************************************************/
#include "../wifi.h"
#include "../pci.h"
#include "reg.h"
#include "led.h"
static void _rtl8723ae_init_led(struct ieee80211_hw *hw,
struct rtl_led *pled, enum rtl_led_pin ledpin)
{
pled->hw = hw;
pled->ledpin = ledpin;
pled->ledon = false;
}
void rtl8723ae_sw_led_on(struct ieee80211_hw *hw, struct rtl_led *pled)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
u8 ledcfg;
RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD,
"LedAddr:%X ledpin=%d\n", REG_LEDCFG2, pled->ledpin);
ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG2);
switch (pled->ledpin) {
case LED_PIN_GPIO0:
break;
case LED_PIN_LED0:
ledcfg &= ~BIT(6);
rtl_write_byte(rtlpriv,
REG_LEDCFG2, (ledcfg & 0xf0) | BIT(5));
break;
case LED_PIN_LED1:
rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg & 0x0f) | BIT(5));
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
pled->ledon = true;
}
void rtl8723ae_sw_led_off(struct ieee80211_hw *hw, struct rtl_led *pled)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
u8 ledcfg;
RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD,
"LedAddr:%X ledpin=%d\n", REG_LEDCFG2, pled->ledpin);
ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG2);
switch (pled->ledpin) {
case LED_PIN_GPIO0:
break;
case LED_PIN_LED0:
ledcfg &= 0xf0;
if (pcipriv->ledctl.led_opendrain) {
ledcfg &= 0x90;
rtl_write_byte(rtlpriv, REG_LEDCFG2, (ledcfg|BIT(3)));
ledcfg = rtl_read_byte(rtlpriv, REG_MAC_PINMUX_CFG);
ledcfg &= 0xFE;
rtl_write_byte(rtlpriv, REG_MAC_PINMUX_CFG, ledcfg);
} else {
ledcfg &= ~BIT(6);
rtl_write_byte(rtlpriv, REG_LEDCFG2,
(ledcfg | BIT(3) | BIT(5)));
}
break;
case LED_PIN_LED1:
ledcfg = rtl_read_byte(rtlpriv, REG_LEDCFG1) & 0x10;
rtl_write_byte(rtlpriv, REG_LEDCFG1, (ledcfg | BIT(3)));
break;
default:
RT_TRACE(rtlpriv, COMP_ERR, DBG_EMERG,
"switch case not processed\n");
break;
}
pled->ledon = false;
}
void rtl8723ae_init_sw_leds(struct ieee80211_hw *hw)
{
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
_rtl8723ae_init_led(hw, &(pcipriv->ledctl.sw_led0), LED_PIN_LED0);
_rtl8723ae_init_led(hw, &(pcipriv->ledctl.sw_led1), LED_PIN_LED1);
}
static void _rtl8723ae_sw_led_control(struct ieee80211_hw *hw,
enum led_ctl_mode ledaction)
{
struct rtl_pci_priv *pcipriv = rtl_pcipriv(hw);
struct rtl_led *pLed0 = &(pcipriv->ledctl.sw_led0);
switch (ledaction) {
case LED_CTL_POWER_ON:
case LED_CTL_LINK:
case LED_CTL_NO_LINK:
rtl8723ae_sw_led_on(hw, pLed0);
break;
case LED_CTL_POWER_OFF:
rtl8723ae_sw_led_off(hw, pLed0);
break;
default:
break;
}
}
void rtl8723ae_led_control(struct ieee80211_hw *hw, enum led_ctl_mode ledaction)
{
struct rtl_priv *rtlpriv = rtl_priv(hw);
struct rtl_ps_ctl *ppsc = rtl_psc(rtl_priv(hw));
if ((ppsc->rfoff_reason > RF_CHANGE_BY_PS) &&
(ledaction == LED_CTL_TX ||
ledaction == LED_CTL_RX ||
ledaction == LED_CTL_SITE_SURVEY ||
ledaction == LED_CTL_LINK ||
ledaction == LED_CTL_NO_LINK ||
ledaction == LED_CTL_START_TO_LINK ||
ledaction == LED_CTL_POWER_ON)) {
return;
}
RT_TRACE(rtlpriv, COMP_LED, DBG_LOUD, "ledaction %d,\n", ledaction);
_rtl8723ae_sw_led_control(hw, ledaction);
}
|
gpl-3.0
|
adomasalcore3/android_kernel_Vodafone_VDF600
|
drivers/net/wireless/ath/ath9k/htc_drv_debug.c
|
2280
|
30597
|
/*
* Copyright (c) 2010-2011 Atheros Communications Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include "htc.h"
static ssize_t read_file_tgt_int_stats(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
struct ath9k_htc_target_int_stats cmd_rsp;
char buf[512];
unsigned int len = 0;
int ret = 0;
memset(&cmd_rsp, 0, sizeof(cmd_rsp));
ath9k_htc_ps_wakeup(priv);
WMI_CMD(WMI_INT_STATS_CMDID);
if (ret) {
ath9k_htc_ps_restore(priv);
return -EINVAL;
}
ath9k_htc_ps_restore(priv);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "RX",
be32_to_cpu(cmd_rsp.rx));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "RXORN",
be32_to_cpu(cmd_rsp.rxorn));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "RXEOL",
be32_to_cpu(cmd_rsp.rxeol));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "TXURN",
be32_to_cpu(cmd_rsp.txurn));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "TXTO",
be32_to_cpu(cmd_rsp.txto));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "CST",
be32_to_cpu(cmd_rsp.cst));
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_tgt_int_stats = {
.read = read_file_tgt_int_stats,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_tgt_tx_stats(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
struct ath9k_htc_target_tx_stats cmd_rsp;
char buf[512];
unsigned int len = 0;
int ret = 0;
memset(&cmd_rsp, 0, sizeof(cmd_rsp));
ath9k_htc_ps_wakeup(priv);
WMI_CMD(WMI_TX_STATS_CMDID);
if (ret) {
ath9k_htc_ps_restore(priv);
return -EINVAL;
}
ath9k_htc_ps_restore(priv);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "Xretries",
be32_to_cpu(cmd_rsp.xretries));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "FifoErr",
be32_to_cpu(cmd_rsp.fifoerr));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "Filtered",
be32_to_cpu(cmd_rsp.filtered));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "TimerExp",
be32_to_cpu(cmd_rsp.timer_exp));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "ShortRetries",
be32_to_cpu(cmd_rsp.shortretries));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "LongRetries",
be32_to_cpu(cmd_rsp.longretries));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "QueueNull",
be32_to_cpu(cmd_rsp.qnull));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "EncapFail",
be32_to_cpu(cmd_rsp.encap_fail));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "NoBuf",
be32_to_cpu(cmd_rsp.nobuf));
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_tgt_tx_stats = {
.read = read_file_tgt_tx_stats,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_tgt_rx_stats(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
struct ath9k_htc_target_rx_stats cmd_rsp;
char buf[512];
unsigned int len = 0;
int ret = 0;
memset(&cmd_rsp, 0, sizeof(cmd_rsp));
ath9k_htc_ps_wakeup(priv);
WMI_CMD(WMI_RX_STATS_CMDID);
if (ret) {
ath9k_htc_ps_restore(priv);
return -EINVAL;
}
ath9k_htc_ps_restore(priv);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "NoBuf",
be32_to_cpu(cmd_rsp.nobuf));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "HostSend",
be32_to_cpu(cmd_rsp.host_send));
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "HostDone",
be32_to_cpu(cmd_rsp.host_done));
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_tgt_rx_stats = {
.read = read_file_tgt_rx_stats,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_xmit(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
char buf[512];
unsigned int len = 0;
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "Buffers queued",
priv->debug.tx_stats.buf_queued);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "Buffers completed",
priv->debug.tx_stats.buf_completed);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "SKBs queued",
priv->debug.tx_stats.skb_queued);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "SKBs success",
priv->debug.tx_stats.skb_success);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "SKBs failed",
priv->debug.tx_stats.skb_failed);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "CAB queued",
priv->debug.tx_stats.cab_queued);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "BE queued",
priv->debug.tx_stats.queue_stats[IEEE80211_AC_BE]);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "BK queued",
priv->debug.tx_stats.queue_stats[IEEE80211_AC_BK]);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "VI queued",
priv->debug.tx_stats.queue_stats[IEEE80211_AC_VI]);
len += snprintf(buf + len, sizeof(buf) - len,
"%20s : %10u\n", "VO queued",
priv->debug.tx_stats.queue_stats[IEEE80211_AC_VO]);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_xmit = {
.read = read_file_xmit,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
void ath9k_htc_err_stat_rx(struct ath9k_htc_priv *priv,
struct ath_htc_rx_status *rxs)
{
#define RX_PHY_ERR_INC(c) priv->debug.rx_stats.err_phy_stats[c]++
if (rxs->rs_status & ATH9K_RXERR_CRC)
priv->debug.rx_stats.err_crc++;
if (rxs->rs_status & ATH9K_RXERR_DECRYPT)
priv->debug.rx_stats.err_decrypt_crc++;
if (rxs->rs_status & ATH9K_RXERR_MIC)
priv->debug.rx_stats.err_mic++;
if (rxs->rs_status & ATH9K_RX_DELIM_CRC_PRE)
priv->debug.rx_stats.err_pre_delim++;
if (rxs->rs_status & ATH9K_RX_DELIM_CRC_POST)
priv->debug.rx_stats.err_post_delim++;
if (rxs->rs_status & ATH9K_RX_DECRYPT_BUSY)
priv->debug.rx_stats.err_decrypt_busy++;
if (rxs->rs_status & ATH9K_RXERR_PHY) {
priv->debug.rx_stats.err_phy++;
if (rxs->rs_phyerr < ATH9K_PHYERR_MAX)
RX_PHY_ERR_INC(rxs->rs_phyerr);
}
#undef RX_PHY_ERR_INC
}
static ssize_t read_file_recv(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
#define PHY_ERR(s, p) \
len += snprintf(buf + len, size - len, "%20s : %10u\n", s, \
priv->debug.rx_stats.err_phy_stats[p]);
struct ath9k_htc_priv *priv = file->private_data;
char *buf;
unsigned int len = 0, size = 1500;
ssize_t retval = 0;
buf = kzalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "SKBs allocated",
priv->debug.rx_stats.skb_allocated);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "SKBs completed",
priv->debug.rx_stats.skb_completed);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "SKBs Dropped",
priv->debug.rx_stats.skb_dropped);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "CRC ERR",
priv->debug.rx_stats.err_crc);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "DECRYPT CRC ERR",
priv->debug.rx_stats.err_decrypt_crc);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "MIC ERR",
priv->debug.rx_stats.err_mic);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "PRE-DELIM CRC ERR",
priv->debug.rx_stats.err_pre_delim);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "POST-DELIM CRC ERR",
priv->debug.rx_stats.err_post_delim);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "DECRYPT BUSY ERR",
priv->debug.rx_stats.err_decrypt_busy);
len += snprintf(buf + len, size - len,
"%20s : %10u\n", "TOTAL PHY ERR",
priv->debug.rx_stats.err_phy);
PHY_ERR("UNDERRUN", ATH9K_PHYERR_UNDERRUN);
PHY_ERR("TIMING", ATH9K_PHYERR_TIMING);
PHY_ERR("PARITY", ATH9K_PHYERR_PARITY);
PHY_ERR("RATE", ATH9K_PHYERR_RATE);
PHY_ERR("LENGTH", ATH9K_PHYERR_LENGTH);
PHY_ERR("RADAR", ATH9K_PHYERR_RADAR);
PHY_ERR("SERVICE", ATH9K_PHYERR_SERVICE);
PHY_ERR("TOR", ATH9K_PHYERR_TOR);
PHY_ERR("OFDM-TIMING", ATH9K_PHYERR_OFDM_TIMING);
PHY_ERR("OFDM-SIGNAL-PARITY", ATH9K_PHYERR_OFDM_SIGNAL_PARITY);
PHY_ERR("OFDM-RATE", ATH9K_PHYERR_OFDM_RATE_ILLEGAL);
PHY_ERR("OFDM-LENGTH", ATH9K_PHYERR_OFDM_LENGTH_ILLEGAL);
PHY_ERR("OFDM-POWER-DROP", ATH9K_PHYERR_OFDM_POWER_DROP);
PHY_ERR("OFDM-SERVICE", ATH9K_PHYERR_OFDM_SERVICE);
PHY_ERR("OFDM-RESTART", ATH9K_PHYERR_OFDM_RESTART);
PHY_ERR("FALSE-RADAR-EXT", ATH9K_PHYERR_FALSE_RADAR_EXT);
PHY_ERR("CCK-TIMING", ATH9K_PHYERR_CCK_TIMING);
PHY_ERR("CCK-HEADER-CRC", ATH9K_PHYERR_CCK_HEADER_CRC);
PHY_ERR("CCK-RATE", ATH9K_PHYERR_CCK_RATE_ILLEGAL);
PHY_ERR("CCK-SERVICE", ATH9K_PHYERR_CCK_SERVICE);
PHY_ERR("CCK-RESTART", ATH9K_PHYERR_CCK_RESTART);
PHY_ERR("CCK-LENGTH", ATH9K_PHYERR_CCK_LENGTH_ILLEGAL);
PHY_ERR("CCK-POWER-DROP", ATH9K_PHYERR_CCK_POWER_DROP);
PHY_ERR("HT-CRC", ATH9K_PHYERR_HT_CRC_ERROR);
PHY_ERR("HT-LENGTH", ATH9K_PHYERR_HT_LENGTH_ILLEGAL);
PHY_ERR("HT-RATE", ATH9K_PHYERR_HT_RATE_ILLEGAL);
if (len > size)
len = size;
retval = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return retval;
#undef PHY_ERR
}
static const struct file_operations fops_recv = {
.read = read_file_recv,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_slot(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
char buf[512];
unsigned int len = 0;
spin_lock_bh(&priv->tx.tx_lock);
len += snprintf(buf + len, sizeof(buf) - len, "TX slot bitmap : ");
len += bitmap_scnprintf(buf + len, sizeof(buf) - len,
priv->tx.tx_slot, MAX_TX_BUF_NUM);
len += snprintf(buf + len, sizeof(buf) - len, "\n");
len += snprintf(buf + len, sizeof(buf) - len,
"Used slots : %d\n",
bitmap_weight(priv->tx.tx_slot, MAX_TX_BUF_NUM));
spin_unlock_bh(&priv->tx.tx_lock);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_slot = {
.read = read_file_slot,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_queue(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
char buf[512];
unsigned int len = 0;
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Mgmt endpoint", skb_queue_len(&priv->tx.mgmt_ep_queue));
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Cab endpoint", skb_queue_len(&priv->tx.cab_ep_queue));
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Data BE endpoint", skb_queue_len(&priv->tx.data_be_queue));
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Data BK endpoint", skb_queue_len(&priv->tx.data_bk_queue));
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Data VI endpoint", skb_queue_len(&priv->tx.data_vi_queue));
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Data VO endpoint", skb_queue_len(&priv->tx.data_vo_queue));
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Failed queue", skb_queue_len(&priv->tx.tx_failed));
spin_lock_bh(&priv->tx.tx_lock);
len += snprintf(buf + len, sizeof(buf) - len, "%20s : %10u\n",
"Queued count", priv->tx.queued_cnt);
spin_unlock_bh(&priv->tx.tx_lock);
if (len > sizeof(buf))
len = sizeof(buf);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static const struct file_operations fops_queue = {
.read = read_file_queue,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_debug(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
struct ath_common *common = ath9k_hw_common(priv->ah);
char buf[32];
unsigned int len;
len = sprintf(buf, "0x%08x\n", common->debug_mask);
return simple_read_from_buffer(user_buf, count, ppos, buf, len);
}
static ssize_t write_file_debug(struct file *file, const char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
struct ath_common *common = ath9k_hw_common(priv->ah);
unsigned long mask;
char buf[32];
ssize_t len;
len = min(count, sizeof(buf) - 1);
if (copy_from_user(buf, user_buf, len))
return -EFAULT;
buf[len] = '\0';
if (strict_strtoul(buf, 0, &mask))
return -EINVAL;
common->debug_mask = mask;
return count;
}
static const struct file_operations fops_debug = {
.read = read_file_debug,
.write = write_file_debug,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_file_base_eeprom(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
struct ath_common *common = ath9k_hw_common(priv->ah);
struct base_eep_header *pBase = NULL;
unsigned int len = 0, size = 1500;
ssize_t retval = 0;
char *buf;
/*
* This can be done since all the 3 EEPROM families have the
* same base header upto a certain point, and we are interested in
* the data only upto that point.
*/
if (AR_SREV_9271(priv->ah))
pBase = (struct base_eep_header *)
&priv->ah->eeprom.map4k.baseEepHeader;
else if (priv->ah->hw_version.usbdev == AR9280_USB)
pBase = (struct base_eep_header *)
&priv->ah->eeprom.def.baseEepHeader;
else if (priv->ah->hw_version.usbdev == AR9287_USB)
pBase = (struct base_eep_header *)
&priv->ah->eeprom.map9287.baseEepHeader;
if (pBase == NULL) {
ath_err(common, "Unknown EEPROM type\n");
return 0;
}
buf = kzalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
len += snprintf(buf + len, size - len,
"%20s : %10d\n", "Major Version",
pBase->version >> 12);
len += snprintf(buf + len, size - len,
"%20s : %10d\n", "Minor Version",
pBase->version & 0xFFF);
len += snprintf(buf + len, size - len,
"%20s : %10d\n", "Checksum",
pBase->checksum);
len += snprintf(buf + len, size - len,
"%20s : %10d\n", "Length",
pBase->length);
len += snprintf(buf + len, size - len,
"%20s : %10d\n", "RegDomain1",
pBase->regDmn[0]);
len += snprintf(buf + len, size - len,
"%20s : %10d\n", "RegDomain2",
pBase->regDmn[1]);
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"TX Mask", pBase->txMask);
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"RX Mask", pBase->rxMask);
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Allow 5GHz",
!!(pBase->opCapFlags & AR5416_OPFLAGS_11A));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Allow 2GHz",
!!(pBase->opCapFlags & AR5416_OPFLAGS_11G));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Disable 2GHz HT20",
!!(pBase->opCapFlags & AR5416_OPFLAGS_N_2G_HT20));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Disable 2GHz HT40",
!!(pBase->opCapFlags & AR5416_OPFLAGS_N_2G_HT40));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Disable 5Ghz HT20",
!!(pBase->opCapFlags & AR5416_OPFLAGS_N_5G_HT20));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Disable 5Ghz HT40",
!!(pBase->opCapFlags & AR5416_OPFLAGS_N_5G_HT40));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Big Endian",
!!(pBase->eepMisc & 0x01));
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Cal Bin Major Ver",
(pBase->binBuildNumber >> 24) & 0xFF);
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Cal Bin Minor Ver",
(pBase->binBuildNumber >> 16) & 0xFF);
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"Cal Bin Build",
(pBase->binBuildNumber >> 8) & 0xFF);
/*
* UB91 specific data.
*/
if (AR_SREV_9271(priv->ah)) {
struct base_eep_header_4k *pBase4k =
&priv->ah->eeprom.map4k.baseEepHeader;
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"TX Gain type",
pBase4k->txGainType);
}
/*
* UB95 specific data.
*/
if (priv->ah->hw_version.usbdev == AR9287_USB) {
struct base_eep_ar9287_header *pBase9287 =
&priv->ah->eeprom.map9287.baseEepHeader;
len += snprintf(buf + len, size - len,
"%20s : %10ddB\n",
"Power Table Offset",
pBase9287->pwrTableOffset);
len += snprintf(buf + len, size - len,
"%20s : %10d\n",
"OpenLoop Power Ctrl",
pBase9287->openLoopPwrCntl);
}
len += snprintf(buf + len, size - len, "%20s : %pM\n", "MacAddress",
pBase->macAddr);
if (len > size)
len = size;
retval = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return retval;
}
static const struct file_operations fops_base_eeprom = {
.read = read_file_base_eeprom,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
static ssize_t read_4k_modal_eeprom(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
#define PR_EEP(_s, _val) \
do { \
len += snprintf(buf + len, size - len, "%20s : %10d\n", \
_s, (_val)); \
} while (0)
struct ath9k_htc_priv *priv = file->private_data;
struct modal_eep_4k_header *pModal = &priv->ah->eeprom.map4k.modalHeader;
unsigned int len = 0, size = 2048;
ssize_t retval = 0;
char *buf;
buf = kzalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
PR_EEP("Chain0 Ant. Control", pModal->antCtrlChain[0]);
PR_EEP("Ant. Common Control", pModal->antCtrlCommon);
PR_EEP("Chain0 Ant. Gain", pModal->antennaGainCh[0]);
PR_EEP("Switch Settle", pModal->switchSettling);
PR_EEP("Chain0 TxRxAtten", pModal->txRxAttenCh[0]);
PR_EEP("Chain0 RxTxMargin", pModal->rxTxMarginCh[0]);
PR_EEP("ADC Desired size", pModal->adcDesiredSize);
PR_EEP("PGA Desired size", pModal->pgaDesiredSize);
PR_EEP("Chain0 xlna Gain", pModal->xlnaGainCh[0]);
PR_EEP("txEndToXpaOff", pModal->txEndToXpaOff);
PR_EEP("txEndToRxOn", pModal->txEndToRxOn);
PR_EEP("txFrameToXpaOn", pModal->txFrameToXpaOn);
PR_EEP("CCA Threshold)", pModal->thresh62);
PR_EEP("Chain0 NF Threshold", pModal->noiseFloorThreshCh[0]);
PR_EEP("xpdGain", pModal->xpdGain);
PR_EEP("External PD", pModal->xpd);
PR_EEP("Chain0 I Coefficient", pModal->iqCalICh[0]);
PR_EEP("Chain0 Q Coefficient", pModal->iqCalQCh[0]);
PR_EEP("pdGainOverlap", pModal->pdGainOverlap);
PR_EEP("O/D Bias Version", pModal->version);
PR_EEP("CCK OutputBias", pModal->ob_0);
PR_EEP("BPSK OutputBias", pModal->ob_1);
PR_EEP("QPSK OutputBias", pModal->ob_2);
PR_EEP("16QAM OutputBias", pModal->ob_3);
PR_EEP("64QAM OutputBias", pModal->ob_4);
PR_EEP("CCK Driver1_Bias", pModal->db1_0);
PR_EEP("BPSK Driver1_Bias", pModal->db1_1);
PR_EEP("QPSK Driver1_Bias", pModal->db1_2);
PR_EEP("16QAM Driver1_Bias", pModal->db1_3);
PR_EEP("64QAM Driver1_Bias", pModal->db1_4);
PR_EEP("CCK Driver2_Bias", pModal->db2_0);
PR_EEP("BPSK Driver2_Bias", pModal->db2_1);
PR_EEP("QPSK Driver2_Bias", pModal->db2_2);
PR_EEP("16QAM Driver2_Bias", pModal->db2_3);
PR_EEP("64QAM Driver2_Bias", pModal->db2_4);
PR_EEP("xPA Bias Level", pModal->xpaBiasLvl);
PR_EEP("txFrameToDataStart", pModal->txFrameToDataStart);
PR_EEP("txFrameToPaOn", pModal->txFrameToPaOn);
PR_EEP("HT40 Power Inc.", pModal->ht40PowerIncForPdadc);
PR_EEP("Chain0 bswAtten", pModal->bswAtten[0]);
PR_EEP("Chain0 bswMargin", pModal->bswMargin[0]);
PR_EEP("HT40 Switch Settle", pModal->swSettleHt40);
PR_EEP("Chain0 xatten2Db", pModal->xatten2Db[0]);
PR_EEP("Chain0 xatten2Margin", pModal->xatten2Margin[0]);
PR_EEP("Ant. Diversity ctl1", pModal->antdiv_ctl1);
PR_EEP("Ant. Diversity ctl2", pModal->antdiv_ctl2);
PR_EEP("TX Diversity", pModal->tx_diversity);
if (len > size)
len = size;
retval = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return retval;
#undef PR_EEP
}
static ssize_t read_def_modal_eeprom(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
#define PR_EEP(_s, _val) \
do { \
if (pBase->opCapFlags & AR5416_OPFLAGS_11G) { \
pModal = &priv->ah->eeprom.def.modalHeader[1]; \
len += snprintf(buf + len, size - len, "%20s : %8d%7s", \
_s, (_val), "|"); \
} \
if (pBase->opCapFlags & AR5416_OPFLAGS_11A) { \
pModal = &priv->ah->eeprom.def.modalHeader[0]; \
len += snprintf(buf + len, size - len, "%9d\n", \
(_val)); \
} \
} while (0)
struct ath9k_htc_priv *priv = file->private_data;
struct base_eep_header *pBase = &priv->ah->eeprom.def.baseEepHeader;
struct modal_eep_header *pModal = NULL;
unsigned int len = 0, size = 3500;
ssize_t retval = 0;
char *buf;
buf = kzalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
len += snprintf(buf + len, size - len,
"%31s %15s\n", "2G", "5G");
len += snprintf(buf + len, size - len,
"%32s %16s\n", "====", "====\n");
PR_EEP("Chain0 Ant. Control", pModal->antCtrlChain[0]);
PR_EEP("Chain1 Ant. Control", pModal->antCtrlChain[1]);
PR_EEP("Chain2 Ant. Control", pModal->antCtrlChain[2]);
PR_EEP("Ant. Common Control", pModal->antCtrlCommon);
PR_EEP("Chain0 Ant. Gain", pModal->antennaGainCh[0]);
PR_EEP("Chain1 Ant. Gain", pModal->antennaGainCh[1]);
PR_EEP("Chain2 Ant. Gain", pModal->antennaGainCh[2]);
PR_EEP("Switch Settle", pModal->switchSettling);
PR_EEP("Chain0 TxRxAtten", pModal->txRxAttenCh[0]);
PR_EEP("Chain1 TxRxAtten", pModal->txRxAttenCh[1]);
PR_EEP("Chain2 TxRxAtten", pModal->txRxAttenCh[2]);
PR_EEP("Chain0 RxTxMargin", pModal->rxTxMarginCh[0]);
PR_EEP("Chain1 RxTxMargin", pModal->rxTxMarginCh[1]);
PR_EEP("Chain2 RxTxMargin", pModal->rxTxMarginCh[2]);
PR_EEP("ADC Desired size", pModal->adcDesiredSize);
PR_EEP("PGA Desired size", pModal->pgaDesiredSize);
PR_EEP("Chain0 xlna Gain", pModal->xlnaGainCh[0]);
PR_EEP("Chain1 xlna Gain", pModal->xlnaGainCh[1]);
PR_EEP("Chain2 xlna Gain", pModal->xlnaGainCh[2]);
PR_EEP("txEndToXpaOff", pModal->txEndToXpaOff);
PR_EEP("txEndToRxOn", pModal->txEndToRxOn);
PR_EEP("txFrameToXpaOn", pModal->txFrameToXpaOn);
PR_EEP("CCA Threshold)", pModal->thresh62);
PR_EEP("Chain0 NF Threshold", pModal->noiseFloorThreshCh[0]);
PR_EEP("Chain1 NF Threshold", pModal->noiseFloorThreshCh[1]);
PR_EEP("Chain2 NF Threshold", pModal->noiseFloorThreshCh[2]);
PR_EEP("xpdGain", pModal->xpdGain);
PR_EEP("External PD", pModal->xpd);
PR_EEP("Chain0 I Coefficient", pModal->iqCalICh[0]);
PR_EEP("Chain1 I Coefficient", pModal->iqCalICh[1]);
PR_EEP("Chain2 I Coefficient", pModal->iqCalICh[2]);
PR_EEP("Chain0 Q Coefficient", pModal->iqCalQCh[0]);
PR_EEP("Chain1 Q Coefficient", pModal->iqCalQCh[1]);
PR_EEP("Chain2 Q Coefficient", pModal->iqCalQCh[2]);
PR_EEP("pdGainOverlap", pModal->pdGainOverlap);
PR_EEP("Chain0 OutputBias", pModal->ob);
PR_EEP("Chain0 DriverBias", pModal->db);
PR_EEP("xPA Bias Level", pModal->xpaBiasLvl);
PR_EEP("2chain pwr decrease", pModal->pwrDecreaseFor2Chain);
PR_EEP("3chain pwr decrease", pModal->pwrDecreaseFor3Chain);
PR_EEP("txFrameToDataStart", pModal->txFrameToDataStart);
PR_EEP("txFrameToPaOn", pModal->txFrameToPaOn);
PR_EEP("HT40 Power Inc.", pModal->ht40PowerIncForPdadc);
PR_EEP("Chain0 bswAtten", pModal->bswAtten[0]);
PR_EEP("Chain1 bswAtten", pModal->bswAtten[1]);
PR_EEP("Chain2 bswAtten", pModal->bswAtten[2]);
PR_EEP("Chain0 bswMargin", pModal->bswMargin[0]);
PR_EEP("Chain1 bswMargin", pModal->bswMargin[1]);
PR_EEP("Chain2 bswMargin", pModal->bswMargin[2]);
PR_EEP("HT40 Switch Settle", pModal->swSettleHt40);
PR_EEP("Chain0 xatten2Db", pModal->xatten2Db[0]);
PR_EEP("Chain1 xatten2Db", pModal->xatten2Db[1]);
PR_EEP("Chain2 xatten2Db", pModal->xatten2Db[2]);
PR_EEP("Chain0 xatten2Margin", pModal->xatten2Margin[0]);
PR_EEP("Chain1 xatten2Margin", pModal->xatten2Margin[1]);
PR_EEP("Chain2 xatten2Margin", pModal->xatten2Margin[2]);
PR_EEP("Chain1 OutputBias", pModal->ob_ch1);
PR_EEP("Chain1 DriverBias", pModal->db_ch1);
PR_EEP("LNA Control", pModal->lna_ctl);
PR_EEP("XPA Bias Freq0", pModal->xpaBiasLvlFreq[0]);
PR_EEP("XPA Bias Freq1", pModal->xpaBiasLvlFreq[1]);
PR_EEP("XPA Bias Freq2", pModal->xpaBiasLvlFreq[2]);
if (len > size)
len = size;
retval = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return retval;
#undef PR_EEP
}
static ssize_t read_9287_modal_eeprom(struct file *file,
char __user *user_buf,
size_t count, loff_t *ppos)
{
#define PR_EEP(_s, _val) \
do { \
len += snprintf(buf + len, size - len, "%20s : %10d\n", \
_s, (_val)); \
} while (0)
struct ath9k_htc_priv *priv = file->private_data;
struct modal_eep_ar9287_header *pModal = &priv->ah->eeprom.map9287.modalHeader;
unsigned int len = 0, size = 3000;
ssize_t retval = 0;
char *buf;
buf = kzalloc(size, GFP_KERNEL);
if (buf == NULL)
return -ENOMEM;
PR_EEP("Chain0 Ant. Control", pModal->antCtrlChain[0]);
PR_EEP("Chain1 Ant. Control", pModal->antCtrlChain[1]);
PR_EEP("Ant. Common Control", pModal->antCtrlCommon);
PR_EEP("Chain0 Ant. Gain", pModal->antennaGainCh[0]);
PR_EEP("Chain1 Ant. Gain", pModal->antennaGainCh[1]);
PR_EEP("Switch Settle", pModal->switchSettling);
PR_EEP("Chain0 TxRxAtten", pModal->txRxAttenCh[0]);
PR_EEP("Chain1 TxRxAtten", pModal->txRxAttenCh[1]);
PR_EEP("Chain0 RxTxMargin", pModal->rxTxMarginCh[0]);
PR_EEP("Chain1 RxTxMargin", pModal->rxTxMarginCh[1]);
PR_EEP("ADC Desired size", pModal->adcDesiredSize);
PR_EEP("txEndToXpaOff", pModal->txEndToXpaOff);
PR_EEP("txEndToRxOn", pModal->txEndToRxOn);
PR_EEP("txFrameToXpaOn", pModal->txFrameToXpaOn);
PR_EEP("CCA Threshold)", pModal->thresh62);
PR_EEP("Chain0 NF Threshold", pModal->noiseFloorThreshCh[0]);
PR_EEP("Chain1 NF Threshold", pModal->noiseFloorThreshCh[1]);
PR_EEP("xpdGain", pModal->xpdGain);
PR_EEP("External PD", pModal->xpd);
PR_EEP("Chain0 I Coefficient", pModal->iqCalICh[0]);
PR_EEP("Chain1 I Coefficient", pModal->iqCalICh[1]);
PR_EEP("Chain0 Q Coefficient", pModal->iqCalQCh[0]);
PR_EEP("Chain1 Q Coefficient", pModal->iqCalQCh[1]);
PR_EEP("pdGainOverlap", pModal->pdGainOverlap);
PR_EEP("xPA Bias Level", pModal->xpaBiasLvl);
PR_EEP("txFrameToDataStart", pModal->txFrameToDataStart);
PR_EEP("txFrameToPaOn", pModal->txFrameToPaOn);
PR_EEP("HT40 Power Inc.", pModal->ht40PowerIncForPdadc);
PR_EEP("Chain0 bswAtten", pModal->bswAtten[0]);
PR_EEP("Chain1 bswAtten", pModal->bswAtten[1]);
PR_EEP("Chain0 bswMargin", pModal->bswMargin[0]);
PR_EEP("Chain1 bswMargin", pModal->bswMargin[1]);
PR_EEP("HT40 Switch Settle", pModal->swSettleHt40);
PR_EEP("AR92x7 Version", pModal->version);
PR_EEP("DriverBias1", pModal->db1);
PR_EEP("DriverBias2", pModal->db1);
PR_EEP("CCK OutputBias", pModal->ob_cck);
PR_EEP("PSK OutputBias", pModal->ob_psk);
PR_EEP("QAM OutputBias", pModal->ob_qam);
PR_EEP("PAL_OFF OutputBias", pModal->ob_pal_off);
if (len > size)
len = size;
retval = simple_read_from_buffer(user_buf, count, ppos, buf, len);
kfree(buf);
return retval;
#undef PR_EEP
}
static ssize_t read_file_modal_eeprom(struct file *file, char __user *user_buf,
size_t count, loff_t *ppos)
{
struct ath9k_htc_priv *priv = file->private_data;
if (AR_SREV_9271(priv->ah))
return read_4k_modal_eeprom(file, user_buf, count, ppos);
else if (priv->ah->hw_version.usbdev == AR9280_USB)
return read_def_modal_eeprom(file, user_buf, count, ppos);
else if (priv->ah->hw_version.usbdev == AR9287_USB)
return read_9287_modal_eeprom(file, user_buf, count, ppos);
return 0;
}
static const struct file_operations fops_modal_eeprom = {
.read = read_file_modal_eeprom,
.open = simple_open,
.owner = THIS_MODULE,
.llseek = default_llseek,
};
int ath9k_htc_init_debug(struct ath_hw *ah)
{
struct ath_common *common = ath9k_hw_common(ah);
struct ath9k_htc_priv *priv = (struct ath9k_htc_priv *) common->priv;
priv->debug.debugfs_phy = debugfs_create_dir(KBUILD_MODNAME,
priv->hw->wiphy->debugfsdir);
if (!priv->debug.debugfs_phy)
return -ENOMEM;
debugfs_create_file("tgt_int_stats", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_tgt_int_stats);
debugfs_create_file("tgt_tx_stats", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_tgt_tx_stats);
debugfs_create_file("tgt_rx_stats", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_tgt_rx_stats);
debugfs_create_file("xmit", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_xmit);
debugfs_create_file("recv", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_recv);
debugfs_create_file("slot", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_slot);
debugfs_create_file("queue", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_queue);
debugfs_create_file("debug", S_IRUSR | S_IWUSR, priv->debug.debugfs_phy,
priv, &fops_debug);
debugfs_create_file("base_eeprom", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_base_eeprom);
debugfs_create_file("modal_eeprom", S_IRUSR, priv->debug.debugfs_phy,
priv, &fops_modal_eeprom);
return 0;
}
|
gpl-3.0
|
vinodjam/analyser-game-android
|
jni/SDL2_image-2.0.0/external/zlib-1.2.8/contrib/infback9/infback9.c
|
747
|
21629
|
/* infback9.c -- inflate deflate64 data using a call-back interface
* Copyright (C) 1995-2008 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h
*/
#include "zutil.h"
#include "infback9.h"
#include "inftree9.h"
#include "inflate9.h"
#define WSIZE 65536UL
/*
strm provides memory allocation functions in zalloc and zfree, or
Z_NULL to use the library memory allocation functions.
window is a user-supplied window and output buffer that is 64K bytes.
*/
int ZEXPORT inflateBack9Init_(strm, window, version, stream_size)
z_stream FAR *strm;
unsigned char FAR *window;
const char *version;
int stream_size;
{
struct inflate_state FAR *state;
if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
stream_size != (int)(sizeof(z_stream)))
return Z_VERSION_ERROR;
if (strm == Z_NULL || window == Z_NULL)
return Z_STREAM_ERROR;
strm->msg = Z_NULL; /* in case we return an error */
if (strm->zalloc == (alloc_func)0) {
strm->zalloc = zcalloc;
strm->opaque = (voidpf)0;
}
if (strm->zfree == (free_func)0) strm->zfree = zcfree;
state = (struct inflate_state FAR *)ZALLOC(strm, 1,
sizeof(struct inflate_state));
if (state == Z_NULL) return Z_MEM_ERROR;
Tracev((stderr, "inflate: allocated\n"));
strm->state = (voidpf)state;
state->window = window;
return Z_OK;
}
/*
Build and output length and distance decoding tables for fixed code
decoding.
*/
#ifdef MAKEFIXED
#include <stdio.h>
void makefixed9(void)
{
unsigned sym, bits, low, size;
code *next, *lenfix, *distfix;
struct inflate_state state;
code fixed[544];
/* literal/length table */
sym = 0;
while (sym < 144) state.lens[sym++] = 8;
while (sym < 256) state.lens[sym++] = 9;
while (sym < 280) state.lens[sym++] = 7;
while (sym < 288) state.lens[sym++] = 8;
next = fixed;
lenfix = next;
bits = 9;
inflate_table9(LENS, state.lens, 288, &(next), &(bits), state.work);
/* distance table */
sym = 0;
while (sym < 32) state.lens[sym++] = 5;
distfix = next;
bits = 5;
inflate_table9(DISTS, state.lens, 32, &(next), &(bits), state.work);
/* write tables */
puts(" /* inffix9.h -- table for decoding deflate64 fixed codes");
puts(" * Generated automatically by makefixed9().");
puts(" */");
puts("");
puts(" /* WARNING: this file should *not* be used by applications.");
puts(" It is part of the implementation of this library and is");
puts(" subject to change. Applications should only use zlib.h.");
puts(" */");
puts("");
size = 1U << 9;
printf(" static const code lenfix[%u] = {", size);
low = 0;
for (;;) {
if ((low % 6) == 0) printf("\n ");
printf("{%u,%u,%d}", lenfix[low].op, lenfix[low].bits,
lenfix[low].val);
if (++low == size) break;
putchar(',');
}
puts("\n };");
size = 1U << 5;
printf("\n static const code distfix[%u] = {", size);
low = 0;
for (;;) {
if ((low % 5) == 0) printf("\n ");
printf("{%u,%u,%d}", distfix[low].op, distfix[low].bits,
distfix[low].val);
if (++low == size) break;
putchar(',');
}
puts("\n };");
}
#endif /* MAKEFIXED */
/* Macros for inflateBack(): */
/* Clear the input bit accumulator */
#define INITBITS() \
do { \
hold = 0; \
bits = 0; \
} while (0)
/* Assure that some input is available. If input is requested, but denied,
then return a Z_BUF_ERROR from inflateBack(). */
#define PULL() \
do { \
if (have == 0) { \
have = in(in_desc, &next); \
if (have == 0) { \
next = Z_NULL; \
ret = Z_BUF_ERROR; \
goto inf_leave; \
} \
} \
} while (0)
/* Get a byte of input into the bit accumulator, or return from inflateBack()
with an error if there is no input available. */
#define PULLBYTE() \
do { \
PULL(); \
have--; \
hold += (unsigned long)(*next++) << bits; \
bits += 8; \
} while (0)
/* Assure that there are at least n bits in the bit accumulator. If there is
not enough available input to do that, then return from inflateBack() with
an error. */
#define NEEDBITS(n) \
do { \
while (bits < (unsigned)(n)) \
PULLBYTE(); \
} while (0)
/* Return the low n bits of the bit accumulator (n <= 16) */
#define BITS(n) \
((unsigned)hold & ((1U << (n)) - 1))
/* Remove n bits from the bit accumulator */
#define DROPBITS(n) \
do { \
hold >>= (n); \
bits -= (unsigned)(n); \
} while (0)
/* Remove zero to seven bits as needed to go to a byte boundary */
#define BYTEBITS() \
do { \
hold >>= bits & 7; \
bits -= bits & 7; \
} while (0)
/* Assure that some output space is available, by writing out the window
if it's full. If the write fails, return from inflateBack() with a
Z_BUF_ERROR. */
#define ROOM() \
do { \
if (left == 0) { \
put = window; \
left = WSIZE; \
wrap = 1; \
if (out(out_desc, put, (unsigned)left)) { \
ret = Z_BUF_ERROR; \
goto inf_leave; \
} \
} \
} while (0)
/*
strm provides the memory allocation functions and window buffer on input,
and provides information on the unused input on return. For Z_DATA_ERROR
returns, strm will also provide an error message.
in() and out() are the call-back input and output functions. When
inflateBack() needs more input, it calls in(). When inflateBack() has
filled the window with output, or when it completes with data in the
window, it calls out() to write out the data. The application must not
change the provided input until in() is called again or inflateBack()
returns. The application must not change the window/output buffer until
inflateBack() returns.
in() and out() are called with a descriptor parameter provided in the
inflateBack() call. This parameter can be a structure that provides the
information required to do the read or write, as well as accumulated
information on the input and output such as totals and check values.
in() should return zero on failure. out() should return non-zero on
failure. If either in() or out() fails, than inflateBack() returns a
Z_BUF_ERROR. strm->next_in can be checked for Z_NULL to see whether it
was in() or out() that caused in the error. Otherwise, inflateBack()
returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
error, or Z_MEM_ERROR if it could not allocate memory for the state.
inflateBack() can also return Z_STREAM_ERROR if the input parameters
are not correct, i.e. strm is Z_NULL or the state was not initialized.
*/
int ZEXPORT inflateBack9(strm, in, in_desc, out, out_desc)
z_stream FAR *strm;
in_func in;
void FAR *in_desc;
out_func out;
void FAR *out_desc;
{
struct inflate_state FAR *state;
z_const unsigned char FAR *next; /* next input */
unsigned char FAR *put; /* next output */
unsigned have; /* available input */
unsigned long left; /* available output */
inflate_mode mode; /* current inflate mode */
int lastblock; /* true if processing last block */
int wrap; /* true if the window has wrapped */
unsigned char FAR *window; /* allocated sliding window, if needed */
unsigned long hold; /* bit buffer */
unsigned bits; /* bits in bit buffer */
unsigned extra; /* extra bits needed */
unsigned long length; /* literal or length of data to copy */
unsigned long offset; /* distance back to copy string from */
unsigned long copy; /* number of stored or match bytes to copy */
unsigned char FAR *from; /* where to copy match bytes from */
code const FAR *lencode; /* starting table for length/literal codes */
code const FAR *distcode; /* starting table for distance codes */
unsigned lenbits; /* index bits for lencode */
unsigned distbits; /* index bits for distcode */
code here; /* current decoding table entry */
code last; /* parent table entry */
unsigned len; /* length to copy for repeats, bits to drop */
int ret; /* return code */
static const unsigned short order[19] = /* permutation of code lengths */
{16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
#include "inffix9.h"
/* Check that the strm exists and that the state was initialized */
if (strm == Z_NULL || strm->state == Z_NULL)
return Z_STREAM_ERROR;
state = (struct inflate_state FAR *)strm->state;
/* Reset the state */
strm->msg = Z_NULL;
mode = TYPE;
lastblock = 0;
wrap = 0;
window = state->window;
next = strm->next_in;
have = next != Z_NULL ? strm->avail_in : 0;
hold = 0;
bits = 0;
put = window;
left = WSIZE;
lencode = Z_NULL;
distcode = Z_NULL;
/* Inflate until end of block marked as last */
for (;;)
switch (mode) {
case TYPE:
/* determine and dispatch block type */
if (lastblock) {
BYTEBITS();
mode = DONE;
break;
}
NEEDBITS(3);
lastblock = BITS(1);
DROPBITS(1);
switch (BITS(2)) {
case 0: /* stored block */
Tracev((stderr, "inflate: stored block%s\n",
lastblock ? " (last)" : ""));
mode = STORED;
break;
case 1: /* fixed block */
lencode = lenfix;
lenbits = 9;
distcode = distfix;
distbits = 5;
Tracev((stderr, "inflate: fixed codes block%s\n",
lastblock ? " (last)" : ""));
mode = LEN; /* decode codes */
break;
case 2: /* dynamic block */
Tracev((stderr, "inflate: dynamic codes block%s\n",
lastblock ? " (last)" : ""));
mode = TABLE;
break;
case 3:
strm->msg = (char *)"invalid block type";
mode = BAD;
}
DROPBITS(2);
break;
case STORED:
/* get and verify stored block length */
BYTEBITS(); /* go to byte boundary */
NEEDBITS(32);
if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
strm->msg = (char *)"invalid stored block lengths";
mode = BAD;
break;
}
length = (unsigned)hold & 0xffff;
Tracev((stderr, "inflate: stored length %lu\n",
length));
INITBITS();
/* copy stored block from input to output */
while (length != 0) {
copy = length;
PULL();
ROOM();
if (copy > have) copy = have;
if (copy > left) copy = left;
zmemcpy(put, next, copy);
have -= copy;
next += copy;
left -= copy;
put += copy;
length -= copy;
}
Tracev((stderr, "inflate: stored end\n"));
mode = TYPE;
break;
case TABLE:
/* get dynamic table entries descriptor */
NEEDBITS(14);
state->nlen = BITS(5) + 257;
DROPBITS(5);
state->ndist = BITS(5) + 1;
DROPBITS(5);
state->ncode = BITS(4) + 4;
DROPBITS(4);
if (state->nlen > 286) {
strm->msg = (char *)"too many length symbols";
mode = BAD;
break;
}
Tracev((stderr, "inflate: table sizes ok\n"));
/* get code length code lengths (not a typo) */
state->have = 0;
while (state->have < state->ncode) {
NEEDBITS(3);
state->lens[order[state->have++]] = (unsigned short)BITS(3);
DROPBITS(3);
}
while (state->have < 19)
state->lens[order[state->have++]] = 0;
state->next = state->codes;
lencode = (code const FAR *)(state->next);
lenbits = 7;
ret = inflate_table9(CODES, state->lens, 19, &(state->next),
&(lenbits), state->work);
if (ret) {
strm->msg = (char *)"invalid code lengths set";
mode = BAD;
break;
}
Tracev((stderr, "inflate: code lengths ok\n"));
/* get length and distance code code lengths */
state->have = 0;
while (state->have < state->nlen + state->ndist) {
for (;;) {
here = lencode[BITS(lenbits)];
if ((unsigned)(here.bits) <= bits) break;
PULLBYTE();
}
if (here.val < 16) {
NEEDBITS(here.bits);
DROPBITS(here.bits);
state->lens[state->have++] = here.val;
}
else {
if (here.val == 16) {
NEEDBITS(here.bits + 2);
DROPBITS(here.bits);
if (state->have == 0) {
strm->msg = (char *)"invalid bit length repeat";
mode = BAD;
break;
}
len = (unsigned)(state->lens[state->have - 1]);
copy = 3 + BITS(2);
DROPBITS(2);
}
else if (here.val == 17) {
NEEDBITS(here.bits + 3);
DROPBITS(here.bits);
len = 0;
copy = 3 + BITS(3);
DROPBITS(3);
}
else {
NEEDBITS(here.bits + 7);
DROPBITS(here.bits);
len = 0;
copy = 11 + BITS(7);
DROPBITS(7);
}
if (state->have + copy > state->nlen + state->ndist) {
strm->msg = (char *)"invalid bit length repeat";
mode = BAD;
break;
}
while (copy--)
state->lens[state->have++] = (unsigned short)len;
}
}
/* handle error breaks in while */
if (mode == BAD) break;
/* check for end-of-block code (better have one) */
if (state->lens[256] == 0) {
strm->msg = (char *)"invalid code -- missing end-of-block";
mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftree9.h
concerning the ENOUGH constants, which depend on those values */
state->next = state->codes;
lencode = (code const FAR *)(state->next);
lenbits = 9;
ret = inflate_table9(LENS, state->lens, state->nlen,
&(state->next), &(lenbits), state->work);
if (ret) {
strm->msg = (char *)"invalid literal/lengths set";
mode = BAD;
break;
}
distcode = (code const FAR *)(state->next);
distbits = 6;
ret = inflate_table9(DISTS, state->lens + state->nlen,
state->ndist, &(state->next), &(distbits),
state->work);
if (ret) {
strm->msg = (char *)"invalid distances set";
mode = BAD;
break;
}
Tracev((stderr, "inflate: codes ok\n"));
mode = LEN;
case LEN:
/* get a literal, length, or end-of-block code */
for (;;) {
here = lencode[BITS(lenbits)];
if ((unsigned)(here.bits) <= bits) break;
PULLBYTE();
}
if (here.op && (here.op & 0xf0) == 0) {
last = here;
for (;;) {
here = lencode[last.val +
(BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE();
}
DROPBITS(last.bits);
}
DROPBITS(here.bits);
length = (unsigned)here.val;
/* process literal */
if (here.op == 0) {
Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
"inflate: literal '%c'\n" :
"inflate: literal 0x%02x\n", here.val));
ROOM();
*put++ = (unsigned char)(length);
left--;
mode = LEN;
break;
}
/* process end of block */
if (here.op & 32) {
Tracevv((stderr, "inflate: end of block\n"));
mode = TYPE;
break;
}
/* invalid code */
if (here.op & 64) {
strm->msg = (char *)"invalid literal/length code";
mode = BAD;
break;
}
/* length code -- get extra bits, if any */
extra = (unsigned)(here.op) & 31;
if (extra != 0) {
NEEDBITS(extra);
length += BITS(extra);
DROPBITS(extra);
}
Tracevv((stderr, "inflate: length %lu\n", length));
/* get distance code */
for (;;) {
here = distcode[BITS(distbits)];
if ((unsigned)(here.bits) <= bits) break;
PULLBYTE();
}
if ((here.op & 0xf0) == 0) {
last = here;
for (;;) {
here = distcode[last.val +
(BITS(last.bits + last.op) >> last.bits)];
if ((unsigned)(last.bits + here.bits) <= bits) break;
PULLBYTE();
}
DROPBITS(last.bits);
}
DROPBITS(here.bits);
if (here.op & 64) {
strm->msg = (char *)"invalid distance code";
mode = BAD;
break;
}
offset = (unsigned)here.val;
/* get distance extra bits, if any */
extra = (unsigned)(here.op) & 15;
if (extra != 0) {
NEEDBITS(extra);
offset += BITS(extra);
DROPBITS(extra);
}
if (offset > WSIZE - (wrap ? 0: left)) {
strm->msg = (char *)"invalid distance too far back";
mode = BAD;
break;
}
Tracevv((stderr, "inflate: distance %lu\n", offset));
/* copy match from window to output */
do {
ROOM();
copy = WSIZE - offset;
if (copy < left) {
from = put + copy;
copy = left - copy;
}
else {
from = put - offset;
copy = left;
}
if (copy > length) copy = length;
length -= copy;
left -= copy;
do {
*put++ = *from++;
} while (--copy);
} while (length != 0);
break;
case DONE:
/* inflate stream terminated properly -- write leftover output */
ret = Z_STREAM_END;
if (left < WSIZE) {
if (out(out_desc, window, (unsigned)(WSIZE - left)))
ret = Z_BUF_ERROR;
}
goto inf_leave;
case BAD:
ret = Z_DATA_ERROR;
goto inf_leave;
default: /* can't happen, but makes compilers happy */
ret = Z_STREAM_ERROR;
goto inf_leave;
}
/* Return unused input */
inf_leave:
strm->next_in = next;
strm->avail_in = have;
return ret;
}
int ZEXPORT inflateBack9End(strm)
z_stream FAR *strm;
{
if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
return Z_STREAM_ERROR;
ZFREE(strm, strm->state);
strm->state = Z_NULL;
Tracev((stderr, "inflate: end\n"));
return Z_OK;
}
|
gpl-3.0
|
CognetTestbed/COGNET_CODE
|
KERNEL_SOURCE_CODE/linux-source-3.8.11-voyage/arch/arm/mach-s3c24xx/dma-s3c2440.c
|
5102
|
4876
|
/* linux/arch/arm/mach-s3c2440/dma.c
*
* Copyright (c) 2006 Simtec Electronics
* Ben Dooks <ben@simtec.co.uk>
*
* S3C2440 DMA selection
*
* http://armlinux.simtec.co.uk/
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/device.h>
#include <linux/serial_core.h>
#include <mach/map.h>
#include <mach/dma.h>
#include <plat/dma-s3c24xx.h>
#include <plat/cpu.h>
#include <plat/regs-serial.h>
#include <mach/regs-gpio.h>
#include <plat/regs-ac97.h>
#include <plat/regs-dma.h>
#include <mach/regs-mem.h>
#include <mach/regs-lcd.h>
#include <mach/regs-sdi.h>
#include <plat/regs-iis.h>
#include <plat/regs-spi.h>
static struct s3c24xx_dma_map __initdata s3c2440_dma_mappings[] = {
[DMACH_XD0] = {
.name = "xdreq0",
.channels[0] = S3C2410_DCON_CH0_XDREQ0 | DMA_CH_VALID,
},
[DMACH_XD1] = {
.name = "xdreq1",
.channels[1] = S3C2410_DCON_CH1_XDREQ1 | DMA_CH_VALID,
},
[DMACH_SDI] = {
.name = "sdi",
.channels[0] = S3C2410_DCON_CH0_SDI | DMA_CH_VALID,
.channels[1] = S3C2440_DCON_CH1_SDI | DMA_CH_VALID,
.channels[2] = S3C2410_DCON_CH2_SDI | DMA_CH_VALID,
.channels[3] = S3C2410_DCON_CH3_SDI | DMA_CH_VALID,
},
[DMACH_SPI0] = {
.name = "spi0",
.channels[1] = S3C2410_DCON_CH1_SPI | DMA_CH_VALID,
},
[DMACH_SPI1] = {
.name = "spi1",
.channels[3] = S3C2410_DCON_CH3_SPI | DMA_CH_VALID,
},
[DMACH_UART0] = {
.name = "uart0",
.channels[0] = S3C2410_DCON_CH0_UART0 | DMA_CH_VALID,
},
[DMACH_UART1] = {
.name = "uart1",
.channels[1] = S3C2410_DCON_CH1_UART1 | DMA_CH_VALID,
},
[DMACH_UART2] = {
.name = "uart2",
.channels[3] = S3C2410_DCON_CH3_UART2 | DMA_CH_VALID,
},
[DMACH_TIMER] = {
.name = "timer",
.channels[0] = S3C2410_DCON_CH0_TIMER | DMA_CH_VALID,
.channels[2] = S3C2410_DCON_CH2_TIMER | DMA_CH_VALID,
.channels[3] = S3C2410_DCON_CH3_TIMER | DMA_CH_VALID,
},
[DMACH_I2S_IN] = {
.name = "i2s-sdi",
.channels[1] = S3C2410_DCON_CH1_I2SSDI | DMA_CH_VALID,
.channels[2] = S3C2410_DCON_CH2_I2SSDI | DMA_CH_VALID,
},
[DMACH_I2S_OUT] = {
.name = "i2s-sdo",
.channels[0] = S3C2440_DCON_CH0_I2SSDO | DMA_CH_VALID,
.channels[2] = S3C2410_DCON_CH2_I2SSDO | DMA_CH_VALID,
},
[DMACH_PCM_IN] = {
.name = "pcm-in",
.channels[0] = S3C2440_DCON_CH0_PCMIN | DMA_CH_VALID,
.channels[2] = S3C2440_DCON_CH2_PCMIN | DMA_CH_VALID,
},
[DMACH_PCM_OUT] = {
.name = "pcm-out",
.channels[1] = S3C2440_DCON_CH1_PCMOUT | DMA_CH_VALID,
.channels[3] = S3C2440_DCON_CH3_PCMOUT | DMA_CH_VALID,
},
[DMACH_MIC_IN] = {
.name = "mic-in",
.channels[2] = S3C2440_DCON_CH2_MICIN | DMA_CH_VALID,
.channels[3] = S3C2440_DCON_CH3_MICIN | DMA_CH_VALID,
},
[DMACH_USB_EP1] = {
.name = "usb-ep1",
.channels[0] = S3C2410_DCON_CH0_USBEP1 | DMA_CH_VALID,
},
[DMACH_USB_EP2] = {
.name = "usb-ep2",
.channels[1] = S3C2410_DCON_CH1_USBEP2 | DMA_CH_VALID,
},
[DMACH_USB_EP3] = {
.name = "usb-ep3",
.channels[2] = S3C2410_DCON_CH2_USBEP3 | DMA_CH_VALID,
},
[DMACH_USB_EP4] = {
.name = "usb-ep4",
.channels[3] = S3C2410_DCON_CH3_USBEP4 | DMA_CH_VALID,
},
};
static void s3c2440_dma_select(struct s3c2410_dma_chan *chan,
struct s3c24xx_dma_map *map)
{
chan->dcon = map->channels[chan->number] & ~DMA_CH_VALID;
}
static struct s3c24xx_dma_selection __initdata s3c2440_dma_sel = {
.select = s3c2440_dma_select,
.dcon_mask = 7 << 24,
.map = s3c2440_dma_mappings,
.map_size = ARRAY_SIZE(s3c2440_dma_mappings),
};
static struct s3c24xx_dma_order __initdata s3c2440_dma_order = {
.channels = {
[DMACH_SDI] = {
.list = {
[0] = 3 | DMA_CH_VALID,
[1] = 2 | DMA_CH_VALID,
[2] = 1 | DMA_CH_VALID,
[3] = 0 | DMA_CH_VALID,
},
},
[DMACH_I2S_IN] = {
.list = {
[0] = 1 | DMA_CH_VALID,
[1] = 2 | DMA_CH_VALID,
},
},
[DMACH_I2S_OUT] = {
.list = {
[0] = 2 | DMA_CH_VALID,
[1] = 1 | DMA_CH_VALID,
},
},
[DMACH_PCM_IN] = {
.list = {
[0] = 2 | DMA_CH_VALID,
[1] = 1 | DMA_CH_VALID,
},
},
[DMACH_PCM_OUT] = {
.list = {
[0] = 1 | DMA_CH_VALID,
[1] = 3 | DMA_CH_VALID,
},
},
[DMACH_MIC_IN] = {
.list = {
[0] = 3 | DMA_CH_VALID,
[1] = 2 | DMA_CH_VALID,
},
},
},
};
static int __init s3c2440_dma_add(struct device *dev,
struct subsys_interface *sif)
{
s3c2410_dma_init();
s3c24xx_dma_order_set(&s3c2440_dma_order);
return s3c24xx_dma_init_map(&s3c2440_dma_sel);
}
static struct subsys_interface s3c2440_dma_interface = {
.name = "s3c2440_dma",
.subsys = &s3c2440_subsys,
.add_dev = s3c2440_dma_add,
};
static int __init s3c2440_dma_init(void)
{
return subsys_interface_register(&s3c2440_dma_interface);
}
arch_initcall(s3c2440_dma_init);
|
gpl-3.0
|
r2t2sdr/r2t2
|
linux/trunk/linux-4.0-adi/drivers/clk/mvebu/clk-cpu.c
|
1017
|
6638
|
/*
* Marvell MVEBU CPU clock handling.
*
* Copyright (C) 2012 Marvell
*
* Gregory CLEMENT <gregory.clement@free-electrons.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/clkdev.h>
#include <linux/clk-provider.h>
#include <linux/of_address.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/delay.h>
#include <linux/mvebu-pmsu.h>
#include <asm/smp_plat.h>
#define SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET 0x0
#define SYS_CTRL_CLK_DIVIDER_CTRL_RESET_ALL 0xff
#define SYS_CTRL_CLK_DIVIDER_CTRL_RESET_SHIFT 8
#define SYS_CTRL_CLK_DIVIDER_CTRL2_OFFSET 0x8
#define SYS_CTRL_CLK_DIVIDER_CTRL2_NBCLK_RATIO_SHIFT 16
#define SYS_CTRL_CLK_DIVIDER_VALUE_OFFSET 0xC
#define SYS_CTRL_CLK_DIVIDER_MASK 0x3F
#define PMU_DFS_RATIO_SHIFT 16
#define PMU_DFS_RATIO_MASK 0x3F
#define MAX_CPU 4
struct cpu_clk {
struct clk_hw hw;
int cpu;
const char *clk_name;
const char *parent_name;
void __iomem *reg_base;
void __iomem *pmu_dfs;
};
static struct clk **clks;
static struct clk_onecell_data clk_data;
#define to_cpu_clk(p) container_of(p, struct cpu_clk, hw)
static unsigned long clk_cpu_recalc_rate(struct clk_hw *hwclk,
unsigned long parent_rate)
{
struct cpu_clk *cpuclk = to_cpu_clk(hwclk);
u32 reg, div;
reg = readl(cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_VALUE_OFFSET);
div = (reg >> (cpuclk->cpu * 8)) & SYS_CTRL_CLK_DIVIDER_MASK;
return parent_rate / div;
}
static long clk_cpu_round_rate(struct clk_hw *hwclk, unsigned long rate,
unsigned long *parent_rate)
{
/* Valid ratio are 1:1, 1:2 and 1:3 */
u32 div;
div = *parent_rate / rate;
if (div == 0)
div = 1;
else if (div > 3)
div = 3;
return *parent_rate / div;
}
static int clk_cpu_off_set_rate(struct clk_hw *hwclk, unsigned long rate,
unsigned long parent_rate)
{
struct cpu_clk *cpuclk = to_cpu_clk(hwclk);
u32 reg, div;
u32 reload_mask;
div = parent_rate / rate;
reg = (readl(cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_VALUE_OFFSET)
& (~(SYS_CTRL_CLK_DIVIDER_MASK << (cpuclk->cpu * 8))))
| (div << (cpuclk->cpu * 8));
writel(reg, cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_VALUE_OFFSET);
/* Set clock divider reload smooth bit mask */
reload_mask = 1 << (20 + cpuclk->cpu);
reg = readl(cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET)
| reload_mask;
writel(reg, cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET);
/* Now trigger the clock update */
reg = readl(cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET)
| 1 << 24;
writel(reg, cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET);
/* Wait for clocks to settle down then clear reload request */
udelay(1000);
reg &= ~(reload_mask | 1 << 24);
writel(reg, cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET);
udelay(1000);
return 0;
}
static int clk_cpu_on_set_rate(struct clk_hw *hwclk, unsigned long rate,
unsigned long parent_rate)
{
u32 reg;
unsigned long fabric_div, target_div, cur_rate;
struct cpu_clk *cpuclk = to_cpu_clk(hwclk);
/*
* PMU DFS registers are not mapped, Device Tree does not
* describes them. We cannot change the frequency dynamically.
*/
if (!cpuclk->pmu_dfs)
return -ENODEV;
cur_rate = __clk_get_rate(hwclk->clk);
reg = readl(cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL2_OFFSET);
fabric_div = (reg >> SYS_CTRL_CLK_DIVIDER_CTRL2_NBCLK_RATIO_SHIFT) &
SYS_CTRL_CLK_DIVIDER_MASK;
/* Frequency is going up */
if (rate == 2 * cur_rate)
target_div = fabric_div / 2;
/* Frequency is going down */
else
target_div = fabric_div;
if (target_div == 0)
target_div = 1;
reg = readl(cpuclk->pmu_dfs);
reg &= ~(PMU_DFS_RATIO_MASK << PMU_DFS_RATIO_SHIFT);
reg |= (target_div << PMU_DFS_RATIO_SHIFT);
writel(reg, cpuclk->pmu_dfs);
reg = readl(cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET);
reg |= (SYS_CTRL_CLK_DIVIDER_CTRL_RESET_ALL <<
SYS_CTRL_CLK_DIVIDER_CTRL_RESET_SHIFT);
writel(reg, cpuclk->reg_base + SYS_CTRL_CLK_DIVIDER_CTRL_OFFSET);
return mvebu_pmsu_dfs_request(cpuclk->cpu);
}
static int clk_cpu_set_rate(struct clk_hw *hwclk, unsigned long rate,
unsigned long parent_rate)
{
if (__clk_is_enabled(hwclk->clk))
return clk_cpu_on_set_rate(hwclk, rate, parent_rate);
else
return clk_cpu_off_set_rate(hwclk, rate, parent_rate);
}
static const struct clk_ops cpu_ops = {
.recalc_rate = clk_cpu_recalc_rate,
.round_rate = clk_cpu_round_rate,
.set_rate = clk_cpu_set_rate,
};
static void __init of_cpu_clk_setup(struct device_node *node)
{
struct cpu_clk *cpuclk;
void __iomem *clock_complex_base = of_iomap(node, 0);
void __iomem *pmu_dfs_base = of_iomap(node, 1);
int ncpus = 0;
struct device_node *dn;
if (clock_complex_base == NULL) {
pr_err("%s: clock-complex base register not set\n",
__func__);
return;
}
if (pmu_dfs_base == NULL)
pr_warn("%s: pmu-dfs base register not set, dynamic frequency scaling not available\n",
__func__);
for_each_node_by_type(dn, "cpu")
ncpus++;
cpuclk = kzalloc(ncpus * sizeof(*cpuclk), GFP_KERNEL);
if (WARN_ON(!cpuclk))
goto cpuclk_out;
clks = kzalloc(ncpus * sizeof(*clks), GFP_KERNEL);
if (WARN_ON(!clks))
goto clks_out;
for_each_node_by_type(dn, "cpu") {
struct clk_init_data init;
struct clk *clk;
struct clk *parent_clk;
char *clk_name = kzalloc(5, GFP_KERNEL);
int cpu, err;
if (WARN_ON(!clk_name))
goto bail_out;
err = of_property_read_u32(dn, "reg", &cpu);
if (WARN_ON(err))
goto bail_out;
sprintf(clk_name, "cpu%d", cpu);
parent_clk = of_clk_get(node, 0);
cpuclk[cpu].parent_name = __clk_get_name(parent_clk);
cpuclk[cpu].clk_name = clk_name;
cpuclk[cpu].cpu = cpu;
cpuclk[cpu].reg_base = clock_complex_base;
if (pmu_dfs_base)
cpuclk[cpu].pmu_dfs = pmu_dfs_base + 4 * cpu;
cpuclk[cpu].hw.init = &init;
init.name = cpuclk[cpu].clk_name;
init.ops = &cpu_ops;
init.flags = 0;
init.parent_names = &cpuclk[cpu].parent_name;
init.num_parents = 1;
clk = clk_register(NULL, &cpuclk[cpu].hw);
if (WARN_ON(IS_ERR(clk)))
goto bail_out;
clks[cpu] = clk;
}
clk_data.clk_num = MAX_CPU;
clk_data.clks = clks;
of_clk_add_provider(node, of_clk_src_onecell_get, &clk_data);
return;
bail_out:
kfree(clks);
while(ncpus--)
kfree(cpuclk[ncpus].clk_name);
clks_out:
kfree(cpuclk);
cpuclk_out:
iounmap(clock_complex_base);
}
CLK_OF_DECLARE(armada_xp_cpu_clock, "marvell,armada-xp-cpu-clock",
of_cpu_clk_setup);
|
gpl-3.0
|
joyent/sdcboot
|
freedos/source/command/command/suppl/src/mcb_apar.c
|
2
|
3182
|
/*
This file is part of SUPPL - the supplemental library for DOS
Copyright (C) 1996-2000 Steffen Kaiser
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Library General Public
License as published by the Free Software Foundation; either
version 2 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Library General Public License for more details.
You should have received a copy of the GNU Library General Public
License along with this library; if not, write to the Free
Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/* $RCSfile: mcb_apar.c,v $
$Locker: $ $Name: $ $State: Exp $
ob(ject): mcb_allParents
su(bsystem): mcb
ty(pe):
sh(ort description): Enumerate all parents of a process
lo(ng description): Enumerates all parents of a process and launches
the given function for each of them. \em{Note:} Because DOS shells
patch their own "parent process ID", the last enumerated process is
the shell the process was invoked by. This behaviour makes it
unable to create full process trees known from Unix systems.\par
If \tok{mcb == 0}, the enumeration begins with the current process;
otherwise, the segment is probed via \tok{isPSP()} for validity.\newline
The callback function \para{fct} must have the type \tok{MCB_WALKFUNC},
which is a pointer to a function:\example{|}
|int MCB_WALKFUNC(void *arg, unsigned mcb)
The first parameter \para{arg} is the unchanged parameter \para{arg} passed
into \tok{mcb_allParents} itself and \para{mcb} is the MCB ID of the
enumerated process. If the callback function returns \tok{0} (zero),
the enumeration process proceeds, otherwise it is terminated.
pr(erequistes): fct != NULL
va(lue): -1: on failure, e.g. corrupted MCB chain or invalid passed in
\para{mcb}
\item 0: callback function always returned \tok{0} (zero) itself and
there is no parent for the currently enumerated process
\item else: the value returned by the callback function, if it is
non-zero
re(lated to): MCB_WALKFUNC mcb_walk
se(condary subsystems):
bu(gs):
co(mpilers):
*/
#include "initsupl.loc"
#ifndef _MICROC_
#include <dos.h>
#endif
#include <portable.h>
#include "mcb.h"
#include "suppldbg.h"
#ifdef RCS_Version
static char const rcsid[] =
"$Id: mcb_apar.c,v 1.1 2006/06/17 03:25:05 blairdude Exp $";
#endif
int mcb_allParents(word mcb, MCB_WALKFUNC fct, void *arg)
{ word mcb1;
DBG_ENTER("mcb_allParents", Suppl_mcb)
DBG_ARGUMENTS( ("mcb=%u", mcb) )
assert(fct);
if(mcb) {
if(!isPSP(mcb)) {
DBG_STRING("Invalid MCB")
DBG_RETURN_I( -1)
}
}
else mcb = _psp;
DBG_ARGUMENTS( ("effective mcb=%u", mcb) )
do {
if((mcb1 = peekw(mcb, SEG_OFFSET + 0x16)) == mcb)
DBG_RETURN_I( 0) /* no parent process */
if((mcb1 = (*fct)(arg, mcb = mcb1)) != 0) /* function terminates */
DBG_RETURN_I( mcb1)
} while(mcb > 0x40);
DBG_STRING("Corrupted MCB chain")
DBG_RETURN_I( -1)
}
|
mpl-2.0
|
mtasende/BLAS_for_Parallella
|
blis-master/frame/compat/cblas/src/cblas_sgbmv.c
|
5
|
2421
|
#include "bli_config.h"
#include "bli_system.h"
#include "bli_type_defs.h"
#include "bli_cblas.h"
#ifdef BLIS_ENABLE_CBLAS
/*
*
* cblas_sgbmv.c
* This program is a C interface to sgbmv.
* Written by Keita Teranishi
* 4/6/1998
*
*/
#include "cblas.h"
#include "cblas_f77.h"
void cblas_sgbmv(const enum CBLAS_ORDER order,
const enum CBLAS_TRANSPOSE TransA, const int M, const int N,
const int KL, const int KU,
const float alpha, const float *A, const int lda,
const float *X, const int incX, const float beta,
float *Y, const int incY)
{
char TA;
#ifdef F77_CHAR
F77_CHAR F77_TA;
#else
#define F77_TA &TA
#endif
#ifdef F77_INT
F77_INT F77_M=M, F77_N=N, F77_lda=lda, F77_incX=incX, F77_incY=incY;
F77_INT F77_KL=KL,F77_KU=KU;
#else
#define F77_M M
#define F77_N N
#define F77_lda lda
#define F77_KL KL
#define F77_KU KU
#define F77_incX incX
#define F77_incY incY
#endif
extern int CBLAS_CallFromC;
extern int RowMajorStrg;
RowMajorStrg = 0;
CBLAS_CallFromC = 1;
if (order == CblasColMajor)
{
if (TransA == CblasNoTrans) TA = 'N';
else if (TransA == CblasTrans) TA = 'T';
else if (TransA == CblasConjTrans) TA = 'C';
else
{
cblas_xerbla(2, "cblas_sgbmv","Illegal TransA setting, %d\n", TransA);
CBLAS_CallFromC = 0;
RowMajorStrg = 0;
return;
}
#ifdef F77_CHAR
F77_TA = C2F_CHAR(&TA);
#endif
F77_sgbmv(F77_TA, &F77_M, &F77_N, &F77_KL, &F77_KU, &alpha,
A, &F77_lda, X, &F77_incX, &beta, Y, &F77_incY);
}
else if (order == CblasRowMajor)
{
RowMajorStrg = 1;
if (TransA == CblasNoTrans) TA = 'T';
else if (TransA == CblasTrans) TA = 'N';
else if (TransA == CblasConjTrans) TA = 'N';
else
{
cblas_xerbla(2, "cblas_sgbmv","Illegal TransA setting, %d\n", TransA);
CBLAS_CallFromC = 0;
RowMajorStrg = 0;
return;
}
#ifdef F77_CHAR
F77_TA = C2F_CHAR(&TA);
#endif
F77_sgbmv(F77_TA, &F77_N, &F77_M, &F77_KU, &F77_KL, &alpha,
A ,&F77_lda, X, &F77_incX, &beta, Y, &F77_incY);
}
else cblas_xerbla(1, "cblas_sgbmv", "Illegal Order setting, %d\n", order);
CBLAS_CallFromC = 0;
RowMajorStrg = 0;
return;
}
#endif
|
mpl-2.0
|
ovr/postgres-xl
|
src/test/modules/test_shm_mq/worker.c
|
7
|
6865
|
/*--------------------------------------------------------------------------
*
* worker.c
* Code for sample worker making use of shared memory message queues.
* Our test worker simply reads messages from one message queue and
* writes them back out to another message queue. In a real
* application, you'd presumably want the worker to do some more
* complex calculation rather than simply returning the input,
* but it should be possible to use much of the control logic just
* as presented here.
*
* Copyright (C) 2013-2014, PostgreSQL Global Development Group
*
* IDENTIFICATION
* src/test/modules/test_shm_mq/worker.c
*
* -------------------------------------------------------------------------
*/
#include "postgres.h"
#include "miscadmin.h"
#include "storage/ipc.h"
#include "storage/procarray.h"
#include "storage/shm_mq.h"
#include "storage/shm_toc.h"
#include "utils/resowner.h"
#include "test_shm_mq.h"
static void handle_sigterm(SIGNAL_ARGS);
static void attach_to_queues(dsm_segment *seg, shm_toc *toc,
int myworkernumber, shm_mq_handle **inqhp,
shm_mq_handle **outqhp);
static void copy_messages(shm_mq_handle *inqh, shm_mq_handle *outqh);
/*
* Background worker entrypoint.
*
* This is intended to demonstrate how a background worker can be used to
* facilitate a parallel computation. Most of the logic here is fairly
* boilerplate stuff, designed to attach to the shared memory segment,
* notify the user backend that we're alive, and so on. The
* application-specific bits of logic that you'd replace for your own worker
* are attach_to_queues() and copy_messages().
*/
void
test_shm_mq_main(Datum main_arg)
{
dsm_segment *seg;
shm_toc *toc;
shm_mq_handle *inqh;
shm_mq_handle *outqh;
volatile test_shm_mq_header *hdr;
int myworkernumber;
PGPROC *registrant;
/*
* Establish signal handlers.
*
* We want CHECK_FOR_INTERRUPTS() to kill off this worker process just as
* it would a normal user backend. To make that happen, we establish a
* signal handler that is a stripped-down version of die().
*/
pqsignal(SIGTERM, handle_sigterm);
BackgroundWorkerUnblockSignals();
/*
* Connect to the dynamic shared memory segment.
*
* The backend that registered this worker passed us the ID of a shared
* memory segment to which we must attach for further instructions. In
* order to attach to dynamic shared memory, we need a resource owner.
* Once we've mapped the segment in our address space, attach to the table
* of contents so we can locate the various data structures we'll need to
* find within the segment.
*/
CurrentResourceOwner = ResourceOwnerCreate(NULL, "test_shm_mq worker");
seg = dsm_attach(DatumGetInt32(main_arg));
if (seg == NULL)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("unable to map dynamic shared memory segment")));
toc = shm_toc_attach(PG_TEST_SHM_MQ_MAGIC, dsm_segment_address(seg));
if (toc == NULL)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("bad magic number in dynamic shared memory segment")));
/*
* Acquire a worker number.
*
* By convention, the process registering this background worker should
* have stored the control structure at key 0. We look up that key to
* find it. Our worker number gives our identity: there may be just one
* worker involved in this parallel operation, or there may be many.
*/
hdr = shm_toc_lookup(toc, 0);
SpinLockAcquire(&hdr->mutex);
myworkernumber = ++hdr->workers_attached;
SpinLockRelease(&hdr->mutex);
if (myworkernumber > hdr->workers_total)
ereport(ERROR,
(errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE),
errmsg("too many message queue testing workers already")));
/*
* Attach to the appropriate message queues.
*/
attach_to_queues(seg, toc, myworkernumber, &inqh, &outqh);
/*
* Indicate that we're fully initialized and ready to begin the main part
* of the parallel operation.
*
* Once we signal that we're ready, the user backend is entitled to assume
* that our on_dsm_detach callbacks will fire before we disconnect from
* the shared memory segment and exit. Generally, that means we must have
* attached to all relevant dynamic shared memory data structures by now.
*/
SpinLockAcquire(&hdr->mutex);
++hdr->workers_ready;
SpinLockRelease(&hdr->mutex);
registrant = BackendPidGetProc(MyBgworkerEntry->bgw_notify_pid);
if (registrant == NULL)
{
elog(DEBUG1, "registrant backend has exited prematurely");
proc_exit(1);
}
SetLatch(®istrant->procLatch);
/* Do the work. */
copy_messages(inqh, outqh);
/*
* We're done. Explicitly detach the shared memory segment so that we
* don't get a resource leak warning at commit time. This will fire any
* on_dsm_detach callbacks we've registered, as well. Once that's done,
* we can go ahead and exit.
*/
dsm_detach(seg);
proc_exit(1);
}
/*
* Attach to shared memory message queues.
*
* We use our worker number to determine to which queue we should attach.
* The queues are registered at keys 1..<number-of-workers>. The user backend
* writes to queue #1 and reads from queue #<number-of-workers>; each worker
* reads from the queue whose number is equal to its worker number and writes
* to the next higher-numbered queue.
*/
static void
attach_to_queues(dsm_segment *seg, shm_toc *toc, int myworkernumber,
shm_mq_handle **inqhp, shm_mq_handle **outqhp)
{
shm_mq *inq;
shm_mq *outq;
inq = shm_toc_lookup(toc, myworkernumber);
shm_mq_set_receiver(inq, MyProc);
*inqhp = shm_mq_attach(inq, seg, NULL);
outq = shm_toc_lookup(toc, myworkernumber + 1);
shm_mq_set_sender(outq, MyProc);
*outqhp = shm_mq_attach(outq, seg, NULL);
}
/*
* Loop, receiving and sending messages, until the connection is broken.
*
* This is the "real work" performed by this worker process. Everything that
* happens before this is initialization of one form or another, and everything
* after this point is cleanup.
*/
static void
copy_messages(shm_mq_handle *inqh, shm_mq_handle *outqh)
{
Size len;
void *data;
shm_mq_result res;
for (;;)
{
/* Notice any interrupts that have occurred. */
CHECK_FOR_INTERRUPTS();
/* Receive a message. */
res = shm_mq_receive(inqh, &len, &data, false);
if (res != SHM_MQ_SUCCESS)
break;
/* Send it back out. */
res = shm_mq_send(outqh, len, data, false);
if (res != SHM_MQ_SUCCESS)
break;
}
}
/*
* When we receive a SIGTERM, we set InterruptPending and ProcDiePending just
* like a normal backend. The next CHECK_FOR_INTERRUPTS() will do the right
* thing.
*/
static void
handle_sigterm(SIGNAL_ARGS)
{
int save_errno = errno;
SetLatch(MyLatch);
if (!proc_exit_inprogress)
{
InterruptPending = true;
ProcDiePending = true;
}
errno = save_errno;
}
|
mpl-2.0
|
hi-kasama/libmusicxml
|
samples/xmliter.cpp
|
7
|
3226
|
#ifdef WIN32
# pragma warning (disable : 4786)
#endif
#include <algorithm>
/*
Copyright (C) 2003-2008 Grame
Grame Research Laboratory, 9 rue du Garet, 69001 Lyon - France
research@grame.fr
This file is provided as an example of the MusicXML Library use.
*/
#include <iostream>
#include "elements.h"
#include "factory.h"
#include "xml.h"
#include "xmlfile.h"
#include "xmlreader.h"
using namespace std;
using namespace MusicXML2;
#define debug 0
//_______________________________________________________________________________
class predicate {
public:
int fType;
predicate(int type) : fType(type) {}
virtual ~predicate() {}
virtual bool operator () (const Sxmlelement elt) const {
return elt->getType() == fType;
}
};
//_______________________________________________________________________________
static void count(Sxmlelement elt, int type)
{
predicate p(type);
cerr << " count of type " << type << " elements: "
<< count_if(elt->begin(), elt->end(), p) << endl;
}
//_______________________________________________________________________________
static void test1(Sxmlelement elt)
{
cerr << "test1: iterate thru the tree" << endl;
ctree<xmlelement>::iterator iter = elt->begin();
cerr << "=> test1: iterate thru the tree" << endl;
while (iter != elt->end()) {
Sxmlelement xml = *iter;
if (xml)
cerr << " element type " << xml->getType()
<< " - " << xml->getName()
<< " - size: " << xml->size() << endl;
else
cerr << "iterate thru unknown element type " << endl;
iter++;
}
}
//_______________________________________________________________________________
static void test2(Sxmlelement elt)
{
cerr << "test2: erasing all the par measures" << endl;
ctree<xmlelement>::iterator next, iter = elt->begin();
int measure=1;
while (iter != elt->end()) {
Sxmlelement xml = *iter;
next = iter;
next++;
assert (xml);
if (xml->getType() == k_software) {
next = elt->erase(iter);
}
else if (xml->getType() == k_measure) {
if (!(measure & 1)) {
next = elt->erase(iter);
}
measure++;
}
iter = next;
}
}
//_______________________________________________________________________________
static void test3(Sxmlelement elt)
{
cerr << "test3: insert a note before the par notes" << endl;
ctree<xmlelement>::iterator next, iter = elt->begin();
int note=1;
while (iter != elt->end()) {
Sxmlelement xml = *iter;
assert (xml);
if (xml->getType() == k_note) {
if (!(note & 1)) {
Sxmlelement note = factory::instance().create(k_note);
iter = elt->insert(iter, note);
iter++;
}
note++;
}
iter++;
}
}
//_______________________________________________________________________________
int main(int argc, char *argv[]) {
#if debug
char *path = "rm.xml";
argc = 2;
#else
char *path = argv[1];
#endif
if (argc > 1) {
xmlreader r;
SXMLFile file = r.read(path);
if (file) {
Sxmlelement st = file->elements();
if (st) {
test1(st);
count(st, k_measure);
count(st, k_note);
test2(st);
count(st, k_measure);
count(st, k_note);
test3(st);
count(st, k_measure);
count(st, k_note);
file->print (cout);
cout << endl;
}
}
}
return 0;
}
|
mpl-2.0
|
lancernet/Espruino
|
libs/hashlib/sha2.c
|
12
|
32987
|
/*
* FIPS 180-2 SHA-224/256/384/512 implementation
* Last update: 02/02/2007
* Issue date: 04/30/2005
*
* Copyright (C) 2005, 2007 Olivier Gay <olivier.gay@a3.epfl.ch>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the project 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 PROJECT 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 PROJECT 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.
*/
#if 0
#define UNROLL_LOOPS /* Enable loops unrolling */
#endif
#include <string.h>
#include "sha2.h"
#define SHFR(x, n) (x >> n)
#define ROTR(x, n) ((x >> n) | (x << ((sizeof(x) << 3) - n)))
#define ROTL(x, n) ((x << n) | (x >> ((sizeof(x) << 3) - n)))
#define CH(x, y, z) ((x & y) ^ (~x & z))
#define MAJ(x, y, z) ((x & y) ^ (x & z) ^ (y & z))
#define SHA256_F1(x) (ROTR(x, 2) ^ ROTR(x, 13) ^ ROTR(x, 22))
#define SHA256_F2(x) (ROTR(x, 6) ^ ROTR(x, 11) ^ ROTR(x, 25))
#define SHA256_F3(x) (ROTR(x, 7) ^ ROTR(x, 18) ^ SHFR(x, 3))
#define SHA256_F4(x) (ROTR(x, 17) ^ ROTR(x, 19) ^ SHFR(x, 10))
#define SHA512_F1(x) (ROTR(x, 28) ^ ROTR(x, 34) ^ ROTR(x, 39))
#define SHA512_F2(x) (ROTR(x, 14) ^ ROTR(x, 18) ^ ROTR(x, 41))
#define SHA512_F3(x) (ROTR(x, 1) ^ ROTR(x, 8) ^ SHFR(x, 7))
#define SHA512_F4(x) (ROTR(x, 19) ^ ROTR(x, 61) ^ SHFR(x, 6))
#define UNPACK32(x, str) \
{ \
*((str) + 3) = (uint8) ((x) ); \
*((str) + 2) = (uint8) ((x) >> 8); \
*((str) + 1) = (uint8) ((x) >> 16); \
*((str) + 0) = (uint8) ((x) >> 24); \
}
#define PACK32(str, x) \
{ \
*(x) = ((uint32) *((str) + 3) ) \
| ((uint32) *((str) + 2) << 8) \
| ((uint32) *((str) + 1) << 16) \
| ((uint32) *((str) + 0) << 24); \
}
#define UNPACK64(x, str) \
{ \
*((str) + 7) = (uint8) ((x) ); \
*((str) + 6) = (uint8) ((x) >> 8); \
*((str) + 5) = (uint8) ((x) >> 16); \
*((str) + 4) = (uint8) ((x) >> 24); \
*((str) + 3) = (uint8) ((x) >> 32); \
*((str) + 2) = (uint8) ((x) >> 40); \
*((str) + 1) = (uint8) ((x) >> 48); \
*((str) + 0) = (uint8) ((x) >> 56); \
}
#define PACK64(str, x) \
{ \
*(x) = ((uint64) *((str) + 7) ) \
| ((uint64) *((str) + 6) << 8) \
| ((uint64) *((str) + 5) << 16) \
| ((uint64) *((str) + 4) << 24) \
| ((uint64) *((str) + 3) << 32) \
| ((uint64) *((str) + 2) << 40) \
| ((uint64) *((str) + 1) << 48) \
| ((uint64) *((str) + 0) << 56); \
}
/* Macros used for loops unrolling */
#define SHA256_SCR(i) \
{ \
w[i] = SHA256_F4(w[i - 2]) + w[i - 7] \
+ SHA256_F3(w[i - 15]) + w[i - 16]; \
}
#define SHA512_SCR(i) \
{ \
w[i] = SHA512_F4(w[i - 2]) + w[i - 7] \
+ SHA512_F3(w[i - 15]) + w[i - 16]; \
}
#define SHA256_EXP(a, b, c, d, e, f, g, h, j) \
{ \
t1 = wv[h] + SHA256_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \
+ sha256_k[j] + w[j]; \
t2 = SHA256_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \
wv[d] += t1; \
wv[h] = t1 + t2; \
}
#define SHA512_EXP(a, b, c, d, e, f, g ,h, j) \
{ \
t1 = wv[h] + SHA512_F2(wv[e]) + CH(wv[e], wv[f], wv[g]) \
+ sha512_k[j] + w[j]; \
t2 = SHA512_F1(wv[a]) + MAJ(wv[a], wv[b], wv[c]); \
wv[d] += t1; \
wv[h] = t1 + t2; \
}
const uint32 sha224_h0[8] =
{0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4};
const uint32 sha256_h0[8] =
{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19};
const uint64 sha384_h0[8] =
{0xcbbb9d5dc1059ed8ULL, 0x629a292a367cd507ULL,
0x9159015a3070dd17ULL, 0x152fecd8f70e5939ULL,
0x67332667ffc00b31ULL, 0x8eb44a8768581511ULL,
0xdb0c2e0d64f98fa7ULL, 0x47b5481dbefa4fa4ULL};
const uint64 sha512_h0[8] =
{0x6a09e667f3bcc908ULL, 0xbb67ae8584caa73bULL,
0x3c6ef372fe94f82bULL, 0xa54ff53a5f1d36f1ULL,
0x510e527fade682d1ULL, 0x9b05688c2b3e6c1fULL,
0x1f83d9abfb41bd6bULL, 0x5be0cd19137e2179ULL};
const uint32 sha256_k[64] =
{0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2};
const uint64 sha512_k[80] =
{0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL,
0xb5c0fbcfec4d3b2fULL, 0xe9b5dba58189dbbcULL,
0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL,
0xd807aa98a3030242ULL, 0x12835b0145706fbeULL,
0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL,
0x9bdc06a725c71235ULL, 0xc19bf174cf692694ULL,
0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL,
0x2de92c6f592b0275ULL, 0x4a7484aa6ea6e483ULL,
0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL,
0xb00327c898fb213fULL, 0xbf597fc7beef0ee4ULL,
0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
0x06ca6351e003826fULL, 0x142929670a0e6e70ULL,
0x27b70a8546d22ffcULL, 0x2e1b21385c26c926ULL,
0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL,
0x81c2c92e47edaee6ULL, 0x92722c851482353bULL,
0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL,
0xd192e819d6ef5218ULL, 0xd69906245565a910ULL,
0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL,
0x2748774cdf8eeb99ULL, 0x34b0bcb5e19b48a8ULL,
0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL,
0x748f82ee5defb2fcULL, 0x78a5636f43172f60ULL,
0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL,
0xbef9a3f7b2c67915ULL, 0xc67178f2e372532bULL,
0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL,
0x06f067aa72176fbaULL, 0x0a637dc5a2c898a6ULL,
0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
0x28db77f523047d84ULL, 0x32caab7b40c72493ULL,
0x3c9ebe0a15c9bebcULL, 0x431d67c49c100d4cULL,
0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL};
/* SHA-256 functions */
void sha256_transf(sha256_ctx *ctx, const unsigned char *message,
unsigned int block_nb)
{
uint32 w[64];
uint32 wv[8];
uint32 t1, t2;
const unsigned char *sub_block;
int i;
#ifndef UNROLL_LOOPS
int j;
#endif
for (i = 0; i < (int) block_nb; i++) {
sub_block = message + (i << 6);
#ifndef UNROLL_LOOPS
for (j = 0; j < 16; j++) {
PACK32(&sub_block[j << 2], &w[j]);
}
for (j = 16; j < 64; j++) {
SHA256_SCR(j);
}
for (j = 0; j < 8; j++) {
wv[j] = ctx->h[j];
}
for (j = 0; j < 64; j++) {
t1 = wv[7] + SHA256_F2(wv[4]) + CH(wv[4], wv[5], wv[6])
+ sha256_k[j] + w[j];
t2 = SHA256_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]);
wv[7] = wv[6];
wv[6] = wv[5];
wv[5] = wv[4];
wv[4] = wv[3] + t1;
wv[3] = wv[2];
wv[2] = wv[1];
wv[1] = wv[0];
wv[0] = t1 + t2;
}
for (j = 0; j < 8; j++) {
ctx->h[j] += wv[j];
}
#else
PACK32(&sub_block[ 0], &w[ 0]); PACK32(&sub_block[ 4], &w[ 1]);
PACK32(&sub_block[ 8], &w[ 2]); PACK32(&sub_block[12], &w[ 3]);
PACK32(&sub_block[16], &w[ 4]); PACK32(&sub_block[20], &w[ 5]);
PACK32(&sub_block[24], &w[ 6]); PACK32(&sub_block[28], &w[ 7]);
PACK32(&sub_block[32], &w[ 8]); PACK32(&sub_block[36], &w[ 9]);
PACK32(&sub_block[40], &w[10]); PACK32(&sub_block[44], &w[11]);
PACK32(&sub_block[48], &w[12]); PACK32(&sub_block[52], &w[13]);
PACK32(&sub_block[56], &w[14]); PACK32(&sub_block[60], &w[15]);
SHA256_SCR(16); SHA256_SCR(17); SHA256_SCR(18); SHA256_SCR(19);
SHA256_SCR(20); SHA256_SCR(21); SHA256_SCR(22); SHA256_SCR(23);
SHA256_SCR(24); SHA256_SCR(25); SHA256_SCR(26); SHA256_SCR(27);
SHA256_SCR(28); SHA256_SCR(29); SHA256_SCR(30); SHA256_SCR(31);
SHA256_SCR(32); SHA256_SCR(33); SHA256_SCR(34); SHA256_SCR(35);
SHA256_SCR(36); SHA256_SCR(37); SHA256_SCR(38); SHA256_SCR(39);
SHA256_SCR(40); SHA256_SCR(41); SHA256_SCR(42); SHA256_SCR(43);
SHA256_SCR(44); SHA256_SCR(45); SHA256_SCR(46); SHA256_SCR(47);
SHA256_SCR(48); SHA256_SCR(49); SHA256_SCR(50); SHA256_SCR(51);
SHA256_SCR(52); SHA256_SCR(53); SHA256_SCR(54); SHA256_SCR(55);
SHA256_SCR(56); SHA256_SCR(57); SHA256_SCR(58); SHA256_SCR(59);
SHA256_SCR(60); SHA256_SCR(61); SHA256_SCR(62); SHA256_SCR(63);
wv[0] = ctx->h[0]; wv[1] = ctx->h[1];
wv[2] = ctx->h[2]; wv[3] = ctx->h[3];
wv[4] = ctx->h[4]; wv[5] = ctx->h[5];
wv[6] = ctx->h[6]; wv[7] = ctx->h[7];
SHA256_EXP(0,1,2,3,4,5,6,7, 0); SHA256_EXP(7,0,1,2,3,4,5,6, 1);
SHA256_EXP(6,7,0,1,2,3,4,5, 2); SHA256_EXP(5,6,7,0,1,2,3,4, 3);
SHA256_EXP(4,5,6,7,0,1,2,3, 4); SHA256_EXP(3,4,5,6,7,0,1,2, 5);
SHA256_EXP(2,3,4,5,6,7,0,1, 6); SHA256_EXP(1,2,3,4,5,6,7,0, 7);
SHA256_EXP(0,1,2,3,4,5,6,7, 8); SHA256_EXP(7,0,1,2,3,4,5,6, 9);
SHA256_EXP(6,7,0,1,2,3,4,5,10); SHA256_EXP(5,6,7,0,1,2,3,4,11);
SHA256_EXP(4,5,6,7,0,1,2,3,12); SHA256_EXP(3,4,5,6,7,0,1,2,13);
SHA256_EXP(2,3,4,5,6,7,0,1,14); SHA256_EXP(1,2,3,4,5,6,7,0,15);
SHA256_EXP(0,1,2,3,4,5,6,7,16); SHA256_EXP(7,0,1,2,3,4,5,6,17);
SHA256_EXP(6,7,0,1,2,3,4,5,18); SHA256_EXP(5,6,7,0,1,2,3,4,19);
SHA256_EXP(4,5,6,7,0,1,2,3,20); SHA256_EXP(3,4,5,6,7,0,1,2,21);
SHA256_EXP(2,3,4,5,6,7,0,1,22); SHA256_EXP(1,2,3,4,5,6,7,0,23);
SHA256_EXP(0,1,2,3,4,5,6,7,24); SHA256_EXP(7,0,1,2,3,4,5,6,25);
SHA256_EXP(6,7,0,1,2,3,4,5,26); SHA256_EXP(5,6,7,0,1,2,3,4,27);
SHA256_EXP(4,5,6,7,0,1,2,3,28); SHA256_EXP(3,4,5,6,7,0,1,2,29);
SHA256_EXP(2,3,4,5,6,7,0,1,30); SHA256_EXP(1,2,3,4,5,6,7,0,31);
SHA256_EXP(0,1,2,3,4,5,6,7,32); SHA256_EXP(7,0,1,2,3,4,5,6,33);
SHA256_EXP(6,7,0,1,2,3,4,5,34); SHA256_EXP(5,6,7,0,1,2,3,4,35);
SHA256_EXP(4,5,6,7,0,1,2,3,36); SHA256_EXP(3,4,5,6,7,0,1,2,37);
SHA256_EXP(2,3,4,5,6,7,0,1,38); SHA256_EXP(1,2,3,4,5,6,7,0,39);
SHA256_EXP(0,1,2,3,4,5,6,7,40); SHA256_EXP(7,0,1,2,3,4,5,6,41);
SHA256_EXP(6,7,0,1,2,3,4,5,42); SHA256_EXP(5,6,7,0,1,2,3,4,43);
SHA256_EXP(4,5,6,7,0,1,2,3,44); SHA256_EXP(3,4,5,6,7,0,1,2,45);
SHA256_EXP(2,3,4,5,6,7,0,1,46); SHA256_EXP(1,2,3,4,5,6,7,0,47);
SHA256_EXP(0,1,2,3,4,5,6,7,48); SHA256_EXP(7,0,1,2,3,4,5,6,49);
SHA256_EXP(6,7,0,1,2,3,4,5,50); SHA256_EXP(5,6,7,0,1,2,3,4,51);
SHA256_EXP(4,5,6,7,0,1,2,3,52); SHA256_EXP(3,4,5,6,7,0,1,2,53);
SHA256_EXP(2,3,4,5,6,7,0,1,54); SHA256_EXP(1,2,3,4,5,6,7,0,55);
SHA256_EXP(0,1,2,3,4,5,6,7,56); SHA256_EXP(7,0,1,2,3,4,5,6,57);
SHA256_EXP(6,7,0,1,2,3,4,5,58); SHA256_EXP(5,6,7,0,1,2,3,4,59);
SHA256_EXP(4,5,6,7,0,1,2,3,60); SHA256_EXP(3,4,5,6,7,0,1,2,61);
SHA256_EXP(2,3,4,5,6,7,0,1,62); SHA256_EXP(1,2,3,4,5,6,7,0,63);
ctx->h[0] += wv[0]; ctx->h[1] += wv[1];
ctx->h[2] += wv[2]; ctx->h[3] += wv[3];
ctx->h[4] += wv[4]; ctx->h[5] += wv[5];
ctx->h[6] += wv[6]; ctx->h[7] += wv[7];
#endif /* !UNROLL_LOOPS */
}
}
void sha256(const unsigned char *message, unsigned int len, unsigned char *digest)
{
sha256_ctx ctx;
sha256_init(&ctx);
sha256_update(&ctx, message, len);
sha256_final(&ctx, digest);
}
void sha256_init(sha256_ctx *ctx)
{
#ifndef UNROLL_LOOPS
int i;
for (i = 0; i < 8; i++) {
ctx->h[i] = sha256_h0[i];
}
#else
ctx->h[0] = sha256_h0[0]; ctx->h[1] = sha256_h0[1];
ctx->h[2] = sha256_h0[2]; ctx->h[3] = sha256_h0[3];
ctx->h[4] = sha256_h0[4]; ctx->h[5] = sha256_h0[5];
ctx->h[6] = sha256_h0[6]; ctx->h[7] = sha256_h0[7];
#endif /* !UNROLL_LOOPS */
ctx->len = 0;
ctx->tot_len = 0;
}
void sha256_update(sha256_ctx *ctx, const unsigned char *message,
unsigned int len)
{
unsigned int block_nb;
unsigned int new_len, rem_len, tmp_len;
const unsigned char *shifted_message;
tmp_len = SHA256_BLOCK_SIZE - ctx->len;
rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA256_BLOCK_SIZE) {
ctx->len += len;
return;
}
new_len = len - rem_len;
block_nb = new_len / SHA256_BLOCK_SIZE;
shifted_message = message + rem_len;
sha256_transf(ctx, ctx->block, 1);
sha256_transf(ctx, shifted_message, block_nb);
rem_len = new_len % SHA256_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 6],
rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 6;
}
void sha256_final(sha256_ctx *ctx, unsigned char *digest)
{
unsigned int block_nb;
unsigned int pm_len;
unsigned int len_b;
#ifndef UNROLL_LOOPS
int i;
#endif
block_nb = (1 + ((SHA256_BLOCK_SIZE - 9)
< (ctx->len % SHA256_BLOCK_SIZE)));
len_b = (ctx->tot_len + ctx->len) << 3;
pm_len = block_nb << 6;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
sha256_transf(ctx, ctx->block, block_nb);
#ifndef UNROLL_LOOPS
for (i = 0 ; i < 8; i++) {
UNPACK32(ctx->h[i], &digest[i << 2]);
}
#else
UNPACK32(ctx->h[0], &digest[ 0]);
UNPACK32(ctx->h[1], &digest[ 4]);
UNPACK32(ctx->h[2], &digest[ 8]);
UNPACK32(ctx->h[3], &digest[12]);
UNPACK32(ctx->h[4], &digest[16]);
UNPACK32(ctx->h[5], &digest[20]);
UNPACK32(ctx->h[6], &digest[24]);
UNPACK32(ctx->h[7], &digest[28]);
#endif /* !UNROLL_LOOPS */
}
/* SHA-512 functions */
void sha512_transf(sha512_ctx *ctx, const unsigned char *message,
unsigned int block_nb)
{
uint64 w[80];
uint64 wv[8];
uint64 t1, t2;
const unsigned char *sub_block;
int i, j;
for (i = 0; i < (int) block_nb; i++) {
sub_block = message + (i << 7);
#ifndef UNROLL_LOOPS
for (j = 0; j < 16; j++) {
PACK64(&sub_block[j << 3], &w[j]);
}
for (j = 16; j < 80; j++) {
SHA512_SCR(j);
}
for (j = 0; j < 8; j++) {
wv[j] = ctx->h[j];
}
for (j = 0; j < 80; j++) {
t1 = wv[7] + SHA512_F2(wv[4]) + CH(wv[4], wv[5], wv[6])
+ sha512_k[j] + w[j];
t2 = SHA512_F1(wv[0]) + MAJ(wv[0], wv[1], wv[2]);
wv[7] = wv[6];
wv[6] = wv[5];
wv[5] = wv[4];
wv[4] = wv[3] + t1;
wv[3] = wv[2];
wv[2] = wv[1];
wv[1] = wv[0];
wv[0] = t1 + t2;
}
for (j = 0; j < 8; j++) {
ctx->h[j] += wv[j];
}
#else
PACK64(&sub_block[ 0], &w[ 0]); PACK64(&sub_block[ 8], &w[ 1]);
PACK64(&sub_block[ 16], &w[ 2]); PACK64(&sub_block[ 24], &w[ 3]);
PACK64(&sub_block[ 32], &w[ 4]); PACK64(&sub_block[ 40], &w[ 5]);
PACK64(&sub_block[ 48], &w[ 6]); PACK64(&sub_block[ 56], &w[ 7]);
PACK64(&sub_block[ 64], &w[ 8]); PACK64(&sub_block[ 72], &w[ 9]);
PACK64(&sub_block[ 80], &w[10]); PACK64(&sub_block[ 88], &w[11]);
PACK64(&sub_block[ 96], &w[12]); PACK64(&sub_block[104], &w[13]);
PACK64(&sub_block[112], &w[14]); PACK64(&sub_block[120], &w[15]);
SHA512_SCR(16); SHA512_SCR(17); SHA512_SCR(18); SHA512_SCR(19);
SHA512_SCR(20); SHA512_SCR(21); SHA512_SCR(22); SHA512_SCR(23);
SHA512_SCR(24); SHA512_SCR(25); SHA512_SCR(26); SHA512_SCR(27);
SHA512_SCR(28); SHA512_SCR(29); SHA512_SCR(30); SHA512_SCR(31);
SHA512_SCR(32); SHA512_SCR(33); SHA512_SCR(34); SHA512_SCR(35);
SHA512_SCR(36); SHA512_SCR(37); SHA512_SCR(38); SHA512_SCR(39);
SHA512_SCR(40); SHA512_SCR(41); SHA512_SCR(42); SHA512_SCR(43);
SHA512_SCR(44); SHA512_SCR(45); SHA512_SCR(46); SHA512_SCR(47);
SHA512_SCR(48); SHA512_SCR(49); SHA512_SCR(50); SHA512_SCR(51);
SHA512_SCR(52); SHA512_SCR(53); SHA512_SCR(54); SHA512_SCR(55);
SHA512_SCR(56); SHA512_SCR(57); SHA512_SCR(58); SHA512_SCR(59);
SHA512_SCR(60); SHA512_SCR(61); SHA512_SCR(62); SHA512_SCR(63);
SHA512_SCR(64); SHA512_SCR(65); SHA512_SCR(66); SHA512_SCR(67);
SHA512_SCR(68); SHA512_SCR(69); SHA512_SCR(70); SHA512_SCR(71);
SHA512_SCR(72); SHA512_SCR(73); SHA512_SCR(74); SHA512_SCR(75);
SHA512_SCR(76); SHA512_SCR(77); SHA512_SCR(78); SHA512_SCR(79);
wv[0] = ctx->h[0]; wv[1] = ctx->h[1];
wv[2] = ctx->h[2]; wv[3] = ctx->h[3];
wv[4] = ctx->h[4]; wv[5] = ctx->h[5];
wv[6] = ctx->h[6]; wv[7] = ctx->h[7];
j = 0;
do {
SHA512_EXP(0,1,2,3,4,5,6,7,j); j++;
SHA512_EXP(7,0,1,2,3,4,5,6,j); j++;
SHA512_EXP(6,7,0,1,2,3,4,5,j); j++;
SHA512_EXP(5,6,7,0,1,2,3,4,j); j++;
SHA512_EXP(4,5,6,7,0,1,2,3,j); j++;
SHA512_EXP(3,4,5,6,7,0,1,2,j); j++;
SHA512_EXP(2,3,4,5,6,7,0,1,j); j++;
SHA512_EXP(1,2,3,4,5,6,7,0,j); j++;
} while (j < 80);
ctx->h[0] += wv[0]; ctx->h[1] += wv[1];
ctx->h[2] += wv[2]; ctx->h[3] += wv[3];
ctx->h[4] += wv[4]; ctx->h[5] += wv[5];
ctx->h[6] += wv[6]; ctx->h[7] += wv[7];
#endif /* !UNROLL_LOOPS */
}
}
void sha512(const unsigned char *message, unsigned int len,
unsigned char *digest)
{
sha512_ctx ctx;
sha512_init(&ctx);
sha512_update(&ctx, message, len);
sha512_final(&ctx, digest);
}
void sha512_init(sha512_ctx *ctx)
{
#ifndef UNROLL_LOOPS
int i;
for (i = 0; i < 8; i++) {
ctx->h[i] = sha512_h0[i];
}
#else
ctx->h[0] = sha512_h0[0]; ctx->h[1] = sha512_h0[1];
ctx->h[2] = sha512_h0[2]; ctx->h[3] = sha512_h0[3];
ctx->h[4] = sha512_h0[4]; ctx->h[5] = sha512_h0[5];
ctx->h[6] = sha512_h0[6]; ctx->h[7] = sha512_h0[7];
#endif /* !UNROLL_LOOPS */
ctx->len = 0;
ctx->tot_len = 0;
}
void sha512_update(sha512_ctx *ctx, const unsigned char *message,
unsigned int len)
{
unsigned int block_nb;
unsigned int new_len, rem_len, tmp_len;
const unsigned char *shifted_message;
tmp_len = SHA512_BLOCK_SIZE - ctx->len;
rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA512_BLOCK_SIZE) {
ctx->len += len;
return;
}
new_len = len - rem_len;
block_nb = new_len / SHA512_BLOCK_SIZE;
shifted_message = message + rem_len;
sha512_transf(ctx, ctx->block, 1);
sha512_transf(ctx, shifted_message, block_nb);
rem_len = new_len % SHA512_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 7],
rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 7;
}
void sha512_final(sha512_ctx *ctx, unsigned char *digest)
{
unsigned int block_nb;
unsigned int pm_len;
unsigned int len_b;
#ifndef UNROLL_LOOPS
int i;
#endif
block_nb = 1 + ((SHA512_BLOCK_SIZE - 17)
< (ctx->len % SHA512_BLOCK_SIZE));
len_b = (ctx->tot_len + ctx->len) << 3;
pm_len = block_nb << 7;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
sha512_transf(ctx, ctx->block, block_nb);
#ifndef UNROLL_LOOPS
for (i = 0 ; i < 8; i++) {
UNPACK64(ctx->h[i], &digest[i << 3]);
}
#else
UNPACK64(ctx->h[0], &digest[ 0]);
UNPACK64(ctx->h[1], &digest[ 8]);
UNPACK64(ctx->h[2], &digest[16]);
UNPACK64(ctx->h[3], &digest[24]);
UNPACK64(ctx->h[4], &digest[32]);
UNPACK64(ctx->h[5], &digest[40]);
UNPACK64(ctx->h[6], &digest[48]);
UNPACK64(ctx->h[7], &digest[56]);
#endif /* !UNROLL_LOOPS */
}
/* SHA-384 functions */
void sha384(const unsigned char *message, unsigned int len,
unsigned char *digest)
{
sha384_ctx ctx;
sha384_init(&ctx);
sha384_update(&ctx, message, len);
sha384_final(&ctx, digest);
}
void sha384_init(sha384_ctx *ctx)
{
#ifndef UNROLL_LOOPS
int i;
for (i = 0; i < 8; i++) {
ctx->h[i] = sha384_h0[i];
}
#else
ctx->h[0] = sha384_h0[0]; ctx->h[1] = sha384_h0[1];
ctx->h[2] = sha384_h0[2]; ctx->h[3] = sha384_h0[3];
ctx->h[4] = sha384_h0[4]; ctx->h[5] = sha384_h0[5];
ctx->h[6] = sha384_h0[6]; ctx->h[7] = sha384_h0[7];
#endif /* !UNROLL_LOOPS */
ctx->len = 0;
ctx->tot_len = 0;
}
void sha384_update(sha384_ctx *ctx, const unsigned char *message,
unsigned int len)
{
unsigned int block_nb;
unsigned int new_len, rem_len, tmp_len;
const unsigned char *shifted_message;
tmp_len = SHA384_BLOCK_SIZE - ctx->len;
rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA384_BLOCK_SIZE) {
ctx->len += len;
return;
}
new_len = len - rem_len;
block_nb = new_len / SHA384_BLOCK_SIZE;
shifted_message = message + rem_len;
sha512_transf(ctx, ctx->block, 1);
sha512_transf(ctx, shifted_message, block_nb);
rem_len = new_len % SHA384_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 7],
rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 7;
}
void sha384_final(sha384_ctx *ctx, unsigned char *digest)
{
unsigned int block_nb;
unsigned int pm_len;
unsigned int len_b;
#ifndef UNROLL_LOOPS
int i;
#endif
block_nb = (1 + ((SHA384_BLOCK_SIZE - 17)
< (ctx->len % SHA384_BLOCK_SIZE)));
len_b = (ctx->tot_len + ctx->len) << 3;
pm_len = block_nb << 7;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
sha512_transf(ctx, ctx->block, block_nb);
#ifndef UNROLL_LOOPS
for (i = 0 ; i < 6; i++) {
UNPACK64(ctx->h[i], &digest[i << 3]);
}
#else
UNPACK64(ctx->h[0], &digest[ 0]);
UNPACK64(ctx->h[1], &digest[ 8]);
UNPACK64(ctx->h[2], &digest[16]);
UNPACK64(ctx->h[3], &digest[24]);
UNPACK64(ctx->h[4], &digest[32]);
UNPACK64(ctx->h[5], &digest[40]);
#endif /* !UNROLL_LOOPS */
}
/* SHA-224 functions */
void sha224(const unsigned char *message, unsigned int len,
unsigned char *digest)
{
sha224_ctx ctx;
sha224_init(&ctx);
sha224_update(&ctx, message, len);
sha224_final(&ctx, digest);
}
void sha224_init(sha224_ctx *ctx)
{
#ifndef UNROLL_LOOPS
int i;
for (i = 0; i < 8; i++) {
ctx->h[i] = sha224_h0[i];
}
#else
ctx->h[0] = sha224_h0[0]; ctx->h[1] = sha224_h0[1];
ctx->h[2] = sha224_h0[2]; ctx->h[3] = sha224_h0[3];
ctx->h[4] = sha224_h0[4]; ctx->h[5] = sha224_h0[5];
ctx->h[6] = sha224_h0[6]; ctx->h[7] = sha224_h0[7];
#endif /* !UNROLL_LOOPS */
ctx->len = 0;
ctx->tot_len = 0;
}
void sha224_update(sha224_ctx *ctx, const unsigned char *message,
unsigned int len)
{
unsigned int block_nb;
unsigned int new_len, rem_len, tmp_len;
const unsigned char *shifted_message;
tmp_len = SHA224_BLOCK_SIZE - ctx->len;
rem_len = len < tmp_len ? len : tmp_len;
memcpy(&ctx->block[ctx->len], message, rem_len);
if (ctx->len + len < SHA224_BLOCK_SIZE) {
ctx->len += len;
return;
}
new_len = len - rem_len;
block_nb = new_len / SHA224_BLOCK_SIZE;
shifted_message = message + rem_len;
sha256_transf(ctx, ctx->block, 1);
sha256_transf(ctx, shifted_message, block_nb);
rem_len = new_len % SHA224_BLOCK_SIZE;
memcpy(ctx->block, &shifted_message[block_nb << 6],
rem_len);
ctx->len = rem_len;
ctx->tot_len += (block_nb + 1) << 6;
}
void sha224_final(sha224_ctx *ctx, unsigned char *digest)
{
unsigned int block_nb;
unsigned int pm_len;
unsigned int len_b;
#ifndef UNROLL_LOOPS
int i;
#endif
block_nb = (1 + ((SHA224_BLOCK_SIZE - 9)
< (ctx->len % SHA224_BLOCK_SIZE)));
len_b = (ctx->tot_len + ctx->len) << 3;
pm_len = block_nb << 6;
memset(ctx->block + ctx->len, 0, pm_len - ctx->len);
ctx->block[ctx->len] = 0x80;
UNPACK32(len_b, ctx->block + pm_len - 4);
sha256_transf(ctx, ctx->block, block_nb);
#ifndef UNROLL_LOOPS
for (i = 0 ; i < 7; i++) {
UNPACK32(ctx->h[i], &digest[i << 2]);
}
#else
UNPACK32(ctx->h[0], &digest[ 0]);
UNPACK32(ctx->h[1], &digest[ 4]);
UNPACK32(ctx->h[2], &digest[ 8]);
UNPACK32(ctx->h[3], &digest[12]);
UNPACK32(ctx->h[4], &digest[16]);
UNPACK32(ctx->h[5], &digest[20]);
UNPACK32(ctx->h[6], &digest[24]);
#endif /* !UNROLL_LOOPS */
}
#ifdef TEST_VECTORS
/* FIPS 180-2 Validation tests */
#include <stdio.h>
#include <stdlib.h>
void test(const char *vector, unsigned char *digest,
unsigned int digest_size)
{
char output[2 * SHA512_DIGEST_SIZE + 1];
int i;
output[2 * digest_size] = '\0';
for (i = 0; i < (int) digest_size ; i++) {
sprintf(output + 2 * i, "%02x", digest[i]);
}
printf("H: %s\n", output);
if (strcmp(vector, output)) {
fprintf(stderr, "Test failed.\n");
exit(EXIT_FAILURE);
}
}
int main(void)
{
static const char *vectors[4][3] =
{ /* SHA-224 */
{
"23097d223405d8228642a477bda255b32aadbce4bda0b3f7e36c9da7",
"75388b16512776cc5dba5da1fd890150b0c6455cb4f58b1952522525",
"20794655980c91d8bbb4c1ea97618a4bf03f42581948b2ee4ee7ad67",
},
/* SHA-256 */
{
"ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad",
"248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1",
"cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0",
},
/* SHA-384 */
{
"cb00753f45a35e8bb5a03d699ac65007272c32ab0eded1631a8b605a43ff5bed"
"8086072ba1e7cc2358baeca134c825a7",
"09330c33f71147e83d192fc782cd1b4753111b173b3b05d22fa08086e3b0f712"
"fcc7c71a557e2db966c3e9fa91746039",
"9d0e1809716474cb086e834e310a4a1ced149e9c00f248527972cec5704c2a5b"
"07b8b3dc38ecc4ebae97ddd87f3d8985",
},
/* SHA-512 */
{
"ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a"
"2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f",
"8e959b75dae313da8cf4f72814fc143f8f7779c6eb9f7fa17299aeadb6889018"
"501d289e4900f7e4331b99dec4b5433ac7d329eeb6dd26545e96e55b874be909",
"e718483d0ce769644e2e42c7bc15b4638e1f98b13b2044285632a803afa973eb"
"de0ff244877ea60a4cb0432ce577c31beb009c5c2c49aa2e4eadb217ad8cc09b"
}
};
static const char message1[] = "abc";
static const char message2a[] = "abcdbcdecdefdefgefghfghighijhi"
"jkijkljklmklmnlmnomnopnopq";
static const char message2b[] = "abcdefghbcdefghicdefghijdefghijkefghij"
"klfghijklmghijklmnhijklmnoijklmnopjklm"
"nopqklmnopqrlmnopqrsmnopqrstnopqrstu";
unsigned char *message3;
unsigned int message3_len = 1000000;
unsigned char digest[SHA512_DIGEST_SIZE];
message3 = malloc(message3_len);
if (message3 == NULL) {
fprintf(stderr, "Can't allocate memory\n");
return -1;
}
memset(message3, 'a', message3_len);
printf("SHA-2 FIPS 180-2 Validation tests\n\n");
printf("SHA-224 Test vectors\n");
sha224((const unsigned char *) message1, strlen(message1), digest);
test(vectors[0][0], digest, SHA224_DIGEST_SIZE);
sha224((const unsigned char *) message2a, strlen(message2a), digest);
test(vectors[0][1], digest, SHA224_DIGEST_SIZE);
sha224(message3, message3_len, digest);
test(vectors[0][2], digest, SHA224_DIGEST_SIZE);
printf("\n");
printf("SHA-256 Test vectors\n");
sha256((const unsigned char *) message1, strlen(message1), digest);
test(vectors[1][0], digest, SHA256_DIGEST_SIZE);
sha256((const unsigned char *) message2a, strlen(message2a), digest);
test(vectors[1][1], digest, SHA256_DIGEST_SIZE);
sha256(message3, message3_len, digest);
test(vectors[1][2], digest, SHA256_DIGEST_SIZE);
printf("\n");
printf("SHA-384 Test vectors\n");
sha384((const unsigned char *) message1, strlen(message1), digest);
test(vectors[2][0], digest, SHA384_DIGEST_SIZE);
sha384((const unsigned char *)message2b, strlen(message2b), digest);
test(vectors[2][1], digest, SHA384_DIGEST_SIZE);
sha384(message3, message3_len, digest);
test(vectors[2][2], digest, SHA384_DIGEST_SIZE);
printf("\n");
printf("SHA-512 Test vectors\n");
sha512((const unsigned char *) message1, strlen(message1), digest);
test(vectors[3][0], digest, SHA512_DIGEST_SIZE);
sha512((const unsigned char *) message2b, strlen(message2b), digest);
test(vectors[3][1], digest, SHA512_DIGEST_SIZE);
sha512(message3, message3_len, digest);
test(vectors[3][2], digest, SHA512_DIGEST_SIZE);
printf("\n");
printf("All tests passed.\n");
return 0;
}
#endif /* TEST_VECTORS */
|
mpl-2.0
|
thindil/laeran-mud
|
src/ed/vars.c
|
1
|
2331
|
/*
* This file is part of DGD, https://github.com/dworkin/dgd
* Copyright (C) 1993-2010 Dworkin B.V.
* Copyright (C) 2010 DGD Authors (see the commit log for details)
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
# include "ed.h"
# include "vars.h"
/*
* The editor variables are handled here.
*/
/*
* NAME: vars->new()
* DESCRIPTION: allocate and initialize a variable buffer
*/
vars *va_new()
{
static vars dflt[] = {
{ "ignorecase", "ic", FALSE },
{ "shiftwidth", "sw", 4 },
{ "window", "wi", 20 },
};
vars *v;
v = ALLOC(vars, NUMBER_OF_VARS);
memcpy(v, dflt, sizeof(dflt));
return v;
}
/*
* NAME: vars->del()
* DESCRIPTION: delete a variable buffer
*/
void va_del(vars *v)
{
FREE(v);
}
/*
* NAME: vars->set()
* DESCRIPTION: set the value of a variable.
*/
void va_set(vars *v, char *option)
{
char *val;
Int i;
if (strncmp(option, "no", 2) == 0) {
option += 2;
val = "0";
} else {
val = strchr(option, '=');
if (val != (char *) NULL) {
*val++ = '\0';
}
}
for (i = NUMBER_OF_VARS; i > 0; --i, v++) {
if (strcmp(v->name, option) == 0 ||
strcmp(v->sname, option) == 0) {
if (!val) {
v->val = 1;
} else {
char *p;
p = val;
i = strtoint(&p);
if (val == p || i < 0) {
error("Bad numeric value for option \"%s\"", v->name);
}
v->val = i;
}
return;
}
}
error("No such option");
}
/*
* NAME: vars->show()
* DESCRIPTION: show all variables
*/
void va_show(vars *v)
{
output("%signorecase\011", ((v++)->val) ? "" : "no"); /* HT */
output("shiftwidth=%ld\011", (long) (v++)->val); /* HT */
output("window=%ld\012", (long) (v++)->val); /* LF */
}
|
agpl-3.0
|
Appled/AscEmu
|
src/shared/Network/SocketMgrLinux.cpp
|
2
|
5099
|
/*
* Multiplatform Async Network Library
* Copyright (c) 2007 Burlex
*
* SocketMgr - epoll manager for Linux.
*
*/
#include "Network.h"
#ifdef CONFIG_USE_EPOLL
//#define ENABLE_ANTI_DOS
void SocketMgr::AddSocket(Socket* s)
{
#ifdef ENABLE_ANTI_DOS
uint32 saddr;
int i, count;
// Check how many connections we already have from that ip
saddr = s->GetRemoteAddress().s_addr;
for(i = 0, count = 0; i <= max_fd; i++)
{
if(fds[i])
{
if(fds[i]->GetRemoteAddress().s_addr == saddr) count++;
}
}
// More than 16 connections from the same ip? enough! xD
if(count > 16)
{
s->Disconnect(false);
return;
}
#endif
if(fds[s->GetFd()] != NULL)
{
//fds[s->GetFd()]->Delete();
//fds[s->GetFd()] = NULL;
s->Delete();
return;
}
if(max_fd < s->GetFd()) max_fd = s->GetFd();
fds[s->GetFd()] = s;
++socket_count;
// Add epoll event based on socket activity.
struct epoll_event ev;
memset(&ev, 0, sizeof(epoll_event));
ev.events = (s->writeBuffer.GetSize()) ? EPOLLOUT : EPOLLIN;
ev.events |= EPOLLET; /* use edge-triggered instead of level-triggered because we're using nonblocking sockets */
ev.data.fd = s->GetFd();
if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ev.data.fd, &ev))
sLogger.failure("Could not add event to epoll set on fd %u", ev.data.fd);
}
void SocketMgr::AddListenSocket(ListenSocketBase* s)
{
assert(listenfds[s->GetFd()] == 0);
listenfds[s->GetFd()] = s;
// Add epoll event based on socket activity.
struct epoll_event ev;
memset(&ev, 0, sizeof(epoll_event));
ev.events = EPOLLIN;
ev.events |= EPOLLET; /* use edge-triggered instead of level-triggered because we're using nonblocking sockets */
ev.data.fd = s->GetFd();
if(epoll_ctl(epoll_fd, EPOLL_CTL_ADD, ev.data.fd, &ev))
sLogger.failure("Could not add event to epoll set on fd %u", ev.data.fd);
}
void SocketMgr::RemoveSocket(Socket* s)
{
if(fds[s->GetFd()] != s)
{
sLogger.failure("Could not remove fd %u from the set due to it not existing?", s->GetFd());
return;
}
fds[s->GetFd()] = NULL;
--socket_count;
// Remove from epoll list.
struct epoll_event ev;
memset(&ev, 0, sizeof(epoll_event));
ev.data.fd = s->GetFd();
ev.events = EPOLLIN | EPOLLOUT | EPOLLERR | EPOLLHUP | EPOLLONESHOT;
if(epoll_ctl(epoll_fd, EPOLL_CTL_DEL, ev.data.fd, &ev))
sLogger.failure("Could not remove fd %u from epoll set, errno %u", s->GetFd(), errno);
}
void SocketMgr::CloseAll()
{
for(uint32 i = 0; i < SOCKET_HOLDER_SIZE; ++i)
if(fds[i] != NULL)
fds[i]->Delete();
}
void SocketMgr::SpawnWorkerThreads()
{
uint32 count = 1;
for(uint32 i = 0; i < count; ++i)
ThreadPool.ExecuteTask(new SocketWorkerThread());
}
void SocketMgr::ShowStatus()
{
sLogger.info("sockets count = %u", static_cast<uint32_t>(socket_count.load()));
}
bool SocketWorkerThread::runThread()
{
int fd_count;
Socket* ptr;
int i;
running = true;
while(running)
{
fd_count = epoll_wait(sSocketMgr.epoll_fd, events, THREAD_EVENT_SIZE, 5000);
for(i = 0; i < fd_count; ++i)
{
if(events[i].data.fd >= SOCKET_HOLDER_SIZE)
{
sLogger.failure("Requested FD that is too high (%u)", events[i].data.fd);
continue;
}
ptr = sSocketMgr.fds[events[i].data.fd];
if(ptr == NULL)
{
if((ptr = ((Socket*)sSocketMgr.listenfds[events[i].data.fd])) != NULL)
((ListenSocketBase*)ptr)->OnAccept();
else
sLogger.failure("Returned invalid fd (no pointer) of FD %u", events[i].data.fd);
continue;
}
if(events[i].events & EPOLLHUP || events[i].events & EPOLLERR)
{
ptr->Disconnect();
continue;
}
else if(events[i].events & EPOLLIN)
{
ptr->ReadCallback(0); // Len is unknown at this point.
/* changing to written state? */
if(ptr->writeBuffer.GetSize() && !ptr->HasSendLock() && ptr->IsConnected())
ptr->PostEvent(EPOLLOUT);
}
else if(events[i].events & EPOLLOUT)
{
ptr->BurstBegin(); // Lock receive mutex
ptr->WriteCallback(); // Perform actual send()
if(ptr->writeBuffer.GetSize() > 0)
{
/* we don't have to do anything here. no more oneshots :) */
}
else
{
/* change back to a read event */
ptr->DecSendLock();
ptr->PostEvent(EPOLLIN);
}
ptr->BurstEnd(); // Unlock
}
}
}
return true;
}
#endif
|
agpl-3.0
|
te42kyfo/Feldrand
|
include/OpenClHelper/clcc/clinfo.cpp
|
2
|
13454
|
//////////////////////////////////////////////////////////////////////////
// Copyright (c) 2009-2011 Organic Vectory B.V.
// Written by George van Venrooij
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file license.txt)
//////////////////////////////////////////////////////////////////////////
//! \file clinfo.cpp
//! \brief OpenCL information classes source
#include "clinfo.hpp"
#include "clpp.hpp"
namespace cl
{
namespace
{
//! \brief Retrieve a single value of device info
template <typename T>
void
get_device_info(cl_device_id device_id, cl_device_info device_info, T* value)
{
CLCALL(clGetDeviceInfo(device_id, device_info, sizeof(T), value, NULL));
}
//! \brief Retrieve an array of values of device info
template <typename T>
void
get_device_info(cl_device_id device_id, cl_device_info device_info, T* values, ::size_t count)
{
CLCALL(clGetDeviceInfo(device_id, device_info, sizeof(T) * count, values, NULL));
}
//! \brief Retrieve a string value of device info
template <>
void
get_device_info(cl_device_id device_id, cl_device_info device_info, std::string* value)
{
::size_t size = 0;
boost::scoped_array<char> data;
// Get all params for the given platform id, first query their size, then get the actual data
CLCALL(clGetDeviceInfo(device_id, device_info, 0, NULL, &size));
data.reset(new char[size]);
CLCALL(clGetDeviceInfo(device_id, device_info, size, data.get(), NULL));
value->assign(data.get(), data.get() + size);
}
}
//! \brief Constructor
//! \param device_id a valid OpenCL device ID
//!
//! Retrieves all available information on the given device
device::device(cl_device_id device_id)
: device_id_(device_id)
{
// Retrieve all device info
get_device_info(device_id, CL_DEVICE_TYPE , &device_type_ );
get_device_info(device_id, CL_DEVICE_VENDOR_ID , &vendor_id_ );
get_device_info(device_id, CL_DEVICE_MAX_COMPUTE_UNITS , &max_compute_units_ );
get_device_info(device_id, CL_DEVICE_MAX_WORK_ITEM_DIMENSIONS , &max_work_item_dimensions_ );
// Allocate max_work_group_size_
max_work_item_sizes_.reset(new ::size_t[max_work_item_dimensions_]);
get_device_info(device_id, CL_DEVICE_MAX_WORK_ITEM_SIZES , max_work_item_sizes_.get() , max_work_item_dimensions_);
get_device_info(device_id, CL_DEVICE_MAX_WORK_GROUP_SIZE , &max_work_group_size_ );
get_device_info(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_CHAR , &preferred_vector_width_char_ );
get_device_info(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_SHORT , &preferred_vector_width_short_ );
get_device_info(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_INT , &preferred_vector_width_int_ );
get_device_info(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_LONG , &preferred_vector_width_long_ );
get_device_info(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT , &preferred_vector_width_float_ );
get_device_info(device_id, CL_DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE , &preferred_vector_width_double_ );
get_device_info(device_id, CL_DEVICE_MAX_CLOCK_FREQUENCY , &max_clock_frequency_ );
get_device_info(device_id, CL_DEVICE_ADDRESS_BITS , &address_bits_ );
get_device_info(device_id, CL_DEVICE_MAX_MEM_ALLOC_SIZE , &max_mem_alloc_size_ );
get_device_info(device_id, CL_DEVICE_IMAGE_SUPPORT , &image_support_ );
get_device_info(device_id, CL_DEVICE_MAX_READ_IMAGE_ARGS , &max_read_image_args_ );
get_device_info(device_id, CL_DEVICE_MAX_WRITE_IMAGE_ARGS , &max_write_image_args_ );
get_device_info(device_id, CL_DEVICE_IMAGE2D_MAX_WIDTH , &image2d_max_width_ );
get_device_info(device_id, CL_DEVICE_IMAGE2D_MAX_HEIGHT , &image2d_max_height_ );
get_device_info(device_id, CL_DEVICE_IMAGE3D_MAX_WIDTH , &image3d_max_width_ );
get_device_info(device_id, CL_DEVICE_IMAGE3D_MAX_HEIGHT , &image3d_max_height_ );
get_device_info(device_id, CL_DEVICE_IMAGE3D_MAX_DEPTH , &image3d_max_depth_ );
get_device_info(device_id, CL_DEVICE_MAX_SAMPLERS , &max_samplers_ );
get_device_info(device_id, CL_DEVICE_MAX_PARAMETER_SIZE , &max_parameter_size_ );
get_device_info(device_id, CL_DEVICE_MEM_BASE_ADDR_ALIGN , &mem_base_addr_align_ );
get_device_info(device_id, CL_DEVICE_MIN_DATA_TYPE_ALIGN_SIZE , &min_data_type_align_size_ );
get_device_info(device_id, CL_DEVICE_SINGLE_FP_CONFIG , &single_fp_config_ );
get_device_info(device_id, CL_DEVICE_GLOBAL_MEM_CACHE_TYPE , &global_mem_cache_type_ );
get_device_info(device_id, CL_DEVICE_GLOBAL_MEM_CACHELINE_SIZE , &global_mem_cacheline_size_ );
get_device_info(device_id, CL_DEVICE_GLOBAL_MEM_CACHE_SIZE , &global_mem_cache_size_ );
get_device_info(device_id, CL_DEVICE_GLOBAL_MEM_SIZE , &global_mem_size_ );
get_device_info(device_id, CL_DEVICE_MAX_CONSTANT_BUFFER_SIZE , &max_constant_buffer_size_ );
get_device_info(device_id, CL_DEVICE_MAX_CONSTANT_ARGS , &max_constant_args_ );
get_device_info(device_id, CL_DEVICE_LOCAL_MEM_TYPE , &local_mem_type_ );
get_device_info(device_id, CL_DEVICE_LOCAL_MEM_SIZE , &local_mem_size_ );
get_device_info(device_id, CL_DEVICE_ERROR_CORRECTION_SUPPORT , &error_correction_support_ );
get_device_info(device_id, CL_DEVICE_PROFILING_TIMER_RESOLUTION , &profiling_timer_resolution_ );
get_device_info(device_id, CL_DEVICE_ENDIAN_LITTLE , &endian_little_ );
get_device_info(device_id, CL_DEVICE_AVAILABLE , &available_ );
get_device_info(device_id, CL_DEVICE_COMPILER_AVAILABLE , &compiler_available_ );
get_device_info(device_id, CL_DEVICE_EXECUTION_CAPABILITIES , &execution_capabilities_ );
get_device_info(device_id, CL_DEVICE_QUEUE_PROPERTIES , &queue_properties_ );
get_device_info(device_id, CL_DEVICE_PLATFORM , &platform_id_ );
get_device_info(device_id, CL_DEVICE_NAME , &name_ );
get_device_info(device_id, CL_DEVICE_VENDOR , &vendor_ );
get_device_info(device_id, CL_DRIVER_VERSION , &driver_version_ );
get_device_info(device_id, CL_DEVICE_PROFILE , &profile_ );
get_device_info(device_id, CL_DEVICE_VERSION , &device_version_ );
get_device_info(device_id, CL_DEVICE_EXTENSIONS , &extensions_ );
}
//! \brief Destructor
device::~device()
{
}
//! \brief Checks if an extension is supported
//! \param extension_name the name of the extension
//! \return \e true if the extension is supported, \e false otherwise
bool
device::extension_supported(const std::string& extension_name) const
{
return (extensions_.find(extension_name) != std::string::npos);
}
//! \brief Platform copy-constructor
platform::platform(const platform& platform)
: platform_id_ (platform.platform_id_)
, profile_ (platform.profile_)
, version_ (platform.version_)
, name_ (platform.name_ )
, vendor_ (platform.vendor_ )
, extensions_ (platform.extensions_)
{
}
//! \brief Platform assignment-operator
platform&
platform::operator=(const platform& platform)
{
platform_id_ = platform.platform_id_ ;
profile_ = platform.profile_ ;
version_ = platform.version_ ;
name_ = platform.name_ ;
vendor_ = platform.vendor_ ;
extensions_ = platform.extensions_ ;
return *this;
}
//! \brief Platform destructor
platform::~platform()
{
}
//! \brief Checks if an extension is supported
//! \param extension_name the name of the extension
//! \return \e true if the extension is supported, \e false otherwise
bool
platform::extension_supported(const std::string& extension_name) const
{
return (extensions_.find(extension_name) != std::string::npos);
}
//! \brief Returns the number of devices
//! \return the number of devices in this platform
cl_uint
platform::num_devices() const
{
return num_devices_;
}
//! \brief Returns a specific device
//! \param index zero-based index of the device requested
//! \return an object representing the device
device
platform::get_device(cl_uint index) const
{
if (index >= num_devices_)
{
BOOST_THROW_EXCEPTION(cl::exception("index out of range"));
}
return device(device_ids_[index]);
}
// anonymous namespace containing some utility functions for retrieving
// platform info of various types
namespace
{
//! \brief Retrieve a string value of platform info
void
get_platform_info(cl_platform_id platform_id, cl_platform_info platform_info, std::string* value)
{
::size_t size = 0;
boost::scoped_array<char> data;
// Get all params for the given platform id, first query their size, then get the actual data
CLCALL(clGetPlatformInfo(platform_id, platform_info, 0, NULL, &size));
data.reset(new char[size]);
CLCALL(clGetPlatformInfo(platform_id, platform_info, size, data.get(), NULL));
value->assign(data.get(), data.get() + size);
}
}
//! \brief Platform constructor
//! \param platform_id valid OpenCL %platform ID
//!
//! Retrieves all available information on the given platform
platform::platform(cl_platform_id platform_id)
: platform_id_(platform_id)
, num_devices_(0)
{
get_platform_info(platform_id, CL_PLATFORM_PROFILE , &profile_ );
get_platform_info(platform_id, CL_PLATFORM_VERSION , &version_ );
get_platform_info(platform_id, CL_PLATFORM_NAME , &name_ );
get_platform_info(platform_id, CL_PLATFORM_VENDOR , &vendor_ );
get_platform_info(platform_id, CL_PLATFORM_EXTENSIONS , &extensions_ );
// Retrieve device id count
CLCALL(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, 0, NULL, &num_devices_));
// Allocate
device_ids_.reset(new cl_device_id[num_devices_]);
// Retrieve all id's
CLCALL(clGetDeviceIDs(platform_id, CL_DEVICE_TYPE_ALL, num_devices_, device_ids_.get(), NULL));
}
//! \brief Default constructor
driver::driver()
: num_platforms_(0)
{
// Get number of platforms
CLCALL(clGetPlatformIDs(0, NULL, &num_platforms_));
// Allocate platform id's
platform_ids_.reset(new cl_platform_id[num_platforms_]);
// Retrieve platform id's
CLCALL(clGetPlatformIDs(num_platforms_, platform_ids_.get(), NULL));
}
//! \brief Destructor
driver::~driver()
{
}
//! \brief Retrieve the number of platforms
//! \return the number of OpenCL platforms
cl_uint
driver::num_platforms() const
{
return num_platforms_;
}
//! \brief Returns a specific platform
//! \param index zero-based index of the platform requested
//! \return an object representing the platform
platform
driver::get_platform(cl_uint index) const
{
if (index >= num_platforms_)
{
BOOST_THROW_EXCEPTION(cl::exception("index out of range"));
}
return platform(platform_ids_[index]);
}
} // namespace cl
|
agpl-3.0
|
raesjo/SKIRTcorona
|
SKIRTcore/PowAxDustGridStructure.cpp
|
2
|
3251
|
/*//////////////////////////////////////////////////////////////////
//// SKIRT -- an advanced radiative transfer code ////
//// © Astronomical Observatory, Ghent University ////
///////////////////////////////////////////////////////////////// */
#include <cmath>
#include "NR.hpp"
#include "PowAxDustGridStructure.hpp"
#include "FatalError.hpp"
using namespace std;
//////////////////////////////////////////////////////////////////////
PowAxDustGridStructure::PowAxDustGridStructure()
: _Rratio(0), _zratio(0)
{
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setupSelfBefore()
{
AxDustGridStructure::setupSelfBefore();
// verify property values
if (_NR <= 0) throw FATALERROR("NR should be positive");
if (_Rmax <= 0) throw FATALERROR("Rmax should be positive");
if (_Rratio <= 0) throw FATALERROR("Rratio should be positive");
if (_Nz <= 0) throw FATALERROR("Nz should be positive");
if (_zmax <= 0) throw FATALERROR("zmax should be positive");
if (_zratio <= 0) throw FATALERROR("zratio should be positive");
// setup grid distribution in R
NR::powgrid(_Rv, -0., _Rmax, _NR, _Rratio);
// setup grid distribution in z
NR::sympowgrid(_zv, _zmax, _Nz, _zratio);
// the total number of cells
_Ncells = _NR*_Nz;
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setRadialExtent(double value)
{
_Rmax = value;
}
//////////////////////////////////////////////////////////////////////
double PowAxDustGridStructure::radialExtent() const
{
return _Rmax;
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setRadialRatio(double value)
{
_Rratio = value;
}
//////////////////////////////////////////////////////////////////////
double PowAxDustGridStructure::radialRatio() const
{
return _Rratio;
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setRadialPoints(int value)
{
_NR = value;
}
//////////////////////////////////////////////////////////////////////
int PowAxDustGridStructure::radialPoints() const
{
return _NR;
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setAxialExtent(double value)
{
_zmax = value;
_zmin = - value;
}
//////////////////////////////////////////////////////////////////////
double PowAxDustGridStructure::axialExtent() const
{
return _zmax;
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setAxialRatio(double value)
{
_zratio = value;
}
//////////////////////////////////////////////////////////////////////
double PowAxDustGridStructure::axialRatio() const
{
return _zratio;
}
//////////////////////////////////////////////////////////////////////
void PowAxDustGridStructure::setAxialPoints(int value)
{
_Nz = value;
}
//////////////////////////////////////////////////////////////////////
int PowAxDustGridStructure::axialPoints() const
{
return _Nz;
}
//////////////////////////////////////////////////////////////////////
|
agpl-3.0
|
xibosignage/xibo-linux
|
player/control/media/MediaParser.cpp
|
2
|
7811
|
#include "MediaParser.hpp"
#include "control/media/Media.hpp"
#include "control/media/MediaParsersRepo.hpp"
#include "control/media/MediaResources.hpp"
#include "control/transitions/FadeTransitionExecutor.hpp"
#include "control/transitions/FlyTransitionExecutor.hpp"
#include "common/fs/FileSystem.hpp"
#include "common/fs/Resource.hpp"
namespace MediaResources = XlfResources::Media;
const bool DefaultEnableStat = true;
std::istream& operator>>(std::istream& in, MediaGeometry::ScaleType& scaleType)
{
std::string temp;
in >> temp;
if (temp == MediaResources::Geometry::Scaled || temp == MediaResources::Geometry::Aspect)
scaleType = MediaGeometry::ScaleType::Scaled;
else if (temp == MediaResources::Geometry::Stretch)
scaleType = MediaGeometry::ScaleType::Stretch;
return in;
}
std::istream& operator>>(std::istream& in, MediaGeometry::Align& align)
{
std::string temp;
in >> temp;
if (temp == MediaResources::Geometry::LeftAlign)
align = MediaGeometry::Align::Left;
else if (temp == MediaResources::Geometry::CenterAlign)
align = MediaGeometry::Align::Center;
else if (temp == MediaResources::Geometry::RightAlign)
align = MediaGeometry::Align::Right;
return in;
}
std::istream& operator>>(std::istream& in, MediaGeometry::Valign& valign)
{
std::string temp;
in >> temp;
if (temp == MediaResources::Geometry::TopValign)
valign = MediaGeometry::Valign::Top;
else if (temp == MediaResources::Geometry::MiddleValign)
valign = MediaGeometry::Valign::Middle;
else if (temp == MediaResources::Geometry::BottomValign)
valign = MediaGeometry::Valign::Bottom;
return in;
}
std::istream& operator>>(std::istream& in, Transition::Type& type)
{
std::string temp;
in >> temp;
if (temp == MediaResources::Tranisiton::Fly)
type = Transition::Type::Fly;
else if (temp == MediaResources::Tranisiton::FadeIn || temp == MediaResources::Tranisiton::FadeOut)
type = Transition::Type::Fade;
return in;
}
std::istream& operator>>(std::istream& in, Transition::Direction& direction)
{
std::string temp;
in >> temp;
if (temp == MediaResources::Tranisiton::N)
direction = Transition::Direction::N;
else if (temp == MediaResources::Tranisiton::NE)
direction = Transition::Direction::NE;
else if (temp == MediaResources::Tranisiton::E)
direction = Transition::Direction::E;
else if (temp == MediaResources::Tranisiton::SE)
direction = Transition::Direction::SE;
else if (temp == MediaResources::Tranisiton::S)
direction = Transition::Direction::S;
else if (temp == MediaResources::Tranisiton::SW)
direction = Transition::Direction::SW;
else if (temp == MediaResources::Tranisiton::W)
direction = Transition::Direction::W;
else if (temp == MediaResources::Tranisiton::NW)
direction = Transition::Direction::NW;
return in;
}
std::unique_ptr<Xibo::Media> MediaParser::mediaFrom(const XmlNode& node,
int parentWidth,
int parentHeight,
bool globalStatEnabled)
{
using namespace std::string_literals;
try
{
globalStatEnabled_ = globalStatEnabled;
auto baseOptions = baseOptionsFrom(node);
auto media = createMedia(baseOptions, node, parentWidth, parentHeight);
media->inTransition(inTransitionFrom(node, media->view()));
media->outTransition(outTransitionFrom(node, media->view()));
attach(*media, node);
return media;
}
catch (PlayerRuntimeError& e)
{
throw MediaParser::Error{"MediaParser - " + e.domain(), e.message()};
}
catch (std::exception& e)
{
throw MediaParser::Error{"MediaParser", e.what()};
}
}
MediaOptions MediaParser::baseOptionsFrom(const XmlNode& node)
{
auto type = typeFrom(node);
auto id = idFrom(node);
auto uri = uriFrom(node);
auto duration = durationFrom(node);
auto stat = globalStatEnabled_ && statFrom(node);
auto geometry = geometryFrom(node);
return MediaOptions{type, id, uri, duration, stat, geometry};
}
MediaOptions::Type MediaParser::typeFrom(const XmlNode& node)
{
auto type = node.get<std::string>(MediaResources::Type);
auto render = node.get<std::string>(MediaResources::Render);
return {type, render};
}
int MediaParser::idFrom(const XmlNode& node)
{
return node.get<int>(MediaResources::Id);
}
Uri MediaParser::uriFrom(const XmlNode& node)
{
auto uri = node.get_optional<std::string>(MediaResources::Uri);
if (uri)
{
Resource fullPath{uri.value()};
if (!FileSystem::isRegularFile(fullPath)) return Uri::fromString(uri.value());
return Uri::fromFile(fullPath);
}
throw Error{"MediaParser", "Uri is empty"};
}
int MediaParser::durationFrom(const XmlNode& node)
{
return node.get<int>(MediaResources::Duration);
}
MediaGeometry MediaParser::geometryFrom(const XmlNode& /*node*/)
{
return MediaGeometry{MediaGeometry::ScaleType::Scaled, MediaGeometry::Align::Left, MediaGeometry::Valign::Top};
}
bool MediaParser::statFrom(const XmlNode& node)
{
return node.get<bool>(MediaResources::EnableStat, DefaultEnableStat);
}
void MediaParser::attach(Xibo::Media& media, const XmlNode& node)
{
for (auto [nodeName, attachedNode] : node)
{
MediaOptions::Type type{nodeName + "node", MediaResources::NativeRender};
auto parser = MediaParsersRepo::get(type);
if (parser)
{
media.attach(parser->mediaFrom(attachedNode, 0, 0, globalStatEnabled_)); // TODO: remove 0, 0
}
}
}
template <Transition::Heading heading>
std::unique_ptr<TransitionExecutor> MediaParser::createTransition(Transition::Type type,
Transition::Direction direction,
int duration,
const std::shared_ptr<Xibo::Widget>& view)
{
switch (type)
{
case Transition::Type::Fly: return std::make_unique<FlyTransitionExecutor>(heading, direction, duration, view);
case Transition::Type::Fade: return std::make_unique<FadeTransitionExecutor>(heading, duration, view);
}
return nullptr;
}
std::unique_ptr<TransitionExecutor> MediaParser::inTransitionFrom(const XmlNode& node,
const std::shared_ptr<Xibo::Widget>& view)
{
if (auto type = node.get_optional<Transition::Type>(MediaResources::Tranisiton::InType))
{
auto direction =
node.get<Transition::Direction>(MediaResources::Tranisiton::InDirection, Transition::Direction::N);
int duration = node.get<int>(MediaResources::Tranisiton::InDuration);
return createTransition<Transition::Heading::In>(type.value(), direction, duration, view);
}
return nullptr;
}
std::unique_ptr<TransitionExecutor> MediaParser::outTransitionFrom(const XmlNode& node,
const std::shared_ptr<Xibo::Widget>& view)
{
if (auto type = node.get_optional<Transition::Type>(MediaResources::Tranisiton::OutType))
{
auto direction =
node.get<Transition::Direction>(MediaResources::Tranisiton::OutDirection, Transition::Direction::N);
int duration = node.get<int>(MediaResources::Tranisiton::OutDuration);
return createTransition<Transition::Heading::Out>(type.value(), direction, duration, view);
}
return nullptr;
}
|
agpl-3.0
|
hongyunnchen/openbts
|
Control/DCCHDispatch.cpp
|
8
|
4104
|
/**@file Idle-mode dispatcher for dedicated control channels. */
/*
* Copyright 2008, 2009 Free Software Foundation, Inc.
* Copyright 2011, 2014 Range Networks, Inc.
*
* This software is distributed under multiple licenses;
* see the COPYING file in the main directory for licensing
* information for this specific distribution.
*
* This use of this software may be subject to additional restrictions.
* See the LEGAL file in the main directory for details.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*/
#define LOG_GROUP LogGroup::Control
#include "ControlCommon.h"
//#include "L3CallControl.h"
#include "L3MobilityManagement.h"
#include "L3StateMachine.h"
#include "L3LogicalChannel.h"
#include <GSMConfig.h>
#include <Logger.h>
#undef WARNING
#include <Reporting.h>
#include <Globals.h>
using namespace std;
using namespace GSM;
using namespace Control;
/** Example of a closed-loop, persistent-thread control function for the DCCH. */
// (pat) DCCH is a TCHFACCHLogicalChannel or SDCCHLogicalChannel
void Control::DCCHDispatcher(L3LogicalChannel *DCCH)
{
while (! gBTS.btsShutdown()) {
// This 'try' is redundant, but we are ultra-cautious here since a mistake means a crash.
try {
// Wait for a transaction to start.
LOG(DEBUG);
LOG(DEBUG) << "waiting for " << *DCCH << " ESTABLISH or HANDOVER_ACCESS";
L3Frame *frame = DCCH->waitForEstablishOrHandover();
LOG(DEBUG) << *DCCH << " received " << *frame;
gResetWatchdog();
L3DCCHLoop(DCCH,frame); // This will not return until the channel is released.
}
catch (...) {
LOG(ERR) << "channel killed by unexpected exception ";
}
#if 0
// Catch the various error cases.
catch (RemovedTransaction except) {
LOG(ERR) << "attempt to use removed transaciton " << except.transactionID();
}
catch (ChannelReadTimeout except) {
LOG(NOTICE) << "ChannelReadTimeout";
// Cause 0x03 means "abnormal release, timer expired".
DCCH->l2sendm(L3ChannelRelease((RRCause)0x03));
gTransactionTable.remove(except.transactionID());
}
catch (UnexpectedPrimitive except) {
LOG(NOTICE) << "UnexpectedPrimitive";
// Cause 0x62 means "message type not not compatible with protocol state".
DCCH->l2sendm(L3ChannelRelease((RRCause)0x62));
if (except.transactionID()) gTransactionTable.remove(except.transactionID());
}
catch (UnexpectedMessage except) {
LOG(NOTICE) << "UnexpectedMessage";
// Cause 0x62 means "message type not not compatible with protocol state".
DCCH->l2sendm(L3ChannelRelease((RRCause)0x62));
if (except.transactionID()) gTransactionTable.remove(except.transactionID());
}
catch (UnsupportedMessage except) {
LOG(NOTICE) << "UnsupportedMessage";
// Cause 0x61 means "message type not implemented".
DCCH->l2sendm(L3ChannelRelease((RRCause)0x61));
if (except.transactionID()) gTransactionTable.remove(except.transactionID());
}
catch (Q931TimerExpired except) {
LOG(NOTICE) << "Q.931 T3xx timer expired";
// Cause 0x03 means "abnormal release, timer expired".
// TODO -- Send diagnostics.
DCCH->l2sendm(L3ChannelRelease((RRCause)0x03));
if (except.transactionID()) gTransactionTable.remove(except.transactionID());
}
catch (SIP::SIPTimeout except) {
// FIXME -- The transaction ID should be an argument here.
LOG(WARNING) << "Uncaught SIPTimeout, will leave a stray transcation";
// Cause 0x03 means "abnormal release, timer expired".
DCCH->l2sendm(L3ChannelRelease((RRCause)0x03));
if (except.transactionID()) gTransactionTable.remove(except.transactionID());
}
catch (SIP::SIPError except) {
// FIXME -- The transaction ID should be an argument here.
LOG(WARNING) << "Uncaught SIPError, will leave a stray transcation";
// Cause 0x01 means "abnormal release, unspecified".
DCCH->l2sendm(L3ChannelRelease((RRCause)0x01));
if (except.transactionID()) gTransactionTable.remove(except.transactionID());
}
#endif
}
}
// vim: ts=4 sw=4
|
agpl-3.0
|
adan91/gd-pdfview
|
thirdparty/freetype/src/smooth/ftgrays.c
|
32
|
60585
|
/***************************************************************************/
/* */
/* ftgrays.c */
/* */
/* A new `perfect' anti-aliasing renderer (body). */
/* */
/* Copyright 2000-2003, 2005-2012 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. */
/* */
/***************************************************************************/
/*************************************************************************/
/* */
/* This file can be compiled without the rest of the FreeType engine, by */
/* defining the _STANDALONE_ macro when compiling it. You also need to */
/* put the files `ftgrays.h' and `ftimage.h' into the current */
/* compilation directory. Typically, you could do something like */
/* */
/* - copy `src/smooth/ftgrays.c' (this file) to your current directory */
/* */
/* - copy `include/freetype/ftimage.h' and `src/smooth/ftgrays.h' to the */
/* same directory */
/* */
/* - compile `ftgrays' with the _STANDALONE_ macro defined, as in */
/* */
/* cc -c -D_STANDALONE_ ftgrays.c */
/* */
/* The renderer can be initialized with a call to */
/* `ft_gray_raster.raster_new'; an anti-aliased bitmap can be generated */
/* with a call to `ft_gray_raster.raster_render'. */
/* */
/* See the comments and documentation in the file `ftimage.h' for more */
/* details on how the raster works. */
/* */
/*************************************************************************/
/*************************************************************************/
/* */
/* This is a new anti-aliasing scan-converter for FreeType 2. The */
/* algorithm used here is _very_ different from the one in the standard */
/* `ftraster' module. Actually, `ftgrays' computes the _exact_ */
/* coverage of the outline on each pixel cell. */
/* */
/* It is based on ideas that I initially found in Raph Levien's */
/* excellent LibArt graphics library (see http://www.levien.com/libart */
/* for more information, though the web pages do not tell anything */
/* about the renderer; you'll have to dive into the source code to */
/* understand how it works). */
/* */
/* Note, however, that this is a _very_ different implementation */
/* compared to Raph's. Coverage information is stored in a very */
/* different way, and I don't use sorted vector paths. Also, it doesn't */
/* use floating point values. */
/* */
/* This renderer has the following advantages: */
/* */
/* - It doesn't need an intermediate bitmap. Instead, one can supply a */
/* callback function that will be called by the renderer to draw gray */
/* spans on any target surface. You can thus do direct composition on */
/* any kind of bitmap, provided that you give the renderer the right */
/* callback. */
/* */
/* - A perfect anti-aliaser, i.e., it computes the _exact_ coverage on */
/* each pixel cell. */
/* */
/* - It performs a single pass on the outline (the `standard' FT2 */
/* renderer makes two passes). */
/* */
/* - It can easily be modified to render to _any_ number of gray levels */
/* cheaply. */
/* */
/* - For small (< 20) pixel sizes, it is faster than the standard */
/* renderer. */
/* */
/*************************************************************************/
/*************************************************************************/
/* */
/* 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_smooth
#ifdef _STANDALONE_
/* define this to dump debugging information */
/* #define FT_DEBUG_LEVEL_TRACE */
#ifdef FT_DEBUG_LEVEL_TRACE
#include <stdio.h>
#include <stdarg.h>
#endif
#include <stddef.h>
#include <string.h>
#include <setjmp.h>
#include <limits.h>
#define FT_UINT_MAX UINT_MAX
#define FT_INT_MAX INT_MAX
#define ft_memset memset
#define ft_setjmp setjmp
#define ft_longjmp longjmp
#define ft_jmp_buf jmp_buf
typedef ptrdiff_t FT_PtrDist;
#define ErrRaster_Invalid_Mode -2
#define ErrRaster_Invalid_Outline -1
#define ErrRaster_Invalid_Argument -3
#define ErrRaster_Memory_Overflow -4
#define FT_BEGIN_HEADER
#define FT_END_HEADER
#include "ftimage.h"
#include "ftgrays.h"
/* This macro is used to indicate that a function parameter is unused. */
/* Its purpose is simply to reduce compiler warnings. Note also that */
/* simply defining it as `(void)x' doesn't avoid warnings with certain */
/* ANSI compilers (e.g. LCC). */
#define FT_UNUSED( x ) (x) = (x)
/* we only use level 5 & 7 tracing messages; cf. ftdebug.h */
#ifdef FT_DEBUG_LEVEL_TRACE
void
FT_Message( const char* fmt,
... )
{
va_list ap;
va_start( ap, fmt );
vfprintf( stderr, fmt, ap );
va_end( ap );
}
/* we don't handle tracing levels in stand-alone mode; */
#ifndef FT_TRACE5
#define FT_TRACE5( varformat ) FT_Message varformat
#endif
#ifndef FT_TRACE7
#define FT_TRACE7( varformat ) FT_Message varformat
#endif
#ifndef FT_ERROR
#define FT_ERROR( varformat ) FT_Message varformat
#endif
#else /* !FT_DEBUG_LEVEL_TRACE */
#define FT_TRACE5( x ) do { } while ( 0 ) /* nothing */
#define FT_TRACE7( x ) do { } while ( 0 ) /* nothing */
#define FT_ERROR( x ) do { } while ( 0 ) /* nothing */
#endif /* !FT_DEBUG_LEVEL_TRACE */
#define FT_DEFINE_OUTLINE_FUNCS( class_, \
move_to_, line_to_, \
conic_to_, cubic_to_, \
shift_, delta_ ) \
static const FT_Outline_Funcs class_ = \
{ \
move_to_, \
line_to_, \
conic_to_, \
cubic_to_, \
shift_, \
delta_ \
};
#define FT_DEFINE_RASTER_FUNCS( class_, glyph_format_, \
raster_new_, raster_reset_, \
raster_set_mode_, raster_render_, \
raster_done_ ) \
const FT_Raster_Funcs class_ = \
{ \
glyph_format_, \
raster_new_, \
raster_reset_, \
raster_set_mode_, \
raster_render_, \
raster_done_ \
};
#else /* !_STANDALONE_ */
#include <ft2build.h>
#include "ftgrays.h"
#include FT_INTERNAL_OBJECTS_H
#include FT_INTERNAL_DEBUG_H
#include FT_OUTLINE_H
#include "ftsmerrs.h"
#include "ftspic.h"
#define ErrRaster_Invalid_Mode Smooth_Err_Cannot_Render_Glyph
#define ErrRaster_Invalid_Outline Smooth_Err_Invalid_Outline
#define ErrRaster_Memory_Overflow Smooth_Err_Out_Of_Memory
#define ErrRaster_Invalid_Argument Smooth_Err_Invalid_Argument
#endif /* !_STANDALONE_ */
#ifndef FT_MEM_SET
#define FT_MEM_SET( d, s, c ) ft_memset( d, s, c )
#endif
#ifndef FT_MEM_ZERO
#define FT_MEM_ZERO( dest, count ) FT_MEM_SET( dest, 0, count )
#endif
/* as usual, for the speed hungry :-) */
#undef RAS_ARG
#undef RAS_ARG_
#undef RAS_VAR
#undef RAS_VAR_
#ifndef FT_STATIC_RASTER
#define RAS_ARG gray_PWorker worker
#define RAS_ARG_ gray_PWorker worker,
#define RAS_VAR worker
#define RAS_VAR_ worker,
#else /* FT_STATIC_RASTER */
#define RAS_ARG /* empty */
#define RAS_ARG_ /* empty */
#define RAS_VAR /* empty */
#define RAS_VAR_ /* empty */
#endif /* FT_STATIC_RASTER */
/* must be at least 6 bits! */
#define PIXEL_BITS 8
#undef FLOOR
#undef CEILING
#undef TRUNC
#undef SCALED
#define ONE_PIXEL ( 1L << PIXEL_BITS )
#define PIXEL_MASK ( -1L << PIXEL_BITS )
#define TRUNC( x ) ( (TCoord)( (x) >> PIXEL_BITS ) )
#define SUBPIXELS( x ) ( (TPos)(x) << PIXEL_BITS )
#define FLOOR( x ) ( (x) & -ONE_PIXEL )
#define CEILING( x ) ( ( (x) + ONE_PIXEL - 1 ) & -ONE_PIXEL )
#define ROUND( x ) ( ( (x) + ONE_PIXEL / 2 ) & -ONE_PIXEL )
#if PIXEL_BITS >= 6
#define UPSCALE( x ) ( (x) << ( PIXEL_BITS - 6 ) )
#define DOWNSCALE( x ) ( (x) >> ( PIXEL_BITS - 6 ) )
#else
#define UPSCALE( x ) ( (x) >> ( 6 - PIXEL_BITS ) )
#define DOWNSCALE( x ) ( (x) << ( 6 - PIXEL_BITS ) )
#endif
/*************************************************************************/
/* */
/* TYPE DEFINITIONS */
/* */
/* don't change the following types to FT_Int or FT_Pos, since we might */
/* need to define them to "float" or "double" when experimenting with */
/* new algorithms */
typedef long TCoord; /* integer scanline/pixel coordinate */
typedef long TPos; /* sub-pixel coordinate */
/* determine the type used to store cell areas. This normally takes at */
/* least PIXEL_BITS*2 + 1 bits. On 16-bit systems, we need to use */
/* `long' instead of `int', otherwise bad things happen */
#if PIXEL_BITS <= 7
typedef int TArea;
#else /* PIXEL_BITS >= 8 */
/* approximately determine the size of integers using an ANSI-C header */
#if FT_UINT_MAX == 0xFFFFU
typedef long TArea;
#else
typedef int TArea;
#endif
#endif /* PIXEL_BITS >= 8 */
/* maximum number of gray spans in a call to the span callback */
#define FT_MAX_GRAY_SPANS 32
typedef struct TCell_* PCell;
typedef struct TCell_
{
TPos x; /* same with gray_TWorker.ex */
TCoord cover; /* same with gray_TWorker.cover */
TArea area;
PCell next;
} TCell;
typedef struct gray_TWorker_
{
TCoord ex, ey;
TPos min_ex, max_ex;
TPos min_ey, max_ey;
TPos count_ex, count_ey;
TArea area;
TCoord cover;
int invalid;
PCell cells;
FT_PtrDist max_cells;
FT_PtrDist num_cells;
TCoord cx, cy;
TPos x, y;
TPos last_ey;
FT_Vector bez_stack[32 * 3 + 1];
int lev_stack[32];
FT_Outline outline;
FT_Bitmap target;
FT_BBox clip_box;
FT_Span gray_spans[FT_MAX_GRAY_SPANS];
int num_gray_spans;
FT_Raster_Span_Func render_span;
void* render_span_data;
int span_y;
int band_size;
int band_shoot;
ft_jmp_buf jump_buffer;
void* buffer;
long buffer_size;
PCell* ycells;
TPos ycount;
} gray_TWorker, *gray_PWorker;
#ifndef FT_STATIC_RASTER
#define ras (*worker)
#else
static gray_TWorker ras;
#endif
typedef struct gray_TRaster_
{
void* buffer;
long buffer_size;
int band_size;
void* memory;
gray_PWorker worker;
} gray_TRaster, *gray_PRaster;
/*************************************************************************/
/* */
/* Initialize the cells table. */
/* */
static void
gray_init_cells( RAS_ARG_ void* buffer,
long byte_size )
{
ras.buffer = buffer;
ras.buffer_size = byte_size;
ras.ycells = (PCell*) buffer;
ras.cells = NULL;
ras.max_cells = 0;
ras.num_cells = 0;
ras.area = 0;
ras.cover = 0;
ras.invalid = 1;
}
/*************************************************************************/
/* */
/* Compute the outline bounding box. */
/* */
static void
gray_compute_cbox( RAS_ARG )
{
FT_Outline* outline = &ras.outline;
FT_Vector* vec = outline->points;
FT_Vector* limit = vec + outline->n_points;
if ( outline->n_points <= 0 )
{
ras.min_ex = ras.max_ex = 0;
ras.min_ey = ras.max_ey = 0;
return;
}
ras.min_ex = ras.max_ex = vec->x;
ras.min_ey = ras.max_ey = vec->y;
vec++;
for ( ; vec < limit; vec++ )
{
TPos x = vec->x;
TPos y = vec->y;
if ( x < ras.min_ex ) ras.min_ex = x;
if ( x > ras.max_ex ) ras.max_ex = x;
if ( y < ras.min_ey ) ras.min_ey = y;
if ( y > ras.max_ey ) ras.max_ey = y;
}
/* truncate the bounding box to integer pixels */
ras.min_ex = ras.min_ex >> 6;
ras.min_ey = ras.min_ey >> 6;
ras.max_ex = ( ras.max_ex + 63 ) >> 6;
ras.max_ey = ( ras.max_ey + 63 ) >> 6;
}
/*************************************************************************/
/* */
/* Record the current cell in the table. */
/* */
static PCell
gray_find_cell( RAS_ARG )
{
PCell *pcell, cell;
TPos x = ras.ex;
if ( x > ras.count_ex )
x = ras.count_ex;
pcell = &ras.ycells[ras.ey];
for (;;)
{
cell = *pcell;
if ( cell == NULL || cell->x > x )
break;
if ( cell->x == x )
goto Exit;
pcell = &cell->next;
}
if ( ras.num_cells >= ras.max_cells )
ft_longjmp( ras.jump_buffer, 1 );
cell = ras.cells + ras.num_cells++;
cell->x = x;
cell->area = 0;
cell->cover = 0;
cell->next = *pcell;
*pcell = cell;
Exit:
return cell;
}
static void
gray_record_cell( RAS_ARG )
{
if ( !ras.invalid && ( ras.area | ras.cover ) )
{
PCell cell = gray_find_cell( RAS_VAR );
cell->area += ras.area;
cell->cover += ras.cover;
}
}
/*************************************************************************/
/* */
/* Set the current cell to a new position. */
/* */
static void
gray_set_cell( RAS_ARG_ TCoord ex,
TCoord ey )
{
/* Move the cell pointer to a new position. We set the `invalid' */
/* flag to indicate that the cell isn't part of those we're interested */
/* in during the render phase. This means that: */
/* */
/* . the new vertical position must be within min_ey..max_ey-1. */
/* . the new horizontal position must be strictly less than max_ex */
/* */
/* Note that if a cell is to the left of the clipping region, it is */
/* actually set to the (min_ex-1) horizontal position. */
/* All cells that are on the left of the clipping region go to the */
/* min_ex - 1 horizontal position. */
ey -= ras.min_ey;
if ( ex > ras.max_ex )
ex = ras.max_ex;
ex -= ras.min_ex;
if ( ex < 0 )
ex = -1;
/* are we moving to a different cell ? */
if ( ex != ras.ex || ey != ras.ey )
{
/* record the current one if it is valid */
if ( !ras.invalid )
gray_record_cell( RAS_VAR );
ras.area = 0;
ras.cover = 0;
}
ras.ex = ex;
ras.ey = ey;
ras.invalid = ( (unsigned)ey >= (unsigned)ras.count_ey ||
ex >= ras.count_ex );
}
/*************************************************************************/
/* */
/* Start a new contour at a given cell. */
/* */
static void
gray_start_cell( RAS_ARG_ TCoord ex,
TCoord ey )
{
if ( ex > ras.max_ex )
ex = (TCoord)( ras.max_ex );
if ( ex < ras.min_ex )
ex = (TCoord)( ras.min_ex - 1 );
ras.area = 0;
ras.cover = 0;
ras.ex = ex - ras.min_ex;
ras.ey = ey - ras.min_ey;
ras.last_ey = SUBPIXELS( ey );
ras.invalid = 0;
gray_set_cell( RAS_VAR_ ex, ey );
}
/*************************************************************************/
/* */
/* Render a scanline as one or more cells. */
/* */
static void
gray_render_scanline( RAS_ARG_ TCoord ey,
TPos x1,
TCoord y1,
TPos x2,
TCoord y2 )
{
TCoord ex1, ex2, fx1, fx2, delta, mod, lift, rem;
long p, first, dx;
int incr;
dx = x2 - x1;
ex1 = TRUNC( x1 );
ex2 = TRUNC( x2 );
fx1 = (TCoord)( x1 - SUBPIXELS( ex1 ) );
fx2 = (TCoord)( x2 - SUBPIXELS( ex2 ) );
/* trivial case. Happens often */
if ( y1 == y2 )
{
gray_set_cell( RAS_VAR_ ex2, ey );
return;
}
/* everything is located in a single cell. That is easy! */
/* */
if ( ex1 == ex2 )
{
delta = y2 - y1;
ras.area += (TArea)(( fx1 + fx2 ) * delta);
ras.cover += delta;
return;
}
/* ok, we'll have to render a run of adjacent cells on the same */
/* scanline... */
/* */
p = ( ONE_PIXEL - fx1 ) * ( y2 - y1 );
first = ONE_PIXEL;
incr = 1;
if ( dx < 0 )
{
p = fx1 * ( y2 - y1 );
first = 0;
incr = -1;
dx = -dx;
}
delta = (TCoord)( p / dx );
mod = (TCoord)( p % dx );
if ( mod < 0 )
{
delta--;
mod += (TCoord)dx;
}
ras.area += (TArea)(( fx1 + first ) * delta);
ras.cover += delta;
ex1 += incr;
gray_set_cell( RAS_VAR_ ex1, ey );
y1 += delta;
if ( ex1 != ex2 )
{
p = ONE_PIXEL * ( y2 - y1 + delta );
lift = (TCoord)( p / dx );
rem = (TCoord)( p % dx );
if ( rem < 0 )
{
lift--;
rem += (TCoord)dx;
}
mod -= (int)dx;
while ( ex1 != ex2 )
{
delta = lift;
mod += rem;
if ( mod >= 0 )
{
mod -= (TCoord)dx;
delta++;
}
ras.area += (TArea)(ONE_PIXEL * delta);
ras.cover += delta;
y1 += delta;
ex1 += incr;
gray_set_cell( RAS_VAR_ ex1, ey );
}
}
delta = y2 - y1;
ras.area += (TArea)(( fx2 + ONE_PIXEL - first ) * delta);
ras.cover += delta;
}
/*************************************************************************/
/* */
/* Render a given line as a series of scanlines. */
/* */
static void
gray_render_line( RAS_ARG_ TPos to_x,
TPos to_y )
{
TCoord ey1, ey2, fy1, fy2, mod;
TPos dx, dy, x, x2;
long p, first;
int delta, rem, lift, incr;
ey1 = TRUNC( ras.last_ey );
ey2 = TRUNC( to_y ); /* if (ey2 >= ras.max_ey) ey2 = ras.max_ey-1; */
fy1 = (TCoord)( ras.y - ras.last_ey );
fy2 = (TCoord)( to_y - SUBPIXELS( ey2 ) );
dx = to_x - ras.x;
dy = to_y - ras.y;
/* XXX: we should do something about the trivial case where dx == 0, */
/* as it happens very often! */
/* perform vertical clipping */
{
TCoord min, max;
min = ey1;
max = ey2;
if ( ey1 > ey2 )
{
min = ey2;
max = ey1;
}
if ( min >= ras.max_ey || max < ras.min_ey )
goto End;
}
/* everything is on a single scanline */
if ( ey1 == ey2 )
{
gray_render_scanline( RAS_VAR_ ey1, ras.x, fy1, to_x, fy2 );
goto End;
}
/* vertical line - avoid calling gray_render_scanline */
incr = 1;
if ( dx == 0 )
{
TCoord ex = TRUNC( ras.x );
TCoord two_fx = (TCoord)( ( ras.x - SUBPIXELS( ex ) ) << 1 );
TArea area;
first = ONE_PIXEL;
if ( dy < 0 )
{
first = 0;
incr = -1;
}
delta = (int)( first - fy1 );
ras.area += (TArea)two_fx * delta;
ras.cover += delta;
ey1 += incr;
gray_set_cell( RAS_VAR_ ex, ey1 );
delta = (int)( first + first - ONE_PIXEL );
area = (TArea)two_fx * delta;
while ( ey1 != ey2 )
{
ras.area += area;
ras.cover += delta;
ey1 += incr;
gray_set_cell( RAS_VAR_ ex, ey1 );
}
delta = (int)( fy2 - ONE_PIXEL + first );
ras.area += (TArea)two_fx * delta;
ras.cover += delta;
goto End;
}
/* ok, we have to render several scanlines */
p = ( ONE_PIXEL - fy1 ) * dx;
first = ONE_PIXEL;
incr = 1;
if ( dy < 0 )
{
p = fy1 * dx;
first = 0;
incr = -1;
dy = -dy;
}
delta = (int)( p / dy );
mod = (int)( p % dy );
if ( mod < 0 )
{
delta--;
mod += (TCoord)dy;
}
x = ras.x + delta;
gray_render_scanline( RAS_VAR_ ey1, ras.x, fy1, x, (TCoord)first );
ey1 += incr;
gray_set_cell( RAS_VAR_ TRUNC( x ), ey1 );
if ( ey1 != ey2 )
{
p = ONE_PIXEL * dx;
lift = (int)( p / dy );
rem = (int)( p % dy );
if ( rem < 0 )
{
lift--;
rem += (int)dy;
}
mod -= (int)dy;
while ( ey1 != ey2 )
{
delta = lift;
mod += rem;
if ( mod >= 0 )
{
mod -= (int)dy;
delta++;
}
x2 = x + delta;
gray_render_scanline( RAS_VAR_ ey1, x,
(TCoord)( ONE_PIXEL - first ), x2,
(TCoord)first );
x = x2;
ey1 += incr;
gray_set_cell( RAS_VAR_ TRUNC( x ), ey1 );
}
}
gray_render_scanline( RAS_VAR_ ey1, x,
(TCoord)( ONE_PIXEL - first ), to_x,
fy2 );
End:
ras.x = to_x;
ras.y = to_y;
ras.last_ey = SUBPIXELS( ey2 );
}
static void
gray_split_conic( FT_Vector* base )
{
TPos a, b;
base[4].x = base[2].x;
b = base[1].x;
a = base[3].x = ( base[2].x + b ) / 2;
b = base[1].x = ( base[0].x + b ) / 2;
base[2].x = ( a + b ) / 2;
base[4].y = base[2].y;
b = base[1].y;
a = base[3].y = ( base[2].y + b ) / 2;
b = base[1].y = ( base[0].y + b ) / 2;
base[2].y = ( a + b ) / 2;
}
static void
gray_render_conic( RAS_ARG_ const FT_Vector* control,
const FT_Vector* to )
{
TPos dx, dy;
TPos min, max, y;
int top, level;
int* levels;
FT_Vector* arc;
levels = ras.lev_stack;
arc = ras.bez_stack;
arc[0].x = UPSCALE( to->x );
arc[0].y = UPSCALE( to->y );
arc[1].x = UPSCALE( control->x );
arc[1].y = UPSCALE( control->y );
arc[2].x = ras.x;
arc[2].y = ras.y;
top = 0;
dx = FT_ABS( arc[2].x + arc[0].x - 2 * arc[1].x );
dy = FT_ABS( arc[2].y + arc[0].y - 2 * arc[1].y );
if ( dx < dy )
dx = dy;
if ( dx < ONE_PIXEL / 4 )
goto Draw;
/* short-cut the arc that crosses the current band */
min = max = arc[0].y;
y = arc[1].y;
if ( y < min ) min = y;
if ( y > max ) max = y;
y = arc[2].y;
if ( y < min ) min = y;
if ( y > max ) max = y;
if ( TRUNC( min ) >= ras.max_ey || TRUNC( max ) < ras.min_ey )
goto Draw;
level = 0;
do
{
dx >>= 2;
level++;
} while ( dx > ONE_PIXEL / 4 );
levels[0] = level;
do
{
level = levels[top];
if ( level > 0 )
{
gray_split_conic( arc );
arc += 2;
top++;
levels[top] = levels[top - 1] = level - 1;
continue;
}
Draw:
gray_render_line( RAS_VAR_ arc[0].x, arc[0].y );
top--;
arc -= 2;
} while ( top >= 0 );
}
static void
gray_split_cubic( FT_Vector* base )
{
TPos a, b, c, d;
base[6].x = base[3].x;
c = base[1].x;
d = base[2].x;
base[1].x = a = ( base[0].x + c ) / 2;
base[5].x = b = ( base[3].x + d ) / 2;
c = ( c + d ) / 2;
base[2].x = a = ( a + c ) / 2;
base[4].x = b = ( b + c ) / 2;
base[3].x = ( a + b ) / 2;
base[6].y = base[3].y;
c = base[1].y;
d = base[2].y;
base[1].y = a = ( base[0].y + c ) / 2;
base[5].y = b = ( base[3].y + d ) / 2;
c = ( c + d ) / 2;
base[2].y = a = ( a + c ) / 2;
base[4].y = b = ( b + c ) / 2;
base[3].y = ( a + b ) / 2;
}
static void
gray_render_cubic( RAS_ARG_ const FT_Vector* control1,
const FT_Vector* control2,
const FT_Vector* to )
{
FT_Vector* arc;
TPos min, max, y;
arc = ras.bez_stack;
arc[0].x = UPSCALE( to->x );
arc[0].y = UPSCALE( to->y );
arc[1].x = UPSCALE( control2->x );
arc[1].y = UPSCALE( control2->y );
arc[2].x = UPSCALE( control1->x );
arc[2].y = UPSCALE( control1->y );
arc[3].x = ras.x;
arc[3].y = ras.y;
/* Short-cut the arc that crosses the current band. */
min = max = arc[0].y;
y = arc[1].y;
if ( y < min )
min = y;
if ( y > max )
max = y;
y = arc[2].y;
if ( y < min )
min = y;
if ( y > max )
max = y;
y = arc[3].y;
if ( y < min )
min = y;
if ( y > max )
max = y;
if ( TRUNC( min ) >= ras.max_ey || TRUNC( max ) < ras.min_ey )
goto Draw;
for (;;)
{
/* Decide whether to split or draw. See `Rapid Termination */
/* Evaluation for Recursive Subdivision of Bezier Curves' by Thomas */
/* F. Hain, at */
/* http://www.cis.southalabama.edu/~hain/general/Publications/Bezier/Camera-ready%20CISST02%202.pdf */
{
TPos dx, dy, dx_, dy_;
TPos dx1, dy1, dx2, dy2;
TPos L, s, s_limit;
/* dx and dy are x and y components of the P0-P3 chord vector. */
dx = arc[3].x - arc[0].x;
dy = arc[3].y - arc[0].y;
/* L is an (under)estimate of the Euclidean distance P0-P3. */
/* */
/* If dx >= dy, then r = sqrt(dx^2 + dy^2) can be overestimated */
/* with least maximum error by */
/* */
/* r_upperbound = dx + (sqrt(2) - 1) * dy , */
/* */
/* where sqrt(2) - 1 can be (over)estimated by 107/256, giving an */
/* error of no more than 8.4%. */
/* */
/* Similarly, some elementary calculus shows that r can be */
/* underestimated with least maximum error by */
/* */
/* r_lowerbound = sqrt(2 + sqrt(2)) / 2 * dx */
/* + sqrt(2 - sqrt(2)) / 2 * dy . */
/* */
/* 236/256 and 97/256 are (under)estimates of the two algebraic */
/* numbers, giving an error of no more than 8.1%. */
dx_ = FT_ABS( dx );
dy_ = FT_ABS( dy );
/* This is the same as */
/* */
/* L = ( 236 * FT_MAX( dx_, dy_ ) */
/* + 97 * FT_MIN( dx_, dy_ ) ) >> 8; */
L = ( dx_ > dy_ ? 236 * dx_ + 97 * dy_
: 97 * dx_ + 236 * dy_ ) >> 8;
/* Avoid possible arithmetic overflow below by splitting. */
if ( L > 32767 )
goto Split;
/* Max deviation may be as much as (s/L) * 3/4 (if Hain's v = 1). */
s_limit = L * (TPos)( ONE_PIXEL / 6 );
/* s is L * the perpendicular distance from P1 to the line P0-P3. */
dx1 = arc[1].x - arc[0].x;
dy1 = arc[1].y - arc[0].y;
s = FT_ABS( dy * dx1 - dx * dy1 );
if ( s > s_limit )
goto Split;
/* s is L * the perpendicular distance from P2 to the line P0-P3. */
dx2 = arc[2].x - arc[0].x;
dy2 = arc[2].y - arc[0].y;
s = FT_ABS( dy * dx2 - dx * dy2 );
if ( s > s_limit )
goto Split;
/* Split super curvy segments where the off points are so far
from the chord that the angles P0-P1-P3 or P0-P2-P3 become
acute as detected by appropriate dot products. */
if ( dx1 * ( dx1 - dx ) + dy1 * ( dy1 - dy ) > 0 ||
dx2 * ( dx2 - dx ) + dy2 * ( dy2 - dy ) > 0 )
goto Split;
/* No reason to split. */
goto Draw;
}
Split:
gray_split_cubic( arc );
arc += 3;
continue;
Draw:
gray_render_line( RAS_VAR_ arc[0].x, arc[0].y );
if ( arc == ras.bez_stack )
return;
arc -= 3;
}
}
static int
gray_move_to( const FT_Vector* to,
gray_PWorker worker )
{
TPos x, y;
/* record current cell, if any */
gray_record_cell( RAS_VAR );
/* start to a new position */
x = UPSCALE( to->x );
y = UPSCALE( to->y );
gray_start_cell( RAS_VAR_ TRUNC( x ), TRUNC( y ) );
worker->x = x;
worker->y = y;
return 0;
}
static int
gray_line_to( const FT_Vector* to,
gray_PWorker worker )
{
gray_render_line( RAS_VAR_ UPSCALE( to->x ), UPSCALE( to->y ) );
return 0;
}
static int
gray_conic_to( const FT_Vector* control,
const FT_Vector* to,
gray_PWorker worker )
{
gray_render_conic( RAS_VAR_ control, to );
return 0;
}
static int
gray_cubic_to( const FT_Vector* control1,
const FT_Vector* control2,
const FT_Vector* to,
gray_PWorker worker )
{
gray_render_cubic( RAS_VAR_ control1, control2, to );
return 0;
}
static void
gray_render_span( int y,
int count,
const FT_Span* spans,
gray_PWorker worker )
{
unsigned char* p;
FT_Bitmap* map = &worker->target;
/* first of all, compute the scanline offset */
p = (unsigned char*)map->buffer - y * map->pitch;
if ( map->pitch >= 0 )
p += (unsigned)( ( map->rows - 1 ) * map->pitch );
for ( ; count > 0; count--, spans++ )
{
unsigned char coverage = spans->coverage;
if ( coverage )
{
/* For small-spans it is faster to do it by ourselves than
* calling `memset'. This is mainly due to the cost of the
* function call.
*/
if ( spans->len >= 8 )
FT_MEM_SET( p + spans->x, (unsigned char)coverage, spans->len );
else
{
unsigned char* q = p + spans->x;
switch ( spans->len )
{
case 7: *q++ = (unsigned char)coverage;
case 6: *q++ = (unsigned char)coverage;
case 5: *q++ = (unsigned char)coverage;
case 4: *q++ = (unsigned char)coverage;
case 3: *q++ = (unsigned char)coverage;
case 2: *q++ = (unsigned char)coverage;
case 1: *q = (unsigned char)coverage;
default:
;
}
}
}
}
}
static void
gray_hline( RAS_ARG_ TCoord x,
TCoord y,
TPos area,
TCoord acount )
{
FT_Span* span;
int count;
int coverage;
/* compute the coverage line's coverage, depending on the */
/* outline fill rule */
/* */
/* the coverage percentage is area/(PIXEL_BITS*PIXEL_BITS*2) */
/* */
coverage = (int)( area >> ( PIXEL_BITS * 2 + 1 - 8 ) );
/* use range 0..256 */
if ( coverage < 0 )
coverage = -coverage;
if ( ras.outline.flags & FT_OUTLINE_EVEN_ODD_FILL )
{
coverage &= 511;
if ( coverage > 256 )
coverage = 512 - coverage;
else if ( coverage == 256 )
coverage = 255;
}
else
{
/* normal non-zero winding rule */
if ( coverage >= 256 )
coverage = 255;
}
y += (TCoord)ras.min_ey;
x += (TCoord)ras.min_ex;
/* FT_Span.x is a 16-bit short, so limit our coordinates appropriately */
if ( x >= 32767 )
x = 32767;
/* FT_Span.y is an integer, so limit our coordinates appropriately */
if ( y >= FT_INT_MAX )
y = FT_INT_MAX;
if ( coverage )
{
/* see whether we can add this span to the current list */
count = ras.num_gray_spans;
span = ras.gray_spans + count - 1;
if ( count > 0 &&
ras.span_y == y &&
(int)span->x + span->len == (int)x &&
span->coverage == coverage )
{
span->len = (unsigned short)( span->len + acount );
return;
}
if ( ras.span_y != y || count >= FT_MAX_GRAY_SPANS )
{
if ( ras.render_span && count > 0 )
ras.render_span( ras.span_y, count, ras.gray_spans,
ras.render_span_data );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( count > 0 )
{
int n;
FT_TRACE7(( "y = %3d ", ras.span_y ));
span = ras.gray_spans;
for ( n = 0; n < count; n++, span++ )
FT_TRACE7(( "[%d..%d]:%02x ",
span->x, span->x + span->len - 1, span->coverage ));
FT_TRACE7(( "\n" ));
}
#endif /* FT_DEBUG_LEVEL_TRACE */
ras.num_gray_spans = 0;
ras.span_y = (int)y;
count = 0;
span = ras.gray_spans;
}
else
span++;
/* add a gray span to the current list */
span->x = (short)x;
span->len = (unsigned short)acount;
span->coverage = (unsigned char)coverage;
ras.num_gray_spans++;
}
}
#ifdef FT_DEBUG_LEVEL_TRACE
/* to be called while in the debugger -- */
/* this function causes a compiler warning since it is unused otherwise */
static void
gray_dump_cells( RAS_ARG )
{
int yindex;
for ( yindex = 0; yindex < ras.ycount; yindex++ )
{
PCell cell;
printf( "%3d:", yindex );
for ( cell = ras.ycells[yindex]; cell != NULL; cell = cell->next )
printf( " (%3ld, c:%4ld, a:%6d)", cell->x, cell->cover, cell->area );
printf( "\n" );
}
}
#endif /* FT_DEBUG_LEVEL_TRACE */
static void
gray_sweep( RAS_ARG_ const FT_Bitmap* target )
{
int yindex;
FT_UNUSED( target );
if ( ras.num_cells == 0 )
return;
ras.num_gray_spans = 0;
FT_TRACE7(( "gray_sweep: start\n" ));
for ( yindex = 0; yindex < ras.ycount; yindex++ )
{
PCell cell = ras.ycells[yindex];
TCoord cover = 0;
TCoord x = 0;
for ( ; cell != NULL; cell = cell->next )
{
TPos area;
if ( cell->x > x && cover != 0 )
gray_hline( RAS_VAR_ x, yindex, cover * ( ONE_PIXEL * 2 ),
cell->x - x );
cover += cell->cover;
area = cover * ( ONE_PIXEL * 2 ) - cell->area;
if ( area != 0 && cell->x >= 0 )
gray_hline( RAS_VAR_ cell->x, yindex, area, 1 );
x = cell->x + 1;
}
if ( cover != 0 )
gray_hline( RAS_VAR_ x, yindex, cover * ( ONE_PIXEL * 2 ),
ras.count_ex - x );
}
if ( ras.render_span && ras.num_gray_spans > 0 )
ras.render_span( ras.span_y, ras.num_gray_spans,
ras.gray_spans, ras.render_span_data );
#ifdef FT_DEBUG_LEVEL_TRACE
if ( ras.num_gray_spans > 0 )
{
FT_Span* span;
int n;
FT_TRACE7(( "y = %3d ", ras.span_y ));
span = ras.gray_spans;
for ( n = 0; n < ras.num_gray_spans; n++, span++ )
FT_TRACE7(( "[%d..%d]:%02x ",
span->x, span->x + span->len - 1, span->coverage ));
FT_TRACE7(( "\n" ));
}
FT_TRACE7(( "gray_sweep: end\n" ));
#endif /* FT_DEBUG_LEVEL_TRACE */
}
#ifdef _STANDALONE_
/*************************************************************************/
/* */
/* The following function should only compile in stand-alone mode, */
/* i.e., when building this component without the rest of FreeType. */
/* */
/*************************************************************************/
/*************************************************************************/
/* */
/* <Function> */
/* FT_Outline_Decompose */
/* */
/* <Description> */
/* Walk over an outline's structure to decompose it into individual */
/* segments and Bézier arcs. This function is also able to emit */
/* `move to' and `close to' operations to indicate the start and end */
/* of new contours in the outline. */
/* */
/* <Input> */
/* outline :: A pointer to the source target. */
/* */
/* func_interface :: A table of `emitters', i.e., function pointers */
/* called during decomposition to indicate path */
/* operations. */
/* */
/* <InOut> */
/* user :: A typeless pointer which is passed to each */
/* emitter during the decomposition. It can be */
/* used to store the state during the */
/* decomposition. */
/* */
/* <Return> */
/* Error code. 0 means success. */
/* */
static int
FT_Outline_Decompose( const FT_Outline* outline,
const FT_Outline_Funcs* func_interface,
void* user )
{
#undef SCALED
#define SCALED( x ) ( ( (x) << shift ) - delta )
FT_Vector v_last;
FT_Vector v_control;
FT_Vector v_start;
FT_Vector* point;
FT_Vector* limit;
char* tags;
int error;
int n; /* index of contour in outline */
int first; /* index of first point in contour */
char tag; /* current point's state */
int shift;
TPos delta;
if ( !outline || !func_interface )
return ErrRaster_Invalid_Argument;
shift = func_interface->shift;
delta = func_interface->delta;
first = 0;
for ( n = 0; n < outline->n_contours; n++ )
{
int last; /* index of last point in contour */
FT_TRACE5(( "FT_Outline_Decompose: Outline %d\n", n ));
last = outline->contours[n];
if ( last < 0 )
goto Invalid_Outline;
limit = outline->points + last;
v_start = outline->points[first];
v_start.x = SCALED( v_start.x );
v_start.y = SCALED( v_start.y );
v_last = outline->points[last];
v_last.x = SCALED( v_last.x );
v_last.y = SCALED( v_last.y );
v_control = v_start;
point = outline->points + first;
tags = outline->tags + first;
tag = FT_CURVE_TAG( tags[0] );
/* A contour cannot start with a cubic control point! */
if ( tag == FT_CURVE_TAG_CUBIC )
goto Invalid_Outline;
/* check first point to determine origin */
if ( tag == FT_CURVE_TAG_CONIC )
{
/* first point is conic control. Yes, this happens. */
if ( FT_CURVE_TAG( outline->tags[last] ) == FT_CURVE_TAG_ON )
{
/* start at last point if it is on the curve */
v_start = v_last;
limit--;
}
else
{
/* if both first and last points are conic, */
/* start at their middle and record its position */
/* for closure */
v_start.x = ( v_start.x + v_last.x ) / 2;
v_start.y = ( v_start.y + v_last.y ) / 2;
v_last = v_start;
}
point--;
tags--;
}
FT_TRACE5(( " move to (%.2f, %.2f)\n",
v_start.x / 64.0, v_start.y / 64.0 ));
error = func_interface->move_to( &v_start, user );
if ( error )
goto Exit;
while ( point < limit )
{
point++;
tags++;
tag = FT_CURVE_TAG( tags[0] );
switch ( tag )
{
case FT_CURVE_TAG_ON: /* emit a single line_to */
{
FT_Vector vec;
vec.x = SCALED( point->x );
vec.y = SCALED( point->y );
FT_TRACE5(( " line to (%.2f, %.2f)\n",
vec.x / 64.0, vec.y / 64.0 ));
error = func_interface->line_to( &vec, user );
if ( error )
goto Exit;
continue;
}
case FT_CURVE_TAG_CONIC: /* consume conic arcs */
v_control.x = SCALED( point->x );
v_control.y = SCALED( point->y );
Do_Conic:
if ( point < limit )
{
FT_Vector vec;
FT_Vector v_middle;
point++;
tags++;
tag = FT_CURVE_TAG( tags[0] );
vec.x = SCALED( point->x );
vec.y = SCALED( point->y );
if ( tag == FT_CURVE_TAG_ON )
{
FT_TRACE5(( " conic to (%.2f, %.2f)"
" with control (%.2f, %.2f)\n",
vec.x / 64.0, vec.y / 64.0,
v_control.x / 64.0, v_control.y / 64.0 ));
error = func_interface->conic_to( &v_control, &vec, user );
if ( error )
goto Exit;
continue;
}
if ( tag != FT_CURVE_TAG_CONIC )
goto Invalid_Outline;
v_middle.x = ( v_control.x + vec.x ) / 2;
v_middle.y = ( v_control.y + vec.y ) / 2;
FT_TRACE5(( " conic to (%.2f, %.2f)"
" with control (%.2f, %.2f)\n",
v_middle.x / 64.0, v_middle.y / 64.0,
v_control.x / 64.0, v_control.y / 64.0 ));
error = func_interface->conic_to( &v_control, &v_middle, user );
if ( error )
goto Exit;
v_control = vec;
goto Do_Conic;
}
FT_TRACE5(( " conic to (%.2f, %.2f)"
" with control (%.2f, %.2f)\n",
v_start.x / 64.0, v_start.y / 64.0,
v_control.x / 64.0, v_control.y / 64.0 ));
error = func_interface->conic_to( &v_control, &v_start, user );
goto Close;
default: /* FT_CURVE_TAG_CUBIC */
{
FT_Vector vec1, vec2;
if ( point + 1 > limit ||
FT_CURVE_TAG( tags[1] ) != FT_CURVE_TAG_CUBIC )
goto Invalid_Outline;
point += 2;
tags += 2;
vec1.x = SCALED( point[-2].x );
vec1.y = SCALED( point[-2].y );
vec2.x = SCALED( point[-1].x );
vec2.y = SCALED( point[-1].y );
if ( point <= limit )
{
FT_Vector vec;
vec.x = SCALED( point->x );
vec.y = SCALED( point->y );
FT_TRACE5(( " cubic to (%.2f, %.2f)"
" with controls (%.2f, %.2f) and (%.2f, %.2f)\n",
vec.x / 64.0, vec.y / 64.0,
vec1.x / 64.0, vec1.y / 64.0,
vec2.x / 64.0, vec2.y / 64.0 ));
error = func_interface->cubic_to( &vec1, &vec2, &vec, user );
if ( error )
goto Exit;
continue;
}
FT_TRACE5(( " cubic to (%.2f, %.2f)"
" with controls (%.2f, %.2f) and (%.2f, %.2f)\n",
v_start.x / 64.0, v_start.y / 64.0,
vec1.x / 64.0, vec1.y / 64.0,
vec2.x / 64.0, vec2.y / 64.0 ));
error = func_interface->cubic_to( &vec1, &vec2, &v_start, user );
goto Close;
}
}
}
/* close the contour with a line segment */
FT_TRACE5(( " line to (%.2f, %.2f)\n",
v_start.x / 64.0, v_start.y / 64.0 ));
error = func_interface->line_to( &v_start, user );
Close:
if ( error )
goto Exit;
first = last + 1;
}
FT_TRACE5(( "FT_Outline_Decompose: Done\n", n ));
return 0;
Exit:
FT_TRACE5(( "FT_Outline_Decompose: Error %d\n", error ));
return error;
Invalid_Outline:
return ErrRaster_Invalid_Outline;
}
#endif /* _STANDALONE_ */
typedef struct gray_TBand_
{
TPos min, max;
} gray_TBand;
FT_DEFINE_OUTLINE_FUNCS(func_interface,
(FT_Outline_MoveTo_Func) gray_move_to,
(FT_Outline_LineTo_Func) gray_line_to,
(FT_Outline_ConicTo_Func)gray_conic_to,
(FT_Outline_CubicTo_Func)gray_cubic_to,
0,
0
)
static int
gray_convert_glyph_inner( RAS_ARG )
{
volatile int error = 0;
#ifdef FT_CONFIG_OPTION_PIC
FT_Outline_Funcs func_interface;
Init_Class_func_interface(&func_interface);
#endif
if ( ft_setjmp( ras.jump_buffer ) == 0 )
{
error = FT_Outline_Decompose( &ras.outline, &func_interface, &ras );
gray_record_cell( RAS_VAR );
}
else
error = ErrRaster_Memory_Overflow;
return error;
}
static int
gray_convert_glyph( RAS_ARG )
{
gray_TBand bands[40];
gray_TBand* volatile band;
int volatile n, num_bands;
TPos volatile min, max, max_y;
FT_BBox* clip;
/* Set up state in the raster object */
gray_compute_cbox( RAS_VAR );
/* clip to target bitmap, exit if nothing to do */
clip = &ras.clip_box;
if ( ras.max_ex <= clip->xMin || ras.min_ex >= clip->xMax ||
ras.max_ey <= clip->yMin || ras.min_ey >= clip->yMax )
return 0;
if ( ras.min_ex < clip->xMin ) ras.min_ex = clip->xMin;
if ( ras.min_ey < clip->yMin ) ras.min_ey = clip->yMin;
if ( ras.max_ex > clip->xMax ) ras.max_ex = clip->xMax;
if ( ras.max_ey > clip->yMax ) ras.max_ey = clip->yMax;
ras.count_ex = ras.max_ex - ras.min_ex;
ras.count_ey = ras.max_ey - ras.min_ey;
/* set up vertical bands */
num_bands = (int)( ( ras.max_ey - ras.min_ey ) / ras.band_size );
if ( num_bands == 0 )
num_bands = 1;
if ( num_bands >= 39 )
num_bands = 39;
ras.band_shoot = 0;
min = ras.min_ey;
max_y = ras.max_ey;
for ( n = 0; n < num_bands; n++, min = max )
{
max = min + ras.band_size;
if ( n == num_bands - 1 || max > max_y )
max = max_y;
bands[0].min = min;
bands[0].max = max;
band = bands;
while ( band >= bands )
{
TPos bottom, top, middle;
int error;
{
PCell cells_max;
int yindex;
long cell_start, cell_end, cell_mod;
ras.ycells = (PCell*)ras.buffer;
ras.ycount = band->max - band->min;
cell_start = sizeof ( PCell ) * ras.ycount;
cell_mod = cell_start % sizeof ( TCell );
if ( cell_mod > 0 )
cell_start += sizeof ( TCell ) - cell_mod;
cell_end = ras.buffer_size;
cell_end -= cell_end % sizeof ( TCell );
cells_max = (PCell)( (char*)ras.buffer + cell_end );
ras.cells = (PCell)( (char*)ras.buffer + cell_start );
if ( ras.cells >= cells_max )
goto ReduceBands;
ras.max_cells = cells_max - ras.cells;
if ( ras.max_cells < 2 )
goto ReduceBands;
for ( yindex = 0; yindex < ras.ycount; yindex++ )
ras.ycells[yindex] = NULL;
}
ras.num_cells = 0;
ras.invalid = 1;
ras.min_ey = band->min;
ras.max_ey = band->max;
ras.count_ey = band->max - band->min;
error = gray_convert_glyph_inner( RAS_VAR );
if ( !error )
{
gray_sweep( RAS_VAR_ &ras.target );
band--;
continue;
}
else if ( error != ErrRaster_Memory_Overflow )
return 1;
ReduceBands:
/* render pool overflow; we will reduce the render band by half */
bottom = band->min;
top = band->max;
middle = bottom + ( ( top - bottom ) >> 1 );
/* This is too complex for a single scanline; there must */
/* be some problems. */
if ( middle == bottom )
{
#ifdef FT_DEBUG_LEVEL_TRACE
FT_TRACE7(( "gray_convert_glyph: rotten glyph\n" ));
#endif
return 1;
}
if ( bottom-top >= ras.band_size )
ras.band_shoot++;
band[1].min = bottom;
band[1].max = middle;
band[0].min = middle;
band[0].max = top;
band++;
}
}
if ( ras.band_shoot > 8 && ras.band_size > 16 )
ras.band_size = ras.band_size / 2;
return 0;
}
static int
gray_raster_render( gray_PRaster raster,
const FT_Raster_Params* params )
{
const FT_Outline* outline = (const FT_Outline*)params->source;
const FT_Bitmap* target_map = params->target;
gray_PWorker worker;
if ( !raster || !raster->buffer || !raster->buffer_size )
return ErrRaster_Invalid_Argument;
if ( !outline )
return ErrRaster_Invalid_Outline;
/* return immediately if the outline is empty */
if ( outline->n_points == 0 || outline->n_contours <= 0 )
return 0;
if ( !outline->contours || !outline->points )
return ErrRaster_Invalid_Outline;
if ( outline->n_points !=
outline->contours[outline->n_contours - 1] + 1 )
return ErrRaster_Invalid_Outline;
worker = raster->worker;
/* if direct mode is not set, we must have a target bitmap */
if ( !( params->flags & FT_RASTER_FLAG_DIRECT ) )
{
if ( !target_map )
return ErrRaster_Invalid_Argument;
/* nothing to do */
if ( !target_map->width || !target_map->rows )
return 0;
if ( !target_map->buffer )
return ErrRaster_Invalid_Argument;
}
/* this version does not support monochrome rendering */
if ( !( params->flags & FT_RASTER_FLAG_AA ) )
return ErrRaster_Invalid_Mode;
/* compute clipping box */
if ( !( params->flags & FT_RASTER_FLAG_DIRECT ) )
{
/* compute clip box from target pixmap */
ras.clip_box.xMin = 0;
ras.clip_box.yMin = 0;
ras.clip_box.xMax = target_map->width;
ras.clip_box.yMax = target_map->rows;
}
else if ( params->flags & FT_RASTER_FLAG_CLIP )
ras.clip_box = params->clip_box;
else
{
ras.clip_box.xMin = -32768L;
ras.clip_box.yMin = -32768L;
ras.clip_box.xMax = 32767L;
ras.clip_box.yMax = 32767L;
}
gray_init_cells( RAS_VAR_ raster->buffer, raster->buffer_size );
ras.outline = *outline;
ras.num_cells = 0;
ras.invalid = 1;
ras.band_size = raster->band_size;
ras.num_gray_spans = 0;
if ( params->flags & FT_RASTER_FLAG_DIRECT )
{
ras.render_span = (FT_Raster_Span_Func)params->gray_spans;
ras.render_span_data = params->user;
}
else
{
ras.target = *target_map;
ras.render_span = (FT_Raster_Span_Func)gray_render_span;
ras.render_span_data = &ras;
}
return gray_convert_glyph( RAS_VAR );
}
/**** RASTER OBJECT CREATION: In stand-alone mode, we simply use *****/
/**** a static object. *****/
#ifdef _STANDALONE_
static int
gray_raster_new( void* memory,
FT_Raster* araster )
{
static gray_TRaster the_raster;
FT_UNUSED( memory );
*araster = (FT_Raster)&the_raster;
FT_MEM_ZERO( &the_raster, sizeof ( the_raster ) );
return 0;
}
static void
gray_raster_done( FT_Raster raster )
{
/* nothing */
FT_UNUSED( raster );
}
#else /* !_STANDALONE_ */
static int
gray_raster_new( FT_Memory memory,
FT_Raster* araster )
{
FT_Error error;
gray_PRaster raster = NULL;
*araster = 0;
if ( !FT_ALLOC( raster, sizeof ( gray_TRaster ) ) )
{
raster->memory = memory;
*araster = (FT_Raster)raster;
}
return error;
}
static void
gray_raster_done( FT_Raster raster )
{
FT_Memory memory = (FT_Memory)((gray_PRaster)raster)->memory;
FT_FREE( raster );
}
#endif /* !_STANDALONE_ */
static void
gray_raster_reset( FT_Raster raster,
char* pool_base,
long pool_size )
{
gray_PRaster rast = (gray_PRaster)raster;
if ( raster )
{
if ( pool_base && pool_size >= (long)sizeof ( gray_TWorker ) + 2048 )
{
gray_PWorker worker = (gray_PWorker)pool_base;
rast->worker = worker;
rast->buffer = pool_base +
( ( sizeof ( gray_TWorker ) +
sizeof ( TCell ) - 1 ) &
~( sizeof ( TCell ) - 1 ) );
rast->buffer_size = (long)( ( pool_base + pool_size ) -
(char*)rast->buffer ) &
~( sizeof ( TCell ) - 1 );
rast->band_size = (int)( rast->buffer_size /
( sizeof ( TCell ) * 8 ) );
}
else
{
rast->buffer = NULL;
rast->buffer_size = 0;
rast->worker = NULL;
}
}
}
FT_DEFINE_RASTER_FUNCS(ft_grays_raster,
FT_GLYPH_FORMAT_OUTLINE,
(FT_Raster_New_Func) gray_raster_new,
(FT_Raster_Reset_Func) gray_raster_reset,
(FT_Raster_Set_Mode_Func)0,
(FT_Raster_Render_Func) gray_raster_render,
(FT_Raster_Done_Func) gray_raster_done
)
/* END */
/* Local Variables: */
/* coding: utf-8 */
/* End: */
|
agpl-3.0
|
sensorlab/OsuSmartphoneApp
|
plugins/nl.x-services.plugins.toast/src/blackberry10/native/public/json_value.cpp
|
942
|
39212
|
#include <iostream>
#include <json/value.h>
#include <json/writer.h>
#include <utility>
#include <stdexcept>
#include <cstring>
#include <cassert>
#ifdef JSON_USE_CPPTL
# include <cpptl/conststring.h>
#endif
#include <cstddef> // size_t
#ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
# include "json_batchallocator.h"
#endif // #ifndef JSON_USE_SIMPLE_INTERNAL_ALLOCATOR
#define JSON_ASSERT_UNREACHABLE assert( false )
#define JSON_ASSERT( condition ) assert( condition ); // @todo <= change this into an exception throw
#define JSON_ASSERT_MESSAGE( condition, message ) if (!( condition )) throw std::runtime_error( message );
namespace Json {
// QNX is strict about declaring C symbols in the std namespace.
#ifdef __QNXNTO__
using std::memcpy;
using std::strchr;
using std::strcmp;
using std::strlen;
#endif
const Value Value::null;
const Int Value::minInt = Int( ~(UInt(-1)/2) );
const Int Value::maxInt = Int( UInt(-1)/2 );
const UInt Value::maxUInt = UInt(-1);
// A "safe" implementation of strdup. Allow null pointer to be passed.
// Also avoid warning on msvc80.
//
//inline char *safeStringDup( const char *czstring )
//{
// if ( czstring )
// {
// const size_t length = (unsigned int)( strlen(czstring) + 1 );
// char *newString = static_cast<char *>( malloc( length ) );
// memcpy( newString, czstring, length );
// return newString;
// }
// return 0;
//}
//
//inline char *safeStringDup( const std::string &str )
//{
// if ( !str.empty() )
// {
// const size_t length = str.length();
// char *newString = static_cast<char *>( malloc( length + 1 ) );
// memcpy( newString, str.c_str(), length );
// newString[length] = 0;
// return newString;
// }
// return 0;
//}
ValueAllocator::~ValueAllocator()
{
}
class DefaultValueAllocator : public ValueAllocator
{
public:
virtual ~DefaultValueAllocator()
{
}
virtual char *makeMemberName( const char *memberName )
{
return duplicateStringValue( memberName );
}
virtual void releaseMemberName( char *memberName )
{
releaseStringValue( memberName );
}
virtual char *duplicateStringValue( const char *value,
unsigned int length = unknown )
{
//@todo invesgate this old optimization
//if ( !value || value[0] == 0 )
// return 0;
if ( length == unknown )
length = (unsigned int)strlen(value);
char *newString = static_cast<char *>( malloc( length + 1 ) );
memcpy( newString, value, length );
newString[length] = 0;
return newString;
}
virtual void releaseStringValue( char *value )
{
if ( value )
free( value );
}
};
static ValueAllocator *&valueAllocator()
{
static DefaultValueAllocator defaultAllocator;
static ValueAllocator *valueAllocator = &defaultAllocator;
return valueAllocator;
}
static struct DummyValueAllocatorInitializer {
DummyValueAllocatorInitializer()
{
valueAllocator(); // ensure valueAllocator() statics are initialized before main().
}
} dummyValueAllocatorInitializer;
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// ValueInternals...
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
#ifdef JSON_VALUE_USE_INTERNAL_MAP
# include "json_internalarray.inl"
# include "json_internalmap.inl"
#endif // JSON_VALUE_USE_INTERNAL_MAP
# include "json_valueiterator.inl"
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CommentInfo
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
Value::CommentInfo::CommentInfo()
: comment_( 0 )
{
}
Value::CommentInfo::~CommentInfo()
{
if ( comment_ )
valueAllocator()->releaseStringValue( comment_ );
}
void
Value::CommentInfo::setComment( const char *text )
{
if ( comment_ )
valueAllocator()->releaseStringValue( comment_ );
JSON_ASSERT( text );
JSON_ASSERT_MESSAGE( text[0]=='\0' || text[0]=='/', "Comments must start with /");
// It seems that /**/ style comments are acceptable as well.
comment_ = valueAllocator()->duplicateStringValue( text );
}
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::CZString
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
# ifndef JSON_VALUE_USE_INTERNAL_MAP
// Notes: index_ indicates if the string was allocated when
// a string is stored.
Value::CZString::CZString( int index )
: cstr_( 0 )
, index_( index )
{
}
Value::CZString::CZString( const char *cstr, DuplicationPolicy allocate )
: cstr_( allocate == duplicate ? valueAllocator()->makeMemberName(cstr)
: cstr )
, index_( allocate )
{
}
Value::CZString::CZString( const CZString &other )
: cstr_( other.index_ != noDuplication && other.cstr_ != 0
? valueAllocator()->makeMemberName( other.cstr_ )
: other.cstr_ )
, index_( other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate)
: other.index_ )
{
}
Value::CZString::~CZString()
{
if ( cstr_ && index_ == duplicate )
valueAllocator()->releaseMemberName( const_cast<char *>( cstr_ ) );
}
void
Value::CZString::swap( CZString &other )
{
std::swap( cstr_, other.cstr_ );
std::swap( index_, other.index_ );
}
Value::CZString &
Value::CZString::operator =( const CZString &other )
{
CZString temp( other );
swap( temp );
return *this;
}
bool
Value::CZString::operator<( const CZString &other ) const
{
if ( cstr_ )
return strcmp( cstr_, other.cstr_ ) < 0;
return index_ < other.index_;
}
bool
Value::CZString::operator==( const CZString &other ) const
{
if ( cstr_ )
return strcmp( cstr_, other.cstr_ ) == 0;
return index_ == other.index_;
}
int
Value::CZString::index() const
{
return index_;
}
const char *
Value::CZString::c_str() const
{
return cstr_;
}
bool
Value::CZString::isStaticString() const
{
return index_ == noDuplication;
}
#endif // ifndef JSON_VALUE_USE_INTERNAL_MAP
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// class Value::Value
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
// //////////////////////////////////////////////////////////////////
/*! \internal Default constructor initialization must be equivalent to:
* memset( this, 0, sizeof(Value) )
* This optimization is used in ValueInternalMap fast allocator.
*/
Value::Value( ValueType type )
: type_( type )
, allocated_( 0 )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
switch ( type )
{
case nullValue:
break;
case intValue:
case uintValue:
value_.int_ = 0;
break;
case realValue:
value_.real_ = 0.0;
break;
case stringValue:
value_.string_ = 0;
break;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues();
break;
#else
case arrayValue:
value_.array_ = arrayAllocator()->newArray();
break;
case objectValue:
value_.map_ = mapAllocator()->newMap();
break;
#endif
case booleanValue:
value_.bool_ = false;
break;
default:
JSON_ASSERT_UNREACHABLE;
}
}
Value::Value( Int value )
: type_( intValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.int_ = value;
}
Value::Value( UInt value )
: type_( uintValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.uint_ = value;
}
Value::Value( double value )
: type_( realValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.real_ = value;
}
Value::Value( const char *value )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( value );
}
Value::Value( const char *beginValue,
const char *endValue )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( beginValue,
UInt(endValue - beginValue) );
}
Value::Value( const std::string &value )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( value.c_str(),
(unsigned int)value.length() );
}
Value::Value( const StaticString &value )
: type_( stringValue )
, allocated_( false )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = const_cast<char *>( value.c_str() );
}
# ifdef JSON_USE_CPPTL
Value::Value( const CppTL::ConstString &value )
: type_( stringValue )
, allocated_( true )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.string_ = valueAllocator()->duplicateStringValue( value, value.length() );
}
# endif
Value::Value( bool value )
: type_( booleanValue )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
value_.bool_ = value;
}
Value::Value( const Value &other )
: type_( other.type_ )
, comments_( 0 )
# ifdef JSON_VALUE_USE_INTERNAL_MAP
, itemIsUsed_( 0 )
#endif
{
switch ( type_ )
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
value_ = other.value_;
break;
case stringValue:
if ( other.value_.string_ )
{
value_.string_ = valueAllocator()->duplicateStringValue( other.value_.string_ );
allocated_ = true;
}
else
value_.string_ = 0;
break;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_ = new ObjectValues( *other.value_.map_ );
break;
#else
case arrayValue:
value_.array_ = arrayAllocator()->newArrayCopy( *other.value_.array_ );
break;
case objectValue:
value_.map_ = mapAllocator()->newMapCopy( *other.value_.map_ );
break;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
if ( other.comments_ )
{
comments_ = new CommentInfo[numberOfCommentPlacement];
for ( int comment =0; comment < numberOfCommentPlacement; ++comment )
{
const CommentInfo &otherComment = other.comments_[comment];
if ( otherComment.comment_ )
comments_[comment].setComment( otherComment.comment_ );
}
}
}
Value::~Value()
{
switch ( type_ )
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue:
if ( allocated_ )
valueAllocator()->releaseStringValue( value_.string_ );
break;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
delete value_.map_;
break;
#else
case arrayValue:
arrayAllocator()->destructArray( value_.array_ );
break;
case objectValue:
mapAllocator()->destructMap( value_.map_ );
break;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
if ( comments_ )
delete[] comments_;
}
Value &
Value::operator=( const Value &other )
{
Value temp( other );
swap( temp );
return *this;
}
void
Value::swap( Value &other )
{
ValueType temp = type_;
type_ = other.type_;
other.type_ = temp;
std::swap( value_, other.value_ );
int temp2 = allocated_;
allocated_ = other.allocated_;
other.allocated_ = temp2;
}
ValueType
Value::type() const
{
return type_;
}
int
Value::compare( const Value &other )
{
/*
int typeDelta = other.type_ - type_;
switch ( type_ )
{
case nullValue:
return other.type_ == type_;
case intValue:
if ( other.type_.isNumeric()
case uintValue:
case realValue:
case booleanValue:
break;
case stringValue,
break;
case arrayValue:
delete value_.array_;
break;
case objectValue:
delete value_.map_;
default:
JSON_ASSERT_UNREACHABLE;
}
*/
return 0; // unreachable
}
bool
Value::operator <( const Value &other ) const
{
int typeDelta = type_ - other.type_;
if ( typeDelta )
return typeDelta < 0 ? true : false;
switch ( type_ )
{
case nullValue:
return false;
case intValue:
return value_.int_ < other.value_.int_;
case uintValue:
return value_.uint_ < other.value_.uint_;
case realValue:
return value_.real_ < other.value_.real_;
case booleanValue:
return value_.bool_ < other.value_.bool_;
case stringValue:
return ( value_.string_ == 0 && other.value_.string_ )
|| ( other.value_.string_
&& value_.string_
&& strcmp( value_.string_, other.value_.string_ ) < 0 );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
{
int delta = int( value_.map_->size() - other.value_.map_->size() );
if ( delta )
return delta < 0;
return (*value_.map_) < (*other.value_.map_);
}
#else
case arrayValue:
return value_.array_->compare( *(other.value_.array_) ) < 0;
case objectValue:
return value_.map_->compare( *(other.value_.map_) ) < 0;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable
}
bool
Value::operator <=( const Value &other ) const
{
return !(other > *this);
}
bool
Value::operator >=( const Value &other ) const
{
return !(*this < other);
}
bool
Value::operator >( const Value &other ) const
{
return other < *this;
}
bool
Value::operator ==( const Value &other ) const
{
//if ( type_ != other.type_ )
// GCC 2.95.3 says:
// attempt to take address of bit-field structure member `Json::Value::type_'
// Beats me, but a temp solves the problem.
int temp = other.type_;
if ( type_ != temp )
return false;
switch ( type_ )
{
case nullValue:
return true;
case intValue:
return value_.int_ == other.value_.int_;
case uintValue:
return value_.uint_ == other.value_.uint_;
case realValue:
return value_.real_ == other.value_.real_;
case booleanValue:
return value_.bool_ == other.value_.bool_;
case stringValue:
return ( value_.string_ == other.value_.string_ )
|| ( other.value_.string_
&& value_.string_
&& strcmp( value_.string_, other.value_.string_ ) == 0 );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
return value_.map_->size() == other.value_.map_->size()
&& (*value_.map_) == (*other.value_.map_);
#else
case arrayValue:
return value_.array_->compare( *(other.value_.array_) ) == 0;
case objectValue:
return value_.map_->compare( *(other.value_.map_) ) == 0;
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable
}
bool
Value::operator !=( const Value &other ) const
{
return !( *this == other );
}
const char *
Value::asCString() const
{
JSON_ASSERT( type_ == stringValue );
return value_.string_;
}
std::string
Value::asString() const
{
switch ( type_ )
{
case nullValue:
return "";
case stringValue:
return value_.string_ ? value_.string_ : "";
case booleanValue:
return value_.bool_ ? "true" : "false";
case intValue:
case uintValue:
case realValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to string" );
default:
JSON_ASSERT_UNREACHABLE;
}
return ""; // unreachable
}
# ifdef JSON_USE_CPPTL
CppTL::ConstString
Value::asConstString() const
{
return CppTL::ConstString( asString().c_str() );
}
# endif
Value::Int
Value::asInt() const
{
switch ( type_ )
{
case nullValue:
return 0;
case intValue:
return value_.int_;
case uintValue:
JSON_ASSERT_MESSAGE( value_.uint_ < (unsigned)maxInt, "integer out of signed integer range" );
return value_.uint_;
case realValue:
JSON_ASSERT_MESSAGE( value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range" );
return Int( value_.real_ );
case booleanValue:
return value_.bool_ ? 1 : 0;
case stringValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to int" );
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
Value::UInt
Value::asUInt() const
{
switch ( type_ )
{
case nullValue:
return 0;
case intValue:
JSON_ASSERT_MESSAGE( value_.int_ >= 0, "Negative integer can not be converted to unsigned integer" );
return value_.int_;
case uintValue:
return value_.uint_;
case realValue:
JSON_ASSERT_MESSAGE( value_.real_ >= 0 && value_.real_ <= maxUInt, "Real out of unsigned integer range" );
return UInt( value_.real_ );
case booleanValue:
return value_.bool_ ? 1 : 0;
case stringValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to uint" );
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
double
Value::asDouble() const
{
switch ( type_ )
{
case nullValue:
return 0.0;
case intValue:
return value_.int_;
case uintValue:
return value_.uint_;
case realValue:
return value_.real_;
case booleanValue:
return value_.bool_ ? 1.0 : 0.0;
case stringValue:
case arrayValue:
case objectValue:
JSON_ASSERT_MESSAGE( false, "Type is not convertible to double" );
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
bool
Value::asBool() const
{
switch ( type_ )
{
case nullValue:
return false;
case intValue:
case uintValue:
return value_.int_ != 0;
case realValue:
return value_.real_ != 0.0;
case booleanValue:
return value_.bool_;
case stringValue:
return value_.string_ && value_.string_[0] != 0;
case arrayValue:
case objectValue:
return value_.map_->size() != 0;
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable;
}
bool
Value::isConvertibleTo( ValueType other ) const
{
switch ( type_ )
{
case nullValue:
return true;
case intValue:
return ( other == nullValue && value_.int_ == 0 )
|| other == intValue
|| ( other == uintValue && value_.int_ >= 0 )
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case uintValue:
return ( other == nullValue && value_.uint_ == 0 )
|| ( other == intValue && value_.uint_ <= (unsigned)maxInt )
|| other == uintValue
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case realValue:
return ( other == nullValue && value_.real_ == 0.0 )
|| ( other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt )
|| ( other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt )
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case booleanValue:
return ( other == nullValue && value_.bool_ == false )
|| other == intValue
|| other == uintValue
|| other == realValue
|| other == stringValue
|| other == booleanValue;
case stringValue:
return other == stringValue
|| ( other == nullValue && (!value_.string_ || value_.string_[0] == 0) );
case arrayValue:
return other == arrayValue
|| ( other == nullValue && value_.map_->size() == 0 );
case objectValue:
return other == objectValue
|| ( other == nullValue && value_.map_->size() == 0 );
default:
JSON_ASSERT_UNREACHABLE;
}
return false; // unreachable;
}
/// Number of values in array or object
Value::UInt
Value::size() const
{
switch ( type_ )
{
case nullValue:
case intValue:
case uintValue:
case realValue:
case booleanValue:
case stringValue:
return 0;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue: // size of the array is highest index + 1
if ( !value_.map_->empty() )
{
ObjectValues::const_iterator itLast = value_.map_->end();
--itLast;
return (*itLast).first.index()+1;
}
return 0;
case objectValue:
return Int( value_.map_->size() );
#else
case arrayValue:
return Int( value_.array_->size() );
case objectValue:
return Int( value_.map_->size() );
#endif
default:
JSON_ASSERT_UNREACHABLE;
}
return 0; // unreachable;
}
bool
Value::empty() const
{
if ( isNull() || isArray() || isObject() )
return size() == 0u;
else
return false;
}
bool
Value::operator!() const
{
return isNull();
}
void
Value::clear()
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue || type_ == objectValue );
switch ( type_ )
{
#ifndef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
case objectValue:
value_.map_->clear();
break;
#else
case arrayValue:
value_.array_->clear();
break;
case objectValue:
value_.map_->clear();
break;
#endif
default:
break;
}
}
void
Value::resize( UInt newSize )
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue );
if ( type_ == nullValue )
*this = Value( arrayValue );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
UInt oldSize = size();
if ( newSize == 0 )
clear();
else if ( newSize > oldSize )
(*this)[ newSize - 1 ];
else
{
for ( UInt index = newSize; index < oldSize; ++index )
value_.map_->erase( index );
assert( size() == newSize );
}
#else
value_.array_->resize( newSize );
#endif
}
Value &
Value::operator[]( UInt index )
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue );
if ( type_ == nullValue )
*this = Value( arrayValue );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString key( index );
ObjectValues::iterator it = value_.map_->lower_bound( key );
if ( it != value_.map_->end() && (*it).first == key )
return (*it).second;
ObjectValues::value_type defaultValue( key, null );
it = value_.map_->insert( it, defaultValue );
return (*it).second;
#else
return value_.array_->resolveReference( index );
#endif
}
const Value &
Value::operator[]( UInt index ) const
{
JSON_ASSERT( type_ == nullValue || type_ == arrayValue );
if ( type_ == nullValue )
return null;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString key( index );
ObjectValues::const_iterator it = value_.map_->find( key );
if ( it == value_.map_->end() )
return null;
return (*it).second;
#else
Value *value = value_.array_->find( index );
return value ? *value : null;
#endif
}
Value &
Value::operator[]( const char *key )
{
return resolveReference( key, false );
}
Value &
Value::resolveReference( const char *key,
bool isStatic )
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
*this = Value( objectValue );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey( key, isStatic ? CZString::noDuplication
: CZString::duplicateOnCopy );
ObjectValues::iterator it = value_.map_->lower_bound( actualKey );
if ( it != value_.map_->end() && (*it).first == actualKey )
return (*it).second;
ObjectValues::value_type defaultValue( actualKey, null );
it = value_.map_->insert( it, defaultValue );
Value &value = (*it).second;
return value;
#else
return value_.map_->resolveReference( key, isStatic );
#endif
}
Value
Value::get( UInt index,
const Value &defaultValue ) const
{
const Value *value = &((*this)[index]);
return value == &null ? defaultValue : *value;
}
bool
Value::isValidIndex( UInt index ) const
{
return index < size();
}
const Value &
Value::operator[]( const char *key ) const
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
return null;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey( key, CZString::noDuplication );
ObjectValues::const_iterator it = value_.map_->find( actualKey );
if ( it == value_.map_->end() )
return null;
return (*it).second;
#else
const Value *value = value_.map_->find( key );
return value ? *value : null;
#endif
}
Value &
Value::operator[]( const std::string &key )
{
return (*this)[ key.c_str() ];
}
const Value &
Value::operator[]( const std::string &key ) const
{
return (*this)[ key.c_str() ];
}
Value &
Value::operator[]( const StaticString &key )
{
return resolveReference( key, true );
}
# ifdef JSON_USE_CPPTL
Value &
Value::operator[]( const CppTL::ConstString &key )
{
return (*this)[ key.c_str() ];
}
const Value &
Value::operator[]( const CppTL::ConstString &key ) const
{
return (*this)[ key.c_str() ];
}
# endif
Value &
Value::append( const Value &value )
{
return (*this)[size()] = value;
}
Value
Value::get( const char *key,
const Value &defaultValue ) const
{
const Value *value = &((*this)[key]);
return value == &null ? defaultValue : *value;
}
Value
Value::get( const std::string &key,
const Value &defaultValue ) const
{
return get( key.c_str(), defaultValue );
}
Value
Value::removeMember( const char* key )
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
return null;
#ifndef JSON_VALUE_USE_INTERNAL_MAP
CZString actualKey( key, CZString::noDuplication );
ObjectValues::iterator it = value_.map_->find( actualKey );
if ( it == value_.map_->end() )
return null;
Value old(it->second);
value_.map_->erase(it);
return old;
#else
Value *value = value_.map_->find( key );
if (value){
Value old(*value);
value_.map_.remove( key );
return old;
} else {
return null;
}
#endif
}
Value
Value::removeMember( const std::string &key )
{
return removeMember( key.c_str() );
}
# ifdef JSON_USE_CPPTL
Value
Value::get( const CppTL::ConstString &key,
const Value &defaultValue ) const
{
return get( key.c_str(), defaultValue );
}
# endif
bool
Value::isMember( const char *key ) const
{
const Value *value = &((*this)[key]);
return value != &null;
}
bool
Value::isMember( const std::string &key ) const
{
return isMember( key.c_str() );
}
# ifdef JSON_USE_CPPTL
bool
Value::isMember( const CppTL::ConstString &key ) const
{
return isMember( key.c_str() );
}
#endif
Value::Members
Value::getMemberNames() const
{
JSON_ASSERT( type_ == nullValue || type_ == objectValue );
if ( type_ == nullValue )
return Value::Members();
Members members;
members.reserve( value_.map_->size() );
#ifndef JSON_VALUE_USE_INTERNAL_MAP
ObjectValues::const_iterator it = value_.map_->begin();
ObjectValues::const_iterator itEnd = value_.map_->end();
for ( ; it != itEnd; ++it )
members.push_back( std::string( (*it).first.c_str() ) );
#else
ValueInternalMap::IteratorState it;
ValueInternalMap::IteratorState itEnd;
value_.map_->makeBeginIterator( it );
value_.map_->makeEndIterator( itEnd );
for ( ; !ValueInternalMap::equals( it, itEnd ); ValueInternalMap::increment(it) )
members.push_back( std::string( ValueInternalMap::key( it ) ) );
#endif
return members;
}
//
//# ifdef JSON_USE_CPPTL
//EnumMemberNames
//Value::enumMemberNames() const
//{
// if ( type_ == objectValue )
// {
// return CppTL::Enum::any( CppTL::Enum::transform(
// CppTL::Enum::keys( *(value_.map_), CppTL::Type<const CZString &>() ),
// MemberNamesTransform() ) );
// }
// return EnumMemberNames();
//}
//
//
//EnumValues
//Value::enumValues() const
//{
// if ( type_ == objectValue || type_ == arrayValue )
// return CppTL::Enum::anyValues( *(value_.map_),
// CppTL::Type<const Value &>() );
// return EnumValues();
//}
//
//# endif
bool
Value::isNull() const
{
return type_ == nullValue;
}
bool
Value::isBool() const
{
return type_ == booleanValue;
}
bool
Value::isInt() const
{
return type_ == intValue;
}
bool
Value::isUInt() const
{
return type_ == uintValue;
}
bool
Value::isIntegral() const
{
return type_ == intValue
|| type_ == uintValue
|| type_ == booleanValue;
}
bool
Value::isDouble() const
{
return type_ == realValue;
}
bool
Value::isNumeric() const
{
return isIntegral() || isDouble();
}
bool
Value::isString() const
{
return type_ == stringValue;
}
bool
Value::isArray() const
{
return type_ == nullValue || type_ == arrayValue;
}
bool
Value::isObject() const
{
return type_ == nullValue || type_ == objectValue;
}
void
Value::setComment( const char *comment,
CommentPlacement placement )
{
if ( !comments_ )
comments_ = new CommentInfo[numberOfCommentPlacement];
comments_[placement].setComment( comment );
}
void
Value::setComment( const std::string &comment,
CommentPlacement placement )
{
setComment( comment.c_str(), placement );
}
bool
Value::hasComment( CommentPlacement placement ) const
{
return comments_ != 0 && comments_[placement].comment_ != 0;
}
std::string
Value::getComment( CommentPlacement placement ) const
{
if ( hasComment(placement) )
return comments_[placement].comment_;
return "";
}
std::string
Value::toStyledString() const
{
StyledWriter writer;
return writer.write( *this );
}
Value::const_iterator
Value::begin() const
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeBeginIterator( it );
return const_iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeBeginIterator( it );
return const_iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return const_iterator( value_.map_->begin() );
break;
#endif
default:
break;
}
return const_iterator();
}
Value::const_iterator
Value::end() const
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeEndIterator( it );
return const_iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeEndIterator( it );
return const_iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return const_iterator( value_.map_->end() );
break;
#endif
default:
break;
}
return const_iterator();
}
Value::iterator
Value::begin()
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeBeginIterator( it );
return iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeBeginIterator( it );
return iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return iterator( value_.map_->begin() );
break;
#endif
default:
break;
}
return iterator();
}
Value::iterator
Value::end()
{
switch ( type_ )
{
#ifdef JSON_VALUE_USE_INTERNAL_MAP
case arrayValue:
if ( value_.array_ )
{
ValueInternalArray::IteratorState it;
value_.array_->makeEndIterator( it );
return iterator( it );
}
break;
case objectValue:
if ( value_.map_ )
{
ValueInternalMap::IteratorState it;
value_.map_->makeEndIterator( it );
return iterator( it );
}
break;
#else
case arrayValue:
case objectValue:
if ( value_.map_ )
return iterator( value_.map_->end() );
break;
#endif
default:
break;
}
return iterator();
}
// class PathArgument
// //////////////////////////////////////////////////////////////////
PathArgument::PathArgument()
: kind_( kindNone )
{
}
PathArgument::PathArgument( Value::UInt index )
: index_( index )
, kind_( kindIndex )
{
}
PathArgument::PathArgument( const char *key )
: key_( key )
, kind_( kindKey )
{
}
PathArgument::PathArgument( const std::string &key )
: key_( key.c_str() )
, kind_( kindKey )
{
}
// class Path
// //////////////////////////////////////////////////////////////////
Path::Path( const std::string &path,
const PathArgument &a1,
const PathArgument &a2,
const PathArgument &a3,
const PathArgument &a4,
const PathArgument &a5 )
{
InArgs in;
in.push_back( &a1 );
in.push_back( &a2 );
in.push_back( &a3 );
in.push_back( &a4 );
in.push_back( &a5 );
makePath( path, in );
}
void
Path::makePath( const std::string &path,
const InArgs &in )
{
const char *current = path.c_str();
const char *end = current + path.length();
InArgs::const_iterator itInArg = in.begin();
while ( current != end )
{
if ( *current == '[' )
{
++current;
if ( *current == '%' )
addPathInArg( path, in, itInArg, PathArgument::kindIndex );
else
{
Value::UInt index = 0;
for ( ; current != end && *current >= '0' && *current <= '9'; ++current )
index = index * 10 + Value::UInt(*current - '0');
args_.push_back( index );
}
if ( current == end || *current++ != ']' )
invalidPath( path, int(current - path.c_str()) );
}
else if ( *current == '%' )
{
addPathInArg( path, in, itInArg, PathArgument::kindKey );
++current;
}
else if ( *current == '.' )
{
++current;
}
else
{
const char *beginName = current;
while ( current != end && !strchr( "[.", *current ) )
++current;
args_.push_back( std::string( beginName, current ) );
}
}
}
void
Path::addPathInArg( const std::string &path,
const InArgs &in,
InArgs::const_iterator &itInArg,
PathArgument::Kind kind )
{
if ( itInArg == in.end() )
{
// Error: missing argument %d
}
else if ( (*itInArg)->kind_ != kind )
{
// Error: bad argument type
}
else
{
args_.push_back( **itInArg );
}
}
void
Path::invalidPath( const std::string &path,
int location )
{
// Error: invalid path.
}
const Value &
Path::resolve( const Value &root ) const
{
const Value *node = &root;
for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it )
{
const PathArgument &arg = *it;
if ( arg.kind_ == PathArgument::kindIndex )
{
if ( !node->isArray() || node->isValidIndex( arg.index_ ) )
{
// Error: unable to resolve path (array value expected at position...
}
node = &((*node)[arg.index_]);
}
else if ( arg.kind_ == PathArgument::kindKey )
{
if ( !node->isObject() )
{
// Error: unable to resolve path (object value expected at position...)
}
node = &((*node)[arg.key_]);
if ( node == &Value::null )
{
// Error: unable to resolve path (object has no member named '' at position...)
}
}
}
return *node;
}
Value
Path::resolve( const Value &root,
const Value &defaultValue ) const
{
const Value *node = &root;
for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it )
{
const PathArgument &arg = *it;
if ( arg.kind_ == PathArgument::kindIndex )
{
if ( !node->isArray() || node->isValidIndex( arg.index_ ) )
return defaultValue;
node = &((*node)[arg.index_]);
}
else if ( arg.kind_ == PathArgument::kindKey )
{
if ( !node->isObject() )
return defaultValue;
node = &((*node)[arg.key_]);
if ( node == &Value::null )
return defaultValue;
}
}
return *node;
}
Value &
Path::make( Value &root ) const
{
Value *node = &root;
for ( Args::const_iterator it = args_.begin(); it != args_.end(); ++it )
{
const PathArgument &arg = *it;
if ( arg.kind_ == PathArgument::kindIndex )
{
if ( !node->isArray() )
{
// Error: node is not an array at position ...
}
node = &((*node)[arg.index_]);
}
else if ( arg.kind_ == PathArgument::kindKey )
{
if ( !node->isObject() )
{
// Error: node is not an object at position...
}
node = &((*node)[arg.key_]);
}
}
return *node;
}
} // namespace Json
|
agpl-3.0
|
stmh/osg
|
src/osgWrappers/deprecated-dotosg/osg/NodeCallback.cpp
|
1
|
1431
|
#include <osg/Notify>
#include <osg/NodeCallback>
#include <osgDB/Registry>
#include <osgDB/Input>
#include <osgDB/Output>
using namespace osg;
using namespace osgDB;
bool NodeCallback_readLocalData(osg::Object &obj, osgDB::Input &fr);
bool NodeCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw); // register the read and write functions with the osgDB::Registry.
REGISTER_DOTOSGWRAPPER(NodeCallback)
(
new NodeCallback,
"NodeCallback",
"Object NodeCallback",
&NodeCallback_readLocalData,
&NodeCallback_writeLocalData
);
bool NodeCallback_readLocalData(osg::Object &obj, osgDB::Input &fr)
{
NodeCallback& nc = dynamic_cast<NodeCallback&>(obj);
if (!(&nc)) return false;
bool itrAdvanced = false;
static osg::ref_ptr<NodeCallback> s_nc = new NodeCallback;
osg::ref_ptr<osg::Object> object = fr.readObjectOfType(*s_nc);
if (object.valid())
{
NodeCallback* ncc = dynamic_cast<NodeCallback*>(object.get());
if (ncc) nc.setNestedCallback(ncc);
itrAdvanced = true;
}
return itrAdvanced;
}
bool NodeCallback_writeLocalData(const osg::Object &obj, osgDB::Output &fw)
{
const NodeCallback* nc = dynamic_cast<const NodeCallback*>(&obj);
if (!nc) return false;
NodeCallback* nnc = (NodeCallback*) nc;
if (nnc->getNestedCallback())
{
fw.writeObject(*(nnc->getNestedCallback()));
}
return true;
}
|
lgpl-2.1
|
sandsmark/zanshin
|
tests/units/utils/mockobjecttest.cpp
|
1
|
2764
|
/* This file is part of Zanshin
Copyright 2014 Kevin Ottens <ervin@kde.org>
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; either version 2 of
the License or (at your option) version 3 or any later version
accepted by the membership of KDE e.V. (or its successor approved
by the membership of KDE e.V.), which shall act as a proxy
defined in Section 14 of version 3 of the license.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
*/
#include <QtTest>
#include "utils/mockobject.h"
using mockitopp::matcher::any;
using namespace Utils;
class FakeInterface
{
public:
FakeInterface() {}
virtual ~FakeInterface() {}
virtual void doSomething() = 0;
virtual int computeMe(QString input) = 0;
};
class MockObjectTest : public QObject
{
Q_OBJECT
private slots:
void testBasics()
{
MockObject<FakeInterface> mock;
mock(&FakeInterface::doSomething).when().thenReturn();
mock(&FakeInterface::doSomething).when().thenThrow("exception");
for (int i = 0; i < 10; i++) {
mock(&FakeInterface::computeMe).when("A").thenReturn(0);
mock(&FakeInterface::computeMe).when("B").thenReturn(1);
mock(&FakeInterface::computeMe).when("C").thenReturn(-1);
mock(&FakeInterface::computeMe).when("Foo").thenReturn(-1);
}
QSharedPointer<FakeInterface> iface1 = mock.getInstance();
QSharedPointer<FakeInterface> iface2 = mock.getInstance(); // Shouldn't cause a crash later
QCOMPARE(iface1.data(), iface2.data());
iface1->doSomething();
try {
iface2->doSomething();
QFAIL("No exception thrown");
} catch (...) {
// We expect to catch something
}
for (int i = 0; i < 10; i++) {
QCOMPARE(iface1->computeMe("A"), 0);
QCOMPARE(iface2->computeMe("B"), 1);
QCOMPARE(iface1->computeMe("C"), -1);
QCOMPARE(iface2->computeMe("Foo"), -1);
}
QVERIFY(mock(&FakeInterface::doSomething).when().exactly(2));
QVERIFY(mock(&FakeInterface::computeMe).when(any<QString>()).exactly(40));
}
};
QTEST_MAIN(MockObjectTest)
#include "mockobjecttest.moc"
|
lgpl-2.1
|
1045917067/live555_20141217
|
client_demos/demux_main.c
|
1
|
6107
|
/** ============================================================================
*
* tsmux_main.c
*
* Author : zzx
*
* Date : Sep 17, 2013
*
* Description:
* ============================================================================
*/
/* --------------------- Include system headers ---------------------------- */
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <time.h>
#include <sys/time.h>
#include <pthread.h>
/* --------------------- Include user headers ---------------------------- */
#include "live555.h"
#if defined(__cplusplus)
extern "C" {
#endif
/*
* --------------------- Macro definition -------------------------------------
*/
/** ============================================================================
* @Macro: Macro name
*
* @Description: Description of this macro.
* ============================================================================
*/
#define TSMUX_TMP_BUFFER_SIZE (1024 *1024)
#ifndef TRUE
#define TRUE 1
#endif
#ifndef FALSE
#define FALSE 0
#endif
/*
* --------------------- Structure definition ---------------------------------
*/
/** ----------------------------------------------------------------------------
* @Name: Structure name
*
* @Description: Description of the structure.
*
* @Field: Field1 member
*
* @Field Field2 member
* ----------------------------------------------------------------------------
*/
struct __demux_object_t;
typedef struct __demux_object_t demux_object_t;
struct __demux_object_t
{
demux_prm_t m_prm;
int m_exit;
FILE * m_vout;
FILE * m_aout;
demux_t * m_demux;
};
#if 0
struct __rtspclient_object_t;
typedef struct __rtspclient_object_t rtspclient_object_t;
struct __rtspclient_object_t
{
unsigned char * m_ves;
unsigned char * m_aes;
unsigned int m_ves_size;
unsigned int m_aes_size;
RingBufferHandle_t
m_video_que;
RingBufferHandle_t
m_audio_que;
};
#endif
/*
* --------------------- Global variable definition ---------------------------
*/
/** ----------------------------------------------------------------------------
* @Name: Variable name
*
* @Description: Description of the variable.
* -----------------------------------------------------------------------------
*/
static demux_object_t glb_demux_obj;
/*
* --------------------- Local function forward declaration -------------------
*/
/** ============================================================================
*
* @Function: Local function forward declaration.
*
* @Description: // 函数功能、性能等的描述
*
* @Calls: // 被本函数调用的函数清单
*
* @Called By: // 调用本函数的函数清单
*
* @Table Accessed:// 被访问的表(此项仅对于牵扯到数据库操作的程序)
*
* @Table Updated: // 被修改的表(此项仅对于牵扯到数据库操作的程序)
*
* @Input: // 对输入参数的说明
*
* @Output: // 对输出参数的说明
*
* @Return: // 函数返回值的说明
*
* @Enter // Precondition
*
* @Leave // Postcondition
*
* @Others: // 其它说明
*
* ============================================================================
*/
static status_t __demux_callback_fxn(void *buf, unsigned int size, int av_type, void *ud);
/*
* --------------------- Public function definition ---------------------------
*/
/** ============================================================================
*
* @Function: Public function definition.
*
* @Description: // 函数功能、性能等的描述
*
* @Calls: // 被本函数调用的函数清单
*
* @Called By: // 调用本函数的函数清单
*
* @Table Accessed:// 被访问的表(此项仅对于牵扯到数据库操作的程序)
*
* @Table Updated: // 被修改的表(此项仅对于牵扯到数据库操作的程序)
*
* @Input: // 对输入参数的说明
*
* @Output: // 对输出参数的说明
*
* @Return: // 函数返回值的说明
*
* @Enter // Precondition
*
* @Leave // Postcondition
*
* @Others: // 其它说明
*
* ============================================================================
*/
int main(int argc, char *argv[])
{
int status = 0;
static int count = 0;
demux_object_t * pobj = &glb_demux_obj;
snprintf(pobj->m_prm.m_url, sizeof(pobj->m_prm.m_url) - 1, "%s", argv[1]);
pobj->m_vout = fopen("v.es", "wb+");
status = demux_open(&pobj->m_demux, &pobj->m_prm);
while (1) {
status = demux_exec(pobj->m_demux, __demux_callback_fxn, (void *)pobj);
if (status != 0) {
fprintf(stderr, "demux: Failed to demux data, exit...\n");
break;
}
//usleep(15000);
}
fclose(pobj->m_vout);
status = demux_close(&pobj->m_demux);
return 0;
}
/*
* --------------------- Local function definition ----------------------------
*/
/** ============================================================================
*
* @Function: Local function definition.
*
* @Description: // 函数功能、性能等的描述
*
* ============================================================================
*/
static status_t __demux_callback_fxn(void *buf, unsigned int size, int av_type, void *ud)
{
demux_object_t *pobj = (demux_object_t *)ud;
FILE * out = NULL;
if (av_type == VIDEO_ES) {
static FILE *vfp = NULL;
if(vfp == NULL)
vfp = fopen("vout.h264","wb+");
fwrite(buf,size,1,vfp);
out = pobj->m_vout;
} else {
static FILE *afp = NULL;
if(afp == NULL)
afp = fopen("aout.aac","wb+");
fwrite(buf,size,1,afp);
out = pobj->m_aout;
}
if (size > 0 && out) {
fwrite(buf, size, 1, out);
}
return 0;
}
#if defined(__cplusplus)
}
#endif
|
lgpl-2.1
|
fredrik-johansson/flint2
|
fmpz_mpoly/test/t-push_term_fmpz_fmpz.c
|
2
|
3948
|
/*
Copyright (C) 2018 Daniel Schultz
This file is part of FLINT.
FLINT is free software: you can redistribute it and/or modify it under
the terms of the GNU Lesser General Public License (LGPL) as published
by the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version. See <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include "fmpz_mpoly.h"
int
main(void)
{
slong i, j, k;
FLINT_TEST_INIT(state);
flint_printf("push_term_fmpz_fmpz....");
fflush(stdout);
/* Check pushback matches add */
for (i = 0; i < 1000 * flint_test_multiplier(); i++)
{
fmpz_mpoly_ctx_t ctx;
fmpz_mpoly_t f1, f2, m;
flint_bitcnt_t coeff_bits, exp_bits;
fmpz ** exp, ** exp2;
slong len, nvars;
fmpz_t c, c2;
fmpz_mpoly_ctx_init_rand(ctx, state, 10);
fmpz_mpoly_init(f1, ctx);
fmpz_mpoly_init(f2, ctx);
fmpz_mpoly_init(m, ctx);
fmpz_init(c);
fmpz_init(c2);
nvars = fmpz_mpoly_ctx_nvars(ctx);
exp = (fmpz **) flint_malloc(nvars*sizeof(fmpz *));
exp2 = (fmpz **) flint_malloc(nvars*sizeof(fmpz *));
for (k = 0; k < nvars; k++)
{
exp[k] = (fmpz *) flint_malloc(sizeof(fmpz));
fmpz_init(exp[k]);
exp2[k] = (fmpz *) flint_malloc(sizeof(fmpz));
fmpz_init(exp2[k]);
}
len = n_randint(state, 20);
coeff_bits = n_randint(state, 100) + 1;
exp_bits = n_randint(state, 200);
fmpz_mpoly_zero(f1, ctx);
fmpz_mpoly_zero(f2, ctx);
for (j = 0; j < len; j++)
{
/* get random term */
fmpz_randtest(c, state, coeff_bits);
for (k = 0; k < nvars; k++)
fmpz_randtest_unsigned(exp[k], state, exp_bits);
/* add it to f1 */
fmpz_mpoly_zero(m, ctx);
fmpz_mpoly_set_coeff_fmpz_fmpz(m, c, exp, ctx);
fmpz_mpoly_add(f1, f1, m, ctx);
fmpz_mpoly_assert_canonical(f1, ctx);
/* push it back on f2 */
fmpz_mpoly_push_term_fmpz_fmpz(f2, c, exp, ctx);
/* make sure last term matches */
fmpz_mpoly_get_term_coeff_fmpz(c2, f2, fmpz_mpoly_length(f2, ctx) - 1, ctx);
fmpz_mpoly_get_term_exp_fmpz(exp2, f2, fmpz_mpoly_length(f2, ctx) - 1, ctx);
if (!fmpz_equal(c, c2))
{
printf("FAIL\n");
flint_printf("Check pushed coefficient matches\ni=%wd, j=%wd\n", i, j);
fflush(stdout);
flint_abort();
}
for (k = 0; k < nvars; k++)
{
if (!fmpz_equal(exp[k], exp2[k]))
{
printf("FAIL\n");
flint_printf("Check pushed exponent matches\ni=%wd, j=%wd\n", i, j);
fflush(stdout);
flint_abort();
}
}
}
fmpz_mpoly_sort_terms(f2, ctx);
fmpz_mpoly_combine_like_terms(f2, ctx);
fmpz_mpoly_assert_canonical(f2, ctx);
if (!fmpz_mpoly_equal(f1, f2, ctx))
{
printf("FAIL\n");
flint_printf("Check pushed polynomial matches add\ni=%wd\n",i,j);
fflush(stdout);
flint_abort();
}
fmpz_clear(c2);
fmpz_clear(c);
fmpz_mpoly_clear(f1, ctx);
fmpz_mpoly_clear(f2, ctx);
fmpz_mpoly_clear(m, ctx);
fmpz_mpoly_ctx_clear(ctx);
for (k = 0; k < nvars; k++)
{
fmpz_clear(exp2[k]);
flint_free(exp2[k]);
fmpz_clear(exp[k]);
flint_free(exp[k]);
}
flint_free(exp2);
flint_free(exp);
}
FLINT_TEST_CLEANUP(state);
flint_printf("PASS\n");
return 0;
}
|
lgpl-2.1
|
kobolabs/qt-everywhere-opensource-src-4.6.2
|
examples/widgets/styles/norwegianwoodstyle.cpp
|
2
|
10895
|
/****************************************************************************
**
** Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial Usage
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
** $QT_END_LICENSE$
**
****************************************************************************/
#include <QtGui>
#include "norwegianwoodstyle.h"
//! [0]
void NorwegianWoodStyle::polish(QPalette &palette)
{
QColor brown(212, 140, 95);
QColor beige(236, 182, 120);
QColor slightlyOpaqueBlack(0, 0, 0, 63);
QPixmap backgroundImage(":/images/woodbackground.png");
QPixmap buttonImage(":/images/woodbutton.png");
QPixmap midImage = buttonImage;
QPainter painter;
painter.begin(&midImage);
painter.setPen(Qt::NoPen);
painter.fillRect(midImage.rect(), slightlyOpaqueBlack);
painter.end();
//! [0]
//! [1]
palette = QPalette(brown);
palette.setBrush(QPalette::BrightText, Qt::white);
palette.setBrush(QPalette::Base, beige);
palette.setBrush(QPalette::Highlight, Qt::darkGreen);
setTexture(palette, QPalette::Button, buttonImage);
setTexture(palette, QPalette::Mid, midImage);
setTexture(palette, QPalette::Window, backgroundImage);
QBrush brush = palette.background();
brush.setColor(brush.color().dark());
palette.setBrush(QPalette::Disabled, QPalette::WindowText, brush);
palette.setBrush(QPalette::Disabled, QPalette::Text, brush);
palette.setBrush(QPalette::Disabled, QPalette::ButtonText, brush);
palette.setBrush(QPalette::Disabled, QPalette::Base, brush);
palette.setBrush(QPalette::Disabled, QPalette::Button, brush);
palette.setBrush(QPalette::Disabled, QPalette::Mid, brush);
}
//! [1]
//! [3]
void NorwegianWoodStyle::polish(QWidget *widget)
//! [3] //! [4]
{
if (qobject_cast<QPushButton *>(widget)
|| qobject_cast<QComboBox *>(widget))
widget->setAttribute(Qt::WA_Hover, true);
}
//! [4]
//! [5]
void NorwegianWoodStyle::unpolish(QWidget *widget)
//! [5] //! [6]
{
if (qobject_cast<QPushButton *>(widget)
|| qobject_cast<QComboBox *>(widget))
widget->setAttribute(Qt::WA_Hover, false);
}
//! [6]
//! [7]
int NorwegianWoodStyle::pixelMetric(PixelMetric metric,
//! [7] //! [8]
const QStyleOption *option,
const QWidget *widget) const
{
switch (metric) {
case PM_ComboBoxFrameWidth:
return 8;
case PM_ScrollBarExtent:
return QMotifStyle::pixelMetric(metric, option, widget) + 4;
default:
return QMotifStyle::pixelMetric(metric, option, widget);
}
}
//! [8]
//! [9]
int NorwegianWoodStyle::styleHint(StyleHint hint, const QStyleOption *option,
//! [9] //! [10]
const QWidget *widget,
QStyleHintReturn *returnData) const
{
switch (hint) {
case SH_DitherDisabledText:
return int(false);
case SH_EtchDisabledText:
return int(true);
default:
return QMotifStyle::styleHint(hint, option, widget, returnData);
}
}
//! [10]
//! [11]
void NorwegianWoodStyle::drawPrimitive(PrimitiveElement element,
//! [11] //! [12]
const QStyleOption *option,
QPainter *painter,
const QWidget *widget) const
{
switch (element) {
case PE_PanelButtonCommand:
{
int delta = (option->state & State_MouseOver) ? 64 : 0;
QColor slightlyOpaqueBlack(0, 0, 0, 63);
QColor semiTransparentWhite(255, 255, 255, 127 + delta);
QColor semiTransparentBlack(0, 0, 0, 127 - delta);
int x, y, width, height;
option->rect.getRect(&x, &y, &width, &height);
//! [12]
//! [13]
QPainterPath roundRect = roundRectPath(option->rect);
//! [13] //! [14]
int radius = qMin(width, height) / 2;
//! [14]
//! [15]
QBrush brush;
//! [15] //! [16]
bool darker;
const QStyleOptionButton *buttonOption =
qstyleoption_cast<const QStyleOptionButton *>(option);
if (buttonOption
&& (buttonOption->features & QStyleOptionButton::Flat)) {
brush = option->palette.background();
darker = (option->state & (State_Sunken | State_On));
} else {
if (option->state & (State_Sunken | State_On)) {
brush = option->palette.mid();
darker = !(option->state & State_Sunken);
} else {
brush = option->palette.button();
darker = false;
//! [16] //! [17]
}
//! [17] //! [18]
}
//! [18]
//! [19]
painter->save();
//! [19] //! [20]
painter->setRenderHint(QPainter::Antialiasing, true);
//! [20] //! [21]
painter->fillPath(roundRect, brush);
//! [21] //! [22]
if (darker)
//! [22] //! [23]
painter->fillPath(roundRect, slightlyOpaqueBlack);
//! [23]
//! [24]
int penWidth;
//! [24] //! [25]
if (radius < 10)
penWidth = 3;
else if (radius < 20)
penWidth = 5;
else
penWidth = 7;
QPen topPen(semiTransparentWhite, penWidth);
QPen bottomPen(semiTransparentBlack, penWidth);
if (option->state & (State_Sunken | State_On))
qSwap(topPen, bottomPen);
//! [25]
//! [26]
int x1 = x;
int x2 = x + radius;
int x3 = x + width - radius;
int x4 = x + width;
if (option->direction == Qt::RightToLeft) {
qSwap(x1, x4);
qSwap(x2, x3);
}
QPolygon topHalf;
topHalf << QPoint(x1, y)
<< QPoint(x4, y)
<< QPoint(x3, y + radius)
<< QPoint(x2, y + height - radius)
<< QPoint(x1, y + height);
painter->setClipPath(roundRect);
painter->setClipRegion(topHalf, Qt::IntersectClip);
painter->setPen(topPen);
painter->drawPath(roundRect);
//! [26] //! [32]
QPolygon bottomHalf = topHalf;
bottomHalf[0] = QPoint(x4, y + height);
painter->setClipPath(roundRect);
painter->setClipRegion(bottomHalf, Qt::IntersectClip);
painter->setPen(bottomPen);
painter->drawPath(roundRect);
painter->setPen(option->palette.foreground().color());
painter->setClipping(false);
painter->drawPath(roundRect);
painter->restore();
}
break;
//! [32] //! [33]
default:
//! [33] //! [34]
QMotifStyle::drawPrimitive(element, option, painter, widget);
}
}
//! [34]
//! [35]
void NorwegianWoodStyle::drawControl(ControlElement element,
//! [35] //! [36]
const QStyleOption *option,
QPainter *painter,
const QWidget *widget) const
{
switch (element) {
case CE_PushButtonLabel:
{
QStyleOptionButton myButtonOption;
const QStyleOptionButton *buttonOption =
qstyleoption_cast<const QStyleOptionButton *>(option);
if (buttonOption) {
myButtonOption = *buttonOption;
if (myButtonOption.palette.currentColorGroup()
!= QPalette::Disabled) {
if (myButtonOption.state & (State_Sunken | State_On)) {
myButtonOption.palette.setBrush(QPalette::ButtonText,
myButtonOption.palette.brightText());
}
}
}
QMotifStyle::drawControl(element, &myButtonOption, painter, widget);
}
break;
default:
QMotifStyle::drawControl(element, option, painter, widget);
}
}
//! [36]
//! [37]
void NorwegianWoodStyle::setTexture(QPalette &palette, QPalette::ColorRole role,
//! [37] //! [38]
const QPixmap &pixmap)
{
for (int i = 0; i < QPalette::NColorGroups; ++i) {
QColor color = palette.brush(QPalette::ColorGroup(i), role).color();
palette.setBrush(QPalette::ColorGroup(i), role, QBrush(color, pixmap));
}
}
//! [38]
//! [39]
QPainterPath NorwegianWoodStyle::roundRectPath(const QRect &rect)
//! [39] //! [40]
{
int radius = qMin(rect.width(), rect.height()) / 2;
int diam = 2 * radius;
int x1, y1, x2, y2;
rect.getCoords(&x1, &y1, &x2, &y2);
QPainterPath path;
path.moveTo(x2, y1 + radius);
path.arcTo(QRect(x2 - diam, y1, diam, diam), 0.0, +90.0);
path.lineTo(x1 + radius, y1);
path.arcTo(QRect(x1, y1, diam, diam), 90.0, +90.0);
path.lineTo(x1, y2 - radius);
path.arcTo(QRect(x1, y2 - diam, diam, diam), 180.0, +90.0);
path.lineTo(x1 + radius, y2);
path.arcTo(QRect(x2 - diam, y2 - diam, diam, diam), 270.0, +90.0);
path.closeSubpath();
return path;
}
//! [40]
|
lgpl-2.1
|
RT-Thread/rtthread_fsl
|
bsp/kinetis/platform/hal/src/tsi/fsl_tsi_hal.c
|
2
|
2021
|
/*
* Copyright (c) 2013 - 2014, Freescale Semiconductor, Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* o Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
*
* o 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.
*
* o Neither the name of Freescale Semiconductor, Inc. nor the names of its
* contributors may be used to endorse or promote products derived from this
* software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "fsl_tsi_hal.h"
#include <assert.h>
#if FSL_FEATURE_SOC_TSI_COUNT
/*FUNCTION**********************************************************************
*
* Function Name : TSI_HAL_DisableLowPower
* Description : Function disables low power
*END**************************************************************************/
void TSI_HAL_DisableLowPower(TSI_Type * base)
{
TSI_HAL_DisableStop(base);
}
#endif
|
lgpl-2.1
|
jbakosi/HYPRE
|
src/parcsr_ls/par_cgc_coarsen.c
|
2
|
44524
|
/*BHEADER**********************************************************************
* Copyright (c) 2008, Lawrence Livermore National Security, LLC.
* Produced at the Lawrence Livermore National Laboratory.
* This file is part of HYPRE. See file COPYRIGHT for details.
*
* HYPRE 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) version 2.1 dated February 1999.
*
* $Revision$
***********************************************************************EHEADER*/
/******************************************************************************
*
*****************************************************************************/
/* following should be in a header file */
#include "_hypre_parcsr_ls.h"
#include "../HYPRE.h" /* BM Aug 15, 2006 */
#define C_PT 1
#define F_PT -1
#define Z_PT -2
#define SF_PT -3 /* special fine points */
#define UNDECIDED 0
/**************************************************************
*
* CGC Coarsening routine
*
**************************************************************/
HYPRE_Int
hypre_BoomerAMGCoarsenCGCb( hypre_ParCSRMatrix *S,
hypre_ParCSRMatrix *A,
HYPRE_Int measure_type,
HYPRE_Int coarsen_type,
HYPRE_Int cgc_its,
HYPRE_Int debug_flag,
HYPRE_Int **CF_marker_ptr)
{
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg(S);
hypre_ParCSRCommHandle *comm_handle;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag(S);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd(S);
HYPRE_Int *S_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_j = hypre_CSRMatrixJ(S_diag);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j;
HYPRE_Int num_variables = hypre_CSRMatrixNumRows(S_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols(S_offd);
hypre_CSRMatrix *S_ext;
HYPRE_Int *S_ext_i;
HYPRE_Int *S_ext_j;
hypre_CSRMatrix *ST;
HYPRE_Int *ST_i;
HYPRE_Int *ST_j;
HYPRE_Int *CF_marker;
HYPRE_Int *CF_marker_offd=NULL;
HYPRE_Int ci_tilde = -1;
HYPRE_Int ci_tilde_mark = -1;
HYPRE_Int *measure_array;
HYPRE_Int *measure_array_master;
HYPRE_Int *graph_array;
HYPRE_Int *int_buf_data=NULL;
/*HYPRE_Int *ci_array=NULL;*/
HYPRE_Int i, j, k, l, jS;
HYPRE_Int ji, jj, index;
HYPRE_Int set_empty = 1;
HYPRE_Int C_i_nonempty = 0;
HYPRE_Int num_nonzeros;
HYPRE_Int num_procs, my_id;
HYPRE_Int num_sends = 0;
HYPRE_Int first_col, start;
HYPRE_Int col_0, col_n;
hypre_LinkList LoL_head;
hypre_LinkList LoL_tail;
HYPRE_Int *lists, *where;
HYPRE_Int measure, new_meas;
HYPRE_Int num_left;
HYPRE_Int nabor, nabor_two;
HYPRE_Int ierr = 0;
HYPRE_Int use_commpkg_A = 0;
HYPRE_Real wall_time;
HYPRE_Int measure_max; /* BM Aug 30, 2006: maximal measure, needed for CGC */
if (coarsen_type < 0) coarsen_type = -coarsen_type;
/*-------------------------------------------------------
* Initialize the C/F marker, LoL_head, LoL_tail arrays
*-------------------------------------------------------*/
LoL_head = NULL;
LoL_tail = NULL;
lists = hypre_CTAlloc(HYPRE_Int, num_variables);
where = hypre_CTAlloc(HYPRE_Int, num_variables);
#if 0 /* debugging */
char filename[256];
FILE *fp;
HYPRE_Int iter = 0;
#endif
/*--------------------------------------------------------------
* Compute a CSR strength matrix, S.
*
* For now, the "strength" of dependence/influence is defined in
* the following way: i depends on j if
* aij > hypre_max (k != i) aik, aii < 0
* or
* aij < hypre_min (k != i) aik, aii >= 0
* Then S_ij = 1, else S_ij = 0.
*
* NOTE: the entries are negative initially, corresponding
* to "unaccounted-for" dependence.
*----------------------------------------------------------------*/
if (debug_flag == 3) wall_time = time_getWallclockSeconds();
hypre_MPI_Comm_size(comm,&num_procs);
hypre_MPI_Comm_rank(comm,&my_id);
if (!comm_pkg)
{
use_commpkg_A = 1;
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
if (!comm_pkg)
{
hypre_MatvecCommPkgCreate(A);
comm_pkg = hypre_ParCSRMatrixCommPkg(A);
}
num_sends = hypre_ParCSRCommPkgNumSends(comm_pkg);
if (num_cols_offd) S_offd_j = hypre_CSRMatrixJ(S_offd);
jS = S_i[num_variables];
ST = hypre_CSRMatrixCreate(num_variables, num_variables, jS);
ST_i = hypre_CTAlloc(HYPRE_Int,num_variables+1);
ST_j = hypre_CTAlloc(HYPRE_Int,jS);
hypre_CSRMatrixI(ST) = ST_i;
hypre_CSRMatrixJ(ST) = ST_j;
/*----------------------------------------------------------
* generate transpose of S, ST
*----------------------------------------------------------*/
for (i=0; i <= num_variables; i++)
ST_i[i] = 0;
for (i=0; i < jS; i++)
{
ST_i[S_j[i]+1]++;
}
for (i=0; i < num_variables; i++)
{
ST_i[i+1] += ST_i[i];
}
for (i=0; i < num_variables; i++)
{
for (j=S_i[i]; j < S_i[i+1]; j++)
{
index = S_j[j];
ST_j[ST_i[index]] = i;
ST_i[index]++;
}
}
for (i = num_variables; i > 0; i--)
{
ST_i[i] = ST_i[i-1];
}
ST_i[0] = 0;
/*----------------------------------------------------------
* Compute the measures
*
* The measures are given by the row sums of ST.
* Hence, measure_array[i] is the number of influences
* of variable i.
* correct actual measures through adding influences from
* neighbor processors
*----------------------------------------------------------*/
measure_array_master = hypre_CTAlloc(HYPRE_Int, num_variables);
measure_array = hypre_CTAlloc(HYPRE_Int, num_variables);
for (i = 0; i < num_variables; i++)
{
measure_array_master[i] = ST_i[i+1]-ST_i[i];
}
if ((measure_type || (coarsen_type != 1 && coarsen_type != 11))
&& num_procs > 1)
{
if (use_commpkg_A)
S_ext = hypre_ParCSRMatrixExtractBExt(S,A,0);
else
S_ext = hypre_ParCSRMatrixExtractBExt(S,S,0);
S_ext_i = hypre_CSRMatrixI(S_ext);
S_ext_j = hypre_CSRMatrixJ(S_ext);
num_nonzeros = S_ext_i[num_cols_offd];
first_col = hypre_ParCSRMatrixFirstColDiag(S);
col_0 = first_col-1;
col_n = col_0+num_variables;
if (measure_type)
{
for (i=0; i < num_nonzeros; i++)
{
index = S_ext_j[i] - first_col;
if (index > -1 && index < num_variables)
measure_array_master[index]++;
}
}
}
/*---------------------------------------------------
* Loop until all points are either fine or coarse.
*---------------------------------------------------*/
if (debug_flag == 3) wall_time = time_getWallclockSeconds();
/* first coarsening phase */
/*************************************************************
*
* Initialize the lists
*
*************************************************************/
CF_marker = hypre_CTAlloc(HYPRE_Int, num_variables);
num_left = 0;
for (j = 0; j < num_variables; j++)
{
if ((S_i[j+1]-S_i[j])== 0 &&
(S_offd_i[j+1]-S_offd_i[j]) == 0)
{
CF_marker[j] = SF_PT;
measure_array_master[j] = 0;
}
else
{
CF_marker[j] = UNDECIDED;
/* num_left++; */ /* BM May 19, 2006: see below*/
}
}
if (coarsen_type==22) {
/* BM Sep 8, 2006: allow_emptygrids only if the following holds for all points j:
(a) the point has no strong connections at all, OR
(b) the point has a strong connection across a boundary */
for (j=0;j<num_variables;j++)
if (S_i[j+1]>S_i[j] && S_offd_i[j+1] == S_offd_i[j]) {coarsen_type=21;break;}
}
for (l = 1; l <= cgc_its; l++)
{
LoL_head = NULL;
LoL_tail = NULL;
num_left = 0; /* compute num_left before each RS coarsening loop */
memcpy (measure_array,measure_array_master,num_variables*sizeof(HYPRE_Int));
memset (lists,0,sizeof(HYPRE_Int)*num_variables);
memset (where,0,sizeof(HYPRE_Int)*num_variables);
for (j = 0; j < num_variables; j++)
{
measure = measure_array[j];
if (CF_marker[j] != SF_PT)
{
if (measure > 0)
{
enter_on_lists(&LoL_head, &LoL_tail, measure, j, lists, where);
num_left++; /* compute num_left before each RS coarsening loop */
}
else if (CF_marker[j] == 0) /* increase weight of strongly coupled neighbors only
if j is not conained in a previously constructed coarse grid.
Reason: these neighbors should start with the same initial weight
in each CGC iteration. BM Aug 30, 2006 */
{
if (measure < 0) hypre_printf("negative measure!\n");
/* CF_marker[j] = f_pnt; */
for (k = S_i[j]; k < S_i[j+1]; k++)
{
nabor = S_j[k];
/* if (CF_marker[nabor] != SF_PT) */
if (CF_marker[nabor] == 0) /* BM Aug 30, 2006: don't alter weights of points
contained in other candidate coarse grids */
{
if (nabor < j)
{
new_meas = measure_array[nabor];
if (new_meas > 0)
remove_point(&LoL_head, &LoL_tail, new_meas,
nabor, lists, where);
else num_left++; /* BM Aug 29, 2006 */
new_meas = ++(measure_array[nabor]);
enter_on_lists(&LoL_head, &LoL_tail, new_meas,
nabor, lists, where);
}
else
{
new_meas = ++(measure_array[nabor]);
}
}
}
/* --num_left; */ /* BM May 19, 2006 */
}
}
}
/* BM Aug 30, 2006: first iteration: determine maximal weight */
if (num_left && l==1) measure_max = measure_array[LoL_head->head];
/* BM Aug 30, 2006: break CGC iteration if no suitable
starting point is available any more */
if (!num_left || measure_array[LoL_head->head]<measure_max) {
while (LoL_head) {
hypre_LinkList list_ptr = LoL_head;
LoL_head = LoL_head->next_elt;
dispose_elt (list_ptr);
}
break;
}
/****************************************************************
*
* Main loop of Ruge-Stueben first coloring pass.
*
* WHILE there are still points to classify DO:
* 1) find first point, i, on list with max_measure
* make i a C-point, remove it from the lists
* 2) For each point, j, in S_i^T,
* a) Set j to be an F-point
* b) For each point, k, in S_j
* move k to the list in LoL with measure one
* greater than it occupies (creating new LoL
* entry if necessary)
* 3) For each point, j, in S_i,
* move j to the list in LoL with measure one
* smaller than it occupies (creating new LoL
* entry if necessary)
*
****************************************************************/
while (num_left > 0)
{
index = LoL_head -> head;
/* index = LoL_head -> tail; */
/* CF_marker[index] = C_PT; */
CF_marker[index] = l; /* BM Aug 18, 2006 */
measure = measure_array[index];
measure_array[index] = 0;
measure_array_master[index] = 0; /* BM May 19: for CGC */
--num_left;
remove_point(&LoL_head, &LoL_tail, measure, index, lists, where);
for (j = ST_i[index]; j < ST_i[index+1]; j++)
{
nabor = ST_j[j];
/* if (CF_marker[nabor] == UNDECIDED) */
if (measure_array[nabor]>0) /* undecided point */
{
/* CF_marker[nabor] = F_PT; */ /* BM Aug 18, 2006 */
measure = measure_array[nabor];
measure_array[nabor]=0;
remove_point(&LoL_head, &LoL_tail, measure, nabor, lists, where);
--num_left;
for (k = S_i[nabor]; k < S_i[nabor+1]; k++)
{
nabor_two = S_j[k];
/* if (CF_marker[nabor_two] == UNDECIDED) */
if (measure_array[nabor_two]>0) /* undecided point */
{
measure = measure_array[nabor_two];
remove_point(&LoL_head, &LoL_tail, measure,
nabor_two, lists, where);
new_meas = ++(measure_array[nabor_two]);
enter_on_lists(&LoL_head, &LoL_tail, new_meas,
nabor_two, lists, where);
}
}
}
}
for (j = S_i[index]; j < S_i[index+1]; j++)
{
nabor = S_j[j];
/* if (CF_marker[nabor] == UNDECIDED) */
if (measure_array[nabor]>0) /* undecided point */
{
measure = measure_array[nabor];
remove_point(&LoL_head, &LoL_tail, measure, nabor, lists, where);
measure_array[nabor] = --measure;
if (measure > 0)
enter_on_lists(&LoL_head, &LoL_tail, measure, nabor,
lists, where);
else
{
/* CF_marker[nabor] = F_PT; */ /* BM Aug 18, 2006 */
--num_left;
for (k = S_i[nabor]; k < S_i[nabor+1]; k++)
{
nabor_two = S_j[k];
/* if (CF_marker[nabor_two] == UNDECIDED) */
if (measure_array[nabor_two]>0)
{
new_meas = measure_array[nabor_two];
remove_point(&LoL_head, &LoL_tail, new_meas,
nabor_two, lists, where);
new_meas = ++(measure_array[nabor_two]);
enter_on_lists(&LoL_head, &LoL_tail, new_meas,
nabor_two, lists, where);
}
}
}
}
}
}
if (LoL_head) hypre_printf ("Linked list not empty! head: %d\n",LoL_head->head);
}
l--; /* BM Aug 15, 2006 */
hypre_TFree(measure_array);
hypre_TFree(measure_array_master);
hypre_CSRMatrixDestroy(ST);
if (debug_flag == 3)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Coarsen 1st pass = %f\n",
my_id, wall_time);
}
hypre_TFree(lists);
hypre_TFree(where);
if (num_procs>1) {
if (debug_flag == 3) wall_time = time_getWallclockSeconds();
hypre_BoomerAMGCoarsenCGC (S,l,coarsen_type,CF_marker);
if (debug_flag == 3) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Coarsen CGC = %f\n",
my_id, wall_time);
}
}
else {
/* the first candiate coarse grid is the coarse grid */
for (j=0;j<num_variables;j++) {
if (CF_marker[j]==1) CF_marker[j]=C_PT;
else CF_marker[j]=F_PT;
}
}
/* BM May 19, 2006:
Set all undecided points to be fine grid points. */
for (j=0;j<num_variables;j++)
if (!CF_marker[j]) CF_marker[j]=F_PT;
/*---------------------------------------------------
* Initialize the graph array
*---------------------------------------------------*/
graph_array = hypre_CTAlloc(HYPRE_Int, num_variables);
for (i = 0; i < num_variables; i++)
{
graph_array[i] = -1;
}
if (debug_flag == 3) wall_time = time_getWallclockSeconds();
for (i=0; i < num_variables; i++)
{
if (ci_tilde_mark != i) ci_tilde = -1;
if (CF_marker[i] == -1)
{
for (ji = S_i[i]; ji < S_i[i+1]; ji++)
{
j = S_j[ji];
if (CF_marker[j] > 0)
graph_array[j] = i;
}
for (ji = S_i[i]; ji < S_i[i+1]; ji++)
{
j = S_j[ji];
if (CF_marker[j] == -1)
{
set_empty = 1;
for (jj = S_i[j]; jj < S_i[j+1]; jj++)
{
index = S_j[jj];
if (graph_array[index] == i)
{
set_empty = 0;
break;
}
}
if (set_empty)
{
if (C_i_nonempty)
{
CF_marker[i] = 1;
if (ci_tilde > -1)
{
CF_marker[ci_tilde] = -1;
ci_tilde = -1;
}
C_i_nonempty = 0;
break;
}
else
{
ci_tilde = j;
ci_tilde_mark = i;
CF_marker[j] = 1;
C_i_nonempty = 1;
i--;
break;
}
}
}
}
}
}
if (debug_flag == 3 && coarsen_type != 2)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d Coarsen 2nd pass = %f\n",
my_id, wall_time);
}
/* third pass, check boundary fine points for coarse neighbors */
/*------------------------------------------------
* Exchange boundary data for CF_marker
*------------------------------------------------*/
if (debug_flag == 3) wall_time = time_getWallclockSeconds();
CF_marker_offd = hypre_CTAlloc(HYPRE_Int, num_cols_offd);
int_buf_data = hypre_CTAlloc(HYPRE_Int, hypre_ParCSRCommPkgSendMapStart(comm_pkg,
num_sends));
index = 0;
for (i = 0; i < num_sends; i++)
{
start = hypre_ParCSRCommPkgSendMapStart(comm_pkg, i);
for (j = start; j < hypre_ParCSRCommPkgSendMapStart(comm_pkg, i+1); j++)
int_buf_data[index++]
= CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
if (num_procs > 1)
{
comm_handle = hypre_ParCSRCommHandleCreate(11, comm_pkg, int_buf_data,
CF_marker_offd);
hypre_ParCSRCommHandleDestroy(comm_handle);
}
AmgCGCBoundaryFix (S,CF_marker,CF_marker_offd);
if (debug_flag == 3)
{
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf("Proc = %d CGC boundary fix = %f\n",
my_id, wall_time);
}
/*---------------------------------------------------
* Clean up and return
*---------------------------------------------------*/
/*if (coarsen_type != 1)
{ */
if (CF_marker_offd) hypre_TFree(CF_marker_offd); /* BM Aug 21, 2006 */
if (int_buf_data) hypre_TFree(int_buf_data); /* BM Aug 21, 2006 */
/*if (ci_array) hypre_TFree(ci_array);*/ /* BM Aug 21, 2006 */
/*} */
hypre_TFree(graph_array);
if ((measure_type || (coarsen_type != 1 && coarsen_type != 11))
&& num_procs > 1)
hypre_CSRMatrixDestroy(S_ext);
*CF_marker_ptr = CF_marker;
return (ierr);
}
/* begin Bram added */
HYPRE_Int hypre_BoomerAMGCoarsenCGC (hypre_ParCSRMatrix *S,HYPRE_Int numberofgrids,HYPRE_Int coarsen_type,HYPRE_Int *CF_marker)
/* CGC algorithm
* ====================================================================================================
* coupling : the strong couplings
* numberofgrids : the number of grids
* coarsen_type : the coarsening type
* gridpartition : the grid partition
* =====================================================================================================*/
{
HYPRE_Int j,/*p,*/mpisize,mpirank,/*rstart,rend,*/choice,*coarse,ierr=0;
HYPRE_Int *vertexrange = NULL;
HYPRE_Int *vertexrange_all = NULL;
HYPRE_Int *CF_marker_offd = NULL;
HYPRE_Int num_variables = hypre_CSRMatrixNumRows (hypre_ParCSRMatrixDiag(S));
/* HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols (hypre_ParCSRMatrixOffd (S)); */
/* HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd (S); */
/* HYPRE_Real wall_time; */
HYPRE_IJMatrix ijG;
hypre_ParCSRMatrix *G;
hypre_CSRMatrix *Gseq;
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_MPI_Comm_size (comm,&mpisize);
hypre_MPI_Comm_rank (comm,&mpirank);
#if 0
if (!mpirank) {
wall_time = time_getWallclockSeconds();
hypre_printf ("Starting CGC preparation\n");
}
#endif
AmgCGCPrepare (S,numberofgrids,CF_marker,&CF_marker_offd,coarsen_type,&vertexrange);
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf ("Finished CGC preparation, wall_time = %f s\n",wall_time);
wall_time = time_getWallclockSeconds();
hypre_printf ("Starting CGC matrix assembly\n");
}
#endif
AmgCGCGraphAssemble (S,vertexrange,CF_marker,CF_marker_offd,coarsen_type,&ijG);
#if 0
HYPRE_IJMatrixPrint (ijG,"graph.txt");
#endif
HYPRE_IJMatrixGetObject (ijG,(void**)&G);
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf ("Finished CGC matrix assembly, wall_time = %f s\n",wall_time);
wall_time = time_getWallclockSeconds();
hypre_printf ("Starting CGC matrix communication\n");
}
#endif
#ifdef HYPRE_NO_GLOBAL_PARTITION
{
/* classical CGC does not really make sense in combination with HYPRE_NO_GLOBAL_PARTITION,
but anyway, here it is:
*/
HYPRE_Int nlocal = vertexrange[1]-vertexrange[0];
vertexrange_all = hypre_CTAlloc (HYPRE_Int,mpisize+1);
hypre_MPI_Allgather (&nlocal,1,HYPRE_MPI_INT,vertexrange_all+1,1,HYPRE_MPI_INT,comm);
vertexrange_all[0]=0;
for (j=2;j<=mpisize;j++) vertexrange_all[j]+=vertexrange_all[j-1];
}
#else
vertexrange_all = vertexrange;
#endif
Gseq = hypre_ParCSRMatrixToCSRMatrixAll (G);
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf ("Finished CGC matrix communication, wall_time = %f s\n",wall_time);
}
#endif
if (Gseq) { /* BM Aug 31, 2006: Gseq==NULL if G has no local rows */
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds();
hypre_printf ("Starting CGC election\n");
}
#endif
AmgCGCChoose (Gseq,vertexrange_all,mpisize,&coarse);
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf ("Finished CGC election, wall_time = %f s\n",wall_time);
}
#endif
#if 0 /* debugging */
if (!mpirank) {
for (j=0;j<mpisize;j++)
hypre_printf ("Processor %d, choice = %d of range %d - %d\n",j,coarse[j],vertexrange_all[j]+1,vertexrange_all[j+1]);
}
fflush(stdout);
#endif
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds();
hypre_printf ("Starting CGC CF assignment\n");
}
#endif
choice = coarse[mpirank];
for (j=0;j<num_variables;j++) {
if (CF_marker[j]==choice)
CF_marker[j] = C_PT;
else
CF_marker[j] = F_PT;
}
hypre_CSRMatrixDestroy (Gseq);
hypre_TFree (coarse);
}
else
for (j=0;j<num_variables;j++) CF_marker[j] = F_PT;
#if 0
if (!mpirank) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf ("Finished CGC CF assignment, wall_time = %f s\n",wall_time);
}
#endif
#if 0 /* debugging */
if (!mpirank) {
wall_time = time_getWallclockSeconds();
hypre_printf ("Starting CGC cleanup\n");
}
#endif
HYPRE_IJMatrixDestroy (ijG);
hypre_TFree (vertexrange);
#ifdef HYPRE_NO_GLOBAL_PARTITION
hypre_TFree (vertexrange_all);
#endif
hypre_TFree (CF_marker_offd);
#if 0
if (!mpirank) {
wall_time = time_getWallclockSeconds() - wall_time;
hypre_printf ("Finished CGC cleanup, wall_time = %f s\n",wall_time);
}
#endif
return(ierr);
}
HYPRE_Int AmgCGCPrepare (hypre_ParCSRMatrix *S,HYPRE_Int nlocal,HYPRE_Int *CF_marker,HYPRE_Int **CF_marker_offd,HYPRE_Int coarsen_type,HYPRE_Int **vrange)
/* assemble a graph representing the connections between the grids
* ================================================================================================
* S : the strength matrix
* nlocal : the number of locally created coarse grids
* CF_marker, CF_marker_offd : the coare/fine markers
* coarsen_type : the coarsening type
* vrange : the ranges of the vertices representing coarse grids
* ================================================================================================*/
{
HYPRE_Int ierr=0;
HYPRE_Int mpisize,mpirank;
HYPRE_Int num_sends;
HYPRE_Int *vertexrange=NULL;
HYPRE_Int vstart,vend;
HYPRE_Int *int_buf_data;
HYPRE_Int start;
HYPRE_Int i,ii,j;
HYPRE_Int num_variables = hypre_CSRMatrixNumRows (hypre_ParCSRMatrixDiag(S));
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols (hypre_ParCSRMatrixOffd (S));
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
/* hypre_MPI_Status status; */
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg (S);
hypre_ParCSRCommHandle *comm_handle;
hypre_MPI_Comm_size (comm,&mpisize);
hypre_MPI_Comm_rank (comm,&mpirank);
if (!comm_pkg) {
hypre_MatvecCommPkgCreate (S);
comm_pkg = hypre_ParCSRMatrixCommPkg (S);
}
num_sends = hypre_ParCSRCommPkgNumSends (comm_pkg);
if (coarsen_type % 2 == 0) nlocal++; /* even coarsen_type means allow_emptygrids */
#ifdef HYPRE_NO_GLOBAL_PARTITION
{
HYPRE_Int scan_recv;
vertexrange = hypre_CTAlloc(HYPRE_Int,2);
hypre_MPI_Scan(&nlocal, &scan_recv, 1, HYPRE_MPI_INT, hypre_MPI_SUM, comm);
/* first point in my range */
vertexrange[0] = scan_recv - nlocal;
/* first point in next proc's range */
vertexrange[1] = scan_recv;
vstart = vertexrange[0];
vend = vertexrange[1];
}
#else
vertexrange = hypre_CTAlloc (HYPRE_Int,mpisize+1);
hypre_MPI_Allgather (&nlocal,1,HYPRE_MPI_INT,vertexrange+1,1,HYPRE_MPI_INT,comm);
vertexrange[0]=0;
for (i=2;i<=mpisize;i++) vertexrange[i]+=vertexrange[i-1];
vstart = vertexrange[mpirank];
vend = vertexrange[mpirank+1];
#endif
/* Note: vstart uses 0-based indexing, while CF_marker uses 1-based indexing */
if (coarsen_type % 2 == 1) { /* see above */
for (i=0;i<num_variables;i++)
if (CF_marker[i]>0)
CF_marker[i]+=vstart;
}
else {
/* hypre_printf ("processor %d: empty grid allowed\n",mpirank); */
for (i=0;i<num_variables;i++) {
if (CF_marker[i]>0)
CF_marker[i]+=vstart+1; /* add one because vertexrange[mpirank]+1 denotes the empty grid.
Hence, vertexrange[mpirank]+2 is the first coarse grid denoted in
global indices, ... */
}
}
/* exchange data */
*CF_marker_offd = hypre_CTAlloc (HYPRE_Int,num_cols_offd);
int_buf_data = hypre_CTAlloc (HYPRE_Int,hypre_ParCSRCommPkgSendMapStart (comm_pkg,num_sends));
for (i=0,ii=0;i<num_sends;i++) {
start = hypre_ParCSRCommPkgSendMapStart (comm_pkg,i);
for (j=start;j<hypre_ParCSRCommPkgSendMapStart (comm_pkg,i+1);j++)
int_buf_data [ii++] = CF_marker[hypre_ParCSRCommPkgSendMapElmt(comm_pkg,j)];
}
if (mpisize>1) {
comm_handle = hypre_ParCSRCommHandleCreate (11,comm_pkg,int_buf_data,*CF_marker_offd);
hypre_ParCSRCommHandleDestroy (comm_handle);
}
hypre_TFree (int_buf_data);
*vrange=vertexrange;
return (ierr);
}
#define tag_pointrange 301
#define tag_vertexrange 302
HYPRE_Int AmgCGCGraphAssemble (hypre_ParCSRMatrix *S,HYPRE_Int *vertexrange,HYPRE_Int *CF_marker,HYPRE_Int *CF_marker_offd,HYPRE_Int coarsen_type,
HYPRE_IJMatrix *ijG)
/* assemble a graph representing the connections between the grids
* ================================================================================================
* S : the strength matrix
* vertexrange : the parallel layout of the candidate coarse grid vertices
* CF_marker, CF_marker_offd : the coarse/fine markers
* coarsen_type : the coarsening type
* ijG : the created graph
* ================================================================================================*/
{
HYPRE_Int ierr=0;
HYPRE_Int i,/* ii,*/ip,j,jj,m,n,p;
HYPRE_Int mpisize,mpirank;
HYPRE_Real weight;
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
/* hypre_MPI_Status status; */
HYPRE_IJMatrix ijmatrix;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag (S);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd (S);
/* HYPRE_Int *S_i = hypre_CSRMatrixI(S_diag); */
/* HYPRE_Int *S_j = hypre_CSRMatrixJ(S_diag); */
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = NULL;
HYPRE_Int num_variables = hypre_CSRMatrixNumRows (S_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols (S_offd);
HYPRE_Int *col_map_offd = hypre_ParCSRMatrixColMapOffd (S);
HYPRE_Int pointrange_start,pointrange_end;
HYPRE_Int *pointrange,*pointrange_nonlocal,*pointrange_strong=NULL;
HYPRE_Int vertexrange_start,vertexrange_end;
HYPRE_Int *vertexrange_strong= NULL;
HYPRE_Int *vertexrange_nonlocal;
HYPRE_Int num_recvs,num_recvs_strong;
HYPRE_Int *recv_procs,*recv_procs_strong=NULL;
HYPRE_Int /* *zeros,*rownz,*/*rownz_diag,*rownz_offd;
HYPRE_Int nz;
HYPRE_Int nlocal;
HYPRE_Int one=1;
hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg (S);
hypre_MPI_Comm_size (comm,&mpisize);
hypre_MPI_Comm_rank (comm,&mpirank);
/* determine neighbor processors */
num_recvs = hypre_ParCSRCommPkgNumRecvs (comm_pkg);
recv_procs = hypre_ParCSRCommPkgRecvProcs (comm_pkg);
pointrange = hypre_ParCSRMatrixRowStarts (S);
pointrange_nonlocal = hypre_CTAlloc (HYPRE_Int, 2*num_recvs);
vertexrange_nonlocal = hypre_CTAlloc (HYPRE_Int, 2*num_recvs);
#ifdef HYPRE_NO_GLOBAL_PARTITION
{
HYPRE_Int num_sends = hypre_ParCSRCommPkgNumSends (comm_pkg);
HYPRE_Int *send_procs = hypre_ParCSRCommPkgSendProcs (comm_pkg);
HYPRE_Int *int_buf_data = hypre_CTAlloc (HYPRE_Int,4*num_sends);
HYPRE_Int *int_buf_data2 = int_buf_data + 2*num_sends;
hypre_MPI_Request *sendrequest,*recvrequest;
nlocal = vertexrange[1] - vertexrange[0];
pointrange_start = pointrange[0];
pointrange_end = pointrange[1];
vertexrange_start = vertexrange[0];
vertexrange_end = vertexrange[1];
sendrequest = hypre_CTAlloc (hypre_MPI_Request,2*(num_sends+num_recvs));
recvrequest = sendrequest+2*num_sends;
for (i=0;i<num_recvs;i++) {
hypre_MPI_Irecv (pointrange_nonlocal+2*i,2,HYPRE_MPI_INT,recv_procs[i],tag_pointrange,comm,&recvrequest[2*i]);
hypre_MPI_Irecv (vertexrange_nonlocal+2*i,2,HYPRE_MPI_INT,recv_procs[i],tag_vertexrange,comm,&recvrequest[2*i+1]);
}
for (i=0;i<num_sends;i++) {
int_buf_data[2*i] = pointrange_start;
int_buf_data[2*i+1] = pointrange_end;
int_buf_data2[2*i] = vertexrange_start;
int_buf_data2[2*i+1] = vertexrange_end;
hypre_MPI_Isend (int_buf_data+2*i,2,HYPRE_MPI_INT,send_procs[i],tag_pointrange,comm,&sendrequest[2*i]);
hypre_MPI_Isend (int_buf_data2+2*i,2,HYPRE_MPI_INT,send_procs[i],tag_vertexrange,comm,&sendrequest[2*i+1]);
}
hypre_MPI_Waitall (2*(num_sends+num_recvs),sendrequest,hypre_MPI_STATUSES_IGNORE);
hypre_TFree (int_buf_data);
hypre_TFree (sendrequest);
}
#else
nlocal = vertexrange[mpirank+1] - vertexrange[mpirank];
pointrange_start = pointrange[mpirank];
pointrange_end = pointrange[mpirank+1];
vertexrange_start = vertexrange[mpirank];
vertexrange_end = vertexrange[mpirank+1];
for (i=0;i<num_recvs;i++) {
pointrange_nonlocal[2*i] = pointrange[recv_procs[i]];
pointrange_nonlocal[2*i+1] = pointrange[recv_procs[i]+1];
vertexrange_nonlocal[2*i] = vertexrange[recv_procs[i]];
vertexrange_nonlocal[2*i+1] = vertexrange[recv_procs[i]+1];
}
#endif
/* now we have the array recv_procs. However, it may contain too many entries as it is
inherited from A. We now have to determine the subset which contains only the
strongly connected neighbors */
if (num_cols_offd) {
S_offd_j = hypre_CSRMatrixJ(S_offd);
recv_procs_strong = hypre_CTAlloc (HYPRE_Int,num_recvs);
memset (recv_procs_strong,0,num_recvs*sizeof(HYPRE_Int));
/* don't forget to shorten the pointrange and vertexrange arrays accordingly */
pointrange_strong = hypre_CTAlloc (HYPRE_Int,2*num_recvs);
memset (pointrange_strong,0,2*num_recvs*sizeof(HYPRE_Int));
vertexrange_strong = hypre_CTAlloc (HYPRE_Int,2*num_recvs);
memset (vertexrange_strong,0,2*num_recvs*sizeof(HYPRE_Int));
for (i=0;i<num_variables;i++)
for (j=S_offd_i[i];j<S_offd_i[i+1];j++) {
jj = col_map_offd[S_offd_j[j]];
for (p=0;p<num_recvs;p++) /* S_offd_j is NOT sorted! */
if (jj >= pointrange_nonlocal[2*p] && jj < pointrange_nonlocal[2*p+1]) break;
#if 0
hypre_printf ("Processor %d, remote point %d on processor %d\n",mpirank,jj,recv_procs[p]);
#endif
recv_procs_strong [p]=1;
}
for (p=0,num_recvs_strong=0;p<num_recvs;p++) {
if (recv_procs_strong[p]) {
recv_procs_strong[num_recvs_strong]=recv_procs[p];
pointrange_strong[2*num_recvs_strong] = pointrange_nonlocal[2*p];
pointrange_strong[2*num_recvs_strong+1] = pointrange_nonlocal[2*p+1];
vertexrange_strong[2*num_recvs_strong] = vertexrange_nonlocal[2*p];
vertexrange_strong[2*num_recvs_strong+1] = vertexrange_nonlocal[2*p+1];
num_recvs_strong++;
}
}
}
else num_recvs_strong=0;
hypre_TFree (pointrange_nonlocal);
hypre_TFree (vertexrange_nonlocal);
rownz_diag = hypre_CTAlloc (HYPRE_Int,2*nlocal);
rownz_offd = rownz_diag + nlocal;
for (p=0,nz=0;p<num_recvs_strong;p++) {
nz += vertexrange_strong[2*p+1]-vertexrange_strong[2*p];
}
for (m=0;m<nlocal;m++) {
rownz_diag[m]=nlocal-1;
rownz_offd[m]=nz;
}
HYPRE_IJMatrixCreate(comm, vertexrange_start, vertexrange_end-1, vertexrange_start, vertexrange_end-1, &ijmatrix);
HYPRE_IJMatrixSetObjectType(ijmatrix, HYPRE_PARCSR);
HYPRE_IJMatrixSetDiagOffdSizes (ijmatrix, rownz_diag, rownz_offd);
HYPRE_IJMatrixInitialize(ijmatrix);
hypre_TFree (rownz_diag);
/* initialize graph */
weight = -1;
for (m=vertexrange_start;m<vertexrange_end;m++) {
for (p=0;p<num_recvs_strong;p++) {
for (n=vertexrange_strong[2*p];n<vertexrange_strong[2*p+1];n++) {
ierr = HYPRE_IJMatrixAddToValues (ijmatrix,1,&one,&m,&n,&weight);
#if 0
if (ierr) hypre_printf ("Processor %d: error %d while initializing graphs at (%d, %d)\n",mpirank,ierr,m,n);
#endif
}
}
}
/* weight graph */
for (i=0;i<num_variables;i++) {
for (j=S_offd_i[i];j<S_offd_i[i+1];j++) {
jj = S_offd_j[j]; /* jj is not a global index!!! */
/* determine processor */
for (p=0;p<num_recvs_strong;p++)
if (col_map_offd[jj] >= pointrange_strong[2*p] && col_map_offd[jj] < pointrange_strong[2*p+1]) break;
ip=recv_procs_strong[p];
/* loop over all coarse grids constructed on this processor domain */
for (m=vertexrange_start;m<vertexrange_end;m++) {
/* loop over all coarse grids constructed on neighbor processor domain */
for (n=vertexrange_strong[2*p];n<vertexrange_strong[2*p+1];n++) {
/* coarse grid counting inside gridpartition->local/gridpartition->nonlocal starts with one
while counting inside range starts with zero */
if (CF_marker[i]-1==m && CF_marker_offd[jj]-1==n)
/* C-C-coupling */
weight = -1;
else if ( (CF_marker[i]-1==m && (CF_marker_offd[jj]==0 || CF_marker_offd[jj]-1!=n) )
|| ( (CF_marker[i]==0 || CF_marker[i]-1!=m) && CF_marker_offd[jj]-1==n ) )
/* C-F-coupling */
weight = 0;
else weight = -8; /* F-F-coupling */
ierr = HYPRE_IJMatrixAddToValues (ijmatrix,1,&one,&m,&n,&weight);
#if 0
if (ierr) hypre_printf ("Processor %d: error %d while adding %lf to entry (%d, %d)\n",mpirank,ierr,weight,m,n);
#endif
}
}
}
}
/* assemble */
HYPRE_IJMatrixAssemble (ijmatrix);
/*if (num_recvs_strong) {*/
hypre_TFree (recv_procs_strong);
hypre_TFree (pointrange_strong);
hypre_TFree (vertexrange_strong);
/*} */
*ijG = ijmatrix;
return (ierr);
}
HYPRE_Int AmgCGCChoose (hypre_CSRMatrix *G,HYPRE_Int *vertexrange,HYPRE_Int mpisize,HYPRE_Int **coarse)
/* chooses one grid for every processor
* ============================================================
* G : the connectivity graph
* map : the parallel layout
* mpisize : number of procs
* coarse : the chosen coarse grids
* ===========================================================*/
{
HYPRE_Int i,j,jj,p,choice,*processor,ierr=0;
HYPRE_Int measure,new_measure;
/* MPI_Comm comm = hypre_ParCSRMatrixComm(G); */
/* hypre_ParCSRCommPkg *comm_pkg = hypre_ParCSRMatrixCommPkg (G); */
/* hypre_ParCSRCommHandle *comm_handle; */
HYPRE_Real *G_data = hypre_CSRMatrixData (G);
HYPRE_Real max;
HYPRE_Int *G_i = hypre_CSRMatrixI(G);
HYPRE_Int *G_j = hypre_CSRMatrixJ(G);
hypre_CSRMatrix *H,*HT;
HYPRE_Int *H_i,*H_j,*HT_i,*HT_j;
HYPRE_Int jG,jH;
HYPRE_Int num_vertices = hypre_CSRMatrixNumRows (G);
HYPRE_Int *measure_array;
HYPRE_Int *lists,*where;
hypre_LinkList LoL_head = NULL;
hypre_LinkList LoL_tail = NULL;
processor = hypre_CTAlloc (HYPRE_Int,num_vertices);
*coarse = hypre_CTAlloc (HYPRE_Int,mpisize);
memset (*coarse,0,sizeof(HYPRE_Int)*mpisize);
measure_array = hypre_CTAlloc (HYPRE_Int,num_vertices);
lists = hypre_CTAlloc (HYPRE_Int,num_vertices);
where = hypre_CTAlloc (HYPRE_Int,num_vertices);
/* for (p=0;p<mpisize;p++) hypre_printf ("%d: %d-%d\n",p,range[p]+1,range[p+1]); */
/******************************************************************
* determine heavy edges
******************************************************************/
jG = G_i[num_vertices];
H = hypre_CSRMatrixCreate (num_vertices,num_vertices,jG);
H_i = hypre_CTAlloc (HYPRE_Int,num_vertices+1);
H_j = hypre_CTAlloc (HYPRE_Int,jG);
hypre_CSRMatrixI(H) = H_i;
hypre_CSRMatrixJ(H) = H_j;
for (i=0,p=0;i<num_vertices;i++) {
while (vertexrange[p+1]<=i) p++;
processor[i]=p;
}
H_i[0]=0;
for (i=0,jj=0;i<num_vertices;i++) {
#if 0
hypre_printf ("neighbors of grid %d:",i);
#endif
H_i[i+1]=H_i[i];
for (j=G_i[i],choice=-1,max=0;j<G_i[i+1];j++) {
#if 0
if (G_data[j]>=0.0)
hypre_printf ("G[%d,%d]=0. G_j(j)=%d, G_data(j)=%f.\n",i,G_j[j],j,G_data[j]);
#endif
/* G_data is always negative, so this test is sufficient */
if (choice==-1 || G_data[j]>max) {
choice = G_j[j];
max = G_data[j];
}
if (j==G_i[i+1]-1 || processor[G_j[j+1]] > processor[choice]) {
/* we are done for this processor boundary */
H_j[jj++]=choice;
H_i[i+1]++;
#if 0
hypre_printf (" %d",choice);
#endif
choice = -1; max=0;
}
}
#if 0
hypre_printf("\n");
#endif
}
/******************************************************************
* compute H^T, the transpose of H
******************************************************************/
jH = H_i[num_vertices];
HT = hypre_CSRMatrixCreate (num_vertices,num_vertices,jH);
HT_i = hypre_CTAlloc (HYPRE_Int,num_vertices+1);
HT_j = hypre_CTAlloc (HYPRE_Int,jH);
hypre_CSRMatrixI(HT) = HT_i;
hypre_CSRMatrixJ(HT) = HT_j;
for (i=0; i <= num_vertices; i++)
HT_i[i] = 0;
for (i=0; i < jH; i++) {
HT_i[H_j[i]+1]++;
}
for (i=0; i < num_vertices; i++) {
HT_i[i+1] += HT_i[i];
}
for (i=0; i < num_vertices; i++) {
for (j=H_i[i]; j < H_i[i+1]; j++) {
HYPRE_Int myindex = H_j[j];
HT_j[HT_i[myindex]] = i;
HT_i[myindex]++;
}
}
for (i = num_vertices; i > 0; i--) {
HT_i[i] = HT_i[i-1];
}
HT_i[0] = 0;
/*****************************************************************
* set initial vertex weights
*****************************************************************/
for (i=0;i<num_vertices;i++) {
measure_array[i] = H_i[i+1] - H_i[i] + HT_i[i+1] - HT_i[i];
enter_on_lists (&LoL_head,&LoL_tail,measure_array[i],i,lists,where);
}
/******************************************************************
* apply CGC iteration
******************************************************************/
while (LoL_head && measure_array[LoL_head->head]) {
choice = LoL_head->head;
measure = measure_array[choice];
#if 0
hypre_printf ("Choice: %d, measure %d, processor %d\n",choice, measure,processor[choice]);
fflush(stdout);
#endif
(*coarse)[processor[choice]] = choice+1; /* add one because coarsegrid indexing starts with 1, not 0 */
/* new maximal weight */
new_measure = measure+1;
for (i=vertexrange[processor[choice]];i<vertexrange[processor[choice]+1];i++) {
/* set weights for all remaining vertices on this processor to zero */
measure = measure_array[i];
remove_point (&LoL_head,&LoL_tail,measure,i,lists,where);
measure_array[i]=0;
}
for (j=H_i[choice];j<H_i[choice+1];j++){
jj = H_j[j];
/* if no vertex is chosen on this proc, set weights of all heavily coupled vertices to max1 */
if (!(*coarse)[processor[jj]]) {
measure = measure_array[jj];
remove_point (&LoL_head,&LoL_tail,measure,jj,lists,where);
enter_on_lists (&LoL_head,&LoL_tail,new_measure,jj,lists,where);
measure_array[jj]=new_measure;
}
}
for (j=HT_i[choice];j<HT_i[choice+1];j++) {
jj = HT_j[j];
/* if no vertex is chosen on this proc, set weights of all heavily coupled vertices to max1 */
if (!(*coarse)[processor[jj]]) {
measure = measure_array[jj];
remove_point (&LoL_head,&LoL_tail,measure,jj,lists,where);
enter_on_lists (&LoL_head,&LoL_tail,new_measure,jj,lists,where);
measure_array[jj]=new_measure;
}
}
}
/* remove remaining list elements, if they exist. They all should have measure 0 */
while (LoL_head) {
i = LoL_head->head;
measure = measure_array[i];
#if 0
hypre_assert (measure==0);
#endif
remove_point (&LoL_head,&LoL_tail,measure,i,lists,where);
}
for (p=0;p<mpisize;p++)
/* if the algorithm has not determined a coarse vertex for this proc, simply take the last one
Do not take the first one, it might by empty! */
if (!(*coarse)[p]) {
(*coarse)[p] = vertexrange[p+1];
/* hypre_printf ("choice for processor %d: %d\n",p,range[p]+1); */
}
/********************************************
* clean up
********************************************/
hypre_CSRMatrixDestroy (H);
hypre_CSRMatrixDestroy (HT);
hypre_TFree (processor);
hypre_TFree (measure_array);
hypre_TFree (lists);
hypre_TFree (where);
return(ierr);
}
HYPRE_Int AmgCGCBoundaryFix (hypre_ParCSRMatrix *S,HYPRE_Int *CF_marker,HYPRE_Int *CF_marker_offd)
/* Checks whether an interpolation is possible for a fine grid point with strong couplings.
* Required after CGC coarsening
* ========================================================================================
* S : the strength matrix
* CF_marker, CF_marker_offd : the coarse/fine markers
* ========================================================================================*/
{
HYPRE_Int mpirank,i,j,has_c_pt,ierr=0;
hypre_CSRMatrix *S_diag = hypre_ParCSRMatrixDiag (S);
hypre_CSRMatrix *S_offd = hypre_ParCSRMatrixOffd (S);
HYPRE_Int *S_i = hypre_CSRMatrixI(S_diag);
HYPRE_Int *S_j = hypre_CSRMatrixJ(S_diag);
HYPRE_Int *S_offd_i = hypre_CSRMatrixI(S_offd);
HYPRE_Int *S_offd_j = NULL;
HYPRE_Int num_variables = hypre_CSRMatrixNumRows (S_diag);
HYPRE_Int num_cols_offd = hypre_CSRMatrixNumCols (S_offd);
HYPRE_Int added_cpts=0;
MPI_Comm comm = hypre_ParCSRMatrixComm(S);
hypre_MPI_Comm_rank (comm,&mpirank);
if (num_cols_offd) {
S_offd_j = hypre_CSRMatrixJ(S_offd);
}
for (i=0;i<num_variables;i++) {
if (S_offd_i[i]==S_offd_i[i+1] || CF_marker[i] == C_PT) continue;
has_c_pt=0;
/* fine grid point with strong connections across the boundary */
for (j=S_i[i];j<S_i[i+1];j++)
if (CF_marker[S_j[j]] == C_PT) {has_c_pt=1; break;}
if (has_c_pt) continue;
for (j=S_offd_i[i];j<S_offd_i[i+1];j++)
if (CF_marker_offd[S_offd_j[j]] == C_PT) {has_c_pt=1; break;}
if (has_c_pt) continue;
/* all points i is strongly coupled to are fine: make i C_PT */
CF_marker[i] = C_PT;
#if 0
hypre_printf ("Processor %d: added point %d in AmgCGCBoundaryFix\n",mpirank,i);
#endif
added_cpts++;
}
#if 0
if (added_cpts) hypre_printf ("Processor %d: added %d points in AmgCGCBoundaryFix\n",mpirank,added_cpts);
fflush(stdout);
#endif
return(ierr);
}
|
lgpl-2.1
|
Uli1/geos
|
tests/unit/io/ByteOrderValuesTest.cpp
|
2
|
4286
|
// $Id$
//
// Test Suite for geos::io::ByteOrderValues
// tut
#include <tut.hpp>
// geos
#include <geos/io/ByteOrderValues.h>
#include <geos/platform.h> // for int64
// std
#include <sstream>
#include <memory>
namespace tut
{
//
// Test Group
//
// dummy data, not used
struct test_byteordervalues_data
{
};
typedef test_group<test_byteordervalues_data> group;
typedef group::object object;
group test_byteordervalues_group("geos::io::ByteOrderValues");
//
// Test Cases
//
// 1 - Read/write an int
template<>
template<>
void object::test<1>()
{
using geos::io::ByteOrderValues;
unsigned char buf[4];
int in = 1;
int out;
ByteOrderValues::putInt(in, buf, ByteOrderValues::ENDIAN_BIG);
ensure("putInt big endian[0]", buf[0] == 0);
ensure("putInt big endian[1]", buf[1] == 0);
ensure("putInt big endian[2]", buf[2] == 0);
ensure("putInt big endian[3]", buf[3] == 1);
out = ByteOrderValues::getInt(buf,
geos::io::ByteOrderValues::ENDIAN_BIG);
ensure_equals("getInt big endian", out, in);
ByteOrderValues::putInt(1, buf, geos::io::ByteOrderValues::ENDIAN_LITTLE);
ensure("putInt little endian[0]", buf[0] == 1);
ensure("putInt little endian[1]", buf[1] == 0);
ensure("putInt little endian[2]", buf[2] == 0);
ensure("putInt little endian[3]", buf[3] == 0);
out = ByteOrderValues::getInt(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getInt little endian", out, in);
}
// 2 - Read/write a double
template<>
template<>
void object::test<2>()
{
using geos::io::ByteOrderValues;
unsigned char buf[8];
double in = 2;
double out;
ByteOrderValues::putDouble(in, buf,
ByteOrderValues::ENDIAN_BIG);
ensure("putDouble big endian[0]", buf[0] == 64);
ensure("putDouble big endian[1]", buf[1] == 0);
ensure("putDouble big endian[2]", buf[2] == 0);
ensure("putDouble big endian[3]", buf[3] == 0);
ensure("putDouble big endian[4]", buf[4] == 0);
ensure("putDouble big endian[5]", buf[5] == 0);
ensure("putDouble big endian[6]", buf[6] == 0);
ensure("putDouble big endian[7]", buf[7] == 0);
out = ByteOrderValues::getDouble(buf,
ByteOrderValues::ENDIAN_BIG);
ensure_equals("getDouble big endian", out, in);
ByteOrderValues::putDouble(in, buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure("putDouble little endian[0]", buf[0] == 0);
ensure("putDouble little endian[1]", buf[1] == 0);
ensure("putDouble little endian[2]", buf[2] == 0);
ensure("putDouble little endian[3]", buf[3] == 0);
ensure("putDouble little endian[4]", buf[4] == 0);
ensure("putDouble little endian[5]", buf[5] == 0);
ensure("putDouble little endian[6]", buf[6] == 0);
ensure("putDouble little endian[7]", buf[7] == 64);
out = ByteOrderValues::getDouble(buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure_equals("getDouble little endian", out, in);
}
// 3 - Read/write a long
template<>
template<>
void object::test<3>()
{
using geos::io::ByteOrderValues;
unsigned char buf[8];
long in = 2;
long out;
ByteOrderValues::putLong(in, buf,
ByteOrderValues::ENDIAN_BIG);
ensure("putLong big endian[0]", buf[0] == 0);
ensure("putLong big endian[1]", buf[1] == 0);
ensure("putLong big endian[2]", buf[2] == 0);
ensure("putLong big endian[3]", buf[3] == 0);
ensure("putLong big endian[4]", buf[4] == 0);
ensure("putLong big endian[5]", buf[5] == 0);
ensure("putLong big endian[6]", buf[6] == 0);
ensure("putLong big endian[7]", buf[7] == 2);
out = static_cast<long>(ByteOrderValues::getLong(buf, ByteOrderValues::ENDIAN_BIG));
ensure_equals("getLong big endian", out, in);
ByteOrderValues::putLong(in, buf,
ByteOrderValues::ENDIAN_LITTLE);
ensure("putLong little endian[0]", buf[0] == 2);
ensure("putLong little endian[1]", buf[1] == 0);
ensure("putLong little endian[2]", buf[2] == 0);
ensure("putLong little endian[3]", buf[3] == 0);
ensure("putLong little endian[4]", buf[4] == 0);
ensure("putLong little endian[5]", buf[5] == 0);
ensure("putLong little endian[6]", buf[6] == 0);
ensure("putLong little endian[7]", buf[7] == 0);
out = static_cast<long>(ByteOrderValues::getLong(buf, ByteOrderValues::ENDIAN_LITTLE));
ensure_equals("getLong little endian", out, in);
}
} // namespace tut
|
lgpl-2.1
|
xianian/qt-creator
|
src/plugins/help/centralwidget.cpp
|
3
|
2660
|
/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://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 http://www.qt.io/terms-conditions. For further information
** use the contact form at http://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, The Qt Company gives you certain additional
** rights. These rights are described in The Qt Company LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "centralwidget.h"
#include "helpviewer.h"
#include "localhelpmanager.h"
#include <utils/qtcassert.h>
using namespace Help::Internal;
CentralWidget *gStaticCentralWidget = 0;
// -- CentralWidget
CentralWidget::CentralWidget(const Core::Context &context, QWidget *parent)
: HelpWidget(context, HelpWidget::ModeWidget, parent)
{
QTC_CHECK(!gStaticCentralWidget);
gStaticCentralWidget = this;
}
CentralWidget::~CentralWidget()
{
// TODO: this shouldn't be done here
QList<float> zoomFactors;
QStringList currentPages;
for (int i = 0; i < viewerCount(); ++i) {
const HelpViewer * const viewer = viewerAt(i);
const QUrl &source = viewer->source();
if (source.isValid()) {
currentPages.append(source.toString());
zoomFactors.append(viewer->scale());
}
}
LocalHelpManager::setLastShownPages(currentPages);
LocalHelpManager::setLastShownPagesZoom(zoomFactors);
LocalHelpManager::setLastSelectedTab(currentIndex());
}
CentralWidget *CentralWidget::instance()
{
Q_ASSERT(gStaticCentralWidget);
return gStaticCentralWidget;
}
|
lgpl-2.1
|
tchx84/debian-pkg-sugar-base
|
src/sugar/_sugarbaseextmodule.c
|
3
|
1262
|
/*
* Copyright (C) 2006-2007, 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 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
/* include this first, before NO_IMPORT_PYGOBJECT is defined */
#include <pygobject.h>
extern PyMethodDef py_sugarbaseext_functions[];
DL_EXPORT(void)
init_sugarbaseext(void)
{
PyObject *m, *d;
init_pygobject ();
m = Py_InitModule ("_sugarbaseext", py_sugarbaseext_functions);
d = PyModule_GetDict (m);
if (PyErr_Occurred ()) {
Py_FatalError ("can't initialise module _sugarext");
}
}
|
lgpl-2.1
|
duythanhphan/qt-creator
|
src/libs/qmljs/parser/qmlerror.cpp
|
3
|
6966
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
****************************************************************************/
#include "qmlerror.h"
#include <QtCore/qdebug.h>
#include <QtCore/qfile.h>
#include <QtCore/qstringlist.h>
QT_BEGIN_NAMESPACE
/*!
\class QmlError
\since 5.0
\inmodule QtQml
\brief The QmlError class encapsulates a QML error.
QmlError includes a textual description of the error, as well
as location information (the file, line, and column). The toString()
method creates a single-line, human-readable string containing all of
this information, for example:
\code
file:///home/user/test.qml:7:8: Invalid property assignment: double expected
\endcode
You can use qDebug() or qWarning() to output errors to the console. This method
will attempt to open the file indicated by the error
and include additional contextual information.
\code
file:///home/user/test.qml:7:8: Invalid property assignment: double expected
y: "hello"
^
\endcode
Note that the QtQuick 1 version is named QDeclarativeError
\sa QQuickView::errors(), QmlComponent::errors()
*/
static quint16 qmlSourceCoordinate(int n)
{
return (n > 0 && n <= static_cast<int>(USHRT_MAX)) ? static_cast<quint16>(n) : 0;
}
class QmlErrorPrivate
{
public:
QmlErrorPrivate();
QUrl url;
QString description;
quint16 line;
quint16 column;
};
QmlErrorPrivate::QmlErrorPrivate()
: line(0), column(0)
{
}
/*!
Creates an empty error object.
*/
QmlError::QmlError()
: d(0)
{
}
/*!
Creates a copy of \a other.
*/
QmlError::QmlError(const QmlError &other)
: d(0)
{
*this = other;
}
/*!
Assigns \a other to this error object.
*/
QmlError &QmlError::operator=(const QmlError &other)
{
if (!other.d) {
delete d;
d = 0;
} else {
if (!d) d = new QmlErrorPrivate;
d->url = other.d->url;
d->description = other.d->description;
d->line = other.d->line;
d->column = other.d->column;
}
return *this;
}
/*!
\internal
*/
QmlError::~QmlError()
{
delete d; d = 0;
}
/*!
Returns true if this error is valid, otherwise false.
*/
bool QmlError::isValid() const
{
return d != 0;
}
/*!
Returns the url for the file that caused this error.
*/
QUrl QmlError::url() const
{
if (d) return d->url;
else return QUrl();
}
/*!
Sets the \a url for the file that caused this error.
*/
void QmlError::setUrl(const QUrl &url)
{
if (!d) d = new QmlErrorPrivate;
d->url = url;
}
/*!
Returns the error description.
*/
QString QmlError::description() const
{
if (d) return d->description;
else return QString();
}
/*!
Sets the error \a description.
*/
void QmlError::setDescription(const QString &description)
{
if (!d) d = new QmlErrorPrivate;
d->description = description;
}
/*!
Returns the error line number.
*/
int QmlError::line() const
{
if (d) return qmlSourceCoordinate(d->line);
else return -1;
}
/*!
Sets the error \a line number.
*/
void QmlError::setLine(int line)
{
if (!d) d = new QmlErrorPrivate;
d->line = qmlSourceCoordinate(line);
}
/*!
Returns the error column number.
*/
int QmlError::column() const
{
if (d) return qmlSourceCoordinate(d->column);
else return -1;
}
/*!
Sets the error \a column number.
*/
void QmlError::setColumn(int column)
{
if (!d) d = new QmlErrorPrivate;
d->column = qmlSourceCoordinate(column);
}
/*!
Returns the error as a human readable string.
*/
QString QmlError::toString() const
{
QString rv;
QUrl u(url());
int l(line());
if (u.isEmpty()) {
rv = QLatin1String("<Unknown File>");
} else if (l != -1) {
rv = u.toString() + QLatin1Char(':') + QString::number(l);
int c(column());
if (c != -1)
rv += QLatin1Char(':') + QString::number(c);
} else {
rv = u.toString();
}
rv += QLatin1String(": ") + description();
return rv;
}
/*!
\relates QmlError
Outputs a human readable version of \a error to \a debug.
*/
QDebug operator<<(QDebug debug, const QmlError &error)
{
debug << qPrintable(error.toString());
QUrl url = error.url();
if (error.line() > 0 && url.scheme() == QLatin1String("file")) {
QString file = url.toLocalFile();
QFile f(file);
if (f.open(QIODevice::ReadOnly)) {
QByteArray data = f.readAll();
QTextStream stream(data, QIODevice::ReadOnly);
#ifndef QT_NO_TEXTCODEC
stream.setCodec("UTF-8");
#endif
const QString code = stream.readAll();
const QStringList lines = code.split(QLatin1Char('\n'));
if (lines.count() >= error.line()) {
const QString &line = lines.at(error.line() - 1);
debug << "\n " << qPrintable(line);
if(error.column() > 0) {
int column = qMax(0, error.column() - 1);
column = qMin(column, line.length());
QByteArray ind;
ind.reserve(column);
for (int i = 0; i < column; ++i) {
const QChar ch = line.at(i);
if (ch.isSpace())
ind.append(ch.unicode());
else
ind.append(' ');
}
ind.append('^');
debug << "\n " << ind.constData();
}
}
}
}
return debug;
}
QT_END_NAMESPACE
|
lgpl-2.1
|
scorpion007/pixie
|
src/sdrc/pp3.c
|
3
|
22160
|
/************************************************************************/
/* */
/* File: pp3.c */
/* */
/* General I/O for PP. */
/* */
/* Written by: */
/* Gary Oliver */
/* 3420 NW Elmwood Dr. */
/* PO Box 826 */
/* Corvallis, Oregon 97339 */
/* (503)758-5549 */
/* Maintained by: */
/* Kirk Bailey */
/* Logical Systems */
/* P.O. Box 1702 */
/* Corvallis, OR 97339 */
/* (503)753-9051 */
/* */
/* This program is hereby placed in the public domain. In */
/* contrast to other claims of "public domain", this means no */
/* copyright is claimed and you may do anything you like with PP, */
/* including selling it! As a gesture of courtesy, please retain */
/* the authorship information in the source code and */
/* documentation. */
/* */
/* Functions contained in this module: */
/* */
/* cur_user Select current disk-user (CPM). */
/* do_line Issue #line output directive. */
/* doinclude Process #include directive. */
/* doline Process #line directive. */
/* gchbuf Get char from file buffer. */
/* gchfile Get new buffer from file and return ch. */
/* gchpb Get char from pushback buffers. */
/* getchn Get char from buffer, ignoring "\\n" */
/* inc_open Open file for inclusion. */
/* init_path Initialize Ipath information. */
/* popfile Pop to next lower file level. */
/* readline Read and macro-process a line of text. */
/* scaneol Scan to eol, leaving EOL as next token. */
/* set_user Select a disk-user (CPM). */
/* trigraph Handle ANSI trigraph translations. */
/* */
/************************************************************************/
#include "pp.h"
#include "ppext.h"
#if HOST == H_CPM
/************************************************************************/
/* */
/* cur_user */
/* */
/* Restore disk/user to that at program start. */
/* */
/************************************************************************/
void
cur_user()
{
bdos(BDOS_SELDISK,Orig_disk);
bdos(BDOS_USER,Orig_user);
}
#endif /* HOST == H_CPM */
/************************************************************************/
/* */
/* do_line */
/* */
/* Write #line directive to output file, synching to current */
/* input line number and file name. */
/* */
/************************************************************************/
/*
* The following definition of NL_CHAR is used to minimize the file
* storage space required for the output file PP writes. If the external
* file format stores "\n" as a single character (as on the UNIX systems),
* then NL_CHAR is set to 1. Otherwise it is set to 2 to reflect the CR/
* LF used for external files. NLCHAR is only used by this function to
* optimize the tradeoff between emitting extra "#line" directives (if
* enabled), or to output extra "\n" characters instead.
*/
#if (HOST == H_BSD)OR(HOST == H_MPW)OR(HOST == H_UNIX)OR(HOST == H_XENIX)
#define NL_CHAR 1
#else /* H_BSD || H_MPW || H_UNIX || H_XENIX */
#define NL_CHAR 2
#endif /* H_BSD || H_MPW || H_UNIX || H_XENIX */
void
do_line(at_bol)
char at_bol; /* TRUE if already at BOL */
{
char buf[TOKENSIZE + 1];
char filen[FILENAMESIZE + 1];
register int n;
n = Tokenline - Outline; /* Difference in line #s */
sprintf(filen," \"%s\"",Filestack[Tokenfile]->f_name);
sprintf(buf,"%s#%s %d%s\n",
!at_bol ? "\n" : "", /* Emit a \n if needed */
Lineopt == LINE_EXP ? "line" : "",
#if TARGET == T_QC
Tokenline-1, /* QC bug */
#else /* TARGET != T_QC */
Tokenline,
#endif /* TARGET == T_QC */
Do_name ? filen : "");
#if (TARGET == T_QC) OR (TARGET == T_QCX)
if((!Do_name && (n >= 0) && (((unsigned int) n) <
(strlen(buf)/NL_CHAR + 1))) || Do_asm)
#else /* ! ((TARGET == T_QC) OR (TARGET == T_QCX)) */
if(!Do_name && (n >= 0) && (((unsigned int) n) <
(strlen(buf)/NL_CHAR + 1)))
#endif /* (TARGET == T_QC) OR (TARGET == T_QCX) */
{
while(n-- > 0)
putc('\n',Output); /* Write newlines to synch */
}
else
{
fprintf(Output,buf);
}
Outline = Tokenline; /* Make them the same */
Do_name = FALSE;
}
/************************************************************************/
/* */
/* doinclude */
/* */
/* Process #include file commands. */
/* */
/* The file name is parsed and the file is opened. A stack of */
/* current files and file names is pushed, with the new one */
/* being placed upon the top of the other, currently opened, */
/* files. Upon return, the next character read is from the */
/* newly opened file. */
/* */
/* */
/************************************************************************/
void
doinclude()
{
char buf[TOKENSIZE];
register int c;
register int d;
register char *incf;
char incfile[FILENAMESIZE + 1];
#if HOST != H_CPM
char filename[FILENAMESIZE + 1];
register char **ip;
#endif /* HOST != H_CPM */
register int ok;
#if HOST == H_CPM
register int disk;
register char *p;
register char **ip;
register int user;
#endif /* HOST == H_CPM */
#if DEBUG
if(Debug) printf("doinclude: include level:%d\n",Filelevel);
#endif /* DEBUG */
if(Filelevel >= FILESTACKSIZE)
{
non_fatal("Too many include files","");
return;
}
/*
* Read line and process any macros encountered.
*/
pbcstr(readline(buf,TOKENSIZE,GT_ANGLE,TRUE));
while(istype((c = getchn()),C_W))
;
if(c == EOF)
end_of_file();
else if(c == '<')
d = '>';
else if(c == '"')
d = '"';
else
{
non_fatal("Bad include argument","");
if(c == '\n')
pushback('\n');
return;
}
for(incf = incfile; c != EOF && c != '\n';)
{
if((c = getchn()) == d)
break;
if(incf >= &incfile[FILENAMESIZE])
{
non_fatal("Include filename too long","");
return;
}
else
*incf++ = c;
}
while((c != '\n') && (c != EOF))
c = getchn(); /* Slurp trailing \n */
if(incf != incfile)
*incf = '\0';
else
{
non_fatal("Invalid filename","");
return;
}
if(Lineopt)
do_line(TRUE); /* Catch up before inc file switch */
#if DEBUG
if(Debug) printf("doinclude: <%s>\n",incfile);
#endif /* DEBUG */
if(Verbose)
printf("*** Include %s\n",incfile);
ok = FALSE;
#if HOST == H_CPM /* The following stuff works only under CP/M */
/*
* Determine the type of include: if d == '<' then search the path
* indicated by the -i parameter (or the default.) If the delimiter is
* '"' then include the current directory as well.
*/
if(d == '"')
ok = inc_open(incfile,-1,0); /* The current location */
/* Try all path options in -i list (including DFLT_PATH stuff) */
for(ip = &Ipath[0]; (*ip != NULL) && !ok; ip++)
{
p = *ip;
while(istype(*p & 0xFF,C_W))
++p; /* Skip white space */
disk = *p++; /* Get drive letter */
if(isupper(disk))
disk = tolower(disk);
if(disk == '*')
user = -1; /* Use the default */
else if((disk >= 'a') && (disk <= 'p'))
{
disk -= 'a'; /* Drive */
if(! isdigit(*p))
user = -1; /* Default */
else
{
user = atoi(p);
if((user < 0) || (user > 31))
{
non_fatal("Invalid user number","");
return;
}
}
}
else
{
non_fatal("Invalid disk drive specifier","");
return;
}
ok = inc_open(incfile,user,disk);
}
#else /* HOST != H_CPM */
if(d == '"')
{
/* Look in current directory */
strcpy(filename,Filestack[Filelevel]->f_name);
if(strrchr(filename,SLASHCHAR))
strcpy(strrchr(filename,SLASHCHAR) + 1,incfile);
else
strcpy(filename,incfile);
ok = inc_open(filename);
}
/* Look through all paths for an existance of the file */
for(ip = &Ipath[0]; *ip != NULL && !ok; ip++)
{
strcpy(filename,*ip); /* Copy path name */
strcat(filename,SLASHSTR); /* Append / for directory */
strcat(filename,incfile); /* Append local file name */
ok = inc_open(filename); /* Attempt an open */
}
#endif /* (HOST != H_CPM) */
#if HOST == H_CPM
cur_user(); /* Restore current user/disk */
#endif /* HOST == H_CPM */
if(! ok)
non_fatal("Failed to open include file",incfile);
pushback('\n');
/* Let token scanner see first things on line */
Lastnl = TRUE;
}
/************************************************************************/
/* */
/* doline */
/* */
/* Set current line number and file identifier to that specified. */
/* */
/************************************************************************/
void
doline()
{
char buf[TOKENSIZE];
int c;
int l;
char *p;
/*
* Read line and process any macros encountered.
*/
pbcstr(readline(buf,TOKENSIZE,GT_STR,TRUE));
while(istype((c = getchn()),C_W))
;
if(istype(c,C_D))
{
for(l = 0; istype(c,C_D); c = getchn())
l = l * 10 + c - '0';
LLine = l - 1; /* Set line number */
pushback(c);
c = getnstoken(GT_STR);
if((c != '\n') && (c != EOF))
{
if(c == '"')
{
p = strrchr(Token,'"'); /* Find ending " */
/* Allow for first " */
if(p-Token > FILENAMESIZE)
p = &Token[FILENAMESIZE + 1];
*p = '\0'; /* Terminate it */
strcpy(Filestack[Filelevel]->f_name,Token + 1);
/* Need filename on "output" #line */
Do_name = TRUE;
}
else
{
pushback(c);
c = '\0';
}
}
}
else
{
pushback(c);
c = '\0';
}
if(c == '\0')
non_fatal("\"#line\" argument error","");
while((c != '\n') && (c != EOF))
c = getnstoken(GT_STR); /* Slurp trailing \n */
pushback('\n');
}
/************************************************************************/
/* */
/* gchbuf */
/* */
/* Get char from input buffer. If out of chars in buffer, read */
/* another buffer. */
/* */
/************************************************************************/
int
gchbuf()
{
register int c;
for(;;)
{
if(Lasteol)
{
Lasteol = FALSE;
LLine++;
}
if(! istype(c = (Bufc-- ? *Bufp++ : gchfile()),C_C))
break; /* If no need to examine closely */
#ifdef IGNORE_CR
if(c == '\r')
continue;
#endif /* IGNORE_CR */
if(c == '\n')
Lasteol = TRUE; /* Inc line number next time */
#ifdef PP_SYSIO
#if HOST == H_CPM
else if(c == ENDFILE)
{
Bufc = 0;
continue; /* Try to get next file */
}
#endif /* HOST == H_CPM */
#endif /* PP_SYSIO */
break;
}
return(c); /* And exit */
}
/************************************************************************/
/* */
/* gchfile */
/* */
/* Get next buffer of chars from input file. If end of file */
/* found, pop file level and read from lower file. If out of */
/* files, return EOF. */
/* */
/************************************************************************/
int
gchfile()
{
#ifdef PP_SYSIO
extern int read();
#endif /* PP_SYSIO */
register struct file *f;
if(Filelevel < 0)
{
Bufc = 0;
return (EOF);
}
else if((Filestack[Filelevel]->f_eof) && popfile())
return (A_trigraph ? trigraph() : gchbuf());
if(Filelevel < 0)
{
Bufc = 0;
return (EOF);
}
f = Filestack[Filelevel];
#if HOST == H_CPM
set_user();
#endif /* HOST == H_CPM */
Bufp = f->f_buf; /* Set buffer address */
#ifdef PP_SYSIO
if((Bufc = read(f->f_fd, Bufp, BUFFERSIZE)) == 0)
#else /* !PP_SYSIO */
if((Bufc = fread(Bufp, 1, BUFFERSIZE, f->f_file)) == 0)
#endif /* PP_SYSIO */
{
f->f_eof = TRUE;
return ('\n'); /* Fake '\n' before EOF */
}
#if HOST == H_CPM
cur_user();
#endif /* HOST == H_CPM */
Bufc--;
return(*Bufp++ & 0xFF); /* Return the char */
}
/************************************************************************/
/* */
/* gchpb */
/* */
/* Get character from push-back buffer. If out of chars, return */
/* next char routine to get chars from file. */
/* */
/************************************************************************/
int
gchpb()
{
register int c;
for(;;)
{
if(Pbbufp->pb_type == PB_CHAR)
c = (Pbbufp--)->pb_val.pb_char; /* Pop the char */
else if(Pbbufp->pb_type == PB_STRING)
{
/* Get next char from string */
if((c = *(Pbbufp->pb_val.pb_str++) & 0xFF) == '\0')
{
/*
* End of the string. Pop the stack to get the next pushback buffer
* which contains the starting address for the string.
*/
Pbbufp--;
/* Free up the memory */ free(Pbbufp->pb_val.pb_str);
/* Get nxt real pushback buf */ Pbbufp--;
/* Try again to get input */ continue;
}
}
else
{
/* Assume PB_TOS and pop to file input */
/* Next char source */ Nextch = A_trigraph ? trigraph : gchbuf;
return (A_trigraph ? trigraph() : gchbuf());
}
return (c);
}
}
/************************************************************************/
/* */
/* getchn */
/* */
/* Get next char from nextch() routine, ignoring \ followed */
/* by a newline character. */
/* */
/************************************************************************/
int
getchn()
{
int c;
int c2;
for(;;)
{
if((c = nextch()) == '\\')
{
c2 = nextch();
if(c2 == '\n')
continue; /* Ignore char and get next */
pushback(c2); /* We'll get to this char later */
}
return (c);
}
}
/************************************************************************/
/* */
/* inc_open */
/* */
/* Open an include file for the selected path. */
/* */
/************************************************************************/
#if HOST == H_CPM
int
inc_open(incfile,u,d)
register char *incfile;
int u;
int d;
#else /* HOST != H_CPM */
int
inc_open(incfile)
char *incfile;
#endif /* HOST == H_CPM */
{
#ifdef PP_SYSIO
extern int open();
#endif /* PP_SYSIO */
register int v;
register struct file *f;
register struct file *fold;
#if HOST == H_CPM
#if DEBUG
if(Debug)
printf("inc_open: %s on %c%d\n",incfile,d+'A',u);
#endif /* DEBUG */
if(u >= 0)
{
bdos(BDOS_USER,u);
bdos(BDOS_SELDISK,d);
}
#else /* HOST != H_CPM */
#if DEBUG
if(Debug)
printf("inc_open: %s\n",incfile);
#endif /* DEBUG */
#endif /* HOST == H_CPM */
f = Filestack[Filelevel+1] =
(struct file *) malloc(sizeof(struct file));
if(f == NULL)
out_of_memory();
#ifdef PP_SYSIO
if((v = ((f->f_fd = open(incfile,0)) != -1)) != 0)
#else /* !PP_SYSIO */
if((v = (int)((f->f_file = fopen(incfile,"r")) != NULL)) != 0)
#endif /* PP_SYSIO */
{
if(Filelevel >= 0) /* Don't do if first time thru */
{
#if DEBUG
if(Debug)
{
printf("inc_open pushing: Bufc=%d, Bufp=%p, Lasteol=%d, Line=%d\n",
Bufc,Bufp,Lasteol,LLine);
}
#endif /* DEBUG */
fold = Filestack[Filelevel];
fold->f_bufp = Bufp; /* Save current buf ptr */
fold->f_bufc = Bufc; /* Save current buffer count */
fold->f_lasteol = Lasteol; /* Save last char */
fold->f_line = LLine; /* Save current line # */
}
Filelevel++;
strcpy(f->f_name,incfile);
LLine = 1; /* Initial line number */
Bufc = 0; /* No chars in buffer */
f->f_eof = /* Not at eof yet */
Lasteol = FALSE;/* Last char was not EOL */
#if HOST == H_CPM
f->f_disk = d;
f->f_user = u;
#endif /* HOST == H_CPM */
}
else
free((char *)f); /* Return the memory used */
#if HOST == H_CPM
if(u >= 0)
cur_user(); /* Restore current user/disk */
#endif /* HOST == H_CPM */
if(v)
{
Do_name = TRUE;
return (TRUE);
}
else
return (FALSE);
}
/************************************************************************/
/* */
/* init_path */
/* */
/* Initialize path searching information. Try to open a file */
/* defined as PATHFILE on A0:. If available, read in the path */
/* default information, otherwise use CPM_PATH as the default. */
/* */
/* If initializing for non-CPM, initialize Ipath to whatever is */
/* specified by the PPINC environment variable or DFLT_PATH if no */
/* matching environment variable is found. */
/* */
/************************************************************************/
void
init_path()
{
#if HOST == H_CPM
register int inum;
char pb[TOKENSIZE];
register FILE *pf;
bdos(BDOS_USER,0);
bdos(BDOS_SELDISK,0); /* Select A0 */
if(pf = fopen(PATHFILE,"r"))
{
/* Found the file -- read lines and use as paths */
for(inum = Ipcnt; inum < NIPATHS; inum++)
{
if(fgets(pb,TOKENSIZE,pf) != NULL)
{
if((Ipath[inum] = malloc((unsigned)
(strlen(pb) + 1))) == NULL)
{
out_of_memory();
}
else
/* Copy the default path */ strcpy(Ipath[inum],pb);
}
else
{
if(inum == Ipcnt)
{
/* Didn't find any -- give error msg */
warning("Bad format on include path file",
PATHFILE);
/* Use default path */ Ipath[inum++] = DFLT_PATH;
}
break;
}
}
Ipcnt = inum; /* Keep counter correct */
if(fclose(pf) == EOF)
{
non_fatal("Failed to close include path file",
PATHFILE);
}
}
else
Ipath[Ipcnt++] = DFLT_PATH; /* The default path list */
cur_user(); /* Restore user/disk defaults */
#endif /* HOST == H_CPM */
#if HOST != H_CPM
char *cptr1;
char *cptr2;
char pb[TOKENSIZE];
/*
* See if there is an environment variable for the default search path.
*/
if((cptr1 = getenv(ENV_PATH)) == NULL)
cptr1 = strcpy(pb,DFLT_PATH); /* Nope, use default path */
else
cptr1 = strcpy(pb,cptr1);
for(; (*cptr1 != '\0') && (Ipcnt < NIPATHS); cptr1 = cptr2)
{
if((cptr2 = strchr(cptr1,PATHPUNC)) != NULL)
*cptr2++ = '\0';
else
cptr2 = "\0";
if((Ipath[Ipcnt] = malloc((unsigned) (strlen(cptr1) + 1))) ==
NULL)
{
out_of_memory();
}
else
strcpy(Ipath[Ipcnt++],cptr1);
}
#endif /* HOST != H_CPM */
}
/************************************************************************/
/* */
/* popfile */
/* */
/* Pop file stack to previous file and return FALSE if no more. */
/* */
/************************************************************************/
int
popfile()
{
#ifdef PP_SYSIO
extern int close();
#endif /* PP_SYSIO */
register struct file *f;
#if HOST == H_CPM
set_user();
#endif /* HOST == H_CPM */
#ifdef PP_SYSIO
if(close((f = Filestack[Filelevel])->f_fd) == -1)
#else /* !PP_SYSIO */
if(fclose((f = Filestack[Filelevel])->f_file) == EOF)
#endif /* PP_SYSIO */
non_fatal("Failed to close file",f->f_name);
free((char *)f); /* Free the entry */
#if HOST == H_CPM
cur_user();
#endif /* HOST == H_CPM */
if(Filelevel-- == 0)
return (FALSE); /* At bottom level, real EOF */
f = Filestack[Filelevel];
if(Verbose)
printf("*** Resume %s\n",f->f_name);
Do_name = TRUE; /* Next time do_line called, name it */
Bufc = f->f_bufc;
Bufp = f->f_bufp;
Lasteol = f->f_lasteol;
LLine = f->f_line;
#if DEBUG
if(Debug)
printf("popfile: Bufc=%d, Bufp=%p, Lasteol=%d, Line=%d\n",
Bufc, Bufp, Lasteol, LLine);
#endif /* DEBUG */
return (TRUE); /* All is ok -- return success */
}
/************************************************************************/
/* */
/* readline */
/* */
/* Read and edit a line into buffer with optional macro expansion. */
/* */
/************************************************************************/
char *
readline(buf,bufsize,flags,doexpand)
register char *buf;
register int bufsize;
register int flags;
int doexpand;
{
static char rbo[] = "Read buffer overflow";
register char *bufp;
struct symtab *sy;
register int t;
for(bufp = buf; (t = gettoken(flags)) != '\n'; )
{
if(t == EOF)
end_of_file();
if((t == LETTER) && ((sy = lookup(Token,NULL)) != NULL) &&
(sy->disable != TRUE) && (doexpand == TRUE))
{
bufp = docall(sy,bufp,&buf[bufsize - 1]);
}
else
bufp = addstr(bufp,&buf[bufsize - 1],rbo,Token);
}
pushback('\n');
*bufp = '\0';
for(bufp = buf; istype(*bufp & 0xFF,C_W); ++bufp)
; /* Skip leading blanks */
return(bufp);
}
/************************************************************************/
/* */
/* scaneol */
/* */
/* Scan for end of current line. */
/* */
/************************************************************************/
void
scaneol()
{
register int t;
while((t = gettoken(GT_STR)) != '\n')
{
if(t == EOF)
return; /* Absorb chars */
}
pushback('\n'); /* So the newline is seen */
}
#if HOST == H_CPM
/************************************************************************/
/* */
/* set_user */
/* */
/* Set disk/user to that of current input file. */
/* */
/************************************************************************/
void
set_user()
{
/* Don't change if < 0 */
if(Filestack[Filelevel]->f_user >= 0)
{
bdos(BDOS_SELDISK,Filestack[Filelevel]->f_disk);
bdos(BDOS_USER,Filestack[Filelevel]->f_user);
}
}
#endif /* HOST == H_CPM */
/************************************************************************/
/* */
/* trigraph */
/* */
/* Handles ANSI trigraph substitutions (alternate to "gchbuf"). */
/* */
/************************************************************************/
int
trigraph()
{
int c;
int q_count;
if((c = gchbuf()) == '?')
{
if((c = gchbuf()) == '?')
{
q_count = 0; /* Extra '?' encountered */
for(;;)
{
switch((int) (c = gchbuf()))
{
case '=':
c = '#';
break;
case '(':
c = '[';
break;
case '/':
c = '\\';
break;
case ')':
c = ']';
break;
case '\'':
c = '^';
break;
case '<':
c = '{';
break;
case '!':
c = '|';
break;
case '>':
c = '}';
break;
case '-':
c = '~';
break;
case '?':
q_count++;
continue;
default:
pushback(c);
pushback('?');
c = '?';
break;
}
/*
* Handle stuff like "????????????#" correctly.
*/
if(q_count > 0)
{
pushback(c);
while(q_count-- > 1)
pushback('?');
c = '?';
}
break;
}
}
else
{
pushback(c);
c = '?';
}
}
return (c);
}
|
lgpl-2.1
|
ProfessorKaos64/openlierox
|
src/game/Settings.cpp
|
3
|
5346
|
/*
* Settings.cpp
* OpenLieroX
*
* Created by Albert Zeyer on 24.02.10.
* code under LGPL
*
*/
#include "Settings.h"
#include "Options.h"
#include "CServer.h"
#include "IniReader.h"
#include "Debug.h"
#include "gusanos/luaapi/classes.h"
#include "game/Game.h"
#include "CClient.h"
Settings gameSettings;
FeatureSettingsLayer modSettings("Mod properties");
FeatureSettingsLayer gamePresetSettings("Settings preset");
void FeatureSettingsLayer::makeSet(bool v) {
for(size_t i = 0; i < FeatureArrayLen; ++i)
isSet[i] = v;
}
ScriptVar_t& FeatureSettingsLayer::set(FeatureIndex i) {
if(!isSet[i]) {
((FeatureSettings&)(*this))[i] = featureArray[i].unsetValue; // just to be sure; in case modSettings is init before featureArray, also important
isSet[i] = true;
}
gameSettings.pushUpdateHint(i);
return ((FeatureSettings&)(*this))[i];
}
void FeatureSettingsLayer::dump() const {
notes << debug_name << " {" << endl;
for(size_t i = 0; i < FeatureArrayLen; ++i)
if(isSet[i])
notes << " " << featureArray[i].name << " : " << (*this)[(FeatureIndex)i] << endl;
notes << "}" << endl;
}
void Settings::layersInitStandard(bool withCustom) {
layersClear();
layers.push_back(&modSettings);
layers.push_back(&gamePresetSettings);
if(withCustom) {
if(tLXOptions)
layers.push_back(&tLXOptions->customSettings);
else
errors << "Settings::layersInitStandard: tLXOptions == NULL" << endl;
}
}
ScriptVar_t Settings::hostGet(FeatureIndex i) {
ScriptVar_t var = (*this)[i];
Feature* f = &featureArray[i];
if(f->getValueFct)
var = f->getValueFct( var );
return var;
}
bool Settings::olderClientsSupportSetting(Feature* f) {
if( f->optionalForClient ) return true;
return hostGet(f) == f->unsetValue;
}
bool FeatureSettingsLayer::loadFromConfig(const std::string& cfgfile, bool reset, std::map<std::string, std::string>* unknown) {
if(reset) makeSet(false);
IniReader ini(cfgfile);
if(!ini.Parse()) return false;
IniReader::Section& section = ini.m_sections["GameInfo"];
for(IniReader::Section::iterator i = section.begin(); i != section.end(); ++i) {
Feature* f = featureByName(i->first);
if(f) {
FeatureIndex fi = featureArrayIndex(f);
if(!set(fi).fromString(i->second))
notes << "loadFromConfig " << cfgfile << ": cannot understand: " << i->first << " = " << i->second << endl;
}
else {
if(unknown)
(*unknown)[i->first] = i->second;
}
}
return true;
}
bool Settings::isRelevant(FeatureSettingsLayer* layer, FeatureIndex i) const {
for(Layers::const_reverse_iterator it = layers.rbegin(); it != layers.rend(); ++it) {
if(layer == *it) return true;
if((*it)->isSet[i]) return false;
}
return false; // layer not registered at all
}
bool Settings::isRelevant(FeatureSettingsLayer* layer, Feature* f) const {
return isRelevant(layer, featureArrayIndex(f));
}
void Settings::dumpAllLayers() const {
notes << "Settings (" << layers.size() << " layers) {" << endl;
size_t num = 1;
for(Layers::const_iterator i = layers.begin(); i != layers.end(); ++i, ++num) {
notes << "Layer " << num << ": ";
(*i)->dump();
}
notes << "}" << endl;
}
static ScriptVar_t Settings_attrGetValue(const BaseObject* obj, const AttrDesc* attrDesc) {
const Settings* s = dynamic_cast<const Settings*>(obj);
assert(s != NULL);
assert(s == &gameSettings); // it's a singleton
return s->attrGetValue(attrDesc);
}
static AttrExt& Settings_attrGetAttrExt(BaseObject* obj, const AttrDesc* attrDesc) {
Settings* s = dynamic_cast<Settings*>(obj);
assert(s != NULL);
assert(s == &gameSettings); // it's a singleton
return s->attrGetAttrExt(attrDesc);
}
Settings::AttrDescs::AttrDescs() {
for(size_t i = 0; i < FeatureArrayLen; ++i) {
attrDescs[i].objTypeId = LuaID<Settings>::value;
attrDescs[i].attrId = featureArray[i].id;
attrDescs[i].attrType = featureArray[i].valueType;
attrDescs[i].attrName = featureArray[i].name;
attrDescs[i].defaultValue = featureArray[i].unsetValue;
attrDescs[i].isStatic = false;
attrDescs[i].dynGetValue = Settings_attrGetValue;
attrDescs[i].dynGetAttrExt = Settings_attrGetAttrExt;
attrDescs[i].onUpdate = Game::onSettingsUpdate;
registerAttrDesc(attrDescs[i]);
}
}
Settings::Settings() {
thisRef.classId = LuaID<Settings>::value;
thisRef.objId = 1;
for(size_t i = 0; i < FeatureArrayLen; ++i) {
wrappers[i].i = (FeatureIndex)i;
wrappers[i].s = this;
}
}
bool Settings::AttrDescs::belongsToUs(const AttrDesc *attrDesc) {
return attrDesc >= &attrDescs[0] && attrDesc < &attrDesc[FeatureArrayLen];
}
FeatureIndex Settings::AttrDescs::getIndex(const AttrDesc* attrDesc) {
assert(belongsToUs(attrDesc));
return FeatureIndex(attrDesc - &attrDescs[0]);
}
void Settings::pushUpdateHint(FeatureIndex i) {
pushObjAttrUpdate(*this, &getAttrDescs().attrDescs[i]);
}
void Settings::pushUpdateHintAll() {
for(size_t i = 0; i < FeatureArrayLen; ++i)
pushUpdateHint((FeatureIndex)i);
}
ScriptVar_t Settings::attrGetValue(const AttrDesc* attrDesc) const {
FeatureIndex i = getAttrDescs().getIndex(attrDesc);
if(game.isServer() || game.state <= Game::S_Inactive)
return (*this)[i];
else
return cClient->getGameLobby()[i];
}
AttrExt& Settings::attrGetAttrExt(const AttrDesc* attrDesc) {
FeatureIndex i = getAttrDescs().getIndex(attrDesc);
return attrExts[i];
}
REGISTER_CLASS(Settings, ClassId(-1))
|
lgpl-2.1
|
pocketbook-free/browser
|
icu/source/test/intltest/dtfmtrtts.cpp
|
4
|
20834
|
/***********************************************************************
* COPYRIGHT:
* Copyright (c) 1997-2010, International Business Machines Corporation
* and others. All Rights Reserved.
***********************************************************************/
#include "unicode/utypes.h"
#if !UCONFIG_NO_FORMATTING
#include "unicode/datefmt.h"
#include "unicode/smpdtfmt.h"
#include "unicode/gregocal.h"
#include "dtfmtrtts.h"
#include "caltest.h"
#include <stdio.h>
#include <string.h>
// *****************************************************************************
// class DateFormatRoundTripTest
// *****************************************************************************
// Useful for turning up subtle bugs: Change the following to TRUE, recompile,
// and run while at lunch.
// Warning -- makes test run infinite loop!!!
#ifndef INFINITE
#define INFINITE 0
#endif
// Define this to test just a single locale
//#define TEST_ONE_LOC "cs_CZ"
// If SPARSENESS is > 0, we don't run each exhaustive possibility.
// There are 24 total possible tests per each locale. A SPARSENESS
// of 12 means we run half of them. A SPARSENESS of 23 means we run
// 1 of them. SPARSENESS _must_ be in the range 0..23.
int32_t DateFormatRoundTripTest::SPARSENESS = 0;
int32_t DateFormatRoundTripTest::TRIALS = 4;
int32_t DateFormatRoundTripTest::DEPTH = 5;
DateFormatRoundTripTest::DateFormatRoundTripTest() : dateFormat(0) {
}
DateFormatRoundTripTest::~DateFormatRoundTripTest() {
delete dateFormat;
}
#define CASE(id,test) case id: name = #test; if (exec) { logln(#test "---"); logln((UnicodeString)""); test(); } break;
void
DateFormatRoundTripTest::runIndexedTest( int32_t index, UBool exec, const char* &name, char* par )
{
optionv = (par && *par=='v');
switch (index) {
CASE(0,TestDateFormatRoundTrip)
CASE(1, TestCentury)
default: name = ""; break;
}
}
UBool
DateFormatRoundTripTest::failure(UErrorCode status, const char* msg)
{
if(U_FAILURE(status)) {
errln(UnicodeString("FAIL: ") + msg + " failed, error " + u_errorName(status));
return TRUE;
}
return FALSE;
}
UBool
DateFormatRoundTripTest::failure(UErrorCode status, const char* msg, const UnicodeString& str)
{
if(U_FAILURE(status)) {
UnicodeString escaped;
escape(str,escaped);
errln(UnicodeString("FAIL: ") + msg + " failed, error " + u_errorName(status) + ", str=" + escaped);
return TRUE;
}
return FALSE;
}
void DateFormatRoundTripTest::TestCentury()
{
UErrorCode status = U_ZERO_ERROR;
Locale locale("es_PA");
UnicodeString pattern = "MM/dd/yy hh:mm:ss a z";
SimpleDateFormat fmt(pattern, locale, status);
if (U_FAILURE(status)) {
dataerrln("Fail: construct SimpleDateFormat: %s", u_errorName(status));
return;
}
UDate date[] = {-55018555891590.05, 0, 0};
UnicodeString result[2];
fmt.format(date[0], result[0]);
date[1] = fmt.parse(result[0], status);
fmt.format(date[1], result[1]);
date[2] = fmt.parse(result[1], status);
/* This test case worked OK by accident before. date[1] != date[0],
* because we use -80/+20 year window for 2-digit year parsing.
* (date[0] is in year 1926, date[1] is in year 2026.) result[1] set
* by the first format call returns "07/13/26 07:48:28 p.m. PST",
* which is correct, because DST was not used in year 1926 in zone
* America/Los_Angeles. When this is parsed, date[1] becomes a time
* in 2026, which is "07/13/26 08:48:28 p.m. PDT". There was a zone
* offset calculation bug that observed DST in 1926, which was resolved.
* Before the bug was resolved, result[0] == result[1] was true,
* but after the bug fix, the expected result is actually
* result[0] != result[1]. -Yoshito
*/
/* TODO: We need to review this code and clarify what we really
* want to test here.
*/
//if (date[1] != date[2] || result[0] != result[1]) {
if (date[1] != date[2]) {
errln("Round trip failure: \"%S\" (%f), \"%S\" (%f)", result[0].getBuffer(), date[1], result[1].getBuffer(), date[2]);
}
}
// ==
void DateFormatRoundTripTest::TestDateFormatRoundTrip()
{
UErrorCode status = U_ZERO_ERROR;
getFieldCal = Calendar::createInstance(status);
if (U_FAILURE(status)) {
dataerrln("Fail: Calendar::createInstance: %s", u_errorName(status));
return;
}
int32_t locCount = 0;
const Locale *avail = DateFormat::getAvailableLocales(locCount);
logln("DateFormat available locales: %d", locCount);
if(quick) {
SPARSENESS = 18;
logln("Quick mode: only testing SPARSENESS = 18");
}
TimeZone *tz = TimeZone::createDefault();
UnicodeString temp;
logln("Default TimeZone: " + tz->getID(temp));
delete tz;
#ifdef TEST_ONE_LOC // define this to just test ONE locale.
Locale loc(TEST_ONE_LOC);
test(loc);
#if INFINITE
for(;;) {
test(loc);
}
#endif
#else
# if INFINITE
// Special infinite loop test mode for finding hard to reproduce errors
Locale loc = Locale::getDefault();
logln("ENTERING INFINITE TEST LOOP FOR Locale: " + loc.getDisplayName(temp));
for(;;)
test(loc);
# else
test(Locale::getDefault());
#if 1
// installed locales
for (int i=0; i < locCount; ++i) {
test(avail[i]);
}
#endif
#if 1
// special locales
int32_t jCount = CalendarTest::testLocaleCount();
for (int32_t j=0; j < jCount; ++j) {
test(Locale(CalendarTest::testLocaleID(j)));
}
#endif
# endif
#endif
delete getFieldCal;
}
static const char *styleName(DateFormat::EStyle s)
{
switch(s)
{
case DateFormat::SHORT: return "SHORT";
case DateFormat::MEDIUM: return "MEDIUM";
case DateFormat::LONG: return "LONG";
case DateFormat::FULL: return "FULL";
// case DateFormat::DEFAULT: return "DEFAULT";
case DateFormat::DATE_OFFSET: return "DATE_OFFSET";
case DateFormat::NONE: return "NONE";
case DateFormat::DATE_TIME: return "DATE_TIME";
default: return "Unknown";
}
}
void DateFormatRoundTripTest::test(const Locale& loc)
{
UnicodeString temp;
#if !INFINITE
logln("Locale: " + loc.getDisplayName(temp));
#endif
// Total possibilities = 24
// 4 date
// 4 time
// 16 date-time
UBool TEST_TABLE [24];//= new boolean[24];
int32_t i = 0;
for(i = 0; i < 24; ++i)
TEST_TABLE[i] = TRUE;
// If we have some sparseness, implement it here. Sparseness decreases
// test time by eliminating some tests, up to 23.
for(i = 0; i < SPARSENESS; ) {
int random = (int)(randFraction() * 24);
if (random >= 0 && random < 24 && TEST_TABLE[i]) {
TEST_TABLE[i] = FALSE;
++i;
}
}
int32_t itable = 0;
int32_t style = 0;
for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) {
if(TEST_TABLE[itable++]) {
logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style)));
DateFormat *df = DateFormat::createDateInstance((DateFormat::EStyle)style, loc);
if(df == NULL) {
errln(UnicodeString("Could not DF::createDateInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp));
} else {
test(df, loc);
delete df;
}
}
}
for(style = DateFormat::FULL; style <= DateFormat::SHORT; ++style) {
if (TEST_TABLE[itable++]) {
logln("Testing style " + UnicodeString(styleName((DateFormat::EStyle)style)));
DateFormat *df = DateFormat::createTimeInstance((DateFormat::EStyle)style, loc);
if(df == NULL) {
errln(UnicodeString("Could not DF::createTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)style)) + " Locale: " + loc.getDisplayName(temp));
} else {
test(df, loc, TRUE);
delete df;
}
}
}
for(int32_t dstyle = DateFormat::FULL; dstyle <= DateFormat::SHORT; ++dstyle) {
for(int32_t tstyle = DateFormat::FULL; tstyle <= DateFormat::SHORT; ++tstyle) {
if(TEST_TABLE[itable++]) {
logln("Testing dstyle" + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) );
DateFormat *df = DateFormat::createDateTimeInstance((DateFormat::EStyle)dstyle, (DateFormat::EStyle)tstyle, loc);
if(df == NULL) {
dataerrln(UnicodeString("Could not DF::createDateTimeInstance ") + UnicodeString(styleName((DateFormat::EStyle)dstyle)) + ", tstyle" + UnicodeString(styleName((DateFormat::EStyle)tstyle)) + "Locale: " + loc.getDisplayName(temp));
} else {
test(df, loc);
delete df;
}
}
}
}
}
void DateFormatRoundTripTest::test(DateFormat *fmt, const Locale &origLocale, UBool timeOnly)
{
UnicodeString pat;
if(fmt->getDynamicClassID() != SimpleDateFormat::getStaticClassID()) {
errln("DateFormat wasn't a SimpleDateFormat");
return;
}
UBool isGregorian = FALSE;
UErrorCode minStatus = U_ZERO_ERROR;
UDate minDate = CalendarTest::minDateOfCalendar(*fmt->getCalendar(), isGregorian, minStatus);
if(U_FAILURE(minStatus)) {
errln((UnicodeString)"Failure getting min date for " + origLocale.getName());
return;
}
//logln(UnicodeString("Min date is ") + fullFormat(minDate) + " for " + origLocale.getName());
pat = ((SimpleDateFormat*)fmt)->toPattern(pat);
// NOTE TO MAINTAINER
// This indexOf check into the pattern needs to be refined to ignore
// quoted characters. Currently, this isn't a problem with the locale
// patterns we have, but it may be a problem later.
UBool hasEra = (pat.indexOf(UnicodeString("G")) != -1);
UBool hasZoneDisplayName = (pat.indexOf(UnicodeString("z")) != -1) || (pat.indexOf(UnicodeString("v")) != -1)
|| (pat.indexOf(UnicodeString("V")) != -1);
// Because patterns contain incomplete data representing the Date,
// we must be careful of how we do the roundtrip. We start with
// a randomly generated Date because they're easier to generate.
// From this we get a string. The string is our real starting point,
// because this string should parse the same way all the time. Note
// that it will not necessarily parse back to the original date because
// of incompleteness in patterns. For example, a time-only pattern won't
// parse back to the same date.
//try {
for(int i = 0; i < TRIALS; ++i) {
UDate *d = new UDate [DEPTH];
UnicodeString *s = new UnicodeString[DEPTH];
if(isGregorian == TRUE) {
d[0] = generateDate();
} else {
d[0] = generateDate(minDate);
}
UErrorCode status = U_ZERO_ERROR;
// We go through this loop until we achieve a match or until
// the maximum loop count is reached. We record the points at
// which the date and the string starts to match. Once matching
// starts, it should continue.
int loop;
int dmatch = 0; // d[dmatch].getTime() == d[dmatch-1].getTime()
int smatch = 0; // s[smatch].equals(s[smatch-1])
for(loop = 0; loop < DEPTH; ++loop) {
if (loop > 0) {
d[loop] = fmt->parse(s[loop-1], status);
failure(status, "fmt->parse", s[loop-1]+" in locale: " + origLocale.getName());
status = U_ZERO_ERROR; /* any error would have been reported */
}
s[loop] = fmt->format(d[loop], s[loop]);
// For displaying which date is being tested
//logln(s[loop] + " = " + fullFormat(d[loop]));
if(s[loop].length() == 0) {
errln("FAIL: fmt->format gave 0-length string in " + pat + " with number " + d[loop] + " in locale " + origLocale.getName());
}
if(loop > 0) {
if(smatch == 0) {
UBool match = s[loop] == s[loop-1];
if(smatch == 0) {
if(match)
smatch = loop;
}
else if( ! match)
errln("FAIL: String mismatch after match");
}
if(dmatch == 0) {
// {sfb} watch out here, this might not work
UBool match = d[loop]/*.getTime()*/ == d[loop-1]/*.getTime()*/;
if(dmatch == 0) {
if(match)
dmatch = loop;
}
else if( ! match)
errln("FAIL: Date mismatch after match");
}
if(smatch != 0 && dmatch != 0)
break;
}
}
// At this point loop == DEPTH if we've failed, otherwise loop is the
// max(smatch, dmatch), that is, the index at which we have string and
// date matching.
// Date usually matches in 2. Exceptions handled below.
int maxDmatch = 2;
int maxSmatch = 1;
if (dmatch > maxDmatch) {
// Time-only pattern with zone information and a starting date in PST.
if(timeOnly && hasZoneDisplayName) {
int32_t startRaw, startDst;
fmt->getTimeZone().getOffset(d[0], FALSE, startRaw, startDst, status);
failure(status, "TimeZone::getOffset");
// if the start offset is greater than the offset on Jan 1, 1970
// in PST, then need one more round trip. There are two cases
// fall into this category. The start date is 1) DST or
// 2) LMT (GMT-07:52:58).
if (startRaw + startDst > -28800000) {
maxDmatch = 3;
maxSmatch = 2;
}
}
}
// String usually matches in 1. Exceptions are checked for here.
if(smatch > maxSmatch) { // Don't compute unless necessary
UBool in0;
// Starts in BC, with no era in pattern
if( ! hasEra && getField(d[0], UCAL_ERA) == GregorianCalendar::BC)
maxSmatch = 2;
// Starts in DST, no year in pattern
else if((in0=fmt->getTimeZone().inDaylightTime(d[0], status)) && ! failure(status, "gettingDaylightTime") &&
pat.indexOf(UnicodeString("yyyy")) == -1)
maxSmatch = 2;
// If we start not in DST, but transition into DST
else if (!in0 &&
fmt->getTimeZone().inDaylightTime(d[1], status) && !failure(status, "gettingDaylightTime"))
maxSmatch = 2;
// Two digit year with no time zone change,
// unless timezone isn't used or we aren't close to the DST changover
else if (pat.indexOf(UnicodeString("y")) != -1
&& pat.indexOf(UnicodeString("yyyy")) == -1
&& getField(d[0], UCAL_YEAR)
!= getField(d[dmatch], UCAL_YEAR)
&& !failure(status, "error status [smatch>maxSmatch]")
&& ((hasZoneDisplayName
&& (fmt->getTimeZone().inDaylightTime(d[0], status)
== fmt->getTimeZone().inDaylightTime(d[dmatch], status)
|| getField(d[0], UCAL_MONTH) == UCAL_APRIL
|| getField(d[0], UCAL_MONTH) == UCAL_OCTOBER))
|| !hasZoneDisplayName)
)
{
maxSmatch = 2;
}
// If zone display name is used, fallback format might be used before 1970
else if (hasZoneDisplayName && d[0] < 0) {
maxSmatch = 2;
}
}
if(dmatch > maxDmatch || smatch > maxSmatch) { // Special case for Japanese and Islamic (could have large negative years)
const char *type = fmt->getCalendar()->getType();
if(!strcmp(type,"japanese")) {
maxSmatch = 4;
maxDmatch = 4;
}
}
// Use @v to see verbose results on successful cases
UBool fail = (dmatch > maxDmatch || smatch > maxSmatch);
if (optionv || fail) {
if (fail) {
errln(UnicodeString("\nFAIL: Pattern: ") + pat +
" in Locale: " + origLocale.getName());
} else {
errln(UnicodeString("\nOk: Pattern: ") + pat +
" in Locale: " + origLocale.getName());
}
logln("Date iters until match=%d (max allowed=%d), string iters until match=%d (max allowed=%d)",
dmatch,maxDmatch, smatch, maxSmatch);
for(int j = 0; j <= loop && j < DEPTH; ++j) {
UnicodeString temp;
FieldPosition pos(FieldPosition::DONT_CARE);
errln((j>0?" P> ":" ") + fullFormat(d[j]) + " F> " +
escape(s[j], temp) + UnicodeString(" d=") + d[j] +
(j > 0 && d[j]/*.getTime()*/==d[j-1]/*.getTime()*/?" d==":"") +
(j > 0 && s[j] == s[j-1]?" s==":""));
}
}
delete[] d;
delete[] s;
}
/*}
catch (ParseException e) {
errln("Exception: " + e.getMessage());
logln(e.toString());
}*/
}
const UnicodeString& DateFormatRoundTripTest::fullFormat(UDate d) {
UErrorCode ec = U_ZERO_ERROR;
if (dateFormat == 0) {
dateFormat = new SimpleDateFormat((UnicodeString)"EEE MMM dd HH:mm:ss.SSS zzz yyyy G", ec);
if (U_FAILURE(ec) || dateFormat == 0) {
fgStr = "[FAIL: SimpleDateFormat constructor]";
delete dateFormat;
dateFormat = 0;
return fgStr;
}
}
fgStr.truncate(0);
dateFormat->format(d, fgStr);
return fgStr;
}
/**
* Return a field of the given date
*/
int32_t DateFormatRoundTripTest::getField(UDate d, int32_t f) {
// Should be synchronized, but we're single threaded so it's ok
UErrorCode status = U_ZERO_ERROR;
getFieldCal->setTime(d, status);
failure(status, "getfieldCal->setTime");
int32_t ret = getFieldCal->get((UCalendarDateFields)f, status);
failure(status, "getfieldCal->get");
return ret;
}
UnicodeString& DateFormatRoundTripTest::escape(const UnicodeString& src, UnicodeString& dst )
{
dst.remove();
for (int32_t i = 0; i < src.length(); ++i) {
UChar c = src[i];
if(c < 0x0080)
dst += c;
else {
dst += UnicodeString("[");
char buf [8];
sprintf(buf, "%#x", c);
dst += UnicodeString(buf);
dst += UnicodeString("]");
}
}
return dst;
}
#define U_MILLIS_PER_YEAR (365.25 * 24 * 60 * 60 * 1000)
UDate DateFormatRoundTripTest::generateDate(UDate minDate)
{
// Bring range in conformance to generateDate() below.
if(minDate < (U_MILLIS_PER_YEAR * -(4000-1970))) {
minDate = (U_MILLIS_PER_YEAR * -(4000-1970));
}
for(int i=0;i<8;i++) {
double a = randFraction();
// Range from (min) to (8000-1970) AD
double dateRange = (0.0 - minDate) + (U_MILLIS_PER_YEAR + (8000-1970));
a *= dateRange;
// Now offset from minDate
a += minDate;
// Last sanity check
if(a>=minDate) {
return a;
}
}
return minDate;
}
UDate DateFormatRoundTripTest::generateDate()
{
double a = randFraction();
// Now 'a' ranges from 0..1; scale it to range from 0 to 8000 years
a *= 8000;
// Range from (4000-1970) BC to (8000-1970) AD
a -= 4000;
// Now scale up to ms
a *= 365.25 * 24 * 60 * 60 * 1000;
//return new Date((long)a);
return a;
}
#endif /* #if !UCONFIG_NO_FORMATTING */
//eof
|
lgpl-2.1
|
lord2894/AOT-VS2012-13
|
Source/GraphanLib/HtmlConv.cpp
|
4
|
6277
|
// ========== This file is under LGPL, the GNU Lesser General Public Licence
// ========== Dialing Graphematical Module (www.aot.ru)
// ========== Copyright by Alexey Sokirko and Andrey Kalinin(1996-2001)
#include "StdGraph.h"
#include "assert.h"
#include "HTMLConv.h"
/*
* Return offset...
*/
unsigned long HTML::getOffset(unsigned long off)
{
assert (m_bCollectOffsets);
unsigned long cur_offset = 0;
int i=0;
for(; i < offsets.size(); i++)
{
cur_offset += offsets[i].high - offsets[i].low + 1;
if(off <= cur_offset) break;
}
assert(i != offsets.size());
return offsets[i].high - (cur_offset - off);
}
/*
* Add offset to the container
*/
void HTML::addOffset(unsigned long off)
{
if (!m_bCollectOffsets) return;
if(offsets.empty())
offsets.push_back(offset_range(off, off));
else
if(offsets.back().high == off - 1)
offsets.back().high++;
else
offsets.push_back(offset_range(off, off));
}
/***************************************************************************
* Very simple parser
*/
string HTML::GetTextFromHTMLBuffer(const char* Buffer, size_t BufferLen)
{
offsets.clear();
size_t cur_offset = 0, old_offset = 0;
string result;
string cur_tag, cur_amp;
bool next_read = true;
enum
{
normal = 0,
tag,
amp,
spaces
} state = normal;
stack<string> NotTextTags;
BYTE ch;
while (cur_offset < BufferLen)
{
if(next_read)
{
ch = (BYTE)Buffer[cur_offset];
cur_offset++;
}
else
next_read = true;
switch(state)
{
case normal:
{
if(isspace(ch))
{
if (NotTextTags.empty())
{
result += ' ';
addOffset(cur_offset-1);
}
state = spaces;
break;
}
else
switch(ch)
{
case '<':
state = tag;
old_offset = cur_offset-1;
cur_tag.erase();
break;
case '&':
state = amp;
old_offset = cur_offset-1;
cur_amp.erase();
break;
default:
if (NotTextTags.empty())
{
result += ch;
addOffset(cur_offset-1);
};
}
break;
}
case tag:
{
switch(ch)
{
case '>':
state = normal;
if(checkTag(cur_tag,"br"))
{
if (NotTextTags.empty())
{
result += "\n";
addOffset(old_offset);
};
state = spaces;
}
else
if( checkTag(cur_tag,"xml") )
{
NotTextTags.push("/xml");
}
else
// the tag itself can be very long for example"<script language="JavaScript1.1">"
if(checkTag(cur_tag,"script") )
{
NotTextTags.push("/script");
}
else
if( !NotTextTags.empty() && checkTag(cur_tag, NotTextTags.top().c_str()) )
{
NotTextTags.pop();
}
else
if( checkTag(cur_tag,"li") ||
checkTag(cur_tag,"/li") ||
checkTag(cur_tag,"ul") ||
checkTag(cur_tag,"/ul") ||
checkTag(cur_tag,"dl") ||
checkTag(cur_tag,"/dl") ||
checkTag(cur_tag,"dt") ||
checkTag(cur_tag,"/dt") ||
checkTag(cur_tag,"/p") ||
checkTag(cur_tag,"title") ||
checkTag(cur_tag,"/title") ||
checkTag(cur_tag,"table") ||
checkTag(cur_tag,"/table") ||
checkTag(cur_tag,"tr") ||
checkTag(cur_tag,"/tr") ||
checkTag(cur_tag,"td") ||
checkTag(cur_tag,"/td") ||
checkTag(cur_tag,"h1") ||
checkTag(cur_tag,"/h1") ||
checkTag(cur_tag,"h2") ||
checkTag(cur_tag,"/h2") ||
checkTag(cur_tag,"h3") ||
checkTag(cur_tag,"/h3")
)
{
if (NotTextTags.empty())
{
result += "\n\n";
addOffset(old_offset);
addOffset(cur_offset-1);
};
state = spaces;
}
break;
default :
cur_tag += ch;
}
break;
}
case amp:
{
if(isalnum(ch))
cur_amp += ch;
else
{
if(ch != ';') next_read = false;
if (NotTextTags.empty())
{
if(cur_amp == "amp") { result += "&"; addOffset(old_offset); }
else if(cur_amp == "lt") { result += "<"; addOffset(old_offset); }
else if(cur_amp == "gt") { result += ">"; addOffset(old_offset); }
else if(cur_amp == "nbsp") { result += " "; addOffset(old_offset); }
else if(cur_amp == "ouml") { result += ouml; addOffset(old_offset); }
else if(cur_amp == "auml") { result += auml; addOffset(old_offset); }
else if(cur_amp == "uuml") { result += uuml; addOffset(old_offset); }
else if(cur_amp == "Ouml") { result += Ouml; addOffset(old_offset); }
else if(cur_amp == "Auml") { result += Auml; addOffset(old_offset); }
else if(cur_amp == "Uuml") { result += Uuml; addOffset(old_offset); }
else if(cur_amp == "szlig") { result += szlig; addOffset(old_offset); }
else if(cur_amp == "agrave") { result += agrave; addOffset(old_offset); }
else if(cur_amp == "egrave") { result += egrave; addOffset(old_offset); }
else if(cur_amp == "eacute") { result += eacute; addOffset(old_offset); }
}
state = normal;
}
break;
}
case spaces:
{
if(!isspace(ch))
{
state = normal;
next_read = false;
}
break;
}
}
}
return result;
}
/*
* Check tag in the string
*/
bool HTML::checkTag(const string& str, const char* tag)
{
string::const_iterator i = str.begin();
const char* j;
for( ; i != str.end(); i++) if(!isspace(*i)) break;
for(j = tag; *j && i != str.end(); j++, i++)
if(toupper(*j) != toupper(*i))
break;
if(*j) return false;
if(i == str.end()) return true;
if(isspace(*i)) return true;
return false;
}
/***************************************************************************
* Very simple parser
*/
string HTML::GetTextFromHtmlFile(string FileName)
{
string result;
FILE* fp = fopen(FileName.c_str(), "rb");
vector<char> buffer;
for (;;)
{
int ch = fgetc(fp);
if(ch == EOF) break;
buffer.push_back(ch);
};
fclose (fp);
if (buffer.empty()) return "";
return GetTextFromHTMLBuffer(&buffer[0], buffer.size());
}
|
lgpl-2.1
|
krafczyk/root-5.34.09-ams
|
cint/demo/graphs/modulation.c
|
7
|
1056
|
/* -*- C++ -*- */
/*************************************************************************
* Copyright(c) 1995~2005 Masaharu Goto (root-cint@cern.ch)
*
* For the licensing terms see the file COPYING
*
************************************************************************/
/*************************************************************************
* modulation.c
*
* array and fft pre-compiled class library is needed to run
* this demo program.
*************************************************************************/
#include <array.h>
#include <fft.h>
const double PI=3.141592;
main() {
// create AM waveform and plot
// start , stop ,npoint
array time=array(-20*PI , 20*PI , 256 ),y1;
y1 = sin(time)*sin(time/10);
plot << "time domain" << time << "time" << y1 << "\n";
// FFT and save data
array freq,y2;
spectrum << time << y1 >> freq >> y2 >> endl;
arrayostream("datafile") << "freq domain" << freq << y2 << endl;
// load data and and plot
graphbuf buf;
arrayistream("datafile") >> buf;
plot << buf ;
}
|
lgpl-2.1
|
mgrunditz/qtdeclarative-2d
|
src/particles/qquickpointattractor.cpp
|
7
|
5526
|
/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtQuick module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** 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 Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file. Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qquickpointattractor_p.h"
#include <cmath>
#include <QDebug>
QT_BEGIN_NAMESPACE
/*!
\qmltype Attractor
\instantiates QQuickAttractorAffector
\inqmlmodule QtQuick.Particles 2
\ingroup qtquick-particles
\inherits Affector
\brief For attracting particles towards a specific point
Note that the size and position of this element affects which particles it affects.
The size of the point attracted to is always 0x0, and the location of that point
is specified by the pointX and pointY properties.
Note that Attractor has the standard Item x,y,width and height properties.
Like other affectors, these represent the affected area. They
do not represent the 0x0 point which is the target of the attraction.
*/
/*!
\qmlproperty real QtQuick.Particles::PointAttractor::pointX
The x coordinate of the attracting point. This is relative
to the x coordinate of the Attractor.
*/
/*!
\qmlproperty real QtQuick.Particles::PointAttractor::pointY
The y coordinate of the attracting point. This is relative
to the y coordinate of the Attractor.
*/
/*!
\qmlproperty real QtQuick.Particles::PointAttractor::strength
The pull, in units per second, to be exerted on an item one pixel away.
Depending on how the attraction is proportionalToDistance this may have to
be very high or very low to have a reasonable effect on particles at a
distance.
*/
/*!
\qmlproperty AffectableParameter QtQuick.Particles::Attractor::affectedParameter
What attribute of particles is directly affected.
\list
\li Attractor.Position
\li Attractor.Velocity
\li Attractor.Acceleration
\endlist
*/
/*!
\qmlproperty Proportion QtQuick.Particles::Attractor::proportionalToDistance
How the distance from the particle to the point affects the strength of the attraction.
\list
\li Attractor.Constant
\li Attractor.Linear
\li Attractor.InverseLinear
\li Attractor.Quadratic
\li Attractor.InverseQuadratic
\endlist
*/
QQuickAttractorAffector::QQuickAttractorAffector(QQuickItem *parent) :
QQuickParticleAffector(parent), m_strength(0.0), m_x(0), m_y(0)
, m_physics(Velocity), m_proportionalToDistance(Linear)
{
}
bool QQuickAttractorAffector::affectParticle(QQuickParticleData *d, qreal dt)
{
if (m_strength == 0.0)
return false;
qreal dx = m_x+m_offset.x() - d->curX();
qreal dy = m_y+m_offset.y() - d->curY();
qreal r = std::sqrt((dx*dx) + (dy*dy));
qreal theta = std::atan2(dy,dx);
qreal ds = 0;
switch (m_proportionalToDistance){
case InverseQuadratic:
ds = (m_strength / qMax<qreal>(1.,r*r));
break;
case InverseLinear:
ds = (m_strength / qMax<qreal>(1.,r));
break;
case Quadratic:
ds = (m_strength * qMax<qreal>(1.,r*r));
break;
case Linear:
ds = (m_strength * qMax<qreal>(1.,r));
break;
default: //also Constant
ds = m_strength;
}
ds *= dt;
dx = ds * std::cos(theta);
dy = ds * std::sin(theta);
qreal vx,vy;
switch (m_physics){
case Position:
d->x = (d->x + dx);
d->y = (d->y + dy);
break;
case Acceleration:
d->setInstantaneousAX(d->ax + dx);
d->setInstantaneousAY(d->ay + dy);
break;
case Velocity: //also default
default:
vx = d->curVX();
vy = d->curVY();
d->setInstantaneousVX(vx + dx);
d->setInstantaneousVY(vy + dy);
}
return true;
}
QT_END_NAMESPACE
|
lgpl-2.1
|
chrta/canfestival-3-ct
|
examples/TestMasterSlaveLSS/TestMasterSlaveLSS.c
|
10
|
10110
|
/*
This file is part of CanFestival, a library implementing CanOpen Stack.
Copyright (C): Edouard TISSERANT and Francis DUPIN
See COPYING file for copyrights details.
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#if defined(WIN32) && !defined(__CYGWIN__)
#include <windows.h>
#include "getopt.h"
void pause(void)
{
system("PAUSE");
}
#else
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <stdlib.h>
#include <signal.h>
#endif
#include "canfestival.h"
//#include <can_driver.h>
//#include <timers_driver.h>
#include "Master.h"
#include "SlaveA.h"
#include "SlaveB.h"
#include "TestMasterSlaveLSS.h"
s_BOARD SlaveBoardA = {"0", "125K"};
s_BOARD SlaveBoardB = {"1", "125K"};
s_BOARD MasterBoard = {"2", "125K"};
#if !defined(WIN32) || defined(__CYGWIN__)
void catch_signal(int sig)
{
signal(SIGTERM, catch_signal);
signal(SIGINT, catch_signal);
eprintf("Got Signal %d\n",sig);
}
#endif
void help(void)
{
printf("**************************************************************\n");
printf("* TestMasterSlaveLSS *\n");
printf("* *\n");
printf("* A LSS example for PC. It does implement 3 CanOpen *\n");
printf("* nodes in the same process. A master and 2 slaves. All *\n");
printf("* communicate together, exchanging periodically NMT, SYNC, *\n");
printf("* SDO and PDO. Master configure heartbeat producer time *\n");
printf("* at 1000 ms for the slaves by concise DCF. *\n");
printf("* *\n");
printf("* Usage: *\n");
printf("* ./TestMasterSlaveLSS [OPTIONS] *\n");
printf("* *\n");
printf("* OPTIONS: *\n");
printf("* -l : Can library [\"libcanfestival_can_virtual.so\"] *\n");
printf("* *\n");
printf("* SlaveA: *\n");
printf("* -a : bus name [\"0\"] *\n");
printf("* -A : 1M,500K,250K,125K,100K,50K,20K,10K,none(disable) *\n");
printf("* *\n");
printf("* SlaveB: *\n");
printf("* -b : bus name [\"1\"] *\n");
printf("* -B : 1M,500K,250K,125K,100K,50K,20K,10K,none(disable) *\n");
printf("* *\n");
printf("* Master: *\n");
printf("* -m : bus name [\"2\"] *\n");
printf("* -M : 1M,500K,250K,125K,100K,50K,20K,10K,none(disable) *\n");
printf("* *\n");
printf("**************************************************************\n");
}
/*************************** INIT *****************************************/
void InitNodes(CO_Data* d, UNS32 id)
{
/****************************** INITIALISATION SLAVE_A *******************************/
if(strcmp(SlaveBoardA.baudrate, "none")) {
/* Set an invalid nodeID */
setNodeId(&TestSlaveA_Data, 0xFF);
/* init */
setState(&TestSlaveA_Data, Initialisation);
}
/****************************** INITIALISATION SLAVE_B *******************************/
if(strcmp(SlaveBoardB.baudrate, "none")) {
/* Set an invalid nodeID */
setNodeId(&TestSlaveB_Data, 0xFF);
/* init */
setState(&TestSlaveB_Data, Initialisation);
}
/****************************** INITIALISATION MASTER *******************************/
if(strcmp(MasterBoard.baudrate, "none")){
/* Defining the node Id */
setNodeId(&TestMaster_Data, 0x01);
/* init */
setState(&TestMaster_Data, Initialisation);
}
}
/*************************** EXIT *****************************************/
void Exit(CO_Data* d, UNS32 id)
{
if(strcmp(MasterBoard.baudrate, "none")){
eprintf("Finishing.\n");
masterSendNMTstateChange (&TestMaster_Data, 0x00, NMT_Stop_Node);
eprintf("reset\n");
// Stop master
setState(&TestMaster_Data, Stopped);
}
}
/****************************************************************************/
/*************************** MAIN *****************************************/
/****************************************************************************/
int main(int argc,char **argv)
{
int c;
extern char *optarg;
char* LibraryPath="../../drivers/can_virtual/libcanfestival_can_virtual.so";
while ((c = getopt(argc, argv, "-m:a:b:M:A:B:l:")) != EOF)
{
switch(c)
{
case 'a' :
if (optarg[0] == 0)
{
help();
exit(1);
}
SlaveBoardA.busname = optarg;
break;
case 'b' :
if (optarg[0] == 0)
{
help();
exit(1);
}
SlaveBoardB.busname = optarg;
break;
case 'm' :
if (optarg[0] == 0)
{
help();
exit(1);
}
MasterBoard.busname = optarg;
break;
case 'A' :
if (optarg[0] == 0)
{
help();
exit(1);
}
SlaveBoardA.baudrate = optarg;
break;
case 'B' :
if (optarg[0] == 0)
{
help();
exit(1);
}
SlaveBoardB.baudrate = optarg;
break;
case 'M' :
if (optarg[0] == 0)
{
help();
exit(1);
}
MasterBoard.baudrate = optarg;
break;
case 'l' :
if (optarg[0] == 0)
{
help();
exit(1);
}
LibraryPath = optarg;
break;
default:
help();
exit(1);
}
}
#if !defined(WIN32) || defined(__CYGWIN__)
/* install signal handler for manual break */
signal(SIGTERM, catch_signal);
signal(SIGINT, catch_signal);
TimerInit();
#endif
#ifndef NOT_USE_DYNAMIC_LOADING
if (LoadCanDriver(LibraryPath) == NULL)
printf("Unable to load library: %s\n",LibraryPath);
#endif
// Open CAN devices
if(strcmp(SlaveBoardA.baudrate, "none")){
TestSlaveA_Data.heartbeatError = TestSlaveA_heartbeatError;
TestSlaveA_Data.initialisation = TestSlaveA_initialisation;
TestSlaveA_Data.preOperational = TestSlaveA_preOperational;
TestSlaveA_Data.operational = TestSlaveA_operational;
TestSlaveA_Data.stopped = TestSlaveA_stopped;
TestSlaveA_Data.post_sync = TestSlaveA_post_sync;
TestSlaveA_Data.post_TPDO = TestSlaveA_post_TPDO;
TestSlaveA_Data.storeODSubIndex = TestSlaveA_storeODSubIndex;
TestSlaveA_Data.post_emcy = TestSlaveA_post_emcy;
/* in this example the slave doesn't implement NMT_Slave_Communications_Reset_Callback */
//TestSlaveA_Data.NMT_Slave_Communications_Reset_Callback = TestSlaveA_NMT_Slave_Communications_Reset_Callback;
TestSlaveA_Data.lss_StoreConfiguration = TestSlaveA_StoreConfiguration;
if(!canOpen(&SlaveBoardA,&TestSlaveA_Data)){
eprintf("Cannot open SlaveA Board (%s,%s)\n",SlaveBoardA.busname, SlaveBoardA.baudrate);
goto fail_slaveA;
}
}
if(strcmp(SlaveBoardB.baudrate, "none")){
TestSlaveB_Data.heartbeatError = TestSlaveB_heartbeatError;
TestSlaveB_Data.initialisation = TestSlaveB_initialisation;
TestSlaveB_Data.preOperational = TestSlaveB_preOperational;
TestSlaveB_Data.operational = TestSlaveB_operational;
TestSlaveB_Data.stopped = TestSlaveB_stopped;
TestSlaveB_Data.post_sync = TestSlaveB_post_sync;
TestSlaveB_Data.post_TPDO = TestSlaveB_post_TPDO;
TestSlaveB_Data.storeODSubIndex = TestSlaveB_storeODSubIndex;
TestSlaveB_Data.post_emcy = TestSlaveB_post_emcy;
TestSlaveB_Data.NMT_Slave_Communications_Reset_Callback = TestSlaveB_NMT_Slave_Communications_Reset_Callback;
TestSlaveB_Data.lss_StoreConfiguration = TestSlaveB_StoreConfiguration;
if(!canOpen(&SlaveBoardB,&TestSlaveB_Data)){
eprintf("Cannot open SlaveB Board (%s,%s)\n",SlaveBoardB.busname, SlaveBoardB.baudrate);
goto fail_slaveB;
}
}
if(strcmp(MasterBoard.baudrate, "none")){
TestMaster_Data.heartbeatError = TestMaster_heartbeatError;
TestMaster_Data.initialisation = TestMaster_initialisation;
TestMaster_Data.preOperational = TestMaster_preOperational;
TestMaster_Data.operational = TestMaster_operational;
TestMaster_Data.stopped = TestMaster_stopped;
TestMaster_Data.post_sync = TestMaster_post_sync;
TestMaster_Data.post_TPDO = TestMaster_post_TPDO;
TestMaster_Data.post_emcy = TestMaster_post_emcy;
TestMaster_Data.post_SlaveBootup=TestMaster_post_SlaveBootup;
if(!canOpen(&MasterBoard,&TestMaster_Data)){
eprintf("Cannot open Master Board (%s,%s)\n",MasterBoard.busname, MasterBoard.baudrate);
goto fail_master;
}
}
// Start timer thread
StartTimerLoop(&InitNodes);
// wait Ctrl-C
pause();
// Stop timer thread
StopTimerLoop(&Exit);
// Close CAN devices (and can threads)
if(strcmp(MasterBoard.baudrate, "none")) canClose(&TestMaster_Data);
fail_master:
if(strcmp(SlaveBoardB.baudrate, "none")) canClose(&TestSlaveB_Data);
fail_slaveB:
if(strcmp(SlaveBoardA.baudrate, "none")) canClose(&TestSlaveA_Data);
fail_slaveA:
TimerCleanup();
return 0;
}
|
lgpl-2.1
|
cxhernandez/msmbuilder
|
msmbuilder/msm/src/metzner_mcmc.c
|
12
|
3690
|
/**
* Author: Robert T. McGibbon
* Contributors:
* Copyright: 2014 Stanford University and the Authors
*
* Implementation of the reversible transition matrix sampler from [1].
*
* .. [1] P. Metzner, F. Noe and C. Schutte, "Estimating the sampling error:
* Distribution of transition matrices and functions of transition
* matrices for given trajectory data." Phys. Rev. E 80 021106 (2009)
*/
#include <stdio.h>
#include <math.h>
#define MAX(X,Y) ((X) > (Y) ? (X) : (Y))
/* Upper and lower bounds on the sum of the K matrix, to ensure proper *
/* proposal weights. See Eq. 17 of [1]. */
static const double K_MINUS = 0.9;
static const double K_PLUS = 1.1;
static double
acceptance_ratio(int i, int j, int n_states, double epsilon,
const double* Z,
const double* K,
const double* N,
const double* Q)
{
double term1, term2, term3, term4;
term1 = Z[i*n_states + j] * (log(K[i*n_states + j] + epsilon) - log(K[i*n_states + j]));
term3 = N[i] * (log(Q[i]) - log(Q[i] + (epsilon)));
if (i == j)
return exp(term1 + term3);
term2 = Z[j*n_states + i] * (log(K[j*n_states + i] + epsilon) - log(K[j*n_states + i]));
term4 = N[j] * (log(Q[j]) - log(Q[j] + (epsilon)));
return exp(term1 + term2 + term3 + term4);
}
/**
* Run n_steps of Metropolis MCMC for the Metzner reversible transition
* matrix sampler
*
* Parameters
* ----------
* Z : [in] array, shape=(n_states, n_states)
* Effective number of transition counts (the sufficient statistic)
* N : [in] array, shape=(n_states)
* Row-sums of Z
* K : [in/out] array, shape=(n_states, n_states)
* The parameters being sampled -- the "virtual counts". These parameters
* are directly modified when a step is accepted. Note that K is symmetric,
* and will stay symmetric.
* Q : [in/out] array, shape=(n_states)
* Row-sums of K. This will
* random : [in] array, shape=(n_steps * 4)
* Array of n_steps*4 random doubles in [0, 1). The quality of the C
* stdlib's random number generation is pretty flakey, so instead this
* requires the caller to pass in random numbers its own source (e.g. numpy)
* n_states : int
* The dimension for the matrices
* n_steps : int
* The number of MCMC steps to take. The K and Q matrices will be updated
* on acceptances.
*/
void
metzner_mcmc_step(const double* Z, const double* N, double* K,
double* Q, const double* random, double* sc, int n_states,
int n_steps)
{
int i, j, t;
double a, b, r, epsilon, cutoff;
for (t = 0; t < n_steps; t++) {
i = (int) ((*(random++)) * n_states);
j = (int) ((*(random++)) * n_states);
if (i == j) {
a = MAX(-K[i*n_states+j], K_MINUS - (*sc));
b = K_PLUS - (*sc);
} else {
a = MAX(-K[i*n_states+j], 0.5*(K_MINUS - (*sc)));
b = 0.5 * (K_PLUS - (*sc));
}
epsilon = a + (*(random++)) * (b-a);
cutoff = acceptance_ratio(i, j, n_states, epsilon, Z, K, N, Q);
r = (*(random++));
/* printf("i=%d, j=%d\n", i, j); */
/* printf("a=%f, b=%f\n", a, b); */
/* printf("epsilon=%f\n", epsilon); */
/* printf("cutoff=%f\n", cutoff); */
/* printf("sc = %f\n", (*sc)); */
/* printf("r=%f\n", r); */
if (r < cutoff) {
K[i*n_states + j] += epsilon;
(*sc) += epsilon;
Q[i] += epsilon;
if (i != j) {
K[j*n_states + i] += epsilon;
(*sc) += epsilon;
Q[j] += epsilon;
}
}
}
}
|
lgpl-2.1
|
Corillian/libgit2
|
tests/checkout/checkout_helpers.c
|
12
|
3584
|
#include "clar_libgit2.h"
#include "checkout_helpers.h"
#include "refs.h"
#include "fileops.h"
#include "index.h"
void assert_on_branch(git_repository *repo, const char *branch)
{
git_reference *head;
git_buf bname = GIT_BUF_INIT;
cl_git_pass(git_reference_lookup(&head, repo, GIT_HEAD_FILE));
cl_assert_(git_reference_type(head) == GIT_REF_SYMBOLIC, branch);
cl_git_pass(git_buf_joinpath(&bname, "refs/heads", branch));
cl_assert_equal_s(bname.ptr, git_reference_symbolic_target(head));
git_reference_free(head);
git_buf_free(&bname);
}
void reset_index_to_treeish(git_object *treeish)
{
git_object *tree;
git_index *index;
git_repository *repo = git_object_owner(treeish);
cl_git_pass(git_object_peel(&tree, treeish, GIT_OBJ_TREE));
cl_git_pass(git_repository_index(&index, repo));
cl_git_pass(git_index_read_tree(index, (git_tree *)tree));
cl_git_pass(git_index_write(index));
git_object_free(tree);
git_index_free(index);
}
int checkout_count_callback(
git_checkout_notify_t why,
const char *path,
const git_diff_file *baseline,
const git_diff_file *target,
const git_diff_file *workdir,
void *payload)
{
checkout_counts *ct = payload;
GIT_UNUSED(baseline); GIT_UNUSED(target); GIT_UNUSED(workdir);
if (why & GIT_CHECKOUT_NOTIFY_CONFLICT) {
ct->n_conflicts++;
if (ct->debug) {
if (workdir) {
if (baseline) {
if (target)
fprintf(stderr, "M %s (conflicts with M %s)\n",
workdir->path, target->path);
else
fprintf(stderr, "M %s (conflicts with D %s)\n",
workdir->path, baseline->path);
} else {
if (target)
fprintf(stderr, "Existing %s (conflicts with A %s)\n",
workdir->path, target->path);
else
fprintf(stderr, "How can an untracked file be a conflict (%s)\n", workdir->path);
}
} else {
if (baseline) {
if (target)
fprintf(stderr, "D %s (conflicts with M %s)\n",
target->path, baseline->path);
else
fprintf(stderr, "D %s (conflicts with D %s)\n",
baseline->path, baseline->path);
} else {
if (target)
fprintf(stderr, "How can an added file with no workdir be a conflict (%s)\n", target->path);
else
fprintf(stderr, "How can a nonexistent file be a conflict (%s)\n", path);
}
}
}
}
if (why & GIT_CHECKOUT_NOTIFY_DIRTY) {
ct->n_dirty++;
if (ct->debug) {
if (workdir)
fprintf(stderr, "M %s\n", workdir->path);
else
fprintf(stderr, "D %s\n", baseline->path);
}
}
if (why & GIT_CHECKOUT_NOTIFY_UPDATED) {
ct->n_updates++;
if (ct->debug) {
if (baseline) {
if (target)
fprintf(stderr, "update: M %s\n", path);
else
fprintf(stderr, "update: D %s\n", path);
} else {
if (target)
fprintf(stderr, "update: A %s\n", path);
else
fprintf(stderr, "update: this makes no sense %s\n", path);
}
}
}
if (why & GIT_CHECKOUT_NOTIFY_UNTRACKED) {
ct->n_untracked++;
if (ct->debug)
fprintf(stderr, "? %s\n", path);
}
if (why & GIT_CHECKOUT_NOTIFY_IGNORED) {
ct->n_ignored++;
if (ct->debug)
fprintf(stderr, "I %s\n", path);
}
return 0;
}
void tick_index(git_index *index)
{
struct timespec ts;
struct p_timeval times[2];
cl_assert(index->on_disk);
cl_assert(git_index_path(index));
cl_git_pass(git_index_read(index, true));
ts = index->stamp.mtime;
times[0].tv_sec = ts.tv_sec;
times[0].tv_usec = ts.tv_nsec / 1000;
times[1].tv_sec = ts.tv_sec + 5;
times[1].tv_usec = ts.tv_nsec / 1000;
cl_git_pass(p_utimes(git_index_path(index), times));
cl_git_pass(git_index_read(index, true));
}
|
lgpl-2.1
|
iConsole/Console-OS_external_bluetooth_glib
|
glib/gdataset.c
|
14
|
36927
|
/* GLIB - Library of useful routines for C programming
* Copyright (C) 1995-1997 Peter Mattis, Spencer Kimball and Josh MacDonald
*
* gdataset.c: Generic dataset mechanism, similar to GtkObject data.
* Copyright (C) 1998 Tim Janik
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA.
*/
/*
* Modified by the GLib Team and others 1997-2000. See the AUTHORS
* file for a list of people on the GLib Team. See the ChangeLog
* files for a list of changes. These files are distributed with
* GLib at ftp://ftp.gtk.org/pub/gtk/.
*/
/*
* MT safe ; except for g_data*_foreach()
*/
#include "config.h"
#include <string.h>
#include "gdataset.h"
#include "gbitlock.h"
#include "gslice.h"
#include "gdatasetprivate.h"
#include "ghash.h"
#include "gquark.h"
#include "gstrfuncs.h"
#include "gtestutils.h"
#include "gthread.h"
#include "glib_trace.h"
/**
* SECTION:datasets
* @title: Datasets
* @short_description: associate groups of data elements with
* particular memory locations
*
* Datasets associate groups of data elements with particular memory
* locations. These are useful if you need to associate data with a
* structure returned from an external library. Since you cannot modify
* the structure, you use its location in memory as the key into a
* dataset, where you can associate any number of data elements with it.
*
* There are two forms of most of the dataset functions. The first form
* uses strings to identify the data elements associated with a
* location. The second form uses #GQuark identifiers, which are
* created with a call to g_quark_from_string() or
* g_quark_from_static_string(). The second form is quicker, since it
* does not require looking up the string in the hash table of #GQuark
* identifiers.
*
* There is no function to create a dataset. It is automatically
* created as soon as you add elements to it.
*
* To add data elements to a dataset use g_dataset_id_set_data(),
* g_dataset_id_set_data_full(), g_dataset_set_data() and
* g_dataset_set_data_full().
*
* To get data elements from a dataset use g_dataset_id_get_data() and
* g_dataset_get_data().
*
* To iterate over all data elements in a dataset use
* g_dataset_foreach() (not thread-safe).
*
* To remove data elements from a dataset use
* g_dataset_id_remove_data() and g_dataset_remove_data().
*
* To destroy a dataset, use g_dataset_destroy().
**/
/**
* SECTION:datalist
* @title: Keyed Data Lists
* @short_description: lists of data elements which are accessible by a
* string or GQuark identifier
*
* Keyed data lists provide lists of arbitrary data elements which can
* be accessed either with a string or with a #GQuark corresponding to
* the string.
*
* The #GQuark methods are quicker, since the strings have to be
* converted to #GQuarks anyway.
*
* Data lists are used for associating arbitrary data with #GObjects,
* using g_object_set_data() and related functions.
*
* To create a datalist, use g_datalist_init().
*
* To add data elements to a datalist use g_datalist_id_set_data(),
* g_datalist_id_set_data_full(), g_datalist_set_data() and
* g_datalist_set_data_full().
*
* To get data elements from a datalist use g_datalist_id_get_data()
* and g_datalist_get_data().
*
* To iterate over all data elements in a datalist use
* g_datalist_foreach() (not thread-safe).
*
* To remove data elements from a datalist use
* g_datalist_id_remove_data() and g_datalist_remove_data().
*
* To remove all data elements from a datalist, use g_datalist_clear().
**/
/**
* GData:
*
* The #GData struct is an opaque data structure to represent a <link
* linkend="glib-Keyed-Data-Lists">Keyed Data List</link>. It should
* only be accessed via the following functions.
**/
/**
* GDestroyNotify:
* @data: the data element.
*
* Specifies the type of function which is called when a data element
* is destroyed. It is passed the pointer to the data element and
* should free any memory and resources allocated for it.
**/
/* --- defines --- */
#define G_QUARK_BLOCK_SIZE (2048)
#define G_DATALIST_FLAGS_MASK_INTERNAL 0x7
/* datalist pointer accesses have to be carried out atomically */
#define G_DATALIST_GET_POINTER(datalist) \
((GData*) ((gsize) g_atomic_pointer_get (datalist) & ~(gsize) G_DATALIST_FLAGS_MASK_INTERNAL))
#define G_DATALIST_SET_POINTER(datalist, pointer) G_STMT_START { \
gpointer _oldv, _newv; \
do { \
_oldv = g_atomic_pointer_get (datalist); \
_newv = (gpointer) (((gsize) _oldv & G_DATALIST_FLAGS_MASK_INTERNAL) | (gsize) pointer); \
} while (!g_atomic_pointer_compare_and_exchange ((void**) datalist, _oldv, _newv)); \
} G_STMT_END
/* --- structures --- */
typedef struct {
GQuark key;
gpointer data;
GDestroyNotify destroy;
} GDataElt;
typedef struct _GDataset GDataset;
struct _GData
{
guint32 len; /* Number of elements */
guint32 alloc; /* Number of allocated elements */
GDataElt data[1]; /* Flexible array */
};
struct _GDataset
{
gconstpointer location;
GData *datalist;
};
/* --- prototypes --- */
static inline GDataset* g_dataset_lookup (gconstpointer dataset_location);
static inline void g_datalist_clear_i (GData **datalist);
static void g_dataset_destroy_internal (GDataset *dataset);
static inline gpointer g_data_set_internal (GData **datalist,
GQuark key_id,
gpointer data,
GDestroyNotify destroy_func,
GDataset *dataset);
static void g_data_initialize (void);
static inline GQuark g_quark_new (gchar *string);
/* Locking model:
* Each standalone GDataList is protected by a bitlock in the datalist pointer,
* which protects that modification of the non-flags part of the datalist pointer
* and the contents of the datalist.
*
* For GDataSet we have a global lock g_dataset_global that protects
* the global dataset hash and cache, and additionally it protects the
* datalist such that we can avoid to use the bit lock in a few places
* where it is easy.
*/
/* --- variables --- */
G_LOCK_DEFINE_STATIC (g_dataset_global);
static GHashTable *g_dataset_location_ht = NULL;
static GDataset *g_dataset_cached = NULL; /* should this be
thread specific? */
G_LOCK_DEFINE_STATIC (g_quark_global);
static GHashTable *g_quark_ht = NULL;
static gchar **g_quarks = NULL;
static int g_quark_seq_id = 0;
/* --- functions --- */
#define DATALIST_LOCK_BIT 2
static void
g_datalist_lock (GData **datalist)
{
g_pointer_bit_lock ((void **)datalist, DATALIST_LOCK_BIT);
}
static void
g_datalist_unlock (GData **datalist)
{
g_pointer_bit_unlock ((void **)datalist, DATALIST_LOCK_BIT);
}
/* Called with the datalist lock held, or the dataset global
* lock for dataset lists
*/
static void
g_datalist_clear_i (GData **datalist)
{
GData *data;
gint i;
data = G_DATALIST_GET_POINTER (datalist);
G_DATALIST_SET_POINTER (datalist, NULL);
if (data)
{
G_UNLOCK (g_dataset_global);
for (i = 0; i < data->len; i++)
{
if (data->data[i].data && data->data[i].destroy)
data->data[i].destroy (data->data[i].data);
}
G_LOCK (g_dataset_global);
g_free (data);
}
}
/**
* g_datalist_clear:
* @datalist: a datalist.
*
* Frees all the data elements of the datalist.
* The data elements' destroy functions are called
* if they have been set.
**/
void
g_datalist_clear (GData **datalist)
{
GData *data;
gint i;
g_return_if_fail (datalist != NULL);
g_datalist_lock (datalist);
data = G_DATALIST_GET_POINTER (datalist);
G_DATALIST_SET_POINTER (datalist, NULL);
g_datalist_unlock (datalist);
if (data)
{
for (i = 0; i < data->len; i++)
{
if (data->data[i].data && data->data[i].destroy)
data->data[i].destroy (data->data[i].data);
}
g_free (data);
}
}
/* HOLDS: g_dataset_global_lock */
static inline GDataset*
g_dataset_lookup (gconstpointer dataset_location)
{
register GDataset *dataset;
if (g_dataset_cached && g_dataset_cached->location == dataset_location)
return g_dataset_cached;
dataset = g_hash_table_lookup (g_dataset_location_ht, dataset_location);
if (dataset)
g_dataset_cached = dataset;
return dataset;
}
/* HOLDS: g_dataset_global_lock */
static void
g_dataset_destroy_internal (GDataset *dataset)
{
register gconstpointer dataset_location;
dataset_location = dataset->location;
while (dataset)
{
if (G_DATALIST_GET_POINTER(&dataset->datalist) == NULL)
{
if (dataset == g_dataset_cached)
g_dataset_cached = NULL;
g_hash_table_remove (g_dataset_location_ht, dataset_location);
g_slice_free (GDataset, dataset);
break;
}
g_datalist_clear_i (&dataset->datalist);
dataset = g_dataset_lookup (dataset_location);
}
}
/**
* g_dataset_destroy:
* @dataset_location: the location identifying the dataset.
*
* Destroys the dataset, freeing all memory allocated, and calling any
* destroy functions set for data elements.
*/
void
g_dataset_destroy (gconstpointer dataset_location)
{
g_return_if_fail (dataset_location != NULL);
G_LOCK (g_dataset_global);
if (g_dataset_location_ht)
{
register GDataset *dataset;
dataset = g_dataset_lookup (dataset_location);
if (dataset)
g_dataset_destroy_internal (dataset);
}
G_UNLOCK (g_dataset_global);
}
/* HOLDS: g_dataset_global_lock if dataset != null */
static inline gpointer
g_data_set_internal (GData **datalist,
GQuark key_id,
gpointer new_data,
GDestroyNotify new_destroy_func,
GDataset *dataset)
{
GData *d, *old_d;
GDataElt old, *data, *data_last, *data_end;
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (new_data == NULL) /* remove */
{
if (d)
{
data = d->data;
data_last = data + d->len - 1;
while (data <= data_last)
{
if (data->key == key_id)
{
old = *data;
if (data != data_last)
*data = *data_last;
d->len--;
/* We don't bother to shrink, but if all data are now gone
* we at least free the memory
*/
if (d->len == 0)
{
G_DATALIST_SET_POINTER (datalist, NULL);
g_free (d);
/* datalist may be situated in dataset, so must not be
* unlocked after we free it
*/
g_datalist_unlock (datalist);
/* the dataset destruction *must* be done
* prior to invocation of the data destroy function
*/
if (dataset)
g_dataset_destroy_internal (dataset);
}
else
{
g_datalist_unlock (datalist);
}
/* We found and removed an old value
* the GData struct *must* already be unlinked
* when invoking the destroy function.
* we use (new_data==NULL && new_destroy_func!=NULL) as
* a special hint combination to "steal"
* data without destroy notification
*/
if (old.destroy && !new_destroy_func)
{
if (dataset)
G_UNLOCK (g_dataset_global);
old.destroy (old.data);
if (dataset)
G_LOCK (g_dataset_global);
old.data = NULL;
}
return old.data;
}
data++;
}
}
}
else
{
old.data = NULL;
if (d)
{
data = d->data;
data_end = data + d->len;
while (data < data_end)
{
if (data->key == key_id)
{
if (!data->destroy)
{
data->data = new_data;
data->destroy = new_destroy_func;
g_datalist_unlock (datalist);
}
else
{
old = *data;
data->data = new_data;
data->destroy = new_destroy_func;
g_datalist_unlock (datalist);
/* We found and replaced an old value
* the GData struct *must* already be unlinked
* when invoking the destroy function.
*/
if (dataset)
G_UNLOCK (g_dataset_global);
old.destroy (old.data);
if (dataset)
G_LOCK (g_dataset_global);
}
return NULL;
}
data++;
}
}
/* The key was not found, insert it */
old_d = d;
if (d == NULL)
{
d = g_malloc (sizeof (GData));
d->len = 0;
d->alloc = 1;
}
else if (d->len == d->alloc)
{
d->alloc = d->alloc * 2;
d = g_realloc (d, sizeof (GData) + (d->alloc - 1) * sizeof (GDataElt));
}
if (old_d != d)
G_DATALIST_SET_POINTER (datalist, d);
d->data[d->len].key = key_id;
d->data[d->len].data = new_data;
d->data[d->len].destroy = new_destroy_func;
d->len++;
}
g_datalist_unlock (datalist);
return NULL;
}
/**
* g_dataset_id_set_data_full:
* @dataset_location: the location identifying the dataset.
* @key_id: the #GQuark id to identify the data element.
* @data: the data element.
* @destroy_func: the function to call when the data element is
* removed. This function will be called with the data
* element and can be used to free any memory allocated
* for it.
*
* Sets the data element associated with the given #GQuark id, and also
* the function to call when the data element is destroyed. Any
* previous data with the same key is removed, and its destroy function
* is called.
**/
/**
* g_dataset_set_data_full:
* @l: the location identifying the dataset.
* @k: the string to identify the data element.
* @d: the data element.
* @f: the function to call when the data element is removed. This
* function will be called with the data element and can be used to
* free any memory allocated for it.
*
* Sets the data corresponding to the given string identifier, and the
* function to call when the data element is destroyed.
**/
/**
* g_dataset_id_set_data:
* @l: the location identifying the dataset.
* @k: the #GQuark id to identify the data element.
* @d: the data element.
*
* Sets the data element associated with the given #GQuark id. Any
* previous data with the same key is removed, and its destroy function
* is called.
**/
/**
* g_dataset_set_data:
* @l: the location identifying the dataset.
* @k: the string to identify the data element.
* @d: the data element.
*
* Sets the data corresponding to the given string identifier.
**/
/**
* g_dataset_id_remove_data:
* @l: the location identifying the dataset.
* @k: the #GQuark id identifying the data element.
*
* Removes a data element from a dataset. The data element's destroy
* function is called if it has been set.
**/
/**
* g_dataset_remove_data:
* @l: the location identifying the dataset.
* @k: the string identifying the data element.
*
* Removes a data element corresponding to a string. Its destroy
* function is called if it has been set.
**/
void
g_dataset_id_set_data_full (gconstpointer dataset_location,
GQuark key_id,
gpointer data,
GDestroyNotify destroy_func)
{
register GDataset *dataset;
g_return_if_fail (dataset_location != NULL);
if (!data)
g_return_if_fail (destroy_func == NULL);
if (!key_id)
{
if (data)
g_return_if_fail (key_id > 0);
else
return;
}
G_LOCK (g_dataset_global);
if (!g_dataset_location_ht)
g_data_initialize ();
dataset = g_dataset_lookup (dataset_location);
if (!dataset)
{
dataset = g_slice_new (GDataset);
dataset->location = dataset_location;
g_datalist_init (&dataset->datalist);
g_hash_table_insert (g_dataset_location_ht,
(gpointer) dataset->location,
dataset);
}
g_data_set_internal (&dataset->datalist, key_id, data, destroy_func, dataset);
G_UNLOCK (g_dataset_global);
}
/**
* g_datalist_id_set_data_full:
* @datalist: a datalist.
* @key_id: the #GQuark to identify the data element.
* @data: (allow-none): the data element or %NULL to remove any previous element
* corresponding to @key_id.
* @destroy_func: the function to call when the data element is
* removed. This function will be called with the data
* element and can be used to free any memory allocated
* for it. If @data is %NULL, then @destroy_func must
* also be %NULL.
*
* Sets the data corresponding to the given #GQuark id, and the
* function to be called when the element is removed from the datalist.
* Any previous data with the same key is removed, and its destroy
* function is called.
**/
/**
* g_datalist_set_data_full:
* @dl: a datalist.
* @k: the string to identify the data element.
* @d: (allow-none): the data element, or %NULL to remove any previous element
* corresponding to @k.
* @f: the function to call when the data element is removed. This
* function will be called with the data element and can be used to
* free any memory allocated for it. If @d is %NULL, then @f must
* also be %NULL.
*
* Sets the data element corresponding to the given string identifier,
* and the function to be called when the data element is removed.
**/
/**
* g_datalist_id_set_data:
* @dl: a datalist.
* @q: the #GQuark to identify the data element.
* @d: (allow-none): the data element, or %NULL to remove any previous element
* corresponding to @q.
*
* Sets the data corresponding to the given #GQuark id. Any previous
* data with the same key is removed, and its destroy function is
* called.
**/
/**
* g_datalist_set_data:
* @dl: a datalist.
* @k: the string to identify the data element.
* @d: (allow-none): the data element, or %NULL to remove any previous element
* corresponding to @k.
*
* Sets the data element corresponding to the given string identifier.
**/
/**
* g_datalist_id_remove_data:
* @dl: a datalist.
* @q: the #GQuark identifying the data element.
*
* Removes an element, using its #GQuark identifier.
**/
/**
* g_datalist_remove_data:
* @dl: a datalist.
* @k: the string identifying the data element.
*
* Removes an element using its string identifier. The data element's
* destroy function is called if it has been set.
**/
void
g_datalist_id_set_data_full (GData **datalist,
GQuark key_id,
gpointer data,
GDestroyNotify destroy_func)
{
g_return_if_fail (datalist != NULL);
if (!data)
g_return_if_fail (destroy_func == NULL);
if (!key_id)
{
if (data)
g_return_if_fail (key_id > 0);
else
return;
}
g_data_set_internal (datalist, key_id, data, destroy_func, NULL);
}
/**
* g_dataset_id_remove_no_notify:
* @dataset_location: the location identifying the dataset.
* @key_id: the #GQuark ID identifying the data element.
* @Returns: the data previously stored at @key_id, or %NULL if none.
*
* Removes an element, without calling its destroy notification
* function.
**/
/**
* g_dataset_remove_no_notify:
* @l: the location identifying the dataset.
* @k: the string identifying the data element.
*
* Removes an element, without calling its destroy notifier.
**/
gpointer
g_dataset_id_remove_no_notify (gconstpointer dataset_location,
GQuark key_id)
{
gpointer ret_data = NULL;
g_return_val_if_fail (dataset_location != NULL, NULL);
G_LOCK (g_dataset_global);
if (key_id && g_dataset_location_ht)
{
GDataset *dataset;
dataset = g_dataset_lookup (dataset_location);
if (dataset)
ret_data = g_data_set_internal (&dataset->datalist, key_id, NULL, (GDestroyNotify) 42, dataset);
}
G_UNLOCK (g_dataset_global);
return ret_data;
}
/**
* g_datalist_id_remove_no_notify:
* @datalist: a datalist.
* @key_id: the #GQuark identifying a data element.
* @Returns: the data previously stored at @key_id, or %NULL if none.
*
* Removes an element, without calling its destroy notification
* function.
**/
/**
* g_datalist_remove_no_notify:
* @dl: a datalist.
* @k: the string identifying the data element.
*
* Removes an element, without calling its destroy notifier.
**/
gpointer
g_datalist_id_remove_no_notify (GData **datalist,
GQuark key_id)
{
gpointer ret_data = NULL;
g_return_val_if_fail (datalist != NULL, NULL);
if (key_id)
ret_data = g_data_set_internal (datalist, key_id, NULL, (GDestroyNotify) 42, NULL);
return ret_data;
}
/**
* g_dataset_id_get_data:
* @dataset_location: the location identifying the dataset.
* @key_id: the #GQuark id to identify the data element.
* @Returns: the data element corresponding to the #GQuark, or %NULL if
* it is not found.
*
* Gets the data element corresponding to a #GQuark.
**/
/**
* g_dataset_get_data:
* @l: the location identifying the dataset.
* @k: the string identifying the data element.
* @Returns: the data element corresponding to the string, or %NULL if
* it is not found.
*
* Gets the data element corresponding to a string.
**/
gpointer
g_dataset_id_get_data (gconstpointer dataset_location,
GQuark key_id)
{
gpointer retval = NULL;
g_return_val_if_fail (dataset_location != NULL, NULL);
G_LOCK (g_dataset_global);
if (key_id && g_dataset_location_ht)
{
GDataset *dataset;
dataset = g_dataset_lookup (dataset_location);
if (dataset)
retval = g_datalist_id_get_data (&dataset->datalist, key_id);
}
G_UNLOCK (g_dataset_global);
return retval;
}
/**
* g_datalist_id_get_data:
* @datalist: a datalist.
* @key_id: the #GQuark identifying a data element.
* @Returns: the data element, or %NULL if it is not found.
*
* Retrieves the data element corresponding to @key_id.
**/
gpointer
g_datalist_id_get_data (GData **datalist,
GQuark key_id)
{
gpointer res = NULL;
g_return_val_if_fail (datalist != NULL, NULL);
if (key_id)
{
GData *d;
GDataElt *data, *data_end;
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (d)
{
data = d->data;
data_end = data + d->len;
while (data < data_end)
{
if (data->key == key_id)
{
res = data->data;
break;
}
data++;
}
}
g_datalist_unlock (datalist);
}
return res;
}
/**
* g_datalist_get_data:
* @datalist: a datalist.
* @key: the string identifying a data element.
* @Returns: the data element, or %NULL if it is not found.
*
* Gets a data element, using its string identifier. This is slower than
* g_datalist_id_get_data() because it compares strings.
**/
gpointer
g_datalist_get_data (GData **datalist,
const gchar *key)
{
gpointer res = NULL;
GData *d;
GDataElt *data, *data_end;
g_return_val_if_fail (datalist != NULL, NULL);
g_datalist_lock (datalist);
d = G_DATALIST_GET_POINTER (datalist);
if (d)
{
data = d->data;
data_end = data + d->len;
while (data < data_end)
{
if (strcmp (g_quark_to_string (data->key), key) == 0)
{
res = data->data;
break;
}
data++;
}
}
g_datalist_unlock (datalist);
return res;
}
/**
* GDataForeachFunc:
* @key_id: the #GQuark id to identifying the data element.
* @data: the data element.
* @user_data: user data passed to g_dataset_foreach().
*
* Specifies the type of function passed to g_dataset_foreach(). It is
* called with each #GQuark id and associated data element, together
* with the @user_data parameter supplied to g_dataset_foreach().
**/
/**
* g_dataset_foreach:
* @dataset_location: the location identifying the dataset.
* @func: the function to call for each data element.
* @user_data: user data to pass to the function.
*
* Calls the given function for each data element which is associated
* with the given location. Note that this function is NOT thread-safe.
* So unless @datalist can be protected from any modifications during
* invocation of this function, it should not be called.
**/
void
g_dataset_foreach (gconstpointer dataset_location,
GDataForeachFunc func,
gpointer user_data)
{
register GDataset *dataset;
g_return_if_fail (dataset_location != NULL);
g_return_if_fail (func != NULL);
G_LOCK (g_dataset_global);
if (g_dataset_location_ht)
{
dataset = g_dataset_lookup (dataset_location);
G_UNLOCK (g_dataset_global);
if (dataset)
g_datalist_foreach (&dataset->datalist, func, user_data);
}
else
{
G_UNLOCK (g_dataset_global);
}
}
/**
* g_datalist_foreach:
* @datalist: a datalist.
* @func: the function to call for each data element.
* @user_data: user data to pass to the function.
*
* Calls the given function for each data element of the datalist. The
* function is called with each data element's #GQuark id and data,
* together with the given @user_data parameter. Note that this
* function is NOT thread-safe. So unless @datalist can be protected
* from any modifications during invocation of this function, it should
* not be called.
**/
void
g_datalist_foreach (GData **datalist,
GDataForeachFunc func,
gpointer user_data)
{
GData *d;
int i, j, len;
GQuark *keys;
g_return_if_fail (datalist != NULL);
g_return_if_fail (func != NULL);
d = G_DATALIST_GET_POINTER (datalist);
if (d == NULL)
return;
/* We make a copy of the keys so that we can handle it changing
in the callback */
len = d->len;
keys = g_new (GQuark, len);
for (i = 0; i < len; i++)
keys[i] = d->data[i].key;
for (i = 0; i < len; i++)
{
/* A previous callback might have removed a later item, so always check that
it still exists before calling */
d = G_DATALIST_GET_POINTER (datalist);
if (d == NULL)
break;
for (j = 0; j < d->len; j++)
{
if (d->data[j].key == keys[i]) {
func (d->data[i].key, d->data[i].data, user_data);
break;
}
}
}
g_free (keys);
}
/**
* g_datalist_init:
* @datalist: a pointer to a pointer to a datalist.
*
* Resets the datalist to %NULL. It does not free any memory or call
* any destroy functions.
**/
void
g_datalist_init (GData **datalist)
{
g_return_if_fail (datalist != NULL);
g_atomic_pointer_set (datalist, NULL);
}
/**
* g_datalist_set_flags:
* @datalist: pointer to the location that holds a list
* @flags: the flags to turn on. The values of the flags are
* restricted by %G_DATALIST_FLAGS_MASK (currently
* 3; giving two possible boolean flags).
* A value for @flags that doesn't fit within the mask is
* an error.
*
* Turns on flag values for a data list. This function is used
* to keep a small number of boolean flags in an object with
* a data list without using any additional space. It is
* not generally useful except in circumstances where space
* is very tight. (It is used in the base #GObject type, for
* example.)
*
* Since: 2.8
**/
void
g_datalist_set_flags (GData **datalist,
guint flags)
{
g_return_if_fail (datalist != NULL);
g_return_if_fail ((flags & ~G_DATALIST_FLAGS_MASK) == 0);
g_atomic_pointer_or (datalist, (gsize)flags);
}
/**
* g_datalist_unset_flags:
* @datalist: pointer to the location that holds a list
* @flags: the flags to turn off. The values of the flags are
* restricted by %G_DATALIST_FLAGS_MASK (currently
* 3: giving two possible boolean flags).
* A value for @flags that doesn't fit within the mask is
* an error.
*
* Turns off flag values for a data list. See g_datalist_unset_flags()
*
* Since: 2.8
**/
void
g_datalist_unset_flags (GData **datalist,
guint flags)
{
g_return_if_fail (datalist != NULL);
g_return_if_fail ((flags & ~G_DATALIST_FLAGS_MASK) == 0);
g_atomic_pointer_and (datalist, ~(gsize)flags);
}
/**
* g_datalist_get_flags:
* @datalist: pointer to the location that holds a list
*
* Gets flags values packed in together with the datalist.
* See g_datalist_set_flags().
*
* Return value: the flags of the datalist
*
* Since: 2.8
**/
guint
g_datalist_get_flags (GData **datalist)
{
g_return_val_if_fail (datalist != NULL, 0);
return G_DATALIST_GET_FLAGS (datalist); /* atomic macro */
}
/* HOLDS: g_dataset_global_lock */
static void
g_data_initialize (void)
{
g_return_if_fail (g_dataset_location_ht == NULL);
g_dataset_location_ht = g_hash_table_new (g_direct_hash, NULL);
g_dataset_cached = NULL;
}
/**
* SECTION:quarks
* @title: Quarks
* @short_description: a 2-way association between a string and a
* unique integer identifier
*
* Quarks are associations between strings and integer identifiers.
* Given either the string or the #GQuark identifier it is possible to
* retrieve the other.
*
* Quarks are used for both <link
* linkend="glib-Datasets">Datasets</link> and <link
* linkend="glib-Keyed-Data-Lists">Keyed Data Lists</link>.
*
* To create a new quark from a string, use g_quark_from_string() or
* g_quark_from_static_string().
*
* To find the string corresponding to a given #GQuark, use
* g_quark_to_string().
*
* To find the #GQuark corresponding to a given string, use
* g_quark_try_string().
*
* Another use for the string pool maintained for the quark functions
* is string interning, using g_intern_string() or
* g_intern_static_string(). An interned string is a canonical
* representation for a string. One important advantage of interned
* strings is that they can be compared for equality by a simple
* pointer comparison, rather than using strcmp().
**/
/**
* GQuark:
*
* A GQuark is a non-zero integer which uniquely identifies a
* particular string. A GQuark value of zero is associated to %NULL.
**/
/**
* g_quark_try_string:
* @string: (allow-none): a string.
* @Returns: the #GQuark associated with the string, or 0 if @string is
* %NULL or there is no #GQuark associated with it.
*
* Gets the #GQuark associated with the given string, or 0 if string is
* %NULL or it has no associated #GQuark.
*
* If you want the GQuark to be created if it doesn't already exist,
* use g_quark_from_string() or g_quark_from_static_string().
**/
GQuark
g_quark_try_string (const gchar *string)
{
GQuark quark = 0;
if (string == NULL)
return 0;
G_LOCK (g_quark_global);
if (g_quark_ht)
quark = GPOINTER_TO_UINT (g_hash_table_lookup (g_quark_ht, string));
G_UNLOCK (g_quark_global);
return quark;
}
#define QUARK_STRING_BLOCK_SIZE (4096 - sizeof (gsize))
static char *quark_block = NULL;
static int quark_block_offset = 0;
/* HOLDS: g_quark_global_lock */
static char *
quark_strdup(const gchar *string)
{
gchar *copy;
gsize len;
len = strlen (string) + 1;
/* For strings longer than half the block size, fall back
to strdup so that we fill our blocks at least 50%. */
if (len > QUARK_STRING_BLOCK_SIZE / 2)
return g_strdup (string);
if (quark_block == NULL ||
QUARK_STRING_BLOCK_SIZE - quark_block_offset < len)
{
quark_block = g_malloc (QUARK_STRING_BLOCK_SIZE);
quark_block_offset = 0;
}
copy = quark_block + quark_block_offset;
memcpy (copy, string, len);
quark_block_offset += len;
return copy;
}
/* HOLDS: g_quark_global_lock */
static inline GQuark
g_quark_from_string_internal (const gchar *string,
gboolean duplicate)
{
GQuark quark = 0;
if (g_quark_ht)
quark = GPOINTER_TO_UINT (g_hash_table_lookup (g_quark_ht, string));
if (!quark)
{
quark = g_quark_new (duplicate ? quark_strdup (string) : (gchar *)string);
TRACE(GLIB_QUARK_NEW(string, quark));
}
return quark;
}
/**
* g_quark_from_string:
* @string: (allow-none): a string.
* @Returns: the #GQuark identifying the string, or 0 if @string is
* %NULL.
*
* Gets the #GQuark identifying the given string. If the string does
* not currently have an associated #GQuark, a new #GQuark is created,
* using a copy of the string.
**/
GQuark
g_quark_from_string (const gchar *string)
{
GQuark quark;
if (!string)
return 0;
G_LOCK (g_quark_global);
quark = g_quark_from_string_internal (string, TRUE);
G_UNLOCK (g_quark_global);
return quark;
}
/**
* g_quark_from_static_string:
* @string: (allow-none): a string.
* @Returns: the #GQuark identifying the string, or 0 if @string is
* %NULL.
*
* Gets the #GQuark identifying the given (static) string. If the
* string does not currently have an associated #GQuark, a new #GQuark
* is created, linked to the given string.
*
* Note that this function is identical to g_quark_from_string() except
* that if a new #GQuark is created the string itself is used rather
* than a copy. This saves memory, but can only be used if the string
* will <emphasis>always</emphasis> exist. It can be used with
* statically allocated strings in the main program, but not with
* statically allocated memory in dynamically loaded modules, if you
* expect to ever unload the module again (e.g. do not use this
* function in GTK+ theme engines).
**/
GQuark
g_quark_from_static_string (const gchar *string)
{
GQuark quark;
if (!string)
return 0;
G_LOCK (g_quark_global);
quark = g_quark_from_string_internal (string, FALSE);
G_UNLOCK (g_quark_global);
return quark;
}
/**
* g_quark_to_string:
* @quark: a #GQuark.
* @Returns: the string associated with the #GQuark.
*
* Gets the string associated with the given #GQuark.
**/
const gchar *
g_quark_to_string (GQuark quark)
{
gchar* result = NULL;
gchar **quarks;
gint quark_seq_id;
quark_seq_id = g_atomic_int_get (&g_quark_seq_id);
quarks = g_atomic_pointer_get (&g_quarks);
if (quark < quark_seq_id)
result = quarks[quark];
return result;
}
/* HOLDS: g_quark_global_lock */
static inline GQuark
g_quark_new (gchar *string)
{
GQuark quark;
gchar **g_quarks_new;
if (g_quark_seq_id % G_QUARK_BLOCK_SIZE == 0)
{
g_quarks_new = g_new (gchar*, g_quark_seq_id + G_QUARK_BLOCK_SIZE);
if (g_quark_seq_id != 0)
memcpy (g_quarks_new, g_quarks, sizeof (char *) * g_quark_seq_id);
memset (g_quarks_new + g_quark_seq_id, 0, sizeof (char *) * G_QUARK_BLOCK_SIZE);
/* This leaks the old quarks array. Its unfortunate, but it allows
us to do lockless lookup of the arrays, and there shouldn't be that
many quarks in an app */
g_atomic_pointer_set (&g_quarks, g_quarks_new);
}
if (!g_quark_ht)
{
g_assert (g_quark_seq_id == 0);
g_quark_ht = g_hash_table_new (g_str_hash, g_str_equal);
g_quarks[g_quark_seq_id] = NULL;
g_atomic_int_inc (&g_quark_seq_id);
}
quark = g_quark_seq_id;
g_atomic_pointer_set (&g_quarks[quark], string);
g_hash_table_insert (g_quark_ht, string, GUINT_TO_POINTER (quark));
g_atomic_int_inc (&g_quark_seq_id);
return quark;
}
/**
* g_intern_string:
* @string: (allow-none): a string
*
* Returns a canonical representation for @string. Interned strings can
* be compared for equality by comparing the pointers, instead of using strcmp().
*
* Returns: a canonical representation for the string
*
* Since: 2.10
*/
const gchar *
g_intern_string (const gchar *string)
{
const gchar *result;
GQuark quark;
if (!string)
return NULL;
G_LOCK (g_quark_global);
quark = g_quark_from_string_internal (string, TRUE);
result = g_quarks[quark];
G_UNLOCK (g_quark_global);
return result;
}
/**
* g_intern_static_string:
* @string: (allow-none): a static string
*
* Returns a canonical representation for @string. Interned strings can
* be compared for equality by comparing the pointers, instead of using strcmp().
* g_intern_static_string() does not copy the string, therefore @string must
* not be freed or modified.
*
* Returns: a canonical representation for the string
*
* Since: 2.10
*/
const gchar *
g_intern_static_string (const gchar *string)
{
GQuark quark;
const gchar *result;
if (!string)
return NULL;
G_LOCK (g_quark_global);
quark = g_quark_from_string_internal (string, FALSE);
result = g_quarks[quark];
G_UNLOCK (g_quark_global);
return result;
}
|
lgpl-2.1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.