code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
/* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is mozilla.org code.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1999
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Mike McCabe <[email protected]>
* John Bandhauer <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
/* Implementation of xptiInterfaceInfoManager. */
#include "xptiprivate.h"
#include "nsDependentString.h"
#include "nsString.h"
#define NS_ZIPLOADER_CONTRACTID NS_XPTLOADER_CONTRACTID_PREFIX "zip"
NS_IMPL_THREADSAFE_ISUPPORTS2(xptiInterfaceInfoManager,
nsIInterfaceInfoManager,
nsIInterfaceInfoSuperManager)
static xptiInterfaceInfoManager* gInterfaceInfoManager = nsnull;
#ifdef DEBUG
static int gCallCount = 0;
#endif
// static
xptiInterfaceInfoManager*
xptiInterfaceInfoManager::GetInterfaceInfoManagerNoAddRef()
{
if(!gInterfaceInfoManager)
{
nsCOMPtr<nsISupportsArray> searchPath;
BuildFileSearchPath(getter_AddRefs(searchPath));
if(!searchPath)
{
NS_ERROR("can't get xpt search path!");
return nsnull;
}
gInterfaceInfoManager = new xptiInterfaceInfoManager(searchPath);
if(gInterfaceInfoManager)
NS_ADDREF(gInterfaceInfoManager);
if(!gInterfaceInfoManager->IsValid())
{
NS_RELEASE(gInterfaceInfoManager);
}
else
{
PRBool mustAutoReg =
!xptiManifest::Read(gInterfaceInfoManager,
&gInterfaceInfoManager->mWorkingSet);
#ifdef DEBUG
{
// This sets what will be returned by GetOpenLogFile().
xptiAutoLog autoLog(gInterfaceInfoManager,
gInterfaceInfoManager->mAutoRegLogFile, PR_TRUE);
LOG_AUTOREG(("debug build forced autoreg after %s load of manifest\n", mustAutoReg ? "FAILED" : "successful"));
mustAutoReg = PR_TRUE;
}
#endif // DEBUG
if(mustAutoReg)
gInterfaceInfoManager->AutoRegisterInterfaces();
}
}
return gInterfaceInfoManager;
}
void
xptiInterfaceInfoManager::FreeInterfaceInfoManager()
{
if(gInterfaceInfoManager)
gInterfaceInfoManager->LogStats();
NS_IF_RELEASE(gInterfaceInfoManager);
}
PRBool
xptiInterfaceInfoManager::IsValid()
{
return mWorkingSet.IsValid() &&
mResolveLock &&
mAutoRegLock &&
mInfoMonitor &&
mAdditionalManagersLock;
}
xptiInterfaceInfoManager::xptiInterfaceInfoManager(nsISupportsArray* aSearchPath)
: mWorkingSet(aSearchPath),
mOpenLogFile(nsnull),
mResolveLock(PR_NewLock()),
mAutoRegLock(PR_NewLock()),
mInfoMonitor(nsAutoMonitor::NewMonitor("xptiInfoMonitor")),
mAdditionalManagersLock(PR_NewLock()),
mSearchPath(aSearchPath)
{
const char* statsFilename = PR_GetEnv("MOZILLA_XPTI_STATS");
if(statsFilename)
{
mStatsLogFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
if(mStatsLogFile &&
NS_SUCCEEDED(mStatsLogFile->InitWithNativePath(nsDependentCString(statsFilename))))
{
printf("* Logging xptinfo stats to: %s\n", statsFilename);
}
else
{
printf("* Failed to create xptinfo stats file: %s\n", statsFilename);
mStatsLogFile = nsnull;
}
}
const char* autoRegFilename = PR_GetEnv("MOZILLA_XPTI_REGLOG");
if(autoRegFilename)
{
mAutoRegLogFile = do_CreateInstance(NS_LOCAL_FILE_CONTRACTID);
if(mAutoRegLogFile &&
NS_SUCCEEDED(mAutoRegLogFile->InitWithNativePath(nsDependentCString(autoRegFilename))))
{
printf("* Logging xptinfo autoreg to: %s\n", autoRegFilename);
}
else
{
printf("* Failed to create xptinfo autoreg file: %s\n", autoRegFilename);
mAutoRegLogFile = nsnull;
}
}
}
xptiInterfaceInfoManager::~xptiInterfaceInfoManager()
{
// We only do this on shutdown of the service.
mWorkingSet.InvalidateInterfaceInfos();
if(mResolveLock)
PR_DestroyLock(mResolveLock);
if(mAutoRegLock)
PR_DestroyLock(mAutoRegLock);
if(mInfoMonitor)
nsAutoMonitor::DestroyMonitor(mInfoMonitor);
if(mAdditionalManagersLock)
PR_DestroyLock(mAdditionalManagersLock);
gInterfaceInfoManager = nsnull;
#ifdef DEBUG
xptiInterfaceInfo::DEBUG_ShutdownNotification();
gCallCount = 0;
#endif
}
static nsresult
GetDirectoryFromDirService(const char* codename, nsILocalFile** aDir)
{
NS_ASSERTION(codename,"loser!");
NS_ASSERTION(aDir,"loser!");
nsresult rv;
nsCOMPtr<nsIProperties> dirService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID, &rv);
if (NS_FAILED(rv)) return rv;
return dirService->Get(codename, NS_GET_IID(nsILocalFile), (void**) aDir);
}
static PRBool
AppendFromDirServiceList(const char* codename, nsISupportsArray* aPath)
{
NS_ASSERTION(codename,"loser!");
NS_ASSERTION(aPath,"loser!");
nsCOMPtr<nsIProperties> dirService =
do_GetService(NS_DIRECTORY_SERVICE_CONTRACTID);
if(!dirService)
return PR_FALSE;
nsCOMPtr<nsISimpleEnumerator> fileList;
dirService->Get(codename, NS_GET_IID(nsISimpleEnumerator),
getter_AddRefs(fileList));
if(!fileList)
return PR_FALSE;
PRBool more;
while(NS_SUCCEEDED(fileList->HasMoreElements(&more)) && more)
{
nsCOMPtr<nsILocalFile> dir;
fileList->GetNext(getter_AddRefs(dir));
if(!dir || !aPath->AppendElement(dir))
return PR_FALSE;
}
return PR_TRUE;
}
// static
PRBool xptiInterfaceInfoManager::BuildFileSearchPath(nsISupportsArray** aPath)
{
#ifdef DEBUG
NS_ASSERTION(!gCallCount++, "Expected only one call!");
#endif
nsCOMPtr<nsISupportsArray> searchPath;
NS_NewISupportsArray(getter_AddRefs(searchPath));
if(!searchPath)
return PR_FALSE;
nsCOMPtr<nsILocalFile> compDir;
// Always put components directory first
if(NS_FAILED(GetDirectoryFromDirService(NS_XPCOM_COMPONENT_DIR,
getter_AddRefs(compDir))) ||
!searchPath->AppendElement(compDir))
{
return PR_FALSE;
}
// Add additional plugins dirs
// No error checking here since this is optional in some embeddings
// Add the GRE's component directory to searchPath if the
// application is using an GRE.
// An application indicates that it's using an GRE by returning
// a valid nsIFile via it's directory service provider interface.
//
// Please see http://www.mozilla.org/projects/embedding/MRE.html
// for more info. on GREs
//
nsCOMPtr<nsILocalFile> greComponentDirectory;
nsresult rv = GetDirectoryFromDirService(NS_GRE_COMPONENT_DIR,
getter_AddRefs(greComponentDirectory));
if(NS_SUCCEEDED(rv) && greComponentDirectory)
{
// make sure we only append a directory if its a different one
PRBool equalsCompDir = PR_FALSE;
greComponentDirectory->Equals(compDir, &equalsCompDir);
if(!equalsCompDir)
searchPath->AppendElement(greComponentDirectory);
}
(void)AppendFromDirServiceList(NS_XPCOM_COMPONENT_DIR_LIST, searchPath);
(void)AppendFromDirServiceList(NS_APP_PLUGINS_DIR_LIST, searchPath);
NS_ADDREF(*aPath = searchPath);
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::GetCloneOfManifestLocation(nsILocalFile** aFile)
{
// We *trust* that this will not change!
nsCOMPtr<nsILocalFile> lf;
nsresult rv = GetDirectoryFromDirService(NS_XPCOM_XPTI_REGISTRY_FILE,
getter_AddRefs(lf));
if (NS_FAILED(rv)) return PR_FALSE;
rv = xptiCloneLocalFile(lf, aFile);
if (NS_FAILED(rv)) return PR_FALSE;
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::GetApplicationDir(nsILocalFile** aDir)
{
// We *trust* that this will not change!
return NS_SUCCEEDED(GetDirectoryFromDirService(NS_XPCOM_CURRENT_PROCESS_DIR, aDir));
}
PRBool
xptiInterfaceInfoManager::BuildFileList(nsISupportsArray* aSearchPath,
nsISupportsArray** aFileList)
{
NS_ASSERTION(aFileList, "loser!");
nsresult rv;
nsCOMPtr<nsISupportsArray> fileList =
do_CreateInstance(NS_SUPPORTSARRAY_CONTRACTID);
if(!fileList)
return PR_FALSE;
PRUint32 pathCount;
if(NS_FAILED(aSearchPath->Count(&pathCount)))
return PR_FALSE;
for(PRUint32 i = 0; i < pathCount; i++)
{
nsCOMPtr<nsILocalFile> dir;
rv = xptiCloneElementAsLocalFile(aSearchPath, i, getter_AddRefs(dir));
if(NS_FAILED(rv) || !dir)
return PR_FALSE;
nsCOMPtr<nsISimpleEnumerator> entries;
rv = dir->GetDirectoryEntries(getter_AddRefs(entries));
if(NS_FAILED(rv) || !entries)
continue;
PRUint32 count = 0;
PRBool hasMore;
while(NS_SUCCEEDED(entries->HasMoreElements(&hasMore)) && hasMore)
{
nsCOMPtr<nsISupports> sup;
entries->GetNext(getter_AddRefs(sup));
if(!sup)
return PR_FALSE;
nsCOMPtr<nsILocalFile> file = do_QueryInterface(sup);
if(!file)
return PR_FALSE;
PRBool isFile;
if(NS_FAILED(file->IsFile(&isFile)) || !isFile)
{
continue;
}
nsCAutoString name;
if(NS_FAILED(file->GetNativeLeafName(name)))
return PR_FALSE;
if(xptiFileType::IsUnknown(name.get()))
continue;
LOG_AUTOREG(("found file: %s\n", name.get()));
if(!fileList->InsertElementAt(file, count))
return PR_FALSE;
++count;
}
}
NS_ADDREF(*aFileList = fileList);
return PR_TRUE;
}
XPTHeader*
xptiInterfaceInfoManager::ReadXPTFile(nsILocalFile* aFile,
xptiWorkingSet* aWorkingSet)
{
NS_ASSERTION(aFile, "loser!");
XPTHeader *header = nsnull;
char *whole = nsnull;
PRFileDesc* fd = nsnull;
XPTState *state = nsnull;
XPTCursor cursor;
PRInt32 flen;
PRInt64 fileSize;
PRBool saveFollowLinks;
aFile->GetFollowLinks(&saveFollowLinks);
aFile->SetFollowLinks(PR_TRUE);
if(NS_FAILED(aFile->GetFileSize(&fileSize)) || !(flen = nsInt64(fileSize)))
{
aFile->SetFollowLinks(saveFollowLinks);
return nsnull;
}
whole = new char[flen];
if (!whole)
{
aFile->SetFollowLinks(saveFollowLinks);
return nsnull;
}
// all exits from on here should be via 'goto out'
if(NS_FAILED(aFile->OpenNSPRFileDesc(PR_RDONLY, 0444, &fd)) || !fd)
{
goto out;
}
if(flen > PR_Read(fd, whole, flen))
{
goto out;
}
if(!(state = XPT_NewXDRState(XPT_DECODE, whole, flen)))
{
goto out;
}
if(!XPT_MakeCursor(state, XPT_HEADER, 0, &cursor))
{
goto out;
}
if (!XPT_DoHeader(aWorkingSet->GetStructArena(), &cursor, &header))
{
header = nsnull;
goto out;
}
out:
if(fd)
PR_Close(fd);
if(state)
XPT_DestroyXDRState(state);
if(whole)
delete [] whole;
aFile->SetFollowLinks(saveFollowLinks);
return header;
}
PRBool
xptiInterfaceInfoManager::LoadFile(const xptiTypelib& aTypelibRecord,
xptiWorkingSet* aWorkingSet)
{
if(!aWorkingSet)
aWorkingSet = &mWorkingSet;
if(!aWorkingSet->IsValid())
return PR_FALSE;
xptiFile* fileRecord = &aWorkingSet->GetFileAt(aTypelibRecord.GetFileIndex());
xptiZipItem* zipItem = nsnull;
nsCOMPtr<nsILocalFile> file;
if(NS_FAILED(aWorkingSet->GetCloneOfDirectoryAt(fileRecord->GetDirectory(),
getter_AddRefs(file))) || !file)
return PR_FALSE;
if(NS_FAILED(file->AppendNative(nsDependentCString(fileRecord->GetName()))))
return PR_FALSE;
XPTHeader* header;
if(aTypelibRecord.IsZip())
{
zipItem = &aWorkingSet->GetZipItemAt(aTypelibRecord.GetZipItemIndex());
// See the big comment below in the 'non-zip' case...
if(zipItem->GetGuts())
{
NS_ERROR("Trying to load an xpt file from a zip twice");
// Force an autoreg on next run
(void) xptiManifest::Delete(this);
return PR_FALSE;
}
LOG_LOAD(("# loading zip item %s::%s\n", fileRecord->GetName(), zipItem->GetName()));
nsCOMPtr<nsIXPTLoader> loader =
do_GetService(NS_ZIPLOADER_CONTRACTID);
if (loader) {
nsresult rv;
nsCOMPtr<nsIInputStream> stream;
rv = loader->LoadEntry(file, zipItem->GetName(),
getter_AddRefs(stream));
if (NS_FAILED(rv))
return PR_FALSE;
header =
xptiZipLoader::ReadXPTFileFromInputStream(stream, aWorkingSet);
} else {
header = nsnull;
NS_WARNING("Could not load XPT Zip loader");
}
}
else
{
// The file would only have guts already if we previously failed to
// find an interface info in a file where the manifest claimed it was
// going to be.
//
// Normally, when the file gets loaded (and the guts set) then all
// interfaces would also be resolved. So, if we are here again for
// the same file then there must have been some interface that was
// expected but not present. Now we are explicitly trying to find it
// and it isn't going to be there this time either.
//
// This is an assertion style error in a DEBUG build because it shows
// that we failed to detect this in autoreg. For release builds (where
// autoreg is not run on every startup) it is just bad. But by returning
// PR_FALSE we mark this interface as RESOLVE_FAILED and get on with
// things without crashing or anything.
//
// We don't want to do an autoreg here because this is too much of an
// edge case (and in that odd case it might autoreg multiple times if
// many interfaces had been removed). But, by deleting the manifest we
// force the system to get it right on the next run.
if(fileRecord->GetGuts())
{
NS_ERROR("Trying to load an xpt file twice");
// Force an autoreg on next run
(void) xptiManifest::Delete(this);
return PR_FALSE;
}
LOG_LOAD(("^ loading file %s\n", fileRecord->GetName()));
header = ReadXPTFile(file, aWorkingSet);
}
if(!header)
return PR_FALSE;
if(aTypelibRecord.IsZip())
{
// This also allocs zipItem.GetGuts() used below.
if(!zipItem->SetHeader(header, aWorkingSet))
return PR_FALSE;
}
else
{
// This also allocs fileRecord.GetGuts() used below.
if(!fileRecord->SetHeader(header, aWorkingSet))
return PR_FALSE;
}
// For each interface in the header we want to find the xptiInterfaceInfo
// object and set its resolution info.
for(PRUint16 i = 0; i < header->num_interfaces; i++)
{
static const nsID zeroIID =
{ 0x0, 0x0, 0x0, { 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0 } };
XPTInterfaceDirectoryEntry* iface = header->interface_directory + i;
xptiHashEntry* hashEntry;
if(!iface->iid.Equals(zeroIID))
{
hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aWorkingSet->mIIDTable,
&iface->iid, PL_DHASH_LOOKUP);
}
else
{
hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aWorkingSet->mNameTable,
iface->name, PL_DHASH_LOOKUP);
}
xptiInterfaceEntry* entry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
if(!entry)
{
// This one is just not resolved anywhere!
continue;
}
if(aTypelibRecord.IsZip())
zipItem->GetGuts()->SetEntryAt(i, entry);
else
fileRecord->GetGuts()->SetEntryAt(i, entry);
XPTInterfaceDescriptor* descriptor = iface->interface_descriptor;
if(descriptor && aTypelibRecord.Equals(entry->GetTypelibRecord()))
entry->PartiallyResolveLocked(descriptor, aWorkingSet);
}
return PR_TRUE;
}
static int
IndexOfFileWithName(const char* aName, const xptiWorkingSet* aWorkingSet)
{
NS_ASSERTION(aName, "loser!");
for(PRUint32 i = 0; i < aWorkingSet->GetFileCount(); ++i)
{
if(0 == PL_strcmp(aName, aWorkingSet->GetFileAt(i).GetName()))
return i;
}
return -1;
}
static int
IndexOfDirectoryOfFile(nsISupportsArray* aSearchPath, nsILocalFile* aFile)
{
nsCOMPtr<nsIFile> parent;
aFile->GetParent(getter_AddRefs(parent));
if(parent)
{
PRUint32 count = 0;
aSearchPath->Count(&count);
NS_ASSERTION(count, "broken search path! bad count");
for(PRUint32 i = 0; i < count; i++)
{
nsCOMPtr<nsIFile> current;
aSearchPath->QueryElementAt(i, NS_GET_IID(nsIFile),
getter_AddRefs(current));
NS_ASSERTION(current, "broken search path! bad element");
PRBool same;
if(NS_SUCCEEDED(parent->Equals(current, &same)) && same)
return (int) i;
}
}
NS_ERROR("file not in search directory!");
return -1;
}
struct SortData
{
nsISupportsArray* mSearchPath;
xptiWorkingSet* mWorkingSet;
};
PR_STATIC_CALLBACK(int)
xptiSortFileList(const void * p1, const void *p2, void * closure)
{
nsILocalFile* pFile1 = *((nsILocalFile**) p1);
nsILocalFile* pFile2 = *((nsILocalFile**) p2);
SortData* data = (SortData*) closure;
nsCAutoString name1;
nsCAutoString name2;
if(NS_FAILED(pFile1->GetNativeLeafName(name1)))
{
NS_ERROR("way bad, with no happy out!");
return 0;
}
if(NS_FAILED(pFile2->GetNativeLeafName(name2)))
{
NS_ERROR("way bad, with no happy out!");
return 0;
}
int index1 = IndexOfFileWithName(name1.get(), data->mWorkingSet);
int index2 = IndexOfFileWithName(name2.get(), data->mWorkingSet);
// Get these now in case we need them later.
PRBool isXPT1 = xptiFileType::IsXPT(name1.get());
PRBool isXPT2 = xptiFileType::IsXPT(name2.get());
int nameOrder = Compare(name1, name2);
// both in workingSet, preserve old order
if(index1 != -1 && index2 != -1)
return index1 - index2;
if(index1 != -1)
return 1;
if(index2 != -1)
return -1;
// neither is in workingset
// check how they compare in search path order
int dirIndex1 = IndexOfDirectoryOfFile(data->mSearchPath, pFile1);
int dirIndex2 = IndexOfDirectoryOfFile(data->mSearchPath, pFile2);
if(dirIndex1 != dirIndex2)
return dirIndex1 - dirIndex2;
// .xpt files come before archives (.zip, .jar, etc)
if(isXPT1 &&!isXPT2)
return -1;
if(!isXPT1 && isXPT2)
return 1;
// neither element is in the workingSet and both are same type and in
// the same directory, sort by size
PRInt64 size1;
PRInt64 size2;
if(NS_FAILED(pFile1->GetFileSize(&size1)))
{
NS_ERROR("way bad, with no happy out!");
return 0;
}
if(NS_FAILED(pFile2->GetFileSize(&size2)))
{
NS_ERROR("way bad, with no happy out!");
return 0;
}
// by size with largest first, or by name if size is the same
int sizeDiff = int(PRInt32(nsInt64(size2) - nsInt64(size1)));
return sizeDiff != 0 ? sizeDiff : nameOrder;
}
nsILocalFile**
xptiInterfaceInfoManager::BuildOrderedFileArray(nsISupportsArray* aSearchPath,
nsISupportsArray* aFileList,
xptiWorkingSet* aWorkingSet)
{
// We want to end up with a file list that starts with the files from
// aWorkingSet (but only those that are in aFileList) in the order in
// which they appeared in aWorkingSet-> Following those files will be those
// files in aFileList which are not in aWorkingSet-> These additional
// files will be ordered by file size (larger first) but all .xpt files
// will preceed all zipfile of those files not already in the working set.
// To do this we will do a fancy sort on a copy of aFileList.
nsILocalFile** orderedFileList = nsnull;
PRUint32 countOfFilesInFileList;
PRUint32 i;
NS_ASSERTION(aFileList, "loser!");
NS_ASSERTION(aWorkingSet, "loser!");
NS_ASSERTION(aWorkingSet->IsValid(), "loser!");
if(NS_FAILED(aFileList->Count(&countOfFilesInFileList)) ||
0 == countOfFilesInFileList)
return nsnull;
orderedFileList = (nsILocalFile**)
XPT_MALLOC(aWorkingSet->GetStructArena(),
sizeof(nsILocalFile*) * countOfFilesInFileList);
if(!orderedFileList)
return nsnull;
// fill our list for sorting
for(i = 0; i < countOfFilesInFileList; ++i)
{
nsCOMPtr<nsILocalFile> file;
aFileList->QueryElementAt(i, NS_GET_IID(nsILocalFile), getter_AddRefs(file));
NS_ASSERTION(file, "loser!");
// Intentionally NOT addref'd cuz we know these are pinned in aFileList.
orderedFileList[i] = file.get();
}
// sort the filelist
SortData sortData = {aSearchPath, aWorkingSet};
NS_QuickSort(orderedFileList, countOfFilesInFileList, sizeof(nsILocalFile*),
xptiSortFileList, &sortData);
return orderedFileList;
}
xptiInterfaceInfoManager::AutoRegMode
xptiInterfaceInfoManager::DetermineAutoRegStrategy(nsISupportsArray* aSearchPath,
nsISupportsArray* aFileList,
xptiWorkingSet* aWorkingSet)
{
NS_ASSERTION(aFileList, "loser!");
NS_ASSERTION(aWorkingSet, "loser!");
NS_ASSERTION(aWorkingSet->IsValid(), "loser!");
PRUint32 countOfFilesInWorkingSet = aWorkingSet->GetFileCount();
PRUint32 countOfFilesInFileList;
PRUint32 i;
PRUint32 k;
if(0 == countOfFilesInWorkingSet)
{
// Loading manifest might have failed. Better safe...
return FULL_VALIDATION_REQUIRED;
}
if(NS_FAILED(aFileList->Count(&countOfFilesInFileList)))
{
NS_ERROR("unexpected!");
return FULL_VALIDATION_REQUIRED;
}
if(countOfFilesInFileList == countOfFilesInWorkingSet)
{
// try to determine if *no* files are new or changed.
PRBool same = PR_TRUE;
for(i = 0; i < countOfFilesInFileList && same; ++i)
{
nsCOMPtr<nsILocalFile> file;
aFileList->QueryElementAt(i, NS_GET_IID(nsILocalFile), getter_AddRefs(file));
NS_ASSERTION(file, "loser!");
PRInt64 size;
PRInt64 date;
nsCAutoString name;
PRUint32 directory;
if(NS_FAILED(file->GetFileSize(&size)) ||
NS_FAILED(file->GetLastModifiedTime(&date)) ||
NS_FAILED(file->GetNativeLeafName(name)) ||
!aWorkingSet->FindDirectoryOfFile(file, &directory))
{
NS_ERROR("unexpected!");
return FULL_VALIDATION_REQUIRED;
}
for(k = 0; k < countOfFilesInWorkingSet; ++k)
{
xptiFile& target = aWorkingSet->GetFileAt(k);
if(directory == target.GetDirectory() &&
name.Equals(target.GetName()))
{
if(nsInt64(size) != target.GetSize() ||
nsInt64(date) != target.GetDate())
same = PR_FALSE;
break;
}
}
// failed to find our file in the workingset?
if(k == countOfFilesInWorkingSet)
same = PR_FALSE;
}
if(same)
return NO_FILES_CHANGED;
}
else if(countOfFilesInFileList > countOfFilesInWorkingSet)
{
// try to determine if the only changes are additional new files
// XXX Wimping out and doing this as a separate walk through the lists.
PRBool same = PR_TRUE;
for(i = 0; i < countOfFilesInWorkingSet && same; ++i)
{
xptiFile& target = aWorkingSet->GetFileAt(i);
for(k = 0; k < countOfFilesInFileList; ++k)
{
nsCOMPtr<nsILocalFile> file;
aFileList->QueryElementAt(k, NS_GET_IID(nsILocalFile), getter_AddRefs(file));
NS_ASSERTION(file, "loser!");
nsCAutoString name;
PRInt64 size;
PRInt64 date;
if(NS_FAILED(file->GetFileSize(&size)) ||
NS_FAILED(file->GetLastModifiedTime(&date)) ||
NS_FAILED(file->GetNativeLeafName(name)))
{
NS_ERROR("unexpected!");
return FULL_VALIDATION_REQUIRED;
}
PRBool sameName = name.Equals(target.GetName());
if(sameName)
{
if(nsInt64(size) != target.GetSize() ||
nsInt64(date) != target.GetDate())
same = PR_FALSE;
break;
}
}
// failed to find our file in the file list?
if(k == countOfFilesInFileList)
same = PR_FALSE;
}
if(same)
return FILES_ADDED_ONLY;
}
return FULL_VALIDATION_REQUIRED;
}
PRBool
xptiInterfaceInfoManager::AddOnlyNewFilesFromFileList(nsISupportsArray* aSearchPath,
nsISupportsArray* aFileList,
xptiWorkingSet* aWorkingSet)
{
nsILocalFile** orderedFileArray;
PRUint32 countOfFilesInFileList;
PRUint32 i;
NS_ASSERTION(aFileList, "loser!");
NS_ASSERTION(aWorkingSet, "loser!");
NS_ASSERTION(aWorkingSet->IsValid(), "loser!");
if(NS_FAILED(aFileList->Count(&countOfFilesInFileList)))
return PR_FALSE;
NS_ASSERTION(countOfFilesInFileList, "loser!");
NS_ASSERTION(countOfFilesInFileList > aWorkingSet->GetFileCount(), "loser!");
orderedFileArray = BuildOrderedFileArray(aSearchPath, aFileList, aWorkingSet);
if(!orderedFileArray)
return PR_FALSE;
// Make enough space in aWorkingset for additions to xptiFile array.
if(!aWorkingSet->ExtendFileArray(countOfFilesInFileList))
return PR_FALSE;
// For each file that is not already in our working set, add any valid
// interfaces that don't conflict with previous interfaces added.
for(i = 0; i < countOfFilesInFileList; i++)
{
nsILocalFile* file = orderedFileArray[i];
nsCAutoString name;
PRInt64 size;
PRInt64 date;
PRUint32 dir;
if(NS_FAILED(file->GetFileSize(&size)) ||
NS_FAILED(file->GetLastModifiedTime(&date)) ||
NS_FAILED(file->GetNativeLeafName(name)) ||
!aWorkingSet->FindDirectoryOfFile(file, &dir))
{
return PR_FALSE;
}
if(xptiWorkingSet::NOT_FOUND != aWorkingSet->FindFile(dir, name.get()))
{
// This file was found in the working set, so skip it.
continue;
}
LOG_AUTOREG((" finding interfaces in new file: %s\n", name.get()));
xptiFile fileRecord;
fileRecord = xptiFile(nsInt64(size), nsInt64(date), dir,
name.get(), aWorkingSet);
if(xptiFileType::IsXPT(fileRecord.GetName()))
{
XPTHeader* header = ReadXPTFile(file, aWorkingSet);
if(!header)
{
// XXX do something!
NS_ERROR("");
continue;
}
xptiTypelib typelibRecord;
typelibRecord.Init(aWorkingSet->GetFileCount());
PRBool AddedFile = PR_FALSE;
if(header->major_version >= XPT_MAJOR_INCOMPATIBLE_VERSION)
{
NS_ASSERTION(!header->num_interfaces,"bad libxpt");
LOG_AUTOREG((" file is version %d.%d Type file of version %d.0 or higher can not be read.\n", (int)header->major_version, (int)header->minor_version, (int)XPT_MAJOR_INCOMPATIBLE_VERSION));
}
for(PRUint16 k = 0; k < header->num_interfaces; k++)
{
xptiInterfaceEntry* entry = nsnull;
if(!VerifyAndAddEntryIfNew(aWorkingSet,
header->interface_directory + k,
typelibRecord,
&entry))
return PR_FALSE;
if(!entry)
continue;
// If this is the first interface we found for this file then
// setup the fileRecord for the header and infos.
if(!AddedFile)
{
if(!fileRecord.SetHeader(header, aWorkingSet))
{
// XXX that would be bad.
return PR_FALSE;
}
AddedFile = PR_TRUE;
}
fileRecord.GetGuts()->SetEntryAt(k, entry);
}
// This will correspond to typelibRecord above.
aWorkingSet->AppendFile(fileRecord);
}
else // its another kind of archive
{
nsCOMPtr<nsIXPTLoader> loader =
do_GetService(NS_ZIPLOADER_CONTRACTID);
if (loader) {
nsresult rv;
nsCOMPtr<nsIXPTLoaderSink> sink =
new xptiZipLoaderSink(this, aWorkingSet);
if (!sink)
return PR_FALSE;
rv = loader->EnumerateEntries(file, sink);
if (NS_FAILED(rv))
return PR_FALSE;
// This will correspond to typelibRecord used in
// xptiInterfaceInfoManager::FoundEntry.
aWorkingSet->AppendFile(fileRecord);
} else {
NS_WARNING("Could not load XPT Zip loader");
}
}
}
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::DoFullValidationMergeFromFileList(nsISupportsArray* aSearchPath,
nsISupportsArray* aFileList,
xptiWorkingSet* aWorkingSet)
{
nsILocalFile** orderedFileArray;
PRUint32 countOfFilesInFileList;
PRUint32 i;
NS_ASSERTION(aFileList, "loser!");
if(!aWorkingSet->IsValid())
return PR_FALSE;
if(NS_FAILED(aFileList->Count(&countOfFilesInFileList)))
return PR_FALSE;
if(!countOfFilesInFileList)
{
// maybe there are no xpt files to register.
// a minimal install would have this case.
return PR_TRUE;
}
orderedFileArray = BuildOrderedFileArray(aSearchPath, aFileList, aWorkingSet);
if(!orderedFileArray)
return PR_FALSE;
// DEBUG_DumpFileArray(orderedFileArray, countOfFilesInFileList);
// Make space in aWorkingset for a new xptiFile array.
if(!aWorkingSet->NewFileArray(countOfFilesInFileList))
return PR_FALSE;
aWorkingSet->ClearZipItems();
aWorkingSet->ClearHashTables();
// For each file, add any valid interfaces that don't conflict with
// previous interfaces added.
for(i = 0; i < countOfFilesInFileList; i++)
{
nsILocalFile* file = orderedFileArray[i];
nsCAutoString name;
PRInt64 size;
PRInt64 date;
PRUint32 dir;
if(NS_FAILED(file->GetFileSize(&size)) ||
NS_FAILED(file->GetLastModifiedTime(&date)) ||
NS_FAILED(file->GetNativeLeafName(name)) ||
!aWorkingSet->FindDirectoryOfFile(file, &dir))
{
return PR_FALSE;
}
LOG_AUTOREG((" finding interfaces in file: %s\n", name.get()));
xptiFile fileRecord;
fileRecord = xptiFile(nsInt64(size), nsInt64(date), dir,
name.get(), aWorkingSet);
// printf("* found %s\n", fileRecord.GetName());
if(xptiFileType::IsXPT(fileRecord.GetName()))
{
XPTHeader* header = ReadXPTFile(file, aWorkingSet);
if(!header)
{
// XXX do something!
NS_ERROR("Unable to read an XPT file, turn logging on to see which file");
LOG_AUTOREG((" unable to read file\n"));
continue;
}
xptiTypelib typelibRecord;
typelibRecord.Init(aWorkingSet->GetFileCount());
PRBool AddedFile = PR_FALSE;
if(header->major_version >= XPT_MAJOR_INCOMPATIBLE_VERSION)
{
NS_ASSERTION(!header->num_interfaces,"bad libxpt");
LOG_AUTOREG((" file is version %d.%d Type file of version %d.0 or higher can not be read.\n", (int)header->major_version, (int)header->minor_version, (int)XPT_MAJOR_INCOMPATIBLE_VERSION));
}
for(PRUint16 k = 0; k < header->num_interfaces; k++)
{
xptiInterfaceEntry* entry = nsnull;
if(!VerifyAndAddEntryIfNew(aWorkingSet,
header->interface_directory + k,
typelibRecord,
&entry))
return PR_FALSE;
if(!entry)
continue;
// If this is the first interface we found for this file then
// setup the fileRecord for the header and infos.
if(!AddedFile)
{
if(!fileRecord.SetHeader(header, aWorkingSet))
{
// XXX that would be bad.
return PR_FALSE;
}
AddedFile = PR_TRUE;
}
fileRecord.GetGuts()->SetEntryAt(k, entry);
}
// This will correspond to typelibRecord above.
aWorkingSet->AppendFile(fileRecord);
}
else
{
nsCOMPtr<nsIXPTLoader> loader =
do_GetService(NS_ZIPLOADER_CONTRACTID);
if (loader) {
nsresult rv;
nsCOMPtr<nsIXPTLoaderSink> sink =
new xptiZipLoaderSink(this, aWorkingSet);
if (!sink)
return PR_FALSE;
rv = loader->EnumerateEntries(file, sink);
if (NS_FAILED(rv))
return PR_FALSE;
// This will correspond to typelibRecord used in
// xptiInterfaceInfoManager::FoundEntry.
aWorkingSet->AppendFile(fileRecord);
} else {
NS_WARNING("Could not load XPT Zip loader");
}
}
}
return PR_TRUE;
}
NS_IMPL_ISUPPORTS1(xptiZipLoaderSink, nsIXPTLoaderSink)
// implement nsIXPTLoader
NS_IMETHODIMP
xptiZipLoaderSink::FoundEntry(const char* entryName,
PRInt32 index,
nsIInputStream *aStream)
{
XPTHeader *header =
xptiZipLoader::ReadXPTFileFromInputStream(aStream, mWorkingSet);
if (!header)
return NS_ERROR_OUT_OF_MEMORY;
if (!mManager->FoundZipEntry(entryName, index, header, mWorkingSet))
return NS_ERROR_FAILURE;
return NS_OK;
}
// implement xptiEntrySink
PRBool
xptiInterfaceInfoManager::FoundZipEntry(const char* entryName,
int index,
XPTHeader* header,
xptiWorkingSet* aWorkingSet)
{
NS_ASSERTION(entryName, "loser!");
NS_ASSERTION(header, "loser!");
NS_ASSERTION(aWorkingSet, "loser!");
int countOfInterfacesAddedForItem = 0;
xptiZipItem zipItemRecord(entryName, aWorkingSet);
LOG_AUTOREG((" finding interfaces in file: %s\n", entryName));
if(header->major_version >= XPT_MAJOR_INCOMPATIBLE_VERSION)
{
NS_ASSERTION(!header->num_interfaces,"bad libxpt");
LOG_AUTOREG((" file is version %d.%d. Type file of version %d.0 or higher can not be read.\n", (int)header->major_version, (int)header->minor_version, (int)XPT_MAJOR_INCOMPATIBLE_VERSION));
}
if(!header->num_interfaces)
{
// We are not interested in files without interfaces.
return PR_TRUE;
}
xptiTypelib typelibRecord;
typelibRecord.Init(aWorkingSet->GetFileCount(),
aWorkingSet->GetZipItemCount());
for(PRUint16 k = 0; k < header->num_interfaces; k++)
{
xptiInterfaceEntry* entry = nsnull;
if(!VerifyAndAddEntryIfNew(aWorkingSet,
header->interface_directory + k,
typelibRecord,
&entry))
return PR_FALSE;
if(!entry)
continue;
// If this is the first interface we found for this item
// then setup the zipItemRecord for the header and infos.
if(!countOfInterfacesAddedForItem)
{
// XXX fix this!
if(!zipItemRecord.SetHeader(header, aWorkingSet))
{
// XXX that would be bad.
return PR_FALSE;
}
}
// zipItemRecord.GetGuts()->SetEntryAt(k, entry);
++countOfInterfacesAddedForItem;
}
if(countOfInterfacesAddedForItem)
{
if(!aWorkingSet->GetZipItemFreeSpace())
{
if(!aWorkingSet->ExtendZipItemArray(
aWorkingSet->GetZipItemCount() + 20))
{
// out of space!
return PR_FALSE;
}
}
aWorkingSet->AppendZipItem(zipItemRecord);
}
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::VerifyAndAddEntryIfNew(xptiWorkingSet* aWorkingSet,
XPTInterfaceDirectoryEntry* iface,
const xptiTypelib& typelibRecord,
xptiInterfaceEntry** entryAdded)
{
NS_ASSERTION(iface, "loser!");
NS_ASSERTION(entryAdded, "loser!");
*entryAdded = nsnull;
if(!iface->interface_descriptor)
{
// Not resolved, ignore this one.
// XXX full logging might note this...
return PR_TRUE;
}
xptiHashEntry* hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aWorkingSet->mIIDTable, &iface->iid, PL_DHASH_LOOKUP);
xptiInterfaceEntry* entry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
if(entry)
{
// XXX validate this info to find possible inconsistencies
LOG_AUTOREG((" ignoring repeated interface: %s\n", iface->name));
return PR_TRUE;
}
// Build a new xptiInterfaceEntry object and hook it up.
entry = xptiInterfaceEntry::NewEntry(iface->name, strlen(iface->name),
iface->iid,
typelibRecord, aWorkingSet);
if(!entry)
{
// XXX bad!
return PR_FALSE;
}
//XXX We should SetHeader too as part of the validation, no?
entry->SetScriptableFlag(XPT_ID_IS_SCRIPTABLE(iface->interface_descriptor->flags));
// Add our entry to the iid hashtable.
hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aWorkingSet->mNameTable,
entry->GetTheName(), PL_DHASH_ADD);
if(hashEntry)
hashEntry->value = entry;
// Add our entry to the name hashtable.
hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aWorkingSet->mIIDTable,
entry->GetTheIID(), PL_DHASH_ADD);
if(hashEntry)
hashEntry->value = entry;
*entryAdded = entry;
LOG_AUTOREG((" added interface: %s\n", iface->name));
return PR_TRUE;
}
// local struct used to pass two pointers as one pointer
struct TwoWorkingSets
{
TwoWorkingSets(xptiWorkingSet* src, xptiWorkingSet* dest)
: aSrcWorkingSet(src), aDestWorkingSet(dest) {}
xptiWorkingSet* aSrcWorkingSet;
xptiWorkingSet* aDestWorkingSet;
};
PR_STATIC_CALLBACK(PLDHashOperator)
xpti_Merger(PLDHashTable *table, PLDHashEntryHdr *hdr,
PRUint32 number, void *arg)
{
xptiInterfaceEntry* srcEntry = ((xptiHashEntry*)hdr)->value;
xptiWorkingSet* aSrcWorkingSet = ((TwoWorkingSets*)arg)->aSrcWorkingSet;
xptiWorkingSet* aDestWorkingSet = ((TwoWorkingSets*)arg)->aDestWorkingSet;
xptiHashEntry* hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aDestWorkingSet->mIIDTable,
srcEntry->GetTheIID(), PL_DHASH_LOOKUP);
xptiInterfaceEntry* destEntry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
if(destEntry)
{
// Let's see if this is referring to the same exact typelib
const char* destFilename =
aDestWorkingSet->GetTypelibFileName(destEntry->GetTypelibRecord());
const char* srcFilename =
aSrcWorkingSet->GetTypelibFileName(srcEntry->GetTypelibRecord());
if(0 == PL_strcmp(destFilename, srcFilename) &&
(destEntry->GetTypelibRecord().GetZipItemIndex() ==
srcEntry->GetTypelibRecord().GetZipItemIndex()))
{
// This is the same item.
// But... Let's make sure they didn't change the interface name.
// There are wacky developers that do stuff like that!
if(0 == PL_strcmp(destEntry->GetTheName(), srcEntry->GetTheName()))
return PL_DHASH_NEXT;
}
}
// Clone the xptiInterfaceEntry into our destination WorkingSet.
xptiTypelib typelibRecord;
uint16 fileIndex = srcEntry->GetTypelibRecord().GetFileIndex();
uint16 zipItemIndex = srcEntry->GetTypelibRecord().GetZipItemIndex();
fileIndex += aDestWorkingSet->mFileMergeOffsetMap[fileIndex];
// If it is not a zipItem, then the original index is fine.
if(srcEntry->GetTypelibRecord().IsZip())
zipItemIndex += aDestWorkingSet->mZipItemMergeOffsetMap[zipItemIndex];
typelibRecord.Init(fileIndex, zipItemIndex);
destEntry = xptiInterfaceEntry::NewEntry(*srcEntry, typelibRecord,
aDestWorkingSet);
if(!destEntry)
{
// XXX bad! should log
return PL_DHASH_NEXT;
}
// Add our entry to the iid hashtable.
hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aDestWorkingSet->mNameTable,
destEntry->GetTheName(), PL_DHASH_ADD);
if(hashEntry)
hashEntry->value = destEntry;
// Add our entry to the name hashtable.
hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(aDestWorkingSet->mIIDTable,
destEntry->GetTheIID(), PL_DHASH_ADD);
if(hashEntry)
hashEntry->value = destEntry;
return PL_DHASH_NEXT;
}
PRBool
xptiInterfaceInfoManager::MergeWorkingSets(xptiWorkingSet* aDestWorkingSet,
xptiWorkingSet* aSrcWorkingSet)
{
PRUint32 i;
// Combine file lists.
PRUint32 originalFileCount = aDestWorkingSet->GetFileCount();
PRUint32 additionalFileCount = aSrcWorkingSet->GetFileCount();
// Create a new array big enough to hold both lists and copy existing files
if(additionalFileCount)
{
if(!aDestWorkingSet->ExtendFileArray(originalFileCount +
additionalFileCount))
return PR_FALSE;
// Now we are where we started, but we know we have enough space.
// Prepare offset array for later fixups.
// NOTE: Storing with dest, but alloc'ing from src. This is intentional.
aDestWorkingSet->mFileMergeOffsetMap = (PRUint32*)
XPT_CALLOC(aSrcWorkingSet->GetStructArena(),
additionalFileCount * sizeof(PRUint32));
if(!aDestWorkingSet->mFileMergeOffsetMap)
return PR_FALSE;
}
for(i = 0; i < additionalFileCount; ++i)
{
xptiFile& srcFile = aSrcWorkingSet->GetFileAt(i);
PRUint32 k;
for(k = 0; k < originalFileCount; ++k)
{
// If file (with same name, date, and time) is in both lists
// then reuse that record.
xptiFile& destFile = aDestWorkingSet->GetFileAt(k);
if(srcFile.Equals(destFile))
{
aDestWorkingSet->mFileMergeOffsetMap[i] = k - i;
break;
}
}
if(k == originalFileCount)
{
// No match found, tack it on the end.
PRUint32 newIndex = aDestWorkingSet->GetFileCount();
aDestWorkingSet->AppendFile(xptiFile(srcFile, aDestWorkingSet));
// Fixup the merge offset map.
aDestWorkingSet->mFileMergeOffsetMap[i] = newIndex - i;
}
}
// Combine ZipItem lists.
PRUint32 originalZipItemCount = aDestWorkingSet->GetZipItemCount();
PRUint32 additionalZipItemCount = aSrcWorkingSet->GetZipItemCount();
// Create a new array big enough to hold both lists and copy existing ZipItems
if(additionalZipItemCount)
{
if(!aDestWorkingSet->ExtendZipItemArray(originalZipItemCount +
additionalZipItemCount))
return PR_FALSE;
// Now we are where we started, but we know we have enough space.
// Prepare offset array for later fixups.
// NOTE: Storing with dest, but alloc'ing from src. This is intentional.
aDestWorkingSet->mZipItemMergeOffsetMap = (PRUint32*)
XPT_CALLOC(aSrcWorkingSet->GetStructArena(),
additionalZipItemCount * sizeof(PRUint32));
if(!aDestWorkingSet->mZipItemMergeOffsetMap)
return PR_FALSE;
}
for(i = 0; i < additionalZipItemCount; ++i)
{
xptiZipItem& srcZipItem = aSrcWorkingSet->GetZipItemAt(i);
PRUint32 k;
for(k = 0; k < originalZipItemCount; ++k)
{
// If ZipItem (with same name) is in both lists
// then reuse that record.
xptiZipItem& destZipItem = aDestWorkingSet->GetZipItemAt(k);
if(srcZipItem.Equals(destZipItem))
{
aDestWorkingSet->mZipItemMergeOffsetMap[i] = k - i;
break;
}
}
if(k == originalZipItemCount)
{
// No match found, tack it on the end.
PRUint32 newIndex = aDestWorkingSet->GetZipItemCount();
aDestWorkingSet->AppendZipItem(
xptiZipItem(srcZipItem, aDestWorkingSet));
// Fixup the merge offset map.
aDestWorkingSet->mZipItemMergeOffsetMap[i] = newIndex - i;
}
}
// Migrate xptiInterfaceInfos
TwoWorkingSets sets(aSrcWorkingSet, aDestWorkingSet);
PL_DHashTableEnumerate(aSrcWorkingSet->mNameTable, xpti_Merger, &sets);
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::DEBUG_DumpFileList(nsISupportsArray* aFileList)
{
PRUint32 count;
if(NS_FAILED(aFileList->Count(&count)))
return PR_FALSE;
for(PRUint32 i = 0; i < count; i++)
{
nsCOMPtr<nsIFile> file;
aFileList->QueryElementAt(i, NS_GET_IID(nsILocalFile), getter_AddRefs(file));
if(!file)
return PR_FALSE;
nsCAutoString name;
if(NS_FAILED(file->GetNativeLeafName(name)))
return PR_FALSE;
printf("* found %s\n", name.get());
}
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::DEBUG_DumpFileListInWorkingSet(xptiWorkingSet* aWorkingSet)
{
for(PRUint16 i = 0; i < aWorkingSet->GetFileCount(); ++i)
{
xptiFile& record = aWorkingSet->GetFileAt(i);
printf("! has %s\n", record.GetName());
}
return PR_TRUE;
}
PRBool
xptiInterfaceInfoManager::DEBUG_DumpFileArray(nsILocalFile** aFileArray,
PRUint32 count)
{
// dump the sorted list
for(PRUint32 i = 0; i < count; ++i)
{
nsILocalFile* file = aFileArray[i];
nsCAutoString name;
if(NS_FAILED(file->GetNativeLeafName(name)))
return PR_FALSE;
printf("found file: %s\n", name.get());
}
return PR_TRUE;
}
/***************************************************************************/
// static
void
xptiInterfaceInfoManager::WriteToLog(const char *fmt, ...)
{
if(!gInterfaceInfoManager)
return;
PRFileDesc* fd = gInterfaceInfoManager->GetOpenLogFile();
if(fd)
{
va_list ap;
va_start(ap, fmt);
PR_vfprintf(fd, fmt, ap);
va_end(ap);
}
}
PR_STATIC_CALLBACK(PLDHashOperator)
xpti_ResolvedFileNameLogger(PLDHashTable *table, PLDHashEntryHdr *hdr,
PRUint32 number, void *arg)
{
xptiInterfaceEntry* entry = ((xptiHashEntry*)hdr)->value;
xptiInterfaceInfoManager* mgr = (xptiInterfaceInfoManager*) arg;
if(entry->IsFullyResolved())
{
xptiWorkingSet* aWorkingSet = mgr->GetWorkingSet();
PRFileDesc* fd = mgr->GetOpenLogFile();
const xptiTypelib& typelib = entry->GetTypelibRecord();
const char* filename =
aWorkingSet->GetFileAt(typelib.GetFileIndex()).GetName();
if(typelib.IsZip())
{
const char* zipItemName =
aWorkingSet->GetZipItemAt(typelib.GetZipItemIndex()).GetName();
PR_fprintf(fd, "xpti used interface: %s from %s::%s\n",
entry->GetTheName(), filename, zipItemName);
}
else
{
PR_fprintf(fd, "xpti used interface: %s from %s\n",
entry->GetTheName(), filename);
}
}
return PL_DHASH_NEXT;
}
void
xptiInterfaceInfoManager::LogStats()
{
PRUint32 i;
// This sets what will be returned by GetOpenLogFile().
xptiAutoLog autoLog(this, mStatsLogFile, PR_FALSE);
PRFileDesc* fd = GetOpenLogFile();
if(!fd)
return;
// Show names of xpt (only) files from which at least one interface
// was resolved.
PRUint32 fileCount = mWorkingSet.GetFileCount();
for(i = 0; i < fileCount; ++i)
{
xptiFile& f = mWorkingSet.GetFileAt(i);
if(f.GetGuts())
PR_fprintf(fd, "xpti used file: %s\n", f.GetName());
}
PR_fprintf(fd, "\n");
// Show names of xptfiles loaded from zips from which at least
// one interface was resolved.
PRUint32 zipItemCount = mWorkingSet.GetZipItemCount();
for(i = 0; i < zipItemCount; ++i)
{
xptiZipItem& zi = mWorkingSet.GetZipItemAt(i);
if(zi.GetGuts())
PR_fprintf(fd, "xpti used file from zip: %s\n", zi.GetName());
}
PR_fprintf(fd, "\n");
// Show name of each interface that was fully resolved and the name
// of the file and (perhaps) zip from which it was loaded.
PL_DHashTableEnumerate(mWorkingSet.mNameTable,
xpti_ResolvedFileNameLogger, this);
}
/***************************************************************************/
// this is a private helper
static nsresult
EntryToInfo(xptiInterfaceEntry* entry, nsIInterfaceInfo **_retval)
{
xptiInterfaceInfo* info;
nsresult rv;
if(!entry)
{
*_retval = nsnull;
return NS_ERROR_FAILURE;
}
rv = entry->GetInterfaceInfo(&info);
if(NS_FAILED(rv))
return rv;
// Transfer the AddRef done by GetInterfaceInfo.
*_retval = NS_STATIC_CAST(nsIInterfaceInfo*, info);
return NS_OK;
}
/* nsIInterfaceInfo getInfoForIID (in nsIIDPtr iid); */
NS_IMETHODIMP xptiInterfaceInfoManager::GetInfoForIID(const nsIID * iid, nsIInterfaceInfo **_retval)
{
NS_ASSERTION(iid, "bad param");
NS_ASSERTION(_retval, "bad param");
xptiHashEntry* hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(mWorkingSet.mIIDTable, iid, PL_DHASH_LOOKUP);
xptiInterfaceEntry* entry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
return EntryToInfo(entry, _retval);
}
/* nsIInterfaceInfo getInfoForName (in string name); */
NS_IMETHODIMP xptiInterfaceInfoManager::GetInfoForName(const char *name, nsIInterfaceInfo **_retval)
{
NS_ASSERTION(name, "bad param");
NS_ASSERTION(_retval, "bad param");
xptiHashEntry* hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(mWorkingSet.mNameTable, name, PL_DHASH_LOOKUP);
xptiInterfaceEntry* entry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
return EntryToInfo(entry, _retval);
}
/* nsIIDPtr getIIDForName (in string name); */
NS_IMETHODIMP xptiInterfaceInfoManager::GetIIDForName(const char *name, nsIID * *_retval)
{
NS_ASSERTION(name, "bad param");
NS_ASSERTION(_retval, "bad param");
xptiHashEntry* hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(mWorkingSet.mNameTable, name, PL_DHASH_LOOKUP);
xptiInterfaceEntry* entry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
if(!entry)
{
*_retval = nsnull;
return NS_ERROR_FAILURE;
}
return entry->GetIID(_retval);
}
/* string getNameForIID (in nsIIDPtr iid); */
NS_IMETHODIMP xptiInterfaceInfoManager::GetNameForIID(const nsIID * iid, char **_retval)
{
NS_ASSERTION(iid, "bad param");
NS_ASSERTION(_retval, "bad param");
xptiHashEntry* hashEntry = (xptiHashEntry*)
PL_DHashTableOperate(mWorkingSet.mIIDTable, iid, PL_DHASH_LOOKUP);
xptiInterfaceEntry* entry =
PL_DHASH_ENTRY_IS_FREE(hashEntry) ? nsnull : hashEntry->value;
if(!entry)
{
*_retval = nsnull;
return NS_ERROR_FAILURE;
}
return entry->GetName(_retval);
}
PR_STATIC_CALLBACK(PLDHashOperator)
xpti_ArrayAppender(PLDHashTable *table, PLDHashEntryHdr *hdr,
PRUint32 number, void *arg)
{
xptiInterfaceEntry* entry = ((xptiHashEntry*)hdr)->value;
nsISupportsArray* array = (nsISupportsArray*) arg;
nsCOMPtr<nsIInterfaceInfo> ii;
if(NS_SUCCEEDED(EntryToInfo(entry, getter_AddRefs(ii))))
array->AppendElement(ii);
return PL_DHASH_NEXT;
}
/* nsIEnumerator enumerateInterfaces (); */
NS_IMETHODIMP xptiInterfaceInfoManager::EnumerateInterfaces(nsIEnumerator **_retval)
{
// I didn't want to incur the size overhead of using nsHashtable just to
// make building an enumerator easier. So, this code makes a snapshot of
// the table using an nsISupportsArray and builds an enumerator for that.
// We can afford this transient cost.
nsCOMPtr<nsISupportsArray> array;
NS_NewISupportsArray(getter_AddRefs(array));
if(!array)
return NS_ERROR_UNEXPECTED;
PL_DHashTableEnumerate(mWorkingSet.mNameTable, xpti_ArrayAppender, array);
return array->Enumerate(_retval);
}
struct ArrayAndPrefix
{
nsISupportsArray* array;
const char* prefix;
PRUint32 length;
};
PR_STATIC_CALLBACK(PLDHashOperator)
xpti_ArrayPrefixAppender(PLDHashTable *table, PLDHashEntryHdr *hdr,
PRUint32 number, void *arg)
{
xptiInterfaceEntry* entry = ((xptiHashEntry*)hdr)->value;
ArrayAndPrefix* args = (ArrayAndPrefix*) arg;
const char* name = entry->GetTheName();
if(name != PL_strnstr(name, args->prefix, args->length))
return PL_DHASH_NEXT;
nsCOMPtr<nsIInterfaceInfo> ii;
if(NS_SUCCEEDED(EntryToInfo(entry, getter_AddRefs(ii))))
args->array->AppendElement(ii);
return PL_DHASH_NEXT;
}
/* nsIEnumerator enumerateInterfacesWhoseNamesStartWith (in string prefix); */
NS_IMETHODIMP xptiInterfaceInfoManager::EnumerateInterfacesWhoseNamesStartWith(const char *prefix, nsIEnumerator **_retval)
{
nsCOMPtr<nsISupportsArray> array;
NS_NewISupportsArray(getter_AddRefs(array));
if(!array)
return NS_ERROR_UNEXPECTED;
ArrayAndPrefix args = {array, prefix, PL_strlen(prefix)};
PL_DHashTableEnumerate(mWorkingSet.mNameTable, xpti_ArrayPrefixAppender, &args);
return array->Enumerate(_retval);
}
/* void autoRegisterInterfaces (); */
NS_IMETHODIMP xptiInterfaceInfoManager::AutoRegisterInterfaces()
{
nsCOMPtr<nsISupportsArray> fileList;
AutoRegMode mode;
PRBool ok;
nsAutoLock lock(xptiInterfaceInfoManager::GetAutoRegLock(this));
xptiWorkingSet workingSet(mSearchPath);
if(!workingSet.IsValid())
return NS_ERROR_UNEXPECTED;
// This sets what will be returned by GetOpenLogFile().
xptiAutoLog autoLog(this, mAutoRegLogFile, PR_TRUE);
LOG_AUTOREG(("start AutoRegister\n"));
// We re-read the manifest rather than muck with the 'live' one.
// It is OK if this fails.
// XXX But we should track failure as a warning.
ok = xptiManifest::Read(this, &workingSet);
LOG_AUTOREG(("read of manifest %s\n", ok ? "successful" : "FAILED"));
// Grovel for all the typelibs we can find (in .xpt or .zip, .jar,...).
if(!BuildFileList(mSearchPath, getter_AddRefs(fileList)) || !fileList)
return NS_ERROR_UNEXPECTED;
// DEBUG_DumpFileList(fileList);
// Check to see how much work we need to do.
mode = DetermineAutoRegStrategy(mSearchPath, fileList, &workingSet);
switch(mode)
{
case NO_FILES_CHANGED:
LOG_AUTOREG(("autoreg strategy: no files changed\n"));
LOG_AUTOREG(("successful end of AutoRegister\n"));
return NS_OK;
case FILES_ADDED_ONLY:
LOG_AUTOREG(("autoreg strategy: files added only\n"));
if(!AddOnlyNewFilesFromFileList(mSearchPath, fileList, &workingSet))
{
LOG_AUTOREG(("FAILED to add new files\n"));
return NS_ERROR_UNEXPECTED;
}
break;
case FULL_VALIDATION_REQUIRED:
LOG_AUTOREG(("autoreg strategy: doing full validation merge\n"));
if(!DoFullValidationMergeFromFileList(mSearchPath, fileList, &workingSet))
{
LOG_AUTOREG(("FAILED to do full validation\n"));
return NS_ERROR_UNEXPECTED;
}
break;
default:
NS_ERROR("switch missing a case");
return NS_ERROR_UNEXPECTED;
}
// Failure to write the manifest is not fatal in production builds.
// However, this would require the next startup to find and read all the
// xpt files. This will make that startup slower. If this ever becomes a
// chronic problem for anyone, then we'll want to figure out why!
if(!xptiManifest::Write(this, &workingSet))
{
LOG_AUTOREG(("FAILED to write manifest\n"));
NS_ERROR("Failed to write xpti manifest!");
}
if(!MergeWorkingSets(&mWorkingSet, &workingSet))
{
LOG_AUTOREG(("FAILED to merge into live workingset\n"));
return NS_ERROR_UNEXPECTED;
}
// DEBUG_DumpFileListInWorkingSet(mWorkingSet);
LOG_AUTOREG(("successful end of AutoRegister\n"));
return NS_OK;
}
/***************************************************************************/
class xptiAdditionalManagersEnumerator : public nsISimpleEnumerator
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISIMPLEENUMERATOR
xptiAdditionalManagersEnumerator();
PRBool SizeTo(PRUint32 likelyCount) {return mArray.SizeTo(likelyCount);}
PRBool AppendElement(nsIInterfaceInfoManager* element);
private:
~xptiAdditionalManagersEnumerator() {}
nsSupportsArray mArray;
PRUint32 mIndex;
PRUint32 mCount;
};
NS_IMPL_ISUPPORTS1(xptiAdditionalManagersEnumerator, nsISimpleEnumerator)
xptiAdditionalManagersEnumerator::xptiAdditionalManagersEnumerator()
: mIndex(0), mCount(0)
{
}
PRBool xptiAdditionalManagersEnumerator::AppendElement(nsIInterfaceInfoManager* element)
{
if(!mArray.AppendElement(NS_STATIC_CAST(nsISupports*, element)))
return PR_FALSE;
mCount++;
return PR_TRUE;
}
/* boolean hasMoreElements (); */
NS_IMETHODIMP xptiAdditionalManagersEnumerator::HasMoreElements(PRBool *_retval)
{
*_retval = mIndex < mCount;
return NS_OK;
}
/* nsISupports getNext (); */
NS_IMETHODIMP xptiAdditionalManagersEnumerator::GetNext(nsISupports **_retval)
{
if(!(mIndex < mCount))
{
NS_ERROR("Bad nsISimpleEnumerator caller!");
return NS_ERROR_FAILURE;
}
*_retval = mArray.ElementAt(mIndex++);
return *_retval ? NS_OK : NS_ERROR_FAILURE;
}
/***************************************************************************/
/* void addAdditionalManager (in nsIInterfaceInfoManager manager); */
NS_IMETHODIMP xptiInterfaceInfoManager::AddAdditionalManager(nsIInterfaceInfoManager *manager)
{
nsCOMPtr<nsIWeakReference> weakRef = do_GetWeakReference(manager);
nsISupports* ptrToAdd = weakRef ?
NS_STATIC_CAST(nsISupports*, weakRef) :
NS_STATIC_CAST(nsISupports*, manager);
{ // scoped lock...
nsAutoLock lock(mAdditionalManagersLock);
PRInt32 index;
nsresult rv = mAdditionalManagers.GetIndexOf(ptrToAdd, &index);
if(NS_FAILED(rv) || -1 != index)
return NS_ERROR_FAILURE;
if(!mAdditionalManagers.AppendElement(ptrToAdd))
return NS_ERROR_OUT_OF_MEMORY;
}
return NS_OK;
}
/* void removeAdditionalManager (in nsIInterfaceInfoManager manager); */
NS_IMETHODIMP xptiInterfaceInfoManager::RemoveAdditionalManager(nsIInterfaceInfoManager *manager)
{
nsCOMPtr<nsIWeakReference> weakRef = do_GetWeakReference(manager);
nsISupports* ptrToRemove = weakRef ?
NS_STATIC_CAST(nsISupports*, weakRef) :
NS_STATIC_CAST(nsISupports*, manager);
{ // scoped lock...
nsAutoLock lock(mAdditionalManagersLock);
if(!mAdditionalManagers.RemoveElement(ptrToRemove))
return NS_ERROR_FAILURE;
}
return NS_OK;
}
/* PRBool hasAdditionalManagers (); */
NS_IMETHODIMP xptiInterfaceInfoManager::HasAdditionalManagers(PRBool *_retval)
{
PRUint32 count;
nsresult rv = mAdditionalManagers.Count(&count);
*_retval = count != 0;
return rv;
}
/* nsISimpleEnumerator enumerateAdditionalManagers (); */
NS_IMETHODIMP xptiInterfaceInfoManager::EnumerateAdditionalManagers(nsISimpleEnumerator **_retval)
{
nsAutoLock lock(mAdditionalManagersLock);
PRUint32 count;
nsresult rv = mAdditionalManagers.Count(&count);
if(NS_FAILED(rv))
return rv;
nsCOMPtr<xptiAdditionalManagersEnumerator> enumerator =
new xptiAdditionalManagersEnumerator();
if(!enumerator)
return NS_ERROR_OUT_OF_MEMORY;
enumerator->SizeTo(count);
for(PRUint32 i = 0; i < count; /* i incremented in the loop body */)
{
nsCOMPtr<nsISupports> raw =
dont_AddRef(mAdditionalManagers.ElementAt(i++));
if(!raw)
return NS_ERROR_FAILURE;
nsCOMPtr<nsIWeakReference> weakRef = do_QueryInterface(raw);
if(weakRef)
{
nsCOMPtr<nsIInterfaceInfoManager> manager =
do_QueryReferent(weakRef);
if(manager)
{
if(!enumerator->AppendElement(manager))
return NS_ERROR_FAILURE;
}
else
{
// The manager is no more. Remove the element.
if(!mAdditionalManagers.RemoveElementAt(--i))
return NS_ERROR_FAILURE;
count--;
}
}
else
{
// We *know* we put a pointer to either a nsIWeakReference or
// an nsIInterfaceInfoManager into the array, so we can avoid an
// extra QI here and just do a cast.
if(!enumerator->AppendElement(
NS_REINTERPRET_CAST(nsIInterfaceInfoManager*, raw.get())))
return NS_ERROR_FAILURE;
}
}
NS_ADDREF(*_retval = enumerator);
return NS_OK;
}
/***************************************************************************/
XPTI_PUBLIC_API(nsIInterfaceInfoManager*)
XPTI_GetInterfaceInfoManager()
{
nsIInterfaceInfoManager* iim =
xptiInterfaceInfoManager::GetInterfaceInfoManagerNoAddRef();
NS_IF_ADDREF(iim);
return iim;
}
XPTI_PUBLIC_API(void)
XPTI_FreeInterfaceInfoManager()
{
xptiInterfaceInfoManager::FreeInterfaceInfoManager();
}
| miguelinux/vbox | src/libs/xpcom18a4/xpcom/reflect/xptinfo/src/xptiInterfaceInfoManager.cpp | C++ | gpl-2.0 | 68,010 |
/**
* Theme.js
*
* Released under LGPL License.
* Copyright (c) 1999-2016 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
define('tinymce/inlite/Theme', [
'global!tinymce.ThemeManager',
'global!tinymce.util.Delay',
'tinymce/inlite/ui/Panel',
'tinymce/inlite/ui/Buttons',
'tinymce/inlite/core/SkinLoader',
'tinymce/inlite/core/SelectionMatcher',
'tinymce/inlite/core/ElementMatcher',
'tinymce/inlite/core/Matcher',
'tinymce/inlite/alien/Arr',
'tinymce/inlite/alien/EditorSettings',
'tinymce/inlite/core/PredicateId'
], function(ThemeManager, Delay, Panel, Buttons, SkinLoader, SelectionMatcher, ElementMatcher, Matcher, Arr, EditorSettings, PredicateId) {
var getSelectionElements = function (editor) {
var node = editor.selection.getNode();
var elms = editor.dom.getParents(node);
return elms;
};
var createToolbar = function (editor, selector, id, items) {
var selectorPredicate = function (elm) {
return editor.dom.is(elm, selector);
};
return {
predicate: selectorPredicate,
id: id,
items: items
};
};
var getToolbars = function (editor) {
var contextToolbars = editor.contextToolbars;
return Arr.flatten([
contextToolbars ? contextToolbars : [],
createToolbar(editor, 'img', 'image', 'alignleft aligncenter alignright')
]);
};
var findMatchResult = function (editor, toolbars) {
var result, elements, contextToolbarsPredicateIds;
elements = getSelectionElements(editor);
contextToolbarsPredicateIds = PredicateId.fromContextToolbars(toolbars);
result = Matcher.match(editor, [
ElementMatcher.element(elements[0], contextToolbarsPredicateIds),
SelectionMatcher.textSelection('text'),
SelectionMatcher.emptyTextBlock(elements, 'insert'),
ElementMatcher.parent(elements, contextToolbarsPredicateIds)
]);
return result && result.rect ? result : null;
};
var togglePanel = function (editor, panel) {
var toggle = function () {
var toolbars = getToolbars(editor);
var result = findMatchResult(editor, toolbars);
if (result) {
panel.show(editor, result.id, result.rect, toolbars);
} else {
panel.hide();
}
};
return function () {
if (!editor.removed) {
toggle();
}
};
};
var ignoreWhenFormIsVisible = function (panel, f) {
return function () {
if (!panel.inForm()) {
f();
}
};
};
var bindContextualToolbarsEvents = function (editor, panel) {
var throttledTogglePanel = Delay.throttle(togglePanel(editor, panel), 0);
var throttledTogglePanelWhenNotInForm = Delay.throttle(ignoreWhenFormIsVisible(panel, togglePanel(editor, panel)), 0);
editor.on('blur hide ObjectResizeStart', panel.hide);
editor.on('click', throttledTogglePanel);
editor.on('nodeChange mouseup', throttledTogglePanelWhenNotInForm);
editor.on('ResizeEditor ResizeWindow keyup', throttledTogglePanel);
editor.on('remove', panel.remove);
editor.shortcuts.add('Alt+F10', '', panel.focus);
};
var overrideLinkShortcut = function (editor, panel) {
editor.shortcuts.remove('meta+k');
editor.shortcuts.add('meta+k', '', function () {
var toolbars = getToolbars(editor);
var result = result = Matcher.match(editor, [
SelectionMatcher.textSelection('quicklink')
]);
if (result) {
panel.show(editor, result.id, result.rect, toolbars);
}
});
};
var renderInlineUI = function (editor, panel) {
SkinLoader.load(editor, function () {
bindContextualToolbarsEvents(editor, panel);
overrideLinkShortcut(editor, panel);
});
return {};
};
var fail = function (message) {
throw new Error(message);
};
ThemeManager.add('inlite', function (editor) {
var panel = new Panel();
Buttons.addToEditor(editor, panel);
var renderUI = function () {
return editor.inline ? renderInlineUI(editor, panel) : fail('inlite theme only supports inline mode.');
};
return {
renderUI: renderUI
};
});
return function() {};
});
| luis-knd/technoMvc | views/tinymce/js/tinymce/themes/inlite/src/main/js/tinymce/inlite/Theme.js | JavaScript | gpl-2.0 | 3,994 |
/* 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.
*
* Additional copyright for this file:
* Copyright (C) 1995-1997 Presto Studios, Inc.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*
*/
#ifndef PEGASUS_NEIGHBORHOOD_WSC_WSC_H
#define PEGASUS_NEIGHBORHOOD_WSC_WSC_H
#include "pegasus/neighborhood/neighborhood.h"
#include "pegasus/neighborhood/wsc/moleculebin.h"
namespace Pegasus {
static const DisplayOrder kWSCMoleculeBinOrder = kMonitorLayer;
static const DisplayOrder kWSCMoleculesMovieOrder = kWSCMoleculeBinOrder + 1;
static const RoomID kWSC01 = 0;
static const RoomID kWSC02Morph = 2;
static const RoomID kWSC02Messages = 3;
static const RoomID kWSC62 = 62;
class WSC : public Neighborhood {
public:
WSC(InputHandler *, PegasusEngine *);
virtual ~WSC() {}
void flushGameState();
virtual uint16 getDateResID() const;
bool okayToJump();
void checkContinuePoint(const RoomID, const DirectionConstant);
bool inSynthesizerGame();
bool canSolve();
void doSolve();
virtual void prepareForAIHint(const Common::String &);
virtual void cleanUpAfterAIHint(const Common::String &);
void init();
void start();
protected:
enum {
kWSCDraggingAntidoteFlag,
kWSCPrivateLabMessagesOpenFlag,
kWSCPrivateInterruptedMorphFlag,
kWSCPrivateInMoleculeGameFlag,
kWSCPrivateSinclairOfficeOpenFlag,
kWSCPrivateOfficeLogOpenFlag,
kWSCPrivate58SouthOpenFlag,
kWSCPrivateClickedCatwalkCableFlag,
kWSCPrivateRobotHeadOpenFlag,
kWSCPrivateSeenPeopleAt17WestFlag,
kWSCPrivateSeenPeopleAt19NorthFlag,
kWSCPrivateSeenPeopleAt21SouthFlag,
kWSCPrivateSeenPeopleAt24SouthFlag,
kWSCPrivateSeenPeopleAt34EastFlag,
kWSCPrivateSeenPeopleAt36WestFlag,
kWSCPrivateSeenPeopleAt38NorthFlag,
kWSCPrivateSeenPeopleAt46SouthFlag,
kWSCPrivateSeenPeopleAt49NorthFlag,
kWSCPrivateSeenPeopleAt73WestFlag,
kWSCPrivateNeedPeopleAt17WestFlag,
kWSCPrivateNeedPeopleAt21SouthFlag,
kWSCPrivateNeedPeopleAt24SouthFlag,
kWSCPrivateNeedPeopleAt34EastFlag,
kWSCPrivateNeedPeopleAt36WestFlag,
kWSCPrivateNeedPeopleAt38NorthFlag,
kWSCPrivateNeedPeopleAt46SouthFlag,
kWSCPrivateNeedPeopleAt49NorthFlag,
kWSCPrivateNeedPeopleAt73WestFlag,
kWSCPrivateGotRetScanChipFlag,
kWSCPrivateGotMapChipFlag,
kWSCPrivateGotOpticalChipFlag,
kNumWSCPrivateFlags
};
void arriveAt(const RoomID, const DirectionConstant);
void turnTo(const DirectionConstant);
void receiveNotification(Notification *, const NotificationFlags);
void dropItemIntoRoom(Item *, Hotspot *);
void clickInHotspot(const Input &, const Hotspot *);
TimeValue getViewTime(const RoomID, const DirectionConstant);
void getZoomEntry(const HotSpotID, ZoomTable::Entry &);
CanMoveForwardReason canMoveForward(ExitTable::Entry &entry);
void cantMoveThatWay(CanMoveForwardReason reason);
CanTurnReason canTurn(TurnDirection turn, DirectionConstant &nextDir);
void zoomTo(const Hotspot *hotspot);
void activateOneHotspot(HotspotInfoTable::Entry &, Hotspot *);
void setUpMoleculeGame();
void nextMoleculeGameLevel();
void startMoleculeGameLevel();
void moleculeGameClick(const HotSpotID);
void loadAmbientLoops();
CanOpenDoorReason canOpenDoor(DoorTable::Entry &);
void cantOpenDoor(CanOpenDoorReason);
void pickedUpItem(Item *);
void doorOpened();
void startExtraSequence(const ExtraID, const NotificationFlags, const InputBits);
void getExtraEntry(const uint32, ExtraTable::Entry &);
void takeItemFromRoom(Item *item);
void checkPeopleCrossing();
void turnLeft();
void turnRight();
void moveForward();
Hotspot *getItemScreenSpot(Item *, DisplayElement *);
int16 getStaticCompassAngle(const RoomID, const DirectionConstant);
void getExitCompassMove(const ExitTable::Entry &exitEntry, FaderMoveSpec &compassMove);
void getExtraCompassMove(const ExtraTable::Entry &entry, FaderMoveSpec &compassMove);
void bumpIntoWall();
void activateHotspots();
void setUpAIRules();
Common::String getBriefingMovie();
Common::String getEnvScanMovie();
uint getNumHints();
Common::String getHintMovie(uint);
void closeDoorOffScreen(const RoomID, const DirectionConstant);
void setUpPoison();
void findSpotEntry(const RoomID, const DirectionConstant, SpotFlags, SpotTable::Entry &);
void timerExpired(const uint32);
Common::String getSoundSpotsName();
Common::String getNavMovieName();
FlagsArray<byte, kNumWSCPrivateFlags> _privateFlags;
const Hotspot *_cachedZoomSpot;
MoleculeBin _moleculeBin;
int32 _moleculeGameLevel, _numCorrect;
Movie _moleculesMovie;
uint32 _levelArray[6];
Common::Rational _energyDrainRate;
Sprite *_argonSprite;
};
} // End of namespace Pegasus
#endif
| fuzzie/scummvm | engines/pegasus/neighborhood/wsc/wsc.h | C | gpl-2.0 | 5,452 |
/*
* 'raw' table, which is the very first hooked in at PRE_ROUTING and LOCAL_OUT .
*
* Copyright (C) 2003 Jozsef Kadlecsik <[email protected]>
*/
#include <linux/module.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <net/ip.h>
#define RAW_VALID_HOOKS ((1 << NF_INET_PRE_ROUTING) | (1 << NF_INET_LOCAL_OUT))
static struct
{
struct ipt_replace repl;
struct ipt_standard entries[2];
struct ipt_error term;
} initial_table __net_initdata = {
.repl = {
.name = "raw",
.valid_hooks = RAW_VALID_HOOKS,
.num_entries = 3,
.size = sizeof(struct ipt_standard) * 2 + sizeof(struct ipt_error),
.hook_entry = {
[NF_INET_PRE_ROUTING] = 0,
[NF_INET_LOCAL_OUT] = sizeof(struct ipt_standard)
},
.underflow = {
[NF_INET_PRE_ROUTING] = 0,
[NF_INET_LOCAL_OUT] = sizeof(struct ipt_standard)
},
},
.entries = {
IPT_STANDARD_INIT(NF_ACCEPT), /* PRE_ROUTING */
IPT_STANDARD_INIT(NF_ACCEPT), /* LOCAL_OUT */
},
.term = IPT_ERROR_INIT, /* ERROR */
};
static struct xt_table packet_raw = {
.name = "raw",
.valid_hooks = RAW_VALID_HOOKS,
.lock = __RW_LOCK_UNLOCKED(packet_raw.lock),
.me = THIS_MODULE,
.af = AF_INET,
};
/* The work comes in here from netfilter.c. */
static unsigned int
ipt_hook(unsigned int hook,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
return ipt_do_table(skb, hook, in, out,
nf_pre_routing_net(in, out)->ipv4.iptable_raw);
}
static unsigned int
ipt_local_hook(unsigned int hook,
struct sk_buff *skb,
const struct net_device *in,
const struct net_device *out,
int (*okfn)(struct sk_buff *))
{
/* root is playing with raw sockets. */
if (skb->len < sizeof(struct iphdr) ||
ip_hdrlen(skb) < sizeof(struct iphdr)) {
if (net_ratelimit())
printk("iptable_raw: ignoring short SOCK_RAW "
"packet.\n");
return NF_ACCEPT;
}
return ipt_do_table(skb, hook, in, out,
nf_local_out_net(in, out)->ipv4.iptable_raw);
}
/* 'raw' is the very first table. */
static struct nf_hook_ops ipt_ops[] __read_mostly = {
{
.hook = ipt_hook,
.pf = PF_INET,
.hooknum = NF_INET_PRE_ROUTING,
.priority = NF_IP_PRI_RAW,
.owner = THIS_MODULE,
},
{
.hook = ipt_local_hook,
.pf = PF_INET,
.hooknum = NF_INET_LOCAL_OUT,
.priority = NF_IP_PRI_RAW,
.owner = THIS_MODULE,
},
};
static int __net_init iptable_raw_net_init(struct net *net)
{
/* Register table */
net->ipv4.iptable_raw =
ipt_register_table(net, &packet_raw, &initial_table.repl);
if (IS_ERR(net->ipv4.iptable_raw))
return PTR_ERR(net->ipv4.iptable_raw);
return 0;
}
static void __net_exit iptable_raw_net_exit(struct net *net)
{
ipt_unregister_table(net->ipv4.iptable_raw);
}
static struct pernet_operations iptable_raw_net_ops = {
.init = iptable_raw_net_init,
.exit = iptable_raw_net_exit,
};
static int __init iptable_raw_init(void)
{
int ret;
ret = register_pernet_subsys(&iptable_raw_net_ops);
if (ret < 0)
return ret;
/* Register hooks */
ret = nf_register_hooks(ipt_ops, ARRAY_SIZE(ipt_ops));
if (ret < 0)
goto cleanup_table;
return ret;
cleanup_table:
unregister_pernet_subsys(&iptable_raw_net_ops);
return ret;
}
static void __exit iptable_raw_fini(void)
{
nf_unregister_hooks(ipt_ops, ARRAY_SIZE(ipt_ops));
unregister_pernet_subsys(&iptable_raw_net_ops);
}
module_init(iptable_raw_init);
module_exit(iptable_raw_fini);
MODULE_LICENSE("GPL");
| binhqnguyen/ln | nsc/linux-2.6.26/net/ipv4/netfilter/iptable_raw.c | C | gpl-2.0 | 3,457 |
---
license: >
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
title: accelerometerSuccess
---
accelerometerSuccess
====================
onSuccess callback function that provides the `[Acceleration](../acceleration/acceleration.html)` information.
function(acceleration) {
// Do something
}
Parameters
----------
- __acceleration__: The acceleration at a single moment in time. (Acceleration)
[Example](../../storage/storage.opendatabase.html)
-------
function onSuccess(acceleration) {
alert('Acceleration X: ' + acceleration.x + '\n' +
'Acceleration Y: ' + acceleration.y + '\n' +
'Acceleration Z: ' + acceleration.z + '\n' +
'Timestamp: ' + acceleration.timestamp + '\n');
};
| Icenium/cordova-docs | www/docs/en/3.0.0/cordova/accelerometer/parameters/accelerometerSuccess.md | Markdown | apache-2.0 | 1,531 |
package mysql
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
import (
"context"
"github.com/Azure/go-autorest/autorest"
"github.com/Azure/go-autorest/autorest/azure"
"net/http"
)
// LogFilesClient is the the Microsoft Azure management API provides create, read, update, and delete functionality for
// Azure MySQL resources including servers, databases, firewall rules, log files and configurations.
type LogFilesClient struct {
BaseClient
}
// NewLogFilesClient creates an instance of the LogFilesClient client.
func NewLogFilesClient(subscriptionID string) LogFilesClient {
return NewLogFilesClientWithBaseURI(DefaultBaseURI, subscriptionID)
}
// NewLogFilesClientWithBaseURI creates an instance of the LogFilesClient client.
func NewLogFilesClientWithBaseURI(baseURI string, subscriptionID string) LogFilesClient {
return LogFilesClient{NewWithBaseURI(baseURI, subscriptionID)}
}
// ListByServer list all the log files in a given server.
//
// resourceGroupName is the name of the resource group that contains the resource. You can obtain this value from
// the Azure Resource Manager API or the portal. serverName is the name of the server.
func (client LogFilesClient) ListByServer(ctx context.Context, resourceGroupName string, serverName string) (result LogFileListResult, err error) {
req, err := client.ListByServerPreparer(ctx, resourceGroupName, serverName)
if err != nil {
err = autorest.NewErrorWithError(err, "mysql.LogFilesClient", "ListByServer", nil, "Failure preparing request")
return
}
resp, err := client.ListByServerSender(req)
if err != nil {
result.Response = autorest.Response{Response: resp}
err = autorest.NewErrorWithError(err, "mysql.LogFilesClient", "ListByServer", resp, "Failure sending request")
return
}
result, err = client.ListByServerResponder(resp)
if err != nil {
err = autorest.NewErrorWithError(err, "mysql.LogFilesClient", "ListByServer", resp, "Failure responding to request")
}
return
}
// ListByServerPreparer prepares the ListByServer request.
func (client LogFilesClient) ListByServerPreparer(ctx context.Context, resourceGroupName string, serverName string) (*http.Request, error) {
pathParameters := map[string]interface{}{
"resourceGroupName": autorest.Encode("path", resourceGroupName),
"serverName": autorest.Encode("path", serverName),
"subscriptionId": autorest.Encode("path", client.SubscriptionID),
}
const APIVersion = "2017-04-30-preview"
queryParameters := map[string]interface{}{
"api-version": APIVersion,
}
preparer := autorest.CreatePreparer(
autorest.AsGet(),
autorest.WithBaseURL(client.BaseURI),
autorest.WithPathParameters("/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DBforMySQL/servers/{serverName}/logFiles", pathParameters),
autorest.WithQueryParameters(queryParameters))
return preparer.Prepare((&http.Request{}).WithContext(ctx))
}
// ListByServerSender sends the ListByServer request. The method will close the
// http.Response Body if it receives an error.
func (client LogFilesClient) ListByServerSender(req *http.Request) (*http.Response, error) {
return autorest.SendWithSender(client, req,
azure.DoRetryWithRegistration(client.Client))
}
// ListByServerResponder handles the response to the ListByServer request. The method always
// closes the http.Response Body.
func (client LogFilesClient) ListByServerResponder(resp *http.Response) (result LogFileListResult, err error) {
err = autorest.Respond(
resp,
client.ByInspecting(),
azure.WithErrorUnlessStatusCode(http.StatusOK),
autorest.ByUnmarshallingJSON(&result),
autorest.ByClosing())
result.Response = autorest.Response{Response: resp}
return
}
| childsb/origin | vendor/github.com/Azure/azure-sdk-for-go/services/mysql/mgmt/2017-04-30-preview/mysql/logfiles.go | GO | apache-2.0 | 4,435 |
cask 'jetbrains-toolbox' do
version '1.4.2492'
sha256 'd8426a5dc0c9c46773a8a41b72e71b8f80cdac0545e942d4fff3f2dabcbf3a68'
url "https://download.jetbrains.com/toolbox/jetbrains-toolbox-#{version}.dmg"
appcast 'https://data.services.jetbrains.com/products/releases?code=TBA&latest=true&type=release',
checkpoint: '1284ec7ed798f102479a563ef7789d963c961fd9ccf2fc68fe35ea5fc14dd1ef'
name 'JetBrains Toolbox'
homepage 'https://www.jetbrains.com/toolbox/app/'
auto_updates true
app 'JetBrains Toolbox.app'
end
| klane/homebrew-cask | Casks/jetbrains-toolbox.rb | Ruby | bsd-2-clause | 531 |
/* Implementation of the MAXLOC intrinsic
Copyright (C) 2002-2013 Free Software Foundation, Inc.
Contributed by Paul Brook <[email protected]>
This file is part of the GNU Fortran 95 runtime library (libgfortran).
Libgfortran 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.
Libgfortran 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.
Under Section 7 of GPL version 3, you are granted additional
permissions described in the GCC Runtime Library Exception, version
3.1, as published by the Free Software Foundation.
You should have received a copy of the GNU General Public License and
a copy of the GCC Runtime Library Exception along with this program;
see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
<http://www.gnu.org/licenses/>. */
#include "libgfortran.h"
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#if defined (HAVE_GFC_INTEGER_2) && defined (HAVE_GFC_INTEGER_16)
extern void maxloc0_16_i2 (gfc_array_i16 * const restrict retarray,
gfc_array_i2 * const restrict array);
export_proto(maxloc0_16_i2);
void
maxloc0_16_i2 (gfc_array_i16 * const restrict retarray,
gfc_array_i2 * const restrict array)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type sstride[GFC_MAX_DIMENSIONS];
index_type dstride;
const GFC_INTEGER_2 *base;
GFC_INTEGER_16 * restrict dest;
index_type rank;
index_type n;
rank = GFC_DESCRIPTOR_RANK (array);
if (rank <= 0)
runtime_error ("Rank of array needs to be > 0");
if (retarray->base_addr == NULL)
{
GFC_DIMENSION_SET(retarray->dim[0], 0, rank-1, 1);
retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1;
retarray->offset = 0;
retarray->base_addr = xmalloc (sizeof (GFC_INTEGER_16) * rank);
}
else
{
if (unlikely (compile_options.bounds_check))
bounds_iforeach_return ((array_t *) retarray, (array_t *) array,
"MAXLOC");
}
dstride = GFC_DESCRIPTOR_STRIDE(retarray,0);
dest = retarray->base_addr;
for (n = 0; n < rank; n++)
{
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n);
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n);
count[n] = 0;
if (extent[n] <= 0)
{
/* Set the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 0;
return;
}
}
base = array->base_addr;
/* Initialize the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 1;
{
GFC_INTEGER_2 maxval;
#if defined(GFC_INTEGER_2_QUIET_NAN)
int fast = 0;
#endif
#if defined(GFC_INTEGER_2_INFINITY)
maxval = -GFC_INTEGER_2_INFINITY;
#else
maxval = (-GFC_INTEGER_2_HUGE-1);
#endif
while (base)
{
do
{
/* Implementation start. */
#if defined(GFC_INTEGER_2_QUIET_NAN)
}
while (0);
if (unlikely (!fast))
{
do
{
if (*base >= maxval)
{
fast = 1;
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
break;
}
base += sstride[0];
}
while (++count[0] != extent[0]);
if (likely (fast))
continue;
}
else do
{
#endif
if (*base > maxval)
{
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
}
/* Implementation end. */
/* Advance to the next element. */
base += sstride[0];
}
while (++count[0] != extent[0]);
n = 0;
do
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
base -= sstride[n] * extent[n];
n++;
if (n == rank)
{
/* Break out of the loop. */
base = NULL;
break;
}
else
{
count[n]++;
base += sstride[n];
}
}
while (count[n] == extent[n]);
}
}
}
extern void mmaxloc0_16_i2 (gfc_array_i16 * const restrict,
gfc_array_i2 * const restrict, gfc_array_l1 * const restrict);
export_proto(mmaxloc0_16_i2);
void
mmaxloc0_16_i2 (gfc_array_i16 * const restrict retarray,
gfc_array_i2 * const restrict array,
gfc_array_l1 * const restrict mask)
{
index_type count[GFC_MAX_DIMENSIONS];
index_type extent[GFC_MAX_DIMENSIONS];
index_type sstride[GFC_MAX_DIMENSIONS];
index_type mstride[GFC_MAX_DIMENSIONS];
index_type dstride;
GFC_INTEGER_16 *dest;
const GFC_INTEGER_2 *base;
GFC_LOGICAL_1 *mbase;
int rank;
index_type n;
int mask_kind;
rank = GFC_DESCRIPTOR_RANK (array);
if (rank <= 0)
runtime_error ("Rank of array needs to be > 0");
if (retarray->base_addr == NULL)
{
GFC_DIMENSION_SET(retarray->dim[0], 0, rank - 1, 1);
retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1;
retarray->offset = 0;
retarray->base_addr = xmalloc (sizeof (GFC_INTEGER_16) * rank);
}
else
{
if (unlikely (compile_options.bounds_check))
{
bounds_iforeach_return ((array_t *) retarray, (array_t *) array,
"MAXLOC");
bounds_equal_extents ((array_t *) mask, (array_t *) array,
"MASK argument", "MAXLOC");
}
}
mask_kind = GFC_DESCRIPTOR_SIZE (mask);
mbase = mask->base_addr;
if (mask_kind == 1 || mask_kind == 2 || mask_kind == 4 || mask_kind == 8
#ifdef HAVE_GFC_LOGICAL_16
|| mask_kind == 16
#endif
)
mbase = GFOR_POINTER_TO_L1 (mbase, mask_kind);
else
runtime_error ("Funny sized logical array");
dstride = GFC_DESCRIPTOR_STRIDE(retarray,0);
dest = retarray->base_addr;
for (n = 0; n < rank; n++)
{
sstride[n] = GFC_DESCRIPTOR_STRIDE(array,n);
mstride[n] = GFC_DESCRIPTOR_STRIDE_BYTES(mask,n);
extent[n] = GFC_DESCRIPTOR_EXTENT(array,n);
count[n] = 0;
if (extent[n] <= 0)
{
/* Set the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 0;
return;
}
}
base = array->base_addr;
/* Initialize the return value. */
for (n = 0; n < rank; n++)
dest[n * dstride] = 0;
{
GFC_INTEGER_2 maxval;
int fast = 0;
#if defined(GFC_INTEGER_2_INFINITY)
maxval = -GFC_INTEGER_2_INFINITY;
#else
maxval = (-GFC_INTEGER_2_HUGE-1);
#endif
while (base)
{
do
{
/* Implementation start. */
}
while (0);
if (unlikely (!fast))
{
do
{
if (*mbase)
{
#if defined(GFC_INTEGER_2_QUIET_NAN)
if (unlikely (dest[0] == 0))
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
if (*base >= maxval)
#endif
{
fast = 1;
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
break;
}
}
base += sstride[0];
mbase += mstride[0];
}
while (++count[0] != extent[0]);
if (likely (fast))
continue;
}
else do
{
if (*mbase && *base > maxval)
{
maxval = *base;
for (n = 0; n < rank; n++)
dest[n * dstride] = count[n] + 1;
}
/* Implementation end. */
/* Advance to the next element. */
base += sstride[0];
mbase += mstride[0];
}
while (++count[0] != extent[0]);
n = 0;
do
{
/* When we get to the end of a dimension, reset it and increment
the next dimension. */
count[n] = 0;
/* We could precalculate these products, but this is a less
frequently used path so probably not worth it. */
base -= sstride[n] * extent[n];
mbase -= mstride[n] * extent[n];
n++;
if (n == rank)
{
/* Break out of the loop. */
base = NULL;
break;
}
else
{
count[n]++;
base += sstride[n];
mbase += mstride[n];
}
}
while (count[n] == extent[n]);
}
}
}
extern void smaxloc0_16_i2 (gfc_array_i16 * const restrict,
gfc_array_i2 * const restrict, GFC_LOGICAL_4 *);
export_proto(smaxloc0_16_i2);
void
smaxloc0_16_i2 (gfc_array_i16 * const restrict retarray,
gfc_array_i2 * const restrict array,
GFC_LOGICAL_4 * mask)
{
index_type rank;
index_type dstride;
index_type n;
GFC_INTEGER_16 *dest;
if (*mask)
{
maxloc0_16_i2 (retarray, array);
return;
}
rank = GFC_DESCRIPTOR_RANK (array);
if (rank <= 0)
runtime_error ("Rank of array needs to be > 0");
if (retarray->base_addr == NULL)
{
GFC_DIMENSION_SET(retarray->dim[0], 0, rank-1, 1);
retarray->dtype = (retarray->dtype & ~GFC_DTYPE_RANK_MASK) | 1;
retarray->offset = 0;
retarray->base_addr = xmalloc (sizeof (GFC_INTEGER_16) * rank);
}
else if (unlikely (compile_options.bounds_check))
{
bounds_iforeach_return ((array_t *) retarray, (array_t *) array,
"MAXLOC");
}
dstride = GFC_DESCRIPTOR_STRIDE(retarray,0);
dest = retarray->base_addr;
for (n = 0; n<rank; n++)
dest[n * dstride] = 0 ;
}
#endif
| wilseypa/llamaOS | src/sys/gcc-4.8.0/libgfortran/generated/maxloc0_16_i2.c | C | bsd-2-clause | 9,176 |
require 'formula'
class LittleCms < Formula
homepage 'http://www.littlecms.com/'
url 'https://downloads.sourceforge.net/project/lcms/lcms/1.19/lcms-1.19.tar.gz'
sha1 'd5b075ccffc0068015f74f78e4bc39138bcfe2d4'
bottle do
cellar :any
revision 1
sha1 "bf1ee324d9c03017d15e380e5f6efc25ec8e2831" => :yosemite
sha1 "3642f7bcd6d1e64826b3a184a000fe6e3ea9ad0f" => :mavericks
sha1 "bc893b9e8deeaed1a4cd2f84595d17f8a7e44d76" => :mountain_lion
end
option :universal
depends_on :python => :optional
depends_on 'jpeg' => :recommended
depends_on 'libtiff' => :recommended
def install
ENV.universal_binary if build.universal?
args = %W{--disable-dependency-tracking --disable-debug --prefix=#{prefix}}
args << "--without-tiff" if build.without? "libtiff"
args << "--without-jpeg" if build.without? "jpeg"
if build.with? "python"
args << "--with-python"
inreplace "python/Makefile.in" do |s|
s.change_make_var! "pkgdir", lib/"python2.7/site-packages"
end
end
system "./configure", *args
system "make"
ENV.deparallelize
system "make", "install"
end
end
| jtrag/homebrew | Library/Formula/little-cms.rb | Ruby | bsd-2-clause | 1,148 |
Oj.optimize_rails
| nbrady-techempower/FrameworkBenchmarks | frameworks/Ruby/rails/config/initializers/oj.rb | Ruby | bsd-3-clause | 18 |
// Copyright 2013 The Closure Library Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS-IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
/**
* @fileoverview Implementation of a WebChannel transport using WebChannelBase.
*
* When WebChannelBase is used as the underlying transport, the capabilities
* of the WebChannel are limited to what's supported by the implementation.
* Particularly, multiplexing is not possible, and only strings are
* supported as message types.
*
*/
goog.provide('goog.labs.net.webChannel.WebChannelBaseTransport');
goog.require('goog.asserts');
goog.require('goog.events.EventTarget');
goog.require('goog.json');
goog.require('goog.labs.net.webChannel.ChannelRequest');
goog.require('goog.labs.net.webChannel.WebChannelBase');
goog.require('goog.log');
goog.require('goog.net.WebChannel');
goog.require('goog.net.WebChannelTransport');
goog.require('goog.object');
goog.require('goog.string.path');
/**
* Implementation of {@link goog.net.WebChannelTransport} with
* {@link goog.labs.net.webChannel.WebChannelBase} as the underlying channel
* implementation.
*
* @constructor
* @struct
* @implements {goog.net.WebChannelTransport}
* @final
*/
goog.labs.net.webChannel.WebChannelBaseTransport = function() {
if (!goog.labs.net.webChannel.ChannelRequest.supportsXhrStreaming()) {
throw new Error('Environmental error: no available transport.');
}
};
goog.scope(function() {
var WebChannelBaseTransport = goog.labs.net.webChannel.WebChannelBaseTransport;
var WebChannelBase = goog.labs.net.webChannel.WebChannelBase;
/**
* @override
*/
WebChannelBaseTransport.prototype.createWebChannel = function(
url, opt_options) {
return new WebChannelBaseTransport.Channel(url, opt_options);
};
/**
* Implementation of the {@link goog.net.WebChannel} interface.
*
* @param {string} url The URL path for the new WebChannel instance.
* @param {!goog.net.WebChannel.Options=} opt_options Configuration for the
* new WebChannel instance.
*
* @constructor
* @implements {goog.net.WebChannel}
* @extends {goog.events.EventTarget}
* @final
*/
WebChannelBaseTransport.Channel = function(url, opt_options) {
WebChannelBaseTransport.Channel.base(this, 'constructor');
/**
* @private {!WebChannelBase} The underlying channel object.
*/
this.channel_ = new WebChannelBase(opt_options);
/**
* @private {string} The URL of the target server end-point.
*/
this.url_ = url;
/**
* The test URL of the target server end-point. This value defaults to
* this.url_ + '/test'.
*
* @private {string}
*/
this.testUrl_ = (opt_options && opt_options.testUrl) ?
opt_options.testUrl :
goog.string.path.join(this.url_, 'test');
/**
* @private {goog.log.Logger} The logger for this class.
*/
this.logger_ =
goog.log.getLogger('goog.labs.net.webChannel.WebChannelBaseTransport');
/**
* @private {Object<string, string>} Extra URL parameters
* to be added to each HTTP request.
*/
this.messageUrlParams_ =
(opt_options && opt_options.messageUrlParams) || null;
var messageHeaders = (opt_options && opt_options.messageHeaders) || null;
// default is false
if (opt_options && opt_options.clientProtocolHeaderRequired) {
if (messageHeaders) {
goog.object.set(
messageHeaders, goog.net.WebChannel.X_CLIENT_PROTOCOL,
goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);
} else {
messageHeaders = goog.object.create(
goog.net.WebChannel.X_CLIENT_PROTOCOL,
goog.net.WebChannel.X_CLIENT_PROTOCOL_WEB_CHANNEL);
}
}
this.channel_.setExtraHeaders(messageHeaders);
/**
* @private {boolean} Whether to enable CORS.
*/
this.supportsCrossDomainXhr_ =
(opt_options && opt_options.supportsCrossDomainXhr) || false;
/**
* @private {boolean} Whether to send raw Json and bypass v8 wire format.
*/
this.sendRawJson_ = (opt_options && opt_options.sendRawJson) || false;
/**
* The channel handler.
*
* @private {!WebChannelBaseTransport.Channel.Handler_}
*/
this.channelHandler_ = new WebChannelBaseTransport.Channel.Handler_(this);
};
goog.inherits(WebChannelBaseTransport.Channel, goog.events.EventTarget);
/**
* Test path is always set to "/url/test".
*
* @override
*/
WebChannelBaseTransport.Channel.prototype.open = function() {
this.channel_.setHandler(this.channelHandler_);
if (this.supportsCrossDomainXhr_) {
this.channel_.setSupportsCrossDomainXhrs(true);
}
this.channel_.connect(
this.testUrl_, this.url_, (this.messageUrlParams_ || undefined));
};
/**
* @override
*/
WebChannelBaseTransport.Channel.prototype.close = function() {
this.channel_.disconnect();
};
/**
* The WebChannelBase only supports object types.
*
* @param {!goog.net.WebChannel.MessageData} message The message to send.
* @override
*/
WebChannelBaseTransport.Channel.prototype.send = function(message) {
goog.asserts.assert(goog.isObject(message), 'only object type expected');
if (this.sendRawJson_) {
var rawJson = {};
rawJson['__data__'] = goog.json.serialize(message);
this.channel_.sendMap(rawJson);
} else {
this.channel_.sendMap(message);
}
};
/**
* @override
*/
WebChannelBaseTransport.Channel.prototype.disposeInternal = function() {
this.channel_.setHandler(null);
delete this.channelHandler_;
this.channel_.disconnect();
delete this.channel_;
WebChannelBaseTransport.Channel.base(this, 'disposeInternal');
};
/**
* The message event.
*
* @param {!Array<?>} array The data array from the underlying channel.
* @constructor
* @extends {goog.net.WebChannel.MessageEvent}
* @final
*/
WebChannelBaseTransport.Channel.MessageEvent = function(array) {
WebChannelBaseTransport.Channel.MessageEvent.base(this, 'constructor');
this.data = array;
};
goog.inherits(
WebChannelBaseTransport.Channel.MessageEvent,
goog.net.WebChannel.MessageEvent);
/**
* The error event.
*
* @param {WebChannelBase.Error} error The error code.
* @constructor
* @extends {goog.net.WebChannel.ErrorEvent}
* @final
*/
WebChannelBaseTransport.Channel.ErrorEvent = function(error) {
WebChannelBaseTransport.Channel.ErrorEvent.base(this, 'constructor');
/**
* Transport specific error code is not to be propagated with the event.
*/
this.status = goog.net.WebChannel.ErrorStatus.NETWORK_ERROR;
};
goog.inherits(
WebChannelBaseTransport.Channel.ErrorEvent, goog.net.WebChannel.ErrorEvent);
/**
* Implementation of {@link WebChannelBase.Handler} interface.
*
* @param {!WebChannelBaseTransport.Channel} channel The enclosing WebChannel.
*
* @constructor
* @extends {WebChannelBase.Handler}
* @private
*/
WebChannelBaseTransport.Channel.Handler_ = function(channel) {
WebChannelBaseTransport.Channel.Handler_.base(this, 'constructor');
/**
* @type {!WebChannelBaseTransport.Channel}
* @private
*/
this.channel_ = channel;
};
goog.inherits(WebChannelBaseTransport.Channel.Handler_, WebChannelBase.Handler);
/**
* @override
*/
WebChannelBaseTransport.Channel.Handler_.prototype.channelOpened = function(
channel) {
goog.log.info(
this.channel_.logger_, 'WebChannel opened on ' + this.channel_.url_);
this.channel_.dispatchEvent(goog.net.WebChannel.EventType.OPEN);
};
/**
* @override
*/
WebChannelBaseTransport.Channel.Handler_.prototype.channelHandleArray =
function(channel, array) {
goog.asserts.assert(array, 'array expected to be defined');
this.channel_.dispatchEvent(
new WebChannelBaseTransport.Channel.MessageEvent(array));
};
/**
* @override
*/
WebChannelBaseTransport.Channel.Handler_.prototype.channelError = function(
channel, error) {
goog.log.info(
this.channel_.logger_, 'WebChannel aborted on ' + this.channel_.url_ +
' due to channel error: ' + error);
this.channel_.dispatchEvent(
new WebChannelBaseTransport.Channel.ErrorEvent(error));
};
/**
* @override
*/
WebChannelBaseTransport.Channel.Handler_.prototype.channelClosed = function(
channel, opt_pendingMaps, opt_undeliveredMaps) {
goog.log.info(
this.channel_.logger_, 'WebChannel closed on ' + this.channel_.url_);
this.channel_.dispatchEvent(goog.net.WebChannel.EventType.CLOSE);
};
/**
* @override
*/
WebChannelBaseTransport.Channel.prototype.getRuntimeProperties = function() {
return new WebChannelBaseTransport.ChannelProperties(this.channel_);
};
/**
* Implementation of the {@link goog.net.WebChannel.RuntimeProperties}.
*
* @param {!WebChannelBase} channel The underlying channel object.
*
* @constructor
* @implements {goog.net.WebChannel.RuntimeProperties}
* @final
*/
WebChannelBaseTransport.ChannelProperties = function(channel) {
/**
* The underlying channel object.
*
* @private {!WebChannelBase}
*/
this.channel_ = channel;
};
/**
* @override
*/
WebChannelBaseTransport.ChannelProperties.prototype.getConcurrentRequestLimit =
function() {
return this.channel_.getForwardChannelRequestPool().getMaxSize();
};
/**
* @override
*/
WebChannelBaseTransport.ChannelProperties.prototype.isSpdyEnabled = function() {
return this.getConcurrentRequestLimit() > 1;
};
/**
* @override
*/
WebChannelBaseTransport.ChannelProperties.prototype.setServerFlowControl =
goog.abstractMethod;
/**
* @override
*/
WebChannelBaseTransport.ChannelProperties.prototype.getNonAckedMessageCount =
goog.abstractMethod;
/** @override */
WebChannelBaseTransport.ChannelProperties.prototype.getLastStatusCode =
function() {
return this.channel_.getLastStatusCode();
};
}); // goog.scope
| LeoLombardi/tos-laimas-compass | tos-laimas-compass-win32-x64/resources/app/node_modules/closure-util/.deps/library/b06c979ecae7d78dd1ac4f7b09adec643baac308/closure/goog/labs/net/webchannel/webchannelbasetransport.js | JavaScript | mit | 10,134 |
// Type definitions for materialize-css 1.0
// Project: http://materializecss.com/
// Definitions by: 胡玮文 <https://github.com/huww98>
// Maxim Balaganskiy <https://github.com/MaximBalaganskiy>
// David Moniz <https://github.com/MonizDave>
// Daniel Hoenes <https://github.com/broccoliarchy>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.4
/// <reference types="jquery" />
/// <reference path="./autocomplete.d.ts" />
/// <reference path="./carousel.d.ts" />
/// <reference path="./character-counter.d.ts" />
/// <reference path="./chips.d.ts" />
/// <reference path="./collapsible.d.ts" />
/// <reference path="./common.d.ts" />
/// <reference path="./datepicker.d.ts" />
/// <reference path="./dropdown.d.ts" />
/// <reference path="./fab.d.ts" />
/// <reference path="./formselect.d.ts" />
/// <reference path="./inputfields.d.ts" />
/// <reference path="./materialbox.d.ts" />
/// <reference path="./modal.d.ts" />
/// <reference path="./parallax.d.ts" />
/// <reference path="./pushpin.d.ts" />
/// <reference path="./range.d.ts" />
/// <reference path="./scrollspy.d.ts" />
/// <reference path="./sidenav.d.ts" />
/// <reference path="./slider.d.ts" />
/// <reference path="./tabs.d.ts" />
/// <reference path="./taptarget.d.ts" />
/// <reference path="./timepicker.d.ts" />
/// <reference path="./toast.d.ts" />
/// <reference path="./tooltip.d.ts" />
/// <reference path="./waves.d.ts" />
export = M;
| rolandzwaga/DefinitelyTyped | types/materialize-css/index.d.ts | TypeScript | mit | 1,514 |
// Copyright 2014 beego Author. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Package context provide the context utils
// Usage:
//
// import "github.com/astaxie/beego/context"
//
// ctx := context.Context{Request:req,ResponseWriter:rw}
//
// more docs http://beego.me/docs/module/context.md
package context
import (
"bufio"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"errors"
"fmt"
"net"
"net/http"
"strconv"
"strings"
"time"
"github.com/astaxie/beego/utils"
)
// NewContext return the Context with Input and Output
func NewContext() *Context {
return &Context{
Input: NewInput(),
Output: NewOutput(),
}
}
// Context Http request context struct including BeegoInput, BeegoOutput, http.Request and http.ResponseWriter.
// BeegoInput and BeegoOutput provides some api to operate request and response more easily.
type Context struct {
Input *BeegoInput
Output *BeegoOutput
Request *http.Request
ResponseWriter *Response
_xsrfToken string
}
// Reset init Context, BeegoInput and BeegoOutput
func (ctx *Context) Reset(rw http.ResponseWriter, r *http.Request) {
ctx.Request = r
if ctx.ResponseWriter == nil {
ctx.ResponseWriter = &Response{}
}
ctx.ResponseWriter.reset(rw)
ctx.Input.Reset(ctx)
ctx.Output.Reset(ctx)
ctx._xsrfToken = ""
}
// Redirect does redirection to localurl with http header status code.
func (ctx *Context) Redirect(status int, localurl string) {
http.Redirect(ctx.ResponseWriter, ctx.Request, localurl, status)
}
// Abort stops this request.
// if beego.ErrorMaps exists, panic body.
func (ctx *Context) Abort(status int, body string) {
ctx.Output.SetStatus(status)
panic(body)
}
// WriteString Write string to response body.
// it sends response body.
func (ctx *Context) WriteString(content string) {
ctx.ResponseWriter.Write([]byte(content))
}
// GetCookie Get cookie from request by a given key.
// It's alias of BeegoInput.Cookie.
func (ctx *Context) GetCookie(key string) string {
return ctx.Input.Cookie(key)
}
// SetCookie Set cookie for response.
// It's alias of BeegoOutput.Cookie.
func (ctx *Context) SetCookie(name string, value string, others ...interface{}) {
ctx.Output.Cookie(name, value, others...)
}
// GetSecureCookie Get secure cookie from request by a given key.
func (ctx *Context) GetSecureCookie(Secret, key string) (string, bool) {
val := ctx.Input.Cookie(key)
if val == "" {
return "", false
}
parts := strings.SplitN(val, "|", 3)
if len(parts) != 3 {
return "", false
}
vs := parts[0]
timestamp := parts[1]
sig := parts[2]
h := hmac.New(sha1.New, []byte(Secret))
fmt.Fprintf(h, "%s%s", vs, timestamp)
if fmt.Sprintf("%02x", h.Sum(nil)) != sig {
return "", false
}
res, _ := base64.URLEncoding.DecodeString(vs)
return string(res), true
}
// SetSecureCookie Set Secure cookie for response.
func (ctx *Context) SetSecureCookie(Secret, name, value string, others ...interface{}) {
vs := base64.URLEncoding.EncodeToString([]byte(value))
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
h := hmac.New(sha1.New, []byte(Secret))
fmt.Fprintf(h, "%s%s", vs, timestamp)
sig := fmt.Sprintf("%02x", h.Sum(nil))
cookie := strings.Join([]string{vs, timestamp, sig}, "|")
ctx.Output.Cookie(name, cookie, others...)
}
// XSRFToken creates a xsrf token string and returns.
func (ctx *Context) XSRFToken(key string, expire int64) string {
if ctx._xsrfToken == "" {
token, ok := ctx.GetSecureCookie(key, "_xsrf")
if !ok {
token = string(utils.RandomCreateBytes(32))
ctx.SetSecureCookie(key, "_xsrf", token, expire)
}
ctx._xsrfToken = token
}
return ctx._xsrfToken
}
// CheckXSRFCookie checks xsrf token in this request is valid or not.
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
// or in form field value named as "_xsrf".
func (ctx *Context) CheckXSRFCookie() bool {
token := ctx.Input.Query("_xsrf")
if token == "" {
token = ctx.Request.Header.Get("X-Xsrftoken")
}
if token == "" {
token = ctx.Request.Header.Get("X-Csrftoken")
}
if token == "" {
ctx.Abort(403, "'_xsrf' argument missing from POST")
return false
}
if ctx._xsrfToken != token {
ctx.Abort(403, "XSRF cookie does not match POST argument")
return false
}
return true
}
//Response is a wrapper for the http.ResponseWriter
//started set to true if response was written to then don't execute other handler
type Response struct {
http.ResponseWriter
Started bool
Status int
}
func (r *Response) reset(rw http.ResponseWriter) {
r.ResponseWriter = rw
r.Status = 0
r.Started = false
}
// Write writes the data to the connection as part of an HTTP reply,
// and sets `started` to true.
// started means the response has sent out.
func (r *Response) Write(p []byte) (int, error) {
r.Started = true
return r.ResponseWriter.Write(p)
}
// WriteHeader sends an HTTP response header with status code,
// and sets `started` to true.
func (r *Response) WriteHeader(code int) {
if r.Status > 0 {
//prevent multiple response.WriteHeader calls
return
}
r.Status = code
r.Started = true
r.ResponseWriter.WriteHeader(code)
}
// Hijack hijacker for http
func (r *Response) Hijack() (net.Conn, *bufio.ReadWriter, error) {
hj, ok := r.ResponseWriter.(http.Hijacker)
if !ok {
return nil, nil, errors.New("webserver doesn't support hijacking")
}
return hj.Hijack()
}
// Flush http.Flusher
func (r *Response) Flush() {
if f, ok := r.ResponseWriter.(http.Flusher); ok {
f.Flush()
}
}
// CloseNotify http.CloseNotifier
func (r *Response) CloseNotify() <-chan bool {
if cn, ok := r.ResponseWriter.(http.CloseNotifier); ok {
return cn.CloseNotify()
}
return nil
}
| laincloud/hagrid | vendor/github.com/astaxie/beego/context/context.go | GO | mit | 6,203 |
#!/usr/bin/env ruby
$:.unshift '../../../../../lib'
require 'xmpp4r'
require 'xmpp4r/roster'
require 'xmpp4r/tune'
require 'rbosa'
#
# Send XEP-0118 User Tune events...
#
# See Jabber::UserTune::Helper for the gory details...
#
# NB needs rbosa library to access iTunes - only on MacOSX
#
if ARGV.length != 2:
puts "Usage: ruby tune_server.rb <jid> <pw>"
exit 1
end
jid=ARGV[0]
pw=ARGV[1]
Jabber::debug=true
cl = Jabber::Client.new(jid)
cl.connect
cl.auth(pw)
# Following XEP-0163 PEP we need to
# ensure we have a 'both' subscription to the Tune client
roster = Jabber::Roster::Helper.new(cl)
roster.add_subscription_request_callback do |item,pres|
roster.accept_subscription(pres.from)
reply = pres.answer
reply.type = :subscribe
cl.send(reply)
end
cl.send(Jabber::Presence.new.set_show(:chat))
t=Jabber::UserTune::Helper.new(cl, nil)
itunes=OSA.app('iTunes')
loop do
track = itunes.current_track
if track
puts "Now playing: #{track.name} by #{track.artist}"
t.now_playing(Jabber::UserTune::Tune.new(track.artist, track.name))
end
sleep 5
end
| activenetwork/owl | vendor/gems/xmpp4r-0.4/data/doc/xmpp4r/examples/basic/tune_server.rb | Ruby | mit | 1,088 |
/*****************************************************************************
* ft2_font.cpp
*****************************************************************************
* Copyright (C) 2003 the VideoLAN team
* $Id$
*
* Authors: Cyril Deguet <[email protected]>
* Olivier Teulière <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* 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 <errno.h>
#include "ft2_font.hpp"
#include "ft2_bitmap.hpp"
#include "ft2_err.h"
#include "../utils/ustring.hpp"
#ifdef HAVE_FRIBIDI
#include <fribidi/fribidi.h>
#endif
FT2Font::FT2Font( intf_thread_t *pIntf, const std::string &rName, int size ):
GenericFont( pIntf ), m_name( rName ), m_buffer( NULL ), m_size( size ),
m_lib( NULL ), m_face( NULL )
{
}
FT2Font::~FT2Font()
{
GlyphMap_t::iterator iter;
for( iter = m_glyphCache.begin(); iter != m_glyphCache.end(); ++iter )
FT_Done_Glyph( (*iter).second.m_glyph );
if( m_face ) FT_Done_Face( m_face );
if( m_lib ) FT_Done_FreeType( m_lib );
delete[] m_buffer;
}
bool FT2Font::init()
{
unsigned err;
if( ( err = FT_Init_FreeType( &m_lib ) ) )
{
msg_Err( getIntf(), "failed to initialize freetype (%s)",
ft2_strerror( err ) );
return false;
}
FILE *file = vlc_fopen( m_name.c_str(), "rb" );
if( !file )
{
msg_Dbg( getIntf(), "failed to open font %s (%s)",
m_name.c_str(), strerror(errno) );
return false;
}
msg_Dbg( getIntf(), "loading font %s", m_name.c_str() );
fseek( file, 0, SEEK_END );
long size = ftell( file );
rewind( file );
if( -1==size )
{
msg_Dbg( getIntf(), "fseek loading font %s (%s)",
m_name.c_str(), strerror(errno) );
fclose( file );
return false;
}
m_buffer = new (std::nothrow) char[size];
if( !m_buffer )
{
fclose( file );
return false;
}
if( fread( m_buffer, size, 1, file ) != 1 )
{
msg_Err( getIntf(), "unexpected result for read" );
fclose( file );
return false;
}
fclose( file );
err = FT_New_Memory_Face( m_lib, (const FT_Byte*)m_buffer, size, 0,
&m_face );
if ( err == FT_Err_Unknown_File_Format )
{
msg_Err( getIntf(), "unsupported font format (%s)", m_name.c_str() );
return false;
}
else if ( err )
{
msg_Err( getIntf(), "error opening font %s (%s)",
m_name.c_str(), ft2_strerror(err) );
return false;
}
// Select the charset
if( ( err = FT_Select_Charmap( m_face, ft_encoding_unicode ) ) )
{
msg_Err( getIntf(), "font %s has no UNICODE table (%s)",
m_name.c_str(), ft2_strerror(err) );
return false;
}
// Set the pixel size
if( ( err = FT_Set_Pixel_Sizes( m_face, 0, m_size ) ) )
{
msg_Warn( getIntf(), "cannot set a pixel size of %d for %s (%s)",
m_size, m_name.c_str(), ft2_strerror(err) );
}
// Get the font metrucs
m_height = m_face->size->metrics.height >> 6;
m_ascender = m_face->size->metrics.ascender >> 6;
m_descender = m_face->size->metrics.descender >> 6;
return true;
}
GenericBitmap *FT2Font::drawString( const UString &rString, uint32_t color,
int maxWidth ) const
{
uint32_t code;
int n;
int penX = 0;
int width1 = 0, width2 = 0;
int yMin = 0, yMax = 0;
uint32_t *pString = (uint32_t*)rString.u_str();
// Check if freetype has been initialized
if( !m_face )
{
return NULL;
}
// Get the length of the string
int len = rString.length();
// Use fribidi if available
#ifdef HAVE_FRIBIDI
uint32_t *pFribidiString = NULL;
if( len > 0 )
{
pFribidiString = new uint32_t[len+1];
FriBidiCharType baseDir = FRIBIDI_TYPE_ON;
fribidi_log2vis( (FriBidiChar*)pString, len, &baseDir,
(FriBidiChar*)pFribidiString, 0, 0, 0 );
pString = pFribidiString;
}
#endif
// Array of glyph bitmaps and position
FT_BitmapGlyphRec **glyphs = new FT_BitmapGlyphRec*[len];
int *pos = new int[len];
// Does the font support kerning ?
FT_Bool useKerning = FT_HAS_KERNING( m_face );
int previous = 0;
// Index of the last glyph when the text is truncated with trailing ...
int maxIndex = 0;
// Position of the first trailing dot
int firstDotX = 0;
/// Get the dot glyph
Glyph_t &dotGlyph = getGlyph( '.' );
// First, render all the glyphs
for( n = 0; n < len; n++ )
{
code = *(pString++);
// Get the glyph for this character
Glyph_t &glyph = getGlyph( code );
glyphs[n] = (FT_BitmapGlyphRec*)(glyph.m_glyph);
// Retrieve kerning distance and move pen position
if( useKerning && previous && glyph.m_index )
{
FT_Vector delta;
FT_Get_Kerning( m_face, previous, glyph.m_index,
ft_kerning_default, &delta );
penX += delta.x >> 6;
}
pos[n] = penX;
width1 = penX + glyph.m_size.xMax - glyph.m_size.xMin;
yMin = __MIN( yMin, glyph.m_size.yMin );
yMax = __MAX( yMax, glyph.m_size.yMax );
// Next position
penX += glyph.m_advance;
// Save glyph index
previous = glyph.m_index;
if( maxWidth != -1 )
{
// Check if the truncated text with the '...' fit in the maxWidth
int curX = penX;
if( useKerning )
{
FT_Vector delta;
FT_Get_Kerning( m_face, glyph.m_index, dotGlyph.m_index,
ft_kerning_default, &delta );
curX += delta.x >> 6;
}
int dotWidth = 2 * dotGlyph.m_advance +
dotGlyph.m_size.xMax - dotGlyph.m_size.xMin;
if( curX + dotWidth < maxWidth )
{
width2 = curX + dotWidth;
maxIndex++;
firstDotX = curX;
}
}
else
{
// No check
width2 = width1;
maxIndex++;
}
// Stop here if the text is too large
if( maxWidth != -1 && width1 > maxWidth )
{
break;
}
}
#ifdef HAVE_FRIBIDI
if( len > 0 )
{
delete[] pFribidiString;
}
#endif
// Adjust the size for vertical padding
yMax = __MAX( yMax, m_ascender );
yMin = __MIN( yMin, m_descender );
// Create the bitmap
FT2Bitmap *pBmp = new FT2Bitmap( getIntf(), __MIN( width1, width2 ),
yMax - yMin );
// Draw the glyphs on the bitmap
for( n = 0; n < maxIndex; n++ )
{
FT_BitmapGlyphRec *pBmpGlyph = (FT_BitmapGlyphRec*)glyphs[n];
// Draw the glyph on the bitmap
pBmp->draw( pBmpGlyph->bitmap, pos[n], yMax - pBmpGlyph->top, color );
}
// Draw the trailing dots if the text is truncated
if( maxIndex < len )
{
int penX = firstDotX;
FT_BitmapGlyphRec *pBmpGlyph = (FT_BitmapGlyphRec*)dotGlyph.m_glyph;
for( n = 0; n < 3; n++ )
{
// Draw the glyph on the bitmap
pBmp->draw( pBmpGlyph->bitmap, penX, yMax - pBmpGlyph->top,
color );
penX += dotGlyph.m_advance;
}
}
delete [] glyphs;
delete [] pos;
return pBmp;
}
FT2Font::Glyph_t &FT2Font::getGlyph( uint32_t code ) const
{
// Try to find the glyph in the cache
GlyphMap_t::iterator iter = m_glyphCache.find( code );
if( iter != m_glyphCache.end() )
{
return (*iter).second;
}
else
{
// Add a new glyph in the cache
Glyph_t &glyph = m_glyphCache[code];
// Load and render the glyph
glyph.m_index = FT_Get_Char_Index( m_face, code );
FT_Load_Glyph( m_face, glyph.m_index, FT_LOAD_DEFAULT );
FT_Get_Glyph( m_face->glyph, &glyph.m_glyph );
FT_Glyph_Get_CBox( glyph.m_glyph, ft_glyph_bbox_pixels,
&glyph.m_size );
glyph.m_advance = m_face->glyph->advance.x >> 6;
FT_Glyph_To_Bitmap( &glyph.m_glyph, ft_render_mode_normal, NULL, 1 );
return glyph;
}
}
| 9034725985/vlc | modules/gui/skins2/src/ft2_font.cpp | C++ | gpl-2.0 | 9,147 |
<?php
/**
* @package Joomla.Site
* @subpackage com_finder
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
defined('_JEXEC') or die;
if ($this->params->get('show_advanced', 1) || $this->params->get('show_autosuggest', 1))
{
JHtml::_('jquery.framework');
$script = "
jQuery(function() {";
if ($this->params->get('show_advanced', 1))
{
/*
* This segment of code disables select boxes that have no value when the
* form is submitted so that the URL doesn't get blown up with null values.
*/
$script .= "
jQuery('#finder-search').on('submit', function(e){
e.stopPropagation();
// Disable select boxes with no value selected.
jQuery('#advancedSearch').find('select').each(function(index, el) {
var el = jQuery(el);
if(!el.val()){
el.attr('disabled', 'disabled');
}
});
});";
}
/*
* This segment of code sets up the autocompleter.
*/
if ($this->params->get('show_autosuggest', 1))
{
JHtml::_('script', 'jui/jquery.autocomplete.min.js', array('version' => 'auto', 'relative' => true));
$script .= "
var suggest = jQuery('#q').autocomplete({
serviceUrl: '" . JRoute::_('index.php?option=com_finder&task=suggestions.suggest&format=json&tmpl=component') . "',
paramName: 'q',
minChars: 1,
maxHeight: 400,
width: 300,
zIndex: 9999,
deferRequestBy: 500
});";
}
$script .= "
});";
JFactory::getDocument()->addScriptDeclaration($script);
}
?>
<form id="finder-search" action="<?php echo JRoute::_($this->query->toUri()); ?>" method="get" class="form-inline">
<?php echo $this->getFields(); ?>
<?php // DISABLED UNTIL WEIRD VALUES CAN BE TRACKED DOWN. ?>
<?php if (false && $this->state->get('list.ordering') !== 'relevance_dsc') : ?>
<input type="hidden" name="o" value="<?php echo $this->escape($this->state->get('list.ordering')); ?>" />
<?php endif; ?>
<fieldset class="word">
<label for="q">
<?php echo JText::_('COM_FINDER_SEARCH_TERMS'); ?>
</label>
<input type="text" name="q" id="q" size="30" value="<?php echo $this->escape($this->query->input); ?>" class="inputbox" />
<?php if ($this->escape($this->query->input) != '' || $this->params->get('allow_empty_query')) : ?>
<button name="Search" type="submit" class="btn btn-primary">
<span class="icon-search icon-white"></span>
<?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?>
</button>
<?php else : ?>
<button name="Search" type="submit" class="btn btn-primary disabled">
<span class="icon-search icon-white"></span>
<?php echo JText::_('JSEARCH_FILTER_SUBMIT'); ?>
</button>
<?php endif; ?>
<?php if ($this->params->get('show_advanced', 1)) : ?>
<a href="#advancedSearch" data-toggle="collapse" class="btn">
<span class="icon-list" aria-hidden="true"></span>
<?php echo JText::_('COM_FINDER_ADVANCED_SEARCH_TOGGLE'); ?>
</a>
<?php endif; ?>
</fieldset>
<?php if ($this->params->get('show_advanced', 1)) : ?>
<div id="advancedSearch" class="collapse<?php if ($this->params->get('expand_advanced', 0)) echo ' in'; ?>">
<hr />
<?php if ($this->params->get('show_advanced_tips', 1)) : ?>
<div id="search-query-explained">
<div class="advanced-search-tip">
<?php echo JText::_('COM_FINDER_ADVANCED_TIPS'); ?>
</div>
<hr />
</div>
<?php endif; ?>
<div id="finder-filter-window">
<?php echo JHtml::_('filter.select', $this->query, $this->params); ?>
</div>
</div>
<?php endif; ?>
</form>
| hans2103/joomla-cms | components/com_finder/views/search/tmpl/default_form.php | PHP | gpl-2.0 | 3,557 |
<?php
/**
* Joomla! Content Management System
*
* @copyright Copyright (C) 2005 - 2020 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE.txt
*/
namespace Joomla\CMS\Form\Field;
defined('JPATH_PLATFORM') or die;
use Joomla\CMS\Factory;
use Joomla\CMS\Form\Form;
use Joomla\CMS\Form\FormHelper;
FormHelper::loadFieldClass('predefinedlist');
/**
* Field to show a list of available date ranges to filter on last visit date.
*
* @since 3.6
*/
class LastvisitdaterangeField extends \JFormFieldPredefinedList
{
/**
* Method to instantiate the form field object.
*
* @param Form $form The form to attach to the form field object.
*
* @since 1.7.0
*/
public function __construct($form = null)
{
parent::__construct($form);
// Set the type
$this->type = 'LastvisitDateRange';
// Load the required language
$lang = Factory::getLanguage();
$lang->load('com_users', JPATH_ADMINISTRATOR);
// Set the pre-defined options
$this->predefinedOptions = array(
'today' => 'COM_USERS_OPTION_RANGE_TODAY',
'past_week' => 'COM_USERS_OPTION_RANGE_PAST_WEEK',
'past_1month' => 'COM_USERS_OPTION_RANGE_PAST_1MONTH',
'past_3month' => 'COM_USERS_OPTION_RANGE_PAST_3MONTH',
'past_6month' => 'COM_USERS_OPTION_RANGE_PAST_6MONTH',
'past_year' => 'COM_USERS_OPTION_RANGE_PAST_YEAR',
'post_year' => 'COM_USERS_OPTION_RANGE_POST_YEAR',
'never' => 'COM_USERS_OPTION_RANGE_NEVER',
);
}
}
| Harmageddon/joomla-cms | libraries/src/Form/Field/LastvisitdaterangeField.php | PHP | gpl-2.0 | 1,523 |
// SPDX-License-Identifier: GPL-2.0
/******************************************************************************
*
* Copyright(c) 2007 - 2012 Realtek Corporation. All rights reserved.
*
******************************************************************************/
#define _SDIO_HALINIT_C_
#include <drv_types.h>
#include <rtw_debug.h>
#include <rtl8723b_hal.h>
#include "hal_com_h2c.h"
/*
* Description:
*Call power on sequence to enable card
*
* Return:
*_SUCCESS enable success
*_FAIL enable fail
*/
static u8 CardEnable(struct adapter *padapter)
{
u8 bMacPwrCtrlOn;
u8 ret = _FAIL;
rtw_hal_get_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn);
if (!bMacPwrCtrlOn) {
/* RSV_CTRL 0x1C[7:0] = 0x00 */
/* unlock ISO/CLK/Power control register */
rtw_write8(padapter, REG_RSV_CTRL, 0x0);
ret = HalPwrSeqCmdParsing(padapter, PWR_CUT_ALL_MSK, PWR_FAB_ALL_MSK, PWR_INTF_SDIO_MSK, rtl8723B_card_enable_flow);
if (ret == _SUCCESS) {
u8 bMacPwrCtrlOn = true;
rtw_hal_set_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn);
}
} else
ret = _SUCCESS;
return ret;
}
static
u8 _InitPowerOn_8723BS(struct adapter *padapter)
{
u8 value8;
u16 value16;
u32 value32;
u8 ret;
/* u8 bMacPwrCtrlOn; */
/* all of these MUST be configured before power on */
/* only cmd52 can be used before power on(card enable) */
ret = CardEnable(padapter);
if (!ret)
return _FAIL;
/* Radio-Off Pin Trigger */
value8 = rtw_read8(padapter, REG_GPIO_INTM + 1);
value8 |= BIT(1); /* Enable falling edge triggering interrupt */
rtw_write8(padapter, REG_GPIO_INTM + 1, value8);
value8 = rtw_read8(padapter, REG_GPIO_IO_SEL_2 + 1);
value8 |= BIT(1);
rtw_write8(padapter, REG_GPIO_IO_SEL_2 + 1, value8);
/* Enable power down and GPIO interrupt */
value16 = rtw_read16(padapter, REG_APS_FSMCO);
value16 |= EnPDN; /* Enable HW power down and RF on */
rtw_write16(padapter, REG_APS_FSMCO, value16);
/* Enable CMD53 R/W Operation */
/* bMacPwrCtrlOn = true; */
/* rtw_hal_set_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn); */
rtw_write8(padapter, REG_CR, 0x00);
/* Enable MAC DMA/WMAC/SCHEDULE/SEC block */
value16 = rtw_read16(padapter, REG_CR);
value16 |= (
HCI_TXDMA_EN |
HCI_RXDMA_EN |
TXDMA_EN |
RXDMA_EN |
PROTOCOL_EN |
SCHEDULE_EN |
ENSEC |
CALTMR_EN
);
rtw_write16(padapter, REG_CR, value16);
hal_btcoex_PowerOnSetting(padapter);
/* external switch to S1 */
/* 0x38[11] = 0x1 */
/* 0x4c[23] = 0x1 */
/* 0x64[0] = 0 */
value16 = rtw_read16(padapter, REG_PWR_DATA);
/* Switch the control of EESK, EECS to RFC for DPDT or Antenna switch */
value16 |= BIT(11); /* BIT_EEPRPAD_RFE_CTRL_EN */
rtw_write16(padapter, REG_PWR_DATA, value16);
value32 = rtw_read32(padapter, REG_LEDCFG0);
value32 |= BIT(23); /* DPDT_SEL_EN, 1 for SW control */
rtw_write32(padapter, REG_LEDCFG0, value32);
value8 = rtw_read8(padapter, REG_PAD_CTRL1_8723B);
value8 &= ~BIT(0); /* BIT_SW_DPDT_SEL_DATA, DPDT_SEL default configuration */
rtw_write8(padapter, REG_PAD_CTRL1_8723B, value8);
return _SUCCESS;
}
/* Tx Page FIFO threshold */
static void _init_available_page_threshold(struct adapter *padapter, u8 numHQ, u8 numNQ, u8 numLQ, u8 numPubQ)
{
u16 HQ_threshold, NQ_threshold, LQ_threshold;
HQ_threshold = (numPubQ + numHQ + 1) >> 1;
HQ_threshold |= (HQ_threshold << 8);
NQ_threshold = (numPubQ + numNQ + 1) >> 1;
NQ_threshold |= (NQ_threshold << 8);
LQ_threshold = (numPubQ + numLQ + 1) >> 1;
LQ_threshold |= (LQ_threshold << 8);
rtw_write16(padapter, 0x218, HQ_threshold);
rtw_write16(padapter, 0x21A, NQ_threshold);
rtw_write16(padapter, 0x21C, LQ_threshold);
}
static void _InitQueueReservedPage(struct adapter *padapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(padapter);
struct registry_priv *pregistrypriv = &padapter->registrypriv;
u32 numHQ = 0;
u32 numLQ = 0;
u32 numNQ = 0;
u32 numPubQ;
u32 value32;
u8 value8;
bool bWiFiConfig = pregistrypriv->wifi_spec;
if (pHalData->OutEpQueueSel & TX_SELE_HQ)
numHQ = bWiFiConfig ? WMM_NORMAL_PAGE_NUM_HPQ_8723B : NORMAL_PAGE_NUM_HPQ_8723B;
if (pHalData->OutEpQueueSel & TX_SELE_LQ)
numLQ = bWiFiConfig ? WMM_NORMAL_PAGE_NUM_LPQ_8723B : NORMAL_PAGE_NUM_LPQ_8723B;
/* NOTE: This step shall be proceed before writing REG_RQPN. */
if (pHalData->OutEpQueueSel & TX_SELE_NQ)
numNQ = bWiFiConfig ? WMM_NORMAL_PAGE_NUM_NPQ_8723B : NORMAL_PAGE_NUM_NPQ_8723B;
numPubQ = TX_TOTAL_PAGE_NUMBER_8723B - numHQ - numLQ - numNQ;
value8 = (u8)_NPQ(numNQ);
rtw_write8(padapter, REG_RQPN_NPQ, value8);
/* TX DMA */
value32 = _HPQ(numHQ) | _LPQ(numLQ) | _PUBQ(numPubQ) | LD_RQPN;
rtw_write32(padapter, REG_RQPN, value32);
rtw_hal_set_sdio_tx_max_length(padapter, numHQ, numNQ, numLQ, numPubQ);
_init_available_page_threshold(padapter, numHQ, numNQ, numLQ, numPubQ);
}
static void _InitTxBufferBoundary(struct adapter *padapter)
{
struct registry_priv *pregistrypriv = &padapter->registrypriv;
/* u16 txdmactrl; */
u8 txpktbuf_bndy;
if (!pregistrypriv->wifi_spec) {
txpktbuf_bndy = TX_PAGE_BOUNDARY_8723B;
} else {
/* for WMM */
txpktbuf_bndy = WMM_NORMAL_TX_PAGE_BOUNDARY_8723B;
}
rtw_write8(padapter, REG_TXPKTBUF_BCNQ_BDNY_8723B, txpktbuf_bndy);
rtw_write8(padapter, REG_TXPKTBUF_MGQ_BDNY_8723B, txpktbuf_bndy);
rtw_write8(padapter, REG_TXPKTBUF_WMAC_LBK_BF_HD_8723B, txpktbuf_bndy);
rtw_write8(padapter, REG_TRXFF_BNDY, txpktbuf_bndy);
rtw_write8(padapter, REG_TDECTRL + 1, txpktbuf_bndy);
}
static void _InitNormalChipRegPriority(
struct adapter *Adapter,
u16 beQ,
u16 bkQ,
u16 viQ,
u16 voQ,
u16 mgtQ,
u16 hiQ
)
{
u16 value16 = (rtw_read16(Adapter, REG_TRXDMA_CTRL) & 0x7);
value16 |=
_TXDMA_BEQ_MAP(beQ) |
_TXDMA_BKQ_MAP(bkQ) |
_TXDMA_VIQ_MAP(viQ) |
_TXDMA_VOQ_MAP(voQ) |
_TXDMA_MGQ_MAP(mgtQ) |
_TXDMA_HIQ_MAP(hiQ);
rtw_write16(Adapter, REG_TRXDMA_CTRL, value16);
}
static void _InitNormalChipOneOutEpPriority(struct adapter *Adapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(Adapter);
u16 value = 0;
switch (pHalData->OutEpQueueSel) {
case TX_SELE_HQ:
value = QUEUE_HIGH;
break;
case TX_SELE_LQ:
value = QUEUE_LOW;
break;
case TX_SELE_NQ:
value = QUEUE_NORMAL;
break;
default:
/* RT_ASSERT(false, ("Shall not reach here!\n")); */
break;
}
_InitNormalChipRegPriority(
Adapter, value, value, value, value, value, value
);
}
static void _InitNormalChipTwoOutEpPriority(struct adapter *Adapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(Adapter);
struct registry_priv *pregistrypriv = &Adapter->registrypriv;
u16 beQ, bkQ, viQ, voQ, mgtQ, hiQ;
u16 valueHi = 0;
u16 valueLow = 0;
switch (pHalData->OutEpQueueSel) {
case (TX_SELE_HQ | TX_SELE_LQ):
valueHi = QUEUE_HIGH;
valueLow = QUEUE_LOW;
break;
case (TX_SELE_NQ | TX_SELE_LQ):
valueHi = QUEUE_NORMAL;
valueLow = QUEUE_LOW;
break;
case (TX_SELE_HQ | TX_SELE_NQ):
valueHi = QUEUE_HIGH;
valueLow = QUEUE_NORMAL;
break;
default:
/* RT_ASSERT(false, ("Shall not reach here!\n")); */
break;
}
if (!pregistrypriv->wifi_spec) {
beQ = valueLow;
bkQ = valueLow;
viQ = valueHi;
voQ = valueHi;
mgtQ = valueHi;
hiQ = valueHi;
} else {
/* for WMM , CONFIG_OUT_EP_WIFI_MODE */
beQ = valueLow;
bkQ = valueHi;
viQ = valueHi;
voQ = valueLow;
mgtQ = valueHi;
hiQ = valueHi;
}
_InitNormalChipRegPriority(Adapter, beQ, bkQ, viQ, voQ, mgtQ, hiQ);
}
static void _InitNormalChipThreeOutEpPriority(struct adapter *padapter)
{
struct registry_priv *pregistrypriv = &padapter->registrypriv;
u16 beQ, bkQ, viQ, voQ, mgtQ, hiQ;
if (!pregistrypriv->wifi_spec) {
/* typical setting */
beQ = QUEUE_LOW;
bkQ = QUEUE_LOW;
viQ = QUEUE_NORMAL;
voQ = QUEUE_HIGH;
mgtQ = QUEUE_HIGH;
hiQ = QUEUE_HIGH;
} else {
/* for WMM */
beQ = QUEUE_LOW;
bkQ = QUEUE_NORMAL;
viQ = QUEUE_NORMAL;
voQ = QUEUE_HIGH;
mgtQ = QUEUE_HIGH;
hiQ = QUEUE_HIGH;
}
_InitNormalChipRegPriority(padapter, beQ, bkQ, viQ, voQ, mgtQ, hiQ);
}
static void _InitQueuePriority(struct adapter *Adapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(Adapter);
switch (pHalData->OutEpNumber) {
case 1:
_InitNormalChipOneOutEpPriority(Adapter);
break;
case 2:
_InitNormalChipTwoOutEpPriority(Adapter);
break;
case 3:
_InitNormalChipThreeOutEpPriority(Adapter);
break;
default:
/* RT_ASSERT(false, ("Shall not reach here!\n")); */
break;
}
}
static void _InitPageBoundary(struct adapter *padapter)
{
/* RX Page Boundary */
u16 rxff_bndy = RX_DMA_BOUNDARY_8723B;
rtw_write16(padapter, (REG_TRXFF_BNDY + 2), rxff_bndy);
}
static void _InitTransferPageSize(struct adapter *padapter)
{
/* Tx page size is always 128. */
u8 value8;
value8 = _PSRX(PBP_128) | _PSTX(PBP_128);
rtw_write8(padapter, REG_PBP, value8);
}
static void _InitDriverInfoSize(struct adapter *padapter, u8 drvInfoSize)
{
rtw_write8(padapter, REG_RX_DRVINFO_SZ, drvInfoSize);
}
static void _InitNetworkType(struct adapter *padapter)
{
u32 value32;
value32 = rtw_read32(padapter, REG_CR);
/* TODO: use the other function to set network type */
/* value32 = (value32 & ~MASK_NETTYPE) | _NETTYPE(NT_LINK_AD_HOC); */
value32 = (value32 & ~MASK_NETTYPE) | _NETTYPE(NT_LINK_AP);
rtw_write32(padapter, REG_CR, value32);
}
static void _InitWMACSetting(struct adapter *padapter)
{
struct hal_com_data *pHalData;
u16 value16;
pHalData = GET_HAL_DATA(padapter);
pHalData->ReceiveConfig = 0;
pHalData->ReceiveConfig |= RCR_APM | RCR_AM | RCR_AB;
pHalData->ReceiveConfig |= RCR_CBSSID_DATA | RCR_CBSSID_BCN | RCR_AMF;
pHalData->ReceiveConfig |= RCR_HTC_LOC_CTRL;
pHalData->ReceiveConfig |= RCR_APP_PHYST_RXFF | RCR_APP_ICV | RCR_APP_MIC;
rtw_write32(padapter, REG_RCR, pHalData->ReceiveConfig);
/* Accept all multicast address */
rtw_write32(padapter, REG_MAR, 0xFFFFFFFF);
rtw_write32(padapter, REG_MAR + 4, 0xFFFFFFFF);
/* Accept all data frames */
value16 = 0xFFFF;
rtw_write16(padapter, REG_RXFLTMAP2, value16);
/* 2010.09.08 hpfan */
/* Since ADF is removed from RCR, ps-poll will not be indicate to driver, */
/* RxFilterMap should mask ps-poll to gurantee AP mode can rx ps-poll. */
value16 = 0x400;
rtw_write16(padapter, REG_RXFLTMAP1, value16);
/* Accept all management frames */
value16 = 0xFFFF;
rtw_write16(padapter, REG_RXFLTMAP0, value16);
}
static void _InitAdaptiveCtrl(struct adapter *padapter)
{
u16 value16;
u32 value32;
/* Response Rate Set */
value32 = rtw_read32(padapter, REG_RRSR);
value32 &= ~RATE_BITMAP_ALL;
value32 |= RATE_RRSR_CCK_ONLY_1M;
rtw_write32(padapter, REG_RRSR, value32);
/* CF-END Threshold */
/* m_spIoBase->rtw_write8(REG_CFEND_TH, 0x1); */
/* SIFS (used in NAV) */
value16 = _SPEC_SIFS_CCK(0x10) | _SPEC_SIFS_OFDM(0x10);
rtw_write16(padapter, REG_SPEC_SIFS, value16);
/* Retry Limit */
value16 = _LRL(0x30) | _SRL(0x30);
rtw_write16(padapter, REG_RL, value16);
}
static void _InitEDCA(struct adapter *padapter)
{
/* Set Spec SIFS (used in NAV) */
rtw_write16(padapter, REG_SPEC_SIFS, 0x100a);
rtw_write16(padapter, REG_MAC_SPEC_SIFS, 0x100a);
/* Set SIFS for CCK */
rtw_write16(padapter, REG_SIFS_CTX, 0x100a);
/* Set SIFS for OFDM */
rtw_write16(padapter, REG_SIFS_TRX, 0x100a);
/* TXOP */
rtw_write32(padapter, REG_EDCA_BE_PARAM, 0x005EA42B);
rtw_write32(padapter, REG_EDCA_BK_PARAM, 0x0000A44F);
rtw_write32(padapter, REG_EDCA_VI_PARAM, 0x005EA324);
rtw_write32(padapter, REG_EDCA_VO_PARAM, 0x002FA226);
}
static void _InitRetryFunction(struct adapter *padapter)
{
u8 value8;
value8 = rtw_read8(padapter, REG_FWHW_TXQ_CTRL);
value8 |= EN_AMPDU_RTY_NEW;
rtw_write8(padapter, REG_FWHW_TXQ_CTRL, value8);
/* Set ACK timeout */
rtw_write8(padapter, REG_ACKTO, 0x40);
}
static void HalRxAggr8723BSdio(struct adapter *padapter)
{
u8 valueDMATimeout;
u8 valueDMAPageCount;
valueDMATimeout = 0x06;
valueDMAPageCount = 0x06;
rtw_write8(padapter, REG_RXDMA_AGG_PG_TH + 1, valueDMATimeout);
rtw_write8(padapter, REG_RXDMA_AGG_PG_TH, valueDMAPageCount);
}
static void sdio_AggSettingRxUpdate(struct adapter *padapter)
{
u8 valueDMA;
u8 valueRxAggCtrl = 0;
u8 aggBurstNum = 3; /* 0:1, 1:2, 2:3, 3:4 */
u8 aggBurstSize = 0; /* 0:1K, 1:512Byte, 2:256Byte... */
valueDMA = rtw_read8(padapter, REG_TRXDMA_CTRL);
valueDMA |= RXDMA_AGG_EN;
rtw_write8(padapter, REG_TRXDMA_CTRL, valueDMA);
valueRxAggCtrl |= RXDMA_AGG_MODE_EN;
valueRxAggCtrl |= ((aggBurstNum << 2) & 0x0C);
valueRxAggCtrl |= ((aggBurstSize << 4) & 0x30);
rtw_write8(padapter, REG_RXDMA_MODE_CTRL_8723B, valueRxAggCtrl);/* RxAggLowThresh = 4*1K */
}
static void _initSdioAggregationSetting(struct adapter *padapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(padapter);
/* Tx aggregation setting */
/* sdio_AggSettingTxUpdate(padapter); */
/* Rx aggregation setting */
HalRxAggr8723BSdio(padapter);
sdio_AggSettingRxUpdate(padapter);
/* 201/12/10 MH Add for USB agg mode dynamic switch. */
pHalData->UsbRxHighSpeedMode = false;
}
static void _InitOperationMode(struct adapter *padapter)
{
struct mlme_ext_priv *pmlmeext;
u8 regBwOpMode = 0;
pmlmeext = &padapter->mlmeextpriv;
/* 1 This part need to modified according to the rate set we filtered!! */
/* */
/* Set RRSR, RATR, and REG_BWOPMODE registers */
/* */
switch (pmlmeext->cur_wireless_mode) {
case WIRELESS_MODE_B:
regBwOpMode = BW_OPMODE_20MHZ;
break;
case WIRELESS_MODE_A:
/* RT_ASSERT(false, ("Error wireless a mode\n")); */
break;
case WIRELESS_MODE_G:
regBwOpMode = BW_OPMODE_20MHZ;
break;
case WIRELESS_MODE_AUTO:
regBwOpMode = BW_OPMODE_20MHZ;
break;
case WIRELESS_MODE_N_24G:
/* It support CCK rate by default. */
/* CCK rate will be filtered out only when associated AP does not support it. */
regBwOpMode = BW_OPMODE_20MHZ;
break;
case WIRELESS_MODE_N_5G:
/* RT_ASSERT(false, ("Error wireless mode")); */
regBwOpMode = BW_OPMODE_5G;
break;
default: /* for MacOSX compiler warning. */
break;
}
rtw_write8(padapter, REG_BWOPMODE, regBwOpMode);
}
static void _InitInterrupt(struct adapter *padapter)
{
/* HISR - turn all off */
rtw_write32(padapter, REG_HISR, 0);
/* HIMR - turn all off */
rtw_write32(padapter, REG_HIMR, 0);
/* */
/* Initialize and enable SDIO Host Interrupt. */
/* */
InitInterrupt8723BSdio(padapter);
/* */
/* Initialize system Host Interrupt. */
/* */
InitSysInterrupt8723BSdio(padapter);
}
static void _InitRFType(struct adapter *padapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(padapter);
#if DISABLE_BB_RF
pHalData->rf_chip = RF_PSEUDO_11N;
return;
#endif
pHalData->rf_chip = RF_6052;
pHalData->rf_type = RF_1T1R;
}
static void _RfPowerSave(struct adapter *padapter)
{
/* YJ, TODO */
}
/* */
/* 2010/08/09 MH Add for power down check. */
/* */
static bool HalDetectPwrDownMode(struct adapter *Adapter)
{
u8 tmpvalue;
struct hal_com_data *pHalData = GET_HAL_DATA(Adapter);
struct pwrctrl_priv *pwrctrlpriv = adapter_to_pwrctl(Adapter);
EFUSE_ShadowRead(Adapter, 1, 0x7B/*EEPROM_RF_OPT3_92C*/, (u32 *)&tmpvalue);
/* 2010/08/25 MH INF priority > PDN Efuse value. */
if (tmpvalue & BIT4 && pwrctrlpriv->reg_pdnmode)
pHalData->pwrdown = true;
else
pHalData->pwrdown = false;
return pHalData->pwrdown;
} /* HalDetectPwrDownMode */
static u32 rtl8723bs_hal_init(struct adapter *padapter)
{
s32 ret;
struct hal_com_data *pHalData;
struct pwrctrl_priv *pwrctrlpriv;
u32 NavUpper = WiFiNavUpperUs;
u8 u1bTmp;
pHalData = GET_HAL_DATA(padapter);
pwrctrlpriv = adapter_to_pwrctl(padapter);
if (
adapter_to_pwrctl(padapter)->bips_processing == true &&
adapter_to_pwrctl(padapter)->pre_ips_type == 0
) {
unsigned long start_time;
u8 cpwm_orig, cpwm_now;
u8 val8, bMacPwrCtrlOn = true;
/* for polling cpwm */
cpwm_orig = 0;
rtw_hal_get_hwreg(padapter, HW_VAR_CPWM, &cpwm_orig);
/* ser rpwm */
val8 = rtw_read8(padapter, SDIO_LOCAL_BASE | SDIO_REG_HRPWM1);
val8 &= 0x80;
val8 += 0x80;
val8 |= BIT(6);
rtw_write8(padapter, SDIO_LOCAL_BASE | SDIO_REG_HRPWM1, val8);
adapter_to_pwrctl(padapter)->tog = (val8 + 0x80) & 0x80;
/* do polling cpwm */
start_time = jiffies;
do {
mdelay(1);
rtw_hal_get_hwreg(padapter, HW_VAR_CPWM, &cpwm_now);
if ((cpwm_orig ^ cpwm_now) & 0x80)
break;
if (jiffies_to_msecs(jiffies - start_time) > 100)
break;
} while (1);
rtl8723b_set_FwPwrModeInIPS_cmd(padapter, 0);
rtw_hal_set_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn);
hal_btcoex_InitHwConfig(padapter, false);
return _SUCCESS;
}
/* Disable Interrupt first. */
/* rtw_hal_disable_interrupt(padapter); */
ret = _InitPowerOn_8723BS(padapter);
if (ret == _FAIL)
return _FAIL;
rtw_write8(padapter, REG_EARLY_MODE_CONTROL, 0);
ret = rtl8723b_FirmwareDownload(padapter, false);
if (ret != _SUCCESS) {
padapter->bFWReady = false;
pHalData->fw_ractrl = false;
return ret;
} else {
padapter->bFWReady = true;
pHalData->fw_ractrl = true;
}
rtl8723b_InitializeFirmwareVars(padapter);
/* SIC_Init(padapter); */
if (pwrctrlpriv->reg_rfoff)
pwrctrlpriv->rf_pwrstate = rf_off;
/* 2010/08/09 MH We need to check if we need to turnon or off RF after detecting */
/* HW GPIO pin. Before PHY_RFConfig8192C. */
HalDetectPwrDownMode(padapter);
/* Set RF type for BB/RF configuration */
_InitRFType(padapter);
/* Save target channel */
/* <Roger_Notes> Current Channel will be updated again later. */
pHalData->CurrentChannel = 6;
#if (HAL_MAC_ENABLE == 1)
ret = PHY_MACConfig8723B(padapter);
if (ret != _SUCCESS)
return ret;
#endif
/* */
/* d. Initialize BB related configurations. */
/* */
#if (HAL_BB_ENABLE == 1)
ret = PHY_BBConfig8723B(padapter);
if (ret != _SUCCESS)
return ret;
#endif
/* If RF is on, we need to init RF. Otherwise, skip the procedure. */
/* We need to follow SU method to change the RF cfg.txt. Default disable RF TX/RX mode. */
/* if (pHalData->eRFPowerState == eRfOn) */
{
#if (HAL_RF_ENABLE == 1)
ret = PHY_RFConfig8723B(padapter);
if (ret != _SUCCESS)
return ret;
#endif
}
/* */
/* Joseph Note: Keep RfRegChnlVal for later use. */
/* */
pHalData->RfRegChnlVal[0] =
PHY_QueryRFReg(padapter, (enum rf_path)0, RF_CHNLBW, bRFRegOffsetMask);
pHalData->RfRegChnlVal[1] =
PHY_QueryRFReg(padapter, (enum rf_path)1, RF_CHNLBW, bRFRegOffsetMask);
/* if (!pHalData->bMACFuncEnable) { */
_InitQueueReservedPage(padapter);
_InitTxBufferBoundary(padapter);
/* init LLT after tx buffer boundary is defined */
ret = rtl8723b_InitLLTTable(padapter);
if (ret != _SUCCESS)
return _FAIL;
/* */
_InitQueuePriority(padapter);
_InitPageBoundary(padapter);
_InitTransferPageSize(padapter);
/* Get Rx PHY status in order to report RSSI and others. */
_InitDriverInfoSize(padapter, DRVINFO_SZ);
hal_init_macaddr(padapter);
_InitNetworkType(padapter);
_InitWMACSetting(padapter);
_InitAdaptiveCtrl(padapter);
_InitEDCA(padapter);
_InitRetryFunction(padapter);
_initSdioAggregationSetting(padapter);
_InitOperationMode(padapter);
rtl8723b_InitBeaconParameters(padapter);
_InitInterrupt(padapter);
_InitBurstPktLen_8723BS(padapter);
/* YJ, TODO */
rtw_write8(padapter, REG_SECONDARY_CCA_CTRL_8723B, 0x3); /* CCA */
rtw_write8(padapter, 0x976, 0); /* hpfan_todo: 2nd CCA related */
rtw_write16(padapter, REG_PKT_VO_VI_LIFE_TIME, 0x0400); /* unit: 256us. 256ms */
rtw_write16(padapter, REG_PKT_BE_BK_LIFE_TIME, 0x0400); /* unit: 256us. 256ms */
invalidate_cam_all(padapter);
rtw_hal_set_chnl_bw(padapter, padapter->registrypriv.channel,
CHANNEL_WIDTH_20, HAL_PRIME_CHNL_OFFSET_DONT_CARE, HAL_PRIME_CHNL_OFFSET_DONT_CARE);
/* Record original value for template. This is arough data, we can only use the data */
/* for power adjust. The value can not be adjustde according to different power!!! */
/* pHalData->OriginalCckTxPwrIdx = pHalData->CurrentCckTxPwrIdx; */
/* pHalData->OriginalOfdm24GTxPwrIdx = pHalData->CurrentOfdm24GTxPwrIdx; */
rtl8723b_InitAntenna_Selection(padapter);
/* */
/* Disable BAR, suggested by Scott */
/* 2010.04.09 add by hpfan */
/* */
rtw_write32(padapter, REG_BAR_MODE_CTRL, 0x0201ffff);
/* HW SEQ CTRL */
/* set 0x0 to 0xFF by tynli. Default enable HW SEQ NUM. */
rtw_write8(padapter, REG_HWSEQ_CTRL, 0xFF);
/* */
/* Configure SDIO TxRx Control to enable Rx DMA timer masking. */
/* 2010.02.24. */
/* */
rtw_write32(padapter, SDIO_LOCAL_BASE | SDIO_REG_TX_CTRL, 0);
_RfPowerSave(padapter);
rtl8723b_InitHalDm(padapter);
/* DbgPrint("pHalData->DefaultTxPwrDbm = %d\n", pHalData->DefaultTxPwrDbm); */
/* */
/* Update current Tx FIFO page status. */
/* */
HalQueryTxBufferStatus8723BSdio(padapter);
HalQueryTxOQTBufferStatus8723BSdio(padapter);
pHalData->SdioTxOQTMaxFreeSpace = pHalData->SdioTxOQTFreeSpace;
/* Enable MACTXEN/MACRXEN block */
u1bTmp = rtw_read8(padapter, REG_CR);
u1bTmp |= (MACTXEN | MACRXEN);
rtw_write8(padapter, REG_CR, u1bTmp);
rtw_hal_set_hwreg(padapter, HW_VAR_NAV_UPPER, (u8 *)&NavUpper);
/* ack for xmit mgmt frames. */
rtw_write32(padapter, REG_FWHW_TXQ_CTRL, rtw_read32(padapter, REG_FWHW_TXQ_CTRL) | BIT(12));
/* pHalData->PreRpwmVal = SdioLocalCmd52Read1Byte(padapter, SDIO_REG_HRPWM1) & 0x80; */
{
pwrctrlpriv->rf_pwrstate = rf_on;
if (pwrctrlpriv->rf_pwrstate == rf_on) {
struct pwrctrl_priv *pwrpriv;
unsigned long start_time;
u8 restore_iqk_rst;
u8 b2Ant;
u8 h2cCmdBuf;
pwrpriv = adapter_to_pwrctl(padapter);
PHY_LCCalibrate_8723B(&pHalData->odmpriv);
/* Inform WiFi FW that it is the beginning of IQK */
h2cCmdBuf = 1;
FillH2CCmd8723B(padapter, H2C_8723B_BT_WLAN_CALIBRATION, 1, &h2cCmdBuf);
start_time = jiffies;
do {
if (rtw_read8(padapter, 0x1e7) & 0x01)
break;
msleep(50);
} while (jiffies_to_msecs(jiffies - start_time) <= 400);
hal_btcoex_IQKNotify(padapter, true);
restore_iqk_rst = pwrpriv->bips_processing;
b2Ant = pHalData->EEPROMBluetoothAntNum == Ant_x2;
PHY_IQCalibrate_8723B(padapter, false, restore_iqk_rst, b2Ant, pHalData->ant_path);
pHalData->odmpriv.RFCalibrateInfo.bIQKInitialized = true;
hal_btcoex_IQKNotify(padapter, false);
/* Inform WiFi FW that it is the finish of IQK */
h2cCmdBuf = 0;
FillH2CCmd8723B(padapter, H2C_8723B_BT_WLAN_CALIBRATION, 1, &h2cCmdBuf);
ODM_TXPowerTrackingCheck(&pHalData->odmpriv);
}
}
/* Init BT hw config. */
hal_btcoex_InitHwConfig(padapter, false);
return _SUCCESS;
}
/* */
/* Description: */
/* RTL8723e card disable power sequence v003 which suggested by Scott. */
/* */
/* First created by tynli. 2011.01.28. */
/* */
static void CardDisableRTL8723BSdio(struct adapter *padapter)
{
u8 u1bTmp;
u8 bMacPwrCtrlOn;
u8 ret = _FAIL;
/* Run LPS WL RFOFF flow */
ret = HalPwrSeqCmdParsing(padapter, PWR_CUT_ALL_MSK, PWR_FAB_ALL_MSK, PWR_INTF_SDIO_MSK, rtl8723B_enter_lps_flow);
/* ==== Reset digital sequence ====== */
u1bTmp = rtw_read8(padapter, REG_MCUFWDL);
if ((u1bTmp & RAM_DL_SEL) && padapter->bFWReady) /* 8051 RAM code */
rtl8723b_FirmwareSelfReset(padapter);
/* Reset MCU 0x2[10]= 0. Suggested by Filen. 2011.01.26. by tynli. */
u1bTmp = rtw_read8(padapter, REG_SYS_FUNC_EN + 1);
u1bTmp &= ~BIT(2); /* 0x2[10], FEN_CPUEN */
rtw_write8(padapter, REG_SYS_FUNC_EN + 1, u1bTmp);
/* MCUFWDL 0x80[1:0]= 0 */
/* reset MCU ready status */
rtw_write8(padapter, REG_MCUFWDL, 0);
/* Reset MCU IO Wrapper, added by Roger, 2011.08.30 */
u1bTmp = rtw_read8(padapter, REG_RSV_CTRL + 1);
u1bTmp &= ~BIT(0);
rtw_write8(padapter, REG_RSV_CTRL + 1, u1bTmp);
u1bTmp = rtw_read8(padapter, REG_RSV_CTRL + 1);
u1bTmp |= BIT(0);
rtw_write8(padapter, REG_RSV_CTRL+1, u1bTmp);
/* ==== Reset digital sequence end ====== */
bMacPwrCtrlOn = false; /* Disable CMD53 R/W */
ret = false;
rtw_hal_set_hwreg(padapter, HW_VAR_APFM_ON_MAC, &bMacPwrCtrlOn);
ret = HalPwrSeqCmdParsing(padapter, PWR_CUT_ALL_MSK, PWR_FAB_ALL_MSK, PWR_INTF_SDIO_MSK, rtl8723B_card_disable_flow);
}
static u32 rtl8723bs_hal_deinit(struct adapter *padapter)
{
struct dvobj_priv *psdpriv = padapter->dvobj;
struct debug_priv *pdbgpriv = &psdpriv->drv_dbg;
if (padapter->hw_init_completed) {
if (adapter_to_pwrctl(padapter)->bips_processing) {
if (padapter->netif_up) {
int cnt = 0;
u8 val8 = 0;
rtl8723b_set_FwPwrModeInIPS_cmd(padapter, 0x3);
/* poll 0x1cc to make sure H2C command already finished by FW; MAC_0x1cc = 0 means H2C done by FW. */
do {
val8 = rtw_read8(padapter, REG_HMETFR);
cnt++;
mdelay(10);
} while (cnt < 100 && (val8 != 0));
/* H2C done, enter 32k */
if (val8 == 0) {
/* ser rpwm to enter 32k */
val8 = rtw_read8(padapter, SDIO_LOCAL_BASE | SDIO_REG_HRPWM1);
val8 += 0x80;
val8 |= BIT(0);
rtw_write8(padapter, SDIO_LOCAL_BASE | SDIO_REG_HRPWM1, val8);
adapter_to_pwrctl(padapter)->tog = (val8 + 0x80) & 0x80;
cnt = val8 = 0;
do {
val8 = rtw_read8(padapter, REG_CR);
cnt++;
mdelay(10);
} while (cnt < 100 && (val8 != 0xEA));
}
adapter_to_pwrctl(padapter)->pre_ips_type = 0;
} else {
pdbgpriv->dbg_carddisable_cnt++;
CardDisableRTL8723BSdio(padapter);
adapter_to_pwrctl(padapter)->pre_ips_type = 1;
}
} else {
pdbgpriv->dbg_carddisable_cnt++;
CardDisableRTL8723BSdio(padapter);
}
} else
pdbgpriv->dbg_deinit_fail_cnt++;
return _SUCCESS;
}
static u32 rtl8723bs_inirp_init(struct adapter *padapter)
{
return _SUCCESS;
}
static u32 rtl8723bs_inirp_deinit(struct adapter *padapter)
{
return _SUCCESS;
}
static void rtl8723bs_init_default_value(struct adapter *padapter)
{
struct hal_com_data *pHalData;
pHalData = GET_HAL_DATA(padapter);
rtl8723b_init_default_value(padapter);
/* interface related variable */
pHalData->SdioRxFIFOCnt = 0;
}
static void rtl8723bs_interface_configure(struct adapter *padapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(padapter);
struct dvobj_priv *pdvobjpriv = adapter_to_dvobj(padapter);
struct registry_priv *pregistrypriv = &padapter->registrypriv;
bool bWiFiConfig = pregistrypriv->wifi_spec;
pdvobjpriv->RtOutPipe[0] = WLAN_TX_HIQ_DEVICE_ID;
pdvobjpriv->RtOutPipe[1] = WLAN_TX_MIQ_DEVICE_ID;
pdvobjpriv->RtOutPipe[2] = WLAN_TX_LOQ_DEVICE_ID;
if (bWiFiConfig)
pHalData->OutEpNumber = 2;
else
pHalData->OutEpNumber = SDIO_MAX_TX_QUEUE;
switch (pHalData->OutEpNumber) {
case 3:
pHalData->OutEpQueueSel = TX_SELE_HQ | TX_SELE_LQ | TX_SELE_NQ;
break;
case 2:
pHalData->OutEpQueueSel = TX_SELE_HQ | TX_SELE_NQ;
break;
case 1:
pHalData->OutEpQueueSel = TX_SELE_HQ;
break;
default:
break;
}
Hal_MappingOutPipe(padapter, pHalData->OutEpNumber);
}
/* */
/* Description: */
/* We should set Efuse cell selection to WiFi cell in default. */
/* */
/* Assumption: */
/* PASSIVE_LEVEL */
/* */
/* Added by Roger, 2010.11.23. */
/* */
static void _EfuseCellSel(struct adapter *padapter)
{
u32 value32;
value32 = rtw_read32(padapter, EFUSE_TEST);
value32 = (value32 & ~EFUSE_SEL_MASK) | EFUSE_SEL(EFUSE_WIFI_SEL_0);
rtw_write32(padapter, EFUSE_TEST, value32);
}
static void _ReadRFType(struct adapter *Adapter)
{
struct hal_com_data *pHalData = GET_HAL_DATA(Adapter);
#if DISABLE_BB_RF
pHalData->rf_chip = RF_PSEUDO_11N;
#else
pHalData->rf_chip = RF_6052;
#endif
}
static void Hal_EfuseParseMACAddr_8723BS(
struct adapter *padapter, u8 *hwinfo, bool AutoLoadFail
)
{
u16 i;
u8 sMacAddr[6] = {0x00, 0xE0, 0x4C, 0xb7, 0x23, 0x00};
struct eeprom_priv *pEEPROM = GET_EEPROM_EFUSE_PRIV(padapter);
if (AutoLoadFail) {
/* sMacAddr[5] = (u8)GetRandomNumber(1, 254); */
for (i = 0; i < 6; i++)
pEEPROM->mac_addr[i] = sMacAddr[i];
} else {
/* Read Permanent MAC address */
memcpy(pEEPROM->mac_addr, &hwinfo[EEPROM_MAC_ADDR_8723BS], ETH_ALEN);
}
}
static void Hal_EfuseParseBoardType_8723BS(
struct adapter *padapter, u8 *hwinfo, bool AutoLoadFail
)
{
struct hal_com_data *pHalData = GET_HAL_DATA(padapter);
if (!AutoLoadFail) {
pHalData->BoardType = (hwinfo[EEPROM_RF_BOARD_OPTION_8723B] & 0xE0) >> 5;
if (pHalData->BoardType == 0xFF)
pHalData->BoardType = (EEPROM_DEFAULT_BOARD_OPTION & 0xE0) >> 5;
} else
pHalData->BoardType = 0;
}
static void _ReadEfuseInfo8723BS(struct adapter *padapter)
{
struct eeprom_priv *pEEPROM = GET_EEPROM_EFUSE_PRIV(padapter);
u8 *hwinfo = NULL;
/* */
/* This part read and parse the eeprom/efuse content */
/* */
hwinfo = pEEPROM->efuse_eeprom_data;
Hal_InitPGData(padapter, hwinfo);
Hal_EfuseParseIDCode(padapter, hwinfo);
Hal_EfuseParseEEPROMVer_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseMACAddr_8723BS(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseTxPowerInfo_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseBoardType_8723BS(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
/* */
/* Read Bluetooth co-exist and initialize */
/* */
Hal_EfuseParsePackageType_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseBTCoexistInfo_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseChnlPlan_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseXtal_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseThermalMeter_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseAntennaDiversity_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseCustomerID_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_EfuseParseVoltage_8723B(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
Hal_ReadRFGainOffset(padapter, hwinfo, pEEPROM->bautoload_fail_flag);
}
static void _ReadPROMContent(struct adapter *padapter)
{
struct eeprom_priv *pEEPROM = GET_EEPROM_EFUSE_PRIV(padapter);
u8 eeValue;
eeValue = rtw_read8(padapter, REG_9346CR);
/* To check system boot selection. */
pEEPROM->EepromOrEfuse = (eeValue & BOOT_FROM_EEPROM) ? true : false;
pEEPROM->bautoload_fail_flag = (eeValue & EEPROM_EN) ? false : true;
/* pHalData->EEType = IS_BOOT_FROM_EEPROM(Adapter) ? EEPROM_93C46 : EEPROM_BOOT_EFUSE; */
_ReadEfuseInfo8723BS(padapter);
}
static void _InitOtherVariable(struct adapter *Adapter)
{
}
/* */
/* Description: */
/* Read HW adapter information by E-Fuse or EEPROM according CR9346 reported. */
/* */
/* Assumption: */
/* PASSIVE_LEVEL (SDIO interface) */
/* */
/* */
static s32 _ReadAdapterInfo8723BS(struct adapter *padapter)
{
u8 val8;
/* before access eFuse, make sure card enable has been called */
if (!padapter->hw_init_completed)
_InitPowerOn_8723BS(padapter);
val8 = rtw_read8(padapter, 0x4e);
val8 |= BIT(6);
rtw_write8(padapter, 0x4e, val8);
_EfuseCellSel(padapter);
_ReadRFType(padapter);
_ReadPROMContent(padapter);
_InitOtherVariable(padapter);
if (!padapter->hw_init_completed) {
rtw_write8(padapter, 0x67, 0x00); /* for BT, Switch Ant control to BT */
CardDisableRTL8723BSdio(padapter);/* for the power consumption issue, wifi ko module is loaded during booting, but wifi GUI is off */
}
return _SUCCESS;
}
static void ReadAdapterInfo8723BS(struct adapter *padapter)
{
/* Read EEPROM size before call any EEPROM function */
padapter->EepromAddressSize = GetEEPROMSize8723B(padapter);
_ReadAdapterInfo8723BS(padapter);
}
/*
* If variable not handled here,
* some variables will be processed in SetHwReg8723B()
*/
static void SetHwReg8723BS(struct adapter *padapter, u8 variable, u8 *val)
{
u8 val8;
switch (variable) {
case HW_VAR_SET_RPWM:
/* rpwm value only use BIT0(clock bit) , BIT6(Ack bit), and BIT7(Toggle bit) */
/* BIT0 value - 1: 32k, 0:40MHz. */
/* BIT6 value - 1: report cpwm value after success set, 0:do not report. */
/* BIT7 value - Toggle bit change. */
{
val8 = *val;
val8 &= 0xC1;
rtw_write8(padapter, SDIO_LOCAL_BASE | SDIO_REG_HRPWM1, val8);
}
break;
case HW_VAR_SET_REQ_FW_PS:
{
u8 req_fw_ps = 0;
req_fw_ps = rtw_read8(padapter, 0x8f);
req_fw_ps |= 0x10;
rtw_write8(padapter, 0x8f, req_fw_ps);
}
break;
case HW_VAR_RXDMA_AGG_PG_TH:
val8 = *val;
break;
case HW_VAR_DM_IN_LPS:
rtl8723b_hal_dm_in_lps(padapter);
break;
default:
SetHwReg8723B(padapter, variable, val);
break;
}
}
/*
* If variable not handled here,
* some variables will be processed in GetHwReg8723B()
*/
static void GetHwReg8723BS(struct adapter *padapter, u8 variable, u8 *val)
{
switch (variable) {
case HW_VAR_CPWM:
*val = rtw_read8(padapter, SDIO_LOCAL_BASE | SDIO_REG_HCPWM1_8723B);
break;
case HW_VAR_FW_PS_STATE:
{
/* 3. read dword 0x88 driver read fw ps state */
*((u16 *)val) = rtw_read16(padapter, 0x88);
}
break;
default:
GetHwReg8723B(padapter, variable, val);
break;
}
}
static void SetHwRegWithBuf8723B(struct adapter *padapter, u8 variable, u8 *pbuf, int len)
{
switch (variable) {
case HW_VAR_C2H_HANDLE:
C2HPacketHandler_8723B(padapter, pbuf, len);
break;
default:
break;
}
}
/* */
/* Description: */
/* Query setting of specified variable. */
/* */
static u8 GetHalDefVar8723BSDIO(
struct adapter *Adapter, enum hal_def_variable eVariable, void *pValue
)
{
u8 bResult = _SUCCESS;
switch (eVariable) {
case HAL_DEF_IS_SUPPORT_ANT_DIV:
break;
case HAL_DEF_CURRENT_ANTENNA:
break;
case HW_VAR_MAX_RX_AMPDU_FACTOR:
/* [email protected] suggests 16K can get stable performance */
/* coding by Lucas@20130730 */
*(u32 *)pValue = IEEE80211_HT_MAX_AMPDU_16K;
break;
default:
bResult = GetHalDefVar8723B(Adapter, eVariable, pValue);
break;
}
return bResult;
}
/* */
/* Description: */
/* Change default setting of specified variable. */
/* */
static u8 SetHalDefVar8723BSDIO(struct adapter *Adapter,
enum hal_def_variable eVariable, void *pValue)
{
return SetHalDefVar8723B(Adapter, eVariable, pValue);
}
void rtl8723bs_set_hal_ops(struct adapter *padapter)
{
struct hal_ops *pHalFunc = &padapter->HalFunc;
rtl8723b_set_hal_ops(pHalFunc);
pHalFunc->hal_init = &rtl8723bs_hal_init;
pHalFunc->hal_deinit = &rtl8723bs_hal_deinit;
pHalFunc->inirp_init = &rtl8723bs_inirp_init;
pHalFunc->inirp_deinit = &rtl8723bs_inirp_deinit;
pHalFunc->init_xmit_priv = &rtl8723bs_init_xmit_priv;
pHalFunc->free_xmit_priv = &rtl8723bs_free_xmit_priv;
pHalFunc->init_recv_priv = &rtl8723bs_init_recv_priv;
pHalFunc->free_recv_priv = &rtl8723bs_free_recv_priv;
pHalFunc->init_default_value = &rtl8723bs_init_default_value;
pHalFunc->intf_chip_configure = &rtl8723bs_interface_configure;
pHalFunc->read_adapter_info = &ReadAdapterInfo8723BS;
pHalFunc->enable_interrupt = &EnableInterrupt8723BSdio;
pHalFunc->disable_interrupt = &DisableInterrupt8723BSdio;
pHalFunc->check_ips_status = &CheckIPSStatus;
pHalFunc->SetHwRegHandler = &SetHwReg8723BS;
pHalFunc->GetHwRegHandler = &GetHwReg8723BS;
pHalFunc->SetHwRegHandlerWithBuf = &SetHwRegWithBuf8723B;
pHalFunc->GetHalDefVarHandler = &GetHalDefVar8723BSDIO;
pHalFunc->SetHalDefVarHandler = &SetHalDefVar8723BSDIO;
pHalFunc->hal_xmit = &rtl8723bs_hal_xmit;
pHalFunc->mgnt_xmit = &rtl8723bs_mgnt_xmit;
pHalFunc->hal_xmitframe_enqueue = &rtl8723bs_hal_xmitframe_enqueue;
}
| rperier/linux-rockchip | drivers/staging/rtl8723bs/hal/sdio_halinit.c | C | gpl-2.0 | 35,276 |
<?php
header('Content-Type: text/html;charset=UTF-8');
header('X-Robots-Tag: noindex,nofollow,noarchive');
header('Cache-Control: no-cache,no-store,private');
include '../../../../wp-load.php';
$user = NewsletterSubscription::instance()->save_profile();
NewsletterSubscription::instance()->show_message('profile', $user, NewsletterSubscription::instance()->options['profile_saved']);
| FrostLife07/songhang1 | wp-content/plugins/newsletter/do/save.php | PHP | gpl-2.0 | 386 |
<?php
/**
* @file
* Contains \Drupal\Core\Condition\ConditionPluginBase.
*/
namespace Drupal\Core\Condition;
use Drupal\Core\Executable\ExecutablePluginBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a basis for fulfilling contexts for condition plugins.
*
* @see \Drupal\Core\Condition\Annotation\Condition
* @see \Drupal\Core\Condition\ConditionInterface
* @see \Drupal\Core\Condition\ConditionManager
*
* @ingroup plugin_api
*/
abstract class ConditionPluginBase extends ExecutablePluginBase implements ConditionInterface {
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->setConfiguration($configuration);
}
/**
* {@inheritdoc}
*/
public function isNegated() {
return !empty($this->configuration['negate']);
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['negate'] = array(
'#type' => 'checkbox',
'#title' => $this->t('Negate the condition'),
'#default_value' => $this->configuration['negate'],
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->configuration['negate'] = $form_state->getValue('negate');
}
/**
* {@inheritdoc}
*/
public function execute() {
return $this->executableManager->execute($this);
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return array(
'id' => $this->getPluginId(),
) + $this->configuration;
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$this->configuration = $configuration + $this->defaultConfiguration();
return $this;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return array(
'negate' => FALSE,
);
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
return array();
}
}
| podarok/csua_d8 | drupal/core/lib/Drupal/Core/Condition/ConditionPluginBase.php | PHP | gpl-2.0 | 2,255 |
<?php
namespace Drupal\Tests\media\Kernel;
use Drupal\media\Entity\Media;
use Drupal\media\Entity\MediaType;
use Drupal\media\MediaInterface;
use Drupal\media\MediaTypeInterface;
use Drupal\user\Entity\Role;
use Drupal\user\Entity\User;
/**
* Tests creation of media types and media items.
*
* @group media
*/
class MediaCreationTest extends MediaKernelTestBase {
/**
* Tests creating a media type programmatically.
*/
public function testMediaTypeCreation() {
$media_type_storage = $this->container->get('entity_type.manager')->getStorage('media_type');
$this->assertInstanceOf(MediaTypeInterface::class, MediaType::load($this->testMediaType->id()), 'The new media type has not been correctly created in the database.');
// Test a media type created from default configuration.
$this->container->get('module_installer')->install(['media_test_type']);
$test_media_type = $media_type_storage->load('test');
$this->assertInstanceOf(MediaTypeInterface::class, $test_media_type, 'The media type from default configuration has not been created in the database.');
$this->assertEquals('Test type', $test_media_type->get('label'), 'Could not assure the correct type name.');
$this->assertEquals('Test type.', $test_media_type->get('description'), 'Could not assure the correct type description.');
$this->assertEquals('test', $test_media_type->get('source'), 'Could not assure the correct media source.');
// Source field is not set on the media source, but it should never
// be created automatically when a config is being imported.
$this->assertEquals(['source_field' => '', 'test_config_value' => 'Kakec'], $test_media_type->get('source_configuration'), 'Could not assure the correct media source configuration.');
$this->assertEquals(['metadata_attribute' => 'field_attribute_config_test'], $test_media_type->get('field_map'), 'Could not assure the correct field map.');
// Check the Media Type access handler behavior.
// We grant access to the 'view label' operation to all users having
// permission to 'view media'.
$user1 = User::create([
'name' => 'username1',
'status' => 1,
]);
$user1->save();
$user2 = User::create([
'name' => 'username2',
'status' => 1,
]);
$user2->save();
$role = Role::create([
'id' => 'role1',
'label' => 'role1',
]);
$role->grantPermission('view media')->trustData()->save();
$user2->addRole($role->id());
$this->assertFalse($test_media_type->access('view label', $user1));
$this->assertTrue($test_media_type->access('view label', $user2));
}
/**
* Tests creating a media item programmatically.
*/
public function testMediaEntityCreation() {
$media = Media::create([
'bundle' => $this->testMediaType->id(),
'name' => 'Unnamed',
'field_media_test' => 'Nation of sheep, ruled by wolves, owned by pigs.',
]);
$media->save();
$this->assertNotInstanceOf(MediaInterface::class, Media::load(rand(1000, 9999)), 'Failed asserting a non-existent media.');
$this->assertInstanceOf(MediaInterface::class, Media::load($media->id()), 'The new media item has not been created in the database.');
$this->assertEquals($this->testMediaType->id(), $media->bundle(), 'The media item was not created with the correct type.');
$this->assertEquals('Unnamed', $media->getName(), 'The media item was not created with the correct name.');
$source_field_name = $media->bundle->entity->getSource()->getSourceFieldDefinition($media->bundle->entity)->getName();
$this->assertEquals('Nation of sheep, ruled by wolves, owned by pigs.', $media->get($source_field_name)->value, 'Source returns incorrect source field value.');
}
}
| isauragalafate/drupal8 | web/core/modules/media/tests/src/Kernel/MediaCreationTest.php | PHP | gpl-2.0 | 3,766 |
/*
* linux/kernel/power/swap.c
*
* This file provides functions for reading the suspend image from
* and writing it to a swap partition.
*
* Copyright (C) 1998,2001-2005 Pavel Machek <[email protected]>
* Copyright (C) 2006 Rafael J. Wysocki <[email protected]>
*
* This file is released under the GPLv2.
*
*/
#include <linux/module.h>
#include <linux/file.h>
#include <linux/utsname.h>
#include <linux/version.h>
#include <linux/delay.h>
#include <linux/bitops.h>
#include <linux/genhd.h>
#include <linux/device.h>
#include <linux/buffer_head.h>
#include <linux/bio.h>
#include <linux/blkdev.h>
#include <linux/swap.h>
#include <linux/swapops.h>
#include <linux/pm.h>
#include "power.h"
extern char resume_file[];
#define SWSUSP_SIG "S1SUSPEND"
struct swsusp_header {
char reserved[PAGE_SIZE - 20 - sizeof(sector_t) - sizeof(int)];
sector_t image;
unsigned int flags; /* Flags to pass to the "boot" kernel */
char orig_sig[10];
char sig[10];
} __attribute__((packed));
static struct swsusp_header *swsusp_header;
/*
* General things
*/
static unsigned short root_swap = 0xffff;
static struct block_device *resume_bdev;
/**
* submit - submit BIO request.
* @rw: READ or WRITE.
* @off physical offset of page.
* @page: page we're reading or writing.
* @bio_chain: list of pending biod (for async reading)
*
* Straight from the textbook - allocate and initialize the bio.
* If we're reading, make sure the page is marked as dirty.
* Then submit it and, if @bio_chain == NULL, wait.
*/
static int submit(int rw, pgoff_t page_off, struct page *page,
struct bio **bio_chain)
{
struct bio *bio;
bio = bio_alloc(__GFP_WAIT | __GFP_HIGH, 1);
if (!bio)
return -ENOMEM;
bio->bi_sector = page_off * (PAGE_SIZE >> 9);
bio->bi_bdev = resume_bdev;
bio->bi_end_io = end_swap_bio_read;
if (bio_add_page(bio, page, PAGE_SIZE, 0) < PAGE_SIZE) {
printk("swsusp: ERROR: adding page to bio at %ld\n", page_off);
bio_put(bio);
return -EFAULT;
}
lock_page(page);
bio_get(bio);
if (bio_chain == NULL) {
submit_bio(rw | (1 << BIO_RW_SYNC), bio);
wait_on_page_locked(page);
if (rw == READ)
bio_set_pages_dirty(bio);
bio_put(bio);
} else {
if (rw == READ)
get_page(page); /* These pages are freed later */
bio->bi_private = *bio_chain;
*bio_chain = bio;
submit_bio(rw | (1 << BIO_RW_SYNC), bio);
}
return 0;
}
static int bio_read_page(pgoff_t page_off, void *addr, struct bio **bio_chain)
{
return submit(READ, page_off, virt_to_page(addr), bio_chain);
}
static int bio_write_page(pgoff_t page_off, void *addr, struct bio **bio_chain)
{
return submit(WRITE, page_off, virt_to_page(addr), bio_chain);
}
static int wait_on_bio_chain(struct bio **bio_chain)
{
struct bio *bio;
struct bio *next_bio;
int ret = 0;
if (bio_chain == NULL)
return 0;
bio = *bio_chain;
if (bio == NULL)
return 0;
while (bio) {
struct page *page;
next_bio = bio->bi_private;
page = bio->bi_io_vec[0].bv_page;
wait_on_page_locked(page);
if (!PageUptodate(page) || PageError(page))
ret = -EIO;
put_page(page);
bio_put(bio);
bio = next_bio;
}
*bio_chain = NULL;
return ret;
}
/*
* Saving part
*/
static int mark_swapfiles(sector_t start, unsigned int flags)
{
int error;
bio_read_page(swsusp_resume_block, swsusp_header, NULL);
if (!memcmp("SWAP-SPACE",swsusp_header->sig, 10) ||
!memcmp("SWAPSPACE2",swsusp_header->sig, 10)) {
memcpy(swsusp_header->orig_sig,swsusp_header->sig, 10);
memcpy(swsusp_header->sig,SWSUSP_SIG, 10);
swsusp_header->image = start;
swsusp_header->flags = flags;
error = bio_write_page(swsusp_resume_block,
swsusp_header, NULL);
} else {
printk(KERN_ERR "swsusp: Swap header not found!\n");
error = -ENODEV;
}
return error;
}
/**
* swsusp_swap_check - check if the resume device is a swap device
* and get its index (if so)
*/
static int swsusp_swap_check(void) /* This is called before saving image */
{
int res;
res = swap_type_of(swsusp_resume_device, swsusp_resume_block,
&resume_bdev);
if (res < 0)
return res;
root_swap = res;
res = blkdev_get(resume_bdev, FMODE_WRITE, O_RDWR);
if (res)
return res;
res = set_blocksize(resume_bdev, PAGE_SIZE);
if (res < 0)
blkdev_put(resume_bdev);
return res;
}
/**
* write_page - Write one page to given swap location.
* @buf: Address we're writing.
* @offset: Offset of the swap page we're writing to.
* @bio_chain: Link the next write BIO here
*/
static int write_page(void *buf, sector_t offset, struct bio **bio_chain)
{
void *src;
if (!offset)
return -ENOSPC;
if (bio_chain) {
src = (void *)__get_free_page(__GFP_WAIT | __GFP_HIGH);
if (src) {
memcpy(src, buf, PAGE_SIZE);
} else {
WARN_ON_ONCE(1);
bio_chain = NULL; /* Go synchronous */
src = buf;
}
} else {
src = buf;
}
return bio_write_page(offset, src, bio_chain);
}
/*
* The swap map is a data structure used for keeping track of each page
* written to a swap partition. It consists of many swap_map_page
* structures that contain each an array of MAP_PAGE_SIZE swap entries.
* These structures are stored on the swap and linked together with the
* help of the .next_swap member.
*
* The swap map is created during suspend. The swap map pages are
* allocated and populated one at a time, so we only need one memory
* page to set up the entire structure.
*
* During resume we also only need to use one swap_map_page structure
* at a time.
*/
#define MAP_PAGE_ENTRIES (PAGE_SIZE / sizeof(sector_t) - 1)
struct swap_map_page {
sector_t entries[MAP_PAGE_ENTRIES];
sector_t next_swap;
};
/**
* The swap_map_handle structure is used for handling swap in
* a file-alike way
*/
struct swap_map_handle {
struct swap_map_page *cur;
sector_t cur_swap;
unsigned int k;
};
static void release_swap_writer(struct swap_map_handle *handle)
{
if (handle->cur)
free_page((unsigned long)handle->cur);
handle->cur = NULL;
}
static int get_swap_writer(struct swap_map_handle *handle)
{
handle->cur = (struct swap_map_page *)get_zeroed_page(GFP_KERNEL);
if (!handle->cur)
return -ENOMEM;
handle->cur_swap = alloc_swapdev_block(root_swap);
if (!handle->cur_swap) {
release_swap_writer(handle);
return -ENOSPC;
}
handle->k = 0;
return 0;
}
static int swap_write_page(struct swap_map_handle *handle, void *buf,
struct bio **bio_chain)
{
int error = 0;
sector_t offset;
if (!handle->cur)
return -EINVAL;
offset = alloc_swapdev_block(root_swap);
error = write_page(buf, offset, bio_chain);
if (error)
return error;
handle->cur->entries[handle->k++] = offset;
if (handle->k >= MAP_PAGE_ENTRIES) {
error = wait_on_bio_chain(bio_chain);
if (error)
goto out;
offset = alloc_swapdev_block(root_swap);
if (!offset)
return -ENOSPC;
handle->cur->next_swap = offset;
error = write_page(handle->cur, handle->cur_swap, NULL);
if (error)
goto out;
memset(handle->cur, 0, PAGE_SIZE);
handle->cur_swap = offset;
handle->k = 0;
}
out:
return error;
}
static int flush_swap_writer(struct swap_map_handle *handle)
{
if (handle->cur && handle->cur_swap)
return write_page(handle->cur, handle->cur_swap, NULL);
else
return -EINVAL;
}
/**
* save_image - save the suspend image data
*/
static int save_image(struct swap_map_handle *handle,
struct snapshot_handle *snapshot,
unsigned int nr_to_write)
{
unsigned int m;
int ret;
int error = 0;
int nr_pages;
int err2;
struct bio *bio;
struct timeval start;
struct timeval stop;
printk("Saving image data pages (%u pages) ... ", nr_to_write);
m = nr_to_write / 100;
if (!m)
m = 1;
nr_pages = 0;
bio = NULL;
do_gettimeofday(&start);
do {
ret = snapshot_read_next(snapshot, PAGE_SIZE);
if (ret > 0) {
error = swap_write_page(handle, data_of(*snapshot),
&bio);
if (error)
break;
if (!(nr_pages % m))
printk("\b\b\b\b%3d%%", nr_pages / m);
nr_pages++;
}
} while (ret > 0);
err2 = wait_on_bio_chain(&bio);
do_gettimeofday(&stop);
if (!error)
error = err2;
if (!error)
printk("\b\b\b\bdone\n");
swsusp_show_speed(&start, &stop, nr_to_write, "Wrote");
return error;
}
/**
* enough_swap - Make sure we have enough swap to save the image.
*
* Returns TRUE or FALSE after checking the total amount of swap
* space avaiable from the resume partition.
*/
static int enough_swap(unsigned int nr_pages)
{
unsigned int free_swap = count_swap_pages(root_swap, 1);
pr_debug("swsusp: free swap pages: %u\n", free_swap);
return free_swap > nr_pages + PAGES_FOR_IO;
}
/**
* swsusp_write - Write entire image and metadata.
* @flags: flags to pass to the "boot" kernel in the image header
*
* It is important _NOT_ to umount filesystems at this point. We want
* them synced (in case something goes wrong) but we DO not want to mark
* filesystem clean: it is not. (And it does not matter, if we resume
* correctly, we'll mark system clean, anyway.)
*/
int swsusp_write(unsigned int flags)
{
struct swap_map_handle handle;
struct snapshot_handle snapshot;
struct swsusp_info *header;
int error;
error = swsusp_swap_check();
if (error) {
printk(KERN_ERR "swsusp: Cannot find swap device, try "
"swapon -a.\n");
return error;
}
memset(&snapshot, 0, sizeof(struct snapshot_handle));
error = snapshot_read_next(&snapshot, PAGE_SIZE);
if (error < PAGE_SIZE) {
if (error >= 0)
error = -EFAULT;
goto out;
}
header = (struct swsusp_info *)data_of(snapshot);
if (!enough_swap(header->pages)) {
printk(KERN_ERR "swsusp: Not enough free swap\n");
error = -ENOSPC;
goto out;
}
error = get_swap_writer(&handle);
if (!error) {
sector_t start = handle.cur_swap;
error = swap_write_page(&handle, header, NULL);
if (!error)
error = save_image(&handle, &snapshot,
header->pages - 1);
if (!error) {
flush_swap_writer(&handle);
printk("S");
error = mark_swapfiles(start, flags);
printk("|\n");
}
}
if (error)
free_all_swap_pages(root_swap);
release_swap_writer(&handle);
out:
swsusp_close();
return error;
}
/**
* The following functions allow us to read data using a swap map
* in a file-alike way
*/
static void release_swap_reader(struct swap_map_handle *handle)
{
if (handle->cur)
free_page((unsigned long)handle->cur);
handle->cur = NULL;
}
static int get_swap_reader(struct swap_map_handle *handle, sector_t start)
{
int error;
if (!start)
return -EINVAL;
handle->cur = (struct swap_map_page *)get_zeroed_page(__GFP_WAIT | __GFP_HIGH);
if (!handle->cur)
return -ENOMEM;
error = bio_read_page(start, handle->cur, NULL);
if (error) {
release_swap_reader(handle);
return error;
}
handle->k = 0;
return 0;
}
static int swap_read_page(struct swap_map_handle *handle, void *buf,
struct bio **bio_chain)
{
sector_t offset;
int error;
if (!handle->cur)
return -EINVAL;
offset = handle->cur->entries[handle->k];
if (!offset)
return -EFAULT;
error = bio_read_page(offset, buf, bio_chain);
if (error)
return error;
if (++handle->k >= MAP_PAGE_ENTRIES) {
error = wait_on_bio_chain(bio_chain);
handle->k = 0;
offset = handle->cur->next_swap;
if (!offset)
release_swap_reader(handle);
else if (!error)
error = bio_read_page(offset, handle->cur, NULL);
}
return error;
}
/**
* load_image - load the image using the swap map handle
* @handle and the snapshot handle @snapshot
* (assume there are @nr_pages pages to load)
*/
static int load_image(struct swap_map_handle *handle,
struct snapshot_handle *snapshot,
unsigned int nr_to_read)
{
unsigned int m;
int error = 0;
struct timeval start;
struct timeval stop;
struct bio *bio;
int err2;
unsigned nr_pages;
printk("Loading image data pages (%u pages) ... ", nr_to_read);
m = nr_to_read / 100;
if (!m)
m = 1;
nr_pages = 0;
bio = NULL;
do_gettimeofday(&start);
for ( ; ; ) {
error = snapshot_write_next(snapshot, PAGE_SIZE);
if (error <= 0)
break;
error = swap_read_page(handle, data_of(*snapshot), &bio);
if (error)
break;
if (snapshot->sync_read)
error = wait_on_bio_chain(&bio);
if (error)
break;
if (!(nr_pages % m))
printk("\b\b\b\b%3d%%", nr_pages / m);
nr_pages++;
}
err2 = wait_on_bio_chain(&bio);
do_gettimeofday(&stop);
if (!error)
error = err2;
if (!error) {
printk("\b\b\b\bdone\n");
snapshot_write_finalize(snapshot);
if (!snapshot_image_loaded(snapshot))
error = -ENODATA;
}
swsusp_show_speed(&start, &stop, nr_to_read, "Read");
return error;
}
/**
* swsusp_read - read the hibernation image.
* @flags_p: flags passed by the "frozen" kernel in the image header should
* be written into this memeory location
*/
int swsusp_read(unsigned int *flags_p)
{
int error;
struct swap_map_handle handle;
struct snapshot_handle snapshot;
struct swsusp_info *header;
*flags_p = swsusp_header->flags;
if (IS_ERR(resume_bdev)) {
pr_debug("swsusp: block device not initialised\n");
return PTR_ERR(resume_bdev);
}
memset(&snapshot, 0, sizeof(struct snapshot_handle));
error = snapshot_write_next(&snapshot, PAGE_SIZE);
if (error < PAGE_SIZE)
return error < 0 ? error : -EFAULT;
header = (struct swsusp_info *)data_of(snapshot);
error = get_swap_reader(&handle, swsusp_header->image);
if (!error)
error = swap_read_page(&handle, header, NULL);
if (!error)
error = load_image(&handle, &snapshot, header->pages - 1);
release_swap_reader(&handle);
blkdev_put(resume_bdev);
if (!error)
pr_debug("swsusp: Reading resume file was successful\n");
else
pr_debug("swsusp: Error %d resuming\n", error);
return error;
}
/**
* swsusp_check - Check for swsusp signature in the resume device
*/
int swsusp_check(void)
{
int error;
resume_bdev = open_by_devnum(swsusp_resume_device, FMODE_READ);
if (!IS_ERR(resume_bdev)) {
set_blocksize(resume_bdev, PAGE_SIZE);
memset(swsusp_header, 0, PAGE_SIZE);
error = bio_read_page(swsusp_resume_block,
swsusp_header, NULL);
if (error)
return error;
if (!memcmp(SWSUSP_SIG, swsusp_header->sig, 10)) {
memcpy(swsusp_header->sig, swsusp_header->orig_sig, 10);
/* Reset swap signature now */
error = bio_write_page(swsusp_resume_block,
swsusp_header, NULL);
} else {
return -EINVAL;
}
if (error)
blkdev_put(resume_bdev);
else
pr_debug("swsusp: Signature found, resuming\n");
} else {
error = PTR_ERR(resume_bdev);
}
if (error)
pr_debug("swsusp: Error %d check for resume file\n", error);
return error;
}
/**
* swsusp_close - close swap device.
*/
void swsusp_close(void)
{
if (IS_ERR(resume_bdev)) {
pr_debug("swsusp: block device not initialised\n");
return;
}
blkdev_put(resume_bdev);
}
static int swsusp_header_init(void)
{
swsusp_header = (struct swsusp_header*) __get_free_page(GFP_KERNEL);
if (!swsusp_header)
panic("Could not allocate memory for swsusp_header\n");
return 0;
}
core_initcall(swsusp_header_init);
| kidmaple/CoolWall | linux-2.6.x/kernel/power/swap.c | C | gpl-2.0 | 14,970 |
// @file querypattern.h - Query pattern matching for selecting similar plans given similar queries.
/* Copyright 2011 10gen Inc.
*
* 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.
*/
#pragma once
#include "jsobj.h"
namespace mongo {
class FieldRangeSet;
/**
* Implements query pattern matching, used to determine if a query is
* similar to an earlier query and should use the same plan.
*
* Two queries will generate the same QueryPattern, and therefore match each
* other, if their fields have the same Types and they have the same sort
* spec.
*/
class QueryPattern {
public:
QueryPattern( const FieldRangeSet &frs, const BSONObj &sort );
enum Type {
Empty,
Equality,
LowerBound,
UpperBound,
UpperAndLowerBound,
ConstraintPresent
};
bool operator<( const QueryPattern &other ) const;
/** for testing only */
bool operator==( const QueryPattern &other ) const;
/** for testing only */
bool operator!=( const QueryPattern &other ) const;
/** for development / debugging */
string toString() const;
private:
void setSort( const BSONObj sort );
static BSONObj normalizeSort( const BSONObj &spec );
map<string,Type> _fieldTypes;
BSONObj _sort;
};
/** Summarizes the candidate plans that may run for a query. */
class CandidatePlanCharacter {
public:
CandidatePlanCharacter( bool mayRunInOrderPlan, bool mayRunOutOfOrderPlan ) :
_mayRunInOrderPlan( mayRunInOrderPlan ),
_mayRunOutOfOrderPlan( mayRunOutOfOrderPlan ) {
}
CandidatePlanCharacter() :
_mayRunInOrderPlan(),
_mayRunOutOfOrderPlan() {
}
bool mayRunInOrderPlan() const { return _mayRunInOrderPlan; }
bool mayRunOutOfOrderPlan() const { return _mayRunOutOfOrderPlan; }
bool valid() const { return mayRunInOrderPlan() || mayRunOutOfOrderPlan(); }
bool hybridPlanSet() const { return mayRunInOrderPlan() && mayRunOutOfOrderPlan(); }
private:
bool _mayRunInOrderPlan;
bool _mayRunOutOfOrderPlan;
};
/** Information about a query plan that ran successfully for a QueryPattern. */
class CachedQueryPlan {
public:
CachedQueryPlan() :
_nScanned() {
}
CachedQueryPlan( const BSONObj &indexKey, long long nScanned,
CandidatePlanCharacter planCharacter );
BSONObj indexKey() const { return _indexKey; }
long long nScanned() const { return _nScanned; }
CandidatePlanCharacter planCharacter() const { return _planCharacter; }
private:
BSONObj _indexKey;
long long _nScanned;
CandidatePlanCharacter _planCharacter;
};
inline bool QueryPattern::operator<( const QueryPattern &other ) const {
map<string,Type>::const_iterator i = _fieldTypes.begin();
map<string,Type>::const_iterator j = other._fieldTypes.begin();
while( i != _fieldTypes.end() ) {
if ( j == other._fieldTypes.end() )
return false;
if ( i->first < j->first )
return true;
else if ( i->first > j->first )
return false;
if ( i->second < j->second )
return true;
else if ( i->second > j->second )
return false;
++i;
++j;
}
if ( j != other._fieldTypes.end() )
return true;
return _sort.woCompare( other._sort ) < 0;
}
} // namespace mongo
| linghegu/gsnetwork | thirdparty/mongo-driver/src/mongo/db/querypattern.h | C | gpl-3.0 | 4,228 |
-----------------------------------
-- Vorpal Scythe
-- Scythe weapon skill
-- Skill level: 150
-- Delivers a single-hit attack. params.crit varies with TP.
-- Modifiers: STR:100%
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
--ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 1.0; params.ftp200 = 1.0; params.ftp300 = 1.0;
--wscs are in % so 0.2=20%
params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
--critical mods, again in % (ONLY USE FOR critICAL HIT VARIES WITH TP)
params.crit100 = 0.3; params.crit200=0.6; params.crit300=0.9;
params.canCrit = true;
--accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
--attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| AlexandreCA/update | scripts/globals/weaponskills/vorpal_scythe.lua | Lua | gpl-3.0 | 1,561 |
CC = gcc
CFLAGS = -g -Wall
LIBS = -lglib-2.0
DEPS =
OBJ = glibhash.o
mem_errors: mem_errors.c
gcc $(CFLAGS) -o mem_errors mem_errors.c
list_errors: list_errors.c
gcc $(CFLAGS) -o list_errors list_errors.c
valgrind:
G_SLICE=always-malloc G_DEBUG=gc-friendly valgrind --tool=memcheck --leak-check=full --leak-resolution=high --num-callers=20 --log-file=vgdump --show-reachable=yes ./mem_errors
| dennis-chen/SoftwareSystems | lecture24/Makefile | Makefile | gpl-3.0 | 405 |
/* This file is part of Clementine.
Copyright 2012, David Sansome <[email protected]>
Clementine 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.
Clementine 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 Clementine. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef MOODBARLOADER_H
#define MOODBARLOADER_H
#include <QMap>
#include <QObject>
#include <QSet>
class QNetworkDiskCache;
class QUrl;
class Application;
class MoodbarPipeline;
class MoodbarLoader : public QObject {
Q_OBJECT
public:
MoodbarLoader(Application* app, QObject* parent = nullptr);
~MoodbarLoader();
enum Result {
// The URL isn't a local file or the moodbar plugin was not available -
// moodbar data can never be loaded.
CannotLoad,
// Moodbar data was loaded and returned.
Loaded,
// Moodbar data will be loaded in the background, a MoodbarPipeline* was
// was returned that you can connect to the Finished() signal on.
WillLoadAsync
};
Result Load(const QUrl& url, QByteArray* data,
MoodbarPipeline** async_pipeline);
private slots:
void ReloadSettings();
void RequestFinished(MoodbarPipeline* request, const QUrl& filename);
void MaybeTakeNextRequest();
private:
static QStringList MoodFilenames(const QString& song_filename);
private:
QNetworkDiskCache* cache_;
QThread* thread_;
const int kMaxActiveRequests;
QMap<QUrl, MoodbarPipeline*> requests_;
QList<QUrl> queued_requests_;
QSet<QUrl> active_requests_;
bool save_alongside_originals_;
bool disable_moodbar_calculation_;
};
#endif // MOODBARLOADER_H
| ivan-leontiev/clementine-free-grooveshark | src/moodbar/moodbarloader.h | C | gpl-3.0 | 2,059 |
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright: (c) 2017, Davis Phillips [email protected]
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt)
from __future__ import absolute_import, division, print_function
__metaclass__ = type
ANSIBLE_METADATA = {'metadata_version': '1.1',
'status': ['preview'],
'supported_by': 'community'}
DOCUMENTATION = '''
---
module: vmware_resource_pool
short_description: Add/remove resource pools to/from vCenter
description:
- This module can be used to add/remove a resource pool to/from vCenter
version_added: 2.3
author:
- Davis Phillips (@dav1x)
notes:
- Tested on vSphere 6.5
requirements:
- "python >= 2.6"
- PyVmomi
options:
datacenter:
description:
- Name of the datacenter to add the host.
required: True
cluster:
description:
- Name of the cluster to add the host.
required: True
resource_pool:
description:
- Resource pool name to manage.
required: True
cpu_expandable_reservations:
description:
- In a resource pool with an expandable reservation, the reservation on a resource pool can grow beyond the specified value.
default: True
type: bool
cpu_reservation:
description:
- Amount of resource that is guaranteed available to the virtual machine or resource pool.
default: 0
cpu_limit:
description:
- The utilization of a virtual machine/resource pool will not exceed this limit, even if there are available resources.
- The default value -1 indicates no limit.
default: -1
cpu_shares:
description:
- Memory shares are used in case of resource contention.
choices:
- high
- custom
- low
- normal
default: normal
mem_expandable_reservations:
description:
- In a resource pool with an expandable reservation, the reservation on a resource pool can grow beyond the specified value.
default: True
type: bool
mem_reservation:
description:
- Amount of resource that is guaranteed available to the virtual machine or resource pool.
default: 0
mem_limit:
description:
- The utilization of a virtual machine/resource pool will not exceed this limit, even if there are available resources.
- The default value -1 indicates no limit.
default: -1
mem_shares:
description:
- Memory shares are used in case of resource contention.
choices:
- high
- custom
- low
- normal
default: normal
state:
description:
- Add or remove the resource pool
default: 'present'
choices:
- 'present'
- 'absent'
extends_documentation_fragment: vmware.documentation
'''
EXAMPLES = '''
# Create a resource pool
- name: Add resource pool to vCenter
vmware_resource_pool:
hostname: vcsa_host
username: vcsa_user
password: vcsa_pass
datacenter: datacenter
cluster: cluster
resource_pool: resource_pool
mem_shares: normal
mem_limit: -1
mem_reservation: 0
mem_expandable_reservations: True
cpu_shares: normal
cpu_limit: -1
cpu_reservation: 0
cpu_expandable_reservations: True
state: present
'''
RETURN = """
instance:
description: metadata about the new resource pool
returned: always
type: dict
sample: None
"""
try:
from pyVmomi import vim, vmodl
HAS_PYVMOMI = True
except ImportError:
HAS_PYVMOMI = False
from ansible.module_utils.vmware import get_all_objs, connect_to_api, vmware_argument_spec, find_datacenter_by_name, \
find_cluster_by_name, wait_for_task, find_host_by_cluster_datacenter
from ansible.module_utils.basic import AnsibleModule
class VMwareResourcePool(object):
def __init__(self, module):
self.module = module
self.datacenter = module.params['datacenter']
self.cluster = module.params['cluster']
self.resource_pool = module.params['resource_pool']
self.hostname = module.params['hostname']
self.username = module.params['username']
self.password = module.params['password']
self.state = module.params['state']
self.mem_shares = module.params['mem_shares']
self.mem_limit = module.params['mem_limit']
self.mem_reservation = module.params['mem_reservation']
self.mem_expandable_reservations = module.params[
'cpu_expandable_reservations']
self.cpu_shares = module.params['cpu_shares']
self.cpu_limit = module.params['cpu_limit']
self.cpu_reservation = module.params['cpu_reservation']
self.cpu_expandable_reservations = module.params[
'cpu_expandable_reservations']
self.dc_obj = None
self.cluster_obj = None
self.host_obj = None
self.resource_pool_obj = None
self.content = connect_to_api(module)
def select_resource_pool(self, host):
pool_obj = None
resource_pools = get_all_objs(self.content, [vim.ResourcePool])
pool_selections = self.get_obj(
[vim.ResourcePool],
self.resource_pool,
return_all=True
)
if pool_selections:
for p in pool_selections:
if p in resource_pools:
pool_obj = p
break
return pool_obj
def get_obj(self, vimtype, name, return_all=False):
obj = list()
container = self.content.viewManager.CreateContainerView(
self.content.rootFolder, vimtype, True)
for c in container.view:
if name in [c.name, c._GetMoId()]:
if return_all is False:
return c
else:
obj.append(c)
if len(obj) > 0:
return obj
else:
# for backwards-compat
return None
def process_state(self):
try:
rp_states = {
'absent': {
'present': self.state_remove_rp,
'absent': self.state_exit_unchanged,
},
'present': {
'present': self.state_exit_unchanged,
'absent': self.state_add_rp,
}
}
rp_states[self.state][self.check_rp_state()]()
except vmodl.RuntimeFault as runtime_fault:
self.module.fail_json(msg=runtime_fault.msg)
except vmodl.MethodFault as method_fault:
self.module.fail_json(msg=method_fault.msg)
except Exception as e:
self.module.fail_json(msg=str(e))
def state_exit_unchanged(self):
self.module.exit_json(changed=False)
def state_remove_rp(self):
changed = True
result = None
resource_pool = self.select_resource_pool(self.host_obj)
try:
task = self.resource_pool_obj.Destroy()
success, result = wait_for_task(task)
except:
self.module.fail_json(msg="Failed to remove resource pool '%s' '%s'" % (
self.resource_pool, resource_pool))
self.module.exit_json(changed=changed, result=str(result))
def state_add_rp(self):
changed = True
rp_spec = vim.ResourceConfigSpec()
cpu_alloc = vim.ResourceAllocationInfo()
cpu_alloc.expandableReservation = self.cpu_expandable_reservations
cpu_alloc.limit = int(self.cpu_limit)
cpu_alloc.reservation = int(self.cpu_reservation)
cpu_alloc_shares = vim.SharesInfo()
cpu_alloc_shares.level = self.cpu_shares
cpu_alloc.shares = cpu_alloc_shares
rp_spec.cpuAllocation = cpu_alloc
mem_alloc = vim.ResourceAllocationInfo()
mem_alloc.limit = int(self.mem_limit)
mem_alloc.expandableReservation = self.mem_expandable_reservations
mem_alloc.reservation = int(self.mem_reservation)
mem_alloc_shares = vim.SharesInfo()
mem_alloc_shares.level = self.mem_shares
mem_alloc.shares = mem_alloc_shares
rp_spec.memoryAllocation = mem_alloc
self.dc_obj = find_datacenter_by_name(self.content, self.datacenter)
if self.dc_obj is None:
self.module.fail_json(msg="Unable to find datacenter with name %s" % self.datacenter)
self.cluster_obj = find_cluster_by_name(self.content, self.cluster, datacenter=self.dc_obj)
if self.cluster_obj is None:
self.module.fail_json(msg="Unable to find cluster with name %s" % self.cluster)
rootResourcePool = self.cluster_obj.resourcePool
rootResourcePool.CreateResourcePool(self.resource_pool, rp_spec)
self.module.exit_json(changed=changed)
def check_rp_state(self):
self.host_obj, self.cluster_obj = find_host_by_cluster_datacenter(self.module, self.content, self.datacenter,
self.cluster, self.hostname)
self.resource_pool_obj = self.select_resource_pool(self.host_obj)
if self.resource_pool_obj is None:
return 'absent'
else:
return 'present'
def main():
argument_spec = vmware_argument_spec()
argument_spec.update(dict(datacenter=dict(required=True, type='str'),
cluster=dict(required=True, type='str'),
resource_pool=dict(required=True, type='str'),
mem_shares=dict(type='str', default="normal", choices=[
'high', 'custom', 'normal', 'low']),
mem_limit=dict(type='int', default=-1),
mem_reservation=dict(type='int', default=0),
mem_expandable_reservations=dict(
type='bool', default="True"),
cpu_shares=dict(type='str', default="normal", choices=[
'high', 'custom', 'normal', 'low']),
cpu_limit=dict(type='int', default=-1),
cpu_reservation=dict(type='int', default=0),
cpu_expandable_reservations=dict(
type='bool', default="True"),
state=dict(default='present', choices=['present', 'absent'], type='str')))
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
if not HAS_PYVMOMI:
module.fail_json(msg='pyvmomi is required for this module')
vmware_rp = VMwareResourcePool(module)
vmware_rp.process_state()
if __name__ == '__main__':
main()
| hkariti/ansible | lib/ansible/modules/cloud/vmware/vmware_resource_pool.py | Python | gpl-3.0 | 11,094 |
using System.Collections.Specialized;
namespace Kudu.Web.Models
{
public class SettingsViewModel
{
public NameValueCollection AppSettings { get; set; }
public NameValueCollection ConnectionStrings { get; set; }
public DeploymentSettingsViewModel KuduSettings { get; set; }
public bool Enabled { get; set; }
}
} | bbauya/kudu | Kudu.Web/Models/SettingsViewModel.cs | C# | apache-2.0 | 358 |
#include "ping.h"
void
proc_v4(char *ptr, ssize_t len, struct msghdr *msg, struct timeval *tvrecv)
{
int hlen1, icmplen;
double rtt;
struct ip *ip;
struct icmp *icmp;
struct timeval *tvsend;
ip = (struct ip *) ptr; /* start of IP header */
hlen1 = ip->ip_hl << 2; /* length of IP header */
if (ip->ip_p != IPPROTO_ICMP)
return; /* not ICMP */
icmp = (struct icmp *) (ptr + hlen1); /* start of ICMP header */
if ( (icmplen = len - hlen1) < 8)
return; /* malformed packet */
if (icmp->icmp_type == ICMP_ECHOREPLY) {
if (icmp->icmp_id != pid)
return; /* not a response to our ECHO_REQUEST */
if (icmplen < 16)
return; /* not enough data to use */
tvsend = (struct timeval *) icmp->icmp_data;
tv_sub(tvrecv, tvsend);
rtt = tvrecv->tv_sec * 1000.0 + tvrecv->tv_usec / 1000.0;
printf("%d bytes from %s: seq=%u, ttl=%d, rtt=%.3f ms\n",
icmplen, Sock_ntop_host(pr->sarecv, pr->salen),
icmp->icmp_seq, ip->ip_ttl, rtt);
} else if (verbose) {
printf(" %d bytes from %s: type = %d, code = %d\n",
icmplen, Sock_ntop_host(pr->sarecv, pr->salen),
icmp->icmp_type, icmp->icmp_code);
}
}
| star1989/practice | unpv13e/ping/proc_v4.c | C | apache-2.0 | 1,152 |
#include "map/country_tree.hpp"
#include "map/framework.hpp"
#include "storage/storage.hpp"
namespace storage
{
namespace
{
int const RootItemIndex = 0;
int const ChildItemsOffset = 1;
}
inline TIndex GetIndexChild(TIndex const & index, int i)
{
TIndex child(index);
if (child.m_group == TIndex::INVALID)
child.m_group = i;
else if (child.m_country == TIndex::INVALID)
child.m_country = i;
else if (child.m_region == TIndex::INVALID)
child.m_region = i;
return child;
}
inline TIndex GetIndexParent(TIndex const & index)
{
ASSERT(index != TIndex(), ());
TIndex parent(index);
if (parent.m_region != TIndex::INVALID)
parent.m_region = TIndex::INVALID;
else if (parent.m_country != TIndex::INVALID)
parent.m_country = TIndex::INVALID;
else
parent.m_group = TIndex::INVALID;
return parent;
}
CountryTree::CountryTree(Framework & framework)
{
m_layout.reset(new ActiveMapsLayout(framework));
ConnectToCoreStorage();
}
CountryTree::~CountryTree()
{
DisconnectFromCoreStorage();
}
CountryTree & CountryTree::operator=(CountryTree const & other)
{
if (this == &other)
return *this;
DisconnectFromCoreStorage();
m_levelItems = other.m_levelItems;
m_listener = other.m_listener;
m_layout = other.m_layout;
ConnectToCoreStorage();
return *this;
}
void CountryTree::Init(vector<ActiveMapsLayout::TLocalFilePtr> const & maps)
{
ASSERT(IsValid(), ());
m_layout->Init(maps);
}
void CountryTree::Clear()
{
ASSERT(IsValid(), ());
ResetRoot();
m_layout->Clear();
}
ActiveMapsLayout & CountryTree::GetActiveMapLayout()
{
ASSERT(IsValid(), ());
return *m_layout;
}
ActiveMapsLayout const & CountryTree::GetActiveMapLayout() const
{
ASSERT(IsValid(), ());
return *m_layout;
}
bool CountryTree::IsValid() const
{
return m_layout != nullptr;
}
void CountryTree::SetDefaultRoot()
{
SetRoot(TIndex());
}
void CountryTree::SetParentAsRoot()
{
ASSERT(HasParent(), ());
SetRoot(GetIndexParent(GetCurrentRoot()));
}
void CountryTree::SetChildAsRoot(int childPosition)
{
ASSERT(!IsLeaf(childPosition), ());
SetRoot(GetChild(childPosition));
}
void CountryTree::ResetRoot()
{
m_levelItems.clear();
}
bool CountryTree::HasRoot() const
{
return !m_levelItems.empty();
}
bool CountryTree::HasParent() const
{
return GetCurrentRoot() != TIndex();
}
int CountryTree::GetChildCount() const
{
ASSERT(HasRoot(), ());
return m_levelItems.size() - ChildItemsOffset;
}
bool CountryTree::IsLeaf(int childPosition) const
{
return GetStorage().CountriesCount(GetChild(childPosition)) == 0;
}
string const & CountryTree::GetChildName(int position) const
{
return GetStorage().CountryName(GetChild(position));
}
TStatus CountryTree::GetLeafStatus(int position) const
{
return GetStorage().CountryStatusEx(GetChild(position));
}
MapOptions CountryTree::GetLeafOptions(int position) const
{
TStatus status;
MapOptions options;
GetStorage().CountryStatusEx(GetChild(position), status, options);
return options;
}
LocalAndRemoteSizeT const CountryTree::GetDownloadableLeafSize(int position) const
{
return GetActiveMapLayout().GetDownloadableCountrySize(GetChild(position));
}
LocalAndRemoteSizeT const CountryTree::GetLeafSize(int position, MapOptions const & options) const
{
return GetActiveMapLayout().GetCountrySize(GetChild(position), options);
}
LocalAndRemoteSizeT const CountryTree::GetRemoteLeafSizes(int position) const
{
return GetActiveMapLayout().GetRemoteCountrySizes(GetChild(position));
}
bool CountryTree::IsCountryRoot() const
{
TIndex index = GetCurrentRoot();
ASSERT(index.m_region == TIndex::INVALID, ());
if (index.m_country != TIndex::INVALID)
return true;
return false;
}
string const & CountryTree::GetRootName() const
{
return GetStorage().CountryName(GetCurrentRoot());
}
void CountryTree::DownloadCountry(int childPosition, MapOptions const & options)
{
ASSERT(IsLeaf(childPosition), ());
GetActiveMapLayout().DownloadMap(GetChild(childPosition), options);
}
void CountryTree::DeleteCountry(int childPosition, MapOptions const & options)
{
ASSERT(IsLeaf(childPosition), ());
GetActiveMapLayout().DeleteMap(GetChild(childPosition), options);
}
void CountryTree::RetryDownloading(int childPosition)
{
ASSERT(IsLeaf(childPosition), ());
GetActiveMapLayout().RetryDownloading(GetChild(childPosition));
}
void CountryTree::CancelDownloading(int childPosition)
{
GetStorage().DeleteFromDownloader(GetChild(childPosition));
}
void CountryTree::SetListener(CountryTreeListener * listener)
{
m_listener = listener;
}
void CountryTree::ResetListener()
{
m_listener = nullptr;
}
void CountryTree::ShowLeafOnMap(int position)
{
ASSERT(IsLeaf(position), ());
GetActiveMapLayout().ShowMap(GetChild(position));
}
Storage const & CountryTree::GetStorage() const
{
ASSERT(IsValid(), ());
return m_layout->GetStorage();
}
Storage & CountryTree::GetStorage()
{
ASSERT(IsValid(), ());
return m_layout->GetStorage();
}
void CountryTree::ConnectToCoreStorage()
{
if (IsValid())
{
m_subscribeSlotID = GetStorage().Subscribe(bind(&CountryTree::NotifyStatusChanged, this, _1),
bind(&CountryTree::NotifyProgressChanged, this, _1, _2));
}
}
void CountryTree::DisconnectFromCoreStorage()
{
if (IsValid())
GetStorage().Unsubscribe(m_subscribeSlotID);
}
TIndex const & CountryTree::GetCurrentRoot() const
{
ASSERT(HasRoot(), ());
return m_levelItems[RootItemIndex];
}
void CountryTree::SetRoot(TIndex index)
{
ResetRoot();
size_t const count = GetStorage().CountriesCount(index);
m_levelItems.reserve(ChildItemsOffset + count);
m_levelItems.push_back(index);
for (size_t i = 0; i < count; ++i)
m_levelItems.push_back(GetIndexChild(index, i));
}
TIndex const & CountryTree::GetChild(int childPosition) const
{
ASSERT(childPosition < GetChildCount(), ());
return m_levelItems[ChildItemsOffset + childPosition];
}
int CountryTree::GetChildPosition(TIndex const & index)
{
int result = -1;
if (HasRoot())
{
auto iter = find(m_levelItems.begin(), m_levelItems.end(), index);
if (iter != m_levelItems.end())
result = distance(m_levelItems.begin(), iter) - ChildItemsOffset;
}
return result;
}
void CountryTree::NotifyStatusChanged(TIndex const & index)
{
if (m_listener != nullptr)
{
int position = GetChildPosition(index);
if (position != -1)
m_listener->ItemStatusChanged(position);
}
}
void CountryTree::NotifyProgressChanged(TIndex const & index, LocalAndRemoteSizeT const & sizes)
{
if (m_listener != nullptr)
{
int position = GetChildPosition(index);
if (position != -1)
m_listener->ItemProgressChanged(position, sizes);
}
}
}
| guard163/omim | map/country_tree.cpp | C++ | apache-2.0 | 6,758 |
// @target: es6
try {
} catch(e) {
const e = null;
}
try {
} catch(e) {
let e;
}
try {
} catch ([a, b]) {
const [c, b] = [0, 1];
}
try {
} catch ({ a: x, b: x }) {
}
try {
} catch(e) {
function test() {
let e;
}
}
| weswigham/TypeScript | tests/cases/compiler/redeclareParameterInCatchBlock.ts | TypeScript | apache-2.0 | 253 |
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*
*/
package org.wso2.andes.client;
import org.wso2.andes.test.utils.QpidBrokerTestCase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.jms.Connection;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageListener;
import javax.jms.MessageProducer;
import javax.jms.Queue;
import javax.jms.Session;
import javax.jms.TextMessage;
import javax.naming.Context;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* QPID-293 Setting MessageListener after connection has started can cause messages to be "lost" on a internal delivery
* queue <p/> The message delivery process: Mina puts a message on _queue in AMQSession and the dispatcher thread
* take()s from here and dispatches to the _consumers. If the _consumer1 doesn't have a message listener set at
* connection start then messages are stored on _synchronousQueue (which needs to be > 1 to pass JMS TCK as multiple
* consumers on a session can run in any order and a synchronous put/poll will block the dispatcher). <p/> When setting
* the message listener later the _synchronousQueue is just poll()'ed and the first message delivered the remaining
* messages will be left on the queue and lost, subsequent messages on the session will arrive first.
*/
public class ResetMessageListenerTest extends QpidBrokerTestCase
{
private static final Logger _logger = LoggerFactory.getLogger(ResetMessageListenerTest.class);
Context _context;
private static final int MSG_COUNT = 6;
private Connection _clientConnection, _producerConnection;
private MessageConsumer _consumer1;
MessageProducer _producer;
Session _clientSession, _producerSession;
private final CountDownLatch _allFirstMessagesSent = new CountDownLatch(MSG_COUNT); // all messages Sent Lock
private final CountDownLatch _allSecondMessagesSent = new CountDownLatch(MSG_COUNT); // all messages Sent Lock
protected void setUp() throws Exception
{
super.setUp();
_clientConnection = getConnection("guest", "guest");
_clientConnection.start();
// Create Client 1
_clientSession = _clientConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Queue queue = _clientSession.createQueue("reset-message-listener-test-queue");
_consumer1 = _clientSession.createConsumer(queue);
// Create Producer
_producerConnection = getConnection("guest", "guest");
_producerConnection.start();
_producerSession = _producerConnection.createSession(false, Session.AUTO_ACKNOWLEDGE);
_producer = _producerSession.createProducer(queue);
TextMessage m = _producerSession.createTextMessage();
m.setStringProperty("rank", "first");
for (int msg = 0; msg < MSG_COUNT; msg++)
{
m.setText("Message " + msg);
_producer.send(m);
}
}
protected void tearDown() throws Exception
{
_clientConnection.close();
super.tearDown();
}
public void testAsynchronousRecieve()
{
_logger.info("Test Start");
try
{
_consumer1.setMessageListener(new MessageListener()
{
public void onMessage(Message message)
{
try
{
if (message.getStringProperty("rank").equals("first"))
{
_allFirstMessagesSent.countDown();
}
}
catch (JMSException e)
{
e.printStackTrace();
fail("error receiving message");
}
}
});
}
catch (JMSException e)
{
_logger.error("Error Setting Default ML on consumer1");
}
try
{
assertTrue("Did not receive all first batch of messages",
_allFirstMessagesSent.await(1000, TimeUnit.MILLISECONDS));
_logger.info("Received first batch of messages");
}
catch (InterruptedException e)
{
// do nothing
}
try
{
_clientConnection.stop();
}
catch (JMSException e)
{
_logger.error("Error stopping connection");
}
_logger.info("Reset Message Listener ");
try
{
_consumer1.setMessageListener(new MessageListener()
{
public void onMessage(Message message)
{
try
{
if (message.getStringProperty("rank").equals("first"))
{
// Something ugly will happen, it'll probably kill the dispatcher
fail("All first set of messages should have been received");
}
else
{
_allSecondMessagesSent.countDown();
}
}
catch (JMSException e)
{
e.printStackTrace();
// Something ugly will happen, it'll probably kill the dispatcher
fail("error receiving message");
}
}
});
_clientConnection.start();
}
catch (javax.jms.IllegalStateException e)
{
_logger.error("Connection not stopped while setting ML", e);
fail("Unable to change message listener:" + e.getCause());
}
catch (JMSException e)
{
_logger.error("Error Setting Better ML on consumer1", e);
}
try
{
_logger.info("Send additional messages");
TextMessage m = _producerSession.createTextMessage();
m.setStringProperty("rank", "second");
for (int msg = 0; msg < MSG_COUNT; msg++)
{
m.setText("Message " + msg);
_producer.send(m);
}
}
catch (JMSException e)
{
_logger.error("Unable to send additional messages", e);
}
_logger.info("Waiting for messages");
try
{
assertTrue(_allSecondMessagesSent.await(1000, TimeUnit.MILLISECONDS));
}
catch (InterruptedException e)
{
// do nothing
}
assertEquals("First batch of messages not received correctly", 0, _allFirstMessagesSent.getCount());
assertEquals("Second batch of messages not received correctly", 0, _allSecondMessagesSent.getCount());
}
public static junit.framework.Test suite()
{
return new junit.framework.TestSuite(ResetMessageListenerTest.class);
}
}
| Dilshani/andes | modules/andes-core/systests/src/main/java/org/wso2/andes/client/ResetMessageListenerTest.java | Java | apache-2.0 | 7,871 |
.media-section .modal-footer{
margin-top:0px;
}
.media-section .modal .modal-header .close{
padding-bottom:2px;
}
.media-section .modal-content{
border:0px;
}
.media-section .modal-header{
background:#21A9E1;
}
.media-section #confirm_delete_modal .modal-header{
background:#E14421;
}
.media-section #move_file_modal .modal-header{
background:#FC9A24;
}
.media-section .modal-header h4{
color:#fff;
}
.confirm_delete_name{
color:#4DA7E8;
}
#move_btn{
background:#FABE28;
border:1px solid #FABE28;
}
/**************************************************/
/*** TOOLBAR CSS ***/
/**************************************************/
#toolbar{
background:#E0E0E0;
padding:20px;
border-top-left-radius:3px;
border-top-right-radius:3px;
}
#toolbar .btn{
padding:8px 13px;
font-size: 13px;
border-radius:2px;
}
#toolbar .btn-group .btn{
border-radius:0px;
}
#toolbar .btn-group .btn:first-child{
border-top-left-radius: 2px;
border-bottom-left-radius: 2px;
}
#toolbar .btn-group .btn:last-child{
border-top-right-radius: 2px;
border-bottom-right-radius: 2px;
}
#toolbar .btn-group .btn.btn-default:nth-child(2), #toolbar .btn-group .btn.btn-default:last-child{
border-left:1px solid #CBCBCD;
}
#toolbar .btn-group .btn.btn-default:nth-child(2), #toolbar .btn-group .btn.btn-default:nth-child(1){
margin-right:1px;
}
#toolbar .btn.btn-default:focus{
background:#F0F0F1;
border-color:#F0F0F1;
}
#toolbar .btn.btn-primary{
background:#4DA7E8;
border:1px solid #4DA7E8;
}
#toolbar .btn.btn-primary:hover{
background:#2995E3;
}
#toolbar #refresh.btn{
margin:0px 10px;
}
#toolbar i{
position: relative;
top: 2px;
}
/**************************************************/
/*** BREADCRUMB CSS ***/
/**************************************************/
.breadcrumb-container{
position:relative;
}
.breadcrumb.filemanager{
top:0px;
background:#f0f0f0;
border:1px solid #E0E0E0;
border-bottom:0px;
border-radius:0px;
padding-left:20px;
width: 100%;
margin-top: 0;
left: 0;
}
.breadcrumb.filemanager li{
cursor:pointer;
transition:color 0.1s linear;
position:relative;
}
.breadcrumb.filemanager li:hover{
color:#555;
}
.breadcrumb li .arrow{
display: none;
position: absolute;
bottom: -14px;
width: 12px;
height: 12px;
-ms-transform: rotate(45deg);
-webkit-transform: rotate(45deg);
transform: rotate(45deg);
background: #f0f0f0;
left: 50%;
border-right: 1px solid #efefef;
border-bottom: 1px solid #efefef;
}
.select2-display-none{
z-index:999999 !important;
}
.breadcrumb li:last-child .arrow{
display:block;
}
.breadcrumb li:first-child .arrow{
margin-left:-5px;
}
.breadcrumb li{
color:#4DA7E8;
cursor:pointer;
font-weight:bold;
}
.breadcrumb li:last-child{
color:#949494;
cursor:pointer;
}
.breadcrumb-container .toggle{
float: right;
position: absolute;
top: 11px;
cursor: pointer;
right: 5px;
color: #bbb;
transition: color 0.1s linear;
overflow:visible;
}
.breadcrumb-container .toggle:hover{
color:#aaa;
}
.breadcrumb-container .toggle span{
font-size:9px;
text-transform: uppercase;
float:left;
top:2px;
position:relative;
font-weight:bold;
right:10px;
}
.breadcrumb-container .toggle i{
font-size:18px;
float:right;
margin-right:5px;
position:relative;
top:-4px;
}
.nothingfound{
display:none;
}
#filemanager{
position:relative;
min-height:200px;
}
#filemanager .loader{
margin-top:25px;
}
#filemanager #content{
display: block;
background:#fff;
}
.flex{
display:flex;
flex-wrap: wrap;
border:1px solid #E0E0E0;
border-top:0px;
}
.flex #left{
flex:4;
position:relative;
min-height:230px;
}
.flex #left #no_files{
display:none;
}
.flex #left #no_files h3{
text-align: center;
margin-top: 55px;
margin-bottom:75px;
color:#949494;
}
.flex #right{
flex:1;
border-left:1px solid #f1f1f1;
}
#right .right_details{
display:block;
}
#right .right_none_selected{
display:none;
text-align:center;
}
#right .right_none_selected i{
width: 100%;
text-align: center;
font-size: 30px;
margin-left: 0;
padding: 50px;
display:block;
background: #f9f9f9;
}
#right .right_none_selected p{
text-align: center;
color: #bbb;
padding: 10px;
border-bottom: 1px solid #f1f1f1;
}
#files{
display:flex;
list-style:none;
width:100%;
margin:0px;
padding:0px;
flex-wrap:wrap;
padding:10px;
position:relative;
-webkit-touch-callout: none; /* iOS Safari */
-webkit-user-select: none; /* Chrome/Safari/Opera */
-khtml-user-select: none; /* Konqueror */
-moz-user-select: none; /* Firefox */
-ms-user-select: none; /* Internet Explorer/Edge */
user-select: none;
}
#files li{
flex:1;
width:100%;
min-width:200px;
max-width:250px;
}
#files li .file_link{
background:#eee;
padding:10px;
margin:10px;
cursor:pointer;
border-radius: 3px;
border: 1px solid #ecf0f1;
overflow: hidden;
background: #f6f8f9;
display:flex;
}
#files li .file_link .details{
flex:2;
overflow:hidden;
width:100%;
}
#files li .file_link .details small{
font-size: 11px;
position: relative;
top: -3px;
}
#files li .file_link .link_icon{
flex:1;
}
#files li .file_link img, #files li .file_link .img_icon{
display:none;
}
#files li .file_link.image img, #files li .file_link.image .img_icon{
display:block;
}
#files li .file_link.image img{
height:50px;
}
#files li .file_link.image .img_icon{
width:50px;
height:50px;
display:block;
}
#files li .file_link.selected, #files li .file_link:hover{
background: #4da7e8 !important;
border-color: #2581b8;
color:#fff;
}
#files li .file_link.selected h4, #files li .file_link:hover h4{
color:#fff;
}
#files li .details h4{
margin-bottom:2px;
margin-top:10px;
max-height: 17px;
height:17px;
overflow: hidden;
font-size:14px;
text-overflow: ellipsis;
}
#files li .details.folder h4{
margin-top:16px;
}
.file_link.folder i.icon{
float:left;
margin-left:10px;
}
.file_link.folder .num_items{
display:block;
}
.file_link .link_icon{
text-align: center;
padding-left: 0;
margin-left: 0;
margin-right: 5px;
}
.file_link .link_icon i{
padding-left:0px;
padding-right:0px;
position: relative;
top: 5px;
}
.file_link i.icon:before{
font-size:40px;
}
.detail_img{
border-bottom:1px solid #f1f1f1;
background:#eee;
}
.detail_img img{
width:100%;
height:auto;
display:inline-block;
}
.detail_img i{
display:block;
width: 100%;
text-align: center;
font-size: 70px;
margin-left: 0;
padding: 30px;
background: #f9f9f9;
}
.detail_img.folder i.fa-folder{
display:block;
}
.detail_img.file i.fa-file{
display:block;
}
.detail_img.image img{
display:block;
}
.detail_info{
padding:10px;
}
.detail_info .selected_file_count, .detail_info.folder .selected_file_size{
display:none;
}
.detail_info.folder .selected_file_count{
display:block;
}
.detail_info span{
display:block;
clear:both;
}
.detail_info a{
color:#4DA7E8;
}
.detail_info .selected_file_count, .detail_info .selected_file_size{
padding-top:0;
}
.detail_info h4{
float:left;
color:#bbb;
margin:0;
font-size:12px;
margin-top:3px;
margin-right:8px;
padding-bottom:2px;
font-weight:400;
}
.detail_info p{
float:left;
color:#444;
padding-bottom:3px;
font-size:12px;
font-weight:400;
}
/********** file upload progress **********/
#filemanager .progress{
border-radius:0;
margin-bottom:0;
}
#uploadProgress{
display:none;
background:#eee;
}
/********** end file upload progress **********/
#file_loader{
position:absolute;
width:100%;
height:100%;
left:0;
top:0;
background: rgba(255, 255, 255, 0.7);
z-index: 9;
text-align:center;
}
#file_loader #file_loader_inner{
width:60px;
height:60px;
position:absolute;
top:50%;
left:50%;
margin-left:-30px;
margin-top:-30px;
}
#file_loader img{
width:80px;
height:80px;
margin-top:50px;
opacity:0.5;
-webkit-animation:spin 1.2s ease-in-out infinite;
-moz-animation:spin 1.2s ease-in-out infinite;
animation:spin 1.2s ease-in-out infinite;
}
#file_loader p{
margin-top: 40px;
position: absolute;
text-align: center;
width: 100%;
top:50%;
font-weight: 400;
font-size: 12px;
}
@-moz-keyframes spin { 100% { -moz-transform: rotate(360deg); } }
@-webkit-keyframes spin { 100% { -webkit-transform: rotate(360deg); } }
@keyframes spin { 100% { -webkit-transform: rotate(360deg); transform:rotate(360deg); } }
| softwarebd/Softbd | publishable/assets/css/media/media.css | CSS | apache-2.0 | 8,510 |
require 'formula'
class Gwt < Formula
homepage 'https://developers.google.com/web-toolkit/'
url 'https://storage.googleapis.com/gwt-releases/gwt-2.6.1.zip'
sha1 '8ebc808e9ca6ef7e8f6460c8c0840423c192b3c5'
def install
rm Dir['*.cmd'] # remove Windows cmd files
share.install Dir['*']
# Don't use the GWT scripts because they expect the GWT jars to
# be in the same place as the script.
(bin/'webAppCreator').write <<-EOS.undent
#!/bin/sh
HOMEDIR=#{share}
java -cp "$HOMEDIR/gwt-user.jar:$HOMEDIR/gwt-dev.jar" com.google.gwt.user.tools.WebAppCreator "$@";
EOS
(bin/'benchmarkViewer').write <<-EOS.undent
#!/bin/sh
APPDIR=#{share}
java -Dcom.google.gwt.junit.reportPath="$1" -cp "$APPDIR/gwt-dev.jar" com.google.gwt.dev.RunWebApp -port auto $APPDIR/gwt-benchmark-viewer.war;
EOS
(bin/'i18nCreator').write <<-EOS.undent
#!/bin/sh
HOMEDIR=#{share}
java -cp "$HOMEDIR/gwt-user.jar:$HOMEDIR/gwt-dev.jar" com.google.gwt.i18n.tools.I18NCreator "$@";
EOS
end
def caveats
<<-EOS.undent
The GWT jars are available at #{share}
EOS
end
end
| jtrag/homebrew | Library/Formula/gwt.rb | Ruby | bsd-2-clause | 1,154 |
cask :v1 => 'subclassed-mnemosyne' do
version '1.1'
sha256 'c641f423f449104615f614bedc7a54938ae67b63a97842351a3258b0a283f6b3'
url 'https://www.subclassed.com/download/Mnemosyne.zip'
name 'Mnemosyne'
homepage 'https://www.subclassed.com/apps/mnemosyne/details'
license :gratis
app 'Mnemosyne.app'
end
| crzrcn/homebrew-cask | Casks/subclassed-mnemosyne.rb | Ruby | bsd-2-clause | 316 |
#ifndef BOOST_MPL_PROTECT_HPP_INCLUDED
#define BOOST_MPL_PROTECT_HPP_INCLUDED
// Copyright Peter Dimov 2001
// Copyright Aleksey Gurtovoy 2002-2004
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://www.boost.org/libs/mpl for documentation.
// $Id$
// $Date$
// $Revision$
#include <boost/mpl/aux_/arity.hpp>
#include <boost/mpl/aux_/config/dtp.hpp>
#include <boost/mpl/aux_/nttp_decl.hpp>
#include <boost/mpl/aux_/na_spec.hpp>
namespace boost { namespace mpl {
template<
typename BOOST_MPL_AUX_NA_PARAM(T)
, int not_le_ = 0
>
struct protect : T
{
#if BOOST_WORKAROUND(__EDG_VERSION__, == 238)
typedef mpl::protect type;
#else
typedef protect type;
#endif
};
#if defined(BOOST_MPL_CFG_BROKEN_DEFAULT_PARAMETERS_IN_NESTED_TEMPLATES)
namespace aux {
template< BOOST_MPL_AUX_NTTP_DECL(int, N), typename T >
struct arity< protect<T>, N >
: arity<T,N>
{
};
} // namespace aux
#endif
BOOST_MPL_AUX_NA_SPEC_MAIN(1, protect)
#if !defined(BOOST_MPL_CFG_NO_FULL_LAMBDA_SUPPORT)
BOOST_MPL_AUX_NA_SPEC_TEMPLATE_ARITY(1, 1, protect)
#endif
}}
#endif // BOOST_MPL_PROTECT_HPP_INCLUDED
| LeZhang2016/borderrouter-1 | third_party/wpantund/repo/third_party/boost/boost/mpl/protect.hpp | C++ | bsd-3-clause | 1,232 |
/**
* Advanced example using namespaces for a library and named arguments
*
* Run:
* node example4.js --help
* and play with the options to see the behavior.
*/
var opts = require('./../js/opts')
, host = 'localhost'; // default host value
// Example of using some library in the same app
var libOpts = [
{ short : 'l'
, long : 'list'
, description : 'Show the library list'
, callback : function () { console.log('mylib list!'); },
},
];
opts.add(libOpts, 'mylib');
// NOTE: ------------
// You would never actually add options for a library from within your
// app, this would be done from within the library itself. It is shown
// here for readability
var options = [
{ short : 'l' // deliberately conflicting with 'mylib' option
, long : 'list'
, description : 'List all files'
},
{ short : 'd'
, long : 'debug'
, description : 'Set a debug level'
, value : true
},
];
var arguments = [ { name : 'script' , required : true }
, { name : 'timeout' }
];
opts.parse(options, arguments, true);
var debug = opts.get('d') || 'info' // default debug value
, list = opts.get('list');
var script = opts.arg('script')
, timeout = opts.arg('timeout') || 30;
if (list) console.log('List arg was set');
console.log('Debug level is: ' + debug);
console.log('Script is: ' + script);
console.log('Timeout is: ' + timeout);
process.exit(0);
| danpomerantz/buses | node_modules/zombie/node_modules/html5/node_modules/opts/examples/example4.js | JavaScript | bsd-3-clause | 1,464 |
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2013 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_View
*/
namespace ZendTest\View\Renderer\TestAsset;
use JsonSerializable;
/**
* @category Zend
* @package Zend_View
* @subpackage UnitTest
*/
class JsonModel implements JsonSerializable
{
public $value = false;
public function jsonSerialize()
{
return $this->value;
}
}
| neerav999/cloud | vendor/ZF2/tests/ZendTest/View/Renderer/TestAsset/JsonModel.php | PHP | bsd-3-clause | 660 |
#!/usr/bin/env python
from setuptools import setup
import rsa
setup(name='rsa',
version=rsa.__version__,
description='Pure-Python RSA implementation',
author='Sybren A. Stuvel',
author_email='[email protected]',
maintainer='Sybren A. Stuvel',
maintainer_email='[email protected]',
url='http://stuvel.eu/rsa',
packages=['rsa'],
license='ASL 2',
classifiers=[
'Development Status :: 5 - Production/Stable',
'Intended Audience :: Developers',
'Intended Audience :: Education',
'Intended Audience :: Information Technology',
'License :: OSI Approved :: Apache Software License',
'Operating System :: OS Independent',
'Programming Language :: Python',
'Programming Language :: Python :: 3',
'Topic :: Security :: Cryptography',
],
install_requires=[
'pyasn1 >= 0.1.3',
],
entry_points={ 'console_scripts': [
'pyrsa-priv2pub = rsa.util:private_to_public',
'pyrsa-keygen = rsa.cli:keygen',
'pyrsa-encrypt = rsa.cli:encrypt',
'pyrsa-decrypt = rsa.cli:decrypt',
'pyrsa-sign = rsa.cli:sign',
'pyrsa-verify = rsa.cli:verify',
'pyrsa-encrypt-bigfile = rsa.cli:encrypt_bigfile',
'pyrsa-decrypt-bigfile = rsa.cli:decrypt_bigfile',
]},
)
| vadimtk/chrome4sdp | tools/telemetry/third_party/gsutilz/third_party/rsa/setup.py | Python | bsd-3-clause | 1,322 |
/*
* Copyright (c) 2011 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "list_wrapper.h"
#include "critical_section_wrapper.h"
#include "trace.h"
namespace webrtc {
ListItem::ListItem(const void* item)
: next_(0),
prev_(0),
item_ptr_(item),
item_(0)
{
}
ListItem::ListItem(const unsigned int item)
: next_(0),
prev_(0),
item_ptr_(0),
item_(item)
{
}
ListItem::~ListItem()
{
}
void* ListItem::GetItem() const
{
return const_cast<void*>(item_ptr_);
}
unsigned int ListItem::GetUnsignedItem() const
{
return item_;
}
ListWrapper::ListWrapper()
: critical_section_(CriticalSectionWrapper::CreateCriticalSection()),
first_(0),
last_(0),
size_(0)
{
}
ListWrapper::~ListWrapper()
{
if (!Empty())
{
// TODO (hellner) I'm not sure this loggin is useful.
WEBRTC_TRACE(kTraceMemory, kTraceUtility, -1,
"Potential memory leak in ListWrapper");
// Remove all remaining list items.
while (Erase(First()) == 0)
{}
}
delete critical_section_;
}
bool ListWrapper::Empty() const
{
return !first_ && !last_;
}
unsigned int ListWrapper::GetSize() const
{
return size_;
}
int ListWrapper::PushBack(const void* ptr)
{
ListItem* item = new ListItem(ptr);
CriticalSectionScoped lock(critical_section_);
PushBackImpl(item);
return 0;
}
int ListWrapper::PushBack(const unsigned int item_id)
{
ListItem* item = new ListItem(item_id);
CriticalSectionScoped lock(critical_section_);
PushBackImpl(item);
return 0;
}
int ListWrapper::PushFront(const unsigned int item_id)
{
ListItem* item = new ListItem(item_id);
CriticalSectionScoped lock(critical_section_);
PushFrontImpl(item);
return 0;
}
int ListWrapper::PushFront(const void* ptr)
{
ListItem* item = new ListItem(ptr);
CriticalSectionScoped lock(critical_section_);
PushFrontImpl(item);
return 0;
}
int ListWrapper::PopFront()
{
return Erase(first_);
}
int ListWrapper::PopBack()
{
return Erase(last_);
}
ListItem* ListWrapper::First() const
{
return first_;
}
ListItem* ListWrapper::Last() const
{
return last_;
}
ListItem* ListWrapper::Next(ListItem* item) const
{
if(!item)
{
return 0;
}
return item->next_;
}
ListItem* ListWrapper::Previous(ListItem* item) const
{
if (!item)
{
return 0;
}
return item->prev_;
}
int ListWrapper::Insert(ListItem* existing_previous_item, ListItem* new_item)
{
if (!new_item)
{
return -1;
}
// Allow existing_previous_item to be NULL if the list is empty.
// TODO (hellner) why allow this? Keep it as is for now to avoid
// breaking API contract.
if (!existing_previous_item && !Empty())
{
return -1;
}
CriticalSectionScoped lock(critical_section_);
if (!existing_previous_item)
{
PushBackImpl(new_item);
return 0;
}
ListItem* next_item = existing_previous_item->next_;
new_item->next_ = existing_previous_item->next_;
new_item->prev_ = existing_previous_item;
existing_previous_item->next_ = new_item;
if (next_item)
{
next_item->prev_ = new_item;
}
else
{
last_ = new_item;
}
size_++;
return 0;
}
int ListWrapper::InsertBefore(ListItem* existing_next_item,
ListItem* new_item)
{
if (!new_item)
{
return -1;
}
// Allow existing_next_item to be NULL if the list is empty.
// Todo: why allow this? Keep it as is for now to avoid breaking API
// contract.
if (!existing_next_item && !Empty())
{
return -1;
}
CriticalSectionScoped lock(critical_section_);
if (!existing_next_item)
{
PushBackImpl(new_item);
return 0;
}
ListItem* previous_item = existing_next_item->prev_;
new_item->next_ = existing_next_item;
new_item->prev_ = previous_item;
existing_next_item->prev_ = new_item;
if (previous_item)
{
previous_item->next_ = new_item;
}
else
{
first_ = new_item;
}
size_++;
return 0;
}
int ListWrapper::Erase(ListItem* item)
{
if (!item)
{
return -1;
}
size_--;
ListItem* previous_item = item->prev_;
ListItem* next_item = item->next_;
if (!previous_item)
{
if(next_item)
{
next_item->prev_ = 0;
}
first_ = next_item;
}
else
{
previous_item->next_ = next_item;
}
if (!next_item)
{
if(previous_item)
{
previous_item->next_ = 0;
}
last_ = previous_item;
}
else
{
next_item->prev_ = previous_item;
}
delete item;
return 0;
}
void ListWrapper::PushBackImpl(ListItem* item)
{
if (Empty())
{
first_ = item;
last_ = item;
size_++;
return;
}
item->prev_ = last_;
last_->next_ = item;
last_ = item;
size_++;
}
void ListWrapper::PushFrontImpl(ListItem* item)
{
if (Empty())
{
first_ = item;
last_ = item;
size_++;
return;
}
item->next_ = first_;
first_->prev_ = item;
first_ = item;
size_++;
}
} //namespace webrtc
| leighpauls/k2cro4 | third_party/webrtc/system_wrappers/source/list_no_stl.cc | C++ | bsd-3-clause | 5,665 |
<?php
/**
* Arr.php
*
* Part of Overtrue\Wechat.
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @author overtrue <[email protected]>
* @copyright 2015 overtrue <[email protected]>
* @link https://github.com/overtrue
* @link http://overtrue.me
* @link https://github.com/laravel/framework/blob/4.2/src/Illuminate/Support/Arr.php
*/
namespace Overtrue\Wechat\Utils;
use Closure;
/**
* Array helper from Illuminate\Support\Arr
*/
class Arr
{
/**
* Add an element to an array using "dot" notation if it doesn't exist.
*
* @param array $array
* @param string $key
* @param mixed $value
*
* @return array
*/
public static function add($array, $key, $value)
{
if (is_null(static::get($array, $key))) {
static::set($array, $key, $value);
}
return $array;
}
/**
* Build a new array using a callback.
*
* @param array $array
* @param \Closure $callback
*
* @return array
*/
public static function build($array, Closure $callback)
{
$results = array();
foreach ($array as $key => $value) {
list($innerKey, $innerValue) = call_user_func($callback, $key, $value);
$results[$innerKey] = $innerValue;
}
return $results;
}
/**
* Divide an array into two arrays. One with keys and the other with values.
*
* @param array $array
*
* @return array
*/
public static function divide($array)
{
return array(
array_keys($array),
array_values($array),
);
}
/**
* Flatten a multi-dimensional associative array with dots.
*
* @param array $array
* @param string $prepend
*
* @return array
*/
public static function dot($array, $prepend = '')
{
$results = array();
foreach ($array as $key => $value) {
if (is_array($value)) {
$results = array_merge($results, static::dot($value, $prepend.$key.'.'));
} else {
$results[$prepend.$key] = $value;
}
}
return $results;
}
/**
* Get all of the given array except for a specified array of items.
*
* @param array $array
* @param array|string $keys
*
* @return array
*/
public static function except($array, $keys)
{
return array_diff_key($array, array_flip((array) $keys));
}
/**
* Fetch a flattened array of a nested array element.
*
* @param array $array
* @param string $key
*
* @return array
*/
public static function fetch($array, $key)
{
$results = array();
foreach (explode('.', $key) as $segment) {
$results = array();
foreach ($array as $value) {
$value = (array) $value;
$results[] = $value[$segment];
}
$array = array_values($results);
}
return array_values($results);
}
/**
* Return the first element in an array passing a given truth test.
*
* @param array $array
* @param \Closure $callback
* @param mixed $default
*
* @return mixed
*/
public static function first($array, $callback, $default = null)
{
foreach ($array as $key => $value) {
if (call_user_func($callback, $key, $value)) {
return $value;
}
}
return $default;
}
/**
* Return the last element in an array passing a given truth test.
*
* @param array $array
* @param \Closure $callback
* @param mixed $default
*
* @return mixed
*/
public static function last($array, $callback, $default = null)
{
return static::first(array_reverse($array), $callback, $default);
}
/**
* Flatten a multi-dimensional array into a single level.
*
* @param array $array
*
* @return array
*/
public static function flatten($array)
{
$return = array();
array_walk_recursive(
$array,
function ($x) use (&$return) {
$return[] = $x;
}
);
return $return;
}
/**
* Remove one or many array items from a given array using "dot" notation.
*
* @param array $array
* @param array|string $keys
*/
public static function forget(&$array, $keys)
{
$original = &$array;
foreach ((array) $keys as $key) {
$parts = explode('.', $key);
while (count($parts) > 1) {
$part = array_shift($parts);
if (isset($array[$part]) && is_array($array[$part])) {
$array = &$array[$part];
}
}
unset($array[array_shift($parts)]);
// clean up after each pass
$array = &$original;
}
}
/**
* Get an item from an array using "dot" notation.
*
* @param array $array
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public static function get($array, $key, $default = null)
{
if (is_null($key)) {
return $array;
}
if (isset($array[$key])) {
return $array[$key];
}
foreach (explode('.', $key) as $segment) {
if (!is_array($array) || !array_key_exists($segment, $array)) {
return $default;
}
$array = $array[$segment];
}
return $array;
}
/**
* Get a subset of the items from the given array.
*
* @param array $array
* @param array|string $keys
*
* @return array
*/
public static function only($array, $keys)
{
return array_intersect_key($array, array_flip((array) $keys));
}
/**
* Pluck an array of values from an array.
*
* @param array $array
* @param string $value
* @param string $key
*
* @return array
*/
public static function pluck($array, $value, $key = null)
{
$results = array();
foreach ($array as $item) {
$itemValue = is_object($item) ? $item->{$value} : $item[$value];
// If the key is "null", we will just append the value to the array and keep
// looping. Otherwise we will key the array using the value of the key we
// received from the developer. Then we'll return the final array form.
if (is_null($key)) {
$results[] = $itemValue;
} else {
$itemKey = is_object($item) ? $item->{$key} : $item[$key];
$results[$itemKey] = $itemValue;
}
}
return $results;
}
/**
* Get a value from the array, and remove it.
*
* @param array $array
* @param string $key
* @param mixed $default
*
* @return mixed
*/
public static function pull(&$array, $key, $default = null)
{
$value = static::get($array, $key, $default);
static::forget($array, $key);
return $value;
}
/**
* Set an array item to a given value using "dot" notation.
*
* If no key is given to the method, the entire array will be replaced.
*
* @param array $array
* @param string $key
* @param mixed $value
*
* @return array
*/
public static function set(&$array, $key, $value)
{
if (is_null($key)) {
return $array = $value;
}
$keys = explode('.', $key);
while (count($keys) > 1) {
$key = array_shift($keys);
// If the key doesn't exist at this depth, we will just create an empty array
// to hold the next value, allowing us to create the arrays to hold final
// values at the correct depth. Then we'll keep digging into the array.
if (!isset($array[$key]) || !is_array($array[$key])) {
$array[$key] = array();
}
$array = &$array[$key];
}
$array[array_shift($keys)] = $value;
return $array;
}
/**
* Sort the array using the given Closure.
*
* @param array $array
* @param \Closure $callback
*
* @return array
*/
public static function sort($array, Closure $callback)
{
$results = array();
foreach ($array as $key => $value) {
$results[$key] = $callback($value);
}
return $results;
}
/**
* Filter the array using the given Closure.
*
* @param array $array
* @param \Closure $callback
*
* @return array
*/
public static function where($array, Closure $callback)
{
$filtered = array();
foreach ($array as $key => $value) {
if (call_user_func($callback, $key, $value)) {
$filtered[$key] = $value;
}
}
return $filtered;
}
}
| JJjie/GuoMei | wechat/src/Wechat/Utils/Arr.php | PHP | mit | 9,324 |
@font-face {
font-family: 'fontello';
src: url('../font/fontello.eot?9377982');
src: url('../font/fontello.eot?9377982#iefix') format('embedded-opentype'),
url('../font/fontello.woff2?9377982') format('woff2'),
url('../font/fontello.woff?9377982') format('woff'),
url('../font/fontello.ttf?9377982') format('truetype'),
url('../font/fontello.svg?9377982#fontello') format('svg');
font-weight: normal;
font-style: normal;
}
/* Chrome hack: SVG is rendered more smooth in Windozze. 100% magic, uncomment if you need it. */
/* Note, that will break hinting! In other OS-es font will be not as sharp as it could be */
/*
@media screen and (-webkit-min-device-pixel-ratio:0) {
@font-face {
font-family: 'fontello';
src: url('../font/fontello.svg?9377982#fontello') format('svg');
}
}
*/
[class^="icon-"]:before, [class*=" icon-"]:before {
font-family: "fontello";
font-style: normal;
font-weight: normal;
speak: none;
display: inline-block;
text-decoration: inherit;
width: 1em;
margin-right: .2em;
text-align: center;
/* opacity: .8; */
/* For safety - reset parent styles, that can break glyph codes*/
font-variant: normal;
text-transform: none;
/* fix buttons height, for twitter bootstrap */
line-height: 1em;
/* Animation center compensation - margins should be symmetric */
/* remove if not needed */
margin-left: .2em;
/* you can be more comfortable with increased icons size */
/* font-size: 120%; */
/* Font smoothing. That was taken from TWBS */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
/* Uncomment for 3D effect */
/* text-shadow: 1px 1px 1px rgba(127, 127, 127, 0.3); */
}
.icon-parking:before { content: '\21'; } /* '!' */
.icon-bedroom:before { content: '\22'; } /* '"' */
.icon-elevator:before { content: '\23'; } /* '#' */
.icon-kettle:before { content: '\24'; } /* '$' */
.icon-pan:before { content: '\25'; } /* '%' */
.icon-tap:before { content: '\26'; } /* '&' */
.icon-foxter:before { content: '\27'; } /* ''' */
.icon-left-circled2:before { content: '\28'; } /* '(' */
.icon-right-circled2:before { content: '\29'; } /* ')' */
.icon-football:before { content: '\2a'; } /* '*' */
.icon-tennis:before { content: '\2b'; } /* '+' */
.icon-chrome:before { content: '\2c'; } /* ',' */
.icon-opera:before { content: '\2d'; } /* '-' */
.icon-crown:before { content: '\2e'; } /* '.' */
.icon-ie:before { content: '\2f'; } /* '/' */
.icon-glass:before { content: '\30'; } /* '0' */
.icon-music:before { content: '\31'; } /* '1' */
.icon-search:before { content: '\32'; } /* '2' */
.icon-360:before { content: '\33'; } /* '3' */
.icon-mail:before { content: '\34'; } /* '4' */
.icon-mail-alt:before { content: '\35'; } /* '5' */
.icon-heart:before { content: '\36'; } /* '6' */
.icon-heart-empty:before { content: '\37'; } /* '7' */
.icon-camera-tour:before { content: '\38'; } /* '8' */
.icon-hubot:before { content: '\39'; } /* '9' */
.icon-squirrel:before { content: '\3a'; } /* ':' */
.icon-clippy:before { content: '\3b'; } /* ';' */
.icon-left-dir:before { content: '\3c'; } /* '<' */
.icon-right-dir:before { content: '\3e'; } /* '>' */
.icon-star-half:before { content: '\3f'; } /* '?' */
.icon-star-half-alt:before { content: '\40'; } /* '@' */
.icon-marquee:before { content: '\41'; } /* 'A' */
.icon-user:before { content: '\42'; } /* 'B' */
.icon-users:before { content: '\43'; } /* 'C' */
.icon-shower:before { content: '\44'; } /* 'D' */
.icon-male:before { content: '\45'; } /* 'E' */
.icon-female:before { content: '\46'; } /* 'F' */
.icon-video:before { content: '\47'; } /* 'G' */
.icon-videocam:before { content: '\48'; } /* 'H' */
.icon-picture:before { content: '\49'; } /* 'I' */
.icon-camera:before { content: '\4a'; } /* 'J' */
.icon-th-large:before { content: '\4b'; } /* 'K' */
.icon-th:before { content: '\4c'; } /* 'L' */
.icon-th-list:before { content: '\4d'; } /* 'M' */
.icon-child:before { content: '\4e'; } /* 'N' */
.icon-ok:before { content: '\4f'; } /* 'O' */
.icon-ok-circled:before { content: '\50'; } /* 'P' */
.icon-ok-squared:before { content: '\51'; } /* 'Q' */
.icon-cancel:before { content: '\52'; } /* 'R' */
.icon-plus:before { content: '\53'; } /* 'S' */
.icon-plus-circled:before { content: '\54'; } /* 'T' */
.icon-plus-squared:before { content: '\55'; } /* 'U' */
.icon-plus-squared-alt:before { content: '\56'; } /* 'V' */
.icon-minus:before { content: '\57'; } /* 'W' */
.icon-minus-circled:before { content: '\58'; } /* 'X' */
.icon-minus-squared:before { content: '\59'; } /* 'Y' */
.icon-minus-squared-alt:before { content: '\5a'; } /* 'Z' */
.icon-left-open:before { content: '\5b'; } /* '[' */
.icon-help-circled:before { content: '\5c'; } /* '\' */
.icon-right-open:before { content: '\5d'; } /* ']' */
.icon-info:before { content: '\5e'; } /* '^' */
.icon-home:before { content: '\5f'; } /* '_' */
.icon-link:before { content: '\60'; } /* '`' */
.icon-unlink:before { content: '\61'; } /* 'a' */
.icon-link-ext:before { content: '\62'; } /* 'b' */
.icon-link-ext-alt:before { content: '\63'; } /* 'c' */
.icon-lock:before { content: '\65'; } /* 'e' */
.icon-lock-open:before { content: '\66'; } /* 'f' */
.icon-cancel-circled:before { content: '\67'; } /* 'g' */
.icon-lock-open-alt:before { content: '\68'; } /* 'h' */
.icon-meteor:before { content: '\69'; } /* 'i' */
.icon-pin:before { content: '\6a'; } /* 'j' */
.icon-eye:before { content: '\6b'; } /* 'k' */
.icon-eye-off:before { content: '\6c'; } /* 'l' */
.icon-gitlab:before { content: '\6d'; } /* 'm' */
.icon-rocketchat:before { content: '\6e'; } /* 'n' */
.icon-repo:before { content: '\6f'; } /* 'o' */
.icon-tag:before { content: '\70'; } /* 'p' */
.icon-spin:before { content: '\71'; } /* 'q' */
.icon-firefox:before { content: '\72'; } /* 'r' */
.icon-tags:before { content: '\73'; } /* 's' */
.icon-bookmark:before { content: '\74'; } /* 't' */
.icon-bookmark-empty:before { content: '\75'; } /* 'u' */
.icon-flag:before { content: '\76'; } /* 'v' */
.icon-flag-empty:before { content: '\77'; } /* 'w' */
.icon-flag-checkered:before { content: '\78'; } /* 'x' */
.icon-thumbs-up:before { content: '\79'; } /* 'y' */
.icon-thumbs-down:before { content: '\7a'; } /* 'z' */
.icon-angle-left:before { content: '\7b'; } /* '{' */
.icon-checklist:before { content: '\7c'; } /* '|' */
.icon-angle-right:before { content: '\7d'; } /* '}' */
.icon-upload:before { content: '\7e'; } /* '~' */
.icon-angle-circled-left:before { content: '\ab'; } /* '«' */
.icon-angle-circled-right:before { content: '\bb'; } /* '»' */
.icon-angle-double-left:before { content: '\2039'; } /* '‹' */
.icon-angle-double-right:before { content: '\203a'; } /* '›' */
.icon-right:before { content: '\2264'; } /* '≤' */
.icon-left:before { content: '\2265'; } /* '≥' */
.icon-left-big:before { content: '\2266'; } /* '≦' */
.icon-right-big:before { content: '\2267'; } /* '≧' */
.icon-right-hand:before { content: '\2268'; } /* '≨' */
.icon-left-hand:before { content: '\2269'; } /* '≩' */
.icon-left-circled:before { content: '\226a'; } /* '≪' */
.icon-right-circled:before { content: '\226b'; } /* '≫' */
.icon-expand-right:before { content: '\2276'; } /* '≶' */
.icon-collapse-left:before { content: '\2277'; } /* '≷' */
.icon-right-open-small:before { content: '\22a2'; } /* '⊢' */
.icon-left-open-small:before { content: '\22a3'; } /* '⊣' */
.icon-download-cloud:before { content: '\e800'; } /* '' */
.icon-upload-cloud:before { content: '\e801'; } /* '' */
.icon-reply:before { content: '\e802'; } /* '' */
.icon-reply-all:before { content: '\e803'; } /* '' */
.icon-forward:before { content: '\e804'; } /* '' */
.icon-quote-left:before { content: '\e805'; } /* '' */
.icon-quote-right:before { content: '\e806'; } /* '' */
.icon-code:before { content: '\e807'; } /* '' */
.icon-export:before { content: '\e808'; } /* '' */
.icon-export-alt:before { content: '\e809'; } /* '' */
.icon-share:before { content: '\e80a'; } /* '' */
.icon-share-squared:before { content: '\e80b'; } /* '' */
.icon-pencil:before { content: '\e80c'; } /* '' */
.icon-pencil-squared:before { content: '\e80d'; } /* '' */
.icon-edit:before { content: '\e80e'; } /* '' */
.icon-print:before { content: '\e80f'; } /* '' */
.icon-retweet:before { content: '\e810'; } /* '' */
.icon-keyboard:before { content: '\e811'; } /* '' */
.icon-gamepad:before { content: '\e812'; } /* '' */
.icon-comment:before { content: '\e813'; } /* '' */
.icon-chat:before { content: '\e814'; } /* '' */
.icon-comment-empty:before { content: '\e815'; } /* '' */
.icon-chat-empty:before { content: '\e816'; } /* '' */
.icon-bell:before { content: '\e817'; } /* '' */
.icon-bell-alt:before { content: '\e818'; } /* '' */
.icon-bell-off:before { content: '\e819'; } /* '' */
.icon-bell-off-empty:before { content: '\e81a'; } /* '' */
.icon-attention-alt:before { content: '\e81b'; } /* '' */
.icon-attention:before { content: '\e81c'; } /* '' */
.icon-attention-circled:before { content: '\e81d'; } /* '' */
.icon-location:before { content: '\e81e'; } /* '' */
.icon-direction:before { content: '\e81f'; } /* '' */
.icon-compass:before { content: '\e820'; } /* '' */
.icon-trash-alt:before { content: '\e821'; } /* '' */
.icon-trash:before { content: '\e822'; } /* '' */
.icon-doc:before { content: '\e823'; } /* '' */
.icon-docs:before { content: '\e824'; } /* '' */
.icon-doc-text:before { content: '\e825'; } /* '' */
.icon-doc-inv:before { content: '\e826'; } /* '' */
.icon-doc-text-inv:before { content: '\e827'; } /* '' */
.icon-folder:before { content: '\e828'; } /* '' */
.icon-folder-open:before { content: '\e829'; } /* '' */
.icon-folder-empty:before { content: '\e82a'; } /* '' */
.icon-folder-open-empty:before { content: '\e82b'; } /* '' */
.icon-box:before { content: '\e82c'; } /* '' */
.icon-rss:before { content: '\e82d'; } /* '' */
.icon-rss-squared:before { content: '\e82e'; } /* '' */
.icon-phone:before { content: '\e82f'; } /* '' */
.icon-phone-squared:before { content: '\e830'; } /* '' */
.icon-fax:before { content: '\e831'; } /* '' */
.icon-menu:before { content: '\e832'; } /* '' */
.icon-cog:before { content: '\e833'; } /* '' */
.icon-cog-alt:before { content: '\e834'; } /* '' */
.icon-wrench:before { content: '\e835'; } /* '' */
.icon-sliders:before { content: '\e836'; } /* '' */
.icon-basket:before { content: '\e837'; } /* '' */
.icon-calendar:before { content: '\e838'; } /* '' */
.icon-calendar-empty:before { content: '\e839'; } /* '' */
.icon-login:before { content: '\e83a'; } /* '' */
.icon-logout:before { content: '\e83b'; } /* '' */
.icon-mic:before { content: '\e83c'; } /* '' */
.icon-mute:before { content: '\e83d'; } /* '' */
.icon-volume-off:before { content: '\e83e'; } /* '' */
.icon-volume-down:before { content: '\e83f'; } /* '' */
.icon-volume-up:before { content: '\e840'; } /* '' */
.icon-headphones:before { content: '\e841'; } /* '' */
.icon-clock:before { content: '\e842'; } /* '' */
.icon-lightbulb:before { content: '\e843'; } /* '' */
.icon-block:before { content: '\e844'; } /* '' */
.icon-resize-full:before { content: '\e845'; } /* '' */
.icon-resize-full-alt:before { content: '\e846'; } /* '' */
.icon-resize-small:before { content: '\e847'; } /* '' */
.icon-resize-vertical:before { content: '\e848'; } /* '' */
.icon-resize-horizontal:before { content: '\e849'; } /* '' */
.icon-move:before { content: '\e84a'; } /* '' */
.icon-zoom-in:before { content: '\e84b'; } /* '' */
.icon-zoom-out:before { content: '\e84c'; } /* '' */
.icon-down-circled2:before { content: '\e84d'; } /* '' */
.icon-up-circled2:before { content: '\e84e'; } /* '' */
.icon-help:before { content: '\e84f'; } /* '' */
.icon-info-circled:before { content: '\e850'; } /* '' */
.icon-down-dir:before { content: '\e851'; } /* '' */
.icon-up-dir:before { content: '\e852'; } /* '' */
.icon-star:before { content: '\e853'; } /* '' */
.icon-star-empty:before { content: '\e854'; } /* '' */
.icon-down-open:before { content: '\e855'; } /* '' */
.icon-gym:before { content: '\e856'; } /* '' */
.icon-sports:before { content: '\e857'; } /* '' */
.icon-up-open:before { content: '\e858'; } /* '' */
.icon-browser:before { content: '\e859'; } /* '' */
.icon-download:before { content: '\e85a'; } /* '' */
.icon-angle-up:before { content: '\e85b'; } /* '' */
.icon-angle-down:before { content: '\e85c'; } /* '' */
.icon-language:before { content: '\e85d'; } /* '' */
.icon-angle-circled-up:before { content: '\e85f'; } /* '' */
.icon-angle-circled-down:before { content: '\e860'; } /* '' */
.icon-angle-double-up:before { content: '\e863'; } /* '' */
.icon-angle-double-down:before { content: '\e864'; } /* '' */
.icon-down:before { content: '\e865'; } /* '' */
.icon-up:before { content: '\e868'; } /* '' */
.icon-down-big:before { content: '\e869'; } /* '' */
.icon-up-big:before { content: '\e86c'; } /* '' */
.icon-up-hand:before { content: '\e86f'; } /* '' */
.icon-down-hand:before { content: '\e870'; } /* '' */
.icon-up-circled:before { content: '\e873'; } /* '' */
.icon-down-circled:before { content: '\e874'; } /* '' */
.icon-cw:before { content: '\e875'; } /* '' */
.icon-ccw:before { content: '\e876'; } /* '' */
.icon-arrows-cw:before { content: '\e877'; } /* '' */
.icon-level-up:before { content: '\e878'; } /* '' */
.icon-level-down:before { content: '\e879'; } /* '' */
.icon-shuffle:before { content: '\e87a'; } /* '' */
.icon-exchange:before { content: '\e87b'; } /* '' */
.icon-history:before { content: '\e87c'; } /* '' */
.icon-expand:before { content: '\e87d'; } /* '' */
.icon-collapse:before { content: '\e87e'; } /* '' */
.icon-play:before { content: '\e881'; } /* '' */
.icon-play-circled:before { content: '\e882'; } /* '' */
.icon-play-circled2:before { content: '\e883'; } /* '' */
.icon-stop:before { content: '\e884'; } /* '' */
.icon-pause:before { content: '\e885'; } /* '' */
.icon-to-end:before { content: '\e886'; } /* '' */
.icon-to-end-alt:before { content: '\e887'; } /* '' */
.icon-to-start:before { content: '\e888'; } /* '' */
.icon-to-start-alt:before { content: '\e889'; } /* '' */
.icon-fast-fw:before { content: '\e88a'; } /* '' */
.icon-fast-bw:before { content: '\e88b'; } /* '' */
.icon-eject:before { content: '\e88c'; } /* '' */
.icon-target:before { content: '\e88d'; } /* '' */
.icon-signal:before { content: '\e88e'; } /* '' */
.icon-award:before { content: '\e88f'; } /* '' */
.icon-desktop:before { content: '\e890'; } /* '' */
.icon-laptop:before { content: '\e891'; } /* '' */
.icon-tablet:before { content: '\e892'; } /* '' */
.icon-mobile:before { content: '\e893'; } /* '' */
.icon-inbox:before { content: '\e894'; } /* '' */
.icon-globe:before { content: '\e895'; } /* '' */
.icon-sun:before { content: '\e896'; } /* '' */
.icon-cloud:before { content: '\e897'; } /* '' */
.icon-flash:before { content: '\e898'; } /* '' */
.icon-moon:before { content: '\e899'; } /* '' */
.icon-umbrella:before { content: '\e89a'; } /* '' */
.icon-flight:before { content: '\e89b'; } /* '' */
.icon-tasklist:before { content: '\e89c'; } /* '' */
.icon-paper-plane:before { content: '\e89d'; } /* '' */
.icon-leaf:before { content: '\e89e'; } /* '' */
.icon-font:before { content: '\e89f'; } /* '' */
.icon-bold:before { content: '\e8a0'; } /* '' */
.icon-italic:before { content: '\e8a1'; } /* '' */
.icon-paragraph:before { content: '\e8a2'; } /* '' */
.icon-text-height:before { content: '\e8a3'; } /* '' */
.icon-text-width:before { content: '\e8a4'; } /* '' */
.icon-align-left:before { content: '\e8a5'; } /* '' */
.icon-align-center:before { content: '\e8a6'; } /* '' */
.icon-align-right:before { content: '\e8a7'; } /* '' */
.icon-align-justify:before { content: '\e8a8'; } /* '' */
.icon-list:before { content: '\e8a9'; } /* '' */
.icon-indent-left:before { content: '\e8aa'; } /* '' */
.icon-indent-right:before { content: '\e8ab'; } /* '' */
.icon-list-bullet:before { content: '\e8ac'; } /* '' */
.icon-list-numbered:before { content: '\e8ad'; } /* '' */
.icon-strike:before { content: '\e8ae'; } /* '' */
.icon-underline:before { content: '\e8af'; } /* '' */
.icon-superscript:before { content: '\e8b0'; } /* '' */
.icon-subscript:before { content: '\e8b1'; } /* '' */
.icon-table:before { content: '\e8b2'; } /* '' */
.icon-columns:before { content: '\e8b3'; } /* '' */
.icon-crop:before { content: '\e8b4'; } /* '' */
.icon-scissors:before { content: '\e8b5'; } /* '' */
.icon-paste:before { content: '\e8b6'; } /* '' */
.icon-briefcase:before { content: '\e8b7'; } /* '' */
.icon-suitcase:before { content: '\e8b8'; } /* '' */
.icon-ellipsis:before { content: '\e8b9'; } /* '' */
.icon-ellipsis-vert:before { content: '\e8ba'; } /* '' */
.icon-off:before { content: '\e8bb'; } /* '' */
.icon-road:before { content: '\e8bc'; } /* '' */
.icon-list-alt:before { content: '\e8bd'; } /* '' */
.icon-qrcode:before { content: '\e8be'; } /* '' */
.icon-barcode:before { content: '\e8bf'; } /* '' */
.icon-book:before { content: '\e8c0'; } /* '' */
.icon-ajust:before { content: '\e8c1'; } /* '' */
.icon-tint:before { content: '\e8c2'; } /* '' */
.icon-toggle-off:before { content: '\e8c3'; } /* '' */
.icon-toggle-on:before { content: '\e8c4'; } /* '' */
.icon-check:before { content: '\e8c5'; } /* '' */
.icon-check-empty:before { content: '\e8c6'; } /* '' */
.icon-circle:before { content: '\e8c7'; } /* '' */
.icon-circle-empty:before { content: '\e8c8'; } /* '' */
.icon-circle-notch:before { content: '\e8c9'; } /* '' */
.icon-dot-circled:before { content: '\e8ca'; } /* '' */
.icon-asterisk:before { content: '\e8cb'; } /* '' */
.icon-gift:before { content: '\e8cc'; } /* '' */
.icon-fire:before { content: '\e8cd'; } /* '' */
.icon-magnet:before { content: '\e8ce'; } /* '' */
.icon-chart-bar:before { content: '\e8cf'; } /* '' */
.icon-chart-area:before { content: '\e8d0'; } /* '' */
.icon-chart-pie:before { content: '\e8d1'; } /* '' */
.icon-chart-line:before { content: '\e8d2'; } /* '' */
.icon-ticket:before { content: '\e8d3'; } /* '' */
.icon-credit-card:before { content: '\e8d4'; } /* '' */
.icon-floppy:before { content: '\e8d5'; } /* '' */
.icon-megaphone:before { content: '\e8d6'; } /* '' */
.icon-hdd:before { content: '\e8d7'; } /* '' */
.icon-fork:before { content: '\e8d9'; } /* '' */
.icon-rocket:before { content: '\e8da'; } /* '' */
.icon-bug:before { content: '\e8db'; } /* '' */
.icon-certificate:before { content: '\e8dc'; } /* '' */
.icon-tasks:before { content: '\e8dd'; } /* '' */
.icon-filter:before { content: '\e8de'; } /* '' */
.icon-beaker:before { content: '\e8df'; } /* '' */
.icon-magic:before { content: '\e8e0'; } /* '' */
.icon-cab:before { content: '\e8e1'; } /* '' */
.icon-taxi:before { content: '\e8e2'; } /* '' */
.icon-truck:before { content: '\e8e3'; } /* '' */
.icon-bus:before { content: '\e8e4'; } /* '' */
.icon-bicycle:before { content: '\e8e5'; } /* '' */
.icon-money:before { content: '\e8e6'; } /* '' */
.icon-euro:before { content: '\e8e7'; } /* '' */
.icon-pound:before { content: '\e8e8'; } /* '' */
.icon-dollar:before { content: '\e8e9'; } /* '' */
.icon-sort:before { content: '\e8ea'; } /* '' */
.icon-sort-down:before { content: '\e8eb'; } /* '' */
.icon-sort-up:before { content: '\e8ec'; } /* '' */
.icon-sort-alt-up:before { content: '\e8ed'; } /* '' */
.icon-sort-alt-down:before { content: '\e8ee'; } /* '' */
.icon-sort-name-up:before { content: '\e8ef'; } /* '' */
.icon-sort-name-down:before { content: '\e8f0'; } /* '' */
.icon-sort-number-up:before { content: '\e8f1'; } /* '' */
.icon-sort-number-down:before { content: '\e8f2'; } /* '' */
.icon-hammer:before { content: '\e8f3'; } /* '' */
.icon-gauge:before { content: '\e8f4'; } /* '' */
.icon-sitemap:before { content: '\e8f5'; } /* '' */
.icon-spinner:before { content: '\e8f6'; } /* '' */
.icon-coffee:before { content: '\e8f7'; } /* '' */
.icon-food:before { content: '\e8f8'; } /* '' */
.icon-beer:before { content: '\e8f9'; } /* '' */
.icon-user-md:before { content: '\e8fa'; } /* '' */
.icon-stethoscope:before { content: '\e8fb'; } /* '' */
.icon-ambulance:before { content: '\e8fc'; } /* '' */
.icon-medkit:before { content: '\e8fd'; } /* '' */
.icon-h-sigh:before { content: '\e8fe'; } /* '' */
.icon-hospital:before { content: '\e8ff'; } /* '' */
.icon-building:before { content: '\e900'; } /* '' */
.icon-building-filled:before { content: '\e901'; } /* '' */
.icon-bank:before { content: '\e902'; } /* '' */
.icon-smile:before { content: '\e903'; } /* '' */
.icon-frown:before { content: '\e904'; } /* '' */
.icon-meh:before { content: '\e905'; } /* '' */
.icon-anchor:before { content: '\e906'; } /* '' */
.icon-terminal:before { content: '\e907'; } /* '' */
.icon-eraser:before { content: '\e908'; } /* '' */
.icon-puzzle:before { content: '\e909'; } /* '' */
.icon-shield:before { content: '\e90a'; } /* '' */
.icon-extinguisher:before { content: '\e90b'; } /* '' */
.icon-bullseye:before { content: '\e90c'; } /* '' */
.icon-wheelchair:before { content: '\e90d'; } /* '' */
.icon-attach:before { content: '\e90e'; } /* '' */
.icon-paw:before { content: '\e90f'; } /* '' */
.icon-spoon:before { content: '\e910'; } /* '' */
.icon-cube:before { content: '\e911'; } /* '' */
.icon-cubes:before { content: '\e912'; } /* '' */
.icon-recycle:before { content: '\e913'; } /* '' */
.icon-tree:before { content: '\e914'; } /* '' */
.icon-database:before { content: '\e915'; } /* '' */
.icon-lifebuoy:before { content: '\e916'; } /* '' */
.icon-birthday:before { content: '\e917'; } /* '' */
.icon-adn:before { content: '\e918'; } /* '' */
.icon-android:before { content: '\e919'; } /* '' */
.icon-angellist:before { content: '\e91a'; } /* '' */
.icon-apple:before { content: '\e91b'; } /* '' */
.icon-behance:before { content: '\e91c'; } /* '' */
.icon-bitbucket:before { content: '\e91d'; } /* '' */
.icon-bitbucket-squared:before { content: '\e91e'; } /* '' */
.icon-css3:before { content: '\e91f'; } /* '' */
.icon-delicious:before { content: '\e920'; } /* '' */
.icon-digg:before { content: '\e921'; } /* '' */
.icon-dribbble:before { content: '\e922'; } /* '' */
.icon-dropbox:before { content: '\e923'; } /* '' */
.icon-facebook:before { content: '\e924'; } /* '' */
.icon-facebook-squared:before { content: '\e925'; } /* '' */
.icon-flickr:before { content: '\e926'; } /* '' */
.icon-foursquare:before { content: '\e927'; } /* '' */
.icon-git-squared:before { content: '\e928'; } /* '' */
.icon-github-circled:before { content: '\e929'; } /* '' */
.icon-gittip:before { content: '\e92a'; } /* '' */
.icon-google:before { content: '\e92b'; } /* '' */
.icon-gplus:before { content: '\e92c'; } /* '' */
.icon-gplus-squared:before { content: '\e92d'; } /* '' */
.icon-html5:before { content: '\e92e'; } /* '' */
.icon-instagramm:before { content: '\e92f'; } /* '' */
.icon-linkedin-squared:before { content: '\e930'; } /* '' */
.icon-linux:before { content: '\e931'; } /* '' */
.icon-linkedin:before { content: '\e932'; } /* '' */
.icon-pagelines:before { content: '\e933'; } /* '' */
.icon-pied-piper-squared:before { content: '\e934'; } /* '' */
.icon-pinterest-circled:before { content: '\e935'; } /* '' */
.icon-pinterest-squared:before { content: '\e936'; } /* '' */
.icon-renren:before { content: '\e937'; } /* '' */
.icon-skype:before { content: '\e938'; } /* '' */
.icon-slideshare:before { content: '\e939'; } /* '' */
.icon-stackexchange:before { content: '\e93a'; } /* '' */
.icon-stackoverflow:before { content: '\e93b'; } /* '' */
.icon-trello:before { content: '\e93c'; } /* '' */
.icon-tumblr:before { content: '\e93d'; } /* '' */
.icon-tumblr-squared:before { content: '\e93e'; } /* '' */
.icon-twitter-squared:before { content: '\e93f'; } /* '' */
.icon-twitter:before { content: '\e940'; } /* '' */
.icon-vimeo-squared:before { content: '\e941'; } /* '' */
.icon-windows:before { content: '\e942'; } /* '' */
.icon-wordpress:before { content: '\e943'; } /* '' */
.icon-youtube:before { content: '\e944'; } /* '' */
.icon-youtube-squared:before { content: '\e945'; } /* '' */
.icon-youtube-play:before { content: '\e946'; } /* '' */
.icon-blank:before { content: '\e947'; } /* '' */
.icon-lemon:before { content: '\e948'; } /* '' */
.icon-note:before { content: '\e949'; } /* '' */
.icon-note-beamed:before { content: '\e94a'; } /* '' */
.icon-alert:before { content: '\e94c'; } /* '' */
.icon-graduation-cap:before { content: '\e94f'; } /* '' */
.icon-water:before { content: '\e950'; } /* '' */
.icon-droplet:before { content: '\e951'; } /* '' */
.icon-key:before { content: '\e952'; } /* '' */
.icon-infinity:before { content: '\e953'; } /* '' */
.icon-at:before { content: '\e956'; } /* '' */
.icon-money-bag:before { content: '\e957'; } /* '' */
.icon-hash:before { content: '\e958'; } /* '' */
.icon-airport:before { content: '\e959'; } /* '' */
.icon-fast-food:before { content: '\e95a'; } /* '' */
.icon-fuel:before { content: '\e95b'; } /* '' */
.icon-police:before { content: '\e95c'; } /* '' */
.icon-religious-christian:before { content: '\e95d'; } /* '' */
.icon-religious-islam:before { content: '\e95e'; } /* '' */
.icon-religious-jewish:before { content: '\e95f'; } /* '' */
.icon-school:before { content: '\e960'; } /* '' */
.icon-swimming:before { content: '\e961'; } /* '' */
.icon-toilet:before { content: '\e962'; } /* '' */
.icon-universal-access:before { content: '\e964'; } /* '' */
.icon-travel:before { content: '\e966'; } /* '' */
.icon-symbols:before { content: '\e967'; } /* '' */
.icon-recent:before { content: '\e968'; } /* '' */
.icon-people:before { content: '\e969'; } /* '' */
.icon-objects:before { content: '\e96a'; } /* '' */
.icon-nature:before { content: '\e96b'; } /* '' */
.icon-foods:before { content: '\e96c'; } /* '' */
.icon-activity:before { content: '\e96d'; } /* '' */
.icon-flags:before { content: '\e96e'; } /* '' */
.icon-people-plus:before { content: '\e96f'; } /* '' */
.icon-file-pdf:before { content: '\e970'; } /* '' */
.icon-file-word:before { content: '\e971'; } /* '' */
.icon-file-excel:before { content: '\e972'; } /* '' */
.icon-file-powerpoint:before { content: '\e973'; } /* '' */
.icon-file-image:before { content: '\e974'; } /* '' */
.icon-file-archive:before { content: '\e975'; } /* '' */
.icon-file-audio:before { content: '\e976'; } /* '' */
.icon-file-video:before { content: '\e977'; } /* '' */
.icon-file-code:before { content: '\e978'; } /* '' */
.icon-issue-closed:before { content: '\e979'; } /* '' */
.icon-issue-opened:before { content: '\e97a'; } /* '' */
.icon-issue-reopened:before { content: '\e97b'; } /* '' */
.icon-milestone:before { content: '\e97c'; } /* '' */
.icon-mirror:before { content: '\e97d'; } /* '' */
.icon-plug:before { content: '\e97e'; } /* '' */
.icon-repo-forked:before { content: '\e980'; } /* '' */
.icon-repo-pull:before { content: '\e981'; } /* '' */
.icon-repo-push:before { content: '\e982'; } /* '' */
.icon-shield-key:before { content: '\e983'; } /* '' */
.icon-repo-clone:before { content: '\e984'; } /* '' */
.icon-repo-force-push:before { content: '\e985'; } /* '' */
.icon-unverified:before { content: '\e986'; } /* '' */
.icon-verified:before { content: '\e987'; } /* '' */
.icon-zap:before { content: '\e988'; } /* '' */
.icon-pulse:before { content: '\e989'; } /* '' */
.icon-versions:before { content: '\e98a'; } /* '' */
.icon-text-size:before { content: '\e98b'; } /* '' */
.icon-markdown:before { content: '\e98c'; } /* '' */
.icon-no-newline:before { content: '\e98d'; } /* '' */
.icon-tools:before { content: '\e98e'; } /* '' */
.icon-tape:before { content: '\e98f'; } /* '' */ | pkgodara/Rocket.Chat | packages/rocketchat_theme/client/vendor/fontello/css/fontello.css | CSS | mit | 28,632 |
/* linux/arch/arm/mach-s5pv210/pd-s5pv210.c
*
* Copyright (c) 2010 Samsung Electronics Co., Ltd.
* http://www.samsung.com/
*
* based on linux/arch/arm/plat-samsung/clock.c
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*/
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/io.h>
#include <linux/spinlock.h>
#include <linux/string.h>
#include <linux/delay.h>
#include <linux/module.h>
#include <mach/pd.h>
#include <mach/regs-clock.h>
static LIST_HEAD(pd_domains);
DEFINE_SPINLOCK(pd_lock);
static int s5pv210_pd_clk_on(struct pd_domain *pd)
{
struct pd_domain *p;
struct power_domain *parent_p;
u32 tmp;
parent_p = pd->parent_pd;
list_for_each_entry(p, &pd_domains, list) {
if ((p->parent_pd) == parent_p) {
tmp = __raw_readl(p->clk_reg);
tmp |= (p->clk_bit);
__raw_writel(tmp, p->clk_reg);
}
}
return 0;
}
static int s5pv210_pd_clk_off(struct pd_domain *pd)
{
struct pd_domain *p;
struct power_domain *parent_p;
u32 tmp;
parent_p = pd->parent_pd;
list_for_each_entry(p, &pd_domains, list) {
if ((p->parent_pd) == parent_p) {
tmp = __raw_readl(p->clk_reg);
tmp &= ~(p->clk_bit);
__raw_writel(tmp, p->clk_reg);
}
}
return 0;
}
static int s5pv210_pd_ctrl(struct pd_domain *pd, int enable)
{
struct power_domain *parent_p;
u32 pd_status;
parent_p = pd->parent_pd;
pd_status = __raw_readl(S5P_NORMAL_CFG);
/*
* Before turn on some power domain, every clocks which were
* depended on power domain must turned on.
*/
if (enable == PD_ACTIVE) {
parent_p->usage++;
if (!(pd_status&parent_p->ctrlbit)) {
s5pv210_pd_clk_on(pd);
pd_status |= (parent_p->ctrlbit);
__raw_writel(pd_status, S5P_NORMAL_CFG);
s5pv210_pd_clk_off(pd);
udelay(PD_CLOCK_TIME);
}
} else if (enable == PD_INACTIVE) {
parent_p->usage--;
if (parent_p->usage == 0) {
pd_status &= ~(parent_p->ctrlbit);
__raw_writel(pd_status, S5P_NORMAL_CFG);
}
}
return 0;
}
struct pd_domain *s5pv210_pd_find(const char *id)
{
struct pd_domain *p;
struct pd_domain *check_pd = 0;
spin_lock(&pd_lock);
list_for_each_entry(p, &pd_domains, list) {
if (strcmp(id, p->name) == 0) {
check_pd = p;
break;
}
}
spin_unlock(&pd_lock);
return check_pd;
}
int s5pv210_pd_enable(const char *id)
{
#if 0
struct pd_domain *pd_p;
pd_p = s5pv210_pd_find(id);
if (!(pd_p)) {
printk(KERN_ERR "%s:Can not find %s\n", __func__, id);
return -EINVAL;
}
spin_lock(&pd_lock);
(pd_p->enable)(pd_p, 1);
spin_unlock(&pd_lock);
#endif
return 0;
}
EXPORT_SYMBOL(s5pv210_pd_enable);
int s5pv210_pd_disable(const char *id)
{
#if 0
struct pd_domain *pd_p;
pd_p = s5pv210_pd_find(id);
if (!(pd_p)) {
printk(KERN_ERR "%s:Can not find %s\n", __func__, id);
return -EINVAL;
}
spin_lock(&pd_lock);
(pd_p->enable)(pd_p, 0);
spin_unlock(&pd_lock);
#endif
return 0;
}
EXPORT_SYMBOL(s5pv210_pd_disable);
static struct power_domain pd_cam = {
.nr_clks = 0,
.usage = 0,
.ctrlbit = S5PV210_PD_CAM,
};
static struct power_domain pd_tv = {
.nr_clks = 0,
.usage = 0,
.ctrlbit = S5PV210_PD_TV,
};
static struct power_domain pd_lcd = {
.nr_clks = 0,
.usage = 0,
.ctrlbit = S5PV210_PD_LCD,
};
static struct power_domain pd_audio = {
.nr_clks = 0,
.usage = 0,
.ctrlbit = S5PV210_PD_AUDIO,
};
static struct power_domain pd_g3d = {
.nr_clks = 0,
.usage = 0,
.ctrlbit = S5PV210_PD_G3D,
};
static struct power_domain pd_mfc = {
.nr_clks = 0,
.usage = 0,
.ctrlbit = S5PV210_PD_MFC,
};
static struct pd_domain init_pd[] = {
{
.name = "fimc_pd",
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = ((1<<24)|(1<<25)|(1<<26)),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_cam,
}, {
.name = "csis_pd",
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = (1<<31),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_cam,
}, {
.name = "jpeg_pd",
#if defined(CONFIG_CPU_S5PV210_EVT1)
.clk_reg = S5P_CLKGATE_IP5,
.clk_bit = (1<<29),
#else
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = (1<<28),
#endif
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_cam,
}, {
.name = "rotator_pd",
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = (1<<29),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_cam,
}, {
.name = "vp_pd",
.clk_reg = S5P_CLKGATE_IP1,
.clk_bit = (1<<8),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_tv,
}, {
.name = "mixer_pd",
.clk_reg = S5P_CLKGATE_IP1,
.clk_bit = (1<<9),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_tv,
}, {
.name = "tv_enc_pd",
.clk_reg = S5P_CLKGATE_IP1,
.clk_bit = (1<<10),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_tv,
}, {
.name = "hdmi_pd",
.clk_reg = S5P_CLKGATE_IP1,
.clk_bit = (1<<11),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_tv,
}, {
.name = "fimd_pd",
.clk_reg = S5P_CLKGATE_IP1,
.clk_bit = (1<<0),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_lcd,
}, {
.name = "dsim_pd",
.clk_reg = S5P_CLKGATE_IP1,
.clk_bit = (1<<2),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_lcd,
}, {
.name = "g2d_pd",
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = (1<<12),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_lcd,
}, {
.name = "g3d_pd",
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = (1<<8),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_g3d,
}, {
.name = "mfc_pd",
.clk_reg = S5P_CLKGATE_IP0,
.clk_bit = (1<<16),
.enable = s5pv210_pd_ctrl,
.parent_pd = &pd_mfc,
},
};
static int s5pv210_register_pd(struct pd_domain *pd)
{
spin_lock(&pd_lock);
list_add(&pd->list, &pd_domains);
spin_unlock(&pd_lock);
return 0;
}
static void s5pv210_register_pds(void)
{
struct pd_domain *pd_p;
int liter;
int ret;
pd_p = init_pd;
for (liter = 0 ; liter < ARRAY_SIZE(init_pd) ; liter++, pd_p++) {
ret = s5pv210_register_pd(pd_p);
if (ret < 0)
printk(KERN_INFO "Failed to regster pd domain %s : %d",
pd_p->name, ret);
}
}
static int __init s5pv210_pd_init(void)
{
printk(KERN_INFO "S5PV210 Power Domain API Enable\n");
#if 0
s5pv210_register_pds();
/* All Power Domain always on by temporary */
s5pv210_pd_enable("camera_pd");
s5pv210_pd_enable("csis_pd");
s5pv210_pd_enable("jpeg_pd");
s5pv210_pd_enable("rotator_pd");
s5pv210_pd_enable("vp_pd");
s5pv210_pd_enable("mixer_pd");
s5pv210_pd_enable("tv_enc_pd");
s5pv210_pd_enable("hdmi_pd");
s5pv210_pd_enable("fimd_pd");
s5pv210_pd_enable("dsim_pd");
s5pv210_pd_enable("g2d_pd");
s5pv210_pd_enable("g3d_pd");
s5pv210_pd_enable("mfc_pd");
#if 0
s5pv210_pd_disable("camera_pd");
s5pv210_pd_disable("csis_pd");
s5pv210_pd_disable("jpeg_pd");
s5pv210_pd_disable("rotator_pd");
s5pv210_pd_disable("vp_pd");
s5pv210_pd_disable("mixer_pd");
s5pv210_pd_disable("tv_enc_pd");
s5pv210_pd_disable("hdmi_pd");
s5pv210_pd_disable("fimd_pd");
s5pv210_pd_disable("dsim_pd");
s5pv210_pd_disable("g2d_pd");
s5pv210_pd_disable("g3d_pd");
s5pv210_pd_disable("mfc_pd");
#endif
#endif
return 0;
}
arch_initcall(s5pv210_pd_init);
| barakinflorida/Vibrant-open | arch/arm/mach-s5pv210/pd.c | C | gpl-2.0 | 7,116 |
// Copyright (C) 2011 Davis E. King ([email protected])
// License: Boost Software License See LICENSE.txt for the full license.
#include <sstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <cmath>
#include <dlib/crc32.h>
#include "tester.h"
namespace
{
using namespace test;
using namespace dlib;
using namespace std;
logger dlog("test.crc32");
class crc32_tester : public tester
{
public:
crc32_tester (
) :
tester ("test_crc32",
"Runs tests on the crc32 component.")
{}
void perform_test (
)
{
DLIB_TEST(crc32("davis").get_checksum() == 0x0445527C);
crc32 c, c2;
DLIB_TEST(c.get_checksum() == 0);
c.add("davis");
DLIB_TEST(c.get_checksum() == 0x0445527C);
DLIB_TEST(c2.get_checksum() == 0);
c2 = c;
DLIB_TEST(c2.get_checksum() == 0x0445527C);
crc32 c3(c);
DLIB_TEST(c3.get_checksum() == 0x0445527C);
c.add('a');
c2.add('a');
c3.add('a');
DLIB_TEST(c.get_checksum() == 0xB100C606);
DLIB_TEST(c2.get_checksum() == 0xB100C606);
DLIB_TEST(c3.get_checksum() == 0xB100C606);
crc32::kernel_1a cold;
DLIB_TEST(cold.get_checksum() == 0);
cold.add("davis");
DLIB_TEST(cold.get_checksum() == 0x0445527C);
c.clear();
DLIB_TEST(c.get_checksum() == 0);
c.add("davis");
DLIB_TEST(c.get_checksum() == 0x0445527C);
std::vector<char> buf;
for (int i = 0; i < 4000; ++i)
buf.push_back(i);
DLIB_TEST(crc32(buf) == 492662731);
}
} a;
}
| abalckin/cwavenet | wavenet/dlib/test/crc32.cpp | C++ | gpl-2.0 | 1,818 |
<?php
/**
*
* Description
*
* @package VirtueMart
* @subpackage Country
* @author RickG
* @link http://www.virtuemart.net
* @copyright Copyright (c) 2004 - 2010 VirtueMart Team. All rights reserved.
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* VirtueMart is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* @version $Id: default.php 8534 2014-10-28 10:23:03Z Milbo $
*/
// Check to ensure this file is included in Joomla!
defined('_JEXEC') or die('Restricted access');
AdminUIHelper::startAdminArea($this);
$states = vmText::_('COM_VIRTUEMART_STATE_S');
?>
<form action="index.php" method="post" name="adminForm" id="adminForm">
<div id="header">
<div id="filterbox">
<table>
<tr>
<td align="left" width="100%">
<?php echo vmText::_('COM_VIRTUEMART_FILTER') ?>:
<input type="text" value="<?php echo vRequest::getVar('filter_country'); ?>" name="filter_country" size="25" />
<button class="btn btn-small" onclick="this.form.submit();"><?php echo vmText::_('COM_VIRTUEMART_GO'); ?></button>
</td>
</tr>
</table>
</div>
<div id="resultscounter"><?php echo $this->pagination->getResultsCounter();?></div>
</div>
<div id="editcell">
<table class="adminlist table table-striped" cellspacing="0" cellpadding="0">
<thead>
<tr>
<th class="admin-checkbox">
<input type="checkbox" name="toggle" value="" onclick="Joomla.checkAll(this)" />
</th>
<th>
<?php echo $this->sort('country_name') ?>
</th>
<?php /* TODO not implemented <th>
<?php echo vmText::_('COM_VIRTUEMART_ZONE_ASSIGN_CURRENT_LBL'); ?>
</th> */ ?>
<th>
<?php echo $this->sort('country_2_code') ?>
</th>
<th>
<?php echo $this->sort('country_3_code') ?>
</th>
<th width="20">
<?php echo vmText::_('COM_VIRTUEMART_PUBLISHED'); ?>
</th>
<th width="20">
<?php echo $this->sort('virtuemart_country_id') ?>
</th>
</tr>
</thead>
<?php
$k = 0;
for ($i=0, $n=count( $this->countries ); $i < $n; $i++) {
$row = $this->countries[$i];
$checked = JHtml::_('grid.id', $i, $row->virtuemart_country_id);
$published = $this->gridPublished( $row, $i );
$editlink = JROUTE::_('index.php?option=com_virtuemart&view=country&task=edit&cid[]=' . $row->virtuemart_country_id);
$statelink = JROUTE::_('index.php?option=com_virtuemart&view=state&view=state&virtuemart_country_id=' . $row->virtuemart_country_id);
?>
<tr class="row<?php echo $k ; ?>">
<td class="admin-checkbox">
<?php echo $checked; ?>
</td>
<td align="left">
<?php
$prefix="COM_VIRTUEMART_COUNTRY_";
$country_string= vmText::_($prefix.$row->country_3_code); ?>
<a href="<?php echo $editlink; ?>"><?php echo $row->country_name ?> </a>
<?php
$lang =JFactory::getLanguage();
if ($lang->hasKey($prefix.$row->country_3_code)) {
echo "(".$country_string.") ";
}
?>
<a title="<?php echo vmText::sprintf('COM_VIRTUEMART_STATES_VIEW_LINK', $country_string ); ?>" href="<?php echo $statelink; ?>">[<?php echo $states ?>]</a>
</td>
<?php /* TODO not implemented <td align="left">
<?php echo $row->virtuemart_worldzone_id; ?>
</td> */ ?>
<td>
<?php echo $row->country_2_code; ?>
</td>
<td>
<?php echo $row->country_3_code ; ?>
</td>
<td align="center">
<?php echo $published; ?>
</td>
<td align="center">
<?php echo $row->virtuemart_country_id; ?>
</td>
</tr>
<?php
$k = 1 - $k;
}
?>
<tfoot>
<tr>
<td colspan="10">
<?php echo $this->pagination->getListFooter(); ?>
</td>
</tr>
</tfoot>
</table>
</div>
<input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['filter_order_Dir']; ?>" />
<input type="hidden" name="filter_order" value="<?php echo $this->lists['filter_order']; ?>" />
<input type="hidden" name="option" value="com_virtuemart" />
<input type="hidden" name="controller" value="country" />
<input type="hidden" name="view" value="country" />
<input type="hidden" name="task" value="" />
<input type="hidden" name="boxchecked" value="0" />
<?php echo JHtml::_( 'form.token' ); ?>
</form>
<?php AdminUIHelper::endAdminArea(); ?> | jburnim/example-virtuemart-store-heroku | virtuemart/administrator/components/com_virtuemart/views/country/tmpl/default.php | PHP | gpl-2.0 | 4,456 |
/* SPDX-License-Identifier: GPL-2.0 */
/* IP Virtual Server
* data structure and functionality definitions
*/
#ifndef _NET_IP_VS_H
#define _NET_IP_VS_H
#include <linux/ip_vs.h> /* definitions shared with userland */
#include <asm/types.h> /* for __uXX types */
#include <linux/list.h> /* for struct list_head */
#include <linux/spinlock.h> /* for struct rwlock_t */
#include <linux/atomic.h> /* for struct atomic_t */
#include <linux/refcount.h> /* for struct refcount_t */
#include <linux/compiler.h>
#include <linux/timer.h>
#include <linux/bug.h>
#include <net/checksum.h>
#include <linux/netfilter.h> /* for union nf_inet_addr */
#include <linux/ip.h>
#include <linux/ipv6.h> /* for struct ipv6hdr */
#include <net/ipv6.h>
#if IS_ENABLED(CONFIG_IP_VS_IPV6)
#include <linux/netfilter_ipv6/ip6_tables.h>
#endif
#if IS_ENABLED(CONFIG_NF_CONNTRACK)
#include <net/netfilter/nf_conntrack.h>
#endif
#include <net/net_namespace.h> /* Netw namespace */
#define IP_VS_HDR_INVERSE 1
#define IP_VS_HDR_ICMP 2
/* Generic access of ipvs struct */
static inline struct netns_ipvs *net_ipvs(struct net* net)
{
return net->ipvs;
}
/* This one needed for single_open_net since net is stored directly in
* private not as a struct i.e. seq_file_net can't be used.
*/
static inline struct net *seq_file_single_net(struct seq_file *seq)
{
#ifdef CONFIG_NET_NS
return (struct net *)seq->private;
#else
return &init_net;
#endif
}
/* Connections' size value needed by ip_vs_ctl.c */
extern int ip_vs_conn_tab_size;
struct ip_vs_iphdr {
int hdr_flags; /* ipvs flags */
__u32 off; /* Where IP or IPv4 header starts */
__u32 len; /* IPv4 simply where L4 starts
* IPv6 where L4 Transport Header starts */
__u16 fragoffs; /* IPv6 fragment offset, 0 if first frag (or not frag)*/
__s16 protocol;
__s32 flags;
union nf_inet_addr saddr;
union nf_inet_addr daddr;
};
static inline void *frag_safe_skb_hp(const struct sk_buff *skb, int offset,
int len, void *buffer,
const struct ip_vs_iphdr *ipvsh)
{
return skb_header_pointer(skb, offset, len, buffer);
}
/* This function handles filling *ip_vs_iphdr, both for IPv4 and IPv6.
* IPv6 requires some extra work, as finding proper header position,
* depend on the IPv6 extension headers.
*/
static inline int
ip_vs_fill_iph_skb_off(int af, const struct sk_buff *skb, int offset,
int hdr_flags, struct ip_vs_iphdr *iphdr)
{
iphdr->hdr_flags = hdr_flags;
iphdr->off = offset;
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6) {
struct ipv6hdr _iph;
const struct ipv6hdr *iph = skb_header_pointer(
skb, offset, sizeof(_iph), &_iph);
if (!iph)
return 0;
iphdr->saddr.in6 = iph->saddr;
iphdr->daddr.in6 = iph->daddr;
/* ipv6_find_hdr() updates len, flags */
iphdr->len = offset;
iphdr->flags = 0;
iphdr->protocol = ipv6_find_hdr(skb, &iphdr->len, -1,
&iphdr->fragoffs,
&iphdr->flags);
if (iphdr->protocol < 0)
return 0;
} else
#endif
{
struct iphdr _iph;
const struct iphdr *iph = skb_header_pointer(
skb, offset, sizeof(_iph), &_iph);
if (!iph)
return 0;
iphdr->len = offset + iph->ihl * 4;
iphdr->fragoffs = 0;
iphdr->protocol = iph->protocol;
iphdr->saddr.ip = iph->saddr;
iphdr->daddr.ip = iph->daddr;
}
return 1;
}
static inline int
ip_vs_fill_iph_skb_icmp(int af, const struct sk_buff *skb, int offset,
bool inverse, struct ip_vs_iphdr *iphdr)
{
int hdr_flags = IP_VS_HDR_ICMP;
if (inverse)
hdr_flags |= IP_VS_HDR_INVERSE;
return ip_vs_fill_iph_skb_off(af, skb, offset, hdr_flags, iphdr);
}
static inline int
ip_vs_fill_iph_skb(int af, const struct sk_buff *skb, bool inverse,
struct ip_vs_iphdr *iphdr)
{
int hdr_flags = 0;
if (inverse)
hdr_flags |= IP_VS_HDR_INVERSE;
return ip_vs_fill_iph_skb_off(af, skb, skb_network_offset(skb),
hdr_flags, iphdr);
}
static inline bool
ip_vs_iph_inverse(const struct ip_vs_iphdr *iph)
{
return !!(iph->hdr_flags & IP_VS_HDR_INVERSE);
}
static inline bool
ip_vs_iph_icmp(const struct ip_vs_iphdr *iph)
{
return !!(iph->hdr_flags & IP_VS_HDR_ICMP);
}
static inline void ip_vs_addr_copy(int af, union nf_inet_addr *dst,
const union nf_inet_addr *src)
{
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6)
dst->in6 = src->in6;
else
#endif
dst->ip = src->ip;
}
static inline void ip_vs_addr_set(int af, union nf_inet_addr *dst,
const union nf_inet_addr *src)
{
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6) {
dst->in6 = src->in6;
return;
}
#endif
dst->ip = src->ip;
dst->all[1] = 0;
dst->all[2] = 0;
dst->all[3] = 0;
}
static inline int ip_vs_addr_equal(int af, const union nf_inet_addr *a,
const union nf_inet_addr *b)
{
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6)
return ipv6_addr_equal(&a->in6, &b->in6);
#endif
return a->ip == b->ip;
}
#ifdef CONFIG_IP_VS_DEBUG
#include <linux/net.h>
int ip_vs_get_debug_level(void);
static inline const char *ip_vs_dbg_addr(int af, char *buf, size_t buf_len,
const union nf_inet_addr *addr,
int *idx)
{
int len;
#ifdef CONFIG_IP_VS_IPV6
if (af == AF_INET6)
len = snprintf(&buf[*idx], buf_len - *idx, "[%pI6c]",
&addr->in6) + 1;
else
#endif
len = snprintf(&buf[*idx], buf_len - *idx, "%pI4",
&addr->ip) + 1;
*idx += len;
BUG_ON(*idx > buf_len + 1);
return &buf[*idx - len];
}
#define IP_VS_DBG_BUF(level, msg, ...) \
do { \
char ip_vs_dbg_buf[160]; \
int ip_vs_dbg_idx = 0; \
if (level <= ip_vs_get_debug_level()) \
printk(KERN_DEBUG pr_fmt(msg), ##__VA_ARGS__); \
} while (0)
#define IP_VS_ERR_BUF(msg...) \
do { \
char ip_vs_dbg_buf[160]; \
int ip_vs_dbg_idx = 0; \
pr_err(msg); \
} while (0)
/* Only use from within IP_VS_DBG_BUF() or IP_VS_ERR_BUF macros */
#define IP_VS_DBG_ADDR(af, addr) \
ip_vs_dbg_addr(af, ip_vs_dbg_buf, \
sizeof(ip_vs_dbg_buf), addr, \
&ip_vs_dbg_idx)
#define IP_VS_DBG(level, msg, ...) \
do { \
if (level <= ip_vs_get_debug_level()) \
printk(KERN_DEBUG pr_fmt(msg), ##__VA_ARGS__); \
} while (0)
#define IP_VS_DBG_RL(msg, ...) \
do { \
if (net_ratelimit()) \
printk(KERN_DEBUG pr_fmt(msg), ##__VA_ARGS__); \
} while (0)
#define IP_VS_DBG_PKT(level, af, pp, skb, ofs, msg) \
do { \
if (level <= ip_vs_get_debug_level()) \
pp->debug_packet(af, pp, skb, ofs, msg); \
} while (0)
#define IP_VS_DBG_RL_PKT(level, af, pp, skb, ofs, msg) \
do { \
if (level <= ip_vs_get_debug_level() && \
net_ratelimit()) \
pp->debug_packet(af, pp, skb, ofs, msg); \
} while (0)
#else /* NO DEBUGGING at ALL */
#define IP_VS_DBG_BUF(level, msg...) do {} while (0)
#define IP_VS_ERR_BUF(msg...) do {} while (0)
#define IP_VS_DBG(level, msg...) do {} while (0)
#define IP_VS_DBG_RL(msg...) do {} while (0)
#define IP_VS_DBG_PKT(level, af, pp, skb, ofs, msg) do {} while (0)
#define IP_VS_DBG_RL_PKT(level, af, pp, skb, ofs, msg) do {} while (0)
#endif
#define IP_VS_BUG() BUG()
#define IP_VS_ERR_RL(msg, ...) \
do { \
if (net_ratelimit()) \
pr_err(msg, ##__VA_ARGS__); \
} while (0)
#ifdef CONFIG_IP_VS_DEBUG
#define EnterFunction(level) \
do { \
if (level <= ip_vs_get_debug_level()) \
printk(KERN_DEBUG \
pr_fmt("Enter: %s, %s line %i\n"), \
__func__, __FILE__, __LINE__); \
} while (0)
#define LeaveFunction(level) \
do { \
if (level <= ip_vs_get_debug_level()) \
printk(KERN_DEBUG \
pr_fmt("Leave: %s, %s line %i\n"), \
__func__, __FILE__, __LINE__); \
} while (0)
#else
#define EnterFunction(level) do {} while (0)
#define LeaveFunction(level) do {} while (0)
#endif
/* The port number of FTP service (in network order). */
#define FTPPORT cpu_to_be16(21)
#define FTPDATA cpu_to_be16(20)
/* TCP State Values */
enum {
IP_VS_TCP_S_NONE = 0,
IP_VS_TCP_S_ESTABLISHED,
IP_VS_TCP_S_SYN_SENT,
IP_VS_TCP_S_SYN_RECV,
IP_VS_TCP_S_FIN_WAIT,
IP_VS_TCP_S_TIME_WAIT,
IP_VS_TCP_S_CLOSE,
IP_VS_TCP_S_CLOSE_WAIT,
IP_VS_TCP_S_LAST_ACK,
IP_VS_TCP_S_LISTEN,
IP_VS_TCP_S_SYNACK,
IP_VS_TCP_S_LAST
};
/* UDP State Values */
enum {
IP_VS_UDP_S_NORMAL,
IP_VS_UDP_S_LAST,
};
/* ICMP State Values */
enum {
IP_VS_ICMP_S_NORMAL,
IP_VS_ICMP_S_LAST,
};
/* SCTP State Values */
enum ip_vs_sctp_states {
IP_VS_SCTP_S_NONE,
IP_VS_SCTP_S_INIT1,
IP_VS_SCTP_S_INIT,
IP_VS_SCTP_S_COOKIE_SENT,
IP_VS_SCTP_S_COOKIE_REPLIED,
IP_VS_SCTP_S_COOKIE_WAIT,
IP_VS_SCTP_S_COOKIE,
IP_VS_SCTP_S_COOKIE_ECHOED,
IP_VS_SCTP_S_ESTABLISHED,
IP_VS_SCTP_S_SHUTDOWN_SENT,
IP_VS_SCTP_S_SHUTDOWN_RECEIVED,
IP_VS_SCTP_S_SHUTDOWN_ACK_SENT,
IP_VS_SCTP_S_REJECTED,
IP_VS_SCTP_S_CLOSED,
IP_VS_SCTP_S_LAST
};
/* Delta sequence info structure
* Each ip_vs_conn has 2 (output AND input seq. changes).
* Only used in the VS/NAT.
*/
struct ip_vs_seq {
__u32 init_seq; /* Add delta from this seq */
__u32 delta; /* Delta in sequence numbers */
__u32 previous_delta; /* Delta in sequence numbers
* before last resized pkt */
};
/* counters per cpu */
struct ip_vs_counters {
__u64 conns; /* connections scheduled */
__u64 inpkts; /* incoming packets */
__u64 outpkts; /* outgoing packets */
__u64 inbytes; /* incoming bytes */
__u64 outbytes; /* outgoing bytes */
};
/* Stats per cpu */
struct ip_vs_cpu_stats {
struct ip_vs_counters cnt;
struct u64_stats_sync syncp;
};
/* IPVS statistics objects */
struct ip_vs_estimator {
struct list_head list;
u64 last_inbytes;
u64 last_outbytes;
u64 last_conns;
u64 last_inpkts;
u64 last_outpkts;
u64 cps;
u64 inpps;
u64 outpps;
u64 inbps;
u64 outbps;
};
/*
* IPVS statistics object, 64-bit kernel version of struct ip_vs_stats_user
*/
struct ip_vs_kstats {
u64 conns; /* connections scheduled */
u64 inpkts; /* incoming packets */
u64 outpkts; /* outgoing packets */
u64 inbytes; /* incoming bytes */
u64 outbytes; /* outgoing bytes */
u64 cps; /* current connection rate */
u64 inpps; /* current in packet rate */
u64 outpps; /* current out packet rate */
u64 inbps; /* current in byte rate */
u64 outbps; /* current out byte rate */
};
struct ip_vs_stats {
struct ip_vs_kstats kstats; /* kernel statistics */
struct ip_vs_estimator est; /* estimator */
struct ip_vs_cpu_stats __percpu *cpustats; /* per cpu counters */
spinlock_t lock; /* spin lock */
struct ip_vs_kstats kstats0; /* reset values */
};
struct dst_entry;
struct iphdr;
struct ip_vs_conn;
struct ip_vs_app;
struct sk_buff;
struct ip_vs_proto_data;
struct ip_vs_protocol {
struct ip_vs_protocol *next;
char *name;
u16 protocol;
u16 num_states;
int dont_defrag;
void (*init)(struct ip_vs_protocol *pp);
void (*exit)(struct ip_vs_protocol *pp);
int (*init_netns)(struct netns_ipvs *ipvs, struct ip_vs_proto_data *pd);
void (*exit_netns)(struct netns_ipvs *ipvs, struct ip_vs_proto_data *pd);
int (*conn_schedule)(struct netns_ipvs *ipvs,
int af, struct sk_buff *skb,
struct ip_vs_proto_data *pd,
int *verdict, struct ip_vs_conn **cpp,
struct ip_vs_iphdr *iph);
struct ip_vs_conn *
(*conn_in_get)(struct netns_ipvs *ipvs,
int af,
const struct sk_buff *skb,
const struct ip_vs_iphdr *iph);
struct ip_vs_conn *
(*conn_out_get)(struct netns_ipvs *ipvs,
int af,
const struct sk_buff *skb,
const struct ip_vs_iphdr *iph);
int (*snat_handler)(struct sk_buff *skb, struct ip_vs_protocol *pp,
struct ip_vs_conn *cp, struct ip_vs_iphdr *iph);
int (*dnat_handler)(struct sk_buff *skb, struct ip_vs_protocol *pp,
struct ip_vs_conn *cp, struct ip_vs_iphdr *iph);
int (*csum_check)(int af, struct sk_buff *skb,
struct ip_vs_protocol *pp);
const char *(*state_name)(int state);
void (*state_transition)(struct ip_vs_conn *cp, int direction,
const struct sk_buff *skb,
struct ip_vs_proto_data *pd);
int (*register_app)(struct netns_ipvs *ipvs, struct ip_vs_app *inc);
void (*unregister_app)(struct netns_ipvs *ipvs, struct ip_vs_app *inc);
int (*app_conn_bind)(struct ip_vs_conn *cp);
void (*debug_packet)(int af, struct ip_vs_protocol *pp,
const struct sk_buff *skb,
int offset,
const char *msg);
void (*timeout_change)(struct ip_vs_proto_data *pd, int flags);
};
/* protocol data per netns */
struct ip_vs_proto_data {
struct ip_vs_proto_data *next;
struct ip_vs_protocol *pp;
int *timeout_table; /* protocol timeout table */
atomic_t appcnt; /* counter of proto app incs. */
struct tcp_states_t *tcp_state_table;
};
struct ip_vs_protocol *ip_vs_proto_get(unsigned short proto);
struct ip_vs_proto_data *ip_vs_proto_data_get(struct netns_ipvs *ipvs,
unsigned short proto);
struct ip_vs_conn_param {
struct netns_ipvs *ipvs;
const union nf_inet_addr *caddr;
const union nf_inet_addr *vaddr;
__be16 cport;
__be16 vport;
__u16 protocol;
u16 af;
const struct ip_vs_pe *pe;
char *pe_data;
__u8 pe_data_len;
};
/* IP_VS structure allocated for each dynamically scheduled connection */
struct ip_vs_conn {
struct hlist_node c_list; /* hashed list heads */
/* Protocol, addresses and port numbers */
__be16 cport;
__be16 dport;
__be16 vport;
u16 af; /* address family */
union nf_inet_addr caddr; /* client address */
union nf_inet_addr vaddr; /* virtual address */
union nf_inet_addr daddr; /* destination address */
volatile __u32 flags; /* status flags */
__u16 protocol; /* Which protocol (TCP/UDP) */
__u16 daf; /* Address family of the dest */
struct netns_ipvs *ipvs;
/* counter and timer */
refcount_t refcnt; /* reference count */
struct timer_list timer; /* Expiration timer */
volatile unsigned long timeout; /* timeout */
/* Flags and state transition */
spinlock_t lock; /* lock for state transition */
volatile __u16 state; /* state info */
volatile __u16 old_state; /* old state, to be used for
* state transition triggerd
* synchronization
*/
__u32 fwmark; /* Fire wall mark from skb */
unsigned long sync_endtime; /* jiffies + sent_retries */
/* Control members */
struct ip_vs_conn *control; /* Master control connection */
atomic_t n_control; /* Number of controlled ones */
struct ip_vs_dest *dest; /* real server */
atomic_t in_pkts; /* incoming packet counter */
/* Packet transmitter for different forwarding methods. If it
* mangles the packet, it must return NF_DROP or better NF_STOLEN,
* otherwise this must be changed to a sk_buff **.
* NF_ACCEPT can be returned when destination is local.
*/
int (*packet_xmit)(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
/* Note: we can group the following members into a structure,
* in order to save more space, and the following members are
* only used in VS/NAT anyway
*/
struct ip_vs_app *app; /* bound ip_vs_app object */
void *app_data; /* Application private data */
struct ip_vs_seq in_seq; /* incoming seq. struct */
struct ip_vs_seq out_seq; /* outgoing seq. struct */
const struct ip_vs_pe *pe;
char *pe_data;
__u8 pe_data_len;
struct rcu_head rcu_head;
};
/* Extended internal versions of struct ip_vs_service_user and ip_vs_dest_user
* for IPv6 support.
*
* We need these to conveniently pass around service and destination
* options, but unfortunately, we also need to keep the old definitions to
* maintain userspace backwards compatibility for the setsockopt interface.
*/
struct ip_vs_service_user_kern {
/* virtual service addresses */
u16 af;
u16 protocol;
union nf_inet_addr addr; /* virtual ip address */
__be16 port;
u32 fwmark; /* firwall mark of service */
/* virtual service options */
char *sched_name;
char *pe_name;
unsigned int flags; /* virtual service flags */
unsigned int timeout; /* persistent timeout in sec */
__be32 netmask; /* persistent netmask or plen */
};
struct ip_vs_dest_user_kern {
/* destination server address */
union nf_inet_addr addr;
__be16 port;
/* real server options */
unsigned int conn_flags; /* connection flags */
int weight; /* destination weight */
/* thresholds for active connections */
u32 u_threshold; /* upper threshold */
u32 l_threshold; /* lower threshold */
/* Address family of addr */
u16 af;
};
/*
* The information about the virtual service offered to the net and the
* forwarding entries.
*/
struct ip_vs_service {
struct hlist_node s_list; /* for normal service table */
struct hlist_node f_list; /* for fwmark-based service table */
atomic_t refcnt; /* reference counter */
u16 af; /* address family */
__u16 protocol; /* which protocol (TCP/UDP) */
union nf_inet_addr addr; /* IP address for virtual service */
__be16 port; /* port number for the service */
__u32 fwmark; /* firewall mark of the service */
unsigned int flags; /* service status flags */
unsigned int timeout; /* persistent timeout in ticks */
__be32 netmask; /* grouping granularity, mask/plen */
struct netns_ipvs *ipvs;
struct list_head destinations; /* real server d-linked list */
__u32 num_dests; /* number of servers */
struct ip_vs_stats stats; /* statistics for the service */
/* for scheduling */
struct ip_vs_scheduler __rcu *scheduler; /* bound scheduler object */
spinlock_t sched_lock; /* lock sched_data */
void *sched_data; /* scheduler application data */
/* alternate persistence engine */
struct ip_vs_pe __rcu *pe;
struct rcu_head rcu_head;
};
/* Information for cached dst */
struct ip_vs_dest_dst {
struct dst_entry *dst_cache; /* destination cache entry */
u32 dst_cookie;
union nf_inet_addr dst_saddr;
struct rcu_head rcu_head;
};
/* The real server destination forwarding entry with ip address, port number,
* and so on.
*/
struct ip_vs_dest {
struct list_head n_list; /* for the dests in the service */
struct hlist_node d_list; /* for table with all the dests */
u16 af; /* address family */
__be16 port; /* port number of the server */
union nf_inet_addr addr; /* IP address of the server */
volatile unsigned int flags; /* dest status flags */
atomic_t conn_flags; /* flags to copy to conn */
atomic_t weight; /* server weight */
refcount_t refcnt; /* reference counter */
struct ip_vs_stats stats; /* statistics */
unsigned long idle_start; /* start time, jiffies */
/* connection counters and thresholds */
atomic_t activeconns; /* active connections */
atomic_t inactconns; /* inactive connections */
atomic_t persistconns; /* persistent connections */
__u32 u_threshold; /* upper threshold */
__u32 l_threshold; /* lower threshold */
/* for destination cache */
spinlock_t dst_lock; /* lock of dst_cache */
struct ip_vs_dest_dst __rcu *dest_dst; /* cached dst info */
/* for virtual service */
struct ip_vs_service __rcu *svc; /* service it belongs to */
__u16 protocol; /* which protocol (TCP/UDP) */
__be16 vport; /* virtual port number */
union nf_inet_addr vaddr; /* virtual IP address */
__u32 vfwmark; /* firewall mark of service */
struct list_head t_list; /* in dest_trash */
unsigned int in_rs_table:1; /* we are in rs_table */
};
/* The scheduler object */
struct ip_vs_scheduler {
struct list_head n_list; /* d-linked list head */
char *name; /* scheduler name */
atomic_t refcnt; /* reference counter */
struct module *module; /* THIS_MODULE/NULL */
/* scheduler initializing service */
int (*init_service)(struct ip_vs_service *svc);
/* scheduling service finish */
void (*done_service)(struct ip_vs_service *svc);
/* dest is linked */
int (*add_dest)(struct ip_vs_service *svc, struct ip_vs_dest *dest);
/* dest is unlinked */
int (*del_dest)(struct ip_vs_service *svc, struct ip_vs_dest *dest);
/* dest is updated */
int (*upd_dest)(struct ip_vs_service *svc, struct ip_vs_dest *dest);
/* selecting a server from the given service */
struct ip_vs_dest* (*schedule)(struct ip_vs_service *svc,
const struct sk_buff *skb,
struct ip_vs_iphdr *iph);
};
/* The persistence engine object */
struct ip_vs_pe {
struct list_head n_list; /* d-linked list head */
char *name; /* scheduler name */
atomic_t refcnt; /* reference counter */
struct module *module; /* THIS_MODULE/NULL */
/* get the connection template, if any */
int (*fill_param)(struct ip_vs_conn_param *p, struct sk_buff *skb);
bool (*ct_match)(const struct ip_vs_conn_param *p,
struct ip_vs_conn *ct);
u32 (*hashkey_raw)(const struct ip_vs_conn_param *p, u32 initval,
bool inverse);
int (*show_pe_data)(const struct ip_vs_conn *cp, char *buf);
/* create connections for real-server outgoing packets */
struct ip_vs_conn* (*conn_out)(struct ip_vs_service *svc,
struct ip_vs_dest *dest,
struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
__be16 dport, __be16 cport);
};
/* The application module object (a.k.a. app incarnation) */
struct ip_vs_app {
struct list_head a_list; /* member in app list */
int type; /* IP_VS_APP_TYPE_xxx */
char *name; /* application module name */
__u16 protocol;
struct module *module; /* THIS_MODULE/NULL */
struct list_head incs_list; /* list of incarnations */
/* members for application incarnations */
struct list_head p_list; /* member in proto app list */
struct ip_vs_app *app; /* its real application */
__be16 port; /* port number in net order */
atomic_t usecnt; /* usage counter */
struct rcu_head rcu_head;
/* output hook: Process packet in inout direction, diff set for TCP.
* Return: 0=Error, 1=Payload Not Mangled/Mangled but checksum is ok,
* 2=Mangled but checksum was not updated
*/
int (*pkt_out)(struct ip_vs_app *, struct ip_vs_conn *,
struct sk_buff *, int *diff);
/* input hook: Process packet in outin direction, diff set for TCP.
* Return: 0=Error, 1=Payload Not Mangled/Mangled but checksum is ok,
* 2=Mangled but checksum was not updated
*/
int (*pkt_in)(struct ip_vs_app *, struct ip_vs_conn *,
struct sk_buff *, int *diff);
/* ip_vs_app initializer */
int (*init_conn)(struct ip_vs_app *, struct ip_vs_conn *);
/* ip_vs_app finish */
int (*done_conn)(struct ip_vs_app *, struct ip_vs_conn *);
/* not used now */
int (*bind_conn)(struct ip_vs_app *, struct ip_vs_conn *,
struct ip_vs_protocol *);
void (*unbind_conn)(struct ip_vs_app *, struct ip_vs_conn *);
int * timeout_table;
int * timeouts;
int timeouts_size;
int (*conn_schedule)(struct sk_buff *skb, struct ip_vs_app *app,
int *verdict, struct ip_vs_conn **cpp);
struct ip_vs_conn *
(*conn_in_get)(const struct sk_buff *skb, struct ip_vs_app *app,
const struct iphdr *iph, int inverse);
struct ip_vs_conn *
(*conn_out_get)(const struct sk_buff *skb, struct ip_vs_app *app,
const struct iphdr *iph, int inverse);
int (*state_transition)(struct ip_vs_conn *cp, int direction,
const struct sk_buff *skb,
struct ip_vs_app *app);
void (*timeout_change)(struct ip_vs_app *app, int flags);
};
struct ipvs_master_sync_state {
struct list_head sync_queue;
struct ip_vs_sync_buff *sync_buff;
unsigned long sync_queue_len;
unsigned int sync_queue_delay;
struct task_struct *master_thread;
struct delayed_work master_wakeup_work;
struct netns_ipvs *ipvs;
};
/* How much time to keep dests in trash */
#define IP_VS_DEST_TRASH_PERIOD (120 * HZ)
struct ipvs_sync_daemon_cfg {
union nf_inet_addr mcast_group;
int syncid;
u16 sync_maxlen;
u16 mcast_port;
u8 mcast_af;
u8 mcast_ttl;
/* multicast interface name */
char mcast_ifn[IP_VS_IFNAME_MAXLEN];
};
/* IPVS in network namespace */
struct netns_ipvs {
int gen; /* Generation */
int enable; /* enable like nf_hooks do */
/* Hash table: for real service lookups */
#define IP_VS_RTAB_BITS 4
#define IP_VS_RTAB_SIZE (1 << IP_VS_RTAB_BITS)
#define IP_VS_RTAB_MASK (IP_VS_RTAB_SIZE - 1)
struct hlist_head rs_table[IP_VS_RTAB_SIZE];
/* ip_vs_app */
struct list_head app_list;
/* ip_vs_proto */
#define IP_VS_PROTO_TAB_SIZE 32 /* must be power of 2 */
struct ip_vs_proto_data *proto_data_table[IP_VS_PROTO_TAB_SIZE];
/* ip_vs_proto_tcp */
#ifdef CONFIG_IP_VS_PROTO_TCP
#define TCP_APP_TAB_BITS 4
#define TCP_APP_TAB_SIZE (1 << TCP_APP_TAB_BITS)
#define TCP_APP_TAB_MASK (TCP_APP_TAB_SIZE - 1)
struct list_head tcp_apps[TCP_APP_TAB_SIZE];
#endif
/* ip_vs_proto_udp */
#ifdef CONFIG_IP_VS_PROTO_UDP
#define UDP_APP_TAB_BITS 4
#define UDP_APP_TAB_SIZE (1 << UDP_APP_TAB_BITS)
#define UDP_APP_TAB_MASK (UDP_APP_TAB_SIZE - 1)
struct list_head udp_apps[UDP_APP_TAB_SIZE];
#endif
/* ip_vs_proto_sctp */
#ifdef CONFIG_IP_VS_PROTO_SCTP
#define SCTP_APP_TAB_BITS 4
#define SCTP_APP_TAB_SIZE (1 << SCTP_APP_TAB_BITS)
#define SCTP_APP_TAB_MASK (SCTP_APP_TAB_SIZE - 1)
/* Hash table for SCTP application incarnations */
struct list_head sctp_apps[SCTP_APP_TAB_SIZE];
#endif
/* ip_vs_conn */
atomic_t conn_count; /* connection counter */
/* ip_vs_ctl */
struct ip_vs_stats tot_stats; /* Statistics & est. */
int num_services; /* no of virtual services */
/* Trash for destinations */
struct list_head dest_trash;
spinlock_t dest_trash_lock;
struct timer_list dest_trash_timer; /* expiration timer */
/* Service counters */
atomic_t ftpsvc_counter;
atomic_t nullsvc_counter;
atomic_t conn_out_counter;
#ifdef CONFIG_SYSCTL
/* 1/rate drop and drop-entry variables */
struct delayed_work defense_work; /* Work handler */
int drop_rate;
int drop_counter;
atomic_t dropentry;
/* locks in ctl.c */
spinlock_t dropentry_lock; /* drop entry handling */
spinlock_t droppacket_lock; /* drop packet handling */
spinlock_t securetcp_lock; /* state and timeout tables */
/* sys-ctl struct */
struct ctl_table_header *sysctl_hdr;
struct ctl_table *sysctl_tbl;
#endif
/* sysctl variables */
int sysctl_amemthresh;
int sysctl_am_droprate;
int sysctl_drop_entry;
int sysctl_drop_packet;
int sysctl_secure_tcp;
#ifdef CONFIG_IP_VS_NFCT
int sysctl_conntrack;
#endif
int sysctl_snat_reroute;
int sysctl_sync_ver;
int sysctl_sync_ports;
int sysctl_sync_persist_mode;
unsigned long sysctl_sync_qlen_max;
int sysctl_sync_sock_size;
int sysctl_cache_bypass;
int sysctl_expire_nodest_conn;
int sysctl_sloppy_tcp;
int sysctl_sloppy_sctp;
int sysctl_expire_quiescent_template;
int sysctl_sync_threshold[2];
unsigned int sysctl_sync_refresh_period;
int sysctl_sync_retries;
int sysctl_nat_icmp_send;
int sysctl_pmtu_disc;
int sysctl_backup_only;
int sysctl_conn_reuse_mode;
int sysctl_schedule_icmp;
int sysctl_ignore_tunneled;
/* ip_vs_lblc */
int sysctl_lblc_expiration;
struct ctl_table_header *lblc_ctl_header;
struct ctl_table *lblc_ctl_table;
/* ip_vs_lblcr */
int sysctl_lblcr_expiration;
struct ctl_table_header *lblcr_ctl_header;
struct ctl_table *lblcr_ctl_table;
/* ip_vs_est */
struct list_head est_list; /* estimator list */
spinlock_t est_lock;
struct timer_list est_timer; /* Estimation timer */
/* ip_vs_sync */
spinlock_t sync_lock;
struct ipvs_master_sync_state *ms;
spinlock_t sync_buff_lock;
struct task_struct **backup_threads;
int threads_mask;
volatile int sync_state;
struct mutex sync_mutex;
struct ipvs_sync_daemon_cfg mcfg; /* Master Configuration */
struct ipvs_sync_daemon_cfg bcfg; /* Backup Configuration */
/* net name space ptr */
struct net *net; /* Needed by timer routines */
/* Number of heterogeneous destinations, needed becaus heterogeneous
* are not supported when synchronization is enabled.
*/
unsigned int mixed_address_family_dests;
};
#define DEFAULT_SYNC_THRESHOLD 3
#define DEFAULT_SYNC_PERIOD 50
#define DEFAULT_SYNC_VER 1
#define DEFAULT_SLOPPY_TCP 0
#define DEFAULT_SLOPPY_SCTP 0
#define DEFAULT_SYNC_REFRESH_PERIOD (0U * HZ)
#define DEFAULT_SYNC_RETRIES 0
#define IPVS_SYNC_WAKEUP_RATE 8
#define IPVS_SYNC_QLEN_MAX (IPVS_SYNC_WAKEUP_RATE * 4)
#define IPVS_SYNC_SEND_DELAY (HZ / 50)
#define IPVS_SYNC_CHECK_PERIOD HZ
#define IPVS_SYNC_FLUSH_TIME (HZ * 2)
#define IPVS_SYNC_PORTS_MAX (1 << 6)
#ifdef CONFIG_SYSCTL
static inline int sysctl_sync_threshold(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sync_threshold[0];
}
static inline int sysctl_sync_period(struct netns_ipvs *ipvs)
{
return ACCESS_ONCE(ipvs->sysctl_sync_threshold[1]);
}
static inline unsigned int sysctl_sync_refresh_period(struct netns_ipvs *ipvs)
{
return ACCESS_ONCE(ipvs->sysctl_sync_refresh_period);
}
static inline int sysctl_sync_retries(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sync_retries;
}
static inline int sysctl_sync_ver(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sync_ver;
}
static inline int sysctl_sloppy_tcp(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sloppy_tcp;
}
static inline int sysctl_sloppy_sctp(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sloppy_sctp;
}
static inline int sysctl_sync_ports(struct netns_ipvs *ipvs)
{
return ACCESS_ONCE(ipvs->sysctl_sync_ports);
}
static inline int sysctl_sync_persist_mode(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sync_persist_mode;
}
static inline unsigned long sysctl_sync_qlen_max(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sync_qlen_max;
}
static inline int sysctl_sync_sock_size(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_sync_sock_size;
}
static inline int sysctl_pmtu_disc(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_pmtu_disc;
}
static inline int sysctl_backup_only(struct netns_ipvs *ipvs)
{
return ipvs->sync_state & IP_VS_STATE_BACKUP &&
ipvs->sysctl_backup_only;
}
static inline int sysctl_conn_reuse_mode(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_conn_reuse_mode;
}
static inline int sysctl_schedule_icmp(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_schedule_icmp;
}
static inline int sysctl_ignore_tunneled(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_ignore_tunneled;
}
static inline int sysctl_cache_bypass(struct netns_ipvs *ipvs)
{
return ipvs->sysctl_cache_bypass;
}
#else
static inline int sysctl_sync_threshold(struct netns_ipvs *ipvs)
{
return DEFAULT_SYNC_THRESHOLD;
}
static inline int sysctl_sync_period(struct netns_ipvs *ipvs)
{
return DEFAULT_SYNC_PERIOD;
}
static inline unsigned int sysctl_sync_refresh_period(struct netns_ipvs *ipvs)
{
return DEFAULT_SYNC_REFRESH_PERIOD;
}
static inline int sysctl_sync_retries(struct netns_ipvs *ipvs)
{
return DEFAULT_SYNC_RETRIES & 3;
}
static inline int sysctl_sync_ver(struct netns_ipvs *ipvs)
{
return DEFAULT_SYNC_VER;
}
static inline int sysctl_sloppy_tcp(struct netns_ipvs *ipvs)
{
return DEFAULT_SLOPPY_TCP;
}
static inline int sysctl_sloppy_sctp(struct netns_ipvs *ipvs)
{
return DEFAULT_SLOPPY_SCTP;
}
static inline int sysctl_sync_ports(struct netns_ipvs *ipvs)
{
return 1;
}
static inline int sysctl_sync_persist_mode(struct netns_ipvs *ipvs)
{
return 0;
}
static inline unsigned long sysctl_sync_qlen_max(struct netns_ipvs *ipvs)
{
return IPVS_SYNC_QLEN_MAX;
}
static inline int sysctl_sync_sock_size(struct netns_ipvs *ipvs)
{
return 0;
}
static inline int sysctl_pmtu_disc(struct netns_ipvs *ipvs)
{
return 1;
}
static inline int sysctl_backup_only(struct netns_ipvs *ipvs)
{
return 0;
}
static inline int sysctl_conn_reuse_mode(struct netns_ipvs *ipvs)
{
return 1;
}
static inline int sysctl_schedule_icmp(struct netns_ipvs *ipvs)
{
return 0;
}
static inline int sysctl_ignore_tunneled(struct netns_ipvs *ipvs)
{
return 0;
}
static inline int sysctl_cache_bypass(struct netns_ipvs *ipvs)
{
return 0;
}
#endif
/* IPVS core functions
* (from ip_vs_core.c)
*/
const char *ip_vs_proto_name(unsigned int proto);
void ip_vs_init_hash_table(struct list_head *table, int rows);
struct ip_vs_conn *ip_vs_new_conn_out(struct ip_vs_service *svc,
struct ip_vs_dest *dest,
struct sk_buff *skb,
const struct ip_vs_iphdr *iph,
__be16 dport,
__be16 cport);
#define IP_VS_INIT_HASH_TABLE(t) ip_vs_init_hash_table((t), ARRAY_SIZE((t)))
#define IP_VS_APP_TYPE_FTP 1
/* ip_vs_conn handling functions
* (from ip_vs_conn.c)
*/
enum {
IP_VS_DIR_INPUT = 0,
IP_VS_DIR_OUTPUT,
IP_VS_DIR_INPUT_ONLY,
IP_VS_DIR_LAST,
};
static inline void ip_vs_conn_fill_param(struct netns_ipvs *ipvs, int af, int protocol,
const union nf_inet_addr *caddr,
__be16 cport,
const union nf_inet_addr *vaddr,
__be16 vport,
struct ip_vs_conn_param *p)
{
p->ipvs = ipvs;
p->af = af;
p->protocol = protocol;
p->caddr = caddr;
p->cport = cport;
p->vaddr = vaddr;
p->vport = vport;
p->pe = NULL;
p->pe_data = NULL;
}
struct ip_vs_conn *ip_vs_conn_in_get(const struct ip_vs_conn_param *p);
struct ip_vs_conn *ip_vs_ct_in_get(const struct ip_vs_conn_param *p);
struct ip_vs_conn * ip_vs_conn_in_get_proto(struct netns_ipvs *ipvs, int af,
const struct sk_buff *skb,
const struct ip_vs_iphdr *iph);
struct ip_vs_conn *ip_vs_conn_out_get(const struct ip_vs_conn_param *p);
struct ip_vs_conn * ip_vs_conn_out_get_proto(struct netns_ipvs *ipvs, int af,
const struct sk_buff *skb,
const struct ip_vs_iphdr *iph);
/* Get reference to gain full access to conn.
* By default, RCU read-side critical sections have access only to
* conn fields and its PE data, see ip_vs_conn_rcu_free() for reference.
*/
static inline bool __ip_vs_conn_get(struct ip_vs_conn *cp)
{
return refcount_inc_not_zero(&cp->refcnt);
}
/* put back the conn without restarting its timer */
static inline void __ip_vs_conn_put(struct ip_vs_conn *cp)
{
smp_mb__before_atomic();
refcount_dec(&cp->refcnt);
}
void ip_vs_conn_put(struct ip_vs_conn *cp);
void ip_vs_conn_fill_cport(struct ip_vs_conn *cp, __be16 cport);
struct ip_vs_conn *ip_vs_conn_new(const struct ip_vs_conn_param *p, int dest_af,
const union nf_inet_addr *daddr,
__be16 dport, unsigned int flags,
struct ip_vs_dest *dest, __u32 fwmark);
void ip_vs_conn_expire_now(struct ip_vs_conn *cp);
const char *ip_vs_state_name(__u16 proto, int state);
void ip_vs_tcp_conn_listen(struct ip_vs_conn *cp);
int ip_vs_check_template(struct ip_vs_conn *ct, struct ip_vs_dest *cdest);
void ip_vs_random_dropentry(struct netns_ipvs *ipvs);
int ip_vs_conn_init(void);
void ip_vs_conn_cleanup(void);
static inline void ip_vs_control_del(struct ip_vs_conn *cp)
{
struct ip_vs_conn *ctl_cp = cp->control;
if (!ctl_cp) {
IP_VS_ERR_BUF("request control DEL for uncontrolled: "
"%s:%d to %s:%d\n",
IP_VS_DBG_ADDR(cp->af, &cp->caddr),
ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr),
ntohs(cp->vport));
return;
}
IP_VS_DBG_BUF(7, "DELeting control for: "
"cp.dst=%s:%d ctl_cp.dst=%s:%d\n",
IP_VS_DBG_ADDR(cp->af, &cp->caddr),
ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &ctl_cp->caddr),
ntohs(ctl_cp->cport));
cp->control = NULL;
if (atomic_read(&ctl_cp->n_control) == 0) {
IP_VS_ERR_BUF("BUG control DEL with n=0 : "
"%s:%d to %s:%d\n",
IP_VS_DBG_ADDR(cp->af, &cp->caddr),
ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr),
ntohs(cp->vport));
return;
}
atomic_dec(&ctl_cp->n_control);
}
static inline void
ip_vs_control_add(struct ip_vs_conn *cp, struct ip_vs_conn *ctl_cp)
{
if (cp->control) {
IP_VS_ERR_BUF("request control ADD for already controlled: "
"%s:%d to %s:%d\n",
IP_VS_DBG_ADDR(cp->af, &cp->caddr),
ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &cp->vaddr),
ntohs(cp->vport));
ip_vs_control_del(cp);
}
IP_VS_DBG_BUF(7, "ADDing control for: "
"cp.dst=%s:%d ctl_cp.dst=%s:%d\n",
IP_VS_DBG_ADDR(cp->af, &cp->caddr),
ntohs(cp->cport),
IP_VS_DBG_ADDR(cp->af, &ctl_cp->caddr),
ntohs(ctl_cp->cport));
cp->control = ctl_cp;
atomic_inc(&ctl_cp->n_control);
}
/* IPVS netns init & cleanup functions */
int ip_vs_estimator_net_init(struct netns_ipvs *ipvs);
int ip_vs_control_net_init(struct netns_ipvs *ipvs);
int ip_vs_protocol_net_init(struct netns_ipvs *ipvs);
int ip_vs_app_net_init(struct netns_ipvs *ipvs);
int ip_vs_conn_net_init(struct netns_ipvs *ipvs);
int ip_vs_sync_net_init(struct netns_ipvs *ipvs);
void ip_vs_conn_net_cleanup(struct netns_ipvs *ipvs);
void ip_vs_app_net_cleanup(struct netns_ipvs *ipvs);
void ip_vs_protocol_net_cleanup(struct netns_ipvs *ipvs);
void ip_vs_control_net_cleanup(struct netns_ipvs *ipvs);
void ip_vs_estimator_net_cleanup(struct netns_ipvs *ipvs);
void ip_vs_sync_net_cleanup(struct netns_ipvs *ipvs);
void ip_vs_service_net_cleanup(struct netns_ipvs *ipvs);
/* IPVS application functions
* (from ip_vs_app.c)
*/
#define IP_VS_APP_MAX_PORTS 8
struct ip_vs_app *register_ip_vs_app(struct netns_ipvs *ipvs, struct ip_vs_app *app);
void unregister_ip_vs_app(struct netns_ipvs *ipvs, struct ip_vs_app *app);
int ip_vs_bind_app(struct ip_vs_conn *cp, struct ip_vs_protocol *pp);
void ip_vs_unbind_app(struct ip_vs_conn *cp);
int register_ip_vs_app_inc(struct netns_ipvs *ipvs, struct ip_vs_app *app, __u16 proto,
__u16 port);
int ip_vs_app_inc_get(struct ip_vs_app *inc);
void ip_vs_app_inc_put(struct ip_vs_app *inc);
int ip_vs_app_pkt_out(struct ip_vs_conn *, struct sk_buff *skb);
int ip_vs_app_pkt_in(struct ip_vs_conn *, struct sk_buff *skb);
int register_ip_vs_pe(struct ip_vs_pe *pe);
int unregister_ip_vs_pe(struct ip_vs_pe *pe);
struct ip_vs_pe *ip_vs_pe_getbyname(const char *name);
struct ip_vs_pe *__ip_vs_pe_getbyname(const char *pe_name);
/* Use a #define to avoid all of module.h just for these trivial ops */
#define ip_vs_pe_get(pe) \
if (pe && pe->module) \
__module_get(pe->module);
#define ip_vs_pe_put(pe) \
if (pe && pe->module) \
module_put(pe->module);
/* IPVS protocol functions (from ip_vs_proto.c) */
int ip_vs_protocol_init(void);
void ip_vs_protocol_cleanup(void);
void ip_vs_protocol_timeout_change(struct netns_ipvs *ipvs, int flags);
int *ip_vs_create_timeout_table(int *table, int size);
void ip_vs_tcpudp_debug_packet(int af, struct ip_vs_protocol *pp,
const struct sk_buff *skb, int offset,
const char *msg);
extern struct ip_vs_protocol ip_vs_protocol_tcp;
extern struct ip_vs_protocol ip_vs_protocol_udp;
extern struct ip_vs_protocol ip_vs_protocol_icmp;
extern struct ip_vs_protocol ip_vs_protocol_esp;
extern struct ip_vs_protocol ip_vs_protocol_ah;
extern struct ip_vs_protocol ip_vs_protocol_sctp;
/* Registering/unregistering scheduler functions
* (from ip_vs_sched.c)
*/
int register_ip_vs_scheduler(struct ip_vs_scheduler *scheduler);
int unregister_ip_vs_scheduler(struct ip_vs_scheduler *scheduler);
int ip_vs_bind_scheduler(struct ip_vs_service *svc,
struct ip_vs_scheduler *scheduler);
void ip_vs_unbind_scheduler(struct ip_vs_service *svc,
struct ip_vs_scheduler *sched);
struct ip_vs_scheduler *ip_vs_scheduler_get(const char *sched_name);
void ip_vs_scheduler_put(struct ip_vs_scheduler *scheduler);
struct ip_vs_conn *
ip_vs_schedule(struct ip_vs_service *svc, struct sk_buff *skb,
struct ip_vs_proto_data *pd, int *ignored,
struct ip_vs_iphdr *iph);
int ip_vs_leave(struct ip_vs_service *svc, struct sk_buff *skb,
struct ip_vs_proto_data *pd, struct ip_vs_iphdr *iph);
void ip_vs_scheduler_err(struct ip_vs_service *svc, const char *msg);
/* IPVS control data and functions (from ip_vs_ctl.c) */
extern struct ip_vs_stats ip_vs_stats;
extern int sysctl_ip_vs_sync_ver;
struct ip_vs_service *
ip_vs_service_find(struct netns_ipvs *ipvs, int af, __u32 fwmark, __u16 protocol,
const union nf_inet_addr *vaddr, __be16 vport);
bool ip_vs_has_real_service(struct netns_ipvs *ipvs, int af, __u16 protocol,
const union nf_inet_addr *daddr, __be16 dport);
struct ip_vs_dest *
ip_vs_find_real_service(struct netns_ipvs *ipvs, int af, __u16 protocol,
const union nf_inet_addr *daddr, __be16 dport);
int ip_vs_use_count_inc(void);
void ip_vs_use_count_dec(void);
int ip_vs_register_nl_ioctl(void);
void ip_vs_unregister_nl_ioctl(void);
int ip_vs_control_init(void);
void ip_vs_control_cleanup(void);
struct ip_vs_dest *
ip_vs_find_dest(struct netns_ipvs *ipvs, int svc_af, int dest_af,
const union nf_inet_addr *daddr, __be16 dport,
const union nf_inet_addr *vaddr, __be16 vport,
__u16 protocol, __u32 fwmark, __u32 flags);
void ip_vs_try_bind_dest(struct ip_vs_conn *cp);
static inline void ip_vs_dest_hold(struct ip_vs_dest *dest)
{
refcount_inc(&dest->refcnt);
}
static inline void ip_vs_dest_put(struct ip_vs_dest *dest)
{
smp_mb__before_atomic();
refcount_dec(&dest->refcnt);
}
static inline void ip_vs_dest_put_and_free(struct ip_vs_dest *dest)
{
if (refcount_dec_and_test(&dest->refcnt))
kfree(dest);
}
/* IPVS sync daemon data and function prototypes
* (from ip_vs_sync.c)
*/
int start_sync_thread(struct netns_ipvs *ipvs, struct ipvs_sync_daemon_cfg *cfg,
int state);
int stop_sync_thread(struct netns_ipvs *ipvs, int state);
void ip_vs_sync_conn(struct netns_ipvs *ipvs, struct ip_vs_conn *cp, int pkts);
/* IPVS rate estimator prototypes (from ip_vs_est.c) */
void ip_vs_start_estimator(struct netns_ipvs *ipvs, struct ip_vs_stats *stats);
void ip_vs_stop_estimator(struct netns_ipvs *ipvs, struct ip_vs_stats *stats);
void ip_vs_zero_estimator(struct ip_vs_stats *stats);
void ip_vs_read_estimator(struct ip_vs_kstats *dst, struct ip_vs_stats *stats);
/* Various IPVS packet transmitters (from ip_vs_xmit.c) */
int ip_vs_null_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_bypass_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_nat_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_tunnel_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_dr_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_icmp_xmit(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, int offset,
unsigned int hooknum, struct ip_vs_iphdr *iph);
void ip_vs_dest_dst_rcu_free(struct rcu_head *head);
#ifdef CONFIG_IP_VS_IPV6
int ip_vs_bypass_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_nat_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_tunnel_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_dr_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, struct ip_vs_iphdr *iph);
int ip_vs_icmp_xmit_v6(struct sk_buff *skb, struct ip_vs_conn *cp,
struct ip_vs_protocol *pp, int offset,
unsigned int hooknum, struct ip_vs_iphdr *iph);
#endif
#ifdef CONFIG_SYSCTL
/* This is a simple mechanism to ignore packets when
* we are loaded. Just set ip_vs_drop_rate to 'n' and
* we start to drop 1/rate of the packets
*/
static inline int ip_vs_todrop(struct netns_ipvs *ipvs)
{
if (!ipvs->drop_rate)
return 0;
if (--ipvs->drop_counter > 0)
return 0;
ipvs->drop_counter = ipvs->drop_rate;
return 1;
}
#else
static inline int ip_vs_todrop(struct netns_ipvs *ipvs) { return 0; }
#endif
/* ip_vs_fwd_tag returns the forwarding tag of the connection */
#define IP_VS_FWD_METHOD(cp) (cp->flags & IP_VS_CONN_F_FWD_MASK)
static inline char ip_vs_fwd_tag(struct ip_vs_conn *cp)
{
char fwd;
switch (IP_VS_FWD_METHOD(cp)) {
case IP_VS_CONN_F_MASQ:
fwd = 'M'; break;
case IP_VS_CONN_F_LOCALNODE:
fwd = 'L'; break;
case IP_VS_CONN_F_TUNNEL:
fwd = 'T'; break;
case IP_VS_CONN_F_DROUTE:
fwd = 'R'; break;
case IP_VS_CONN_F_BYPASS:
fwd = 'B'; break;
default:
fwd = '?'; break;
}
return fwd;
}
void ip_vs_nat_icmp(struct sk_buff *skb, struct ip_vs_protocol *pp,
struct ip_vs_conn *cp, int dir);
#ifdef CONFIG_IP_VS_IPV6
void ip_vs_nat_icmp_v6(struct sk_buff *skb, struct ip_vs_protocol *pp,
struct ip_vs_conn *cp, int dir);
#endif
__sum16 ip_vs_checksum_complete(struct sk_buff *skb, int offset);
static inline __wsum ip_vs_check_diff4(__be32 old, __be32 new, __wsum oldsum)
{
__be32 diff[2] = { ~old, new };
return csum_partial(diff, sizeof(diff), oldsum);
}
#ifdef CONFIG_IP_VS_IPV6
static inline __wsum ip_vs_check_diff16(const __be32 *old, const __be32 *new,
__wsum oldsum)
{
__be32 diff[8] = { ~old[3], ~old[2], ~old[1], ~old[0],
new[3], new[2], new[1], new[0] };
return csum_partial(diff, sizeof(diff), oldsum);
}
#endif
static inline __wsum ip_vs_check_diff2(__be16 old, __be16 new, __wsum oldsum)
{
__be16 diff[2] = { ~old, new };
return csum_partial(diff, sizeof(diff), oldsum);
}
/* Forget current conntrack (unconfirmed) and attach notrack entry */
static inline void ip_vs_notrack(struct sk_buff *skb)
{
#if defined(CONFIG_NF_CONNTRACK) || defined(CONFIG_NF_CONNTRACK_MODULE)
enum ip_conntrack_info ctinfo;
struct nf_conn *ct = nf_ct_get(skb, &ctinfo);
if (ct) {
nf_conntrack_put(&ct->ct_general);
nf_ct_set(skb, NULL, IP_CT_UNTRACKED);
}
#endif
}
#ifdef CONFIG_IP_VS_NFCT
/* Netfilter connection tracking
* (from ip_vs_nfct.c)
*/
static inline int ip_vs_conntrack_enabled(struct netns_ipvs *ipvs)
{
#ifdef CONFIG_SYSCTL
return ipvs->sysctl_conntrack;
#else
return 0;
#endif
}
void ip_vs_update_conntrack(struct sk_buff *skb, struct ip_vs_conn *cp,
int outin);
int ip_vs_confirm_conntrack(struct sk_buff *skb);
void ip_vs_nfct_expect_related(struct sk_buff *skb, struct nf_conn *ct,
struct ip_vs_conn *cp, u_int8_t proto,
const __be16 port, int from_rs);
void ip_vs_conn_drop_conntrack(struct ip_vs_conn *cp);
#else
static inline int ip_vs_conntrack_enabled(struct netns_ipvs *ipvs)
{
return 0;
}
static inline void ip_vs_update_conntrack(struct sk_buff *skb,
struct ip_vs_conn *cp, int outin)
{
}
static inline int ip_vs_confirm_conntrack(struct sk_buff *skb)
{
return NF_ACCEPT;
}
static inline void ip_vs_conn_drop_conntrack(struct ip_vs_conn *cp)
{
}
#endif /* CONFIG_IP_VS_NFCT */
/* Really using conntrack? */
static inline bool ip_vs_conn_uses_conntrack(struct ip_vs_conn *cp,
struct sk_buff *skb)
{
#ifdef CONFIG_IP_VS_NFCT
enum ip_conntrack_info ctinfo;
struct nf_conn *ct;
if (!(cp->flags & IP_VS_CONN_F_NFCT))
return false;
ct = nf_ct_get(skb, &ctinfo);
if (ct)
return true;
#endif
return false;
}
static inline int
ip_vs_dest_conn_overhead(struct ip_vs_dest *dest)
{
/* We think the overhead of processing active connections is 256
* times higher than that of inactive connections in average. (This
* 256 times might not be accurate, we will change it later) We
* use the following formula to estimate the overhead now:
* dest->activeconns*256 + dest->inactconns
*/
return (atomic_read(&dest->activeconns) << 8) +
atomic_read(&dest->inactconns);
}
#endif /* _NET_IP_VS_H */
| BPI-SINOVOIP/BPI-Mainline-kernel | linux-4.14/include/net/ip_vs.h | C | gpl-2.0 | 47,815 |
/*
* drivers/gpu/ion/ion_priv.h
*
* Copyright (C) 2011 Google, Inc.
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef _ION_PRIV_H
#define _ION_PRIV_H
#include <linux/ion.h>
#include <linux/kref.h>
#include <linux/mm_types.h>
#include <linux/mutex.h>
#include <linux/rbtree.h>
#include <linux/sched.h>
#include <linux/shrinker.h>
#include <linux/types.h>
#include <linux/semaphore.h>
#include <linux/vmalloc.h>
#include <linux/dma-direction.h>
#include <linux/dma-buf.h>
#include <asm/cacheflush.h>
#include <plat/iovmm.h>
struct ion_buffer *ion_handle_buffer(struct ion_handle *handle);
struct ion_iovm_map {
struct list_head list;
unsigned int map_cnt;
struct device *dev;
dma_addr_t iova;
int region_id;
};
/**
* struct ion_buffer - metadata for a particular buffer
* @ref: refernce count
* @node: node in the ion_device buffers tree
* @dev: back pointer to the ion_device
* @heap: back pointer to the heap the buffer came from
* @flags: buffer specific flags
* @size: size of the buffer
* @priv_virt: private data to the buffer representable as
* a void *
* @priv_phys: private data to the buffer representable as
* an ion_phys_addr_t (and someday a phys_addr_t)
* @lock: protects the buffers cnt fields
* @kmap_cnt: number of times the buffer is mapped to the kernel
* @vaddr: the kenrel mapping if kmap_cnt is not zero
* @dmap_cnt: number of times the buffer is mapped for dma
* @sg_table: the sg table for the buffer if dmap_cnt is not zero
* @dirty: bitmask representing which pages of this buffer have
* been dirtied by the cpu and need cache maintenance
* before dma
* @vmas: list of vma's mapping this buffer
* @handle_count: count of handles referencing this buffer
* @task_comm: taskcomm of last client to reference this buffer in a
* handle, used for debugging
* @pid: pid of last client to reference this buffer in a
* handle, used for debugging
* @dma_address: dma address of this buffer for ion_device.special_dev
*/
struct ion_buffer {
struct kref ref;
union {
struct rb_node node;
struct list_head list;
};
struct ion_device *dev;
struct ion_heap *heap;
unsigned long flags;
size_t size;
union {
void *priv_virt;
ion_phys_addr_t priv_phys;
};
struct mutex lock;
int kmap_cnt;
void *vaddr;
int dmap_cnt;
struct sg_table *sg_table;
unsigned long *dirty;
struct list_head vmas;
struct list_head iovas;
/* used to track orphaned buffers */
int handle_count;
char task_comm[TASK_COMM_LEN];
pid_t pid;
dma_addr_t dma_address[IOVMM_MAX_NUM_ID];
};
/**
* struct ion_heap_ops - ops to operate on a given heap
* @allocate: allocate memory
* @free: free memory
* @phys get physical address of a buffer (only define on
* physically contiguous heaps)
* @map_dma map the memory for dma to a scatterlist
* @unmap_dma unmap the memory for dma
* @map_kernel map memory to the kernel
* @unmap_kernel unmap memory to the kernel
* @map_user map memory to userspace
*/
struct ion_heap_ops {
int (*allocate) (struct ion_heap *heap,
struct ion_buffer *buffer, unsigned long len,
unsigned long align, unsigned long flags);
void (*free) (struct ion_buffer *buffer);
int (*phys) (struct ion_heap *heap, struct ion_buffer *buffer,
ion_phys_addr_t *addr, size_t *len);
struct sg_table *(*map_dma) (struct ion_heap *heap,
struct ion_buffer *buffer);
void (*unmap_dma) (struct ion_heap *heap, struct ion_buffer *buffer);
void * (*map_kernel) (struct ion_heap *heap, struct ion_buffer *buffer);
void (*unmap_kernel) (struct ion_heap *heap, struct ion_buffer *buffer);
int (*map_user) (struct ion_heap *mapper, struct ion_buffer *buffer,
struct vm_area_struct *vma);
};
/* [INTERNAL USE ONLY] flush needed before first use */
#define ION_FLAG_READY_TO_USE (1 << 13)
/* [INTERNAL USE ONLY] threshold value for whole cache flush */
#define ION_FLUSH_ALL_HIGHLIMIT SZ_8M
#define ION_FLUSH_ALL_LOWLIMIT SZ_256K
/**
* heap flags - flags between the heaps and core ion code
*/
#define ION_HEAP_FLAG_DEFER_FREE (1 << 0)
/**
* struct ion_heap - represents a heap in the system
* @node: rb node to put the heap on the device's tree of heaps
* @dev: back pointer to the ion_device
* @type: type of heap
* @ops: ops struct as above
* @flags: flags
* @id: id of heap, also indicates priority of this heap when
* allocating. These are specified by platform data and
* MUST be unique
* @name: used for debugging
* @free_list: free list head if deferred free is used
* @lock: protects the free list
* @waitqueue: queue to wait on from deferred free thread
* @task: task struct of deferred free thread
* @vm_sem: semaphore for reserved_vm_area
* @page_idx: index of reserved_vm_area slots
* @reserved_vm_area: reserved vm area
* @pte: pte lists for reserved_vm_area
* @debug_show: called when heap debug file is read to add any
* heap specific debug info to output
*
* Represents a pool of memory from which buffers can be made. In some
* systems the only heap is regular system memory allocated via vmalloc.
* On others, some blocks might require large physically contiguous buffers
* that are allocated from a specially reserved heap.
*/
struct ion_heap {
struct plist_node node;
struct ion_device *dev;
enum ion_heap_type type;
struct ion_heap_ops *ops;
unsigned long flags;
unsigned int id;
const char *name;
struct list_head free_list;
struct rt_mutex lock;
wait_queue_head_t waitqueue;
struct task_struct *task;
int (*debug_show)(struct ion_heap *heap, struct seq_file *, void *);
void (*showmem)(struct ion_heap *heap);
};
/**
* ion_buffer_cached - this ion buffer is cached
* @buffer: buffer
*
* indicates whether this ion buffer is cached
*/
static inline bool ion_buffer_cached(struct ion_buffer *buffer)
{
return !!(buffer->flags & ION_FLAG_CACHED);
}
/**
* ion_buffer_fault_user_mappings - fault in user mappings of this buffer
* @buffer: buffer
*
* indicates whether userspace mappings of this buffer will be faulted
* in, this can affect how buffers are allocated from the heap.
*/
static inline bool ion_buffer_fault_user_mappings(struct ion_buffer *buffer)
{
return (buffer->flags & ION_FLAG_CACHED) &&
!(buffer->flags & ION_FLAG_CACHED_NEEDS_SYNC);
}
static inline void ion_buffer_set_ready(struct ion_buffer *buffer)
{
buffer->flags |= ION_FLAG_READY_TO_USE;
}
static inline bool ion_buffer_need_flush_all(struct ion_buffer *buffer)
{
return buffer->size >= ION_FLUSH_ALL_HIGHLIMIT;
}
/**
* ion_device_create - allocates and returns an ion device
* @custom_ioctl: arch specific ioctl function if applicable
*
* returns a valid device or -PTR_ERR
*/
struct ion_device *ion_device_create(long (*custom_ioctl)
(struct ion_client *client,
unsigned int cmd,
unsigned long arg));
/**
* ion_device_destroy - free and device and it's resource
* @dev: the device
*/
void ion_device_destroy(struct ion_device *dev);
/**
* ion_device_add_heap - adds a heap to the ion device
* @dev: the device
* @heap: the heap to add
*/
void ion_device_add_heap(struct ion_device *dev, struct ion_heap *heap);
/**
* some helpers for common operations on buffers using the sg_table
* and vaddr fields
*/
void *ion_heap_map_kernel(struct ion_heap *, struct ion_buffer *);
void ion_heap_unmap_kernel(struct ion_heap *, struct ion_buffer *);
int ion_heap_map_user(struct ion_heap *, struct ion_buffer *,
struct vm_area_struct *);
int ion_heap_buffer_zero(struct ion_buffer *buffer);
/**
* functions for creating and destroying the built in ion heaps.
* architectures can add their own custom architecture specific
* heaps as appropriate.
*/
struct ion_heap *ion_heap_create(struct ion_platform_heap *);
void ion_heap_destroy(struct ion_heap *);
struct ion_heap *ion_system_heap_create(struct ion_platform_heap *);
void ion_system_heap_destroy(struct ion_heap *);
struct ion_heap *ion_system_contig_heap_create(struct ion_platform_heap *);
void ion_system_contig_heap_destroy(struct ion_heap *);
struct ion_heap *ion_carveout_heap_create(struct ion_platform_heap *);
void ion_carveout_heap_destroy(struct ion_heap *);
struct ion_heap *ion_chunk_heap_create(struct ion_platform_heap *);
void ion_chunk_heap_destroy(struct ion_heap *);
typedef void (*ion_device_sync_func)(const void *, size_t, int);
void ion_device_sync(struct ion_device *dev, struct sg_table *sgt,
enum dma_data_direction dir,
ion_device_sync_func sync, bool memzero);
static inline void ion_buffer_flush(const void *vaddr, size_t size, int dir)
{
dmac_flush_range(vaddr, vaddr + size);
}
static inline void ion_buffer_make_ready(struct ion_buffer *buffer)
{
if (!(buffer->flags & ION_FLAG_READY_TO_USE)) {
ion_device_sync(buffer->dev, buffer->sg_table, DMA_BIDIRECTIONAL,
(ion_buffer_cached(buffer) &&
!ion_buffer_fault_user_mappings(buffer)) ? NULL : ion_buffer_flush,
!(buffer->flags & ION_FLAG_NOZEROED));
buffer->flags |= ION_FLAG_READY_TO_USE;
}
}
/**
* kernel api to allocate/free from carveout -- used when carveout is
* used to back an architecture specific custom heap
*/
ion_phys_addr_t ion_carveout_allocate(struct ion_heap *heap, unsigned long size,
unsigned long align);
void ion_carveout_free(struct ion_heap *heap, ion_phys_addr_t addr,
unsigned long size);
/**
* The carveout heap returns physical addresses, since 0 may be a valid
* physical address, this is used to indicate allocation failed
*/
#define ION_CARVEOUT_ALLOCATE_FAIL -1
/**
* functions for creating and destroying a heap pool -- allows you
* to keep a pool of pre allocated memory to use from your heap. Keeping
* a pool of memory that is ready for dma, ie any cached mapping have been
* invalidated from the cache, provides a significant peformance benefit on
* many systems */
/**
* struct ion_page_pool - pagepool struct
* @high_count: number of highmem items in the pool
* @low_count: number of lowmem items in the pool
* @high_items: list of highmem items
* @low_items: list of lowmem items
* @shrinker: a shrinker for the items
* @mutex: lock protecting this struct and especially the count
* item list
* @alloc: function to be used to allocate pageory when the pool
* is empty
* @free: function to be used to free pageory back to the system
* when the shrinker fires
* @gfp_mask: gfp_mask to use from alloc
* @order: order of pages in the pool
* @list: plist node for list of pools
*
* Allows you to keep a pool of pre allocated pages to use from your heap.
* Keeping a pool of pages that is ready for dma, ie any cached mapping have
* been invalidated from the cache, provides a significant peformance benefit
* on many systems
*/
struct ion_page_pool {
int high_count;
int low_count;
struct list_head high_items;
struct list_head low_items;
struct mutex mutex;
void *(*alloc)(struct ion_page_pool *pool);
void (*free)(struct ion_page_pool *pool, struct page *page);
gfp_t gfp_mask;
unsigned int order;
struct plist_node list;
};
struct ion_page_pool *ion_page_pool_create(gfp_t gfp_mask, unsigned int order);
void ion_page_pool_destroy(struct ion_page_pool *);
void *ion_page_pool_alloc(struct ion_page_pool *);
void ion_page_pool_free(struct ion_page_pool *, struct page *);
#endif /* _ION_PRIV_H */
| nbars/Custom-Kernel-SM-P600 | kernel-src/drivers/gpu/ion/ion_priv.h | C | gpl-2.0 | 11,758 |
// { dg-do compile }
// 2007-04-30 Benjamin Kosnik <[email protected]>
// Copyright (C) 2007-2013 Free Software Foundation, Inc.
//
// This file is part of the GNU ISO C++ Library. This library is free
// software; you can redistribute it and/or modify it under the
// terms of the GNU General Public License as published by the
// Free Software Foundation; either version 3, or (at your option)
// any later version.
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License along
// with this library; see the file COPYING3. If not see
// <http://www.gnu.org/licenses/>.
// NB: This file is for testing type_traits with NO OTHER INCLUDES.
#include <tr1/type_traits>
namespace std
{
namespace tr1
{
typedef short test_type;
template struct remove_pointer<test_type>;
}
}
| pschorf/gcc-races | libstdc++-v3/testsuite/tr1/4_metaprogramming/remove_pointer/requirements/explicit_instantiation.cc | C++ | gpl-2.0 | 1,050 |
/*
* osk5912.c -- SoC audio for OSK 5912
*
* Copyright (C) 2008 Mistral Solutions
*
* Contact: Arun KS <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*
*/
#include <linux/clk.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include <asm/mach-types.h>
#include <mach/hardware.h>
#include <linux/gpio.h>
#include <mach/mcbsp.h>
#include "omap-mcbsp.h"
#include "omap-pcm.h"
#include "../codecs/tlv320aic23.h"
#define CODEC_CLOCK 12000000
static struct clk *tlv320aic23_mclk;
static int osk_startup(struct snd_pcm_substream *substream)
{
return clk_enable(tlv320aic23_mclk);
}
static void osk_shutdown(struct snd_pcm_substream *substream)
{
clk_disable(tlv320aic23_mclk);
}
static int osk_hw_params(struct snd_pcm_substream *substream,
struct snd_pcm_hw_params *params)
{
struct snd_soc_pcm_runtime *rtd = substream->private_data;
struct snd_soc_dai *codec_dai = rtd->dai->codec_dai;
struct snd_soc_dai *cpu_dai = rtd->dai->cpu_dai;
int err;
/* Set codec DAI configuration */
err = snd_soc_dai_set_fmt(codec_dai,
SND_SOC_DAIFMT_DSP_A |
SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_CBM_CFM);
if (err < 0) {
printk(KERN_ERR "can't set codec DAI configuration\n");
return err;
}
/* Set cpu DAI configuration */
err = snd_soc_dai_set_fmt(cpu_dai,
SND_SOC_DAIFMT_DSP_A |
SND_SOC_DAIFMT_NB_IF |
SND_SOC_DAIFMT_CBM_CFM);
if (err < 0) {
printk(KERN_ERR "can't set cpu DAI configuration\n");
return err;
}
/* Set the codec system clock for DAC and ADC */
err =
snd_soc_dai_set_sysclk(codec_dai, 0, CODEC_CLOCK, SND_SOC_CLOCK_IN);
if (err < 0) {
printk(KERN_ERR "can't set codec system clock\n");
return err;
}
return err;
}
static struct snd_soc_ops osk_ops = {
.startup = osk_startup,
.hw_params = osk_hw_params,
.shutdown = osk_shutdown,
};
static const struct snd_soc_dapm_widget tlv320aic23_dapm_widgets[] = {
SND_SOC_DAPM_HP("Headphone Jack", NULL),
SND_SOC_DAPM_LINE("Line In", NULL),
SND_SOC_DAPM_MIC("Mic Jack", NULL),
};
static const struct snd_soc_dapm_route audio_map[] = {
{"Headphone Jack", NULL, "LHPOUT"},
{"Headphone Jack", NULL, "RHPOUT"},
{"LLINEIN", NULL, "Line In"},
{"RLINEIN", NULL, "Line In"},
{"MICIN", NULL, "Mic Jack"},
};
static int osk_tlv320aic23_init(struct snd_soc_codec *codec)
{
/* Add osk5912 specific widgets */
snd_soc_dapm_new_controls(codec, tlv320aic23_dapm_widgets,
ARRAY_SIZE(tlv320aic23_dapm_widgets));
/* Set up osk5912 specific audio path audio_map */
snd_soc_dapm_add_routes(codec, audio_map, ARRAY_SIZE(audio_map));
snd_soc_dapm_enable_pin(codec, "Headphone Jack");
snd_soc_dapm_enable_pin(codec, "Line In");
snd_soc_dapm_enable_pin(codec, "Mic Jack");
snd_soc_dapm_sync(codec);
return 0;
}
/* Digital audio interface glue - connects codec <--> CPU */
static struct snd_soc_dai_link osk_dai = {
.name = "TLV320AIC23",
.stream_name = "AIC23",
.cpu_dai = &omap_mcbsp_dai[0],
.codec_dai = &tlv320aic23_dai,
.init = osk_tlv320aic23_init,
.ops = &osk_ops,
};
/* Audio machine driver */
static struct snd_soc_machine snd_soc_machine_osk = {
.name = "OSK5912",
.dai_link = &osk_dai,
.num_links = 1,
};
/* Audio subsystem */
static struct snd_soc_device osk_snd_devdata = {
.machine = &snd_soc_machine_osk,
.platform = &omap_soc_platform,
.codec_dev = &soc_codec_dev_tlv320aic23,
};
static struct platform_device *osk_snd_device;
static int __init osk_soc_init(void)
{
int err;
u32 curRate;
struct device *dev;
if (!(machine_is_omap_osk()))
return -ENODEV;
osk_snd_device = platform_device_alloc("soc-audio", -1);
if (!osk_snd_device)
return -ENOMEM;
platform_set_drvdata(osk_snd_device, &osk_snd_devdata);
osk_snd_devdata.dev = &osk_snd_device->dev;
*(unsigned int *)osk_dai.cpu_dai->private_data = 0; /* McBSP1 */
err = platform_device_add(osk_snd_device);
if (err)
goto err1;
dev = &osk_snd_device->dev;
tlv320aic23_mclk = clk_get(dev, "mclk");
if (IS_ERR(tlv320aic23_mclk)) {
printk(KERN_ERR "Could not get mclk clock\n");
return -ENODEV;
}
if (clk_get_usecount(tlv320aic23_mclk) > 0) {
/* MCLK is already in use */
printk(KERN_WARNING
"MCLK in use at %d Hz. We change it to %d Hz\n",
(uint) clk_get_rate(tlv320aic23_mclk), CODEC_CLOCK);
}
/*
* Configure 12 MHz output on MCLK.
*/
curRate = (uint) clk_get_rate(tlv320aic23_mclk);
if (curRate != CODEC_CLOCK) {
if (clk_set_rate(tlv320aic23_mclk, CODEC_CLOCK)) {
printk(KERN_ERR "Cannot set MCLK for AIC23 CODEC\n");
err = -ECANCELED;
goto err1;
}
}
printk(KERN_INFO "MCLK = %d [%d], usecount = %d\n",
(uint) clk_get_rate(tlv320aic23_mclk), CODEC_CLOCK,
clk_get_usecount(tlv320aic23_mclk));
return 0;
err1:
clk_put(tlv320aic23_mclk);
platform_device_del(osk_snd_device);
platform_device_put(osk_snd_device);
return err;
}
static void __exit osk_soc_exit(void)
{
platform_device_unregister(osk_snd_device);
}
module_init(osk_soc_init);
module_exit(osk_soc_exit);
MODULE_AUTHOR("Arun KS <[email protected]>");
MODULE_DESCRIPTION("ALSA SoC OSK 5912");
MODULE_LICENSE("GPL");
| ZhizhouTian/s3c-linux | sound/soc/omap/osk5912.c | C | gpl-2.0 | 5,838 |
/*
* OHCI HCD (Host Controller Driver) for USB.
*
* (C) Copyright 1999 Roman Weissgaerber <[email protected]>
* (C) Copyright 2000-2005 David Brownell
* (C) Copyright 2002 Hewlett-Packard Company
*
* OMAP Bus Glue
*
* Modified for OMAP by Tony Lindgren <[email protected]>
* Based on the 2.4 OMAP OHCI driver originally done by MontaVista Software Inc.
* and on ohci-sa1111.c by Christopher Hoover <[email protected]>
*
* This file is licenced under the GPL.
*/
#include <linux/signal.h> /* IRQF_DISABLED */
#include <linux/jiffies.h>
#include <linux/platform_device.h>
#include <linux/clk.h>
#include <asm/hardware.h>
#include <asm/io.h>
#include <asm/mach-types.h>
#include <asm/arch/mux.h>
#include <asm/arch/irqs.h>
#include <asm/arch/gpio.h>
#include <asm/arch/fpga.h>
#include <asm/arch/usb.h>
/* OMAP-1510 OHCI has its own MMU for DMA */
#define OMAP1510_LB_MEMSIZE 32 /* Should be same as SDRAM size */
#define OMAP1510_LB_CLOCK_DIV 0xfffec10c
#define OMAP1510_LB_MMU_CTL 0xfffec208
#define OMAP1510_LB_MMU_LCK 0xfffec224
#define OMAP1510_LB_MMU_LD_TLB 0xfffec228
#define OMAP1510_LB_MMU_CAM_H 0xfffec22c
#define OMAP1510_LB_MMU_CAM_L 0xfffec230
#define OMAP1510_LB_MMU_RAM_H 0xfffec234
#define OMAP1510_LB_MMU_RAM_L 0xfffec238
#ifndef CONFIG_ARCH_OMAP
#error "This file is OMAP bus glue. CONFIG_OMAP must be defined."
#endif
#ifdef CONFIG_TPS65010
#include <asm/arch/tps65010.h>
#else
#define LOW 0
#define HIGH 1
#define GPIO1 1
static inline int tps65010_set_gpio_out_value(unsigned gpio, unsigned value)
{
return 0;
}
#endif
extern int usb_disabled(void);
extern int ocpi_enable(void);
static struct clk *usb_host_ck;
static struct clk *usb_dc_ck;
static int host_enabled;
static int host_initialized;
static void omap_ohci_clock_power(int on)
{
if (on) {
clk_enable(usb_dc_ck);
clk_enable(usb_host_ck);
/* guesstimate for T5 == 1x 32K clock + APLL lock time */
udelay(100);
} else {
clk_disable(usb_host_ck);
clk_disable(usb_dc_ck);
}
}
/*
* Board specific gang-switched transceiver power on/off.
* NOTE: OSK supplies power from DC, not battery.
*/
static int omap_ohci_transceiver_power(int on)
{
if (on) {
if (machine_is_omap_innovator() && cpu_is_omap1510())
fpga_write(fpga_read(INNOVATOR_FPGA_CAM_USB_CONTROL)
| ((1 << 5/*usb1*/) | (1 << 3/*usb2*/)),
INNOVATOR_FPGA_CAM_USB_CONTROL);
else if (machine_is_omap_osk())
tps65010_set_gpio_out_value(GPIO1, LOW);
} else {
if (machine_is_omap_innovator() && cpu_is_omap1510())
fpga_write(fpga_read(INNOVATOR_FPGA_CAM_USB_CONTROL)
& ~((1 << 5/*usb1*/) | (1 << 3/*usb2*/)),
INNOVATOR_FPGA_CAM_USB_CONTROL);
else if (machine_is_omap_osk())
tps65010_set_gpio_out_value(GPIO1, HIGH);
}
return 0;
}
#ifdef CONFIG_ARCH_OMAP15XX
/*
* OMAP-1510 specific Local Bus clock on/off
*/
static int omap_1510_local_bus_power(int on)
{
if (on) {
omap_writel((1 << 1) | (1 << 0), OMAP1510_LB_MMU_CTL);
udelay(200);
} else {
omap_writel(0, OMAP1510_LB_MMU_CTL);
}
return 0;
}
/*
* OMAP-1510 specific Local Bus initialization
* NOTE: This assumes 32MB memory size in OMAP1510LB_MEMSIZE.
* See also arch/mach-omap/memory.h for __virt_to_dma() and
* __dma_to_virt() which need to match with the physical
* Local Bus address below.
*/
static int omap_1510_local_bus_init(void)
{
unsigned int tlb;
unsigned long lbaddr, physaddr;
omap_writel((omap_readl(OMAP1510_LB_CLOCK_DIV) & 0xfffffff8) | 0x4,
OMAP1510_LB_CLOCK_DIV);
/* Configure the Local Bus MMU table */
for (tlb = 0; tlb < OMAP1510_LB_MEMSIZE; tlb++) {
lbaddr = tlb * 0x00100000 + OMAP1510_LB_OFFSET;
physaddr = tlb * 0x00100000 + PHYS_OFFSET;
omap_writel((lbaddr & 0x0fffffff) >> 22, OMAP1510_LB_MMU_CAM_H);
omap_writel(((lbaddr & 0x003ffc00) >> 6) | 0xc,
OMAP1510_LB_MMU_CAM_L);
omap_writel(physaddr >> 16, OMAP1510_LB_MMU_RAM_H);
omap_writel((physaddr & 0x0000fc00) | 0x300, OMAP1510_LB_MMU_RAM_L);
omap_writel(tlb << 4, OMAP1510_LB_MMU_LCK);
omap_writel(0x1, OMAP1510_LB_MMU_LD_TLB);
}
/* Enable the walking table */
omap_writel(omap_readl(OMAP1510_LB_MMU_CTL) | (1 << 3), OMAP1510_LB_MMU_CTL);
udelay(200);
return 0;
}
#else
#define omap_1510_local_bus_power(x) {}
#define omap_1510_local_bus_init() {}
#endif
#ifdef CONFIG_USB_OTG
static void start_hnp(struct ohci_hcd *ohci)
{
const unsigned port = ohci_to_hcd(ohci)->self.otg_port - 1;
unsigned long flags;
otg_start_hnp(ohci->transceiver);
local_irq_save(flags);
ohci->transceiver->state = OTG_STATE_A_SUSPEND;
writel (RH_PS_PSS, &ohci->regs->roothub.portstatus [port]);
OTG_CTRL_REG &= ~OTG_A_BUSREQ;
local_irq_restore(flags);
}
#endif
/*-------------------------------------------------------------------------*/
static int ohci_omap_init(struct usb_hcd *hcd)
{
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
struct omap_usb_config *config = hcd->self.controller->platform_data;
int need_transceiver = (config->otg != 0);
int ret;
dev_dbg(hcd->self.controller, "starting USB Controller\n");
if (config->otg) {
ohci_to_hcd(ohci)->self.otg_port = config->otg;
/* default/minimum OTG power budget: 8 mA */
ohci_to_hcd(ohci)->power_budget = 8;
}
/* boards can use OTG transceivers in non-OTG modes */
need_transceiver = need_transceiver
|| machine_is_omap_h2() || machine_is_omap_h3();
if (cpu_is_omap16xx())
ocpi_enable();
#ifdef CONFIG_ARCH_OMAP_OTG
if (need_transceiver) {
ohci->transceiver = otg_get_transceiver();
if (ohci->transceiver) {
int status = otg_set_host(ohci->transceiver,
&ohci_to_hcd(ohci)->self);
dev_dbg(hcd->self.controller, "init %s transceiver, status %d\n",
ohci->transceiver->label, status);
if (status) {
if (ohci->transceiver)
put_device(ohci->transceiver->dev);
return status;
}
} else {
dev_err(hcd->self.controller, "can't find transceiver\n");
return -ENODEV;
}
}
#endif
omap_ohci_clock_power(1);
if (cpu_is_omap1510()) {
omap_1510_local_bus_power(1);
omap_1510_local_bus_init();
}
if ((ret = ohci_init(ohci)) < 0)
return ret;
/* board-specific power switching and overcurrent support */
if (machine_is_omap_osk() || machine_is_omap_innovator()) {
u32 rh = roothub_a (ohci);
/* power switching (ganged by default) */
rh &= ~RH_A_NPS;
/* TPS2045 switch for internal transceiver (port 1) */
if (machine_is_omap_osk()) {
ohci_to_hcd(ohci)->power_budget = 250;
rh &= ~RH_A_NOCP;
/* gpio9 for overcurrent detction */
omap_cfg_reg(W8_1610_GPIO9);
omap_request_gpio(9);
omap_set_gpio_direction(9, 1 /* IN */);
/* for paranoia's sake: disable USB.PUEN */
omap_cfg_reg(W4_USB_HIGHZ);
}
ohci_writel(ohci, rh, &ohci->regs->roothub.a);
distrust_firmware = 0;
} else if (machine_is_nokia770()) {
/* We require a self-powered hub, which should have
* plenty of power. */
ohci_to_hcd(ohci)->power_budget = 0;
}
/* FIXME khubd hub requests should manage power switching */
omap_ohci_transceiver_power(1);
/* board init will have already handled HMC and mux setup.
* any external transceiver should already be initialized
* too, so all configured ports use the right signaling now.
*/
return 0;
}
static void ohci_omap_stop(struct usb_hcd *hcd)
{
dev_dbg(hcd->self.controller, "stopping USB Controller\n");
omap_ohci_clock_power(0);
}
/*-------------------------------------------------------------------------*/
/**
* usb_hcd_omap_probe - initialize OMAP-based HCDs
* Context: !in_interrupt()
*
* Allocates basic resources for this USB host controller, and
* then invokes the start() method for the HCD associated with it
* through the hotplug entry's driver_data.
*/
static int usb_hcd_omap_probe (const struct hc_driver *driver,
struct platform_device *pdev)
{
int retval, irq;
struct usb_hcd *hcd = 0;
struct ohci_hcd *ohci;
if (pdev->num_resources != 2) {
printk(KERN_ERR "hcd probe: invalid num_resources: %i\n",
pdev->num_resources);
return -ENODEV;
}
if (pdev->resource[0].flags != IORESOURCE_MEM
|| pdev->resource[1].flags != IORESOURCE_IRQ) {
printk(KERN_ERR "hcd probe: invalid resource type\n");
return -ENODEV;
}
usb_host_ck = clk_get(0, "usb_hhc_ck");
if (IS_ERR(usb_host_ck))
return PTR_ERR(usb_host_ck);
if (!cpu_is_omap1510())
usb_dc_ck = clk_get(0, "usb_dc_ck");
else
usb_dc_ck = clk_get(0, "lb_ck");
if (IS_ERR(usb_dc_ck)) {
clk_put(usb_host_ck);
return PTR_ERR(usb_dc_ck);
}
hcd = usb_create_hcd (driver, &pdev->dev, pdev->dev.bus_id);
if (!hcd) {
retval = -ENOMEM;
goto err0;
}
hcd->rsrc_start = pdev->resource[0].start;
hcd->rsrc_len = pdev->resource[0].end - pdev->resource[0].start + 1;
if (!request_mem_region(hcd->rsrc_start, hcd->rsrc_len, hcd_name)) {
dev_dbg(&pdev->dev, "request_mem_region failed\n");
retval = -EBUSY;
goto err1;
}
hcd->regs = (void __iomem *) (int) IO_ADDRESS(hcd->rsrc_start);
ohci = hcd_to_ohci(hcd);
ohci_hcd_init(ohci);
host_initialized = 0;
host_enabled = 1;
irq = platform_get_irq(pdev, 0);
if (irq < 0) {
retval = -ENXIO;
goto err2;
}
retval = usb_add_hcd(hcd, irq, IRQF_DISABLED);
if (retval)
goto err2;
host_initialized = 1;
if (!host_enabled)
omap_ohci_clock_power(0);
return 0;
err2:
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
err1:
usb_put_hcd(hcd);
err0:
clk_put(usb_dc_ck);
clk_put(usb_host_ck);
return retval;
}
/* may be called with controller, bus, and devices active */
/**
* usb_hcd_omap_remove - shutdown processing for OMAP-based HCDs
* @dev: USB Host Controller being removed
* Context: !in_interrupt()
*
* Reverses the effect of usb_hcd_omap_probe(), first invoking
* the HCD's stop() method. It is always called from a thread
* context, normally "rmmod", "apmd", or something similar.
*/
static inline void
usb_hcd_omap_remove (struct usb_hcd *hcd, struct platform_device *pdev)
{
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
usb_remove_hcd(hcd);
if (ohci->transceiver) {
(void) otg_set_host(ohci->transceiver, 0);
put_device(ohci->transceiver->dev);
}
if (machine_is_omap_osk())
omap_free_gpio(9);
release_mem_region(hcd->rsrc_start, hcd->rsrc_len);
usb_put_hcd(hcd);
clk_put(usb_dc_ck);
clk_put(usb_host_ck);
}
/*-------------------------------------------------------------------------*/
static int
ohci_omap_start (struct usb_hcd *hcd)
{
struct omap_usb_config *config;
struct ohci_hcd *ohci = hcd_to_ohci (hcd);
int ret;
if (!host_enabled)
return 0;
config = hcd->self.controller->platform_data;
if (config->otg || config->rwc) {
ohci->hc_control = OHCI_CTRL_RWC;
writel(OHCI_CTRL_RWC, &ohci->regs->control);
}
if ((ret = ohci_run (ohci)) < 0) {
dev_err(hcd->self.controller, "can't start\n");
ohci_stop (hcd);
return ret;
}
return 0;
}
/*-------------------------------------------------------------------------*/
static const struct hc_driver ohci_omap_hc_driver = {
.description = hcd_name,
.product_desc = "OMAP OHCI",
.hcd_priv_size = sizeof(struct ohci_hcd),
/*
* generic hardware linkage
*/
.irq = ohci_irq,
.flags = HCD_USB11 | HCD_MEMORY,
/*
* basic lifecycle operations
*/
.reset = ohci_omap_init,
.start = ohci_omap_start,
.stop = ohci_omap_stop,
.shutdown = ohci_shutdown,
/*
* managing i/o requests and associated device resources
*/
.urb_enqueue = ohci_urb_enqueue,
.urb_dequeue = ohci_urb_dequeue,
.endpoint_disable = ohci_endpoint_disable,
/*
* scheduling support
*/
.get_frame_number = ohci_get_frame,
/*
* root hub support
*/
.hub_status_data = ohci_hub_status_data,
.hub_control = ohci_hub_control,
.hub_irq_enable = ohci_rhsc_enable,
#ifdef CONFIG_PM
.bus_suspend = ohci_bus_suspend,
.bus_resume = ohci_bus_resume,
#endif
.start_port_reset = ohci_start_port_reset,
};
/*-------------------------------------------------------------------------*/
static int ohci_hcd_omap_drv_probe(struct platform_device *dev)
{
return usb_hcd_omap_probe(&ohci_omap_hc_driver, dev);
}
static int ohci_hcd_omap_drv_remove(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
usb_hcd_omap_remove(hcd, dev);
platform_set_drvdata(dev, NULL);
return 0;
}
/*-------------------------------------------------------------------------*/
#ifdef CONFIG_PM
static int ohci_omap_suspend(struct platform_device *dev, pm_message_t message)
{
struct ohci_hcd *ohci = hcd_to_ohci(platform_get_drvdata(dev));
if (time_before(jiffies, ohci->next_statechange))
msleep(5);
ohci->next_statechange = jiffies;
omap_ohci_clock_power(0);
ohci_to_hcd(ohci)->state = HC_STATE_SUSPENDED;
return 0;
}
static int ohci_omap_resume(struct platform_device *dev)
{
struct usb_hcd *hcd = platform_get_drvdata(dev);
struct ohci_hcd *ohci = hcd_to_ohci(hcd);
if (time_before(jiffies, ohci->next_statechange))
msleep(5);
ohci->next_statechange = jiffies;
omap_ohci_clock_power(1);
ohci_finish_controller_resume(hcd);
return 0;
}
#endif
/*-------------------------------------------------------------------------*/
/*
* Driver definition to register with the OMAP bus
*/
static struct platform_driver ohci_hcd_omap_driver = {
.probe = ohci_hcd_omap_drv_probe,
.remove = ohci_hcd_omap_drv_remove,
.shutdown = usb_hcd_platform_shutdown,
#ifdef CONFIG_PM
.suspend = ohci_omap_suspend,
.resume = ohci_omap_resume,
#endif
.driver = {
.owner = THIS_MODULE,
.name = "ohci",
},
};
| ghmajx/asuswrt-merlin | release/src-rt/linux/linux-2.6/drivers/usb/host/ohci-omap.c | C | gpl-2.0 | 13,473 |
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/safe_browsing/ping_manager.h"
#include "base/logging.h"
#include "base/stl_util.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "chrome/common/env_vars.h"
#include "content/public/browser/browser_thread.h"
#include "google_apis/google_api_keys.h"
#include "net/base/escape.h"
#include "net/base/load_flags.h"
#include "net/url_request/url_fetcher.h"
#include "net/url_request/url_request_context_getter.h"
#include "net/url_request/url_request_status.h"
using content::BrowserThread;
// SafeBrowsingPingManager implementation ----------------------------------
// static
SafeBrowsingPingManager* SafeBrowsingPingManager::Create(
net::URLRequestContextGetter* request_context_getter,
const SafeBrowsingProtocolConfig& config) {
DCHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
return new SafeBrowsingPingManager(request_context_getter, config);
}
SafeBrowsingPingManager::SafeBrowsingPingManager(
net::URLRequestContextGetter* request_context_getter,
const SafeBrowsingProtocolConfig& config)
: client_name_(config.client_name),
request_context_getter_(request_context_getter),
url_prefix_(config.url_prefix) {
DCHECK(!url_prefix_.empty());
version_ = SafeBrowsingProtocolManagerHelper::Version();
}
SafeBrowsingPingManager::~SafeBrowsingPingManager() {
// Delete in-progress safebrowsing reports (hits and details).
STLDeleteContainerPointers(safebrowsing_reports_.begin(),
safebrowsing_reports_.end());
}
// net::URLFetcherDelegate implementation ----------------------------------
// All SafeBrowsing request responses are handled here.
void SafeBrowsingPingManager::OnURLFetchComplete(
const net::URLFetcher* source) {
Reports::iterator sit = safebrowsing_reports_.find(source);
DCHECK(sit != safebrowsing_reports_.end());
delete *sit;
safebrowsing_reports_.erase(sit);
}
// Sends a SafeBrowsing "hit" for UMA users.
void SafeBrowsingPingManager::ReportSafeBrowsingHit(
const GURL& malicious_url,
const GURL& page_url,
const GURL& referrer_url,
bool is_subresource,
SBThreatType threat_type,
const std::string& post_data) {
GURL report_url = SafeBrowsingHitUrl(malicious_url, page_url,
referrer_url, is_subresource,
threat_type);
net::URLFetcher* report = net::URLFetcher::Create(
report_url,
post_data.empty() ? net::URLFetcher::GET : net::URLFetcher::POST,
this);
report->SetLoadFlags(net::LOAD_DISABLE_CACHE);
report->SetRequestContext(request_context_getter_.get());
if (!post_data.empty())
report->SetUploadData("text/plain", post_data);
safebrowsing_reports_.insert(report);
report->Start();
}
// Sends malware details for users who opt-in.
void SafeBrowsingPingManager::ReportMalwareDetails(
const std::string& report) {
GURL report_url = MalwareDetailsUrl();
net::URLFetcher* fetcher = net::URLFetcher::Create(
report_url, net::URLFetcher::POST, this);
fetcher->SetLoadFlags(net::LOAD_DISABLE_CACHE);
fetcher->SetRequestContext(request_context_getter_.get());
fetcher->SetUploadData("application/octet-stream", report);
// Don't try too hard to send reports on failures.
fetcher->SetAutomaticallyRetryOn5xx(false);
fetcher->Start();
safebrowsing_reports_.insert(fetcher);
}
GURL SafeBrowsingPingManager::SafeBrowsingHitUrl(
const GURL& malicious_url, const GURL& page_url,
const GURL& referrer_url, bool is_subresource,
SBThreatType threat_type) const {
DCHECK(threat_type == SB_THREAT_TYPE_URL_MALWARE ||
threat_type == SB_THREAT_TYPE_URL_PHISHING ||
threat_type == SB_THREAT_TYPE_BINARY_MALWARE_URL ||
threat_type == SB_THREAT_TYPE_BINARY_MALWARE_HASH ||
threat_type == SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL ||
threat_type == SB_THREAT_TYPE_CLIENT_SIDE_MALWARE_URL);
std::string url = SafeBrowsingProtocolManagerHelper::ComposeUrl(
url_prefix_, "report", client_name_, version_, std::string());
std::string threat_list = "none";
switch (threat_type) {
case SB_THREAT_TYPE_URL_MALWARE:
threat_list = "malblhit";
break;
case SB_THREAT_TYPE_URL_PHISHING:
threat_list = "phishblhit";
break;
case SB_THREAT_TYPE_BINARY_MALWARE_URL:
threat_list = "binurlhit";
break;
case SB_THREAT_TYPE_BINARY_MALWARE_HASH:
threat_list = "binhashhit";
break;
case SB_THREAT_TYPE_CLIENT_SIDE_PHISHING_URL:
threat_list = "phishcsdhit";
break;
case SB_THREAT_TYPE_CLIENT_SIDE_MALWARE_URL:
threat_list = "malcsdhit";
break;
default:
NOTREACHED();
}
return GURL(base::StringPrintf("%s&evts=%s&evtd=%s&evtr=%s&evhr=%s&evtb=%d",
url.c_str(), threat_list.c_str(),
net::EscapeQueryParamValue(malicious_url.spec(), true).c_str(),
net::EscapeQueryParamValue(page_url.spec(), true).c_str(),
net::EscapeQueryParamValue(referrer_url.spec(), true).c_str(),
is_subresource));
}
GURL SafeBrowsingPingManager::MalwareDetailsUrl() const {
std::string url = base::StringPrintf(
"%s/clientreport/malware?client=%s&appver=%s&pver=1.0",
url_prefix_.c_str(),
client_name_.c_str(),
version_.c_str());
std::string api_key = google_apis::GetAPIKey();
if (!api_key.empty()) {
base::StringAppendF(&url, "&key=%s",
net::EscapeQueryParamValue(api_key, true).c_str());
}
return GURL(url);
}
| qtekfun/htcDesire820Kernel | external/chromium_org/chrome/browser/safe_browsing/ping_manager.cc | C++ | gpl-2.0 | 5,747 |
/**
* -----------------------------------------------------------------------------
* @package smartVISU
* @author Martin Gleiß
* @copyright 2012 - 2015
* @license GPL [http://www.gnu.de]
* -----------------------------------------------------------------------------
*/
{% extends "rooms.html" %}
{% block content %}
<h1><img class="icon" src='{{ icon0 }}sani_buffer_temp_down.svg' />Heizung</h1>
{% endblock %}
| Foxi352/smartvisu | pages/gleiss.smarthome.py/room_ug_heating.html | HTML | gpl-3.0 | 436 |
/*
===========================================================================
Doom 3 BFG Edition GPL Source Code
Copyright (C) 1993-2012 id Software LLC, a ZeniMax Media company.
This file is part of the Doom 3 BFG Edition GPL Source Code ("Doom 3 BFG Edition Source Code").
Doom 3 BFG Edition 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 BFG Edition 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 BFG Edition Source Code. If not, see <http://www.gnu.org/licenses/>.
In addition, the Doom 3 BFG Edition 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 BFG Edition 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.
===========================================================================
*/
#ifndef __HASHINDEX_H__
#define __HASHINDEX_H__
/*
===============================================================================
Fast hash table for indexes and arrays.
Does not allocate memory until the first key/index pair is added.
===============================================================================
*/
#define DEFAULT_HASH_SIZE 1024
#define DEFAULT_HASH_GRANULARITY 1024
class idHashIndex {
public:
static const int NULL_INDEX = -1;
idHashIndex();
idHashIndex( const int initialHashSize, const int initialIndexSize );
~idHashIndex();
// returns total size of allocated memory
size_t Allocated() const;
// returns total size of allocated memory including size of hash index type
size_t Size() const;
idHashIndex & operator=( const idHashIndex &other );
// add an index to the hash, assumes the index has not yet been added to the hash
void Add( const int key, const int index );
// remove an index from the hash
void Remove( const int key, const int index );
// get the first index from the hash, returns -1 if empty hash entry
int First( const int key ) const;
// get the next index from the hash, returns -1 if at the end of the hash chain
int Next( const int index ) const;
// For porting purposes...
int GetFirst( const int key ) const { return First( key ); }
int GetNext( const int index ) const { return Next( index ); }
// insert an entry into the index and add it to the hash, increasing all indexes >= index
void InsertIndex( const int key, const int index );
// remove an entry from the index and remove it from the hash, decreasing all indexes >= index
void RemoveIndex( const int key, const int index );
// clear the hash
void Clear();
// clear and resize
void Clear( const int newHashSize, const int newIndexSize );
// free allocated memory
void Free();
// get size of hash table
int GetHashSize() const;
// get size of the index
int GetIndexSize() const;
// set granularity
void SetGranularity( const int newGranularity );
// force resizing the index, current hash table stays intact
void ResizeIndex( const int newIndexSize );
// returns number in the range [0-100] representing the spread over the hash table
int GetSpread() const;
// returns a key for a string
int GenerateKey( const char *string, bool caseSensitive = true ) const;
// returns a key for a vector
int GenerateKey( const idVec3 &v ) const;
// returns a key for two integers
int GenerateKey( const int n1, const int n2 ) const;
// returns a key for a single integer
int GenerateKey( const int n ) const;
private:
int hashSize;
int * hash;
int indexSize;
int * indexChain;
int granularity;
int hashMask;
int lookupMask;
static int INVALID_INDEX[1];
void Init( const int initialHashSize, const int initialIndexSize );
void Allocate( const int newHashSize, const int newIndexSize );
};
/*
================
idHashIndex::idHashIndex
================
*/
ID_INLINE idHashIndex::idHashIndex() {
Init( DEFAULT_HASH_SIZE, DEFAULT_HASH_SIZE );
}
/*
================
idHashIndex::idHashIndex
================
*/
ID_INLINE idHashIndex::idHashIndex( const int initialHashSize, const int initialIndexSize ) {
Init( initialHashSize, initialIndexSize );
}
/*
================
idHashIndex::~idHashIndex
================
*/
ID_INLINE idHashIndex::~idHashIndex() {
Free();
}
/*
================
idHashIndex::Allocated
================
*/
ID_INLINE size_t idHashIndex::Allocated() const {
return hashSize * sizeof( int ) + indexSize * sizeof( int );
}
/*
================
idHashIndex::Size
================
*/
ID_INLINE size_t idHashIndex::Size() const {
return sizeof( *this ) + Allocated();
}
/*
================
idHashIndex::operator=
================
*/
ID_INLINE idHashIndex &idHashIndex::operator=( const idHashIndex &other ) {
granularity = other.granularity;
hashMask = other.hashMask;
lookupMask = other.lookupMask;
if ( other.lookupMask == 0 ) {
hashSize = other.hashSize;
indexSize = other.indexSize;
Free();
}
else {
if ( other.hashSize != hashSize || hash == INVALID_INDEX ) {
if ( hash != INVALID_INDEX ) {
delete[] hash;
}
hashSize = other.hashSize;
hash = new (TAG_IDLIB_HASH) int[hashSize];
}
if ( other.indexSize != indexSize || indexChain == INVALID_INDEX ) {
if ( indexChain != INVALID_INDEX ) {
delete[] indexChain;
}
indexSize = other.indexSize;
indexChain = new (TAG_IDLIB_HASH) int[indexSize];
}
memcpy( hash, other.hash, hashSize * sizeof( hash[0] ) );
memcpy( indexChain, other.indexChain, indexSize * sizeof( indexChain[0] ) );
}
return *this;
}
/*
================
idHashIndex::Add
================
*/
ID_INLINE void idHashIndex::Add( const int key, const int index ) {
int h;
assert( index >= 0 );
if ( hash == INVALID_INDEX ) {
Allocate( hashSize, index >= indexSize ? index + 1 : indexSize );
}
else if ( index >= indexSize ) {
ResizeIndex( index + 1 );
}
h = key & hashMask;
indexChain[index] = hash[h];
hash[h] = index;
}
/*
================
idHashIndex::Remove
================
*/
ID_INLINE void idHashIndex::Remove( const int key, const int index ) {
int k = key & hashMask;
if ( hash == INVALID_INDEX ) {
return;
}
if ( hash[k] == index ) {
hash[k] = indexChain[index];
}
else {
for ( int i = hash[k]; i != -1; i = indexChain[i] ) {
if ( indexChain[i] == index ) {
indexChain[i] = indexChain[index];
break;
}
}
}
indexChain[index] = -1;
}
/*
================
idHashIndex::First
================
*/
ID_INLINE int idHashIndex::First( const int key ) const {
return hash[key & hashMask & lookupMask];
}
/*
================
idHashIndex::Next
================
*/
ID_INLINE int idHashIndex::Next( const int index ) const {
assert( index >= 0 && index < indexSize );
return indexChain[index & lookupMask];
}
/*
================
idHashIndex::InsertIndex
================
*/
ID_INLINE void idHashIndex::InsertIndex( const int key, const int index ) {
int i, max;
if ( hash != INVALID_INDEX ) {
max = index;
for ( i = 0; i < hashSize; i++ ) {
if ( hash[i] >= index ) {
hash[i]++;
if ( hash[i] > max ) {
max = hash[i];
}
}
}
for ( i = 0; i < indexSize; i++ ) {
if ( indexChain[i] >= index ) {
indexChain[i]++;
if ( indexChain[i] > max ) {
max = indexChain[i];
}
}
}
if ( max >= indexSize ) {
ResizeIndex( max + 1 );
}
for ( i = max; i > index; i-- ) {
indexChain[i] = indexChain[i-1];
}
indexChain[index] = -1;
}
Add( key, index );
}
/*
================
idHashIndex::RemoveIndex
================
*/
ID_INLINE void idHashIndex::RemoveIndex( const int key, const int index ) {
int i, max;
Remove( key, index );
if ( hash != INVALID_INDEX ) {
max = index;
for ( i = 0; i < hashSize; i++ ) {
if ( hash[i] >= index ) {
if ( hash[i] > max ) {
max = hash[i];
}
hash[i]--;
}
}
for ( i = 0; i < indexSize; i++ ) {
if ( indexChain[i] >= index ) {
if ( indexChain[i] > max ) {
max = indexChain[i];
}
indexChain[i]--;
}
}
for ( i = index; i < max; i++ ) {
indexChain[i] = indexChain[i+1];
}
indexChain[max] = -1;
}
}
/*
================
idHashIndex::Clear
================
*/
ID_INLINE void idHashIndex::Clear() {
// only clear the hash table because clearing the indexChain is not really needed
if ( hash != INVALID_INDEX ) {
memset( hash, 0xff, hashSize * sizeof( hash[0] ) );
}
}
/*
================
idHashIndex::Clear
================
*/
ID_INLINE void idHashIndex::Clear( const int newHashSize, const int newIndexSize ) {
Free();
hashSize = newHashSize;
indexSize = newIndexSize;
}
/*
================
idHashIndex::GetHashSize
================
*/
ID_INLINE int idHashIndex::GetHashSize() const {
return hashSize;
}
/*
================
idHashIndex::GetIndexSize
================
*/
ID_INLINE int idHashIndex::GetIndexSize() const {
return indexSize;
}
/*
================
idHashIndex::SetGranularity
================
*/
ID_INLINE void idHashIndex::SetGranularity( const int newGranularity ) {
assert( newGranularity > 0 );
granularity = newGranularity;
}
/*
================
idHashIndex::GenerateKey
================
*/
ID_INLINE int idHashIndex::GenerateKey( const char *string, bool caseSensitive ) const {
if ( caseSensitive ) {
return ( idStr::Hash( string ) & hashMask );
} else {
return ( idStr::IHash( string ) & hashMask );
}
}
/*
================
idHashIndex::GenerateKey
================
*/
ID_INLINE int idHashIndex::GenerateKey( const idVec3 &v ) const {
return ( (((int) v[0]) + ((int) v[1]) + ((int) v[2])) & hashMask );
}
/*
================
idHashIndex::GenerateKey
================
*/
ID_INLINE int idHashIndex::GenerateKey( const int n1, const int n2 ) const {
return ( ( n1 + n2 ) & hashMask );
}
/*
================
idHashIndex::GenerateKey
================
*/
ID_INLINE int idHashIndex::GenerateKey( const int n ) const {
return n & hashMask;
}
#endif /* !__HASHINDEX_H__ */
| jslhs/DOOM-3-BFG | neo/idlib/containers/HashIndex.h | C | gpl-3.0 | 10,730 |
/**
* $Revision$
* $Date$
*
* Copyright (C) 2005-2008 Jive Software. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jivesoftware.openfire.security;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jivesoftware.database.DbConnectionManager;
import org.jivesoftware.database.SequenceManager;
import org.jivesoftware.openfire.XMPPServer;
import org.jivesoftware.util.JiveConstants;
import org.jivesoftware.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* The default security audit provider stores the logs in a ofSecurityAuditLog table.
*
* @author Daniel Henninger
*/
public class DefaultSecurityAuditProvider implements SecurityAuditProvider {
private static final Logger Log = LoggerFactory.getLogger(DefaultSecurityAuditProvider.class);
private static final String LOG_ENTRY =
"INSERT INTO ofSecurityAuditLog(msgID,username,entryStamp,summary,node,details) VALUES(?,?,?,?,?,?)";
private static final String GET_EVENTS =
"SELECT msgID,username,entryStamp,summary,node,details FROM ofSecurityAuditLog";
private static final String GET_EVENT =
"SELECT msgID,username,entryStamp,summary,node,details FROM ofSecurityAuditLog WHERE msgID=?";
private static final String GET_EVENT_COUNT =
"SELECT COUNT(msgID) FROM ofSecurityAuditLog";
/**
* Constructs a new DefaultSecurityAuditProvider
*/
public DefaultSecurityAuditProvider() {
}
/**
* The default provider logs events into a ofSecurityAuditLog table in the database.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#logEvent(String, String, String)
*/
public void logEvent(String username, String summary, String details) {
Connection con = null;
PreparedStatement pstmt = null;
try {
long msgID = SequenceManager.nextID(JiveConstants.SECURITY_AUDIT);
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(LOG_ENTRY);
pstmt.setLong(1, msgID);
pstmt.setString(2, username);
pstmt.setLong(3, new Date().getTime());
pstmt.setString(4, StringUtils.abbreviate(summary, 250));
pstmt.setString(5, XMPPServer.getInstance().getServerInfo().getHostname());
pstmt.setString(6, details);
pstmt.executeUpdate();
}
catch (SQLException e) {
Log.warn("Error trying to insert a new row in ofSecurityAuditLog: ", e);
}
finally {
DbConnectionManager.closeConnection(pstmt, con);
}
}
/**
* The default provider retrieves events from a ofSecurityAuditLog table in the database.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#getEvents(String, Integer, Integer, java.util.Date, java.util.Date)
*/
public List<SecurityAuditEvent> getEvents(String username, Integer skipEvents, Integer numEvents, Date startTime, Date endTime) {
List<SecurityAuditEvent> events = new ArrayList<SecurityAuditEvent>();
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
String sql = GET_EVENTS;
boolean addedOne = false;
if (username != null) {
sql += " WHERE username = ?";
addedOne = true;
}
if (startTime != null) {
if (!addedOne) {
sql += " WHERE";
}
else {
sql += " AND";
}
sql += " entryStamp >= ?";
addedOne = true;
}
if (endTime != null) {
if (!addedOne) {
sql += " WHERE";
}
else {
sql += " AND";
}
sql += " entryStamp <= ?";
}
sql += " ORDER BY entryStamp DESC";
try {
con = DbConnectionManager.getConnection();
pstmt = DbConnectionManager.createScrollablePreparedStatement(con, sql);
int i = 1;
if (username != null) {
pstmt.setString(i, username);
i++;
}
if (startTime != null) {
pstmt.setLong(i, startTime.getTime());
i++;
}
if (endTime != null) {
pstmt.setLong(i, endTime.getTime());
}
rs = pstmt.executeQuery();
if (skipEvents != null) {
DbConnectionManager.scrollResultSet(rs, skipEvents);
}
if (numEvents != null) {
DbConnectionManager.setFetchSize(rs, numEvents);
}
int count = 0;
while (rs.next() && count < numEvents) {
SecurityAuditEvent event = new SecurityAuditEvent();
event.setMsgID(rs.getLong(1));
event.setUsername(rs.getString(2));
event.setEventStamp(new Date(rs.getLong(3)));
event.setSummary(rs.getString(4));
event.setNode(rs.getString(5));
event.setDetails(rs.getString(6));
events.add(event);
count++;
}
}
catch (SQLException e) {
Log.error(e.getMessage(), e);
}
finally {
DbConnectionManager.closeConnection(rs, pstmt, con);
}
return events;
}
/**
* The default provider retrieves events from a ofSecurityAuditLog table in the database.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#getEvent(Integer)
*/
public SecurityAuditEvent getEvent(Integer msgID) throws EventNotFoundException {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
SecurityAuditEvent event = null;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(GET_EVENT);
pstmt.setLong(1, msgID);
rs = pstmt.executeQuery();
if (!rs.next()) {
throw new EventNotFoundException();
}
event = new SecurityAuditEvent();
event.setMsgID(rs.getLong(1));
event.setUsername(rs.getString(2));
event.setEventStamp(new Date(rs.getLong(3)));
event.setSummary(rs.getString(4));
event.setNode(rs.getString(5));
event.setDetails(rs.getString(6));
}
catch (Exception e) {
throw new EventNotFoundException();
}
finally {
DbConnectionManager.closeConnection(rs, pstmt, con);
}
return event;
}
/**
* The default provider counts the number of entries in the ofSecurityAuditLog table.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#getEventCount()
*/
public Integer getEventCount() {
Connection con = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
Integer cnt = 0;
try {
con = DbConnectionManager.getConnection();
pstmt = con.prepareStatement(GET_EVENT_COUNT);
rs = pstmt.executeQuery();
cnt = rs.getInt(1);
}
catch (Exception e) {
// Hrm. That should not occur.
Log.error("Error while looking up number of security audit events: ", e);
}
finally {
DbConnectionManager.closeConnection(rs, pstmt, con);
}
return cnt;
}
/**
* The default provider writes logs into a local Openfire database.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#isWriteOnly()
*/
public boolean isWriteOnly() {
return false;
}
/**
* The default provider uses Openfire's own audit log viewer.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#getAuditURL()
*/
public String getAuditURL() {
return null;
}
/**
* The default provider logs user events.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#blockUserEvents()
*/
public boolean blockUserEvents() {
return false;
}
/**
* The default provider logs group events.
* @see org.jivesoftware.openfire.security.SecurityAuditProvider#blockGroupEvents()
*/
public boolean blockGroupEvents() {
return false;
}
}
| wudingli/openfire | src/java/org/jivesoftware/openfire/security/DefaultSecurityAuditProvider.java | Java | apache-2.0 | 9,192 |
/*
* Copyright 2012-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.boot.actuate.health;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.junit.Before;
import org.junit.Test;
import static org.assertj.core.api.Assertions.assertThat;
/**
* Tests for {@link OrderedHealthAggregator}.
*
* @author Christian Dupuis
*/
public class OrderedHealthAggregatorTests {
private OrderedHealthAggregator healthAggregator;
@Before
public void setup() {
this.healthAggregator = new OrderedHealthAggregator();
}
@Test
public void defaultOrder() {
Map<String, Health> healths = new HashMap<>();
healths.put("h1", new Health.Builder().status(Status.DOWN).build());
healths.put("h2", new Health.Builder().status(Status.UP).build());
healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build());
healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build());
assertThat(this.healthAggregator.aggregate(healths).getStatus())
.isEqualTo(Status.DOWN);
}
@Test
public void customOrder() {
this.healthAggregator.setStatusOrder(Status.UNKNOWN, Status.UP,
Status.OUT_OF_SERVICE, Status.DOWN);
Map<String, Health> healths = new HashMap<>();
healths.put("h1", new Health.Builder().status(Status.DOWN).build());
healths.put("h2", new Health.Builder().status(Status.UP).build());
healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build());
healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build());
assertThat(this.healthAggregator.aggregate(healths).getStatus())
.isEqualTo(Status.UNKNOWN);
}
@Test
public void defaultOrderWithCustomStatus() {
Map<String, Health> healths = new HashMap<>();
healths.put("h1", new Health.Builder().status(Status.DOWN).build());
healths.put("h2", new Health.Builder().status(Status.UP).build());
healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build());
healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build());
healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build());
assertThat(this.healthAggregator.aggregate(healths).getStatus())
.isEqualTo(Status.DOWN);
}
@Test
public void customOrderWithCustomStatus() {
this.healthAggregator.setStatusOrder(
Arrays.asList("DOWN", "OUT_OF_SERVICE", "UP", "UNKNOWN", "CUSTOM"));
Map<String, Health> healths = new HashMap<>();
healths.put("h1", new Health.Builder().status(Status.DOWN).build());
healths.put("h2", new Health.Builder().status(Status.UP).build());
healths.put("h3", new Health.Builder().status(Status.UNKNOWN).build());
healths.put("h4", new Health.Builder().status(Status.OUT_OF_SERVICE).build());
healths.put("h5", new Health.Builder().status(new Status("CUSTOM")).build());
assertThat(this.healthAggregator.aggregate(healths).getStatus())
.isEqualTo(Status.DOWN);
}
}
| bclozel/spring-boot | spring-boot-project/spring-boot-actuator/src/test/java/org/springframework/boot/actuate/health/OrderedHealthAggregatorTests.java | Java | apache-2.0 | 3,468 |
//
// Copyright (c) Microsoft and contributors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Warning: This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if the
// code is regenerated.
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.Management.RecoveryServices.Models;
namespace Microsoft.Azure.Management.RecoveryServices
{
/// <summary>
/// Definition of vault usage operations for the Recovery Services
/// extension.
/// </summary>
public partial interface IReplicationUsagesOperations
{
/// <summary>
/// Get the replication usages of a vault.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the Resource group/ Cloud service containing the
/// resource/ Vault collection.
/// </param>
/// <param name='resourceName'>
/// The name of the resource.
/// </param>
/// <param name='customRequestHeaders'>
/// Request header parameters.
/// </param>
/// <param name='cancellationToken'>
/// Cancellation token.
/// </param>
/// <returns>
/// The response model for the Replication Usgaes.
/// </returns>
Task<ReplicationUsagesResponse> GetAsync(string resourceGroupName, string resourceName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken);
}
}
| nemanja88/azure-sdk-for-net | src/ResourceManagement/RecoveryServices/RecoveryServicesManagement/Generated/IReplicationUsagesOperations.cs | C# | apache-2.0 | 2,050 |
# Copyright 2016 The Kubernetes Authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
FROM centos
ADD kubelet /kubelet
RUN chmod a+rx /kubelet
RUN cp /usr/bin/nsenter /nsenter
VOLUME /var/lib/docker
VOLUME /var/lib/kubelet
CMD [ "/kubelet" ]
| anguslees/kubernetes | cluster/images/kubelet/Dockerfile | Dockerfile | apache-2.0 | 745 |
/**
* @license
* Copyright 2013 Google Inc. All rights reserved.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @fileoverview AES key wrap algorithm as described in RFC 3394. This is the
* key-wrapping method used in ECDH (see section 8, RFC 6637).
* @author [email protected] (Thai Duong)
*/
goog.provide('e2e.cipher.AesKeyWrap');
goog.require('e2e');
goog.require('e2e.async.Result');
/** @suppress {extraRequire} We need the AES algorithm to function. */
goog.require('e2e.cipher.Aes'); // TODO(user): Remove in b/15659131
goog.require('e2e.cipher.Algorithm');
goog.require('e2e.openpgp.error.InvalidArgumentsError');
goog.require('e2e.openpgp.error.UnsupportedError');
goog.require('goog.array');
goog.require('goog.asserts');
/**
* AES key wrap, as described in RFC 3394.
* @param {e2e.cipher.Aes} primitive The AES primitive to used
* for key-wrapping. It must either AES128, AES192 or AES256.
* @constructor
*/
e2e.cipher.AesKeyWrap = function(primitive) {
goog.asserts.assertObject(primitive, 'AES primitive should be defined.');
if (primitive.algorithm != e2e.cipher.Algorithm.AES128 &&
primitive.algorithm != e2e.cipher.Algorithm.AES192 &&
primitive.algorithm != e2e.cipher.Algorithm.AES256) {
throw new e2e.openpgp.error.UnsupportedError(
'Invalid key-wrapping algorithm.');
}
this.aes_ = primitive;
};
/**
* The AES primitive used to wrap or unwrap key.
* @type {e2e.cipher.Aes}
* @private
*/
e2e.cipher.AesKeyWrap.prototype.aes_;
/**
* IV used in key wrapping.
* @type {!e2e.ByteArray}
* @const
* @private
*/
e2e.cipher.AesKeyWrap.prototype.IV_ = goog.array.repeat(0xA6, 8);
/**
* Sets key-wrapping key.
* @param {!e2e.cipher.key.SymmetricKey} key The key-wrapping key.
*/
e2e.cipher.AesKeyWrap.prototype.setKey = function(key) {
goog.asserts.assertObject(this.aes_);
goog.asserts.assert(key['key'].length >= this.aes_.keySize,
'Invalid key-wrapping key.');
this.aes_.setKey(key);
};
/**
* Wraps key data with the key-wrapping key, as described in section 2.2.1 in
* RFC 3394. This key-wrapping method is used in ECDH.
* @param {!e2e.ByteArray} keyData The key data to be wrapped.
* @return {!e2e.ByteArray} The wrapped key data.
*/
e2e.cipher.AesKeyWrap.prototype.wrap = function(keyData) {
goog.asserts.assertArray(keyData,
'Key data to be wrapped should be defined.');
goog.asserts.assert(keyData.length >= 16,
'Key data to be wrapped should be at least 128 bits.');
goog.asserts.assert(keyData.length % 8 == 0,
'Key data to be wrapped should be a multiple of 8 bytes.');
// Set A = IV.
var A = this.IV_;
// For i = 1 to n
// R[i] = P[i]
var R = goog.array.clone(keyData);
var n = keyData.length / 8;
// For j = 0 to 5
// For i=1 to n
for (var j = 0; j <= 5; j++) {
for (var i = 1; i <= n; i++) {
// B = AES(K, A | R[i])
var B = goog.array.concat(A, R.slice((i - 1) * 8, i * 8));
B = e2e.async.Result.getValue(this.aes_.encrypt(B));
// A = MSB(64, B) ^ t where t = (n*j)+i
A = B.slice(0, 8);
// This is slightly incorrect if n * j + i is larger than 255.
// But that won't happen here because n is very small in ECDH's
// usage of this key-wrapping method.
A[7] ^= (n * j + i);
// R[i] = LSB(64, B)
goog.array.splice(R, (i - 1) * 8, 8);
goog.array.insertArrayAt(R, B.slice(8, 16), (i - 1) * 8);
}
}
// Set C[0] = A
// For i = 1 to n
// C[i] = R[i]
goog.array.extend(A, R);
return A;
};
/**
* Unwraps key data with the key-wrapping key, as described in section 2.2.1 in
* RFC 3394. This key-unwrapping method is used in ECDH.
* @param {!e2e.ByteArray} wrappedKeyData The key data to be unwrapped.
* @return {!e2e.ByteArray} The unwrapped key data.
*/
e2e.cipher.AesKeyWrap.prototype.unwrap = function(wrappedKeyData) {
goog.asserts.assertArray(wrappedKeyData,
'Key data to be unwrapped should be defined.');
goog.asserts.assert(wrappedKeyData.length >= 16,
'Key data to be unwrapped should be at least 128 bits.');
goog.asserts.assert(wrappedKeyData.length % 8 == 0,
'Key data to be unwrapped should be a multiple of 8 bytes.');
// Set A = C[0]
// For i = 1 to n
// R[i] = C[i]
var A = wrappedKeyData.slice(0, 8);
var R = wrappedKeyData.slice(8);
var n = wrappedKeyData.length / 8 - 1;
// For j = 5 to 0
// For i = n to 1
for (var j = 5; j >= 0; j--) {
for (var i = n; i >= 1; i--) {
// B = AES-1(K, (A ^ t) | R[i]) where t = n*j+i
A[7] ^= (n * j + i);
var B = goog.array.concat(A, R.slice((i - 1) * 8, i * 8));
B = e2e.async.Result.getValue(this.aes_.decrypt(B));
// A = MSB(64, B)
A = B.slice(0, 8);
// R[i] = LSB(64, B)
goog.array.splice(R, (i - 1) * 8, 8);
goog.array.insertArrayAt(R, B.slice(8, 16), (i - 1) * 8);
}
}
if (!e2e.compareByteArray(A, this.IV_)) {
throw new e2e.openpgp.error.InvalidArgumentsError(
'Invalid wrapped key data.');
}
return R;
};
| adhintz/end-to-end | src/javascript/crypto/e2e/openpgp/aeskeywrap.js | JavaScript | apache-2.0 | 5,570 |
/*hotsite*/
.hotsite_b {
border: 1px solid;
border-color:#d7ddde #d7ddde #cacccc #dfe4e6;
position: relative;
z-index: 4;
border-bottom: none;
}
.hotsite_wrap {
width:100%;
text-align: center;
/*IE<=7 z-index hack*/
/*overflow: hidden;*/
background-color: #fcfdff;
*position: relative;
}
.hotsite-custom {
display: none;
}
.hotsite {
background-color: #fcfdff;
/*overflow:hidden;*/
padding:0px 6px 0px 6px;
border: 1px solid;
border-color:#FFF;
border-bottom:none;
letter-spacing: -0.3em;
word-spacing:-0.3em;
float: left;
width: 944px;
}
.hotsite span {
display: inline-block;
*display:inline;
*zoom:1;
width: 110px;
/*overflow: hidden; */
vertical-align:top;
white-space: nowrap;
letter-spacing: normal;
word-spacing: normal;
margin: 6px 0px 0px 0px;
/*position:relative;*/
}
.hotsite a {
display: block;
color:#454545;
width:100%;
/*float:left;*/
overflow:hidden;
}
.hotsite .hotsite_link {
padding-top: 10px;
line-height: 28px;
text-align:center;
/*position:relative;z-index:1;*/
}
.hotsite .i-hot-sprites {
width: 48px;
height: 48px;
display: block;
margin: 0 auto;
}
.hotsite .more_trigger {
border-top-color:#f56f2f;
border-top-style:solid;
border-width:5px;
display:inline-block;
vertical-align:middle;
margin-top:2px;
}
.hotsite .hotsite-for_tn {
display: none;
}
.hotsite .more_links, .hotsite .search-form {
display: none;
position: absolute;
visibility: hidden;
}
.hotsite_link .span-hot-name {
height:22px;
margin:0;
}
.hotsite_wrap__s .hotsite-container {
height: 398px;
overflow: visible;
}
.hotsite_wrap__s .hotsite-hist {
height: 285px;
}
.hotsite {
position: relative;
height: 100%;
}
.hotsite .hs-each {
position: absolute;
top: 0;
transition: 0.5s;
-webkit-transition: 0.5s;
-o-transition: 0.5s;
-moz-transition: 0.5s;
-ms-transition: 0.5s;
}
.hotsite .hs-each li {
width: 117px;
}
.hotsite .hs-each .more_links li {
width: auto;
}
.hotsite .hs-game {
z-index: 10;
left: 2px;
}
.hotsite .hs-normal {
z-index: 30;
left: 119px;
}
.hotsite .hs-video {
z-index: 20;
right: 2px;
}
.hotsite .hs-list {
float: left;
}
.hotsite .hs-each h3,.hotsite .hs-win h3 {
position: relative;
white-space: nowrap;
letter-spacing: normal;
word-spacing: normal;
font-size: 14px;
font-weight: 700;
color: #595959;
height: 34px;
line-height: 34px;
border-bottom: 1px solid #E6EAEB;
width: 92px;
overflow: hidden;
text-overflow: ellipsis;
text-align: center;
}
.hotsite .hs-normal h3 {
width: 313px;
text-align: left;
left: 16px;
}
.hotsite .hs-video h3 {
left: 128px;
}
.hotsite .hs-game h3 {
left: 12px;
}
.hotsite .hs-hidden {
opacity: 0;
filter: alpha(opacity=0);
-webkit-transition: opacity .3s ease-in;
-o-transition: opacity .3s ease-in;
-moz-transition: opacity .3s ease-in;
-ms-transition: opacity .3s ease-in;
transition: opacity .3s ease-in;
*display: none;
}
.hs-show-normal .hs-normal,.hs-show-game .hs-game,.hs-show-video .hs-video {
z-index: 50;
}
.hs-show-normal .hs-normal .hs-hidden,.hs-show-game .hs-game .hs-hidden,.hs-show-video .hs-video .hs-hidden {
*display: block;
filter: alpha(opacity=100);
opacity: 1;
}
.hs-show-normal .hs-normal h3,.hs-show-game .hs-game h3,.hs-show-video .hs-video h3 {
visibility: hidden;
}
.hs-show-game .hs-normal h3 {
left: 136px;
}
.hotsite .hs-win {
position: absolute;
border: 2px solid #00AE71;
box-shadow: 0 0 8px #808080;
z-index: 9;
transition: 0.5s;
height: 399px;
top: -7px;
}
.hotsite .hs-win h3 {
text-align: left;
padding-left: 18px;
height: 30px;
line-height: 30px;
width: auto;
color: #ffffff;
background-color: #00AF71;
display: none;
}
.hotsite .hs-win img {
margin-right: 8px;
}
.hs-show-normal h3.hs-normal-tle,.hs-show-game h3.hs-game-tle,.hs-show-video h3.hs-video-tle {
display: block;
}
.hs-show-normal div.hs-win {
width: 467px;
left: 118px;
}
.hs-show-game div.hs-win {
width: 238px;
left: -3px;
}
.hs-show-video div.hs-win {
width: 238px;
left: 467px;
}
.hotsite .hs-hidden-left,.hotsite .hs-hidden-right {
-webkit-transition: opacity .3s ease-in;
-o-transition: opacity .3s ease-in;
-moz-transition: opacity .3s ease-in;
-ms-transition: opacity .3s ease-in;
transition: opacity .3s ease-in;
}
.hs-show-normal .hs-hidden-left,.hs-show-normal .hs-hidden-right {
*display: block;
opacity: 1;
filter: alpha(opacity=100);
}
.hs-show-game .hs-hidden-left,.hs-show-video .hs-hidden-right {
opacity: 0;
filter: alpha(opacity=0);
*display: none;
} | taohaoge/fis3 | test/diff_fis3_smarty/product_code/hao123_fis3_smarty/home/widget/hot-site-magic/ltr/ltr.css | CSS | bsd-2-clause | 5,008 |
#ifndef ALICENTRALITYSELECTIONTASK_H
#define ALICENTRALITYSELECTIONTASK_H
/* Copyright(c) 1998-2008, ALICE Experiment at CERN, All rights reserved. *
* See cxx source for full Copyright notice */
//*****************************************************
// Class AliCentralitySelectionTask
// author: Alberica Toia
//*****************************************************
#include "AliAnalysisTaskSE.h"
class TFile;
class TH1F;
class TH2F;
class TList;
class TString;
class AliESDEvent;
class AliESDtrackCuts;
class AliCentralitySelectionTask : public AliAnalysisTaskSE {
public:
AliCentralitySelectionTask();
AliCentralitySelectionTask(const char *name);
AliCentralitySelectionTask& operator= (const AliCentralitySelectionTask& ana);
AliCentralitySelectionTask(const AliCentralitySelectionTask& c);
virtual ~AliCentralitySelectionTask();
// Implementation of interface methods
virtual void UserCreateOutputObjects();
virtual void UserExec(Option_t *option);
virtual void Terminate(Option_t *option);
void SetInput(const char* input) {fAnalysisInput = input;}
void SetMCInput() {fIsMCInput = kTRUE;}
void DontUseScaling() {fUseScaling=kFALSE;}
void DontUseCleaning() {fUseCleaning=kFALSE;}
void SetFillHistos() {fFillHistos=kTRUE; DefineOutput(1, TList::Class()); }
static AliCentralitySelectionTask* AddTaskCentrality ( const Bool_t fillHistos=kTRUE, const Bool_t aod=kFALSE );
private:
Int_t SetupRun(const AliVEvent* const esd);
Bool_t IsOutlierV0MSPD(Float_t spd, Float_t v0, Int_t cent) const;
Bool_t IsOutlierV0MTPC(Int_t tracks, Float_t v0, Int_t cent) const;
Bool_t IsOutlierV0MZDC(Float_t zdc, Float_t v0) const;
Bool_t IsOutlierV0MZDCECal(Float_t zdc, Float_t v0) const;
TString fAnalysisInput; // "ESD", "AOD"
Bool_t fIsMCInput; // true when input is MC
Int_t fCurrentRun; // current run number
Bool_t fUseScaling; // flag to use scaling
Bool_t fUseCleaning; // flag to use cleaning
Bool_t fFillHistos; // flag to fill the QA histos
Float_t fV0MScaleFactor; // scale factor V0M
Float_t fSPDScaleFactor; // scale factor SPD
Float_t fTPCScaleFactor; // scale factor TPC
Float_t fV0MScaleFactorMC; // scale factor V0M for MC
Float_t fV0MSPDOutlierPar0; // outliers parameter
Float_t fV0MSPDOutlierPar1; // outliers parameter
Float_t fV0MTPCOutlierPar0; // outliers parameter
Float_t fV0MTPCOutlierPar1; // outliers parameter
Float_t fV0MSPDSigmaOutlierPar0; // outliers parameter
Float_t fV0MSPDSigmaOutlierPar1; // outliers parameter
Float_t fV0MSPDSigmaOutlierPar2; // outliers parameter
Float_t fV0MTPCSigmaOutlierPar0; // outliers parameter
Float_t fV0MTPCSigmaOutlierPar1; // outliers parameter
Float_t fV0MTPCSigmaOutlierPar2; // outliers parameter
Float_t fV0MZDCOutlierPar0; // outliers parameter
Float_t fV0MZDCOutlierPar1; // outliers parameter
Float_t fV0MZDCEcalOutlierPar0; // outliers parameter
Float_t fV0MZDCEcalOutlierPar1; // outliers parameter
AliESDtrackCuts* fTrackCuts; //! optional track cuts
AliESDtrackCuts* fEsdTrackCuts; //! optional track cuts
AliESDtrackCuts* fEsdTrackCutsExtra1; //! optional track cuts
AliESDtrackCuts* fEsdTrackCutsExtra2; //! optional track cuts
Float_t fZVCut; //! z-vertex cut (in cm)
Float_t fOutliersCut; //! outliers cut (in n-sigma)
Int_t fQuality; //! quality for centrality determination
Bool_t fIsSelected; //! V0BG rejection
Bool_t fMSL; //!
Bool_t fMSH; //!
Bool_t fMUL; //!
Bool_t fMLL; //!
Bool_t fEJE; //!
Bool_t fEGA; //!
Bool_t fPHS; //!
Bool_t fMB; //! if the event is MB
Bool_t fCVHN; //! if the event is central trigger
Bool_t fCVLN; //! if the event is semicentral trigger
Bool_t fCVHNbit; //! if the event is central trigger
Bool_t fCVLNbit; //! if the event is semicentral trigger
Bool_t fCCENT; //! if the event is central trigger
Bool_t fCSEMI; //! if the event is semicentral trigger
Bool_t fCCENTbit; //! if the event is central trigger
Bool_t fCSEMIbit; //! if the event is semicentral trigger
Float_t fCentV0M; // percentile centrality from V0
Float_t fCentV0A; // percentile centrality from V0A
Float_t fCentV0A0; // percentile centrality from V0A-123
Float_t fCentV0A123; // percentile centrality from V0A-123
Float_t fCentV0C; // percentile centrality from V0C
Float_t fCentV0A23; // percentile centrality from V0A rings 23
Float_t fCentV0C01; // percentile centrality from V0C rings 01
Float_t fCentV0S; // percentile centrality from V0A23 and V0C01
Float_t fCentV0MEq; // percentile centrality from V0 equalized channel
Float_t fCentV0AEq; // percentile centrality from V0A equalized channel
Float_t fCentV0CEq; // percentile centrality from V0C equalized channel
Float_t fCentFMD; // percentile centrality from FMD
Float_t fCentTRK; // percentile centrality from tracks
Float_t fCentTKL; // percentile centrality from tracklets
Float_t fCentCL0; // percentile centrality from clusters in layer 0
Float_t fCentCL1; // percentile centrality from clusters in layer 1
Float_t fCentCND; // percentile centrality from candle
Float_t fCentZNA; // percentile centrality from ZNA
Float_t fCentZNC; // percentile centrality from ZNC
Float_t fCentZPA; // percentile centrality from ZPA
Float_t fCentZPC; // percentile centrality from ZPC
Float_t fCentNPA; // percentile centrality from Npart (MC)
Float_t fCentV0MvsFMD; // percentile centrality from V0 vs FMD
Float_t fCentTKLvsV0M; // percentile centrality from tracklets vs V0
Float_t fCentZEMvsZDC; // percentile centrality from ZEM vs ZDC
Float_t fCentV0Mtrue; // percentile centrality from true (sim) V0A+V0C
Float_t fCentV0Atrue; // percentile centrality from true (sim) V0A
Float_t fCentV0Ctrue; // percentile centrality from true (sim) V0C
Float_t fCentV0MEqtrue; // percentile centrality from true (sim) V0A+V0C equalized channel
Float_t fCentV0AEqtrue; // percentile centrality from true (sim) V0A equalized channel
Float_t fCentV0CEqtrue; // percentile centrality from true (sim) V0C equalized channel
Float_t fCentFMDtrue; // percentile centrality from true (sim) FMD
Float_t fCentTRKtrue; // percentile centrality from true (sim) tracks
Float_t fCentTKLtrue; // percentile centrality from true (sim) tracklets
Float_t fCentCL0true; // percentile centrality from true (sim) Clusters in layer 0
Float_t fCentCL1true; // percentile centrality from true (sim) Clusters in layer 1
Float_t fCentCNDtrue; // percentile centrality from true (sim) tracks (candle condition)
Float_t fCentZNAtrue; // percentile centrality from true (sim) ZNA
Float_t fCentZNCtrue; // percentile centrality from true (sim) ZNC
Float_t fCentZPAtrue; // percentile centrality from true (sim) ZPA
Float_t fCentZPCtrue; // percentile centrality from true (sim) ZPC
TH1F *fHtempV0M; // histogram with centrality vs multiplicity using V0
TH1F *fHtempV0A; // histogram with centrality vs multiplicity using V0A
TH1F *fHtempV0A0; // histogram with centrality vs multiplicity using V0A-123
TH1F *fHtempV0A123; // histogram with centrality vs multiplicity using V0A-123
TH1F *fHtempV0C; // histogram with centrality vs multiplicity using V0C
TH1F *fHtempV0A23; // histogram with centrality vs multiplicity using V0A-23
TH1F *fHtempV0C01; // histogram with centrality vs multiplicity using V0C-01
TH1F *fHtempV0S; // histogram with centrality vs multiplicity using V0A23 and V0C01
TH1F *fHtempV0MEq; // histogram with centrality vs multiplicity using V0 equalized channel
TH1F *fHtempV0AEq; // histogram with centrality vs multiplicity using V0A equalized channel
TH1F *fHtempV0CEq; // histogram with centrality vs multiplicity using V0C equalized channel
TH1F *fHtempFMD; // histogram with centrality vs multiplicity using FMD
TH1F *fHtempTRK; // histogram with centrality vs multiplicity using tracks
TH1F *fHtempTKL; // histogram with centrality vs multiplicity using tracklets
TH1F *fHtempCL0; // histogram with centrality vs multiplicity using clusters in layer 0
TH1F *fHtempCL1; // histogram with centrality vs multiplicity using clusters in layer 1
TH1F *fHtempCND; // histogram with centrality vs multiplicity using candle
TH1F *fHtempZNA; // histogram with centrality vs multiplicity using ZNA
TH1F *fHtempZNC; // histogram with centrality vs multiplicity using ZNC
TH1F *fHtempZPA; // histogram with centrality vs multiplicity using ZPA
TH1F *fHtempZPC; // histogram with centrality vs multiplicity using ZPC
TH1F *fHtempV0MvsFMD; // histogram with centrality vs multiplicity using V0 vs FMD
TH1F *fHtempTKLvsV0M; // histogram with centrality vs multiplicity using tracklets vs V0
TH2F *fHtempZEMvsZDC; // histogram with centrality vs multiplicity using ZEM vs ZDC
TH1F *fHtempNPA; // histogram with centrality vs multiplicity using Npart
TH1F *fHtempV0Mtrue; // histogram with centrality true (sim) vs multiplicity using V0
TH1F *fHtempV0Atrue; // histogram with centrality true (sim) vs multiplicity using V0A
TH1F *fHtempV0Ctrue; // histogram with centrality true (sim) vs multiplicity using V0C
TH1F *fHtempV0MEqtrue; // histogram with centrality true (sim) vs multiplicity using V0 equalized channel
TH1F *fHtempV0AEqtrue; // histogram with centrality true (sim) vs multiplicity using V0A equalized channel
TH1F *fHtempV0CEqtrue; // histogram with centrality true (sim) vs multiplicity using V0C equalized channel
TH1F *fHtempFMDtrue; // histogram with centrality true (sim) vs multiplicity using FMD
TH1F *fHtempTRKtrue; // histogram with centrality true (sim) vs multiplicity using tracks
TH1F *fHtempTKLtrue; // histogram with centrality true (sim) vs multiplicity using tracklets
TH1F *fHtempCL0true; // histogram with centrality true (sim) vs multiplicity using clusters in layer 0
TH1F *fHtempCL1true; // histogram with centrality true (sim) vs multiplicity using clusters in layer 1
TH1F *fHtempCNDtrue; // histogram with centrality true (sim) vs multiplicity using candle
TH1F *fHtempZNAtrue; // histogram with centrality true (sim) vs multiplicity using ZNA
TH1F *fHtempZNCtrue; // histogram with centrality true (sim) vs multiplicity using ZNC
TH1F *fHtempZPAtrue; // histogram with centrality true (sim) vs multiplicity using ZPA
TH1F *fHtempZPCtrue; // histogram with centrality true (sim) vs multiplicity using ZPC
TList *fOutputList; // output list
TH1F *fHOutCentV0M ; //control histogram for centrality
TH1F *fHOutCentV0A ; //control histogram for centrality
TH1F *fHOutCentV0A0 ; //control histogram for centrality
TH1F *fHOutCentV0A123 ; //control histogram for centrality
TH1F *fHOutCentV0C ; //control histogram for centrality
TH1F *fHOutCentV0A23 ; //control histogram for centrality
TH1F *fHOutCentV0C01 ; //control histogram for centrality
TH1F *fHOutCentV0S ; //control histogram for centrality
TH1F *fHOutCentV0MEq ; //control histogram for centrality
TH1F *fHOutCentV0AEq ; //control histogram for centrality
TH1F *fHOutCentV0CEq ; //control histogram for centrality
TH1F *fHOutCentV0MCVHN; //control histogram for centrality
TH1F *fHOutCentV0MCVLN; //control histogram for centrality
TH1F *fHOutCentV0MCVHNinMB; //control histogram for centrality
TH1F *fHOutCentV0MCVLNinMB; //control histogram for centrality
TH1F *fHOutCentV0MCCENT; //control histogram for centrality
TH1F *fHOutCentV0MCSEMI; //control histogram for centrality
TH1F *fHOutCentV0MCCENTinMB; //control histogram for centrality
TH1F *fHOutCentV0MCSEMIinMB; //control histogram for centrality
TH1F *fHOutCentV0MMSL; //control histogram for centrality
TH1F *fHOutCentV0MMSH; //control histogram for centrality
TH1F *fHOutCentV0MMUL; //control histogram for centrality
TH1F *fHOutCentV0MMLL; //control histogram for centrality
TH1F *fHOutCentV0MEJE; //control histogram for centrality
TH1F *fHOutCentV0MEGA; //control histogram for centrality
TH1F *fHOutCentV0MPHS; //control histogram for centrality
TH1F *fHOutCentV0MMSLinMB; //control histogram for centrality
TH1F *fHOutCentV0MMSHinMB; //control histogram for centrality
TH1F *fHOutCentV0MMULinMB; //control histogram for centrality
TH1F *fHOutCentV0MMLLinMB; //control histogram for centrality
TH1F *fHOutCentV0MEJEinMB; //control histogram for centrality
TH1F *fHOutCentV0MEGAinMB; //control histogram for centrality
TH1F *fHOutCentV0MPHSinMB; //control histogram for centrality
TH1F *fHOutCentFMD ; //control histogram for centrality
TH1F *fHOutCentTRK ; //control histogram for centrality
TH1F *fHOutCentTKL ; //control histogram for centrality
TH1F *fHOutCentCL0 ; //control histogram for centrality
TH1F *fHOutCentCL1 ; //control histogram for centrality
TH1F *fHOutCentCND ; //control histogram for centrality
TH1F *fHOutCentNPA ; //control histogram for centrality
TH1F *fHOutCentZNA ; //control histogram for centrality
TH1F *fHOutCentZNC ; //control histogram for centrality
TH1F *fHOutCentZPA ; //control histogram for centrality
TH1F *fHOutCentZPC ; //control histogram for centrality
TH1F *fHOutCentV0MvsFMD; //control histogram for centrality
TH1F *fHOutCentTKLvsV0M; //control histogram for centrality
TH1F *fHOutCentZEMvsZDC; //control histogram for centrality
TH2F *fHOutCentV0MvsCentCL1; //control histogram for centrality
TH2F *fHOutCentV0MvsCentTRK; //control histogram for centrality
TH2F *fHOutCentTRKvsCentCL1; //control histogram for centrality
TH2F *fHOutCentV0MvsCentZDC; //control histogram for centrality
TH2F *fHOutCentV0AvsCentV0C; //control histogram for centrality
TH2F *fHOutCentV0AvsCentTRK; //control histogram for centrality
TH2F *fHOutCentV0AvsCentCND; //control histogram for centrality
TH2F *fHOutCentV0AvsCentCL1; //control histogram for centrality
TH2F *fHOutCentV0CvsCentTRK; //control histogram for centrality
TH2F *fHOutCentV0CvsCentCND; //control histogram for centrality
TH2F *fHOutCentV0CvsCentCL1; //control histogram for centrality
TH2F *fHOutCentNPAvsCentV0A; //control histogram for centrality
TH2F *fHOutCentNPAvsCentV0C; //control histogram for centrality
TH2F *fHOutCentNPAvsCentTRK; //control histogram for centrality
TH2F *fHOutCentNPAvsCentCND; //control histogram for centrality
TH2F *fHOutCentNPAvsCentCL1; //control histogram for centrality
TH2F *fHOutCentZNAvsCentV0A; //control histogram for centrality
TH2F *fHOutCentZNAvsCentV0C; //control histogram for centrality
TH2F *fHOutCentZNAvsCentTRK; //control histogram for centrality
TH2F *fHOutCentZNAvsCentCND; //control histogram for centrality
TH2F *fHOutCentZNAvsCentCL1; //control histogram for centrality
TH2F *fHOutCentZNAvsCentZPA; //control histogram for centrality
TH2F *fHOutMultV0AC; //control histogram for multiplicity
TH1F *fHOutMultV0M ; //control histogram for multiplicity
TH1F *fHOutMultV0A ; //control histogram for multiplicity
TH1F *fHOutMultV0A0 ; //control histogram for multiplicity
TH1F *fHOutMultV0A123 ; //control histogram for multiplicity
TH1F *fHOutMultV0C ; //control histogram for multiplicity
TH1F *fHOutMultV0A23 ; //control histogram for multiplicity
TH1F *fHOutMultV0C01 ; //control histogram for multiplicity
TH1F *fHOutMultV0S ; //control histogram for multiplicity
TH1F *fHOutMultV0MEq ; //control histogram for multiplicity
TH1F *fHOutMultV0AEq ; //control histogram for multiplicity
TH1F *fHOutMultV0CEq ; //control histogram for multiplicity
TH1F *fHOutMultV0Mnc ; //control histogram for multiplicity
TH1F *fHOutMultV0Anc ; //control histogram for multiplicity
TH1F *fHOutMultV0Cnc ; //control histogram for multiplicity
TH1F *fHOutMultV0O ; //control histogram for multiplicity
TH2F *fHOutMultV0Cells ; //control histogram for multiplicity
TH1F *fHOutMultFMD ; //control histogram for multiplicity
TH1F *fHOutMultTRK ; //control histogram for multiplicity
TH1F *fHOutMultTKL ; //control histogram for multiplicity
TH1F *fHOutMultCL0 ; //control histogram for multiplicity
TH1F *fHOutMultCL1 ; //control histogram for multiplicity
TH1F *fHOutMultCND ; //control histogram for multiplicity
TH1F *fHOutMultNPA ; //control histogram for multiplicity
TH1F *fHOutMultZNA ; //control histogram for multiplicity
TH1F *fHOutMultZNC ; //control histogram for multiplicity
TH1F *fHOutMultZPA ; //control histogram for multiplicity
TH1F *fHOutMultZPC ; //control histogram for multiplicity
TH2F *fHOutMultV0MvsZDN; //control histogram for multiplicity
TH2F *fHOutMultZEMvsZDN; //control histogram for multiplicity
TH2F *fHOutMultV0MvsZDC; //control histogram for multiplicity
TH2F *fHOutMultZEMvsZDC; //control histogram for multiplicity
TH2F *fHOutMultZEMvsZDCw; //control histogram for multiplicity
TH2F *fHOutMultV0MvsCL1; //control histogram for multiplicity
TH2F *fHOutMultV0MvsTRK; //control histogram for multiplicity
TH2F *fHOutMultTRKvsCL1; //control histogram for multiplicity
TH2F *fHOutMultV0MvsV0O; //control histogram for multiplicity
TH2F *fHOutMultV0OvsCL1; //control histogram for multiplicity
TH2F *fHOutMultV0OvsTRK; //control histogram for multiplicity
TH2F *fHOutMultCL1vsTKL; //control histogram for multiplicity
TH2F *fHOutMultZNAvsZPA; //control histogram for multiplicity
TH1F *fHOutCentV0Mqual1 ; //control histogram for centrality quality 1
TH1F *fHOutCentTRKqual1 ; //control histogram for centrality quality 1
TH1F *fHOutCentCL1qual1 ; //control histogram for centrality quality 1
TH2F *fHOutMultV0MvsCL1qual1; //control histogram for multiplicity quality 1
TH2F *fHOutMultV0MvsTRKqual1; //control histogram for multiplicity quality 1
TH2F *fHOutMultTRKvsCL1qual1; //control histogram for multiplicity quality 1
TH1F *fHOutCentV0Mqual2 ; //control histogram for centrality quality 2
TH1F *fHOutCentTRKqual2 ; //control histogram for centrality quality 2
TH1F *fHOutCentCL1qual2 ; //control histogram for centrality quality 2
TH2F *fHOutMultV0MvsCL1qual2; //control histogram for multiplicity quality 2
TH2F *fHOutMultV0MvsTRKqual2; //control histogram for multiplicity quality 2
TH2F *fHOutMultTRKvsCL1qual2; //control histogram for multiplicity quality 2
TH1F *fHOutQuality ; //control histogram for quality
TH1F *fHOutVertex ; //control histogram for vertex SPD
TH1F *fHOutVertexT0 ; //control histogram for vertex T0
ClassDef(AliCentralitySelectionTask, 31);
};
#endif
| fcolamar/AliPhysics | OADB/AliCentralitySelectionTask.h | C | bsd-3-clause | 20,460 |
YUI.add('widget-stack', function(Y) {
/**
* Provides stackable (z-index) support for Widgets through an extension.
*
* @module widget-stack
*/
var L = Y.Lang,
UA = Y.UA,
Node = Y.Node,
Widget = Y.Widget,
ZINDEX = "zIndex",
SHIM = "shim",
VISIBLE = "visible",
BOUNDING_BOX = "boundingBox",
RENDER_UI = "renderUI",
BIND_UI = "bindUI",
SYNC_UI = "syncUI",
OFFSET_WIDTH = "offsetWidth",
OFFSET_HEIGHT = "offsetHeight",
PARENT_NODE = "parentNode",
FIRST_CHILD = "firstChild",
OWNER_DOCUMENT = "ownerDocument",
WIDTH = "width",
HEIGHT = "height",
PX = "px",
// HANDLE KEYS
SHIM_DEFERRED = "shimdeferred",
SHIM_RESIZE = "shimresize",
// Events
VisibleChange = "visibleChange",
WidthChange = "widthChange",
HeightChange = "heightChange",
ShimChange = "shimChange",
ZIndexChange = "zIndexChange",
ContentUpdate = "contentUpdate",
// CSS
STACKED = "stacked";
/**
* Widget extension, which can be used to add stackable (z-index) support to the
* base Widget class along with a shimming solution, through the
* <a href="Base.html#method_build">Base.build</a> method.
*
* @class WidgetStack
* @param {Object} User configuration object
*/
function Stack(config) {
this._stackNode = this.get(BOUNDING_BOX);
this._stackHandles = {};
// WIDGET METHOD OVERLAP
Y.after(this._renderUIStack, this, RENDER_UI);
Y.after(this._syncUIStack, this, SYNC_UI);
Y.after(this._bindUIStack, this, BIND_UI);
}
// Static Properties
/**
* Static property used to define the default attribute
* configuration introduced by WidgetStack.
*
* @property ATTRS
* @type Object
* @static
*/
Stack.ATTRS = {
/**
* @attribute shim
* @type boolean
* @default false, for all browsers other than IE6, for which a shim is enabled by default.
*
* @description Boolean flag to indicate whether or not a shim should be added to the Widgets
* boundingBox, to protect it from select box bleedthrough.
*/
shim: {
value: (UA.ie == 6)
},
/**
* @attribute zIndex
* @type number
* @default 0
* @description The z-index to apply to the Widgets boundingBox. Non-numerical values for
* zIndex will be converted to 0
*/
zIndex: {
value:1,
setter: function(val) {
return this._setZIndex(val);
}
}
};
/**
* The HTML parsing rules for the WidgetStack class.
*
* @property HTML_PARSER
* @static
* @type Object
*/
Stack.HTML_PARSER = {
zIndex: function(contentBox) {
return contentBox.getStyle(ZINDEX);
}
};
/**
* Default class used to mark the shim element
*
* @property SHIM_CLASS_NAME
* @type String
* @static
* @default "yui3-widget-shim"
*/
Stack.SHIM_CLASS_NAME = Widget.getClassName(SHIM);
/**
* Default class used to mark the boundingBox of a stacked widget.
*
* @property STACKED_CLASS_NAME
* @type String
* @static
* @default "yui3-widget-stacked"
*/
Stack.STACKED_CLASS_NAME = Widget.getClassName(STACKED);
/**
* Default markup template used to generate the shim element.
*
* @property SHIM_TEMPLATE
* @type String
* @static
*/
Stack.SHIM_TEMPLATE = '<iframe class="' + Stack.SHIM_CLASS_NAME + '" frameborder="0" title="Widget Stacking Shim" src="javascript:false" tabindex="-1" role="presentation"></iframe>';
Stack.prototype = {
/**
* Synchronizes the UI to match the Widgets stack state. This method in
* invoked after syncUI is invoked for the Widget class using YUI's aop infrastructure.
*
* @method _syncUIStack
* @protected
*/
_syncUIStack: function() {
this._uiSetShim(this.get(SHIM));
this._uiSetZIndex(this.get(ZINDEX));
},
/**
* Binds event listeners responsible for updating the UI state in response to
* Widget stack related state changes.
* <p>
* This method is invoked after bindUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
* @method _bindUIStack
* @protected
*/
_bindUIStack: function() {
this.after(ShimChange, this._afterShimChange);
this.after(ZIndexChange, this._afterZIndexChange);
},
/**
* Creates/Initializes the DOM to support stackability.
* <p>
* This method in invoked after renderUI is invoked for the Widget class
* using YUI's aop infrastructure.
* </p>
* @method _renderUIStack
* @protected
*/
_renderUIStack: function() {
this._stackNode.addClass(Stack.STACKED_CLASS_NAME);
},
/**
* Default setter for zIndex attribute changes. Normalizes zIndex values to
* numbers, converting non-numerical values to 0.
*
* @method _setZIndex
* @protected
* @param {String | Number} zIndex
* @return {Number} Normalized zIndex
*/
_setZIndex: function(zIndex) {
if (L.isString(zIndex)) {
zIndex = parseInt(zIndex, 10);
}
if (!L.isNumber(zIndex)) {
zIndex = 0;
}
return zIndex;
},
/**
* Default attribute change listener for the shim attribute, responsible
* for updating the UI, in response to attribute changes.
*
* @method _afterShimChange
* @protected
* @param {EventFacade} e The event facade for the attribute change
*/
_afterShimChange : function(e) {
this._uiSetShim(e.newVal);
},
/**
* Default attribute change listener for the zIndex attribute, responsible
* for updating the UI, in response to attribute changes.
*
* @method _afterZIndexChange
* @protected
* @param {EventFacade} e The event facade for the attribute change
*/
_afterZIndexChange : function(e) {
this._uiSetZIndex(e.newVal);
},
/**
* Updates the UI to reflect the zIndex value passed in.
*
* @method _uiSetZIndex
* @protected
* @param {number} zIndex The zindex to be reflected in the UI
*/
_uiSetZIndex: function (zIndex) {
this._stackNode.setStyle(ZINDEX, zIndex);
},
/**
* Updates the UI to enable/disable the shim. If the widget is not currently visible,
* creation of the shim is deferred until it is made visible, for performance reasons.
*
* @method _uiSetShim
* @protected
* @param {boolean} enable If true, creates/renders the shim, if false, removes it.
*/
_uiSetShim: function (enable) {
if (enable) {
// Lazy creation
if (this.get(VISIBLE)) {
this._renderShim();
} else {
this._renderShimDeferred();
}
// Eagerly attach resize handlers
//
// Required because of Event stack behavior, commit ref: cd8dddc
// Should be revisted after Ticket #2531067 is resolved.
if (UA.ie == 6) {
this._addShimResizeHandlers();
}
} else {
this._destroyShim();
}
},
/**
* Sets up change handlers for the visible attribute, to defer shim creation/rendering
* until the Widget is made visible.
*
* @method _renderShimDeferred
* @private
*/
_renderShimDeferred : function() {
this._stackHandles[SHIM_DEFERRED] = this._stackHandles[SHIM_DEFERRED] || [];
var handles = this._stackHandles[SHIM_DEFERRED],
createBeforeVisible = function(e) {
if (e.newVal) {
this._renderShim();
}
};
handles.push(this.on(VisibleChange, createBeforeVisible));
// Depending how how Ticket #2531067 is resolved, a reversal of
// commit ref: cd8dddc could lead to a more elagent solution, with
// the addition of this line here:
//
// handles.push(this.after(VisibleChange, this.sizeShim));
},
/**
* Sets up event listeners to resize the shim when the size of the Widget changes.
* <p>
* NOTE: This method is only used for IE6 currently, since IE6 doesn't support a way to
* resize the shim purely through CSS, when the Widget does not have an explicit width/height
* set.
* </p>
* @method _addShimResizeHandlers
* @private
*/
_addShimResizeHandlers : function() {
this._stackHandles[SHIM_RESIZE] = this._stackHandles[SHIM_RESIZE] || [];
var sizeShim = this.sizeShim,
handles = this._stackHandles[SHIM_RESIZE];
handles.push(this.after(VisibleChange, sizeShim));
handles.push(this.after(WidthChange, sizeShim));
handles.push(this.after(HeightChange, sizeShim));
handles.push(this.after(ContentUpdate, sizeShim));
},
/**
* Detaches any handles stored for the provided key
*
* @method _detachStackHandles
* @param String handleKey The key defining the group of handles which should be detached
* @private
*/
_detachStackHandles : function(handleKey) {
var handles = this._stackHandles[handleKey],
handle;
if (handles && handles.length > 0) {
while((handle = handles.pop())) {
handle.detach();
}
}
},
/**
* Creates the shim element and adds it to the DOM
*
* @method _renderShim
* @private
*/
_renderShim : function() {
var shimEl = this._shimNode,
stackEl = this._stackNode;
if (!shimEl) {
shimEl = this._shimNode = this._getShimTemplate();
stackEl.insertBefore(shimEl, stackEl.get(FIRST_CHILD));
this._detachStackHandles(SHIM_DEFERRED);
}
},
/**
* Removes the shim from the DOM, and detaches any related event
* listeners.
*
* @method _destroyShim
* @private
*/
_destroyShim : function() {
if (this._shimNode) {
this._shimNode.get(PARENT_NODE).removeChild(this._shimNode);
this._shimNode = null;
this._detachStackHandles(SHIM_DEFERRED);
this._detachStackHandles(SHIM_RESIZE);
}
},
/**
* For IE6, synchronizes the size and position of iframe shim to that of
* Widget bounding box which it is protecting. For all other browsers,
* this method does not do anything.
*
* @method sizeShim
*/
sizeShim: function () {
var shim = this._shimNode,
node = this._stackNode;
if (shim && UA.ie === 6 && this.get(VISIBLE)) {
shim.setStyle(WIDTH, node.get(OFFSET_WIDTH) + PX);
shim.setStyle(HEIGHT, node.get(OFFSET_HEIGHT) + PX);
}
},
/**
* Creates a cloned shim node, using the SHIM_TEMPLATE html template, for use on a new instance.
*
* @method _getShimTemplate
* @private
* @return {Node} node A new shim Node instance.
*/
_getShimTemplate : function() {
return Node.create(Stack.SHIM_TEMPLATE, this._stackNode.get(OWNER_DOCUMENT));
}
};
Y.WidgetStack = Stack;
}, '@VERSION@' ,{requires:['base-build', 'widget']});
| MisatoTremor/cdnjs | ajax/libs/yui/3.4.1pr1/widget-stack/widget-stack.js | JavaScript | mit | 12,614 |
<?php
require_once __DIR__.'/../../Base.php';
use Kanboard\Core\Security\Token;
class TokenTest extends Base
{
public function testGenerateToken()
{
$t1 = Token::getToken();
$t2 = Token::getToken();
$this->assertNotEmpty($t1);
$this->assertNotEmpty($t2);
$this->assertNotEquals($t1, $t2);
}
public function testCSRFTokens()
{
$token = new Token($this->container);
$t1 = $token->getCSRFToken();
$this->assertNotEmpty($t1);
$this->assertTrue($token->validateCSRFToken($t1));
$this->assertFalse($token->validateCSRFToken($t1));
}
}
| Shaxine/kanboard | tests/units/Core/Security/TokenTest.php | PHP | mit | 640 |
using System.Collections;
using System.Collections.Generic;
namespace System.Text.Json
{
/// <summary>
/// Supports an iteration over a JSON array.
/// </summary>
public struct JsonArrayEnumerator : IEnumerator<JsonNode>
{
private List<JsonNode>.Enumerator _enumerator;
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayEnumerator"/> class supporting an interation over provided JSON array.
/// </summary>
/// <param name="jsonArray">JSON array to iterate over.</param>
public JsonArrayEnumerator(JsonArray jsonArray) => _enumerator = jsonArray._list.GetEnumerator();
/// <summary>
/// Gets the property in the JSON array at the current position of the enumerator.
/// </summary>
public JsonNode Current => _enumerator.Current;
/// <summary>
/// Gets the property in the JSON array at the current position of the enumerator.
/// </summary>
object IEnumerator.Current => _enumerator.Current;
/// <summary>
/// Releases all resources used by the <see cref="JsonObjectEnumerator"/>.
/// </summary>
public void Dispose() => _enumerator.Dispose();
/// <summary>
/// Advances the enumerator to the next property of the JSON array.
/// </summary>
/// <returns></returns>
public bool MoveNext() => _enumerator.MoveNext();
/// <summary>
/// Sets the enumerator to its initial position, which is before the first element in the JSON array.
/// </summary>
void IEnumerator.Reset()
{
IEnumerator enumerator = _enumerator;
enumerator.Reset();
_enumerator = (List<JsonNode>.Enumerator)enumerator;
}
}
}
| ViktorHofer/corefx | src/System.Text.Json/src/System/Text/Json/Node/JsonArrayEnumerator.cs | C# | mit | 1,828 |
// Type definitions for Material Components Web 0.35
// Project: https://material.io/components/, https://github.com/material-components/material-components-web
// Definitions by: Brent Douglas <https://github.com/BrentDouglas>, Collin Kostichuk <https://github.com/ckosti>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.6
/**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import MDCComponent from 'material__base/component';
import MDCIconToggleFoundation from './foundation';
import MDCIconToggleAdapter from './adapter';
import { MDCRipple } from 'material__ripple';
export { MDCIconToggleAdapter, MDCIconToggleFoundation };
export class MDCIconToggle extends MDCComponent<MDCIconToggleAdapter, MDCIconToggleFoundation> {
static attachTo(root: Element): MDCIconToggle;
initialSyncWithDOM(): void;
readonly ripple: MDCRipple;
on: boolean;
disabled: boolean;
refreshToggleData(): void;
}
| dsebastien/DefinitelyTyped | types/material__icon-toggle/index.d.ts | TypeScript | mit | 1,547 |
/*
* Copyright 2011 The LibYuv Project Authors. All rights reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "libyuv/convert_argb.h"
#include "libyuv/cpu_id.h"
#ifdef HAVE_JPEG
#include "libyuv/mjpeg_decoder.h"
#endif
#include "libyuv/rotate_argb.h"
#include "libyuv/row.h"
#include "libyuv/video_common.h"
#ifdef __cplusplus
namespace libyuv {
extern "C" {
#endif
// Copy ARGB with optional flipping
LIBYUV_API
int ARGBCopy(const uint8* src_argb, int src_stride_argb,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
if (!src_argb || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_argb = src_argb + (height - 1) * src_stride_argb;
src_stride_argb = -src_stride_argb;
}
CopyPlane(src_argb, src_stride_argb, dst_argb, dst_stride_argb,
width * 4, height);
return 0;
}
// Convert I444 to ARGB.
LIBYUV_API
int I444ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*I444ToARGBRow)(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width) = I444ToARGBRow_C;
if (!src_y || !src_u || !src_v ||
!dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width &&
src_stride_u == width &&
src_stride_v == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = src_stride_u = src_stride_v = dst_stride_argb = 0;
}
#if defined(HAS_I444TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I444ToARGBRow = I444ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I444ToARGBRow = I444ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I444TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I444ToARGBRow = I444ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I444ToARGBRow = I444ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
I444ToARGBRow(src_y, src_u, src_v, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
src_u += src_stride_u;
src_v += src_stride_v;
}
return 0;
}
// Convert I422 to ARGB.
LIBYUV_API
int I422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*I422ToARGBRow)(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width) = I422ToARGBRow_C;
if (!src_y || !src_u || !src_v ||
!dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width &&
src_stride_u * 2 == width &&
src_stride_v * 2 == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = src_stride_u = src_stride_v = dst_stride_argb = 0;
}
#if defined(HAS_I422TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I422ToARGBRow = I422ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I422TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
I422ToARGBRow = I422ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
I422ToARGBRow = I422ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_I422TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I422ToARGBRow = I422ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I422ToARGBRow = I422ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_I422TOARGBROW_MIPS_DSPR2)
if (TestCpuFlag(kCpuHasMIPS_DSPR2) && IS_ALIGNED(width, 4) &&
IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
I422ToARGBRow = I422ToARGBRow_MIPS_DSPR2;
}
#endif
for (y = 0; y < height; ++y) {
I422ToARGBRow(src_y, src_u, src_v, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
src_u += src_stride_u;
src_v += src_stride_v;
}
return 0;
}
// Convert I411 to ARGB.
LIBYUV_API
int I411ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*I411ToARGBRow)(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width) = I411ToARGBRow_C;
if (!src_y || !src_u || !src_v ||
!dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width &&
src_stride_u * 4 == width &&
src_stride_v * 4 == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = src_stride_u = src_stride_v = dst_stride_argb = 0;
}
#if defined(HAS_I411TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
I411ToARGBRow = I411ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
I411ToARGBRow = I411ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_I411TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I411ToARGBRow = I411ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I411ToARGBRow = I411ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
I411ToARGBRow(src_y, src_u, src_v, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
src_u += src_stride_u;
src_v += src_stride_v;
}
return 0;
}
// Convert I400 to ARGB.
LIBYUV_API
int I400ToARGB_Reference(const uint8* src_y, int src_stride_y,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*YToARGBRow)(const uint8* y_buf,
uint8* rgb_buf,
int width) = YToARGBRow_C;
if (!src_y || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = dst_stride_argb = 0;
}
#if defined(HAS_YTOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
YToARGBRow = YToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
YToARGBRow = YToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_YTOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
YToARGBRow = YToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
YToARGBRow = YToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_YTOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
YToARGBRow = YToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
YToARGBRow = YToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
YToARGBRow(src_y, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
}
return 0;
}
// Convert I400 to ARGB.
LIBYUV_API
int I400ToARGB(const uint8* src_y, int src_stride_y,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*I400ToARGBRow)(const uint8* src_y, uint8* dst_argb, int pix) =
I400ToARGBRow_C;
if (!src_y || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_y = src_y + (height - 1) * src_stride_y;
src_stride_y = -src_stride_y;
}
// Coalesce rows.
if (src_stride_y == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = dst_stride_argb = 0;
}
#if defined(HAS_I400TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
I400ToARGBRow = I400ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
I400ToARGBRow = I400ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_I400TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
I400ToARGBRow = I400ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
I400ToARGBRow = I400ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
I400ToARGBRow(src_y, dst_argb, width);
src_y += src_stride_y;
dst_argb += dst_stride_argb;
}
return 0;
}
// Shuffle table for converting BGRA to ARGB.
static uvec8 kShuffleMaskBGRAToARGB = {
3u, 2u, 1u, 0u, 7u, 6u, 5u, 4u, 11u, 10u, 9u, 8u, 15u, 14u, 13u, 12u
};
// Shuffle table for converting ABGR to ARGB.
static uvec8 kShuffleMaskABGRToARGB = {
2u, 1u, 0u, 3u, 6u, 5u, 4u, 7u, 10u, 9u, 8u, 11u, 14u, 13u, 12u, 15u
};
// Shuffle table for converting RGBA to ARGB.
static uvec8 kShuffleMaskRGBAToARGB = {
1u, 2u, 3u, 0u, 5u, 6u, 7u, 4u, 9u, 10u, 11u, 8u, 13u, 14u, 15u, 12u
};
// Convert BGRA to ARGB.
LIBYUV_API
int BGRAToARGB(const uint8* src_bgra, int src_stride_bgra,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
return ARGBShuffle(src_bgra, src_stride_bgra,
dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskBGRAToARGB),
width, height);
}
// Convert ARGB to BGRA (same as BGRAToARGB).
LIBYUV_API
int ARGBToBGRA(const uint8* src_bgra, int src_stride_bgra,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
return ARGBShuffle(src_bgra, src_stride_bgra,
dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskBGRAToARGB),
width, height);
}
// Convert ABGR to ARGB.
LIBYUV_API
int ABGRToARGB(const uint8* src_abgr, int src_stride_abgr,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
return ARGBShuffle(src_abgr, src_stride_abgr,
dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskABGRToARGB),
width, height);
}
// Convert ARGB to ABGR to (same as ABGRToARGB).
LIBYUV_API
int ARGBToABGR(const uint8* src_abgr, int src_stride_abgr,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
return ARGBShuffle(src_abgr, src_stride_abgr,
dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskABGRToARGB),
width, height);
}
// Convert RGBA to ARGB.
LIBYUV_API
int RGBAToARGB(const uint8* src_rgba, int src_stride_rgba,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
return ARGBShuffle(src_rgba, src_stride_rgba,
dst_argb, dst_stride_argb,
(const uint8*)(&kShuffleMaskRGBAToARGB),
width, height);
}
// Convert RGB24 to ARGB.
LIBYUV_API
int RGB24ToARGB(const uint8* src_rgb24, int src_stride_rgb24,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*RGB24ToARGBRow)(const uint8* src_rgb, uint8* dst_argb, int pix) =
RGB24ToARGBRow_C;
if (!src_rgb24 || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_rgb24 = src_rgb24 + (height - 1) * src_stride_rgb24;
src_stride_rgb24 = -src_stride_rgb24;
}
// Coalesce rows.
if (src_stride_rgb24 == width * 3 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_rgb24 = dst_stride_argb = 0;
}
#if defined(HAS_RGB24TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
RGB24ToARGBRow = RGB24ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
RGB24ToARGBRow = RGB24ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_RGB24TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
RGB24ToARGBRow = RGB24ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
RGB24ToARGBRow = RGB24ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
RGB24ToARGBRow(src_rgb24, dst_argb, width);
src_rgb24 += src_stride_rgb24;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert RAW to ARGB.
LIBYUV_API
int RAWToARGB(const uint8* src_raw, int src_stride_raw,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*RAWToARGBRow)(const uint8* src_rgb, uint8* dst_argb, int pix) =
RAWToARGBRow_C;
if (!src_raw || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_raw = src_raw + (height - 1) * src_stride_raw;
src_stride_raw = -src_stride_raw;
}
// Coalesce rows.
if (src_stride_raw == width * 3 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_raw = dst_stride_argb = 0;
}
#if defined(HAS_RAWTOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
RAWToARGBRow = RAWToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
RAWToARGBRow = RAWToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_RAWTOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
RAWToARGBRow = RAWToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
RAWToARGBRow = RAWToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
RAWToARGBRow(src_raw, dst_argb, width);
src_raw += src_stride_raw;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert RGB565 to ARGB.
LIBYUV_API
int RGB565ToARGB(const uint8* src_rgb565, int src_stride_rgb565,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*RGB565ToARGBRow)(const uint8* src_rgb565, uint8* dst_argb, int pix) =
RGB565ToARGBRow_C;
if (!src_rgb565 || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_rgb565 = src_rgb565 + (height - 1) * src_stride_rgb565;
src_stride_rgb565 = -src_stride_rgb565;
}
// Coalesce rows.
if (src_stride_rgb565 == width * 2 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_rgb565 = dst_stride_argb = 0;
}
#if defined(HAS_RGB565TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
RGB565ToARGBRow = RGB565ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_RGB565TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
RGB565ToARGBRow = RGB565ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
RGB565ToARGBRow = RGB565ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
RGB565ToARGBRow(src_rgb565, dst_argb, width);
src_rgb565 += src_stride_rgb565;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert ARGB1555 to ARGB.
LIBYUV_API
int ARGB1555ToARGB(const uint8* src_argb1555, int src_stride_argb1555,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*ARGB1555ToARGBRow)(const uint8* src_argb1555, uint8* dst_argb,
int pix) = ARGB1555ToARGBRow_C;
if (!src_argb1555 || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_argb1555 = src_argb1555 + (height - 1) * src_stride_argb1555;
src_stride_argb1555 = -src_stride_argb1555;
}
// Coalesce rows.
if (src_stride_argb1555 == width * 2 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_argb1555 = dst_stride_argb = 0;
}
#if defined(HAS_ARGB1555TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_ARGB1555TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
ARGB1555ToARGBRow = ARGB1555ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
ARGB1555ToARGBRow(src_argb1555, dst_argb, width);
src_argb1555 += src_stride_argb1555;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert ARGB4444 to ARGB.
LIBYUV_API
int ARGB4444ToARGB(const uint8* src_argb4444, int src_stride_argb4444,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*ARGB4444ToARGBRow)(const uint8* src_argb4444, uint8* dst_argb,
int pix) = ARGB4444ToARGBRow_C;
if (!src_argb4444 || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_argb4444 = src_argb4444 + (height - 1) * src_stride_argb4444;
src_stride_argb4444 = -src_stride_argb4444;
}
// Coalesce rows.
if (src_stride_argb4444 == width * 2 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_argb4444 = dst_stride_argb = 0;
}
#if defined(HAS_ARGB4444TOARGBROW_SSE2)
if (TestCpuFlag(kCpuHasSSE2)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_SSE2;
if (IS_ALIGNED(width, 8)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_SSE2;
}
}
#endif
#if defined(HAS_ARGB4444TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
ARGB4444ToARGBRow = ARGB4444ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
ARGB4444ToARGBRow(src_argb4444, dst_argb, width);
src_argb4444 += src_stride_argb4444;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert NV12 to ARGB.
LIBYUV_API
int NV12ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_uv, int src_stride_uv,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*NV12ToARGBRow)(const uint8* y_buf,
const uint8* uv_buf,
uint8* rgb_buf,
int width) = NV12ToARGBRow_C;
if (!src_y || !src_uv || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_NV12TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
NV12ToARGBRow = NV12ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
NV12ToARGBRow = NV12ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
NV12ToARGBRow = NV12ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
NV12ToARGBRow = NV12ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
NV12ToARGBRow(src_y, src_uv, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
if (y & 1) {
src_uv += src_stride_uv;
}
}
return 0;
}
// Convert NV21 to ARGB.
LIBYUV_API
int NV21ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_uv, int src_stride_uv,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*NV21ToARGBRow)(const uint8* y_buf,
const uint8* uv_buf,
uint8* rgb_buf,
int width) = NV21ToARGBRow_C;
if (!src_y || !src_uv || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_NV21TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
NV21ToARGBRow = NV21ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
NV21ToARGBRow = NV21ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_NV21TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
NV21ToARGBRow = NV21ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
NV21ToARGBRow = NV21ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_NV21TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
NV21ToARGBRow = NV21ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
NV21ToARGBRow = NV21ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
NV21ToARGBRow(src_y, src_uv, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
if (y & 1) {
src_uv += src_stride_uv;
}
}
return 0;
}
// Convert M420 to ARGB.
LIBYUV_API
int M420ToARGB(const uint8* src_m420, int src_stride_m420,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*NV12ToARGBRow)(const uint8* y_buf,
const uint8* uv_buf,
uint8* rgb_buf,
int width) = NV12ToARGBRow_C;
if (!src_m420 || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_NV12TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
NV12ToARGBRow = NV12ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
NV12ToARGBRow = NV12ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
NV12ToARGBRow = NV12ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_NV12TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
NV12ToARGBRow = NV12ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
NV12ToARGBRow = NV12ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height - 1; y += 2) {
NV12ToARGBRow(src_m420, src_m420 + src_stride_m420 * 2, dst_argb, width);
NV12ToARGBRow(src_m420 + src_stride_m420, src_m420 + src_stride_m420 * 2,
dst_argb + dst_stride_argb, width);
dst_argb += dst_stride_argb * 2;
src_m420 += src_stride_m420 * 3;
}
if (height & 1) {
NV12ToARGBRow(src_m420, src_m420 + src_stride_m420 * 2, dst_argb, width);
}
return 0;
}
// Convert YUY2 to ARGB.
LIBYUV_API
int YUY2ToARGB(const uint8* src_yuy2, int src_stride_yuy2,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*YUY2ToARGBRow)(const uint8* src_yuy2, uint8* dst_argb, int pix) =
YUY2ToARGBRow_C;
if (!src_yuy2 || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_yuy2 = src_yuy2 + (height - 1) * src_stride_yuy2;
src_stride_yuy2 = -src_stride_yuy2;
}
// Coalesce rows.
if (src_stride_yuy2 == width * 2 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_yuy2 = dst_stride_argb = 0;
}
#if defined(HAS_YUY2TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
YUY2ToARGBRow = YUY2ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_YUY2TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 32)) {
YUY2ToARGBRow = YUY2ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_YUY2TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
YUY2ToARGBRow = YUY2ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
YUY2ToARGBRow = YUY2ToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
YUY2ToARGBRow(src_yuy2, dst_argb, width);
src_yuy2 += src_stride_yuy2;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert UYVY to ARGB.
LIBYUV_API
int UYVYToARGB(const uint8* src_uyvy, int src_stride_uyvy,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*UYVYToARGBRow)(const uint8* src_uyvy, uint8* dst_argb, int pix) =
UYVYToARGBRow_C;
if (!src_uyvy || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
src_uyvy = src_uyvy + (height - 1) * src_stride_uyvy;
src_stride_uyvy = -src_stride_uyvy;
}
// Coalesce rows.
if (src_stride_uyvy == width * 2 &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_uyvy = dst_stride_argb = 0;
}
#if defined(HAS_UYVYTOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
UYVYToARGBRow = UYVYToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 16)) {
UYVYToARGBRow = UYVYToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_UYVYTOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
UYVYToARGBRow = UYVYToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 32)) {
UYVYToARGBRow = UYVYToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_UYVYTOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
UYVYToARGBRow = UYVYToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
UYVYToARGBRow = UYVYToARGBRow_NEON;
}
}
#endif
for (y = 0; y < height; ++y) {
UYVYToARGBRow(src_uyvy, dst_argb, width);
src_uyvy += src_stride_uyvy;
dst_argb += dst_stride_argb;
}
return 0;
}
// Convert J420 to ARGB.
LIBYUV_API
int J420ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*J422ToARGBRow)(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width) = J422ToARGBRow_C;
if (!src_y || !src_u || !src_v || !dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
#if defined(HAS_J422TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
J422ToARGBRow = J422ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
J422ToARGBRow = J422ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_J422TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
J422ToARGBRow = J422ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
J422ToARGBRow = J422ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_J422TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
J422ToARGBRow = J422ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
J422ToARGBRow = J422ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_J422TOARGBROW_MIPS_DSPR2)
if (TestCpuFlag(kCpuHasMIPS_DSPR2) && IS_ALIGNED(width, 4) &&
IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
J422ToARGBRow = J422ToARGBRow_MIPS_DSPR2;
}
#endif
for (y = 0; y < height; ++y) {
J422ToARGBRow(src_y, src_u, src_v, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
if (y & 1) {
src_u += src_stride_u;
src_v += src_stride_v;
}
}
return 0;
}
// Convert J422 to ARGB.
LIBYUV_API
int J422ToARGB(const uint8* src_y, int src_stride_y,
const uint8* src_u, int src_stride_u,
const uint8* src_v, int src_stride_v,
uint8* dst_argb, int dst_stride_argb,
int width, int height) {
int y;
void (*J422ToARGBRow)(const uint8* y_buf,
const uint8* u_buf,
const uint8* v_buf,
uint8* rgb_buf,
int width) = J422ToARGBRow_C;
if (!src_y || !src_u || !src_v ||
!dst_argb ||
width <= 0 || height == 0) {
return -1;
}
// Negative height means invert the image.
if (height < 0) {
height = -height;
dst_argb = dst_argb + (height - 1) * dst_stride_argb;
dst_stride_argb = -dst_stride_argb;
}
// Coalesce rows.
if (src_stride_y == width &&
src_stride_u * 2 == width &&
src_stride_v * 2 == width &&
dst_stride_argb == width * 4) {
width *= height;
height = 1;
src_stride_y = src_stride_u = src_stride_v = dst_stride_argb = 0;
}
#if defined(HAS_J422TOARGBROW_SSSE3)
if (TestCpuFlag(kCpuHasSSSE3)) {
J422ToARGBRow = J422ToARGBRow_Any_SSSE3;
if (IS_ALIGNED(width, 8)) {
J422ToARGBRow = J422ToARGBRow_SSSE3;
}
}
#endif
#if defined(HAS_J422TOARGBROW_AVX2)
if (TestCpuFlag(kCpuHasAVX2)) {
J422ToARGBRow = J422ToARGBRow_Any_AVX2;
if (IS_ALIGNED(width, 16)) {
J422ToARGBRow = J422ToARGBRow_AVX2;
}
}
#endif
#if defined(HAS_J422TOARGBROW_NEON)
if (TestCpuFlag(kCpuHasNEON)) {
J422ToARGBRow = J422ToARGBRow_Any_NEON;
if (IS_ALIGNED(width, 8)) {
J422ToARGBRow = J422ToARGBRow_NEON;
}
}
#endif
#if defined(HAS_J422TOARGBROW_MIPS_DSPR2)
if (TestCpuFlag(kCpuHasMIPS_DSPR2) && IS_ALIGNED(width, 4) &&
IS_ALIGNED(src_y, 4) && IS_ALIGNED(src_stride_y, 4) &&
IS_ALIGNED(src_u, 2) && IS_ALIGNED(src_stride_u, 2) &&
IS_ALIGNED(src_v, 2) && IS_ALIGNED(src_stride_v, 2) &&
IS_ALIGNED(dst_argb, 4) && IS_ALIGNED(dst_stride_argb, 4)) {
J422ToARGBRow = J422ToARGBRow_MIPS_DSPR2;
}
#endif
for (y = 0; y < height; ++y) {
J422ToARGBRow(src_y, src_u, src_v, dst_argb, width);
dst_argb += dst_stride_argb;
src_y += src_stride_y;
src_u += src_stride_u;
src_v += src_stride_v;
}
return 0;
}
#ifdef __cplusplus
} // extern "C"
} // namespace libyuv
#endif
| veyesys/opencvr | velib/3rdparty/libyuv/source/convert_argb.cc | C++ | mit | 31,653 |
// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// POSIX library calls on systems which do not use the largefile
// interface.
package syscall
//sys Fstat(fd int, stat *Stat_t) (err error)
//fstat(fd _C_int, stat *Stat_t) _C_int
//sys Ftruncate(fd int, length int64) (err error)
//ftruncate(fd _C_int, length Offset_t) _C_int
//sys Lstat(path string, stat *Stat_t) (err error)
//lstat(path *byte, stat *Stat_t) _C_int
//sys mmap(addr uintptr, length uintptr, prot int, flags int, fd int, offset int64) (xaddr uintptr, err error)
//mmap(addr *byte, length Size_t, prot _C_int, flags _C_int, fd _C_int, offset Offset_t) *byte
//sys Open(path string, mode int, perm uint32) (fd int, err error)
//__go_open(path *byte, mode _C_int, perm Mode_t) _C_int
//sys Pread(fd int, p []byte, offset int64) (n int, err error)
//pread(fd _C_int, buf *byte, count Size_t, offset Offset_t) Ssize_t
//sys Pwrite(fd int, p []byte, offset int64) (n int, err error)
//pwrite(fd _C_int, buf *byte, count Size_t, offset Offset_t) Ssize_t
//sys Seek(fd int, offset int64, whence int) (off int64, err error)
//lseek(fd _C_int, offset Offset_t, whence _C_int) Offset_t
//sys Stat(path string, stat *Stat_t) (err error)
//stat(path *byte, stat *Stat_t) _C_int
//sys Truncate(path string, length int64) (err error)
//truncate(path *byte, length Offset_t) _C_int
| LeChuck42/or1k-gcc | libgo/go/syscall/libcall_posix_regfile.go | GO | gpl-2.0 | 1,456 |
. /lib/ipq806x.sh
PART_NAME=firmware
platform_check_image() {
local board=$(ipq806x_board_name)
case "$board" in
ap148 |\
d7800 |\
r7500)
nand_do_platform_check $board $1
return $?;
;;
*)
return 1;
esac
}
platform_pre_upgrade() {
local board=$(ipq806x_board_name)
case "$board" in
ap148 |\
d7800 |\
r7500)
nand_do_upgrade "$1"
;;
esac
}
# use default for platform_do_upgrade()
| leexning/openwrt | target/linux/ipq806x/base-files/lib/upgrade/platform.sh | Shell | gpl-2.0 | 408 |
/*
* devices.c
* (C) Copyright 1999 Randy Dunlap.
* (C) Copyright 1999,2000 Thomas Sailer <[email protected]>. (proc file per device)
* (C) Copyright 1999 Deti Fliegl (new USB architecture)
*
* 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
*
*************************************************************
*
* <mountpoint>/devices contains USB topology, device, config, class,
* interface, & endpoint data.
*
* I considered using /proc/bus/usb/devices/device# for each device
* as it is attached or detached, but I didn't like this for some
* reason -- maybe it's just too deep of a directory structure.
* I also don't like looking in multiple places to gather and view
* the data. Having only one file for ./devices also prevents race
* conditions that could arise if a program was reading device info
* for devices that are being removed (unplugged). (That is, the
* program may find a directory for devnum_12 then try to open it,
* but it was just unplugged, so the directory is now deleted.
* But programs would just have to be prepared for situations like
* this in any plug-and-play environment.)
*
* 1999-12-16: Thomas Sailer <[email protected]>
* Converted the whole proc stuff to real
* read methods. Now not the whole device list needs to fit
* into one page, only the device list for one bus.
* Added a poll method to /proc/bus/usb/devices, to wake
* up an eventual usbd
* 2000-01-04: Thomas Sailer <[email protected]>
* Turned into its own filesystem
* 2000-07-05: Ashley Montanaro <[email protected]>
* Converted file reading routine to dump to buffer once
* per device, not per bus
*/
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/poll.h>
#include <linux/usb.h>
#include <linux/smp_lock.h>
#include <linux/usbdevice_fs.h>
#include <linux/mutex.h>
#include <asm/uaccess.h>
#include "usb.h"
#include "hcd.h"
/* Define ALLOW_SERIAL_NUMBER if you want to see the serial number of devices */
#define ALLOW_SERIAL_NUMBER
static const char *format_topo =
/* T: Bus=dd Lev=dd Prnt=dd Port=dd Cnt=dd Dev#=ddd Spd=ddd MxCh=dd */
"\nT: Bus=%2.2d Lev=%2.2d Prnt=%2.2d Port=%2.2d Cnt=%2.2d Dev#=%3d Spd=%3s MxCh=%2d\n";
static const char *format_string_manufacturer =
/* S: Manufacturer=xxxx */
"S: Manufacturer=%.100s\n";
static const char *format_string_product =
/* S: Product=xxxx */
"S: Product=%.100s\n";
#ifdef ALLOW_SERIAL_NUMBER
static const char *format_string_serialnumber =
/* S: SerialNumber=xxxx */
"S: SerialNumber=%.100s\n";
#endif
static const char *format_bandwidth =
/* B: Alloc=ddd/ddd us (xx%), #Int=ddd, #Iso=ddd */
"B: Alloc=%3d/%3d us (%2d%%), #Int=%3d, #Iso=%3d\n";
static const char *format_device1 =
/* D: Ver=xx.xx Cls=xx(sssss) Sub=xx Prot=xx MxPS=dd #Cfgs=dd */
"D: Ver=%2x.%02x Cls=%02x(%-5s) Sub=%02x Prot=%02x MxPS=%2d #Cfgs=%3d\n";
static const char *format_device2 =
/* P: Vendor=xxxx ProdID=xxxx Rev=xx.xx */
"P: Vendor=%04x ProdID=%04x Rev=%2x.%02x\n";
static const char *format_config =
/* C: #Ifs=dd Cfg#=dd Atr=xx MPwr=dddmA */
"C:%c #Ifs=%2d Cfg#=%2d Atr=%02x MxPwr=%3dmA\n";
static const char *format_iad =
/* A: FirstIf#=dd IfCount=dd Cls=xx(sssss) Sub=xx Prot=xx */
"A: FirstIf#=%2d IfCount=%2d Cls=%02x(%-5s) Sub=%02x Prot=%02x\n";
static const char *format_iface =
/* I: If#=dd Alt=dd #EPs=dd Cls=xx(sssss) Sub=xx Prot=xx Driver=xxxx*/
"I:%c If#=%2d Alt=%2d #EPs=%2d Cls=%02x(%-5s) Sub=%02x Prot=%02x Driver=%s\n";
static const char *format_endpt =
/* E: Ad=xx(s) Atr=xx(ssss) MxPS=dddd Ivl=D?s */
"E: Ad=%02x(%c) Atr=%02x(%-4s) MxPS=%4d Ivl=%d%cs\n";
/*
* Need access to the driver and USB bus lists.
* extern struct list_head usb_bus_list;
* However, these will come from functions that return ptrs to each of them.
*/
static DECLARE_WAIT_QUEUE_HEAD(deviceconndiscwq);
static unsigned int conndiscevcnt;
/* this struct stores the poll state for <mountpoint>/devices pollers */
struct usb_device_status {
unsigned int lastev;
};
struct class_info {
int class;
char *class_name;
};
static const struct class_info clas_info[] =
{ /* max. 5 chars. per name string */
{USB_CLASS_PER_INTERFACE, ">ifc"},
{USB_CLASS_AUDIO, "audio"},
{USB_CLASS_COMM, "comm."},
{USB_CLASS_HID, "HID"},
{USB_CLASS_HUB, "hub"},
{USB_CLASS_PHYSICAL, "PID"},
{USB_CLASS_PRINTER, "print"},
{USB_CLASS_MASS_STORAGE, "stor."},
{USB_CLASS_CDC_DATA, "data"},
{USB_CLASS_APP_SPEC, "app."},
{USB_CLASS_VENDOR_SPEC, "vend."},
{USB_CLASS_STILL_IMAGE, "still"},
{USB_CLASS_CSCID, "scard"},
{USB_CLASS_CONTENT_SEC, "c-sec"},
{USB_CLASS_VIDEO, "video"},
{-1, "unk."} /* leave as last */
};
/*****************************************************************/
void usbfs_conn_disc_event(void)
{
conndiscevcnt++;
wake_up(&deviceconndiscwq);
}
static const char *class_decode(const int class)
{
int ix;
for (ix = 0; clas_info[ix].class != -1; ix++)
if (clas_info[ix].class == class)
break;
return clas_info[ix].class_name;
}
static char *usb_dump_endpoint_descriptor(int speed, char *start, char *end,
const struct usb_endpoint_descriptor *desc)
{
char dir, unit, *type;
unsigned interval, bandwidth = 1;
if (start > end)
return start;
dir = usb_endpoint_dir_in(desc) ? 'I' : 'O';
if (speed == USB_SPEED_HIGH) {
switch (le16_to_cpu(desc->wMaxPacketSize) & (0x03 << 11)) {
case 1 << 11: bandwidth = 2; break;
case 2 << 11: bandwidth = 3; break;
}
}
/* this isn't checking for illegal values */
switch (usb_endpoint_type(desc)) {
case USB_ENDPOINT_XFER_CONTROL:
type = "Ctrl";
if (speed == USB_SPEED_HIGH) /* uframes per NAK */
interval = desc->bInterval;
else
interval = 0;
dir = 'B'; /* ctrl is bidirectional */
break;
case USB_ENDPOINT_XFER_ISOC:
type = "Isoc";
interval = 1 << (desc->bInterval - 1);
break;
case USB_ENDPOINT_XFER_BULK:
type = "Bulk";
if (speed == USB_SPEED_HIGH && dir == 'O') /* uframes per NAK */
interval = desc->bInterval;
else
interval = 0;
break;
case USB_ENDPOINT_XFER_INT:
type = "Int.";
if (speed == USB_SPEED_HIGH)
interval = 1 << (desc->bInterval - 1);
else
interval = desc->bInterval;
break;
default: /* "can't happen" */
return start;
}
interval *= (speed == USB_SPEED_HIGH) ? 125 : 1000;
if (interval % 1000)
unit = 'u';
else {
unit = 'm';
interval /= 1000;
}
start += sprintf(start, format_endpt, desc->bEndpointAddress, dir,
desc->bmAttributes, type,
(le16_to_cpu(desc->wMaxPacketSize) & 0x07ff) *
bandwidth,
interval, unit);
return start;
}
static char *usb_dump_interface_descriptor(char *start, char *end,
const struct usb_interface_cache *intfc,
const struct usb_interface *iface,
int setno)
{
const struct usb_interface_descriptor *desc;
const char *driver_name = "";
int active = 0;
if (start > end)
return start;
desc = &intfc->altsetting[setno].desc;
if (iface) {
driver_name = (iface->dev.driver
? iface->dev.driver->name
: "(none)");
active = (desc == &iface->cur_altsetting->desc);
}
start += sprintf(start, format_iface,
active ? '*' : ' ', /* mark active altsetting */
desc->bInterfaceNumber,
desc->bAlternateSetting,
desc->bNumEndpoints,
desc->bInterfaceClass,
class_decode(desc->bInterfaceClass),
desc->bInterfaceSubClass,
desc->bInterfaceProtocol,
driver_name);
return start;
}
static char *usb_dump_interface(int speed, char *start, char *end,
const struct usb_interface_cache *intfc,
const struct usb_interface *iface, int setno)
{
const struct usb_host_interface *desc = &intfc->altsetting[setno];
int i;
start = usb_dump_interface_descriptor(start, end, intfc, iface, setno);
for (i = 0; i < desc->desc.bNumEndpoints; i++) {
if (start > end)
return start;
start = usb_dump_endpoint_descriptor(speed,
start, end, &desc->endpoint[i].desc);
}
return start;
}
static char *usb_dump_iad_descriptor(char *start, char *end,
const struct usb_interface_assoc_descriptor *iad)
{
if (start > end)
return start;
start += sprintf(start, format_iad,
iad->bFirstInterface,
iad->bInterfaceCount,
iad->bFunctionClass,
class_decode(iad->bFunctionClass),
iad->bFunctionSubClass,
iad->bFunctionProtocol);
return start;
}
/* TBD:
* 0. TBDs
* 1. marking active interface altsettings (code lists all, but should mark
* which ones are active, if any)
*/
static char *usb_dump_config_descriptor(char *start, char *end,
const struct usb_config_descriptor *desc,
int active)
{
if (start > end)
return start;
start += sprintf(start, format_config,
/* mark active/actual/current cfg. */
active ? '*' : ' ',
desc->bNumInterfaces,
desc->bConfigurationValue,
desc->bmAttributes,
desc->bMaxPower * 2);
return start;
}
static char *usb_dump_config(int speed, char *start, char *end,
const struct usb_host_config *config, int active)
{
int i, j;
struct usb_interface_cache *intfc;
struct usb_interface *interface;
if (start > end)
return start;
if (!config)
/* getting these some in 2.3.7; none in 2.3.6 */
return start + sprintf(start, "(null Cfg. desc.)\n");
start = usb_dump_config_descriptor(start, end, &config->desc, active);
for (i = 0; i < USB_MAXIADS; i++) {
if (config->intf_assoc[i] == NULL)
break;
start = usb_dump_iad_descriptor(start, end,
config->intf_assoc[i]);
}
for (i = 0; i < config->desc.bNumInterfaces; i++) {
intfc = config->intf_cache[i];
interface = config->interface[i];
for (j = 0; j < intfc->num_altsetting; j++) {
if (start > end)
return start;
start = usb_dump_interface(speed,
start, end, intfc, interface, j);
}
}
return start;
}
/*
* Dump the different USB descriptors.
*/
static char *usb_dump_device_descriptor(char *start, char *end,
const struct usb_device_descriptor *desc)
{
u16 bcdUSB = le16_to_cpu(desc->bcdUSB);
u16 bcdDevice = le16_to_cpu(desc->bcdDevice);
if (start > end)
return start;
start += sprintf(start, format_device1,
bcdUSB >> 8, bcdUSB & 0xff,
desc->bDeviceClass,
class_decode(desc->bDeviceClass),
desc->bDeviceSubClass,
desc->bDeviceProtocol,
desc->bMaxPacketSize0,
desc->bNumConfigurations);
if (start > end)
return start;
start += sprintf(start, format_device2,
le16_to_cpu(desc->idVendor),
le16_to_cpu(desc->idProduct),
bcdDevice >> 8, bcdDevice & 0xff);
return start;
}
/*
* Dump the different strings that this device holds.
*/
static char *usb_dump_device_strings(char *start, char *end,
struct usb_device *dev)
{
if (start > end)
return start;
if (dev->manufacturer)
start += sprintf(start, format_string_manufacturer,
dev->manufacturer);
if (start > end)
goto out;
if (dev->product)
start += sprintf(start, format_string_product, dev->product);
if (start > end)
goto out;
#ifdef ALLOW_SERIAL_NUMBER
if (dev->serial)
start += sprintf(start, format_string_serialnumber,
dev->serial);
#endif
out:
return start;
}
static char *usb_dump_desc(char *start, char *end, struct usb_device *dev)
{
int i;
if (start > end)
return start;
start = usb_dump_device_descriptor(start, end, &dev->descriptor);
if (start > end)
return start;
start = usb_dump_device_strings(start, end, dev);
for (i = 0; i < dev->descriptor.bNumConfigurations; i++) {
if (start > end)
return start;
start = usb_dump_config(dev->speed,
start, end, dev->config + i,
/* active ? */
(dev->config + i) == dev->actconfig);
}
return start;
}
#ifdef PROC_EXTRA /* TBD: may want to add this code later */
static char *usb_dump_hub_descriptor(char *start, char *end,
const struct usb_hub_descriptor *desc)
{
int leng = USB_DT_HUB_NONVAR_SIZE;
unsigned char *ptr = (unsigned char *)desc;
if (start > end)
return start;
start += sprintf(start, "Interface:");
while (leng && start <= end) {
start += sprintf(start, " %02x", *ptr);
ptr++; leng--;
}
*start++ = '\n';
return start;
}
static char *usb_dump_string(char *start, char *end,
const struct usb_device *dev, char *id, int index)
{
if (start > end)
return start;
start += sprintf(start, "Interface:");
if (index <= dev->maxstring && dev->stringindex &&
dev->stringindex[index])
start += sprintf(start, "%s: %.100s ", id,
dev->stringindex[index]);
return start;
}
#endif /* PROC_EXTRA */
/*****************************************************************/
/* This is a recursive function. Parameters:
* buffer - the user-space buffer to write data into
* nbytes - the maximum number of bytes to write
* skip_bytes - the number of bytes to skip before writing anything
* file_offset - the offset into the devices file on completion
* The caller must own the device lock.
*/
static ssize_t usb_device_dump(char __user **buffer, size_t *nbytes,
loff_t *skip_bytes, loff_t *file_offset,
struct usb_device *usbdev, struct usb_bus *bus,
int level, int index, int count)
{
int chix;
int ret, cnt = 0;
int parent_devnum = 0;
char *pages_start, *data_end, *speed;
unsigned int length;
ssize_t total_written = 0;
/* don't bother with anything else if we're not writing any data */
if (*nbytes <= 0)
return 0;
if (level > MAX_TOPO_LEVEL)
return 0;
/* allocate 2^1 pages = 8K (on i386);
* should be more than enough for one device */
pages_start = (char *)__get_free_pages(GFP_KERNEL, 1);
if (!pages_start)
return -ENOMEM;
if (usbdev->parent && usbdev->parent->devnum != -1)
parent_devnum = usbdev->parent->devnum;
/*
* So the root hub's parent is 0 and any device that is
* plugged into the root hub has a parent of 0.
*/
switch (usbdev->speed) {
case USB_SPEED_LOW:
speed = "1.5"; break;
case USB_SPEED_UNKNOWN: /* usb 1.1 root hub code */
case USB_SPEED_FULL:
speed = "12 "; break;
case USB_SPEED_HIGH:
speed = "480"; break;
default:
speed = "?? ";
}
data_end = pages_start + sprintf(pages_start, format_topo,
bus->busnum, level, parent_devnum,
index, count, usbdev->devnum,
speed, usbdev->maxchild);
/*
* level = topology-tier level;
* parent_devnum = parent device number;
* index = parent's connector number;
* count = device count at this level
*/
/* If this is the root hub, display the bandwidth information */
if (level == 0) {
int max;
/* high speed reserves 80%, full/low reserves 90% */
if (usbdev->speed == USB_SPEED_HIGH)
max = 800;
else
max = FRAME_TIME_MAX_USECS_ALLOC;
/* report "average" periodic allocation over a microsecond.
* the schedules are actually bursty, HCDs need to deal with
* that and just compute/report this average.
*/
data_end += sprintf(data_end, format_bandwidth,
bus->bandwidth_allocated, max,
(100 * bus->bandwidth_allocated + max / 2)
/ max,
bus->bandwidth_int_reqs,
bus->bandwidth_isoc_reqs);
}
data_end = usb_dump_desc(data_end, pages_start + (2 * PAGE_SIZE) - 256,
usbdev);
if (data_end > (pages_start + (2 * PAGE_SIZE) - 256))
data_end += sprintf(data_end, "(truncated)\n");
length = data_end - pages_start;
/* if we can start copying some data to the user */
if (length > *skip_bytes) {
length -= *skip_bytes;
if (length > *nbytes)
length = *nbytes;
if (copy_to_user(*buffer, pages_start + *skip_bytes, length)) {
free_pages((unsigned long)pages_start, 1);
return -EFAULT;
}
*nbytes -= length;
*file_offset += length;
total_written += length;
*buffer += length;
*skip_bytes = 0;
} else
*skip_bytes -= length;
free_pages((unsigned long)pages_start, 1);
/* Now look at all of this device's children. */
for (chix = 0; chix < usbdev->maxchild; chix++) {
struct usb_device *childdev = usbdev->children[chix];
if (childdev) {
usb_lock_device(childdev);
ret = usb_device_dump(buffer, nbytes, skip_bytes,
file_offset, childdev, bus,
level + 1, chix, ++cnt);
usb_unlock_device(childdev);
if (ret == -EFAULT)
return total_written;
total_written += ret;
}
}
return total_written;
}
static ssize_t usb_device_read(struct file *file, char __user *buf,
size_t nbytes, loff_t *ppos)
{
struct usb_bus *bus;
ssize_t ret, total_written = 0;
loff_t skip_bytes = *ppos;
if (*ppos < 0)
return -EINVAL;
if (nbytes <= 0)
return 0;
if (!access_ok(VERIFY_WRITE, buf, nbytes))
return -EFAULT;
mutex_lock(&usb_bus_list_lock);
/* print devices for all busses */
list_for_each_entry(bus, &usb_bus_list, bus_list) {
/* recurse through all children of the root hub */
if (!bus->root_hub)
continue;
usb_lock_device(bus->root_hub);
ret = usb_device_dump(&buf, &nbytes, &skip_bytes, ppos,
bus->root_hub, bus, 0, 0, 0);
usb_unlock_device(bus->root_hub);
if (ret < 0) {
mutex_unlock(&usb_bus_list_lock);
return ret;
}
total_written += ret;
}
mutex_unlock(&usb_bus_list_lock);
return total_written;
}
/* Kernel lock for "lastev" protection */
static unsigned int usb_device_poll(struct file *file,
struct poll_table_struct *wait)
{
struct usb_device_status *st = file->private_data;
unsigned int mask = 0;
lock_kernel();
if (!st) {
st = kmalloc(sizeof(struct usb_device_status), GFP_KERNEL);
/* we may have dropped BKL -
* need to check for having lost the race */
if (file->private_data) {
kfree(st);
st = file->private_data;
goto lost_race;
}
/* we haven't lost - check for allocation failure now */
if (!st) {
unlock_kernel();
return POLLIN;
}
/*
* need to prevent the module from being unloaded, since
* proc_unregister does not call the release method and
* we would have a memory leak
*/
st->lastev = conndiscevcnt;
file->private_data = st;
mask = POLLIN;
}
lost_race:
if (file->f_mode & FMODE_READ)
poll_wait(file, &deviceconndiscwq, wait);
if (st->lastev != conndiscevcnt)
mask |= POLLIN;
st->lastev = conndiscevcnt;
unlock_kernel();
return mask;
}
static int usb_device_open(struct inode *inode, struct file *file)
{
file->private_data = NULL;
return 0;
}
static int usb_device_release(struct inode *inode, struct file *file)
{
kfree(file->private_data);
file->private_data = NULL;
return 0;
}
static loff_t usb_device_lseek(struct file *file, loff_t offset, int orig)
{
loff_t ret;
lock_kernel();
switch (orig) {
case 0:
file->f_pos = offset;
ret = file->f_pos;
break;
case 1:
file->f_pos += offset;
ret = file->f_pos;
break;
case 2:
default:
ret = -EINVAL;
}
unlock_kernel();
return ret;
}
const struct file_operations usbfs_devices_fops = {
.llseek = usb_device_lseek,
.read = usb_device_read,
.poll = usb_device_poll,
.open = usb_device_open,
.release = usb_device_release,
};
| librae8226/linux-2.6.30.4 | drivers/usb/core/devices.c | C | gpl-2.0 | 19,482 |
/*
* Definitions for the new Marvell Yukon 2 driver.
*/
#ifndef _SKY2_H
#define _SKY2_H
#define ETH_JUMBO_MTU 9000 /* Maximum MTU supported */
/* PCI config registers */
enum {
PCI_DEV_REG1 = 0x40,
PCI_DEV_REG2 = 0x44,
PCI_DEV_STATUS = 0x7c,
PCI_DEV_REG3 = 0x80,
PCI_DEV_REG4 = 0x84,
PCI_DEV_REG5 = 0x88,
};
enum {
PEX_DEV_CAP = 0xe4,
PEX_DEV_CTRL = 0xe8,
PEX_DEV_STA = 0xea,
PEX_LNK_STAT = 0xf2,
PEX_UNC_ERR_STAT= 0x104,
};
/* Yukon-2 */
enum pci_dev_reg_1 {
PCI_Y2_PIG_ENA = 1<<31, /* Enable Plug-in-Go (YUKON-2) */
PCI_Y2_DLL_DIS = 1<<30, /* Disable PCI DLL (YUKON-2) */
PCI_Y2_PHY2_COMA = 1<<29, /* Set PHY 2 to Coma Mode (YUKON-2) */
PCI_Y2_PHY1_COMA = 1<<28, /* Set PHY 1 to Coma Mode (YUKON-2) */
PCI_Y2_PHY2_POWD = 1<<27, /* Set PHY 2 to Power Down (YUKON-2) */
PCI_Y2_PHY1_POWD = 1<<26, /* Set PHY 1 to Power Down (YUKON-2) */
PCI_Y2_PME_LEGACY= 1<<15, /* PCI Express legacy power management mode */
};
enum pci_dev_reg_2 {
PCI_VPD_WR_THR = 0xffL<<24, /* Bit 31..24: VPD Write Threshold */
PCI_DEV_SEL = 0x7fL<<17, /* Bit 23..17: EEPROM Device Select */
PCI_VPD_ROM_SZ = 7L<<14, /* Bit 16..14: VPD ROM Size */
PCI_PATCH_DIR = 0xfL<<8, /* Bit 11.. 8: Ext Patches dir 3..0 */
PCI_EXT_PATCHS = 0xfL<<4, /* Bit 7.. 4: Extended Patches 3..0 */
PCI_EN_DUMMY_RD = 1<<3, /* Enable Dummy Read */
PCI_REV_DESC = 1<<2, /* Reverse Desc. Bytes */
PCI_USEDATA64 = 1<<0, /* Use 64Bit Data bus ext */
};
/* PCI_OUR_REG_4 32 bit Our Register 4 (Yukon-ECU only) */
enum pci_dev_reg_4 {
/* (Link Training & Status State Machine) */
P_TIMER_VALUE_MSK = 0xffL<<16, /* Bit 23..16: Timer Value Mask */
/* (Active State Power Management) */
P_FORCE_ASPM_REQUEST = 1<<15, /* Force ASPM Request (A1 only) */
P_ASPM_GPHY_LINK_DOWN = 1<<14, /* GPHY Link Down (A1 only) */
P_ASPM_INT_FIFO_EMPTY = 1<<13, /* Internal FIFO Empty (A1 only) */
P_ASPM_CLKRUN_REQUEST = 1<<12, /* CLKRUN Request (A1 only) */
P_ASPM_FORCE_CLKREQ_ENA = 1<<4, /* Force CLKREQ Enable (A1b only) */
P_ASPM_CLKREQ_PAD_CTL = 1<<3, /* CLKREQ PAD Control (A1 only) */
P_ASPM_A1_MODE_SELECT = 1<<2, /* A1 Mode Select (A1 only) */
P_CLK_GATE_PEX_UNIT_ENA = 1<<1, /* Enable Gate PEX Unit Clock */
P_CLK_GATE_ROOT_COR_ENA = 1<<0, /* Enable Gate Root Core Clock */
P_ASPM_CONTROL_MSK = P_FORCE_ASPM_REQUEST | P_ASPM_GPHY_LINK_DOWN
| P_ASPM_CLKRUN_REQUEST | P_ASPM_INT_FIFO_EMPTY,
};
#define PCI_STATUS_ERROR_BITS (PCI_STATUS_DETECTED_PARITY | \
PCI_STATUS_SIG_SYSTEM_ERROR | \
PCI_STATUS_REC_MASTER_ABORT | \
PCI_STATUS_REC_TARGET_ABORT | \
PCI_STATUS_PARITY)
enum pex_dev_ctrl {
PEX_DC_MAX_RRS_MSK = 7<<12, /* Bit 14..12: Max. Read Request Size */
PEX_DC_EN_NO_SNOOP = 1<<11,/* Enable No Snoop */
PEX_DC_EN_AUX_POW = 1<<10,/* Enable AUX Power */
PEX_DC_EN_PHANTOM = 1<<9, /* Enable Phantom Functions */
PEX_DC_EN_EXT_TAG = 1<<8, /* Enable Extended Tag Field */
PEX_DC_MAX_PLS_MSK = 7<<5, /* Bit 7.. 5: Max. Payload Size Mask */
PEX_DC_EN_REL_ORD = 1<<4, /* Enable Relaxed Ordering */
PEX_DC_EN_UNS_RQ_RP = 1<<3, /* Enable Unsupported Request Reporting */
PEX_DC_EN_FAT_ER_RP = 1<<2, /* Enable Fatal Error Reporting */
PEX_DC_EN_NFA_ER_RP = 1<<1, /* Enable Non-Fatal Error Reporting */
PEX_DC_EN_COR_ER_RP = 1<<0, /* Enable Correctable Error Reporting */
};
#define PEX_DC_MAX_RD_RQ_SIZE(x) (((x)<<12) & PEX_DC_MAX_RRS_MSK)
/* PEX_UNC_ERR_STAT PEX Uncorrectable Errors Status Register (Yukon-2) */
enum pex_err {
PEX_UNSUP_REQ = 1<<20, /* Unsupported Request Error */
PEX_MALFOR_TLP = 1<<18, /* Malformed TLP */
PEX_UNEXP_COMP = 1<<16, /* Unexpected Completion */
PEX_COMP_TO = 1<<14, /* Completion Timeout */
PEX_FLOW_CTRL_P = 1<<13, /* Flow Control Protocol Error */
PEX_POIS_TLP = 1<<12, /* Poisoned TLP */
PEX_DATA_LINK_P = 1<<4, /* Data Link Protocol Error */
PEX_FATAL_ERRORS= (PEX_MALFOR_TLP | PEX_FLOW_CTRL_P | PEX_DATA_LINK_P),
};
enum csr_regs {
B0_RAP = 0x0000,
B0_CTST = 0x0004,
B0_Y2LED = 0x0005,
B0_POWER_CTRL = 0x0007,
B0_ISRC = 0x0008,
B0_IMSK = 0x000c,
B0_HWE_ISRC = 0x0010,
B0_HWE_IMSK = 0x0014,
/* Special ISR registers (Yukon-2 only) */
B0_Y2_SP_ISRC2 = 0x001c,
B0_Y2_SP_ISRC3 = 0x0020,
B0_Y2_SP_EISR = 0x0024,
B0_Y2_SP_LISR = 0x0028,
B0_Y2_SP_ICR = 0x002c,
B2_MAC_1 = 0x0100,
B2_MAC_2 = 0x0108,
B2_MAC_3 = 0x0110,
B2_CONN_TYP = 0x0118,
B2_PMD_TYP = 0x0119,
B2_MAC_CFG = 0x011a,
B2_CHIP_ID = 0x011b,
B2_E_0 = 0x011c,
B2_Y2_CLK_GATE = 0x011d,
B2_Y2_HW_RES = 0x011e,
B2_E_3 = 0x011f,
B2_Y2_CLK_CTRL = 0x0120,
B2_TI_INI = 0x0130,
B2_TI_VAL = 0x0134,
B2_TI_CTRL = 0x0138,
B2_TI_TEST = 0x0139,
B2_TST_CTRL1 = 0x0158,
B2_TST_CTRL2 = 0x0159,
B2_GP_IO = 0x015c,
B2_I2C_CTRL = 0x0160,
B2_I2C_DATA = 0x0164,
B2_I2C_IRQ = 0x0168,
B2_I2C_SW = 0x016c,
B3_RAM_ADDR = 0x0180,
B3_RAM_DATA_LO = 0x0184,
B3_RAM_DATA_HI = 0x0188,
/* RAM Interface Registers */
/* Yukon-2: use RAM_BUFFER() to access the RAM buffer */
/*
* The HW-Spec. calls this registers Timeout Value 0..11. But this names are
* not usable in SW. Please notice these are NOT real timeouts, these are
* the number of qWords transferred continuously.
*/
#define RAM_BUFFER(port, reg) (reg | (port <<6))
B3_RI_WTO_R1 = 0x0190,
B3_RI_WTO_XA1 = 0x0191,
B3_RI_WTO_XS1 = 0x0192,
B3_RI_RTO_R1 = 0x0193,
B3_RI_RTO_XA1 = 0x0194,
B3_RI_RTO_XS1 = 0x0195,
B3_RI_WTO_R2 = 0x0196,
B3_RI_WTO_XA2 = 0x0197,
B3_RI_WTO_XS2 = 0x0198,
B3_RI_RTO_R2 = 0x0199,
B3_RI_RTO_XA2 = 0x019a,
B3_RI_RTO_XS2 = 0x019b,
B3_RI_TO_VAL = 0x019c,
B3_RI_CTRL = 0x01a0,
B3_RI_TEST = 0x01a2,
B3_MA_TOINI_RX1 = 0x01b0,
B3_MA_TOINI_RX2 = 0x01b1,
B3_MA_TOINI_TX1 = 0x01b2,
B3_MA_TOINI_TX2 = 0x01b3,
B3_MA_TOVAL_RX1 = 0x01b4,
B3_MA_TOVAL_RX2 = 0x01b5,
B3_MA_TOVAL_TX1 = 0x01b6,
B3_MA_TOVAL_TX2 = 0x01b7,
B3_MA_TO_CTRL = 0x01b8,
B3_MA_TO_TEST = 0x01ba,
B3_MA_RCINI_RX1 = 0x01c0,
B3_MA_RCINI_RX2 = 0x01c1,
B3_MA_RCINI_TX1 = 0x01c2,
B3_MA_RCINI_TX2 = 0x01c3,
B3_MA_RCVAL_RX1 = 0x01c4,
B3_MA_RCVAL_RX2 = 0x01c5,
B3_MA_RCVAL_TX1 = 0x01c6,
B3_MA_RCVAL_TX2 = 0x01c7,
B3_MA_RC_CTRL = 0x01c8,
B3_MA_RC_TEST = 0x01ca,
B3_PA_TOINI_RX1 = 0x01d0,
B3_PA_TOINI_RX2 = 0x01d4,
B3_PA_TOINI_TX1 = 0x01d8,
B3_PA_TOINI_TX2 = 0x01dc,
B3_PA_TOVAL_RX1 = 0x01e0,
B3_PA_TOVAL_RX2 = 0x01e4,
B3_PA_TOVAL_TX1 = 0x01e8,
B3_PA_TOVAL_TX2 = 0x01ec,
B3_PA_CTRL = 0x01f0,
B3_PA_TEST = 0x01f2,
Y2_CFG_SPC = 0x1c00,
};
/* B0_CTST 16 bit Control/Status register */
enum {
Y2_VMAIN_AVAIL = 1<<17,/* VMAIN available (YUKON-2 only) */
Y2_VAUX_AVAIL = 1<<16,/* VAUX available (YUKON-2 only) */
Y2_HW_WOL_ON = 1<<15,/* HW WOL On (Yukon-EC Ultra A1 only) */
Y2_HW_WOL_OFF = 1<<14,/* HW WOL On (Yukon-EC Ultra A1 only) */
Y2_ASF_ENABLE = 1<<13,/* ASF Unit Enable (YUKON-2 only) */
Y2_ASF_DISABLE = 1<<12,/* ASF Unit Disable (YUKON-2 only) */
Y2_CLK_RUN_ENA = 1<<11,/* CLK_RUN Enable (YUKON-2 only) */
Y2_CLK_RUN_DIS = 1<<10,/* CLK_RUN Disable (YUKON-2 only) */
Y2_LED_STAT_ON = 1<<9, /* Status LED On (YUKON-2 only) */
Y2_LED_STAT_OFF = 1<<8, /* Status LED Off (YUKON-2 only) */
CS_ST_SW_IRQ = 1<<7, /* Set IRQ SW Request */
CS_CL_SW_IRQ = 1<<6, /* Clear IRQ SW Request */
CS_STOP_DONE = 1<<5, /* Stop Master is finished */
CS_STOP_MAST = 1<<4, /* Command Bit to stop the master */
CS_MRST_CLR = 1<<3, /* Clear Master reset */
CS_MRST_SET = 1<<2, /* Set Master reset */
CS_RST_CLR = 1<<1, /* Clear Software reset */
CS_RST_SET = 1, /* Set Software reset */
};
/* B0_LED 8 Bit LED register */
enum {
/* Bit 7.. 2: reserved */
LED_STAT_ON = 1<<1, /* Status LED on */
LED_STAT_OFF = 1, /* Status LED off */
};
/* B0_POWER_CTRL 8 Bit Power Control reg (YUKON only) */
enum {
PC_VAUX_ENA = 1<<7, /* Switch VAUX Enable */
PC_VAUX_DIS = 1<<6, /* Switch VAUX Disable */
PC_VCC_ENA = 1<<5, /* Switch VCC Enable */
PC_VCC_DIS = 1<<4, /* Switch VCC Disable */
PC_VAUX_ON = 1<<3, /* Switch VAUX On */
PC_VAUX_OFF = 1<<2, /* Switch VAUX Off */
PC_VCC_ON = 1<<1, /* Switch VCC On */
PC_VCC_OFF = 1<<0, /* Switch VCC Off */
};
/* B2_IRQM_MSK 32 bit IRQ Moderation Mask */
/* B0_Y2_SP_ISRC2 32 bit Special Interrupt Source Reg 2 */
/* B0_Y2_SP_ISRC3 32 bit Special Interrupt Source Reg 3 */
/* B0_Y2_SP_EISR 32 bit Enter ISR Reg */
/* B0_Y2_SP_LISR 32 bit Leave ISR Reg */
enum {
Y2_IS_HW_ERR = 1<<31, /* Interrupt HW Error */
Y2_IS_STAT_BMU = 1<<30, /* Status BMU Interrupt */
Y2_IS_ASF = 1<<29, /* ASF subsystem Interrupt */
Y2_IS_POLL_CHK = 1<<27, /* Check IRQ from polling unit */
Y2_IS_TWSI_RDY = 1<<26, /* IRQ on end of TWSI Tx */
Y2_IS_IRQ_SW = 1<<25, /* SW forced IRQ */
Y2_IS_TIMINT = 1<<24, /* IRQ from Timer */
Y2_IS_IRQ_PHY2 = 1<<12, /* Interrupt from PHY 2 */
Y2_IS_IRQ_MAC2 = 1<<11, /* Interrupt from MAC 2 */
Y2_IS_CHK_RX2 = 1<<10, /* Descriptor error Rx 2 */
Y2_IS_CHK_TXS2 = 1<<9, /* Descriptor error TXS 2 */
Y2_IS_CHK_TXA2 = 1<<8, /* Descriptor error TXA 2 */
Y2_IS_IRQ_PHY1 = 1<<4, /* Interrupt from PHY 1 */
Y2_IS_IRQ_MAC1 = 1<<3, /* Interrupt from MAC 1 */
Y2_IS_CHK_RX1 = 1<<2, /* Descriptor error Rx 1 */
Y2_IS_CHK_TXS1 = 1<<1, /* Descriptor error TXS 1 */
Y2_IS_CHK_TXA1 = 1<<0, /* Descriptor error TXA 1 */
Y2_IS_BASE = Y2_IS_HW_ERR | Y2_IS_STAT_BMU,
Y2_IS_PORT_1 = Y2_IS_IRQ_PHY1 | Y2_IS_IRQ_MAC1
| Y2_IS_CHK_TXA1 | Y2_IS_CHK_RX1,
Y2_IS_PORT_2 = Y2_IS_IRQ_PHY2 | Y2_IS_IRQ_MAC2
| Y2_IS_CHK_TXA2 | Y2_IS_CHK_RX2,
Y2_IS_ERROR = Y2_IS_HW_ERR |
Y2_IS_IRQ_MAC1 | Y2_IS_CHK_TXA1 | Y2_IS_CHK_RX1 |
Y2_IS_IRQ_MAC2 | Y2_IS_CHK_TXA2 | Y2_IS_CHK_RX2,
};
/* B2_IRQM_HWE_MSK 32 bit IRQ Moderation HW Error Mask */
enum {
IS_ERR_MSK = 0x00003fff,/* All Error bits */
IS_IRQ_TIST_OV = 1<<13, /* Time Stamp Timer Overflow (YUKON only) */
IS_IRQ_SENSOR = 1<<12, /* IRQ from Sensor (YUKON only) */
IS_IRQ_MST_ERR = 1<<11, /* IRQ master error detected */
IS_IRQ_STAT = 1<<10, /* IRQ status exception */
IS_NO_STAT_M1 = 1<<9, /* No Rx Status from MAC 1 */
IS_NO_STAT_M2 = 1<<8, /* No Rx Status from MAC 2 */
IS_NO_TIST_M1 = 1<<7, /* No Time Stamp from MAC 1 */
IS_NO_TIST_M2 = 1<<6, /* No Time Stamp from MAC 2 */
IS_RAM_RD_PAR = 1<<5, /* RAM Read Parity Error */
IS_RAM_WR_PAR = 1<<4, /* RAM Write Parity Error */
IS_M1_PAR_ERR = 1<<3, /* MAC 1 Parity Error */
IS_M2_PAR_ERR = 1<<2, /* MAC 2 Parity Error */
IS_R1_PAR_ERR = 1<<1, /* Queue R1 Parity Error */
IS_R2_PAR_ERR = 1<<0, /* Queue R2 Parity Error */
};
/* Hardware error interrupt mask for Yukon 2 */
enum {
Y2_IS_TIST_OV = 1<<29,/* Time Stamp Timer overflow interrupt */
Y2_IS_SENSOR = 1<<28, /* Sensor interrupt */
Y2_IS_MST_ERR = 1<<27, /* Master error interrupt */
Y2_IS_IRQ_STAT = 1<<26, /* Status exception interrupt */
Y2_IS_PCI_EXP = 1<<25, /* PCI-Express interrupt */
Y2_IS_PCI_NEXP = 1<<24, /* PCI-Express error similar to PCI error */
/* Link 2 */
Y2_IS_PAR_RD2 = 1<<13, /* Read RAM parity error interrupt */
Y2_IS_PAR_WR2 = 1<<12, /* Write RAM parity error interrupt */
Y2_IS_PAR_MAC2 = 1<<11, /* MAC hardware fault interrupt */
Y2_IS_PAR_RX2 = 1<<10, /* Parity Error Rx Queue 2 */
Y2_IS_TCP_TXS2 = 1<<9, /* TCP length mismatch sync Tx queue IRQ */
Y2_IS_TCP_TXA2 = 1<<8, /* TCP length mismatch async Tx queue IRQ */
/* Link 1 */
Y2_IS_PAR_RD1 = 1<<5, /* Read RAM parity error interrupt */
Y2_IS_PAR_WR1 = 1<<4, /* Write RAM parity error interrupt */
Y2_IS_PAR_MAC1 = 1<<3, /* MAC hardware fault interrupt */
Y2_IS_PAR_RX1 = 1<<2, /* Parity Error Rx Queue 1 */
Y2_IS_TCP_TXS1 = 1<<1, /* TCP length mismatch sync Tx queue IRQ */
Y2_IS_TCP_TXA1 = 1<<0, /* TCP length mismatch async Tx queue IRQ */
Y2_HWE_L1_MASK = Y2_IS_PAR_RD1 | Y2_IS_PAR_WR1 | Y2_IS_PAR_MAC1 |
Y2_IS_PAR_RX1 | Y2_IS_TCP_TXS1| Y2_IS_TCP_TXA1,
Y2_HWE_L2_MASK = Y2_IS_PAR_RD2 | Y2_IS_PAR_WR2 | Y2_IS_PAR_MAC2 |
Y2_IS_PAR_RX2 | Y2_IS_TCP_TXS2| Y2_IS_TCP_TXA2,
Y2_HWE_ALL_MASK = Y2_IS_TIST_OV | Y2_IS_MST_ERR | Y2_IS_IRQ_STAT |
Y2_IS_PCI_EXP |
Y2_HWE_L1_MASK | Y2_HWE_L2_MASK,
};
/* B28_DPT_CTRL 8 bit Descriptor Poll Timer Ctrl Reg */
enum {
DPT_START = 1<<1,
DPT_STOP = 1<<0,
};
/* B2_TST_CTRL1 8 bit Test Control Register 1 */
enum {
TST_FRC_DPERR_MR = 1<<7, /* force DATAPERR on MST RD */
TST_FRC_DPERR_MW = 1<<6, /* force DATAPERR on MST WR */
TST_FRC_DPERR_TR = 1<<5, /* force DATAPERR on TRG RD */
TST_FRC_DPERR_TW = 1<<4, /* force DATAPERR on TRG WR */
TST_FRC_APERR_M = 1<<3, /* force ADDRPERR on MST */
TST_FRC_APERR_T = 1<<2, /* force ADDRPERR on TRG */
TST_CFG_WRITE_ON = 1<<1, /* Enable Config Reg WR */
TST_CFG_WRITE_OFF= 1<<0, /* Disable Config Reg WR */
};
/* B2_MAC_CFG 8 bit MAC Configuration / Chip Revision */
enum {
CFG_CHIP_R_MSK = 0xf<<4, /* Bit 7.. 4: Chip Revision */
/* Bit 3.. 2: reserved */
CFG_DIS_M2_CLK = 1<<1, /* Disable Clock for 2nd MAC */
CFG_SNG_MAC = 1<<0, /* MAC Config: 0=2 MACs / 1=1 MAC*/
};
/* B2_CHIP_ID 8 bit Chip Identification Number */
enum {
CHIP_ID_YUKON_XL = 0xb3, /* Chip ID for YUKON-2 XL */
CHIP_ID_YUKON_EC_U = 0xb4, /* Chip ID for YUKON-2 EC Ultra */
CHIP_ID_YUKON_EX = 0xb5, /* Chip ID for YUKON-2 Extreme */
CHIP_ID_YUKON_EC = 0xb6, /* Chip ID for YUKON-2 EC */
CHIP_ID_YUKON_FE = 0xb7, /* Chip ID for YUKON-2 FE */
CHIP_REV_YU_EC_A1 = 0, /* Chip Rev. for Yukon-EC A1/A0 */
CHIP_REV_YU_EC_A2 = 1, /* Chip Rev. for Yukon-EC A2 */
CHIP_REV_YU_EC_A3 = 2, /* Chip Rev. for Yukon-EC A3 */
CHIP_REV_YU_EC_U_A0 = 1,
CHIP_REV_YU_EC_U_A1 = 2,
CHIP_REV_YU_EC_U_B0 = 3,
CHIP_REV_YU_FE_A1 = 1,
CHIP_REV_YU_FE_A2 = 2,
};
/* B2_Y2_CLK_GATE 8 bit Clock Gating (Yukon-2 only) */
enum {
Y2_STATUS_LNK2_INAC = 1<<7, /* Status Link 2 inactive (0 = active) */
Y2_CLK_GAT_LNK2_DIS = 1<<6, /* Disable clock gating Link 2 */
Y2_COR_CLK_LNK2_DIS = 1<<5, /* Disable Core clock Link 2 */
Y2_PCI_CLK_LNK2_DIS = 1<<4, /* Disable PCI clock Link 2 */
Y2_STATUS_LNK1_INAC = 1<<3, /* Status Link 1 inactive (0 = active) */
Y2_CLK_GAT_LNK1_DIS = 1<<2, /* Disable clock gating Link 1 */
Y2_COR_CLK_LNK1_DIS = 1<<1, /* Disable Core clock Link 1 */
Y2_PCI_CLK_LNK1_DIS = 1<<0, /* Disable PCI clock Link 1 */
};
/* B2_Y2_HW_RES 8 bit HW Resources (Yukon-2 only) */
enum {
CFG_LED_MODE_MSK = 7<<2, /* Bit 4.. 2: LED Mode Mask */
CFG_LINK_2_AVAIL = 1<<1, /* Link 2 available */
CFG_LINK_1_AVAIL = 1<<0, /* Link 1 available */
};
#define CFG_LED_MODE(x) (((x) & CFG_LED_MODE_MSK) >> 2)
#define CFG_DUAL_MAC_MSK (CFG_LINK_2_AVAIL | CFG_LINK_1_AVAIL)
/* B2_Y2_CLK_CTRL 32 bit Clock Frequency Control Register (Yukon-2/EC) */
enum {
Y2_CLK_DIV_VAL_MSK = 0xff<<16,/* Bit 23..16: Clock Divisor Value */
#define Y2_CLK_DIV_VAL(x) (((x)<<16) & Y2_CLK_DIV_VAL_MSK)
Y2_CLK_DIV_VAL2_MSK = 7<<21, /* Bit 23..21: Clock Divisor Value */
Y2_CLK_SELECT2_MSK = 0x1f<<16,/* Bit 20..16: Clock Select */
#define Y2_CLK_DIV_VAL_2(x) (((x)<<21) & Y2_CLK_DIV_VAL2_MSK)
#define Y2_CLK_SEL_VAL_2(x) (((x)<<16) & Y2_CLK_SELECT2_MSK)
Y2_CLK_DIV_ENA = 1<<1, /* Enable Core Clock Division */
Y2_CLK_DIV_DIS = 1<<0, /* Disable Core Clock Division */
};
/* B2_TI_CTRL 8 bit Timer control */
/* B2_IRQM_CTRL 8 bit IRQ Moderation Timer Control */
enum {
TIM_START = 1<<2, /* Start Timer */
TIM_STOP = 1<<1, /* Stop Timer */
TIM_CLR_IRQ = 1<<0, /* Clear Timer IRQ (!IRQM) */
};
/* B2_TI_TEST 8 Bit Timer Test */
/* B2_IRQM_TEST 8 bit IRQ Moderation Timer Test */
/* B28_DPT_TST 8 bit Descriptor Poll Timer Test Reg */
enum {
TIM_T_ON = 1<<2, /* Test mode on */
TIM_T_OFF = 1<<1, /* Test mode off */
TIM_T_STEP = 1<<0, /* Test step */
};
/* B3_RAM_ADDR 32 bit RAM Address, to read or write */
/* Bit 31..19: reserved */
#define RAM_ADR_RAN 0x0007ffffL /* Bit 18.. 0: RAM Address Range */
/* RAM Interface Registers */
/* B3_RI_CTRL 16 bit RAM Interface Control Register */
enum {
RI_CLR_RD_PERR = 1<<9, /* Clear IRQ RAM Read Parity Err */
RI_CLR_WR_PERR = 1<<8, /* Clear IRQ RAM Write Parity Err*/
RI_RST_CLR = 1<<1, /* Clear RAM Interface Reset */
RI_RST_SET = 1<<0, /* Set RAM Interface Reset */
};
#define SK_RI_TO_53 36 /* RAM interface timeout */
/* Port related registers FIFO, and Arbiter */
#define SK_REG(port,reg) (((port)<<7)+(reg))
/* Transmit Arbiter Registers MAC 1 and 2, use SK_REG() to access */
/* TXA_ITI_INI 32 bit Tx Arb Interval Timer Init Val */
/* TXA_ITI_VAL 32 bit Tx Arb Interval Timer Value */
/* TXA_LIM_INI 32 bit Tx Arb Limit Counter Init Val */
/* TXA_LIM_VAL 32 bit Tx Arb Limit Counter Value */
#define TXA_MAX_VAL 0x00ffffffUL /* Bit 23.. 0: Max TXA Timer/Cnt Val */
/* TXA_CTRL 8 bit Tx Arbiter Control Register */
enum {
TXA_ENA_FSYNC = 1<<7, /* Enable force of sync Tx queue */
TXA_DIS_FSYNC = 1<<6, /* Disable force of sync Tx queue */
TXA_ENA_ALLOC = 1<<5, /* Enable alloc of free bandwidth */
TXA_DIS_ALLOC = 1<<4, /* Disable alloc of free bandwidth */
TXA_START_RC = 1<<3, /* Start sync Rate Control */
TXA_STOP_RC = 1<<2, /* Stop sync Rate Control */
TXA_ENA_ARB = 1<<1, /* Enable Tx Arbiter */
TXA_DIS_ARB = 1<<0, /* Disable Tx Arbiter */
};
/*
* Bank 4 - 5
*/
/* Transmit Arbiter Registers MAC 1 and 2, use SK_REG() to access */
enum {
TXA_ITI_INI = 0x0200,/* 32 bit Tx Arb Interval Timer Init Val*/
TXA_ITI_VAL = 0x0204,/* 32 bit Tx Arb Interval Timer Value */
TXA_LIM_INI = 0x0208,/* 32 bit Tx Arb Limit Counter Init Val */
TXA_LIM_VAL = 0x020c,/* 32 bit Tx Arb Limit Counter Value */
TXA_CTRL = 0x0210,/* 8 bit Tx Arbiter Control Register */
TXA_TEST = 0x0211,/* 8 bit Tx Arbiter Test Register */
TXA_STAT = 0x0212,/* 8 bit Tx Arbiter Status Register */
};
enum {
B6_EXT_REG = 0x0300,/* External registers (GENESIS only) */
B7_CFG_SPC = 0x0380,/* copy of the Configuration register */
B8_RQ1_REGS = 0x0400,/* Receive Queue 1 */
B8_RQ2_REGS = 0x0480,/* Receive Queue 2 */
B8_TS1_REGS = 0x0600,/* Transmit sync queue 1 */
B8_TA1_REGS = 0x0680,/* Transmit async queue 1 */
B8_TS2_REGS = 0x0700,/* Transmit sync queue 2 */
B8_TA2_REGS = 0x0780,/* Transmit sync queue 2 */
B16_RAM_REGS = 0x0800,/* RAM Buffer Registers */
};
/* Queue Register Offsets, use Q_ADDR() to access */
enum {
B8_Q_REGS = 0x0400, /* base of Queue registers */
Q_D = 0x00, /* 8*32 bit Current Descriptor */
Q_DA_L = 0x20, /* 32 bit Current Descriptor Address Low dWord */
Q_DA_H = 0x24, /* 32 bit Current Descriptor Address High dWord */
Q_AC_L = 0x28, /* 32 bit Current Address Counter Low dWord */
Q_AC_H = 0x2c, /* 32 bit Current Address Counter High dWord */
Q_BC = 0x30, /* 32 bit Current Byte Counter */
Q_CSR = 0x34, /* 32 bit BMU Control/Status Register */
Q_F = 0x38, /* 32 bit Flag Register */
Q_T1 = 0x3c, /* 32 bit Test Register 1 */
Q_T1_TR = 0x3c, /* 8 bit Test Register 1 Transfer SM */
Q_T1_WR = 0x3d, /* 8 bit Test Register 1 Write Descriptor SM */
Q_T1_RD = 0x3e, /* 8 bit Test Register 1 Read Descriptor SM */
Q_T1_SV = 0x3f, /* 8 bit Test Register 1 Supervisor SM */
Q_T2 = 0x40, /* 32 bit Test Register 2 */
Q_T3 = 0x44, /* 32 bit Test Register 3 */
/* Yukon-2 */
Q_DONE = 0x24, /* 16 bit Done Index (Yukon-2 only) */
Q_WM = 0x40, /* 16 bit FIFO Watermark */
Q_AL = 0x42, /* 8 bit FIFO Alignment */
Q_RSP = 0x44, /* 16 bit FIFO Read Shadow Pointer */
Q_RSL = 0x46, /* 8 bit FIFO Read Shadow Level */
Q_RP = 0x48, /* 8 bit FIFO Read Pointer */
Q_RL = 0x4a, /* 8 bit FIFO Read Level */
Q_WP = 0x4c, /* 8 bit FIFO Write Pointer */
Q_WSP = 0x4d, /* 8 bit FIFO Write Shadow Pointer */
Q_WL = 0x4e, /* 8 bit FIFO Write Level */
Q_WSL = 0x4f, /* 8 bit FIFO Write Shadow Level */
};
#define Q_ADDR(reg, offs) (B8_Q_REGS + (reg) + (offs))
/* Q_F 32 bit Flag Register */
enum {
F_ALM_FULL = 1<<27, /* Rx FIFO: almost full */
F_EMPTY = 1<<27, /* Tx FIFO: empty flag */
F_FIFO_EOF = 1<<26, /* Tag (EOF Flag) bit in FIFO */
F_WM_REACHED = 1<<25, /* Watermark reached */
F_M_RX_RAM_DIS = 1<<24, /* MAC Rx RAM Read Port disable */
F_FIFO_LEVEL = 0x1fL<<16, /* Bit 23..16: # of Qwords in FIFO */
F_WATER_MARK = 0x0007ffL, /* Bit 10.. 0: Watermark */
};
/* Queue Prefetch Unit Offsets, use Y2_QADDR() to address (Yukon-2 only)*/
enum {
Y2_B8_PREF_REGS = 0x0450,
PREF_UNIT_CTRL = 0x00, /* 32 bit Control register */
PREF_UNIT_LAST_IDX = 0x04, /* 16 bit Last Index */
PREF_UNIT_ADDR_LO = 0x08, /* 32 bit List start addr, low part */
PREF_UNIT_ADDR_HI = 0x0c, /* 32 bit List start addr, high part*/
PREF_UNIT_GET_IDX = 0x10, /* 16 bit Get Index */
PREF_UNIT_PUT_IDX = 0x14, /* 16 bit Put Index */
PREF_UNIT_FIFO_WP = 0x20, /* 8 bit FIFO write pointer */
PREF_UNIT_FIFO_RP = 0x24, /* 8 bit FIFO read pointer */
PREF_UNIT_FIFO_WM = 0x28, /* 8 bit FIFO watermark */
PREF_UNIT_FIFO_LEV = 0x2c, /* 8 bit FIFO level */
PREF_UNIT_MASK_IDX = 0x0fff,
};
#define Y2_QADDR(q,reg) (Y2_B8_PREF_REGS + (q) + (reg))
/* RAM Buffer Register Offsets */
enum {
RB_START = 0x00,/* 32 bit RAM Buffer Start Address */
RB_END = 0x04,/* 32 bit RAM Buffer End Address */
RB_WP = 0x08,/* 32 bit RAM Buffer Write Pointer */
RB_RP = 0x0c,/* 32 bit RAM Buffer Read Pointer */
RB_RX_UTPP = 0x10,/* 32 bit Rx Upper Threshold, Pause Packet */
RB_RX_LTPP = 0x14,/* 32 bit Rx Lower Threshold, Pause Packet */
RB_RX_UTHP = 0x18,/* 32 bit Rx Upper Threshold, High Prio */
RB_RX_LTHP = 0x1c,/* 32 bit Rx Lower Threshold, High Prio */
/* 0x10 - 0x1f: reserved at Tx RAM Buffer Registers */
RB_PC = 0x20,/* 32 bit RAM Buffer Packet Counter */
RB_LEV = 0x24,/* 32 bit RAM Buffer Level Register */
RB_CTRL = 0x28,/* 32 bit RAM Buffer Control Register */
RB_TST1 = 0x29,/* 8 bit RAM Buffer Test Register 1 */
RB_TST2 = 0x2a,/* 8 bit RAM Buffer Test Register 2 */
};
/* Receive and Transmit Queues */
enum {
Q_R1 = 0x0000, /* Receive Queue 1 */
Q_R2 = 0x0080, /* Receive Queue 2 */
Q_XS1 = 0x0200, /* Synchronous Transmit Queue 1 */
Q_XA1 = 0x0280, /* Asynchronous Transmit Queue 1 */
Q_XS2 = 0x0300, /* Synchronous Transmit Queue 2 */
Q_XA2 = 0x0380, /* Asynchronous Transmit Queue 2 */
};
/* Different PHY Types */
enum {
PHY_ADDR_MARV = 0,
};
#define RB_ADDR(offs, queue) ((u16) B16_RAM_REGS + (queue) + (offs))
enum {
LNK_SYNC_INI = 0x0c30,/* 32 bit Link Sync Cnt Init Value */
LNK_SYNC_VAL = 0x0c34,/* 32 bit Link Sync Cnt Current Value */
LNK_SYNC_CTRL = 0x0c38,/* 8 bit Link Sync Cnt Control Register */
LNK_SYNC_TST = 0x0c39,/* 8 bit Link Sync Cnt Test Register */
LNK_LED_REG = 0x0c3c,/* 8 bit Link LED Register */
/* Receive GMAC FIFO (YUKON and Yukon-2) */
RX_GMF_EA = 0x0c40,/* 32 bit Rx GMAC FIFO End Address */
RX_GMF_AF_THR = 0x0c44,/* 32 bit Rx GMAC FIFO Almost Full Thresh. */
RX_GMF_CTRL_T = 0x0c48,/* 32 bit Rx GMAC FIFO Control/Test */
RX_GMF_FL_MSK = 0x0c4c,/* 32 bit Rx GMAC FIFO Flush Mask */
RX_GMF_FL_THR = 0x0c50,/* 32 bit Rx GMAC FIFO Flush Threshold */
RX_GMF_TR_THR = 0x0c54,/* 32 bit Rx Truncation Threshold (Yukon-2) */
RX_GMF_UP_THR = 0x0c58,/* 8 bit Rx Upper Pause Thr (Yukon-EC_U) */
RX_GMF_LP_THR = 0x0c5a,/* 8 bit Rx Lower Pause Thr (Yukon-EC_U) */
RX_GMF_VLAN = 0x0c5c,/* 32 bit Rx VLAN Type Register (Yukon-2) */
RX_GMF_WP = 0x0c60,/* 32 bit Rx GMAC FIFO Write Pointer */
RX_GMF_WLEV = 0x0c68,/* 32 bit Rx GMAC FIFO Write Level */
RX_GMF_RP = 0x0c70,/* 32 bit Rx GMAC FIFO Read Pointer */
RX_GMF_RLEV = 0x0c78,/* 32 bit Rx GMAC FIFO Read Level */
};
/* Q_BC 32 bit Current Byte Counter */
/* BMU Control Status Registers */
/* B0_R1_CSR 32 bit BMU Ctrl/Stat Rx Queue 1 */
/* B0_R2_CSR 32 bit BMU Ctrl/Stat Rx Queue 2 */
/* B0_XA1_CSR 32 bit BMU Ctrl/Stat Sync Tx Queue 1 */
/* B0_XS1_CSR 32 bit BMU Ctrl/Stat Async Tx Queue 1 */
/* B0_XA2_CSR 32 bit BMU Ctrl/Stat Sync Tx Queue 2 */
/* B0_XS2_CSR 32 bit BMU Ctrl/Stat Async Tx Queue 2 */
/* Q_CSR 32 bit BMU Control/Status Register */
/* Rx BMU Control / Status Registers (Yukon-2) */
enum {
BMU_IDLE = 1<<31, /* BMU Idle State */
BMU_RX_TCP_PKT = 1<<30, /* Rx TCP Packet (when RSS Hash enabled) */
BMU_RX_IP_PKT = 1<<29, /* Rx IP Packet (when RSS Hash enabled) */
BMU_ENA_RX_RSS_HASH = 1<<15, /* Enable Rx RSS Hash */
BMU_DIS_RX_RSS_HASH = 1<<14, /* Disable Rx RSS Hash */
BMU_ENA_RX_CHKSUM = 1<<13, /* Enable Rx TCP/IP Checksum Check */
BMU_DIS_RX_CHKSUM = 1<<12, /* Disable Rx TCP/IP Checksum Check */
BMU_CLR_IRQ_PAR = 1<<11, /* Clear IRQ on Parity errors (Rx) */
BMU_CLR_IRQ_TCP = 1<<11, /* Clear IRQ on TCP segment. error (Tx) */
BMU_CLR_IRQ_CHK = 1<<10, /* Clear IRQ Check */
BMU_STOP = 1<<9, /* Stop Rx/Tx Queue */
BMU_START = 1<<8, /* Start Rx/Tx Queue */
BMU_FIFO_OP_ON = 1<<7, /* FIFO Operational On */
BMU_FIFO_OP_OFF = 1<<6, /* FIFO Operational Off */
BMU_FIFO_ENA = 1<<5, /* Enable FIFO */
BMU_FIFO_RST = 1<<4, /* Reset FIFO */
BMU_OP_ON = 1<<3, /* BMU Operational On */
BMU_OP_OFF = 1<<2, /* BMU Operational Off */
BMU_RST_CLR = 1<<1, /* Clear BMU Reset (Enable) */
BMU_RST_SET = 1<<0, /* Set BMU Reset */
BMU_CLR_RESET = BMU_FIFO_RST | BMU_OP_OFF | BMU_RST_CLR,
BMU_OPER_INIT = BMU_CLR_IRQ_PAR | BMU_CLR_IRQ_CHK | BMU_START |
BMU_FIFO_ENA | BMU_OP_ON,
BMU_WM_DEFAULT = 0x600,
BMU_WM_PEX = 0x80,
};
/* Tx BMU Control / Status Registers (Yukon-2) */
/* Bit 31: same as for Rx */
enum {
BMU_TX_IPIDINCR_ON = 1<<13, /* Enable IP ID Increment */
BMU_TX_IPIDINCR_OFF = 1<<12, /* Disable IP ID Increment */
BMU_TX_CLR_IRQ_TCP = 1<<11, /* Clear IRQ on TCP segment length mismatch */
};
/* Queue Prefetch Unit Offsets, use Y2_QADDR() to address (Yukon-2 only)*/
/* PREF_UNIT_CTRL 32 bit Prefetch Control register */
enum {
PREF_UNIT_OP_ON = 1<<3, /* prefetch unit operational */
PREF_UNIT_OP_OFF = 1<<2, /* prefetch unit not operational */
PREF_UNIT_RST_CLR = 1<<1, /* Clear Prefetch Unit Reset */
PREF_UNIT_RST_SET = 1<<0, /* Set Prefetch Unit Reset */
};
/* RAM Buffer Register Offsets, use RB_ADDR(Queue, Offs) to access */
/* RB_START 32 bit RAM Buffer Start Address */
/* RB_END 32 bit RAM Buffer End Address */
/* RB_WP 32 bit RAM Buffer Write Pointer */
/* RB_RP 32 bit RAM Buffer Read Pointer */
/* RB_RX_UTPP 32 bit Rx Upper Threshold, Pause Pack */
/* RB_RX_LTPP 32 bit Rx Lower Threshold, Pause Pack */
/* RB_RX_UTHP 32 bit Rx Upper Threshold, High Prio */
/* RB_RX_LTHP 32 bit Rx Lower Threshold, High Prio */
/* RB_PC 32 bit RAM Buffer Packet Counter */
/* RB_LEV 32 bit RAM Buffer Level Register */
#define RB_MSK 0x0007ffff /* Bit 18.. 0: RAM Buffer Pointer Bits */
/* RB_TST2 8 bit RAM Buffer Test Register 2 */
/* RB_TST1 8 bit RAM Buffer Test Register 1 */
/* RB_CTRL 8 bit RAM Buffer Control Register */
enum {
RB_ENA_STFWD = 1<<5, /* Enable Store & Forward */
RB_DIS_STFWD = 1<<4, /* Disable Store & Forward */
RB_ENA_OP_MD = 1<<3, /* Enable Operation Mode */
RB_DIS_OP_MD = 1<<2, /* Disable Operation Mode */
RB_RST_CLR = 1<<1, /* Clear RAM Buf STM Reset */
RB_RST_SET = 1<<0, /* Set RAM Buf STM Reset */
};
/* Transmit GMAC FIFO (YUKON only) */
enum {
TX_GMF_EA = 0x0d40,/* 32 bit Tx GMAC FIFO End Address */
TX_GMF_AE_THR = 0x0d44,/* 32 bit Tx GMAC FIFO Almost Empty Thresh.*/
TX_GMF_CTRL_T = 0x0d48,/* 32 bit Tx GMAC FIFO Control/Test */
TX_GMF_WP = 0x0d60,/* 32 bit Tx GMAC FIFO Write Pointer */
TX_GMF_WSP = 0x0d64,/* 32 bit Tx GMAC FIFO Write Shadow Ptr. */
TX_GMF_WLEV = 0x0d68,/* 32 bit Tx GMAC FIFO Write Level */
TX_GMF_RP = 0x0d70,/* 32 bit Tx GMAC FIFO Read Pointer */
TX_GMF_RSTP = 0x0d74,/* 32 bit Tx GMAC FIFO Restart Pointer */
TX_GMF_RLEV = 0x0d78,/* 32 bit Tx GMAC FIFO Read Level */
/* Threshold values for Yukon-EC Ultra and Extreme */
ECU_AE_THR = 0x0070, /* Almost Empty Threshold */
ECU_TXFF_LEV = 0x01a0, /* Tx BMU FIFO Level */
ECU_JUMBO_WM = 0x0080, /* Jumbo Mode Watermark */
};
/* Descriptor Poll Timer Registers */
enum {
B28_DPT_INI = 0x0e00,/* 24 bit Descriptor Poll Timer Init Val */
B28_DPT_VAL = 0x0e04,/* 24 bit Descriptor Poll Timer Curr Val */
B28_DPT_CTRL = 0x0e08,/* 8 bit Descriptor Poll Timer Ctrl Reg */
B28_DPT_TST = 0x0e0a,/* 8 bit Descriptor Poll Timer Test Reg */
};
/* Time Stamp Timer Registers (YUKON only) */
enum {
GMAC_TI_ST_VAL = 0x0e14,/* 32 bit Time Stamp Timer Curr Val */
GMAC_TI_ST_CTRL = 0x0e18,/* 8 bit Time Stamp Timer Ctrl Reg */
GMAC_TI_ST_TST = 0x0e1a,/* 8 bit Time Stamp Timer Test Reg */
};
/* Polling Unit Registers (Yukon-2 only) */
enum {
POLL_CTRL = 0x0e20, /* 32 bit Polling Unit Control Reg */
POLL_LAST_IDX = 0x0e24,/* 16 bit Polling Unit List Last Index */
POLL_LIST_ADDR_LO= 0x0e28,/* 32 bit Poll. List Start Addr (low) */
POLL_LIST_ADDR_HI= 0x0e2c,/* 32 bit Poll. List Start Addr (high) */
};
enum {
SMB_CFG = 0x0e40, /* 32 bit SMBus Config Register */
SMB_CSR = 0x0e44, /* 32 bit SMBus Control/Status Register */
};
enum {
CPU_WDOG = 0x0e48, /* 32 bit Watchdog Register */
CPU_CNTR = 0x0e4C, /* 32 bit Counter Register */
CPU_TIM = 0x0e50,/* 32 bit Timer Compare Register */
CPU_AHB_ADDR = 0x0e54, /* 32 bit CPU AHB Debug Register */
CPU_AHB_WDATA = 0x0e58, /* 32 bit CPU AHB Debug Register */
CPU_AHB_RDATA = 0x0e5C, /* 32 bit CPU AHB Debug Register */
HCU_MAP_BASE = 0x0e60, /* 32 bit Reset Mapping Base */
CPU_AHB_CTRL = 0x0e64, /* 32 bit CPU AHB Debug Register */
HCU_CCSR = 0x0e68, /* 32 bit CPU Control and Status Register */
HCU_HCSR = 0x0e6C, /* 32 bit Host Control and Status Register */
};
/* ASF Subsystem Registers (Yukon-2 only) */
enum {
B28_Y2_SMB_CONFIG = 0x0e40,/* 32 bit ASF SMBus Config Register */
B28_Y2_SMB_CSD_REG = 0x0e44,/* 32 bit ASF SMB Control/Status/Data */
B28_Y2_ASF_IRQ_V_BASE=0x0e60,/* 32 bit ASF IRQ Vector Base */
B28_Y2_ASF_STAT_CMD= 0x0e68,/* 32 bit ASF Status and Command Reg */
B28_Y2_ASF_HOST_COM= 0x0e6c,/* 32 bit ASF Host Communication Reg */
B28_Y2_DATA_REG_1 = 0x0e70,/* 32 bit ASF/Host Data Register 1 */
B28_Y2_DATA_REG_2 = 0x0e74,/* 32 bit ASF/Host Data Register 2 */
B28_Y2_DATA_REG_3 = 0x0e78,/* 32 bit ASF/Host Data Register 3 */
B28_Y2_DATA_REG_4 = 0x0e7c,/* 32 bit ASF/Host Data Register 4 */
};
/* Status BMU Registers (Yukon-2 only)*/
enum {
STAT_CTRL = 0x0e80,/* 32 bit Status BMU Control Reg */
STAT_LAST_IDX = 0x0e84,/* 16 bit Status BMU Last Index */
STAT_LIST_ADDR_LO= 0x0e88,/* 32 bit Status List Start Addr (low) */
STAT_LIST_ADDR_HI= 0x0e8c,/* 32 bit Status List Start Addr (high) */
STAT_TXA1_RIDX = 0x0e90,/* 16 bit Status TxA1 Report Index Reg */
STAT_TXS1_RIDX = 0x0e92,/* 16 bit Status TxS1 Report Index Reg */
STAT_TXA2_RIDX = 0x0e94,/* 16 bit Status TxA2 Report Index Reg */
STAT_TXS2_RIDX = 0x0e96,/* 16 bit Status TxS2 Report Index Reg */
STAT_TX_IDX_TH = 0x0e98,/* 16 bit Status Tx Index Threshold Reg */
STAT_PUT_IDX = 0x0e9c,/* 16 bit Status Put Index Reg */
/* FIFO Control/Status Registers (Yukon-2 only)*/
STAT_FIFO_WP = 0x0ea0,/* 8 bit Status FIFO Write Pointer Reg */
STAT_FIFO_RP = 0x0ea4,/* 8 bit Status FIFO Read Pointer Reg */
STAT_FIFO_RSP = 0x0ea6,/* 8 bit Status FIFO Read Shadow Ptr */
STAT_FIFO_LEVEL = 0x0ea8,/* 8 bit Status FIFO Level Reg */
STAT_FIFO_SHLVL = 0x0eaa,/* 8 bit Status FIFO Shadow Level Reg */
STAT_FIFO_WM = 0x0eac,/* 8 bit Status FIFO Watermark Reg */
STAT_FIFO_ISR_WM= 0x0ead,/* 8 bit Status FIFO ISR Watermark Reg */
/* Level and ISR Timer Registers (Yukon-2 only)*/
STAT_LEV_TIMER_INI= 0x0eb0,/* 32 bit Level Timer Init. Value Reg */
STAT_LEV_TIMER_CNT= 0x0eb4,/* 32 bit Level Timer Counter Reg */
STAT_LEV_TIMER_CTRL= 0x0eb8,/* 8 bit Level Timer Control Reg */
STAT_LEV_TIMER_TEST= 0x0eb9,/* 8 bit Level Timer Test Reg */
STAT_TX_TIMER_INI = 0x0ec0,/* 32 bit Tx Timer Init. Value Reg */
STAT_TX_TIMER_CNT = 0x0ec4,/* 32 bit Tx Timer Counter Reg */
STAT_TX_TIMER_CTRL = 0x0ec8,/* 8 bit Tx Timer Control Reg */
STAT_TX_TIMER_TEST = 0x0ec9,/* 8 bit Tx Timer Test Reg */
STAT_ISR_TIMER_INI = 0x0ed0,/* 32 bit ISR Timer Init. Value Reg */
STAT_ISR_TIMER_CNT = 0x0ed4,/* 32 bit ISR Timer Counter Reg */
STAT_ISR_TIMER_CTRL= 0x0ed8,/* 8 bit ISR Timer Control Reg */
STAT_ISR_TIMER_TEST= 0x0ed9,/* 8 bit ISR Timer Test Reg */
};
enum {
LINKLED_OFF = 0x01,
LINKLED_ON = 0x02,
LINKLED_LINKSYNC_OFF = 0x04,
LINKLED_LINKSYNC_ON = 0x08,
LINKLED_BLINK_OFF = 0x10,
LINKLED_BLINK_ON = 0x20,
};
/* GMAC and GPHY Control Registers (YUKON only) */
enum {
GMAC_CTRL = 0x0f00,/* 32 bit GMAC Control Reg */
GPHY_CTRL = 0x0f04,/* 32 bit GPHY Control Reg */
GMAC_IRQ_SRC = 0x0f08,/* 8 bit GMAC Interrupt Source Reg */
GMAC_IRQ_MSK = 0x0f0c,/* 8 bit GMAC Interrupt Mask Reg */
GMAC_LINK_CTRL = 0x0f10,/* 16 bit Link Control Reg */
/* Wake-up Frame Pattern Match Control Registers (YUKON only) */
WOL_CTRL_STAT = 0x0f20,/* 16 bit WOL Control/Status Reg */
WOL_MATCH_CTL = 0x0f22,/* 8 bit WOL Match Control Reg */
WOL_MATCH_RES = 0x0f23,/* 8 bit WOL Match Result Reg */
WOL_MAC_ADDR = 0x0f24,/* 32 bit WOL MAC Address */
WOL_PATT_RPTR = 0x0f2c,/* 8 bit WOL Pattern Read Pointer */
/* WOL Pattern Length Registers (YUKON only) */
WOL_PATT_LEN_LO = 0x0f30,/* 32 bit WOL Pattern Length 3..0 */
WOL_PATT_LEN_HI = 0x0f34,/* 24 bit WOL Pattern Length 6..4 */
/* WOL Pattern Counter Registers (YUKON only) */
WOL_PATT_CNT_0 = 0x0f38,/* 32 bit WOL Pattern Counter 3..0 */
WOL_PATT_CNT_4 = 0x0f3c,/* 24 bit WOL Pattern Counter 6..4 */
};
#define WOL_REGS(port, x) (x + (port)*0x80)
enum {
WOL_PATT_RAM_1 = 0x1000,/* WOL Pattern RAM Link 1 */
WOL_PATT_RAM_2 = 0x1400,/* WOL Pattern RAM Link 2 */
};
#define WOL_PATT_RAM_BASE(port) (WOL_PATT_RAM_1 + (port)*0x400)
enum {
BASE_GMAC_1 = 0x2800,/* GMAC 1 registers */
BASE_GMAC_2 = 0x3800,/* GMAC 2 registers */
};
/*
* Marvel-PHY Registers, indirect addressed over GMAC
*/
enum {
PHY_MARV_CTRL = 0x00,/* 16 bit r/w PHY Control Register */
PHY_MARV_STAT = 0x01,/* 16 bit r/o PHY Status Register */
PHY_MARV_ID0 = 0x02,/* 16 bit r/o PHY ID0 Register */
PHY_MARV_ID1 = 0x03,/* 16 bit r/o PHY ID1 Register */
PHY_MARV_AUNE_ADV = 0x04,/* 16 bit r/w Auto-Neg. Advertisement */
PHY_MARV_AUNE_LP = 0x05,/* 16 bit r/o Link Part Ability Reg */
PHY_MARV_AUNE_EXP = 0x06,/* 16 bit r/o Auto-Neg. Expansion Reg */
PHY_MARV_NEPG = 0x07,/* 16 bit r/w Next Page Register */
PHY_MARV_NEPG_LP = 0x08,/* 16 bit r/o Next Page Link Partner */
/* Marvel-specific registers */
PHY_MARV_1000T_CTRL = 0x09,/* 16 bit r/w 1000Base-T Control Reg */
PHY_MARV_1000T_STAT = 0x0a,/* 16 bit r/o 1000Base-T Status Reg */
PHY_MARV_EXT_STAT = 0x0f,/* 16 bit r/o Extended Status Reg */
PHY_MARV_PHY_CTRL = 0x10,/* 16 bit r/w PHY Specific Ctrl Reg */
PHY_MARV_PHY_STAT = 0x11,/* 16 bit r/o PHY Specific Stat Reg */
PHY_MARV_INT_MASK = 0x12,/* 16 bit r/w Interrupt Mask Reg */
PHY_MARV_INT_STAT = 0x13,/* 16 bit r/o Interrupt Status Reg */
PHY_MARV_EXT_CTRL = 0x14,/* 16 bit r/w Ext. PHY Specific Ctrl */
PHY_MARV_RXE_CNT = 0x15,/* 16 bit r/w Receive Error Counter */
PHY_MARV_EXT_ADR = 0x16,/* 16 bit r/w Ext. Ad. for Cable Diag. */
PHY_MARV_PORT_IRQ = 0x17,/* 16 bit r/o Port 0 IRQ (88E1111 only) */
PHY_MARV_LED_CTRL = 0x18,/* 16 bit r/w LED Control Reg */
PHY_MARV_LED_OVER = 0x19,/* 16 bit r/w Manual LED Override Reg */
PHY_MARV_EXT_CTRL_2 = 0x1a,/* 16 bit r/w Ext. PHY Specific Ctrl 2 */
PHY_MARV_EXT_P_STAT = 0x1b,/* 16 bit r/w Ext. PHY Spec. Stat Reg */
PHY_MARV_CABLE_DIAG = 0x1c,/* 16 bit r/o Cable Diagnostic Reg */
PHY_MARV_PAGE_ADDR = 0x1d,/* 16 bit r/w Extended Page Address Reg */
PHY_MARV_PAGE_DATA = 0x1e,/* 16 bit r/w Extended Page Data Reg */
/* for 10/100 Fast Ethernet PHY (88E3082 only) */
PHY_MARV_FE_LED_PAR = 0x16,/* 16 bit r/w LED Parallel Select Reg. */
PHY_MARV_FE_LED_SER = 0x17,/* 16 bit r/w LED Stream Select S. LED */
PHY_MARV_FE_VCT_TX = 0x1a,/* 16 bit r/w VCT Reg. for TXP/N Pins */
PHY_MARV_FE_VCT_RX = 0x1b,/* 16 bit r/o VCT Reg. for RXP/N Pins */
PHY_MARV_FE_SPEC_2 = 0x1c,/* 16 bit r/w Specific Control Reg. 2 */
};
enum {
PHY_CT_RESET = 1<<15, /* Bit 15: (sc) clear all PHY related regs */
PHY_CT_LOOP = 1<<14, /* Bit 14: enable Loopback over PHY */
PHY_CT_SPS_LSB = 1<<13, /* Bit 13: Speed select, lower bit */
PHY_CT_ANE = 1<<12, /* Bit 12: Auto-Negotiation Enabled */
PHY_CT_PDOWN = 1<<11, /* Bit 11: Power Down Mode */
PHY_CT_ISOL = 1<<10, /* Bit 10: Isolate Mode */
PHY_CT_RE_CFG = 1<<9, /* Bit 9: (sc) Restart Auto-Negotiation */
PHY_CT_DUP_MD = 1<<8, /* Bit 8: Duplex Mode */
PHY_CT_COL_TST = 1<<7, /* Bit 7: Collision Test enabled */
PHY_CT_SPS_MSB = 1<<6, /* Bit 6: Speed select, upper bit */
};
enum {
PHY_CT_SP1000 = PHY_CT_SPS_MSB, /* enable speed of 1000 Mbps */
PHY_CT_SP100 = PHY_CT_SPS_LSB, /* enable speed of 100 Mbps */
PHY_CT_SP10 = 0, /* enable speed of 10 Mbps */
};
enum {
PHY_ST_EXT_ST = 1<<8, /* Bit 8: Extended Status Present */
PHY_ST_PRE_SUP = 1<<6, /* Bit 6: Preamble Suppression */
PHY_ST_AN_OVER = 1<<5, /* Bit 5: Auto-Negotiation Over */
PHY_ST_REM_FLT = 1<<4, /* Bit 4: Remote Fault Condition Occured */
PHY_ST_AN_CAP = 1<<3, /* Bit 3: Auto-Negotiation Capability */
PHY_ST_LSYNC = 1<<2, /* Bit 2: Link Synchronized */
PHY_ST_JAB_DET = 1<<1, /* Bit 1: Jabber Detected */
PHY_ST_EXT_REG = 1<<0, /* Bit 0: Extended Register available */
};
enum {
PHY_I1_OUI_MSK = 0x3f<<10, /* Bit 15..10: Organization Unique ID */
PHY_I1_MOD_NUM = 0x3f<<4, /* Bit 9.. 4: Model Number */
PHY_I1_REV_MSK = 0xf, /* Bit 3.. 0: Revision Number */
};
/* different Marvell PHY Ids */
enum {
PHY_MARV_ID0_VAL= 0x0141, /* Marvell Unique Identifier */
PHY_BCOM_ID1_A1 = 0x6041,
PHY_BCOM_ID1_B2 = 0x6043,
PHY_BCOM_ID1_C0 = 0x6044,
PHY_BCOM_ID1_C5 = 0x6047,
PHY_MARV_ID1_B0 = 0x0C23, /* Yukon (PHY 88E1011) */
PHY_MARV_ID1_B2 = 0x0C25, /* Yukon-Plus (PHY 88E1011) */
PHY_MARV_ID1_C2 = 0x0CC2, /* Yukon-EC (PHY 88E1111) */
PHY_MARV_ID1_Y2 = 0x0C91, /* Yukon-2 (PHY 88E1112) */
PHY_MARV_ID1_FE = 0x0C83, /* Yukon-FE (PHY 88E3082 Rev.A1) */
PHY_MARV_ID1_ECU= 0x0CB0, /* Yukon-ECU (PHY 88E1149 Rev.B2?) */
};
/* Advertisement register bits */
enum {
PHY_AN_NXT_PG = 1<<15, /* Bit 15: Request Next Page */
PHY_AN_ACK = 1<<14, /* Bit 14: (ro) Acknowledge Received */
PHY_AN_RF = 1<<13, /* Bit 13: Remote Fault Bits */
PHY_AN_PAUSE_ASYM = 1<<11,/* Bit 11: Try for asymmetric */
PHY_AN_PAUSE_CAP = 1<<10, /* Bit 10: Try for pause */
PHY_AN_100BASE4 = 1<<9, /* Bit 9: Try for 100mbps 4k packets */
PHY_AN_100FULL = 1<<8, /* Bit 8: Try for 100mbps full-duplex */
PHY_AN_100HALF = 1<<7, /* Bit 7: Try for 100mbps half-duplex */
PHY_AN_10FULL = 1<<6, /* Bit 6: Try for 10mbps full-duplex */
PHY_AN_10HALF = 1<<5, /* Bit 5: Try for 10mbps half-duplex */
PHY_AN_CSMA = 1<<0, /* Bit 0: Only selector supported */
PHY_AN_SEL = 0x1f, /* Bit 4..0: Selector Field, 00001=Ethernet*/
PHY_AN_FULL = PHY_AN_100FULL | PHY_AN_10FULL | PHY_AN_CSMA,
PHY_AN_ALL = PHY_AN_10HALF | PHY_AN_10FULL |
PHY_AN_100HALF | PHY_AN_100FULL,
};
/***** PHY_BCOM_1000T_STAT 16 bit r/o 1000Base-T Status Reg *****/
/***** PHY_MARV_1000T_STAT 16 bit r/o 1000Base-T Status Reg *****/
enum {
PHY_B_1000S_MSF = 1<<15, /* Bit 15: Master/Slave Fault */
PHY_B_1000S_MSR = 1<<14, /* Bit 14: Master/Slave Result */
PHY_B_1000S_LRS = 1<<13, /* Bit 13: Local Receiver Status */
PHY_B_1000S_RRS = 1<<12, /* Bit 12: Remote Receiver Status */
PHY_B_1000S_LP_FD = 1<<11, /* Bit 11: Link Partner can FD */
PHY_B_1000S_LP_HD = 1<<10, /* Bit 10: Link Partner can HD */
/* Bit 9..8: reserved */
PHY_B_1000S_IEC = 0xff, /* Bit 7..0: Idle Error Count */
};
/** Marvell-Specific */
enum {
PHY_M_AN_NXT_PG = 1<<15, /* Request Next Page */
PHY_M_AN_ACK = 1<<14, /* (ro) Acknowledge Received */
PHY_M_AN_RF = 1<<13, /* Remote Fault */
PHY_M_AN_ASP = 1<<11, /* Asymmetric Pause */
PHY_M_AN_PC = 1<<10, /* MAC Pause implemented */
PHY_M_AN_100_T4 = 1<<9, /* Not cap. 100Base-T4 (always 0) */
PHY_M_AN_100_FD = 1<<8, /* Advertise 100Base-TX Full Duplex */
PHY_M_AN_100_HD = 1<<7, /* Advertise 100Base-TX Half Duplex */
PHY_M_AN_10_FD = 1<<6, /* Advertise 10Base-TX Full Duplex */
PHY_M_AN_10_HD = 1<<5, /* Advertise 10Base-TX Half Duplex */
PHY_M_AN_SEL_MSK =0x1f<<4, /* Bit 4.. 0: Selector Field Mask */
};
/* special defines for FIBER (88E1011S only) */
enum {
PHY_M_AN_ASP_X = 1<<8, /* Asymmetric Pause */
PHY_M_AN_PC_X = 1<<7, /* MAC Pause implemented */
PHY_M_AN_1000X_AHD = 1<<6, /* Advertise 10000Base-X Half Duplex */
PHY_M_AN_1000X_AFD = 1<<5, /* Advertise 10000Base-X Full Duplex */
};
/* Pause Bits (PHY_M_AN_ASP_X and PHY_M_AN_PC_X) encoding */
enum {
PHY_M_P_NO_PAUSE_X = 0<<7,/* Bit 8.. 7: no Pause Mode */
PHY_M_P_SYM_MD_X = 1<<7, /* Bit 8.. 7: symmetric Pause Mode */
PHY_M_P_ASYM_MD_X = 2<<7,/* Bit 8.. 7: asymmetric Pause Mode */
PHY_M_P_BOTH_MD_X = 3<<7,/* Bit 8.. 7: both Pause Mode */
};
/***** PHY_MARV_1000T_CTRL 16 bit r/w 1000Base-T Control Reg *****/
enum {
PHY_M_1000C_TEST = 7<<13,/* Bit 15..13: Test Modes */
PHY_M_1000C_MSE = 1<<12, /* Manual Master/Slave Enable */
PHY_M_1000C_MSC = 1<<11, /* M/S Configuration (1=Master) */
PHY_M_1000C_MPD = 1<<10, /* Multi-Port Device */
PHY_M_1000C_AFD = 1<<9, /* Advertise Full Duplex */
PHY_M_1000C_AHD = 1<<8, /* Advertise Half Duplex */
};
/***** PHY_MARV_PHY_CTRL 16 bit r/w PHY Specific Ctrl Reg *****/
enum {
PHY_M_PC_TX_FFD_MSK = 3<<14,/* Bit 15..14: Tx FIFO Depth Mask */
PHY_M_PC_RX_FFD_MSK = 3<<12,/* Bit 13..12: Rx FIFO Depth Mask */
PHY_M_PC_ASS_CRS_TX = 1<<11, /* Assert CRS on Transmit */
PHY_M_PC_FL_GOOD = 1<<10, /* Force Link Good */
PHY_M_PC_EN_DET_MSK = 3<<8,/* Bit 9.. 8: Energy Detect Mask */
PHY_M_PC_ENA_EXT_D = 1<<7, /* Enable Ext. Distance (10BT) */
PHY_M_PC_MDIX_MSK = 3<<5,/* Bit 6.. 5: MDI/MDIX Config. Mask */
PHY_M_PC_DIS_125CLK = 1<<4, /* Disable 125 CLK */
PHY_M_PC_MAC_POW_UP = 1<<3, /* MAC Power up */
PHY_M_PC_SQE_T_ENA = 1<<2, /* SQE Test Enabled */
PHY_M_PC_POL_R_DIS = 1<<1, /* Polarity Reversal Disabled */
PHY_M_PC_DIS_JABBER = 1<<0, /* Disable Jabber */
};
enum {
PHY_M_PC_EN_DET = 2<<8, /* Energy Detect (Mode 1) */
PHY_M_PC_EN_DET_PLUS = 3<<8, /* Energy Detect Plus (Mode 2) */
};
#define PHY_M_PC_MDI_XMODE(x) (((u16)(x)<<5) & PHY_M_PC_MDIX_MSK)
enum {
PHY_M_PC_MAN_MDI = 0, /* 00 = Manual MDI configuration */
PHY_M_PC_MAN_MDIX = 1, /* 01 = Manual MDIX configuration */
PHY_M_PC_ENA_AUTO = 3, /* 11 = Enable Automatic Crossover */
};
/* for 10/100 Fast Ethernet PHY (88E3082 only) */
enum {
PHY_M_PC_ENA_DTE_DT = 1<<15, /* Enable Data Terminal Equ. (DTE) Detect */
PHY_M_PC_ENA_ENE_DT = 1<<14, /* Enable Energy Detect (sense & pulse) */
PHY_M_PC_DIS_NLP_CK = 1<<13, /* Disable Normal Link Puls (NLP) Check */
PHY_M_PC_ENA_LIP_NP = 1<<12, /* Enable Link Partner Next Page Reg. */
PHY_M_PC_DIS_NLP_GN = 1<<11, /* Disable Normal Link Puls Generation */
PHY_M_PC_DIS_SCRAMB = 1<<9, /* Disable Scrambler */
PHY_M_PC_DIS_FEFI = 1<<8, /* Disable Far End Fault Indic. (FEFI) */
PHY_M_PC_SH_TP_SEL = 1<<6, /* Shielded Twisted Pair Select */
PHY_M_PC_RX_FD_MSK = 3<<2,/* Bit 3.. 2: Rx FIFO Depth Mask */
};
/***** PHY_MARV_PHY_STAT 16 bit r/o PHY Specific Status Reg *****/
enum {
PHY_M_PS_SPEED_MSK = 3<<14, /* Bit 15..14: Speed Mask */
PHY_M_PS_SPEED_1000 = 1<<15, /* 10 = 1000 Mbps */
PHY_M_PS_SPEED_100 = 1<<14, /* 01 = 100 Mbps */
PHY_M_PS_SPEED_10 = 0, /* 00 = 10 Mbps */
PHY_M_PS_FULL_DUP = 1<<13, /* Full Duplex */
PHY_M_PS_PAGE_REC = 1<<12, /* Page Received */
PHY_M_PS_SPDUP_RES = 1<<11, /* Speed & Duplex Resolved */
PHY_M_PS_LINK_UP = 1<<10, /* Link Up */
PHY_M_PS_CABLE_MSK = 7<<7, /* Bit 9.. 7: Cable Length Mask */
PHY_M_PS_MDI_X_STAT = 1<<6, /* MDI Crossover Stat (1=MDIX) */
PHY_M_PS_DOWNS_STAT = 1<<5, /* Downshift Status (1=downsh.) */
PHY_M_PS_ENDET_STAT = 1<<4, /* Energy Detect Status (1=act) */
PHY_M_PS_TX_P_EN = 1<<3, /* Tx Pause Enabled */
PHY_M_PS_RX_P_EN = 1<<2, /* Rx Pause Enabled */
PHY_M_PS_POL_REV = 1<<1, /* Polarity Reversed */
PHY_M_PS_JABBER = 1<<0, /* Jabber */
};
#define PHY_M_PS_PAUSE_MSK (PHY_M_PS_TX_P_EN | PHY_M_PS_RX_P_EN)
/* for 10/100 Fast Ethernet PHY (88E3082 only) */
enum {
PHY_M_PS_DTE_DETECT = 1<<15, /* Data Terminal Equipment (DTE) Detected */
PHY_M_PS_RES_SPEED = 1<<14, /* Resolved Speed (1=100 Mbps, 0=10 Mbps */
};
enum {
PHY_M_IS_AN_ERROR = 1<<15, /* Auto-Negotiation Error */
PHY_M_IS_LSP_CHANGE = 1<<14, /* Link Speed Changed */
PHY_M_IS_DUP_CHANGE = 1<<13, /* Duplex Mode Changed */
PHY_M_IS_AN_PR = 1<<12, /* Page Received */
PHY_M_IS_AN_COMPL = 1<<11, /* Auto-Negotiation Completed */
PHY_M_IS_LST_CHANGE = 1<<10, /* Link Status Changed */
PHY_M_IS_SYMB_ERROR = 1<<9, /* Symbol Error */
PHY_M_IS_FALSE_CARR = 1<<8, /* False Carrier */
PHY_M_IS_FIFO_ERROR = 1<<7, /* FIFO Overflow/Underrun Error */
PHY_M_IS_MDI_CHANGE = 1<<6, /* MDI Crossover Changed */
PHY_M_IS_DOWNSH_DET = 1<<5, /* Downshift Detected */
PHY_M_IS_END_CHANGE = 1<<4, /* Energy Detect Changed */
PHY_M_IS_DTE_CHANGE = 1<<2, /* DTE Power Det. Status Changed */
PHY_M_IS_POL_CHANGE = 1<<1, /* Polarity Changed */
PHY_M_IS_JABBER = 1<<0, /* Jabber */
PHY_M_DEF_MSK = PHY_M_IS_LSP_CHANGE | PHY_M_IS_LST_CHANGE
| PHY_M_IS_DUP_CHANGE,
PHY_M_AN_MSK = PHY_M_IS_AN_ERROR | PHY_M_IS_AN_COMPL,
};
/***** PHY_MARV_EXT_CTRL 16 bit r/w Ext. PHY Specific Ctrl *****/
enum {
PHY_M_EC_ENA_BC_EXT = 1<<15, /* Enable Block Carr. Ext. (88E1111 only) */
PHY_M_EC_ENA_LIN_LB = 1<<14, /* Enable Line Loopback (88E1111 only) */
PHY_M_EC_DIS_LINK_P = 1<<12, /* Disable Link Pulses (88E1111 only) */
PHY_M_EC_M_DSC_MSK = 3<<10, /* Bit 11..10: Master Downshift Counter */
/* (88E1011 only) */
PHY_M_EC_S_DSC_MSK = 3<<8,/* Bit 9.. 8: Slave Downshift Counter */
/* (88E1011 only) */
PHY_M_EC_M_DSC_MSK2 = 7<<9,/* Bit 11.. 9: Master Downshift Counter */
/* (88E1111 only) */
PHY_M_EC_DOWN_S_ENA = 1<<8, /* Downshift Enable (88E1111 only) */
/* !!! Errata in spec. (1 = disable) */
PHY_M_EC_RX_TIM_CT = 1<<7, /* RGMII Rx Timing Control*/
PHY_M_EC_MAC_S_MSK = 7<<4,/* Bit 6.. 4: Def. MAC interface speed */
PHY_M_EC_FIB_AN_ENA = 1<<3, /* Fiber Auto-Neg. Enable (88E1011S only) */
PHY_M_EC_DTE_D_ENA = 1<<2, /* DTE Detect Enable (88E1111 only) */
PHY_M_EC_TX_TIM_CT = 1<<1, /* RGMII Tx Timing Control */
PHY_M_EC_TRANS_DIS = 1<<0, /* Transmitter Disable (88E1111 only) */};
#define PHY_M_EC_M_DSC(x) ((u16)(x)<<10 & PHY_M_EC_M_DSC_MSK)
/* 00=1x; 01=2x; 10=3x; 11=4x */
#define PHY_M_EC_S_DSC(x) ((u16)(x)<<8 & PHY_M_EC_S_DSC_MSK)
/* 00=dis; 01=1x; 10=2x; 11=3x */
#define PHY_M_EC_DSC_2(x) ((u16)(x)<<9 & PHY_M_EC_M_DSC_MSK2)
/* 000=1x; 001=2x; 010=3x; 011=4x */
#define PHY_M_EC_MAC_S(x) ((u16)(x)<<4 & PHY_M_EC_MAC_S_MSK)
/* 01X=0; 110=2.5; 111=25 (MHz) */
/* for Yukon-2 Gigabit Ethernet PHY (88E1112 only) */
enum {
PHY_M_PC_DIS_LINK_Pa = 1<<15,/* Disable Link Pulses */
PHY_M_PC_DSC_MSK = 7<<12,/* Bit 14..12: Downshift Counter */
PHY_M_PC_DOWN_S_ENA = 1<<11,/* Downshift Enable */
};
/* !!! Errata in spec. (1 = disable) */
#define PHY_M_PC_DSC(x) (((u16)(x)<<12) & PHY_M_PC_DSC_MSK)
/* 100=5x; 101=6x; 110=7x; 111=8x */
enum {
MAC_TX_CLK_0_MHZ = 2,
MAC_TX_CLK_2_5_MHZ = 6,
MAC_TX_CLK_25_MHZ = 7,
};
/***** PHY_MARV_LED_CTRL 16 bit r/w LED Control Reg *****/
enum {
PHY_M_LEDC_DIS_LED = 1<<15, /* Disable LED */
PHY_M_LEDC_PULS_MSK = 7<<12,/* Bit 14..12: Pulse Stretch Mask */
PHY_M_LEDC_F_INT = 1<<11, /* Force Interrupt */
PHY_M_LEDC_BL_R_MSK = 7<<8,/* Bit 10.. 8: Blink Rate Mask */
PHY_M_LEDC_DP_C_LSB = 1<<7, /* Duplex Control (LSB, 88E1111 only) */
PHY_M_LEDC_TX_C_LSB = 1<<6, /* Tx Control (LSB, 88E1111 only) */
PHY_M_LEDC_LK_C_MSK = 7<<3,/* Bit 5.. 3: Link Control Mask */
/* (88E1111 only) */
};
enum {
PHY_M_LEDC_LINK_MSK = 3<<3,/* Bit 4.. 3: Link Control Mask */
/* (88E1011 only) */
PHY_M_LEDC_DP_CTRL = 1<<2, /* Duplex Control */
PHY_M_LEDC_DP_C_MSB = 1<<2, /* Duplex Control (MSB, 88E1111 only) */
PHY_M_LEDC_RX_CTRL = 1<<1, /* Rx Activity / Link */
PHY_M_LEDC_TX_CTRL = 1<<0, /* Tx Activity / Link */
PHY_M_LEDC_TX_C_MSB = 1<<0, /* Tx Control (MSB, 88E1111 only) */
};
#define PHY_M_LED_PULS_DUR(x) (((u16)(x)<<12) & PHY_M_LEDC_PULS_MSK)
/***** PHY_MARV_PHY_STAT (page 3)16 bit r/w Polarity Control Reg. *****/
enum {
PHY_M_POLC_LS1M_MSK = 0xf<<12, /* Bit 15..12: LOS,STAT1 Mix % Mask */
PHY_M_POLC_IS0M_MSK = 0xf<<8, /* Bit 11.. 8: INIT,STAT0 Mix % Mask */
PHY_M_POLC_LOS_MSK = 0x3<<6, /* Bit 7.. 6: LOS Pol. Ctrl. Mask */
PHY_M_POLC_INIT_MSK = 0x3<<4, /* Bit 5.. 4: INIT Pol. Ctrl. Mask */
PHY_M_POLC_STA1_MSK = 0x3<<2, /* Bit 3.. 2: STAT1 Pol. Ctrl. Mask */
PHY_M_POLC_STA0_MSK = 0x3, /* Bit 1.. 0: STAT0 Pol. Ctrl. Mask */
};
#define PHY_M_POLC_LS1_P_MIX(x) (((x)<<12) & PHY_M_POLC_LS1M_MSK)
#define PHY_M_POLC_IS0_P_MIX(x) (((x)<<8) & PHY_M_POLC_IS0M_MSK)
#define PHY_M_POLC_LOS_CTRL(x) (((x)<<6) & PHY_M_POLC_LOS_MSK)
#define PHY_M_POLC_INIT_CTRL(x) (((x)<<4) & PHY_M_POLC_INIT_MSK)
#define PHY_M_POLC_STA1_CTRL(x) (((x)<<2) & PHY_M_POLC_STA1_MSK)
#define PHY_M_POLC_STA0_CTRL(x) (((x)<<0) & PHY_M_POLC_STA0_MSK)
enum {
PULS_NO_STR = 0,/* no pulse stretching */
PULS_21MS = 1,/* 21 ms to 42 ms */
PULS_42MS = 2,/* 42 ms to 84 ms */
PULS_84MS = 3,/* 84 ms to 170 ms */
PULS_170MS = 4,/* 170 ms to 340 ms */
PULS_340MS = 5,/* 340 ms to 670 ms */
PULS_670MS = 6,/* 670 ms to 1.3 s */
PULS_1300MS = 7,/* 1.3 s to 2.7 s */
};
#define PHY_M_LED_BLINK_RT(x) (((u16)(x)<<8) & PHY_M_LEDC_BL_R_MSK)
enum {
BLINK_42MS = 0,/* 42 ms */
BLINK_84MS = 1,/* 84 ms */
BLINK_170MS = 2,/* 170 ms */
BLINK_340MS = 3,/* 340 ms */
BLINK_670MS = 4,/* 670 ms */
};
/**** PHY_MARV_LED_OVER 16 bit r/w LED control */
enum {
PHY_M_LED_MO_DUP = 3<<10,/* Bit 11..10: Duplex */
PHY_M_LED_MO_10 = 3<<8, /* Bit 9.. 8: Link 10 */
PHY_M_LED_MO_100 = 3<<6, /* Bit 7.. 6: Link 100 */
PHY_M_LED_MO_1000 = 3<<4, /* Bit 5.. 4: Link 1000 */
PHY_M_LED_MO_RX = 3<<2, /* Bit 3.. 2: Rx */
PHY_M_LED_MO_TX = 3<<0, /* Bit 1.. 0: Tx */
PHY_M_LED_ALL = PHY_M_LED_MO_DUP | PHY_M_LED_MO_10
| PHY_M_LED_MO_100 | PHY_M_LED_MO_1000
| PHY_M_LED_MO_RX,
};
/***** PHY_MARV_EXT_CTRL_2 16 bit r/w Ext. PHY Specific Ctrl 2 *****/
enum {
PHY_M_EC2_FI_IMPED = 1<<6, /* Fiber Input Impedance */
PHY_M_EC2_FO_IMPED = 1<<5, /* Fiber Output Impedance */
PHY_M_EC2_FO_M_CLK = 1<<4, /* Fiber Mode Clock Enable */
PHY_M_EC2_FO_BOOST = 1<<3, /* Fiber Output Boost */
PHY_M_EC2_FO_AM_MSK = 7,/* Bit 2.. 0: Fiber Output Amplitude */
};
/***** PHY_MARV_EXT_P_STAT 16 bit r/w Ext. PHY Specific Status *****/
enum {
PHY_M_FC_AUTO_SEL = 1<<15, /* Fiber/Copper Auto Sel. Dis. */
PHY_M_FC_AN_REG_ACC = 1<<14, /* Fiber/Copper AN Reg. Access */
PHY_M_FC_RESOLUTION = 1<<13, /* Fiber/Copper Resolution */
PHY_M_SER_IF_AN_BP = 1<<12, /* Ser. IF AN Bypass Enable */
PHY_M_SER_IF_BP_ST = 1<<11, /* Ser. IF AN Bypass Status */
PHY_M_IRQ_POLARITY = 1<<10, /* IRQ polarity */
PHY_M_DIS_AUT_MED = 1<<9, /* Disable Aut. Medium Reg. Selection */
/* (88E1111 only) */
PHY_M_UNDOC1 = 1<<7, /* undocumented bit !! */
PHY_M_DTE_POW_STAT = 1<<4, /* DTE Power Status (88E1111 only) */
PHY_M_MODE_MASK = 0xf, /* Bit 3.. 0: copy of HWCFG MODE[3:0] */
};
/* for 10/100 Fast Ethernet PHY (88E3082 only) */
/***** PHY_MARV_FE_LED_PAR 16 bit r/w LED Parallel Select Reg. *****/
/* Bit 15..12: reserved (used internally) */
enum {
PHY_M_FELP_LED2_MSK = 0xf<<8, /* Bit 11.. 8: LED2 Mask (LINK) */
PHY_M_FELP_LED1_MSK = 0xf<<4, /* Bit 7.. 4: LED1 Mask (ACT) */
PHY_M_FELP_LED0_MSK = 0xf, /* Bit 3.. 0: LED0 Mask (SPEED) */
};
#define PHY_M_FELP_LED2_CTRL(x) (((u16)(x)<<8) & PHY_M_FELP_LED2_MSK)
#define PHY_M_FELP_LED1_CTRL(x) (((u16)(x)<<4) & PHY_M_FELP_LED1_MSK)
#define PHY_M_FELP_LED0_CTRL(x) (((u16)(x)<<0) & PHY_M_FELP_LED0_MSK)
enum {
LED_PAR_CTRL_COLX = 0x00,
LED_PAR_CTRL_ERROR = 0x01,
LED_PAR_CTRL_DUPLEX = 0x02,
LED_PAR_CTRL_DP_COL = 0x03,
LED_PAR_CTRL_SPEED = 0x04,
LED_PAR_CTRL_LINK = 0x05,
LED_PAR_CTRL_TX = 0x06,
LED_PAR_CTRL_RX = 0x07,
LED_PAR_CTRL_ACT = 0x08,
LED_PAR_CTRL_LNK_RX = 0x09,
LED_PAR_CTRL_LNK_AC = 0x0a,
LED_PAR_CTRL_ACT_BL = 0x0b,
LED_PAR_CTRL_TX_BL = 0x0c,
LED_PAR_CTRL_RX_BL = 0x0d,
LED_PAR_CTRL_COL_BL = 0x0e,
LED_PAR_CTRL_INACT = 0x0f
};
/*****,PHY_MARV_FE_SPEC_2 16 bit r/w Specific Control Reg. 2 *****/
enum {
PHY_M_FESC_DIS_WAIT = 1<<2, /* Disable TDR Waiting Period */
PHY_M_FESC_ENA_MCLK = 1<<1, /* Enable MAC Rx Clock in sleep mode */
PHY_M_FESC_SEL_CL_A = 1<<0, /* Select Class A driver (100B-TX) */
};
/* for Yukon-2 Gigabit Ethernet PHY (88E1112 only) */
/***** PHY_MARV_PHY_CTRL (page 1) 16 bit r/w Fiber Specific Ctrl *****/
enum {
PHY_M_FIB_FORCE_LNK = 1<<10,/* Force Link Good */
PHY_M_FIB_SIGD_POL = 1<<9, /* SIGDET Polarity */
PHY_M_FIB_TX_DIS = 1<<3, /* Transmitter Disable */
};
/* for Yukon-2 Gigabit Ethernet PHY (88E1112 only) */
/***** PHY_MARV_PHY_CTRL (page 2) 16 bit r/w MAC Specific Ctrl *****/
enum {
PHY_M_MAC_MD_MSK = 7<<7, /* Bit 9.. 7: Mode Select Mask */
PHY_M_MAC_MD_AUTO = 3,/* Auto Copper/1000Base-X */
PHY_M_MAC_MD_COPPER = 5,/* Copper only */
PHY_M_MAC_MD_1000BX = 7,/* 1000Base-X only */
};
#define PHY_M_MAC_MODE_SEL(x) (((x)<<7) & PHY_M_MAC_MD_MSK)
/***** PHY_MARV_PHY_CTRL (page 3) 16 bit r/w LED Control Reg. *****/
enum {
PHY_M_LEDC_LOS_MSK = 0xf<<12,/* Bit 15..12: LOS LED Ctrl. Mask */
PHY_M_LEDC_INIT_MSK = 0xf<<8, /* Bit 11.. 8: INIT LED Ctrl. Mask */
PHY_M_LEDC_STA1_MSK = 0xf<<4,/* Bit 7.. 4: STAT1 LED Ctrl. Mask */
PHY_M_LEDC_STA0_MSK = 0xf, /* Bit 3.. 0: STAT0 LED Ctrl. Mask */
};
#define PHY_M_LEDC_LOS_CTRL(x) (((x)<<12) & PHY_M_LEDC_LOS_MSK)
#define PHY_M_LEDC_INIT_CTRL(x) (((x)<<8) & PHY_M_LEDC_INIT_MSK)
#define PHY_M_LEDC_STA1_CTRL(x) (((x)<<4) & PHY_M_LEDC_STA1_MSK)
#define PHY_M_LEDC_STA0_CTRL(x) (((x)<<0) & PHY_M_LEDC_STA0_MSK)
/* GMAC registers */
/* Port Registers */
enum {
GM_GP_STAT = 0x0000, /* 16 bit r/o General Purpose Status */
GM_GP_CTRL = 0x0004, /* 16 bit r/w General Purpose Control */
GM_TX_CTRL = 0x0008, /* 16 bit r/w Transmit Control Reg. */
GM_RX_CTRL = 0x000c, /* 16 bit r/w Receive Control Reg. */
GM_TX_FLOW_CTRL = 0x0010, /* 16 bit r/w Transmit Flow-Control */
GM_TX_PARAM = 0x0014, /* 16 bit r/w Transmit Parameter Reg. */
GM_SERIAL_MODE = 0x0018, /* 16 bit r/w Serial Mode Register */
/* Source Address Registers */
GM_SRC_ADDR_1L = 0x001c, /* 16 bit r/w Source Address 1 (low) */
GM_SRC_ADDR_1M = 0x0020, /* 16 bit r/w Source Address 1 (middle) */
GM_SRC_ADDR_1H = 0x0024, /* 16 bit r/w Source Address 1 (high) */
GM_SRC_ADDR_2L = 0x0028, /* 16 bit r/w Source Address 2 (low) */
GM_SRC_ADDR_2M = 0x002c, /* 16 bit r/w Source Address 2 (middle) */
GM_SRC_ADDR_2H = 0x0030, /* 16 bit r/w Source Address 2 (high) */
/* Multicast Address Hash Registers */
GM_MC_ADDR_H1 = 0x0034, /* 16 bit r/w Multicast Address Hash 1 */
GM_MC_ADDR_H2 = 0x0038, /* 16 bit r/w Multicast Address Hash 2 */
GM_MC_ADDR_H3 = 0x003c, /* 16 bit r/w Multicast Address Hash 3 */
GM_MC_ADDR_H4 = 0x0040, /* 16 bit r/w Multicast Address Hash 4 */
/* Interrupt Source Registers */
GM_TX_IRQ_SRC = 0x0044, /* 16 bit r/o Tx Overflow IRQ Source */
GM_RX_IRQ_SRC = 0x0048, /* 16 bit r/o Rx Overflow IRQ Source */
GM_TR_IRQ_SRC = 0x004c, /* 16 bit r/o Tx/Rx Over. IRQ Source */
/* Interrupt Mask Registers */
GM_TX_IRQ_MSK = 0x0050, /* 16 bit r/w Tx Overflow IRQ Mask */
GM_RX_IRQ_MSK = 0x0054, /* 16 bit r/w Rx Overflow IRQ Mask */
GM_TR_IRQ_MSK = 0x0058, /* 16 bit r/w Tx/Rx Over. IRQ Mask */
/* Serial Management Interface (SMI) Registers */
GM_SMI_CTRL = 0x0080, /* 16 bit r/w SMI Control Register */
GM_SMI_DATA = 0x0084, /* 16 bit r/w SMI Data Register */
GM_PHY_ADDR = 0x0088, /* 16 bit r/w GPHY Address Register */
/* MIB Counters */
GM_MIB_CNT_BASE = 0x0100, /* Base Address of MIB Counters */
GM_MIB_CNT_END = 0x025C, /* Last MIB counter */
};
/*
* MIB Counters base address definitions (low word) -
* use offset 4 for access to high word (32 bit r/o)
*/
enum {
GM_RXF_UC_OK = GM_MIB_CNT_BASE + 0, /* Unicast Frames Received OK */
GM_RXF_BC_OK = GM_MIB_CNT_BASE + 8, /* Broadcast Frames Received OK */
GM_RXF_MPAUSE = GM_MIB_CNT_BASE + 16, /* Pause MAC Ctrl Frames Received */
GM_RXF_MC_OK = GM_MIB_CNT_BASE + 24, /* Multicast Frames Received OK */
GM_RXF_FCS_ERR = GM_MIB_CNT_BASE + 32, /* Rx Frame Check Seq. Error */
GM_RXO_OK_LO = GM_MIB_CNT_BASE + 48, /* Octets Received OK Low */
GM_RXO_OK_HI = GM_MIB_CNT_BASE + 56, /* Octets Received OK High */
GM_RXO_ERR_LO = GM_MIB_CNT_BASE + 64, /* Octets Received Invalid Low */
GM_RXO_ERR_HI = GM_MIB_CNT_BASE + 72, /* Octets Received Invalid High */
GM_RXF_SHT = GM_MIB_CNT_BASE + 80, /* Frames <64 Byte Received OK */
GM_RXE_FRAG = GM_MIB_CNT_BASE + 88, /* Frames <64 Byte Received with FCS Err */
GM_RXF_64B = GM_MIB_CNT_BASE + 96, /* 64 Byte Rx Frame */
GM_RXF_127B = GM_MIB_CNT_BASE + 104,/* 65-127 Byte Rx Frame */
GM_RXF_255B = GM_MIB_CNT_BASE + 112,/* 128-255 Byte Rx Frame */
GM_RXF_511B = GM_MIB_CNT_BASE + 120,/* 256-511 Byte Rx Frame */
GM_RXF_1023B = GM_MIB_CNT_BASE + 128,/* 512-1023 Byte Rx Frame */
GM_RXF_1518B = GM_MIB_CNT_BASE + 136,/* 1024-1518 Byte Rx Frame */
GM_RXF_MAX_SZ = GM_MIB_CNT_BASE + 144,/* 1519-MaxSize Byte Rx Frame */
GM_RXF_LNG_ERR = GM_MIB_CNT_BASE + 152,/* Rx Frame too Long Error */
GM_RXF_JAB_PKT = GM_MIB_CNT_BASE + 160,/* Rx Jabber Packet Frame */
GM_RXE_FIFO_OV = GM_MIB_CNT_BASE + 176,/* Rx FIFO overflow Event */
GM_TXF_UC_OK = GM_MIB_CNT_BASE + 192,/* Unicast Frames Xmitted OK */
GM_TXF_BC_OK = GM_MIB_CNT_BASE + 200,/* Broadcast Frames Xmitted OK */
GM_TXF_MPAUSE = GM_MIB_CNT_BASE + 208,/* Pause MAC Ctrl Frames Xmitted */
GM_TXF_MC_OK = GM_MIB_CNT_BASE + 216,/* Multicast Frames Xmitted OK */
GM_TXO_OK_LO = GM_MIB_CNT_BASE + 224,/* Octets Transmitted OK Low */
GM_TXO_OK_HI = GM_MIB_CNT_BASE + 232,/* Octets Transmitted OK High */
GM_TXF_64B = GM_MIB_CNT_BASE + 240,/* 64 Byte Tx Frame */
GM_TXF_127B = GM_MIB_CNT_BASE + 248,/* 65-127 Byte Tx Frame */
GM_TXF_255B = GM_MIB_CNT_BASE + 256,/* 128-255 Byte Tx Frame */
GM_TXF_511B = GM_MIB_CNT_BASE + 264,/* 256-511 Byte Tx Frame */
GM_TXF_1023B = GM_MIB_CNT_BASE + 272,/* 512-1023 Byte Tx Frame */
GM_TXF_1518B = GM_MIB_CNT_BASE + 280,/* 1024-1518 Byte Tx Frame */
GM_TXF_MAX_SZ = GM_MIB_CNT_BASE + 288,/* 1519-MaxSize Byte Tx Frame */
GM_TXF_COL = GM_MIB_CNT_BASE + 304,/* Tx Collision */
GM_TXF_LAT_COL = GM_MIB_CNT_BASE + 312,/* Tx Late Collision */
GM_TXF_ABO_COL = GM_MIB_CNT_BASE + 320,/* Tx aborted due to Exces. Col. */
GM_TXF_MUL_COL = GM_MIB_CNT_BASE + 328,/* Tx Multiple Collision */
GM_TXF_SNG_COL = GM_MIB_CNT_BASE + 336,/* Tx Single Collision */
GM_TXE_FIFO_UR = GM_MIB_CNT_BASE + 344,/* Tx FIFO Underrun Event */
};
/* GMAC Bit Definitions */
/* GM_GP_STAT 16 bit r/o General Purpose Status Register */
enum {
GM_GPSR_SPEED = 1<<15, /* Bit 15: Port Speed (1 = 100 Mbps) */
GM_GPSR_DUPLEX = 1<<14, /* Bit 14: Duplex Mode (1 = Full) */
GM_GPSR_FC_TX_DIS = 1<<13, /* Bit 13: Tx Flow-Control Mode Disabled */
GM_GPSR_LINK_UP = 1<<12, /* Bit 12: Link Up Status */
GM_GPSR_PAUSE = 1<<11, /* Bit 11: Pause State */
GM_GPSR_TX_ACTIVE = 1<<10, /* Bit 10: Tx in Progress */
GM_GPSR_EXC_COL = 1<<9, /* Bit 9: Excessive Collisions Occured */
GM_GPSR_LAT_COL = 1<<8, /* Bit 8: Late Collisions Occured */
GM_GPSR_PHY_ST_CH = 1<<5, /* Bit 5: PHY Status Change */
GM_GPSR_GIG_SPEED = 1<<4, /* Bit 4: Gigabit Speed (1 = 1000 Mbps) */
GM_GPSR_PART_MODE = 1<<3, /* Bit 3: Partition mode */
GM_GPSR_FC_RX_DIS = 1<<2, /* Bit 2: Rx Flow-Control Mode Disabled */
GM_GPSR_PROM_EN = 1<<1, /* Bit 1: Promiscuous Mode Enabled */
};
/* GM_GP_CTRL 16 bit r/w General Purpose Control Register */
enum {
GM_GPCR_PROM_ENA = 1<<14, /* Bit 14: Enable Promiscuous Mode */
GM_GPCR_FC_TX_DIS = 1<<13, /* Bit 13: Disable Tx Flow-Control Mode */
GM_GPCR_TX_ENA = 1<<12, /* Bit 12: Enable Transmit */
GM_GPCR_RX_ENA = 1<<11, /* Bit 11: Enable Receive */
GM_GPCR_BURST_ENA = 1<<10, /* Bit 10: Enable Burst Mode */
GM_GPCR_LOOP_ENA = 1<<9, /* Bit 9: Enable MAC Loopback Mode */
GM_GPCR_PART_ENA = 1<<8, /* Bit 8: Enable Partition Mode */
GM_GPCR_GIGS_ENA = 1<<7, /* Bit 7: Gigabit Speed (1000 Mbps) */
GM_GPCR_FL_PASS = 1<<6, /* Bit 6: Force Link Pass */
GM_GPCR_DUP_FULL = 1<<5, /* Bit 5: Full Duplex Mode */
GM_GPCR_FC_RX_DIS = 1<<4, /* Bit 4: Disable Rx Flow-Control Mode */
GM_GPCR_SPEED_100 = 1<<3, /* Bit 3: Port Speed 100 Mbps */
GM_GPCR_AU_DUP_DIS = 1<<2, /* Bit 2: Disable Auto-Update Duplex */
GM_GPCR_AU_FCT_DIS = 1<<1, /* Bit 1: Disable Auto-Update Flow-C. */
GM_GPCR_AU_SPD_DIS = 1<<0, /* Bit 0: Disable Auto-Update Speed */
};
#define GM_GPCR_SPEED_1000 (GM_GPCR_GIGS_ENA | GM_GPCR_SPEED_100)
#define GM_GPCR_AU_ALL_DIS (GM_GPCR_AU_DUP_DIS | GM_GPCR_AU_FCT_DIS|GM_GPCR_AU_SPD_DIS)
/* GM_TX_CTRL 16 bit r/w Transmit Control Register */
enum {
GM_TXCR_FORCE_JAM = 1<<15, /* Bit 15: Force Jam / Flow-Control */
GM_TXCR_CRC_DIS = 1<<14, /* Bit 14: Disable insertion of CRC */
GM_TXCR_PAD_DIS = 1<<13, /* Bit 13: Disable padding of packets */
GM_TXCR_COL_THR_MSK = 7<<10, /* Bit 12..10: Collision Threshold */
};
#define TX_COL_THR(x) (((x)<<10) & GM_TXCR_COL_THR_MSK)
#define TX_COL_DEF 0x04
/* GM_RX_CTRL 16 bit r/w Receive Control Register */
enum {
GM_RXCR_UCF_ENA = 1<<15, /* Bit 15: Enable Unicast filtering */
GM_RXCR_MCF_ENA = 1<<14, /* Bit 14: Enable Multicast filtering */
GM_RXCR_CRC_DIS = 1<<13, /* Bit 13: Remove 4-byte CRC */
GM_RXCR_PASS_FC = 1<<12, /* Bit 12: Pass FC packets to FIFO */
};
/* GM_TX_PARAM 16 bit r/w Transmit Parameter Register */
enum {
GM_TXPA_JAMLEN_MSK = 0x03<<14, /* Bit 15..14: Jam Length */
GM_TXPA_JAMIPG_MSK = 0x1f<<9, /* Bit 13..9: Jam IPG */
GM_TXPA_JAMDAT_MSK = 0x1f<<4, /* Bit 8..4: IPG Jam to Data */
GM_TXPA_BO_LIM_MSK = 0x0f, /* Bit 3.. 0: Backoff Limit Mask */
TX_JAM_LEN_DEF = 0x03,
TX_JAM_IPG_DEF = 0x0b,
TX_IPG_JAM_DEF = 0x1c,
TX_BOF_LIM_DEF = 0x04,
};
#define TX_JAM_LEN_VAL(x) (((x)<<14) & GM_TXPA_JAMLEN_MSK)
#define TX_JAM_IPG_VAL(x) (((x)<<9) & GM_TXPA_JAMIPG_MSK)
#define TX_IPG_JAM_DATA(x) (((x)<<4) & GM_TXPA_JAMDAT_MSK)
#define TX_BACK_OFF_LIM(x) ((x) & GM_TXPA_BO_LIM_MSK)
/* GM_SERIAL_MODE 16 bit r/w Serial Mode Register */
enum {
GM_SMOD_DATABL_MSK = 0x1f<<11, /* Bit 15..11: Data Blinder (r/o) */
GM_SMOD_LIMIT_4 = 1<<10, /* Bit 10: 4 consecutive Tx trials */
GM_SMOD_VLAN_ENA = 1<<9, /* Bit 9: Enable VLAN (Max. Frame Len) */
GM_SMOD_JUMBO_ENA = 1<<8, /* Bit 8: Enable Jumbo (Max. Frame Len) */
GM_SMOD_IPG_MSK = 0x1f /* Bit 4..0: Inter-Packet Gap (IPG) */
};
#define DATA_BLIND_VAL(x) (((x)<<11) & GM_SMOD_DATABL_MSK)
#define DATA_BLIND_DEF 0x04
#define IPG_DATA_VAL(x) (x & GM_SMOD_IPG_MSK)
#define IPG_DATA_DEF 0x1e
/* GM_SMI_CTRL 16 bit r/w SMI Control Register */
enum {
GM_SMI_CT_PHY_A_MSK = 0x1f<<11,/* Bit 15..11: PHY Device Address */
GM_SMI_CT_REG_A_MSK = 0x1f<<6,/* Bit 10.. 6: PHY Register Address */
GM_SMI_CT_OP_RD = 1<<5, /* Bit 5: OpCode Read (0=Write)*/
GM_SMI_CT_RD_VAL = 1<<4, /* Bit 4: Read Valid (Read completed) */
GM_SMI_CT_BUSY = 1<<3, /* Bit 3: Busy (Operation in progress) */
};
#define GM_SMI_CT_PHY_AD(x) (((u16)(x)<<11) & GM_SMI_CT_PHY_A_MSK)
#define GM_SMI_CT_REG_AD(x) (((u16)(x)<<6) & GM_SMI_CT_REG_A_MSK)
/* GM_PHY_ADDR 16 bit r/w GPHY Address Register */
enum {
GM_PAR_MIB_CLR = 1<<5, /* Bit 5: Set MIB Clear Counter Mode */
GM_PAR_MIB_TST = 1<<4, /* Bit 4: MIB Load Counter (Test Mode) */
};
/* Receive Frame Status Encoding */
enum {
GMR_FS_LEN = 0xffff<<16, /* Bit 31..16: Rx Frame Length */
GMR_FS_VLAN = 1<<13, /* VLAN Packet */
GMR_FS_JABBER = 1<<12, /* Jabber Packet */
GMR_FS_UN_SIZE = 1<<11, /* Undersize Packet */
GMR_FS_MC = 1<<10, /* Multicast Packet */
GMR_FS_BC = 1<<9, /* Broadcast Packet */
GMR_FS_RX_OK = 1<<8, /* Receive OK (Good Packet) */
GMR_FS_GOOD_FC = 1<<7, /* Good Flow-Control Packet */
GMR_FS_BAD_FC = 1<<6, /* Bad Flow-Control Packet */
GMR_FS_MII_ERR = 1<<5, /* MII Error */
GMR_FS_LONG_ERR = 1<<4, /* Too Long Packet */
GMR_FS_FRAGMENT = 1<<3, /* Fragment */
GMR_FS_CRC_ERR = 1<<1, /* CRC Error */
GMR_FS_RX_FF_OV = 1<<0, /* Rx FIFO Overflow */
GMR_FS_ANY_ERR = GMR_FS_RX_FF_OV | GMR_FS_CRC_ERR |
GMR_FS_FRAGMENT | GMR_FS_LONG_ERR |
GMR_FS_MII_ERR | GMR_FS_BAD_FC |
GMR_FS_UN_SIZE | GMR_FS_JABBER,
};
/* RX_GMF_CTRL_T 32 bit Rx GMAC FIFO Control/Test */
enum {
RX_TRUNC_ON = 1<<27, /* enable packet truncation */
RX_TRUNC_OFF = 1<<26, /* disable packet truncation */
RX_VLAN_STRIP_ON = 1<<25, /* enable VLAN stripping */
RX_VLAN_STRIP_OFF = 1<<24, /* disable VLAN stripping */
GMF_WP_TST_ON = 1<<14, /* Write Pointer Test On */
GMF_WP_TST_OFF = 1<<13, /* Write Pointer Test Off */
GMF_WP_STEP = 1<<12, /* Write Pointer Step/Increment */
GMF_RP_TST_ON = 1<<10, /* Read Pointer Test On */
GMF_RP_TST_OFF = 1<<9, /* Read Pointer Test Off */
GMF_RP_STEP = 1<<8, /* Read Pointer Step/Increment */
GMF_RX_F_FL_ON = 1<<7, /* Rx FIFO Flush Mode On */
GMF_RX_F_FL_OFF = 1<<6, /* Rx FIFO Flush Mode Off */
GMF_CLI_RX_FO = 1<<5, /* Clear IRQ Rx FIFO Overrun */
GMF_CLI_RX_C = 1<<4, /* Clear IRQ Rx Frame Complete */
GMF_OPER_ON = 1<<3, /* Operational Mode On */
GMF_OPER_OFF = 1<<2, /* Operational Mode Off */
GMF_RST_CLR = 1<<1, /* Clear GMAC FIFO Reset */
GMF_RST_SET = 1<<0, /* Set GMAC FIFO Reset */
RX_GMF_FL_THR_DEF = 0xa, /* flush threshold (default) */
GMF_RX_CTRL_DEF = GMF_OPER_ON | GMF_RX_F_FL_ON,
};
/* TX_GMF_CTRL_T 32 bit Tx GMAC FIFO Control/Test */
enum {
TX_STFW_DIS = 1<<31,/* Disable Store & Forward (Yukon-EC Ultra) */
TX_STFW_ENA = 1<<30,/* Enable Store & Forward (Yukon-EC Ultra) */
TX_VLAN_TAG_ON = 1<<25,/* enable VLAN tagging */
TX_VLAN_TAG_OFF = 1<<24,/* disable VLAN tagging */
TX_JUMBO_ENA = 1<<23,/* PCI Jumbo Mode enable (Yukon-EC Ultra) */
TX_JUMBO_DIS = 1<<22,/* PCI Jumbo Mode enable (Yukon-EC Ultra) */
GMF_WSP_TST_ON = 1<<18,/* Write Shadow Pointer Test On */
GMF_WSP_TST_OFF = 1<<17,/* Write Shadow Pointer Test Off */
GMF_WSP_STEP = 1<<16,/* Write Shadow Pointer Step/Increment */
GMF_CLI_TX_FU = 1<<6, /* Clear IRQ Tx FIFO Underrun */
GMF_CLI_TX_FC = 1<<5, /* Clear IRQ Tx Frame Complete */
GMF_CLI_TX_PE = 1<<4, /* Clear IRQ Tx Parity Error */
};
/* GMAC_TI_ST_CTRL 8 bit Time Stamp Timer Ctrl Reg (YUKON only) */
enum {
GMT_ST_START = 1<<2, /* Start Time Stamp Timer */
GMT_ST_STOP = 1<<1, /* Stop Time Stamp Timer */
GMT_ST_CLR_IRQ = 1<<0, /* Clear Time Stamp Timer IRQ */
};
/* B28_Y2_ASF_STAT_CMD 32 bit ASF Status and Command Reg */
enum {
Y2_ASF_OS_PRES = 1<<4, /* ASF operation system present */
Y2_ASF_RESET = 1<<3, /* ASF system in reset state */
Y2_ASF_RUNNING = 1<<2, /* ASF system operational */
Y2_ASF_CLR_HSTI = 1<<1, /* Clear ASF IRQ */
Y2_ASF_IRQ = 1<<0, /* Issue an IRQ to ASF system */
Y2_ASF_UC_STATE = 3<<2, /* ASF uC State */
Y2_ASF_CLK_HALT = 0, /* ASF system clock stopped */
};
/* B28_Y2_ASF_HOST_COM 32 bit ASF Host Communication Reg */
enum {
Y2_ASF_CLR_ASFI = 1<<1, /* Clear host IRQ */
Y2_ASF_HOST_IRQ = 1<<0, /* Issue an IRQ to HOST system */
};
/* HCU_CCSR CPU Control and Status Register */
enum {
HCU_CCSR_SMBALERT_MONITOR= 1<<27, /* SMBALERT pin monitor */
HCU_CCSR_CPU_SLEEP = 1<<26, /* CPU sleep status */
/* Clock Stretching Timeout */
HCU_CCSR_CS_TO = 1<<25,
HCU_CCSR_WDOG = 1<<24, /* Watchdog Reset */
HCU_CCSR_CLR_IRQ_HOST = 1<<17, /* Clear IRQ_HOST */
HCU_CCSR_SET_IRQ_HCU = 1<<16, /* Set IRQ_HCU */
HCU_CCSR_AHB_RST = 1<<9, /* Reset AHB bridge */
HCU_CCSR_CPU_RST_MODE = 1<<8, /* CPU Reset Mode */
HCU_CCSR_SET_SYNC_CPU = 1<<5,
HCU_CCSR_CPU_CLK_DIVIDE_MSK = 3<<3,/* CPU Clock Divide */
HCU_CCSR_CPU_CLK_DIVIDE_BASE= 1<<3,
HCU_CCSR_OS_PRSNT = 1<<2, /* ASF OS Present */
/* Microcontroller State */
HCU_CCSR_UC_STATE_MSK = 3,
HCU_CCSR_UC_STATE_BASE = 1<<0,
HCU_CCSR_ASF_RESET = 0,
HCU_CCSR_ASF_HALTED = 1<<1,
HCU_CCSR_ASF_RUNNING = 1<<0,
};
/* HCU_HCSR Host Control and Status Register */
enum {
HCU_HCSR_SET_IRQ_CPU = 1<<16, /* Set IRQ_CPU */
HCU_HCSR_CLR_IRQ_HCU = 1<<1, /* Clear IRQ_HCU */
HCU_HCSR_SET_IRQ_HOST = 1<<0, /* Set IRQ_HOST */
};
/* STAT_CTRL 32 bit Status BMU control register (Yukon-2 only) */
enum {
SC_STAT_CLR_IRQ = 1<<4, /* Status Burst IRQ clear */
SC_STAT_OP_ON = 1<<3, /* Operational Mode On */
SC_STAT_OP_OFF = 1<<2, /* Operational Mode Off */
SC_STAT_RST_CLR = 1<<1, /* Clear Status Unit Reset (Enable) */
SC_STAT_RST_SET = 1<<0, /* Set Status Unit Reset */
};
/* GMAC_CTRL 32 bit GMAC Control Reg (YUKON only) */
enum {
GMC_H_BURST_ON = 1<<7, /* Half Duplex Burst Mode On */
GMC_H_BURST_OFF = 1<<6, /* Half Duplex Burst Mode Off */
GMC_F_LOOPB_ON = 1<<5, /* FIFO Loopback On */
GMC_F_LOOPB_OFF = 1<<4, /* FIFO Loopback Off */
GMC_PAUSE_ON = 1<<3, /* Pause On */
GMC_PAUSE_OFF = 1<<2, /* Pause Off */
GMC_RST_CLR = 1<<1, /* Clear GMAC Reset */
GMC_RST_SET = 1<<0, /* Set GMAC Reset */
};
/* GPHY_CTRL 32 bit GPHY Control Reg (YUKON only) */
enum {
GPC_RST_CLR = 1<<1, /* Clear GPHY Reset */
GPC_RST_SET = 1<<0, /* Set GPHY Reset */
};
/* GMAC_IRQ_SRC 8 bit GMAC Interrupt Source Reg (YUKON only) */
/* GMAC_IRQ_MSK 8 bit GMAC Interrupt Mask Reg (YUKON only) */
enum {
GM_IS_TX_CO_OV = 1<<5, /* Transmit Counter Overflow IRQ */
GM_IS_RX_CO_OV = 1<<4, /* Receive Counter Overflow IRQ */
GM_IS_TX_FF_UR = 1<<3, /* Transmit FIFO Underrun */
GM_IS_TX_COMPL = 1<<2, /* Frame Transmission Complete */
GM_IS_RX_FF_OR = 1<<1, /* Receive FIFO Overrun */
GM_IS_RX_COMPL = 1<<0, /* Frame Reception Complete */
#define GMAC_DEF_MSK GM_IS_TX_FF_UR
};
/* GMAC_LINK_CTRL 16 bit GMAC Link Control Reg (YUKON only) */
enum { /* Bits 15.. 2: reserved */
GMLC_RST_CLR = 1<<1, /* Clear GMAC Link Reset */
GMLC_RST_SET = 1<<0, /* Set GMAC Link Reset */
};
/* WOL_CTRL_STAT 16 bit WOL Control/Status Reg */
enum {
WOL_CTL_LINK_CHG_OCC = 1<<15,
WOL_CTL_MAGIC_PKT_OCC = 1<<14,
WOL_CTL_PATTERN_OCC = 1<<13,
WOL_CTL_CLEAR_RESULT = 1<<12,
WOL_CTL_ENA_PME_ON_LINK_CHG = 1<<11,
WOL_CTL_DIS_PME_ON_LINK_CHG = 1<<10,
WOL_CTL_ENA_PME_ON_MAGIC_PKT = 1<<9,
WOL_CTL_DIS_PME_ON_MAGIC_PKT = 1<<8,
WOL_CTL_ENA_PME_ON_PATTERN = 1<<7,
WOL_CTL_DIS_PME_ON_PATTERN = 1<<6,
WOL_CTL_ENA_LINK_CHG_UNIT = 1<<5,
WOL_CTL_DIS_LINK_CHG_UNIT = 1<<4,
WOL_CTL_ENA_MAGIC_PKT_UNIT = 1<<3,
WOL_CTL_DIS_MAGIC_PKT_UNIT = 1<<2,
WOL_CTL_ENA_PATTERN_UNIT = 1<<1,
WOL_CTL_DIS_PATTERN_UNIT = 1<<0,
};
/* Control flags */
enum {
UDPTCP = 1<<0,
CALSUM = 1<<1,
WR_SUM = 1<<2,
INIT_SUM= 1<<3,
LOCK_SUM= 1<<4,
INS_VLAN= 1<<5,
EOP = 1<<7,
};
enum {
HW_OWNER = 1<<7,
OP_TCPWRITE = 0x11,
OP_TCPSTART = 0x12,
OP_TCPINIT = 0x14,
OP_TCPLCK = 0x18,
OP_TCPCHKSUM = OP_TCPSTART,
OP_TCPIS = OP_TCPINIT | OP_TCPSTART,
OP_TCPLW = OP_TCPLCK | OP_TCPWRITE,
OP_TCPLSW = OP_TCPLCK | OP_TCPSTART | OP_TCPWRITE,
OP_TCPLISW = OP_TCPLCK | OP_TCPINIT | OP_TCPSTART | OP_TCPWRITE,
OP_ADDR64 = 0x21,
OP_VLAN = 0x22,
OP_ADDR64VLAN = OP_ADDR64 | OP_VLAN,
OP_LRGLEN = 0x24,
OP_LRGLENVLAN = OP_LRGLEN | OP_VLAN,
OP_BUFFER = 0x40,
OP_PACKET = 0x41,
OP_LARGESEND = 0x43,
/* YUKON-2 STATUS opcodes defines */
OP_RXSTAT = 0x60,
OP_RXTIMESTAMP = 0x61,
OP_RXVLAN = 0x62,
OP_RXCHKS = 0x64,
OP_RXCHKSVLAN = OP_RXCHKS | OP_RXVLAN,
OP_RXTIMEVLAN = OP_RXTIMESTAMP | OP_RXVLAN,
OP_RSS_HASH = 0x65,
OP_TXINDEXLE = 0x68,
};
/* Yukon 2 hardware interface */
struct sky2_tx_le {
__le32 addr;
__le16 length; /* also vlan tag or checksum start */
u8 ctrl;
u8 opcode;
} __attribute((packed));
struct sky2_rx_le {
__le32 addr;
__le16 length;
u8 ctrl;
u8 opcode;
} __attribute((packed));
struct sky2_status_le {
__le32 status; /* also checksum */
__le16 length; /* also vlan tag */
u8 link;
u8 opcode;
} __attribute((packed));
struct tx_ring_info {
struct sk_buff *skb;
DECLARE_PCI_UNMAP_ADDR(mapaddr);
DECLARE_PCI_UNMAP_ADDR(maplen);
};
struct rx_ring_info {
struct sk_buff *skb;
dma_addr_t data_addr;
DECLARE_PCI_UNMAP_ADDR(data_size);
dma_addr_t frag_addr[ETH_JUMBO_MTU >> PAGE_SHIFT];
};
enum flow_control {
FC_NONE = 0,
FC_TX = 1,
FC_RX = 2,
FC_BOTH = 3,
};
struct sky2_port {
struct sky2_hw *hw;
struct net_device *netdev;
unsigned port;
u32 msg_enable;
spinlock_t phy_lock;
struct tx_ring_info *tx_ring;
struct sky2_tx_le *tx_le;
u16 tx_cons; /* next le to check */
u16 tx_prod; /* next le to use */
u32 tx_addr64;
u16 tx_pending;
u16 tx_last_mss;
u32 tx_tcpsum;
struct rx_ring_info *rx_ring ____cacheline_aligned_in_smp;
struct sky2_rx_le *rx_le;
u32 rx_addr64;
u16 rx_next; /* next re to check */
u16 rx_put; /* next le index to use */
u16 rx_pending;
u16 rx_data_size;
u16 rx_nfrags;
#ifdef SKY2_VLAN_TAG_USED
u16 rx_tag;
struct vlan_group *vlgrp;
#endif
dma_addr_t rx_le_map;
dma_addr_t tx_le_map;
u16 advertising; /* ADVERTISED_ bits */
u16 speed; /* SPEED_1000, SPEED_100, ... */
u8 autoneg; /* AUTONEG_ENABLE, AUTONEG_DISABLE */
u8 duplex; /* DUPLEX_HALF, DUPLEX_FULL */
u8 rx_csum;
u8 wol;
enum flow_control flow_mode;
enum flow_control flow_status;
struct net_device_stats net_stats;
};
struct sky2_hw {
void __iomem *regs;
struct pci_dev *pdev;
struct net_device *dev[2];
u8 chip_id;
u8 chip_rev;
u8 pmd_type;
u8 ports;
struct sky2_status_le *st_le;
u32 st_idx;
dma_addr_t st_dma;
struct timer_list watchdog_timer;
struct work_struct restart_work;
int msi;
wait_queue_head_t msi_wait;
};
static inline int sky2_is_copper(const struct sky2_hw *hw)
{
return !(hw->pmd_type == 'L' || hw->pmd_type == 'S' || hw->pmd_type == 'P');
}
/* Register accessor for memory mapped device */
static inline u32 sky2_read32(const struct sky2_hw *hw, unsigned reg)
{
return readl(hw->regs + reg);
}
static inline u16 sky2_read16(const struct sky2_hw *hw, unsigned reg)
{
return readw(hw->regs + reg);
}
static inline u8 sky2_read8(const struct sky2_hw *hw, unsigned reg)
{
return readb(hw->regs + reg);
}
static inline void sky2_write32(const struct sky2_hw *hw, unsigned reg, u32 val)
{
writel(val, hw->regs + reg);
}
static inline void sky2_write16(const struct sky2_hw *hw, unsigned reg, u16 val)
{
writew(val, hw->regs + reg);
}
static inline void sky2_write8(const struct sky2_hw *hw, unsigned reg, u8 val)
{
writeb(val, hw->regs + reg);
}
/* Yukon PHY related registers */
#define SK_GMAC_REG(port,reg) \
(BASE_GMAC_1 + (port) * (BASE_GMAC_2-BASE_GMAC_1) + (reg))
#define GM_PHY_RETRIES 100
static inline u16 gma_read16(const struct sky2_hw *hw, unsigned port, unsigned reg)
{
return sky2_read16(hw, SK_GMAC_REG(port,reg));
}
static inline u32 gma_read32(struct sky2_hw *hw, unsigned port, unsigned reg)
{
unsigned base = SK_GMAC_REG(port, reg);
return (u32) sky2_read16(hw, base)
| (u32) sky2_read16(hw, base+4) << 16;
}
static inline void gma_write16(const struct sky2_hw *hw, unsigned port, int r, u16 v)
{
sky2_write16(hw, SK_GMAC_REG(port,r), v);
}
static inline void gma_set_addr(struct sky2_hw *hw, unsigned port, unsigned reg,
const u8 *addr)
{
gma_write16(hw, port, reg, (u16) addr[0] | ((u16) addr[1] << 8));
gma_write16(hw, port, reg+4,(u16) addr[2] | ((u16) addr[3] << 8));
gma_write16(hw, port, reg+8,(u16) addr[4] | ((u16) addr[5] << 8));
}
/* PCI config space access */
static inline u32 sky2_pci_read32(const struct sky2_hw *hw, unsigned reg)
{
return sky2_read32(hw, Y2_CFG_SPC + reg);
}
static inline u16 sky2_pci_read16(const struct sky2_hw *hw, unsigned reg)
{
return sky2_read16(hw, Y2_CFG_SPC + reg);
}
static inline void sky2_pci_write32(struct sky2_hw *hw, unsigned reg, u32 val)
{
sky2_write32(hw, Y2_CFG_SPC + reg, val);
}
static inline void sky2_pci_write16(struct sky2_hw *hw, unsigned reg, u16 val)
{
sky2_write16(hw, Y2_CFG_SPC + reg, val);
}
#endif
| ghmajx/asuswrt-merlin | release/src-rt/linux/linux-2.6/drivers/net/sky2.h | C | gpl-2.0 | 75,971 |
;; GCC machine description for MMIX
;; Copyright (C) 2000-2014 Free Software Foundation, Inc.
;; Contributed by Hans-Peter Nilsson ([email protected])
;; This file is part of GCC.
;; GCC is free software; you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation; either version 3, or (at your option)
;; any later version.
;; GCC 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 GCC; see the file COPYING3. If not see
;; <http://www.gnu.org/licenses/>.
;; The original PO technology requires these to be ordered by speed,
;; so that assigner will pick the fastest.
;; See file "rtl.def" for documentation on define_insn, match_*, et al.
;; Uses of UNSPEC in this file:
;; UNSPEC_VOLATILE:
;;
;; 0 sync_icache (sync icache before trampoline jump)
;; 1 nonlocal_goto_receiver
;;
;; The order of insns is as in Node: Standard Names, with smaller modes
;; before bigger modes.
(define_constants
[(MMIX_rJ_REGNUM 259)
(MMIX_rR_REGNUM 260)
(MMIX_fp_rO_OFFSET -24)]
)
;; Operand and operator predicates.
(include "predicates.md")
(include "constraints.md")
;; FIXME: Can we remove the reg-to-reg for smaller modes? Shouldn't they
;; be synthesized ok?
(define_insn "movqi"
[(set (match_operand:QI 0 "nonimmediate_operand" "=r,r ,r,x ,r,r,m,??r")
(match_operand:QI 1 "general_operand" "r,LS,K,rI,x,m,r,n"))]
""
"@
SET %0,%1
%s1 %0,%v1
NEGU %0,0,%n1
PUT %0,%1
GET %0,%1
LDB%U0 %0,%1
STBU %1,%0
%r0%I1")
(define_insn "movhi"
[(set (match_operand:HI 0 "nonimmediate_operand" "=r,r ,r ,x,r,r,m,??r")
(match_operand:HI 1 "general_operand" "r,LS,K,r,x,m,r,n"))]
""
"@
SET %0,%1
%s1 %0,%v1
NEGU %0,0,%n1
PUT %0,%1
GET %0,%1
LDW%U0 %0,%1
STWU %1,%0
%r0%I1")
;; gcc.c-torture/compile/920428-2.c fails if there's no "n".
(define_insn "movsi"
[(set (match_operand:SI 0 "nonimmediate_operand" "=r,r ,r,x,r,r,m,??r")
(match_operand:SI 1 "general_operand" "r,LS,K,r,x,m,r,n"))]
""
"@
SET %0,%1
%s1 %0,%v1
NEGU %0,0,%n1
PUT %0,%1
GET %0,%1
LDT%U0 %0,%1
STTU %1,%0
%r0%I1")
;; We assume all "s" are addresses. Does that hold?
(define_insn "movdi"
[(set (match_operand:DI 0 "nonimmediate_operand" "=r,r ,r,x,r,m,r,m,r,r,??r")
(match_operand:DI 1 "general_operand" "r,LS,K,r,x,I,m,r,R,s,n"))]
""
"@
SET %0,%1
%s1 %0,%v1
NEGU %0,0,%n1
PUT %0,%1
GET %0,%1
STCO %1,%0
LDO %0,%1
STOU %1,%0
GETA %0,%1
LDA %0,%1
%r0%I1")
;; Note that we move around the float as a collection of bits; no
;; conversion to double.
(define_insn "movsf"
[(set (match_operand:SF 0 "nonimmediate_operand" "=r,r,x,r,r,m,??r")
(match_operand:SF 1 "general_operand" "r,G,r,x,m,r,F"))]
""
"@
SET %0,%1
SETL %0,0
PUT %0,%1
GET %0,%1
LDT %0,%1
STTU %1,%0
%r0%I1")
(define_insn "movdf"
[(set (match_operand:DF 0 "nonimmediate_operand" "=r,r,x,r,r,m,??r")
(match_operand:DF 1 "general_operand" "r,G,r,x,m,r,F"))]
""
"@
SET %0,%1
SETL %0,0
PUT %0,%1
GET %0,%1
LDO %0,%1
STOU %1,%0
%r0%I1")
;; We need to be able to move around the values used as condition codes.
;; First spotted as reported in
;; <URL:http://gcc.gnu.org/ml/gcc-bugs/2003-03/msg00008.html> due to
;; changes in loop optimization. The file machmode.def says they're of
;; size 4 QI. Valid bit-patterns correspond to integers -1, 0 and 1, so
;; we treat them as signed entities; see mmix-modes.def. The following
;; expanders should cover all MODE_CC modes, and expand for this pattern.
(define_insn "*movcc_expanded"
[(set (match_operand 0 "nonimmediate_operand" "=r,x,r,r,m")
(match_operand 1 "nonimmediate_operand" "r,r,x,m,r"))]
"GET_MODE_CLASS (GET_MODE (operands[0])) == MODE_CC
&& GET_MODE_CLASS (GET_MODE (operands[1])) == MODE_CC"
"@
SET %0,%1
PUT %0,%1
GET %0,%1
LDT %0,%1
STT %1,%0")
(define_expand "movcc"
[(set (match_operand:CC 0 "nonimmediate_operand" "")
(match_operand:CC 1 "nonimmediate_operand" ""))]
""
"")
(define_expand "movcc_uns"
[(set (match_operand:CC_UNS 0 "nonimmediate_operand" "")
(match_operand:CC_UNS 1 "nonimmediate_operand" ""))]
""
"")
(define_expand "movcc_fp"
[(set (match_operand:CC_FP 0 "nonimmediate_operand" "")
(match_operand:CC_FP 1 "nonimmediate_operand" ""))]
""
"")
(define_expand "movcc_fpeq"
[(set (match_operand:CC_FPEQ 0 "nonimmediate_operand" "")
(match_operand:CC_FPEQ 1 "nonimmediate_operand" ""))]
""
"")
(define_expand "movcc_fun"
[(set (match_operand:CC_FUN 0 "nonimmediate_operand" "")
(match_operand:CC_FUN 1 "nonimmediate_operand" ""))]
""
"")
(define_insn "adddi3"
[(set (match_operand:DI 0 "register_operand" "=r,r,r")
(plus:DI
(match_operand:DI 1 "register_operand" "%r,r,0")
(match_operand:DI 2 "mmix_reg_or_constant_operand" "rI,K,LS")))]
""
"@
ADDU %0,%1,%2
SUBU %0,%1,%n2
%i2 %0,%v2")
(define_insn "adddf3"
[(set (match_operand:DF 0 "register_operand" "=r")
(plus:DF (match_operand:DF 1 "register_operand" "%r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FADD %0,%1,%2")
;; Insn canonicalization *should* have removed the need for an integer
;; in operand 2.
(define_insn "subdi3"
[(set (match_operand:DI 0 "register_operand" "=r,r")
(minus:DI (match_operand:DI 1 "mmix_reg_or_8bit_operand" "r,I")
(match_operand:DI 2 "register_operand" "r,r")))]
""
"@
SUBU %0,%1,%2
NEGU %0,%1,%2")
(define_insn "subdf3"
[(set (match_operand:DF 0 "register_operand" "=r")
(minus:DF (match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FSUB %0,%1,%2")
;; FIXME: Should we define_expand and match 2, 4, 8 (etc) with shift (or
;; %{something}2ADDU %0,%1,0)? Hopefully GCC should still handle it, so
;; we don't have to taint the machine description. If results are bad
;; enough, we may have to do it anyway.
(define_insn "muldi3"
[(set (match_operand:DI 0 "register_operand" "=r,r")
(mult:DI (match_operand:DI 1 "register_operand" "%r,r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "O,rI")))
(clobber (match_scratch:DI 3 "=X,z"))]
""
"@
%m2ADDU %0,%1,%1
MULU %0,%1,%2")
(define_insn "muldf3"
[(set (match_operand:DF 0 "register_operand" "=r")
(mult:DF (match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FMUL %0,%1,%2")
(define_insn "divdf3"
[(set (match_operand:DF 0 "register_operand" "=r")
(div:DF (match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FDIV %0,%1,%2")
;; FIXME: Is "frem" doing the right operation for moddf3?
(define_insn "moddf3"
[(set (match_operand:DF 0 "register_operand" "=r")
(mod:DF (match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FREM %0,%1,%2")
;; FIXME: Should we define_expand for smin, smax, umin, umax using a
;; nifty conditional sequence?
;; FIXME: The cuter andn combinations don't get here, presumably because
;; they ended up in the constant pool. Check: still?
(define_insn "anddi3"
[(set (match_operand:DI 0 "register_operand" "=r,r")
(and:DI
(match_operand:DI 1 "register_operand" "%r,0")
(match_operand:DI 2 "mmix_reg_or_constant_operand" "rI,NT")))]
""
"@
AND %0,%1,%2
%A2 %0,%V2")
(define_insn "iordi3"
[(set (match_operand:DI 0 "register_operand" "=r,r")
(ior:DI (match_operand:DI 1 "register_operand" "%r,0")
(match_operand:DI 2 "mmix_reg_or_constant_operand" "rI,LS")))]
""
"@
OR %0,%1,%2
%o2 %0,%v2")
(define_insn "xordi3"
[(set (match_operand:DI 0 "register_operand" "=r")
(xor:DI (match_operand:DI 1 "register_operand" "%r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))]
""
"XOR %0,%1,%2")
;; FIXME: When TImode works for other reasons (like cross-compiling from
;; a 32-bit host), add back umulditi3 and umuldi3_highpart here.
;; FIXME: Check what's really reasonable for the mod part.
;; One day we might persuade GCC to expand divisions with constants the
;; way MMIX does; giving the remainder the sign of the divisor. But even
;; then, it might be good to have an option to divide the way "everybody
;; else" does. Perhaps then, this option can be on by default. However,
;; it's not likely to happen because major (C, C++, Fortran) language
;; standards in effect at 2002-04-29 reportedly demand that the sign of
;; the remainder must follow the sign of the dividend.
(define_insn "divmoddi4"
[(set (match_operand:DI 0 "register_operand" "=r")
(div:DI (match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))
(set (match_operand:DI 3 "register_operand" "=y")
(mod:DI (match_dup 1) (match_dup 2)))]
;; Do the library stuff later.
"TARGET_KNUTH_DIVISION"
"DIV %0,%1,%2")
(define_insn "udivmoddi4"
[(set (match_operand:DI 0 "register_operand" "=r")
(udiv:DI (match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))
(set (match_operand:DI 3 "register_operand" "=y")
(umod:DI (match_dup 1) (match_dup 2)))]
""
"DIVU %0,%1,%2")
(define_expand "divdi3"
[(parallel
[(set (match_operand:DI 0 "register_operand" "=&r")
(div:DI (match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "register_operand" "r")))
(clobber (scratch:DI))
(clobber (scratch:DI))
(clobber (reg:DI MMIX_rR_REGNUM))])]
"! TARGET_KNUTH_DIVISION"
"")
;; The %2-is-%1-case is there just to make sure things don't fail. Could
;; presumably happen with optimizations off; no evidence.
(define_insn "*divdi3_nonknuth"
[(set (match_operand:DI 0 "register_operand" "=&r,&r")
(div:DI (match_operand:DI 1 "register_operand" "r,r")
(match_operand:DI 2 "register_operand" "1,r")))
(clobber (match_scratch:DI 3 "=1,1"))
(clobber (match_scratch:DI 4 "=2,2"))
(clobber (reg:DI MMIX_rR_REGNUM))]
"! TARGET_KNUTH_DIVISION"
"@
SETL %0,1
XOR $255,%1,%2\;NEGU %0,0,%2\;CSN %2,%2,%0\;NEGU %0,0,%1\;CSN %1,%1,%0\;\
DIVU %0,%1,%2\;NEGU %1,0,%0\;CSN %0,$255,%1")
(define_expand "moddi3"
[(parallel
[(set (match_operand:DI 0 "register_operand" "=&r")
(mod:DI (match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "register_operand" "r")))
(clobber (scratch:DI))
(clobber (scratch:DI))
(clobber (reg:DI MMIX_rR_REGNUM))])]
"! TARGET_KNUTH_DIVISION"
"")
;; The %2-is-%1-case is there just to make sure things don't fail. Could
;; presumably happen with optimizations off; no evidence.
(define_insn "*moddi3_nonknuth"
[(set (match_operand:DI 0 "register_operand" "=&r,&r")
(mod:DI (match_operand:DI 1 "register_operand" "r,r")
(match_operand:DI 2 "register_operand" "1,r")))
(clobber (match_scratch:DI 3 "=1,1"))
(clobber (match_scratch:DI 4 "=2,2"))
(clobber (reg:DI MMIX_rR_REGNUM))]
"! TARGET_KNUTH_DIVISION"
"@
SETL %0,0
NEGU %0,0,%2\;CSN %2,%2,%0\;NEGU $255,0,%1\;CSN %1,%1,$255\;\
DIVU %1,%1,%2\;GET %0,:rR\;NEGU %2,0,%0\;CSNN %0,$255,%2")
(define_insn "ashldi3"
[(set (match_operand:DI 0 "register_operand" "=r")
(ashift:DI
(match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))]
""
"SLU %0,%1,%2")
(define_insn "ashrdi3"
[(set (match_operand:DI 0 "register_operand" "=r")
(ashiftrt:DI
(match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))]
""
"SR %0,%1,%2")
(define_insn "lshrdi3"
[(set (match_operand:DI 0 "register_operand" "=r")
(lshiftrt:DI
(match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))]
""
"SRU %0,%1,%2")
(define_insn "negdi2"
[(set (match_operand:DI 0 "register_operand" "=r")
(neg:DI (match_operand:DI 1 "register_operand" "r")))]
""
"NEGU %0,0,%1")
(define_expand "negdf2"
[(parallel [(set (match_operand:DF 0 "register_operand" "=r")
(neg:DF (match_operand:DF 1 "register_operand" "r")))
(use (match_dup 2))])]
""
{
/* Emit bit-flipping sequence to be IEEE-safe wrt. -+0. */
operands[2] = force_reg (DImode, GEN_INT ((HOST_WIDE_INT) 1 << 63));
})
(define_insn "*expanded_negdf2"
[(set (match_operand:DF 0 "register_operand" "=r")
(neg:DF (match_operand:DF 1 "register_operand" "r")))
(use (match_operand:DI 2 "register_operand" "r"))]
""
"XOR %0,%1,%2")
;; FIXME: define_expand for absdi2?
(define_insn "absdf2"
[(set (match_operand:DF 0 "register_operand" "=r")
(abs:DF (match_operand:DF 1 "register_operand" "0")))]
""
"ANDNH %0,#8000")
(define_insn "sqrtdf2"
[(set (match_operand:DF 0 "register_operand" "=r")
(sqrt:DF (match_operand:DF 1 "register_operand" "r")))]
""
"FSQRT %0,%1")
;; FIXME: define_expand for ffssi2? (not ffsdi2 since int is SImode).
(define_insn "one_cmpldi2"
[(set (match_operand:DI 0 "register_operand" "=r")
(not:DI (match_operand:DI 1 "register_operand" "r")))]
""
"NOR %0,%1,0")
;; When the user-patterns expand, the resulting insns will match the
;; patterns below.
;; We can fold the signed-compare where the register value is
;; already equal to (compare:CCTYPE (reg) (const_int 0)).
;; We can't do that at all for floating-point, due to NaN, +0.0
;; and -0.0, and we can only do it for the non/zero test of
;; unsigned, so that has to be done another way.
;; FIXME: Perhaps a peep2 changing CCcode to a new code, that
;; gets folded here.
(define_insn "*cmpdi_folded"
[(set (match_operand:CC 0 "register_operand" "=r")
(compare:CC
(match_operand:DI 1 "register_operand" "r")
(const_int 0)))]
;; FIXME: Can we test equivalence any other way?
;; FIXME: Can we fold any other way?
"REG_P (operands[0]) && REG_P (operands[1])
&& REGNO (operands[1]) == REGNO (operands[0])"
"%% folded: cmp %0,%1,0")
(define_insn "*cmps"
[(set (match_operand:CC 0 "register_operand" "=r")
(compare:CC
(match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))]
""
"CMP %0,%1,%2")
(define_insn "*cmpu"
[(set (match_operand:CC_UNS 0 "register_operand" "=r")
(compare:CC_UNS
(match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI")))]
""
"CMPU %0,%1,%2")
(define_insn "*fcmp"
[(set (match_operand:CC_FP 0 "register_operand" "=r")
(compare:CC_FP
(match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FCMP%e0 %0,%1,%2")
;; FIXME: for -mieee, add fsub %0,%1,%1\;fsub %0,%2,%2 before to
;; make signalling compliant.
(define_insn "*feql"
[(set (match_operand:CC_FPEQ 0 "register_operand" "=r")
(compare:CC_FPEQ
(match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FEQL%e0 %0,%1,%2")
(define_insn "*fun"
[(set (match_operand:CC_FUN 0 "register_operand" "=r")
(compare:CC_FUN
(match_operand:DF 1 "register_operand" "r")
(match_operand:DF 2 "register_operand" "r")))]
""
"FUN%e0 %0,%1,%2")
;; In order to get correct rounding, we have to use SFLOT and SFLOTU for
;; conversion. They do not convert to SFmode; they convert to DFmode,
;; with rounding as of SFmode. They are not usable as is, but we pretend
;; we have a single instruction but emit two.
;; Note that this will (somewhat unexpectedly) create an inexact
;; exception if rounding is necessary - has to be masked off in crt0?
(define_expand "floatdisf2"
[(parallel [(set (match_operand:SF 0 "nonimmediate_operand" "=rm")
(float:SF
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI")))
;; Let's use a DI scratch, since SF don't generally get into
;; registers. Dunno what's best; it's really a DF, but that
;; doesn't logically follow from operands in the pattern.
(clobber (match_scratch:DI 2 "=&r"))])]
""
"
{
if (GET_CODE (operands[0]) != MEM)
{
rtx stack_slot;
/* FIXME: This stack-slot remains even at -O3. There must be a
better way. */
stack_slot
= validize_mem (assign_stack_temp (SFmode,
GET_MODE_SIZE (SFmode)));
emit_insn (gen_floatdisf2 (stack_slot, operands[1]));
emit_move_insn (operands[0], stack_slot);
DONE;
}
}")
(define_insn "*floatdisf2_real"
[(set (match_operand:SF 0 "memory_operand" "=m")
(float:SF
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI")))
(clobber (match_scratch:DI 2 "=&r"))]
""
"SFLOT %2,%1\;STSF %2,%0")
(define_expand "floatunsdisf2"
[(parallel [(set (match_operand:SF 0 "nonimmediate_operand" "=rm")
(unsigned_float:SF
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI")))
;; Let's use a DI scratch, since SF don't generally get into
;; registers. Dunno what's best; it's really a DF, but that
;; doesn't logically follow from operands in the pattern.
(clobber (scratch:DI))])]
""
"
{
if (GET_CODE (operands[0]) != MEM)
{
rtx stack_slot;
/* FIXME: This stack-slot remains even at -O3. Must be a better
way. */
stack_slot
= validize_mem (assign_stack_temp (SFmode,
GET_MODE_SIZE (SFmode)));
emit_insn (gen_floatunsdisf2 (stack_slot, operands[1]));
emit_move_insn (operands[0], stack_slot);
DONE;
}
}")
(define_insn "*floatunsdisf2_real"
[(set (match_operand:SF 0 "memory_operand" "=m")
(unsigned_float:SF
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI")))
(clobber (match_scratch:DI 2 "=&r"))]
""
"SFLOTU %2,%1\;STSF %2,%0")
;; Note that this will (somewhat unexpectedly) create an inexact
;; exception if rounding is necessary - has to be masked off in crt0?
(define_insn "floatdidf2"
[(set (match_operand:DF 0 "register_operand" "=r")
(float:DF
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI")))]
""
"FLOT %0,%1")
(define_insn "floatunsdidf2"
[(set (match_operand:DF 0 "register_operand" "=r")
(unsigned_float:DF
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI")))]
""
"FLOTU %0,%1")
(define_insn "ftruncdf2"
[(set (match_operand:DF 0 "register_operand" "=r")
(fix:DF (match_operand:DF 1 "register_operand" "r")))]
""
;; ROUND_OFF
"FINT %0,1,%1")
;; Note that this will (somewhat unexpectedly) create an inexact
;; exception if rounding is necessary - has to be masked off in crt0?
(define_insn "fix_truncdfdi2"
[(set (match_operand:DI 0 "register_operand" "=r")
(fix:DI (fix:DF (match_operand:DF 1 "register_operand" "r"))))]
""
;; ROUND_OFF
"FIX %0,1,%1")
(define_insn "fixuns_truncdfdi2"
[(set (match_operand:DI 0 "register_operand" "=r")
(unsigned_fix:DI
(fix:DF (match_operand:DF 1 "register_operand" "r"))))]
""
;; ROUND_OFF
"FIXU %0,1,%1")
;; It doesn't seem like it's possible to have memory_operand as a
;; predicate here (testcase: libgcc2 floathisf). FIXME: Shouldn't it be
;; possible to do that? Bug in GCC? Anyway, this used to be a simple
;; pattern with a memory_operand predicate, but was split up with a
;; define_expand with the old pattern as "anonymous".
;; FIXME: Perhaps with SECONDARY_MEMORY_NEEDED?
(define_expand "truncdfsf2"
[(set (match_operand:SF 0 "nonimmediate_operand")
(float_truncate:SF (match_operand:DF 1 "register_operand")))]
""
"
{
if (GET_CODE (operands[0]) != MEM)
{
/* FIXME: There should be a way to say: 'put this in operands[0]
but *after* the expanded insn'. */
rtx stack_slot;
/* There is no sane destination but a register here, if it wasn't
already MEM. (It's too hard to get fatal_insn to work here.) */
if (! REG_P (operands[0]))
internal_error (\"MMIX Internal: Bad truncdfsf2 expansion\");
/* FIXME: This stack-slot remains even at -O3. Must be a better
way. */
stack_slot
= validize_mem (assign_stack_temp (SFmode,
GET_MODE_SIZE (SFmode)));
emit_insn (gen_truncdfsf2 (stack_slot, operands[1]));
emit_move_insn (operands[0], stack_slot);
DONE;
}
}")
(define_insn "*truncdfsf2_real"
[(set (match_operand:SF 0 "memory_operand" "=m")
(float_truncate:SF (match_operand:DF 1 "register_operand" "r")))]
""
"STSF %1,%0")
;; Same comment as for truncdfsf2.
(define_expand "extendsfdf2"
[(set (match_operand:DF 0 "register_operand")
(float_extend:DF (match_operand:SF 1 "nonimmediate_operand")))]
""
"
{
if (GET_CODE (operands[1]) != MEM)
{
rtx stack_slot;
/* There is no sane destination but a register here, if it wasn't
already MEM. (It's too hard to get fatal_insn to work here.) */
if (! REG_P (operands[0]))
internal_error (\"MMIX Internal: Bad extendsfdf2 expansion\");
/* FIXME: This stack-slot remains even at -O3. There must be a
better way. */
stack_slot
= validize_mem (assign_stack_temp (SFmode,
GET_MODE_SIZE (SFmode)));
emit_move_insn (stack_slot, operands[1]);
emit_insn (gen_extendsfdf2 (operands[0], stack_slot));
DONE;
}
}")
(define_insn "*extendsfdf2_real"
[(set (match_operand:DF 0 "register_operand" "=r")
(float_extend:DF (match_operand:SF 1 "memory_operand" "m")))]
""
"LDSF %0,%1")
;; Neither sign-extend nor zero-extend are necessary; gcc knows how to
;; synthesize using shifts or and, except with a memory source and not
;; completely optimal. FIXME: Actually, other bugs surface when those
;; patterns are defined; fix later.
;; There are no sane values with the bit-patterns of (int) 0..255 except
;; 0 to use in movdfcc.
(define_expand "movdfcc"
[(set (match_dup 4) (match_dup 5))
(set (match_operand:DF 0 "register_operand" "")
(if_then_else:DF
(match_operand 1 "comparison_operator" "")
(match_operand:DF 2 "mmix_reg_or_0_operand" "")
(match_operand:DF 3 "mmix_reg_or_0_operand" "")))]
""
"
{
enum rtx_code code = GET_CODE (operands[1]);
if (code == LE || code == GE)
FAIL;
operands[4] = mmix_gen_compare_reg (code, XEXP (operands[1], 0),
XEXP (operands[1], 1));
operands[5] = gen_rtx_COMPARE (GET_MODE (operands[4]),
XEXP (operands[1], 0),
XEXP (operands[1], 1));
operands[1] = gen_rtx_fmt_ee (code, VOIDmode, operands[4], const0_rtx);
}")
(define_expand "movdicc"
[(set (match_dup 4) (match_dup 5))
(set (match_operand:DI 0 "register_operand" "")
(if_then_else:DI
(match_operand 1 "comparison_operator" "")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "")
(match_operand:DI 3 "mmix_reg_or_8bit_operand" "")))]
""
"
{
enum rtx_code code = GET_CODE (operands[1]);
if (code == LE || code == GE)
FAIL;
operands[4] = mmix_gen_compare_reg (code, XEXP (operands[1], 0),
XEXP (operands[1], 1));
operands[5] = gen_rtx_COMPARE (GET_MODE (operands[4]),
XEXP (operands[1], 0),
XEXP (operands[1], 1));
operands[1] = gen_rtx_fmt_ee (code, VOIDmode, operands[4], const0_rtx);
}")
;; FIXME: Is this the right way to do "folding" of CCmode -> DImode?
(define_insn "*movdicc_real_foldable"
[(set (match_operand:DI 0 "register_operand" "=r,r,r,r")
(if_then_else:DI
(match_operator 2 "mmix_foldable_comparison_operator"
[(match_operand:DI 3 "register_operand" "r,r,r,r")
(const_int 0)])
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI,0 ,rI,GM")
(match_operand:DI 4 "mmix_reg_or_8bit_operand" "0 ,rI,GM,rI")))]
""
"@
CS%d2 %0,%3,%1
CS%D2 %0,%3,%4
ZS%d2 %0,%3,%1
ZS%D2 %0,%3,%4")
(define_insn "*movdicc_real_reversible"
[(set
(match_operand:DI 0 "register_operand" "=r ,r ,r ,r")
(if_then_else:DI
(match_operator
2 "mmix_comparison_operator"
[(match_operand 3 "mmix_reg_cc_operand" "r ,r ,r ,r")
(const_int 0)])
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI,0 ,rI,GM")
(match_operand:DI 4 "mmix_reg_or_8bit_operand" "0 ,rI,GM,rI")))]
"REVERSIBLE_CC_MODE (GET_MODE (operands[3]))"
"@
CS%d2 %0,%3,%1
CS%D2 %0,%3,%4
ZS%d2 %0,%3,%1
ZS%D2 %0,%3,%4")
(define_insn "*movdicc_real_nonreversible"
[(set
(match_operand:DI 0 "register_operand" "=r ,r")
(if_then_else:DI
(match_operator
2 "mmix_comparison_operator"
[(match_operand 3 "mmix_reg_cc_operand" "r ,r")
(const_int 0)])
(match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI,rI")
(match_operand:DI 4 "mmix_reg_or_0_operand" "0 ,GM")))]
"!REVERSIBLE_CC_MODE (GET_MODE (operands[3]))"
"@
CS%d2 %0,%3,%1
ZS%d2 %0,%3,%1")
(define_insn "*movdfcc_real_foldable"
[(set
(match_operand:DF 0 "register_operand" "=r ,r ,r ,r")
(if_then_else:DF
(match_operator
2 "mmix_foldable_comparison_operator"
[(match_operand:DI 3 "register_operand" "r ,r ,r ,r")
(const_int 0)])
(match_operand:DF 1 "mmix_reg_or_0_operand" "rGM,0 ,rGM,GM")
(match_operand:DF 4 "mmix_reg_or_0_operand" "0 ,rGM,GM ,rGM")))]
""
"@
CS%d2 %0,%3,%1
CS%D2 %0,%3,%4
ZS%d2 %0,%3,%1
ZS%D2 %0,%3,%4")
(define_insn "*movdfcc_real_reversible"
[(set
(match_operand:DF 0 "register_operand" "=r ,r ,r ,r")
(if_then_else:DF
(match_operator
2 "mmix_comparison_operator"
[(match_operand 3 "mmix_reg_cc_operand" "r ,r ,r ,r")
(const_int 0)])
(match_operand:DF 1 "mmix_reg_or_0_operand" "rGM,0 ,rGM,GM")
(match_operand:DF 4 "mmix_reg_or_0_operand" "0 ,rGM,GM ,rGM")))]
"REVERSIBLE_CC_MODE (GET_MODE (operands[3]))"
"@
CS%d2 %0,%3,%1
CS%D2 %0,%3,%4
ZS%d2 %0,%3,%1
ZS%D2 %0,%3,%4")
(define_insn "*movdfcc_real_nonreversible"
[(set
(match_operand:DF 0 "register_operand" "=r ,r")
(if_then_else:DF
(match_operator
2 "mmix_comparison_operator"
[(match_operand 3 "mmix_reg_cc_operand" "r ,r")
(const_int 0)])
(match_operand:DF 1 "mmix_reg_or_0_operand" "rGM,rGM")
(match_operand:DF 4 "mmix_reg_or_0_operand" "0 ,GM")))]
"!REVERSIBLE_CC_MODE (GET_MODE (operands[3]))"
"@
CS%d2 %0,%3,%1
ZS%d2 %0,%3,%1")
;; FIXME: scc insns will probably help, I just skip them
;; right now. Revisit.
(define_expand "cbranchdi4"
[(set (match_dup 4)
(match_op_dup 5
[(match_operand:DI 1 "register_operand" "")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "")]))
(set (pc)
(if_then_else
(match_operator 0 "ordered_comparison_operator"
[(match_dup 4)
(const_int 0)])
(label_ref (match_operand 3 "" ""))
(pc)))]
""
"
{
operands[4] = mmix_gen_compare_reg (GET_CODE (operands[0]),
operands[1], operands[2]);
operands[5] = gen_rtx_fmt_ee (COMPARE,
GET_MODE (operands[4]),
operands[1], operands[2]);
}")
(define_expand "cbranchdf4"
[(set (match_dup 4)
(match_op_dup 5
[(match_operand:DF 1 "register_operand" "")
(match_operand:DF 2 "register_operand" "")]))
(set (pc)
(if_then_else
(match_operator 0 "float_comparison_operator"
[(match_dup 4)
(const_int 0)])
(label_ref (match_operand 3 "" ""))
(pc)))]
""
"
{
/* The head comment of optabs.c:can_compare_p says we're required to
implement this, so we have to clean up the mess here. */
if (GET_CODE (operands[0]) == LE || GET_CODE (operands[0]) == GE)
{
enum rtx_code ltgt_code = GET_CODE (operands[0]) == LE ? LT : GT;
emit_cmp_and_jump_insns (operands[1], operands[2], ltgt_code, NULL_RTX,
DFmode, 0, operands[3]);
emit_cmp_and_jump_insns (operands[1], operands[2], EQ, NULL_RTX,
DFmode, 0, operands[3]);
DONE;
}
operands[4] = mmix_gen_compare_reg (GET_CODE (operands[0]),
operands[1], operands[2]);
operands[5] = gen_rtx_fmt_ee (COMPARE,
GET_MODE (operands[4]),
operands[1], operands[2]);
}")
;; FIXME: we can emit an unordered-or-*not*-equal compare in one insn, but
;; there's no RTL code for it. Maybe revisit in future.
;; FIXME: Odd/Even matchers?
(define_insn "*bCC_foldable"
[(set (pc)
(if_then_else
(match_operator 1 "mmix_foldable_comparison_operator"
[(match_operand:DI 2 "register_operand" "r")
(const_int 0)])
(label_ref (match_operand 0 "" ""))
(pc)))]
""
"%+B%d1 %2,%0")
(define_insn "*bCC"
[(set (pc)
(if_then_else
(match_operator 1 "mmix_comparison_operator"
[(match_operand 2 "mmix_reg_cc_operand" "r")
(const_int 0)])
(label_ref (match_operand 0 "" ""))
(pc)))]
""
"%+B%d1 %2,%0")
(define_insn "*bCC_inverted_foldable"
[(set (pc)
(if_then_else
(match_operator 1 "mmix_foldable_comparison_operator"
[(match_operand:DI 2 "register_operand" "r")
(const_int 0)])
(pc)
(label_ref (match_operand 0 "" ""))))]
;; REVERSIBLE_CC_MODE is checked by mmix_foldable_comparison_operator.
""
"%+B%D1 %2,%0")
(define_insn "*bCC_inverted"
[(set (pc)
(if_then_else
(match_operator 1 "mmix_comparison_operator"
[(match_operand 2 "mmix_reg_cc_operand" "r")
(const_int 0)])
(pc)
(label_ref (match_operand 0 "" ""))))]
"REVERSIBLE_CC_MODE (GET_MODE (operands[2]))"
"%+B%D1 %2,%0")
(define_expand "call"
[(parallel [(call (match_operand:QI 0 "memory_operand" "")
(match_operand 1 "general_operand" ""))
(use (match_operand 2 "general_operand" ""))
(clobber (match_dup 4))])
(set (match_dup 4) (match_dup 3))]
""
"
{
/* The caller checks that the operand is generally valid as an
address, but at -O0 nothing makes sure that it's also a valid
call address for a *call*; a mmix_symbolic_or_address_operand.
Force into a register if it isn't. */
if (!mmix_symbolic_or_address_operand (XEXP (operands[0], 0),
GET_MODE (XEXP (operands[0], 0))))
operands[0]
= replace_equiv_address (operands[0],
force_reg (Pmode, XEXP (operands[0], 0)));
/* Since the epilogue 'uses' the return address, and it is clobbered
in the call, and we set it back after every call (all but one setting
will be optimized away), integrity is maintained. */
operands[3]
= mmix_get_hard_reg_initial_val (Pmode,
MMIX_INCOMING_RETURN_ADDRESS_REGNUM);
/* FIXME: There's a bug in gcc which causes NULL to be passed as
operand[2] when we get out of registers, which later confuses gcc.
Work around it by replacing it with const_int 0. Possibly documentation
error too. */
if (operands[2] == NULL_RTX)
operands[2] = const0_rtx;
operands[4] = gen_rtx_REG (DImode, MMIX_INCOMING_RETURN_ADDRESS_REGNUM);
}")
(define_expand "call_value"
[(parallel [(set (match_operand 0 "" "")
(call (match_operand:QI 1 "memory_operand" "")
(match_operand 2 "general_operand" "")))
(use (match_operand 3 "general_operand" ""))
(clobber (match_dup 5))])
(set (match_dup 5) (match_dup 4))]
""
"
{
/* The caller checks that the operand is generally valid as an
address, but at -O0 nothing makes sure that it's also a valid
call address for a *call*; a mmix_symbolic_or_address_operand.
Force into a register if it isn't. */
if (!mmix_symbolic_or_address_operand (XEXP (operands[1], 0),
GET_MODE (XEXP (operands[1], 0))))
operands[1]
= replace_equiv_address (operands[1],
force_reg (Pmode, XEXP (operands[1], 0)));
/* Since the epilogue 'uses' the return address, and it is clobbered
in the call, and we set it back after every call (all but one setting
will be optimized away), integrity is maintained. */
operands[4]
= mmix_get_hard_reg_initial_val (Pmode,
MMIX_INCOMING_RETURN_ADDRESS_REGNUM);
/* FIXME: See 'call'. */
if (operands[3] == NULL_RTX)
operands[3] = const0_rtx;
/* FIXME: Documentation bug: operands[3] (operands[2] for 'call') is the
*next* argument register, not the number of arguments in registers.
(There used to be code here where that mattered.) */
operands[5] = gen_rtx_REG (DImode, MMIX_INCOMING_RETURN_ADDRESS_REGNUM);
}")
;; Don't use 'p' here. A 'p' must stand first in constraints, or reload
;; messes up, not registering the address for reload. Several C++
;; testcases, including g++.brendan/crash40.C. FIXME: This is arguably a
;; bug in gcc. Note line ~2612 in reload.c, that does things on the
;; condition <<else if (constraints[i][0] == 'p')>> and the comment on
;; ~3017 that says:
;; << case 'p':
;; /* All necessary reloads for an address_operand
;; were handled in find_reloads_address. */>>
;; Sorry, I have not dug deeper. If symbolic addresses are used
;; rarely compared to addresses in registers, disparaging the
;; first ("p") alternative by adding ? in the first operand
;; might do the trick. We define 'U' as a synonym to 'p', but without the
;; caveats (and very small advantages) of 'p'.
;; As of r190682 still so: newlib/libc/stdlib/dtoa.c ICEs if "p" is used.
(define_insn "*call_real"
[(call (mem:QI
(match_operand:DI 0 "mmix_symbolic_or_address_operand" "s,rU"))
(match_operand 1 "" ""))
(use (match_operand 2 "" ""))
(clobber (reg:DI MMIX_rJ_REGNUM))]
""
"@
PUSHJ $%p2,%0
PUSHGO $%p2,%a0")
(define_insn "*call_value_real"
[(set (match_operand 0 "register_operand" "=r,r")
(call (mem:QI
(match_operand:DI 1 "mmix_symbolic_or_address_operand" "s,rU"))
(match_operand 2 "" "")))
(use (match_operand 3 "" ""))
(clobber (reg:DI MMIX_rJ_REGNUM))]
""
"@
PUSHJ $%p3,%1
PUSHGO $%p3,%a1")
;; I hope untyped_call and untyped_return are not needed for MMIX.
;; Users of Objective-C will notice.
; Generated by GCC.
(define_expand "return"
[(return)]
"mmix_use_simple_return ()"
"")
; Generated by the epilogue expander.
(define_insn "*expanded_return"
[(return)]
""
"POP %.,0")
(define_expand "prologue"
[(const_int 0)]
""
"mmix_expand_prologue (); DONE;")
; Note that the (return) from the expander itself is always the last insn
; in the epilogue.
(define_expand "epilogue"
[(return)]
""
"mmix_expand_epilogue ();")
(define_insn "nop"
[(const_int 0)]
""
"SWYM 0,0,0")
(define_insn "jump"
[(set (pc) (label_ref (match_operand 0 "" "")))]
""
"JMP %0")
(define_insn "indirect_jump"
[(set (pc) (match_operand 0 "address_operand" "p"))]
""
"GO $255,%a0")
;; FIXME: This is just a jump, and should be expanded to one.
(define_insn "tablejump"
[(set (pc) (match_operand:DI 0 "address_operand" "p"))
(use (label_ref (match_operand 1 "" "")))]
""
"GO $255,%a0")
;; The only peculiar thing is that the register stack has to be unwound at
;; nonlocal_goto_receiver. At each function that has a nonlocal label, we
;; save at function entry the location of the "alpha" register stack
;; pointer, rO, in a stack slot known to that function (right below where
;; the frame-pointer would be located).
;; In the nonlocal goto receiver, we unwind the register stack by a series
;; of "pop 0,0" until rO equals the saved value. (If it goes lower, we
;; should die with a trap.)
(define_expand "nonlocal_goto_receiver"
[(parallel [(unspec_volatile [(match_dup 1)] 1)
(clobber (scratch:DI))
(clobber (reg:DI MMIX_rJ_REGNUM))])
(set (reg:DI MMIX_rJ_REGNUM) (match_dup 0))]
""
"
{
operands[0]
= mmix_get_hard_reg_initial_val (Pmode,
MMIX_INCOMING_RETURN_ADDRESS_REGNUM);
/* We need the frame-pointer to be live or the equivalent
expression, so refer to in in the pattern. We can't use a MEM
(that may contain out-of-range offsets in the final expression)
for fear that middle-end will legitimize it or replace the address
using temporary registers (which are not revived at this point). */
operands[1] = frame_pointer_rtx;
/* Mark this function as containing a landing-pad. */
cfun->machine->has_landing_pad = 1;
}")
;; GCC can insist on using saved registers to keep the slot address in
;; "across" the exception, or (perhaps) to use saved registers in the
;; address and re-use them after the register stack unwind, so it's best
;; to form the address ourselves.
(define_insn "*nonlocal_goto_receiver_expanded"
[(unspec_volatile [(match_operand:DI 1 "frame_pointer_operand" "Yf")] 1)
(clobber (match_scratch:DI 0 "=&r"))
(clobber (reg:DI MMIX_rJ_REGNUM))]
""
{
rtx my_operands[3];
const char *my_template
= "GETA $255,0f\;PUT rJ,$255\;LDOU $255,%a0\n\
0:\;GET %1,rO\;CMPU %1,%1,$255\;BNP %1,1f\;POP 0,0\n1:";
my_operands[1] = operands[0];
my_operands[2] = GEN_INT (-MMIX_fp_rO_OFFSET);
if (operands[1] == hard_frame_pointer_rtx)
{
mmix_output_register_setting (asm_out_file, REGNO (operands[0]),
MMIX_fp_rO_OFFSET, 1);
my_operands[0]
= gen_rtx_PLUS (Pmode, hard_frame_pointer_rtx, operands[0]);
}
else
{
HOST_WIDEST_INT offs = INTVAL (XEXP (operands[1], 1));
offs += MMIX_fp_rO_OFFSET;
if (insn_const_int_ok_for_constraint (offs, CONSTRAINT_I))
my_operands[0]
= gen_rtx_PLUS (Pmode, stack_pointer_rtx, GEN_INT (offs));
else
{
mmix_output_register_setting (asm_out_file, REGNO (operands[0]),
offs, 1);
my_operands[0]
= gen_rtx_PLUS (Pmode, stack_pointer_rtx, operands[0]);
}
}
output_asm_insn (my_template, my_operands);
return "";
})
(define_insn "*Naddu"
[(set (match_operand:DI 0 "register_operand" "=r")
(plus:DI (mult:DI (match_operand:DI 1 "register_operand" "r")
(match_operand:DI 2 "const_int_operand" "n"))
(match_operand:DI 3 "mmix_reg_or_8bit_operand" "rI")))]
"GET_CODE (operands[2]) == CONST_INT
&& (INTVAL (operands[2]) == 2
|| INTVAL (operands[2]) == 4
|| INTVAL (operands[2]) == 8
|| INTVAL (operands[2]) == 16)"
"%2ADDU %0,%1,%3")
(define_insn "*andn"
[(set (match_operand:DI 0 "register_operand" "=r")
(and:DI
(not:DI (match_operand:DI 1 "mmix_reg_or_8bit_operand" "rI"))
(match_operand:DI 2 "register_operand" "r")))]
""
"ANDN %0,%2,%1")
(define_insn "*nand"
[(set (match_operand:DI 0 "register_operand" "=r")
(ior:DI
(not:DI (match_operand:DI 1 "register_operand" "%r"))
(not:DI (match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI"))))]
""
"NAND %0,%1,%2")
(define_insn "*nor"
[(set (match_operand:DI 0 "register_operand" "=r")
(and:DI
(not:DI (match_operand:DI 1 "register_operand" "%r"))
(not:DI (match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI"))))]
""
"NOR %0,%1,%2")
(define_insn "*nxor"
[(set (match_operand:DI 0 "register_operand" "=r")
(not:DI
(xor:DI (match_operand:DI 1 "register_operand" "%r")
(match_operand:DI 2 "mmix_reg_or_8bit_operand" "rI"))))]
""
"NXOR %0,%1,%2")
(define_insn "sync_icache"
[(unspec_volatile [(match_operand:DI 0 "memory_operand" "m")
(match_operand:DI 1 "const_int_operand" "I")] 0)]
""
"SYNCID %1,%0")
;; Local Variables:
;; mode: lisp
;; indent-tabs-mode: t
;; End:
| SaberMod/GCC_SaberMod | gcc/config/mmix/mmix.md | Markdown | gpl-2.0 | 39,221 |
/* Copyright (c) 2008-2015, The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 and
* only version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#ifndef DIAGCHAR_SHARED
#define DIAGCHAR_SHARED
#define MSG_MASKS_TYPE 0x00000001
#define LOG_MASKS_TYPE 0x00000002
#define EVENT_MASKS_TYPE 0x00000004
#define PKT_TYPE 0x00000008
#define DEINIT_TYPE 0x00000010
#define USER_SPACE_DATA_TYPE 0x00000020
#define DCI_DATA_TYPE 0x00000040
#define USER_SPACE_RAW_DATA_TYPE 0x00000080
#define DCI_LOG_MASKS_TYPE 0x00000100
#define DCI_EVENT_MASKS_TYPE 0x00000200
#define DCI_PKT_TYPE 0x00000400
#define HDLC_SUPPORT_TYPE 0x00001000
#define USB_MODE 1
#define MEMORY_DEVICE_MODE 2
#define NO_LOGGING_MODE 3
#define UART_MODE 4
#define SOCKET_MODE 5
#define CALLBACK_MODE 6
/* different values that go in for diag_data_type */
#define DATA_TYPE_EVENT 0
#define DATA_TYPE_F3 1
#define DATA_TYPE_LOG 2
#define DATA_TYPE_RESPONSE 3
#define DATA_TYPE_DELAYED_RESPONSE 4
#define DATA_TYPE_DCI_LOG 0x00000100
#define DATA_TYPE_DCI_EVENT 0x00000200
/* Different IOCTL values */
#define DIAG_IOCTL_COMMAND_REG 0
#define DIAG_IOCTL_COMMAND_DEREG 1
#define DIAG_IOCTL_SWITCH_LOGGING 7
#define DIAG_IOCTL_GET_DELAYED_RSP_ID 8
#define DIAG_IOCTL_LSM_DEINIT 9
#define DIAG_IOCTL_DCI_INIT 20
#define DIAG_IOCTL_DCI_DEINIT 21
#define DIAG_IOCTL_DCI_SUPPORT 22
#define DIAG_IOCTL_DCI_REG 23
#define DIAG_IOCTL_DCI_STREAM_INIT 24
#define DIAG_IOCTL_DCI_HEALTH_STATS 25
#define DIAG_IOCTL_DCI_LOG_STATUS 26
#define DIAG_IOCTL_DCI_EVENT_STATUS 27
#define DIAG_IOCTL_DCI_CLEAR_LOGS 28
#define DIAG_IOCTL_DCI_CLEAR_EVENTS 29
#define DIAG_IOCTL_REMOTE_DEV 32
#define DIAG_IOCTL_VOTE_REAL_TIME 33
#define DIAG_IOCTL_GET_REAL_TIME 34
#define DIAG_IOCTL_PERIPHERAL_BUF_CONFIG 35
#define DIAG_IOCTL_PERIPHERAL_BUF_DRAIN 36
#define DIAG_IOCTL_REGISTER_CALLBACK 37
#define DIAG_IOCTL_HDLC_TOGGLE 38
/* PC Tools IDs */
#define APQ8060_TOOLS_ID 4062
#define AO8960_TOOLS_ID 4064
#define APQ8064_TOOLS_ID 4072
#define MSM8625_TOOLS_ID 4075
#define MSM8930_TOOLS_ID 4076
#define MSM8630_TOOLS_ID 4077
#define MSM8230_TOOLS_ID 4078
#define APQ8030_TOOLS_ID 4079
#define MSM8627_TOOLS_ID 4080
#define MSM8227_TOOLS_ID 4081
#define MSM8974_TOOLS_ID 4083
#define APQ8074_TOOLS_ID 4090
#define MSM8916_TOOLS_ID 4094
#define APQ8084_TOOLS_ID 4095
#define MSM8994_TOOLS_ID 4097
#define MSM8939_TOOLS_ID 4103
#define APQ8026_TOOLS_ID 4104
#define MSM8909_TOOLS_ID 4108
#define MSM8992_TOOLS_ID 4111
#define MSM8952_TOOLS_ID 4110
#define MSM_8996_TOOLS_ID 4112
#define MSG_MASK_0 (0x00000001)
#define MSG_MASK_1 (0x00000002)
#define MSG_MASK_2 (0x00000004)
#define MSG_MASK_3 (0x00000008)
#define MSG_MASK_4 (0x00000010)
#define MSG_MASK_5 (0x00000020)
#define MSG_MASK_6 (0x00000040)
#define MSG_MASK_7 (0x00000080)
#define MSG_MASK_8 (0x00000100)
#define MSG_MASK_9 (0x00000200)
#define MSG_MASK_10 (0x00000400)
#define MSG_MASK_11 (0x00000800)
#define MSG_MASK_12 (0x00001000)
#define MSG_MASK_13 (0x00002000)
#define MSG_MASK_14 (0x00004000)
#define MSG_MASK_15 (0x00008000)
#define MSG_MASK_16 (0x00010000)
#define MSG_MASK_17 (0x00020000)
#define MSG_MASK_18 (0x00040000)
#define MSG_MASK_19 (0x00080000)
#define MSG_MASK_20 (0x00100000)
#define MSG_MASK_21 (0x00200000)
#define MSG_MASK_22 (0x00400000)
#define MSG_MASK_23 (0x00800000)
#define MSG_MASK_24 (0x01000000)
#define MSG_MASK_25 (0x02000000)
#define MSG_MASK_26 (0x04000000)
#define MSG_MASK_27 (0x08000000)
#define MSG_MASK_28 (0x10000000)
#define MSG_MASK_29 (0x20000000)
#define MSG_MASK_30 (0x40000000)
#define MSG_MASK_31 (0x80000000)
/* These masks are to be used for support of all legacy messages in the sw.
The user does not need to remember the names as they will be embedded in
the appropriate macros. */
#define MSG_LEGACY_LOW MSG_MASK_0
#define MSG_LEGACY_MED MSG_MASK_1
#define MSG_LEGACY_HIGH MSG_MASK_2
#define MSG_LEGACY_ERROR MSG_MASK_3
#define MSG_LEGACY_FATAL MSG_MASK_4
/* Legacy Message Priorities */
#define MSG_LVL_FATAL (MSG_LEGACY_FATAL)
#define MSG_LVL_ERROR (MSG_LEGACY_ERROR | MSG_LVL_FATAL)
#define MSG_LVL_HIGH (MSG_LEGACY_HIGH | MSG_LVL_ERROR)
#define MSG_LVL_MED (MSG_LEGACY_MED | MSG_LVL_HIGH)
#define MSG_LVL_LOW (MSG_LEGACY_LOW | MSG_LVL_MED)
#define MSG_LVL_NONE 0
/* This needs to be modified manually now, when we add
a new RANGE of SSIDs to the msg_mask_tbl */
#define MSG_MASK_TBL_CNT 25
#define APPS_EVENT_LAST_ID 0x0AA2
#define MSG_SSID_0 0
#define MSG_SSID_0_LAST 116
#define MSG_SSID_1 500
#define MSG_SSID_1_LAST 506
#define MSG_SSID_2 1000
#define MSG_SSID_2_LAST 1007
#define MSG_SSID_3 2000
#define MSG_SSID_3_LAST 2008
#define MSG_SSID_4 3000
#define MSG_SSID_4_LAST 3014
#define MSG_SSID_5 4000
#define MSG_SSID_5_LAST 4010
#define MSG_SSID_6 4500
#define MSG_SSID_6_LAST 4526
#define MSG_SSID_7 4600
#define MSG_SSID_7_LAST 4615
#define MSG_SSID_8 5000
#define MSG_SSID_8_LAST 5031
#define MSG_SSID_9 5500
#define MSG_SSID_9_LAST 5516
#define MSG_SSID_10 6000
#define MSG_SSID_10_LAST 6081
#define MSG_SSID_11 6500
#define MSG_SSID_11_LAST 6521
#define MSG_SSID_12 7000
#define MSG_SSID_12_LAST 7003
#define MSG_SSID_13 7100
#define MSG_SSID_13_LAST 7111
#define MSG_SSID_14 7200
#define MSG_SSID_14_LAST 7201
#define MSG_SSID_15 8000
#define MSG_SSID_15_LAST 8000
#define MSG_SSID_16 8500
#define MSG_SSID_16_LAST 8529
#define MSG_SSID_17 9000
#define MSG_SSID_17_LAST 9008
#define MSG_SSID_18 9500
#define MSG_SSID_18_LAST 9510
#define MSG_SSID_19 10200
#define MSG_SSID_19_LAST 10210
#define MSG_SSID_20 10251
#define MSG_SSID_20_LAST 10255
#define MSG_SSID_21 10300
#define MSG_SSID_21_LAST 10300
#define MSG_SSID_22 10350
#define MSG_SSID_22_LAST 10377
#define MSG_SSID_23 10400
#define MSG_SSID_23_LAST 10415
#define MSG_SSID_24 0xC000
#define MSG_SSID_24_LAST 0xC063
static const uint32_t msg_bld_masks_0[] = {
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_ERROR,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_ERROR,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_ERROR,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_LOW|MSG_MASK_5|MSG_MASK_6|MSG_MASK_7|MSG_MASK_8,
MSG_LVL_LOW,
MSG_LVL_ERROR,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED|MSG_MASK_7 | \
MSG_MASK_8|MSG_MASK_9|MSG_MASK_10|MSG_MASK_11|MSG_MASK_12 | \
MSG_MASK_13|MSG_MASK_14|MSG_MASK_15|MSG_MASK_16 | \
MSG_MASK_17|MSG_MASK_18|MSG_MASK_19|MSG_MASK_20|MSG_MASK_21,
MSG_LVL_MED|MSG_MASK_5 | \
MSG_MASK_6|MSG_MASK_7|MSG_MASK_8|MSG_MASK_9|MSG_MASK_10| \
MSG_MASK_11|MSG_MASK_12|MSG_MASK_13|MSG_MASK_14| \
MSG_MASK_15|MSG_MASK_16|MSG_MASK_17,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED|MSG_MASK_5 | \
MSG_MASK_6|MSG_MASK_7|MSG_MASK_8,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_MED,
MSG_LVL_MED|MSG_MASK_5 | \
MSG_MASK_6|MSG_MASK_7|MSG_MASK_8|MSG_MASK_9|MSG_MASK_10| \
MSG_MASK_11|MSG_MASK_12|MSG_MASK_13|MSG_MASK_14|MSG_MASK_15| \
MSG_MASK_16|MSG_MASK_17|MSG_MASK_18|MSG_MASK_19|MSG_MASK_20| \
MSG_MASK_21|MSG_MASK_22|MSG_MASK_23|MSG_MASK_24|MSG_MASK_25,
MSG_LVL_MED|MSG_MASK_5 | \
MSG_MASK_6|MSG_MASK_7|MSG_MASK_8|MSG_MASK_9|MSG_MASK_10,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW | MSG_MASK_5 | \
MSG_MASK_6 | MSG_MASK_7 | MSG_MASK_8,
MSG_LVL_LOW | MSG_MASK_5 | \
MSG_MASK_6,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_MED | MSG_MASK_5 | \
MSG_MASK_6|MSG_MASK_7|MSG_MASK_8|MSG_MASK_9|MSG_MASK_10| \
MSG_MASK_11|MSG_MASK_12|MSG_MASK_13|MSG_MASK_14|MSG_MASK_15 | \
MSG_MASK_16|MSG_MASK_17|MSG_MASK_18|MSG_MASK_19|MSG_MASK_20,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_HIGH | MSG_MASK_21,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_HIGH,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR,
MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR,
MSG_LVL_MED|MSG_LVL_HIGH,
MSG_LVL_MED|MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_HIGH,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_MED,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_1[] = {
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH
};
static const uint32_t msg_bld_masks_2[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED,
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_3[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED|MSG_MASK_5|MSG_MASK_6|MSG_MASK_7|
MSG_MASK_8|MSG_MASK_9|MSG_MASK_10,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_4[] = {
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW
};
static const uint32_t msg_bld_masks_5[] = {
MSG_LVL_HIGH,
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED|MSG_LVL_MED|MSG_MASK_5|MSG_MASK_6|MSG_MASK_7| \
MSG_MASK_8|MSG_MASK_9,
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_6[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW
};
static const uint32_t msg_bld_masks_7[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL
};
static const uint32_t msg_bld_masks_8[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_9[] = {
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5,
MSG_LVL_MED|MSG_MASK_5
};
static const uint32_t msg_bld_masks_10[] = {
MSG_LVL_MED,
MSG_LVL_ERROR,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_MASK_5 | \
MSG_MASK_6|MSG_MASK_7|MSG_MASK_8|MSG_MASK_9|MSG_MASK_10| \
MSG_MASK_11|MSG_MASK_12|MSG_MASK_13|MSG_MASK_14|MSG_MASK_15| \
MSG_MASK_16|MSG_MASK_17|MSG_MASK_18|MSG_MASK_19|MSG_MASK_20| \
MSG_MASK_21|MSG_MASK_22,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_MASK_5,
MSG_LVL_LOW|MSG_MASK_0 | MSG_MASK_1 | MSG_MASK_2 | \
MSG_MASK_3 | MSG_MASK_4 | MSG_MASK_5 | MSG_MASK_6,
MSG_LVL_HIGH,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_11[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
};
static const uint32_t msg_bld_masks_12[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
};
static const uint32_t msg_bld_masks_13[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
};
static const uint32_t msg_bld_masks_14[] = {
MSG_LVL_MED,
MSG_LVL_MED,
};
static const uint32_t msg_bld_masks_15[] = {
MSG_LVL_MED
};
static const uint32_t msg_bld_masks_16[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL,
MSG_LVL_LOW|MSG_LVL_MED|MSG_LVL_HIGH|MSG_LVL_ERROR|MSG_LVL_FATAL
};
static const uint32_t msg_bld_masks_17[] = {
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED,
MSG_LVL_MED | MSG_MASK_6 | \
MSG_MASK_7 | MSG_MASK_8 | MSG_MASK_9,
MSG_LVL_MED | MSG_MASK_5 | \
MSG_MASK_6 | MSG_MASK_7 | MSG_MASK_8 | MSG_MASK_9 | \
MSG_MASK_10 | MSG_MASK_11 | MSG_MASK_12 | MSG_MASK_13 | \
MSG_MASK_14 | MSG_MASK_15 | MSG_MASK_16 | MSG_MASK_17,
MSG_LVL_MED,
MSG_LVL_MED | MSG_MASK_5 | \
MSG_MASK_6 | MSG_MASK_7 | MSG_MASK_8 | MSG_MASK_9 | \
MSG_MASK_10 | MSG_MASK_11 | MSG_MASK_12 | MSG_MASK_13 | \
MSG_MASK_14 | MSG_MASK_15 | MSG_MASK_16 | MSG_MASK_17 | \
MSG_MASK_18 | MSG_MASK_19 | MSG_MASK_20 | MSG_MASK_21 | \
MSG_MASK_22,
MSG_LVL_MED,
MSG_LVL_MED,
};
static const uint32_t msg_bld_masks_18[] = {
MSG_LVL_LOW,
MSG_LVL_LOW | MSG_MASK_8 | MSG_MASK_9 | MSG_MASK_10 | \
MSG_MASK_11|MSG_MASK_12|MSG_MASK_13|MSG_MASK_14|MSG_MASK_15 | \
MSG_MASK_16|MSG_MASK_17|MSG_MASK_18|MSG_MASK_19|MSG_MASK_20,
MSG_LVL_LOW | MSG_MASK_5 | MSG_MASK_6,
MSG_LVL_LOW | MSG_MASK_5,
MSG_LVL_LOW | MSG_MASK_5 | MSG_MASK_6,
MSG_LVL_LOW,
MSG_LVL_LOW | MSG_MASK_5 | \
MSG_MASK_6 | MSG_MASK_7 | MSG_MASK_8 | MSG_MASK_9,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW
};
static const uint32_t msg_bld_masks_19[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW
};
static const uint32_t msg_bld_masks_20[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW
};
static const uint32_t msg_bld_masks_21[] = {
MSG_LVL_HIGH
};
static const uint32_t msg_bld_masks_22[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW
};
static const uint32_t msg_bld_masks_23[] = {
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW,
MSG_LVL_LOW
};
/* LOG CODES */
static const uint32_t log_code_last_tbl[] = {
0x0, /* EQUIP ID 0 */
0x18DE, /* EQUIP ID 1 */
0x0, /* EQUIP ID 2 */
0x0, /* EQUIP ID 3 */
0x4910, /* EQUIP ID 4 */
0x5420, /* EQUIP ID 5 */
0x0, /* EQUIP ID 6 */
0x74FF, /* EQUIP ID 7 */
0x0, /* EQUIP ID 8 */
0x0, /* EQUIP ID 9 */
0xA38A, /* EQUIP ID 10 */
0xB201, /* EQUIP ID 11 */
0x0, /* EQUIP ID 12 */
0xD1FF, /* EQUIP ID 13 */
0x0, /* EQUIP ID 14 */
0x0, /* EQUIP ID 15 */
};
#define LOG_GET_ITEM_NUM(xx_code) (xx_code & 0x0FFF)
#define LOG_GET_EQUIP_ID(xx_code) ((xx_code & 0xF000) >> 12)
#define LOG_ITEMS_TO_SIZE(num_items) ((num_items+7)/8)
#define LOG_SIZE_TO_ITEMS(size) ((8*size) - 7)
#define EVENT_COUNT_TO_BYTES(count) ((count/8) + 1)
#endif
| HostZero/android_kernel_zuk_msm8996 | include/linux/diagchar.h | C | gpl-2.0 | 19,115 |
// ---------------------------------------------------------------------
//
// Copyright (C) 2003 - 2014 by the deal.II authors
//
// This file is part of the deal.II library.
//
// The deal.II library is free software; you can use it, redistribute
// it, and/or modify it under the terms of the GNU Lesser General
// Public License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
// The full text of the license can be found in the file LICENSE at
// the top level of the deal.II distribution.
//
// ---------------------------------------------------------------------
#include "../tests.h"
#include "dof_tools_common.h"
#include <deal.II/lac/vector.h>
// check
// FE::hp_constraints_are_implemented
// a bit like fe_tools_14, but works on a different set of elements
std::string output_file_name = "output";
template <int dim>
void
check_this (const DoFHandler<dim> &dof_handler)
{
deallog << dof_handler.get_fe().get_name()
<< ": "
<< (dof_handler.get_fe().hp_constraints_are_implemented() ? "true" : "false")
<< std::endl;
}
| pesser/dealii | tests/dofs/hp_constraints_are_implemented.cc | C++ | lgpl-2.1 | 1,147 |
tinyMCE.addI18n('id.simple',{
bold_desc:"Bold (Ctrl+B)",
italic_desc:"Italic (Ctrl+I)",
underline_desc:"Underline (Ctrl+U)",
striketrough_desc:"Strikethrough",
bullist_desc:"Unordered list",
numlist_desc:"Ordered list",
undo_desc:"Undo (Ctrl+Z)",
redo_desc:"Redo (Ctrl+Y)",
cleanup_desc:"Cleanup messy code"
}); | srinivasiyerb/Scholst | target/Scholastic/WEB-INF/classes/org/olat/core/gui/components/form/flexible/impl/elements/richText/_static/js/tinymce/themes/simple/langs/id.js | JavaScript | apache-2.0 | 311 |
/*
* Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
package com.amazonaws.services.dynamodbv2.model.transform;
import static com.amazonaws.util.StringUtils.UTF8;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.OutputStreamWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.util.Map;
import java.util.List;
import com.amazonaws.AmazonClientException;
import com.amazonaws.services.dynamodbv2.model.*;
import com.amazonaws.transform.Marshaller;
import com.amazonaws.util.BinaryUtils;
import com.amazonaws.util.StringUtils;
import com.amazonaws.util.StringInputStream;
import com.amazonaws.util.json.*;
/**
* ProjectionMarshaller
*/
public class ProjectionJsonMarshaller {
/**
* Marshall the given parameter object, and output to a JSONWriter
*/
public void marshall(Projection projection, JSONWriter jsonWriter) {
if (projection == null) {
throw new AmazonClientException(
"Invalid argument passed to marshall(...)");
}
try {
jsonWriter.object();
if (projection.getProjectionType() != null) {
jsonWriter.key("ProjectionType").value(
projection.getProjectionType());
}
java.util.List<String> nonKeyAttributesList = projection
.getNonKeyAttributes();
if (nonKeyAttributesList != null) {
jsonWriter.key("NonKeyAttributes");
jsonWriter.array();
for (String nonKeyAttributesListValue : nonKeyAttributesList) {
if (nonKeyAttributesListValue != null) {
jsonWriter.value(nonKeyAttributesListValue);
}
}
jsonWriter.endArray();
}
jsonWriter.endObject();
} catch (Throwable t) {
throw new AmazonClientException(
"Unable to marshall request to JSON: " + t.getMessage(), t);
}
}
private static ProjectionJsonMarshaller instance;
public static ProjectionJsonMarshaller getInstance() {
if (instance == null)
instance = new ProjectionJsonMarshaller();
return instance;
}
}
| mahaliachante/aws-sdk-java | aws-java-sdk-dynamodb/src/main/java/com/amazonaws/services/dynamodbv2/model/transform/ProjectionJsonMarshaller.java | Java | apache-2.0 | 2,819 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<title>Uses of Class com.microsoft.windowsazure.notifications.NotificationsManager</title>
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class com.microsoft.windowsazure.notifications.NotificationsManager";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../com/microsoft/windowsazure/notifications/package-summary.html">Package</a></li>
<li><a href="../../../../../com/microsoft/windowsazure/notifications/NotificationsManager.html" title="class in com.microsoft.windowsazure.notifications">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/microsoft/windowsazure/notifications/class-use/NotificationsManager.html" target="_top">Frames</a></li>
<li><a href="NotificationsManager.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class com.microsoft.windowsazure.notifications.NotificationsManager" class="title">Uses of Class<br>com.microsoft.windowsazure.notifications.NotificationsManager</h2>
</div>
<div class="classUseContainer">No usage of com.microsoft.windowsazure.notifications.NotificationsManager</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../com/microsoft/windowsazure/notifications/package-summary.html">Package</a></li>
<li><a href="../../../../../com/microsoft/windowsazure/notifications/NotificationsManager.html" title="class in com.microsoft.windowsazure.notifications">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../index-files/index-1.html">Index</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?com/microsoft/windowsazure/notifications/class-use/NotificationsManager.html" target="_top">Frames</a></li>
<li><a href="NotificationsManager.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
| Azure/azure-mobile-apps-android-client | sdk/src/notifications-handler/doc/com/microsoft/windowsazure/notifications/class-use/NotificationsManager.html | HTML | apache-2.0 | 4,123 |
/*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.presto.sql.tree;
import java.util.Objects;
import java.util.Optional;
import static com.google.common.base.MoreObjects.toStringHelper;
import static java.util.Objects.requireNonNull;
public final class CallArgument
extends Node
{
private final Optional<String> name;
private final Expression value;
public CallArgument(Expression value)
{
this(Optional.empty(), Optional.empty(), value);
}
public CallArgument(NodeLocation location, Expression value)
{
this(Optional.of(location), Optional.empty(), value);
}
public CallArgument(String name, Expression value)
{
this(Optional.empty(), Optional.of(name), value);
}
public CallArgument(NodeLocation location, String name, Expression value)
{
this(Optional.of(location), Optional.of(name), value);
}
public CallArgument(Optional<NodeLocation> location, Optional<String> name, Expression value)
{
super(location);
this.name = requireNonNull(name, "name is null");
this.value = requireNonNull(value, "value is null");
}
public Optional<String> getName()
{
return name;
}
public Expression getValue()
{
return value;
}
@Override
public <R, C> R accept(AstVisitor<R, C> visitor, C context)
{
return visitor.visitCallArgument(this, context);
}
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if ((obj == null) || (getClass() != obj.getClass())) {
return false;
}
CallArgument o = (CallArgument) obj;
return Objects.equals(name, o.name) &&
Objects.equals(value, o.value);
}
@Override
public int hashCode()
{
return Objects.hash(name, value);
}
@Override
public String toString()
{
return toStringHelper(this)
.add("name", name.orElse(null))
.add("value", value)
.omitNullValues()
.toString();
}
}
| sunchao/presto | presto-parser/src/main/java/com/facebook/presto/sql/tree/CallArgument.java | Java | apache-2.0 | 2,679 |
package me.kafeitu.activiti.web.chapter13;
import me.kafeitu.activiti.chapter13.Page;
import me.kafeitu.activiti.chapter13.PageUtil;
import me.kafeitu.activiti.chapter6.util.UserUtil;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.identity.User;
import org.activiti.engine.impl.persistence.entity.ExecutionEntity;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.Execution;
import org.activiti.engine.runtime.NativeExecutionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.activiti.engine.task.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 运行中的执行实例Execution
* User: henryyan
*/
@Controller
@RequestMapping("/chapter13")
public class ExecutionController {
@Autowired
RuntimeService runtimeService;
@Autowired
RepositoryService repositoryService;
@Autowired
TaskService taskService;
@Autowired
HistoryService historyService;
/**
* 用户参与过的流程
*
* @return
*/
@RequestMapping("execution/list")
public ModelAndView list(HttpServletRequest request) {
ModelAndView mav = new ModelAndView("chapter13/execution-list");
/* 标准查询
List<ProcessInstance> processInstanceList = runtimeService.createProcessInstanceQuery().list();
List<Execution> list = runtimeService.createExecutionQuery().list();
mav.addObject("list", list);
*/
User user = UserUtil.getUserFromSession(request.getSession());
Page<Execution> page = new Page<Execution>(PageUtil.PAGE_SIZE);
int[] pageParams = PageUtil.init(page, request);
NativeExecutionQuery nativeExecutionQuery = runtimeService.createNativeExecutionQuery();
// native query
String sql = "select distinct * from (select RES.* from ACT_RU_EXECUTION RES left join ACT_HI_TASKINST ART on ART.PROC_INST_ID_ = RES.PROC_INST_ID_ "
+ " left join ACT_HI_PROCINST AHP on AHP.PROC_INST_ID_ = RES.PROC_INST_ID_ "
+ " where SUSPENSION_STATE_ = '1' and (ART.ASSIGNEE_ = #{userId} or AHP.START_USER_ID_ = #{userId}) "
+ " and ACT_ID_ is not null and IS_ACTIVE_ = 'TRUE' order by ART.START_TIME_ desc)";
nativeExecutionQuery.parameter("userId", user.getId());
List<Execution> executionList = nativeExecutionQuery.sql(sql).listPage(pageParams[0], pageParams[1]);
// 查询流程定义对象
Map<String, ProcessDefinition> definitionMap = new HashMap<String, ProcessDefinition>();
// 任务的英文-中文对照
Map<String, Task> taskMap = new HashMap<String, Task>();
// 每个Execution的当前活动ID,可能为多个
Map<String, List<String>> currentActivityMap = new HashMap<String, List<String>>();
// 设置每个Execution对象的当前活动节点
for (Execution execution : executionList) {
ExecutionEntity executionEntity = (ExecutionEntity) execution;
String processInstanceId = executionEntity.getProcessInstanceId();
String processDefinitionId = executionEntity.getProcessDefinitionId();
// 缓存ProcessDefinition对象到Map集合
definitionCache(definitionMap, processDefinitionId);
// 查询当前流程的所有处于活动状态的活动ID,如果并行的活动则会有多个
List<String> activeActivityIds = runtimeService.getActiveActivityIds(execution.getId());
currentActivityMap.put(execution.getId(), activeActivityIds);
for (String activityId : activeActivityIds) {
// 查询处于活动状态的任务
Task task = taskService.createTaskQuery().taskDefinitionKey(activityId).executionId(execution.getId()).singleResult();
// 调用活动
if (task == null) {
ProcessInstance processInstance = runtimeService.createProcessInstanceQuery()
.superProcessInstanceId(processInstanceId).singleResult();
if (processInstance != null) {
task = taskService.createTaskQuery().processInstanceId(processInstance.getProcessInstanceId()).singleResult();
definitionCache(definitionMap, processInstance.getProcessDefinitionId());
}
}
taskMap.put(activityId, task);
}
}
mav.addObject("taskMap", taskMap);
mav.addObject("definitions", definitionMap);
mav.addObject("currentActivityMap", currentActivityMap);
page.setResult(executionList);
page.setTotalCount(nativeExecutionQuery.sql("select count(*) from (" + sql + ")").count());
mav.addObject("page", page);
return mav;
}
/**
* 流程定义对象缓存
*
* @param definitionMap
* @param processDefinitionId
*/
private void definitionCache(Map<String, ProcessDefinition> definitionMap, String processDefinitionId) {
if (definitionMap.get(processDefinitionId) == null) {
ProcessDefinitionQuery processDefinitionQuery = repositoryService.createProcessDefinitionQuery();
processDefinitionQuery.processDefinitionId(processDefinitionId);
ProcessDefinition processDefinition = processDefinitionQuery.singleResult();
// 放入缓存
definitionMap.put(processDefinitionId, processDefinition);
}
}
}
| kutala/activiti-in-action-codes | chapter21-invade/src/main/java/me/kafeitu/activiti/web/chapter13/ExecutionController.java | Java | apache-2.0 | 6,015 |
from django.conf import settings
from django.db.models.signals import post_save
from oscar.core.loading import get_model
def send_product_alerts(sender, instance, created, **kwargs):
if kwargs.get('raw', False):
return
from oscar.apps.customer.alerts import utils
utils.send_product_alerts(instance.product)
if settings.OSCAR_EAGER_ALERTS:
StockRecord = get_model('partner', 'StockRecord')
post_save.connect(send_product_alerts, sender=StockRecord)
| itbabu/django-oscar | src/oscar/apps/customer/alerts/receivers.py | Python | bsd-3-clause | 482 |
<!DOCTYPE html>
<meta charset="UTF-8">
<title>max-width composition</title>
<link rel="help" href="https://drafts.csswg.org/css-sizing-3/#propdef-max-width">
<meta name="assert" content="max-width supports animation by computed value">
<script src="/resources/testharness.js"></script>
<script src="/resources/testharnessreport.js"></script>
<script src="/css/support/interpolation-testcommon.js"></script>
<body>
<script>
test_composition({
property: 'max-width',
underlying: '50px',
addFrom: '100px',
addTo: '200px',
}, [
{at: -0.3, expect: '120px'},
{at: 0, expect: '150px'},
{at: 0.5, expect: '200px'},
{at: 1, expect: '250px'},
{at: 1.5, expect: '300px'},
]);
test_composition({
property: 'max-width',
underlying: '100px',
addFrom: '10px',
addTo: '2px',
}, [
{at: -0.5, expect: '114px'},
{at: 0, expect: '110px'},
{at: 0.5, expect: '106px'},
{at: 1, expect: '102px'},
{at: 1.5, expect: '98px'}, // Value clamping should happen after composition.
]);
test_composition({
property: 'max-width',
underlying: '10%',
addFrom: '100px',
addTo: '20%',
}, [
{at: -0.3, expect: 'calc(130px + 4%)'},
{at: 0, expect: 'calc(100px + 10%)'},
{at: 0.5, expect: 'calc(50px + 20%)'},
{at: 1, expect: '30%'},
{at: 1.5, expect: 'calc(-50px + 40%)'},
]);
test_composition({
property: 'max-width',
underlying: '50px',
addFrom: '100px',
replaceTo: '200px',
}, [
{at: -0.3, expect: '135px'},
{at: 0, expect: '150px'},
{at: 0.5, expect: '175px'},
{at: 1, expect: '200px'},
{at: 1.5, expect: '225px'},
]);
test_composition({
property: 'max-width',
underlying: '100px',
addFrom: '100px',
addTo: 'none',
}, [
{at: -0.3, expect: '200px'},
{at: 0, expect: '200px'},
{at: 0.5, expect: 'none'},
{at: 1, expect: 'none'},
{at: 1.5, expect: 'none'},
]);
</script>
</body>
| scheib/chromium | third_party/blink/web_tests/external/wpt/css/css-sizing/animation/max-width-composition.html | HTML | bsd-3-clause | 1,837 |
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_GUEST_VIEW_BROWSER_GUEST_VIEW_MANAGER_FACTORY_H_
#define COMPONENTS_GUEST_VIEW_BROWSER_GUEST_VIEW_MANAGER_FACTORY_H_
namespace content {
class BrowserContext;
}
namespace guest_view {
class GuestViewManager;
class GuestViewManagerDelegate;
class GuestViewManagerFactory {
public:
virtual GuestViewManager* CreateGuestViewManager(
content::BrowserContext* context,
scoped_ptr<GuestViewManagerDelegate> delegate) = 0;
protected:
virtual ~GuestViewManagerFactory() {}
};
} // namespace guest_view
#endif // COMPONENTS_GUEST_VIEW_BROWSER_GUEST_VIEW_MANAGER_FACTORY_H_
| Chilledheart/chromium | components/guest_view/browser/guest_view_manager_factory.h | C | bsd-3-clause | 777 |
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package lex implements lexical analysis for the assembler.
package lex
import (
"fmt"
"log"
"os"
"strings"
"text/scanner"
"cmd/internal/src"
)
// A ScanToken represents an input item. It is a simple wrapping of rune, as
// returned by text/scanner.Scanner, plus a couple of extra values.
type ScanToken rune
const (
// Asm defines some two-character lexemes. We make up
// a rune/ScanToken value for them - ugly but simple.
LSH ScanToken = -1000 - iota // << Left shift.
RSH // >> Logical right shift.
ARR // -> Used on ARM for shift type 3, arithmetic right shift.
ROT // @> Used on ARM for shift type 4, rotate right.
macroName // name of macro that should not be expanded
)
// IsRegisterShift reports whether the token is one of the ARM register shift operators.
func IsRegisterShift(r ScanToken) bool {
return ROT <= r && r <= LSH // Order looks backwards because these are negative.
}
func (t ScanToken) String() string {
switch t {
case scanner.EOF:
return "EOF"
case scanner.Ident:
return "identifier"
case scanner.Int:
return "integer constant"
case scanner.Float:
return "float constant"
case scanner.Char:
return "rune constant"
case scanner.String:
return "string constant"
case scanner.RawString:
return "raw string constant"
case scanner.Comment:
return "comment"
default:
return fmt.Sprintf("%q", rune(t))
}
}
// NewLexer returns a lexer for the named file and the given link context.
func NewLexer(name string) TokenReader {
input := NewInput(name)
fd, err := os.Open(name)
if err != nil {
log.Fatalf("%s\n", err)
}
input.Push(NewTokenizer(name, fd, fd))
return input
}
// The other files in this directory each contain an implementation of TokenReader.
// A TokenReader is like a reader, but returns lex tokens of type Token. It also can tell you what
// the text of the most recently returned token is, and where it was found.
// The underlying scanner elides all spaces except newline, so the input looks like a stream of
// Tokens; original spacing is lost but we don't need it.
type TokenReader interface {
// Next returns the next token.
Next() ScanToken
// The following methods all refer to the most recent token returned by Next.
// Text returns the original string representation of the token.
Text() string
// File reports the source file name of the token.
File() string
// Base reports the position base of the token.
Base() *src.PosBase
// SetBase sets the position base.
SetBase(*src.PosBase)
// Line reports the source line number of the token.
Line() int
// Col reports the source column number of the token.
Col() int
// Close does any teardown required.
Close()
}
// A Token is a scan token plus its string value.
// A macro is stored as a sequence of Tokens with spaces stripped.
type Token struct {
ScanToken
text string
}
// Make returns a Token with the given rune (ScanToken) and text representation.
func Make(token ScanToken, text string) Token {
// If the symbol starts with center dot, as in ·x, rewrite it as ""·x
if token == scanner.Ident && strings.HasPrefix(text, "\u00B7") {
text = `""` + text
}
// Substitute the substitutes for . and /.
text = strings.Replace(text, "\u00B7", ".", -1)
text = strings.Replace(text, "\u2215", "/", -1)
return Token{ScanToken: token, text: text}
}
func (l Token) String() string {
return l.text
}
// A Macro represents the definition of a #defined macro.
type Macro struct {
name string // The #define name.
args []string // Formal arguments.
tokens []Token // Body of macro.
}
// Tokenize turns a string into a list of Tokens; used to parse the -D flag and in tests.
func Tokenize(str string) []Token {
t := NewTokenizer("command line", strings.NewReader(str), nil)
var tokens []Token
for {
tok := t.Next()
if tok == scanner.EOF {
break
}
tokens = append(tokens, Make(tok, t.Text()))
}
return tokens
}
| codestation/go | src/cmd/asm/internal/lex/lex.go | GO | bsd-3-clause | 4,192 |
#ifndef __ASM_SH_ATOMIC_H
#define __ASM_SH_ATOMIC_H
/*
* Atomic operations that C can't guarantee us. Useful for
* resource counting etc..
*
*/
#include <linux/compiler.h>
#include <linux/types.h>
#include <asm/cmpxchg.h>
#include <asm/barrier.h>
#define ATOMIC_INIT(i) { (i) }
#define atomic_read(v) READ_ONCE((v)->counter)
#define atomic_set(v,i) WRITE_ONCE((v)->counter, (i))
#if defined(CONFIG_GUSA_RB)
#include <asm/atomic-grb.h>
#elif defined(CONFIG_CPU_SH4A)
#include <asm/atomic-llsc.h>
#else
#include <asm/atomic-irq.h>
#endif
#define atomic_add_negative(a, v) (atomic_add_return((a), (v)) < 0)
#define atomic_dec_return(v) atomic_sub_return(1, (v))
#define atomic_inc_return(v) atomic_add_return(1, (v))
#define atomic_inc_and_test(v) (atomic_inc_return(v) == 0)
#define atomic_sub_and_test(i,v) (atomic_sub_return((i), (v)) == 0)
#define atomic_dec_and_test(v) (atomic_sub_return(1, (v)) == 0)
#define atomic_inc(v) atomic_add(1, (v))
#define atomic_dec(v) atomic_sub(1, (v))
#define atomic_xchg(v, new) (xchg(&((v)->counter), new))
#define atomic_cmpxchg(v, o, n) (cmpxchg(&((v)->counter), (o), (n)))
/**
* __atomic_add_unless - add unless the number is a given value
* @v: pointer of type atomic_t
* @a: the amount to add to v...
* @u: ...unless v is equal to u.
*
* Atomically adds @a to @v, so long as it was not @u.
* Returns the old value of @v.
*/
static inline int __atomic_add_unless(atomic_t *v, int a, int u)
{
int c, old;
c = atomic_read(v);
for (;;) {
if (unlikely(c == (u)))
break;
old = atomic_cmpxchg((v), c, c + (a));
if (likely(old == c))
break;
c = old;
}
return c;
}
#endif /* __ASM_SH_ATOMIC_H */
| AiJiaZone/linux-4.0 | virt/arch/sh/include/asm/atomic.h | C | gpl-2.0 | 1,684 |
# JSON implementation for Ruby {<img src="https://secure.travis-ci.org/flori/json.png" />}[http://travis-ci.org/flori/json]
## Description
This is a implementation of the JSON specification according to RFC 4627
http://www.ietf.org/rfc/rfc4627.txt . Starting from version 1.0.0 on there
will be two variants available:
* A pure ruby variant, that relies on the iconv and the stringscan
extensions, which are both part of the ruby standard library.
* The quite a bit faster native extension variant, which is in parts
implemented in C or Java and comes with its own unicode conversion
functions and a parser generated by the ragel state machine compiler
http://www.complang.org/ragel/ .
Both variants of the JSON generator generate UTF-8 character sequences by
default. If an :ascii\_only option with a true value is given, they escape all
non-ASCII and control characters with \uXXXX escape sequences, and support
UTF-16 surrogate pairs in order to be able to generate the whole range of
unicode code points.
All strings, that are to be encoded as JSON strings, should be UTF-8 byte
sequences on the Ruby side. To encode raw binary strings, that aren't UTF-8
encoded, please use the to\_json\_raw\_object method of String (which produces
an object, that contains a byte array) and decode the result on the receiving
endpoint.
The JSON parsers can parse UTF-8, UTF-16BE, UTF-16LE, UTF-32BE, and UTF-32LE
JSON documents under Ruby 1.8. Under Ruby 1.9 they take advantage of Ruby's
M17n features and can parse all documents which have the correct
String#encoding set. If a document string has ASCII-8BIT as an encoding the
parser attempts to figure out which of the UTF encodings from above it is and
trys to parse it.
## Installation
It's recommended to use the extension variant of JSON, because it's faster than
the pure ruby variant. If you cannot build it on your system, you can settle
for the latter.
Just type into the command line as root:
# rake install
The above command will build the extensions and install them on your system.
# rake install_pure
or
# ruby install.rb
will just install the pure ruby implementation of JSON.
If you use Rubygems you can type
# gem install json
instead, to install the newest JSON version.
There is also a pure ruby json only variant of the gem, that can be installed
with:
# gem install json_pure
## Compiling the extensions yourself
If you want to create the parser.c file from its parser.rl file or draw nice
graphviz images of the state machines, you need ragel from:
http://www.complang.org/ragel/
## Usage
To use JSON you can
require 'json'
to load the installed variant (either the extension 'json' or the pure
variant 'json\_pure'). If you have installed the extension variant, you can
pick either the extension variant or the pure variant by typing
require 'json/ext'
or
require 'json/pure'
Now you can parse a JSON document into a ruby data structure by calling
JSON.parse(document)
If you want to generate a JSON document from a ruby data structure call
JSON.generate(data)
You can also use the pretty\_generate method (which formats the output more
verbosely and nicely) or fast\_generate (which doesn't do any of the security
checks generate performs, e. g. nesting deepness checks).
To create a valid JSON document you have to make sure, that the output is
embedded in either a JSON array [] or a JSON object {}. The easiest way to do
this, is by putting your values in a Ruby Array or Hash instance.
There are also the JSON and JSON[] methods which use parse on a String or
generate a JSON document from an array or hash:
document = JSON 'test' => 23 # => "{\"test\":23}"
document = JSON['test'] => 23 # => "{\"test\":23}"
and
data = JSON '{"test":23}' # => {"test"=>23}
data = JSON['{"test":23}'] # => {"test"=>23}
You can choose to load a set of common additions to ruby core's objects if
you
require 'json/add/core'
After requiring this you can, e. g., serialise/deserialise Ruby ranges:
JSON JSON(1..10) # => 1..10
To find out how to add JSON support to other or your own classes, read the
section "More Examples" below.
To get the best compatibility to rails' JSON implementation, you can
require 'json/add/rails'
Both of the additions attempt to require 'json' (like above) first, if it has
not been required yet.
## More Examples
To create a JSON document from a ruby data structure, you can call
JSON.generate like that:
json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
# => "[1,2,{\"a\":3.141},false,true,null,\"4..10\"]"
To get back a ruby data structure from a JSON document, you have to call
JSON.parse on it:
JSON.parse json
# => [1, 2, {"a"=>3.141}, false, true, nil, "4..10"]
Note, that the range from the original data structure is a simple
string now. The reason for this is, that JSON doesn't support ranges
or arbitrary classes. In this case the json library falls back to call
Object#to\_json, which is the same as #to\_s.to\_json.
It's possible to add JSON support serialization to arbitrary classes by
simply implementing a more specialized version of the #to\_json method, that
should return a JSON object (a hash converted to JSON with #to\_json) like
this (don't forget the *a for all the arguments):
class Range
def to_json(*a)
{
'json_class' => self.class.name, # = 'Range'
'data' => [ first, last, exclude_end? ]
}.to_json(*a)
end
end
The hash key 'json\_class' is the class, that will be asked to deserialise the
JSON representation later. In this case it's 'Range', but any namespace of
the form 'A::B' or '::A::B' will do. All other keys are arbitrary and can be
used to store the necessary data to configure the object to be deserialised.
If a the key 'json\_class' is found in a JSON object, the JSON parser checks
if the given class responds to the json\_create class method. If so, it is
called with the JSON object converted to a Ruby hash. So a range can
be deserialised by implementing Range.json\_create like this:
class Range
def self.json_create(o)
new(*o['data'])
end
end
Now it possible to serialise/deserialise ranges as well:
json = JSON.generate [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
# => "[1,2,{\"a\":3.141},false,true,null,{\"json_class\":\"Range\",\"data\":[4,10,false]}]"
JSON.parse json
# => [1, 2, {"a"=>3.141}, false, true, nil, 4..10]
JSON.generate always creates the shortest possible string representation of a
ruby data structure in one line. This is good for data storage or network
protocols, but not so good for humans to read. Fortunately there's also
JSON.pretty\_generate (or JSON.pretty\_generate) that creates a more readable
output:
puts JSON.pretty_generate([1, 2, {"a"=>3.141}, false, true, nil, 4..10])
[
1,
2,
{
"a": 3.141
},
false,
true,
null,
{
"json_class": "Range",
"data": [
4,
10,
false
]
}
]
There are also the methods Kernel#j for generate, and Kernel#jj for
pretty\_generate output to the console, that work analogous to Core Ruby's p and
the pp library's pp methods.
The script tools/server.rb contains a small example if you want to test, how
receiving a JSON object from a webrick server in your browser with the
javasript prototype library http://www.prototypejs.org works.
## Speed Comparisons
I have created some benchmark results (see the benchmarks/data-p4-3Ghz
subdir of the package) for the JSON-parser to estimate the speed up in the C
extension:
Comparing times (call_time_mean):
1 ParserBenchmarkExt#parser 900 repeats:
553.922304770 ( real) -> 21.500x
0.001805307
2 ParserBenchmarkYAML#parser 1000 repeats:
224.513358139 ( real) -> 8.714x
0.004454078
3 ParserBenchmarkPure#parser 1000 repeats:
26.755020642 ( real) -> 1.038x
0.037376163
4 ParserBenchmarkRails#parser 1000 repeats:
25.763381731 ( real) -> 1.000x
0.038814780
calls/sec ( time) -> speed covers
secs/call
In the table above 1 is JSON::Ext::Parser, 2 is YAML.load with YAML
compatbile JSON document, 3 is is JSON::Pure::Parser, and 4 is
ActiveSupport::JSON.decode. The ActiveSupport JSON-decoder converts the
input first to YAML and then uses the YAML-parser, the conversion seems to
slow it down so much that it is only as fast as the JSON::Pure::Parser!
If you look at the benchmark data you can see that this is mostly caused by
the frequent high outliers - the median of the Rails-parser runs is still
overall smaller than the median of the JSON::Pure::Parser runs:
Comparing times (call_time_median):
1 ParserBenchmarkExt#parser 900 repeats:
800.592479481 ( real) -> 26.936x
0.001249075
2 ParserBenchmarkYAML#parser 1000 repeats:
271.002390644 ( real) -> 9.118x
0.003690004
3 ParserBenchmarkRails#parser 1000 repeats:
30.227910865 ( real) -> 1.017x
0.033082008
4 ParserBenchmarkPure#parser 1000 repeats:
29.722384421 ( real) -> 1.000x
0.033644676
calls/sec ( time) -> speed covers
secs/call
I have benchmarked the JSON-Generator as well. This generated a few more
values, because there are different modes that also influence the achieved
speed:
Comparing times (call_time_mean):
1 GeneratorBenchmarkExt#generator_fast 1000 repeats:
547.354332608 ( real) -> 15.090x
0.001826970
2 GeneratorBenchmarkExt#generator_safe 1000 repeats:
443.968212317 ( real) -> 12.240x
0.002252414
3 GeneratorBenchmarkExt#generator_pretty 900 repeats:
375.104545883 ( real) -> 10.341x
0.002665923
4 GeneratorBenchmarkPure#generator_fast 1000 repeats:
49.978706968 ( real) -> 1.378x
0.020008521
5 GeneratorBenchmarkRails#generator 1000 repeats:
38.531868759 ( real) -> 1.062x
0.025952543
6 GeneratorBenchmarkPure#generator_safe 1000 repeats:
36.927649925 ( real) -> 1.018x 7 (>=3859)
0.027079979
7 GeneratorBenchmarkPure#generator_pretty 1000 repeats:
36.272134441 ( real) -> 1.000x 6 (>=3859)
0.027569373
calls/sec ( time) -> speed covers
secs/call
In the table above 1-3 are JSON::Ext::Generator methods. 4, 6, and 7 are
JSON::Pure::Generator methods and 5 is the Rails JSON generator. It is now a
bit faster than the generator\_safe and generator\_pretty methods of the pure
variant but slower than the others.
To achieve the fastest JSON document output, you can use the fast\_generate
method. Beware, that this will disable the checking for circular Ruby data
structures, which may cause JSON to go into an infinite loop.
Here are the median comparisons for completeness' sake:
Comparing times (call_time_median):
1 GeneratorBenchmarkExt#generator_fast 1000 repeats:
708.258020939 ( real) -> 16.547x
0.001411915
2 GeneratorBenchmarkExt#generator_safe 1000 repeats:
569.105020353 ( real) -> 13.296x
0.001757145
3 GeneratorBenchmarkExt#generator_pretty 900 repeats:
482.825371244 ( real) -> 11.280x
0.002071142
4 GeneratorBenchmarkPure#generator_fast 1000 repeats:
62.717626652 ( real) -> 1.465x
0.015944481
5 GeneratorBenchmarkRails#generator 1000 repeats:
43.965681162 ( real) -> 1.027x
0.022745013
6 GeneratorBenchmarkPure#generator_safe 1000 repeats:
43.929073409 ( real) -> 1.026x 7 (>=3859)
0.022763968
7 GeneratorBenchmarkPure#generator_pretty 1000 repeats:
42.802514491 ( real) -> 1.000x 6 (>=3859)
0.023363113
calls/sec ( time) -> speed covers
secs/call
## Author
Florian Frank <mailto:[email protected]>
## License
Ruby License, see https://www.ruby-lang.org/en/about/license.txt.
## Download
The latest version of this library can be downloaded at
* https://rubygems.org/gems/json
Online Documentation should be located at
* http://json.rubyforge.org
| 0x6368/LIFred | workflow/bundle/ruby/2.3.0/gems/json-1.8.6/README.md | Markdown | mit | 12,248 |
// Boost.Geometry
// Copyright (c) 2014 Adam Wulkiewicz, Lodz, Poland.
// 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)
#ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_INTERIOR_ITERATOR_HPP
#define BOOST_GEOMETRY_ALGORITHMS_DETAIL_INTERIOR_ITERATOR_HPP
#include <boost/range/iterator.hpp>
#include <boost/range/value_type.hpp>
#include <boost/geometry/core/interior_type.hpp>
namespace boost { namespace geometry
{
#ifndef DOXYGEN_NO_DETAIL
namespace detail
{
/*!
\brief Structure defining the type of interior rings iterator
\note If the Geometry is const, const iterator is defined.
\tparam Geometry \tparam_geometry
*/
template <typename Geometry>
struct interior_iterator
{
typedef typename boost::range_iterator
<
typename geometry::interior_type<Geometry>::type
>::type type;
};
template <typename BaseT, typename T>
struct copy_const
{
typedef T type;
};
template <typename BaseT, typename T>
struct copy_const<BaseT const, T>
{
typedef T const type;
};
template <typename Geometry>
struct interior_ring_iterator
{
typedef typename boost::range_iterator
<
typename copy_const
<
typename geometry::interior_type<Geometry>::type,
typename boost::range_value
<
typename geometry::interior_type<Geometry>::type
>::type
>::type
>::type type;
};
} // namespace detail
#endif // DOXYGEN_NO_DETAIL
}} // namespace boost::geometry
#endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_INTERIOR_ITERATOR_HPP
| nginnever/zogminer | tests/deps/boost/geometry/algorithms/detail/interior_iterator.hpp | C++ | mit | 1,839 |
'use strict';
/**
* Runner for scenarios
*
* Has to be initialized before any test is loaded,
* because it publishes the API into window (global space).
*/
angular.scenario.Runner = function($window) {
this.listeners = [];
this.$window = $window;
this.rootDescribe = new angular.scenario.Describe();
this.currentDescribe = this.rootDescribe;
this.api = {
it: this.it,
iit: this.iit,
xit: angular.noop,
describe: this.describe,
ddescribe: this.ddescribe,
xdescribe: angular.noop,
beforeEach: this.beforeEach,
afterEach: this.afterEach
};
angular.forEach(this.api, angular.bind(this, /** @this */ function(fn, key) {
this.$window[key] = angular.bind(this, fn);
}));
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.Runner.prototype.emit = function(eventName) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
eventName = eventName.toLowerCase();
if (!this.listeners[eventName]) {
return;
}
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
};
/**
* Adds a listener for an event.
*
* @param {string} eventName The name of the event to add a handler for
* @param {string} listener The fn(...) that takes the extra arguments from emit()
*/
angular.scenario.Runner.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Defines a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.describe = function(name, body) {
var self = this;
this.currentDescribe.describe(name, /** @this */ function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Same as describe, but makes ddescribe the only blocks to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.ddescribe = function(name, body) {
var self = this;
this.currentDescribe.ddescribe(name, /** @this */ function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Defines a test in a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.it = function(name, body) {
this.currentDescribe.it(name, body);
};
/**
* Same as it, but makes iit tests the only tests to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.iit = function(name, body) {
this.currentDescribe.iit(name, body);
};
/**
* Defines a function to be called before each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.beforeEach = function(body) {
this.currentDescribe.beforeEach(body);
};
/**
* Defines a function to be called after each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.afterEach = function(body) {
this.currentDescribe.afterEach(body);
};
/**
* Creates a new spec runner.
*
* @private
* @param {Object} scope parent scope
*/
angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
var child = scope.$new();
var Cls = angular.scenario.SpecRunner;
// Export all the methods to child scope manually as now we don't mess controllers with scopes
// TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
for (var name in Cls.prototype) {
child[name] = angular.bind(child, Cls.prototype[name]);
}
Cls.call(child);
return child;
};
/**
* Runs all the loaded tests with the specified runner class on the
* provided application.
*
* @param {angular.scenario.Application} application App to remote control.
*/
angular.scenario.Runner.prototype.run = function(application) {
var self = this;
var $root = angular.injector(['ng']).get('$rootScope');
angular.extend($root, this);
angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
$root[name] = angular.bind(self, fn);
});
$root.application = application;
$root.emit('RunnerBegin');
asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
var dslCache = {};
var runner = self.createSpecRunner_($root);
angular.forEach(angular.scenario.dsl, function(fn, key) {
dslCache[key] = fn.call($root);
});
angular.forEach(angular.scenario.dsl, function(fn, key) {
self.$window[key] = function() {
var line = callerFile(3);
var scope = runner.$new();
// Make the dsl accessible on the current chain
scope.dsl = {};
angular.forEach(dslCache, function(fn, key) {
scope.dsl[key] = function() {
return dslCache[key].apply(scope, arguments);
};
});
// Make these methods work on the current chain
scope.addFuture = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFuture.apply(scope, arguments);
};
scope.addFutureAction = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFutureAction.apply(scope, arguments);
};
return scope.dsl[key].apply(scope, arguments);
};
});
runner.run(spec, /** @this */ function() {
runner.$destroy();
specDone.apply(this, arguments);
});
},
function(error) {
if (error) {
self.emit('RunnerError', error);
}
self.emit('RunnerEnd');
});
};
| Aremyst/angular.js | src/ngScenario/Runner.js | JavaScript | mit | 6,393 |
import * as React from 'react';
import {
BrowserRouter as Router,
RouteComponentProps,
RouteProps,
Route,
Link,
Redirect,
withRouter
} from 'react-router-dom';
////////////////////////////////////////////////////////////
// 1. Click the public page
// 2. Click the protected page
// 3. Log in
// 4. Click the back button, note the URL each time
const AuthExample = () => (
<Router>
<div>
<AuthButton/>
<ul>
<li><Link to="/public">Public Page</Link></li>
<li><Link to="/protected">Protected Page</Link></li>
</ul>
<Route path="/public" component={Public}/>
<Route path="/login" component={Login}/>
<PrivateRoute path="/protected" component={Protected}/>
</div>
</Router>
);
const fakeAuth = {
isAuthenticated: false,
authenticate(this: any, cb: () => void) {
this.isAuthenticated = true;
setTimeout(cb, 100); // fake async
},
signout(this: any, cb: () => void) {
this.isAuthenticated = false;
setTimeout(cb, 100);
}
};
const AuthButton = withRouter(({ history }) => (
fakeAuth.isAuthenticated ? (
<p>
Welcome! <button onClick={() => {
fakeAuth.signout(() => history.push('/'));
}}>Sign out</button>
</p>
) : (
<p>You are not logged in.</p>
)
));
const PrivateRoute: React.SFC<RouteProps> = ({ component, ...rest }) => (
<Route {...rest} render={props => (
fakeAuth.isAuthenticated ? React.createElement(component! as React.SFC<any>, props) : (
<Redirect to={{
pathname: '/login',
state: { from: props.location }
}}/>
)
)}/>
);
const Public: React.SFC<RouteComponentProps<void>> = () => <h3>Public</h3>;
const Protected: React.SFC<RouteComponentProps<void>> = () => <h3>Protected</h3>;
class Login extends React.Component<RouteComponentProps<void>, {redirectToReferrer: boolean}> {
state = {
redirectToReferrer: false
};
login = () => {
fakeAuth.authenticate(() => {
this.setState({ redirectToReferrer: true });
});
}
render() {
const { from } = this.props.location.state || { from: { pathname: '/' } };
const { redirectToReferrer } = this.state;
if (redirectToReferrer) {
return (
<Redirect to={from}/>
);
}
return (
<div>
<p>You must log in to view the page at {from.pathname}</p>
<button onClick={this.login}>Log in</button>
</div>
);
}
}
export default AuthExample;
| amir-arad/DefinitelyTyped | types/react-router/test/examples-from-react-router-website/Auth.tsx | TypeScript | mit | 2,464 |
// Type definitions for react-swf
// Project: https://github.com/syranide/react-swf
// Definitions by: Stepan Mikhaylyuk <https://github.com/stepancar>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
// TypeScript Version: 2.1
import * as React from 'react';
export as namespace ReactSWF;
declare const self: typeof rswf.ReactSWF;
export = self;
declare namespace rswf {
interface State {
}
interface Props {
/**
* Specifies the source location (URL) of the SWF file to load.
*/
src: string;
/**
* Identifies the location of the Flash Player plug-in so that the user can download it if it is not already installed.
*/
pluginspage?:string
/**
* Specifies the width of the SWF content in either pixels or percentage of browser window.
*/
width?: number;
/**
* Specifies the height of the SWF content in either pixels or percentage of browser window.
*/
height?: number;
/**
* (attribute for OBJECT tag) and name (attribute for EMBED tag) - SWF file identifier. Identifies the SWF file to the web browser, allowing browser scripting languages (for example, JavaScript) to reference the SWF content. For cross-browser compatibility, make sure that the id and name are set to the same value.
*/
id?: string;
/**
* Specifies whether a timeline-based SWF file begins playing immediately on loading in the browser. If this attribute is omitted, the default value is true.
*/
play?: boolean;
/**
* Specifies whether a timeline-based SWF file repeats indefinitely or stops when it reaches the last frame. If this attribute is omitted, the default value is true.
*/
loop?: boolean;
/**
* Specifies if movie playback controls are available in the Flash Player context menu.
* true displays a full menu that provides expanded movie playback controls (for example, Zoom, Quality, Play, Loop, Rewind, Forward, Back).
* false displays a menu that hides movie playback controls (for example, Zoom, Quality, Play, Loop, Rewind, Forward, Back). This attribute is useful for SWF content that does not rely on the Timeline, such as content controlled entirely by ActionScript. The short menu includes "Settings" and "About Flash Player" menu items.
*/
menu?: boolean;
/**
* Possible values: low, autolow, autohigh, medium, high, best. Specifies the display list Stage rendering quality. Setting the Stage.quality property via ActionScript overrides this value.
* low favors playback speed over appearance and never uses anti-aliasing.
* autolow emphasizes speed at first but improves appearance whenever possible. Playback begins with anti-aliasing turned off. If Flash Player detects that the processor can handle it, anti-aliasing is turned on.
* autohigh emphasizes playback speed and appearance equally at first but sacrifices appearance for playback speed if necessary. Playback begins with anti-aliasing turned on. If the actual frame rate drops below the specified frame rate, anti-aliasing is turned off to improve playback speed. Use this setting to emulate the View > Antialias setting in Flash Professional.
* medium applies some anti-aliasing and does not smooth bitmaps. It produces a better quality than the Low setting, but lower quality than the High setting.
* high favors appearance over playback speed and always applies anti-aliasing. If the movie does not contain animation, bitmaps are smoothed; if the movie has animation, bitmaps are not smoothed.
* best provides the best display quality and does not consider playback speed. All output is anti-aliased and all bitmaps are smoothed.
*/
quality?: string;
/**
* Possible values: showall, noborder, exactfit, noscale. Specifies how Flash Player scales SWF content to fit the pixel area specified by the OBJECT or EMBED tag.
* default (Show all) makes the entire SWF file visible in the specified area without distortion, while maintaining the original aspect ratio of the movie. Borders can appear on two sides of the movie.
* noborder scales the SWF file to fill the specified area, while maintaining the original aspect ratio of the file. Flash Player can crop the content, but no distortion occurs.
* exactfit makes the entire SWF file visible in the specified area without trying to preserve the original aspect ratio. Distortion can occur.
* noscale prevents the SWF file from scaling to fit the area of the OBJECT or EMBED tag. Cropping can occur.
*/
scale?: string;
/**
* (attribute for Object) - Possible values: l, t, r.
* Default centers the movie in the browser window and crops edges if the browser window is smaller than the movie.
* l (left), r (right), and t (top) align the movie along the corresponding edge of the browser window and crop the remaining three sides as needed.
*/
align?: string;
/**
* Possible values: l, t, r, tl, tr.
* l, r, and t align the movie along the left, right, or top edge of the browser window and crop the remaining sides as needed.
* tl and tr align the movie to the upper-left and top upper-corner of the browser window and crop the bottom and remaining side as necessary.
*/
salign?: string;
/**
* Possible values: window, direct, opaque, transparent, gpu. Sets the Window Mode property of the SWF file for transparency, layering, positioning, and rendering in the browser. If this attribute is omitted, the default value is "window". For more information, see Using Window Mode (wmode) values below.
* window - The SWF content plays in its own rectangle ("window") on a web page. The browser determines how the SWF content is layered against other HTML elements. With this value, you cannot explicitly specify if SWF content appears above or below other HTML elements on the page.
* direct - Use direct to path rendering. This attribute bypasses compositing in the screen buffer and renders the SWF content directly to the screen. This wmode value is recommended to provide the best performance for content playback. It enables hardware accelerated presentation of SWF content that uses Stage Video or Stage 3D.
* opaque - The SWF content is layered together with other HTML elements on the page. The SWF file is opaque and hides everything layered behind it on the page. This option reduces playback performance compared to wmode=window or wmode=direct.
* transparent - The SWF content is layered together with other HTML elements on the page. The SWF file background color (Stage color) is transparent. HTML elements beneath the SWF file are visible through any transparent areas of the SWF, with alpha blending. This option reduces playback performance compared to wmode=window or wmode=direct.
* gpu - Use additional hardware acceleration on some Internet-connected TVs and mobile devices. In contrast to other wmode values, pixel fidelity for display list graphics is not guaranteed. Otherwise, this value is similar to wmode=direct.
*/
wmode?: string;
/**
* [hexadecimal RGB value] in the format #RRGGBB. Specifies the background color of the SWF content. Use this attribute to override the background color (Stage color) setting specified in the SWF file. (This attribute does not affect the background color of the HTML page.)
*/
bgcolor?: string;
/**
* [base directory] or [URL]. Specifies the base directory or URL used to resolve all relative path statements in the SWF file. This attribute is helpful when your SWF file is kept in a different directory from your other files.
*/
base?: string;
/**
* Setting this value to true allows the SWF file to enter full screen mode via ActionScript. For more information, see Exploring full screen mode in Flash Player. If this attribute is omitted, the default value is false.
*/
allowFullScreen?: boolean;
/**
* Possible values: portrait or landscape. Used to control how full screen SWF content appears on mobile devices that support automatic screen rotation, such as phones and tablets. If this attribute is specified, Flash Player uses the specified screen orientation (portrait or landscape) when the SWF is viewed in full screen mode. It doesn't matter how the device is oriented. If this attribute is not specified, orientation of content in full screen mode follows the screen orientation used by the browser.
*/
fullScreenAspectRatio?: string;
/**
* Variables, defined as a string of key=value pairs, that are passed to the SWF file.
* Use flashvars to specify root-level variables in the SWF file. The format of the string is a set of key=value combinations separated by the '&' character.
* Browsers support string sizes of up to 64 KB (65535 bytes) in length.
* For more information on using flashvars, see Using FlashVars to pass variables to a SWF (tn_16417).
*/
flashVars?: Object | string
}
export class ReactSWF extends React.Component<Props, State>{
/**
* Returns the Flash Player object DOM node.
* Should be prefered over `React.findDOMNode`.
* @return {?DOMNode} Flash Player object DOM node.
*/
getFPDOMNode(): Node
/**
* Returns installed Flash Player version. Result is cached.
* Must not be called in a non-browser environment.
* @return {?string} 'X.Y.Z'-version or null.
*/
static getFPVersion(): string
/**
* Returns if installed Flash Player meets version requirement.
* Must not be called in a non-browser environment.
* @return {boolean} true if supported
*/
static isFPVersionSupported(versionString: string): boolean
}
}
| smrq/DefinitelyTyped | types/react-swf/index.d.ts | TypeScript | mit | 10,176 |
export { FolderDetailsReference20 as default } from "../../";
| markogresak/DefinitelyTyped | types/carbon__icons-react/es/folder--details--reference/20.d.ts | TypeScript | mit | 62 |
/**
* Copyright (c) 1997, 2015 by ProSyst Software GmbH and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.smarthome.automation.internal.commands;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
/**
* This class contains methods for facilitating sorting and filtering lists stored in {@link Hashtable}s.
*
* @author Ana Dimova - Initial Contribution
*
*/
public class Utils {
/**
* These constants are used for drawing the table borders.
*/
static final String ROW_END = "\n";
static final char FILLER = ' ';
static final char TABLE_DELIMITER = '-';
/**
* This method puts in a map, the UIDs of the automation objects. Keys are corresponding to the index into the
* array with strings, which is lexicographically sorted.
*
* @param strings holds the list with sorted lexicographically strings.
* @return an indexed UIDs of the automation objects.
*/
static Map<String, String> putInHastable(String[] strings) {
Hashtable<String, String> sorted = new Hashtable<String, String>();
for (int i = 0; i < strings.length; i++) {
sorted.put(new Integer(i + 1).toString(), strings[i]);
}
return sorted;
}
/**
* This method uses the map, indicated by the parameter <tt>listObjects</tt> for filtering the map, indicated by the
* parameter <tt>listUIDs</tt>. After that the map with UIDs of the objects will correspond to the map with the
* objects.
*
* @param listObjects holds the list with the objects for filter criteria.
* @param listUIDs holds the list with UIDs of the objects for filtering.
* @return filtered list with UIDs of the objects.
*/
static Map<String, String> filterList(Map<String, ?> listObjects, Map<String, String> listUIDs) {
Hashtable<String, String> filtered = new Hashtable<String, String>();
for (String id : listUIDs.keySet()) {
String uid = listUIDs.get(id);
Object obj = listObjects.get(uid);
if (obj != null) {
filtered.put(id, uid);
}
}
return filtered;
}
/**
* This method is responsible for the printing of a table with the number and width of the columns,
* as indicated by the parameter of the method <tt>columnWidths</tt> and the content of the columns,
* indicated by the parameter <tt>values</tt>. The table has title with rows, indicated by the
* parameter of the method <tt>titleRows</tt>.
*
* @param columnWidths represents the number and width of the columns of the table.
* @param values contain the rows of the table.
* @param titleRow contain the rows representing the title of the table.
* @return a string representing the table content
*/
static String getTableContent(int width, int[] columnWidths, List<String> values, String titleRow) {
StringBuilder sb = new StringBuilder();
List<String> tableRows = collectTableRows(width, columnWidths, values, titleRow);
for (String tableRow : tableRows) {
sb.append(tableRow + ROW_END);
}
return sb.toString();
}
/**
* This method is responsible for collecting the content of the rows of a table.
*
* @param width represents the table width.
* @param columnWidths represents the number and width of the columns of the table.
* @param values contain the rows of the table.
* @param titleRow contain the title of the table.
* @return a list with strings representing the rows of a table.
*/
static List<String> collectTableRows(int width, int[] columnWidths, List<String> values, String titleRow) {
List<String> tableRows = getTableTitle(titleRow, width);
for (String value : values) {
tableRows.add(value);
}
tableRows.add(getTableBottom(width));
return tableRows;
}
/**
* This method is responsible for the printing of a row of a table with the number and width of the columns,
* as indicated by the parameter of the method <tt>columnWidths</tt> and the content of the columns, indicated by
* the parameter <tt>values</tt>.
*
* @param columnWidths indicates the number and width of the columns of the table.
* @param values indicates the content of the columns of the table.
* @return a string representing the row of the table.
*/
static String getRow(int[] columnWidths, List<String> values) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < columnWidths.length; i++) {
sb.append(getColumn(columnWidths[i], values.get(i)));
}
return sb.toString();
}
/**
* This method is responsible for the printing a title of a table with width specified by the parameter of
* the method - <tt>width</tt> and content specified by the parameter of the method - <tt>titleRows</tt>.
*
* @param titleRow specifies the content of the title.
* @param width specifies the width of the table.
* @return a string representing the title of the table.
*/
static List<String> getTableTitle(String titleRow, int width) {
List<String> res = new ArrayList<String>();
res.add(printChars(TABLE_DELIMITER, width));
res.add(titleRow);
res.add(printChars(TABLE_DELIMITER, width));
return res;
}
/**
* This method is responsible for the printing a bottom of a table with width specified by the parameter of
* the method - <tt>width</tt>.
*
* @param width specifies the width of the table.
* @return a string representing the bottom of the table.
*/
static String getTableBottom(int width) {
return printChars(TABLE_DELIMITER, width);
}
/**
* This method is responsible for the printing a Column with width specified by the parameter of
* the method - <tt>width</tt> and content specified by the parameter of the method - <tt>value</tt>.
*
* @param width specifies the width of the column.
* @param value specifies the content of the column.
* @return a string representing the column value of the table.
*/
static String getColumn(int width, String value) {
value = value + FILLER;
return value + printChars(FILLER, width - value.length());
}
/**
* This method is responsible for the printing a symbol - <tt>ch</tt> as many times as specified by the parameter of
* the method - <tt>count</tt>.
*
* @param ch the specified symbol.
* @param count specifies how many times to append the specified symbol.
* @return a string containing the symbol - <tt>ch</tt> as many times is specified.
*/
static String printChars(char ch, int count) {
if (count < 1) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < count; i++) {
sb.append(ch);
}
return sb.toString();
}
/**
* This method sorts lexicographically the strings.
*
* @param strings holds the list with strings for sorting and indexing.
*/
static void quickSort(String[] strings, int begin, int length) {
int i, j, leftLength, rightLength, t;
String x;
while (length >= 3) {
t = length - 1;
j = t + begin;
i = (t >> 1) + begin;
sort3(strings, begin, i, j);
if (length == 3) {
return;
}
x = strings[i];
i = begin + 1;
j--;
do {
while (strings[i].compareTo(x) < 0) {
i++;
}
while (strings[j].compareTo(x) > 0) {
j--;
}
if (i < j) {
swap(strings, i, j);
} else {
if (i == j) {
i++;
j--;
}
break;
}
} while (++i <= --j);
leftLength = (j - begin) + 1;
rightLength = (begin - i) + length;
if (leftLength < rightLength) {
if (leftLength > 1) {
quickSort(strings, begin, leftLength);
}
begin = i;
length = rightLength;
} else {
if (rightLength > 1) {
quickSort(strings, i, rightLength);
}
length = leftLength;
}
}
if (length == 2 && strings[begin].compareTo(strings[begin + 1]) > 0) {
swap(strings, begin, begin + 1);
}
}
/**
* Auxiliary method for sorting lexicographically the strings at the positions x, y and z.
*
* @param a represents the array with the strings for sorting.
* @param x position of the first string.
* @param y position of the second string.
* @param z position of the third string.
*/
private static void sort3(String[] a, int x, int y, int z) {
if (a[x].compareTo(a[y]) > 0) {
if (a[x].compareTo(a[z]) > 0) {
if (a[y].compareTo(a[z]) > 0) {
swap(a, x, z);
} else {
swap3(a, x, y, z);
}
} else {
swap(a, x, y);
}
} else if (a[x].compareTo(a[z]) > 0) {
swap3(a, x, z, y);
} else if (a[y].compareTo(a[z]) > 0) {
swap(a, y, z);
}
}
/**
* Auxiliary method for sorting lexicographically the strings. Shuffling strings on positions x and y, as the string
* at the position x, goes to the position y, the string at the position y, goes to the position x.
*
* @param a represents the array with the strings for sorting.
* @param x position of the first string.
* @param y position of the second string.
*/
private static void swap(String[] a, int x, int y) {
String t = a[x];
a[x] = a[y];
a[y] = t;
}
/**
* Auxiliary method for sorting lexicographically the strings. Shuffling strings on positions x, y and z, as the
* string
* at the position x, goes to the position z, the string at the position y, goes to the position x and the string
* at the position z, goes to the position y.
*
* @param a represents the array with the strings for sorting.
* @param x position of the first string.
* @param y position of the second string.
* @param z position of the third string.
*/
private static void swap3(String[] a, int x, int y, int z) {
String t = a[x];
a[x] = a[y];
a[y] = a[z];
a[z] = t;
}
}
| marinmitev/smarthome | bundles/automation/org.eclipse.smarthome.automation.commands/src/main/java/org/eclipse/smarthome/automation/internal/commands/Utils.java | Java | epl-1.0 | 11,168 |
! { dg-do compile { target i?86-*-* x86_64-*-* } }
! { dg-additional-options "-O3 -march=core2 -mavx -ffast-math -mveclibabi=svml" }
integer index(18),i,j,k,l,ipiv(18),info,ichange,neq,lda,ldb,
& nrhs,iplas
real*8 ep0(6),al10(18),al20(18),dg0(18),ep(6),al1(18),
& al2(18),dg(18),ddg(18),xm(6,18),h(18,18),ck(18),cn(18),
& c(18),d(18),phi(18),delta(18),r0(18),q(18),b(18),cphi(18),
& q1(18),q2(18),stri(6),htri(18),sg(18),r(42),xmc(6,18),aux(18),
& t(42),gl(18,18),gr(18,18),ee(6),c1111,c1122,c1212,dd,
& skl(3,3),xmtran(3,3),ddsdde(6,6),xx(6,18)
do
do i=1,18
htri(i)=dabs(sg(i))-r0(i)-ck(i)*(dg(i)/dtime)**(1.d0/cn(i))
do j=1,18
enddo
enddo
do
if(i.ne.j) then
gr(index(i),1)=htri(i)
endif
call dgesv(neq,nrhs,gl,lda,ipiv,gr,ldb,info)
enddo
enddo
end
| mickael-guene/gcc | gcc/testsuite/gfortran.dg/vect/pr45714-a.f | FORTRAN | gpl-2.0 | 953 |
<?php
/**
* Tests for various filters.
*/
exit;
/*
* Append the term images to content + excerpt.
*/
function mytheme_append_the_term_images( $content ) {
return $content . apply_filters( 'taxonomy-images-list-the-terms', '', array(
'image_size' => 'detail',
) );
}
add_filter( 'the_content', 'mytheme_append_the_term_images' );
add_filter( 'the_excerpt', 'mytheme_append_the_term_images' );
/*
* Queried Term Image.
*
* Return html markup representing the image associated with the
* currently queried term. In the event that no associated image
* exists, the filter should return an empty object.
*
* In the event that the Taxonomy Images plugin is not installed
* apply_filters() will return it's second parameter.
*/
/* Default */
$img = apply_filters( 'taxonomy-images-queried-term-image', 'PLEASE INSTALL PLUGIN' );
print '<h2>taxonomy-images-queried-term-image</h2>';
print '<pre>' . htmlentities( $img ) . '</pre>';
/* Inside a yellow box */
$img = apply_filters( 'taxonomy-images-queried-term-image', 'PLEASE INSTALL PLUGIN', array(
'before' => '<div style="padding:20px;background-color:yellow;">',
'after' => '</div>',
) );
print '<h2>taxonomy-images-queried-term-image - custom wrapper element.</h2>';
print '<pre>' . htmlentities( $img ) . '</pre>';
/* Medium Size */
$img = apply_filters( 'taxonomy-images-queried-term-image', 'PLEASE INSTALL PLUGIN', array(
'image_size' => 'medium',
) );
print '<h2>taxonomy-images-queried-term-image - medium image size</h2>';
print '<pre>' . htmlentities( $img ) . '</pre>';
/* Unrecognized size */
$img = apply_filters( 'taxonomy-images-queried-term-image', 'PLEASE INSTALL PLUGIN', array(
'image_size' => 'this-is-probably-not-a-real-image-size',
) );
print '<h2>taxonomy-images-queried-term-image - unknown image size</h2>';
print '<pre>' . htmlentities( $img ) . '</pre>';
/* Custom attributes. */
$img = apply_filters( 'taxonomy-images-queried-term-image', 'PLEASE INSTALL PLUGIN', array(
'attr' => array(
'alt' => 'Custom alternative text',
'class' => 'my-class-list bunnies turtles',
'src' => 'this-is-where-the-image-lives.png',
'title' => 'Custom Title',
),
) );
print '<h2>taxonomy-images-queried-term-image - custom attributes</h2>';
print '<pre>' . htmlentities( $img ) . '</pre>';
/*
* Queried Term Image ID.
*
* Return the id of the image associated with the currently
* queried term. In the event that no associated image exists,
* the filter should return zero.
*
* In the event that the Taxonomy Images plugin is not installed
* apply_filters() will return it's second parameter.
*/
$img = apply_filters( 'taxonomy-images-queried-term-image-id', 'PLEASE INSTALL PLUGIN' );
print '<h2>taxonomy-images-queried-term-image-id</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/*
* Queried Term Image Object.
*
* Return an object representing the image associated with the
* currently queried term. In the event that no associated image
* exists, the filter should return an empty object.
*
* In the event that the Taxonomy Images plugin is not installed
* apply_filters() will return it's second parameter.
*/
$img = apply_filters( 'taxonomy-images-queried-term-image-object', 'PLEASE INSTALL PLUGIN' );
print '<h2>taxonomy-images-queried-term-image-object</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/*
* Queried Term Image URL.
*
* Return a url to the image associated with the current queried
* term. In the event that no associated image exists, the filter
* should return an empty string.
*
* In the event that the Taxonomy Images plugin is not installed
* apply_filters() will return it's second parameter.
*/
/* Default */
$img = apply_filters( 'taxonomy-images-queried-term-image-url', 'PLEASE INSTALL PLUGIN' );
print '<h2>taxonomy-images-queried-term-image-url - Default</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/* Medium Size */
$img = apply_filters( 'taxonomy-images-queried-term-image-url', 'PLEASE INSTALL PLUGIN', array(
'image_size' => 'medium'
) );
print '<h2>taxonomy-images-queried-term-image-url - Medium</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/* Unregistered Size */
$img = apply_filters( 'taxonomy-images-queried-term-image-url', 'PLEASE INSTALL PLUGIN', array(
'image_size' => 'this-is-not-real-size-probably-I-hope'
) );
print '<h2>taxonomy-images-queried-term-image-url - Unregistered</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/*
* Queried Term Image Data.
*
* Return an array of data about the image associated with the current
* queried term. In the event that no associated image exists, the filter
* should return an empty string.
*
* In the event that the Taxonomy Images plugin is not installed
* apply_filters() will return it's second parameter.
*/
/* Default */
$img = apply_filters( 'taxonomy-images-queried-term-image-data', 'PLEASE INSTALL PLUGIN' );
print '<h2>taxonomy-images-queried-term-image-data - Default</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/* Medium Size */
$img = apply_filters( 'taxonomy-images-queried-term-image-data', 'PLEASE INSTALL PLUGIN', array(
'image_size' => 'medium'
) );
print '<h2>taxonomy-images-queried-term-image-data - Medium</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
/* Unregistered Size */
$img = apply_filters( 'taxonomy-images-queried-term-image-data', 'PLEASE INSTALL PLUGIN', array(
'image_size' => 'this-is-not-real-size-probably-I-hope'
) );
print '<h2>taxonomy-images-queried-term-image-data - Unregistered</h2>';
print '<pre>'; var_dump( $img ); print '</pre>';
| silasakk/flynow | wp-content/themes/luxroyal/libraries/taxonomy-images/code-snippets.php | PHP | gpl-2.0 | 5,631 |
<?php
/**
* @package Joomla.Platform
* @subpackage Session
*
* @copyright Copyright (C) 2005 - 2012 Open Source Matters, Inc. All rights reserved.
* @license GNU General Public License version 2 or later; see LICENSE
*/
defined('JPATH_PLATFORM') or die;
/**
* Memcached session storage handler for PHP
*
* @package Joomla.Platform
* @subpackage Session
* @since 11.1
*/
class JSessionStorageMemcached extends JSessionStorage
{
/**
* Constructor
*
* @param array $options Optional parameters.
*
* @since 11.1
* @throws RuntimeException
*/
public function __construct($options = array())
{
if (!self::isSupported())
{
throw new RuntimeException('Memcached Extension is not available', 404);
}
parent::__construct($options);
$config = JFactory::getConfig();
// This will be an array of loveliness
// @todo: multiple servers
$this->_servers = array(
array(
'host' => $config->get('memcache_server_host', 'localhost'),
'port' => $config->get('memcache_server_port', 11211)
)
);
}
/**
* Register the functions of this class with PHP's session handler
*
* @return void
*
* @since 12.2
*/
public function register()
{
ini_set('session.save_path', $this->_servers['host'] . ':' . $this->_servers['port']);
ini_set('session.save_handler', 'memcached');
}
/**
* Test to see if the SessionHandler is available.
*
* @return boolean True on success, false otherwise.
*
* @since 12.1
*/
static public function isSupported()
{
return (extension_loaded('memcached') && class_exists('Memcached'));
}
}
| drmmr763/JoomlaExtensionDevelopment | libraries/joomla/session/storage/memcached.php | PHP | gpl-2.0 | 1,629 |
<?php
/**
* This is the template for the output of the events list widget.
* All the items are turned on and off through the widget admin.
* There is currently no default styling, which is highly needed.
*
* You can customize this view by putting a replacement file of the same name (events-list-load-widget-display.php) in the events/ directory of your theme.
*
* @return string
*/
// Vars set:
// '$event->AllDay',
// '$event->StartDate',
// '$event->EndDate',
// '$event->ShowMapLink',
// '$event->ShowMap',
// '$event->Cost',
// '$event->Phone',
// Don't load directly
if ( !defined('ABSPATH') ) { die('-1'); }
$event = array();
$tribe_ecp = TribeEvents::instance();
reset($tribe_ecp->metaTags); // Move pointer to beginning of array.
foreach($tribe_ecp->metaTags as $tag){
$var_name = str_replace('_Event','',$tag);
$event[$var_name] = tribe_get_event_meta( $post->ID, $tag, true );
}
$event = (object) $event; //Easier to work with.
ob_start();
if ( !isset($alt_text) ) { $alt_text = ''; }
post_class($alt_text,$post->ID);
$class = ob_get_contents();
ob_end_clean();
?>
<li <?php echo $class ?>>
<div class="when">
<?php
$space = false;
$output = '';
echo tribe_get_start_date( $post->ID );
if( tribe_is_multiday( $post->ID ) || !$event->AllDay ) {
echo ' – <br/>'. tribe_get_end_date($post->ID);
}
if( $event->AllDay ) {
echo ' <small><em>('.__('All Day','tribe-events-calendar').')</em></small>';
}
?>
</div>
<div class="event">
<a href="<?php echo get_permalink($post->ID); ?>"><?php echo $post->post_title; ?></a>
</div>
</li>
<?php $alt_text = ( empty( $alt_text ) ) ? 'alt' : ''; ?>
| francoisbenjamin/festival | wp-includes/wp-content/plugins/the-events-calendar/views/events-list-load-widget-display.php | PHP | gpl-2.0 | 1,695 |
#ifndef __S3CTVSCALER_H_
#define __S3CTVSCALER_H_
#include "plat/media.h"
#define TVSCALER_IOCTL_MAGIC 'S'
#define PPROC_SET_PARAMS _IO(TVSCALER_IOCTL_MAGIC, 0)
#define PPROC_START _IO(TVSCALER_IOCTL_MAGIC, 1)
#define PPROC_STOP _IO(TVSCALER_IOCTL_MAGIC, 2)
#define PPROC_INTERLACE_MODE _IO(TVSCALER_IOCTL_MAGIC, 3)
#define PPROC_PROGRESSIVE_MODE _IO(TVSCALER_IOCTL_MAGIC, 4)
#define QVGA_XSIZE 320
#define QVGA_YSIZE 240
#define LCD_XSIZE 320
#define LCD_YSIZE 240
#define SCALER_MINOR 251 // Just some number
//#define SYSTEM_RAM 0x08000000 // 128mb
#define SYSTEM_RAM 0x07800000 // 120mb
#define RESERVE_POST_MEM 8*1024*1024 // 8mb
#define PRE_BUFF_SIZE 4*1024*1024 //4 // 4mb
#define POST_BUFF_SIZE ( RESERVE_POST_MEM - PRE_BUFF_SIZE )
typedef unsigned int UINT32;
#define post_buff_base_addr 0x55B00000
#define POST_BUFF_BASE_ADDR (UINT32)s3c_get_media_memory(S3C_MDEV_TV)
#define USE_DEDICATED_MEM 1
typedef enum {
INTERLACE_MODE,
PROGRESSIVE_MODE
} s3c_scaler_scan_mode_t;
typedef enum {
POST_DMA, POST_FIFO
} s3c_scaler_path_t;
typedef enum {
ONE_SHOT, FREE_RUN
} s3c_scaler_run_mode_t;
typedef enum {
PAL1, PAL2, PAL4, PAL8,
RGB8, ARGB8, RGB16, ARGB16, RGB18, RGB24, RGB30, ARGB24,
YC420, YC422, // Non-interleave
CRYCBY, CBYCRY, YCRYCB, YCBYCR, YUV444 // Interleave
} cspace_t;
typedef enum
{
HCLK = 0, PLL_EXT = 1, EXT_27MHZ = 3
} scaler_clk_src_t;
typedef struct{
unsigned int SrcFullWidth; // Source Image Full Width(Virtual screen size)
unsigned int SrcFullHeight; // Source Image Full Height(Virtual screen size)
unsigned int SrcStartX; // Source Image Start width offset
unsigned int SrcStartY; // Source Image Start height offset
unsigned int SrcWidth; // Source Image Width
unsigned int SrcHeight; // Source Image Height
unsigned int SrcFrmSt; // Base Address of the Source Image : Physical Address
cspace_t SrcCSpace; // Color Space ot the Source Image
unsigned int DstFullWidth; // Source Image Full Width(Virtual screen size)
unsigned int DstFullHeight; // Source Image Full Height(Virtual screen size)
unsigned int DstStartX; // Source Image Start width offset
unsigned int DstStartY; // Source Image Start height offset
unsigned int DstWidth; // Source Image Width
unsigned int DstHeight; // Source Image Height
unsigned int DstFrmSt; // Base Address of the Source Image : Physical Address
cspace_t DstCSpace; // Color Space ot the Source Image
unsigned int SrcFrmBufNum; // Frame buffer number
s3c_scaler_run_mode_t Mode; // POST running mode(PER_FRAME or FREE_RUN)
s3c_scaler_path_t InPath; // Data path of the source image
s3c_scaler_path_t OutPath; // Data path of the desitination image
}scaler_params_t;
typedef struct{
unsigned int pre_phy_addr;
unsigned char *pre_virt_addr;
unsigned int post_phy_addr;
unsigned char *post_virt_addr;
} buff_addr_t;
#endif //__S3CTVSCALER_H_
| ghostry/openwrt-ghostry | target/linux/s3c64xx/files-2.6.36/drivers/media/video/samsung/tv/s3c-tvscaler.h | C | gpl-2.0 | 2,959 |
<script type="text/javascript">
function SetSrc(src) {
var plugin = document.getElementById('plugin');
plugin.src = src;
}
function SetSize(w, h) {
var plugin = document.getElementById('plugin');
plugin.width = w;
plugin.height = h;
}
function PostMessage(data, shouldTargetIframe) {
plugin = document.getElementById('plugin');
// TODO(fsamuel): contentWindow can be accessed directly once
// http://wkbug.com/85679 lands.
if (shouldTargetIframe) {
plugin.contentWindow.frames[0].postMessage('testing123', '*');
} else {
plugin.contentWindow.frames.postMessage('testing123', '*');
}
}
function SetTitle(str) {
document.title = str;
}
document.title = 'embedder';
</script>
<object id="plugin"
tabindex="0"
type="application/browser-plugin"
width="640"
height="480"
border="0px"></object>
<script type="text/javascript">
var msg;
function receiveMessage(event) {
msg = event.data;
if (msg == 'ready') {
document.title = 'ready';
return;
}
if (msg.indexOf('stop_ack') == -1) {
event.source.postMessage('stop', '*');
} else {
var name = msg.replace("stop_ack", "").trim();
if (name !== '') {
window.document.title = name;
} else {
window.document.title = 'main guest';
}
}
}
var plugin = document.getElementById('plugin');
window.addEventListener('message', receiveMessage, false);
plugin.addEventListener('-internal-instanceid-allocated', function(e) {
plugin['-internal-attach']({});
});
</script>
| qtekfun/htcDesire820Kernel | external/chromium_org/content/test/data/browser_plugin_embedder.html | HTML | gpl-2.0 | 1,505 |
/*
* Copyright (c) 2002, Intel Corporation. All rights reserved.
* Copyright (c) 2002, Jim Houston. All rights reserved.
* Created by: julie.n.fleischer REMOVE-THIS AT intel DOT com
* Patched by jim.houston REMOVE-THIS AT attbi DOT com
* This file is licensed under the GPL license. For the full content
* of this license, see the COPYING file at the top level of this
* source tree.
* Test that timers are not inherited across a fork().
* Steps:
* 1. Set up a signal handler for timer in parent.
* 2. Create timer using timer_create().
* 3. Activate timer using timer_settime().
* 4. Immediately fork a new process [Note: There is some risk here if
* the system does not fork fast enough that there could be a false
* failure. Times will be set large enough that this risk is minimized.]
* 5. Set up a signal handler for the timer in the parent and ensure it
* is not called by ensuring the child is able to sleep uninterrupted.
* [Note: The delay to set up this handler could also cause false
* results.]
*
* For this test clock CLOCK_REALTIME will be used.
*
* 12/17/02 - Applied Jim Houston's patch that fixed a bug. Parent originally
* was set to return PTS_UNRESOLVED if nanosleep() was interrupted,
* even though expected behavior is that it be interrupted once
* to catch the signal.
*/
#include <time.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
#include "posixtest.h"
#define TIMERSEC 2
#define SLEEPDELTA 4
#define ACCEPTABLEDELTA 1
#define CHILDSUCCESS 1
#define CHILDFAILURE 0
void parenthandler(int signo)
{
printf("Expected - Caught signal\n");
}
void handler(int signo)
{
printf("Not expected - Caught signal\n");
}
int main(void)
{
timer_t tid;
struct sigaction actp;
struct itimerspec its;
int pid;
actp.sa_handler = parenthandler;
actp.sa_flags = 0;
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 0;
its.it_value.tv_sec = TIMERSEC;
its.it_value.tv_nsec = 0;
if (sigemptyset(&actp.sa_mask) == -1) {
perror("Error calling sigemptyset\n");
return PTS_UNRESOLVED;
}
if (sigaction(SIGALRM, &actp, 0) == -1) {
perror("Error calling sigaction\n");
return PTS_UNRESOLVED;
}
if (timer_create(CLOCK_REALTIME, NULL, &tid) != 0) {
perror("timer_create() did not return success\n");
return PTS_UNRESOLVED;
}
if (timer_settime(tid, 0, &its, NULL) != 0) {
perror("timer_settime() did not return success\n");
return PTS_UNRESOLVED;
}
if ((pid = fork()) == 0) {
/* child here */
struct sigaction act;
struct timespec ts, tsleft;
act.sa_handler = handler;
act.sa_flags = 0;
if (sigemptyset(&act.sa_mask) == -1) {
perror("Error calling sigemptyset\n");
return CHILDFAILURE;
}
if (sigaction(SIGALRM, &act, 0) == -1) {
perror("Error calling sigaction\n");
return CHILDFAILURE;
}
ts.tv_sec = TIMERSEC + SLEEPDELTA;
ts.tv_nsec = 0;
if (nanosleep(&ts, &tsleft) == -1) {
printf("child nanosleep() interrupted\n");
return CHILDFAILURE;
}
//nanosleep() not interrupted
return CHILDSUCCESS;
} else {
/* parent here */
int i;
struct timespec tsp, rem;
/*
* parent also sleeps to allow timer to expire
*/
tsp.tv_sec = TIMERSEC;
tsp.tv_nsec = 0;
if (nanosleep(&tsp, &rem) == -1) {
tsp = rem;
if (nanosleep(&tsp, &rem) == -1) {
printf("parent nanosleep() interrupted\n");
return PTS_UNRESOLVED;
}
}
if (wait(&i) == -1) {
perror("Error waiting for child to exit\n");
return PTS_UNRESOLVED;
}
if (WIFEXITED(i) && WEXITSTATUS(i)) {
printf("Test PASSED\n");
return PTS_PASS;
} else {
printf("Child did not exit normally.\n");
printf("Test FAILED\n");
return PTS_FAIL;
}
}
return PTS_UNRESOLVED;
}
| Havner/ltp | testcases/open_posix_testsuite/conformance/interfaces/timer_create/8-1.c | C | gpl-2.0 | 3,816 |
-----------------------------------
-- Ability: Wild Card
-- Has a random effect on all party members within area of effect.
-- Obtained: Corsair Level 1
-- Recast Time: 1:00:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/ability");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0;
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
local roll = math.random(1,6);
caster:setLocalVar("corsairRollTotal", roll);
action:speceffect(caster:getID(), roll);
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end;
function applyRoll(caster,target,ability,action,total)
caster:doWildCard(target,total)
ability:setMsg(435 + math.floor((total-1)/2)*2)
action:animation(target:getID(), 132 + (total) - 1)
return total
end
| UnknownX7/darkstar | scripts/globals/abilities/wild_card.lua | Lua | gpl-3.0 | 1,187 |
<?php
/**
* Shopware 5
* Copyright (c) shopware AG
*
* According to our dual licensing model, this program can be used either
* under the terms of the GNU Affero General Public License, version 3,
* or under a proprietary license.
*
* The texts of the GNU Affero General Public License with an additional
* permission and of our proprietary license can be found at and
* in the LICENSE file you have received along with this program.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* "Shopware" is a registered trademark of shopware AG.
* The licensing of the program under the AGPLv3 does not imply a
* trademark license. Therefore any rights, title and interest in
* our trademarks remain entirely with us.
*/
namespace ShopwarePlugins\SwagUpdate\Components;
/**
* @category Shopware
* @package ShopwarePlugins\SwagUpdate\Components;
* @copyright Copyright (c) shopware AG (http://www.shopware.de)
*/
class FileSystem
{
/**
* @var string[]
*/
private $VCSDirs = array(
'.git',
'.svn',
);
/**
* @param string $directory
* @param bool $fixPermission
* @return array of errors
*/
public function checkDirectoryPermissions($directory, $fixPermission = false)
{
$errors = array();
if (!is_dir($directory)) {
$errors[] = $directory;
return $errors;
}
if ($fixPermission && !is_writable($directory)) {
$fileInfo = new \SplFileInfo($directory);
$this->fixDirectoryPermission($fileInfo);
}
if (!is_writable($directory)) {
$errors[] = $directory;
return $errors;
}
/** @var $fileInfo \DirectoryIterator */
foreach (new \DirectoryIterator($directory) as $fileInfo) {
if ($fileInfo->isDot()) {
continue;
}
if ($fileInfo->isFile()) {
if ($fixPermission && !$fileInfo->isWritable()) {
$this->fixFilePermission($fileInfo);
}
if (!$fileInfo->isWritable()) {
$errors[] = $fileInfo->getPathname();
}
continue;
}
// skip VCS dirs
if (in_array($fileInfo->getBasename(), $this->VCSDirs, true)) {
continue;
}
if ($fixPermission && !$fileInfo->isWritable()) {
$this->fixDirectoryPermission($fileInfo);
}
if (!$fileInfo->isWritable()) {
$errors[] = $fileInfo->getPathname();
continue;
}
$errors = array_merge($errors, $this->checkDirectoryPermissions($fileInfo->getPathname(), $fixPermission));
}
return $errors;
}
/**
* @param \SplFileInfo $fileInfo
*/
private function fixDirectoryPermission(\SplFileInfo $fileInfo)
{
try {
$permission = substr(sprintf('%o', $fileInfo->getPerms()), -4);
} catch (\Exception $e) {
// cannot get permissions...
return;
}
$newPermission = $permission;
// set owner-bit to writable
$newPermission[1] = '7';
// set group-bit to writable
$newPermission[2] = '7';
$newPermission = octdec($newPermission);
chmod($fileInfo->getPathname(), $newPermission);
clearstatcache(false, $fileInfo->getPathname());
}
/**
* @param \SplFileInfo $fileInfo
*/
private function fixFilePermission(\SplFileInfo $fileInfo)
{
try {
$permission = substr(sprintf('%o', $fileInfo->getPerms()), -4);
} catch (\Exception $e) {
// cannot get permissions...
return;
}
$newPermission = $permission;
// set owner-bit to writable
$newPermission[1] = '6';
// set group-bit to writable
$newPermission[2] = '6';
$newPermission = octdec($newPermission);
chmod($fileInfo->getPathname(), $newPermission);
clearstatcache(false, $fileInfo->getPathname());
}
}
| Zwilla/shopware | engine/Shopware/Plugins/Default/Backend/SwagUpdate/Components/FileSystem.php | PHP | agpl-3.0 | 4,368 |
// "Convert to ThreadLocal" "true"
class Test {
final ThreadLocal<Integer> field = ThreadLocal.withInitial(() -> 0);
void foo() {
field.set(field.get() + 1);
}
} | asedunov/intellij-community | java/typeMigration/testData/intentions/threadLocal/after1.java | Java | apache-2.0 | 173 |
<ul class="UIAPIPlugin-toc">
<li><a href="#overview">Overview</a></li>
<li><a href="#options">Arguments</a></li>
</ul>
<div class="UIAPIPlugin">
<h1>jQuery UI switchClass</h1>
<div id="overview">
<h2 class="top-header">Overview</h2>
<div id="overview-main">
<div class="editsection" style="float:right;margin-left:5px;">[<a href="http://docs.jquery.com/action/edit/UI/Effects/switchClass?section=1" title="Edit section: switchClass( remove, add, [duration] )">edit</a>]</div><a name="switchClass.28_remove.2C_add.2C_.5Bduration.5D_.29"></a><h3>switchClass( remove, add, <span class="optional">[</span>duration<span class="optional">]</span> )</h3>
<p>Switches from the class defined in the first argument to the class defined as second argument, using an optional transition.</p>
</div>
<div id="overview-dependencies">
<h3>Dependencies</h3>
<ul>
<li>Effects Core</li>
</ul>
</div>
<div id="overview-example">
<h3>Example</h3>
<div id="overview-example" class="example">
<ul><li><a href="#demo"><span>Demo</span></a></li><li><a href="#source"><span>View Source</span></a></li></ul>
<p><div id="demo" class="tabs-container" rel="170">
Switch the class 'highlight' to 'blue' when a paragraph is clicked with a one second transition.<br />
</p>
<pre>$("p").<a href="http://docs.jquery.com/Events/click" title="Events/click">click</a>(function () {
$(this).<strong class="selflink">switchClass</strong>("highlight", "blue", 1000);
});
</pre>
<p></div><div id="source" class="tabs-container">
</p>
<pre><!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script src="http://ui.jquery.com/latest/ui/effects.core.js"></script>
<style type="text/css">
p { margin: 4px; font-size:16px; font-weight:bolder;
cursor:pointer; }
.blue { background: blue; }
.highlight { background:yellow; }
</style>
<script>
$(document).ready(function() {
$("p").<a href="http://docs.jquery.com/Events/click" title="Events/click">click</a>(function () {
$(this).<strong class="selflink">switchClass</strong>("highlight", "blue", 1000);
});
});
</script>
</head>
<body style="font-size:62.5%;">
<p class="highlight">Click to switch</p>
<p class="highlight">to blue</p>
<p class="highlight">on these</p>
<p class="highlight">paragraphs</p>
</body>
</html>
</pre>
<p></div>
</p><p></div>
</div>
</div>
<div id="options">
<h2 class="top-header">Arguments</h2>
<ul class="options-list">
<li class="option" id="option-remove">
<div class="option-header">
<h3 class="option-name"><a href="#option-remove">remove</a></h3>
<dl>
<dt class="option-type-label">Type:</dt>
<dd class="option-type">String</dd>
</dl>
</div>
<div class="option-description">
<p>The CSS class that will be removed.</p>
</div>
</li>
<li class="option" id="option-add">
<div class="option-header">
<h3 class="option-name"><a href="#option-add">add</a></h3>
<dl>
<dt class="option-type-label">Type:</dt>
<dd class="option-type">String</dd>
</dl>
</div>
<div class="option-description">
<p>The CSS class that will be added.</p>
</div>
</li>
<li class="option" id="option-duration">
<div class="option-header">
<h3 class="option-name"><a href="#option-duration">duration</a></h3>
<dl>
<dt class="option-type-label">Type:</dt>
<dd class="option-type">String, Number</dd>
<dt class="option-optional-label">Optional</dt>
</dl>
</div>
<div class="option-description">
<p>A string representing one of the three predefined speeds ("slow", "normal", or "fast") or the number of milliseconds to run the animation (e.g. 1000).</p>
</div>
</li>
</ul>
</div>
</div>
</p><!--
Pre-expand include size: 5798 bytes
Post-expand include size: 7570 bytes
Template argument size: 4751 bytes
Maximum: 2097152 bytes
-->
<!-- Saved in parser cache with key jqdocs_docs:pcache:idhash:2609-1!1!0!!en!2 and timestamp 20111201124210 -->
| feklee/presvg | vendor/jquery-ui/development-bundle/docs/switchClass.html | HTML | apache-2.0 | 4,659 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.