file_name
int64 0
72.3k
| vulnerable_line_numbers
stringlengths 1
1.06k
⌀ | dataset_type
stringclasses 1
value | commit_hash
stringlengths 40
44
| unique_id
int64 0
271k
| project
stringclasses 10
values | target
int64 0
1
| repo_url
stringclasses 10
values | date
stringlengths 25
25
⌀ | code
stringlengths 0
20.4M
| CVE
stringlengths 13
43
⌀ | CWE
stringclasses 50
values | commit_link
stringlengths 73
97
⌀ | severity
stringclasses 4
values | __index_level_0__
int64 0
124k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
29,999 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 29,999 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/*
** 2003 December 18
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
** Code for testing the SQLite library in a multithreaded environment.
*/
#include "sqliteInt.h"
#if defined(INCLUDE_SQLITE_TCL_H)
# include "sqlite_tcl.h"
#else
# include "tcl.h"
#endif
#if SQLITE_OS_UNIX && SQLITE_THREADSAFE
#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <sched.h>
#include <ctype.h>
extern const char *sqlite3ErrName(int);
/*
** Each thread is controlled by an instance of the following
** structure.
*/
typedef struct Thread Thread;
struct Thread {
/* The first group of fields are writable by the master and read-only
** to the thread. */
char *zFilename; /* Name of database file */
void (*xOp)(Thread*); /* next operation to do */
char *zArg; /* argument usable by xOp */
int opnum; /* Operation number */
int busy; /* True if this thread is in use */
/* The next group of fields are writable by the thread but read-only to the
** master. */
int completed; /* Number of operations completed */
sqlite3 *db; /* Open database */
sqlite3_stmt *pStmt; /* Pending operation */
char *zErr; /* operation error */
char *zStaticErr; /* Static error message */
int rc; /* operation return code */
int argc; /* number of columns in result */
const char *argv[100]; /* result columns */
const char *colv[100]; /* result column names */
};
/*
** There can be as many as 26 threads running at once. Each is named
** by a capital letter: A, B, C, ..., Y, Z.
*/
#define N_THREAD 26
static Thread threadset[N_THREAD];
/*
** The main loop for a thread. Threads use busy waiting.
*/
static void *thread_main(void *pArg){
Thread *p = (Thread*)pArg;
if( p->db ){
sqlite3_close(p->db);
}
sqlite3_open(p->zFilename, &p->db);
if( SQLITE_OK!=sqlite3_errcode(p->db) ){
p->zErr = strdup(sqlite3_errmsg(p->db));
sqlite3_close(p->db);
p->db = 0;
}
p->pStmt = 0;
p->completed = 1;
while( p->opnum<=p->completed ) sched_yield();
while( p->xOp ){
if( p->zErr && p->zErr!=p->zStaticErr ){
sqlite3_free(p->zErr);
p->zErr = 0;
}
(*p->xOp)(p);
p->completed++;
while( p->opnum<=p->completed ) sched_yield();
}
if( p->pStmt ){
sqlite3_finalize(p->pStmt);
p->pStmt = 0;
}
if( p->db ){
sqlite3_close(p->db);
p->db = 0;
}
if( p->zErr && p->zErr!=p->zStaticErr ){
sqlite3_free(p->zErr);
p->zErr = 0;
}
p->completed++;
#ifndef SQLITE_OMIT_DEPRECATED
sqlite3_thread_cleanup();
#endif
return 0;
}
/*
** Get a thread ID which is an upper case letter. Return the index.
** If the argument is not a valid thread ID put an error message in
** the interpreter and return -1.
*/
static int parse_thread_id(Tcl_Interp *interp, const char *zArg){
if( zArg==0 || zArg[0]==0 || zArg[1]!=0 || !isupper((unsigned char)zArg[0]) ){
Tcl_AppendResult(interp, "thread ID must be an upper case letter", 0);
return -1;
}
return zArg[0] - 'A';
}
/*
** Usage: thread_create NAME FILENAME
**
** NAME should be an upper case letter. Start the thread running with
** an open connection to the given database.
*/
static int SQLITE_TCLAPI tcl_thread_create(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
pthread_t x;
int rc;
if( argc!=3 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID FILENAME", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( threadset[i].busy ){
Tcl_AppendResult(interp, "thread ", argv[1], " is already running", 0);
return TCL_ERROR;
}
threadset[i].busy = 1;
sqlite3_free(threadset[i].zFilename);
threadset[i].zFilename = sqlite3_mprintf("%s", argv[2]);
threadset[i].opnum = 1;
threadset[i].completed = 0;
rc = pthread_create(&x, 0, thread_main, &threadset[i]);
if( rc ){
Tcl_AppendResult(interp, "failed to create the thread", 0);
sqlite3_free(threadset[i].zFilename);
threadset[i].busy = 0;
return TCL_ERROR;
}
pthread_detach(x);
return TCL_OK;
}
/*
** Wait for a thread to reach its idle state.
*/
static void thread_wait(Thread *p){
while( p->opnum>p->completed ) sched_yield();
}
/*
** Usage: thread_wait ID
**
** Wait on thread ID to reach its idle state.
*/
static int SQLITE_TCLAPI tcl_thread_wait(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
return TCL_OK;
}
/*
** Stop a thread.
*/
static void stop_thread(Thread *p){
thread_wait(p);
p->xOp = 0;
p->opnum++;
thread_wait(p);
sqlite3_free(p->zArg);
p->zArg = 0;
sqlite3_free(p->zFilename);
p->zFilename = 0;
p->busy = 0;
}
/*
** Usage: thread_halt ID
**
** Cause a thread to shut itself down. Wait for the shutdown to be
** completed. If ID is "*" then stop all threads.
*/
static int SQLITE_TCLAPI tcl_thread_halt(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
if( argv[1][0]=='*' && argv[1][1]==0 ){
for(i=0; i<N_THREAD; i++){
if( threadset[i].busy ) stop_thread(&threadset[i]);
}
}else{
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
stop_thread(&threadset[i]);
}
return TCL_OK;
}
/*
** Usage: thread_argc ID
**
** Wait on the most recent thread_step to complete, then return the
** number of columns in the result set.
*/
static int SQLITE_TCLAPI tcl_thread_argc(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
char zBuf[100];
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
sqlite3_snprintf(sizeof(zBuf), zBuf, "%d", threadset[i].argc);
Tcl_AppendResult(interp, zBuf, 0);
return TCL_OK;
}
/*
** Usage: thread_argv ID N
**
** Wait on the most recent thread_step to complete, then return the
** value of the N-th columns in the result set.
*/
static int SQLITE_TCLAPI tcl_thread_argv(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
int n;
if( argc!=3 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID N", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR;
thread_wait(&threadset[i]);
if( n<0 || n>=threadset[i].argc ){
Tcl_AppendResult(interp, "column number out of range", 0);
return TCL_ERROR;
}
Tcl_AppendResult(interp, threadset[i].argv[n], 0);
return TCL_OK;
}
/*
** Usage: thread_colname ID N
**
** Wait on the most recent thread_step to complete, then return the
** name of the N-th columns in the result set.
*/
static int SQLITE_TCLAPI tcl_thread_colname(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
int n;
if( argc!=3 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID N", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
if( Tcl_GetInt(interp, argv[2], &n) ) return TCL_ERROR;
thread_wait(&threadset[i]);
if( n<0 || n>=threadset[i].argc ){
Tcl_AppendResult(interp, "column number out of range", 0);
return TCL_ERROR;
}
Tcl_AppendResult(interp, threadset[i].colv[n], 0);
return TCL_OK;
}
/*
** Usage: thread_result ID
**
** Wait on the most recent operation to complete, then return the
** result code from that operation.
*/
static int SQLITE_TCLAPI tcl_thread_result(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
const char *zName;
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
zName = sqlite3ErrName(threadset[i].rc);
Tcl_AppendResult(interp, zName, 0);
return TCL_OK;
}
/*
** Usage: thread_error ID
**
** Wait on the most recent operation to complete, then return the
** error string.
*/
static int SQLITE_TCLAPI tcl_thread_error(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
Tcl_AppendResult(interp, threadset[i].zErr, 0);
return TCL_OK;
}
/*
** This procedure runs in the thread to compile an SQL statement.
*/
static void do_compile(Thread *p){
if( p->db==0 ){
p->zErr = p->zStaticErr = "no database is open";
p->rc = SQLITE_ERROR;
return;
}
if( p->pStmt ){
sqlite3_finalize(p->pStmt);
p->pStmt = 0;
}
p->rc = sqlite3_prepare(p->db, p->zArg, -1, &p->pStmt, 0);
}
/*
** Usage: thread_compile ID SQL
**
** Compile a new virtual machine.
*/
static int SQLITE_TCLAPI tcl_thread_compile(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
if( argc!=3 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID SQL", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
threadset[i].xOp = do_compile;
sqlite3_free(threadset[i].zArg);
threadset[i].zArg = sqlite3_mprintf("%s", argv[2]);
threadset[i].opnum++;
return TCL_OK;
}
/*
** This procedure runs in the thread to step the virtual machine.
*/
static void do_step(Thread *p){
int i;
if( p->pStmt==0 ){
p->zErr = p->zStaticErr = "no virtual machine available";
p->rc = SQLITE_ERROR;
return;
}
p->rc = sqlite3_step(p->pStmt);
if( p->rc==SQLITE_ROW ){
p->argc = sqlite3_column_count(p->pStmt);
for(i=0; i<sqlite3_data_count(p->pStmt); i++){
p->argv[i] = (char*)sqlite3_column_text(p->pStmt, i);
}
for(i=0; i<p->argc; i++){
p->colv[i] = sqlite3_column_name(p->pStmt, i);
}
}
}
/*
** Usage: thread_step ID
**
** Advance the virtual machine by one step
*/
static int SQLITE_TCLAPI tcl_thread_step(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" IDL", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
threadset[i].xOp = do_step;
threadset[i].opnum++;
return TCL_OK;
}
/*
** This procedure runs in the thread to finalize a virtual machine.
*/
static void do_finalize(Thread *p){
if( p->pStmt==0 ){
p->zErr = p->zStaticErr = "no virtual machine available";
p->rc = SQLITE_ERROR;
return;
}
p->rc = sqlite3_finalize(p->pStmt);
p->pStmt = 0;
}
/*
** Usage: thread_finalize ID
**
** Finalize the virtual machine.
*/
static int SQLITE_TCLAPI tcl_thread_finalize(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" IDL", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
threadset[i].xOp = do_finalize;
sqlite3_free(threadset[i].zArg);
threadset[i].zArg = 0;
threadset[i].opnum++;
return TCL_OK;
}
/*
** Usage: thread_swap ID ID
**
** Interchange the sqlite* pointer between two threads.
*/
static int SQLITE_TCLAPI tcl_thread_swap(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i, j;
sqlite3 *temp;
if( argc!=3 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID1 ID2", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
j = parse_thread_id(interp, argv[2]);
if( j<0 ) return TCL_ERROR;
if( !threadset[j].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[j]);
temp = threadset[i].db;
threadset[i].db = threadset[j].db;
threadset[j].db = temp;
return TCL_OK;
}
/*
** Usage: thread_db_get ID
**
** Return the database connection pointer for the given thread. Then
** remove the pointer from the thread itself. Afterwards, the thread
** can be stopped and the connection can be used by the main thread.
*/
static int SQLITE_TCLAPI tcl_thread_db_get(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
char zBuf[100];
extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
sqlite3TestMakePointerStr(interp, zBuf, threadset[i].db);
threadset[i].db = 0;
Tcl_AppendResult(interp, zBuf, (char*)0);
return TCL_OK;
}
/*
** Usage: thread_db_put ID DB
**
*/
static int SQLITE_TCLAPI tcl_thread_db_put(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
extern void *sqlite3TestTextToPtr(const char *);
if( argc!=3 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID DB", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
assert( !threadset[i].db );
threadset[i].db = (sqlite3*)sqlite3TestTextToPtr(argv[2]);
return TCL_OK;
}
/*
** Usage: thread_stmt_get ID
**
** Return the database stmt pointer for the given thread. Then
** remove the pointer from the thread itself.
*/
static int SQLITE_TCLAPI tcl_thread_stmt_get(
void *NotUsed,
Tcl_Interp *interp, /* The TCL interpreter that invoked this command */
int argc, /* Number of arguments */
const char **argv /* Text of each argument */
){
int i;
char zBuf[100];
extern int sqlite3TestMakePointerStr(Tcl_Interp*, char*, void*);
if( argc!=2 ){
Tcl_AppendResult(interp, "wrong # args: should be \"", argv[0],
" ID", 0);
return TCL_ERROR;
}
i = parse_thread_id(interp, argv[1]);
if( i<0 ) return TCL_ERROR;
if( !threadset[i].busy ){
Tcl_AppendResult(interp, "no such thread", 0);
return TCL_ERROR;
}
thread_wait(&threadset[i]);
sqlite3TestMakePointerStr(interp, zBuf, threadset[i].pStmt);
threadset[i].pStmt = 0;
Tcl_AppendResult(interp, zBuf, (char*)0);
return TCL_OK;
}
/*
** Register commands with the TCL interpreter.
*/
int Sqlitetest4_Init(Tcl_Interp *interp){
static struct {
char *zName;
Tcl_CmdProc *xProc;
} aCmd[] = {
{ "thread_create", (Tcl_CmdProc*)tcl_thread_create },
{ "thread_wait", (Tcl_CmdProc*)tcl_thread_wait },
{ "thread_halt", (Tcl_CmdProc*)tcl_thread_halt },
{ "thread_argc", (Tcl_CmdProc*)tcl_thread_argc },
{ "thread_argv", (Tcl_CmdProc*)tcl_thread_argv },
{ "thread_colname", (Tcl_CmdProc*)tcl_thread_colname },
{ "thread_result", (Tcl_CmdProc*)tcl_thread_result },
{ "thread_error", (Tcl_CmdProc*)tcl_thread_error },
{ "thread_compile", (Tcl_CmdProc*)tcl_thread_compile },
{ "thread_step", (Tcl_CmdProc*)tcl_thread_step },
{ "thread_finalize", (Tcl_CmdProc*)tcl_thread_finalize },
{ "thread_swap", (Tcl_CmdProc*)tcl_thread_swap },
{ "thread_db_get", (Tcl_CmdProc*)tcl_thread_db_get },
{ "thread_db_put", (Tcl_CmdProc*)tcl_thread_db_put },
{ "thread_stmt_get", (Tcl_CmdProc*)tcl_thread_stmt_get },
};
int i;
for(i=0; i<sizeof(aCmd)/sizeof(aCmd[0]); i++){
Tcl_CreateCommand(interp, aCmd[i].zName, aCmd[i].xProc, 0, 0);
}
return TCL_OK;
}
#else
int Sqlitetest4_Init(Tcl_Interp *interp){ return TCL_OK; }
#endif /* SQLITE_OS_UNIX */
| null | null | null | null | 26,862 |
50,572 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 50,572 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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 "ui/ozone/platform/drm/gpu/mock_scanout_buffer_generator.h"
#include "ui/ozone/platform/drm/common/drm_util.h"
#include "ui/ozone/platform/drm/gpu/mock_scanout_buffer.h"
namespace ui {
MockScanoutBufferGenerator::MockScanoutBufferGenerator() {}
MockScanoutBufferGenerator::~MockScanoutBufferGenerator() {}
scoped_refptr<ScanoutBuffer> MockScanoutBufferGenerator::Create(
const scoped_refptr<DrmDevice>& drm,
uint32_t format,
const gfx::Size& size) {
return CreateWithModifier(drm, format, DRM_FORMAT_MOD_NONE, size);
}
scoped_refptr<ScanoutBuffer> MockScanoutBufferGenerator::CreateWithModifier(
const scoped_refptr<DrmDevice>& drm,
uint32_t format,
uint64_t modifier,
const gfx::Size& size) {
if (allocation_failure_)
return nullptr;
scoped_refptr<MockScanoutBuffer> buffer(
new MockScanoutBuffer(size, format, modifier, drm));
return buffer;
}
} // namespace ui
| null | null | null | null | 47,435 |
4,289 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 4,289 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 IOS_CHROME_BROWSER_STORE_KIT_STORE_KIT_TAB_HELPER_H_
#define IOS_CHROME_BROWSER_STORE_KIT_STORE_KIT_TAB_HELPER_H_
#include "base/macros.h"
#import "ios/chrome/browser/store_kit/store_kit_launcher.h"
#import "ios/web/public/web_state/web_state_user_data.h"
// A Tab Helper object that can open to a page on iOS App Store for a given
// app product ID.
class StoreKitTabHelper : public web::WebStateUserData<StoreKitTabHelper> {
public:
explicit StoreKitTabHelper(web::WebState* web_state);
~StoreKitTabHelper() override;
void SetLauncher(id<StoreKitLauncher> launcher);
id<StoreKitLauncher> GetLauncher();
// Use StoreKitLauncher to launch storekit with |app_id| application
// identifier.
void OpenAppStore(NSString* app_id);
// Use StoreKitLauncher to launch storekit using |product_params| as product
// parameters, application id must be set for key:
// SKStoreProductParameterITunesItemIdentifier. Additional key/value pairs can
// be set in the dictionary to represent analytic/marketing parameters.
void OpenAppStore(NSDictionary* product_params);
private:
__weak id<StoreKitLauncher> store_kit_launcher_ = nil;
DISALLOW_COPY_AND_ASSIGN(StoreKitTabHelper);
};
#endif // IOS_CHROME_BROWSER_STORE_KIT_STORE_KIT_TAB_HELPER_H_
| null | null | null | null | 1,152 |
666 | null |
train_val
|
c536b6be1a72aefd632d5530106a67c516cb9f4b
| 257,053 |
openssl
| 0 |
https://github.com/openssl/openssl
|
2016-09-22 23:12:38+01:00
|
/*
* Copyright 2001-2016 The OpenSSL Project Authors. All Rights Reserved.
*
* Licensed under the OpenSSL license (the "License"). You may not use
* this file except in compliance with the License. You can obtain a copy
* in the file LICENSE in the source distribution or at
* https://www.openssl.org/source/license.html
*/
/* ====================================================================
* Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
* Portions of this software developed by SUN MICROSYSTEMS, INC.,
* and contributed to the OpenSSL project.
*/
#include <openssl/err.h>
#include "ec_lcl.h"
const EC_METHOD *EC_GFp_mont_method(void)
{
static const EC_METHOD ret = {
EC_FLAGS_DEFAULT_OCT,
NID_X9_62_prime_field,
ec_GFp_mont_group_init,
ec_GFp_mont_group_finish,
ec_GFp_mont_group_clear_finish,
ec_GFp_mont_group_copy,
ec_GFp_mont_group_set_curve,
ec_GFp_simple_group_get_curve,
ec_GFp_simple_group_get_degree,
ec_group_simple_order_bits,
ec_GFp_simple_group_check_discriminant,
ec_GFp_simple_point_init,
ec_GFp_simple_point_finish,
ec_GFp_simple_point_clear_finish,
ec_GFp_simple_point_copy,
ec_GFp_simple_point_set_to_infinity,
ec_GFp_simple_set_Jprojective_coordinates_GFp,
ec_GFp_simple_get_Jprojective_coordinates_GFp,
ec_GFp_simple_point_set_affine_coordinates,
ec_GFp_simple_point_get_affine_coordinates,
0, 0, 0,
ec_GFp_simple_add,
ec_GFp_simple_dbl,
ec_GFp_simple_invert,
ec_GFp_simple_is_at_infinity,
ec_GFp_simple_is_on_curve,
ec_GFp_simple_cmp,
ec_GFp_simple_make_affine,
ec_GFp_simple_points_make_affine,
0 /* mul */ ,
0 /* precompute_mult */ ,
0 /* have_precompute_mult */ ,
ec_GFp_mont_field_mul,
ec_GFp_mont_field_sqr,
0 /* field_div */ ,
ec_GFp_mont_field_encode,
ec_GFp_mont_field_decode,
ec_GFp_mont_field_set_to_one,
ec_key_simple_priv2oct,
ec_key_simple_oct2priv,
0, /* set private */
ec_key_simple_generate_key,
ec_key_simple_check_key,
ec_key_simple_generate_public_key,
0, /* keycopy */
0, /* keyfinish */
ecdh_simple_compute_key
};
return &ret;
}
int ec_GFp_mont_group_init(EC_GROUP *group)
{
int ok;
ok = ec_GFp_simple_group_init(group);
group->field_data1 = NULL;
group->field_data2 = NULL;
return ok;
}
void ec_GFp_mont_group_finish(EC_GROUP *group)
{
BN_MONT_CTX_free(group->field_data1);
group->field_data1 = NULL;
BN_free(group->field_data2);
group->field_data2 = NULL;
ec_GFp_simple_group_finish(group);
}
void ec_GFp_mont_group_clear_finish(EC_GROUP *group)
{
BN_MONT_CTX_free(group->field_data1);
group->field_data1 = NULL;
BN_clear_free(group->field_data2);
group->field_data2 = NULL;
ec_GFp_simple_group_clear_finish(group);
}
int ec_GFp_mont_group_copy(EC_GROUP *dest, const EC_GROUP *src)
{
BN_MONT_CTX_free(dest->field_data1);
dest->field_data1 = NULL;
BN_clear_free(dest->field_data2);
dest->field_data2 = NULL;
if (!ec_GFp_simple_group_copy(dest, src))
return 0;
if (src->field_data1 != NULL) {
dest->field_data1 = BN_MONT_CTX_new();
if (dest->field_data1 == NULL)
return 0;
if (!BN_MONT_CTX_copy(dest->field_data1, src->field_data1))
goto err;
}
if (src->field_data2 != NULL) {
dest->field_data2 = BN_dup(src->field_data2);
if (dest->field_data2 == NULL)
goto err;
}
return 1;
err:
BN_MONT_CTX_free(dest->field_data1);
dest->field_data1 = NULL;
return 0;
}
int ec_GFp_mont_group_set_curve(EC_GROUP *group, const BIGNUM *p,
const BIGNUM *a, const BIGNUM *b, BN_CTX *ctx)
{
BN_CTX *new_ctx = NULL;
BN_MONT_CTX *mont = NULL;
BIGNUM *one = NULL;
int ret = 0;
BN_MONT_CTX_free(group->field_data1);
group->field_data1 = NULL;
BN_free(group->field_data2);
group->field_data2 = NULL;
if (ctx == NULL) {
ctx = new_ctx = BN_CTX_new();
if (ctx == NULL)
return 0;
}
mont = BN_MONT_CTX_new();
if (mont == NULL)
goto err;
if (!BN_MONT_CTX_set(mont, p, ctx)) {
ECerr(EC_F_EC_GFP_MONT_GROUP_SET_CURVE, ERR_R_BN_LIB);
goto err;
}
one = BN_new();
if (one == NULL)
goto err;
if (!BN_to_montgomery(one, BN_value_one(), mont, ctx))
goto err;
group->field_data1 = mont;
mont = NULL;
group->field_data2 = one;
one = NULL;
ret = ec_GFp_simple_group_set_curve(group, p, a, b, ctx);
if (!ret) {
BN_MONT_CTX_free(group->field_data1);
group->field_data1 = NULL;
BN_free(group->field_data2);
group->field_data2 = NULL;
}
err:
BN_free(one);
BN_CTX_free(new_ctx);
BN_MONT_CTX_free(mont);
return ret;
}
int ec_GFp_mont_field_mul(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a,
const BIGNUM *b, BN_CTX *ctx)
{
if (group->field_data1 == NULL) {
ECerr(EC_F_EC_GFP_MONT_FIELD_MUL, EC_R_NOT_INITIALIZED);
return 0;
}
return BN_mod_mul_montgomery(r, a, b, group->field_data1, ctx);
}
int ec_GFp_mont_field_sqr(const EC_GROUP *group, BIGNUM *r, const BIGNUM *a,
BN_CTX *ctx)
{
if (group->field_data1 == NULL) {
ECerr(EC_F_EC_GFP_MONT_FIELD_SQR, EC_R_NOT_INITIALIZED);
return 0;
}
return BN_mod_mul_montgomery(r, a, a, group->field_data1, ctx);
}
int ec_GFp_mont_field_encode(const EC_GROUP *group, BIGNUM *r,
const BIGNUM *a, BN_CTX *ctx)
{
if (group->field_data1 == NULL) {
ECerr(EC_F_EC_GFP_MONT_FIELD_ENCODE, EC_R_NOT_INITIALIZED);
return 0;
}
return BN_to_montgomery(r, a, (BN_MONT_CTX *)group->field_data1, ctx);
}
int ec_GFp_mont_field_decode(const EC_GROUP *group, BIGNUM *r,
const BIGNUM *a, BN_CTX *ctx)
{
if (group->field_data1 == NULL) {
ECerr(EC_F_EC_GFP_MONT_FIELD_DECODE, EC_R_NOT_INITIALIZED);
return 0;
}
return BN_from_montgomery(r, a, group->field_data1, ctx);
}
int ec_GFp_mont_field_set_to_one(const EC_GROUP *group, BIGNUM *r,
BN_CTX *ctx)
{
if (group->field_data2 == NULL) {
ECerr(EC_F_EC_GFP_MONT_FIELD_SET_TO_ONE, EC_R_NOT_INITIALIZED);
return 0;
}
if (!BN_copy(r, group->field_data2))
return 0;
return 1;
}
| null | null | null | null | 118,498 |
299 |
2,3,4,5,6,7,8
|
train_val
|
dc7b094a338c6c521f918f478e993f0f74bbea0d
| 299 |
Chrome
| 1 |
https://github.com/chromium/chromium
|
2011-06-15 06:45:53+00:00
|
static void IBusBusConnectedCallback(IBusBus* bus, gpointer user_data) {
LOG(WARNING) << "IBus connection is recovered.";
// ibus-daemon might be restarted, or the daemon was not running when Chrome
// started. Anyway, since |ibus_| connection is now ready, it's possible to
// create |ibus_config_| object by calling MaybeRestoreConnections().
g_return_if_fail(user_data);
InputMethodStatusConnection* self
= static_cast<InputMethodStatusConnection*>(user_data);
self->MaybeRestoreConnections();
}
|
CVE-2011-2804
|
CWE-399
|
https://github.com/chromium/chromium/commit/dc7b094a338c6c521f918f478e993f0f74bbea0d
|
Low
| 299 |
6,237 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 6,237 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#ifndef CHROMEOS_DISKS_DISK_MOUNT_MANAGER_H_
#define CHROMEOS_DISKS_DISK_MOUNT_MANAGER_H_
#include <stdint.h>
#include <map>
#include <memory>
#include "base/callback_forward.h"
#include "base/files/file_path.h"
#include "chromeos/chromeos_export.h"
#include "chromeos/dbus/cros_disks_client.h"
namespace chromeos {
namespace disks {
// Condition of mounted filesystem.
enum MountCondition {
MOUNT_CONDITION_NONE,
MOUNT_CONDITION_UNKNOWN_FILESYSTEM,
MOUNT_CONDITION_UNSUPPORTED_FILESYSTEM,
};
// This class handles the interaction with cros-disks.
// Other classes can add themselves as observers.
class CHROMEOS_EXPORT DiskMountManager {
public:
// Event types passed to the observers.
enum DiskEvent {
DISK_ADDED,
DISK_REMOVED,
DISK_CHANGED,
};
enum DeviceEvent {
DEVICE_ADDED,
DEVICE_REMOVED,
DEVICE_SCANNED,
};
enum MountEvent {
MOUNTING,
UNMOUNTING,
};
enum FormatEvent {
FORMAT_STARTED,
FORMAT_COMPLETED
};
enum RenameEvent { RENAME_STARTED, RENAME_COMPLETED };
// Used to house an instance of each found mount device. Created from
// non-virtual mount devices only - see IsAutoMountable().
class Disk {
public:
Disk(const std::string& device_path,
// The path to the mount point of this device. Empty if not mounted.
// (e.g. /media/removable/VOLUME)
const std::string& mount_path,
// Whether the device is mounted in read-only mode by the policy.
// Valid only when the device mounted and mount_path_ is non-empty.
bool write_disabled_by_policy,
const std::string& system_path,
const std::string& file_path,
const std::string& device_label,
const std::string& drive_label,
const std::string& vendor_id,
const std::string& vendor_name,
const std::string& product_id,
const std::string& product_name,
const std::string& fs_uuid,
const std::string& system_path_prefix,
DeviceType device_type,
uint64_t total_size_in_bytes,
bool is_parent,
bool is_read_only_hardware,
bool has_media,
bool on_boot_device,
bool on_removable_device,
bool is_hidden,
const std::string& file_system_type,
const std::string& base_mount_path);
Disk(const Disk& other);
~Disk();
// The path of the device, used by devicekit-disks.
// (e.g. /sys/devices/pci0000:00/.../8:0:0:0/block/sdb/sdb1)
const std::string& device_path() const { return device_path_; }
// The path to the mount point of this device. Will be empty if not mounted.
// (e.g. /media/removable/VOLUME)
const std::string& mount_path() const { return mount_path_; }
// The path of the device according to the udev system.
// (e.g. /sys/devices/pci0000:00/.../8:0:0:0/block/sdb/sdb1)
const std::string& system_path() const { return system_path_; }
// The path of the device according to filesystem.
// (e.g. /dev/sdb)
const std::string& file_path() const { return file_path_; }
// Device's label.
const std::string& device_label() const { return device_label_; }
void set_device_label(const std::string& device_label) {
device_label_ = device_label;
}
// If disk is a parent, then its label, else parents label.
// (e.g. "TransMemory")
const std::string& drive_label() const { return drive_label_; }
// Vendor ID of the device (e.g. "18d1").
const std::string& vendor_id() const { return vendor_id_; }
// Vendor name of the device (e.g. "Google Inc.").
const std::string& vendor_name() const { return vendor_name_; }
// Product ID of the device (e.g. "4e11").
const std::string& product_id() const { return product_id_; }
// Product name of the device (e.g. "Nexus One").
const std::string& product_name() const { return product_name_; }
// Returns the file system uuid string.
const std::string& fs_uuid() const { return fs_uuid_; }
// Path of the system device this device's block is a part of.
// (e.g. /sys/devices/pci0000:00/.../8:0:0:0/)
const std::string& system_path_prefix() const {
return system_path_prefix_;
}
// Device type.
DeviceType device_type() const { return device_type_; }
// Total size of the device in bytes.
uint64_t total_size_in_bytes() const { return total_size_in_bytes_; }
// Is the device is a parent device (i.e. sdb rather than sdb1).
bool is_parent() const { return is_parent_; }
// Whether the user can write to the device. True if read-only.
bool is_read_only() const {
return is_read_only_hardware_ || write_disabled_by_policy_;
}
// Is the device read only.
bool is_read_only_hardware() const { return is_read_only_hardware_; }
// Does the device contains media.
bool has_media() const { return has_media_; }
// Is the device on the boot device.
bool on_boot_device() const { return on_boot_device_; }
// Is the device on the removable device.
bool on_removable_device() const { return on_removable_device_; }
// Shoud the device be shown in the UI, or automounted.
bool is_hidden() const { return is_hidden_; }
void set_write_disabled_by_policy(bool disable) {
write_disabled_by_policy_ = disable;
}
void clear_mount_path() { mount_path_.clear(); }
bool is_mounted() const { return !mount_path_.empty(); }
const std::string& file_system_type() const { return file_system_type_; }
void set_file_system_type(const std::string& file_system_type) {
file_system_type_ = file_system_type;
}
// Name of the first mount path of the disk.
const std::string& base_mount_path() const { return base_mount_path_; }
void SetMountPath(const std::string& mount_path);
bool IsAutoMountable() const;
bool IsStatefulPartition() const;
private:
std::string device_path_;
std::string mount_path_;
bool write_disabled_by_policy_;
std::string system_path_;
std::string file_path_;
std::string device_label_;
std::string drive_label_;
std::string vendor_id_;
std::string vendor_name_;
std::string product_id_;
std::string product_name_;
std::string fs_uuid_;
std::string system_path_prefix_;
DeviceType device_type_;
uint64_t total_size_in_bytes_;
bool is_parent_;
bool is_read_only_hardware_;
bool has_media_;
bool on_boot_device_;
bool on_removable_device_;
bool is_hidden_;
std::string file_system_type_;
std::string base_mount_path_;
};
typedef std::map<std::string, std::unique_ptr<Disk>> DiskMap;
// A struct to store information about mount point.
struct MountPointInfo {
// Device's path.
std::string source_path;
// Mounted path.
std::string mount_path;
// Type of mount.
MountType mount_type;
// Condition of mount.
MountCondition mount_condition;
MountPointInfo(const std::string& source,
const std::string& mount,
const MountType type,
MountCondition condition)
: source_path(source),
mount_path(mount),
mount_type(type),
mount_condition(condition) {
}
};
// MountPointMap key is mount_path.
typedef std::map<std::string, MountPointInfo> MountPointMap;
// A callback function type which is called after UnmountDeviceRecursively
// finishes.
typedef base::Callback<void(bool)> UnmountDeviceRecursivelyCallbackType;
// A callback type for UnmountPath method.
typedef base::Callback<void(MountError error_code)> UnmountPathCallback;
// A callback type for EnsureMountInfoRefreshed method.
typedef base::Callback<void(bool success)> EnsureMountInfoRefreshedCallback;
// Implement this interface to be notified about disk/mount related events.
// TODO(agawronska): Make observer methods non-pure virtual, because
// subclasses only use small subset of them.
class Observer {
public:
virtual ~Observer() {}
// Called when auto-mountable disk mount status is changed.
virtual void OnAutoMountableDiskEvent(DiskEvent event,
const Disk& disk) = 0;
// Called when fixed storage disk status is changed.
virtual void OnBootDeviceDiskEvent(DiskEvent event, const Disk& disk) = 0;
// Called when device status is changed.
virtual void OnDeviceEvent(DeviceEvent event,
const std::string& device_path) = 0;
// Called after a mount point has been mounted or unmounted.
virtual void OnMountEvent(MountEvent event,
MountError error_code,
const MountPointInfo& mount_info) = 0;
// Called on format process events.
virtual void OnFormatEvent(FormatEvent event,
FormatError error_code,
const std::string& device_path) = 0;
// Called on rename process events.
virtual void OnRenameEvent(RenameEvent event,
RenameError error_code,
const std::string& device_path) = 0;
};
virtual ~DiskMountManager() {}
// Adds an observer.
virtual void AddObserver(Observer* observer) = 0;
// Removes an observer.
virtual void RemoveObserver(Observer* observer) = 0;
// Gets the list of disks found.
virtual const DiskMap& disks() const = 0;
// Returns Disk object corresponding to |source_path| or NULL on failure.
virtual const Disk* FindDiskBySourcePath(
const std::string& source_path) const = 0;
// Gets the list of mount points.
virtual const MountPointMap& mount_points() const = 0;
// Refreshes all the information about mounting if it is not yet done and
// invokes |callback| when finished. If the information is already refreshed
// and |force| is false, it just runs |callback| immediately.
virtual void EnsureMountInfoRefreshed(
const EnsureMountInfoRefreshedCallback& callback,
bool force) = 0;
// Mounts a device or an archive file.
// |source_path| specifies either a device or an archive file path.
// When |type|=MOUNT_TYPE_ARCHIVE, caller may set two optional arguments:
// |source_format| and |mount_label|. See CrosDisksClient::Mount for detail.
// |access_mode| specifies read-only or read-write mount mode for a device.
// Note that the mount operation may fail. To find out the result, one should
// observe DiskMountManager for |Observer::OnMountEvent| event, which will be
// raised upon the mount operation completion.
virtual void MountPath(const std::string& source_path,
const std::string& source_format,
const std::string& mount_label,
MountType type,
MountAccessMode access_mode) = 0;
// Unmounts a mounted disk.
// |UnmountOptions| enum defined in chromeos/dbus/cros_disks_client.h.
// When the method is complete, |callback| will be called and observers'
// |OnMountEvent| will be raised.
//
// |callback| may be empty, in which case it gets ignored.
virtual void UnmountPath(const std::string& mount_path,
UnmountOptions options,
const UnmountPathCallback& callback) = 0;
// Remounts mounted removable devices to change the read-only mount option.
// Devices that can be mounted only in its read-only mode will be ignored.
virtual void RemountAllRemovableDrives(chromeos::MountAccessMode mode) = 0;
// Formats Device given its mount path. Unmounts the device.
// Example: mount_path: /media/VOLUME_LABEL
virtual void FormatMountedDevice(const std::string& mount_path) = 0;
// Renames Device given its mount path.
// Example: mount_path: /media/VOLUME_LABEL
// volume_name: MYUSB
virtual void RenameMountedDevice(const std::string& mount_path,
const std::string& volume_name) = 0;
// Unmounts device_path and all of its known children.
virtual void UnmountDeviceRecursively(
const std::string& device_path,
const UnmountDeviceRecursivelyCallbackType& callback) = 0;
// Used in tests to initialize the manager's disk and mount point sets.
// Default implementation does noting. It just fails.
virtual bool AddDiskForTest(std::unique_ptr<Disk> disk);
virtual bool AddMountPointForTest(const MountPointInfo& mount_point);
// Returns corresponding string to |type| like "unknown_filesystem".
static std::string MountConditionToString(MountCondition type);
// Returns corresponding string to |type|, like "sd", "usb".
static std::string DeviceTypeToString(DeviceType type);
// Creates the global DiskMountManager instance.
static void Initialize();
// Similar to Initialize(), but can inject an alternative
// DiskMountManager such as MockDiskMountManager for testing.
// The injected object will be owned by the internal pointer and deleted
// by Shutdown().
static void InitializeForTesting(DiskMountManager* disk_mount_manager);
// Destroys the global DiskMountManager instance if it exists.
static void Shutdown();
// Returns a pointer to the global DiskMountManager instance.
// Initialize() should already have been called.
static DiskMountManager* GetInstance();
};
} // namespace disks
} // namespace chromeos
#endif // CHROMEOS_DISKS_DISK_MOUNT_MANAGER_H_
| null | null | null | null | 3,100 |
51,085 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 51,085 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2018 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 UI_MESSAGE_CENTER_PUBLIC_CPP_FEATURES_H_
#define UI_MESSAGE_CENTER_PUBLIC_CPP_FEATURES_H_
#include "base/feature_list.h"
#include "ui/message_center/public/cpp/message_center_public_export.h"
namespace message_center {
// This feature controls whether the new (material design) style notifications
// should be used.
MESSAGE_CENTER_PUBLIC_EXPORT extern const base::Feature kNewStyleNotifications;
} // namespace message_center
#endif // UI_MESSAGE_CENTER_PUBLIC_CPP_FEATURES_H_
| null | null | null | null | 47,948 |
1,081 | null |
train_val
|
31e986bc171719c9e6d40d0c2cb1501796a69e6c
| 260,036 |
php-src
| 0 |
https://github.com/php/php-src
|
2016-10-24 10:37:20+01:00
|
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 2006-2016 The PHP Group |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| [email protected] so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
| Authors: Andrey Hristov <[email protected]> |
| Ulf Wendel <[email protected]> |
+----------------------------------------------------------------------+
*/
#ifndef MYSQLND_RESULT_H
#define MYSQLND_RESULT_H
PHPAPI MYSQLND_RES * mysqlnd_result_init(const unsigned int field_count, const zend_bool persistent);
PHPAPI MYSQLND_RES_UNBUFFERED * mysqlnd_result_unbuffered_init(const unsigned int field_count, const zend_bool ps, const zend_bool persistent);
PHPAPI MYSQLND_RES_BUFFERED_ZVAL * mysqlnd_result_buffered_zval_init(const unsigned int field_count, const zend_bool ps, const zend_bool persistent);
PHPAPI MYSQLND_RES_BUFFERED_C * mysqlnd_result_buffered_c_init(const unsigned int field_count, const zend_bool ps, const zend_bool persistent);
enum_func_status mysqlnd_query_read_result_set_header(MYSQLND_CONN_DATA * conn, MYSQLND_STMT * stmt);
#endif /* MYSQLND_RESULT_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
| null | null | null | null | 119,957 |
7,847 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 172,842 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
#include "misc.h"
#if CONFIG_EARLY_PRINTK || CONFIG_RANDOMIZE_BASE
static unsigned long fs;
static inline void set_fs(unsigned long seg)
{
fs = seg << 4; /* shift it back */
}
typedef unsigned long addr_t;
static inline char rdfs8(addr_t addr)
{
return *((char *)(fs + addr));
}
#include "../cmdline.c"
static unsigned long get_cmd_line_ptr(void)
{
unsigned long cmd_line_ptr = boot_params->hdr.cmd_line_ptr;
cmd_line_ptr |= (u64)boot_params->ext_cmd_line_ptr << 32;
return cmd_line_ptr;
}
int cmdline_find_option(const char *option, char *buffer, int bufsize)
{
return __cmdline_find_option(get_cmd_line_ptr(), option, buffer, bufsize);
}
int cmdline_find_option_bool(const char *option)
{
return __cmdline_find_option_bool(get_cmd_line_ptr(), option);
}
#endif
| null | null | null | null | 81,189 |
37,567 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 37,567 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/*
* Copyright (c) 2008, 2009, Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT{
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,{
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/platform/scroll/scrollbar_theme_aura.h"
#include "third_party/blink/public/platform/platform.h"
#include "third_party/blink/public/platform/web_rect.h"
#include "third_party/blink/public/platform/web_theme_engine.h"
#include "third_party/blink/renderer/platform/graphics/graphics_context.h"
#include "third_party/blink/renderer/platform/graphics/paint/drawing_recorder.h"
#include "third_party/blink/renderer/platform/layout_test_support.h"
#include "third_party/blink/renderer/platform/runtime_enabled_features.h"
#include "third_party/blink/renderer/platform/scroll/scrollable_area.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar.h"
#include "third_party/blink/renderer/platform/scroll/scrollbar_theme_overlay.h"
namespace blink {
namespace {
static bool UseMockTheme() {
return LayoutTestSupport::IsRunningLayoutTest();
}
// Contains a flag indicating whether WebThemeEngine should paint a UI widget
// for a scrollbar part, and if so, what part and state apply.
//
// If the PartPaintingParams are not affected by a change in the scrollbar
// state, then the corresponding scrollbar part does not need to be repainted.
struct PartPaintingParams {
PartPaintingParams()
: should_paint(false),
part(WebThemeEngine::kPartScrollbarDownArrow),
state(WebThemeEngine::kStateNormal) {}
PartPaintingParams(WebThemeEngine::Part part, WebThemeEngine::State state)
: should_paint(true), part(part), state(state) {}
bool should_paint;
WebThemeEngine::Part part;
WebThemeEngine::State state;
};
bool operator==(const PartPaintingParams& a, const PartPaintingParams& b) {
return (!a.should_paint && !b.should_paint) ||
std::tie(a.should_paint, a.part, a.state) ==
std::tie(b.should_paint, b.part, b.state);
}
bool operator!=(const PartPaintingParams& a, const PartPaintingParams& b) {
return !(a == b);
}
PartPaintingParams ButtonPartPaintingParams(
const ScrollbarThemeClient& scrollbar,
float position,
ScrollbarPart part) {
WebThemeEngine::Part paint_part;
WebThemeEngine::State state = WebThemeEngine::kStateNormal;
bool check_min = false;
bool check_max = false;
if (scrollbar.Orientation() == kHorizontalScrollbar) {
if (part == kBackButtonStartPart) {
paint_part = WebThemeEngine::kPartScrollbarLeftArrow;
check_min = true;
} else if (UseMockTheme() && part != kForwardButtonEndPart) {
return PartPaintingParams();
} else {
paint_part = WebThemeEngine::kPartScrollbarRightArrow;
check_max = true;
}
} else {
if (part == kBackButtonStartPart) {
paint_part = WebThemeEngine::kPartScrollbarUpArrow;
check_min = true;
} else if (UseMockTheme() && part != kForwardButtonEndPart) {
return PartPaintingParams();
} else {
paint_part = WebThemeEngine::kPartScrollbarDownArrow;
check_max = true;
}
}
if (UseMockTheme() && !scrollbar.Enabled()) {
state = WebThemeEngine::kStateDisabled;
} else if (!UseMockTheme() &&
((check_min && (position <= 0)) ||
(check_max && position >= scrollbar.Maximum()))) {
state = WebThemeEngine::kStateDisabled;
} else {
if (part == scrollbar.PressedPart())
state = WebThemeEngine::kStatePressed;
else if (part == scrollbar.HoveredPart())
state = WebThemeEngine::kStateHover;
}
return PartPaintingParams(paint_part, state);
}
static int GetScrollbarThickness() {
return Platform::Current()
->ThemeEngine()
->GetSize(WebThemeEngine::kPartScrollbarVerticalThumb)
.width;
}
} // namespace
ScrollbarTheme& ScrollbarTheme::NativeTheme() {
if (RuntimeEnabledFeatures::OverlayScrollbarsEnabled()) {
DEFINE_STATIC_LOCAL(
ScrollbarThemeOverlay, theme,
(GetScrollbarThickness(), 0, ScrollbarThemeOverlay::kAllowHitTest));
return theme;
}
DEFINE_STATIC_LOCAL(ScrollbarThemeAura, theme, ());
return theme;
}
int ScrollbarThemeAura::ScrollbarThickness(ScrollbarControlSize control_size) {
// Horiz and Vert scrollbars are the same thickness.
// In unit tests we don't have the mock theme engine (because of layering
// violations), so we hard code the size (see bug 327470).
if (UseMockTheme())
return 15;
IntSize scrollbar_size = Platform::Current()->ThemeEngine()->GetSize(
WebThemeEngine::kPartScrollbarVerticalTrack);
return scrollbar_size.Width();
}
bool ScrollbarThemeAura::HasThumb(const ScrollbarThemeClient& scrollbar) {
// This method is just called as a paint-time optimization to see if
// painting the thumb can be skipped. We don't have to be exact here.
return ThumbLength(scrollbar) > 0;
}
IntRect ScrollbarThemeAura::BackButtonRect(
const ScrollbarThemeClient& scrollbar,
ScrollbarPart part,
bool) {
// Windows and Linux just have single arrows.
if (part == kBackButtonEndPart)
return IntRect();
IntSize size = ButtonSize(scrollbar);
return IntRect(scrollbar.X(), scrollbar.Y(), size.Width(), size.Height());
}
IntRect ScrollbarThemeAura::ForwardButtonRect(
const ScrollbarThemeClient& scrollbar,
ScrollbarPart part,
bool) {
// Windows and Linux just have single arrows.
if (part == kForwardButtonStartPart)
return IntRect();
IntSize size = ButtonSize(scrollbar);
int x, y;
if (scrollbar.Orientation() == kHorizontalScrollbar) {
x = scrollbar.X() + scrollbar.Width() - size.Width();
y = scrollbar.Y();
} else {
x = scrollbar.X();
y = scrollbar.Y() + scrollbar.Height() - size.Height();
}
return IntRect(x, y, size.Width(), size.Height());
}
IntRect ScrollbarThemeAura::TrackRect(const ScrollbarThemeClient& scrollbar,
bool) {
// The track occupies all space between the two buttons.
IntSize bs = ButtonSize(scrollbar);
if (scrollbar.Orientation() == kHorizontalScrollbar) {
if (scrollbar.Width() <= 2 * bs.Width())
return IntRect();
return IntRect(scrollbar.X() + bs.Width(), scrollbar.Y(),
scrollbar.Width() - 2 * bs.Width(), scrollbar.Height());
}
if (scrollbar.Height() <= 2 * bs.Height())
return IntRect();
return IntRect(scrollbar.X(), scrollbar.Y() + bs.Height(), scrollbar.Width(),
scrollbar.Height() - 2 * bs.Height());
}
int ScrollbarThemeAura::MinimumThumbLength(
const ScrollbarThemeClient& scrollbar) {
if (scrollbar.Orientation() == kVerticalScrollbar) {
return Platform::Current()
->ThemeEngine()
->GetSize(WebThemeEngine::kPartScrollbarVerticalThumb)
.height;
}
return Platform::Current()
->ThemeEngine()
->GetSize(WebThemeEngine::kPartScrollbarHorizontalThumb)
.width;
}
void ScrollbarThemeAura::PaintTrackBackground(GraphicsContext& context,
const Scrollbar& scrollbar,
const IntRect& rect) {
// Just assume a forward track part. We only paint the track as a single piece
// when there is no thumb.
if (!HasThumb(scrollbar) && !rect.IsEmpty())
PaintTrackPiece(context, scrollbar, rect, kForwardTrackPart);
}
void ScrollbarThemeAura::PaintTrackPiece(GraphicsContext& gc,
const Scrollbar& scrollbar,
const IntRect& rect,
ScrollbarPart part_type) {
DisplayItem::Type display_item_type =
TrackPiecePartToDisplayItemType(part_type);
if (DrawingRecorder::UseCachedDrawingIfPossible(gc, scrollbar,
display_item_type))
return;
DrawingRecorder recorder(gc, scrollbar, display_item_type);
WebThemeEngine::State state = scrollbar.HoveredPart() == part_type
? WebThemeEngine::kStateHover
: WebThemeEngine::kStateNormal;
if (UseMockTheme() && !scrollbar.Enabled())
state = WebThemeEngine::kStateDisabled;
IntRect align_rect = TrackRect(scrollbar, false);
WebThemeEngine::ExtraParams extra_params;
extra_params.scrollbar_track.is_back = (part_type == kBackTrackPart);
extra_params.scrollbar_track.track_x = align_rect.X();
extra_params.scrollbar_track.track_y = align_rect.Y();
extra_params.scrollbar_track.track_width = align_rect.Width();
extra_params.scrollbar_track.track_height = align_rect.Height();
Platform::Current()->ThemeEngine()->Paint(
gc.Canvas(),
scrollbar.Orientation() == kHorizontalScrollbar
? WebThemeEngine::kPartScrollbarHorizontalTrack
: WebThemeEngine::kPartScrollbarVerticalTrack,
state, WebRect(rect), &extra_params);
}
void ScrollbarThemeAura::PaintButton(GraphicsContext& gc,
const Scrollbar& scrollbar,
const IntRect& rect,
ScrollbarPart part) {
DisplayItem::Type display_item_type = ButtonPartToDisplayItemType(part);
if (DrawingRecorder::UseCachedDrawingIfPossible(gc, scrollbar,
display_item_type))
return;
PartPaintingParams params =
ButtonPartPaintingParams(scrollbar, scrollbar.CurrentPos(), part);
if (!params.should_paint)
return;
DrawingRecorder recorder(gc, scrollbar, display_item_type);
Platform::Current()->ThemeEngine()->Paint(
gc.Canvas(), params.part, params.state, WebRect(rect), nullptr);
}
void ScrollbarThemeAura::PaintThumb(GraphicsContext& gc,
const Scrollbar& scrollbar,
const IntRect& rect) {
if (DrawingRecorder::UseCachedDrawingIfPossible(gc, scrollbar,
DisplayItem::kScrollbarThumb))
return;
DrawingRecorder recorder(gc, scrollbar, DisplayItem::kScrollbarThumb);
WebThemeEngine::State state;
WebCanvas* canvas = gc.Canvas();
if (scrollbar.PressedPart() == kThumbPart)
state = WebThemeEngine::kStatePressed;
else if (scrollbar.HoveredPart() == kThumbPart)
state = WebThemeEngine::kStateHover;
else
state = WebThemeEngine::kStateNormal;
Platform::Current()->ThemeEngine()->Paint(
canvas,
scrollbar.Orientation() == kHorizontalScrollbar
? WebThemeEngine::kPartScrollbarHorizontalThumb
: WebThemeEngine::kPartScrollbarVerticalThumb,
state, WebRect(rect), nullptr);
}
bool ScrollbarThemeAura::ShouldRepaintAllPartsOnInvalidation() const {
// This theme can separately handle thumb invalidation.
return false;
}
ScrollbarPart ScrollbarThemeAura::InvalidateOnThumbPositionChange(
const ScrollbarThemeClient& scrollbar,
float old_position,
float new_position) const {
ScrollbarPart invalid_parts = kNoPart;
DCHECK_EQ(ButtonsPlacement(), kWebScrollbarButtonsPlacementSingle);
static const ScrollbarPart kButtonParts[] = {kBackButtonStartPart,
kForwardButtonEndPart};
for (ScrollbarPart part : kButtonParts) {
if (ButtonPartPaintingParams(scrollbar, old_position, part) !=
ButtonPartPaintingParams(scrollbar, new_position, part))
invalid_parts = static_cast<ScrollbarPart>(invalid_parts | part);
}
return invalid_parts;
}
bool ScrollbarThemeAura::HasScrollbarButtons(
ScrollbarOrientation orientation) const {
WebThemeEngine* theme_engine = Platform::Current()->ThemeEngine();
if (orientation == kVerticalScrollbar) {
return !theme_engine->GetSize(WebThemeEngine::kPartScrollbarDownArrow)
.IsEmpty();
}
return !theme_engine->GetSize(WebThemeEngine::kPartScrollbarLeftArrow)
.IsEmpty();
};
IntSize ScrollbarThemeAura::ButtonSize(const ScrollbarThemeClient& scrollbar) {
if (!HasScrollbarButtons(scrollbar.Orientation()))
return IntSize(0, 0);
if (scrollbar.Orientation() == kVerticalScrollbar) {
int square_size = scrollbar.Width();
return IntSize(square_size, scrollbar.Height() < 2 * square_size
? scrollbar.Height() / 2
: square_size);
}
// HorizontalScrollbar
int square_size = scrollbar.Height();
return IntSize(
scrollbar.Width() < 2 * square_size ? scrollbar.Width() / 2 : square_size,
square_size);
}
} // namespace blink
| null | null | null | null | 34,430 |
6,831 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 171,826 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
#ifndef _ASM_S390_DMA_MAPPING_H
#define _ASM_S390_DMA_MAPPING_H
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/mm.h>
#include <linux/scatterlist.h>
#include <linux/dma-debug.h>
#include <linux/io.h>
#define DMA_ERROR_CODE (~(dma_addr_t) 0x0)
extern const struct dma_map_ops s390_pci_dma_ops;
static inline const struct dma_map_ops *get_arch_dma_ops(struct bus_type *bus)
{
return &dma_noop_ops;
}
static inline void dma_cache_sync(struct device *dev, void *vaddr, size_t size,
enum dma_data_direction direction)
{
}
static inline bool dma_capable(struct device *dev, dma_addr_t addr, size_t size)
{
if (!dev->dma_mask)
return false;
return addr + size - 1 <= *dev->dma_mask;
}
#endif /* _ASM_S390_DMA_MAPPING_H */
| null | null | null | null | 80,173 |
70,753 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 70,753 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#ifndef SANDBOX_LINUX_SECCOMP_BPF_DIE_H__
#define SANDBOX_LINUX_SECCOMP_BPF_DIE_H__
#include "base/macros.h"
#include "sandbox/sandbox_export.h"
namespace sandbox {
// This is the main API for using this file. Prints a error message and
// exits with a fatal error. This is not async-signal safe.
#define SANDBOX_DIE(m) sandbox::Die::SandboxDie(m, __FILE__, __LINE__)
// An async signal safe version of the same API. Won't print the filename
// and line numbers.
#define RAW_SANDBOX_DIE(m) sandbox::Die::RawSandboxDie(m)
// Adds an informational message to the log file or stderr as appropriate.
#define SANDBOX_INFO(m) sandbox::Die::SandboxInfo(m, __FILE__, __LINE__)
class SANDBOX_EXPORT Die {
public:
// Terminate the program, even if the current sandbox policy prevents some
// of the more commonly used functions used for exiting.
// Most users would want to call SANDBOX_DIE() instead, as it logs extra
// information. But calling ExitGroup() is correct and in some rare cases
// preferable. So, we make it part of the public API.
static void ExitGroup() __attribute__((noreturn));
// This method gets called by SANDBOX_DIE(). There is normally no reason
// to call it directly unless you are defining your own exiting macro.
static void SandboxDie(const char* msg, const char* file, int line)
__attribute__((noreturn));
static void RawSandboxDie(const char* msg) __attribute__((noreturn));
// This method gets called by SANDBOX_INFO(). There is normally no reason
// to call it directly unless you are defining your own logging macro.
static void SandboxInfo(const char* msg, const char* file, int line);
// Writes a message to stderr. Used as a fall-back choice, if we don't have
// any other way to report an error.
static void LogToStderr(const char* msg, const char* file, int line);
// We generally want to run all exit handlers. This means, on SANDBOX_DIE()
// we should be calling LOG(FATAL). But there are some situations where
// we just need to print a message and then terminate. This would typically
// happen in cases where we consume the error message internally (e.g. in
// unit tests or in the supportsSeccompSandbox() method).
static void EnableSimpleExit() { simple_exit_ = true; }
// Sometimes we need to disable all informational messages (e.g. from within
// unittests).
static void SuppressInfoMessages(bool flag) { suppress_info_ = flag; }
private:
static bool simple_exit_;
static bool suppress_info_;
DISALLOW_IMPLICIT_CONSTRUCTORS(Die);
};
} // namespace sandbox
#endif // SANDBOX_LINUX_SECCOMP_BPF_DIE_H__
| null | null | null | null | 67,616 |
37,968 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 37,968 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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 THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PLACEHOLDER_IMAGE_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_PLACEHOLDER_IMAGE_H_
#include <stdint.h>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/geometry/int_size.h"
#include "third_party/blink/renderer/platform/graphics/image.h"
#include "third_party/blink/renderer/platform/graphics/image_orientation.h"
#include "third_party/blink/renderer/platform/wtf/optional.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/skia/include/core/SkImage.h"
#include "third_party/skia/include/core/SkRefCnt.h"
namespace blink {
class FloatPoint;
class FloatRect;
class FloatSize;
class GraphicsContext;
class ImageObserver;
// A generated placeholder image that shows a translucent gray rectangle.
class PLATFORM_EXPORT PlaceholderImage final : public Image {
public:
static scoped_refptr<PlaceholderImage> Create(
ImageObserver* observer,
const IntSize& size,
int64_t original_resource_size) {
return base::AdoptRef(
new PlaceholderImage(observer, size, original_resource_size));
}
~PlaceholderImage() override;
IntSize Size() const override;
void Draw(PaintCanvas*,
const PaintFlags&,
const FloatRect& dest_rect,
const FloatRect& src_rect,
RespectImageOrientationEnum,
ImageClampingMode,
ImageDecodingMode) override;
void DestroyDecodedData() override;
PaintImage PaintImageForCurrentFrame() override;
bool IsPlaceholderImage() const override;
const String& GetTextForTesting() const { return text_; }
private:
PlaceholderImage(ImageObserver*,
const IntSize&,
int64_t original_resource_size);
bool CurrentFrameHasSingleSecurityOrigin() const override;
bool CurrentFrameKnownToBeOpaque() override;
void DrawPattern(GraphicsContext&,
const FloatRect& src_rect,
const FloatSize& scale,
const FloatPoint& phase,
SkBlendMode,
const FloatRect& dest_rect,
const FloatSize& repeat_spacing) override;
// SetData does nothing, and the passed in buffer is ignored.
SizeAvailability SetData(scoped_refptr<SharedBuffer>, bool) override;
const IntSize size_;
const String text_;
class SharedFont;
// Lazily initialized. All instances of PlaceholderImage will share the same
// Font object, wrapped as a SharedFont.
scoped_refptr<SharedFont> shared_font_;
// Lazily initialized.
Optional<float> cached_text_width_;
sk_sp<PaintRecord> paint_record_for_current_frame_;
PaintImage::ContentId paint_record_content_id_;
};
} // namespace blink
#endif
| null | null | null | null | 34,831 |
16,308 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 16,308 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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_SYNC_ENGINE_CONNECTION_STATUS_H_
#define COMPONENTS_SYNC_ENGINE_CONNECTION_STATUS_H_
namespace syncer {
// Status of the sync connection to the server.
enum ConnectionStatus {
CONNECTION_NOT_ATTEMPTED,
CONNECTION_OK,
CONNECTION_AUTH_ERROR,
CONNECTION_SERVER_ERROR
};
} // namespace syncer
#endif // COMPONENTS_SYNC_ENGINE_CONNECTION_STATUS_H_
| null | null | null | null | 13,171 |
12,244 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 12,244 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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 <algorithm>
#include "base/debug/crash_logging.h"
#include "base/i18n/break_iterator.h"
#include "base/memory/ptr_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversion_utils.h"
#include "components/pdf/renderer/pdf_accessibility_tree.h"
#include "components/strings/grit/components_strings.h"
#include "content/public/renderer/render_accessibility.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_view.h"
#include "content/public/renderer/renderer_ppapi_host.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/rect_conversions.h"
#include "ui/gfx/transform.h"
namespace pdf {
namespace {
// Don't try to apply font size thresholds to automatically identify headings
// if the median font size is not at least this many points.
const double kMinimumFontSize = 5;
// Don't try to apply line break thresholds to automatically identify
// line breaks if the median line break is not at least this many points.
const double kMinimumLineSpacing = 5;
// Ratio between the font size of one text run and the median on the page
// for that text run to be considered to be a heading instead of normal text.
const double kHeadingFontSizeRatio = 1.2;
// Ratio between the line spacing between two lines and the median on the
// page for that line spacing to be considered a paragraph break.
const double kParagraphLineSpacingRatio = 1.2;
gfx::RectF ToGfxRectF(const PP_FloatRect& r) {
return gfx::RectF(r.point.x, r.point.y, r.size.width, r.size.height);
}
}
PdfAccessibilityTree::PdfAccessibilityTree(
content::RendererPpapiHost* host,
PP_Instance instance)
: host_(host),
instance_(instance),
zoom_(1.0) {
}
PdfAccessibilityTree::~PdfAccessibilityTree() {
content::RenderAccessibility* render_accessibility = GetRenderAccessibility();
if (render_accessibility)
render_accessibility->SetPluginTreeSource(nullptr);
}
void PdfAccessibilityTree::SetAccessibilityViewportInfo(
const PP_PrivateAccessibilityViewportInfo& viewport_info) {
zoom_ = viewport_info.zoom;
CHECK_GT(zoom_, 0);
scroll_ = ToVector2dF(viewport_info.scroll);
scroll_.Scale(1.0 / zoom_);
offset_ = ToVector2dF(viewport_info.offset);
offset_.Scale(1.0 / zoom_);
selection_start_page_index_ = viewport_info.selection_start_page_index;
selection_start_char_index_ = viewport_info.selection_start_char_index;
selection_end_page_index_ = viewport_info.selection_end_page_index;
selection_end_char_index_ = viewport_info.selection_end_char_index;
content::RenderAccessibility* render_accessibility = GetRenderAccessibility();
if (render_accessibility && tree_.size() > 1) {
ui::AXNode* root = tree_.root();
ui::AXNodeData root_data = root->data();
root_data.transform = base::WrapUnique(MakeTransformFromViewInfo());
root->SetData(root_data);
UpdateAXTreeDataFromSelection();
render_accessibility->OnPluginRootNodeUpdated();
}
}
void PdfAccessibilityTree::SetAccessibilityDocInfo(
const PP_PrivateAccessibilityDocInfo& doc_info) {
if (!GetRenderAccessibility())
return;
doc_info_ = doc_info;
doc_node_ = CreateNode(ax::mojom::Role::kGroup);
// Because all of the coordinates are expressed relative to the
// doc's coordinates, the origin of the doc must be (0, 0). Its
// width and height will be updated as we add each page so that the
// doc's bounding box surrounds all pages.
doc_node_->location = gfx::RectF(0, 0, 1, 1);
}
void PdfAccessibilityTree::SetAccessibilityPageInfo(
const PP_PrivateAccessibilityPageInfo& page_info,
const std::vector<PP_PrivateAccessibilityTextRunInfo>& text_runs,
const std::vector<PP_PrivateAccessibilityCharInfo>& chars) {
content::RenderAccessibility* render_accessibility = GetRenderAccessibility();
if (!render_accessibility)
return;
uint32_t page_index = page_info.page_index;
CHECK_GE(page_index, 0U);
CHECK_LT(page_index, doc_info_.page_count);
ui::AXNodeData* page_node = CreateNode(ax::mojom::Role::kRegion);
page_node->AddStringAttribute(
ax::mojom::StringAttribute::kName,
l10n_util::GetPluralStringFUTF8(IDS_PDF_PAGE_INDEX, page_index + 1));
gfx::RectF page_bounds = ToRectF(page_info.bounds);
page_node->location = page_bounds;
doc_node_->location.Union(page_node->location);
doc_node_->child_ids.push_back(page_node->id);
double heading_font_size_threshold = 0;
double line_spacing_threshold = 0;
ComputeParagraphAndHeadingThresholds(text_runs,
&heading_font_size_threshold,
&line_spacing_threshold);
ui::AXNodeData* para_node = nullptr;
ui::AXNodeData* static_text_node = nullptr;
std::string static_text;
uint32_t char_index = 0;
for (size_t i = 0; i < text_runs.size(); ++i) {
// Get the text of the next text run
const auto& text_run = text_runs[i];
std::string chars_utf8 = GetTextRunCharsAsUTF8(text_run, chars, char_index);
std::vector<int32_t> char_offsets = GetTextRunCharOffsets(
text_run, chars, char_index);
static_text += chars_utf8;
uint32_t initial_char_index = char_index;
char_index += text_run.len;
// If we don't have a paragraph, create one.
if (!para_node) {
para_node = CreateNode(ax::mojom::Role::kParagraph);
page_node->child_ids.push_back(para_node->id);
if (heading_font_size_threshold > 0 &&
text_run.font_size > heading_font_size_threshold) {
para_node->role = ax::mojom::Role::kHeading;
para_node->AddIntAttribute(ax::mojom::IntAttribute::kHierarchicalLevel,
2);
para_node->AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag,
"h2");
}
// This node is for the text inside the paragraph, it includes
// the text of all of the text runs.
static_text_node = CreateNode(ax::mojom::Role::kStaticText);
para_node->child_ids.push_back(static_text_node->id);
node_id_to_char_index_in_page_[static_text_node->id] = initial_char_index;
}
// Add this text run to the current static text node.
ui::AXNodeData* inline_text_box_node =
CreateNode(ax::mojom::Role::kInlineTextBox);
static_text_node->child_ids.push_back(inline_text_box_node->id);
inline_text_box_node->AddStringAttribute(ax::mojom::StringAttribute::kName,
chars_utf8);
gfx::RectF text_run_bounds = ToGfxRectF(text_run.bounds);
text_run_bounds += page_bounds.OffsetFromOrigin();
inline_text_box_node->location = text_run_bounds;
inline_text_box_node->AddIntListAttribute(
ax::mojom::IntListAttribute::kCharacterOffsets, char_offsets);
AddWordStartsAndEnds(inline_text_box_node);
para_node->location.Union(inline_text_box_node->location);
static_text_node->location.Union(inline_text_box_node->location);
if (i == text_runs.size() - 1) {
static_text_node->AddStringAttribute(ax::mojom::StringAttribute::kName,
static_text);
break;
}
double line_spacing =
text_runs[i + 1].bounds.point.y - text_run.bounds.point.y;
if (text_run.font_size != text_runs[i + 1].font_size ||
(line_spacing_threshold > 0 &&
line_spacing > line_spacing_threshold)) {
static_text_node->AddStringAttribute(ax::mojom::StringAttribute::kName,
static_text);
para_node = nullptr;
static_text_node = nullptr;
static_text.clear();
}
}
if (page_index == doc_info_.page_count - 1)
Finish();
}
void PdfAccessibilityTree::Finish() {
doc_node_->transform = base::WrapUnique(MakeTransformFromViewInfo());
ui::AXTreeUpdate update;
update.root_id = doc_node_->id;
for (const auto& node : nodes_)
update.nodes.push_back(*node);
if (!tree_.Unserialize(update)) {
static auto* ax_tree_error = base::debug::AllocateCrashKeyString(
"ax_tree_error", base::debug::CrashKeySize::Size32);
static auto* ax_tree_update = base::debug::AllocateCrashKeyString(
"ax_tree_update", base::debug::CrashKeySize::Size64);
// Temporarily log some additional crash keys so we can try to
// figure out why we're getting bad accessibility trees here.
// http://crbug.com/770886
base::debug::SetCrashKeyString(ax_tree_error, tree_.error());
base::debug::SetCrashKeyString(ax_tree_update, update.ToString());
LOG(FATAL) << tree_.error();
}
UpdateAXTreeDataFromSelection();
content::RenderAccessibility* render_accessibility = GetRenderAccessibility();
if (render_accessibility)
render_accessibility->SetPluginTreeSource(this);
}
void PdfAccessibilityTree::UpdateAXTreeDataFromSelection() {
FindNodeOffset(selection_start_page_index_, selection_start_char_index_,
&tree_data_.sel_anchor_object_id,
&tree_data_.sel_anchor_offset);
FindNodeOffset(selection_end_page_index_, selection_end_char_index_,
&tree_data_.sel_focus_object_id, &tree_data_.sel_focus_offset);
}
void PdfAccessibilityTree::FindNodeOffset(uint32_t page_index,
uint32_t page_char_index,
int32_t* out_node_id,
int32_t* out_node_char_index) {
*out_node_id = -1;
*out_node_char_index = 0;
ui::AXNode* root = tree_.root();
if (page_index >= static_cast<uint32_t>(root->child_count()))
return;
ui::AXNode* page = root->ChildAtIndex(page_index);
// Iterate over all paragraphs within this given page, and static text nodes
// within each paragraph.
for (int i = 0; i < page->child_count(); i++) {
ui::AXNode* para = page->ChildAtIndex(i);
for (int j = 0; j < para->child_count(); j++) {
ui::AXNode* static_text = para->ChildAtIndex(j);
// Look up the page-relative character index for this node from a map
// we built while the document was initially built.
DCHECK(
base::ContainsKey(node_id_to_char_index_in_page_, static_text->id()));
uint32_t char_index = node_id_to_char_index_in_page_[static_text->id()];
uint32_t len = static_text->data()
.GetStringAttribute(ax::mojom::StringAttribute::kName)
.size();
// If the character index we're looking for falls within the range
// of this node, return the node ID and index within this node's text.
if (page_char_index <= char_index + len) {
*out_node_id = static_text->id();
*out_node_char_index = page_char_index - char_index;
return;
}
}
}
}
void PdfAccessibilityTree::ComputeParagraphAndHeadingThresholds(
const std::vector<PP_PrivateAccessibilityTextRunInfo>& text_runs,
double* out_heading_font_size_threshold,
double* out_line_spacing_threshold) {
// Scan over the font sizes and line spacing within this page and
// set heuristic thresholds so that text larger than the median font
// size can be marked as a heading, and spacing larger than the median
// line spacing can be a paragraph break.
std::vector<double> font_sizes;
std::vector<double> line_spacings;
for (size_t i = 0; i < text_runs.size(); ++i) {
font_sizes.push_back(text_runs[i].font_size);
if (i > 0) {
const auto& cur = text_runs[i].bounds;
const auto& prev = text_runs[i - 1].bounds;
if (cur.point.y > prev.point.y + prev.size.height / 2)
line_spacings.push_back(cur.point.y - prev.point.y);
}
}
if (font_sizes.size() > 2) {
std::sort(font_sizes.begin(), font_sizes.end());
double median_font_size = font_sizes[font_sizes.size() / 2];
if (median_font_size > kMinimumFontSize) {
*out_heading_font_size_threshold =
median_font_size * kHeadingFontSizeRatio;
}
}
if (line_spacings.size() > 4) {
std::sort(line_spacings.begin(), line_spacings.end());
double median_line_spacing = line_spacings[line_spacings.size() / 2];
if (median_line_spacing > kMinimumLineSpacing) {
*out_line_spacing_threshold =
median_line_spacing * kParagraphLineSpacingRatio;
}
}
}
std::string PdfAccessibilityTree::GetTextRunCharsAsUTF8(
const PP_PrivateAccessibilityTextRunInfo& text_run,
const std::vector<PP_PrivateAccessibilityCharInfo>& chars,
int char_index) {
std::string chars_utf8;
for (uint32_t i = 0; i < text_run.len; ++i) {
base::WriteUnicodeCharacter(chars[char_index + i].unicode_character,
&chars_utf8);
}
return chars_utf8;
}
std::vector<int32_t> PdfAccessibilityTree::GetTextRunCharOffsets(
const PP_PrivateAccessibilityTextRunInfo& text_run,
const std::vector<PP_PrivateAccessibilityCharInfo>& chars,
int char_index) {
std::vector<int32_t> char_offsets(text_run.len);
double offset = 0.0;
for (uint32_t j = 0; j < text_run.len; ++j) {
offset += chars[char_index + j].char_width;
char_offsets[j] = floor(offset);
}
return char_offsets;
}
gfx::Vector2dF PdfAccessibilityTree::ToVector2dF(const PP_Point& p) {
return gfx::Vector2dF(p.x, p.y);
}
gfx::RectF PdfAccessibilityTree::ToRectF(const PP_Rect& r) {
return gfx::RectF(r.point.x, r.point.y, r.size.width, r.size.height);
}
ui::AXNodeData* PdfAccessibilityTree::CreateNode(ax::mojom::Role role) {
content::RenderAccessibility* render_accessibility = GetRenderAccessibility();
DCHECK(render_accessibility);
ui::AXNodeData* node = new ui::AXNodeData();
node->id = render_accessibility->GenerateAXID();
node->role = role;
node->SetRestriction(ax::mojom::Restriction::kReadOnly);
// All nodes other than the first one have coordinates relative to
// the first node.
if (nodes_.size() > 0)
node->offset_container_id = nodes_[0]->id;
nodes_.push_back(base::WrapUnique(node));
return node;
}
float PdfAccessibilityTree::GetDeviceScaleFactor() const {
content::RenderFrame* render_frame =
host_->GetRenderFrameForInstance(instance_);
DCHECK(render_frame);
return render_frame->GetRenderView()->GetDeviceScaleFactor();
}
content::RenderAccessibility* PdfAccessibilityTree::GetRenderAccessibility() {
content::RenderFrame* render_frame =
host_->GetRenderFrameForInstance(instance_);
if (!render_frame)
return nullptr;
content::RenderAccessibility* render_accessibility =
render_frame->GetRenderAccessibility();
if (!render_accessibility)
return nullptr;
// If RenderAccessibility is unable to generate valid positive IDs,
// we shouldn't use it. This can happen if Blink accessibility is disabled
// after we started generating the accessible PDF.
if (render_accessibility->GenerateAXID() <= 0)
return nullptr;
return render_accessibility;
}
gfx::Transform* PdfAccessibilityTree::MakeTransformFromViewInfo() {
gfx::Transform* transform = new gfx::Transform();
float scale_factor = zoom_ / GetDeviceScaleFactor();
transform->Scale(scale_factor, scale_factor);
transform->Translate(offset_);
transform->Translate(-scroll_);
return transform;
}
void PdfAccessibilityTree::AddWordStartsAndEnds(
ui::AXNodeData* inline_text_box) {
base::string16 text =
inline_text_box->GetString16Attribute(ax::mojom::StringAttribute::kName);
base::i18n::BreakIterator iter(text, base::i18n::BreakIterator::BREAK_WORD);
if (!iter.Init())
return;
std::vector<int32_t> word_starts;
std::vector<int32_t> word_ends;
while (iter.Advance()) {
if (iter.IsWord()) {
word_starts.push_back(iter.prev());
word_ends.push_back(iter.pos());
}
}
inline_text_box->AddIntListAttribute(ax::mojom::IntListAttribute::kWordStarts,
word_starts);
inline_text_box->AddIntListAttribute(ax::mojom::IntListAttribute::kWordEnds,
word_ends);
}
//
// AXTreeSource implementation.
//
bool PdfAccessibilityTree::GetTreeData(ui::AXTreeData* tree_data) const {
tree_data->sel_anchor_object_id = tree_data_.sel_anchor_object_id;
tree_data->sel_anchor_offset = tree_data_.sel_anchor_offset;
tree_data->sel_focus_object_id = tree_data_.sel_focus_object_id;
tree_data->sel_focus_offset = tree_data_.sel_focus_offset;
return true;
}
ui::AXNode* PdfAccessibilityTree::GetRoot() const {
return tree_.root();
}
ui::AXNode* PdfAccessibilityTree::GetFromId(int32_t id) const {
return tree_.GetFromId(id);
}
int32_t PdfAccessibilityTree::GetId(const ui::AXNode* node) const {
return node->id();
}
void PdfAccessibilityTree::GetChildren(
const ui::AXNode* node,
std::vector<const ui::AXNode*>* out_children) const {
for (int i = 0; i < node->child_count(); ++i)
out_children->push_back(node->ChildAtIndex(i));
}
ui::AXNode* PdfAccessibilityTree::GetParent(const ui::AXNode* node) const {
return node->parent();
}
bool PdfAccessibilityTree::IsValid(const ui::AXNode* node) const {
return node != nullptr;
}
bool PdfAccessibilityTree::IsEqual(const ui::AXNode* node1,
const ui::AXNode* node2) const {
return node1 == node2;
}
const ui::AXNode* PdfAccessibilityTree::GetNull() const {
return nullptr;
}
void PdfAccessibilityTree::SerializeNode(
const ui::AXNode* node, ui::AXNodeData* out_data) const {
*out_data = node->data();
}
} // namespace pdf
| null | null | null | null | 9,107 |
21,183 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 21,183 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 CONTENT_RENDERER_LOADER_WEB_DATA_CONSUMER_HANDLE_IMPL_H_
#define CONTENT_RENDERER_LOADER_WEB_DATA_CONSUMER_HANDLE_IMPL_H_
#include <stddef.h>
#include <memory>
#include "content/common/content_export.h"
#include "mojo/public/cpp/system/data_pipe.h"
#include "mojo/public/cpp/system/simple_watcher.h"
#include "third_party/blink/public/platform/web_data_consumer_handle.h"
namespace content {
class CONTENT_EXPORT WebDataConsumerHandleImpl final
: public blink::WebDataConsumerHandle {
typedef mojo::ScopedDataPipeConsumerHandle Handle;
class Context;
public:
class CONTENT_EXPORT ReaderImpl final : public Reader {
public:
ReaderImpl(scoped_refptr<Context> context,
Client* client,
scoped_refptr<base::SingleThreadTaskRunner> task_runner);
~ReaderImpl() override;
Result Read(void* data,
size_t size,
Flags flags,
size_t* readSize) override;
Result BeginRead(const void** buffer,
Flags flags,
size_t* available) override;
Result EndRead(size_t readSize) override;
private:
Result HandleReadResult(MojoResult);
void StartWatching();
void OnHandleGotReadable(MojoResult);
scoped_refptr<Context> context_;
mojo::SimpleWatcher handle_watcher_;
Client* client_;
DISALLOW_COPY_AND_ASSIGN(ReaderImpl);
};
std::unique_ptr<Reader> ObtainReader(
Client* client,
scoped_refptr<base::SingleThreadTaskRunner> task_runner) override;
explicit WebDataConsumerHandleImpl(Handle handle);
~WebDataConsumerHandleImpl() override;
private:
const char* DebugName() const override;
scoped_refptr<Context> context_;
DISALLOW_COPY_AND_ASSIGN(WebDataConsumerHandleImpl);
};
} // namespace content
#endif // CONTENT_RENDERER_LOADER_WEB_DATA_CONSUMER_HANDLE_IMPL_H_
| null | null | null | null | 18,046 |
46,083 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 46,083 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 "ash/wm/resize_shadow_controller.h"
#include <memory>
#include <utility>
#include "ash/wm/resize_shadow.h"
#include "ui/aura/window.h"
namespace ash {
ResizeShadowController::ResizeShadowController() = default;
ResizeShadowController::~ResizeShadowController() {
for (const auto& shadow : window_shadows_)
shadow.first->RemoveObserver(this);
}
void ResizeShadowController::ShowShadow(aura::Window* window, int hit_test) {
ResizeShadow* shadow = GetShadowForWindow(window);
if (!shadow)
shadow = CreateShadow(window);
shadow->ShowForHitTest(hit_test);
}
void ResizeShadowController::HideShadow(aura::Window* window) {
ResizeShadow* shadow = GetShadowForWindow(window);
if (shadow)
shadow->Hide();
}
ResizeShadow* ResizeShadowController::GetShadowForWindowForTest(
aura::Window* window) {
return GetShadowForWindow(window);
}
void ResizeShadowController::OnWindowDestroying(aura::Window* window) {
window_shadows_.erase(window);
}
void ResizeShadowController::OnWindowVisibilityChanging(aura::Window* window,
bool visible) {
if (!visible)
HideShadow(window);
}
ResizeShadow* ResizeShadowController::CreateShadow(aura::Window* window) {
auto shadow = std::make_unique<ResizeShadow>(window);
window->AddObserver(this);
ResizeShadow* raw_shadow = shadow.get();
window_shadows_.insert(std::make_pair(window, std::move(shadow)));
return raw_shadow;
}
ResizeShadow* ResizeShadowController::GetShadowForWindow(aura::Window* window) {
auto it = window_shadows_.find(window);
return it != window_shadows_.end() ? it->second.get() : nullptr;
}
} // namespace ash
| null | null | null | null | 42,946 |
4,729 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 4,729 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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 IOS_CHROME_BROWSER_UI_HISTORY_CLEAR_BROWSING_BAR_H_
#define IOS_CHROME_BROWSER_UI_HISTORY_CLEAR_BROWSING_BAR_H_
#import <UIKit/UIKit.h>
// View at the bottom of the history panel that presents options to clear
// browsing data or enter edit mode. When in edit mode, the bar displays a
// delete button and a cancel button instead.
@interface ClearBrowsingBar : UIView
// Yes if in edit mode. Setting to |editing| ClearBrowsingBar for edit
// mode or non-edit mode accordingly.
@property(nonatomic, getter=isEditing) BOOL editing;
// Yes if the edit button is enabled. Setting |editButtonEnabled| enables or
// disables the edit button accordingly.
@property(nonatomic, getter=isEditButtonEnabled) BOOL editButtonEnabled;
// Yes if the delete button is enabled. Setting |deleteButtonEnabled| enables or
// disables the delete button accordingly.
@property(nonatomic, getter=isDeleteButtonEnabled) BOOL deleteButtonEnabled;
// Sets the target/action of the "Clear Browsing Data..." button.
- (void)setClearBrowsingDataTarget:(id)target action:(SEL)action;
// Sets the target/action of the "Edit" button.
- (void)setEditTarget:(id)target action:(SEL)action;
// Sets the target/action of the "Delete" button.
- (void)setDeleteTarget:(id)taret action:(SEL)action;
// Sets the target/action of the "Cancel" button.
- (void)setCancelTarget:(id)target action:(SEL)action;
// Updates the height of the ClearBrowsingBar.
- (void)updateHeight;
@end
#endif // IOS_CHROME_BROWSER_UI_HISTORY_CLEAR_BROWSING_BAR_H_
| null | null | null | null | 1,592 |
39,361 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 39,361 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/*
* Copyright (C) 2013 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/public/mojom/service_worker/service_worker_error_type.mojom-blink.h"
#include "third_party/blink/renderer/modules/serviceworkers/service_worker_error.h"
#include "third_party/blink/renderer/bindings/core/v8/script_promise_resolver.h"
#include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h"
#include "third_party/blink/renderer/core/dom/dom_exception.h"
#include "third_party/blink/renderer/core/dom/exception_code.h"
#include "third_party/blink/renderer/platform/bindings/v8_throw_exception.h"
using blink::WebServiceWorkerError;
namespace blink {
namespace {
struct ExceptionParams {
ExceptionParams(ExceptionCode code,
const String& default_message = String(),
const String& message = String())
: code(code), message(message.IsEmpty() ? default_message : message) {}
ExceptionCode code;
String message;
};
ExceptionParams GetExceptionParams(const WebServiceWorkerError& web_error) {
switch (web_error.error_type) {
case mojom::blink::ServiceWorkerErrorType::kAbort:
return ExceptionParams(kAbortError,
"The Service Worker operation was aborted.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kActivate:
// Not currently returned as a promise rejection.
// TODO: Introduce new ActivateError type to ExceptionCodes?
return ExceptionParams(kAbortError,
"The Service Worker activation failed.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kDisabled:
return ExceptionParams(kNotSupportedError,
"Service Worker support is disabled.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kInstall:
// TODO: Introduce new InstallError type to ExceptionCodes?
return ExceptionParams(kAbortError,
"The Service Worker installation failed.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kScriptEvaluateFailed:
return ExceptionParams(kAbortError,
"The Service Worker script failed to evaluate.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kNavigation:
// ErrorTypeNavigation should have bailed out before calling this.
NOTREACHED();
return ExceptionParams(kUnknownError);
case mojom::blink::ServiceWorkerErrorType::kNetwork:
return ExceptionParams(kNetworkError,
"The Service Worker failed by network.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kNotFound:
return ExceptionParams(
kNotFoundError,
"The specified Service Worker resource was not found.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kSecurity:
return ExceptionParams(
kSecurityError,
"The Service Worker security policy prevented an action.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kState:
return ExceptionParams(kInvalidStateError,
"The Service Worker state was not valid.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kTimeout:
return ExceptionParams(kAbortError,
"The Service Worker operation timed out.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kUnknown:
return ExceptionParams(kUnknownError,
"An unknown error occurred within Service Worker.",
web_error.message);
case mojom::blink::ServiceWorkerErrorType::kNone:
case mojom::blink::ServiceWorkerErrorType::kType:
// ErrorTypeType should have been handled before reaching this point.
NOTREACHED();
return ExceptionParams(kUnknownError);
}
NOTREACHED();
return ExceptionParams(kUnknownError);
}
} // namespace
// static
DOMException* ServiceWorkerError::Take(ScriptPromiseResolver*,
const WebServiceWorkerError& web_error) {
ExceptionParams params = GetExceptionParams(web_error);
return DOMException::Create(params.code, params.message);
}
// static
v8::Local<v8::Value> ServiceWorkerErrorForUpdate::Take(
ScriptPromiseResolver* resolver,
const WebServiceWorkerError& web_error) {
ScriptState* script_state = resolver->GetScriptState();
switch (web_error.error_type) {
case mojom::blink::ServiceWorkerErrorType::kNetwork:
case mojom::blink::ServiceWorkerErrorType::kNotFound:
case mojom::blink::ServiceWorkerErrorType::kScriptEvaluateFailed:
// According to the spec, these errors during update should result in
// a TypeError.
return V8ThrowException::CreateTypeError(
script_state->GetIsolate(), GetExceptionParams(web_error).message);
case mojom::blink::ServiceWorkerErrorType::kType:
return V8ThrowException::CreateTypeError(script_state->GetIsolate(),
web_error.message);
default:
return ToV8(ServiceWorkerError::Take(resolver, web_error),
script_state->GetContext()->Global(),
script_state->GetIsolate());
}
}
} // namespace blink
| null | null | null | null | 36,224 |
10,359 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 175,354 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Copyright (C) 2012 - Virtual Open Systems and Columbia University
* Author: Christoffer Dall <[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, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#ifndef __ARM_KVM_MMIO_H__
#define __ARM_KVM_MMIO_H__
#include <linux/kvm_host.h>
#include <asm/kvm_asm.h>
#include <asm/kvm_arm.h>
struct kvm_decode {
unsigned long rt;
bool sign_extend;
};
void kvm_mmio_write_buf(void *buf, unsigned int len, unsigned long data);
unsigned long kvm_mmio_read_buf(const void *buf, unsigned int len);
int kvm_handle_mmio_return(struct kvm_vcpu *vcpu, struct kvm_run *run);
int io_mem_abort(struct kvm_vcpu *vcpu, struct kvm_run *run,
phys_addr_t fault_ipa);
#endif /* __ARM_KVM_MMIO_H__ */
| null | null | null | null | 83,701 |
1,758 | null |
train_val
|
31e986bc171719c9e6d40d0c2cb1501796a69e6c
| 260,713 |
php-src
| 0 |
https://github.com/php/php-src
|
2016-10-24 10:37:20+01:00
|
/*
zip_fopen_index.c -- open file in zip archive for reading by index
Copyright (C) 1999-2015 Dieter Baron and Thomas Klausner
This file is part of libzip, a library to manipulate ZIP archives.
The authors can be contacted at <[email protected]>
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.
3. The names of the authors may not be used to endorse or promote
products derived from this software without specific prior
written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <stdio.h>
#include <stdlib.h>
#include "zipint.h"
ZIP_EXTERN zip_file_t *
zip_fopen_index(zip_t *za, zip_uint64_t index, zip_flags_t flags)
{
return zip_fopen_index_encrypted(za, index, flags, za->default_password);
}
| null | null | null | null | 120,634 |
27,558 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 27,558 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/* vim: set ts=8 sw=8 noexpandtab: */
// qcms
// Copyright (C) 2009 Mozilla Foundation
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the Software
// is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#ifndef QCMS_H
#define QCMS_H
#ifdef __cplusplus
extern "C" {
#endif
#include <stdio.h>
struct _qcms_profile;
typedef struct _qcms_profile qcms_profile;
struct _qcms_transform;
typedef struct _qcms_transform qcms_transform;
typedef int qcms_bool;
/* ICC Section 6.1.5 Color Space Signatures (abridged) */
typedef enum {
XYZData /* ‘XYZ ’ */ = 0x58595A20,
labData /* ‘Lab ’ */ = 0x4C616220,
luvData /* ‘Luv ’ */ = 0x4C757620,
YCbCrData /* ‘YCbr' */ = 0x59436272,
YxyData /* ‘Yxy ’ */ = 0x59787920,
rgbData /* ‘RGB ’ */ = 0x52474220,
grayData /* ‘GRAY’ */ = 0x47524159,
hsvData /* ‘HSV ’ */ = 0x48535620,
hlsData /* ‘HLS ’ */ = 0x484C5320,
cmykData /* ‘CMYK’ */ = 0x434D594B,
cmyData /* ‘CMY ’ */ = 0x434D5920,
} qcms_color_space;
/* ICC Section 6.1.11 Rendering Intents */
typedef enum {
QCMS_INTENT_DEFAULT = 0,
QCMS_INTENT_PERCEPTUAL = 0,
QCMS_INTENT_RELATIVE_COLORIMETRIC = 1,
QCMS_INTENT_SATURATION = 2,
QCMS_INTENT_ABSOLUTE_COLORIMETRIC = 3
} qcms_intent;
/* Input data formats */
typedef enum {
QCMS_DATA_RGB_8,
QCMS_DATA_RGBA_8,
QCMS_DATA_GRAY_8,
QCMS_DATA_GRAYA_8
} qcms_data_type;
/* Output data format for qcms_transform_data_type() */
typedef enum {
QCMS_OUTPUT_RGBX,
QCMS_OUTPUT_BGRX
} qcms_output_type;
/* Output data format for qcms_transform_get_input|output_trc_rgba() */
typedef enum {
QCMS_TRC_PARAMETRIC, // Not implemented.
QCMS_TRC_FLOAT, // Not implemented.
QCMS_TRC_HALF_FLOAT, // IEE754: binary16.
QCMS_TRC_USHORT, // 0.16 fixed point.
} qcms_trc_type;
/* Output data of specific channel curve for qcms_profile_get_parametric_curve() */
typedef enum {
QCMS_TRC_RED,
QCMS_TRC_GREEN,
QCMS_TRC_BLUE,
} qcms_trc_channel;
typedef struct {
double x;
double y;
double Y;
} qcms_CIE_xyY;
typedef struct {
qcms_CIE_xyY red;
qcms_CIE_xyY green;
qcms_CIE_xyY blue;
} qcms_CIE_xyYTRIPLE;
typedef struct {
float X;
float Y;
float Z;
} qcms_xyz_float;
qcms_profile* qcms_profile_create_rgb_with_gamma(
qcms_CIE_xyY white_point,
qcms_CIE_xyYTRIPLE primaries,
float gamma);
qcms_profile* qcms_profile_from_memory(const void *mem, size_t size);
qcms_profile* qcms_profile_from_file(FILE *file);
qcms_profile* qcms_profile_from_path(const char *path);
#ifdef _WIN32
qcms_profile* qcms_profile_from_unicode_path(const wchar_t *path);
#endif
qcms_profile* qcms_profile_sRGB(void);
void qcms_profile_release(qcms_profile *profile);
qcms_bool qcms_profile_is_bogus(qcms_profile *profile);
qcms_bool qcms_profile_has_white_point(qcms_profile *profile);
qcms_xyz_float qcms_profile_get_white_point(qcms_profile *profile);
qcms_intent qcms_profile_get_rendering_intent(qcms_profile *profile);
qcms_color_space qcms_profile_get_color_space(qcms_profile *profile);
unsigned qcms_profile_get_version(qcms_profile *profile);
qcms_bool qcms_profile_white_transform(qcms_profile *profile, float XYZ[3]);
qcms_bool qcms_profile_match(qcms_profile *p1, qcms_profile *p2);
const char* qcms_profile_get_description(qcms_profile *profile);
void qcms_profile_precache_output_transform(qcms_profile *profile);
size_t qcms_profile_get_vcgt_channel_length(qcms_profile *profile);
qcms_bool qcms_profile_get_vcgt_rgb_channels(qcms_profile *profile, unsigned short *data);
float qcms_profile_ntsc_relative_gamut_size(qcms_profile *profile);
size_t qcms_profile_get_parametric_curve(qcms_profile *profile, qcms_trc_channel channel, float data[7]);
qcms_transform* qcms_transform_create(
qcms_profile *in, qcms_data_type in_type,
qcms_profile *out, qcms_data_type out_type,
qcms_intent intent);
size_t qcms_transform_get_input_trc_rgba(
qcms_transform *transform, qcms_profile *in, qcms_trc_type type, unsigned short *data);
size_t qcms_transform_get_output_trc_rgba(
qcms_transform *transform, qcms_profile *out, qcms_trc_type type, unsigned short *data);
qcms_bool qcms_transform_is_matrix(qcms_transform *transform);
float qcms_transform_get_matrix(qcms_transform *transform, unsigned i, unsigned j);
qcms_bool qcms_transform_create_LUT_zyx_bgra(
qcms_profile *in, qcms_profile *out, qcms_intent intent,
int samples, unsigned char* lut);
void qcms_transform_data(qcms_transform *transform, void *src, void *dest, size_t length);
void qcms_transform_data_type(qcms_transform *transform, void *src, void *dest, size_t length, qcms_output_type type);
void qcms_transform_release(qcms_transform *);
void qcms_enable_iccv4();
#ifdef __cplusplus
}
#endif
/*
* In general, QCMS is not threadsafe. However, it should be safe to create
* profile and transformation objects on different threads, so long as you
* don't use the same objects on different threads at the same time.
*/
#endif
| null | null | null | null | 24,421 |
58,673 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 58,673 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#include <stddef.h>
#include "chrome/browser/chromeos/profiles/profile_helper.h"
#include "chrome/browser/extensions/extension_assets_manager_chromeos.h"
#include "chrome/browser/extensions/extension_garbage_collector_chromeos.h"
#include "components/user_manager/user_manager.h"
#include "extensions/browser/extension_file_task_runner.h"
namespace extensions {
bool ExtensionGarbageCollectorChromeOS::shared_extensions_garbage_collected_ =
false;
ExtensionGarbageCollectorChromeOS::ExtensionGarbageCollectorChromeOS(
content::BrowserContext* context)
: ExtensionGarbageCollector(context),
disable_garbage_collection_(false) {
}
ExtensionGarbageCollectorChromeOS::~ExtensionGarbageCollectorChromeOS() {}
// static
ExtensionGarbageCollectorChromeOS* ExtensionGarbageCollectorChromeOS::Get(
content::BrowserContext* context) {
return static_cast<ExtensionGarbageCollectorChromeOS*>(
ExtensionGarbageCollector::Get(context));
}
// static
void ExtensionGarbageCollectorChromeOS::ClearGarbageCollectedForTesting() {
shared_extensions_garbage_collected_ = false;
}
void ExtensionGarbageCollectorChromeOS::GarbageCollectExtensions() {
if (disable_garbage_collection_)
return;
// Process per-profile extensions dir.
ExtensionGarbageCollector::GarbageCollectExtensions();
if (!shared_extensions_garbage_collected_ &&
CanGarbageCollectSharedExtensions()) {
GarbageCollectSharedExtensions();
shared_extensions_garbage_collected_ = true;
}
}
bool ExtensionGarbageCollectorChromeOS::CanGarbageCollectSharedExtensions() {
user_manager::UserManager* user_manager = user_manager::UserManager::Get();
if (!user_manager) {
NOTREACHED();
return false;
}
const user_manager::UserList& active_users = user_manager->GetLoggedInUsers();
for (size_t i = 0; i < active_users.size(); i++) {
// If the profile for one of the active users is still initializing, we
// can't garbage collect.
if (!active_users[i]->is_profile_created())
return false;
Profile* profile =
chromeos::ProfileHelper::Get()->GetProfileByUserUnsafe(active_users[i]);
ExtensionGarbageCollectorChromeOS* gc =
ExtensionGarbageCollectorChromeOS::Get(profile);
if (gc && gc->crx_installs_in_progress_ > 0)
return false;
}
return true;
}
void ExtensionGarbageCollectorChromeOS::GarbageCollectSharedExtensions() {
std::multimap<std::string, base::FilePath> paths;
if (ExtensionAssetsManagerChromeOS::CleanUpSharedExtensions(&paths)) {
if (!GetExtensionFileTaskRunner()->PostTask(
FROM_HERE,
base::Bind(&GarbageCollectExtensionsOnFileThread,
ExtensionAssetsManagerChromeOS::GetSharedInstallDir(),
paths))) {
NOTREACHED();
}
}
}
} // namespace extensions
| null | null | null | null | 55,536 |
38,839 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 38,839 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_AUDIO_WORKLET_PROCESSOR_DEFINITION_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_AUDIO_WORKLET_PROCESSOR_DEFINITION_H_
#include "third_party/blink/renderer/modules/modules_export.h"
#include "third_party/blink/renderer/modules/webaudio/audio_param_descriptor.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/bindings/trace_wrapper_v8_reference.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "v8/include/v8.h"
namespace blink {
// Represents a JavaScript class definition registered in the
// AudioWorkletGlobalScope. After the registration, a definition class contains
// the V8 representation of class components (constructor, process callback,
// prototypes and parameter descriptors).
//
// This is constructed and destroyed on a worker thread, and all methods also
// must be called on the worker thread.
class MODULES_EXPORT AudioWorkletProcessorDefinition final
: public GarbageCollectedFinalized<AudioWorkletProcessorDefinition>,
public TraceWrapperBase {
public:
static AudioWorkletProcessorDefinition* Create(
v8::Isolate*,
const String& name,
v8::Local<v8::Object> constructor,
v8::Local<v8::Function> process);
virtual ~AudioWorkletProcessorDefinition();
const String& GetName() const { return name_; }
v8::Local<v8::Object> ConstructorLocal(v8::Isolate*);
v8::Local<v8::Function> ProcessLocal(v8::Isolate*);
void SetAudioParamDescriptors(const HeapVector<AudioParamDescriptor>&);
const Vector<String> GetAudioParamDescriptorNames() const;
const AudioParamDescriptor* GetAudioParamDescriptor(const String& key) const;
// Flag for data synchronization of definition between
// AudioWorkletMessagingProxy and AudioWorkletGlobalScope.
bool IsSynchronized() const { return is_synchronized_; }
void MarkAsSynchronized() { is_synchronized_ = true; }
void Trace(blink::Visitor* visitor) {
visitor->Trace(audio_param_descriptors_);
};
void TraceWrappers(const ScriptWrappableVisitor*) const override;
const char* NameInHeapSnapshot() const override {
return "AudioWorkletProcessorDefinition";
}
private:
AudioWorkletProcessorDefinition(
v8::Isolate*,
const String& name,
v8::Local<v8::Object> constructor,
v8::Local<v8::Function> process);
const String name_;
bool is_synchronized_ = false;
// The definition is per global scope. The active instance of
// |AudioProcessorWorklet| should be passed into these to perform JS function.
TraceWrapperV8Reference<v8::Object> constructor_;
TraceWrapperV8Reference<v8::Function> process_;
HeapVector<AudioParamDescriptor> audio_param_descriptors_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_WEBAUDIO_AUDIO_WORKLET_PROCESSOR_DEFINITION_H_
| null | null | null | null | 35,702 |
16,238 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 181,233 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
#ifndef __AU1X00_PROM_H
#define __AU1X00_PROM_H
extern int prom_argc;
extern char **prom_argv;
extern char **prom_envp;
extern void prom_init_cmdline(void);
extern char *prom_getenv(char *envname);
extern int prom_get_ethernet_addr(char *ethernet_addr);
#endif
| null | null | null | null | 89,580 |
25,688 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 190,683 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Copyright 2014 Advanced Micro Devices, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER(S) OR AUTHOR(S) BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "kfd_priv.h"
#include <linux/mm.h>
#include <linux/mman.h>
#include <linux/slab.h>
#include <linux/io.h>
/*
* This extension supports a kernel level doorbells management for
* the kernel queues.
* Basically the last doorbells page is devoted to kernel queues
* and that's assures that any user process won't get access to the
* kernel doorbells page
*/
#define KERNEL_DOORBELL_PASID 1
#define KFD_SIZE_OF_DOORBELL_IN_BYTES 4
/*
* Each device exposes a doorbell aperture, a PCI MMIO aperture that
* receives 32-bit writes that are passed to queues as wptr values.
* The doorbells are intended to be written by applications as part
* of queueing work on user-mode queues.
* We assign doorbells to applications in PAGE_SIZE-sized and aligned chunks.
* We map the doorbell address space into user-mode when a process creates
* its first queue on each device.
* Although the mapping is done by KFD, it is equivalent to an mmap of
* the /dev/kfd with the particular device encoded in the mmap offset.
* There will be other uses for mmap of /dev/kfd, so only a range of
* offsets (KFD_MMAP_DOORBELL_START-END) is used for doorbells.
*/
/* # of doorbell bytes allocated for each process. */
static inline size_t doorbell_process_allocation(void)
{
return roundup(KFD_SIZE_OF_DOORBELL_IN_BYTES *
KFD_MAX_NUM_OF_QUEUES_PER_PROCESS,
PAGE_SIZE);
}
/* Doorbell calculations for device init. */
void kfd_doorbell_init(struct kfd_dev *kfd)
{
size_t doorbell_start_offset;
size_t doorbell_aperture_size;
size_t doorbell_process_limit;
/*
* We start with calculations in bytes because the input data might
* only be byte-aligned.
* Only after we have done the rounding can we assume any alignment.
*/
doorbell_start_offset =
roundup(kfd->shared_resources.doorbell_start_offset,
doorbell_process_allocation());
doorbell_aperture_size =
rounddown(kfd->shared_resources.doorbell_aperture_size,
doorbell_process_allocation());
if (doorbell_aperture_size > doorbell_start_offset)
doorbell_process_limit =
(doorbell_aperture_size - doorbell_start_offset) /
doorbell_process_allocation();
else
doorbell_process_limit = 0;
kfd->doorbell_base = kfd->shared_resources.doorbell_physical_address +
doorbell_start_offset;
kfd->doorbell_id_offset = doorbell_start_offset / sizeof(u32);
kfd->doorbell_process_limit = doorbell_process_limit - 1;
kfd->doorbell_kernel_ptr = ioremap(kfd->doorbell_base,
doorbell_process_allocation());
BUG_ON(!kfd->doorbell_kernel_ptr);
pr_debug("kfd: doorbell initialization:\n");
pr_debug("kfd: doorbell base == 0x%08lX\n",
(uintptr_t)kfd->doorbell_base);
pr_debug("kfd: doorbell_id_offset == 0x%08lX\n",
kfd->doorbell_id_offset);
pr_debug("kfd: doorbell_process_limit == 0x%08lX\n",
doorbell_process_limit);
pr_debug("kfd: doorbell_kernel_offset == 0x%08lX\n",
(uintptr_t)kfd->doorbell_base);
pr_debug("kfd: doorbell aperture size == 0x%08lX\n",
kfd->shared_resources.doorbell_aperture_size);
pr_debug("kfd: doorbell kernel address == 0x%08lX\n",
(uintptr_t)kfd->doorbell_kernel_ptr);
}
int kfd_doorbell_mmap(struct kfd_process *process, struct vm_area_struct *vma)
{
phys_addr_t address;
struct kfd_dev *dev;
/*
* For simplicitly we only allow mapping of the entire doorbell
* allocation of a single device & process.
*/
if (vma->vm_end - vma->vm_start != doorbell_process_allocation())
return -EINVAL;
/* Find kfd device according to gpu id */
dev = kfd_device_by_id(vma->vm_pgoff);
if (dev == NULL)
return -EINVAL;
/* Calculate physical address of doorbell */
address = kfd_get_process_doorbells(dev, process);
vma->vm_flags |= VM_IO | VM_DONTCOPY | VM_DONTEXPAND | VM_NORESERVE |
VM_DONTDUMP | VM_PFNMAP;
vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot);
pr_debug("kfd: mapping doorbell page in %s\n"
" target user address == 0x%08llX\n"
" physical address == 0x%08llX\n"
" vm_flags == 0x%04lX\n"
" size == 0x%04lX\n",
__func__,
(unsigned long long) vma->vm_start, address, vma->vm_flags,
doorbell_process_allocation());
return io_remap_pfn_range(vma,
vma->vm_start,
address >> PAGE_SHIFT,
doorbell_process_allocation(),
vma->vm_page_prot);
}
/* get kernel iomem pointer for a doorbell */
u32 __iomem *kfd_get_kernel_doorbell(struct kfd_dev *kfd,
unsigned int *doorbell_off)
{
u32 inx;
BUG_ON(!kfd || !doorbell_off);
mutex_lock(&kfd->doorbell_mutex);
inx = find_first_zero_bit(kfd->doorbell_available_index,
KFD_MAX_NUM_OF_QUEUES_PER_PROCESS);
__set_bit(inx, kfd->doorbell_available_index);
mutex_unlock(&kfd->doorbell_mutex);
if (inx >= KFD_MAX_NUM_OF_QUEUES_PER_PROCESS)
return NULL;
/*
* Calculating the kernel doorbell offset using "faked" kernel
* pasid that allocated for kernel queues only
*/
*doorbell_off = KERNEL_DOORBELL_PASID * (doorbell_process_allocation() /
sizeof(u32)) + inx;
pr_debug("kfd: get kernel queue doorbell\n"
" doorbell offset == 0x%08X\n"
" kernel address == 0x%08lX\n",
*doorbell_off, (uintptr_t)(kfd->doorbell_kernel_ptr + inx));
return kfd->doorbell_kernel_ptr + inx;
}
void kfd_release_kernel_doorbell(struct kfd_dev *kfd, u32 __iomem *db_addr)
{
unsigned int inx;
BUG_ON(!kfd || !db_addr);
inx = (unsigned int)(db_addr - kfd->doorbell_kernel_ptr);
mutex_lock(&kfd->doorbell_mutex);
__clear_bit(inx, kfd->doorbell_available_index);
mutex_unlock(&kfd->doorbell_mutex);
}
inline void write_kernel_doorbell(u32 __iomem *db, u32 value)
{
if (db) {
writel(value, db);
pr_debug("writing %d to doorbell address 0x%p\n", value, db);
}
}
/*
* queue_ids are in the range [0,MAX_PROCESS_QUEUES) and are mapped 1:1
* to doorbells with the process's doorbell page
*/
unsigned int kfd_queue_id_to_doorbell(struct kfd_dev *kfd,
struct kfd_process *process,
unsigned int queue_id)
{
/*
* doorbell_id_offset accounts for doorbells taken by KGD.
* pasid * doorbell_process_allocation/sizeof(u32) adjusts
* to the process's doorbells
*/
return kfd->doorbell_id_offset +
process->pasid * (doorbell_process_allocation()/sizeof(u32)) +
queue_id;
}
uint64_t kfd_get_number_elems(struct kfd_dev *kfd)
{
uint64_t num_of_elems = (kfd->shared_resources.doorbell_aperture_size -
kfd->shared_resources.doorbell_start_offset) /
doorbell_process_allocation() + 1;
return num_of_elems;
}
phys_addr_t kfd_get_process_doorbells(struct kfd_dev *dev,
struct kfd_process *process)
{
return dev->doorbell_base +
process->pasid * doorbell_process_allocation();
}
| null | null | null | null | 99,030 |
53,806 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 53,806 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 ANDROID_WEBVIEW_BROWSER_PARENT_OUTPUT_SURFACE_H_
#define ANDROID_WEBVIEW_BROWSER_PARENT_OUTPUT_SURFACE_H_
#include "base/macros.h"
#include "components/viz/service/display/output_surface.h"
namespace android_webview {
class AwRenderThreadContextProvider;
class ParentOutputSurface : public viz::OutputSurface {
public:
explicit ParentOutputSurface(
scoped_refptr<AwRenderThreadContextProvider> context_provider);
~ParentOutputSurface() override;
// OutputSurface overrides.
void BindToClient(viz::OutputSurfaceClient* client) override;
void EnsureBackbuffer() override;
void DiscardBackbuffer() override;
void BindFramebuffer() override;
void SetDrawRectangle(const gfx::Rect& rect) override;
void Reshape(const gfx::Size& size,
float scale_factor,
const gfx::ColorSpace& color_space,
bool has_alpha,
bool use_stencil) override;
void SwapBuffers(viz::OutputSurfaceFrame frame) override;
bool HasExternalStencilTest() const override;
void ApplyExternalStencil() override;
uint32_t GetFramebufferCopyTextureFormat() override;
viz::OverlayCandidateValidator* GetOverlayCandidateValidator() const override;
bool IsDisplayedAsOverlayPlane() const override;
unsigned GetOverlayTextureId() const override;
gfx::BufferFormat GetOverlayBufferFormat() const override;
bool SurfaceIsSuspendForRecycle() const override;
private:
DISALLOW_COPY_AND_ASSIGN(ParentOutputSurface);
};
} // namespace android_webview
#endif // ANDROID_WEBVIEW_BROWSER_PARENT_OUTPUT_SURFACE_H_
| null | null | null | null | 50,669 |
35,154 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 35,154 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/*
* Copyright (C) 2011 Google Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_VTT_VTT_TOKENIZER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_TRACK_VTT_VTT_TOKENIZER_H_
#include "base/macros.h"
#include "third_party/blink/renderer/core/html/parser/input_stream_preprocessor.h"
#include "third_party/blink/renderer/core/html/track/vtt/vtt_token.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
namespace blink {
class VTTTokenizer {
DISALLOW_NEW();
public:
explicit VTTTokenizer(const String& input);
bool NextToken(VTTToken&);
inline bool ShouldSkipNullCharacters() const { return true; }
private:
SegmentedString input_;
// ://www.whatwg.org/specs/web-apps/current-work/#preprocessing-the-input-stream
InputStreamPreprocessor<VTTTokenizer> input_stream_preprocessor_;
DISALLOW_COPY_AND_ASSIGN(VTTTokenizer);
};
} // namespace blink
#endif
| null | null | null | null | 32,017 |
343 | null |
train_val
|
1b0d3845b454eaaac0b2064c78926ca4d739a080
| 262,911 |
qemu
| 0 |
https://github.com/bonzini/qemu
|
2016-10-18 11:40:27+01:00
|
/*
* i386 specific structures for linux-user
*
* Copyright (c) 2013 Fabrice Bellard
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, see <http://www.gnu.org/licenses/>.
*/
#ifndef I386_TARGET_STRUCTS_H
#define I386_TARGET_STRUCTS_H
struct target_ipc_perm {
abi_int __key; /* Key. */
abi_uint uid; /* Owner's user ID. */
abi_uint gid; /* Owner's group ID. */
abi_uint cuid; /* Creator's user ID. */
abi_uint cgid; /* Creator's group ID. */
abi_ushort mode; /* Read/write permission. */
abi_ushort __pad1;
abi_ushort __seq; /* Sequence number. */
abi_ushort __pad2;
abi_ulong __unused1;
abi_ulong __unused2;
};
struct target_shmid_ds {
struct target_ipc_perm shm_perm; /* operation permission struct */
abi_long shm_segsz; /* size of segment in bytes */
abi_ulong shm_atime; /* time of last shmat() */
#if TARGET_ABI_BITS == 32
abi_ulong __unused1;
#endif
abi_ulong shm_dtime; /* time of last shmdt() */
#if TARGET_ABI_BITS == 32
abi_ulong __unused2;
#endif
abi_ulong shm_ctime; /* time of last change by shmctl() */
#if TARGET_ABI_BITS == 32
abi_ulong __unused3;
#endif
abi_int shm_cpid; /* pid of creator */
abi_int shm_lpid; /* pid of last shmop */
abi_ulong shm_nattch; /* number of current attaches */
abi_ulong __unused4;
abi_ulong __unused5;
};
#endif
| null | null | null | null | 121,035 |
69,574 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 69,574 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/*
* -------------------------------------------------------------
*
* Module: sem_close.c
*
* Purpose:
* Semaphores aren't actually part of the PThreads standard.
* They are defined by the POSIX Standard:
*
* POSIX 1003.1b-1993 (POSIX.1b)
*
* -------------------------------------------------------------
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: [email protected]
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.html
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "semaphore.h"
#include "implement.h"
/* ignore warning "unreferenced formal parameter" */
#if defined(_MSC_VER)
#pragma warning( disable : 4100 )
#endif
int
sem_close (sem_t * sem)
{
errno = ENOSYS;
return -1;
} /* sem_close */
| null | null | null | null | 66,437 |
5,789 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 5,789 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 "chromeos/dbus/blocking_method_caller.h"
#include <memory>
#include <string>
#include <utility>
#include "base/callback.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/task_runner.h"
#include "dbus/message.h"
#include "dbus/mock_bus.h"
#include "dbus/mock_object_proxy.h"
#include "dbus/object_path.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
using ::testing::_;
using ::testing::Invoke;
using ::testing::Return;
namespace chromeos {
namespace {
class FakeTaskRunner : public base::TaskRunner {
public:
bool PostDelayedTask(const base::Location& from_here,
base::OnceClosure task,
base::TimeDelta delay) override {
std::move(task).Run();
return true;
}
bool RunsTasksInCurrentSequence() const override { return true; }
protected:
~FakeTaskRunner() override = default;
};
} // namespace
class BlockingMethodCallerTest : public testing::Test {
public:
BlockingMethodCallerTest() : task_runner_(new FakeTaskRunner) {
}
void SetUp() override {
// Create a mock bus.
dbus::Bus::Options options;
options.bus_type = dbus::Bus::SYSTEM;
mock_bus_ = new dbus::MockBus(options);
// Create a mock proxy.
mock_proxy_ = new dbus::MockObjectProxy(
mock_bus_.get(),
"org.chromium.TestService",
dbus::ObjectPath("/org/chromium/TestObject"));
// Set an expectation so mock_proxy's CallMethodAndBlock() will use
// CreateMockProxyResponse() to return responses.
EXPECT_CALL(*mock_proxy_.get(),
CallMethodAndBlockWithErrorDetails(_, _, _))
.WillRepeatedly(
Invoke(this, &BlockingMethodCallerTest::CreateMockProxyResponse));
// Set an expectation so mock_bus's GetObjectProxy() for the given
// service name and the object path will return mock_proxy_.
EXPECT_CALL(*mock_bus_.get(),
GetObjectProxy("org.chromium.TestService",
dbus::ObjectPath("/org/chromium/TestObject")))
.WillOnce(Return(mock_proxy_.get()));
// Set an expectation so mock_bus's GetDBusTaskRunner will return the fake
// task runner.
EXPECT_CALL(*mock_bus_.get(), GetDBusTaskRunner())
.WillRepeatedly(Return(task_runner_.get()));
// ShutdownAndBlock() will be called in TearDown().
EXPECT_CALL(*mock_bus_.get(), ShutdownAndBlock()).WillOnce(Return());
}
void TearDown() override { mock_bus_->ShutdownAndBlock(); }
protected:
scoped_refptr<FakeTaskRunner> task_runner_;
scoped_refptr<dbus::MockBus> mock_bus_;
scoped_refptr<dbus::MockObjectProxy> mock_proxy_;
private:
// Returns a response for the given method call. Used to implement
// CallMethodAndBlock() for |mock_proxy_|.
std::unique_ptr<dbus::Response> CreateMockProxyResponse(
dbus::MethodCall* method_call,
int timeout_ms,
dbus::ScopedDBusError* error) {
if (method_call->GetInterface() == "org.chromium.TestInterface" &&
method_call->GetMember() == "Echo") {
dbus::MessageReader reader(method_call);
std::string text_message;
if (reader.PopString(&text_message)) {
std::unique_ptr<dbus::Response> response =
dbus::Response::CreateEmpty();
dbus::MessageWriter writer(response.get());
writer.AppendString(text_message);
return response;
}
}
LOG(ERROR) << "Unexpected method call: " << method_call->ToString();
return nullptr;
}
};
TEST_F(BlockingMethodCallerTest, Echo) {
const char kHello[] = "Hello";
// Get an object proxy from the mock bus.
dbus::ObjectProxy* proxy = mock_bus_->GetObjectProxy(
"org.chromium.TestService",
dbus::ObjectPath("/org/chromium/TestObject"));
// Create a method call.
dbus::MethodCall method_call("org.chromium.TestInterface", "Echo");
dbus::MessageWriter writer(&method_call);
writer.AppendString(kHello);
// Call the method.
BlockingMethodCaller blocking_method_caller(mock_bus_.get(), proxy);
std::unique_ptr<dbus::Response> response(
blocking_method_caller.CallMethodAndBlock(&method_call));
// Check the response.
ASSERT_TRUE(response.get());
dbus::MessageReader reader(response.get());
std::string text_message;
ASSERT_TRUE(reader.PopString(&text_message));
// The text message should be echo'ed back.
EXPECT_EQ(kHello, text_message);
}
} // namespace chromeos
| null | null | null | null | 2,652 |
44 |
17,18,19,20,21,22,23,24,25,26,27,28,29
|
train_val
|
b51b33f2bc5d1497ddf5bd107f791c101695000d
| 161,888 |
krb5
| 1 |
https://github.com/krb5/krb5
|
2015-10-26 12:38:24-04:00
|
spnego_gss_delete_sec_context(
OM_uint32 *minor_status,
gss_ctx_id_t *context_handle,
gss_buffer_t output_token)
{
OM_uint32 ret = GSS_S_COMPLETE;
spnego_gss_ctx_id_t *ctx =
(spnego_gss_ctx_id_t *)context_handle;
*minor_status = 0;
if (context_handle == NULL)
return (GSS_S_FAILURE);
if (*ctx == NULL)
return (GSS_S_COMPLETE);
/*
* If this is still an SPNEGO mech, release it locally.
*
if ((*ctx)->magic_num == SPNEGO_MAGIC_ID) {
(void) gss_delete_sec_context(minor_status,
&(*ctx)->ctx_handle,
output_token);
(void) release_spnego_ctx(ctx);
} else {
ret = gss_delete_sec_context(minor_status,
context_handle,
output_token);
}
return (ret);
}
|
CVE-2015-2695
|
CWE-18
|
https://github.com/krb5/krb5/commit/b51b33f2bc5d1497ddf5bd107f791c101695000d
|
Medium
| 2,849 |
54,708 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 54,708 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 <string>
#include "ppapi/cpp/instance.h"
#include "ppapi/cpp/module.h"
#include "ppapi/cpp/var.h"
class SimpleInstance : public pp::Instance {
public:
explicit SimpleInstance(PP_Instance instance) : pp::Instance(instance) {
}
virtual void HandleMessage(const pp::Var& var_message) {
if (var_message.is_string() && var_message.AsString() == "ping") {
PostMessage(pp::Var("pong"));
return;
}
PostMessage(pp::Var("failed"));
}
};
class SimpleModule : public pp::Module {
public:
virtual pp::Instance* CreateInstance(PP_Instance instance) {
return new SimpleInstance(instance);
}
};
namespace pp {
__attribute__((visibility("default")))
Module* CreateModule() {
return new SimpleModule();
}
} // namespace pp
| null | null | null | null | 51,571 |
12,402 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 177,397 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* PowerNV OPAL Dump Interface
*
* Copyright 2013,2014 IBM Corp.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version
* 2 of the License, or (at your option) any later version.
*/
#include <linux/kobject.h>
#include <linux/mm.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <asm/opal.h>
#define DUMP_TYPE_FSP 0x01
struct dump_obj {
struct kobject kobj;
struct bin_attribute dump_attr;
uint32_t id; /* becomes object name */
uint32_t type;
uint32_t size;
char *buffer;
};
#define to_dump_obj(x) container_of(x, struct dump_obj, kobj)
struct dump_attribute {
struct attribute attr;
ssize_t (*show)(struct dump_obj *dump, struct dump_attribute *attr,
char *buf);
ssize_t (*store)(struct dump_obj *dump, struct dump_attribute *attr,
const char *buf, size_t count);
};
#define to_dump_attr(x) container_of(x, struct dump_attribute, attr)
static ssize_t dump_id_show(struct dump_obj *dump_obj,
struct dump_attribute *attr,
char *buf)
{
return sprintf(buf, "0x%x\n", dump_obj->id);
}
static const char* dump_type_to_string(uint32_t type)
{
switch (type) {
case 0x01: return "SP Dump";
case 0x02: return "System/Platform Dump";
case 0x03: return "SMA Dump";
default: return "unknown";
}
}
static ssize_t dump_type_show(struct dump_obj *dump_obj,
struct dump_attribute *attr,
char *buf)
{
return sprintf(buf, "0x%x %s\n", dump_obj->type,
dump_type_to_string(dump_obj->type));
}
static ssize_t dump_ack_show(struct dump_obj *dump_obj,
struct dump_attribute *attr,
char *buf)
{
return sprintf(buf, "ack - acknowledge dump\n");
}
/*
* Send acknowledgement to OPAL
*/
static int64_t dump_send_ack(uint32_t dump_id)
{
int rc;
rc = opal_dump_ack(dump_id);
if (rc)
pr_warn("%s: Failed to send ack to Dump ID 0x%x (%d)\n",
__func__, dump_id, rc);
return rc;
}
static ssize_t dump_ack_store(struct dump_obj *dump_obj,
struct dump_attribute *attr,
const char *buf,
size_t count)
{
dump_send_ack(dump_obj->id);
sysfs_remove_file_self(&dump_obj->kobj, &attr->attr);
kobject_put(&dump_obj->kobj);
return count;
}
/* Attributes of a dump
* The binary attribute of the dump itself is dynamic
* due to the dynamic size of the dump
*/
static struct dump_attribute id_attribute =
__ATTR(id, S_IRUGO, dump_id_show, NULL);
static struct dump_attribute type_attribute =
__ATTR(type, S_IRUGO, dump_type_show, NULL);
static struct dump_attribute ack_attribute =
__ATTR(acknowledge, 0660, dump_ack_show, dump_ack_store);
static ssize_t init_dump_show(struct dump_obj *dump_obj,
struct dump_attribute *attr,
char *buf)
{
return sprintf(buf, "1 - initiate Service Processor(FSP) dump\n");
}
static int64_t dump_fips_init(uint8_t type)
{
int rc;
rc = opal_dump_init(type);
if (rc)
pr_warn("%s: Failed to initiate FSP dump (%d)\n",
__func__, rc);
return rc;
}
static ssize_t init_dump_store(struct dump_obj *dump_obj,
struct dump_attribute *attr,
const char *buf,
size_t count)
{
int rc;
rc = dump_fips_init(DUMP_TYPE_FSP);
if (rc == OPAL_SUCCESS)
pr_info("%s: Initiated FSP dump\n", __func__);
return count;
}
static struct dump_attribute initiate_attribute =
__ATTR(initiate_dump, 0600, init_dump_show, init_dump_store);
static struct attribute *initiate_attrs[] = {
&initiate_attribute.attr,
NULL,
};
static struct attribute_group initiate_attr_group = {
.attrs = initiate_attrs,
};
static struct kset *dump_kset;
static ssize_t dump_attr_show(struct kobject *kobj,
struct attribute *attr,
char *buf)
{
struct dump_attribute *attribute;
struct dump_obj *dump;
attribute = to_dump_attr(attr);
dump = to_dump_obj(kobj);
if (!attribute->show)
return -EIO;
return attribute->show(dump, attribute, buf);
}
static ssize_t dump_attr_store(struct kobject *kobj,
struct attribute *attr,
const char *buf, size_t len)
{
struct dump_attribute *attribute;
struct dump_obj *dump;
attribute = to_dump_attr(attr);
dump = to_dump_obj(kobj);
if (!attribute->store)
return -EIO;
return attribute->store(dump, attribute, buf, len);
}
static const struct sysfs_ops dump_sysfs_ops = {
.show = dump_attr_show,
.store = dump_attr_store,
};
static void dump_release(struct kobject *kobj)
{
struct dump_obj *dump;
dump = to_dump_obj(kobj);
vfree(dump->buffer);
kfree(dump);
}
static struct attribute *dump_default_attrs[] = {
&id_attribute.attr,
&type_attribute.attr,
&ack_attribute.attr,
NULL,
};
static struct kobj_type dump_ktype = {
.sysfs_ops = &dump_sysfs_ops,
.release = &dump_release,
.default_attrs = dump_default_attrs,
};
static int64_t dump_read_info(uint32_t *dump_id, uint32_t *dump_size, uint32_t *dump_type)
{
__be32 id, size, type;
int rc;
type = cpu_to_be32(0xffffffff);
rc = opal_dump_info2(&id, &size, &type);
if (rc == OPAL_PARAMETER)
rc = opal_dump_info(&id, &size);
*dump_id = be32_to_cpu(id);
*dump_size = be32_to_cpu(size);
*dump_type = be32_to_cpu(type);
if (rc)
pr_warn("%s: Failed to get dump info (%d)\n",
__func__, rc);
return rc;
}
static int64_t dump_read_data(struct dump_obj *dump)
{
struct opal_sg_list *list;
uint64_t addr;
int64_t rc;
/* Allocate memory */
dump->buffer = vzalloc(PAGE_ALIGN(dump->size));
if (!dump->buffer) {
pr_err("%s : Failed to allocate memory\n", __func__);
rc = -ENOMEM;
goto out;
}
/* Generate SG list */
list = opal_vmalloc_to_sg_list(dump->buffer, dump->size);
if (!list) {
rc = -ENOMEM;
goto out;
}
/* First entry address */
addr = __pa(list);
/* Fetch data */
rc = OPAL_BUSY_EVENT;
while (rc == OPAL_BUSY || rc == OPAL_BUSY_EVENT) {
rc = opal_dump_read(dump->id, addr);
if (rc == OPAL_BUSY_EVENT) {
opal_poll_events(NULL);
msleep(20);
}
}
if (rc != OPAL_SUCCESS && rc != OPAL_PARTIAL)
pr_warn("%s: Extract dump failed for ID 0x%x\n",
__func__, dump->id);
/* Free SG list */
opal_free_sg_list(list);
out:
return rc;
}
static ssize_t dump_attr_read(struct file *filep, struct kobject *kobj,
struct bin_attribute *bin_attr,
char *buffer, loff_t pos, size_t count)
{
ssize_t rc;
struct dump_obj *dump = to_dump_obj(kobj);
if (!dump->buffer) {
rc = dump_read_data(dump);
if (rc != OPAL_SUCCESS && rc != OPAL_PARTIAL) {
vfree(dump->buffer);
dump->buffer = NULL;
return -EIO;
}
if (rc == OPAL_PARTIAL) {
/* On a partial read, we just return EIO
* and rely on userspace to ask us to try
* again.
*/
pr_info("%s: Platform dump partially read. ID = 0x%x\n",
__func__, dump->id);
return -EIO;
}
}
memcpy(buffer, dump->buffer + pos, count);
/* You may think we could free the dump buffer now and retrieve
* it again later if needed, but due to current firmware limitation,
* that's not the case. So, once read into userspace once,
* we keep the dump around until it's acknowledged by userspace.
*/
return count;
}
static struct dump_obj *create_dump_obj(uint32_t id, size_t size,
uint32_t type)
{
struct dump_obj *dump;
int rc;
dump = kzalloc(sizeof(*dump), GFP_KERNEL);
if (!dump)
return NULL;
dump->kobj.kset = dump_kset;
kobject_init(&dump->kobj, &dump_ktype);
sysfs_bin_attr_init(&dump->dump_attr);
dump->dump_attr.attr.name = "dump";
dump->dump_attr.attr.mode = 0400;
dump->dump_attr.size = size;
dump->dump_attr.read = dump_attr_read;
dump->id = id;
dump->size = size;
dump->type = type;
rc = kobject_add(&dump->kobj, NULL, "0x%x-0x%x", type, id);
if (rc) {
kobject_put(&dump->kobj);
return NULL;
}
rc = sysfs_create_bin_file(&dump->kobj, &dump->dump_attr);
if (rc) {
kobject_put(&dump->kobj);
return NULL;
}
pr_info("%s: New platform dump. ID = 0x%x Size %u\n",
__func__, dump->id, dump->size);
kobject_uevent(&dump->kobj, KOBJ_ADD);
return dump;
}
static irqreturn_t process_dump(int irq, void *data)
{
int rc;
uint32_t dump_id, dump_size, dump_type;
struct dump_obj *dump;
char name[22];
struct kobject *kobj;
rc = dump_read_info(&dump_id, &dump_size, &dump_type);
if (rc != OPAL_SUCCESS)
return rc;
sprintf(name, "0x%x-0x%x", dump_type, dump_id);
/* we may get notified twice, let's handle
* that gracefully and not create two conflicting
* entries.
*/
kobj = kset_find_obj(dump_kset, name);
if (kobj) {
/* Drop reference added by kset_find_obj() */
kobject_put(kobj);
return 0;
}
dump = create_dump_obj(dump_id, dump_size, dump_type);
if (!dump)
return -1;
return IRQ_HANDLED;
}
void __init opal_platform_dump_init(void)
{
int rc;
int dump_irq;
/* ELOG not supported by firmware */
if (!opal_check_token(OPAL_DUMP_READ))
return;
dump_kset = kset_create_and_add("dump", NULL, opal_kobj);
if (!dump_kset) {
pr_warn("%s: Failed to create dump kset\n", __func__);
return;
}
rc = sysfs_create_group(&dump_kset->kobj, &initiate_attr_group);
if (rc) {
pr_warn("%s: Failed to create initiate dump attr group\n",
__func__);
kobject_put(&dump_kset->kobj);
return;
}
dump_irq = opal_event_request(ilog2(OPAL_EVENT_DUMP_AVAIL));
if (!dump_irq) {
pr_err("%s: Can't register OPAL event irq (%d)\n",
__func__, dump_irq);
return;
}
rc = request_threaded_irq(dump_irq, NULL, process_dump,
IRQF_TRIGGER_HIGH | IRQF_ONESHOT,
"opal-dump", NULL);
if (rc) {
pr_err("%s: Can't request OPAL event irq (%d)\n",
__func__, rc);
return;
}
if (opal_check_token(OPAL_DUMP_RESEND))
opal_dump_resend_notification();
}
| null | null | null | null | 85,744 |
51,038 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 51,038 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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 UI_MESSAGE_CENTER_MESSAGE_VIEW_FACTORY_H_
#define UI_MESSAGE_CENTER_MESSAGE_VIEW_FACTORY_H_
#include "ui/message_center/message_center_export.h"
#include <memory>
#include "base/callback_forward.h"
namespace message_center {
class MessageView;
class Notification;
// Creates appropriate MessageViews for notifications depending on the
// notification type. A notification is top level if it needs to be rendered
// outside the browser window. No custom shadows are created for top level
// notifications on Linux with Aura.
class MESSAGE_CENTER_EXPORT MessageViewFactory {
public:
// A function that creates MessageView for a NOTIFICATION_TYPE_CUSTOM
// notification.
typedef base::Callback<std::unique_ptr<MessageView>(const Notification&)>
CustomMessageViewFactoryFunction;
static MessageView* Create(const Notification& notification, bool top_level);
// Sets the function that will be invoked to create a custom notification
// view. This should be a repeating callback. It's an error to attempt to show
// a custom notification without first having called this function. Currently,
// only ARC uses custom notifications, so this doesn't need to distinguish
// between various sources of custom notification.
static void SetCustomNotificationViewFactory(
const CustomMessageViewFactoryFunction& factory_function);
// Returns whether the custom view factory function has already been set.
static bool HasCustomNotificationViewFactory();
};
} // namespace message_center
#endif // UI_MESSAGE_CENTER_MESSAGE_VIEW_FACTORY_H_
| null | null | null | null | 47,901 |
52,453 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 52,453 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 MEDIA_FORMATS_MP4_TRACK_RUN_ITERATOR_H_
#define MEDIA_FORMATS_MP4_TRACK_RUN_ITERATOR_H_
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <vector>
#include "base/macros.h"
#include "base/time/time.h"
#include "media/base/media_export.h"
#include "media/base/media_log.h"
#include "media/base/stream_parser_buffer.h"
#include "media/formats/mp4/box_definitions.h"
#include "media/media_buildflags.h"
namespace media {
class DecryptConfig;
namespace mp4 {
base::TimeDelta MEDIA_EXPORT TimeDeltaFromRational(int64_t numer,
int64_t denom);
DecodeTimestamp MEDIA_EXPORT DecodeTimestampFromRational(int64_t numer,
int64_t denom);
struct SampleInfo;
struct TrackRunInfo;
class MEDIA_EXPORT TrackRunIterator {
public:
// Create a new TrackRunIterator. A reference to |moov| will be retained for
// the lifetime of this object.
TrackRunIterator(const Movie* moov, MediaLog* media_log);
~TrackRunIterator();
// Sets up the iterator to handle all the runs from the current fragment.
bool Init(const MovieFragment& moof);
// Returns true if the properties of the current run or sample are valid.
bool IsRunValid() const;
bool IsSampleValid() const;
// Advance the properties to refer to the next run or sample. These return
// |false| on failure, but note that advancing to the end (IsRunValid() or
// IsSampleValid() return false) is not a failure, and the properties are not
// guaranteed to be consistent in that case.
bool AdvanceRun();
bool AdvanceSample();
// Returns true if this track run has auxiliary information and has not yet
// been cached. Only valid if IsRunValid().
bool AuxInfoNeedsToBeCached();
// Caches the CENC data from the given buffer. |buf| must be a buffer starting
// at the offset given by cenc_offset(), with a |size| of at least
// cenc_size(). Returns true on success, false on error.
bool CacheAuxInfo(const uint8_t* buf, int size);
// Returns the maximum buffer location at which no data earlier in the stream
// will be required in order to read the current or any subsequent sample. You
// may clear all data up to this offset before reading the current sample
// safely. Result is in the same units as offset() (for Media Source this is
// in bytes past the the head of the MOOF box).
int64_t GetMaxClearOffset();
// Property of the current run. Only valid if IsRunValid().
uint32_t track_id() const;
int64_t aux_info_offset() const;
int aux_info_size() const;
bool is_encrypted() const;
bool is_audio() const;
// Only one is valid, based on the value of is_audio().
const AudioSampleEntry& audio_description() const;
const VideoSampleEntry& video_description() const;
// Properties of the current sample. Only valid if IsSampleValid().
int64_t sample_offset() const;
uint32_t sample_size() const;
DecodeTimestamp dts() const;
base::TimeDelta cts() const;
base::TimeDelta duration() const;
bool is_keyframe() const;
// Only call when is_encrypted() is true and AuxInfoNeedsToBeCached() is
// false. Result is owned by caller.
std::unique_ptr<DecryptConfig> GetDecryptConfig();
private:
bool UpdateCts();
bool ResetRun();
const TrackEncryption& track_encryption() const;
uint32_t GetGroupDescriptionIndex(uint32_t sample_index) const;
// Sample encryption information.
bool IsSampleEncrypted(size_t sample_index) const;
uint8_t GetIvSize(size_t sample_index) const;
const std::vector<uint8_t>& GetKeyId(size_t sample_index) const;
#if BUILDFLAG(ENABLE_CBCS_ENCRYPTION_SCHEME)
bool ApplyConstantIv(size_t sample_index, SampleEncryptionEntry* entry) const;
#endif
const Movie* moov_;
MediaLog* media_log_;
std::vector<TrackRunInfo> runs_;
std::vector<TrackRunInfo>::const_iterator run_itr_;
std::vector<SampleInfo>::const_iterator sample_itr_;
int64_t sample_dts_;
int64_t sample_cts_;
int64_t sample_offset_;
DISALLOW_COPY_AND_ASSIGN(TrackRunIterator);
};
} // namespace mp4
} // namespace media
#endif // MEDIA_FORMATS_MP4_TRACK_RUN_ITERATOR_H_
| null | null | null | null | 49,316 |
57,982 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 57,982 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2013 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 CHROME_BROWSER_CHROMEOS_SYSTEM_TIMEZONE_UTIL_H_
#define CHROME_BROWSER_CHROMEOS_SYSTEM_TIMEZONE_UTIL_H_
#include <memory>
#include "base/strings/string16.h"
class Profile;
namespace base {
class ListValue;
}
namespace chromeos {
struct TimeZoneResponseData;
namespace system {
// Gets the current timezone's display name.
base::string16 GetCurrentTimezoneName();
// Creates a list of pairs of each timezone's ID and name.
std::unique_ptr<base::ListValue> GetTimezoneList();
// Returns true if device is managed and has SystemTimezonePolicy set.
bool HasSystemTimezonePolicy();
// Apply TimeZone update from TimeZoneProvider.
void ApplyTimeZone(const TimeZoneResponseData* timezone);
// Returns true if given timezone preference is enterprise-managed.
// Works for:
// - prefs::kUserTimezone
// - prefs::kResolveTimezoneByGeolocationMethod
bool IsTimezonePrefsManaged(const std::string& pref_name);
// Updates system timezone from user profile data if needed.
// This is called from chromeos::Preferences after updating profile
// preferences to apply new value to system time zone.
void UpdateSystemTimezone(Profile* profile);
// Updates Local State preference prefs::kSigninScreenTimezone AND
// also immediately sets system timezone (chromeos::system::TimezoneSettings).
// This is called when there is no user session (i.e. OOBE and signin screen),
// or when device policies are updated.
void SetSystemAndSigninScreenTimezone(const std::string& timezone);
// Returns true if per-user timezone preferences are enabled.
bool PerUserTimezoneEnabled();
// This is called from UI code to apply user-selected time zone.
void SetTimezoneFromUI(Profile* profile, const std::string& timezone_id);
// Returns true if fine-grained time zone detection is enabled.
bool FineGrainedTimeZoneDetectionEnabled();
} // namespace system
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_SYSTEM_TIMEZONE_UTIL_H_
| null | null | null | null | 54,845 |
15,225 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 15,225 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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_PROFILE_METRICS_COUNTS_H_
#define COMPONENTS_PROFILE_METRICS_COUNTS_H_
#include "base/metrics/histogram_base.h"
namespace profile_metrics {
struct Counts {
base::HistogramBase::Sample total;
base::HistogramBase::Sample signedin;
base::HistogramBase::Sample supervised;
base::HistogramBase::Sample unused;
base::HistogramBase::Sample gaia_icon;
base::HistogramBase::Sample auth_errors;
Counts()
: total(0),
signedin(0),
supervised(0),
unused(0),
gaia_icon(0),
auth_errors(0) {}
};
// Logs metrics related to |counts|.
void LogProfileMetricsCounts(const Counts& counts);
} // namespace profile_metrics
#endif // COMPONENTS_PROFILE_METRICS_COUNTS_H_
| null | null | null | null | 12,088 |
41,155 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 41,155 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 The Crashpad 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.
#include "client/annotation.h"
#include <string>
#include <vector>
#include "base/rand_util.h"
#include "client/crashpad_info.h"
#include "gtest/gtest.h"
#include "util/misc/clock.h"
#include "util/thread/thread.h"
namespace crashpad {
namespace test {
namespace {
TEST(AnnotationListStatic, Register) {
ASSERT_FALSE(AnnotationList::Get());
EXPECT_TRUE(AnnotationList::Register());
EXPECT_TRUE(AnnotationList::Get());
EXPECT_EQ(AnnotationList::Get(), AnnotationList::Register());
// This isn't expected usage of the AnnotationList API, but it is necessary
// for testing.
AnnotationList* list = AnnotationList::Get();
CrashpadInfo::GetCrashpadInfo()->set_annotations_list(nullptr);
delete list;
EXPECT_FALSE(AnnotationList::Get());
}
class AnnotationList : public testing::Test {
public:
void SetUp() override {
CrashpadInfo::GetCrashpadInfo()->set_annotations_list(&annotations_);
}
void TearDown() override {
CrashpadInfo::GetCrashpadInfo()->set_annotations_list(nullptr);
}
// NOTE: Annotations should be declared at file-scope, but in order to test
// them, they are declared as part of the test. These members are public so
// they are accessible from global helpers.
crashpad::StringAnnotation<8> one_{"First"};
crashpad::StringAnnotation<256> two_{"Second"};
crashpad::StringAnnotation<101> three_{"First"};
protected:
using AllAnnotations = std::vector<std::pair<std::string, std::string>>;
AllAnnotations CollectAnnotations() {
AllAnnotations annotations;
for (Annotation* curr : annotations_) {
if (!curr->is_set())
continue;
std::string value(static_cast<const char*>(curr->value()), curr->size());
annotations.push_back(std::make_pair(curr->name(), value));
}
return annotations;
}
bool ContainsNameValue(const AllAnnotations& annotations,
const std::string& name,
const std::string& value) {
return std::find(annotations.begin(),
annotations.end(),
std::make_pair(name, value)) != annotations.end();
}
crashpad::AnnotationList annotations_;
};
TEST_F(AnnotationList, SetAndClear) {
one_.Set("this is a value longer than 8 bytes");
AllAnnotations annotations = CollectAnnotations();
EXPECT_EQ(1u, annotations.size());
EXPECT_TRUE(ContainsNameValue(annotations, "First", "this is "));
one_.Clear();
EXPECT_EQ(0u, CollectAnnotations().size());
one_.Set("short");
two_.Set(std::string(500, 'A').data());
annotations = CollectAnnotations();
EXPECT_EQ(2u, annotations.size());
EXPECT_EQ(5u, one_.size());
EXPECT_EQ(256u, two_.size());
EXPECT_TRUE(ContainsNameValue(annotations, "First", "short"));
EXPECT_TRUE(ContainsNameValue(annotations, "Second", std::string(256, 'A')));
}
TEST_F(AnnotationList, DuplicateKeys) {
ASSERT_EQ(0u, CollectAnnotations().size());
one_.Set("1");
three_.Set("2");
AllAnnotations annotations = CollectAnnotations();
EXPECT_EQ(2u, annotations.size());
EXPECT_TRUE(ContainsNameValue(annotations, "First", "1"));
EXPECT_TRUE(ContainsNameValue(annotations, "First", "2"));
one_.Clear();
annotations = CollectAnnotations();
EXPECT_EQ(1u, annotations.size());
}
class RaceThread : public Thread {
public:
explicit RaceThread(test::AnnotationList* test) : Thread(), test_(test) {}
private:
void ThreadMain() override {
for (int i = 0; i <= 50; ++i) {
if (i % 2 == 0) {
test_->three_.Set("three");
test_->two_.Clear();
} else {
test_->three_.Clear();
}
SleepNanoseconds(base::RandInt(1, 1000));
}
}
test::AnnotationList* test_;
};
TEST_F(AnnotationList, MultipleThreads) {
ASSERT_EQ(0u, CollectAnnotations().size());
RaceThread other_thread(this);
other_thread.Start();
for (int i = 0; i <= 50; ++i) {
if (i % 2 == 0) {
one_.Set("one");
two_.Set("two");
} else {
one_.Clear();
}
SleepNanoseconds(base::RandInt(1, 1000));
}
other_thread.Join();
AllAnnotations annotations = CollectAnnotations();
EXPECT_GE(annotations.size(), 2u);
EXPECT_LE(annotations.size(), 3u);
EXPECT_TRUE(ContainsNameValue(annotations, "First", "one"));
EXPECT_TRUE(ContainsNameValue(annotations, "First", "three"));
if (annotations.size() == 3) {
EXPECT_TRUE(ContainsNameValue(annotations, "Second", "two"));
}
}
} // namespace
} // namespace test
} // namespace crashpad
| null | null | null | null | 38,018 |
29,363 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 194,358 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* VMware VMCI Driver
*
* Copyright (C) 2012 VMware, Inc. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation version 2 and no 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.
*/
#include <linux/vmw_vmci_defs.h>
#include <linux/vmw_vmci_api.h>
#include <linux/atomic.h>
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/init.h>
#include "vmci_driver.h"
#include "vmci_event.h"
static bool vmci_disable_host;
module_param_named(disable_host, vmci_disable_host, bool, 0);
MODULE_PARM_DESC(disable_host,
"Disable driver host personality (default=enabled)");
static bool vmci_disable_guest;
module_param_named(disable_guest, vmci_disable_guest, bool, 0);
MODULE_PARM_DESC(disable_guest,
"Disable driver guest personality (default=enabled)");
static bool vmci_guest_personality_initialized;
static bool vmci_host_personality_initialized;
/*
* vmci_get_context_id() - Gets the current context ID.
*
* Returns the current context ID. Note that since this is accessed only
* from code running in the host, this always returns the host context ID.
*/
u32 vmci_get_context_id(void)
{
if (vmci_guest_code_active())
return vmci_get_vm_context_id();
else if (vmci_host_code_active())
return VMCI_HOST_CONTEXT_ID;
return VMCI_INVALID_ID;
}
EXPORT_SYMBOL_GPL(vmci_get_context_id);
static int __init vmci_drv_init(void)
{
int vmci_err;
int error;
vmci_err = vmci_event_init();
if (vmci_err < VMCI_SUCCESS) {
pr_err("Failed to initialize VMCIEvent (result=%d)\n",
vmci_err);
return -EINVAL;
}
if (!vmci_disable_guest) {
error = vmci_guest_init();
if (error) {
pr_warn("Failed to initialize guest personality (err=%d)\n",
error);
} else {
vmci_guest_personality_initialized = true;
pr_info("Guest personality initialized and is %s\n",
vmci_guest_code_active() ?
"active" : "inactive");
}
}
if (!vmci_disable_host) {
error = vmci_host_init();
if (error) {
pr_warn("Unable to initialize host personality (err=%d)\n",
error);
} else {
vmci_host_personality_initialized = true;
pr_info("Initialized host personality\n");
}
}
if (!vmci_guest_personality_initialized &&
!vmci_host_personality_initialized) {
vmci_event_exit();
return -ENODEV;
}
return 0;
}
module_init(vmci_drv_init);
static void __exit vmci_drv_exit(void)
{
if (vmci_guest_personality_initialized)
vmci_guest_exit();
if (vmci_host_personality_initialized)
vmci_host_exit();
vmci_event_exit();
}
module_exit(vmci_drv_exit);
MODULE_AUTHOR("VMware, Inc.");
MODULE_DESCRIPTION("VMware Virtual Machine Communication Interface.");
MODULE_VERSION("1.1.5.0-k");
MODULE_LICENSE("GPL v2");
| null | null | null | null | 102,705 |
6,163 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 171,158 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Generic AC97 sound support for SH7760
*
* (c) 2007 Manuel Lauss
*
* Licensed under the GPLv2.
*/
#include <linux/module.h>
#include <linux/moduleparam.h>
#include <linux/platform_device.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <asm/io.h>
#define IPSEL 0xFE400034
static struct snd_soc_dai_link sh7760_ac97_dai = {
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai_name = "hac-dai.0", /* HAC0 */
.codec_dai_name = "ac97-hifi",
.platform_name = "sh7760-pcm-audio",
.codec_name = "ac97-codec",
.ops = NULL,
};
static struct snd_soc_card sh7760_ac97_soc_machine = {
.name = "SH7760 AC97",
.owner = THIS_MODULE,
.dai_link = &sh7760_ac97_dai,
.num_links = 1,
};
static struct platform_device *sh7760_ac97_snd_device;
static int __init sh7760_ac97_init(void)
{
int ret;
unsigned short ipsel;
/* enable both AC97 controllers in pinmux reg */
ipsel = __raw_readw(IPSEL);
__raw_writew(ipsel | (3 << 10), IPSEL);
ret = -ENOMEM;
sh7760_ac97_snd_device = platform_device_alloc("soc-audio", -1);
if (!sh7760_ac97_snd_device)
goto out;
platform_set_drvdata(sh7760_ac97_snd_device,
&sh7760_ac97_soc_machine);
ret = platform_device_add(sh7760_ac97_snd_device);
if (ret)
platform_device_put(sh7760_ac97_snd_device);
out:
return ret;
}
static void __exit sh7760_ac97_exit(void)
{
platform_device_unregister(sh7760_ac97_snd_device);
}
module_init(sh7760_ac97_init);
module_exit(sh7760_ac97_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION("Generic SH7760 AC97 sound machine");
MODULE_AUTHOR("Manuel Lauss <[email protected]>");
| null | null | null | null | 79,505 |
10,164 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 10,164 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_AURA_H_
#define CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_AURA_H_
#include "base/macros.h"
#include "chromecast/browser/cast_content_window.h"
#include "chromecast/graphics/cast_side_swipe_gesture_handler.h"
namespace content {
class WebContents;
} // namespace content
namespace chromecast {
namespace shell {
class TouchBlocker;
class CastContentWindowAura : public CastContentWindow,
public CastSideSwipeGestureHandlerInterface {
public:
~CastContentWindowAura() override;
// CastContentWindow implementation.
void CreateWindowForWebContents(
content::WebContents* web_contents,
CastWindowManager* window_manager,
bool is_visible,
CastWindowManager::WindowId z_order,
VisibilityPriority visibility_priority) override;
void RequestVisibility(VisibilityPriority visibility_priority) override;
void RequestMoveOut() override;
void EnableTouchInput(bool enabled) override;
// CastSideSwipeGestureHandlerInterface implementation:
void OnSideSwipeBegin(CastSideSwipeOrigin swipe_origin,
ui::GestureEvent* gesture_event) override;
void OnSideSwipeEnd(CastSideSwipeOrigin swipe_origin,
ui::GestureEvent* gesture_event) override;
private:
friend class CastContentWindow;
// This class should only be instantiated by CastContentWindow::Create.
CastContentWindowAura(Delegate* delegate, bool is_touch_enabled);
Delegate* const delegate_;
const bool is_touch_enabled_;
std::unique_ptr<TouchBlocker> touch_blocker_;
// TODO(seantopping): Inject in constructor.
CastWindowManager* window_manager_ = nullptr;
DISALLOW_COPY_AND_ASSIGN(CastContentWindowAura);
};
} // namespace shell
} // namespace chromecast
#endif // CHROMECAST_BROWSER_CAST_CONTENT_WINDOW_AURA_H_
| null | null | null | null | 7,027 |
21,295 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 21,295 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2013 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 CONTENT_RENDERER_APPCACHE_APPCACHE_DISPATCHER_H_
#define CONTENT_RENDERER_APPCACHE_APPCACHE_DISPATCHER_H_
#include <memory>
#include <string>
#include <vector>
#include "content/common/appcache.mojom.h"
#include "content/common/appcache_interfaces.h"
#include "content/renderer/appcache/appcache_backend_proxy.h"
#include "ipc/ipc_listener.h"
#include "mojo/public/cpp/bindings/binding.h"
namespace content {
// Dispatches appcache related messages sent to a child process from the
// main browser process. There is one instance per child process. Messages
// are dispatched on the main child thread. The ChildThread base class
// creates an instance and delegates calls to it.
class AppCacheDispatcher : public mojom::AppCacheFrontend {
public:
explicit AppCacheDispatcher(content::AppCacheFrontend* frontend);
~AppCacheDispatcher() override;
void Bind(mojom::AppCacheFrontendRequest request);
AppCacheBackendProxy* backend_proxy() { return &backend_proxy_; }
private:
// mojom::AppCacheFrontend
void CacheSelected(int32_t host_id, mojom::AppCacheInfoPtr info) override;
void StatusChanged(const std::vector<int32_t>& host_ids,
AppCacheStatus status) override;
void EventRaised(const std::vector<int32_t>& host_ids,
AppCacheEventID event_id) override;
void ProgressEventRaised(const std::vector<int32_t>& host_ids,
const GURL& url,
int32_t num_total,
int32_t num_complete) override;
void ErrorEventRaised(const std::vector<int32_t>& host_ids,
mojom::AppCacheErrorDetailsPtr details) override;
void LogMessage(int32_t host_id,
int32_t log_level,
const std::string& message) override;
void ContentBlocked(int32_t host_id, const GURL& manifest_url) override;
void SetSubresourceFactory(
int32_t host_id,
network::mojom::URLLoaderFactoryPtr url_loader_factory) override;
AppCacheBackendProxy backend_proxy_;
std::unique_ptr<content::AppCacheFrontend> frontend_;
mojo::Binding<mojom::AppCacheFrontend> binding_;
};
} // namespace content
#endif // CONTENT_RENDERER_APPCACHE_APPCACHE_DISPATCHER_H_
| null | null | null | null | 18,158 |
10,739 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 175,734 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Procedures for creating, accessing and interpreting the device tree.
*
* Paul Mackerras August 1996.
* Copyright (C) 1996-2005 Paul Mackerras.
*
* Adapted for 64bit PowerPC by Dave Engebretsen and Peter Bergner.
* {engebret|bergner}@us.ibm.com
*
* Adapted for sparc32 by David S. Miller [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.
*/
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/bootmem.h>
#include <asm/prom.h>
#include <asm/oplib.h>
#include <asm/leon.h>
#include <asm/leon_amba.h>
#include "prom.h"
void * __init prom_early_alloc(unsigned long size)
{
void *ret;
ret = __alloc_bootmem(size, SMP_CACHE_BYTES, 0UL);
if (ret != NULL)
memset(ret, 0, size);
prom_early_allocated += size;
return ret;
}
/* The following routines deal with the black magic of fully naming a
* node.
*
* Certain well known named nodes are just the simple name string.
*
* Actual devices have an address specifier appended to the base name
* string, like this "foo@addr". The "addr" can be in any number of
* formats, and the platform plus the type of the node determine the
* format and how it is constructed.
*
* For children of the ROOT node, the naming convention is fixed and
* determined by whether this is a sun4u or sun4v system.
*
* For children of other nodes, it is bus type specific. So
* we walk up the tree until we discover a "device_type" property
* we recognize and we go from there.
*/
static void __init sparc32_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_registers *regs;
struct property *rprop;
rprop = of_find_property(dp, "reg", NULL);
if (!rprop)
return;
regs = rprop->value;
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
regs->which_io, regs->phys_addr);
}
/* "name@slot,offset" */
static void __init sbus_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_registers *regs;
struct property *prop;
prop = of_find_property(dp, "reg", NULL);
if (!prop)
return;
regs = prop->value;
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
regs->which_io,
regs->phys_addr);
}
/* "name@devnum[,func]" */
static void __init pci_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_pci_registers *regs;
struct property *prop;
unsigned int devfn;
prop = of_find_property(dp, "reg", NULL);
if (!prop)
return;
regs = prop->value;
devfn = (regs->phys_hi >> 8) & 0xff;
if (devfn & 0x07) {
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
devfn >> 3,
devfn & 0x07);
} else {
sprintf(tmp_buf, "%s@%x",
dp->name,
devfn >> 3);
}
}
/* "name@addrhi,addrlo" */
static void __init ebus_path_component(struct device_node *dp, char *tmp_buf)
{
struct linux_prom_registers *regs;
struct property *prop;
prop = of_find_property(dp, "reg", NULL);
if (!prop)
return;
regs = prop->value;
sprintf(tmp_buf, "%s@%x,%x",
dp->name,
regs->which_io, regs->phys_addr);
}
/* "name:vendor:device@irq,addrlo" */
static void __init ambapp_path_component(struct device_node *dp, char *tmp_buf)
{
struct amba_prom_registers *regs;
unsigned int *intr, *device, *vendor, reg0;
struct property *prop;
int interrupt = 0;
/* In order to get a unique ID in the device tree (multiple AMBA devices
* may have the same name) the node number is printed
*/
prop = of_find_property(dp, "reg", NULL);
if (!prop) {
reg0 = (unsigned int)dp->phandle;
} else {
regs = prop->value;
reg0 = regs->phys_addr;
}
/* Not all cores have Interrupt */
prop = of_find_property(dp, "interrupts", NULL);
if (!prop)
intr = &interrupt; /* IRQ0 does not exist */
else
intr = prop->value;
prop = of_find_property(dp, "vendor", NULL);
if (!prop)
return;
vendor = prop->value;
prop = of_find_property(dp, "device", NULL);
if (!prop)
return;
device = prop->value;
sprintf(tmp_buf, "%s:%d:%d@%x,%x",
dp->name, *vendor, *device,
*intr, reg0);
}
static void __init __build_path_component(struct device_node *dp, char *tmp_buf)
{
struct device_node *parent = dp->parent;
if (parent != NULL) {
if (!strcmp(parent->type, "pci") ||
!strcmp(parent->type, "pciex"))
return pci_path_component(dp, tmp_buf);
if (!strcmp(parent->type, "sbus"))
return sbus_path_component(dp, tmp_buf);
if (!strcmp(parent->type, "ebus"))
return ebus_path_component(dp, tmp_buf);
if (!strcmp(parent->type, "ambapp"))
return ambapp_path_component(dp, tmp_buf);
/* "isa" is handled with platform naming */
}
/* Use platform naming convention. */
return sparc32_path_component(dp, tmp_buf);
}
char * __init build_path_component(struct device_node *dp)
{
char tmp_buf[64], *n;
tmp_buf[0] = '\0';
__build_path_component(dp, tmp_buf);
if (tmp_buf[0] == '\0')
strcpy(tmp_buf, dp->name);
n = prom_early_alloc(strlen(tmp_buf) + 1);
strcpy(n, tmp_buf);
return n;
}
extern void restore_current(void);
void __init of_console_init(void)
{
char *msg = "OF stdout device is: %s\n";
struct device_node *dp;
unsigned long flags;
const char *type;
phandle node;
int skip, tmp, fd;
of_console_path = prom_early_alloc(256);
switch (prom_vers) {
case PROM_V0:
skip = 0;
switch (*romvec->pv_stdout) {
case PROMDEV_SCREEN:
type = "display";
break;
case PROMDEV_TTYB:
skip = 1;
/* FALLTHRU */
case PROMDEV_TTYA:
type = "serial";
break;
default:
prom_printf("Invalid PROM_V0 stdout value %u\n",
*romvec->pv_stdout);
prom_halt();
}
tmp = skip;
for_each_node_by_type(dp, type) {
if (!tmp--)
break;
}
if (!dp) {
prom_printf("Cannot find PROM_V0 console node.\n");
prom_halt();
}
of_console_device = dp;
strcpy(of_console_path, dp->full_name);
if (!strcmp(type, "serial")) {
strcat(of_console_path,
(skip ? ":b" : ":a"));
}
break;
default:
case PROM_V2:
case PROM_V3:
fd = *romvec->pv_v2bootargs.fd_stdout;
spin_lock_irqsave(&prom_lock, flags);
node = (*romvec->pv_v2devops.v2_inst2pkg)(fd);
restore_current();
spin_unlock_irqrestore(&prom_lock, flags);
if (!node) {
prom_printf("Cannot resolve stdout node from "
"instance %08x.\n", fd);
prom_halt();
}
dp = of_find_node_by_phandle(node);
type = of_get_property(dp, "device_type", NULL);
if (!type) {
prom_printf("Console stdout lacks "
"device_type property.\n");
prom_halt();
}
if (strcmp(type, "display") && strcmp(type, "serial")) {
prom_printf("Console device_type is neither display "
"nor serial.\n");
prom_halt();
}
of_console_device = dp;
if (prom_vers == PROM_V2) {
strcpy(of_console_path, dp->full_name);
switch (*romvec->pv_stdout) {
case PROMDEV_TTYA:
strcat(of_console_path, ":a");
break;
case PROMDEV_TTYB:
strcat(of_console_path, ":b");
break;
}
} else {
const char *path;
dp = of_find_node_by_path("/");
path = of_get_property(dp, "stdout-path", NULL);
if (!path) {
prom_printf("No stdout-path in root node.\n");
prom_halt();
}
strcpy(of_console_path, path);
}
break;
}
of_console_options = strrchr(of_console_path, ':');
if (of_console_options) {
of_console_options++;
if (*of_console_options == '\0')
of_console_options = NULL;
}
printk(msg, of_console_path);
}
void __init of_fill_in_cpu_data(void)
{
}
void __init irq_trans_init(struct device_node *dp)
{
}
| null | null | null | null | 84,081 |
71,610 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 71,610 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2018 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 "services/video_capture/test/mock_device.h"
namespace video_capture {
MockDevice::MockDevice() = default;
MockDevice::~MockDevice() = default;
void MockDevice::SendStubFrame(const media::VideoCaptureFormat& format,
int rotation,
int frame_feedback_id) {
auto stub_frame = media::VideoFrame::CreateZeroInitializedFrame(
format.pixel_format, format.frame_size,
gfx::Rect(format.frame_size.width(), format.frame_size.height()),
format.frame_size, base::TimeDelta());
client_->OnIncomingCapturedData(
stub_frame->data(0),
static_cast<int>(media::VideoFrame::AllocationSize(
stub_frame->format(), stub_frame->coded_size())),
format, rotation, base::TimeTicks(), base::TimeDelta(),
frame_feedback_id);
}
void MockDevice::AllocateAndStart(const media::VideoCaptureParams& params,
std::unique_ptr<Client> client) {
client_ = std::move(client);
DoAllocateAndStart(params, &client_);
}
void MockDevice::StopAndDeAllocate() {
DoStopAndDeAllocate();
client_.reset();
}
void MockDevice::GetPhotoState(GetPhotoStateCallback callback) {
DoGetPhotoState(&callback);
}
void MockDevice::SetPhotoOptions(media::mojom::PhotoSettingsPtr settings,
SetPhotoOptionsCallback callback) {
DoSetPhotoOptions(&settings, &callback);
}
void MockDevice::TakePhoto(TakePhotoCallback callback) {
DoTakePhoto(&callback);
}
} // namespace video_capture
| null | null | null | null | 68,473 |
58,976 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 58,976 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#ifndef CHROME_BROWSER_EXTENSIONS_EXTENSION_ACTION_MANAGER_H_
#define CHROME_BROWSER_EXTENSIONS_EXTENSION_ACTION_MANAGER_H_
#include <map>
#include <memory>
#include <string>
#include "base/scoped_observer.h"
#include "chrome/common/extensions/api/extension_action/action_info.h"
#include "components/keyed_service/core/keyed_service.h"
#include "extensions/browser/extension_registry_observer.h"
class ExtensionAction;
class Profile;
namespace extensions {
class Extension;
class ExtensionRegistry;
// Owns the ExtensionActions associated with each extension. These actions live
// while an extension is loaded and are destroyed on unload.
class ExtensionActionManager : public KeyedService,
public ExtensionRegistryObserver {
public:
explicit ExtensionActionManager(Profile* profile);
~ExtensionActionManager() override;
// Returns this profile's ExtensionActionManager. One instance is
// shared between a profile and its incognito version.
static ExtensionActionManager* Get(content::BrowserContext* browser_context);
// Retrieves the page action, browser action, or system indicator for
// |extension|.
// If the result is not NULL, it remains valid until the extension is
// unloaded.
ExtensionAction* GetPageAction(const Extension& extension) const;
ExtensionAction* GetBrowserAction(const Extension& extension) const;
ExtensionAction* GetSystemIndicator(const Extension& extension) const;
// Returns either the PageAction or BrowserAction for |extension|, or NULL if
// none exists. Since an extension can only declare one of Browser|PageAction,
// this is okay to use anywhere you need a generic "ExtensionAction".
// Since SystemIndicators are used differently and don't follow this
// rule of mutual exclusion, they are not checked or returned.
ExtensionAction* GetExtensionAction(const Extension& extension) const;
// Gets the best fit ExtensionAction for the given |extension|. This takes
// into account |extension|'s browser or page actions, if any, along with its
// name and any declared icons.
std::unique_ptr<ExtensionAction> GetBestFitAction(
const Extension& extension,
ActionInfo::Type type) const;
private:
// Implement ExtensionRegistryObserver.
void OnExtensionUnloaded(content::BrowserContext* browser_context,
const Extension* extension,
UnloadedExtensionReason reason) override;
Profile* profile_;
// Listen to extension unloaded notifications.
ScopedObserver<ExtensionRegistry, ExtensionRegistryObserver>
extension_registry_observer_;
// Keyed by Extension ID. These maps are populated lazily when their
// ExtensionAction is first requested, and the entries are removed when the
// extension is unloaded. Not every extension has a page action or browser
// action.
using ExtIdToActionMap =
std::map<std::string, std::unique_ptr<ExtensionAction>>;
mutable ExtIdToActionMap page_actions_;
mutable ExtIdToActionMap browser_actions_;
mutable ExtIdToActionMap system_indicators_;
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_EXTENSION_ACTION_MANAGER_H_
| null | null | null | null | 55,839 |
38,836 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 38,836 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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 THIRD_PARTY_BLINK_RENDERER_MODULES_BLUETOOTH_BLUETOOTH_REMOTE_GATT_CHARACTERISTIC_H_
#define THIRD_PARTY_BLINK_RENDERER_MODULES_BLUETOOTH_BLUETOOTH_REMOTE_GATT_CHARACTERISTIC_H_
#include "mojo/public/cpp/bindings/associated_binding_set.h"
#include "third_party/blink/public/platform/modules/bluetooth/web_bluetooth.mojom-blink.h"
#include "third_party/blink/renderer/core/dom/context_lifecycle_observer.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_array_piece.h"
#include "third_party/blink/renderer/core/typed_arrays/dom_data_view.h"
#include "third_party/blink/renderer/modules/bluetooth/bluetooth_remote_gatt_service.h"
#include "third_party/blink/renderer/modules/event_target_modules.h"
#include "third_party/blink/renderer/platform/bindings/script_wrappable.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
class BluetoothCharacteristicProperties;
class BluetoothDevice;
class ExecutionContext;
class ScriptPromise;
class ScriptState;
// BluetoothRemoteGATTCharacteristic represents a GATT Characteristic, which is
// a basic data element that provides further information about a peripheral's
// service.
//
// Callbacks providing WebBluetoothRemoteGATTCharacteristicInit objects are
// handled by CallbackPromiseAdapter templatized with this class. See this
// class's "Interface required by CallbackPromiseAdapter" section and the
// CallbackPromiseAdapter class comments.
class BluetoothRemoteGATTCharacteristic final
: public EventTargetWithInlineData,
public ContextLifecycleObserver,
public mojom::blink::WebBluetoothCharacteristicClient {
USING_PRE_FINALIZER(BluetoothRemoteGATTCharacteristic, Dispose);
DEFINE_WRAPPERTYPEINFO();
USING_GARBAGE_COLLECTED_MIXIN(BluetoothRemoteGATTCharacteristic);
public:
explicit BluetoothRemoteGATTCharacteristic(
ExecutionContext*,
mojom::blink::WebBluetoothRemoteGATTCharacteristicPtr,
BluetoothRemoteGATTService*,
BluetoothDevice*);
static BluetoothRemoteGATTCharacteristic* Create(
ExecutionContext*,
mojom::blink::WebBluetoothRemoteGATTCharacteristicPtr,
BluetoothRemoteGATTService*,
BluetoothDevice*);
// Save value.
void SetValue(DOMDataView*);
// mojom::blink::WebBluetoothCharacteristicClient:
void RemoteCharacteristicValueChanged(
const WTF::Vector<uint8_t>& value) override;
// ContextLifecycleObserver interface.
void ContextDestroyed(ExecutionContext*) override;
// USING_PRE_FINALIZER interface.
// Called before the object gets garbage collected.
void Dispose();
// EventTarget methods:
const AtomicString& InterfaceName() const override;
ExecutionContext* GetExecutionContext() const override;
// Interface required by garbage collection.
void Trace(blink::Visitor*) override;
// IDL exposed interface:
BluetoothRemoteGATTService* service() { return service_; }
String uuid() { return characteristic_->uuid; }
BluetoothCharacteristicProperties* properties() { return properties_; }
DOMDataView* value() const { return value_; }
ScriptPromise getDescriptor(ScriptState*,
const StringOrUnsignedLong& descriptor,
ExceptionState&);
ScriptPromise getDescriptors(ScriptState*, ExceptionState&);
ScriptPromise getDescriptors(ScriptState*,
const StringOrUnsignedLong& descriptor,
ExceptionState&);
ScriptPromise readValue(ScriptState*);
ScriptPromise writeValue(ScriptState*, const DOMArrayPiece&);
ScriptPromise startNotifications(ScriptState*);
ScriptPromise stopNotifications(ScriptState*);
DEFINE_ATTRIBUTE_EVENT_LISTENER(characteristicvaluechanged);
protected:
// EventTarget overrides.
void AddedEventListener(const AtomicString& event_type,
RegisteredEventListener&) override;
private:
friend class BluetoothRemoteGATTDescriptor;
BluetoothRemoteGATTServer* GetGatt() { return service_->device()->gatt(); }
void ReadValueCallback(ScriptPromiseResolver*,
mojom::blink::WebBluetoothResult,
const Optional<Vector<uint8_t>>& value);
void WriteValueCallback(ScriptPromiseResolver*,
const Vector<uint8_t>& value,
mojom::blink::WebBluetoothResult);
void NotificationsCallback(ScriptPromiseResolver*,
mojom::blink::WebBluetoothResult);
ScriptPromise GetDescriptorsImpl(ScriptState*,
mojom::blink::WebBluetoothGATTQueryQuantity,
const String& descriptor_uuid = String());
void GetDescriptorsCallback(
const String& requested_descriptor_uuid,
const String& characteristic_instance_id,
mojom::blink::WebBluetoothGATTQueryQuantity,
ScriptPromiseResolver*,
mojom::blink::WebBluetoothResult,
Optional<Vector<mojom::blink::WebBluetoothRemoteGATTDescriptorPtr>>
descriptors);
DOMException* CreateInvalidCharacteristicError();
mojom::blink::WebBluetoothRemoteGATTCharacteristicPtr characteristic_;
Member<BluetoothRemoteGATTService> service_;
Member<BluetoothCharacteristicProperties> properties_;
Member<DOMDataView> value_;
Member<BluetoothDevice> device_;
mojo::AssociatedBindingSet<mojom::blink::WebBluetoothCharacteristicClient>
client_bindings_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_MODULES_BLUETOOTH_BLUETOOTH_REMOTE_GATT_CHARACTERISTIC_H_
| null | null | null | null | 35,699 |
38,124 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 203,119 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/* $(CROSS_COMPILE)cc -Wall -Wextra -g -lpthread -o testusb testusb.c */
/*
* Copyright (c) 2002 by David Brownell
* Copyright (c) 2010 by Samsung Electronics
* Author: Michal Nazarewicz <[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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
/*
* This program issues ioctls to perform the tests implemented by the
* kernel driver. It can generate a variety of transfer patterns; you
* should make sure to test both regular streaming and mixes of
* transfer sizes (including short transfers).
*
* For more information on how this can be used and on USB testing
* refer to <URL:http://www.linux-usb.org/usbtest/>.
*/
#include <stdio.h>
#include <string.h>
#include <ftw.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <errno.h>
#include <limits.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <linux/usbdevice_fs.h>
/*-------------------------------------------------------------------------*/
#define TEST_CASES 30
// FIXME make these public somewhere; usbdevfs.h?
struct usbtest_param {
// inputs
unsigned test_num; /* 0..(TEST_CASES-1) */
unsigned iterations;
unsigned length;
unsigned vary;
unsigned sglen;
// outputs
struct timeval duration;
};
#define USBTEST_REQUEST _IOWR('U', 100, struct usbtest_param)
/*-------------------------------------------------------------------------*/
/* #include <linux/usb_ch9.h> */
#define USB_DT_DEVICE 0x01
#define USB_DT_INTERFACE 0x04
#define USB_CLASS_PER_INTERFACE 0 /* for DeviceClass */
#define USB_CLASS_VENDOR_SPEC 0xff
struct usb_device_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u16 bcdUSB;
__u8 bDeviceClass;
__u8 bDeviceSubClass;
__u8 bDeviceProtocol;
__u8 bMaxPacketSize0;
__u16 idVendor;
__u16 idProduct;
__u16 bcdDevice;
__u8 iManufacturer;
__u8 iProduct;
__u8 iSerialNumber;
__u8 bNumConfigurations;
} __attribute__ ((packed));
struct usb_interface_descriptor {
__u8 bLength;
__u8 bDescriptorType;
__u8 bInterfaceNumber;
__u8 bAlternateSetting;
__u8 bNumEndpoints;
__u8 bInterfaceClass;
__u8 bInterfaceSubClass;
__u8 bInterfaceProtocol;
__u8 iInterface;
} __attribute__ ((packed));
enum usb_device_speed {
USB_SPEED_UNKNOWN = 0, /* enumerating */
USB_SPEED_LOW, USB_SPEED_FULL, /* usb 1.1 */
USB_SPEED_HIGH /* usb 2.0 */
};
/*-------------------------------------------------------------------------*/
static char *speed (enum usb_device_speed s)
{
switch (s) {
case USB_SPEED_UNKNOWN: return "unknown";
case USB_SPEED_LOW: return "low";
case USB_SPEED_FULL: return "full";
case USB_SPEED_HIGH: return "high";
default: return "??";
}
}
struct testdev {
struct testdev *next;
char *name;
pthread_t thread;
enum usb_device_speed speed;
unsigned ifnum : 8;
unsigned forever : 1;
int test;
struct usbtest_param param;
};
static struct testdev *testdevs;
static int testdev_ffs_ifnum(FILE *fd)
{
union {
char buf[255];
struct usb_interface_descriptor intf;
} u;
for (;;) {
if (fread(u.buf, 1, 1, fd) != 1)
return -1;
if (fread(u.buf + 1, (unsigned char)u.buf[0] - 1, 1, fd) != 1)
return -1;
if (u.intf.bLength == sizeof u.intf
&& u.intf.bDescriptorType == USB_DT_INTERFACE
&& u.intf.bNumEndpoints == 2
&& u.intf.bInterfaceClass == USB_CLASS_VENDOR_SPEC
&& u.intf.bInterfaceSubClass == 0
&& u.intf.bInterfaceProtocol == 0)
return (unsigned char)u.intf.bInterfaceNumber;
}
}
static int testdev_ifnum(FILE *fd)
{
struct usb_device_descriptor dev;
if (fread(&dev, sizeof dev, 1, fd) != 1)
return -1;
if (dev.bLength != sizeof dev || dev.bDescriptorType != USB_DT_DEVICE)
return -1;
/* FX2 with (tweaked) bulksrc firmware */
if (dev.idVendor == 0x0547 && dev.idProduct == 0x1002)
return 0;
/*----------------------------------------------------*/
/* devices that start up using the EZ-USB default device and
* which we can use after loading simple firmware. hotplug
* can fxload it, and then run this test driver.
*
* we return false positives in two cases:
* - the device has a "real" driver (maybe usb-serial) that
* renumerates. the device should vanish quickly.
* - the device doesn't have the test firmware installed.
*/
/* generic EZ-USB FX controller */
if (dev.idVendor == 0x0547 && dev.idProduct == 0x2235)
return 0;
/* generic EZ-USB FX2 controller */
if (dev.idVendor == 0x04b4 && dev.idProduct == 0x8613)
return 0;
/* CY3671 development board with EZ-USB FX */
if (dev.idVendor == 0x0547 && dev.idProduct == 0x0080)
return 0;
/* Keyspan 19Qi uses an21xx (original EZ-USB) */
if (dev.idVendor == 0x06cd && dev.idProduct == 0x010b)
return 0;
/*----------------------------------------------------*/
/* "gadget zero", Linux-USB test software */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4a0)
return 0;
/* user mode subset of that */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4a4)
return testdev_ffs_ifnum(fd);
/* return 0; */
/* iso version of usermode code */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4a3)
return 0;
/* some GPL'd test firmware uses these IDs */
if (dev.idVendor == 0xfff0 && dev.idProduct == 0xfff0)
return 0;
/*----------------------------------------------------*/
/* iBOT2 high speed webcam */
if (dev.idVendor == 0x0b62 && dev.idProduct == 0x0059)
return 0;
/*----------------------------------------------------*/
/* the FunctionFS gadget can have the source/sink interface
* anywhere. We look for an interface descriptor that match
* what we expect. We ignore configuratiens thou. */
if (dev.idVendor == 0x0525 && dev.idProduct == 0xa4ac
&& (dev.bDeviceClass == USB_CLASS_PER_INTERFACE
|| dev.bDeviceClass == USB_CLASS_VENDOR_SPEC))
return testdev_ffs_ifnum(fd);
return -1;
}
static int find_testdev(const char *name, const struct stat *sb, int flag)
{
FILE *fd;
int ifnum;
struct testdev *entry;
(void)sb; /* unused */
if (flag != FTW_F)
return 0;
fd = fopen(name, "rb");
if (!fd) {
perror(name);
return 0;
}
ifnum = testdev_ifnum(fd);
fclose(fd);
if (ifnum < 0)
return 0;
entry = calloc(1, sizeof *entry);
if (!entry)
goto nomem;
entry->name = strdup(name);
if (!entry->name) {
free(entry);
nomem:
perror("malloc");
return 0;
}
entry->ifnum = ifnum;
/* FIXME update USBDEVFS_CONNECTINFO so it tells about high speed etc */
fprintf(stderr, "%s speed\t%s\t%u\n",
speed(entry->speed), entry->name, entry->ifnum);
entry->next = testdevs;
testdevs = entry;
return 0;
}
static int
usbdev_ioctl (int fd, int ifno, unsigned request, void *param)
{
struct usbdevfs_ioctl wrapper;
wrapper.ifno = ifno;
wrapper.ioctl_code = request;
wrapper.data = param;
return ioctl (fd, USBDEVFS_IOCTL, &wrapper);
}
static void *handle_testdev (void *arg)
{
struct testdev *dev = arg;
int fd, i;
int status;
if ((fd = open (dev->name, O_RDWR)) < 0) {
perror ("can't open dev file r/w");
return 0;
}
restart:
for (i = 0; i < TEST_CASES; i++) {
if (dev->test != -1 && dev->test != i)
continue;
dev->param.test_num = i;
status = usbdev_ioctl (fd, dev->ifnum,
USBTEST_REQUEST, &dev->param);
if (status < 0 && errno == EOPNOTSUPP)
continue;
/* FIXME need a "syslog it" option for background testing */
/* NOTE: each thread emits complete lines; no fragments! */
if (status < 0) {
char buf [80];
int err = errno;
if (strerror_r (errno, buf, sizeof buf)) {
snprintf (buf, sizeof buf, "error %d", err);
errno = err;
}
printf ("%s test %d --> %d (%s)\n",
dev->name, i, errno, buf);
} else
printf ("%s test %d, %4d.%.06d secs\n", dev->name, i,
(int) dev->param.duration.tv_sec,
(int) dev->param.duration.tv_usec);
fflush (stdout);
}
if (dev->forever)
goto restart;
close (fd);
return arg;
}
static const char *usb_dir_find(void)
{
static char udev_usb_path[] = "/dev/bus/usb";
if (access(udev_usb_path, F_OK) == 0)
return udev_usb_path;
return NULL;
}
static int parse_num(unsigned *num, const char *str)
{
unsigned long val;
char *end;
errno = 0;
val = strtoul(str, &end, 0);
if (errno || *end || val > UINT_MAX)
return -1;
*num = val;
return 0;
}
int main (int argc, char **argv)
{
int c;
struct testdev *entry;
char *device;
const char *usb_dir = NULL;
int all = 0, forever = 0, not = 0;
int test = -1 /* all */;
struct usbtest_param param;
/* pick defaults that works with all speeds, without short packets.
*
* Best per-frame data rates:
* high speed, bulk 512 * 13 * 8 = 53248
* interrupt 1024 * 3 * 8 = 24576
* full speed, bulk/intr 64 * 19 = 1216
* interrupt 64 * 1 = 64
* low speed, interrupt 8 * 1 = 8
*/
param.iterations = 1000;
param.length = 1024;
param.vary = 512;
param.sglen = 32;
/* for easy use when hotplugging */
device = getenv ("DEVICE");
while ((c = getopt (argc, argv, "D:aA:c:g:hlns:t:v:")) != EOF)
switch (c) {
case 'D': /* device, if only one */
device = optarg;
continue;
case 'A': /* use all devices with specified USB dir */
usb_dir = optarg;
/* FALL THROUGH */
case 'a': /* use all devices */
device = NULL;
all = 1;
continue;
case 'c': /* count iterations */
if (parse_num(¶m.iterations, optarg))
goto usage;
continue;
case 'g': /* scatter/gather entries */
if (parse_num(¶m.sglen, optarg))
goto usage;
continue;
case 'l': /* loop forever */
forever = 1;
continue;
case 'n': /* no test running! */
not = 1;
continue;
case 's': /* size of packet */
if (parse_num(¶m.length, optarg))
goto usage;
continue;
case 't': /* run just one test */
test = atoi (optarg);
if (test < 0)
goto usage;
continue;
case 'v': /* vary packet size by ... */
if (parse_num(¶m.vary, optarg))
goto usage;
continue;
case '?':
case 'h':
default:
usage:
fprintf (stderr,
"usage: %s [options]\n"
"Options:\n"
"\t-D dev only test specific device\n"
"\t-A usb-dir\n"
"\t-a test all recognized devices\n"
"\t-l loop forever(for stress test)\n"
"\t-t testnum only run specified case\n"
"\t-n no test running, show devices to be tested\n"
"Case arguments:\n"
"\t-c iterations default 1000\n"
"\t-s transfer length default 1024\n"
"\t-g sglen default 32\n"
"\t-v vary default 512\n",
argv[0]);
return 1;
}
if (optind != argc)
goto usage;
if (!all && !device) {
fprintf (stderr, "must specify '-a' or '-D dev', "
"or DEVICE=/dev/bus/usb/BBB/DDD in env\n");
goto usage;
}
/* Find usb device subdirectory */
if (!usb_dir) {
usb_dir = usb_dir_find();
if (!usb_dir) {
fputs ("USB device files are missing\n", stderr);
return -1;
}
}
/* collect and list the test devices */
if (ftw (usb_dir, find_testdev, 3) != 0) {
fputs ("ftw failed; are USB device files missing?\n", stderr);
return -1;
}
/* quit, run single test, or create test threads */
if (!testdevs && !device) {
fputs ("no test devices recognized\n", stderr);
return -1;
}
if (not)
return 0;
if (testdevs && testdevs->next == 0 && !device)
device = testdevs->name;
for (entry = testdevs; entry; entry = entry->next) {
int status;
entry->param = param;
entry->forever = forever;
entry->test = test;
if (device) {
if (strcmp (entry->name, device))
continue;
return handle_testdev (entry) != entry;
}
status = pthread_create (&entry->thread, 0, handle_testdev, entry);
if (status)
perror ("pthread_create");
}
if (device) {
struct testdev dev;
/* kernel can recognize test devices we don't */
fprintf (stderr, "%s: %s may see only control tests\n",
argv [0], device);
memset (&dev, 0, sizeof dev);
dev.name = device;
dev.param = param;
dev.forever = forever;
dev.test = test;
return handle_testdev (&dev) != &dev;
}
/* wait for tests to complete */
for (entry = testdevs; entry; entry = entry->next) {
void *retval;
if (pthread_join (entry->thread, &retval))
perror ("pthread_join");
/* testing errors discarded! */
}
return 0;
}
| null | null | null | null | 111,466 |
70,723 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 70,723 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 SANDBOX_LINUX_SYSTEM_HEADERS_ARM64_LINUX_SYSCALLS_H_
#define SANDBOX_LINUX_SYSTEM_HEADERS_ARM64_LINUX_SYSCALLS_H_
#include <asm-generic/unistd.h>
#if !defined(__NR_io_setup)
#define __NR_io_setup 0
#endif
#if !defined(__NR_io_destroy)
#define __NR_io_destroy 1
#endif
#if !defined(__NR_io_submit)
#define __NR_io_submit 2
#endif
#if !defined(__NR_io_cancel)
#define __NR_io_cancel 3
#endif
#if !defined(__NR_io_getevents)
#define __NR_io_getevents 4
#endif
#if !defined(__NR_setxattr)
#define __NR_setxattr 5
#endif
#if !defined(__NR_lsetxattr)
#define __NR_lsetxattr 6
#endif
#if !defined(__NR_fsetxattr)
#define __NR_fsetxattr 7
#endif
#if !defined(__NR_getxattr)
#define __NR_getxattr 8
#endif
#if !defined(__NR_lgetxattr)
#define __NR_lgetxattr 9
#endif
#if !defined(__NR_fgetxattr)
#define __NR_fgetxattr 10
#endif
#if !defined(__NR_listxattr)
#define __NR_listxattr 11
#endif
#if !defined(__NR_llistxattr)
#define __NR_llistxattr 12
#endif
#if !defined(__NR_flistxattr)
#define __NR_flistxattr 13
#endif
#if !defined(__NR_removexattr)
#define __NR_removexattr 14
#endif
#if !defined(__NR_lremovexattr)
#define __NR_lremovexattr 15
#endif
#if !defined(__NR_fremovexattr)
#define __NR_fremovexattr 16
#endif
#if !defined(__NR_getcwd)
#define __NR_getcwd 17
#endif
#if !defined(__NR_lookup_dcookie)
#define __NR_lookup_dcookie 18
#endif
#if !defined(__NR_eventfd2)
#define __NR_eventfd2 19
#endif
#if !defined(__NR_epoll_create1)
#define __NR_epoll_create1 20
#endif
#if !defined(__NR_epoll_ctl)
#define __NR_epoll_ctl 21
#endif
#if !defined(__NR_epoll_pwait)
#define __NR_epoll_pwait 22
#endif
#if !defined(__NR_dup)
#define __NR_dup 23
#endif
#if !defined(__NR_dup3)
#define __NR_dup3 24
#endif
#if !defined(__NR_fcntl)
#define __NR_fcntl 25
#endif
#if !defined(__NR_inotify_init1)
#define __NR_inotify_init1 26
#endif
#if !defined(__NR_inotify_add_watch)
#define __NR_inotify_add_watch 27
#endif
#if !defined(__NR_inotify_rm_watch)
#define __NR_inotify_rm_watch 28
#endif
#if !defined(__NR_ioctl)
#define __NR_ioctl 29
#endif
#if !defined(__NR_ioprio_set)
#define __NR_ioprio_set 30
#endif
#if !defined(__NR_ioprio_get)
#define __NR_ioprio_get 31
#endif
#if !defined(__NR_flock)
#define __NR_flock 32
#endif
#if !defined(__NR_mknodat)
#define __NR_mknodat 33
#endif
#if !defined(__NR_mkdirat)
#define __NR_mkdirat 34
#endif
#if !defined(__NR_unlinkat)
#define __NR_unlinkat 35
#endif
#if !defined(__NR_symlinkat)
#define __NR_symlinkat 36
#endif
#if !defined(__NR_linkat)
#define __NR_linkat 37
#endif
#if !defined(__NR_renameat)
#define __NR_renameat 38
#endif
#if !defined(__NR_umount2)
#define __NR_umount2 39
#endif
#if !defined(__NR_mount)
#define __NR_mount 40
#endif
#if !defined(__NR_pivot_root)
#define __NR_pivot_root 41
#endif
#if !defined(__NR_nfsservctl)
#define __NR_nfsservctl 42
#endif
#if !defined(__NR_statfs)
#define __NR_statfs 43
#endif
#if !defined(__NR_fstatfs)
#define __NR_fstatfs 44
#endif
#if !defined(__NR_truncate)
#define __NR_truncate 45
#endif
#if !defined(__NR_ftruncate)
#define __NR_ftruncate 46
#endif
#if !defined(__NR_fallocate)
#define __NR_fallocate 47
#endif
#if !defined(__NR_faccessat)
#define __NR_faccessat 48
#endif
#if !defined(__NR_chdir)
#define __NR_chdir 49
#endif
#if !defined(__NR_fchdir)
#define __NR_fchdir 50
#endif
#if !defined(__NR_chroot)
#define __NR_chroot 51
#endif
#if !defined(__NR_fchmod)
#define __NR_fchmod 52
#endif
#if !defined(__NR_fchmodat)
#define __NR_fchmodat 53
#endif
#if !defined(__NR_fchownat)
#define __NR_fchownat 54
#endif
#if !defined(__NR_fchown)
#define __NR_fchown 55
#endif
#if !defined(__NR_openat)
#define __NR_openat 56
#endif
#if !defined(__NR_close)
#define __NR_close 57
#endif
#if !defined(__NR_vhangup)
#define __NR_vhangup 58
#endif
#if !defined(__NR_pipe2)
#define __NR_pipe2 59
#endif
#if !defined(__NR_quotactl)
#define __NR_quotactl 60
#endif
#if !defined(__NR_getdents64)
#define __NR_getdents64 61
#endif
#if !defined(__NR_lseek)
#define __NR_lseek 62
#endif
#if !defined(__NR_read)
#define __NR_read 63
#endif
#if !defined(__NR_write)
#define __NR_write 64
#endif
#if !defined(__NR_readv)
#define __NR_readv 65
#endif
#if !defined(__NR_writev)
#define __NR_writev 66
#endif
#if !defined(__NR_pread64)
#define __NR_pread64 67
#endif
#if !defined(__NR_pwrite64)
#define __NR_pwrite64 68
#endif
#if !defined(__NR_preadv)
#define __NR_preadv 69
#endif
#if !defined(__NR_pwritev)
#define __NR_pwritev 70
#endif
#if !defined(__NR_sendfile)
#define __NR_sendfile 71
#endif
#if !defined(__NR_pselect6)
#define __NR_pselect6 72
#endif
#if !defined(__NR_ppoll)
#define __NR_ppoll 73
#endif
#if !defined(__NR_signalfd4)
#define __NR_signalfd4 74
#endif
#if !defined(__NR_vmsplice)
#define __NR_vmsplice 75
#endif
#if !defined(__NR_splice)
#define __NR_splice 76
#endif
#if !defined(__NR_tee)
#define __NR_tee 77
#endif
#if !defined(__NR_readlinkat)
#define __NR_readlinkat 78
#endif
#if !defined(__NR_newfstatat)
#define __NR_newfstatat 79
#endif
#if !defined(__NR_fstat)
#define __NR_fstat 80
#endif
#if !defined(__NR_sync)
#define __NR_sync 81
#endif
#if !defined(__NR_fsync)
#define __NR_fsync 82
#endif
#if !defined(__NR_fdatasync)
#define __NR_fdatasync 83
#endif
#if !defined(__NR_sync_file_range)
#define __NR_sync_file_range 84
#endif
#if !defined(__NR_timerfd_create)
#define __NR_timerfd_create 85
#endif
#if !defined(__NR_timerfd_settime)
#define __NR_timerfd_settime 86
#endif
#if !defined(__NR_timerfd_gettime)
#define __NR_timerfd_gettime 87
#endif
#if !defined(__NR_utimensat)
#define __NR_utimensat 88
#endif
#if !defined(__NR_acct)
#define __NR_acct 89
#endif
#if !defined(__NR_capget)
#define __NR_capget 90
#endif
#if !defined(__NR_capset)
#define __NR_capset 91
#endif
#if !defined(__NR_personality)
#define __NR_personality 92
#endif
#if !defined(__NR_exit)
#define __NR_exit 93
#endif
#if !defined(__NR_exit_group)
#define __NR_exit_group 94
#endif
#if !defined(__NR_waitid)
#define __NR_waitid 95
#endif
#if !defined(__NR_set_tid_address)
#define __NR_set_tid_address 96
#endif
#if !defined(__NR_unshare)
#define __NR_unshare 97
#endif
#if !defined(__NR_futex)
#define __NR_futex 98
#endif
#if !defined(__NR_set_robust_list)
#define __NR_set_robust_list 99
#endif
#if !defined(__NR_get_robust_list)
#define __NR_get_robust_list 100
#endif
#if !defined(__NR_nanosleep)
#define __NR_nanosleep 101
#endif
#if !defined(__NR_getitimer)
#define __NR_getitimer 102
#endif
#if !defined(__NR_setitimer)
#define __NR_setitimer 103
#endif
#if !defined(__NR_kexec_load)
#define __NR_kexec_load 104
#endif
#if !defined(__NR_init_module)
#define __NR_init_module 105
#endif
#if !defined(__NR_delete_module)
#define __NR_delete_module 106
#endif
#if !defined(__NR_timer_create)
#define __NR_timer_create 107
#endif
#if !defined(__NR_timer_gettime)
#define __NR_timer_gettime 108
#endif
#if !defined(__NR_timer_getoverrun)
#define __NR_timer_getoverrun 109
#endif
#if !defined(__NR_timer_settime)
#define __NR_timer_settime 110
#endif
#if !defined(__NR_timer_delete)
#define __NR_timer_delete 111
#endif
#if !defined(__NR_clock_settime)
#define __NR_clock_settime 112
#endif
#if !defined(__NR_clock_gettime)
#define __NR_clock_gettime 113
#endif
#if !defined(__NR_clock_getres)
#define __NR_clock_getres 114
#endif
#if !defined(__NR_clock_nanosleep)
#define __NR_clock_nanosleep 115
#endif
#if !defined(__NR_syslog)
#define __NR_syslog 116
#endif
#if !defined(__NR_ptrace)
#define __NR_ptrace 117
#endif
#if !defined(__NR_sched_setparam)
#define __NR_sched_setparam 118
#endif
#if !defined(__NR_sched_setscheduler)
#define __NR_sched_setscheduler 119
#endif
#if !defined(__NR_sched_getscheduler)
#define __NR_sched_getscheduler 120
#endif
#if !defined(__NR_sched_getparam)
#define __NR_sched_getparam 121
#endif
#if !defined(__NR_sched_setaffinity)
#define __NR_sched_setaffinity 122
#endif
#if !defined(__NR_sched_getaffinity)
#define __NR_sched_getaffinity 123
#endif
#if !defined(__NR_sched_yield)
#define __NR_sched_yield 124
#endif
#if !defined(__NR_sched_get_priority_max)
#define __NR_sched_get_priority_max 125
#endif
#if !defined(__NR_sched_get_priority_min)
#define __NR_sched_get_priority_min 126
#endif
#if !defined(__NR_sched_rr_get_interval)
#define __NR_sched_rr_get_interval 127
#endif
#if !defined(__NR_restart_syscall)
#define __NR_restart_syscall 128
#endif
#if !defined(__NR_kill)
#define __NR_kill 129
#endif
#if !defined(__NR_tkill)
#define __NR_tkill 130
#endif
#if !defined(__NR_tgkill)
#define __NR_tgkill 131
#endif
#if !defined(__NR_sigaltstack)
#define __NR_sigaltstack 132
#endif
#if !defined(__NR_rt_sigsuspend)
#define __NR_rt_sigsuspend 133
#endif
#if !defined(__NR_rt_sigaction)
#define __NR_rt_sigaction 134
#endif
#if !defined(__NR_rt_sigprocmask)
#define __NR_rt_sigprocmask 135
#endif
#if !defined(__NR_rt_sigpending)
#define __NR_rt_sigpending 136
#endif
#if !defined(__NR_rt_sigtimedwait)
#define __NR_rt_sigtimedwait 137
#endif
#if !defined(__NR_rt_sigqueueinfo)
#define __NR_rt_sigqueueinfo 138
#endif
#if !defined(__NR_rt_sigreturn)
#define __NR_rt_sigreturn 139
#endif
#if !defined(__NR_setpriority)
#define __NR_setpriority 140
#endif
#if !defined(__NR_getpriority)
#define __NR_getpriority 141
#endif
#if !defined(__NR_reboot)
#define __NR_reboot 142
#endif
#if !defined(__NR_setregid)
#define __NR_setregid 143
#endif
#if !defined(__NR_setgid)
#define __NR_setgid 144
#endif
#if !defined(__NR_setreuid)
#define __NR_setreuid 145
#endif
#if !defined(__NR_setuid)
#define __NR_setuid 146
#endif
#if !defined(__NR_setresuid)
#define __NR_setresuid 147
#endif
#if !defined(__NR_getresuid)
#define __NR_getresuid 148
#endif
#if !defined(__NR_setresgid)
#define __NR_setresgid 149
#endif
#if !defined(__NR_getresgid)
#define __NR_getresgid 150
#endif
#if !defined(__NR_setfsuid)
#define __NR_setfsuid 151
#endif
#if !defined(__NR_setfsgid)
#define __NR_setfsgid 152
#endif
#if !defined(__NR_times)
#define __NR_times 153
#endif
#if !defined(__NR_setpgid)
#define __NR_setpgid 154
#endif
#if !defined(__NR_getpgid)
#define __NR_getpgid 155
#endif
#if !defined(__NR_getsid)
#define __NR_getsid 156
#endif
#if !defined(__NR_setsid)
#define __NR_setsid 157
#endif
#if !defined(__NR_getgroups)
#define __NR_getgroups 158
#endif
#if !defined(__NR_setgroups)
#define __NR_setgroups 159
#endif
#if !defined(__NR_uname)
#define __NR_uname 160
#endif
#if !defined(__NR_sethostname)
#define __NR_sethostname 161
#endif
#if !defined(__NR_setdomainname)
#define __NR_setdomainname 162
#endif
#if !defined(__NR_getrlimit)
#define __NR_getrlimit 163
#endif
#if !defined(__NR_setrlimit)
#define __NR_setrlimit 164
#endif
#if !defined(__NR_getrusage)
#define __NR_getrusage 165
#endif
#if !defined(__NR_umask)
#define __NR_umask 166
#endif
#if !defined(__NR_prctl)
#define __NR_prctl 167
#endif
#if !defined(__NR_getcpu)
#define __NR_getcpu 168
#endif
#if !defined(__NR_gettimeofday)
#define __NR_gettimeofday 169
#endif
#if !defined(__NR_settimeofday)
#define __NR_settimeofday 170
#endif
#if !defined(__NR_adjtimex)
#define __NR_adjtimex 171
#endif
#if !defined(__NR_getpid)
#define __NR_getpid 172
#endif
#if !defined(__NR_getppid)
#define __NR_getppid 173
#endif
#if !defined(__NR_getuid)
#define __NR_getuid 174
#endif
#if !defined(__NR_geteuid)
#define __NR_geteuid 175
#endif
#if !defined(__NR_getgid)
#define __NR_getgid 176
#endif
#if !defined(__NR_getegid)
#define __NR_getegid 177
#endif
#if !defined(__NR_gettid)
#define __NR_gettid 178
#endif
#if !defined(__NR_sysinfo)
#define __NR_sysinfo 179
#endif
#if !defined(__NR_mq_open)
#define __NR_mq_open 180
#endif
#if !defined(__NR_mq_unlink)
#define __NR_mq_unlink 181
#endif
#if !defined(__NR_mq_timedsend)
#define __NR_mq_timedsend 182
#endif
#if !defined(__NR_mq_timedreceive)
#define __NR_mq_timedreceive 183
#endif
#if !defined(__NR_mq_notify)
#define __NR_mq_notify 184
#endif
#if !defined(__NR_mq_getsetattr)
#define __NR_mq_getsetattr 185
#endif
#if !defined(__NR_msgget)
#define __NR_msgget 186
#endif
#if !defined(__NR_msgctl)
#define __NR_msgctl 187
#endif
#if !defined(__NR_msgrcv)
#define __NR_msgrcv 188
#endif
#if !defined(__NR_msgsnd)
#define __NR_msgsnd 189
#endif
#if !defined(__NR_semget)
#define __NR_semget 190
#endif
#if !defined(__NR_semctl)
#define __NR_semctl 191
#endif
#if !defined(__NR_semtimedop)
#define __NR_semtimedop 192
#endif
#if !defined(__NR_semop)
#define __NR_semop 193
#endif
#if !defined(__NR_shmget)
#define __NR_shmget 194
#endif
#if !defined(__NR_shmctl)
#define __NR_shmctl 195
#endif
#if !defined(__NR_shmat)
#define __NR_shmat 196
#endif
#if !defined(__NR_shmdt)
#define __NR_shmdt 197
#endif
#if !defined(__NR_socket)
#define __NR_socket 198
#endif
#if !defined(__NR_socketpair)
#define __NR_socketpair 199
#endif
#if !defined(__NR_bind)
#define __NR_bind 200
#endif
#if !defined(__NR_listen)
#define __NR_listen 201
#endif
#if !defined(__NR_accept)
#define __NR_accept 202
#endif
#if !defined(__NR_connect)
#define __NR_connect 203
#endif
#if !defined(__NR_getsockname)
#define __NR_getsockname 204
#endif
#if !defined(__NR_getpeername)
#define __NR_getpeername 205
#endif
#if !defined(__NR_sendto)
#define __NR_sendto 206
#endif
#if !defined(__NR_recvfrom)
#define __NR_recvfrom 207
#endif
#if !defined(__NR_setsockopt)
#define __NR_setsockopt 208
#endif
#if !defined(__NR_getsockopt)
#define __NR_getsockopt 209
#endif
#if !defined(__NR_shutdown)
#define __NR_shutdown 210
#endif
#if !defined(__NR_sendmsg)
#define __NR_sendmsg 211
#endif
#if !defined(__NR_recvmsg)
#define __NR_recvmsg 212
#endif
#if !defined(__NR_readahead)
#define __NR_readahead 213
#endif
#if !defined(__NR_brk)
#define __NR_brk 214
#endif
#if !defined(__NR_munmap)
#define __NR_munmap 215
#endif
#if !defined(__NR_mremap)
#define __NR_mremap 216
#endif
#if !defined(__NR_add_key)
#define __NR_add_key 217
#endif
#if !defined(__NR_request_key)
#define __NR_request_key 218
#endif
#if !defined(__NR_keyctl)
#define __NR_keyctl 219
#endif
#if !defined(__NR_clone)
#define __NR_clone 220
#endif
#if !defined(__NR_execve)
#define __NR_execve 221
#endif
#if !defined(__NR_mmap)
#define __NR_mmap 222
#endif
#if !defined(__NR_fadvise64)
#define __NR_fadvise64 223
#endif
#if !defined(__NR_swapon)
#define __NR_swapon 224
#endif
#if !defined(__NR_swapoff)
#define __NR_swapoff 225
#endif
#if !defined(__NR_mprotect)
#define __NR_mprotect 226
#endif
#if !defined(__NR_msync)
#define __NR_msync 227
#endif
#if !defined(__NR_mlock)
#define __NR_mlock 228
#endif
#if !defined(__NR_munlock)
#define __NR_munlock 229
#endif
#if !defined(__NR_mlockall)
#define __NR_mlockall 230
#endif
#if !defined(__NR_munlockall)
#define __NR_munlockall 231
#endif
#if !defined(__NR_mincore)
#define __NR_mincore 232
#endif
#if !defined(__NR_madvise)
#define __NR_madvise 233
#endif
#if !defined(__NR_remap_file_pages)
#define __NR_remap_file_pages 234
#endif
#if !defined(__NR_mbind)
#define __NR_mbind 235
#endif
#if !defined(__NR_get_mempolicy)
#define __NR_get_mempolicy 236
#endif
#if !defined(__NR_set_mempolicy)
#define __NR_set_mempolicy 237
#endif
#if !defined(__NR_migrate_pages)
#define __NR_migrate_pages 238
#endif
#if !defined(__NR_move_pages)
#define __NR_move_pages 239
#endif
#if !defined(__NR_rt_tgsigqueueinfo)
#define __NR_rt_tgsigqueueinfo 240
#endif
#if !defined(__NR_perf_event_open)
#define __NR_perf_event_open 241
#endif
#if !defined(__NR_accept4)
#define __NR_accept4 242
#endif
#if !defined(__NR_recvmmsg)
#define __NR_recvmmsg 243
#endif
#if !defined(__NR_wait4)
#define __NR_wait4 260
#endif
#if !defined(__NR_prlimit64)
#define __NR_prlimit64 261
#endif
#if !defined(__NR_fanotify_init)
#define __NR_fanotify_init 262
#endif
#if !defined(__NR_fanotify_mark)
#define __NR_fanotify_mark 263
#endif
#if !defined(__NR_name_to_handle_at)
#define __NR_name_to_handle_at 264
#endif
#if !defined(__NR_open_by_handle_at)
#define __NR_open_by_handle_at 265
#endif
#if !defined(__NR_clock_adjtime)
#define __NR_clock_adjtime 266
#endif
#if !defined(__NR_syncfs)
#define __NR_syncfs 267
#endif
#if !defined(__NR_setns)
#define __NR_setns 268
#endif
#if !defined(__NR_sendmmsg)
#define __NR_sendmmsg 269
#endif
#if !defined(__NR_process_vm_readv)
#define __NR_process_vm_readv 270
#endif
#if !defined(__NR_process_vm_writev)
#define __NR_process_vm_writev 271
#endif
#if !defined(__NR_kcmp)
#define __NR_kcmp 272
#endif
#if !defined(__NR_finit_module)
#define __NR_finit_module 273
#endif
#if !defined(__NR_sched_setattr)
#define __NR_sched_setattr 274
#endif
#if !defined(__NR_sched_getattr)
#define __NR_sched_getattr 275
#endif
#if !defined(__NR_renameat2)
#define __NR_renameat2 276
#endif
#if !defined(__NR_seccomp)
#define __NR_seccomp 277
#endif
#if !defined(__NR_getrandom)
#define __NR_getrandom 278
#endif
#if !defined(__NR_memfd_create)
#define __NR_memfd_create 279
#endif
#endif // SANDBOX_LINUX_SYSTEM_HEADERS_ARM64_LINUX_SYSCALLS_H_
| null | null | null | null | 67,586 |
66,012 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 66,012 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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/media/protected_media_identifier_permission_context.h"
#include "base/test/scoped_command_line.h"
#include "chrome/common/chrome_switches.h"
#include "media/base/media_switches.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "url/gurl.h"
class ProtectedMediaIdentifierPermissionContextTest : public testing::Test {
public:
ProtectedMediaIdentifierPermissionContextTest()
: requesting_origin_("https://example.com"),
requesting_sub_domain_origin_("https://subdomain.example.com") {
command_line_ = scoped_command_line_.GetProcessCommandLine();
}
bool IsOriginWhitelisted(const GURL& origin) {
return ProtectedMediaIdentifierPermissionContext::IsOriginWhitelisted(
origin);
}
GURL requesting_origin_;
GURL requesting_sub_domain_origin_;
base::test::ScopedCommandLine scoped_command_line_;
base::CommandLine* command_line_;
};
TEST_F(ProtectedMediaIdentifierPermissionContextTest,
BypassWithFlagWithSingleDomain) {
// The request should need to ask for permission
ASSERT_FALSE(IsOriginWhitelisted(requesting_origin_));
// Add the switch value that the
// ProtectedMediaIdentifierPermissionContext reads from
command_line_->AppendSwitchASCII(
switches::kUnsafelyAllowProtectedMediaIdentifierForDomain, "example.com");
// The request should no longer need to ask for permission
ASSERT_TRUE(IsOriginWhitelisted(requesting_origin_));
}
TEST_F(ProtectedMediaIdentifierPermissionContextTest,
BypassWithFlagWithDomainList) {
// The request should need to ask for permission
ASSERT_FALSE(IsOriginWhitelisted(requesting_origin_));
// Add the switch value that the
// ProtectedMediaIdentifierPermissionContext reads from
command_line_->AppendSwitchASCII(
switches::kUnsafelyAllowProtectedMediaIdentifierForDomain,
"example.ca,example.com,example.edu");
// The request should no longer need to ask for permission
ASSERT_TRUE(IsOriginWhitelisted(requesting_origin_));
}
TEST_F(ProtectedMediaIdentifierPermissionContextTest,
BypassWithFlagAndSubdomain) {
// The request should need to ask for permission
ASSERT_FALSE(IsOriginWhitelisted(requesting_sub_domain_origin_));
// Add the switch value that the
// ProtectedMediaIdentifierPermissionContext reads from
command_line_->AppendSwitchASCII(
switches::kUnsafelyAllowProtectedMediaIdentifierForDomain, "example.com");
// The request should no longer need to ask for permission
ASSERT_TRUE(IsOriginWhitelisted(requesting_sub_domain_origin_));
}
| null | null | null | null | 62,875 |
15,982 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 15,982 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#include "components/sync/engine_impl/worker_entity_tracker.h"
#include "components/sync/base/hash_util.h"
#include "components/sync/base/model_type.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace syncer {
// Some simple tests for the WorkerEntityTracker.
//
// The WorkerEntityTracker is an implementation detail of the ModelTypeWorker.
// As such, it doesn't make much sense to test it exhaustively, since it
// already gets a lot of test coverage from the ModelTypeWorker unit tests.
//
// These tests are intended as a basic sanity check. Anything more complicated
// would be redundant.
class WorkerEntityTrackerTest : public ::testing::Test {
public:
WorkerEntityTrackerTest()
: kServerId("ServerID"),
kClientTag("some.sample.tag"),
kClientTagHash(GenerateSyncableHash(PREFERENCES, kClientTag)),
entity_(new WorkerEntityTracker(kClientTagHash)) {
specifics.mutable_preference()->set_name(kClientTag);
specifics.mutable_preference()->set_value("pref.value");
}
~WorkerEntityTrackerTest() override {}
UpdateResponseData MakeUpdateResponseData(int64_t response_version) {
EntityData data;
data.id = kServerId;
data.client_tag_hash = kClientTagHash;
UpdateResponseData response_data;
response_data.entity = data.PassToPtr();
response_data.response_version = response_version;
return response_data;
}
const std::string kServerId;
const std::string kClientTag;
const std::string kClientTagHash;
sync_pb::EntitySpecifics specifics;
std::unique_ptr<WorkerEntityTracker> entity_;
};
// Construct a new entity from a server update. Then receive another update.
TEST_F(WorkerEntityTrackerTest, FromUpdateResponse) {
EXPECT_EQ("", entity_->id());
entity_->ReceiveUpdate(MakeUpdateResponseData(20));
EXPECT_EQ(kServerId, entity_->id());
}
} // namespace syncer
| null | null | null | null | 12,845 |
19,937 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 19,937 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#ifndef CONTENT_PUBLIC_RENDERER_RENDERER_PPAPI_HOST_H_
#define CONTENT_PUBLIC_RENDERER_RENDERER_PPAPI_HOST_H_
#include <vector>
#include "base/callback_forward.h"
#include "base/files/file.h"
#include "base/memory/ref_counted.h"
#include "base/memory/shared_memory.h"
#include "base/process/process.h"
#include "content/common/content_export.h"
#include "ipc/ipc_platform_file.h"
#include "ppapi/c/pp_instance.h"
#include "url/gurl.h"
namespace gfx {
class Point;
}
namespace IPC {
class Message;
}
namespace ppapi {
namespace host {
class PpapiHost;
}
}
namespace blink {
class WebPluginContainer;
}
namespace content {
class PepperPluginInstance;
class RenderFrame;
class RenderView;
// Interface that allows components in the embedder app to talk to the
// PpapiHost in the renderer process.
//
// There will be one of these objects in the renderer per plugin module.
class RendererPpapiHost {
public:
// Returns the RendererPpapiHost associated with the given PP_Instance,
// or NULL if the instance is invalid.
//
// Do NOT use this when dealing with an "external plugin" that serves as a
// bootstrap to load a second plugin. This is because the two will share a
// PP_Instance, and the RendererPpapiHost* for the second plugin will be
// returned after we switch the proxy on.
CONTENT_EXPORT static RendererPpapiHost* GetForPPInstance(
PP_Instance instance);
// Returns the PpapiHost object.
virtual ppapi::host::PpapiHost* GetPpapiHost() = 0;
// Returns true if the given PP_Instance is valid and belongs to the
// plugin associated with this host.
virtual bool IsValidInstance(PP_Instance instance) const = 0;
// Returns the PluginInstance for the given PP_Instance, or NULL if the
// PP_Instance is invalid (the common case this will be invalid is during
// plugin teardown when resource hosts are being force-freed).
virtual PepperPluginInstance* GetPluginInstance(
PP_Instance instance) const = 0;
// Returns the RenderFrame for the given plugin instance, or NULL if the
// instance is invalid.
virtual RenderFrame* GetRenderFrameForInstance(
PP_Instance instance) const = 0;
// Returns the RenderView for the given plugin instance, or NULL if the
// instance is invalid.
virtual RenderView* GetRenderViewForInstance(PP_Instance instance) const = 0;
// Returns the WebPluginContainer for the given plugin instance, or NULL if
// the instance is invalid.
virtual blink::WebPluginContainer* GetContainerForInstance(
PP_Instance instance) const = 0;
// Returns true if the given instance is considered to be currently
// processing a user gesture or the plugin module has the "override user
// gesture" flag set (in which case it can always do things normally
// restricted by user gestures). Returns false if the instance is invalid or
// if there is no current user gesture.
virtual bool HasUserGesture(PP_Instance instance) const = 0;
// Returns the routing ID for the render widget containing the given
// instance. This will take into account the current Flash fullscreen state,
// so if there is a Flash fullscreen instance active, this will return the
// routing ID of the fullscreen widget. Returns 0 on failure.
virtual int GetRoutingIDForWidget(PP_Instance instance) const = 0;
// Converts the given plugin coordinate to the containing RenderFrame. This
// will take into account the current Flash fullscreen state so will use
// the fullscreen widget if it's displayed.
virtual gfx::Point PluginPointToRenderFrame(
PP_Instance instance,
const gfx::Point& pt) const = 0;
// Shares a file handle (HANDLE / file descriptor) with the remote side. It
// returns a handle that should be sent in exactly one IPC message. Upon
// receipt, the remote side then owns that handle. Note: if sending the
// message fails, the returned handle is properly closed by the IPC system. If
// |should_close_source| is set to true, the original handle is closed by this
// operation and should not be used again.
virtual IPC::PlatformFileForTransit ShareHandleWithRemote(
base::PlatformFile handle,
bool should_close_source) = 0;
// Shares a shared memory handle with the remote side. It
// returns a handle that should be sent in exactly one IPC message. Upon
// receipt, the remote side then owns that handle. Note: if sending the
// message fails, the returned handle is properly closed by the IPC system.
virtual base::SharedMemoryHandle ShareSharedMemoryHandleWithRemote(
const base::SharedMemoryHandle& handle) = 0;
// Returns true if the plugin is running in process.
virtual bool IsRunningInProcess() const = 0;
virtual std::string GetPluginName() const = 0;
// Used by the embedder to inform this RendererPpapiHost that the associated
// plugin module is a host for "external plugins."
//
// An embedder may, at the time a plugin module is created, configure it to
// be a host for external plugins. Instances of such plugins go through two
// two stages of initialization; the first stage initializes a host plugin
// instance, which then loads and initializes a child plugin which takes
// over control. These are treated as one Pepper Instance, because despite the
// two-stage initialization process, the host and child appear to blink as
// one plugin instance.
//
// The host plugin appears as an in-process plugin, while we interact with the
// child plugin via the Pepper proxy.
virtual void SetToExternalPluginHost() = 0;
// There are times when the renderer needs to create a ResourceHost in the
// browser. This function does so asynchronously. |nested_msgs| is a list of
// resource host creation messages and |instance| is the PP_Instance which
// the resource will belong to. |callback| will be called asynchronously with
// the pending host IDs when the ResourceHosts have been created. This can be
// passed back to the plugin to attach to the ResourceHosts. Pending IDs of 0
// will be passed to the callback if a ResourceHost fails to be created.
virtual void CreateBrowserResourceHosts(
PP_Instance instance,
const std::vector<IPC::Message>& nested_msgs,
const base::Callback<void(const std::vector<int>&)>& callback) const = 0;
// Gets the URL of the document containing the given PP_Instance.
// Returns an empty URL if the instance is invalid.
// TODO(yzshen): Some methods such as this one don't need to be pure virtual.
// Instead, they could be directly implemented using other methods in this
// interface. Consider changing them to static helpers.
virtual GURL GetDocumentURL(PP_Instance instance) const = 0;
protected:
virtual ~RendererPpapiHost() {}
};
} // namespace content
#endif // CONTENT_PUBLIC_RENDERER_RENDERER_PPAPI_HOST_H_
| null | null | null | null | 16,800 |
48,693 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 48,693 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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 "ui/views/animation/test/test_ink_drop_host.h"
#include "base/memory/ptr_util.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/animation/ink_drop_highlight.h"
#include "ui/views/animation/ink_drop_impl.h"
#include "ui/views/animation/square_ink_drop_ripple.h"
#include "ui/views/animation/test/ink_drop_highlight_test_api.h"
#include "ui/views/animation/test/square_ink_drop_ripple_test_api.h"
namespace views {
namespace {
// Test specific subclass of InkDropRipple that returns a test api from
// GetTestApi().
class TestInkDropRipple : public SquareInkDropRipple {
public:
TestInkDropRipple(const gfx::Size& large_size,
int large_corner_radius,
const gfx::Size& small_size,
int small_corner_radius,
const gfx::Point& center_point,
SkColor color,
float visible_opacity)
: SquareInkDropRipple(large_size,
large_corner_radius,
small_size,
small_corner_radius,
center_point,
color,
visible_opacity) {}
~TestInkDropRipple() override {}
test::InkDropRippleTestApi* GetTestApi() override {
if (!test_api_)
test_api_.reset(new test::SquareInkDropRippleTestApi(this));
return test_api_.get();
}
private:
std::unique_ptr<test::InkDropRippleTestApi> test_api_;
DISALLOW_COPY_AND_ASSIGN(TestInkDropRipple);
};
// Test specific subclass of InkDropHighlight that returns a test api from
// GetTestApi().
class TestInkDropHighlight : public InkDropHighlight {
public:
TestInkDropHighlight(const gfx::Size& size,
int corner_radius,
const gfx::PointF& center_point,
SkColor color)
: InkDropHighlight(size, corner_radius, center_point, color) {}
~TestInkDropHighlight() override {}
test::InkDropHighlightTestApi* GetTestApi() override {
if (!test_api_)
test_api_.reset(new test::InkDropHighlightTestApi(this));
return test_api_.get();
}
private:
std::unique_ptr<test::InkDropHighlightTestApi> test_api_;
DISALLOW_COPY_AND_ASSIGN(TestInkDropHighlight);
};
} // namespace
TestInkDropHost::TestInkDropHost()
: num_ink_drop_layers_added_(0),
num_ink_drop_layers_removed_(0),
disable_timers_for_test_(false) {}
TestInkDropHost::~TestInkDropHost() {}
void TestInkDropHost::AddInkDropLayer(ui::Layer* ink_drop_layer) {
++num_ink_drop_layers_added_;
}
void TestInkDropHost::RemoveInkDropLayer(ui::Layer* ink_drop_layer) {
++num_ink_drop_layers_removed_;
}
std::unique_ptr<InkDrop> TestInkDropHost::CreateInkDrop() {
NOTREACHED();
return nullptr;
}
std::unique_ptr<InkDropRipple> TestInkDropHost::CreateInkDropRipple() const {
gfx::Size size(10, 10);
std::unique_ptr<InkDropRipple> ripple(new TestInkDropRipple(
size, 5, size, 5, gfx::Point(), SK_ColorBLACK, 0.175f));
if (disable_timers_for_test_)
ripple->GetTestApi()->SetDisableAnimationTimers(true);
return ripple;
}
std::unique_ptr<InkDropHighlight> TestInkDropHost::CreateInkDropHighlight()
const {
std::unique_ptr<InkDropHighlight> highlight;
highlight.reset(new TestInkDropHighlight(gfx::Size(10, 10), 4, gfx::PointF(),
SK_ColorBLACK));
if (disable_timers_for_test_)
highlight->GetTestApi()->SetDisableAnimationTimers(true);
return highlight;
}
} // namespace views
| null | null | null | null | 45,556 |
7,630 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 172,625 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Copyright (C) 1991, 1992 Linus Torvalds
* Copyright (C) 2000, 2001, 2002 Andi Kleen, SuSE Labs
*/
#include <linux/sched/debug.h>
#include <linux/kallsyms.h>
#include <linux/kprobes.h>
#include <linux/uaccess.h>
#include <linux/hardirq.h>
#include <linux/kdebug.h>
#include <linux/export.h>
#include <linux/ptrace.h>
#include <linux/kexec.h>
#include <linux/sysfs.h>
#include <linux/bug.h>
#include <linux/nmi.h>
#include <asm/stacktrace.h>
static char *exception_stack_names[N_EXCEPTION_STACKS] = {
[ DOUBLEFAULT_STACK-1 ] = "#DF",
[ NMI_STACK-1 ] = "NMI",
[ DEBUG_STACK-1 ] = "#DB",
[ MCE_STACK-1 ] = "#MC",
};
static unsigned long exception_stack_sizes[N_EXCEPTION_STACKS] = {
[0 ... N_EXCEPTION_STACKS - 1] = EXCEPTION_STKSZ,
[DEBUG_STACK - 1] = DEBUG_STKSZ
};
const char *stack_type_name(enum stack_type type)
{
BUILD_BUG_ON(N_EXCEPTION_STACKS != 4);
if (type == STACK_TYPE_IRQ)
return "IRQ";
if (type >= STACK_TYPE_EXCEPTION && type <= STACK_TYPE_EXCEPTION_LAST)
return exception_stack_names[type - STACK_TYPE_EXCEPTION];
return NULL;
}
static bool in_exception_stack(unsigned long *stack, struct stack_info *info)
{
unsigned long *begin, *end;
struct pt_regs *regs;
unsigned k;
BUILD_BUG_ON(N_EXCEPTION_STACKS != 4);
for (k = 0; k < N_EXCEPTION_STACKS; k++) {
end = (unsigned long *)raw_cpu_ptr(&orig_ist)->ist[k];
begin = end - (exception_stack_sizes[k] / sizeof(long));
regs = (struct pt_regs *)end - 1;
if (stack < begin || stack >= end)
continue;
info->type = STACK_TYPE_EXCEPTION + k;
info->begin = begin;
info->end = end;
info->next_sp = (unsigned long *)regs->sp;
return true;
}
return false;
}
static bool in_irq_stack(unsigned long *stack, struct stack_info *info)
{
unsigned long *end = (unsigned long *)this_cpu_read(irq_stack_ptr);
unsigned long *begin = end - (IRQ_STACK_SIZE / sizeof(long));
/*
* This is a software stack, so 'end' can be a valid stack pointer.
* It just means the stack is empty.
*/
if (stack < begin || stack > end)
return false;
info->type = STACK_TYPE_IRQ;
info->begin = begin;
info->end = end;
/*
* The next stack pointer is the first thing pushed by the entry code
* after switching to the irq stack.
*/
info->next_sp = (unsigned long *)*(end - 1);
return true;
}
int get_stack_info(unsigned long *stack, struct task_struct *task,
struct stack_info *info, unsigned long *visit_mask)
{
if (!stack)
goto unknown;
task = task ? : current;
if (in_task_stack(stack, task, info))
goto recursion_check;
if (task != current)
goto unknown;
if (in_exception_stack(stack, info))
goto recursion_check;
if (in_irq_stack(stack, info))
goto recursion_check;
goto unknown;
recursion_check:
/*
* Make sure we don't iterate through any given stack more than once.
* If it comes up a second time then there's something wrong going on:
* just break out and report an unknown stack type.
*/
if (visit_mask) {
if (*visit_mask & (1UL << info->type)) {
printk_deferred_once(KERN_WARNING "WARNING: stack recursion on stack type %d\n", info->type);
goto unknown;
}
*visit_mask |= 1UL << info->type;
}
return 0;
unknown:
info->type = STACK_TYPE_UNKNOWN;
return -EINVAL;
}
void show_regs(struct pt_regs *regs)
{
int i;
show_regs_print_info(KERN_DEFAULT);
__show_regs(regs, 1);
/*
* When in-kernel, we also print out the stack and code at the
* time of the fault..
*/
if (!user_mode(regs)) {
unsigned int code_prologue = code_bytes * 43 / 64;
unsigned int code_len = code_bytes;
unsigned char c;
u8 *ip;
show_trace_log_lvl(current, regs, NULL, KERN_DEFAULT);
printk(KERN_DEFAULT "Code: ");
ip = (u8 *)regs->ip - code_prologue;
if (ip < (u8 *)PAGE_OFFSET || probe_kernel_address(ip, c)) {
/* try starting at IP */
ip = (u8 *)regs->ip;
code_len = code_len - code_prologue + 1;
}
for (i = 0; i < code_len; i++, ip++) {
if (ip < (u8 *)PAGE_OFFSET ||
probe_kernel_address(ip, c)) {
pr_cont(" Bad RIP value.");
break;
}
if (ip == (u8 *)regs->ip)
pr_cont("<%02x> ", c);
else
pr_cont("%02x ", c);
}
}
pr_cont("\n");
}
int is_valid_bugaddr(unsigned long ip)
{
unsigned short ud2;
if (__copy_from_user(&ud2, (const void __user *) ip, sizeof(ud2)))
return 0;
return ud2 == 0x0b0f;
}
| null | null | null | null | 80,972 |
12,112 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 12,112 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2013 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_DRIVE_DRIVE_NOTIFICATION_MANAGER_H_
#define COMPONENTS_DRIVE_DRIVE_NOTIFICATION_MANAGER_H_
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/observer_list.h"
#include "base/timer/timer.h"
#include "components/drive/drive_notification_observer.h"
#include "components/invalidation/public/invalidation_handler.h"
#include "components/keyed_service/core/keyed_service.h"
namespace invalidation {
class InvalidationService;
} // namespace invalidation
namespace drive {
// Informs observers when they should check Google Drive for updates.
// Conditions under which updates should be searched:
// 1. XMPP invalidation is received from Google Drive.
// 2. Polling timer counts down.
class DriveNotificationManager : public KeyedService,
public syncer::InvalidationHandler {
public:
explicit DriveNotificationManager(
invalidation::InvalidationService* invalidation_service);
~DriveNotificationManager() override;
// KeyedService override.
void Shutdown() override;
// syncer::InvalidationHandler implementation.
void OnInvalidatorStateChange(syncer::InvalidatorState state) override;
void OnIncomingInvalidation(
const syncer::ObjectIdInvalidationMap& invalidation_map) override;
std::string GetOwnerName() const override;
void AddObserver(DriveNotificationObserver* observer);
void RemoveObserver(DriveNotificationObserver* observer);
// True when XMPP notification is currently enabled.
bool push_notification_enabled() const {
return push_notification_enabled_;
}
// True when XMPP notification has been registered.
bool push_notification_registered() const {
return push_notification_registered_;
}
private:
enum NotificationSource {
NOTIFICATION_XMPP,
NOTIFICATION_POLLING,
};
// Restarts the polling timer. Used for polling-based notification.
void RestartPollingTimer();
// Notifies the observers that it's time to check for updates.
// |source| indicates where the notification comes from.
void NotifyObserversToUpdate(NotificationSource source);
// Registers for Google Drive invalidation notifications through XMPP.
void RegisterDriveNotifications();
// Returns a string representation of NotificationSource.
static std::string NotificationSourceToString(NotificationSource source);
invalidation::InvalidationService* invalidation_service_;
base::ObserverList<DriveNotificationObserver> observers_;
// True when Drive File Sync Service is registered for Drive notifications.
bool push_notification_registered_;
// True if the XMPP-based push notification is currently enabled.
bool push_notification_enabled_;
// True once observers are notified for the first time.
bool observers_notified_;
// The timer is used for polling based notification. XMPP should usually be
// used but notification is done per polling when XMPP is not working.
base::Timer polling_timer_;
// Note: This should remain the last member so it'll be destroyed and
// invalidate its weak pointers before any other members are destroyed.
base::WeakPtrFactory<DriveNotificationManager> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(DriveNotificationManager);
};
} // namespace drive
#endif // COMPONENTS_DRIVE_DRIVE_NOTIFICATION_MANAGER_H_
| null | null | null | null | 8,975 |
58,175 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 58,175 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 CHROME_BROWSER_PERMISSIONS_PERMISSION_REQUEST_MANAGER_TEST_API_H_
#define CHROME_BROWSER_PERMISSIONS_PERMISSION_REQUEST_MANAGER_TEST_API_H_
#include "base/macros.h"
#include "chrome/browser/permissions/permission_request_manager.h"
#include "components/content_settings/core/common/content_settings_types.h"
class Browser;
namespace test {
class PermissionRequestManagerTestApi {
public:
explicit PermissionRequestManagerTestApi(PermissionRequestManager* manager);
// Wraps the PermissionRequestManager for the active tab in |browser|.
explicit PermissionRequestManagerTestApi(Browser* browser);
PermissionRequestManager* manager() { return manager_; }
// Add a "simple" permission request. One that uses PermissionRequestImpl,
// such as for ContentSettingsType including MIDI_SYSEX, PUSH_MESSAGING,
// NOTIFICATIONS, GEOLOCATON, or PLUGINS.
void AddSimpleRequest(ContentSettingsType type);
// Return the bubble window for the permission prompt or null if there is no
// prompt currently showing.
gfx::NativeWindow GetPromptWindow();
void SimulateWebContentsDestroyed();
private:
PermissionRequestManager* manager_;
DISALLOW_COPY_AND_ASSIGN(PermissionRequestManagerTestApi);
};
} // namespace test
#endif // CHROME_BROWSER_PERMISSIONS_PERMISSION_REQUEST_MANAGER_TEST_API_H_
| null | null | null | null | 55,038 |
39,355 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 39,355 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 "third_party/blink/renderer/modules/serviceworkers/service_worker_content_settings_proxy.h"
#include <memory>
namespace blink {
ServiceWorkerContentSettingsProxy::ServiceWorkerContentSettingsProxy(
mojom::blink::WorkerContentSettingsProxyPtrInfo host_info)
: host_info_(std::move(host_info)) {}
ServiceWorkerContentSettingsProxy::~ServiceWorkerContentSettingsProxy() =
default;
bool ServiceWorkerContentSettingsProxy::RequestFileSystemAccessSync() {
NOTREACHED();
return false;
}
bool ServiceWorkerContentSettingsProxy::AllowIndexedDB(
const blink::WebString& name,
const blink::WebSecurityOrigin&) {
bool result = false;
GetService()->AllowIndexedDB(name, &result);
return result;
}
// Use ThreadSpecific to ensure that |content_settings_instance_host| is
// destructed on worker thread.
// Each worker has a dedicated thread so this is safe.
mojom::blink::WorkerContentSettingsProxyPtr&
ServiceWorkerContentSettingsProxy::GetService() {
DEFINE_THREAD_SAFE_STATIC_LOCAL(
ThreadSpecific<mojom::blink::WorkerContentSettingsProxyPtr>,
content_settings_instance_host, ());
if (!content_settings_instance_host.IsSet()) {
DCHECK(host_info_.is_valid());
content_settings_instance_host->Bind(std::move(host_info_));
}
return *content_settings_instance_host;
}
} // namespace blink
| null | null | null | null | 36,218 |
3,969 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 168,964 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* file.c - NTFS kernel file operations. Part of the Linux-NTFS project.
*
* Copyright (c) 2001-2015 Anton Altaparmakov and Tuxera Inc.
*
* This program/include file 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/include file 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 (in the main directory of the Linux-NTFS
* distribution in the file COPYING); if not, write to the Free Software
* Foundation,Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/backing-dev.h>
#include <linux/buffer_head.h>
#include <linux/gfp.h>
#include <linux/pagemap.h>
#include <linux/pagevec.h>
#include <linux/sched/signal.h>
#include <linux/swap.h>
#include <linux/uio.h>
#include <linux/writeback.h>
#include <asm/page.h>
#include <linux/uaccess.h>
#include "attrib.h"
#include "bitmap.h"
#include "inode.h"
#include "debug.h"
#include "lcnalloc.h"
#include "malloc.h"
#include "mft.h"
#include "ntfs.h"
/**
* ntfs_file_open - called when an inode is about to be opened
* @vi: inode to be opened
* @filp: file structure describing the inode
*
* Limit file size to the page cache limit on architectures where unsigned long
* is 32-bits. This is the most we can do for now without overflowing the page
* cache page index. Doing it this way means we don't run into problems because
* of existing too large files. It would be better to allow the user to read
* the beginning of the file but I doubt very much anyone is going to hit this
* check on a 32-bit architecture, so there is no point in adding the extra
* complexity required to support this.
*
* On 64-bit architectures, the check is hopefully optimized away by the
* compiler.
*
* After the check passes, just call generic_file_open() to do its work.
*/
static int ntfs_file_open(struct inode *vi, struct file *filp)
{
if (sizeof(unsigned long) < 8) {
if (i_size_read(vi) > MAX_LFS_FILESIZE)
return -EOVERFLOW;
}
return generic_file_open(vi, filp);
}
#ifdef NTFS_RW
/**
* ntfs_attr_extend_initialized - extend the initialized size of an attribute
* @ni: ntfs inode of the attribute to extend
* @new_init_size: requested new initialized size in bytes
*
* Extend the initialized size of an attribute described by the ntfs inode @ni
* to @new_init_size bytes. This involves zeroing any non-sparse space between
* the old initialized size and @new_init_size both in the page cache and on
* disk (if relevant complete pages are already uptodate in the page cache then
* these are simply marked dirty).
*
* As a side-effect, the file size (vfs inode->i_size) may be incremented as,
* in the resident attribute case, it is tied to the initialized size and, in
* the non-resident attribute case, it may not fall below the initialized size.
*
* Note that if the attribute is resident, we do not need to touch the page
* cache at all. This is because if the page cache page is not uptodate we
* bring it uptodate later, when doing the write to the mft record since we
* then already have the page mapped. And if the page is uptodate, the
* non-initialized region will already have been zeroed when the page was
* brought uptodate and the region may in fact already have been overwritten
* with new data via mmap() based writes, so we cannot just zero it. And since
* POSIX specifies that the behaviour of resizing a file whilst it is mmap()ped
* is unspecified, we choose not to do zeroing and thus we do not need to touch
* the page at all. For a more detailed explanation see ntfs_truncate() in
* fs/ntfs/inode.c.
*
* Return 0 on success and -errno on error. In the case that an error is
* encountered it is possible that the initialized size will already have been
* incremented some way towards @new_init_size but it is guaranteed that if
* this is the case, the necessary zeroing will also have happened and that all
* metadata is self-consistent.
*
* Locking: i_mutex on the vfs inode corrseponsind to the ntfs inode @ni must be
* held by the caller.
*/
static int ntfs_attr_extend_initialized(ntfs_inode *ni, const s64 new_init_size)
{
s64 old_init_size;
loff_t old_i_size;
pgoff_t index, end_index;
unsigned long flags;
struct inode *vi = VFS_I(ni);
ntfs_inode *base_ni;
MFT_RECORD *m = NULL;
ATTR_RECORD *a;
ntfs_attr_search_ctx *ctx = NULL;
struct address_space *mapping;
struct page *page = NULL;
u8 *kattr;
int err;
u32 attr_len;
read_lock_irqsave(&ni->size_lock, flags);
old_init_size = ni->initialized_size;
old_i_size = i_size_read(vi);
BUG_ON(new_init_size > ni->allocated_size);
read_unlock_irqrestore(&ni->size_lock, flags);
ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, "
"old_initialized_size 0x%llx, "
"new_initialized_size 0x%llx, i_size 0x%llx.",
vi->i_ino, (unsigned)le32_to_cpu(ni->type),
(unsigned long long)old_init_size,
(unsigned long long)new_init_size, old_i_size);
if (!NInoAttr(ni))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
/* Use goto to reduce indentation and we need the label below anyway. */
if (NInoNonResident(ni))
goto do_non_resident_extend;
BUG_ON(old_init_size != old_i_size);
m = map_mft_record(base_ni);
if (IS_ERR(m)) {
err = PTR_ERR(m);
m = NULL;
goto err_out;
}
ctx = ntfs_attr_get_search_ctx(base_ni, m);
if (unlikely(!ctx)) {
err = -ENOMEM;
goto err_out;
}
err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
if (err == -ENOENT)
err = -EIO;
goto err_out;
}
m = ctx->mrec;
a = ctx->attr;
BUG_ON(a->non_resident);
/* The total length of the attribute value. */
attr_len = le32_to_cpu(a->data.resident.value_length);
BUG_ON(old_i_size != (loff_t)attr_len);
/*
* Do the zeroing in the mft record and update the attribute size in
* the mft record.
*/
kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
memset(kattr + attr_len, 0, new_init_size - attr_len);
a->data.resident.value_length = cpu_to_le32((u32)new_init_size);
/* Finally, update the sizes in the vfs and ntfs inodes. */
write_lock_irqsave(&ni->size_lock, flags);
i_size_write(vi, new_init_size);
ni->initialized_size = new_init_size;
write_unlock_irqrestore(&ni->size_lock, flags);
goto done;
do_non_resident_extend:
/*
* If the new initialized size @new_init_size exceeds the current file
* size (vfs inode->i_size), we need to extend the file size to the
* new initialized size.
*/
if (new_init_size > old_i_size) {
m = map_mft_record(base_ni);
if (IS_ERR(m)) {
err = PTR_ERR(m);
m = NULL;
goto err_out;
}
ctx = ntfs_attr_get_search_ctx(base_ni, m);
if (unlikely(!ctx)) {
err = -ENOMEM;
goto err_out;
}
err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
if (err == -ENOENT)
err = -EIO;
goto err_out;
}
m = ctx->mrec;
a = ctx->attr;
BUG_ON(!a->non_resident);
BUG_ON(old_i_size != (loff_t)
sle64_to_cpu(a->data.non_resident.data_size));
a->data.non_resident.data_size = cpu_to_sle64(new_init_size);
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
/* Update the file size in the vfs inode. */
i_size_write(vi, new_init_size);
ntfs_attr_put_search_ctx(ctx);
ctx = NULL;
unmap_mft_record(base_ni);
m = NULL;
}
mapping = vi->i_mapping;
index = old_init_size >> PAGE_SHIFT;
end_index = (new_init_size + PAGE_SIZE - 1) >> PAGE_SHIFT;
do {
/*
* Read the page. If the page is not present, this will zero
* the uninitialized regions for us.
*/
page = read_mapping_page(mapping, index, NULL);
if (IS_ERR(page)) {
err = PTR_ERR(page);
goto init_err_out;
}
if (unlikely(PageError(page))) {
put_page(page);
err = -EIO;
goto init_err_out;
}
/*
* Update the initialized size in the ntfs inode. This is
* enough to make ntfs_writepage() work.
*/
write_lock_irqsave(&ni->size_lock, flags);
ni->initialized_size = (s64)(index + 1) << PAGE_SHIFT;
if (ni->initialized_size > new_init_size)
ni->initialized_size = new_init_size;
write_unlock_irqrestore(&ni->size_lock, flags);
/* Set the page dirty so it gets written out. */
set_page_dirty(page);
put_page(page);
/*
* Play nice with the vm and the rest of the system. This is
* very much needed as we can potentially be modifying the
* initialised size from a very small value to a really huge
* value, e.g.
* f = open(somefile, O_TRUNC);
* truncate(f, 10GiB);
* seek(f, 10GiB);
* write(f, 1);
* And this would mean we would be marking dirty hundreds of
* thousands of pages or as in the above example more than
* two and a half million pages!
*
* TODO: For sparse pages could optimize this workload by using
* the FsMisc / MiscFs page bit as a "PageIsSparse" bit. This
* would be set in readpage for sparse pages and here we would
* not need to mark dirty any pages which have this bit set.
* The only caveat is that we have to clear the bit everywhere
* where we allocate any clusters that lie in the page or that
* contain the page.
*
* TODO: An even greater optimization would be for us to only
* call readpage() on pages which are not in sparse regions as
* determined from the runlist. This would greatly reduce the
* number of pages we read and make dirty in the case of sparse
* files.
*/
balance_dirty_pages_ratelimited(mapping);
cond_resched();
} while (++index < end_index);
read_lock_irqsave(&ni->size_lock, flags);
BUG_ON(ni->initialized_size != new_init_size);
read_unlock_irqrestore(&ni->size_lock, flags);
/* Now bring in sync the initialized_size in the mft record. */
m = map_mft_record(base_ni);
if (IS_ERR(m)) {
err = PTR_ERR(m);
m = NULL;
goto init_err_out;
}
ctx = ntfs_attr_get_search_ctx(base_ni, m);
if (unlikely(!ctx)) {
err = -ENOMEM;
goto init_err_out;
}
err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
if (err == -ENOENT)
err = -EIO;
goto init_err_out;
}
m = ctx->mrec;
a = ctx->attr;
BUG_ON(!a->non_resident);
a->data.non_resident.initialized_size = cpu_to_sle64(new_init_size);
done:
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (m)
unmap_mft_record(base_ni);
ntfs_debug("Done, initialized_size 0x%llx, i_size 0x%llx.",
(unsigned long long)new_init_size, i_size_read(vi));
return 0;
init_err_out:
write_lock_irqsave(&ni->size_lock, flags);
ni->initialized_size = old_init_size;
write_unlock_irqrestore(&ni->size_lock, flags);
err_out:
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (m)
unmap_mft_record(base_ni);
ntfs_debug("Failed. Returning error code %i.", err);
return err;
}
static ssize_t ntfs_prepare_file_for_write(struct kiocb *iocb,
struct iov_iter *from)
{
loff_t pos;
s64 end, ll;
ssize_t err;
unsigned long flags;
struct file *file = iocb->ki_filp;
struct inode *vi = file_inode(file);
ntfs_inode *base_ni, *ni = NTFS_I(vi);
ntfs_volume *vol = ni->vol;
ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
"0x%llx, count 0x%zx.", vi->i_ino,
(unsigned)le32_to_cpu(ni->type),
(unsigned long long)iocb->ki_pos,
iov_iter_count(from));
err = generic_write_checks(iocb, from);
if (unlikely(err <= 0))
goto out;
/*
* All checks have passed. Before we start doing any writing we want
* to abort any totally illegal writes.
*/
BUG_ON(NInoMstProtected(ni));
BUG_ON(ni->type != AT_DATA);
/* If file is encrypted, deny access, just like NT4. */
if (NInoEncrypted(ni)) {
/* Only $DATA attributes can be encrypted. */
/*
* Reminder for later: Encrypted files are _always_
* non-resident so that the content can always be encrypted.
*/
ntfs_debug("Denying write access to encrypted file.");
err = -EACCES;
goto out;
}
if (NInoCompressed(ni)) {
/* Only unnamed $DATA attribute can be compressed. */
BUG_ON(ni->name_len);
/*
* Reminder for later: If resident, the data is not actually
* compressed. Only on the switch to non-resident does
* compression kick in. This is in contrast to encrypted files
* (see above).
*/
ntfs_error(vi->i_sb, "Writing to compressed files is not "
"implemented yet. Sorry.");
err = -EOPNOTSUPP;
goto out;
}
base_ni = ni;
if (NInoAttr(ni))
base_ni = ni->ext.base_ntfs_ino;
err = file_remove_privs(file);
if (unlikely(err))
goto out;
/*
* Our ->update_time method always succeeds thus file_update_time()
* cannot fail either so there is no need to check the return code.
*/
file_update_time(file);
pos = iocb->ki_pos;
/* The first byte after the last cluster being written to. */
end = (pos + iov_iter_count(from) + vol->cluster_size_mask) &
~(u64)vol->cluster_size_mask;
/*
* If the write goes beyond the allocated size, extend the allocation
* to cover the whole of the write, rounded up to the nearest cluster.
*/
read_lock_irqsave(&ni->size_lock, flags);
ll = ni->allocated_size;
read_unlock_irqrestore(&ni->size_lock, flags);
if (end > ll) {
/*
* Extend the allocation without changing the data size.
*
* Note we ensure the allocation is big enough to at least
* write some data but we do not require the allocation to be
* complete, i.e. it may be partial.
*/
ll = ntfs_attr_extend_allocation(ni, end, -1, pos);
if (likely(ll >= 0)) {
BUG_ON(pos >= ll);
/* If the extension was partial truncate the write. */
if (end > ll) {
ntfs_debug("Truncating write to inode 0x%lx, "
"attribute type 0x%x, because "
"the allocation was only "
"partially extended.",
vi->i_ino, (unsigned)
le32_to_cpu(ni->type));
iov_iter_truncate(from, ll - pos);
}
} else {
err = ll;
read_lock_irqsave(&ni->size_lock, flags);
ll = ni->allocated_size;
read_unlock_irqrestore(&ni->size_lock, flags);
/* Perform a partial write if possible or fail. */
if (pos < ll) {
ntfs_debug("Truncating write to inode 0x%lx "
"attribute type 0x%x, because "
"extending the allocation "
"failed (error %d).",
vi->i_ino, (unsigned)
le32_to_cpu(ni->type),
(int)-err);
iov_iter_truncate(from, ll - pos);
} else {
if (err != -ENOSPC)
ntfs_error(vi->i_sb, "Cannot perform "
"write to inode "
"0x%lx, attribute "
"type 0x%x, because "
"extending the "
"allocation failed "
"(error %ld).",
vi->i_ino, (unsigned)
le32_to_cpu(ni->type),
(long)-err);
else
ntfs_debug("Cannot perform write to "
"inode 0x%lx, "
"attribute type 0x%x, "
"because there is not "
"space left.",
vi->i_ino, (unsigned)
le32_to_cpu(ni->type));
goto out;
}
}
}
/*
* If the write starts beyond the initialized size, extend it up to the
* beginning of the write and initialize all non-sparse space between
* the old initialized size and the new one. This automatically also
* increments the vfs inode->i_size to keep it above or equal to the
* initialized_size.
*/
read_lock_irqsave(&ni->size_lock, flags);
ll = ni->initialized_size;
read_unlock_irqrestore(&ni->size_lock, flags);
if (pos > ll) {
/*
* Wait for ongoing direct i/o to complete before proceeding.
* New direct i/o cannot start as we hold i_mutex.
*/
inode_dio_wait(vi);
err = ntfs_attr_extend_initialized(ni, pos);
if (unlikely(err < 0))
ntfs_error(vi->i_sb, "Cannot perform write to inode "
"0x%lx, attribute type 0x%x, because "
"extending the initialized size "
"failed (error %d).", vi->i_ino,
(unsigned)le32_to_cpu(ni->type),
(int)-err);
}
out:
return err;
}
/**
* __ntfs_grab_cache_pages - obtain a number of locked pages
* @mapping: address space mapping from which to obtain page cache pages
* @index: starting index in @mapping at which to begin obtaining pages
* @nr_pages: number of page cache pages to obtain
* @pages: array of pages in which to return the obtained page cache pages
* @cached_page: allocated but as yet unused page
*
* Obtain @nr_pages locked page cache pages from the mapping @mapping and
* starting at index @index.
*
* If a page is newly created, add it to lru list
*
* Note, the page locks are obtained in ascending page index order.
*/
static inline int __ntfs_grab_cache_pages(struct address_space *mapping,
pgoff_t index, const unsigned nr_pages, struct page **pages,
struct page **cached_page)
{
int err, nr;
BUG_ON(!nr_pages);
err = nr = 0;
do {
pages[nr] = find_get_page_flags(mapping, index, FGP_LOCK |
FGP_ACCESSED);
if (!pages[nr]) {
if (!*cached_page) {
*cached_page = page_cache_alloc(mapping);
if (unlikely(!*cached_page)) {
err = -ENOMEM;
goto err_out;
}
}
err = add_to_page_cache_lru(*cached_page, mapping,
index,
mapping_gfp_constraint(mapping, GFP_KERNEL));
if (unlikely(err)) {
if (err == -EEXIST)
continue;
goto err_out;
}
pages[nr] = *cached_page;
*cached_page = NULL;
}
index++;
nr++;
} while (nr < nr_pages);
out:
return err;
err_out:
while (nr > 0) {
unlock_page(pages[--nr]);
put_page(pages[nr]);
}
goto out;
}
static inline int ntfs_submit_bh_for_read(struct buffer_head *bh)
{
lock_buffer(bh);
get_bh(bh);
bh->b_end_io = end_buffer_read_sync;
return submit_bh(REQ_OP_READ, 0, bh);
}
/**
* ntfs_prepare_pages_for_non_resident_write - prepare pages for receiving data
* @pages: array of destination pages
* @nr_pages: number of pages in @pages
* @pos: byte position in file at which the write begins
* @bytes: number of bytes to be written
*
* This is called for non-resident attributes from ntfs_file_buffered_write()
* with i_mutex held on the inode (@pages[0]->mapping->host). There are
* @nr_pages pages in @pages which are locked but not kmap()ped. The source
* data has not yet been copied into the @pages.
*
* Need to fill any holes with actual clusters, allocate buffers if necessary,
* ensure all the buffers are mapped, and bring uptodate any buffers that are
* only partially being written to.
*
* If @nr_pages is greater than one, we are guaranteed that the cluster size is
* greater than PAGE_SIZE, that all pages in @pages are entirely inside
* the same cluster and that they are the entirety of that cluster, and that
* the cluster is sparse, i.e. we need to allocate a cluster to fill the hole.
*
* i_size is not to be modified yet.
*
* Return 0 on success or -errno on error.
*/
static int ntfs_prepare_pages_for_non_resident_write(struct page **pages,
unsigned nr_pages, s64 pos, size_t bytes)
{
VCN vcn, highest_vcn = 0, cpos, cend, bh_cpos, bh_cend;
LCN lcn;
s64 bh_pos, vcn_len, end, initialized_size;
sector_t lcn_block;
struct page *page;
struct inode *vi;
ntfs_inode *ni, *base_ni = NULL;
ntfs_volume *vol;
runlist_element *rl, *rl2;
struct buffer_head *bh, *head, *wait[2], **wait_bh = wait;
ntfs_attr_search_ctx *ctx = NULL;
MFT_RECORD *m = NULL;
ATTR_RECORD *a = NULL;
unsigned long flags;
u32 attr_rec_len = 0;
unsigned blocksize, u;
int err, mp_size;
bool rl_write_locked, was_hole, is_retry;
unsigned char blocksize_bits;
struct {
u8 runlist_merged:1;
u8 mft_attr_mapped:1;
u8 mp_rebuilt:1;
u8 attr_switched:1;
} status = { 0, 0, 0, 0 };
BUG_ON(!nr_pages);
BUG_ON(!pages);
BUG_ON(!*pages);
vi = pages[0]->mapping->host;
ni = NTFS_I(vi);
vol = ni->vol;
ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
"index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
vi->i_ino, ni->type, pages[0]->index, nr_pages,
(long long)pos, bytes);
blocksize = vol->sb->s_blocksize;
blocksize_bits = vol->sb->s_blocksize_bits;
u = 0;
do {
page = pages[u];
BUG_ON(!page);
/*
* create_empty_buffers() will create uptodate/dirty buffers if
* the page is uptodate/dirty.
*/
if (!page_has_buffers(page)) {
create_empty_buffers(page, blocksize, 0);
if (unlikely(!page_has_buffers(page)))
return -ENOMEM;
}
} while (++u < nr_pages);
rl_write_locked = false;
rl = NULL;
err = 0;
vcn = lcn = -1;
vcn_len = 0;
lcn_block = -1;
was_hole = false;
cpos = pos >> vol->cluster_size_bits;
end = pos + bytes;
cend = (end + vol->cluster_size - 1) >> vol->cluster_size_bits;
/*
* Loop over each page and for each page over each buffer. Use goto to
* reduce indentation.
*/
u = 0;
do_next_page:
page = pages[u];
bh_pos = (s64)page->index << PAGE_SHIFT;
bh = head = page_buffers(page);
do {
VCN cdelta;
s64 bh_end;
unsigned bh_cofs;
/* Clear buffer_new on all buffers to reinitialise state. */
if (buffer_new(bh))
clear_buffer_new(bh);
bh_end = bh_pos + blocksize;
bh_cpos = bh_pos >> vol->cluster_size_bits;
bh_cofs = bh_pos & vol->cluster_size_mask;
if (buffer_mapped(bh)) {
/*
* The buffer is already mapped. If it is uptodate,
* ignore it.
*/
if (buffer_uptodate(bh))
continue;
/*
* The buffer is not uptodate. If the page is uptodate
* set the buffer uptodate and otherwise ignore it.
*/
if (PageUptodate(page)) {
set_buffer_uptodate(bh);
continue;
}
/*
* Neither the page nor the buffer are uptodate. If
* the buffer is only partially being written to, we
* need to read it in before the write, i.e. now.
*/
if ((bh_pos < pos && bh_end > pos) ||
(bh_pos < end && bh_end > end)) {
/*
* If the buffer is fully or partially within
* the initialized size, do an actual read.
* Otherwise, simply zero the buffer.
*/
read_lock_irqsave(&ni->size_lock, flags);
initialized_size = ni->initialized_size;
read_unlock_irqrestore(&ni->size_lock, flags);
if (bh_pos < initialized_size) {
ntfs_submit_bh_for_read(bh);
*wait_bh++ = bh;
} else {
zero_user(page, bh_offset(bh),
blocksize);
set_buffer_uptodate(bh);
}
}
continue;
}
/* Unmapped buffer. Need to map it. */
bh->b_bdev = vol->sb->s_bdev;
/*
* If the current buffer is in the same clusters as the map
* cache, there is no need to check the runlist again. The
* map cache is made up of @vcn, which is the first cached file
* cluster, @vcn_len which is the number of cached file
* clusters, @lcn is the device cluster corresponding to @vcn,
* and @lcn_block is the block number corresponding to @lcn.
*/
cdelta = bh_cpos - vcn;
if (likely(!cdelta || (cdelta > 0 && cdelta < vcn_len))) {
map_buffer_cached:
BUG_ON(lcn < 0);
bh->b_blocknr = lcn_block +
(cdelta << (vol->cluster_size_bits -
blocksize_bits)) +
(bh_cofs >> blocksize_bits);
set_buffer_mapped(bh);
/*
* If the page is uptodate so is the buffer. If the
* buffer is fully outside the write, we ignore it if
* it was already allocated and we mark it dirty so it
* gets written out if we allocated it. On the other
* hand, if we allocated the buffer but we are not
* marking it dirty we set buffer_new so we can do
* error recovery.
*/
if (PageUptodate(page)) {
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
if (unlikely(was_hole)) {
/* We allocated the buffer. */
clean_bdev_bh_alias(bh);
if (bh_end <= pos || bh_pos >= end)
mark_buffer_dirty(bh);
else
set_buffer_new(bh);
}
continue;
}
/* Page is _not_ uptodate. */
if (likely(!was_hole)) {
/*
* Buffer was already allocated. If it is not
* uptodate and is only partially being written
* to, we need to read it in before the write,
* i.e. now.
*/
if (!buffer_uptodate(bh) && bh_pos < end &&
bh_end > pos &&
(bh_pos < pos ||
bh_end > end)) {
/*
* If the buffer is fully or partially
* within the initialized size, do an
* actual read. Otherwise, simply zero
* the buffer.
*/
read_lock_irqsave(&ni->size_lock,
flags);
initialized_size = ni->initialized_size;
read_unlock_irqrestore(&ni->size_lock,
flags);
if (bh_pos < initialized_size) {
ntfs_submit_bh_for_read(bh);
*wait_bh++ = bh;
} else {
zero_user(page, bh_offset(bh),
blocksize);
set_buffer_uptodate(bh);
}
}
continue;
}
/* We allocated the buffer. */
clean_bdev_bh_alias(bh);
/*
* If the buffer is fully outside the write, zero it,
* set it uptodate, and mark it dirty so it gets
* written out. If it is partially being written to,
* zero region surrounding the write but leave it to
* commit write to do anything else. Finally, if the
* buffer is fully being overwritten, do nothing.
*/
if (bh_end <= pos || bh_pos >= end) {
if (!buffer_uptodate(bh)) {
zero_user(page, bh_offset(bh),
blocksize);
set_buffer_uptodate(bh);
}
mark_buffer_dirty(bh);
continue;
}
set_buffer_new(bh);
if (!buffer_uptodate(bh) &&
(bh_pos < pos || bh_end > end)) {
u8 *kaddr;
unsigned pofs;
kaddr = kmap_atomic(page);
if (bh_pos < pos) {
pofs = bh_pos & ~PAGE_MASK;
memset(kaddr + pofs, 0, pos - bh_pos);
}
if (bh_end > end) {
pofs = end & ~PAGE_MASK;
memset(kaddr + pofs, 0, bh_end - end);
}
kunmap_atomic(kaddr);
flush_dcache_page(page);
}
continue;
}
/*
* Slow path: this is the first buffer in the cluster. If it
* is outside allocated size and is not uptodate, zero it and
* set it uptodate.
*/
read_lock_irqsave(&ni->size_lock, flags);
initialized_size = ni->allocated_size;
read_unlock_irqrestore(&ni->size_lock, flags);
if (bh_pos > initialized_size) {
if (PageUptodate(page)) {
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
} else if (!buffer_uptodate(bh)) {
zero_user(page, bh_offset(bh), blocksize);
set_buffer_uptodate(bh);
}
continue;
}
is_retry = false;
if (!rl) {
down_read(&ni->runlist.lock);
retry_remap:
rl = ni->runlist.rl;
}
if (likely(rl != NULL)) {
/* Seek to element containing target cluster. */
while (rl->length && rl[1].vcn <= bh_cpos)
rl++;
lcn = ntfs_rl_vcn_to_lcn(rl, bh_cpos);
if (likely(lcn >= 0)) {
/*
* Successful remap, setup the map cache and
* use that to deal with the buffer.
*/
was_hole = false;
vcn = bh_cpos;
vcn_len = rl[1].vcn - vcn;
lcn_block = lcn << (vol->cluster_size_bits -
blocksize_bits);
cdelta = 0;
/*
* If the number of remaining clusters touched
* by the write is smaller or equal to the
* number of cached clusters, unlock the
* runlist as the map cache will be used from
* now on.
*/
if (likely(vcn + vcn_len >= cend)) {
if (rl_write_locked) {
up_write(&ni->runlist.lock);
rl_write_locked = false;
} else
up_read(&ni->runlist.lock);
rl = NULL;
}
goto map_buffer_cached;
}
} else
lcn = LCN_RL_NOT_MAPPED;
/*
* If it is not a hole and not out of bounds, the runlist is
* probably unmapped so try to map it now.
*/
if (unlikely(lcn != LCN_HOLE && lcn != LCN_ENOENT)) {
if (likely(!is_retry && lcn == LCN_RL_NOT_MAPPED)) {
/* Attempt to map runlist. */
if (!rl_write_locked) {
/*
* We need the runlist locked for
* writing, so if it is locked for
* reading relock it now and retry in
* case it changed whilst we dropped
* the lock.
*/
up_read(&ni->runlist.lock);
down_write(&ni->runlist.lock);
rl_write_locked = true;
goto retry_remap;
}
err = ntfs_map_runlist_nolock(ni, bh_cpos,
NULL);
if (likely(!err)) {
is_retry = true;
goto retry_remap;
}
/*
* If @vcn is out of bounds, pretend @lcn is
* LCN_ENOENT. As long as the buffer is out
* of bounds this will work fine.
*/
if (err == -ENOENT) {
lcn = LCN_ENOENT;
err = 0;
goto rl_not_mapped_enoent;
}
} else
err = -EIO;
/* Failed to map the buffer, even after retrying. */
bh->b_blocknr = -1;
ntfs_error(vol->sb, "Failed to write to inode 0x%lx, "
"attribute type 0x%x, vcn 0x%llx, "
"vcn offset 0x%x, because its "
"location on disk could not be "
"determined%s (error code %i).",
ni->mft_no, ni->type,
(unsigned long long)bh_cpos,
(unsigned)bh_pos &
vol->cluster_size_mask,
is_retry ? " even after retrying" : "",
err);
break;
}
rl_not_mapped_enoent:
/*
* The buffer is in a hole or out of bounds. We need to fill
* the hole, unless the buffer is in a cluster which is not
* touched by the write, in which case we just leave the buffer
* unmapped. This can only happen when the cluster size is
* less than the page cache size.
*/
if (unlikely(vol->cluster_size < PAGE_SIZE)) {
bh_cend = (bh_end + vol->cluster_size - 1) >>
vol->cluster_size_bits;
if ((bh_cend <= cpos || bh_cpos >= cend)) {
bh->b_blocknr = -1;
/*
* If the buffer is uptodate we skip it. If it
* is not but the page is uptodate, we can set
* the buffer uptodate. If the page is not
* uptodate, we can clear the buffer and set it
* uptodate. Whether this is worthwhile is
* debatable and this could be removed.
*/
if (PageUptodate(page)) {
if (!buffer_uptodate(bh))
set_buffer_uptodate(bh);
} else if (!buffer_uptodate(bh)) {
zero_user(page, bh_offset(bh),
blocksize);
set_buffer_uptodate(bh);
}
continue;
}
}
/*
* Out of bounds buffer is invalid if it was not really out of
* bounds.
*/
BUG_ON(lcn != LCN_HOLE);
/*
* We need the runlist locked for writing, so if it is locked
* for reading relock it now and retry in case it changed
* whilst we dropped the lock.
*/
BUG_ON(!rl);
if (!rl_write_locked) {
up_read(&ni->runlist.lock);
down_write(&ni->runlist.lock);
rl_write_locked = true;
goto retry_remap;
}
/* Find the previous last allocated cluster. */
BUG_ON(rl->lcn != LCN_HOLE);
lcn = -1;
rl2 = rl;
while (--rl2 >= ni->runlist.rl) {
if (rl2->lcn >= 0) {
lcn = rl2->lcn + rl2->length;
break;
}
}
rl2 = ntfs_cluster_alloc(vol, bh_cpos, 1, lcn, DATA_ZONE,
false);
if (IS_ERR(rl2)) {
err = PTR_ERR(rl2);
ntfs_debug("Failed to allocate cluster, error code %i.",
err);
break;
}
lcn = rl2->lcn;
rl = ntfs_runlists_merge(ni->runlist.rl, rl2);
if (IS_ERR(rl)) {
err = PTR_ERR(rl);
if (err != -ENOMEM)
err = -EIO;
if (ntfs_cluster_free_from_rl(vol, rl2)) {
ntfs_error(vol->sb, "Failed to release "
"allocated cluster in error "
"code path. Run chkdsk to "
"recover the lost cluster.");
NVolSetErrors(vol);
}
ntfs_free(rl2);
break;
}
ni->runlist.rl = rl;
status.runlist_merged = 1;
ntfs_debug("Allocated cluster, lcn 0x%llx.",
(unsigned long long)lcn);
/* Map and lock the mft record and get the attribute record. */
if (!NInoAttr(ni))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
m = map_mft_record(base_ni);
if (IS_ERR(m)) {
err = PTR_ERR(m);
break;
}
ctx = ntfs_attr_get_search_ctx(base_ni, m);
if (unlikely(!ctx)) {
err = -ENOMEM;
unmap_mft_record(base_ni);
break;
}
status.mft_attr_mapped = 1;
err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, bh_cpos, NULL, 0, ctx);
if (unlikely(err)) {
if (err == -ENOENT)
err = -EIO;
break;
}
m = ctx->mrec;
a = ctx->attr;
/*
* Find the runlist element with which the attribute extent
* starts. Note, we cannot use the _attr_ version because we
* have mapped the mft record. That is ok because we know the
* runlist fragment must be mapped already to have ever gotten
* here, so we can just use the _rl_ version.
*/
vcn = sle64_to_cpu(a->data.non_resident.lowest_vcn);
rl2 = ntfs_rl_find_vcn_nolock(rl, vcn);
BUG_ON(!rl2);
BUG_ON(!rl2->length);
BUG_ON(rl2->lcn < LCN_HOLE);
highest_vcn = sle64_to_cpu(a->data.non_resident.highest_vcn);
/*
* If @highest_vcn is zero, calculate the real highest_vcn
* (which can really be zero).
*/
if (!highest_vcn)
highest_vcn = (sle64_to_cpu(
a->data.non_resident.allocated_size) >>
vol->cluster_size_bits) - 1;
/*
* Determine the size of the mapping pairs array for the new
* extent, i.e. the old extent with the hole filled.
*/
mp_size = ntfs_get_size_for_mapping_pairs(vol, rl2, vcn,
highest_vcn);
if (unlikely(mp_size <= 0)) {
if (!(err = mp_size))
err = -EIO;
ntfs_debug("Failed to get size for mapping pairs "
"array, error code %i.", err);
break;
}
/*
* Resize the attribute record to fit the new mapping pairs
* array.
*/
attr_rec_len = le32_to_cpu(a->length);
err = ntfs_attr_record_resize(m, a, mp_size + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset));
if (unlikely(err)) {
BUG_ON(err != -ENOSPC);
// TODO: Deal with this by using the current attribute
// and fill it with as much of the mapping pairs
// array as possible. Then loop over each attribute
// extent rewriting the mapping pairs arrays as we go
// along and if when we reach the end we have not
// enough space, try to resize the last attribute
// extent and if even that fails, add a new attribute
// extent.
// We could also try to resize at each step in the hope
// that we will not need to rewrite every single extent.
// Note, we may need to decompress some extents to fill
// the runlist as we are walking the extents...
ntfs_error(vol->sb, "Not enough space in the mft "
"record for the extended attribute "
"record. This case is not "
"implemented yet.");
err = -EOPNOTSUPP;
break ;
}
status.mp_rebuilt = 1;
/*
* Generate the mapping pairs array directly into the attribute
* record.
*/
err = ntfs_mapping_pairs_build(vol, (u8*)a + le16_to_cpu(
a->data.non_resident.mapping_pairs_offset),
mp_size, rl2, vcn, highest_vcn, NULL);
if (unlikely(err)) {
ntfs_error(vol->sb, "Cannot fill hole in inode 0x%lx, "
"attribute type 0x%x, because building "
"the mapping pairs failed with error "
"code %i.", vi->i_ino,
(unsigned)le32_to_cpu(ni->type), err);
err = -EIO;
break;
}
/* Update the highest_vcn but only if it was not set. */
if (unlikely(!a->data.non_resident.highest_vcn))
a->data.non_resident.highest_vcn =
cpu_to_sle64(highest_vcn);
/*
* If the attribute is sparse/compressed, update the compressed
* size in the ntfs_inode structure and the attribute record.
*/
if (likely(NInoSparse(ni) || NInoCompressed(ni))) {
/*
* If we are not in the first attribute extent, switch
* to it, but first ensure the changes will make it to
* disk later.
*/
if (a->data.non_resident.lowest_vcn) {
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_reinit_search_ctx(ctx);
err = ntfs_attr_lookup(ni->type, ni->name,
ni->name_len, CASE_SENSITIVE,
0, NULL, 0, ctx);
if (unlikely(err)) {
status.attr_switched = 1;
break;
}
/* @m is not used any more so do not set it. */
a = ctx->attr;
}
write_lock_irqsave(&ni->size_lock, flags);
ni->itype.compressed.size += vol->cluster_size;
a->data.non_resident.compressed_size =
cpu_to_sle64(ni->itype.compressed.size);
write_unlock_irqrestore(&ni->size_lock, flags);
}
/* Ensure the changes make it to disk. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(base_ni);
/* Successfully filled the hole. */
status.runlist_merged = 0;
status.mft_attr_mapped = 0;
status.mp_rebuilt = 0;
/* Setup the map cache and use that to deal with the buffer. */
was_hole = true;
vcn = bh_cpos;
vcn_len = 1;
lcn_block = lcn << (vol->cluster_size_bits - blocksize_bits);
cdelta = 0;
/*
* If the number of remaining clusters in the @pages is smaller
* or equal to the number of cached clusters, unlock the
* runlist as the map cache will be used from now on.
*/
if (likely(vcn + vcn_len >= cend)) {
up_write(&ni->runlist.lock);
rl_write_locked = false;
rl = NULL;
}
goto map_buffer_cached;
} while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
/* If there are no errors, do the next page. */
if (likely(!err && ++u < nr_pages))
goto do_next_page;
/* If there are no errors, release the runlist lock if we took it. */
if (likely(!err)) {
if (unlikely(rl_write_locked)) {
up_write(&ni->runlist.lock);
rl_write_locked = false;
} else if (unlikely(rl))
up_read(&ni->runlist.lock);
rl = NULL;
}
/* If we issued read requests, let them complete. */
read_lock_irqsave(&ni->size_lock, flags);
initialized_size = ni->initialized_size;
read_unlock_irqrestore(&ni->size_lock, flags);
while (wait_bh > wait) {
bh = *--wait_bh;
wait_on_buffer(bh);
if (likely(buffer_uptodate(bh))) {
page = bh->b_page;
bh_pos = ((s64)page->index << PAGE_SHIFT) +
bh_offset(bh);
/*
* If the buffer overflows the initialized size, need
* to zero the overflowing region.
*/
if (unlikely(bh_pos + blocksize > initialized_size)) {
int ofs = 0;
if (likely(bh_pos < initialized_size))
ofs = initialized_size - bh_pos;
zero_user_segment(page, bh_offset(bh) + ofs,
blocksize);
}
} else /* if (unlikely(!buffer_uptodate(bh))) */
err = -EIO;
}
if (likely(!err)) {
/* Clear buffer_new on all buffers. */
u = 0;
do {
bh = head = page_buffers(pages[u]);
do {
if (buffer_new(bh))
clear_buffer_new(bh);
} while ((bh = bh->b_this_page) != head);
} while (++u < nr_pages);
ntfs_debug("Done.");
return err;
}
if (status.attr_switched) {
/* Get back to the attribute extent we modified. */
ntfs_attr_reinit_search_ctx(ctx);
if (ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, bh_cpos, NULL, 0, ctx)) {
ntfs_error(vol->sb, "Failed to find required "
"attribute extent of attribute in "
"error code path. Run chkdsk to "
"recover.");
write_lock_irqsave(&ni->size_lock, flags);
ni->itype.compressed.size += vol->cluster_size;
write_unlock_irqrestore(&ni->size_lock, flags);
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
/*
* The only thing that is now wrong is the compressed
* size of the base attribute extent which chkdsk
* should be able to fix.
*/
NVolSetErrors(vol);
} else {
m = ctx->mrec;
a = ctx->attr;
status.attr_switched = 0;
}
}
/*
* If the runlist has been modified, need to restore it by punching a
* hole into it and we then need to deallocate the on-disk cluster as
* well. Note, we only modify the runlist if we are able to generate a
* new mapping pairs array, i.e. only when the mapped attribute extent
* is not switched.
*/
if (status.runlist_merged && !status.attr_switched) {
BUG_ON(!rl_write_locked);
/* Make the file cluster we allocated sparse in the runlist. */
if (ntfs_rl_punch_nolock(vol, &ni->runlist, bh_cpos, 1)) {
ntfs_error(vol->sb, "Failed to punch hole into "
"attribute runlist in error code "
"path. Run chkdsk to recover the "
"lost cluster.");
NVolSetErrors(vol);
} else /* if (success) */ {
status.runlist_merged = 0;
/*
* Deallocate the on-disk cluster we allocated but only
* if we succeeded in punching its vcn out of the
* runlist.
*/
down_write(&vol->lcnbmp_lock);
if (ntfs_bitmap_clear_bit(vol->lcnbmp_ino, lcn)) {
ntfs_error(vol->sb, "Failed to release "
"allocated cluster in error "
"code path. Run chkdsk to "
"recover the lost cluster.");
NVolSetErrors(vol);
}
up_write(&vol->lcnbmp_lock);
}
}
/*
* Resize the attribute record to its old size and rebuild the mapping
* pairs array. Note, we only can do this if the runlist has been
* restored to its old state which also implies that the mapped
* attribute extent is not switched.
*/
if (status.mp_rebuilt && !status.runlist_merged) {
if (ntfs_attr_record_resize(m, a, attr_rec_len)) {
ntfs_error(vol->sb, "Failed to restore attribute "
"record in error code path. Run "
"chkdsk to recover.");
NVolSetErrors(vol);
} else /* if (success) */ {
if (ntfs_mapping_pairs_build(vol, (u8*)a +
le16_to_cpu(a->data.non_resident.
mapping_pairs_offset), attr_rec_len -
le16_to_cpu(a->data.non_resident.
mapping_pairs_offset), ni->runlist.rl,
vcn, highest_vcn, NULL)) {
ntfs_error(vol->sb, "Failed to restore "
"mapping pairs array in error "
"code path. Run chkdsk to "
"recover.");
NVolSetErrors(vol);
}
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
}
}
/* Release the mft record and the attribute. */
if (status.mft_attr_mapped) {
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(base_ni);
}
/* Release the runlist lock. */
if (rl_write_locked)
up_write(&ni->runlist.lock);
else if (rl)
up_read(&ni->runlist.lock);
/*
* Zero out any newly allocated blocks to avoid exposing stale data.
* If BH_New is set, we know that the block was newly allocated above
* and that it has not been fully zeroed and marked dirty yet.
*/
nr_pages = u;
u = 0;
end = bh_cpos << vol->cluster_size_bits;
do {
page = pages[u];
bh = head = page_buffers(page);
do {
if (u == nr_pages &&
((s64)page->index << PAGE_SHIFT) +
bh_offset(bh) >= end)
break;
if (!buffer_new(bh))
continue;
clear_buffer_new(bh);
if (!buffer_uptodate(bh)) {
if (PageUptodate(page))
set_buffer_uptodate(bh);
else {
zero_user(page, bh_offset(bh),
blocksize);
set_buffer_uptodate(bh);
}
}
mark_buffer_dirty(bh);
} while ((bh = bh->b_this_page) != head);
} while (++u <= nr_pages);
ntfs_error(vol->sb, "Failed. Returning error code %i.", err);
return err;
}
static inline void ntfs_flush_dcache_pages(struct page **pages,
unsigned nr_pages)
{
BUG_ON(!nr_pages);
/*
* Warning: Do not do the decrement at the same time as the call to
* flush_dcache_page() because it is a NULL macro on i386 and hence the
* decrement never happens so the loop never terminates.
*/
do {
--nr_pages;
flush_dcache_page(pages[nr_pages]);
} while (nr_pages > 0);
}
/**
* ntfs_commit_pages_after_non_resident_write - commit the received data
* @pages: array of destination pages
* @nr_pages: number of pages in @pages
* @pos: byte position in file at which the write begins
* @bytes: number of bytes to be written
*
* See description of ntfs_commit_pages_after_write(), below.
*/
static inline int ntfs_commit_pages_after_non_resident_write(
struct page **pages, const unsigned nr_pages,
s64 pos, size_t bytes)
{
s64 end, initialized_size;
struct inode *vi;
ntfs_inode *ni, *base_ni;
struct buffer_head *bh, *head;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *m;
ATTR_RECORD *a;
unsigned long flags;
unsigned blocksize, u;
int err;
vi = pages[0]->mapping->host;
ni = NTFS_I(vi);
blocksize = vi->i_sb->s_blocksize;
end = pos + bytes;
u = 0;
do {
s64 bh_pos;
struct page *page;
bool partial;
page = pages[u];
bh_pos = (s64)page->index << PAGE_SHIFT;
bh = head = page_buffers(page);
partial = false;
do {
s64 bh_end;
bh_end = bh_pos + blocksize;
if (bh_end <= pos || bh_pos >= end) {
if (!buffer_uptodate(bh))
partial = true;
} else {
set_buffer_uptodate(bh);
mark_buffer_dirty(bh);
}
} while (bh_pos += blocksize, (bh = bh->b_this_page) != head);
/*
* If all buffers are now uptodate but the page is not, set the
* page uptodate.
*/
if (!partial && !PageUptodate(page))
SetPageUptodate(page);
} while (++u < nr_pages);
/*
* Finally, if we do not need to update initialized_size or i_size we
* are finished.
*/
read_lock_irqsave(&ni->size_lock, flags);
initialized_size = ni->initialized_size;
read_unlock_irqrestore(&ni->size_lock, flags);
if (end <= initialized_size) {
ntfs_debug("Done.");
return 0;
}
/*
* Update initialized_size/i_size as appropriate, both in the inode and
* the mft record.
*/
if (!NInoAttr(ni))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
/* Map, pin, and lock the mft record. */
m = map_mft_record(base_ni);
if (IS_ERR(m)) {
err = PTR_ERR(m);
m = NULL;
ctx = NULL;
goto err_out;
}
BUG_ON(!NInoNonResident(ni));
ctx = ntfs_attr_get_search_ctx(base_ni, m);
if (unlikely(!ctx)) {
err = -ENOMEM;
goto err_out;
}
err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
if (err == -ENOENT)
err = -EIO;
goto err_out;
}
a = ctx->attr;
BUG_ON(!a->non_resident);
write_lock_irqsave(&ni->size_lock, flags);
BUG_ON(end > ni->allocated_size);
ni->initialized_size = end;
a->data.non_resident.initialized_size = cpu_to_sle64(end);
if (end > i_size_read(vi)) {
i_size_write(vi, end);
a->data.non_resident.data_size =
a->data.non_resident.initialized_size;
}
write_unlock_irqrestore(&ni->size_lock, flags);
/* Mark the mft record dirty, so it gets written back. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(base_ni);
ntfs_debug("Done.");
return 0;
err_out:
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (m)
unmap_mft_record(base_ni);
ntfs_error(vi->i_sb, "Failed to update initialized_size/i_size (error "
"code %i).", err);
if (err != -ENOMEM)
NVolSetErrors(ni->vol);
return err;
}
/**
* ntfs_commit_pages_after_write - commit the received data
* @pages: array of destination pages
* @nr_pages: number of pages in @pages
* @pos: byte position in file at which the write begins
* @bytes: number of bytes to be written
*
* This is called from ntfs_file_buffered_write() with i_mutex held on the inode
* (@pages[0]->mapping->host). There are @nr_pages pages in @pages which are
* locked but not kmap()ped. The source data has already been copied into the
* @page. ntfs_prepare_pages_for_non_resident_write() has been called before
* the data was copied (for non-resident attributes only) and it returned
* success.
*
* Need to set uptodate and mark dirty all buffers within the boundary of the
* write. If all buffers in a page are uptodate we set the page uptodate, too.
*
* Setting the buffers dirty ensures that they get written out later when
* ntfs_writepage() is invoked by the VM.
*
* Finally, we need to update i_size and initialized_size as appropriate both
* in the inode and the mft record.
*
* This is modelled after fs/buffer.c::generic_commit_write(), which marks
* buffers uptodate and dirty, sets the page uptodate if all buffers in the
* page are uptodate, and updates i_size if the end of io is beyond i_size. In
* that case, it also marks the inode dirty.
*
* If things have gone as outlined in
* ntfs_prepare_pages_for_non_resident_write(), we do not need to do any page
* content modifications here for non-resident attributes. For resident
* attributes we need to do the uptodate bringing here which we combine with
* the copying into the mft record which means we save one atomic kmap.
*
* Return 0 on success or -errno on error.
*/
static int ntfs_commit_pages_after_write(struct page **pages,
const unsigned nr_pages, s64 pos, size_t bytes)
{
s64 end, initialized_size;
loff_t i_size;
struct inode *vi;
ntfs_inode *ni, *base_ni;
struct page *page;
ntfs_attr_search_ctx *ctx;
MFT_RECORD *m;
ATTR_RECORD *a;
char *kattr, *kaddr;
unsigned long flags;
u32 attr_len;
int err;
BUG_ON(!nr_pages);
BUG_ON(!pages);
page = pages[0];
BUG_ON(!page);
vi = page->mapping->host;
ni = NTFS_I(vi);
ntfs_debug("Entering for inode 0x%lx, attribute type 0x%x, start page "
"index 0x%lx, nr_pages 0x%x, pos 0x%llx, bytes 0x%zx.",
vi->i_ino, ni->type, page->index, nr_pages,
(long long)pos, bytes);
if (NInoNonResident(ni))
return ntfs_commit_pages_after_non_resident_write(pages,
nr_pages, pos, bytes);
BUG_ON(nr_pages > 1);
/*
* Attribute is resident, implying it is not compressed, encrypted, or
* sparse.
*/
if (!NInoAttr(ni))
base_ni = ni;
else
base_ni = ni->ext.base_ntfs_ino;
BUG_ON(NInoNonResident(ni));
/* Map, pin, and lock the mft record. */
m = map_mft_record(base_ni);
if (IS_ERR(m)) {
err = PTR_ERR(m);
m = NULL;
ctx = NULL;
goto err_out;
}
ctx = ntfs_attr_get_search_ctx(base_ni, m);
if (unlikely(!ctx)) {
err = -ENOMEM;
goto err_out;
}
err = ntfs_attr_lookup(ni->type, ni->name, ni->name_len,
CASE_SENSITIVE, 0, NULL, 0, ctx);
if (unlikely(err)) {
if (err == -ENOENT)
err = -EIO;
goto err_out;
}
a = ctx->attr;
BUG_ON(a->non_resident);
/* The total length of the attribute value. */
attr_len = le32_to_cpu(a->data.resident.value_length);
i_size = i_size_read(vi);
BUG_ON(attr_len != i_size);
BUG_ON(pos > attr_len);
end = pos + bytes;
BUG_ON(end > le32_to_cpu(a->length) -
le16_to_cpu(a->data.resident.value_offset));
kattr = (u8*)a + le16_to_cpu(a->data.resident.value_offset);
kaddr = kmap_atomic(page);
/* Copy the received data from the page to the mft record. */
memcpy(kattr + pos, kaddr + pos, bytes);
/* Update the attribute length if necessary. */
if (end > attr_len) {
attr_len = end;
a->data.resident.value_length = cpu_to_le32(attr_len);
}
/*
* If the page is not uptodate, bring the out of bounds area(s)
* uptodate by copying data from the mft record to the page.
*/
if (!PageUptodate(page)) {
if (pos > 0)
memcpy(kaddr, kattr, pos);
if (end < attr_len)
memcpy(kaddr + end, kattr + end, attr_len - end);
/* Zero the region outside the end of the attribute value. */
memset(kaddr + attr_len, 0, PAGE_SIZE - attr_len);
flush_dcache_page(page);
SetPageUptodate(page);
}
kunmap_atomic(kaddr);
/* Update initialized_size/i_size if necessary. */
read_lock_irqsave(&ni->size_lock, flags);
initialized_size = ni->initialized_size;
BUG_ON(end > ni->allocated_size);
read_unlock_irqrestore(&ni->size_lock, flags);
BUG_ON(initialized_size != i_size);
if (end > initialized_size) {
write_lock_irqsave(&ni->size_lock, flags);
ni->initialized_size = end;
i_size_write(vi, end);
write_unlock_irqrestore(&ni->size_lock, flags);
}
/* Mark the mft record dirty, so it gets written back. */
flush_dcache_mft_record_page(ctx->ntfs_ino);
mark_mft_record_dirty(ctx->ntfs_ino);
ntfs_attr_put_search_ctx(ctx);
unmap_mft_record(base_ni);
ntfs_debug("Done.");
return 0;
err_out:
if (err == -ENOMEM) {
ntfs_warning(vi->i_sb, "Error allocating memory required to "
"commit the write.");
if (PageUptodate(page)) {
ntfs_warning(vi->i_sb, "Page is uptodate, setting "
"dirty so the write will be retried "
"later on by the VM.");
/*
* Put the page on mapping->dirty_pages, but leave its
* buffers' dirty state as-is.
*/
__set_page_dirty_nobuffers(page);
err = 0;
} else
ntfs_error(vi->i_sb, "Page is not uptodate. Written "
"data has been lost.");
} else {
ntfs_error(vi->i_sb, "Resident attribute commit write failed "
"with error %i.", err);
NVolSetErrors(ni->vol);
}
if (ctx)
ntfs_attr_put_search_ctx(ctx);
if (m)
unmap_mft_record(base_ni);
return err;
}
/*
* Copy as much as we can into the pages and return the number of bytes which
* were successfully copied. If a fault is encountered then clear the pages
* out to (ofs + bytes) and return the number of bytes which were copied.
*/
static size_t ntfs_copy_from_user_iter(struct page **pages, unsigned nr_pages,
unsigned ofs, struct iov_iter *i, size_t bytes)
{
struct page **last_page = pages + nr_pages;
size_t total = 0;
struct iov_iter data = *i;
unsigned len, copied;
do {
len = PAGE_SIZE - ofs;
if (len > bytes)
len = bytes;
copied = iov_iter_copy_from_user_atomic(*pages, &data, ofs,
len);
total += copied;
bytes -= copied;
if (!bytes)
break;
iov_iter_advance(&data, copied);
if (copied < len)
goto err;
ofs = 0;
} while (++pages < last_page);
out:
return total;
err:
/* Zero the rest of the target like __copy_from_user(). */
len = PAGE_SIZE - copied;
do {
if (len > bytes)
len = bytes;
zero_user(*pages, copied, len);
bytes -= len;
copied = 0;
len = PAGE_SIZE;
} while (++pages < last_page);
goto out;
}
/**
* ntfs_perform_write - perform buffered write to a file
* @file: file to write to
* @i: iov_iter with data to write
* @pos: byte offset in file at which to begin writing to
*/
static ssize_t ntfs_perform_write(struct file *file, struct iov_iter *i,
loff_t pos)
{
struct address_space *mapping = file->f_mapping;
struct inode *vi = mapping->host;
ntfs_inode *ni = NTFS_I(vi);
ntfs_volume *vol = ni->vol;
struct page *pages[NTFS_MAX_PAGES_PER_CLUSTER];
struct page *cached_page = NULL;
VCN last_vcn;
LCN lcn;
size_t bytes;
ssize_t status, written = 0;
unsigned nr_pages;
ntfs_debug("Entering for i_ino 0x%lx, attribute type 0x%x, pos "
"0x%llx, count 0x%lx.", vi->i_ino,
(unsigned)le32_to_cpu(ni->type),
(unsigned long long)pos,
(unsigned long)iov_iter_count(i));
/*
* If a previous ntfs_truncate() failed, repeat it and abort if it
* fails again.
*/
if (unlikely(NInoTruncateFailed(ni))) {
int err;
inode_dio_wait(vi);
err = ntfs_truncate(vi);
if (err || NInoTruncateFailed(ni)) {
if (!err)
err = -EIO;
ntfs_error(vol->sb, "Cannot perform write to inode "
"0x%lx, attribute type 0x%x, because "
"ntfs_truncate() failed (error code "
"%i).", vi->i_ino,
(unsigned)le32_to_cpu(ni->type), err);
return err;
}
}
/*
* Determine the number of pages per cluster for non-resident
* attributes.
*/
nr_pages = 1;
if (vol->cluster_size > PAGE_SIZE && NInoNonResident(ni))
nr_pages = vol->cluster_size >> PAGE_SHIFT;
last_vcn = -1;
do {
VCN vcn;
pgoff_t idx, start_idx;
unsigned ofs, do_pages, u;
size_t copied;
start_idx = idx = pos >> PAGE_SHIFT;
ofs = pos & ~PAGE_MASK;
bytes = PAGE_SIZE - ofs;
do_pages = 1;
if (nr_pages > 1) {
vcn = pos >> vol->cluster_size_bits;
if (vcn != last_vcn) {
last_vcn = vcn;
/*
* Get the lcn of the vcn the write is in. If
* it is a hole, need to lock down all pages in
* the cluster.
*/
down_read(&ni->runlist.lock);
lcn = ntfs_attr_vcn_to_lcn_nolock(ni, pos >>
vol->cluster_size_bits, false);
up_read(&ni->runlist.lock);
if (unlikely(lcn < LCN_HOLE)) {
if (lcn == LCN_ENOMEM)
status = -ENOMEM;
else {
status = -EIO;
ntfs_error(vol->sb, "Cannot "
"perform write to "
"inode 0x%lx, "
"attribute type 0x%x, "
"because the attribute "
"is corrupt.",
vi->i_ino, (unsigned)
le32_to_cpu(ni->type));
}
break;
}
if (lcn == LCN_HOLE) {
start_idx = (pos & ~(s64)
vol->cluster_size_mask)
>> PAGE_SHIFT;
bytes = vol->cluster_size - (pos &
vol->cluster_size_mask);
do_pages = nr_pages;
}
}
}
if (bytes > iov_iter_count(i))
bytes = iov_iter_count(i);
again:
/*
* Bring in the user page(s) that we will copy from _first_.
* Otherwise there is a nasty deadlock on copying from the same
* page(s) as we are writing to, without it/them being marked
* up-to-date. Note, at present there is nothing to stop the
* pages being swapped out between us bringing them into memory
* and doing the actual copying.
*/
if (unlikely(iov_iter_fault_in_readable(i, bytes))) {
status = -EFAULT;
break;
}
/* Get and lock @do_pages starting at index @start_idx. */
status = __ntfs_grab_cache_pages(mapping, start_idx, do_pages,
pages, &cached_page);
if (unlikely(status))
break;
/*
* For non-resident attributes, we need to fill any holes with
* actual clusters and ensure all bufferes are mapped. We also
* need to bring uptodate any buffers that are only partially
* being written to.
*/
if (NInoNonResident(ni)) {
status = ntfs_prepare_pages_for_non_resident_write(
pages, do_pages, pos, bytes);
if (unlikely(status)) {
do {
unlock_page(pages[--do_pages]);
put_page(pages[do_pages]);
} while (do_pages);
break;
}
}
u = (pos >> PAGE_SHIFT) - pages[0]->index;
copied = ntfs_copy_from_user_iter(pages + u, do_pages - u, ofs,
i, bytes);
ntfs_flush_dcache_pages(pages + u, do_pages - u);
status = 0;
if (likely(copied == bytes)) {
status = ntfs_commit_pages_after_write(pages, do_pages,
pos, bytes);
if (!status)
status = bytes;
}
do {
unlock_page(pages[--do_pages]);
put_page(pages[do_pages]);
} while (do_pages);
if (unlikely(status < 0))
break;
copied = status;
cond_resched();
if (unlikely(!copied)) {
size_t sc;
/*
* We failed to copy anything. Fall back to single
* segment length write.
*
* This is needed to avoid possible livelock in the
* case that all segments in the iov cannot be copied
* at once without a pagefault.
*/
sc = iov_iter_single_seg_count(i);
if (bytes > sc)
bytes = sc;
goto again;
}
iov_iter_advance(i, copied);
pos += copied;
written += copied;
balance_dirty_pages_ratelimited(mapping);
if (fatal_signal_pending(current)) {
status = -EINTR;
break;
}
} while (iov_iter_count(i));
if (cached_page)
put_page(cached_page);
ntfs_debug("Done. Returning %s (written 0x%lx, status %li).",
written ? "written" : "status", (unsigned long)written,
(long)status);
return written ? written : status;
}
/**
* ntfs_file_write_iter - simple wrapper for ntfs_file_write_iter_nolock()
* @iocb: IO state structure
* @from: iov_iter with data to write
*
* Basically the same as generic_file_write_iter() except that it ends up
* up calling ntfs_perform_write() instead of generic_perform_write() and that
* O_DIRECT is not implemented.
*/
static ssize_t ntfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
{
struct file *file = iocb->ki_filp;
struct inode *vi = file_inode(file);
ssize_t written = 0;
ssize_t err;
inode_lock(vi);
/* We can write back this queue in page reclaim. */
current->backing_dev_info = inode_to_bdi(vi);
err = ntfs_prepare_file_for_write(iocb, from);
if (iov_iter_count(from) && !err)
written = ntfs_perform_write(file, from, iocb->ki_pos);
current->backing_dev_info = NULL;
inode_unlock(vi);
iocb->ki_pos += written;
if (likely(written > 0))
written = generic_write_sync(iocb, written);
return written ? written : err;
}
/**
* ntfs_file_fsync - sync a file to disk
* @filp: file to be synced
* @datasync: if non-zero only flush user data and not metadata
*
* Data integrity sync of a file to disk. Used for fsync, fdatasync, and msync
* system calls. This function is inspired by fs/buffer.c::file_fsync().
*
* If @datasync is false, write the mft record and all associated extent mft
* records as well as the $DATA attribute and then sync the block device.
*
* If @datasync is true and the attribute is non-resident, we skip the writing
* of the mft record and all associated extent mft records (this might still
* happen due to the write_inode_now() call).
*
* Also, if @datasync is true, we do not wait on the inode to be written out
* but we always wait on the page cache pages to be written out.
*
* Locking: Caller must hold i_mutex on the inode.
*
* TODO: We should probably also write all attribute/index inodes associated
* with this inode but since we have no simple way of getting to them we ignore
* this problem for now.
*/
static int ntfs_file_fsync(struct file *filp, loff_t start, loff_t end,
int datasync)
{
struct inode *vi = filp->f_mapping->host;
int err, ret = 0;
ntfs_debug("Entering for inode 0x%lx.", vi->i_ino);
err = filemap_write_and_wait_range(vi->i_mapping, start, end);
if (err)
return err;
inode_lock(vi);
BUG_ON(S_ISDIR(vi->i_mode));
if (!datasync || !NInoNonResident(NTFS_I(vi)))
ret = __ntfs_write_inode(vi, 1);
write_inode_now(vi, !datasync);
/*
* NOTE: If we were to use mapping->private_list (see ext2 and
* fs/buffer.c) for dirty blocks then we could optimize the below to be
* sync_mapping_buffers(vi->i_mapping).
*/
err = sync_blockdev(vi->i_sb->s_bdev);
if (unlikely(err && !ret))
ret = err;
if (likely(!ret))
ntfs_debug("Done.");
else
ntfs_warning(vi->i_sb, "Failed to f%ssync inode 0x%lx. Error "
"%u.", datasync ? "data" : "", vi->i_ino, -ret);
inode_unlock(vi);
return ret;
}
#endif /* NTFS_RW */
const struct file_operations ntfs_file_ops = {
.llseek = generic_file_llseek,
.read_iter = generic_file_read_iter,
#ifdef NTFS_RW
.write_iter = ntfs_file_write_iter,
.fsync = ntfs_file_fsync,
#endif /* NTFS_RW */
.mmap = generic_file_mmap,
.open = ntfs_file_open,
.splice_read = generic_file_splice_read,
};
const struct inode_operations ntfs_file_inode_ops = {
#ifdef NTFS_RW
.setattr = ntfs_setattr,
#endif /* NTFS_RW */
};
const struct file_operations ntfs_empty_file_ops = {};
const struct inode_operations ntfs_empty_inode_ops = {};
| null | null | null | null | 77,311 |
20,388 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 20,388 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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 CONTENT_PUBLIC_BROWSER_BACKGROUND_TRACING_CONFIG_H_
#define CONTENT_PUBLIC_BROWSER_BACKGROUND_TRACING_CONFIG_H_
#include <memory>
#include "base/trace_event/trace_event_impl.h"
#include "content/common/content_export.h"
namespace base {
class DictionaryValue;
}
namespace content {
// BackgroundTracingConfig is passed to the BackgroundTracingManager to
// setup the trigger rules used to enable/disable background tracing.
class CONTENT_EXPORT BackgroundTracingConfig {
public:
virtual ~BackgroundTracingConfig();
enum TracingMode {
PREEMPTIVE,
REACTIVE,
};
TracingMode tracing_mode() const { return tracing_mode_; }
static std::unique_ptr<BackgroundTracingConfig> FromDict(
const base::DictionaryValue* dict);
virtual void IntoDict(base::DictionaryValue* dict) const = 0;
private:
friend class BackgroundTracingConfigImpl;
explicit BackgroundTracingConfig(TracingMode tracing_mode);
const TracingMode tracing_mode_;
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_BACKGROUND_TRACING_CONFIG_H_
| null | null | null | null | 17,251 |
18,043 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 18,043 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 "components/policy/core/common/policy_scheduler.h"
#include <memory>
#include "base/bind.h"
#include "base/run_loop.h"
#include "base/test/scoped_task_environment.h"
#include "base/threading/thread_task_runner_handle.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace policy {
class PolicySchedulerTest : public testing::Test {
public:
void DoTask(PolicyScheduler::TaskCallback callback) {
do_counter_++;
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback), true));
}
void OnTaskDone(bool success) {
done_counter_++;
// Terminate PolicyScheduler after 5 iterations.
if (done_counter_ >= 5) {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(&PolicySchedulerTest::Terminate,
base::Unretained(this)));
}
}
// To simulate a slow task the callback is captured instead of running it.
void CaptureCallbackForSlowTask(PolicyScheduler::TaskCallback callback) {
do_counter_++;
slow_callback_ = std::move(callback);
}
// Runs the captured callback to simulate the end of the slow task.
void PostSlowTaskCallback() {
base::ThreadTaskRunnerHandle::Get()->PostTask(
FROM_HERE, base::BindOnce(std::move(slow_callback_), true));
}
void Terminate() { scheduler_.reset(); }
protected:
int do_counter_ = 0;
int done_counter_ = 0;
std::unique_ptr<PolicyScheduler> scheduler_;
PolicyScheduler::TaskCallback slow_callback_;
base::test::ScopedTaskEnvironment scoped_task_environment_;
};
TEST_F(PolicySchedulerTest, Run) {
scheduler_ = std::make_unique<PolicyScheduler>(
base::BindRepeating(&PolicySchedulerTest::DoTask, base::Unretained(this)),
base::BindRepeating(&PolicySchedulerTest::OnTaskDone,
base::Unretained(this)),
base::TimeDelta::Max());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, done_counter_);
}
TEST_F(PolicySchedulerTest, Loop) {
scheduler_ = std::make_unique<PolicyScheduler>(
base::BindRepeating(&PolicySchedulerTest::DoTask, base::Unretained(this)),
base::BindRepeating(&PolicySchedulerTest::OnTaskDone,
base::Unretained(this)),
base::TimeDelta());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(5, done_counter_);
}
TEST_F(PolicySchedulerTest, Reschedule) {
scheduler_ = std::make_unique<PolicyScheduler>(
base::BindRepeating(&PolicySchedulerTest::DoTask, base::Unretained(this)),
base::BindRepeating(&PolicySchedulerTest::OnTaskDone,
base::Unretained(this)),
base::TimeDelta::Max());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, done_counter_);
// Delayed action is not run.
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, done_counter_);
// Rescheduling with 0 delay causes it to run.
scheduler_->ScheduleTaskNow();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, done_counter_);
}
TEST_F(PolicySchedulerTest, OverlappingTasks) {
scheduler_ = std::make_unique<PolicyScheduler>(
base::BindRepeating(&PolicySchedulerTest::CaptureCallbackForSlowTask,
base::Unretained(this)),
base::BindRepeating(&PolicySchedulerTest::OnTaskDone,
base::Unretained(this)),
base::TimeDelta::Max());
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, do_counter_);
EXPECT_EQ(0, done_counter_);
// Second action doesn't start while first is still pending.
scheduler_->ScheduleTaskNow();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1, do_counter_);
EXPECT_EQ(0, done_counter_);
// After first action has finished, the second is started.
PostSlowTaskCallback();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, do_counter_);
EXPECT_EQ(1, done_counter_);
// Let the second action finish.
PostSlowTaskCallback();
base::RunLoop().RunUntilIdle();
EXPECT_EQ(2, do_counter_);
EXPECT_EQ(2, done_counter_);
}
} // namespace policy
| null | null | null | null | 14,906 |
19,525 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 184,520 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Copyright (C) 2008-2010
*
* - Kurt Van Dijck, EIA Electronics
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the version 2 of the GNU General Public License
* as published by the Free Software Foundation
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <linux/module.h>
#include <linux/interrupt.h>
#include <asm/io.h>
#include "softing.h"
#define TX_ECHO_SKB_MAX (((TXMAX+1)/2)-1)
/*
* test is a specific CAN netdev
* is online (ie. up 'n running, not sleeping, not busoff
*/
static inline int canif_is_active(struct net_device *netdev)
{
struct can_priv *can = netdev_priv(netdev);
if (!netif_running(netdev))
return 0;
return (can->state <= CAN_STATE_ERROR_PASSIVE);
}
/* reset DPRAM */
static inline void softing_set_reset_dpram(struct softing *card)
{
if (card->pdat->generation >= 2) {
spin_lock_bh(&card->spin);
iowrite8(ioread8(&card->dpram[DPRAM_V2_RESET]) & ~1,
&card->dpram[DPRAM_V2_RESET]);
spin_unlock_bh(&card->spin);
}
}
static inline void softing_clr_reset_dpram(struct softing *card)
{
if (card->pdat->generation >= 2) {
spin_lock_bh(&card->spin);
iowrite8(ioread8(&card->dpram[DPRAM_V2_RESET]) | 1,
&card->dpram[DPRAM_V2_RESET]);
spin_unlock_bh(&card->spin);
}
}
/* trigger the tx queue-ing */
static netdev_tx_t softing_netdev_start_xmit(struct sk_buff *skb,
struct net_device *dev)
{
struct softing_priv *priv = netdev_priv(dev);
struct softing *card = priv->card;
int ret;
uint8_t *ptr;
uint8_t fifo_wr, fifo_rd;
struct can_frame *cf = (struct can_frame *)skb->data;
uint8_t buf[DPRAM_TX_SIZE];
if (can_dropped_invalid_skb(dev, skb))
return NETDEV_TX_OK;
spin_lock(&card->spin);
ret = NETDEV_TX_BUSY;
if (!card->fw.up ||
(card->tx.pending >= TXMAX) ||
(priv->tx.pending >= TX_ECHO_SKB_MAX))
goto xmit_done;
fifo_wr = ioread8(&card->dpram[DPRAM_TX_WR]);
fifo_rd = ioread8(&card->dpram[DPRAM_TX_RD]);
if (fifo_wr == fifo_rd)
/* fifo full */
goto xmit_done;
memset(buf, 0, sizeof(buf));
ptr = buf;
*ptr = CMD_TX;
if (cf->can_id & CAN_RTR_FLAG)
*ptr |= CMD_RTR;
if (cf->can_id & CAN_EFF_FLAG)
*ptr |= CMD_XTD;
if (priv->index)
*ptr |= CMD_BUS2;
++ptr;
*ptr++ = cf->can_dlc;
*ptr++ = (cf->can_id >> 0);
*ptr++ = (cf->can_id >> 8);
if (cf->can_id & CAN_EFF_FLAG) {
*ptr++ = (cf->can_id >> 16);
*ptr++ = (cf->can_id >> 24);
} else {
/* increment 1, not 2 as you might think */
ptr += 1;
}
if (!(cf->can_id & CAN_RTR_FLAG))
memcpy(ptr, &cf->data[0], cf->can_dlc);
memcpy_toio(&card->dpram[DPRAM_TX + DPRAM_TX_SIZE * fifo_wr],
buf, DPRAM_TX_SIZE);
if (++fifo_wr >= DPRAM_TX_CNT)
fifo_wr = 0;
iowrite8(fifo_wr, &card->dpram[DPRAM_TX_WR]);
card->tx.last_bus = priv->index;
++card->tx.pending;
++priv->tx.pending;
can_put_echo_skb(skb, dev, priv->tx.echo_put);
++priv->tx.echo_put;
if (priv->tx.echo_put >= TX_ECHO_SKB_MAX)
priv->tx.echo_put = 0;
/* can_put_echo_skb() saves the skb, safe to return TX_OK */
ret = NETDEV_TX_OK;
xmit_done:
spin_unlock(&card->spin);
if (card->tx.pending >= TXMAX) {
int j;
for (j = 0; j < ARRAY_SIZE(card->net); ++j) {
if (card->net[j])
netif_stop_queue(card->net[j]);
}
}
if (ret != NETDEV_TX_OK)
netif_stop_queue(dev);
return ret;
}
/*
* shortcut for skb delivery
*/
int softing_netdev_rx(struct net_device *netdev, const struct can_frame *msg,
ktime_t ktime)
{
struct sk_buff *skb;
struct can_frame *cf;
skb = alloc_can_skb(netdev, &cf);
if (!skb)
return -ENOMEM;
memcpy(cf, msg, sizeof(*msg));
skb->tstamp = ktime;
return netif_rx(skb);
}
/*
* softing_handle_1
* pop 1 entry from the DPRAM queue, and process
*/
static int softing_handle_1(struct softing *card)
{
struct net_device *netdev;
struct softing_priv *priv;
ktime_t ktime;
struct can_frame msg;
int cnt = 0, lost_msg;
uint8_t fifo_rd, fifo_wr, cmd;
uint8_t *ptr;
uint32_t tmp_u32;
uint8_t buf[DPRAM_RX_SIZE];
memset(&msg, 0, sizeof(msg));
/* test for lost msgs */
lost_msg = ioread8(&card->dpram[DPRAM_RX_LOST]);
if (lost_msg) {
int j;
/* reset condition */
iowrite8(0, &card->dpram[DPRAM_RX_LOST]);
/* prepare msg */
msg.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
msg.can_dlc = CAN_ERR_DLC;
msg.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
/*
* service to all busses, we don't know which it was applicable
* but only service busses that are online
*/
for (j = 0; j < ARRAY_SIZE(card->net); ++j) {
netdev = card->net[j];
if (!netdev)
continue;
if (!canif_is_active(netdev))
/* a dead bus has no overflows */
continue;
++netdev->stats.rx_over_errors;
softing_netdev_rx(netdev, &msg, 0);
}
/* prepare for other use */
memset(&msg, 0, sizeof(msg));
++cnt;
}
fifo_rd = ioread8(&card->dpram[DPRAM_RX_RD]);
fifo_wr = ioread8(&card->dpram[DPRAM_RX_WR]);
if (++fifo_rd >= DPRAM_RX_CNT)
fifo_rd = 0;
if (fifo_wr == fifo_rd)
return cnt;
memcpy_fromio(buf, &card->dpram[DPRAM_RX + DPRAM_RX_SIZE*fifo_rd],
DPRAM_RX_SIZE);
mb();
/* trigger dual port RAM */
iowrite8(fifo_rd, &card->dpram[DPRAM_RX_RD]);
ptr = buf;
cmd = *ptr++;
if (cmd == 0xff)
/* not quite useful, probably the card has got out */
return 0;
netdev = card->net[0];
if (cmd & CMD_BUS2)
netdev = card->net[1];
priv = netdev_priv(netdev);
if (cmd & CMD_ERR) {
uint8_t can_state, state;
state = *ptr++;
msg.can_id = CAN_ERR_FLAG;
msg.can_dlc = CAN_ERR_DLC;
if (state & SF_MASK_BUSOFF) {
can_state = CAN_STATE_BUS_OFF;
msg.can_id |= CAN_ERR_BUSOFF;
state = STATE_BUSOFF;
} else if (state & SF_MASK_EPASSIVE) {
can_state = CAN_STATE_ERROR_PASSIVE;
msg.can_id |= CAN_ERR_CRTL;
msg.data[1] = CAN_ERR_CRTL_TX_PASSIVE;
state = STATE_EPASSIVE;
} else {
can_state = CAN_STATE_ERROR_ACTIVE;
msg.can_id |= CAN_ERR_CRTL;
state = STATE_EACTIVE;
}
/* update DPRAM */
iowrite8(state, &card->dpram[priv->index ?
DPRAM_INFO_BUSSTATE2 : DPRAM_INFO_BUSSTATE]);
/* timestamp */
tmp_u32 = le32_to_cpup((void *)ptr);
ptr += 4;
ktime = softing_raw2ktime(card, tmp_u32);
++netdev->stats.rx_errors;
/* update internal status */
if (can_state != priv->can.state) {
priv->can.state = can_state;
if (can_state == CAN_STATE_ERROR_PASSIVE)
++priv->can.can_stats.error_passive;
else if (can_state == CAN_STATE_BUS_OFF) {
/* this calls can_close_cleanup() */
++priv->can.can_stats.bus_off;
can_bus_off(netdev);
netif_stop_queue(netdev);
}
/* trigger socketcan */
softing_netdev_rx(netdev, &msg, ktime);
}
} else {
if (cmd & CMD_RTR)
msg.can_id |= CAN_RTR_FLAG;
msg.can_dlc = get_can_dlc(*ptr++);
if (cmd & CMD_XTD) {
msg.can_id |= CAN_EFF_FLAG;
msg.can_id |= le32_to_cpup((void *)ptr);
ptr += 4;
} else {
msg.can_id |= le16_to_cpup((void *)ptr);
ptr += 2;
}
/* timestamp */
tmp_u32 = le32_to_cpup((void *)ptr);
ptr += 4;
ktime = softing_raw2ktime(card, tmp_u32);
if (!(msg.can_id & CAN_RTR_FLAG))
memcpy(&msg.data[0], ptr, 8);
ptr += 8;
/* update socket */
if (cmd & CMD_ACK) {
/* acknowledge, was tx msg */
struct sk_buff *skb;
skb = priv->can.echo_skb[priv->tx.echo_get];
if (skb)
skb->tstamp = ktime;
can_get_echo_skb(netdev, priv->tx.echo_get);
++priv->tx.echo_get;
if (priv->tx.echo_get >= TX_ECHO_SKB_MAX)
priv->tx.echo_get = 0;
if (priv->tx.pending)
--priv->tx.pending;
if (card->tx.pending)
--card->tx.pending;
++netdev->stats.tx_packets;
if (!(msg.can_id & CAN_RTR_FLAG))
netdev->stats.tx_bytes += msg.can_dlc;
} else {
int ret;
ret = softing_netdev_rx(netdev, &msg, ktime);
if (ret == NET_RX_SUCCESS) {
++netdev->stats.rx_packets;
if (!(msg.can_id & CAN_RTR_FLAG))
netdev->stats.rx_bytes += msg.can_dlc;
} else {
++netdev->stats.rx_dropped;
}
}
}
++cnt;
return cnt;
}
/*
* real interrupt handler
*/
static irqreturn_t softing_irq_thread(int irq, void *dev_id)
{
struct softing *card = (struct softing *)dev_id;
struct net_device *netdev;
struct softing_priv *priv;
int j, offset, work_done;
work_done = 0;
spin_lock_bh(&card->spin);
while (softing_handle_1(card) > 0) {
++card->irq.svc_count;
++work_done;
}
spin_unlock_bh(&card->spin);
/* resume tx queue's */
offset = card->tx.last_bus;
for (j = 0; j < ARRAY_SIZE(card->net); ++j) {
if (card->tx.pending >= TXMAX)
break;
netdev = card->net[(j + offset + 1) % card->pdat->nbus];
if (!netdev)
continue;
priv = netdev_priv(netdev);
if (!canif_is_active(netdev))
/* it makes no sense to wake dead busses */
continue;
if (priv->tx.pending >= TX_ECHO_SKB_MAX)
continue;
++work_done;
netif_wake_queue(netdev);
}
return work_done ? IRQ_HANDLED : IRQ_NONE;
}
/*
* interrupt routines:
* schedule the 'real interrupt handler'
*/
static irqreturn_t softing_irq_v2(int irq, void *dev_id)
{
struct softing *card = (struct softing *)dev_id;
uint8_t ir;
ir = ioread8(&card->dpram[DPRAM_V2_IRQ_TOHOST]);
iowrite8(0, &card->dpram[DPRAM_V2_IRQ_TOHOST]);
return (1 == ir) ? IRQ_WAKE_THREAD : IRQ_NONE;
}
static irqreturn_t softing_irq_v1(int irq, void *dev_id)
{
struct softing *card = (struct softing *)dev_id;
uint8_t ir;
ir = ioread8(&card->dpram[DPRAM_IRQ_TOHOST]);
iowrite8(0, &card->dpram[DPRAM_IRQ_TOHOST]);
return ir ? IRQ_WAKE_THREAD : IRQ_NONE;
}
/*
* netdev/candev inter-operability
*/
static int softing_netdev_open(struct net_device *ndev)
{
int ret;
/* check or determine and set bittime */
ret = open_candev(ndev);
if (!ret)
ret = softing_startstop(ndev, 1);
return ret;
}
static int softing_netdev_stop(struct net_device *ndev)
{
int ret;
netif_stop_queue(ndev);
/* softing cycle does close_candev() */
ret = softing_startstop(ndev, 0);
return ret;
}
static int softing_candev_set_mode(struct net_device *ndev, enum can_mode mode)
{
int ret;
switch (mode) {
case CAN_MODE_START:
/* softing_startstop does close_candev() */
ret = softing_startstop(ndev, 1);
return ret;
case CAN_MODE_STOP:
case CAN_MODE_SLEEP:
return -EOPNOTSUPP;
}
return 0;
}
/*
* Softing device management helpers
*/
int softing_enable_irq(struct softing *card, int enable)
{
int ret;
if (!card->irq.nr) {
return 0;
} else if (card->irq.requested && !enable) {
free_irq(card->irq.nr, card);
card->irq.requested = 0;
} else if (!card->irq.requested && enable) {
ret = request_threaded_irq(card->irq.nr,
(card->pdat->generation >= 2) ?
softing_irq_v2 : softing_irq_v1,
softing_irq_thread, IRQF_SHARED,
dev_name(&card->pdev->dev), card);
if (ret) {
dev_alert(&card->pdev->dev,
"request_threaded_irq(%u) failed\n",
card->irq.nr);
return ret;
}
card->irq.requested = 1;
}
return 0;
}
static void softing_card_shutdown(struct softing *card)
{
int fw_up = 0;
if (mutex_lock_interruptible(&card->fw.lock))
/* return -ERESTARTSYS */;
fw_up = card->fw.up;
card->fw.up = 0;
if (card->irq.requested && card->irq.nr) {
free_irq(card->irq.nr, card);
card->irq.requested = 0;
}
if (fw_up) {
if (card->pdat->enable_irq)
card->pdat->enable_irq(card->pdev, 0);
softing_set_reset_dpram(card);
if (card->pdat->reset)
card->pdat->reset(card->pdev, 1);
}
mutex_unlock(&card->fw.lock);
}
static int softing_card_boot(struct softing *card)
{
int ret, j;
static const uint8_t stream[] = {
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, };
unsigned char back[sizeof(stream)];
if (mutex_lock_interruptible(&card->fw.lock))
return -ERESTARTSYS;
if (card->fw.up) {
mutex_unlock(&card->fw.lock);
return 0;
}
/* reset board */
if (card->pdat->enable_irq)
card->pdat->enable_irq(card->pdev, 1);
/* boot card */
softing_set_reset_dpram(card);
if (card->pdat->reset)
card->pdat->reset(card->pdev, 1);
for (j = 0; (j + sizeof(stream)) < card->dpram_size;
j += sizeof(stream)) {
memcpy_toio(&card->dpram[j], stream, sizeof(stream));
/* flush IO cache */
mb();
memcpy_fromio(back, &card->dpram[j], sizeof(stream));
if (!memcmp(back, stream, sizeof(stream)))
continue;
/* memory is not equal */
dev_alert(&card->pdev->dev, "dpram failed at 0x%04x\n", j);
ret = -EIO;
goto failed;
}
wmb();
/* load boot firmware */
ret = softing_load_fw(card->pdat->boot.fw, card, card->dpram,
card->dpram_size,
card->pdat->boot.offs - card->pdat->boot.addr);
if (ret < 0)
goto failed;
/* load loader firmware */
ret = softing_load_fw(card->pdat->load.fw, card, card->dpram,
card->dpram_size,
card->pdat->load.offs - card->pdat->load.addr);
if (ret < 0)
goto failed;
if (card->pdat->reset)
card->pdat->reset(card->pdev, 0);
softing_clr_reset_dpram(card);
ret = softing_bootloader_command(card, 0, "card boot");
if (ret < 0)
goto failed;
ret = softing_load_app_fw(card->pdat->app.fw, card);
if (ret < 0)
goto failed;
ret = softing_chip_poweron(card);
if (ret < 0)
goto failed;
card->fw.up = 1;
mutex_unlock(&card->fw.lock);
return 0;
failed:
card->fw.up = 0;
if (card->pdat->enable_irq)
card->pdat->enable_irq(card->pdev, 0);
softing_set_reset_dpram(card);
if (card->pdat->reset)
card->pdat->reset(card->pdev, 1);
mutex_unlock(&card->fw.lock);
return ret;
}
/*
* netdev sysfs
*/
static ssize_t show_chip(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct net_device *ndev = to_net_dev(dev);
struct softing_priv *priv = netdev2softing(ndev);
return sprintf(buf, "%i\n", priv->chip);
}
static ssize_t show_output(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct net_device *ndev = to_net_dev(dev);
struct softing_priv *priv = netdev2softing(ndev);
return sprintf(buf, "0x%02x\n", priv->output);
}
static ssize_t store_output(struct device *dev, struct device_attribute *attr,
const char *buf, size_t count)
{
struct net_device *ndev = to_net_dev(dev);
struct softing_priv *priv = netdev2softing(ndev);
struct softing *card = priv->card;
unsigned long val;
int ret;
ret = kstrtoul(buf, 0, &val);
if (ret < 0)
return ret;
val &= 0xFF;
ret = mutex_lock_interruptible(&card->fw.lock);
if (ret)
return -ERESTARTSYS;
if (netif_running(ndev)) {
mutex_unlock(&card->fw.lock);
return -EBUSY;
}
priv->output = val;
mutex_unlock(&card->fw.lock);
return count;
}
static const DEVICE_ATTR(chip, S_IRUGO, show_chip, NULL);
static const DEVICE_ATTR(output, S_IRUGO | S_IWUSR, show_output, store_output);
static const struct attribute *const netdev_sysfs_attrs[] = {
&dev_attr_chip.attr,
&dev_attr_output.attr,
NULL,
};
static const struct attribute_group netdev_sysfs_group = {
.name = NULL,
.attrs = (struct attribute **)netdev_sysfs_attrs,
};
static const struct net_device_ops softing_netdev_ops = {
.ndo_open = softing_netdev_open,
.ndo_stop = softing_netdev_stop,
.ndo_start_xmit = softing_netdev_start_xmit,
.ndo_change_mtu = can_change_mtu,
};
static const struct can_bittiming_const softing_btr_const = {
.name = "softing",
.tseg1_min = 1,
.tseg1_max = 16,
.tseg2_min = 1,
.tseg2_max = 8,
.sjw_max = 4, /* overruled */
.brp_min = 1,
.brp_max = 32, /* overruled */
.brp_inc = 1,
};
static struct net_device *softing_netdev_create(struct softing *card,
uint16_t chip_id)
{
struct net_device *netdev;
struct softing_priv *priv;
netdev = alloc_candev(sizeof(*priv), TX_ECHO_SKB_MAX);
if (!netdev) {
dev_alert(&card->pdev->dev, "alloc_candev failed\n");
return NULL;
}
priv = netdev_priv(netdev);
priv->netdev = netdev;
priv->card = card;
memcpy(&priv->btr_const, &softing_btr_const, sizeof(priv->btr_const));
priv->btr_const.brp_max = card->pdat->max_brp;
priv->btr_const.sjw_max = card->pdat->max_sjw;
priv->can.bittiming_const = &priv->btr_const;
priv->can.clock.freq = 8000000;
priv->chip = chip_id;
priv->output = softing_default_output(netdev);
SET_NETDEV_DEV(netdev, &card->pdev->dev);
netdev->flags |= IFF_ECHO;
netdev->netdev_ops = &softing_netdev_ops;
priv->can.do_set_mode = softing_candev_set_mode;
priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES;
return netdev;
}
static int softing_netdev_register(struct net_device *netdev)
{
int ret;
ret = register_candev(netdev);
if (ret) {
dev_alert(&netdev->dev, "register failed\n");
return ret;
}
if (sysfs_create_group(&netdev->dev.kobj, &netdev_sysfs_group) < 0)
netdev_alert(netdev, "sysfs group failed\n");
return 0;
}
static void softing_netdev_cleanup(struct net_device *netdev)
{
sysfs_remove_group(&netdev->dev.kobj, &netdev_sysfs_group);
unregister_candev(netdev);
free_candev(netdev);
}
/*
* sysfs for Platform device
*/
#define DEV_ATTR_RO(name, member) \
static ssize_t show_##name(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct softing *card = platform_get_drvdata(to_platform_device(dev)); \
return sprintf(buf, "%u\n", card->member); \
} \
static DEVICE_ATTR(name, 0444, show_##name, NULL)
#define DEV_ATTR_RO_STR(name, member) \
static ssize_t show_##name(struct device *dev, \
struct device_attribute *attr, char *buf) \
{ \
struct softing *card = platform_get_drvdata(to_platform_device(dev)); \
return sprintf(buf, "%s\n", card->member); \
} \
static DEVICE_ATTR(name, 0444, show_##name, NULL)
DEV_ATTR_RO(serial, id.serial);
DEV_ATTR_RO_STR(firmware, pdat->app.fw);
DEV_ATTR_RO(firmware_version, id.fw_version);
DEV_ATTR_RO_STR(hardware, pdat->name);
DEV_ATTR_RO(hardware_version, id.hw_version);
DEV_ATTR_RO(license, id.license);
static struct attribute *softing_pdev_attrs[] = {
&dev_attr_serial.attr,
&dev_attr_firmware.attr,
&dev_attr_firmware_version.attr,
&dev_attr_hardware.attr,
&dev_attr_hardware_version.attr,
&dev_attr_license.attr,
NULL,
};
static const struct attribute_group softing_pdev_group = {
.name = NULL,
.attrs = softing_pdev_attrs,
};
/*
* platform driver
*/
static int softing_pdev_remove(struct platform_device *pdev)
{
struct softing *card = platform_get_drvdata(pdev);
int j;
/* first, disable card*/
softing_card_shutdown(card);
for (j = 0; j < ARRAY_SIZE(card->net); ++j) {
if (!card->net[j])
continue;
softing_netdev_cleanup(card->net[j]);
card->net[j] = NULL;
}
sysfs_remove_group(&pdev->dev.kobj, &softing_pdev_group);
iounmap(card->dpram);
kfree(card);
return 0;
}
static int softing_pdev_probe(struct platform_device *pdev)
{
const struct softing_platform_data *pdat = dev_get_platdata(&pdev->dev);
struct softing *card;
struct net_device *netdev;
struct softing_priv *priv;
struct resource *pres;
int ret;
int j;
if (!pdat) {
dev_warn(&pdev->dev, "no platform data\n");
return -EINVAL;
}
if (pdat->nbus > ARRAY_SIZE(card->net)) {
dev_warn(&pdev->dev, "%u nets??\n", pdat->nbus);
return -EINVAL;
}
card = kzalloc(sizeof(*card), GFP_KERNEL);
if (!card)
return -ENOMEM;
card->pdat = pdat;
card->pdev = pdev;
platform_set_drvdata(pdev, card);
mutex_init(&card->fw.lock);
spin_lock_init(&card->spin);
ret = -EINVAL;
pres = platform_get_resource(pdev, IORESOURCE_MEM, 0);
if (!pres)
goto platform_resource_failed;
card->dpram_phys = pres->start;
card->dpram_size = resource_size(pres);
card->dpram = ioremap_nocache(card->dpram_phys, card->dpram_size);
if (!card->dpram) {
dev_alert(&card->pdev->dev, "dpram ioremap failed\n");
goto ioremap_failed;
}
pres = platform_get_resource(pdev, IORESOURCE_IRQ, 0);
if (pres)
card->irq.nr = pres->start;
/* reset card */
ret = softing_card_boot(card);
if (ret < 0) {
dev_alert(&pdev->dev, "failed to boot\n");
goto boot_failed;
}
/* only now, the chip's are known */
card->id.freq = card->pdat->freq;
ret = sysfs_create_group(&pdev->dev.kobj, &softing_pdev_group);
if (ret < 0) {
dev_alert(&card->pdev->dev, "sysfs failed\n");
goto sysfs_failed;
}
for (j = 0; j < ARRAY_SIZE(card->net); ++j) {
card->net[j] = netdev =
softing_netdev_create(card, card->id.chip[j]);
if (!netdev) {
dev_alert(&pdev->dev, "failed to make can[%i]", j);
ret = -ENOMEM;
goto netdev_failed;
}
netdev->dev_id = j;
priv = netdev_priv(card->net[j]);
priv->index = j;
ret = softing_netdev_register(netdev);
if (ret) {
free_candev(netdev);
card->net[j] = NULL;
dev_alert(&card->pdev->dev,
"failed to register can[%i]\n", j);
goto netdev_failed;
}
}
dev_info(&card->pdev->dev, "%s ready.\n", card->pdat->name);
return 0;
netdev_failed:
for (j = 0; j < ARRAY_SIZE(card->net); ++j) {
if (!card->net[j])
continue;
softing_netdev_cleanup(card->net[j]);
}
sysfs_remove_group(&pdev->dev.kobj, &softing_pdev_group);
sysfs_failed:
softing_card_shutdown(card);
boot_failed:
iounmap(card->dpram);
ioremap_failed:
platform_resource_failed:
kfree(card);
return ret;
}
static struct platform_driver softing_driver = {
.driver = {
.name = "softing",
},
.probe = softing_pdev_probe,
.remove = softing_pdev_remove,
};
module_platform_driver(softing_driver);
MODULE_ALIAS("platform:softing");
MODULE_DESCRIPTION("Softing DPRAM CAN driver");
MODULE_AUTHOR("Kurt Van Dijck <[email protected]>");
MODULE_LICENSE("GPL v2");
| null | null | null | null | 92,867 |
33,779 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 33,779 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
/*
* Copyright (C) 2013 Adobe Systems Incorporated. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* 2. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "third_party/blink/renderer/core/layout/shapes/box_shape.h"
#include <memory>
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/renderer/platform/geometry/float_rounded_rect.h"
namespace blink {
class BoxShapeTest : public testing::Test {
protected:
BoxShapeTest() = default;
std::unique_ptr<Shape> CreateBoxShape(const FloatRoundedRect& bounds,
float shape_margin) {
return Shape::CreateLayoutBoxShape(bounds, WritingMode::kHorizontalTb,
shape_margin);
}
};
namespace {
#define TEST_EXCLUDED_INTERVAL(shapePtr, lineTop, lineHeight, expectedLeft, \
expectedRight) \
{ \
LineSegment segment = shapePtr->GetExcludedInterval(lineTop, lineHeight); \
EXPECT_TRUE(segment.is_valid); \
if (segment.is_valid) { \
EXPECT_FLOAT_EQ(expectedLeft, segment.logical_left); \
EXPECT_FLOAT_EQ(expectedRight, segment.logical_right); \
} \
}
#define TEST_NO_EXCLUDED_INTERVAL(shapePtr, lineTop, lineHeight) \
{ \
LineSegment segment = shapePtr->GetExcludedInterval(lineTop, lineHeight); \
EXPECT_FALSE(segment.is_valid); \
}
/* The BoxShape is based on a 100x50 rectangle at 0,0. The shape-margin value is
* 10, so the shapeMarginBoundingBox rectangle is 120x70 at -10,-10:
*
* -10,-10 110,-10
* +--------+
* | |
* +--------+
* -10,60 60,60
*/
TEST_F(BoxShapeTest, zeroRadii) {
std::unique_ptr<Shape> shape =
CreateBoxShape(FloatRoundedRect(0, 0, 100, 50), 10);
EXPECT_FALSE(shape->IsEmpty());
EXPECT_EQ(LayoutRect(-10, -10, 120, 70),
shape->ShapeMarginLogicalBoundingBox());
// A BoxShape's bounds include the top edge but not the bottom edge.
// Similarly a "line", specified as top,height to the overlap methods,
// is defined as top <= y < top + height.
EXPECT_TRUE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(-9), LayoutUnit(1)));
EXPECT_TRUE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(-10), LayoutUnit()));
EXPECT_TRUE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(-10), LayoutUnit(200)));
EXPECT_TRUE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(5), LayoutUnit(10)));
EXPECT_TRUE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(59), LayoutUnit(1)));
EXPECT_FALSE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(-12), LayoutUnit(2)));
EXPECT_FALSE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(60), LayoutUnit(1)));
EXPECT_FALSE(
shape->LineOverlapsShapeMarginBounds(LayoutUnit(100), LayoutUnit(200)));
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(-9), LayoutUnit(1), -10, 110);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(-10), LayoutUnit(), -10, 110);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(-10), LayoutUnit(200), -10, 110);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(5), LayoutUnit(10), -10, 110);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(59), LayoutUnit(1), -10, 110);
TEST_NO_EXCLUDED_INTERVAL(shape, LayoutUnit(-12), LayoutUnit(2));
TEST_NO_EXCLUDED_INTERVAL(shape, LayoutUnit(60), LayoutUnit(1));
TEST_NO_EXCLUDED_INTERVAL(shape, LayoutUnit(100), LayoutUnit(200));
}
/* BoxShape geometry for this test. Corner radii are in parens, x and y
* intercepts for the elliptical corners are noted. The rectangle itself is at
* 0,0 with width and height 100.
*
* (10, 15) x=10 x=90 (10, 20)
* (--+---------+--)
* y=15 +--| |-+ y=20
* | |
* | |
* y=85 + -| |- + y=70
* (--+---------+--)
* (25, 15) x=25 x=80 (20, 30)
*/
TEST_F(BoxShapeTest, getIntervals) {
const FloatRoundedRect::Radii corner_radii(
FloatSize(10, 15), FloatSize(10, 20), FloatSize(25, 15),
FloatSize(20, 30));
std::unique_ptr<Shape> shape = CreateBoxShape(
FloatRoundedRect(IntRect(0, 0, 100, 100), corner_radii), 0);
EXPECT_FALSE(shape->IsEmpty());
EXPECT_EQ(LayoutRect(0, 0, 100, 100), shape->ShapeMarginLogicalBoundingBox());
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(10), LayoutUnit(95), 0, 100);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(5), LayoutUnit(25), 0, 100);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(15), LayoutUnit(6), 0, 100);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(20), LayoutUnit(50), 0, 100);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(69), LayoutUnit(5), 0, 100);
TEST_EXCLUDED_INTERVAL(shape, LayoutUnit(85), LayoutUnit(10), 0, 97.320511f);
}
} // anonymous namespace
} // namespace blink
| null | null | null | null | 30,642 |
35,438 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 35,438 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2018 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 THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_TEXT_OFFSET_MAPPING_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_TEXT_OFFSET_MAPPING_H_
#include "base/macros.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/editing/ephemeral_range.h"
#include "third_party/blink/renderer/core/editing/forward.h"
#include "third_party/blink/renderer/core/editing/iterators/text_iterator_behavior.h"
#include "third_party/blink/renderer/platform/heap/member.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
namespace blink {
class LayoutBlock;
// Mapping between position and text offset in |LayoutBlock| == CSS Block
// with using characters from |TextIterator|.
//
// This class is similar to |NGOffsetMapping| which uses |text_offset_| in
// |NGInlineNodeData| except for
// - Treats characters with CSS property "-webkit-text-security" as "x"
// instead of a bullet (U+2022), which breaks words.
// - Contains characters in float and inline-blocks. |NGOffsetMapping| treats
// them as one object replacement character (U+FFFC). See |CollectInlines|
// in |NGInlineNode|.
class CORE_EXPORT TextOffsetMapping final {
STACK_ALLOCATED();
public:
// Constructor |TextOffsetMapping| for specified |LayoutBlock|.
explicit TextOffsetMapping(const LayoutBlock&);
~TextOffsetMapping() = default;
// Returns range of |LayoutBlock|.
const EphemeralRangeInFlatTree GetRange() const { return range_; }
// Returns characters in subtree of |LayoutBlock|, collapsed whitespaces
// are not included.
const String& GetText() const { return text16_; }
// Returns offset in |text16_| of specified position.
int ComputeTextOffset(const PositionInFlatTree&) const;
// Returns position before |offset| in |text16_|
PositionInFlatTree GetPositionBefore(unsigned offset) const;
// Returns position after |offset| in |text16_|
PositionInFlatTree GetPositionAfter(unsigned offset) const;
// Returns a range specified by |start| and |end| offset in |text16_|.
EphemeralRangeInFlatTree ComputeRange(unsigned start, unsigned end) const;
// Returns an offset in |text16_| before non-whitespace character from
// |offset|, inclusive, otherwise returns |text16_.length()|.
// This function is used for computing trailing whitespace after word.
unsigned FindNonWhitespaceCharacterFrom(unsigned offset) const;
// Helper functions to constructor |TextOffsetMapping|.
static const LayoutBlock& ComputeContainigBlock(const PositionInFlatTree&);
static LayoutBlock* NextBlockFor(const LayoutBlock&);
static LayoutBlock* PreviousBlockFor(const LayoutBlock&);
private:
TextOffsetMapping(const LayoutBlock&, const TextIteratorBehavior);
const TextIteratorBehavior behavior_;
const EphemeralRangeInFlatTree range_;
const String text16_;
DISALLOW_COPY_AND_ASSIGN(TextOffsetMapping);
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_EDITING_TEXT_OFFSET_MAPPING_H_
| null | null | null | null | 32,301 |
50,116 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 50,116 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 UI_BASE_COCOA_CONTROLS_IMAGEVIEW_UTILS_H_
#define UI_BASE_COCOA_CONTROLS_IMAGEVIEW_UTILS_H_
#include "ui/base/ui_base_export.h"
#include <Cocoa/Cocoa.h>
UI_BASE_EXPORT
@interface ImageViewUtils : NSObject
// These methods are a polyfill for convenience constructors that exist on
// NSImageView in macOS 10.12+.
// TODO(ellyjones): once we target only 10.12+, delete these and migrate
// callers over to NSImageView directly.
+ (NSImageView*)imageViewWithImage:(NSImage*)image;
@end
#endif // UI_BASE_COCOA_CONTROLS_IMAGEVIEW_UTILS_H_
| null | null | null | null | 46,979 |
30,722 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 30,722 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
// This file has been auto-generated from the Jinja2 template
// third_party/blink/renderer/bindings/templates/callback_function.cpp.tmpl
// by the script code_generator_v8.py.
// DO NOT MODIFY!
// clang-format off
#include "v8_void_callback_function_test_interface_sequence_arg.h"
#include "bindings/core/v8/exception_state.h"
#include "bindings/core/v8/generated_code_helper.h"
#include "bindings/core/v8/idl_types.h"
#include "bindings/core/v8/native_value_traits_impl.h"
#include "bindings/core/v8/to_v8_for_core.h"
#include "bindings/core/v8/v8_binding_for_core.h"
#include "bindings/core/v8/v8_test_interface.h"
#include "core/execution_context/execution_context.h"
namespace blink {
v8::Maybe<void> V8VoidCallbackFunctionTestInterfaceSequenceArg::Invoke(ScriptWrappable* callback_this_value, const HeapVector<Member<TestInterfaceImplementation>>& arg) {
// This function implements "invoke" steps in
// "3.10. Invoking callback functions".
// https://heycam.github.io/webidl/#es-invoking-callback-functions
if (!IsCallbackFunctionRunnable(CallbackRelevantScriptState())) {
// Wrapper-tracing for the callback function makes the function object and
// its creation context alive. Thus it's safe to use the creation context
// of the callback function here.
v8::HandleScope handle_scope(GetIsolate());
CHECK(!CallbackFunction().IsEmpty());
v8::Context::Scope context_scope(CallbackFunction()->CreationContext());
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"invoke",
"VoidCallbackFunctionTestInterfaceSequenceArg",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
// step 4. If ! IsCallable(F) is false:
//
// As Blink no longer supports [TreatNonObjectAsNull], there must be no such a
// case.
#if DCHECK_IS_ON()
{
v8::HandleScope handle_scope(GetIsolate());
DCHECK(CallbackFunction()->IsFunction());
}
#endif
// step 8. Prepare to run script with relevant settings.
ScriptState::Scope callback_relevant_context_scope(
CallbackRelevantScriptState());
// step 9. Prepare to run a callback with stored settings.
if (IncumbentScriptState()->GetContext().IsEmpty()) {
V8ThrowException::ThrowError(
GetIsolate(),
ExceptionMessages::FailedToExecute(
"invoke",
"VoidCallbackFunctionTestInterfaceSequenceArg",
"The provided callback is no longer runnable."));
return v8::Nothing<void>();
}
v8::Context::BackupIncumbentScope backup_incumbent_scope(
IncumbentScriptState()->GetContext());
v8::Local<v8::Value> this_arg = ToV8(callback_this_value,
CallbackRelevantScriptState());
// step 10. Let esArgs be the result of converting args to an ECMAScript
// arguments list. If this throws an exception, set completion to the
// completion value representing the thrown exception and jump to the step
// labeled return.
v8::Local<v8::Object> argument_creation_context =
CallbackRelevantScriptState()->GetContext()->Global();
ALLOW_UNUSED_LOCAL(argument_creation_context);
v8::Local<v8::Value> v8_arg = ToV8(arg, argument_creation_context, GetIsolate());
v8::Local<v8::Value> argv[] = { v8_arg };
// step 11. Let callResult be Call(X, thisArg, esArgs).
v8::Local<v8::Value> call_result;
if (!V8ScriptRunner::CallFunction(
CallbackFunction(),
ExecutionContext::From(CallbackRelevantScriptState()),
this_arg,
1,
argv,
GetIsolate()).ToLocal(&call_result)) {
// step 12. If callResult is an abrupt completion, set completion to
// callResult and jump to the step labeled return.
return v8::Nothing<void>();
}
// step 13. Set completion to the result of converting callResult.[[Value]] to
// an IDL value of the same type as the operation's return type.
return v8::JustVoid();
}
void V8VoidCallbackFunctionTestInterfaceSequenceArg::InvokeAndReportException(ScriptWrappable* callback_this_value, const HeapVector<Member<TestInterfaceImplementation>>& arg) {
v8::TryCatch try_catch(GetIsolate());
try_catch.SetVerbose(true);
v8::Maybe<void> maybe_result =
Invoke(callback_this_value, arg);
// An exception if any is killed with the v8::TryCatch above.
ALLOW_UNUSED_LOCAL(maybe_result);
}
CORE_TEMPLATE_EXPORT
v8::Maybe<void> V8PersistentCallbackFunction<V8VoidCallbackFunctionTestInterfaceSequenceArg>::Invoke(ScriptWrappable* callback_this_value, const HeapVector<Member<TestInterfaceImplementation>>& arg) {
return Proxy()->Invoke(
callback_this_value, arg);
}
CORE_TEMPLATE_EXPORT
void V8PersistentCallbackFunction<V8VoidCallbackFunctionTestInterfaceSequenceArg>::InvokeAndReportException(ScriptWrappable* callback_this_value, const HeapVector<Member<TestInterfaceImplementation>>& arg) {
Proxy()->InvokeAndReportException(
callback_this_value, arg);
}
} // namespace blink
| null | null | null | null | 27,585 |
32,610 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 197,605 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Common code to handle absent "placeholder" devices
* Copyright 2001 Resilience Corporation <[email protected]>
*
* This map driver is used to allocate "placeholder" MTD
* devices on systems that have socketed/removable media.
* Use of this driver as a fallback preserves the expected
* registration of MTD device nodes regardless of probe outcome.
* A usage example is as follows:
*
* my_dev[i] = do_map_probe("cfi", &my_map[i]);
* if(NULL == my_dev[i]) {
* my_dev[i] = do_map_probe("map_absent", &my_map[i]);
* }
*
* Any device 'probed' with this driver will return -ENODEV
* upon open.
*/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/errno.h>
#include <linux/slab.h>
#include <linux/init.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/map.h>
static int map_absent_read (struct mtd_info *, loff_t, size_t, size_t *, u_char *);
static int map_absent_write (struct mtd_info *, loff_t, size_t, size_t *, const u_char *);
static int map_absent_erase (struct mtd_info *, struct erase_info *);
static void map_absent_sync (struct mtd_info *);
static struct mtd_info *map_absent_probe(struct map_info *map);
static void map_absent_destroy (struct mtd_info *);
static struct mtd_chip_driver map_absent_chipdrv = {
.probe = map_absent_probe,
.destroy = map_absent_destroy,
.name = "map_absent",
.module = THIS_MODULE
};
static struct mtd_info *map_absent_probe(struct map_info *map)
{
struct mtd_info *mtd;
mtd = kzalloc(sizeof(*mtd), GFP_KERNEL);
if (!mtd) {
return NULL;
}
map->fldrv = &map_absent_chipdrv;
mtd->priv = map;
mtd->name = map->name;
mtd->type = MTD_ABSENT;
mtd->size = map->size;
mtd->_erase = map_absent_erase;
mtd->_read = map_absent_read;
mtd->_write = map_absent_write;
mtd->_sync = map_absent_sync;
mtd->flags = 0;
mtd->erasesize = PAGE_SIZE;
mtd->writesize = 1;
__module_get(THIS_MODULE);
return mtd;
}
static int map_absent_read(struct mtd_info *mtd, loff_t from, size_t len, size_t *retlen, u_char *buf)
{
return -ENODEV;
}
static int map_absent_write(struct mtd_info *mtd, loff_t to, size_t len, size_t *retlen, const u_char *buf)
{
return -ENODEV;
}
static int map_absent_erase(struct mtd_info *mtd, struct erase_info *instr)
{
return -ENODEV;
}
static void map_absent_sync(struct mtd_info *mtd)
{
/* nop */
}
static void map_absent_destroy(struct mtd_info *mtd)
{
/* nop */
}
static int __init map_absent_init(void)
{
register_mtd_chip_driver(&map_absent_chipdrv);
return 0;
}
static void __exit map_absent_exit(void)
{
unregister_mtd_chip_driver(&map_absent_chipdrv);
}
module_init(map_absent_init);
module_exit(map_absent_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Resilience Corporation - Eric Brower <[email protected]>");
MODULE_DESCRIPTION("Placeholder MTD chip driver for 'absent' chips");
| null | null | null | null | 105,952 |
12,861 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 177,856 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Copyright 2007 Sony Corporation
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; version 2 of the License.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program.
* If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef _ASM_POWERPC_EMULATED_OPS_H
#define _ASM_POWERPC_EMULATED_OPS_H
#include <linux/atomic.h>
#include <linux/perf_event.h>
#ifdef CONFIG_PPC_EMULATED_STATS
struct ppc_emulated_entry {
const char *name;
atomic_t val;
};
extern struct ppc_emulated {
#ifdef CONFIG_ALTIVEC
struct ppc_emulated_entry altivec;
#endif
struct ppc_emulated_entry dcba;
struct ppc_emulated_entry dcbz;
struct ppc_emulated_entry fp_pair;
struct ppc_emulated_entry isel;
struct ppc_emulated_entry mcrxr;
struct ppc_emulated_entry mfpvr;
struct ppc_emulated_entry multiple;
struct ppc_emulated_entry popcntb;
struct ppc_emulated_entry spe;
struct ppc_emulated_entry string;
struct ppc_emulated_entry sync;
struct ppc_emulated_entry unaligned;
#ifdef CONFIG_MATH_EMULATION
struct ppc_emulated_entry math;
#endif
#ifdef CONFIG_VSX
struct ppc_emulated_entry vsx;
#endif
#ifdef CONFIG_PPC64
struct ppc_emulated_entry mfdscr;
struct ppc_emulated_entry mtdscr;
struct ppc_emulated_entry lq_stq;
#endif
} ppc_emulated;
extern u32 ppc_warn_emulated;
extern void ppc_warn_emulated_print(const char *type);
#define __PPC_WARN_EMULATED(type) \
do { \
atomic_inc(&ppc_emulated.type.val); \
if (ppc_warn_emulated) \
ppc_warn_emulated_print(ppc_emulated.type.name); \
} while (0)
#else /* !CONFIG_PPC_EMULATED_STATS */
#define __PPC_WARN_EMULATED(type) do { } while (0)
#endif /* !CONFIG_PPC_EMULATED_STATS */
#define PPC_WARN_EMULATED(type, regs) \
do { \
perf_sw_event(PERF_COUNT_SW_EMULATION_FAULTS, \
1, regs, 0); \
__PPC_WARN_EMULATED(type); \
} while (0)
#define PPC_WARN_ALIGNMENT(type, regs) \
do { \
perf_sw_event(PERF_COUNT_SW_ALIGNMENT_FAULTS, \
1, regs, regs->dar); \
__PPC_WARN_EMULATED(type); \
} while (0)
#endif /* _ASM_POWERPC_EMULATED_OPS_H */
| null | null | null | null | 86,203 |
37,924 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 37,924 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright (C) 2013 Google Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#ifndef THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_STROKE_DATA_H_
#define THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_STROKE_DATA_H_
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/renderer/platform/graphics/dash_array.h"
#include "third_party/blink/renderer/platform/graphics/gradient.h"
#include "third_party/blink/renderer/platform/graphics/graphics_types.h"
#include "third_party/blink/renderer/platform/graphics/paint/paint_flags.h"
#include "third_party/blink/renderer/platform/graphics/pattern.h"
#include "third_party/blink/renderer/platform/platform_export.h"
#include "third_party/blink/renderer/platform/wtf/allocator.h"
#include "third_party/skia/include/core/SkPaint.h"
#include "third_party/skia/include/core/SkPathEffect.h"
namespace blink {
// Encapsulates stroke geometry information.
// It is pulled out of GraphicsContextState to enable other methods to use it.
class PLATFORM_EXPORT StrokeData final {
DISALLOW_NEW();
public:
StrokeData()
: style_(kSolidStroke),
thickness_(0),
line_cap_(PaintFlags::kDefault_Cap),
line_join_(PaintFlags::kDefault_Join),
miter_limit_(4) {}
StrokeStyle Style() const { return style_; }
void SetStyle(StrokeStyle style) { style_ = style; }
float Thickness() const { return thickness_; }
void SetThickness(float thickness) { thickness_ = thickness; }
void SetLineCap(LineCap cap) { line_cap_ = (PaintFlags::Cap)cap; }
void SetLineJoin(LineJoin join) { line_join_ = (PaintFlags::Join)join; }
float MiterLimit() const { return miter_limit_; }
void SetMiterLimit(float miter_limit) { miter_limit_ = miter_limit; }
void SetLineDash(const DashArray&, float);
// Sets everything on the paint except the pattern, gradient and color.
// If a non-zero length is provided, the number of dashes/dots on a
// dashed/dotted line will be adjusted to start and end that length with a
// dash/dot. If non-zero, dash_thickness is the thickness to use when
// deciding on dash sizes. Used in border painting when we stroke thick
// to allow for clipping at corners, but still want small dashes.
void SetupPaint(PaintFlags*,
const int length = 0,
const int dash_thickess = 0) const;
// Setup any DashPathEffect on the paint. See SetupPaint above for parameter
// information.
void SetupPaintDashPathEffect(PaintFlags*,
const int path_length = 0,
const int dash_thickness = 0) const;
// Determine whether a stroked line should be drawn using dashes. In practice,
// we draw dashes when a dashed stroke is specified or when a dotted stroke
// is specified but the line width is too small to draw circles.
static bool StrokeIsDashed(float width, StrokeStyle);
// The length of the dash relative to the line thickness for dashed stroking.
// A different dash length may be used when dashes are adjusted to better
// fit a given length path. Thin lines need longer dashes to avoid
// looking like dots when drawn.
static float DashLengthRatio(float thickness) {
return thickness >= 3 ? 2.0 : 3.0;
}
// The length of the gap between dashes relative to the line thickness for
// dashed stroking. A different gap may be used when dashes are adjusted to
// better fit a given length path. Thin lines need longer gaps to avoid
// looking like a continuous line when drawn.
static float DashGapRatio(float thickness) {
return thickness >= 3 ? 1.0 : 2.0;
}
// Return a dash gap size that places dashes at each end of a stroke that is
// strokeLength long, given preferred dash and gap sizes. The gap returned is
// the one that minimizes deviation from the preferred gap length.
static float SelectBestDashGap(float stroke_length,
float dash_length,
float gap_length);
private:
StrokeStyle style_;
float thickness_;
PaintFlags::Cap line_cap_;
PaintFlags::Join line_join_;
float miter_limit_;
sk_sp<SkPathEffect> dash_;
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_PLATFORM_GRAPHICS_STROKE_DATA_H_
| null | null | null | null | 34,787 |
46,310 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 46,310 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 ASH_ROTATOR_SCREEN_ROTATION_ANIMATOR_OBSERVER_H
#define ASH_ROTATOR_SCREEN_ROTATION_ANIMATOR_OBSERVER_H
#include "ash/ash_export.h"
namespace ash {
class ScreenRotationAnimator;
class ASH_EXPORT ScreenRotationAnimatorObserver {
public:
ScreenRotationAnimatorObserver() {}
// This will be called when the animation is ended or aborted.
virtual void OnScreenRotationAnimationFinished(
ScreenRotationAnimator* animator) = 0;
protected:
virtual ~ScreenRotationAnimatorObserver() {}
};
} // namespace ash
#endif // ASH_ROTATOR_SCREEN_ROTATION_ANIMATOR_OBSERVER_H
| null | null | null | null | 43,173 |
64,693 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 64,693 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2018 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 CHROME_BROWSER_UI_COCOA_EXTENSIONS_EXTENSION_POPUP_VIEWS_MAC_H_
#define CHROME_BROWSER_UI_COCOA_EXTENSIONS_EXTENSION_POPUP_VIEWS_MAC_H_
#import <Foundation/Foundation.h>
#include <memory>
#import "base/mac/scoped_nsobject.h"
#include "base/macros.h"
#include "chrome/browser/ui/views/extensions/extension_popup.h"
#include "ui/gfx/native_widget_types.h"
#include "ui/views/bubble/bubble_border.h"
// Bridges NSWindow and the Anchor View expected by ExtensionPopup.
class ExtensionPopupViewsMac : public ExtensionPopup {
public:
~ExtensionPopupViewsMac() override;
// Create and show a popup with the given |host| anchored at |anchor_point| in
// screen coordinates. The |parent_window| serves as the parent to the popup
// and is used to handle dismissing the popup on activation and lifetime
// events. |show_action| controls the dismissal of the popup with respect to
// dev tools. The actual display of the popup is delayed until the page
// contents finish loading in order to minimize UI flashing and resizing.
static ExtensionPopupViewsMac* ShowPopup(
std::unique_ptr<extensions::ExtensionViewHost> host,
gfx::NativeWindow parent_window,
const gfx::Point& anchor_point,
ExtensionPopup::ShowAction show_action);
private:
ExtensionPopupViewsMac(std::unique_ptr<extensions::ExtensionViewHost> host,
const gfx::Point& anchor_point,
ExtensionPopup::ShowAction show_action);
base::scoped_nsobject<NSMutableArray> observer_tokens_;
DISALLOW_COPY_AND_ASSIGN(ExtensionPopupViewsMac);
};
#endif // CHROME_BROWSER_UI_COCOA_EXTENSIONS_EXTENSION_POPUP_VIEWS_MAC_H_
| null | null | null | null | 61,556 |
8,103 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 173,098 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
#ifndef _ASM_X86_NOPS_H
#define _ASM_X86_NOPS_H
/*
* Define nops for use with alternative() and for tracing.
*
* *_NOP5_ATOMIC must be a single instruction.
*/
#define NOP_DS_PREFIX 0x3e
/* generic versions from gas
1: nop
the following instructions are NOT nops in 64-bit mode,
for 64-bit mode use K8 or P6 nops instead
2: movl %esi,%esi
3: leal 0x00(%esi),%esi
4: leal 0x00(,%esi,1),%esi
6: leal 0x00000000(%esi),%esi
7: leal 0x00000000(,%esi,1),%esi
*/
#define GENERIC_NOP1 0x90
#define GENERIC_NOP2 0x89,0xf6
#define GENERIC_NOP3 0x8d,0x76,0x00
#define GENERIC_NOP4 0x8d,0x74,0x26,0x00
#define GENERIC_NOP5 GENERIC_NOP1,GENERIC_NOP4
#define GENERIC_NOP6 0x8d,0xb6,0x00,0x00,0x00,0x00
#define GENERIC_NOP7 0x8d,0xb4,0x26,0x00,0x00,0x00,0x00
#define GENERIC_NOP8 GENERIC_NOP1,GENERIC_NOP7
#define GENERIC_NOP5_ATOMIC NOP_DS_PREFIX,GENERIC_NOP4
/* Opteron 64bit nops
1: nop
2: osp nop
3: osp osp nop
4: osp osp osp nop
*/
#define K8_NOP1 GENERIC_NOP1
#define K8_NOP2 0x66,K8_NOP1
#define K8_NOP3 0x66,K8_NOP2
#define K8_NOP4 0x66,K8_NOP3
#define K8_NOP5 K8_NOP3,K8_NOP2
#define K8_NOP6 K8_NOP3,K8_NOP3
#define K8_NOP7 K8_NOP4,K8_NOP3
#define K8_NOP8 K8_NOP4,K8_NOP4
#define K8_NOP5_ATOMIC 0x66,K8_NOP4
/* K7 nops
uses eax dependencies (arbitrary choice)
1: nop
2: movl %eax,%eax
3: leal (,%eax,1),%eax
4: leal 0x00(,%eax,1),%eax
6: leal 0x00000000(%eax),%eax
7: leal 0x00000000(,%eax,1),%eax
*/
#define K7_NOP1 GENERIC_NOP1
#define K7_NOP2 0x8b,0xc0
#define K7_NOP3 0x8d,0x04,0x20
#define K7_NOP4 0x8d,0x44,0x20,0x00
#define K7_NOP5 K7_NOP4,K7_NOP1
#define K7_NOP6 0x8d,0x80,0,0,0,0
#define K7_NOP7 0x8D,0x04,0x05,0,0,0,0
#define K7_NOP8 K7_NOP7,K7_NOP1
#define K7_NOP5_ATOMIC NOP_DS_PREFIX,K7_NOP4
/* P6 nops
uses eax dependencies (Intel-recommended choice)
1: nop
2: osp nop
3: nopl (%eax)
4: nopl 0x00(%eax)
5: nopl 0x00(%eax,%eax,1)
6: osp nopl 0x00(%eax,%eax,1)
7: nopl 0x00000000(%eax)
8: nopl 0x00000000(%eax,%eax,1)
Note: All the above are assumed to be a single instruction.
There is kernel code that depends on this.
*/
#define P6_NOP1 GENERIC_NOP1
#define P6_NOP2 0x66,0x90
#define P6_NOP3 0x0f,0x1f,0x00
#define P6_NOP4 0x0f,0x1f,0x40,0
#define P6_NOP5 0x0f,0x1f,0x44,0x00,0
#define P6_NOP6 0x66,0x0f,0x1f,0x44,0x00,0
#define P6_NOP7 0x0f,0x1f,0x80,0,0,0,0
#define P6_NOP8 0x0f,0x1f,0x84,0x00,0,0,0,0
#define P6_NOP5_ATOMIC P6_NOP5
#ifdef __ASSEMBLY__
#define _ASM_MK_NOP(x) .byte x
#else
#define _ASM_MK_NOP(x) ".byte " __stringify(x) "\n"
#endif
#if defined(CONFIG_MK7)
#define ASM_NOP1 _ASM_MK_NOP(K7_NOP1)
#define ASM_NOP2 _ASM_MK_NOP(K7_NOP2)
#define ASM_NOP3 _ASM_MK_NOP(K7_NOP3)
#define ASM_NOP4 _ASM_MK_NOP(K7_NOP4)
#define ASM_NOP5 _ASM_MK_NOP(K7_NOP5)
#define ASM_NOP6 _ASM_MK_NOP(K7_NOP6)
#define ASM_NOP7 _ASM_MK_NOP(K7_NOP7)
#define ASM_NOP8 _ASM_MK_NOP(K7_NOP8)
#define ASM_NOP5_ATOMIC _ASM_MK_NOP(K7_NOP5_ATOMIC)
#elif defined(CONFIG_X86_P6_NOP)
#define ASM_NOP1 _ASM_MK_NOP(P6_NOP1)
#define ASM_NOP2 _ASM_MK_NOP(P6_NOP2)
#define ASM_NOP3 _ASM_MK_NOP(P6_NOP3)
#define ASM_NOP4 _ASM_MK_NOP(P6_NOP4)
#define ASM_NOP5 _ASM_MK_NOP(P6_NOP5)
#define ASM_NOP6 _ASM_MK_NOP(P6_NOP6)
#define ASM_NOP7 _ASM_MK_NOP(P6_NOP7)
#define ASM_NOP8 _ASM_MK_NOP(P6_NOP8)
#define ASM_NOP5_ATOMIC _ASM_MK_NOP(P6_NOP5_ATOMIC)
#elif defined(CONFIG_X86_64)
#define ASM_NOP1 _ASM_MK_NOP(K8_NOP1)
#define ASM_NOP2 _ASM_MK_NOP(K8_NOP2)
#define ASM_NOP3 _ASM_MK_NOP(K8_NOP3)
#define ASM_NOP4 _ASM_MK_NOP(K8_NOP4)
#define ASM_NOP5 _ASM_MK_NOP(K8_NOP5)
#define ASM_NOP6 _ASM_MK_NOP(K8_NOP6)
#define ASM_NOP7 _ASM_MK_NOP(K8_NOP7)
#define ASM_NOP8 _ASM_MK_NOP(K8_NOP8)
#define ASM_NOP5_ATOMIC _ASM_MK_NOP(K8_NOP5_ATOMIC)
#else
#define ASM_NOP1 _ASM_MK_NOP(GENERIC_NOP1)
#define ASM_NOP2 _ASM_MK_NOP(GENERIC_NOP2)
#define ASM_NOP3 _ASM_MK_NOP(GENERIC_NOP3)
#define ASM_NOP4 _ASM_MK_NOP(GENERIC_NOP4)
#define ASM_NOP5 _ASM_MK_NOP(GENERIC_NOP5)
#define ASM_NOP6 _ASM_MK_NOP(GENERIC_NOP6)
#define ASM_NOP7 _ASM_MK_NOP(GENERIC_NOP7)
#define ASM_NOP8 _ASM_MK_NOP(GENERIC_NOP8)
#define ASM_NOP5_ATOMIC _ASM_MK_NOP(GENERIC_NOP5_ATOMIC)
#endif
#define ASM_NOP_MAX 8
#define NOP_ATOMIC5 (ASM_NOP_MAX+1) /* Entry for the 5-byte atomic NOP */
#ifndef __ASSEMBLY__
extern const unsigned char * const *ideal_nops;
extern void arch_init_ideal_nops(void);
#endif
#endif /* _ASM_X86_NOPS_H */
| null | null | null | null | 81,445 |
15,752 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 180,747 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* include/asm-mips/txx9tmr.h
* TX39/TX49 timer controller definitions.
*
* This file is subject to the terms and conditions of the GNU General Public
* License. See the file "COPYING" in the main directory of this archive
* for more details.
*/
#ifndef __ASM_TXX9TMR_H
#define __ASM_TXX9TMR_H
#include <linux/types.h>
struct txx9_tmr_reg {
u32 tcr;
u32 tisr;
u32 cpra;
u32 cprb;
u32 itmr;
u32 unused0[3];
u32 ccdr;
u32 unused1[3];
u32 pgmr;
u32 unused2[3];
u32 wtmr;
u32 unused3[43];
u32 trr;
};
/* TMTCR : Timer Control */
#define TXx9_TMTCR_TCE 0x00000080
#define TXx9_TMTCR_CCDE 0x00000040
#define TXx9_TMTCR_CRE 0x00000020
#define TXx9_TMTCR_ECES 0x00000008
#define TXx9_TMTCR_CCS 0x00000004
#define TXx9_TMTCR_TMODE_MASK 0x00000003
#define TXx9_TMTCR_TMODE_ITVL 0x00000000
#define TXx9_TMTCR_TMODE_PGEN 0x00000001
#define TXx9_TMTCR_TMODE_WDOG 0x00000002
/* TMTISR : Timer Int. Status */
#define TXx9_TMTISR_TPIBS 0x00000004
#define TXx9_TMTISR_TPIAS 0x00000002
#define TXx9_TMTISR_TIIS 0x00000001
/* TMITMR : Interval Timer Mode */
#define TXx9_TMITMR_TIIE 0x00008000
#define TXx9_TMITMR_TZCE 0x00000001
/* TMWTMR : Watchdog Timer Mode */
#define TXx9_TMWTMR_TWIE 0x00008000
#define TXx9_TMWTMR_WDIS 0x00000080
#define TXx9_TMWTMR_TWC 0x00000001
void txx9_clocksource_init(unsigned long baseaddr,
unsigned int imbusclk);
void txx9_clockevent_init(unsigned long baseaddr, int irq,
unsigned int imbusclk);
void txx9_tmr_init(unsigned long baseaddr);
#ifdef CONFIG_CPU_TX39XX
#define TXX9_TIMER_BITS 24
#else
#define TXX9_TIMER_BITS 32
#endif
#endif /* __ASM_TXX9TMR_H */
| null | null | null | null | 89,094 |
18,005 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 18,005 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 "components/policy/core/common/config_dir_policy_loader.h"
#include <stddef.h>
#include <algorithm>
#include <set>
#include <string>
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/files/file_enumerator.h"
#include "base/files/file_util.h"
#include "base/json/json_file_value_serializer.h"
#include "base/json/json_reader.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/stl_util.h"
#include "components/policy/core/common/policy_bundle.h"
#include "components/policy/core/common/policy_load_status.h"
#include "components/policy/core/common/policy_types.h"
namespace policy {
namespace {
// Subdirectories that contain the mandatory and recommended policies.
constexpr base::FilePath::CharType kMandatoryConfigDir[] =
FILE_PATH_LITERAL("managed");
constexpr base::FilePath::CharType kRecommendedConfigDir[] =
FILE_PATH_LITERAL("recommended");
PolicyLoadStatus JsonErrorToPolicyLoadStatus(int status) {
switch (status) {
case JSONFileValueDeserializer::JSON_ACCESS_DENIED:
case JSONFileValueDeserializer::JSON_CANNOT_READ_FILE:
case JSONFileValueDeserializer::JSON_FILE_LOCKED:
return POLICY_LOAD_STATUS_READ_ERROR;
case JSONFileValueDeserializer::JSON_NO_SUCH_FILE:
return POLICY_LOAD_STATUS_MISSING;
case base::JSONReader::JSON_INVALID_ESCAPE:
case base::JSONReader::JSON_SYNTAX_ERROR:
case base::JSONReader::JSON_UNEXPECTED_TOKEN:
case base::JSONReader::JSON_TRAILING_COMMA:
case base::JSONReader::JSON_TOO_MUCH_NESTING:
case base::JSONReader::JSON_UNEXPECTED_DATA_AFTER_ROOT:
case base::JSONReader::JSON_UNSUPPORTED_ENCODING:
case base::JSONReader::JSON_UNQUOTED_DICTIONARY_KEY:
return POLICY_LOAD_STATUS_PARSE_ERROR;
case base::JSONReader::JSON_NO_ERROR:
NOTREACHED();
return POLICY_LOAD_STATUS_STARTED;
}
NOTREACHED() << "Invalid status " << status;
return POLICY_LOAD_STATUS_PARSE_ERROR;
}
} // namespace
ConfigDirPolicyLoader::ConfigDirPolicyLoader(
scoped_refptr<base::SequencedTaskRunner> task_runner,
const base::FilePath& config_dir,
PolicyScope scope)
: AsyncPolicyLoader(task_runner),
task_runner_(task_runner),
config_dir_(config_dir),
scope_(scope) {}
ConfigDirPolicyLoader::~ConfigDirPolicyLoader() {}
void ConfigDirPolicyLoader::InitOnBackgroundThread() {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
base::FilePathWatcher::Callback callback =
base::Bind(&ConfigDirPolicyLoader::OnFileUpdated, base::Unretained(this));
mandatory_watcher_.Watch(config_dir_.Append(kMandatoryConfigDir), false,
callback);
recommended_watcher_.Watch(config_dir_.Append(kRecommendedConfigDir), false,
callback);
}
std::unique_ptr<PolicyBundle> ConfigDirPolicyLoader::Load() {
std::unique_ptr<PolicyBundle> bundle(new PolicyBundle());
LoadFromPath(config_dir_.Append(kMandatoryConfigDir),
POLICY_LEVEL_MANDATORY,
bundle.get());
LoadFromPath(config_dir_.Append(kRecommendedConfigDir),
POLICY_LEVEL_RECOMMENDED,
bundle.get());
return bundle;
}
base::Time ConfigDirPolicyLoader::LastModificationTime() {
static constexpr const base::FilePath::CharType* kConfigDirSuffixes[] = {
kMandatoryConfigDir, kRecommendedConfigDir,
};
base::Time last_modification = base::Time();
base::File::Info info;
for (size_t i = 0; i < arraysize(kConfigDirSuffixes); ++i) {
base::FilePath path(config_dir_.Append(kConfigDirSuffixes[i]));
// Skip if the file doesn't exist, or it isn't a directory.
if (!base::GetFileInfo(path, &info) || !info.is_directory)
continue;
// Enumerate the files and find the most recent modification timestamp.
base::FileEnumerator file_enumerator(path, false,
base::FileEnumerator::FILES);
for (base::FilePath config_file = file_enumerator.Next();
!config_file.empty();
config_file = file_enumerator.Next()) {
if (base::GetFileInfo(config_file, &info) && !info.is_directory)
last_modification = std::max(last_modification, info.last_modified);
}
}
return last_modification;
}
void ConfigDirPolicyLoader::LoadFromPath(const base::FilePath& path,
PolicyLevel level,
PolicyBundle* bundle) {
// Enumerate the files and sort them lexicographically.
std::set<base::FilePath> files;
base::FileEnumerator file_enumerator(path, false,
base::FileEnumerator::FILES);
for (base::FilePath config_file_path = file_enumerator.Next();
!config_file_path.empty(); config_file_path = file_enumerator.Next())
files.insert(config_file_path);
PolicyLoadStatusUmaReporter status;
if (files.empty()) {
status.Add(POLICY_LOAD_STATUS_NO_POLICY);
return;
}
// Start with an empty dictionary and merge the files' contents.
// The files are processed in reverse order because |MergeFrom| gives priority
// to existing keys, but the ConfigDirPolicyProvider gives priority to the
// last file in lexicographic order.
for (std::set<base::FilePath>::reverse_iterator config_file_iter =
files.rbegin(); config_file_iter != files.rend();
++config_file_iter) {
JSONFileValueDeserializer deserializer(*config_file_iter,
base::JSON_ALLOW_TRAILING_COMMAS);
int error_code = 0;
std::string error_msg;
std::unique_ptr<base::Value> value =
deserializer.Deserialize(&error_code, &error_msg);
if (!value.get()) {
LOG(WARNING) << "Failed to read configuration file "
<< config_file_iter->value() << ": " << error_msg;
status.Add(JsonErrorToPolicyLoadStatus(error_code));
continue;
}
base::DictionaryValue* dictionary_value = nullptr;
if (!value->GetAsDictionary(&dictionary_value)) {
LOG(WARNING) << "Expected JSON dictionary in configuration file "
<< config_file_iter->value();
status.Add(POLICY_LOAD_STATUS_PARSE_ERROR);
continue;
}
// Detach the "3rdparty" node.
std::unique_ptr<base::Value> third_party;
if (dictionary_value->Remove("3rdparty", &third_party))
Merge3rdPartyPolicy(third_party.get(), level, bundle);
// Add chrome policy.
PolicyMap policy_map;
policy_map.LoadFrom(dictionary_value, level, scope_,
POLICY_SOURCE_PLATFORM);
bundle->Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
.MergeFrom(policy_map);
}
}
void ConfigDirPolicyLoader::Merge3rdPartyPolicy(
const base::Value* policies,
PolicyLevel level,
PolicyBundle* bundle) {
// The first-level entries in |policies| are PolicyDomains. The second-level
// entries are component IDs, and the third-level entries are the policies
// for that domain/component namespace.
const base::DictionaryValue* domains_dictionary;
if (!policies->GetAsDictionary(&domains_dictionary)) {
LOG(WARNING) << "3rdparty value is not a dictionary!";
return;
}
// Helper to lookup a domain given its string name.
std::map<std::string, PolicyDomain> supported_domains;
supported_domains["extensions"] = POLICY_DOMAIN_EXTENSIONS;
for (base::DictionaryValue::Iterator domains_it(*domains_dictionary);
!domains_it.IsAtEnd(); domains_it.Advance()) {
if (!base::ContainsKey(supported_domains, domains_it.key())) {
LOG(WARNING) << "Unsupported 3rd party policy domain: "
<< domains_it.key();
continue;
}
const base::DictionaryValue* components_dictionary;
if (!domains_it.value().GetAsDictionary(&components_dictionary)) {
LOG(WARNING) << "3rdparty/" << domains_it.key()
<< " value is not a dictionary!";
continue;
}
PolicyDomain domain = supported_domains[domains_it.key()];
for (base::DictionaryValue::Iterator components_it(*components_dictionary);
!components_it.IsAtEnd(); components_it.Advance()) {
const base::DictionaryValue* policy_dictionary;
if (!components_it.value().GetAsDictionary(&policy_dictionary)) {
LOG(WARNING) << "3rdparty/" << domains_it.key() << "/"
<< components_it.key() << " value is not a dictionary!";
continue;
}
PolicyMap policy;
policy.LoadFrom(policy_dictionary, level, scope_, POLICY_SOURCE_PLATFORM);
bundle->Get(PolicyNamespace(domain, components_it.key()))
.MergeFrom(policy);
}
}
}
void ConfigDirPolicyLoader::OnFileUpdated(const base::FilePath& path,
bool error) {
DCHECK(task_runner_->RunsTasksInCurrentSequence());
if (!error)
Reload(false);
}
} // namespace policy
| null | null | null | null | 14,868 |
32,420 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 197,415 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Swap block device support for MTDs
* Turns an MTD device into a swap device with block wear leveling
*
* Copyright © 2007,2011 Nokia Corporation. All rights reserved.
*
* Authors: Jarkko Lavinen <[email protected]>
*
* Based on Richard Purdie's earlier implementation in 2007. Background
* support and lock-less operation written by Adrian Hunter.
*
* 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/kernel.h>
#include <linux/module.h>
#include <linux/mtd/mtd.h>
#include <linux/mtd/blktrans.h>
#include <linux/rbtree.h>
#include <linux/sched.h>
#include <linux/slab.h>
#include <linux/vmalloc.h>
#include <linux/genhd.h>
#include <linux/swap.h>
#include <linux/debugfs.h>
#include <linux/seq_file.h>
#include <linux/device.h>
#include <linux/math64.h>
#define MTDSWAP_PREFIX "mtdswap"
/*
* The number of free eraseblocks when GC should stop
*/
#define CLEAN_BLOCK_THRESHOLD 20
/*
* Number of free eraseblocks below which GC can also collect low frag
* blocks.
*/
#define LOW_FRAG_GC_TRESHOLD 5
/*
* Wear level cost amortization. We want to do wear leveling on the background
* without disturbing gc too much. This is made by defining max GC frequency.
* Frequency value 6 means 1/6 of the GC passes will pick an erase block based
* on the biggest wear difference rather than the biggest dirtiness.
*
* The lower freq2 should be chosen so that it makes sure the maximum erase
* difference will decrease even if a malicious application is deliberately
* trying to make erase differences large.
*/
#define MAX_ERASE_DIFF 4000
#define COLLECT_NONDIRTY_BASE MAX_ERASE_DIFF
#define COLLECT_NONDIRTY_FREQ1 6
#define COLLECT_NONDIRTY_FREQ2 4
#define PAGE_UNDEF UINT_MAX
#define BLOCK_UNDEF UINT_MAX
#define BLOCK_ERROR (UINT_MAX - 1)
#define BLOCK_MAX (UINT_MAX - 2)
#define EBLOCK_BAD (1 << 0)
#define EBLOCK_NOMAGIC (1 << 1)
#define EBLOCK_BITFLIP (1 << 2)
#define EBLOCK_FAILED (1 << 3)
#define EBLOCK_READERR (1 << 4)
#define EBLOCK_IDX_SHIFT 5
struct swap_eb {
struct rb_node rb;
struct rb_root *root;
unsigned int flags;
unsigned int active_count;
unsigned int erase_count;
unsigned int pad; /* speeds up pointer decrement */
};
#define MTDSWAP_ECNT_MIN(rbroot) (rb_entry(rb_first(rbroot), struct swap_eb, \
rb)->erase_count)
#define MTDSWAP_ECNT_MAX(rbroot) (rb_entry(rb_last(rbroot), struct swap_eb, \
rb)->erase_count)
struct mtdswap_tree {
struct rb_root root;
unsigned int count;
};
enum {
MTDSWAP_CLEAN,
MTDSWAP_USED,
MTDSWAP_LOWFRAG,
MTDSWAP_HIFRAG,
MTDSWAP_DIRTY,
MTDSWAP_BITFLIP,
MTDSWAP_FAILING,
MTDSWAP_TREE_CNT,
};
struct mtdswap_dev {
struct mtd_blktrans_dev *mbd_dev;
struct mtd_info *mtd;
struct device *dev;
unsigned int *page_data;
unsigned int *revmap;
unsigned int eblks;
unsigned int spare_eblks;
unsigned int pages_per_eblk;
unsigned int max_erase_count;
struct swap_eb *eb_data;
struct mtdswap_tree trees[MTDSWAP_TREE_CNT];
unsigned long long sect_read_count;
unsigned long long sect_write_count;
unsigned long long mtd_write_count;
unsigned long long mtd_read_count;
unsigned long long discard_count;
unsigned long long discard_page_count;
unsigned int curr_write_pos;
struct swap_eb *curr_write;
char *page_buf;
char *oob_buf;
struct dentry *debugfs_root;
};
struct mtdswap_oobdata {
__le16 magic;
__le32 count;
} __packed;
#define MTDSWAP_MAGIC_CLEAN 0x2095
#define MTDSWAP_MAGIC_DIRTY (MTDSWAP_MAGIC_CLEAN + 1)
#define MTDSWAP_TYPE_CLEAN 0
#define MTDSWAP_TYPE_DIRTY 1
#define MTDSWAP_OOBSIZE sizeof(struct mtdswap_oobdata)
#define MTDSWAP_ERASE_RETRIES 3 /* Before marking erase block bad */
#define MTDSWAP_IO_RETRIES 3
enum {
MTDSWAP_SCANNED_CLEAN,
MTDSWAP_SCANNED_DIRTY,
MTDSWAP_SCANNED_BITFLIP,
MTDSWAP_SCANNED_BAD,
};
/*
* In the worst case mtdswap_writesect() has allocated the last clean
* page from the current block and is then pre-empted by the GC
* thread. The thread can consume a full erase block when moving a
* block.
*/
#define MIN_SPARE_EBLOCKS 2
#define MIN_ERASE_BLOCKS (MIN_SPARE_EBLOCKS + 1)
#define TREE_ROOT(d, name) (&d->trees[MTDSWAP_ ## name].root)
#define TREE_EMPTY(d, name) (TREE_ROOT(d, name)->rb_node == NULL)
#define TREE_NONEMPTY(d, name) (!TREE_EMPTY(d, name))
#define TREE_COUNT(d, name) (d->trees[MTDSWAP_ ## name].count)
#define MTDSWAP_MBD_TO_MTDSWAP(dev) ((struct mtdswap_dev *)dev->priv)
static char partitions[128] = "";
module_param_string(partitions, partitions, sizeof(partitions), 0444);
MODULE_PARM_DESC(partitions, "MTD partition numbers to use as swap "
"partitions=\"1,3,5\"");
static unsigned int spare_eblocks = 10;
module_param(spare_eblocks, uint, 0444);
MODULE_PARM_DESC(spare_eblocks, "Percentage of spare erase blocks for "
"garbage collection (default 10%)");
static bool header; /* false */
module_param(header, bool, 0444);
MODULE_PARM_DESC(header,
"Include builtin swap header (default 0, without header)");
static int mtdswap_gc(struct mtdswap_dev *d, unsigned int background);
static loff_t mtdswap_eb_offset(struct mtdswap_dev *d, struct swap_eb *eb)
{
return (loff_t)(eb - d->eb_data) * d->mtd->erasesize;
}
static void mtdswap_eb_detach(struct mtdswap_dev *d, struct swap_eb *eb)
{
unsigned int oldidx;
struct mtdswap_tree *tp;
if (eb->root) {
tp = container_of(eb->root, struct mtdswap_tree, root);
oldidx = tp - &d->trees[0];
d->trees[oldidx].count--;
rb_erase(&eb->rb, eb->root);
}
}
static void __mtdswap_rb_add(struct rb_root *root, struct swap_eb *eb)
{
struct rb_node **p, *parent = NULL;
struct swap_eb *cur;
p = &root->rb_node;
while (*p) {
parent = *p;
cur = rb_entry(parent, struct swap_eb, rb);
if (eb->erase_count > cur->erase_count)
p = &(*p)->rb_right;
else
p = &(*p)->rb_left;
}
rb_link_node(&eb->rb, parent, p);
rb_insert_color(&eb->rb, root);
}
static void mtdswap_rb_add(struct mtdswap_dev *d, struct swap_eb *eb, int idx)
{
struct rb_root *root;
if (eb->root == &d->trees[idx].root)
return;
mtdswap_eb_detach(d, eb);
root = &d->trees[idx].root;
__mtdswap_rb_add(root, eb);
eb->root = root;
d->trees[idx].count++;
}
static struct rb_node *mtdswap_rb_index(struct rb_root *root, unsigned int idx)
{
struct rb_node *p;
unsigned int i;
p = rb_first(root);
i = 0;
while (i < idx && p) {
p = rb_next(p);
i++;
}
return p;
}
static int mtdswap_handle_badblock(struct mtdswap_dev *d, struct swap_eb *eb)
{
int ret;
loff_t offset;
d->spare_eblks--;
eb->flags |= EBLOCK_BAD;
mtdswap_eb_detach(d, eb);
eb->root = NULL;
/* badblocks not supported */
if (!mtd_can_have_bb(d->mtd))
return 1;
offset = mtdswap_eb_offset(d, eb);
dev_warn(d->dev, "Marking bad block at %08llx\n", offset);
ret = mtd_block_markbad(d->mtd, offset);
if (ret) {
dev_warn(d->dev, "Mark block bad failed for block at %08llx "
"error %d\n", offset, ret);
return ret;
}
return 1;
}
static int mtdswap_handle_write_error(struct mtdswap_dev *d, struct swap_eb *eb)
{
unsigned int marked = eb->flags & EBLOCK_FAILED;
struct swap_eb *curr_write = d->curr_write;
eb->flags |= EBLOCK_FAILED;
if (curr_write == eb) {
d->curr_write = NULL;
if (!marked && d->curr_write_pos != 0) {
mtdswap_rb_add(d, eb, MTDSWAP_FAILING);
return 0;
}
}
return mtdswap_handle_badblock(d, eb);
}
static int mtdswap_read_oob(struct mtdswap_dev *d, loff_t from,
struct mtd_oob_ops *ops)
{
int ret = mtd_read_oob(d->mtd, from, ops);
if (mtd_is_bitflip(ret))
return ret;
if (ret) {
dev_warn(d->dev, "Read OOB failed %d for block at %08llx\n",
ret, from);
return ret;
}
if (ops->oobretlen < ops->ooblen) {
dev_warn(d->dev, "Read OOB return short read (%zd bytes not "
"%zd) for block at %08llx\n",
ops->oobretlen, ops->ooblen, from);
return -EIO;
}
return 0;
}
static int mtdswap_read_markers(struct mtdswap_dev *d, struct swap_eb *eb)
{
struct mtdswap_oobdata *data, *data2;
int ret;
loff_t offset;
struct mtd_oob_ops ops;
offset = mtdswap_eb_offset(d, eb);
/* Check first if the block is bad. */
if (mtd_can_have_bb(d->mtd) && mtd_block_isbad(d->mtd, offset))
return MTDSWAP_SCANNED_BAD;
ops.ooblen = 2 * d->mtd->oobavail;
ops.oobbuf = d->oob_buf;
ops.ooboffs = 0;
ops.datbuf = NULL;
ops.mode = MTD_OPS_AUTO_OOB;
ret = mtdswap_read_oob(d, offset, &ops);
if (ret && !mtd_is_bitflip(ret))
return ret;
data = (struct mtdswap_oobdata *)d->oob_buf;
data2 = (struct mtdswap_oobdata *)
(d->oob_buf + d->mtd->oobavail);
if (le16_to_cpu(data->magic) == MTDSWAP_MAGIC_CLEAN) {
eb->erase_count = le32_to_cpu(data->count);
if (mtd_is_bitflip(ret))
ret = MTDSWAP_SCANNED_BITFLIP;
else {
if (le16_to_cpu(data2->magic) == MTDSWAP_MAGIC_DIRTY)
ret = MTDSWAP_SCANNED_DIRTY;
else
ret = MTDSWAP_SCANNED_CLEAN;
}
} else {
eb->flags |= EBLOCK_NOMAGIC;
ret = MTDSWAP_SCANNED_DIRTY;
}
return ret;
}
static int mtdswap_write_marker(struct mtdswap_dev *d, struct swap_eb *eb,
u16 marker)
{
struct mtdswap_oobdata n;
int ret;
loff_t offset;
struct mtd_oob_ops ops;
ops.ooboffs = 0;
ops.oobbuf = (uint8_t *)&n;
ops.mode = MTD_OPS_AUTO_OOB;
ops.datbuf = NULL;
if (marker == MTDSWAP_TYPE_CLEAN) {
n.magic = cpu_to_le16(MTDSWAP_MAGIC_CLEAN);
n.count = cpu_to_le32(eb->erase_count);
ops.ooblen = MTDSWAP_OOBSIZE;
offset = mtdswap_eb_offset(d, eb);
} else {
n.magic = cpu_to_le16(MTDSWAP_MAGIC_DIRTY);
ops.ooblen = sizeof(n.magic);
offset = mtdswap_eb_offset(d, eb) + d->mtd->writesize;
}
ret = mtd_write_oob(d->mtd, offset, &ops);
if (ret) {
dev_warn(d->dev, "Write OOB failed for block at %08llx "
"error %d\n", offset, ret);
if (ret == -EIO || mtd_is_eccerr(ret))
mtdswap_handle_write_error(d, eb);
return ret;
}
if (ops.oobretlen != ops.ooblen) {
dev_warn(d->dev, "Short OOB write for block at %08llx: "
"%zd not %zd\n",
offset, ops.oobretlen, ops.ooblen);
return ret;
}
return 0;
}
/*
* Are there any erase blocks without MAGIC_CLEAN header, presumably
* because power was cut off after erase but before header write? We
* need to guestimate the erase count.
*/
static void mtdswap_check_counts(struct mtdswap_dev *d)
{
struct rb_root hist_root = RB_ROOT;
struct rb_node *medrb;
struct swap_eb *eb;
unsigned int i, cnt, median;
cnt = 0;
for (i = 0; i < d->eblks; i++) {
eb = d->eb_data + i;
if (eb->flags & (EBLOCK_NOMAGIC | EBLOCK_BAD | EBLOCK_READERR))
continue;
__mtdswap_rb_add(&hist_root, eb);
cnt++;
}
if (cnt == 0)
return;
medrb = mtdswap_rb_index(&hist_root, cnt / 2);
median = rb_entry(medrb, struct swap_eb, rb)->erase_count;
d->max_erase_count = MTDSWAP_ECNT_MAX(&hist_root);
for (i = 0; i < d->eblks; i++) {
eb = d->eb_data + i;
if (eb->flags & (EBLOCK_NOMAGIC | EBLOCK_READERR))
eb->erase_count = median;
if (eb->flags & (EBLOCK_NOMAGIC | EBLOCK_BAD | EBLOCK_READERR))
continue;
rb_erase(&eb->rb, &hist_root);
}
}
static void mtdswap_scan_eblks(struct mtdswap_dev *d)
{
int status;
unsigned int i, idx;
struct swap_eb *eb;
for (i = 0; i < d->eblks; i++) {
eb = d->eb_data + i;
status = mtdswap_read_markers(d, eb);
if (status < 0)
eb->flags |= EBLOCK_READERR;
else if (status == MTDSWAP_SCANNED_BAD) {
eb->flags |= EBLOCK_BAD;
continue;
}
switch (status) {
case MTDSWAP_SCANNED_CLEAN:
idx = MTDSWAP_CLEAN;
break;
case MTDSWAP_SCANNED_DIRTY:
case MTDSWAP_SCANNED_BITFLIP:
idx = MTDSWAP_DIRTY;
break;
default:
idx = MTDSWAP_FAILING;
}
eb->flags |= (idx << EBLOCK_IDX_SHIFT);
}
mtdswap_check_counts(d);
for (i = 0; i < d->eblks; i++) {
eb = d->eb_data + i;
if (eb->flags & EBLOCK_BAD)
continue;
idx = eb->flags >> EBLOCK_IDX_SHIFT;
mtdswap_rb_add(d, eb, idx);
}
}
/*
* Place eblk into a tree corresponding to its number of active blocks
* it contains.
*/
static void mtdswap_store_eb(struct mtdswap_dev *d, struct swap_eb *eb)
{
unsigned int weight = eb->active_count;
unsigned int maxweight = d->pages_per_eblk;
if (eb == d->curr_write)
return;
if (eb->flags & EBLOCK_BITFLIP)
mtdswap_rb_add(d, eb, MTDSWAP_BITFLIP);
else if (eb->flags & (EBLOCK_READERR | EBLOCK_FAILED))
mtdswap_rb_add(d, eb, MTDSWAP_FAILING);
if (weight == maxweight)
mtdswap_rb_add(d, eb, MTDSWAP_USED);
else if (weight == 0)
mtdswap_rb_add(d, eb, MTDSWAP_DIRTY);
else if (weight > (maxweight/2))
mtdswap_rb_add(d, eb, MTDSWAP_LOWFRAG);
else
mtdswap_rb_add(d, eb, MTDSWAP_HIFRAG);
}
static void mtdswap_erase_callback(struct erase_info *done)
{
wait_queue_head_t *wait_q = (wait_queue_head_t *)done->priv;
wake_up(wait_q);
}
static int mtdswap_erase_block(struct mtdswap_dev *d, struct swap_eb *eb)
{
struct mtd_info *mtd = d->mtd;
struct erase_info erase;
wait_queue_head_t wq;
unsigned int retries = 0;
int ret;
eb->erase_count++;
if (eb->erase_count > d->max_erase_count)
d->max_erase_count = eb->erase_count;
retry:
init_waitqueue_head(&wq);
memset(&erase, 0, sizeof(struct erase_info));
erase.mtd = mtd;
erase.callback = mtdswap_erase_callback;
erase.addr = mtdswap_eb_offset(d, eb);
erase.len = mtd->erasesize;
erase.priv = (u_long)&wq;
ret = mtd_erase(mtd, &erase);
if (ret) {
if (retries++ < MTDSWAP_ERASE_RETRIES) {
dev_warn(d->dev,
"erase of erase block %#llx on %s failed",
erase.addr, mtd->name);
yield();
goto retry;
}
dev_err(d->dev, "Cannot erase erase block %#llx on %s\n",
erase.addr, mtd->name);
mtdswap_handle_badblock(d, eb);
return -EIO;
}
ret = wait_event_interruptible(wq, erase.state == MTD_ERASE_DONE ||
erase.state == MTD_ERASE_FAILED);
if (ret) {
dev_err(d->dev, "Interrupted erase block %#llx erasure on %s\n",
erase.addr, mtd->name);
return -EINTR;
}
if (erase.state == MTD_ERASE_FAILED) {
if (retries++ < MTDSWAP_ERASE_RETRIES) {
dev_warn(d->dev,
"erase of erase block %#llx on %s failed",
erase.addr, mtd->name);
yield();
goto retry;
}
mtdswap_handle_badblock(d, eb);
return -EIO;
}
return 0;
}
static int mtdswap_map_free_block(struct mtdswap_dev *d, unsigned int page,
unsigned int *block)
{
int ret;
struct swap_eb *old_eb = d->curr_write;
struct rb_root *clean_root;
struct swap_eb *eb;
if (old_eb == NULL || d->curr_write_pos >= d->pages_per_eblk) {
do {
if (TREE_EMPTY(d, CLEAN))
return -ENOSPC;
clean_root = TREE_ROOT(d, CLEAN);
eb = rb_entry(rb_first(clean_root), struct swap_eb, rb);
rb_erase(&eb->rb, clean_root);
eb->root = NULL;
TREE_COUNT(d, CLEAN)--;
ret = mtdswap_write_marker(d, eb, MTDSWAP_TYPE_DIRTY);
} while (ret == -EIO || mtd_is_eccerr(ret));
if (ret)
return ret;
d->curr_write_pos = 0;
d->curr_write = eb;
if (old_eb)
mtdswap_store_eb(d, old_eb);
}
*block = (d->curr_write - d->eb_data) * d->pages_per_eblk +
d->curr_write_pos;
d->curr_write->active_count++;
d->revmap[*block] = page;
d->curr_write_pos++;
return 0;
}
static unsigned int mtdswap_free_page_cnt(struct mtdswap_dev *d)
{
return TREE_COUNT(d, CLEAN) * d->pages_per_eblk +
d->pages_per_eblk - d->curr_write_pos;
}
static unsigned int mtdswap_enough_free_pages(struct mtdswap_dev *d)
{
return mtdswap_free_page_cnt(d) > d->pages_per_eblk;
}
static int mtdswap_write_block(struct mtdswap_dev *d, char *buf,
unsigned int page, unsigned int *bp, int gc_context)
{
struct mtd_info *mtd = d->mtd;
struct swap_eb *eb;
size_t retlen;
loff_t writepos;
int ret;
retry:
if (!gc_context)
while (!mtdswap_enough_free_pages(d))
if (mtdswap_gc(d, 0) > 0)
return -ENOSPC;
ret = mtdswap_map_free_block(d, page, bp);
eb = d->eb_data + (*bp / d->pages_per_eblk);
if (ret == -EIO || mtd_is_eccerr(ret)) {
d->curr_write = NULL;
eb->active_count--;
d->revmap[*bp] = PAGE_UNDEF;
goto retry;
}
if (ret < 0)
return ret;
writepos = (loff_t)*bp << PAGE_SHIFT;
ret = mtd_write(mtd, writepos, PAGE_SIZE, &retlen, buf);
if (ret == -EIO || mtd_is_eccerr(ret)) {
d->curr_write_pos--;
eb->active_count--;
d->revmap[*bp] = PAGE_UNDEF;
mtdswap_handle_write_error(d, eb);
goto retry;
}
if (ret < 0) {
dev_err(d->dev, "Write to MTD device failed: %d (%zd written)",
ret, retlen);
goto err;
}
if (retlen != PAGE_SIZE) {
dev_err(d->dev, "Short write to MTD device: %zd written",
retlen);
ret = -EIO;
goto err;
}
return ret;
err:
d->curr_write_pos--;
eb->active_count--;
d->revmap[*bp] = PAGE_UNDEF;
return ret;
}
static int mtdswap_move_block(struct mtdswap_dev *d, unsigned int oldblock,
unsigned int *newblock)
{
struct mtd_info *mtd = d->mtd;
struct swap_eb *eb, *oldeb;
int ret;
size_t retlen;
unsigned int page, retries;
loff_t readpos;
page = d->revmap[oldblock];
readpos = (loff_t) oldblock << PAGE_SHIFT;
retries = 0;
retry:
ret = mtd_read(mtd, readpos, PAGE_SIZE, &retlen, d->page_buf);
if (ret < 0 && !mtd_is_bitflip(ret)) {
oldeb = d->eb_data + oldblock / d->pages_per_eblk;
oldeb->flags |= EBLOCK_READERR;
dev_err(d->dev, "Read Error: %d (block %u)\n", ret,
oldblock);
retries++;
if (retries < MTDSWAP_IO_RETRIES)
goto retry;
goto read_error;
}
if (retlen != PAGE_SIZE) {
dev_err(d->dev, "Short read: %zd (block %u)\n", retlen,
oldblock);
ret = -EIO;
goto read_error;
}
ret = mtdswap_write_block(d, d->page_buf, page, newblock, 1);
if (ret < 0) {
d->page_data[page] = BLOCK_ERROR;
dev_err(d->dev, "Write error: %d\n", ret);
return ret;
}
eb = d->eb_data + *newblock / d->pages_per_eblk;
d->page_data[page] = *newblock;
d->revmap[oldblock] = PAGE_UNDEF;
eb = d->eb_data + oldblock / d->pages_per_eblk;
eb->active_count--;
return 0;
read_error:
d->page_data[page] = BLOCK_ERROR;
d->revmap[oldblock] = PAGE_UNDEF;
return ret;
}
static int mtdswap_gc_eblock(struct mtdswap_dev *d, struct swap_eb *eb)
{
unsigned int i, block, eblk_base, newblock;
int ret, errcode;
errcode = 0;
eblk_base = (eb - d->eb_data) * d->pages_per_eblk;
for (i = 0; i < d->pages_per_eblk; i++) {
if (d->spare_eblks < MIN_SPARE_EBLOCKS)
return -ENOSPC;
block = eblk_base + i;
if (d->revmap[block] == PAGE_UNDEF)
continue;
ret = mtdswap_move_block(d, block, &newblock);
if (ret < 0 && !errcode)
errcode = ret;
}
return errcode;
}
static int __mtdswap_choose_gc_tree(struct mtdswap_dev *d)
{
int idx, stopat;
if (TREE_COUNT(d, CLEAN) < LOW_FRAG_GC_TRESHOLD)
stopat = MTDSWAP_LOWFRAG;
else
stopat = MTDSWAP_HIFRAG;
for (idx = MTDSWAP_BITFLIP; idx >= stopat; idx--)
if (d->trees[idx].root.rb_node != NULL)
return idx;
return -1;
}
static int mtdswap_wlfreq(unsigned int maxdiff)
{
unsigned int h, x, y, dist, base;
/*
* Calculate linear ramp down from f1 to f2 when maxdiff goes from
* MAX_ERASE_DIFF to MAX_ERASE_DIFF + COLLECT_NONDIRTY_BASE. Similar
* to triangle with height f1 - f1 and width COLLECT_NONDIRTY_BASE.
*/
dist = maxdiff - MAX_ERASE_DIFF;
if (dist > COLLECT_NONDIRTY_BASE)
dist = COLLECT_NONDIRTY_BASE;
/*
* Modelling the slop as right angular triangle with base
* COLLECT_NONDIRTY_BASE and height freq1 - freq2. The ratio y/x is
* equal to the ratio h/base.
*/
h = COLLECT_NONDIRTY_FREQ1 - COLLECT_NONDIRTY_FREQ2;
base = COLLECT_NONDIRTY_BASE;
x = dist - base;
y = (x * h + base / 2) / base;
return COLLECT_NONDIRTY_FREQ2 + y;
}
static int mtdswap_choose_wl_tree(struct mtdswap_dev *d)
{
static unsigned int pick_cnt;
unsigned int i, idx = -1, wear, max;
struct rb_root *root;
max = 0;
for (i = 0; i <= MTDSWAP_DIRTY; i++) {
root = &d->trees[i].root;
if (root->rb_node == NULL)
continue;
wear = d->max_erase_count - MTDSWAP_ECNT_MIN(root);
if (wear > max) {
max = wear;
idx = i;
}
}
if (max > MAX_ERASE_DIFF && pick_cnt >= mtdswap_wlfreq(max) - 1) {
pick_cnt = 0;
return idx;
}
pick_cnt++;
return -1;
}
static int mtdswap_choose_gc_tree(struct mtdswap_dev *d,
unsigned int background)
{
int idx;
if (TREE_NONEMPTY(d, FAILING) &&
(background || (TREE_EMPTY(d, CLEAN) && TREE_EMPTY(d, DIRTY))))
return MTDSWAP_FAILING;
idx = mtdswap_choose_wl_tree(d);
if (idx >= MTDSWAP_CLEAN)
return idx;
return __mtdswap_choose_gc_tree(d);
}
static struct swap_eb *mtdswap_pick_gc_eblk(struct mtdswap_dev *d,
unsigned int background)
{
struct rb_root *rp = NULL;
struct swap_eb *eb = NULL;
int idx;
if (background && TREE_COUNT(d, CLEAN) > CLEAN_BLOCK_THRESHOLD &&
TREE_EMPTY(d, DIRTY) && TREE_EMPTY(d, FAILING))
return NULL;
idx = mtdswap_choose_gc_tree(d, background);
if (idx < 0)
return NULL;
rp = &d->trees[idx].root;
eb = rb_entry(rb_first(rp), struct swap_eb, rb);
rb_erase(&eb->rb, rp);
eb->root = NULL;
d->trees[idx].count--;
return eb;
}
static unsigned int mtdswap_test_patt(unsigned int i)
{
return i % 2 ? 0x55555555 : 0xAAAAAAAA;
}
static unsigned int mtdswap_eblk_passes(struct mtdswap_dev *d,
struct swap_eb *eb)
{
struct mtd_info *mtd = d->mtd;
unsigned int test, i, j, patt, mtd_pages;
loff_t base, pos;
unsigned int *p1 = (unsigned int *)d->page_buf;
unsigned char *p2 = (unsigned char *)d->oob_buf;
struct mtd_oob_ops ops;
int ret;
ops.mode = MTD_OPS_AUTO_OOB;
ops.len = mtd->writesize;
ops.ooblen = mtd->oobavail;
ops.ooboffs = 0;
ops.datbuf = d->page_buf;
ops.oobbuf = d->oob_buf;
base = mtdswap_eb_offset(d, eb);
mtd_pages = d->pages_per_eblk * PAGE_SIZE / mtd->writesize;
for (test = 0; test < 2; test++) {
pos = base;
for (i = 0; i < mtd_pages; i++) {
patt = mtdswap_test_patt(test + i);
memset(d->page_buf, patt, mtd->writesize);
memset(d->oob_buf, patt, mtd->oobavail);
ret = mtd_write_oob(mtd, pos, &ops);
if (ret)
goto error;
pos += mtd->writesize;
}
pos = base;
for (i = 0; i < mtd_pages; i++) {
ret = mtd_read_oob(mtd, pos, &ops);
if (ret)
goto error;
patt = mtdswap_test_patt(test + i);
for (j = 0; j < mtd->writesize/sizeof(int); j++)
if (p1[j] != patt)
goto error;
for (j = 0; j < mtd->oobavail; j++)
if (p2[j] != (unsigned char)patt)
goto error;
pos += mtd->writesize;
}
ret = mtdswap_erase_block(d, eb);
if (ret)
goto error;
}
eb->flags &= ~EBLOCK_READERR;
return 1;
error:
mtdswap_handle_badblock(d, eb);
return 0;
}
static int mtdswap_gc(struct mtdswap_dev *d, unsigned int background)
{
struct swap_eb *eb;
int ret;
if (d->spare_eblks < MIN_SPARE_EBLOCKS)
return 1;
eb = mtdswap_pick_gc_eblk(d, background);
if (!eb)
return 1;
ret = mtdswap_gc_eblock(d, eb);
if (ret == -ENOSPC)
return 1;
if (eb->flags & EBLOCK_FAILED) {
mtdswap_handle_badblock(d, eb);
return 0;
}
eb->flags &= ~EBLOCK_BITFLIP;
ret = mtdswap_erase_block(d, eb);
if ((eb->flags & EBLOCK_READERR) &&
(ret || !mtdswap_eblk_passes(d, eb)))
return 0;
if (ret == 0)
ret = mtdswap_write_marker(d, eb, MTDSWAP_TYPE_CLEAN);
if (ret == 0)
mtdswap_rb_add(d, eb, MTDSWAP_CLEAN);
else if (ret != -EIO && !mtd_is_eccerr(ret))
mtdswap_rb_add(d, eb, MTDSWAP_DIRTY);
return 0;
}
static void mtdswap_background(struct mtd_blktrans_dev *dev)
{
struct mtdswap_dev *d = MTDSWAP_MBD_TO_MTDSWAP(dev);
int ret;
while (1) {
ret = mtdswap_gc(d, 1);
if (ret || mtd_blktrans_cease_background(dev))
return;
}
}
static void mtdswap_cleanup(struct mtdswap_dev *d)
{
vfree(d->eb_data);
vfree(d->revmap);
vfree(d->page_data);
kfree(d->oob_buf);
kfree(d->page_buf);
}
static int mtdswap_flush(struct mtd_blktrans_dev *dev)
{
struct mtdswap_dev *d = MTDSWAP_MBD_TO_MTDSWAP(dev);
mtd_sync(d->mtd);
return 0;
}
static unsigned int mtdswap_badblocks(struct mtd_info *mtd, uint64_t size)
{
loff_t offset;
unsigned int badcnt;
badcnt = 0;
if (mtd_can_have_bb(mtd))
for (offset = 0; offset < size; offset += mtd->erasesize)
if (mtd_block_isbad(mtd, offset))
badcnt++;
return badcnt;
}
static int mtdswap_writesect(struct mtd_blktrans_dev *dev,
unsigned long page, char *buf)
{
struct mtdswap_dev *d = MTDSWAP_MBD_TO_MTDSWAP(dev);
unsigned int newblock, mapped;
struct swap_eb *eb;
int ret;
d->sect_write_count++;
if (d->spare_eblks < MIN_SPARE_EBLOCKS)
return -ENOSPC;
if (header) {
/* Ignore writes to the header page */
if (unlikely(page == 0))
return 0;
page--;
}
mapped = d->page_data[page];
if (mapped <= BLOCK_MAX) {
eb = d->eb_data + (mapped / d->pages_per_eblk);
eb->active_count--;
mtdswap_store_eb(d, eb);
d->page_data[page] = BLOCK_UNDEF;
d->revmap[mapped] = PAGE_UNDEF;
}
ret = mtdswap_write_block(d, buf, page, &newblock, 0);
d->mtd_write_count++;
if (ret < 0)
return ret;
eb = d->eb_data + (newblock / d->pages_per_eblk);
d->page_data[page] = newblock;
return 0;
}
/* Provide a dummy swap header for the kernel */
static int mtdswap_auto_header(struct mtdswap_dev *d, char *buf)
{
union swap_header *hd = (union swap_header *)(buf);
memset(buf, 0, PAGE_SIZE - 10);
hd->info.version = 1;
hd->info.last_page = d->mbd_dev->size - 1;
hd->info.nr_badpages = 0;
memcpy(buf + PAGE_SIZE - 10, "SWAPSPACE2", 10);
return 0;
}
static int mtdswap_readsect(struct mtd_blktrans_dev *dev,
unsigned long page, char *buf)
{
struct mtdswap_dev *d = MTDSWAP_MBD_TO_MTDSWAP(dev);
struct mtd_info *mtd = d->mtd;
unsigned int realblock, retries;
loff_t readpos;
struct swap_eb *eb;
size_t retlen;
int ret;
d->sect_read_count++;
if (header) {
if (unlikely(page == 0))
return mtdswap_auto_header(d, buf);
page--;
}
realblock = d->page_data[page];
if (realblock > BLOCK_MAX) {
memset(buf, 0x0, PAGE_SIZE);
if (realblock == BLOCK_UNDEF)
return 0;
else
return -EIO;
}
eb = d->eb_data + (realblock / d->pages_per_eblk);
BUG_ON(d->revmap[realblock] == PAGE_UNDEF);
readpos = (loff_t)realblock << PAGE_SHIFT;
retries = 0;
retry:
ret = mtd_read(mtd, readpos, PAGE_SIZE, &retlen, buf);
d->mtd_read_count++;
if (mtd_is_bitflip(ret)) {
eb->flags |= EBLOCK_BITFLIP;
mtdswap_rb_add(d, eb, MTDSWAP_BITFLIP);
ret = 0;
}
if (ret < 0) {
dev_err(d->dev, "Read error %d\n", ret);
eb->flags |= EBLOCK_READERR;
mtdswap_rb_add(d, eb, MTDSWAP_FAILING);
retries++;
if (retries < MTDSWAP_IO_RETRIES)
goto retry;
return ret;
}
if (retlen != PAGE_SIZE) {
dev_err(d->dev, "Short read %zd\n", retlen);
return -EIO;
}
return 0;
}
static int mtdswap_discard(struct mtd_blktrans_dev *dev, unsigned long first,
unsigned nr_pages)
{
struct mtdswap_dev *d = MTDSWAP_MBD_TO_MTDSWAP(dev);
unsigned long page;
struct swap_eb *eb;
unsigned int mapped;
d->discard_count++;
for (page = first; page < first + nr_pages; page++) {
mapped = d->page_data[page];
if (mapped <= BLOCK_MAX) {
eb = d->eb_data + (mapped / d->pages_per_eblk);
eb->active_count--;
mtdswap_store_eb(d, eb);
d->page_data[page] = BLOCK_UNDEF;
d->revmap[mapped] = PAGE_UNDEF;
d->discard_page_count++;
} else if (mapped == BLOCK_ERROR) {
d->page_data[page] = BLOCK_UNDEF;
d->discard_page_count++;
}
}
return 0;
}
static int mtdswap_show(struct seq_file *s, void *data)
{
struct mtdswap_dev *d = (struct mtdswap_dev *) s->private;
unsigned long sum;
unsigned int count[MTDSWAP_TREE_CNT];
unsigned int min[MTDSWAP_TREE_CNT];
unsigned int max[MTDSWAP_TREE_CNT];
unsigned int i, cw = 0, cwp = 0, cwecount = 0, bb_cnt, mapped, pages;
uint64_t use_size;
char *name[] = {"clean", "used", "low", "high", "dirty", "bitflip",
"failing"};
mutex_lock(&d->mbd_dev->lock);
for (i = 0; i < MTDSWAP_TREE_CNT; i++) {
struct rb_root *root = &d->trees[i].root;
if (root->rb_node) {
count[i] = d->trees[i].count;
min[i] = rb_entry(rb_first(root), struct swap_eb,
rb)->erase_count;
max[i] = rb_entry(rb_last(root), struct swap_eb,
rb)->erase_count;
} else
count[i] = 0;
}
if (d->curr_write) {
cw = 1;
cwp = d->curr_write_pos;
cwecount = d->curr_write->erase_count;
}
sum = 0;
for (i = 0; i < d->eblks; i++)
sum += d->eb_data[i].erase_count;
use_size = (uint64_t)d->eblks * d->mtd->erasesize;
bb_cnt = mtdswap_badblocks(d->mtd, use_size);
mapped = 0;
pages = d->mbd_dev->size;
for (i = 0; i < pages; i++)
if (d->page_data[i] != BLOCK_UNDEF)
mapped++;
mutex_unlock(&d->mbd_dev->lock);
for (i = 0; i < MTDSWAP_TREE_CNT; i++) {
if (!count[i])
continue;
if (min[i] != max[i])
seq_printf(s, "%s:\t%5d erase blocks, erased min %d, "
"max %d times\n",
name[i], count[i], min[i], max[i]);
else
seq_printf(s, "%s:\t%5d erase blocks, all erased %d "
"times\n", name[i], count[i], min[i]);
}
if (bb_cnt)
seq_printf(s, "bad:\t%5u erase blocks\n", bb_cnt);
if (cw)
seq_printf(s, "current erase block: %u pages used, %u free, "
"erased %u times\n",
cwp, d->pages_per_eblk - cwp, cwecount);
seq_printf(s, "total erasures: %lu\n", sum);
seq_puts(s, "\n");
seq_printf(s, "mtdswap_readsect count: %llu\n", d->sect_read_count);
seq_printf(s, "mtdswap_writesect count: %llu\n", d->sect_write_count);
seq_printf(s, "mtdswap_discard count: %llu\n", d->discard_count);
seq_printf(s, "mtd read count: %llu\n", d->mtd_read_count);
seq_printf(s, "mtd write count: %llu\n", d->mtd_write_count);
seq_printf(s, "discarded pages count: %llu\n", d->discard_page_count);
seq_puts(s, "\n");
seq_printf(s, "total pages: %u\n", pages);
seq_printf(s, "pages mapped: %u\n", mapped);
return 0;
}
static int mtdswap_open(struct inode *inode, struct file *file)
{
return single_open(file, mtdswap_show, inode->i_private);
}
static const struct file_operations mtdswap_fops = {
.open = mtdswap_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
static int mtdswap_add_debugfs(struct mtdswap_dev *d)
{
struct gendisk *gd = d->mbd_dev->disk;
struct device *dev = disk_to_dev(gd);
struct dentry *root;
struct dentry *dent;
root = debugfs_create_dir(gd->disk_name, NULL);
if (IS_ERR(root))
return 0;
if (!root) {
dev_err(dev, "failed to initialize debugfs\n");
return -1;
}
d->debugfs_root = root;
dent = debugfs_create_file("stats", S_IRUSR, root, d,
&mtdswap_fops);
if (!dent) {
dev_err(d->dev, "debugfs_create_file failed\n");
debugfs_remove_recursive(root);
d->debugfs_root = NULL;
return -1;
}
return 0;
}
static int mtdswap_init(struct mtdswap_dev *d, unsigned int eblocks,
unsigned int spare_cnt)
{
struct mtd_info *mtd = d->mbd_dev->mtd;
unsigned int i, eblk_bytes, pages, blocks;
int ret = -ENOMEM;
d->mtd = mtd;
d->eblks = eblocks;
d->spare_eblks = spare_cnt;
d->pages_per_eblk = mtd->erasesize >> PAGE_SHIFT;
pages = d->mbd_dev->size;
blocks = eblocks * d->pages_per_eblk;
for (i = 0; i < MTDSWAP_TREE_CNT; i++)
d->trees[i].root = RB_ROOT;
d->page_data = vmalloc(sizeof(int)*pages);
if (!d->page_data)
goto page_data_fail;
d->revmap = vmalloc(sizeof(int)*blocks);
if (!d->revmap)
goto revmap_fail;
eblk_bytes = sizeof(struct swap_eb)*d->eblks;
d->eb_data = vzalloc(eblk_bytes);
if (!d->eb_data)
goto eb_data_fail;
for (i = 0; i < pages; i++)
d->page_data[i] = BLOCK_UNDEF;
for (i = 0; i < blocks; i++)
d->revmap[i] = PAGE_UNDEF;
d->page_buf = kmalloc(PAGE_SIZE, GFP_KERNEL);
if (!d->page_buf)
goto page_buf_fail;
d->oob_buf = kmalloc(2 * mtd->oobavail, GFP_KERNEL);
if (!d->oob_buf)
goto oob_buf_fail;
mtdswap_scan_eblks(d);
return 0;
oob_buf_fail:
kfree(d->page_buf);
page_buf_fail:
vfree(d->eb_data);
eb_data_fail:
vfree(d->revmap);
revmap_fail:
vfree(d->page_data);
page_data_fail:
printk(KERN_ERR "%s: init failed (%d)\n", MTDSWAP_PREFIX, ret);
return ret;
}
static void mtdswap_add_mtd(struct mtd_blktrans_ops *tr, struct mtd_info *mtd)
{
struct mtdswap_dev *d;
struct mtd_blktrans_dev *mbd_dev;
char *parts;
char *this_opt;
unsigned long part;
unsigned int eblocks, eavailable, bad_blocks, spare_cnt;
uint64_t swap_size, use_size, size_limit;
int ret;
parts = &partitions[0];
if (!*parts)
return;
while ((this_opt = strsep(&parts, ",")) != NULL) {
if (kstrtoul(this_opt, 0, &part) < 0)
return;
if (mtd->index == part)
break;
}
if (mtd->index != part)
return;
if (mtd->erasesize < PAGE_SIZE || mtd->erasesize % PAGE_SIZE) {
printk(KERN_ERR "%s: Erase size %u not multiple of PAGE_SIZE "
"%lu\n", MTDSWAP_PREFIX, mtd->erasesize, PAGE_SIZE);
return;
}
if (PAGE_SIZE % mtd->writesize || mtd->writesize > PAGE_SIZE) {
printk(KERN_ERR "%s: PAGE_SIZE %lu not multiple of write size"
" %u\n", MTDSWAP_PREFIX, PAGE_SIZE, mtd->writesize);
return;
}
if (!mtd->oobsize || mtd->oobavail < MTDSWAP_OOBSIZE) {
printk(KERN_ERR "%s: Not enough free bytes in OOB, "
"%d available, %zu needed.\n",
MTDSWAP_PREFIX, mtd->oobavail, MTDSWAP_OOBSIZE);
return;
}
if (spare_eblocks > 100)
spare_eblocks = 100;
use_size = mtd->size;
size_limit = (uint64_t) BLOCK_MAX * PAGE_SIZE;
if (mtd->size > size_limit) {
printk(KERN_WARNING "%s: Device too large. Limiting size to "
"%llu bytes\n", MTDSWAP_PREFIX, size_limit);
use_size = size_limit;
}
eblocks = mtd_div_by_eb(use_size, mtd);
use_size = (uint64_t)eblocks * mtd->erasesize;
bad_blocks = mtdswap_badblocks(mtd, use_size);
eavailable = eblocks - bad_blocks;
if (eavailable < MIN_ERASE_BLOCKS) {
printk(KERN_ERR "%s: Not enough erase blocks. %u available, "
"%d needed\n", MTDSWAP_PREFIX, eavailable,
MIN_ERASE_BLOCKS);
return;
}
spare_cnt = div_u64((uint64_t)eavailable * spare_eblocks, 100);
if (spare_cnt < MIN_SPARE_EBLOCKS)
spare_cnt = MIN_SPARE_EBLOCKS;
if (spare_cnt > eavailable - 1)
spare_cnt = eavailable - 1;
swap_size = (uint64_t)(eavailable - spare_cnt) * mtd->erasesize +
(header ? PAGE_SIZE : 0);
printk(KERN_INFO "%s: Enabling MTD swap on device %lu, size %llu KB, "
"%u spare, %u bad blocks\n",
MTDSWAP_PREFIX, part, swap_size / 1024, spare_cnt, bad_blocks);
d = kzalloc(sizeof(struct mtdswap_dev), GFP_KERNEL);
if (!d)
return;
mbd_dev = kzalloc(sizeof(struct mtd_blktrans_dev), GFP_KERNEL);
if (!mbd_dev) {
kfree(d);
return;
}
d->mbd_dev = mbd_dev;
mbd_dev->priv = d;
mbd_dev->mtd = mtd;
mbd_dev->devnum = mtd->index;
mbd_dev->size = swap_size >> PAGE_SHIFT;
mbd_dev->tr = tr;
if (!(mtd->flags & MTD_WRITEABLE))
mbd_dev->readonly = 1;
if (mtdswap_init(d, eblocks, spare_cnt) < 0)
goto init_failed;
if (add_mtd_blktrans_dev(mbd_dev) < 0)
goto cleanup;
d->dev = disk_to_dev(mbd_dev->disk);
ret = mtdswap_add_debugfs(d);
if (ret < 0)
goto debugfs_failed;
return;
debugfs_failed:
del_mtd_blktrans_dev(mbd_dev);
cleanup:
mtdswap_cleanup(d);
init_failed:
kfree(mbd_dev);
kfree(d);
}
static void mtdswap_remove_dev(struct mtd_blktrans_dev *dev)
{
struct mtdswap_dev *d = MTDSWAP_MBD_TO_MTDSWAP(dev);
debugfs_remove_recursive(d->debugfs_root);
del_mtd_blktrans_dev(dev);
mtdswap_cleanup(d);
kfree(d);
}
static struct mtd_blktrans_ops mtdswap_ops = {
.name = "mtdswap",
.major = 0,
.part_bits = 0,
.blksize = PAGE_SIZE,
.flush = mtdswap_flush,
.readsect = mtdswap_readsect,
.writesect = mtdswap_writesect,
.discard = mtdswap_discard,
.background = mtdswap_background,
.add_mtd = mtdswap_add_mtd,
.remove_dev = mtdswap_remove_dev,
.owner = THIS_MODULE,
};
static int __init mtdswap_modinit(void)
{
return register_mtd_blktrans(&mtdswap_ops);
}
static void __exit mtdswap_modexit(void)
{
deregister_mtd_blktrans(&mtdswap_ops);
}
module_init(mtdswap_modinit);
module_exit(mtdswap_modexit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Jarkko Lavinen <[email protected]>");
MODULE_DESCRIPTION("Block device access to an MTD suitable for using as "
"swap space");
| null | null | null | null | 105,762 |
58,000 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 58,000 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#ifndef CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_SETTINGS_SERVICE_H_
#define CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_SETTINGS_SERVICE_H_
#include <memory>
#include <string>
#include <vector>
#include "base/callback.h"
#include "base/compiler_specific.h"
#include "base/containers/circular_deque.h"
#include "base/macros.h"
#include "base/memory/linked_ptr.h"
#include "base/memory/ref_counted.h"
#include "base/observer_list.h"
#include "chromeos/dbus/session_manager_client.h"
#include "components/ownership/owner_settings_service.h"
#include "components/policy/core/common/cloud/cloud_policy_constants.h"
#include "components/policy/core/common/cloud/cloud_policy_validator.h"
#include "components/policy/proto/chrome_device_policy.pb.h"
#include "components/policy/proto/device_management_backend.pb.h"
#include "crypto/scoped_nss_types.h"
namespace ownership {
class OwnerKeyUtil;
class PublicKey;
}
namespace policy {
namespace off_hours {
class DeviceOffHoursController;
} // namespace off_hours
} // namespace policy
namespace chromeos {
class SessionManagerOperation;
// Deals with the low-level interface to Chrome OS device settings. Device
// settings are stored in a protobuf that's protected by a cryptographic
// signature generated by a key in the device owner's possession. Key and
// settings are brokered by the session_manager daemon.
//
// The purpose of DeviceSettingsService is to keep track of the current key and
// settings blob. For reading and writing device settings, use CrosSettings
// instead, which provides a high-level interface that allows for manipulation
// of individual settings.
//
// DeviceSettingsService generates notifications for key and policy update
// events so interested parties can reload state as appropriate.
class DeviceSettingsService : public SessionManagerClient::Observer {
public:
// Indicates ownership status of the device (listed in upgrade order).
enum OwnershipStatus {
OWNERSHIP_UNKNOWN = 0,
// Not yet owned.
OWNERSHIP_NONE,
// Either consumer ownership, cloud management or Active Directory
// management.
OWNERSHIP_TAKEN
};
typedef base::Callback<void(OwnershipStatus)> OwnershipStatusCallback;
// Status codes for Load() and Store().
enum Status {
STORE_SUCCESS,
STORE_KEY_UNAVAILABLE, // Owner key not yet configured.
STORE_OPERATION_FAILED, // IPC to session_manager daemon failed.
STORE_NO_POLICY, // No settings blob present.
STORE_INVALID_POLICY, // Invalid settings blob (proto parse failed).
STORE_VALIDATION_ERROR, // Policy validation failure.
};
// Observer interface.
class Observer {
public:
virtual ~Observer();
// Indicates device ownership status changes. This is triggered upon every
// browser start since the transition from uninitialized (OWNERSHIP_UNKNOWN)
// to initialized (either of OWNERSHIP_{NONE,TAKEN}) also counts as an
// ownership change.
virtual void OwnershipStatusChanged();
// Gets called after updates to the device settings.
virtual void DeviceSettingsUpdated();
virtual void OnDeviceSettingsServiceShutdown();
};
// Manage singleton instance.
static void Initialize();
static bool IsInitialized();
static void Shutdown();
static DeviceSettingsService* Get();
// Creates a device settings service instance. This is meant for unit tests,
// production code uses the singleton returned by Get() above.
DeviceSettingsService();
~DeviceSettingsService() override;
// To be called on startup once threads are initialized and D-Bus is ready.
void SetSessionManager(SessionManagerClient* session_manager_client,
scoped_refptr<ownership::OwnerKeyUtil> owner_key_util);
// Prevents the service from making further calls to session_manager_client
// and stops any pending operations.
void UnsetSessionManager();
// Must only be used with a |device_mode| that has been read and verified by
// the InstallAttributes class.
void SetDeviceMode(policy::DeviceMode device_mode);
const enterprise_management::PolicyData* policy_data() const {
return policy_data_.get();
}
// Returns the currently active device settings. Returns nullptr if the device
// settings have not been retrieved from session_manager yet.
const enterprise_management::ChromeDeviceSettingsProto*
device_settings() const {
return device_settings_.get();
}
// Returns the currently used owner key.
scoped_refptr<ownership::PublicKey> GetPublicKey();
// Returns the status generated by the *last operation*.
// WARNING: It is not correct to take this method as an indication of whether
// DeviceSettingsService contains valid device settings. In order to answer
// that question, simply check whether device_settings() is different from
// nullptr.
Status status() const { return store_status_; }
// Returns the currently device off hours controller. The returned pointer is
// guaranteed to be non-null.
policy::off_hours::DeviceOffHoursController* device_off_hours_controller()
const {
return device_off_hours_controller_.get();
}
void SetDeviceOffHoursControllerForTesting(
std::unique_ptr<policy::off_hours::DeviceOffHoursController> controller);
// Triggers an attempt to pull the public half of the owner key from disk and
// load the device settings.
void Load();
// Synchronously pulls the public key and loads the device settings.
void LoadImmediately();
// Stores a policy blob to session_manager. The result of the operation is
// reported through |callback|. If successful, the updated device settings are
// present in policy_data() and device_settings() when the callback runs.
void Store(std::unique_ptr<enterprise_management::PolicyFetchResponse> policy,
const base::Closure& callback);
// Returns the ownership status. May return OWNERSHIP_UNKNOWN if the disk
// hasn't been checked yet.
OwnershipStatus GetOwnershipStatus();
// Determines the ownership status and reports the result to |callback|. This
// is guaranteed to never return OWNERSHIP_UNKNOWN.
void GetOwnershipStatusAsync(const OwnershipStatusCallback& callback);
// Checks whether we have the private owner key.
//
// DEPRECATED (ygorshenin@, crbug.com/433840): this method should
// not be used since private key is a profile-specific resource and
// should be checked and used in a profile-aware manner, through
// OwnerSettingsService.
bool HasPrivateOwnerKey();
// Sets the identity of the user that's interacting with the service. This is
// relevant only for writing settings through SignAndStore().
//
// TODO (ygorshenin@, crbug.com/433840): get rid of the method when
// write path for device settings will be removed from
// DeviceSettingsProvider and all existing clients will be switched
// to OwnerSettingsServiceChromeOS.
void InitOwner(const std::string& username,
const base::WeakPtr<ownership::OwnerSettingsService>&
owner_settings_service);
const std::string& GetUsername() const;
ownership::OwnerSettingsService* GetOwnerSettingsService() const;
// Mark that the device will establish consumer ownership. If the flag is set
// and ownership is not taken, policy reload will be deferred until InitOwner
// is called. So that the ownership status is flipped after the private part
// of owner is fully loaded.
void MarkWillEstablishConsumerOwnership();
// Adds an observer.
void AddObserver(Observer* observer);
// Removes an observer.
void RemoveObserver(Observer* observer);
// SessionManagerClient::Observer:
void OwnerKeySet(bool success) override;
void PropertyChangeComplete(bool success) override;
private:
friend class OwnerSettingsServiceChromeOS;
// Enqueues a new operation. Takes ownership of |operation| and starts it
// right away if there is no active operation currently.
void Enqueue(const linked_ptr<SessionManagerOperation>& operation);
// Enqueues a load operation.
void EnqueueLoad(bool request_key_load);
// Makes sure there's a reload operation so changes to the settings (and key,
// in case |request_key_load| is set) are getting picked up.
void EnsureReload(bool request_key_load);
// Runs the next pending operation.
void StartNextOperation();
// Updates status, policy data and owner key from a finished operation.
void HandleCompletedOperation(const base::Closure& callback,
SessionManagerOperation* operation,
Status status);
// Same as HandleCompletedOperation(), but also starts the next pending
// operation if available.
void HandleCompletedAsyncOperation(const base::Closure& callback,
SessionManagerOperation* operation,
Status status);
// Run OwnershipStatusChanged() for observers.
void NotifyOwnershipStatusChanged() const;
// Run DeviceSettingsUpdated() for observers.
void NotifyDeviceSettingsUpdated() const;
// Processes pending callbacks from GetOwnershipStatusAsync().
void RunPendingOwnershipStatusCallbacks();
SessionManagerClient* session_manager_client_ = nullptr;
scoped_refptr<ownership::OwnerKeyUtil> owner_key_util_;
Status store_status_ = STORE_SUCCESS;
std::vector<OwnershipStatusCallback> pending_ownership_status_callbacks_;
std::string username_;
scoped_refptr<ownership::PublicKey> public_key_;
base::WeakPtr<ownership::OwnerSettingsService> owner_settings_service_;
// Ownership status before the current session manager operation.
OwnershipStatus previous_ownership_status_ = OWNERSHIP_UNKNOWN;
std::unique_ptr<enterprise_management::PolicyData> policy_data_;
std::unique_ptr<enterprise_management::ChromeDeviceSettingsProto>
device_settings_;
policy::DeviceMode device_mode_ = policy::DEVICE_MODE_PENDING;
// The queue of pending operations. The first operation on the queue is
// currently active; it gets removed and destroyed once it completes.
base::circular_deque<linked_ptr<SessionManagerOperation>> pending_operations_;
base::ObserverList<Observer> observers_;
// Whether the device will be establishing consumer ownership.
bool will_establish_consumer_ownership_ = false;
std::unique_ptr<policy::off_hours::DeviceOffHoursController>
device_off_hours_controller_;
base::WeakPtrFactory<DeviceSettingsService> weak_factory_{this};
DISALLOW_COPY_AND_ASSIGN(DeviceSettingsService);
};
// Helper class for tests. Initializes the DeviceSettingsService singleton on
// construction and tears it down again on destruction.
class ScopedTestDeviceSettingsService {
public:
ScopedTestDeviceSettingsService();
~ScopedTestDeviceSettingsService();
private:
DISALLOW_COPY_AND_ASSIGN(ScopedTestDeviceSettingsService);
};
} // namespace chromeos
#endif // CHROME_BROWSER_CHROMEOS_SETTINGS_DEVICE_SETTINGS_SERVICE_H_
| null | null | null | null | 54,863 |
66,526 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 66,526 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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/policy/local_sync_policy_handler.h"
#include <memory>
#include "base/files/file_path.h"
#include "base/values.h"
#include "chrome/browser/policy/policy_path_parser.h"
#include "components/policy/core/common/policy_map.h"
#include "components/policy/policy_constants.h"
#include "components/prefs/pref_value_map.h"
#include "components/sync/base/pref_names.h"
namespace policy {
LocalSyncPolicyHandler::LocalSyncPolicyHandler()
: TypeCheckingPolicyHandler(key::kRoamingProfileLocation,
base::Value::Type::STRING) {}
LocalSyncPolicyHandler::~LocalSyncPolicyHandler() {}
void LocalSyncPolicyHandler::ApplyPolicySettings(const PolicyMap& policies,
PrefValueMap* prefs) {
const base::Value* value = policies.GetValue(policy_name());
base::FilePath::StringType string_value;
if (value && value->GetAsString(&string_value)) {
base::FilePath::StringType expanded_value =
policy::path_parser::ExpandPathVariables(string_value);
prefs->SetValue(syncer::prefs::kLocalSyncBackendDir,
std::make_unique<base::Value>(expanded_value));
}
}
} // namespace policy
| null | null | null | null | 63,389 |
7,496 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 172,491 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
#include <linux/string.h>
#include <linux/export.h>
#undef memcpy
#undef memset
__visible void *memcpy(void *to, const void *from, size_t n)
{
#ifdef CONFIG_X86_USE_3DNOW
return __memcpy3d(to, from, n);
#else
return __memcpy(to, from, n);
#endif
}
EXPORT_SYMBOL(memcpy);
__visible void *memset(void *s, int c, size_t count)
{
return __memset(s, c, count);
}
EXPORT_SYMBOL(memset);
__visible void *memmove(void *dest, const void *src, size_t n)
{
int d0,d1,d2,d3,d4,d5;
char *ret = dest;
__asm__ __volatile__(
/* Handle more 16 bytes in loop */
"cmp $0x10, %0\n\t"
"jb 1f\n\t"
/* Decide forward/backward copy mode */
"cmp %2, %1\n\t"
"jb 2f\n\t"
/*
* movs instruction have many startup latency
* so we handle small size by general register.
*/
"cmp $680, %0\n\t"
"jb 3f\n\t"
/*
* movs instruction is only good for aligned case.
*/
"mov %1, %3\n\t"
"xor %2, %3\n\t"
"and $0xff, %3\n\t"
"jz 4f\n\t"
"3:\n\t"
"sub $0x10, %0\n\t"
/*
* We gobble 16 bytes forward in each loop.
*/
"3:\n\t"
"sub $0x10, %0\n\t"
"mov 0*4(%1), %3\n\t"
"mov 1*4(%1), %4\n\t"
"mov %3, 0*4(%2)\n\t"
"mov %4, 1*4(%2)\n\t"
"mov 2*4(%1), %3\n\t"
"mov 3*4(%1), %4\n\t"
"mov %3, 2*4(%2)\n\t"
"mov %4, 3*4(%2)\n\t"
"lea 0x10(%1), %1\n\t"
"lea 0x10(%2), %2\n\t"
"jae 3b\n\t"
"add $0x10, %0\n\t"
"jmp 1f\n\t"
/*
* Handle data forward by movs.
*/
".p2align 4\n\t"
"4:\n\t"
"mov -4(%1, %0), %3\n\t"
"lea -4(%2, %0), %4\n\t"
"shr $2, %0\n\t"
"rep movsl\n\t"
"mov %3, (%4)\n\t"
"jmp 11f\n\t"
/*
* Handle data backward by movs.
*/
".p2align 4\n\t"
"6:\n\t"
"mov (%1), %3\n\t"
"mov %2, %4\n\t"
"lea -4(%1, %0), %1\n\t"
"lea -4(%2, %0), %2\n\t"
"shr $2, %0\n\t"
"std\n\t"
"rep movsl\n\t"
"mov %3,(%4)\n\t"
"cld\n\t"
"jmp 11f\n\t"
/*
* Start to prepare for backward copy.
*/
".p2align 4\n\t"
"2:\n\t"
"cmp $680, %0\n\t"
"jb 5f\n\t"
"mov %1, %3\n\t"
"xor %2, %3\n\t"
"and $0xff, %3\n\t"
"jz 6b\n\t"
/*
* Calculate copy position to tail.
*/
"5:\n\t"
"add %0, %1\n\t"
"add %0, %2\n\t"
"sub $0x10, %0\n\t"
/*
* We gobble 16 bytes backward in each loop.
*/
"7:\n\t"
"sub $0x10, %0\n\t"
"mov -1*4(%1), %3\n\t"
"mov -2*4(%1), %4\n\t"
"mov %3, -1*4(%2)\n\t"
"mov %4, -2*4(%2)\n\t"
"mov -3*4(%1), %3\n\t"
"mov -4*4(%1), %4\n\t"
"mov %3, -3*4(%2)\n\t"
"mov %4, -4*4(%2)\n\t"
"lea -0x10(%1), %1\n\t"
"lea -0x10(%2), %2\n\t"
"jae 7b\n\t"
/*
* Calculate copy position to head.
*/
"add $0x10, %0\n\t"
"sub %0, %1\n\t"
"sub %0, %2\n\t"
/*
* Move data from 8 bytes to 15 bytes.
*/
".p2align 4\n\t"
"1:\n\t"
"cmp $8, %0\n\t"
"jb 8f\n\t"
"mov 0*4(%1), %3\n\t"
"mov 1*4(%1), %4\n\t"
"mov -2*4(%1, %0), %5\n\t"
"mov -1*4(%1, %0), %1\n\t"
"mov %3, 0*4(%2)\n\t"
"mov %4, 1*4(%2)\n\t"
"mov %5, -2*4(%2, %0)\n\t"
"mov %1, -1*4(%2, %0)\n\t"
"jmp 11f\n\t"
/*
* Move data from 4 bytes to 7 bytes.
*/
".p2align 4\n\t"
"8:\n\t"
"cmp $4, %0\n\t"
"jb 9f\n\t"
"mov 0*4(%1), %3\n\t"
"mov -1*4(%1, %0), %4\n\t"
"mov %3, 0*4(%2)\n\t"
"mov %4, -1*4(%2, %0)\n\t"
"jmp 11f\n\t"
/*
* Move data from 2 bytes to 3 bytes.
*/
".p2align 4\n\t"
"9:\n\t"
"cmp $2, %0\n\t"
"jb 10f\n\t"
"movw 0*2(%1), %%dx\n\t"
"movw -1*2(%1, %0), %%bx\n\t"
"movw %%dx, 0*2(%2)\n\t"
"movw %%bx, -1*2(%2, %0)\n\t"
"jmp 11f\n\t"
/*
* Move data for 1 byte.
*/
".p2align 4\n\t"
"10:\n\t"
"cmp $1, %0\n\t"
"jb 11f\n\t"
"movb (%1), %%cl\n\t"
"movb %%cl, (%2)\n\t"
".p2align 4\n\t"
"11:"
: "=&c" (d0), "=&S" (d1), "=&D" (d2),
"=r" (d3),"=r" (d4), "=r"(d5)
:"0" (n),
"1" (src),
"2" (dest)
:"memory");
return ret;
}
EXPORT_SYMBOL(memmove);
| null | null | null | null | 80,838 |
138 |
2
|
train_val
|
f6d8bd051c391c1c0458a30b2a7abcd939329259
| 165,133 |
linux
| 1 |
https://github.com/torvalds/linux
|
2011-04-28 13:16:35-07:00
|
static struct ip_options *ip_options_get_alloc(const int optlen)
{
return kzalloc(sizeof(struct ip_options) + ((optlen + 3) & ~3),
GFP_KERNEL);
}
|
CVE-2012-3552
|
CWE-362
|
https://github.com/torvalds/linux/commit/f6d8bd051c391c1c0458a30b2a7abcd939329259
|
High
| 3,027 |
54,385 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 54,385 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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/test/nacl/nacl_browsertest_util.h"
#include <stdlib.h>
#include "base/command_line.h"
#include "base/json/json_reader.h"
#include "base/macros.h"
#include "base/path_service.h"
#include "base/values.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/test/base/ui_test_utils.h"
#include "components/nacl/common/nacl_switches.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/browser/web_contents.h"
#include "content/public/common/webplugininfo.h"
#include "extensions/common/switches.h"
typedef content::TestMessageHandler::MessageResponse MessageResponse;
MessageResponse StructuredMessageHandler::HandleMessage(
const std::string& json) {
base::JSONReader reader(base::JSON_ALLOW_TRAILING_COMMAS);
// Automation messages are stringified before they are sent because the
// automation channel cannot handle arbitrary objects. This means we
// need to decode the json twice to get the original message.
std::unique_ptr<base::Value> value = reader.ReadToValue(json);
if (!value.get())
return InternalError("Could parse automation JSON: " + json +
" because " + reader.GetErrorMessage());
std::string temp;
if (!value->GetAsString(&temp))
return InternalError("Message was not a string: " + json);
value = reader.ReadToValue(temp);
if (!value.get())
return InternalError("Could not parse message JSON: " + temp +
" because " + reader.GetErrorMessage());
base::DictionaryValue* msg;
if (!value->GetAsDictionary(&msg))
return InternalError("Message was not an object: " + temp);
std::string type;
if (!msg->GetString("type", &type))
return MissingField("unknown", "type");
return HandleStructuredMessage(type, msg);
}
MessageResponse StructuredMessageHandler::MissingField(
const std::string& type,
const std::string& field) {
return InternalError(type + " message did not have field: " + field);
}
MessageResponse StructuredMessageHandler::InternalError(
const std::string& reason) {
SetError(reason);
return DONE;
}
LoadTestMessageHandler::LoadTestMessageHandler()
: test_passed_(false) {
}
void LoadTestMessageHandler::Log(const std::string& type,
const std::string& message) {
// TODO(ncbray) better logging.
LOG(INFO) << type << " " << message;
}
MessageResponse LoadTestMessageHandler::HandleStructuredMessage(
const std::string& type,
base::DictionaryValue* msg) {
if (type == "Log") {
std::string message;
if (!msg->GetString("message", &message))
return MissingField(type, "message");
Log("LOG", message);
return CONTINUE;
} else if (type == "Shutdown") {
std::string message;
if (!msg->GetString("message", &message))
return MissingField(type, "message");
if (!msg->GetBoolean("passed", &test_passed_))
return MissingField(type, "passed");
Log("SHUTDOWN", message);
return DONE;
} else {
return InternalError("Unknown message type: " + type);
}
}
// A message handler for nacl_integration tests ported to be browser_tests.
// nacl_integration tests report to their test jig using a series of RPC calls
// that are encoded as URL requests. When these tests run as browser_tests,
// they make the same RPC requests, but use the automation channel instead of
// URL requests. This message handler decodes and responds to these requests.
class NaClIntegrationMessageHandler : public StructuredMessageHandler {
public:
NaClIntegrationMessageHandler();
void Log(const std::string& message);
MessageResponse HandleStructuredMessage(const std::string& type,
base::DictionaryValue* msg) override;
bool test_passed() const {
return test_passed_;
}
private:
bool test_passed_;
DISALLOW_COPY_AND_ASSIGN(NaClIntegrationMessageHandler);
};
NaClIntegrationMessageHandler::NaClIntegrationMessageHandler()
: test_passed_(false) {
}
void NaClIntegrationMessageHandler::Log(const std::string& message) {
// TODO(ncbray) better logging.
LOG(INFO) << "|||| " << message;
}
MessageResponse NaClIntegrationMessageHandler::HandleStructuredMessage(
const std::string& type,
base::DictionaryValue* msg) {
if (type == "TestLog") {
std::string message;
if (!msg->GetString("message", &message))
return MissingField(type, "message");
Log(message);
return CONTINUE;
} else if (type == "Shutdown") {
std::string message;
if (!msg->GetString("message", &message))
return MissingField(type, "message");
if (!msg->GetBoolean("passed", &test_passed_))
return MissingField(type, "passed");
Log(message);
return DONE;
} else if (type == "Ping") {
return CONTINUE;
} else if (type == "JavaScriptIsAlive") {
return CONTINUE;
} else {
return InternalError("Unknown message type: " + type);
}
}
// NaCl browser tests serve files out of the build directory because nexes and
// pexes are artifacts of the build. To keep things tidy, all test data is kept
// in a subdirectory. Several variants of a test may be run, for example when
// linked against newlib and when linked against glibc. These variants are kept
// in different subdirectories. For example, the build directory will look
// something like this on Linux:
// out/
// Release/
// nacl_test_data/
// newlib/
// glibc/
// pnacl/
static bool GetNaClVariantRoot(const base::FilePath::StringType& variant,
base::FilePath* document_root) {
if (!ui_test_utils::GetRelativeBuildDirectory(document_root))
return false;
*document_root = document_root->Append(FILE_PATH_LITERAL("nacl_test_data"));
*document_root = document_root->Append(variant);
return true;
}
static void AddPnaclParm(const base::FilePath::StringType& url,
base::FilePath::StringType* url_with_parm) {
if (url.find(FILE_PATH_LITERAL("?")) == base::FilePath::StringType::npos) {
*url_with_parm = url + FILE_PATH_LITERAL("?pnacl=1");
} else {
*url_with_parm = url + FILE_PATH_LITERAL("&pnacl=1");
}
}
NaClBrowserTestBase::NaClBrowserTestBase() {
}
NaClBrowserTestBase::~NaClBrowserTestBase() {
}
void NaClBrowserTestBase::SetUpCommandLine(base::CommandLine* command_line) {
command_line->AppendSwitch(switches::kEnableNaCl);
}
void NaClBrowserTestBase::SetUpOnMainThread() {
ASSERT_TRUE(StartTestServer()) << "Cannot start test server.";
}
bool NaClBrowserTestBase::GetDocumentRoot(base::FilePath* document_root) {
return GetNaClVariantRoot(Variant(), document_root);
}
bool NaClBrowserTestBase::IsAPnaclTest() {
return false;
}
GURL NaClBrowserTestBase::TestURL(
const base::FilePath::StringType& url_fragment) {
base::FilePath expanded_url = base::FilePath(FILE_PATH_LITERAL("/"));
expanded_url = expanded_url.Append(url_fragment);
return test_server_->GetURL(expanded_url.MaybeAsASCII());
}
bool NaClBrowserTestBase::RunJavascriptTest(
const GURL& url,
content::TestMessageHandler* handler) {
content::JavascriptTestObserver observer(
browser()->tab_strip_model()->GetActiveWebContents(),
handler);
ui_test_utils::NavigateToURL(browser(), url);
return observer.Run();
}
void NaClBrowserTestBase::RunLoadTest(
const base::FilePath::StringType& test_file) {
LoadTestMessageHandler handler;
base::FilePath::StringType test_file_with_pnacl = test_file;
if (IsAPnaclTest()) {
AddPnaclParm(test_file, &test_file_with_pnacl);
}
base::FilePath::StringType test_file_with_both = test_file_with_pnacl;
bool ok = RunJavascriptTest(TestURL(test_file_with_both), &handler);
ASSERT_TRUE(ok) << handler.error_message();
ASSERT_TRUE(handler.test_passed()) << "Test failed.";
}
void NaClBrowserTestBase::RunNaClIntegrationTest(
const base::FilePath::StringType& url_fragment, bool full_url) {
NaClIntegrationMessageHandler handler;
base::FilePath::StringType url_fragment_with_pnacl = url_fragment;
if (IsAPnaclTest()) {
AddPnaclParm(url_fragment, &url_fragment_with_pnacl);
}
base::FilePath::StringType url_fragment_with_both = url_fragment_with_pnacl;
bool ok = RunJavascriptTest(full_url
? GURL(url_fragment_with_both)
: TestURL(url_fragment_with_both),
&handler);
ASSERT_TRUE(ok) << handler.error_message();
ASSERT_TRUE(handler.test_passed()) << "Test failed.";
}
bool NaClBrowserTestBase::StartTestServer() {
// Launch the web server.
base::FilePath document_root;
if (!GetDocumentRoot(&document_root))
return false;
test_server_.reset(new net::EmbeddedTestServer);
test_server_->ServeFilesFromSourceDirectory(document_root);
return test_server_->Start();
}
base::FilePath::StringType NaClBrowserTestNewlib::Variant() {
return FILE_PATH_LITERAL("newlib");
}
base::FilePath::StringType NaClBrowserTestGLibc::Variant() {
return FILE_PATH_LITERAL("glibc");
}
base::FilePath::StringType NaClBrowserTestPnacl::Variant() {
return FILE_PATH_LITERAL("pnacl");
}
bool NaClBrowserTestPnacl::IsAPnaclTest() {
return true;
}
void NaClBrowserTestPnaclSubzero::SetUpCommandLine(
base::CommandLine* command_line) {
NaClBrowserTestPnacl::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kForcePNaClSubzero);
}
base::FilePath::StringType NaClBrowserTestNonSfiMode::Variant() {
return FILE_PATH_LITERAL("libc-free");
}
void NaClBrowserTestNonSfiMode::SetUpCommandLine(
base::CommandLine* command_line) {
NaClBrowserTestBase::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableNaClNonSfiMode);
}
base::FilePath::StringType NaClBrowserTestStatic::Variant() {
return FILE_PATH_LITERAL("static");
}
bool NaClBrowserTestStatic::GetDocumentRoot(base::FilePath* document_root) {
*document_root = base::FilePath(FILE_PATH_LITERAL("chrome/test/data/nacl"));
return true;
}
base::FilePath::StringType NaClBrowserTestPnaclNonSfi::Variant() {
return FILE_PATH_LITERAL("nonsfi");
}
void NaClBrowserTestPnaclNonSfi::SetUpCommandLine(
base::CommandLine* command_line) {
NaClBrowserTestBase::SetUpCommandLine(command_line);
command_line->AppendSwitch(switches::kEnableNaClNonSfiMode);
}
void NaClBrowserTestNewlibExtension::SetUpCommandLine(
base::CommandLine* command_line) {
NaClBrowserTestBase::SetUpCommandLine(command_line);
base::FilePath src_root;
ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &src_root));
// Extension-based tests should specialize the GetDocumentRoot() / Variant()
// to point at the isolated the test extension directory.
// Otherwise, multiple NaCl extensions tests will end up sharing the
// same directory when loading the extension files.
base::FilePath document_root;
ASSERT_TRUE(GetDocumentRoot(&document_root));
// Document root is relative to source root, and source root may not be CWD.
command_line->AppendSwitchPath(extensions::switches::kLoadExtension,
src_root.Append(document_root));
}
void NaClBrowserTestGLibcExtension::SetUpCommandLine(
base::CommandLine* command_line) {
NaClBrowserTestBase::SetUpCommandLine(command_line);
base::FilePath src_root;
ASSERT_TRUE(PathService::Get(base::DIR_SOURCE_ROOT, &src_root));
// Extension-based tests should specialize the GetDocumentRoot() / Variant()
// to point at the isolated the test extension directory.
// Otherwise, multiple NaCl extensions tests will end up sharing the
// same directory when loading the extension files.
base::FilePath document_root;
ASSERT_TRUE(GetDocumentRoot(&document_root));
// Document root is relative to source root, and source root may not be CWD.
command_line->AppendSwitchPath(extensions::switches::kLoadExtension,
src_root.Append(document_root));
}
| null | null | null | null | 51,248 |
19,113 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 19,113 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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 "components/reading_list/features/reading_list_switches.h"
#include "base/command_line.h"
#include "build/build_config.h"
#include "components/reading_list/features/reading_list_buildflags.h"
namespace reading_list {
namespace switches {
bool IsReadingListEnabled() {
return BUILDFLAG(ENABLE_READING_LIST);
}
} // namespace switches
} // namespace reading_list
| null | null | null | null | 15,976 |
60,996 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 60,996 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 CHROME_BROWSER_ANDROID_COMPOSITOR_LAYER_LAYER_H_
#define CHROME_BROWSER_ANDROID_COMPOSITOR_LAYER_LAYER_H_
#include <memory>
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "cc/layers/layer.h"
#include "cc/paint/filter_operations.h"
#include "ui/gfx/geometry/size.h"
namespace android {
// A simple wrapper for cc::Layer. You can override this to contain
// layers and add functionalities to it.
class Layer : public base::RefCounted<Layer> {
public:
virtual scoped_refptr<cc::Layer> layer() = 0;
protected:
Layer() {}
virtual ~Layer() {}
private:
friend class base::RefCounted<Layer>;
DISALLOW_COPY_AND_ASSIGN(Layer);
};
} // namespace android
#endif // CHROME_BROWSER_ANDROID_COMPOSITOR_LAYER_LAYER_H_
| null | null | null | null | 57,859 |
62,485 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 62,485 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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/ui/hung_plugin_tab_helper.h"
#include <memory>
#include "base/bind.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/process/process.h"
#include "build/build_config.h"
#include "chrome/browser/infobars/infobar_service.h"
#include "chrome/browser/plugins/hung_plugin_infobar_delegate.h"
#include "chrome/common/channel_info.h"
#include "components/infobars/core/infobar.h"
#include "content/public/browser/browser_child_process_host_iterator.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/child_process_data.h"
#include "content/public/browser/plugin_service.h"
#include "content/public/common/process_type.h"
#include "content/public/common/result_codes.h"
#if defined(OS_WIN)
#include "chrome/browser/hang_monitor/hang_crash_dump_win.h"
#endif
namespace {
// Called on the I/O thread to actually kill the plugin with the given child
// ID. We specifically don't want this to be a member function since if the
// user chooses to kill the plugin, we want to kill it even if they close the
// tab first.
//
// Be careful with the child_id. It's supplied by the renderer which might be
// hacked.
void KillPluginOnIOThread(int child_id) {
content::BrowserChildProcessHostIterator iter(
content::PROCESS_TYPE_PPAPI_PLUGIN);
while (!iter.Done()) {
const content::ChildProcessData& data = iter.GetData();
if (data.id == child_id) {
#if defined(OS_WIN)
CrashDumpAndTerminateHungChildProcess(data.handle);
#else
base::Process process =
base::Process::DeprecatedGetProcessFromHandle(data.handle);
process.Terminate(content::RESULT_CODE_HUNG, false);
#endif
break;
}
++iter;
}
// Ignore the case where we didn't find the plugin, it may have terminated
// before this function could run.
}
} // namespace
// HungPluginTabHelper::PluginState -------------------------------------------
// Per-plugin state (since there could be more than one plugin hung). The
// integer key is the child process ID of the plugin process. This maintains
// the state for all plugins on this page that are currently hung, whether or
// not we're currently showing the infobar.
struct HungPluginTabHelper::PluginState {
// Initializes the plugin state to be a hung plugin.
PluginState(const base::FilePath& p, const base::string16& n);
~PluginState();
base::FilePath path;
base::string16 name;
// Possibly-null if we're not showing an infobar right now.
infobars::InfoBar* infobar;
// Time to delay before re-showing the infobar for a hung plugin. This is
// increased each time the user cancels it.
base::TimeDelta next_reshow_delay;
// Handles calling the helper when the infobar should be re-shown.
base::Timer timer;
private:
// Initial delay in seconds before re-showing the hung plugin message.
static const int kInitialReshowDelaySec;
// Since the scope of the timer manages our callback, this struct should
// not be copied.
DISALLOW_COPY_AND_ASSIGN(PluginState);
};
// static
const int HungPluginTabHelper::PluginState::kInitialReshowDelaySec = 10;
HungPluginTabHelper::PluginState::PluginState(const base::FilePath& p,
const base::string16& n)
: path(p),
name(n),
infobar(NULL),
next_reshow_delay(base::TimeDelta::FromSeconds(kInitialReshowDelaySec)),
timer(false, false) {
}
HungPluginTabHelper::PluginState::~PluginState() {
}
// HungPluginTabHelper --------------------------------------------------------
DEFINE_WEB_CONTENTS_USER_DATA_KEY(HungPluginTabHelper);
HungPluginTabHelper::HungPluginTabHelper(content::WebContents* contents)
: content::WebContentsObserver(contents), infobar_observer_(this) {}
HungPluginTabHelper::~HungPluginTabHelper() {
}
void HungPluginTabHelper::PluginCrashed(const base::FilePath& plugin_path,
base::ProcessId plugin_pid) {
// TODO(brettw) ideally this would take the child process ID. When we do this
// for NaCl plugins, we'll want to know exactly which process it was since
// the path won't be useful.
InfoBarService* infobar_service =
InfoBarService::FromWebContents(web_contents());
if (!infobar_service)
return;
// For now, just do a brute-force search to see if we have this plugin. Since
// we'll normally have 0 or 1, this is fast.
for (PluginStateMap::iterator i = hung_plugins_.begin();
i != hung_plugins_.end(); ++i) {
if (i->second->path == plugin_path) {
if (i->second->infobar)
infobar_service->RemoveInfoBar(i->second->infobar);
hung_plugins_.erase(i);
break;
}
}
}
void HungPluginTabHelper::PluginHungStatusChanged(
int plugin_child_id,
const base::FilePath& plugin_path,
bool is_hung) {
InfoBarService* infobar_service =
InfoBarService::FromWebContents(web_contents());
if (!infobar_service)
return;
if (!infobar_observer_.IsObserving(infobar_service))
infobar_observer_.Add(infobar_service);
PluginStateMap::iterator found = hung_plugins_.find(plugin_child_id);
if (found != hung_plugins_.end()) {
if (!is_hung) {
// Hung plugin became un-hung, close the infobar and delete our info.
if (found->second->infobar)
infobar_service->RemoveInfoBar(found->second->infobar);
hung_plugins_.erase(found);
}
return;
}
base::string16 plugin_name =
content::PluginService::GetInstance()->GetPluginDisplayNameByPath(
plugin_path);
linked_ptr<PluginState> state(new PluginState(plugin_path, plugin_name));
hung_plugins_[plugin_child_id] = state;
ShowBar(plugin_child_id, state.get());
}
void HungPluginTabHelper::OnInfoBarRemoved(infobars::InfoBar* infobar,
bool animate) {
for (auto i = hung_plugins_.begin(); i != hung_plugins_.end(); ++i) {
PluginState* state = i->second.get();
if (state->infobar == infobar) {
state->infobar = nullptr;
// Schedule the timer to re-show the infobar if the plugin continues to be
// hung.
state->timer.Start(FROM_HERE, state->next_reshow_delay,
base::Bind(&HungPluginTabHelper::OnReshowTimer,
base::Unretained(this),
i->first));
// Next time we do this, delay it twice as long to avoid being annoying.
state->next_reshow_delay *= 2;
return;
}
}
}
void HungPluginTabHelper::OnManagerShuttingDown(
infobars::InfoBarManager* manager) {
infobar_observer_.Remove(manager);
}
void HungPluginTabHelper::KillPlugin(int child_id) {
PluginStateMap::iterator found = hung_plugins_.find(child_id);
DCHECK(found != hung_plugins_.end());
content::BrowserThread::PostTask(
content::BrowserThread::IO, FROM_HERE,
base::BindOnce(&KillPluginOnIOThread, child_id));
CloseBar(found->second.get());
}
void HungPluginTabHelper::OnReshowTimer(int child_id) {
// The timer should have been cancelled if the record isn't in our map
// anymore.
PluginStateMap::iterator found = hung_plugins_.find(child_id);
DCHECK(found != hung_plugins_.end());
DCHECK(!found->second->infobar);
ShowBar(child_id, found->second.get());
}
void HungPluginTabHelper::ShowBar(int child_id, PluginState* state) {
InfoBarService* infobar_service =
InfoBarService::FromWebContents(web_contents());
if (!infobar_service)
return;
DCHECK(!state->infobar);
state->infobar = HungPluginInfoBarDelegate::Create(infobar_service, this,
child_id, state->name);
}
void HungPluginTabHelper::CloseBar(PluginState* state) {
InfoBarService* infobar_service =
InfoBarService::FromWebContents(web_contents());
if (infobar_service && state->infobar) {
infobar_service->RemoveInfoBar(state->infobar);
state->infobar = NULL;
}
}
| null | null | null | null | 59,348 |
35,491 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 200,486 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Copyright (C) ST-Ericsson SA 2010
*
* License Terms: GNU General Public License, version 2
* Author: Rabin Vincent <[email protected]> for ST-Ericsson
*/
#ifndef __STMPE_H
#define __STMPE_H
#include <linux/device.h>
#include <linux/mfd/core.h>
#include <linux/mfd/stmpe.h>
#include <linux/printk.h>
#include <linux/types.h>
extern const struct dev_pm_ops stmpe_dev_pm_ops;
#ifdef STMPE_DUMP_BYTES
static inline void stmpe_dump_bytes(const char *str, const void *buf,
size_t len)
{
print_hex_dump_bytes(str, DUMP_PREFIX_OFFSET, buf, len);
}
#else
static inline void stmpe_dump_bytes(const char *str, const void *buf,
size_t len)
{
}
#endif
/**
* struct stmpe_variant_block - information about block
* @cell: base mfd cell
* @irq: interrupt number to be added to each IORESOURCE_IRQ
* in the cell
* @block: block id; used for identification with platform data and for
* enable and altfunc callbacks
*/
struct stmpe_variant_block {
const struct mfd_cell *cell;
int irq;
enum stmpe_block block;
};
/**
* struct stmpe_variant_info - variant-specific information
* @name: part name
* @id_val: content of CHIPID register
* @id_mask: bits valid in CHIPID register for comparison with id_val
* @num_gpios: number of GPIOS
* @af_bits: number of bits used to specify the alternate function
* @regs: variant specific registers.
* @blocks: list of blocks present on this device
* @num_blocks: number of blocks present on this device
* @num_irqs: number of internal IRQs available on this device
* @enable: callback to enable the specified blocks.
* Called with the I/O lock held.
* @get_altfunc: callback to get the alternate function number for the
* specific block
* @enable_autosleep: callback to configure autosleep with specified timeout
*/
struct stmpe_variant_info {
const char *name;
u16 id_val;
u16 id_mask;
int num_gpios;
int af_bits;
const u8 *regs;
struct stmpe_variant_block *blocks;
int num_blocks;
int num_irqs;
int (*enable)(struct stmpe *stmpe, unsigned int blocks, bool enable);
int (*get_altfunc)(struct stmpe *stmpe, enum stmpe_block block);
int (*enable_autosleep)(struct stmpe *stmpe, int autosleep_timeout);
};
/**
* struct stmpe_client_info - i2c or spi specific routines/info
* @data: client specific data
* @read_byte: read single byte
* @write_byte: write single byte
* @read_block: read block or multiple bytes
* @write_block: write block or multiple bytes
* @init: client init routine, called during probe
*/
struct stmpe_client_info {
void *data;
int irq;
void *client;
struct device *dev;
int (*read_byte)(struct stmpe *stmpe, u8 reg);
int (*write_byte)(struct stmpe *stmpe, u8 reg, u8 val);
int (*read_block)(struct stmpe *stmpe, u8 reg, u8 len, u8 *values);
int (*write_block)(struct stmpe *stmpe, u8 reg, u8 len,
const u8 *values);
void (*init)(struct stmpe *stmpe);
};
int stmpe_probe(struct stmpe_client_info *ci, enum stmpe_partnum partnum);
int stmpe_remove(struct stmpe *stmpe);
#define STMPE_ICR_LSB_HIGH (1 << 2)
#define STMPE_ICR_LSB_EDGE (1 << 1)
#define STMPE_ICR_LSB_GIM (1 << 0)
#define STMPE_SYS_CTRL_RESET (1 << 7)
#define STMPE_SYS_CTRL_INT_EN (1 << 2)
#define STMPE_SYS_CTRL_INT_HI (1 << 0)
/*
* STMPE801
*/
#define STMPE801_ID 0x0108
#define STMPE801_NR_INTERNAL_IRQS 1
#define STMPE801_REG_CHIP_ID 0x00
#define STMPE801_REG_VERSION_ID 0x02
#define STMPE801_REG_SYS_CTRL 0x04
#define STMPE801_REG_GPIO_INT_EN 0x08
#define STMPE801_REG_GPIO_INT_STA 0x09
#define STMPE801_REG_GPIO_MP_STA 0x10
#define STMPE801_REG_GPIO_SET_PIN 0x11
#define STMPE801_REG_GPIO_DIR 0x12
/*
* STMPE811
*/
#define STMPE811_ID 0x0811
#define STMPE811_IRQ_TOUCH_DET 0
#define STMPE811_IRQ_FIFO_TH 1
#define STMPE811_IRQ_FIFO_OFLOW 2
#define STMPE811_IRQ_FIFO_FULL 3
#define STMPE811_IRQ_FIFO_EMPTY 4
#define STMPE811_IRQ_TEMP_SENS 5
#define STMPE811_IRQ_ADC 6
#define STMPE811_IRQ_GPIOC 7
#define STMPE811_NR_INTERNAL_IRQS 8
#define STMPE811_REG_CHIP_ID 0x00
#define STMPE811_REG_SYS_CTRL 0x03
#define STMPE811_REG_SYS_CTRL2 0x04
#define STMPE811_REG_SPI_CFG 0x08
#define STMPE811_REG_INT_CTRL 0x09
#define STMPE811_REG_INT_EN 0x0A
#define STMPE811_REG_INT_STA 0x0B
#define STMPE811_REG_GPIO_INT_EN 0x0C
#define STMPE811_REG_GPIO_INT_STA 0x0D
#define STMPE811_REG_GPIO_SET_PIN 0x10
#define STMPE811_REG_GPIO_CLR_PIN 0x11
#define STMPE811_REG_GPIO_MP_STA 0x12
#define STMPE811_REG_GPIO_DIR 0x13
#define STMPE811_REG_GPIO_ED 0x14
#define STMPE811_REG_GPIO_RE 0x15
#define STMPE811_REG_GPIO_FE 0x16
#define STMPE811_REG_GPIO_AF 0x17
#define STMPE811_SYS_CTRL_RESET (1 << 1)
#define STMPE811_SYS_CTRL2_ADC_OFF (1 << 0)
#define STMPE811_SYS_CTRL2_TSC_OFF (1 << 1)
#define STMPE811_SYS_CTRL2_GPIO_OFF (1 << 2)
#define STMPE811_SYS_CTRL2_TS_OFF (1 << 3)
/*
* STMPE1600
*/
#define STMPE1600_ID 0x0016
#define STMPE1600_NR_INTERNAL_IRQS 16
#define STMPE1600_REG_CHIP_ID 0x00
#define STMPE1600_REG_SYS_CTRL 0x03
#define STMPE1600_REG_IEGPIOR_LSB 0x08
#define STMPE1600_REG_IEGPIOR_MSB 0x09
#define STMPE1600_REG_ISGPIOR_LSB 0x0A
#define STMPE1600_REG_ISGPIOR_MSB 0x0B
#define STMPE1600_REG_GPMR_LSB 0x10
#define STMPE1600_REG_GPMR_MSB 0x11
#define STMPE1600_REG_GPSR_LSB 0x12
#define STMPE1600_REG_GPSR_MSB 0x13
#define STMPE1600_REG_GPDR_LSB 0x14
#define STMPE1600_REG_GPDR_MSB 0x15
#define STMPE1600_REG_GPPIR_LSB 0x16
#define STMPE1600_REG_GPPIR_MSB 0x17
/*
* STMPE1601
*/
#define STMPE1601_IRQ_GPIOC 8
#define STMPE1601_IRQ_PWM3 7
#define STMPE1601_IRQ_PWM2 6
#define STMPE1601_IRQ_PWM1 5
#define STMPE1601_IRQ_PWM0 4
#define STMPE1601_IRQ_KEYPAD_OVER 2
#define STMPE1601_IRQ_KEYPAD 1
#define STMPE1601_IRQ_WAKEUP 0
#define STMPE1601_NR_INTERNAL_IRQS 9
#define STMPE1601_REG_SYS_CTRL 0x02
#define STMPE1601_REG_SYS_CTRL2 0x03
#define STMPE1601_REG_ICR_MSB 0x10
#define STMPE1601_REG_ICR_LSB 0x11
#define STMPE1601_REG_IER_MSB 0x12
#define STMPE1601_REG_IER_LSB 0x13
#define STMPE1601_REG_ISR_MSB 0x14
#define STMPE1601_REG_ISR_LSB 0x15
#define STMPE1601_REG_INT_EN_GPIO_MASK_MSB 0x16
#define STMPE1601_REG_INT_EN_GPIO_MASK_LSB 0x17
#define STMPE1601_REG_INT_STA_GPIO_MSB 0x18
#define STMPE1601_REG_INT_STA_GPIO_LSB 0x19
#define STMPE1601_REG_CHIP_ID 0x80
#define STMPE1601_REG_GPIO_SET_MSB 0x82
#define STMPE1601_REG_GPIO_SET_LSB 0x83
#define STMPE1601_REG_GPIO_CLR_MSB 0x84
#define STMPE1601_REG_GPIO_CLR_LSB 0x85
#define STMPE1601_REG_GPIO_MP_MSB 0x86
#define STMPE1601_REG_GPIO_MP_LSB 0x87
#define STMPE1601_REG_GPIO_SET_DIR_MSB 0x88
#define STMPE1601_REG_GPIO_SET_DIR_LSB 0x89
#define STMPE1601_REG_GPIO_ED_MSB 0x8A
#define STMPE1601_REG_GPIO_ED_LSB 0x8B
#define STMPE1601_REG_GPIO_RE_MSB 0x8C
#define STMPE1601_REG_GPIO_RE_LSB 0x8D
#define STMPE1601_REG_GPIO_FE_MSB 0x8E
#define STMPE1601_REG_GPIO_FE_LSB 0x8F
#define STMPE1601_REG_GPIO_PU_MSB 0x90
#define STMPE1601_REG_GPIO_PU_LSB 0x91
#define STMPE1601_REG_GPIO_AF_U_MSB 0x92
#define STMPE1601_SYS_CTRL_ENABLE_GPIO (1 << 3)
#define STMPE1601_SYS_CTRL_ENABLE_KPC (1 << 1)
#define STMPE1601_SYS_CTRL_ENABLE_SPWM (1 << 0)
/* The 1601/2403 share the same masks */
#define STMPE1601_AUTOSLEEP_TIMEOUT_MASK (0x7)
#define STPME1601_AUTOSLEEP_ENABLE (1 << 3)
/*
* STMPE1801
*/
#define STMPE1801_ID 0xc110
#define STMPE1801_NR_INTERNAL_IRQS 5
#define STMPE1801_IRQ_KEYPAD_COMBI 4
#define STMPE1801_IRQ_GPIOC 3
#define STMPE1801_IRQ_KEYPAD_OVER 2
#define STMPE1801_IRQ_KEYPAD 1
#define STMPE1801_IRQ_WAKEUP 0
#define STMPE1801_REG_CHIP_ID 0x00
#define STMPE1801_REG_SYS_CTRL 0x02
#define STMPE1801_REG_INT_CTRL_LOW 0x04
#define STMPE1801_REG_INT_EN_MASK_LOW 0x06
#define STMPE1801_REG_INT_STA_LOW 0x08
#define STMPE1801_REG_INT_EN_GPIO_MASK_LOW 0x0A
#define STMPE1801_REG_INT_EN_GPIO_MASK_MID 0x0B
#define STMPE1801_REG_INT_EN_GPIO_MASK_HIGH 0x0C
#define STMPE1801_REG_INT_STA_GPIO_LOW 0x0D
#define STMPE1801_REG_INT_STA_GPIO_MID 0x0E
#define STMPE1801_REG_INT_STA_GPIO_HIGH 0x0F
#define STMPE1801_REG_GPIO_SET_LOW 0x10
#define STMPE1801_REG_GPIO_SET_MID 0x11
#define STMPE1801_REG_GPIO_SET_HIGH 0x12
#define STMPE1801_REG_GPIO_CLR_LOW 0x13
#define STMPE1801_REG_GPIO_CLR_MID 0x14
#define STMPE1801_REG_GPIO_CLR_HIGH 0x15
#define STMPE1801_REG_GPIO_MP_LOW 0x16
#define STMPE1801_REG_GPIO_MP_MID 0x17
#define STMPE1801_REG_GPIO_MP_HIGH 0x18
#define STMPE1801_REG_GPIO_SET_DIR_LOW 0x19
#define STMPE1801_REG_GPIO_SET_DIR_MID 0x1A
#define STMPE1801_REG_GPIO_SET_DIR_HIGH 0x1B
#define STMPE1801_REG_GPIO_RE_LOW 0x1C
#define STMPE1801_REG_GPIO_RE_MID 0x1D
#define STMPE1801_REG_GPIO_RE_HIGH 0x1E
#define STMPE1801_REG_GPIO_FE_LOW 0x1F
#define STMPE1801_REG_GPIO_FE_MID 0x20
#define STMPE1801_REG_GPIO_FE_HIGH 0x21
#define STMPE1801_REG_GPIO_PULL_UP_LOW 0x22
#define STMPE1801_REG_GPIO_PULL_UP_MID 0x23
#define STMPE1801_REG_GPIO_PULL_UP_HIGH 0x24
#define STMPE1801_MSK_INT_EN_KPC (1 << 1)
#define STMPE1801_MSK_INT_EN_GPIO (1 << 3)
/*
* STMPE24xx
*/
#define STMPE24XX_IRQ_GPIOC 8
#define STMPE24XX_IRQ_PWM2 7
#define STMPE24XX_IRQ_PWM1 6
#define STMPE24XX_IRQ_PWM0 5
#define STMPE24XX_IRQ_ROT_OVER 4
#define STMPE24XX_IRQ_ROT 3
#define STMPE24XX_IRQ_KEYPAD_OVER 2
#define STMPE24XX_IRQ_KEYPAD 1
#define STMPE24XX_IRQ_WAKEUP 0
#define STMPE24XX_NR_INTERNAL_IRQS 9
#define STMPE24XX_REG_SYS_CTRL 0x02
#define STMPE24XX_REG_SYS_CTRL2 0x03
#define STMPE24XX_REG_ICR_MSB 0x10
#define STMPE24XX_REG_ICR_LSB 0x11
#define STMPE24XX_REG_IER_MSB 0x12
#define STMPE24XX_REG_IER_LSB 0x13
#define STMPE24XX_REG_ISR_MSB 0x14
#define STMPE24XX_REG_ISR_LSB 0x15
#define STMPE24XX_REG_IEGPIOR_MSB 0x16
#define STMPE24XX_REG_IEGPIOR_CSB 0x17
#define STMPE24XX_REG_IEGPIOR_LSB 0x18
#define STMPE24XX_REG_ISGPIOR_MSB 0x19
#define STMPE24XX_REG_ISGPIOR_CSB 0x1A
#define STMPE24XX_REG_ISGPIOR_LSB 0x1B
#define STMPE24XX_REG_CHIP_ID 0x80
#define STMPE24XX_REG_GPSR_MSB 0x83
#define STMPE24XX_REG_GPSR_CSB 0x84
#define STMPE24XX_REG_GPSR_LSB 0x85
#define STMPE24XX_REG_GPCR_MSB 0x86
#define STMPE24XX_REG_GPCR_CSB 0x87
#define STMPE24XX_REG_GPCR_LSB 0x88
#define STMPE24XX_REG_GPDR_MSB 0x89
#define STMPE24XX_REG_GPDR_CSB 0x8A
#define STMPE24XX_REG_GPDR_LSB 0x8B
#define STMPE24XX_REG_GPEDR_MSB 0x8C
#define STMPE24XX_REG_GPEDR_CSB 0x8D
#define STMPE24XX_REG_GPEDR_LSB 0x8E
#define STMPE24XX_REG_GPRER_MSB 0x8F
#define STMPE24XX_REG_GPRER_CSB 0x90
#define STMPE24XX_REG_GPRER_LSB 0x91
#define STMPE24XX_REG_GPFER_MSB 0x92
#define STMPE24XX_REG_GPFER_CSB 0x93
#define STMPE24XX_REG_GPFER_LSB 0x94
#define STMPE24XX_REG_GPPUR_MSB 0x95
#define STMPE24XX_REG_GPPUR_CSB 0x96
#define STMPE24XX_REG_GPPUR_LSB 0x97
#define STMPE24XX_REG_GPPDR_MSB 0x98
#define STMPE24XX_REG_GPPDR_CSB 0x99
#define STMPE24XX_REG_GPPDR_LSB 0x9A
#define STMPE24XX_REG_GPAFR_U_MSB 0x9B
#define STMPE24XX_REG_GPMR_MSB 0xA2
#define STMPE24XX_REG_GPMR_CSB 0xA3
#define STMPE24XX_REG_GPMR_LSB 0xA4
#define STMPE24XX_SYS_CTRL_ENABLE_GPIO (1 << 3)
#define STMPE24XX_SYSCON_ENABLE_PWM (1 << 2)
#define STMPE24XX_SYS_CTRL_ENABLE_KPC (1 << 1)
#define STMPE24XX_SYSCON_ENABLE_ROT (1 << 0)
#endif
| null | null | null | null | 108,833 |
59,149 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 59,149 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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 CHROME_BROWSER_EXTENSIONS_API_STORAGE_SYNC_STORAGE_BACKEND_H_
#define CHROME_BROWSER_EXTENSIONS_API_STORAGE_SYNC_STORAGE_BACKEND_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include "base/compiler_specific.h"
#include "base/files/file_path.h"
#include "base/macros.h"
#include "base/memory/ref_counted.h"
#include "components/sync/model/syncable_service.h"
#include "extensions/browser/api/storage/settings_observer.h"
#include "extensions/browser/api/storage/settings_storage_quota_enforcer.h"
#include "extensions/browser/value_store/value_store_factory.h"
namespace syncer {
class SyncErrorFactory;
}
namespace extensions {
class SettingsSyncProcessor;
class SyncableSettingsStorage;
class ValueStoreFactory;
// Manages ValueStore objects for extensions, including routing
// changes from sync to them.
// Lives entirely on the FILE thread.
class SyncStorageBackend : public syncer::SyncableService {
public:
// |storage_factory| is use to create leveldb storage areas.
// |observers| is the list of observers to settings changes.
SyncStorageBackend(const scoped_refptr<ValueStoreFactory>& storage_factory,
const SettingsStorageQuotaEnforcer::Limits& quota,
const scoped_refptr<SettingsObserverList>& observers,
syncer::ModelType sync_type,
const syncer::SyncableService::StartSyncFlare& flare);
~SyncStorageBackend() override;
virtual ValueStore* GetStorage(const std::string& extension_id);
virtual void DeleteStorage(const std::string& extension_id);
// syncer::SyncableService implementation.
syncer::SyncDataList GetAllSyncData(syncer::ModelType type) const override;
syncer::SyncMergeResult MergeDataAndStartSyncing(
syncer::ModelType type,
const syncer::SyncDataList& initial_sync_data,
std::unique_ptr<syncer::SyncChangeProcessor> sync_processor,
std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory) override;
syncer::SyncError ProcessSyncChanges(
const base::Location& from_here,
const syncer::SyncChangeList& change_list) override;
void StopSyncing(syncer::ModelType type) override;
private:
// Gets a weak reference to the storage area for a given extension,
// initializing sync with some initial data if sync enabled.
SyncableSettingsStorage* GetOrCreateStorageWithSyncData(
const std::string& extension_id,
std::unique_ptr<base::DictionaryValue> sync_data) const;
// Gets all extension IDs known to extension settings. This may not be all
// installed extensions.
std::set<std::string> GetKnownExtensionIDs(
ValueStoreFactory::ModelType model_type) const;
// Creates a new SettingsSyncProcessor for an extension.
std::unique_ptr<SettingsSyncProcessor> CreateSettingsSyncProcessor(
const std::string& extension_id) const;
// The Factory to use for creating new ValueStores.
const scoped_refptr<ValueStoreFactory> storage_factory_;
// Quota limits (see SettingsStorageQuotaEnforcer).
const SettingsStorageQuotaEnforcer::Limits quota_;
// The list of observers to settings changes.
const scoped_refptr<SettingsObserverList> observers_;
// A cache of ValueStore objects that have already been created.
// Ensure that there is only ever one created per extension.
using StorageObjMap =
std::map<std::string, std::unique_ptr<SyncableSettingsStorage>>;
mutable StorageObjMap storage_objs_;
// Current sync model type. Either EXTENSION_SETTINGS or APP_SETTINGS.
syncer::ModelType sync_type_;
// Current sync processor, if any.
std::unique_ptr<syncer::SyncChangeProcessor> sync_processor_;
// Current sync error handler if any.
std::unique_ptr<syncer::SyncErrorFactory> sync_error_factory_;
syncer::SyncableService::StartSyncFlare flare_;
DISALLOW_COPY_AND_ASSIGN(SyncStorageBackend);
};
} // namespace extensions
#endif // CHROME_BROWSER_EXTENSIONS_API_STORAGE_SYNC_STORAGE_BACKEND_H_
| null | null | null | null | 56,012 |
1,591 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 166,586 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* linux/net/sunrpc/gss_mech_switch.c
*
* Copyright (c) 2001 The Regents of the University of Michigan.
* All rights reserved.
*
* J. Bruce Fields <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* 3. Neither the name of the University nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include <linux/types.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <linux/oid_registry.h>
#include <linux/sunrpc/msg_prot.h>
#include <linux/sunrpc/gss_asn1.h>
#include <linux/sunrpc/auth_gss.h>
#include <linux/sunrpc/svcauth_gss.h>
#include <linux/sunrpc/gss_err.h>
#include <linux/sunrpc/sched.h>
#include <linux/sunrpc/gss_api.h>
#include <linux/sunrpc/clnt.h>
#if IS_ENABLED(CONFIG_SUNRPC_DEBUG)
# define RPCDBG_FACILITY RPCDBG_AUTH
#endif
static LIST_HEAD(registered_mechs);
static DEFINE_SPINLOCK(registered_mechs_lock);
static void
gss_mech_free(struct gss_api_mech *gm)
{
struct pf_desc *pf;
int i;
for (i = 0; i < gm->gm_pf_num; i++) {
pf = &gm->gm_pfs[i];
kfree(pf->auth_domain_name);
pf->auth_domain_name = NULL;
}
}
static inline char *
make_auth_domain_name(char *name)
{
static char *prefix = "gss/";
char *new;
new = kmalloc(strlen(name) + strlen(prefix) + 1, GFP_KERNEL);
if (new) {
strcpy(new, prefix);
strcat(new, name);
}
return new;
}
static int
gss_mech_svc_setup(struct gss_api_mech *gm)
{
struct pf_desc *pf;
int i, status;
for (i = 0; i < gm->gm_pf_num; i++) {
pf = &gm->gm_pfs[i];
pf->auth_domain_name = make_auth_domain_name(pf->name);
status = -ENOMEM;
if (pf->auth_domain_name == NULL)
goto out;
status = svcauth_gss_register_pseudoflavor(pf->pseudoflavor,
pf->auth_domain_name);
if (status)
goto out;
}
return 0;
out:
gss_mech_free(gm);
return status;
}
/**
* gss_mech_register - register a GSS mechanism
* @gm: GSS mechanism handle
*
* Returns zero if successful, or a negative errno.
*/
int gss_mech_register(struct gss_api_mech *gm)
{
int status;
status = gss_mech_svc_setup(gm);
if (status)
return status;
spin_lock(®istered_mechs_lock);
list_add(&gm->gm_list, ®istered_mechs);
spin_unlock(®istered_mechs_lock);
dprintk("RPC: registered gss mechanism %s\n", gm->gm_name);
return 0;
}
EXPORT_SYMBOL_GPL(gss_mech_register);
/**
* gss_mech_unregister - release a GSS mechanism
* @gm: GSS mechanism handle
*
*/
void gss_mech_unregister(struct gss_api_mech *gm)
{
spin_lock(®istered_mechs_lock);
list_del(&gm->gm_list);
spin_unlock(®istered_mechs_lock);
dprintk("RPC: unregistered gss mechanism %s\n", gm->gm_name);
gss_mech_free(gm);
}
EXPORT_SYMBOL_GPL(gss_mech_unregister);
struct gss_api_mech *gss_mech_get(struct gss_api_mech *gm)
{
__module_get(gm->gm_owner);
return gm;
}
EXPORT_SYMBOL(gss_mech_get);
static struct gss_api_mech *
_gss_mech_get_by_name(const char *name)
{
struct gss_api_mech *pos, *gm = NULL;
spin_lock(®istered_mechs_lock);
list_for_each_entry(pos, ®istered_mechs, gm_list) {
if (0 == strcmp(name, pos->gm_name)) {
if (try_module_get(pos->gm_owner))
gm = pos;
break;
}
}
spin_unlock(®istered_mechs_lock);
return gm;
}
struct gss_api_mech * gss_mech_get_by_name(const char *name)
{
struct gss_api_mech *gm = NULL;
gm = _gss_mech_get_by_name(name);
if (!gm) {
request_module("rpc-auth-gss-%s", name);
gm = _gss_mech_get_by_name(name);
}
return gm;
}
struct gss_api_mech *gss_mech_get_by_OID(struct rpcsec_gss_oid *obj)
{
struct gss_api_mech *pos, *gm = NULL;
char buf[32];
if (sprint_oid(obj->data, obj->len, buf, sizeof(buf)) < 0)
return NULL;
dprintk("RPC: %s(%s)\n", __func__, buf);
request_module("rpc-auth-gss-%s", buf);
spin_lock(®istered_mechs_lock);
list_for_each_entry(pos, ®istered_mechs, gm_list) {
if (obj->len == pos->gm_oid.len) {
if (0 == memcmp(obj->data, pos->gm_oid.data, obj->len)) {
if (try_module_get(pos->gm_owner))
gm = pos;
break;
}
}
}
spin_unlock(®istered_mechs_lock);
return gm;
}
static inline int
mech_supports_pseudoflavor(struct gss_api_mech *gm, u32 pseudoflavor)
{
int i;
for (i = 0; i < gm->gm_pf_num; i++) {
if (gm->gm_pfs[i].pseudoflavor == pseudoflavor)
return 1;
}
return 0;
}
static struct gss_api_mech *_gss_mech_get_by_pseudoflavor(u32 pseudoflavor)
{
struct gss_api_mech *gm = NULL, *pos;
spin_lock(®istered_mechs_lock);
list_for_each_entry(pos, ®istered_mechs, gm_list) {
if (!mech_supports_pseudoflavor(pos, pseudoflavor))
continue;
if (try_module_get(pos->gm_owner))
gm = pos;
break;
}
spin_unlock(®istered_mechs_lock);
return gm;
}
struct gss_api_mech *
gss_mech_get_by_pseudoflavor(u32 pseudoflavor)
{
struct gss_api_mech *gm;
gm = _gss_mech_get_by_pseudoflavor(pseudoflavor);
if (!gm) {
request_module("rpc-auth-gss-%u", pseudoflavor);
gm = _gss_mech_get_by_pseudoflavor(pseudoflavor);
}
return gm;
}
/**
* gss_mech_list_pseudoflavors - Discover registered GSS pseudoflavors
* @array: array to fill in
* @size: size of "array"
*
* Returns the number of array items filled in, or a negative errno.
*
* The returned array is not sorted by any policy. Callers should not
* rely on the order of the items in the returned array.
*/
int gss_mech_list_pseudoflavors(rpc_authflavor_t *array_ptr, int size)
{
struct gss_api_mech *pos = NULL;
int j, i = 0;
spin_lock(®istered_mechs_lock);
list_for_each_entry(pos, ®istered_mechs, gm_list) {
for (j = 0; j < pos->gm_pf_num; j++) {
if (i >= size) {
spin_unlock(®istered_mechs_lock);
return -ENOMEM;
}
array_ptr[i++] = pos->gm_pfs[j].pseudoflavor;
}
}
spin_unlock(®istered_mechs_lock);
return i;
}
/**
* gss_svc_to_pseudoflavor - map a GSS service number to a pseudoflavor
* @gm: GSS mechanism handle
* @qop: GSS quality-of-protection value
* @service: GSS service value
*
* Returns a matching security flavor, or RPC_AUTH_MAXFLAVOR if none is found.
*/
rpc_authflavor_t gss_svc_to_pseudoflavor(struct gss_api_mech *gm, u32 qop,
u32 service)
{
int i;
for (i = 0; i < gm->gm_pf_num; i++) {
if (gm->gm_pfs[i].qop == qop &&
gm->gm_pfs[i].service == service) {
return gm->gm_pfs[i].pseudoflavor;
}
}
return RPC_AUTH_MAXFLAVOR;
}
/**
* gss_mech_info2flavor - look up a pseudoflavor given a GSS tuple
* @info: a GSS mech OID, quality of protection, and service value
*
* Returns a matching pseudoflavor, or RPC_AUTH_MAXFLAVOR if the tuple is
* not supported.
*/
rpc_authflavor_t gss_mech_info2flavor(struct rpcsec_gss_info *info)
{
rpc_authflavor_t pseudoflavor;
struct gss_api_mech *gm;
gm = gss_mech_get_by_OID(&info->oid);
if (gm == NULL)
return RPC_AUTH_MAXFLAVOR;
pseudoflavor = gss_svc_to_pseudoflavor(gm, info->qop, info->service);
gss_mech_put(gm);
return pseudoflavor;
}
/**
* gss_mech_flavor2info - look up a GSS tuple for a given pseudoflavor
* @pseudoflavor: GSS pseudoflavor to match
* @info: rpcsec_gss_info structure to fill in
*
* Returns zero and fills in "info" if pseudoflavor matches a
* supported mechanism. Otherwise a negative errno is returned.
*/
int gss_mech_flavor2info(rpc_authflavor_t pseudoflavor,
struct rpcsec_gss_info *info)
{
struct gss_api_mech *gm;
int i;
gm = gss_mech_get_by_pseudoflavor(pseudoflavor);
if (gm == NULL)
return -ENOENT;
for (i = 0; i < gm->gm_pf_num; i++) {
if (gm->gm_pfs[i].pseudoflavor == pseudoflavor) {
memcpy(info->oid.data, gm->gm_oid.data, gm->gm_oid.len);
info->oid.len = gm->gm_oid.len;
info->qop = gm->gm_pfs[i].qop;
info->service = gm->gm_pfs[i].service;
gss_mech_put(gm);
return 0;
}
}
gss_mech_put(gm);
return -ENOENT;
}
u32
gss_pseudoflavor_to_service(struct gss_api_mech *gm, u32 pseudoflavor)
{
int i;
for (i = 0; i < gm->gm_pf_num; i++) {
if (gm->gm_pfs[i].pseudoflavor == pseudoflavor)
return gm->gm_pfs[i].service;
}
return 0;
}
EXPORT_SYMBOL(gss_pseudoflavor_to_service);
bool
gss_pseudoflavor_to_datatouch(struct gss_api_mech *gm, u32 pseudoflavor)
{
int i;
for (i = 0; i < gm->gm_pf_num; i++) {
if (gm->gm_pfs[i].pseudoflavor == pseudoflavor)
return gm->gm_pfs[i].datatouch;
}
return false;
}
char *
gss_service_to_auth_domain_name(struct gss_api_mech *gm, u32 service)
{
int i;
for (i = 0; i < gm->gm_pf_num; i++) {
if (gm->gm_pfs[i].service == service)
return gm->gm_pfs[i].auth_domain_name;
}
return NULL;
}
void
gss_mech_put(struct gss_api_mech * gm)
{
if (gm)
module_put(gm->gm_owner);
}
EXPORT_SYMBOL(gss_mech_put);
/* The mech could probably be determined from the token instead, but it's just
* as easy for now to pass it in. */
int
gss_import_sec_context(const void *input_token, size_t bufsize,
struct gss_api_mech *mech,
struct gss_ctx **ctx_id,
time_t *endtime,
gfp_t gfp_mask)
{
if (!(*ctx_id = kzalloc(sizeof(**ctx_id), gfp_mask)))
return -ENOMEM;
(*ctx_id)->mech_type = gss_mech_get(mech);
return mech->gm_ops->gss_import_sec_context(input_token, bufsize,
*ctx_id, endtime, gfp_mask);
}
/* gss_get_mic: compute a mic over message and return mic_token. */
u32
gss_get_mic(struct gss_ctx *context_handle,
struct xdr_buf *message,
struct xdr_netobj *mic_token)
{
return context_handle->mech_type->gm_ops
->gss_get_mic(context_handle,
message,
mic_token);
}
/* gss_verify_mic: check whether the provided mic_token verifies message. */
u32
gss_verify_mic(struct gss_ctx *context_handle,
struct xdr_buf *message,
struct xdr_netobj *mic_token)
{
return context_handle->mech_type->gm_ops
->gss_verify_mic(context_handle,
message,
mic_token);
}
/*
* This function is called from both the client and server code.
* Each makes guarantees about how much "slack" space is available
* for the underlying function in "buf"'s head and tail while
* performing the wrap.
*
* The client and server code allocate RPC_MAX_AUTH_SIZE extra
* space in both the head and tail which is available for use by
* the wrap function.
*
* Underlying functions should verify they do not use more than
* RPC_MAX_AUTH_SIZE of extra space in either the head or tail
* when performing the wrap.
*/
u32
gss_wrap(struct gss_ctx *ctx_id,
int offset,
struct xdr_buf *buf,
struct page **inpages)
{
return ctx_id->mech_type->gm_ops
->gss_wrap(ctx_id, offset, buf, inpages);
}
u32
gss_unwrap(struct gss_ctx *ctx_id,
int offset,
struct xdr_buf *buf)
{
return ctx_id->mech_type->gm_ops
->gss_unwrap(ctx_id, offset, buf);
}
/* gss_delete_sec_context: free all resources associated with context_handle.
* Note this differs from the RFC 2744-specified prototype in that we don't
* bother returning an output token, since it would never be used anyway. */
u32
gss_delete_sec_context(struct gss_ctx **context_handle)
{
dprintk("RPC: gss_delete_sec_context deleting %p\n",
*context_handle);
if (!*context_handle)
return GSS_S_NO_CONTEXT;
if ((*context_handle)->internal_ctx_id)
(*context_handle)->mech_type->gm_ops
->gss_delete_sec_context((*context_handle)
->internal_ctx_id);
gss_mech_put((*context_handle)->mech_type);
kfree(*context_handle);
*context_handle=NULL;
return GSS_S_COMPLETE;
}
| null | null | null | null | 74,934 |
43,203 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 43,203 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright (c) 2011 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.
// ConditionVariable wraps pthreads condition variable synchronization or, on
// Windows, simulates it. This functionality is very helpful for having
// several threads wait for an event, as is common with a thread pool managed
// by a master. The meaning of such an event in the (worker) thread pool
// scenario is that additional tasks are now available for processing. It is
// used in Chrome in the DNS prefetching system to notify worker threads that
// a queue now has items (tasks) which need to be tended to. A related use
// would have a pool manager waiting on a ConditionVariable, waiting for a
// thread in the pool to announce (signal) that there is now more room in a
// (bounded size) communications queue for the manager to deposit tasks, or,
// as a second example, that the queue of tasks is completely empty and all
// workers are waiting.
//
// USAGE NOTE 1: spurious signal events are possible with this and
// most implementations of condition variables. As a result, be
// *sure* to retest your condition before proceeding. The following
// is a good example of doing this correctly:
//
// while (!work_to_be_done()) Wait(...);
//
// In contrast do NOT do the following:
//
// if (!work_to_be_done()) Wait(...); // Don't do this.
//
// Especially avoid the above if you are relying on some other thread only
// issuing a signal up *if* there is work-to-do. There can/will
// be spurious signals. Recheck state on waiting thread before
// assuming the signal was intentional. Caveat caller ;-).
//
// USAGE NOTE 2: Broadcast() frees up all waiting threads at once,
// which leads to contention for the locks they all held when they
// called Wait(). This results in POOR performance. A much better
// approach to getting a lot of threads out of Wait() is to have each
// thread (upon exiting Wait()) call Signal() to free up another
// Wait'ing thread. Look at condition_variable_unittest.cc for
// both examples.
//
// Broadcast() can be used nicely during teardown, as it gets the job
// done, and leaves no sleeping threads... and performance is less
// critical at that point.
//
// The semantics of Broadcast() are carefully crafted so that *all*
// threads that were waiting when the request was made will indeed
// get signaled. Some implementations mess up, and don't signal them
// all, while others allow the wait to be effectively turned off (for
// a while while waiting threads come around). This implementation
// appears correct, as it will not "lose" any signals, and will guarantee
// that all threads get signaled by Broadcast().
//
// This implementation offers support for "performance" in its selection of
// which thread to revive. Performance, in direct contrast with "fairness,"
// assures that the thread that most recently began to Wait() is selected by
// Signal to revive. Fairness would (if publicly supported) assure that the
// thread that has Wait()ed the longest is selected. The default policy
// may improve performance, as the selected thread may have a greater chance of
// having some of its stack data in various CPU caches.
//
// For a discussion of the many very subtle implementation details, see the FAQ
// at the end of condition_variable_win.cc.
#ifndef BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
#define BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
#include "base/base_export.h"
#include "base/logging.h"
#include "base/macros.h"
#include "base/synchronization/lock.h"
#include "build/build_config.h"
#if defined(OS_POSIX)
#include <pthread.h>
#endif
#if defined(OS_WIN)
#include "base/win/windows_types.h"
#endif
namespace base {
class TimeDelta;
class BASE_EXPORT ConditionVariable {
public:
// Construct a cv for use with ONLY one user lock.
explicit ConditionVariable(Lock* user_lock);
~ConditionVariable();
// Wait() releases the caller's critical section atomically as it starts to
// sleep, and the reacquires it when it is signaled. The wait functions are
// susceptible to spurious wakeups. (See usage note 1 for more details.)
void Wait();
void TimedWait(const TimeDelta& max_time);
// Broadcast() revives all waiting threads. (See usage note 2 for more
// details.)
void Broadcast();
// Signal() revives one waiting thread.
void Signal();
private:
#if defined(OS_WIN)
CHROME_CONDITION_VARIABLE cv_;
CHROME_SRWLOCK* const srwlock_;
#elif defined(OS_POSIX)
pthread_cond_t condition_;
pthread_mutex_t* user_mutex_;
#endif
#if DCHECK_IS_ON() && (defined(OS_WIN) || defined(OS_POSIX))
base::Lock* const user_lock_; // Needed to adjust shadow lock state on wait.
#endif
DISALLOW_COPY_AND_ASSIGN(ConditionVariable);
};
} // namespace base
#endif // BASE_SYNCHRONIZATION_CONDITION_VARIABLE_H_
| null | null | null | null | 40,066 |
3,322 | null |
train_val
|
1b0d3845b454eaaac0b2064c78926ca4d739a080
| 265,890 |
qemu
| 0 |
https://github.com/bonzini/qemu
|
2016-10-18 11:40:27+01:00
|
/*
* pci_regs.h
*
* PCI standard defines
* Copyright 1994, Drew Eckhardt
* Copyright 1997--1999 Martin Mares <[email protected]>
*
* For more information, please consult the following manuals (look at
* http://www.pcisig.com/ for how to get them):
*
* PCI BIOS Specification
* PCI Local Bus Specification
* PCI to PCI Bridge Specification
* PCI System Design Guide
*
* For HyperTransport information, please consult the following manuals
* from http://www.hypertransport.org
*
* The HyperTransport I/O Link Specification
*/
#ifndef LINUX_PCI_REGS_H
#define LINUX_PCI_REGS_H
/*
* Under PCI, each device has 256 bytes of configuration address space,
* of which the first 64 bytes are standardized as follows:
*/
#define PCI_STD_HEADER_SIZEOF 64
#define PCI_VENDOR_ID 0x00 /* 16 bits */
#define PCI_DEVICE_ID 0x02 /* 16 bits */
#define PCI_COMMAND 0x04 /* 16 bits */
#define PCI_COMMAND_IO 0x1 /* Enable response in I/O space */
#define PCI_COMMAND_MEMORY 0x2 /* Enable response in Memory space */
#define PCI_COMMAND_MASTER 0x4 /* Enable bus mastering */
#define PCI_COMMAND_SPECIAL 0x8 /* Enable response to special cycles */
#define PCI_COMMAND_INVALIDATE 0x10 /* Use memory write and invalidate */
#define PCI_COMMAND_VGA_PALETTE 0x20 /* Enable palette snooping */
#define PCI_COMMAND_PARITY 0x40 /* Enable parity checking */
#define PCI_COMMAND_WAIT 0x80 /* Enable address/data stepping */
#define PCI_COMMAND_SERR 0x100 /* Enable SERR */
#define PCI_COMMAND_FAST_BACK 0x200 /* Enable back-to-back writes */
#define PCI_COMMAND_INTX_DISABLE 0x400 /* INTx Emulation Disable */
#define PCI_STATUS 0x06 /* 16 bits */
#define PCI_STATUS_INTERRUPT 0x08 /* Interrupt status */
#define PCI_STATUS_CAP_LIST 0x10 /* Support Capability List */
#define PCI_STATUS_66MHZ 0x20 /* Support 66 MHz PCI 2.1 bus */
#define PCI_STATUS_UDF 0x40 /* Support User Definable Features [obsolete] */
#define PCI_STATUS_FAST_BACK 0x80 /* Accept fast-back to back */
#define PCI_STATUS_PARITY 0x100 /* Detected parity error */
#define PCI_STATUS_DEVSEL_MASK 0x600 /* DEVSEL timing */
#define PCI_STATUS_DEVSEL_FAST 0x000
#define PCI_STATUS_DEVSEL_MEDIUM 0x200
#define PCI_STATUS_DEVSEL_SLOW 0x400
#define PCI_STATUS_SIG_TARGET_ABORT 0x800 /* Set on target abort */
#define PCI_STATUS_REC_TARGET_ABORT 0x1000 /* Master ack of " */
#define PCI_STATUS_REC_MASTER_ABORT 0x2000 /* Set on master abort */
#define PCI_STATUS_SIG_SYSTEM_ERROR 0x4000 /* Set when we drive SERR */
#define PCI_STATUS_DETECTED_PARITY 0x8000 /* Set on parity error */
#define PCI_CLASS_REVISION 0x08 /* High 24 bits are class, low 8 revision */
#define PCI_REVISION_ID 0x08 /* Revision ID */
#define PCI_CLASS_PROG 0x09 /* Reg. Level Programming Interface */
#define PCI_CLASS_DEVICE 0x0a /* Device class */
#define PCI_CACHE_LINE_SIZE 0x0c /* 8 bits */
#define PCI_LATENCY_TIMER 0x0d /* 8 bits */
#define PCI_HEADER_TYPE 0x0e /* 8 bits */
#define PCI_HEADER_TYPE_NORMAL 0
#define PCI_HEADER_TYPE_BRIDGE 1
#define PCI_HEADER_TYPE_CARDBUS 2
#define PCI_BIST 0x0f /* 8 bits */
#define PCI_BIST_CODE_MASK 0x0f /* Return result */
#define PCI_BIST_START 0x40 /* 1 to start BIST, 2 secs or less */
#define PCI_BIST_CAPABLE 0x80 /* 1 if BIST capable */
/*
* Base addresses specify locations in memory or I/O space.
* Decoded size can be determined by writing a value of
* 0xffffffff to the register, and reading it back. Only
* 1 bits are decoded.
*/
#define PCI_BASE_ADDRESS_0 0x10 /* 32 bits */
#define PCI_BASE_ADDRESS_1 0x14 /* 32 bits [htype 0,1 only] */
#define PCI_BASE_ADDRESS_2 0x18 /* 32 bits [htype 0 only] */
#define PCI_BASE_ADDRESS_3 0x1c /* 32 bits */
#define PCI_BASE_ADDRESS_4 0x20 /* 32 bits */
#define PCI_BASE_ADDRESS_5 0x24 /* 32 bits */
#define PCI_BASE_ADDRESS_SPACE 0x01 /* 0 = memory, 1 = I/O */
#define PCI_BASE_ADDRESS_SPACE_IO 0x01
#define PCI_BASE_ADDRESS_SPACE_MEMORY 0x00
#define PCI_BASE_ADDRESS_MEM_TYPE_MASK 0x06
#define PCI_BASE_ADDRESS_MEM_TYPE_32 0x00 /* 32 bit address */
#define PCI_BASE_ADDRESS_MEM_TYPE_1M 0x02 /* Below 1M [obsolete] */
#define PCI_BASE_ADDRESS_MEM_TYPE_64 0x04 /* 64 bit address */
#define PCI_BASE_ADDRESS_MEM_PREFETCH 0x08 /* prefetchable? */
#define PCI_BASE_ADDRESS_MEM_MASK (~0x0fUL)
#define PCI_BASE_ADDRESS_IO_MASK (~0x03UL)
/* bit 1 is reserved if address_space = 1 */
/* Header type 0 (normal devices) */
#define PCI_CARDBUS_CIS 0x28
#define PCI_SUBSYSTEM_VENDOR_ID 0x2c
#define PCI_SUBSYSTEM_ID 0x2e
#define PCI_ROM_ADDRESS 0x30 /* Bits 31..11 are address, 10..1 reserved */
#define PCI_ROM_ADDRESS_ENABLE 0x01
#define PCI_ROM_ADDRESS_MASK (~0x7ffUL)
#define PCI_CAPABILITY_LIST 0x34 /* Offset of first capability list entry */
/* 0x35-0x3b are reserved */
#define PCI_INTERRUPT_LINE 0x3c /* 8 bits */
#define PCI_INTERRUPT_PIN 0x3d /* 8 bits */
#define PCI_MIN_GNT 0x3e /* 8 bits */
#define PCI_MAX_LAT 0x3f /* 8 bits */
/* Header type 1 (PCI-to-PCI bridges) */
#define PCI_PRIMARY_BUS 0x18 /* Primary bus number */
#define PCI_SECONDARY_BUS 0x19 /* Secondary bus number */
#define PCI_SUBORDINATE_BUS 0x1a /* Highest bus number behind the bridge */
#define PCI_SEC_LATENCY_TIMER 0x1b /* Latency timer for secondary interface */
#define PCI_IO_BASE 0x1c /* I/O range behind the bridge */
#define PCI_IO_LIMIT 0x1d
#define PCI_IO_RANGE_TYPE_MASK 0x0fUL /* I/O bridging type */
#define PCI_IO_RANGE_TYPE_16 0x00
#define PCI_IO_RANGE_TYPE_32 0x01
#define PCI_IO_RANGE_MASK (~0x0fUL) /* Standard 4K I/O windows */
#define PCI_IO_1K_RANGE_MASK (~0x03UL) /* Intel 1K I/O windows */
#define PCI_SEC_STATUS 0x1e /* Secondary status register, only bit 14 used */
#define PCI_MEMORY_BASE 0x20 /* Memory range behind */
#define PCI_MEMORY_LIMIT 0x22
#define PCI_MEMORY_RANGE_TYPE_MASK 0x0fUL
#define PCI_MEMORY_RANGE_MASK (~0x0fUL)
#define PCI_PREF_MEMORY_BASE 0x24 /* Prefetchable memory range behind */
#define PCI_PREF_MEMORY_LIMIT 0x26
#define PCI_PREF_RANGE_TYPE_MASK 0x0fUL
#define PCI_PREF_RANGE_TYPE_32 0x00
#define PCI_PREF_RANGE_TYPE_64 0x01
#define PCI_PREF_RANGE_MASK (~0x0fUL)
#define PCI_PREF_BASE_UPPER32 0x28 /* Upper half of prefetchable memory range */
#define PCI_PREF_LIMIT_UPPER32 0x2c
#define PCI_IO_BASE_UPPER16 0x30 /* Upper half of I/O addresses */
#define PCI_IO_LIMIT_UPPER16 0x32
/* 0x34 same as for htype 0 */
/* 0x35-0x3b is reserved */
#define PCI_ROM_ADDRESS1 0x38 /* Same as PCI_ROM_ADDRESS, but for htype 1 */
/* 0x3c-0x3d are same as for htype 0 */
#define PCI_BRIDGE_CONTROL 0x3e
#define PCI_BRIDGE_CTL_PARITY 0x01 /* Enable parity detection on secondary interface */
#define PCI_BRIDGE_CTL_SERR 0x02 /* The same for SERR forwarding */
#define PCI_BRIDGE_CTL_ISA 0x04 /* Enable ISA mode */
#define PCI_BRIDGE_CTL_VGA 0x08 /* Forward VGA addresses */
#define PCI_BRIDGE_CTL_MASTER_ABORT 0x20 /* Report master aborts */
#define PCI_BRIDGE_CTL_BUS_RESET 0x40 /* Secondary bus reset */
#define PCI_BRIDGE_CTL_FAST_BACK 0x80 /* Fast Back2Back enabled on secondary interface */
/* Header type 2 (CardBus bridges) */
#define PCI_CB_CAPABILITY_LIST 0x14
/* 0x15 reserved */
#define PCI_CB_SEC_STATUS 0x16 /* Secondary status */
#define PCI_CB_PRIMARY_BUS 0x18 /* PCI bus number */
#define PCI_CB_CARD_BUS 0x19 /* CardBus bus number */
#define PCI_CB_SUBORDINATE_BUS 0x1a /* Subordinate bus number */
#define PCI_CB_LATENCY_TIMER 0x1b /* CardBus latency timer */
#define PCI_CB_MEMORY_BASE_0 0x1c
#define PCI_CB_MEMORY_LIMIT_0 0x20
#define PCI_CB_MEMORY_BASE_1 0x24
#define PCI_CB_MEMORY_LIMIT_1 0x28
#define PCI_CB_IO_BASE_0 0x2c
#define PCI_CB_IO_BASE_0_HI 0x2e
#define PCI_CB_IO_LIMIT_0 0x30
#define PCI_CB_IO_LIMIT_0_HI 0x32
#define PCI_CB_IO_BASE_1 0x34
#define PCI_CB_IO_BASE_1_HI 0x36
#define PCI_CB_IO_LIMIT_1 0x38
#define PCI_CB_IO_LIMIT_1_HI 0x3a
#define PCI_CB_IO_RANGE_MASK (~0x03UL)
/* 0x3c-0x3d are same as for htype 0 */
#define PCI_CB_BRIDGE_CONTROL 0x3e
#define PCI_CB_BRIDGE_CTL_PARITY 0x01 /* Similar to standard bridge control register */
#define PCI_CB_BRIDGE_CTL_SERR 0x02
#define PCI_CB_BRIDGE_CTL_ISA 0x04
#define PCI_CB_BRIDGE_CTL_VGA 0x08
#define PCI_CB_BRIDGE_CTL_MASTER_ABORT 0x20
#define PCI_CB_BRIDGE_CTL_CB_RESET 0x40 /* CardBus reset */
#define PCI_CB_BRIDGE_CTL_16BIT_INT 0x80 /* Enable interrupt for 16-bit cards */
#define PCI_CB_BRIDGE_CTL_PREFETCH_MEM0 0x100 /* Prefetch enable for both memory regions */
#define PCI_CB_BRIDGE_CTL_PREFETCH_MEM1 0x200
#define PCI_CB_BRIDGE_CTL_POST_WRITES 0x400
#define PCI_CB_SUBSYSTEM_VENDOR_ID 0x40
#define PCI_CB_SUBSYSTEM_ID 0x42
#define PCI_CB_LEGACY_MODE_BASE 0x44 /* 16-bit PC Card legacy mode base address (ExCa) */
/* 0x48-0x7f reserved */
/* Capability lists */
#define PCI_CAP_LIST_ID 0 /* Capability ID */
#define PCI_CAP_ID_PM 0x01 /* Power Management */
#define PCI_CAP_ID_AGP 0x02 /* Accelerated Graphics Port */
#define PCI_CAP_ID_VPD 0x03 /* Vital Product Data */
#define PCI_CAP_ID_SLOTID 0x04 /* Slot Identification */
#define PCI_CAP_ID_MSI 0x05 /* Message Signalled Interrupts */
#define PCI_CAP_ID_CHSWP 0x06 /* CompactPCI HotSwap */
#define PCI_CAP_ID_PCIX 0x07 /* PCI-X */
#define PCI_CAP_ID_HT 0x08 /* HyperTransport */
#define PCI_CAP_ID_VNDR 0x09 /* Vendor-Specific */
#define PCI_CAP_ID_DBG 0x0A /* Debug port */
#define PCI_CAP_ID_CCRC 0x0B /* CompactPCI Central Resource Control */
#define PCI_CAP_ID_SHPC 0x0C /* PCI Standard Hot-Plug Controller */
#define PCI_CAP_ID_SSVID 0x0D /* Bridge subsystem vendor/device ID */
#define PCI_CAP_ID_AGP3 0x0E /* AGP Target PCI-PCI bridge */
#define PCI_CAP_ID_SECDEV 0x0F /* Secure Device */
#define PCI_CAP_ID_EXP 0x10 /* PCI Express */
#define PCI_CAP_ID_MSIX 0x11 /* MSI-X */
#define PCI_CAP_ID_SATA 0x12 /* SATA Data/Index Conf. */
#define PCI_CAP_ID_AF 0x13 /* PCI Advanced Features */
#define PCI_CAP_ID_EA 0x14 /* PCI Enhanced Allocation */
#define PCI_CAP_ID_MAX PCI_CAP_ID_EA
#define PCI_CAP_LIST_NEXT 1 /* Next capability in the list */
#define PCI_CAP_FLAGS 2 /* Capability defined flags (16 bits) */
#define PCI_CAP_SIZEOF 4
/* Power Management Registers */
#define PCI_PM_PMC 2 /* PM Capabilities Register */
#define PCI_PM_CAP_VER_MASK 0x0007 /* Version */
#define PCI_PM_CAP_PME_CLOCK 0x0008 /* PME clock required */
#define PCI_PM_CAP_RESERVED 0x0010 /* Reserved field */
#define PCI_PM_CAP_DSI 0x0020 /* Device specific initialization */
#define PCI_PM_CAP_AUX_POWER 0x01C0 /* Auxiliary power support mask */
#define PCI_PM_CAP_D1 0x0200 /* D1 power state support */
#define PCI_PM_CAP_D2 0x0400 /* D2 power state support */
#define PCI_PM_CAP_PME 0x0800 /* PME pin supported */
#define PCI_PM_CAP_PME_MASK 0xF800 /* PME Mask of all supported states */
#define PCI_PM_CAP_PME_D0 0x0800 /* PME# from D0 */
#define PCI_PM_CAP_PME_D1 0x1000 /* PME# from D1 */
#define PCI_PM_CAP_PME_D2 0x2000 /* PME# from D2 */
#define PCI_PM_CAP_PME_D3 0x4000 /* PME# from D3 (hot) */
#define PCI_PM_CAP_PME_D3cold 0x8000 /* PME# from D3 (cold) */
#define PCI_PM_CAP_PME_SHIFT 11 /* Start of the PME Mask in PMC */
#define PCI_PM_CTRL 4 /* PM control and status register */
#define PCI_PM_CTRL_STATE_MASK 0x0003 /* Current power state (D0 to D3) */
#define PCI_PM_CTRL_NO_SOFT_RESET 0x0008 /* No reset for D3hot->D0 */
#define PCI_PM_CTRL_PME_ENABLE 0x0100 /* PME pin enable */
#define PCI_PM_CTRL_DATA_SEL_MASK 0x1e00 /* Data select (??) */
#define PCI_PM_CTRL_DATA_SCALE_MASK 0x6000 /* Data scale (??) */
#define PCI_PM_CTRL_PME_STATUS 0x8000 /* PME pin status */
#define PCI_PM_PPB_EXTENSIONS 6 /* PPB support extensions (??) */
#define PCI_PM_PPB_B2_B3 0x40 /* Stop clock when in D3hot (??) */
#define PCI_PM_BPCC_ENABLE 0x80 /* Bus power/clock control enable (??) */
#define PCI_PM_DATA_REGISTER 7 /* (??) */
#define PCI_PM_SIZEOF 8
/* AGP registers */
#define PCI_AGP_VERSION 2 /* BCD version number */
#define PCI_AGP_RFU 3 /* Rest of capability flags */
#define PCI_AGP_STATUS 4 /* Status register */
#define PCI_AGP_STATUS_RQ_MASK 0xff000000 /* Maximum number of requests - 1 */
#define PCI_AGP_STATUS_SBA 0x0200 /* Sideband addressing supported */
#define PCI_AGP_STATUS_64BIT 0x0020 /* 64-bit addressing supported */
#define PCI_AGP_STATUS_FW 0x0010 /* FW transfers supported */
#define PCI_AGP_STATUS_RATE4 0x0004 /* 4x transfer rate supported */
#define PCI_AGP_STATUS_RATE2 0x0002 /* 2x transfer rate supported */
#define PCI_AGP_STATUS_RATE1 0x0001 /* 1x transfer rate supported */
#define PCI_AGP_COMMAND 8 /* Control register */
#define PCI_AGP_COMMAND_RQ_MASK 0xff000000 /* Master: Maximum number of requests */
#define PCI_AGP_COMMAND_SBA 0x0200 /* Sideband addressing enabled */
#define PCI_AGP_COMMAND_AGP 0x0100 /* Allow processing of AGP transactions */
#define PCI_AGP_COMMAND_64BIT 0x0020 /* Allow processing of 64-bit addresses */
#define PCI_AGP_COMMAND_FW 0x0010 /* Force FW transfers */
#define PCI_AGP_COMMAND_RATE4 0x0004 /* Use 4x rate */
#define PCI_AGP_COMMAND_RATE2 0x0002 /* Use 2x rate */
#define PCI_AGP_COMMAND_RATE1 0x0001 /* Use 1x rate */
#define PCI_AGP_SIZEOF 12
/* Vital Product Data */
#define PCI_VPD_ADDR 2 /* Address to access (15 bits!) */
#define PCI_VPD_ADDR_MASK 0x7fff /* Address mask */
#define PCI_VPD_ADDR_F 0x8000 /* Write 0, 1 indicates completion */
#define PCI_VPD_DATA 4 /* 32-bits of data returned here */
#define PCI_CAP_VPD_SIZEOF 8
/* Slot Identification */
#define PCI_SID_ESR 2 /* Expansion Slot Register */
#define PCI_SID_ESR_NSLOTS 0x1f /* Number of expansion slots available */
#define PCI_SID_ESR_FIC 0x20 /* First In Chassis Flag */
#define PCI_SID_CHASSIS_NR 3 /* Chassis Number */
/* Message Signalled Interrupts registers */
#define PCI_MSI_FLAGS 2 /* Message Control */
#define PCI_MSI_FLAGS_ENABLE 0x0001 /* MSI feature enabled */
#define PCI_MSI_FLAGS_QMASK 0x000e /* Maximum queue size available */
#define PCI_MSI_FLAGS_QSIZE 0x0070 /* Message queue size configured */
#define PCI_MSI_FLAGS_64BIT 0x0080 /* 64-bit addresses allowed */
#define PCI_MSI_FLAGS_MASKBIT 0x0100 /* Per-vector masking capable */
#define PCI_MSI_RFU 3 /* Rest of capability flags */
#define PCI_MSI_ADDRESS_LO 4 /* Lower 32 bits */
#define PCI_MSI_ADDRESS_HI 8 /* Upper 32 bits (if PCI_MSI_FLAGS_64BIT set) */
#define PCI_MSI_DATA_32 8 /* 16 bits of data for 32-bit devices */
#define PCI_MSI_MASK_32 12 /* Mask bits register for 32-bit devices */
#define PCI_MSI_PENDING_32 16 /* Pending intrs for 32-bit devices */
#define PCI_MSI_DATA_64 12 /* 16 bits of data for 64-bit devices */
#define PCI_MSI_MASK_64 16 /* Mask bits register for 64-bit devices */
#define PCI_MSI_PENDING_64 20 /* Pending intrs for 64-bit devices */
/* MSI-X registers */
#define PCI_MSIX_FLAGS 2 /* Message Control */
#define PCI_MSIX_FLAGS_QSIZE 0x07FF /* Table size */
#define PCI_MSIX_FLAGS_MASKALL 0x4000 /* Mask all vectors for this function */
#define PCI_MSIX_FLAGS_ENABLE 0x8000 /* MSI-X enable */
#define PCI_MSIX_TABLE 4 /* Table offset */
#define PCI_MSIX_TABLE_BIR 0x00000007 /* BAR index */
#define PCI_MSIX_TABLE_OFFSET 0xfffffff8 /* Offset into specified BAR */
#define PCI_MSIX_PBA 8 /* Pending Bit Array offset */
#define PCI_MSIX_PBA_BIR 0x00000007 /* BAR index */
#define PCI_MSIX_PBA_OFFSET 0xfffffff8 /* Offset into specified BAR */
#define PCI_MSIX_FLAGS_BIRMASK PCI_MSIX_PBA_BIR /* deprecated */
#define PCI_CAP_MSIX_SIZEOF 12 /* size of MSIX registers */
/* MSI-X Table entry format */
#define PCI_MSIX_ENTRY_SIZE 16
#define PCI_MSIX_ENTRY_LOWER_ADDR 0
#define PCI_MSIX_ENTRY_UPPER_ADDR 4
#define PCI_MSIX_ENTRY_DATA 8
#define PCI_MSIX_ENTRY_VECTOR_CTRL 12
#define PCI_MSIX_ENTRY_CTRL_MASKBIT 1
/* CompactPCI Hotswap Register */
#define PCI_CHSWP_CSR 2 /* Control and Status Register */
#define PCI_CHSWP_DHA 0x01 /* Device Hiding Arm */
#define PCI_CHSWP_EIM 0x02 /* ENUM# Signal Mask */
#define PCI_CHSWP_PIE 0x04 /* Pending Insert or Extract */
#define PCI_CHSWP_LOO 0x08 /* LED On / Off */
#define PCI_CHSWP_PI 0x30 /* Programming Interface */
#define PCI_CHSWP_EXT 0x40 /* ENUM# status - extraction */
#define PCI_CHSWP_INS 0x80 /* ENUM# status - insertion */
/* PCI Advanced Feature registers */
#define PCI_AF_LENGTH 2
#define PCI_AF_CAP 3
#define PCI_AF_CAP_TP 0x01
#define PCI_AF_CAP_FLR 0x02
#define PCI_AF_CTRL 4
#define PCI_AF_CTRL_FLR 0x01
#define PCI_AF_STATUS 5
#define PCI_AF_STATUS_TP 0x01
#define PCI_CAP_AF_SIZEOF 6 /* size of AF registers */
/* PCI Enhanced Allocation registers */
#define PCI_EA_NUM_ENT 2 /* Number of Capability Entries */
#define PCI_EA_NUM_ENT_MASK 0x3f /* Num Entries Mask */
#define PCI_EA_FIRST_ENT 4 /* First EA Entry in List */
#define PCI_EA_FIRST_ENT_BRIDGE 8 /* First EA Entry for Bridges */
#define PCI_EA_ES 0x00000007 /* Entry Size */
#define PCI_EA_BEI 0x000000f0 /* BAR Equivalent Indicator */
/* 0-5 map to BARs 0-5 respectively */
#define PCI_EA_BEI_BAR0 0
#define PCI_EA_BEI_BAR5 5
#define PCI_EA_BEI_BRIDGE 6 /* Resource behind bridge */
#define PCI_EA_BEI_ENI 7 /* Equivalent Not Indicated */
#define PCI_EA_BEI_ROM 8 /* Expansion ROM */
/* 9-14 map to VF BARs 0-5 respectively */
#define PCI_EA_BEI_VF_BAR0 9
#define PCI_EA_BEI_VF_BAR5 14
#define PCI_EA_BEI_RESERVED 15 /* Reserved - Treat like ENI */
#define PCI_EA_PP 0x0000ff00 /* Primary Properties */
#define PCI_EA_SP 0x00ff0000 /* Secondary Properties */
#define PCI_EA_P_MEM 0x00 /* Non-Prefetch Memory */
#define PCI_EA_P_MEM_PREFETCH 0x01 /* Prefetchable Memory */
#define PCI_EA_P_IO 0x02 /* I/O Space */
#define PCI_EA_P_VF_MEM_PREFETCH 0x03 /* VF Prefetchable Memory */
#define PCI_EA_P_VF_MEM 0x04 /* VF Non-Prefetch Memory */
#define PCI_EA_P_BRIDGE_MEM 0x05 /* Bridge Non-Prefetch Memory */
#define PCI_EA_P_BRIDGE_MEM_PREFETCH 0x06 /* Bridge Prefetchable Memory */
#define PCI_EA_P_BRIDGE_IO 0x07 /* Bridge I/O Space */
/* 0x08-0xfc reserved */
#define PCI_EA_P_MEM_RESERVED 0xfd /* Reserved Memory */
#define PCI_EA_P_IO_RESERVED 0xfe /* Reserved I/O Space */
#define PCI_EA_P_UNAVAILABLE 0xff /* Entry Unavailable */
#define PCI_EA_WRITABLE 0x40000000 /* Writable: 1 = RW, 0 = HwInit */
#define PCI_EA_ENABLE 0x80000000 /* Enable for this entry */
#define PCI_EA_BASE 4 /* Base Address Offset */
#define PCI_EA_MAX_OFFSET 8 /* MaxOffset (resource length) */
/* bit 0 is reserved */
#define PCI_EA_IS_64 0x00000002 /* 64-bit field flag */
#define PCI_EA_FIELD_MASK 0xfffffffc /* For Base & Max Offset */
/* PCI-X registers (Type 0 (non-bridge) devices) */
#define PCI_X_CMD 2 /* Modes & Features */
#define PCI_X_CMD_DPERR_E 0x0001 /* Data Parity Error Recovery Enable */
#define PCI_X_CMD_ERO 0x0002 /* Enable Relaxed Ordering */
#define PCI_X_CMD_READ_512 0x0000 /* 512 byte maximum read byte count */
#define PCI_X_CMD_READ_1K 0x0004 /* 1Kbyte maximum read byte count */
#define PCI_X_CMD_READ_2K 0x0008 /* 2Kbyte maximum read byte count */
#define PCI_X_CMD_READ_4K 0x000c /* 4Kbyte maximum read byte count */
#define PCI_X_CMD_MAX_READ 0x000c /* Max Memory Read Byte Count */
/* Max # of outstanding split transactions */
#define PCI_X_CMD_SPLIT_1 0x0000 /* Max 1 */
#define PCI_X_CMD_SPLIT_2 0x0010 /* Max 2 */
#define PCI_X_CMD_SPLIT_3 0x0020 /* Max 3 */
#define PCI_X_CMD_SPLIT_4 0x0030 /* Max 4 */
#define PCI_X_CMD_SPLIT_8 0x0040 /* Max 8 */
#define PCI_X_CMD_SPLIT_12 0x0050 /* Max 12 */
#define PCI_X_CMD_SPLIT_16 0x0060 /* Max 16 */
#define PCI_X_CMD_SPLIT_32 0x0070 /* Max 32 */
#define PCI_X_CMD_MAX_SPLIT 0x0070 /* Max Outstanding Split Transactions */
#define PCI_X_CMD_VERSION(x) (((x) >> 12) & 3) /* Version */
#define PCI_X_STATUS 4 /* PCI-X capabilities */
#define PCI_X_STATUS_DEVFN 0x000000ff /* A copy of devfn */
#define PCI_X_STATUS_BUS 0x0000ff00 /* A copy of bus nr */
#define PCI_X_STATUS_64BIT 0x00010000 /* 64-bit device */
#define PCI_X_STATUS_133MHZ 0x00020000 /* 133 MHz capable */
#define PCI_X_STATUS_SPL_DISC 0x00040000 /* Split Completion Discarded */
#define PCI_X_STATUS_UNX_SPL 0x00080000 /* Unexpected Split Completion */
#define PCI_X_STATUS_COMPLEX 0x00100000 /* Device Complexity */
#define PCI_X_STATUS_MAX_READ 0x00600000 /* Designed Max Memory Read Count */
#define PCI_X_STATUS_MAX_SPLIT 0x03800000 /* Designed Max Outstanding Split Transactions */
#define PCI_X_STATUS_MAX_CUM 0x1c000000 /* Designed Max Cumulative Read Size */
#define PCI_X_STATUS_SPL_ERR 0x20000000 /* Rcvd Split Completion Error Msg */
#define PCI_X_STATUS_266MHZ 0x40000000 /* 266 MHz capable */
#define PCI_X_STATUS_533MHZ 0x80000000 /* 533 MHz capable */
#define PCI_X_ECC_CSR 8 /* ECC control and status */
#define PCI_CAP_PCIX_SIZEOF_V0 8 /* size of registers for Version 0 */
#define PCI_CAP_PCIX_SIZEOF_V1 24 /* size for Version 1 */
#define PCI_CAP_PCIX_SIZEOF_V2 PCI_CAP_PCIX_SIZEOF_V1 /* Same for v2 */
/* PCI-X registers (Type 1 (bridge) devices) */
#define PCI_X_BRIDGE_SSTATUS 2 /* Secondary Status */
#define PCI_X_SSTATUS_64BIT 0x0001 /* Secondary AD interface is 64 bits */
#define PCI_X_SSTATUS_133MHZ 0x0002 /* 133 MHz capable */
#define PCI_X_SSTATUS_FREQ 0x03c0 /* Secondary Bus Mode and Frequency */
#define PCI_X_SSTATUS_VERS 0x3000 /* PCI-X Capability Version */
#define PCI_X_SSTATUS_V1 0x1000 /* Mode 2, not Mode 1 */
#define PCI_X_SSTATUS_V2 0x2000 /* Mode 1 or Modes 1 and 2 */
#define PCI_X_SSTATUS_266MHZ 0x4000 /* 266 MHz capable */
#define PCI_X_SSTATUS_533MHZ 0x8000 /* 533 MHz capable */
#define PCI_X_BRIDGE_STATUS 4 /* Bridge Status */
/* PCI Bridge Subsystem ID registers */
#define PCI_SSVID_VENDOR_ID 4 /* PCI Bridge subsystem vendor ID */
#define PCI_SSVID_DEVICE_ID 6 /* PCI Bridge subsystem device ID */
/* PCI Express capability registers */
#define PCI_EXP_FLAGS 2 /* Capabilities register */
#define PCI_EXP_FLAGS_VERS 0x000f /* Capability version */
#define PCI_EXP_FLAGS_TYPE 0x00f0 /* Device/Port type */
#define PCI_EXP_TYPE_ENDPOINT 0x0 /* Express Endpoint */
#define PCI_EXP_TYPE_LEG_END 0x1 /* Legacy Endpoint */
#define PCI_EXP_TYPE_ROOT_PORT 0x4 /* Root Port */
#define PCI_EXP_TYPE_UPSTREAM 0x5 /* Upstream Port */
#define PCI_EXP_TYPE_DOWNSTREAM 0x6 /* Downstream Port */
#define PCI_EXP_TYPE_PCI_BRIDGE 0x7 /* PCIe to PCI/PCI-X Bridge */
#define PCI_EXP_TYPE_PCIE_BRIDGE 0x8 /* PCI/PCI-X to PCIe Bridge */
#define PCI_EXP_TYPE_RC_END 0x9 /* Root Complex Integrated Endpoint */
#define PCI_EXP_TYPE_RC_EC 0xa /* Root Complex Event Collector */
#define PCI_EXP_FLAGS_SLOT 0x0100 /* Slot implemented */
#define PCI_EXP_FLAGS_IRQ 0x3e00 /* Interrupt message number */
#define PCI_EXP_DEVCAP 4 /* Device capabilities */
#define PCI_EXP_DEVCAP_PAYLOAD 0x00000007 /* Max_Payload_Size */
#define PCI_EXP_DEVCAP_PHANTOM 0x00000018 /* Phantom functions */
#define PCI_EXP_DEVCAP_EXT_TAG 0x00000020 /* Extended tags */
#define PCI_EXP_DEVCAP_L0S 0x000001c0 /* L0s Acceptable Latency */
#define PCI_EXP_DEVCAP_L1 0x00000e00 /* L1 Acceptable Latency */
#define PCI_EXP_DEVCAP_ATN_BUT 0x00001000 /* Attention Button Present */
#define PCI_EXP_DEVCAP_ATN_IND 0x00002000 /* Attention Indicator Present */
#define PCI_EXP_DEVCAP_PWR_IND 0x00004000 /* Power Indicator Present */
#define PCI_EXP_DEVCAP_RBER 0x00008000 /* Role-Based Error Reporting */
#define PCI_EXP_DEVCAP_PWR_VAL 0x03fc0000 /* Slot Power Limit Value */
#define PCI_EXP_DEVCAP_PWR_SCL 0x0c000000 /* Slot Power Limit Scale */
#define PCI_EXP_DEVCAP_FLR 0x10000000 /* Function Level Reset */
#define PCI_EXP_DEVCTL 8 /* Device Control */
#define PCI_EXP_DEVCTL_CERE 0x0001 /* Correctable Error Reporting En. */
#define PCI_EXP_DEVCTL_NFERE 0x0002 /* Non-Fatal Error Reporting Enable */
#define PCI_EXP_DEVCTL_FERE 0x0004 /* Fatal Error Reporting Enable */
#define PCI_EXP_DEVCTL_URRE 0x0008 /* Unsupported Request Reporting En. */
#define PCI_EXP_DEVCTL_RELAX_EN 0x0010 /* Enable relaxed ordering */
#define PCI_EXP_DEVCTL_PAYLOAD 0x00e0 /* Max_Payload_Size */
#define PCI_EXP_DEVCTL_EXT_TAG 0x0100 /* Extended Tag Field Enable */
#define PCI_EXP_DEVCTL_PHANTOM 0x0200 /* Phantom Functions Enable */
#define PCI_EXP_DEVCTL_AUX_PME 0x0400 /* Auxiliary Power PM Enable */
#define PCI_EXP_DEVCTL_NOSNOOP_EN 0x0800 /* Enable No Snoop */
#define PCI_EXP_DEVCTL_READRQ 0x7000 /* Max_Read_Request_Size */
#define PCI_EXP_DEVCTL_READRQ_128B 0x0000 /* 128 Bytes */
#define PCI_EXP_DEVCTL_READRQ_256B 0x1000 /* 256 Bytes */
#define PCI_EXP_DEVCTL_READRQ_512B 0x2000 /* 512 Bytes */
#define PCI_EXP_DEVCTL_READRQ_1024B 0x3000 /* 1024 Bytes */
#define PCI_EXP_DEVCTL_BCR_FLR 0x8000 /* Bridge Configuration Retry / FLR */
#define PCI_EXP_DEVSTA 10 /* Device Status */
#define PCI_EXP_DEVSTA_CED 0x0001 /* Correctable Error Detected */
#define PCI_EXP_DEVSTA_NFED 0x0002 /* Non-Fatal Error Detected */
#define PCI_EXP_DEVSTA_FED 0x0004 /* Fatal Error Detected */
#define PCI_EXP_DEVSTA_URD 0x0008 /* Unsupported Request Detected */
#define PCI_EXP_DEVSTA_AUXPD 0x0010 /* AUX Power Detected */
#define PCI_EXP_DEVSTA_TRPND 0x0020 /* Transactions Pending */
#define PCI_EXP_LNKCAP 12 /* Link Capabilities */
#define PCI_EXP_LNKCAP_SLS 0x0000000f /* Supported Link Speeds */
#define PCI_EXP_LNKCAP_SLS_2_5GB 0x00000001 /* LNKCAP2 SLS Vector bit 0 */
#define PCI_EXP_LNKCAP_SLS_5_0GB 0x00000002 /* LNKCAP2 SLS Vector bit 1 */
#define PCI_EXP_LNKCAP_MLW 0x000003f0 /* Maximum Link Width */
#define PCI_EXP_LNKCAP_ASPMS 0x00000c00 /* ASPM Support */
#define PCI_EXP_LNKCAP_L0SEL 0x00007000 /* L0s Exit Latency */
#define PCI_EXP_LNKCAP_L1EL 0x00038000 /* L1 Exit Latency */
#define PCI_EXP_LNKCAP_CLKPM 0x00040000 /* Clock Power Management */
#define PCI_EXP_LNKCAP_SDERC 0x00080000 /* Surprise Down Error Reporting Capable */
#define PCI_EXP_LNKCAP_DLLLARC 0x00100000 /* Data Link Layer Link Active Reporting Capable */
#define PCI_EXP_LNKCAP_LBNC 0x00200000 /* Link Bandwidth Notification Capability */
#define PCI_EXP_LNKCAP_PN 0xff000000 /* Port Number */
#define PCI_EXP_LNKCTL 16 /* Link Control */
#define PCI_EXP_LNKCTL_ASPMC 0x0003 /* ASPM Control */
#define PCI_EXP_LNKCTL_ASPM_L0S 0x0001 /* L0s Enable */
#define PCI_EXP_LNKCTL_ASPM_L1 0x0002 /* L1 Enable */
#define PCI_EXP_LNKCTL_RCB 0x0008 /* Read Completion Boundary */
#define PCI_EXP_LNKCTL_LD 0x0010 /* Link Disable */
#define PCI_EXP_LNKCTL_RL 0x0020 /* Retrain Link */
#define PCI_EXP_LNKCTL_CCC 0x0040 /* Common Clock Configuration */
#define PCI_EXP_LNKCTL_ES 0x0080 /* Extended Synch */
#define PCI_EXP_LNKCTL_CLKREQ_EN 0x0100 /* Enable clkreq */
#define PCI_EXP_LNKCTL_HAWD 0x0200 /* Hardware Autonomous Width Disable */
#define PCI_EXP_LNKCTL_LBMIE 0x0400 /* Link Bandwidth Management Interrupt Enable */
#define PCI_EXP_LNKCTL_LABIE 0x0800 /* Link Autonomous Bandwidth Interrupt Enable */
#define PCI_EXP_LNKSTA 18 /* Link Status */
#define PCI_EXP_LNKSTA_CLS 0x000f /* Current Link Speed */
#define PCI_EXP_LNKSTA_CLS_2_5GB 0x0001 /* Current Link Speed 2.5GT/s */
#define PCI_EXP_LNKSTA_CLS_5_0GB 0x0002 /* Current Link Speed 5.0GT/s */
#define PCI_EXP_LNKSTA_CLS_8_0GB 0x0003 /* Current Link Speed 8.0GT/s */
#define PCI_EXP_LNKSTA_NLW 0x03f0 /* Negotiated Link Width */
#define PCI_EXP_LNKSTA_NLW_X1 0x0010 /* Current Link Width x1 */
#define PCI_EXP_LNKSTA_NLW_X2 0x0020 /* Current Link Width x2 */
#define PCI_EXP_LNKSTA_NLW_X4 0x0040 /* Current Link Width x4 */
#define PCI_EXP_LNKSTA_NLW_X8 0x0080 /* Current Link Width x8 */
#define PCI_EXP_LNKSTA_NLW_SHIFT 4 /* start of NLW mask in link status */
#define PCI_EXP_LNKSTA_LT 0x0800 /* Link Training */
#define PCI_EXP_LNKSTA_SLC 0x1000 /* Slot Clock Configuration */
#define PCI_EXP_LNKSTA_DLLLA 0x2000 /* Data Link Layer Link Active */
#define PCI_EXP_LNKSTA_LBMS 0x4000 /* Link Bandwidth Management Status */
#define PCI_EXP_LNKSTA_LABS 0x8000 /* Link Autonomous Bandwidth Status */
#define PCI_CAP_EXP_ENDPOINT_SIZEOF_V1 20 /* v1 endpoints end here */
#define PCI_EXP_SLTCAP 20 /* Slot Capabilities */
#define PCI_EXP_SLTCAP_ABP 0x00000001 /* Attention Button Present */
#define PCI_EXP_SLTCAP_PCP 0x00000002 /* Power Controller Present */
#define PCI_EXP_SLTCAP_MRLSP 0x00000004 /* MRL Sensor Present */
#define PCI_EXP_SLTCAP_AIP 0x00000008 /* Attention Indicator Present */
#define PCI_EXP_SLTCAP_PIP 0x00000010 /* Power Indicator Present */
#define PCI_EXP_SLTCAP_HPS 0x00000020 /* Hot-Plug Surprise */
#define PCI_EXP_SLTCAP_HPC 0x00000040 /* Hot-Plug Capable */
#define PCI_EXP_SLTCAP_SPLV 0x00007f80 /* Slot Power Limit Value */
#define PCI_EXP_SLTCAP_SPLS 0x00018000 /* Slot Power Limit Scale */
#define PCI_EXP_SLTCAP_EIP 0x00020000 /* Electromechanical Interlock Present */
#define PCI_EXP_SLTCAP_NCCS 0x00040000 /* No Command Completed Support */
#define PCI_EXP_SLTCAP_PSN 0xfff80000 /* Physical Slot Number */
#define PCI_EXP_SLTCTL 24 /* Slot Control */
#define PCI_EXP_SLTCTL_ABPE 0x0001 /* Attention Button Pressed Enable */
#define PCI_EXP_SLTCTL_PFDE 0x0002 /* Power Fault Detected Enable */
#define PCI_EXP_SLTCTL_MRLSCE 0x0004 /* MRL Sensor Changed Enable */
#define PCI_EXP_SLTCTL_PDCE 0x0008 /* Presence Detect Changed Enable */
#define PCI_EXP_SLTCTL_CCIE 0x0010 /* Command Completed Interrupt Enable */
#define PCI_EXP_SLTCTL_HPIE 0x0020 /* Hot-Plug Interrupt Enable */
#define PCI_EXP_SLTCTL_AIC 0x00c0 /* Attention Indicator Control */
#define PCI_EXP_SLTCTL_ATTN_IND_ON 0x0040 /* Attention Indicator on */
#define PCI_EXP_SLTCTL_ATTN_IND_BLINK 0x0080 /* Attention Indicator blinking */
#define PCI_EXP_SLTCTL_ATTN_IND_OFF 0x00c0 /* Attention Indicator off */
#define PCI_EXP_SLTCTL_PIC 0x0300 /* Power Indicator Control */
#define PCI_EXP_SLTCTL_PWR_IND_ON 0x0100 /* Power Indicator on */
#define PCI_EXP_SLTCTL_PWR_IND_BLINK 0x0200 /* Power Indicator blinking */
#define PCI_EXP_SLTCTL_PWR_IND_OFF 0x0300 /* Power Indicator off */
#define PCI_EXP_SLTCTL_PCC 0x0400 /* Power Controller Control */
#define PCI_EXP_SLTCTL_PWR_ON 0x0000 /* Power On */
#define PCI_EXP_SLTCTL_PWR_OFF 0x0400 /* Power Off */
#define PCI_EXP_SLTCTL_EIC 0x0800 /* Electromechanical Interlock Control */
#define PCI_EXP_SLTCTL_DLLSCE 0x1000 /* Data Link Layer State Changed Enable */
#define PCI_EXP_SLTSTA 26 /* Slot Status */
#define PCI_EXP_SLTSTA_ABP 0x0001 /* Attention Button Pressed */
#define PCI_EXP_SLTSTA_PFD 0x0002 /* Power Fault Detected */
#define PCI_EXP_SLTSTA_MRLSC 0x0004 /* MRL Sensor Changed */
#define PCI_EXP_SLTSTA_PDC 0x0008 /* Presence Detect Changed */
#define PCI_EXP_SLTSTA_CC 0x0010 /* Command Completed */
#define PCI_EXP_SLTSTA_MRLSS 0x0020 /* MRL Sensor State */
#define PCI_EXP_SLTSTA_PDS 0x0040 /* Presence Detect State */
#define PCI_EXP_SLTSTA_EIS 0x0080 /* Electromechanical Interlock Status */
#define PCI_EXP_SLTSTA_DLLSC 0x0100 /* Data Link Layer State Changed */
#define PCI_EXP_RTCTL 28 /* Root Control */
#define PCI_EXP_RTCTL_SECEE 0x0001 /* System Error on Correctable Error */
#define PCI_EXP_RTCTL_SENFEE 0x0002 /* System Error on Non-Fatal Error */
#define PCI_EXP_RTCTL_SEFEE 0x0004 /* System Error on Fatal Error */
#define PCI_EXP_RTCTL_PMEIE 0x0008 /* PME Interrupt Enable */
#define PCI_EXP_RTCTL_CRSSVE 0x0010 /* CRS Software Visibility Enable */
#define PCI_EXP_RTCAP 30 /* Root Capabilities */
#define PCI_EXP_RTCAP_CRSVIS 0x0001 /* CRS Software Visibility capability */
#define PCI_EXP_RTSTA 32 /* Root Status */
#define PCI_EXP_RTSTA_PME 0x00010000 /* PME status */
#define PCI_EXP_RTSTA_PENDING 0x00020000 /* PME pending */
/*
* The Device Capabilities 2, Device Status 2, Device Control 2,
* Link Capabilities 2, Link Status 2, Link Control 2,
* Slot Capabilities 2, Slot Status 2, and Slot Control 2 registers
* are only present on devices with PCIe Capability version 2.
* Use pcie_capability_read_word() and similar interfaces to use them
* safely.
*/
#define PCI_EXP_DEVCAP2 36 /* Device Capabilities 2 */
#define PCI_EXP_DEVCAP2_ARI 0x00000020 /* Alternative Routing-ID */
#define PCI_EXP_DEVCAP2_LTR 0x00000800 /* Latency tolerance reporting */
#define PCI_EXP_DEVCAP2_OBFF_MASK 0x000c0000 /* OBFF support mechanism */
#define PCI_EXP_DEVCAP2_OBFF_MSG 0x00040000 /* New message signaling */
#define PCI_EXP_DEVCAP2_OBFF_WAKE 0x00080000 /* Re-use WAKE# for OBFF */
#define PCI_EXP_DEVCTL2 40 /* Device Control 2 */
#define PCI_EXP_DEVCTL2_COMP_TIMEOUT 0x000f /* Completion Timeout Value */
#define PCI_EXP_DEVCTL2_ARI 0x0020 /* Alternative Routing-ID */
#define PCI_EXP_DEVCTL2_IDO_REQ_EN 0x0100 /* Allow IDO for requests */
#define PCI_EXP_DEVCTL2_IDO_CMP_EN 0x0200 /* Allow IDO for completions */
#define PCI_EXP_DEVCTL2_LTR_EN 0x0400 /* Enable LTR mechanism */
#define PCI_EXP_DEVCTL2_OBFF_MSGA_EN 0x2000 /* Enable OBFF Message type A */
#define PCI_EXP_DEVCTL2_OBFF_MSGB_EN 0x4000 /* Enable OBFF Message type B */
#define PCI_EXP_DEVCTL2_OBFF_WAKE_EN 0x6000 /* OBFF using WAKE# signaling */
#define PCI_EXP_DEVSTA2 42 /* Device Status 2 */
#define PCI_CAP_EXP_ENDPOINT_SIZEOF_V2 44 /* v2 endpoints end here */
#define PCI_EXP_LNKCAP2 44 /* Link Capabilities 2 */
#define PCI_EXP_LNKCAP2_SLS_2_5GB 0x00000002 /* Supported Speed 2.5GT/s */
#define PCI_EXP_LNKCAP2_SLS_5_0GB 0x00000004 /* Supported Speed 5.0GT/s */
#define PCI_EXP_LNKCAP2_SLS_8_0GB 0x00000008 /* Supported Speed 8.0GT/s */
#define PCI_EXP_LNKCAP2_CROSSLINK 0x00000100 /* Crosslink supported */
#define PCI_EXP_LNKCTL2 48 /* Link Control 2 */
#define PCI_EXP_LNKSTA2 50 /* Link Status 2 */
#define PCI_EXP_SLTCAP2 52 /* Slot Capabilities 2 */
#define PCI_EXP_SLTCTL2 56 /* Slot Control 2 */
#define PCI_EXP_SLTSTA2 58 /* Slot Status 2 */
/* Extended Capabilities (PCI-X 2.0 and Express) */
#define PCI_EXT_CAP_ID(header) (header & 0x0000ffff)
#define PCI_EXT_CAP_VER(header) ((header >> 16) & 0xf)
#define PCI_EXT_CAP_NEXT(header) ((header >> 20) & 0xffc)
#define PCI_EXT_CAP_ID_ERR 0x01 /* Advanced Error Reporting */
#define PCI_EXT_CAP_ID_VC 0x02 /* Virtual Channel Capability */
#define PCI_EXT_CAP_ID_DSN 0x03 /* Device Serial Number */
#define PCI_EXT_CAP_ID_PWR 0x04 /* Power Budgeting */
#define PCI_EXT_CAP_ID_RCLD 0x05 /* Root Complex Link Declaration */
#define PCI_EXT_CAP_ID_RCILC 0x06 /* Root Complex Internal Link Control */
#define PCI_EXT_CAP_ID_RCEC 0x07 /* Root Complex Event Collector */
#define PCI_EXT_CAP_ID_MFVC 0x08 /* Multi-Function VC Capability */
#define PCI_EXT_CAP_ID_VC9 0x09 /* same as _VC */
#define PCI_EXT_CAP_ID_RCRB 0x0A /* Root Complex RB? */
#define PCI_EXT_CAP_ID_VNDR 0x0B /* Vendor-Specific */
#define PCI_EXT_CAP_ID_CAC 0x0C /* Config Access - obsolete */
#define PCI_EXT_CAP_ID_ACS 0x0D /* Access Control Services */
#define PCI_EXT_CAP_ID_ARI 0x0E /* Alternate Routing ID */
#define PCI_EXT_CAP_ID_ATS 0x0F /* Address Translation Services */
#define PCI_EXT_CAP_ID_SRIOV 0x10 /* Single Root I/O Virtualization */
#define PCI_EXT_CAP_ID_MRIOV 0x11 /* Multi Root I/O Virtualization */
#define PCI_EXT_CAP_ID_MCAST 0x12 /* Multicast */
#define PCI_EXT_CAP_ID_PRI 0x13 /* Page Request Interface */
#define PCI_EXT_CAP_ID_AMD_XXX 0x14 /* Reserved for AMD */
#define PCI_EXT_CAP_ID_REBAR 0x15 /* Resizable BAR */
#define PCI_EXT_CAP_ID_DPA 0x16 /* Dynamic Power Allocation */
#define PCI_EXT_CAP_ID_TPH 0x17 /* TPH Requester */
#define PCI_EXT_CAP_ID_LTR 0x18 /* Latency Tolerance Reporting */
#define PCI_EXT_CAP_ID_SECPCI 0x19 /* Secondary PCIe Capability */
#define PCI_EXT_CAP_ID_PMUX 0x1A /* Protocol Multiplexing */
#define PCI_EXT_CAP_ID_PASID 0x1B /* Process Address Space ID */
#define PCI_EXT_CAP_ID_DPC 0x1D /* Downstream Port Containment */
#define PCI_EXT_CAP_ID_MAX PCI_EXT_CAP_ID_DPC
#define PCI_EXT_CAP_DSN_SIZEOF 12
#define PCI_EXT_CAP_MCAST_ENDPOINT_SIZEOF 40
/* Advanced Error Reporting */
#define PCI_ERR_UNCOR_STATUS 4 /* Uncorrectable Error Status */
#define PCI_ERR_UNC_UND 0x00000001 /* Undefined */
#define PCI_ERR_UNC_DLP 0x00000010 /* Data Link Protocol */
#define PCI_ERR_UNC_SURPDN 0x00000020 /* Surprise Down */
#define PCI_ERR_UNC_POISON_TLP 0x00001000 /* Poisoned TLP */
#define PCI_ERR_UNC_FCP 0x00002000 /* Flow Control Protocol */
#define PCI_ERR_UNC_COMP_TIME 0x00004000 /* Completion Timeout */
#define PCI_ERR_UNC_COMP_ABORT 0x00008000 /* Completer Abort */
#define PCI_ERR_UNC_UNX_COMP 0x00010000 /* Unexpected Completion */
#define PCI_ERR_UNC_RX_OVER 0x00020000 /* Receiver Overflow */
#define PCI_ERR_UNC_MALF_TLP 0x00040000 /* Malformed TLP */
#define PCI_ERR_UNC_ECRC 0x00080000 /* ECRC Error Status */
#define PCI_ERR_UNC_UNSUP 0x00100000 /* Unsupported Request */
#define PCI_ERR_UNC_ACSV 0x00200000 /* ACS Violation */
#define PCI_ERR_UNC_INTN 0x00400000 /* internal error */
#define PCI_ERR_UNC_MCBTLP 0x00800000 /* MC blocked TLP */
#define PCI_ERR_UNC_ATOMEG 0x01000000 /* Atomic egress blocked */
#define PCI_ERR_UNC_TLPPRE 0x02000000 /* TLP prefix blocked */
#define PCI_ERR_UNCOR_MASK 8 /* Uncorrectable Error Mask */
/* Same bits as above */
#define PCI_ERR_UNCOR_SEVER 12 /* Uncorrectable Error Severity */
/* Same bits as above */
#define PCI_ERR_COR_STATUS 16 /* Correctable Error Status */
#define PCI_ERR_COR_RCVR 0x00000001 /* Receiver Error Status */
#define PCI_ERR_COR_BAD_TLP 0x00000040 /* Bad TLP Status */
#define PCI_ERR_COR_BAD_DLLP 0x00000080 /* Bad DLLP Status */
#define PCI_ERR_COR_REP_ROLL 0x00000100 /* REPLAY_NUM Rollover */
#define PCI_ERR_COR_REP_TIMER 0x00001000 /* Replay Timer Timeout */
#define PCI_ERR_COR_ADV_NFAT 0x00002000 /* Advisory Non-Fatal */
#define PCI_ERR_COR_INTERNAL 0x00004000 /* Corrected Internal */
#define PCI_ERR_COR_LOG_OVER 0x00008000 /* Header Log Overflow */
#define PCI_ERR_COR_MASK 20 /* Correctable Error Mask */
/* Same bits as above */
#define PCI_ERR_CAP 24 /* Advanced Error Capabilities */
#define PCI_ERR_CAP_FEP(x) ((x) & 31) /* First Error Pointer */
#define PCI_ERR_CAP_ECRC_GENC 0x00000020 /* ECRC Generation Capable */
#define PCI_ERR_CAP_ECRC_GENE 0x00000040 /* ECRC Generation Enable */
#define PCI_ERR_CAP_ECRC_CHKC 0x00000080 /* ECRC Check Capable */
#define PCI_ERR_CAP_ECRC_CHKE 0x00000100 /* ECRC Check Enable */
#define PCI_ERR_HEADER_LOG 28 /* Header Log Register (16 bytes) */
#define PCI_ERR_ROOT_COMMAND 44 /* Root Error Command */
/* Correctable Err Reporting Enable */
#define PCI_ERR_ROOT_CMD_COR_EN 0x00000001
/* Non-fatal Err Reporting Enable */
#define PCI_ERR_ROOT_CMD_NONFATAL_EN 0x00000002
/* Fatal Err Reporting Enable */
#define PCI_ERR_ROOT_CMD_FATAL_EN 0x00000004
#define PCI_ERR_ROOT_STATUS 48
#define PCI_ERR_ROOT_COR_RCV 0x00000001 /* ERR_COR Received */
/* Multi ERR_COR Received */
#define PCI_ERR_ROOT_MULTI_COR_RCV 0x00000002
/* ERR_FATAL/NONFATAL Received */
#define PCI_ERR_ROOT_UNCOR_RCV 0x00000004
/* Multi ERR_FATAL/NONFATAL Received */
#define PCI_ERR_ROOT_MULTI_UNCOR_RCV 0x00000008
#define PCI_ERR_ROOT_FIRST_FATAL 0x00000010 /* First Fatal */
#define PCI_ERR_ROOT_NONFATAL_RCV 0x00000020 /* Non-Fatal Received */
#define PCI_ERR_ROOT_FATAL_RCV 0x00000040 /* Fatal Received */
#define PCI_ERR_ROOT_ERR_SRC 52 /* Error Source Identification */
/* Virtual Channel */
#define PCI_VC_PORT_CAP1 4
#define PCI_VC_CAP1_EVCC 0x00000007 /* extended VC count */
#define PCI_VC_CAP1_LPEVCC 0x00000070 /* low prio extended VC count */
#define PCI_VC_CAP1_ARB_SIZE 0x00000c00
#define PCI_VC_PORT_CAP2 8
#define PCI_VC_CAP2_32_PHASE 0x00000002
#define PCI_VC_CAP2_64_PHASE 0x00000004
#define PCI_VC_CAP2_128_PHASE 0x00000008
#define PCI_VC_CAP2_ARB_OFF 0xff000000
#define PCI_VC_PORT_CTRL 12
#define PCI_VC_PORT_CTRL_LOAD_TABLE 0x00000001
#define PCI_VC_PORT_STATUS 14
#define PCI_VC_PORT_STATUS_TABLE 0x00000001
#define PCI_VC_RES_CAP 16
#define PCI_VC_RES_CAP_32_PHASE 0x00000002
#define PCI_VC_RES_CAP_64_PHASE 0x00000004
#define PCI_VC_RES_CAP_128_PHASE 0x00000008
#define PCI_VC_RES_CAP_128_PHASE_TB 0x00000010
#define PCI_VC_RES_CAP_256_PHASE 0x00000020
#define PCI_VC_RES_CAP_ARB_OFF 0xff000000
#define PCI_VC_RES_CTRL 20
#define PCI_VC_RES_CTRL_LOAD_TABLE 0x00010000
#define PCI_VC_RES_CTRL_ARB_SELECT 0x000e0000
#define PCI_VC_RES_CTRL_ID 0x07000000
#define PCI_VC_RES_CTRL_ENABLE 0x80000000
#define PCI_VC_RES_STATUS 26
#define PCI_VC_RES_STATUS_TABLE 0x00000001
#define PCI_VC_RES_STATUS_NEGO 0x00000002
#define PCI_CAP_VC_BASE_SIZEOF 0x10
#define PCI_CAP_VC_PER_VC_SIZEOF 0x0C
/* Power Budgeting */
#define PCI_PWR_DSR 4 /* Data Select Register */
#define PCI_PWR_DATA 8 /* Data Register */
#define PCI_PWR_DATA_BASE(x) ((x) & 0xff) /* Base Power */
#define PCI_PWR_DATA_SCALE(x) (((x) >> 8) & 3) /* Data Scale */
#define PCI_PWR_DATA_PM_SUB(x) (((x) >> 10) & 7) /* PM Sub State */
#define PCI_PWR_DATA_PM_STATE(x) (((x) >> 13) & 3) /* PM State */
#define PCI_PWR_DATA_TYPE(x) (((x) >> 15) & 7) /* Type */
#define PCI_PWR_DATA_RAIL(x) (((x) >> 18) & 7) /* Power Rail */
#define PCI_PWR_CAP 12 /* Capability */
#define PCI_PWR_CAP_BUDGET(x) ((x) & 1) /* Included in system budget */
#define PCI_EXT_CAP_PWR_SIZEOF 16
/* Vendor-Specific (VSEC, PCI_EXT_CAP_ID_VNDR) */
#define PCI_VNDR_HEADER 4 /* Vendor-Specific Header */
#define PCI_VNDR_HEADER_ID(x) ((x) & 0xffff)
#define PCI_VNDR_HEADER_REV(x) (((x) >> 16) & 0xf)
#define PCI_VNDR_HEADER_LEN(x) (((x) >> 20) & 0xfff)
/*
* HyperTransport sub capability types
*
* Unfortunately there are both 3 bit and 5 bit capability types defined
* in the HT spec, catering for that is a little messy. You probably don't
* want to use these directly, just use pci_find_ht_capability() and it
* will do the right thing for you.
*/
#define HT_3BIT_CAP_MASK 0xE0
#define HT_CAPTYPE_SLAVE 0x00 /* Slave/Primary link configuration */
#define HT_CAPTYPE_HOST 0x20 /* Host/Secondary link configuration */
#define HT_5BIT_CAP_MASK 0xF8
#define HT_CAPTYPE_IRQ 0x80 /* IRQ Configuration */
#define HT_CAPTYPE_REMAPPING_40 0xA0 /* 40 bit address remapping */
#define HT_CAPTYPE_REMAPPING_64 0xA2 /* 64 bit address remapping */
#define HT_CAPTYPE_UNITID_CLUMP 0x90 /* Unit ID clumping */
#define HT_CAPTYPE_EXTCONF 0x98 /* Extended Configuration Space Access */
#define HT_CAPTYPE_MSI_MAPPING 0xA8 /* MSI Mapping Capability */
#define HT_MSI_FLAGS 0x02 /* Offset to flags */
#define HT_MSI_FLAGS_ENABLE 0x1 /* Mapping enable */
#define HT_MSI_FLAGS_FIXED 0x2 /* Fixed mapping only */
#define HT_MSI_FIXED_ADDR 0x00000000FEE00000ULL /* Fixed addr */
#define HT_MSI_ADDR_LO 0x04 /* Offset to low addr bits */
#define HT_MSI_ADDR_LO_MASK 0xFFF00000 /* Low address bit mask */
#define HT_MSI_ADDR_HI 0x08 /* Offset to high addr bits */
#define HT_CAPTYPE_DIRECT_ROUTE 0xB0 /* Direct routing configuration */
#define HT_CAPTYPE_VCSET 0xB8 /* Virtual Channel configuration */
#define HT_CAPTYPE_ERROR_RETRY 0xC0 /* Retry on error configuration */
#define HT_CAPTYPE_GEN3 0xD0 /* Generation 3 HyperTransport configuration */
#define HT_CAPTYPE_PM 0xE0 /* HyperTransport power management configuration */
#define HT_CAP_SIZEOF_LONG 28 /* slave & primary */
#define HT_CAP_SIZEOF_SHORT 24 /* host & secondary */
/* Alternative Routing-ID Interpretation */
#define PCI_ARI_CAP 0x04 /* ARI Capability Register */
#define PCI_ARI_CAP_MFVC 0x0001 /* MFVC Function Groups Capability */
#define PCI_ARI_CAP_ACS 0x0002 /* ACS Function Groups Capability */
#define PCI_ARI_CAP_NFN(x) (((x) >> 8) & 0xff) /* Next Function Number */
#define PCI_ARI_CTRL 0x06 /* ARI Control Register */
#define PCI_ARI_CTRL_MFVC 0x0001 /* MFVC Function Groups Enable */
#define PCI_ARI_CTRL_ACS 0x0002 /* ACS Function Groups Enable */
#define PCI_ARI_CTRL_FG(x) (((x) >> 4) & 7) /* Function Group */
#define PCI_EXT_CAP_ARI_SIZEOF 8
/* Address Translation Service */
#define PCI_ATS_CAP 0x04 /* ATS Capability Register */
#define PCI_ATS_CAP_QDEP(x) ((x) & 0x1f) /* Invalidate Queue Depth */
#define PCI_ATS_MAX_QDEP 32 /* Max Invalidate Queue Depth */
#define PCI_ATS_CTRL 0x06 /* ATS Control Register */
#define PCI_ATS_CTRL_ENABLE 0x8000 /* ATS Enable */
#define PCI_ATS_CTRL_STU(x) ((x) & 0x1f) /* Smallest Translation Unit */
#define PCI_ATS_MIN_STU 12 /* shift of minimum STU block */
#define PCI_EXT_CAP_ATS_SIZEOF 8
/* Page Request Interface */
#define PCI_PRI_CTRL 0x04 /* PRI control register */
#define PCI_PRI_CTRL_ENABLE 0x01 /* Enable */
#define PCI_PRI_CTRL_RESET 0x02 /* Reset */
#define PCI_PRI_STATUS 0x06 /* PRI status register */
#define PCI_PRI_STATUS_RF 0x001 /* Response Failure */
#define PCI_PRI_STATUS_UPRGI 0x002 /* Unexpected PRG index */
#define PCI_PRI_STATUS_STOPPED 0x100 /* PRI Stopped */
#define PCI_PRI_MAX_REQ 0x08 /* PRI max reqs supported */
#define PCI_PRI_ALLOC_REQ 0x0c /* PRI max reqs allowed */
#define PCI_EXT_CAP_PRI_SIZEOF 16
/* Process Address Space ID */
#define PCI_PASID_CAP 0x04 /* PASID feature register */
#define PCI_PASID_CAP_EXEC 0x02 /* Exec permissions Supported */
#define PCI_PASID_CAP_PRIV 0x04 /* Privilege Mode Supported */
#define PCI_PASID_CTRL 0x06 /* PASID control register */
#define PCI_PASID_CTRL_ENABLE 0x01 /* Enable bit */
#define PCI_PASID_CTRL_EXEC 0x02 /* Exec permissions Enable */
#define PCI_PASID_CTRL_PRIV 0x04 /* Privilege Mode Enable */
#define PCI_EXT_CAP_PASID_SIZEOF 8
/* Single Root I/O Virtualization */
#define PCI_SRIOV_CAP 0x04 /* SR-IOV Capabilities */
#define PCI_SRIOV_CAP_VFM 0x01 /* VF Migration Capable */
#define PCI_SRIOV_CAP_INTR(x) ((x) >> 21) /* Interrupt Message Number */
#define PCI_SRIOV_CTRL 0x08 /* SR-IOV Control */
#define PCI_SRIOV_CTRL_VFE 0x01 /* VF Enable */
#define PCI_SRIOV_CTRL_VFM 0x02 /* VF Migration Enable */
#define PCI_SRIOV_CTRL_INTR 0x04 /* VF Migration Interrupt Enable */
#define PCI_SRIOV_CTRL_MSE 0x08 /* VF Memory Space Enable */
#define PCI_SRIOV_CTRL_ARI 0x10 /* ARI Capable Hierarchy */
#define PCI_SRIOV_STATUS 0x0a /* SR-IOV Status */
#define PCI_SRIOV_STATUS_VFM 0x01 /* VF Migration Status */
#define PCI_SRIOV_INITIAL_VF 0x0c /* Initial VFs */
#define PCI_SRIOV_TOTAL_VF 0x0e /* Total VFs */
#define PCI_SRIOV_NUM_VF 0x10 /* Number of VFs */
#define PCI_SRIOV_FUNC_LINK 0x12 /* Function Dependency Link */
#define PCI_SRIOV_VF_OFFSET 0x14 /* First VF Offset */
#define PCI_SRIOV_VF_STRIDE 0x16 /* Following VF Stride */
#define PCI_SRIOV_VF_DID 0x1a /* VF Device ID */
#define PCI_SRIOV_SUP_PGSIZE 0x1c /* Supported Page Sizes */
#define PCI_SRIOV_SYS_PGSIZE 0x20 /* System Page Size */
#define PCI_SRIOV_BAR 0x24 /* VF BAR0 */
#define PCI_SRIOV_NUM_BARS 6 /* Number of VF BARs */
#define PCI_SRIOV_VFM 0x3c /* VF Migration State Array Offset*/
#define PCI_SRIOV_VFM_BIR(x) ((x) & 7) /* State BIR */
#define PCI_SRIOV_VFM_OFFSET(x) ((x) & ~7) /* State Offset */
#define PCI_SRIOV_VFM_UA 0x0 /* Inactive.Unavailable */
#define PCI_SRIOV_VFM_MI 0x1 /* Dormant.MigrateIn */
#define PCI_SRIOV_VFM_MO 0x2 /* Active.MigrateOut */
#define PCI_SRIOV_VFM_AV 0x3 /* Active.Available */
#define PCI_EXT_CAP_SRIOV_SIZEOF 64
#define PCI_LTR_MAX_SNOOP_LAT 0x4
#define PCI_LTR_MAX_NOSNOOP_LAT 0x6
#define PCI_LTR_VALUE_MASK 0x000003ff
#define PCI_LTR_SCALE_MASK 0x00001c00
#define PCI_LTR_SCALE_SHIFT 10
#define PCI_EXT_CAP_LTR_SIZEOF 8
/* Access Control Service */
#define PCI_ACS_CAP 0x04 /* ACS Capability Register */
#define PCI_ACS_SV 0x01 /* Source Validation */
#define PCI_ACS_TB 0x02 /* Translation Blocking */
#define PCI_ACS_RR 0x04 /* P2P Request Redirect */
#define PCI_ACS_CR 0x08 /* P2P Completion Redirect */
#define PCI_ACS_UF 0x10 /* Upstream Forwarding */
#define PCI_ACS_EC 0x20 /* P2P Egress Control */
#define PCI_ACS_DT 0x40 /* Direct Translated P2P */
#define PCI_ACS_EGRESS_BITS 0x05 /* ACS Egress Control Vector Size */
#define PCI_ACS_CTRL 0x06 /* ACS Control Register */
#define PCI_ACS_EGRESS_CTL_V 0x08 /* ACS Egress Control Vector */
#define PCI_VSEC_HDR 4 /* extended cap - vendor-specific */
#define PCI_VSEC_HDR_LEN_SHIFT 20 /* shift for length field */
/* SATA capability */
#define PCI_SATA_REGS 4 /* SATA REGs specifier */
#define PCI_SATA_REGS_MASK 0xF /* location - BAR#/inline */
#define PCI_SATA_REGS_INLINE 0xF /* REGS in config space */
#define PCI_SATA_SIZEOF_SHORT 8
#define PCI_SATA_SIZEOF_LONG 16
/* Resizable BARs */
#define PCI_REBAR_CTRL 8 /* control register */
#define PCI_REBAR_CTRL_NBAR_MASK (7 << 5) /* mask for # bars */
#define PCI_REBAR_CTRL_NBAR_SHIFT 5 /* shift for # bars */
/* Dynamic Power Allocation */
#define PCI_DPA_CAP 4 /* capability register */
#define PCI_DPA_CAP_SUBSTATE_MASK 0x1F /* # substates - 1 */
#define PCI_DPA_BASE_SIZEOF 16 /* size with 0 substates */
/* TPH Requester */
#define PCI_TPH_CAP 4 /* capability register */
#define PCI_TPH_CAP_LOC_MASK 0x600 /* location mask */
#define PCI_TPH_LOC_NONE 0x000 /* no location */
#define PCI_TPH_LOC_CAP 0x200 /* in capability */
#define PCI_TPH_LOC_MSIX 0x400 /* in MSI-X */
#define PCI_TPH_CAP_ST_MASK 0x07FF0000 /* st table mask */
#define PCI_TPH_CAP_ST_SHIFT 16 /* st table shift */
#define PCI_TPH_BASE_SIZEOF 12 /* size with no st table */
/* Downstream Port Containment */
#define PCI_EXP_DPC_CAP 4 /* DPC Capability */
#define PCI_EXP_DPC_CAP_RP_EXT 0x20 /* Root Port Extensions for DPC */
#define PCI_EXP_DPC_CAP_POISONED_TLP 0x40 /* Poisoned TLP Egress Blocking Supported */
#define PCI_EXP_DPC_CAP_SW_TRIGGER 0x80 /* Software Triggering Supported */
#define PCI_EXP_DPC_CAP_DL_ACTIVE 0x1000 /* ERR_COR signal on DL_Active supported */
#define PCI_EXP_DPC_CTL 6 /* DPC control */
#define PCI_EXP_DPC_CTL_EN_NONFATAL 0x02 /* Enable trigger on ERR_NONFATAL message */
#define PCI_EXP_DPC_CTL_INT_EN 0x08 /* DPC Interrupt Enable */
#define PCI_EXP_DPC_STATUS 8 /* DPC Status */
#define PCI_EXP_DPC_STATUS_TRIGGER 0x01 /* Trigger Status */
#define PCI_EXP_DPC_STATUS_INTERRUPT 0x08 /* Interrupt Status */
#define PCI_EXP_DPC_SOURCE_ID 10 /* DPC Source Identifier */
#endif /* LINUX_PCI_REGS_H */
| null | null | null | null | 124,014 |
61,686 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 61,686 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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/ssl/certificate_error_report.h"
#include <vector>
#include "base/stl_util.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "components/network_time/network_time_tracker.h"
#include "net/cert/cert_verifier.h"
#include "net/cert/x509_certificate.h"
#include "net/ssl/ssl_info.h"
#if defined(OS_ANDROID)
#include "net/cert/cert_verify_proc_android.h"
#endif
#include "net/cert/cert_verify_result.h"
using network_time::NetworkTimeTracker;
namespace {
// Add any errors from |cert_status| to |cert_errors|. (net::CertStatus can
// represent both errors and non-error status codes.)
void AddCertStatusToReportErrors(
net::CertStatus cert_status,
::google::protobuf::RepeatedField<int>* cert_errors) {
#define COPY_CERT_STATUS(error) RENAME_CERT_STATUS(error, CERT_##error)
#define RENAME_CERT_STATUS(status_error, logger_error) \
if (cert_status & net::CERT_STATUS_##status_error) \
cert_errors->Add(chrome_browser_ssl::CertLoggerRequest::ERR_##logger_error);
COPY_CERT_STATUS(REVOKED)
COPY_CERT_STATUS(INVALID)
RENAME_CERT_STATUS(PINNED_KEY_MISSING, SSL_PINNED_KEY_NOT_IN_CERT_CHAIN)
COPY_CERT_STATUS(AUTHORITY_INVALID)
COPY_CERT_STATUS(COMMON_NAME_INVALID)
COPY_CERT_STATUS(NON_UNIQUE_NAME)
COPY_CERT_STATUS(NAME_CONSTRAINT_VIOLATION)
COPY_CERT_STATUS(WEAK_SIGNATURE_ALGORITHM)
COPY_CERT_STATUS(WEAK_KEY)
COPY_CERT_STATUS(DATE_INVALID)
COPY_CERT_STATUS(VALIDITY_TOO_LONG)
COPY_CERT_STATUS(UNABLE_TO_CHECK_REVOCATION)
COPY_CERT_STATUS(NO_REVOCATION_MECHANISM)
RENAME_CERT_STATUS(CERTIFICATE_TRANSPARENCY_REQUIRED,
CERTIFICATE_TRANSPARENCY_REQUIRED)
COPY_CERT_STATUS(SYMANTEC_LEGACY)
#undef RENAME_CERT_STATUS
#undef COPY_CERT_STATUS
}
// Add any non-error codes from |cert_status| to |cert_errors|.
// (net::CertStatus can represent both errors and non-error status codes.)
void AddCertStatusToReportStatus(
net::CertStatus cert_status,
::google::protobuf::RepeatedField<int>* report_status) {
#define COPY_CERT_STATUS(error) \
if (cert_status & net::CERT_STATUS_##error) \
report_status->Add(chrome_browser_ssl::CertLoggerRequest::STATUS_##error);
COPY_CERT_STATUS(IS_EV)
COPY_CERT_STATUS(REV_CHECKING_ENABLED)
COPY_CERT_STATUS(SHA1_SIGNATURE_PRESENT)
COPY_CERT_STATUS(CT_COMPLIANCE_FAILED)
#undef COPY_CERT_STATUS
}
void AddVerifyFlagsToReport(
int verify_flags,
::google::protobuf::RepeatedField<int>* report_flags) {
#define COPY_VERIFY_FLAGS(flag) \
if (verify_flags & net::CertVerifier::VERIFY_##flag) \
report_flags->Add(chrome_browser_ssl::TrialVerificationInfo::VERIFY_##flag);
COPY_VERIFY_FLAGS(REV_CHECKING_ENABLED);
COPY_VERIFY_FLAGS(REV_CHECKING_REQUIRED_LOCAL_ANCHORS);
COPY_VERIFY_FLAGS(ENABLE_SHA1_LOCAL_ANCHORS);
COPY_VERIFY_FLAGS(DISABLE_SYMANTEC_ENFORCEMENT);
#undef COPY_VERIFY_FLAGS
}
bool CertificateChainToString(const net::X509Certificate& cert,
std::string* result) {
std::vector<std::string> pem_encoded_chain;
if (!cert.GetPEMEncodedChain(&pem_encoded_chain))
return false;
*result = base::StrCat(pem_encoded_chain);
return true;
}
} // namespace
CertificateErrorReport::CertificateErrorReport()
: cert_report_(new chrome_browser_ssl::CertLoggerRequest()) {}
CertificateErrorReport::CertificateErrorReport(const std::string& hostname,
const net::SSLInfo& ssl_info)
: CertificateErrorReport(hostname,
*ssl_info.cert,
ssl_info.unverified_cert.get(),
ssl_info.is_issued_by_known_root,
ssl_info.cert_status) {
cert_report_->add_pin(ssl_info.pinning_failure_log);
}
CertificateErrorReport::CertificateErrorReport(
const std::string& hostname,
const net::X509Certificate& unverified_cert,
int verify_flags,
const net::CertVerifyResult& primary_result,
const net::CertVerifyResult& trial_result)
: CertificateErrorReport(hostname,
*primary_result.verified_cert,
&unverified_cert,
primary_result.is_issued_by_known_root,
primary_result.cert_status) {
chrome_browser_ssl::CertLoggerFeaturesInfo* features_info =
cert_report_->mutable_features_info();
chrome_browser_ssl::TrialVerificationInfo* trial_report =
features_info->mutable_trial_verification_info();
if (!CertificateChainToString(*trial_result.verified_cert,
trial_report->mutable_cert_chain())) {
LOG(ERROR) << "Could not get PEM encoded chain.";
}
trial_report->set_is_issued_by_known_root(
trial_result.is_issued_by_known_root);
AddCertStatusToReportErrors(trial_result.cert_status,
trial_report->mutable_cert_error());
AddCertStatusToReportStatus(trial_result.cert_status,
trial_report->mutable_cert_status());
AddVerifyFlagsToReport(verify_flags, trial_report->mutable_verify_flags());
}
CertificateErrorReport::~CertificateErrorReport() {}
bool CertificateErrorReport::InitializeFromString(
const std::string& serialized_report) {
return cert_report_->ParseFromString(serialized_report);
}
bool CertificateErrorReport::Serialize(std::string* output) const {
return cert_report_->SerializeToString(output);
}
void CertificateErrorReport::SetInterstitialInfo(
const InterstitialReason& interstitial_reason,
const ProceedDecision& proceed_decision,
const Overridable& overridable,
const base::Time& interstitial_time) {
chrome_browser_ssl::CertLoggerInterstitialInfo* interstitial_info =
cert_report_->mutable_interstitial_info();
switch (interstitial_reason) {
case INTERSTITIAL_SSL:
interstitial_info->set_interstitial_reason(
chrome_browser_ssl::CertLoggerInterstitialInfo::INTERSTITIAL_SSL);
break;
case INTERSTITIAL_CAPTIVE_PORTAL:
interstitial_info->set_interstitial_reason(
chrome_browser_ssl::CertLoggerInterstitialInfo::
INTERSTITIAL_CAPTIVE_PORTAL);
break;
case INTERSTITIAL_CLOCK:
interstitial_info->set_interstitial_reason(
chrome_browser_ssl::CertLoggerInterstitialInfo::INTERSTITIAL_CLOCK);
break;
case INTERSTITIAL_SUPERFISH:
interstitial_info->set_interstitial_reason(
chrome_browser_ssl::CertLoggerInterstitialInfo::
INTERSTITIAL_SUPERFISH);
break;
case INTERSTITIAL_MITM_SOFTWARE:
interstitial_info->set_interstitial_reason(
chrome_browser_ssl::CertLoggerInterstitialInfo::
INTERSTITIAL_MITM_SOFTWARE);
break;
}
interstitial_info->set_user_proceeded(proceed_decision == USER_PROCEEDED);
interstitial_info->set_overridable(overridable == INTERSTITIAL_OVERRIDABLE);
interstitial_info->set_interstitial_created_time_usec(
interstitial_time.ToInternalValue());
}
void CertificateErrorReport::AddNetworkTimeInfo(
const NetworkTimeTracker* network_time_tracker) {
chrome_browser_ssl::CertLoggerFeaturesInfo* features_info =
cert_report_->mutable_features_info();
chrome_browser_ssl::CertLoggerFeaturesInfo::NetworkTimeQueryingInfo*
network_time_info = features_info->mutable_network_time_querying_info();
network_time_info->set_network_time_queries_enabled(
network_time_tracker->AreTimeFetchesEnabled());
NetworkTimeTracker::FetchBehavior behavior =
network_time_tracker->GetFetchBehavior();
chrome_browser_ssl::CertLoggerFeaturesInfo::NetworkTimeQueryingInfo::
NetworkTimeFetchBehavior report_behavior =
chrome_browser_ssl::CertLoggerFeaturesInfo::NetworkTimeQueryingInfo::
NETWORK_TIME_FETCHES_UNKNOWN;
switch (behavior) {
case NetworkTimeTracker::FETCH_BEHAVIOR_UNKNOWN:
report_behavior = chrome_browser_ssl::CertLoggerFeaturesInfo::
NetworkTimeQueryingInfo::NETWORK_TIME_FETCHES_UNKNOWN;
break;
case NetworkTimeTracker::FETCHES_IN_BACKGROUND_ONLY:
report_behavior = chrome_browser_ssl::CertLoggerFeaturesInfo::
NetworkTimeQueryingInfo::NETWORK_TIME_FETCHES_BACKGROUND_ONLY;
break;
case NetworkTimeTracker::FETCHES_ON_DEMAND_ONLY:
report_behavior = chrome_browser_ssl::CertLoggerFeaturesInfo::
NetworkTimeQueryingInfo::NETWORK_TIME_FETCHES_ON_DEMAND_ONLY;
break;
case NetworkTimeTracker::FETCHES_IN_BACKGROUND_AND_ON_DEMAND:
report_behavior =
chrome_browser_ssl::CertLoggerFeaturesInfo::NetworkTimeQueryingInfo::
NETWORK_TIME_FETCHES_IN_BACKGROUND_AND_ON_DEMAND;
break;
}
network_time_info->set_network_time_query_behavior(report_behavior);
}
void CertificateErrorReport::AddChromeChannel(version_info::Channel channel) {
switch (channel) {
case version_info::Channel::STABLE:
cert_report_->set_chrome_channel(
chrome_browser_ssl::CertLoggerRequest::CHROME_CHANNEL_STABLE);
break;
case version_info::Channel::BETA:
cert_report_->set_chrome_channel(
chrome_browser_ssl::CertLoggerRequest::CHROME_CHANNEL_BETA);
break;
case version_info::Channel::CANARY:
cert_report_->set_chrome_channel(
chrome_browser_ssl::CertLoggerRequest::CHROME_CHANNEL_CANARY);
break;
case version_info::Channel::DEV:
cert_report_->set_chrome_channel(
chrome_browser_ssl::CertLoggerRequest::CHROME_CHANNEL_DEV);
break;
case version_info::Channel::UNKNOWN:
cert_report_->set_chrome_channel(
chrome_browser_ssl::CertLoggerRequest::CHROME_CHANNEL_UNKNOWN);
break;
}
}
void CertificateErrorReport::SetIsEnterpriseManaged(
bool is_enterprise_managed) {
cert_report_->set_is_enterprise_managed(is_enterprise_managed);
}
void CertificateErrorReport::SetIsRetryUpload(bool is_retry_upload) {
cert_report_->set_is_retry_upload(is_retry_upload);
}
const std::string& CertificateErrorReport::hostname() const {
return cert_report_->hostname();
}
chrome_browser_ssl::CertLoggerRequest::ChromeChannel
CertificateErrorReport::chrome_channel() const {
return cert_report_->chrome_channel();
}
bool CertificateErrorReport::is_enterprise_managed() const {
return cert_report_->is_enterprise_managed();
}
bool CertificateErrorReport::is_retry_upload() const {
return cert_report_->is_retry_upload();
}
CertificateErrorReport::CertificateErrorReport(
const std::string& hostname,
const net::X509Certificate& cert,
const net::X509Certificate* unverified_cert,
bool is_issued_by_known_root,
net::CertStatus cert_status)
: cert_report_(new chrome_browser_ssl::CertLoggerRequest()) {
base::Time now = base::Time::Now();
cert_report_->set_time_usec(now.ToInternalValue());
cert_report_->set_hostname(hostname);
if (!CertificateChainToString(cert, cert_report_->mutable_cert_chain())) {
LOG(ERROR) << "Could not get PEM encoded chain.";
}
if (unverified_cert &&
!CertificateChainToString(
*unverified_cert, cert_report_->mutable_unverified_cert_chain())) {
LOG(ERROR) << "Could not get PEM encoded unverified certificate chain.";
}
cert_report_->set_is_issued_by_known_root(is_issued_by_known_root);
AddCertStatusToReportErrors(cert_status, cert_report_->mutable_cert_error());
AddCertStatusToReportStatus(cert_status, cert_report_->mutable_cert_status());
#if defined(OS_ANDROID)
chrome_browser_ssl::CertLoggerFeaturesInfo* features_info =
cert_report_->mutable_features_info();
features_info->set_android_aia_fetching_status(
chrome_browser_ssl::CertLoggerFeaturesInfo::ANDROID_AIA_FETCHING_ENABLED);
#endif
}
| null | null | null | null | 58,549 |
9,465 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 174,460 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* arch/arm/mach-mv78x00/rd78x00-masa-setup.c
*
* Marvell RD-78x00-mASA Development Board Setup
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/ata_platform.h>
#include <linux/mv643xx_eth.h>
#include <linux/ethtool.h>
#include <asm/mach-types.h>
#include <asm/mach/arch.h>
#include "mv78xx0.h"
#include "common.h"
static struct mv643xx_eth_platform_data rd78x00_masa_ge00_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(8),
};
static struct mv643xx_eth_platform_data rd78x00_masa_ge01_data = {
.phy_addr = MV643XX_ETH_PHY_ADDR(9),
};
static struct mv643xx_eth_platform_data rd78x00_masa_ge10_data = {
};
static struct mv643xx_eth_platform_data rd78x00_masa_ge11_data = {
};
static struct mv_sata_platform_data rd78x00_masa_sata_data = {
.n_ports = 2,
};
static void __init rd78x00_masa_init(void)
{
/*
* Basic MV78x00 setup. Needs to be called early.
*/
mv78xx0_init();
/*
* Partition on-chip peripherals between the two CPU cores.
*/
if (mv78xx0_core_index() == 0) {
mv78xx0_ehci0_init();
mv78xx0_ehci1_init();
mv78xx0_ge00_init(&rd78x00_masa_ge00_data);
mv78xx0_ge10_init(&rd78x00_masa_ge10_data);
mv78xx0_sata_init(&rd78x00_masa_sata_data);
mv78xx0_uart0_init();
mv78xx0_uart2_init();
} else {
mv78xx0_ehci2_init();
mv78xx0_ge01_init(&rd78x00_masa_ge01_data);
mv78xx0_ge11_init(&rd78x00_masa_ge11_data);
mv78xx0_uart1_init();
mv78xx0_uart3_init();
}
}
static int __init rd78x00_pci_init(void)
{
/*
* Assign all PCIe devices to CPU core #0.
*/
if (machine_is_rd78x00_masa() && mv78xx0_core_index() == 0)
mv78xx0_pcie_init(1, 1);
return 0;
}
subsys_initcall(rd78x00_pci_init);
MACHINE_START(RD78X00_MASA, "Marvell RD-78x00-MASA Development Board")
/* Maintainer: Lennert Buytenhek <[email protected]> */
.atag_offset = 0x100,
.nr_irqs = MV78XX0_NR_IRQS,
.init_machine = rd78x00_masa_init,
.map_io = mv78xx0_map_io,
.init_early = mv78xx0_init_early,
.init_irq = mv78xx0_init_irq,
.init_time = mv78xx0_timer_init,
.restart = mv78xx0_restart,
MACHINE_END
| null | null | null | null | 82,807 |
64,860 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 64,860 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2013 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 CHROME_BROWSER_UI_APP_LIST_EXTENSION_UNINSTALLER_H_
#define CHROME_BROWSER_UI_APP_LIST_EXTENSION_UNINSTALLER_H_
#include "base/macros.h"
#include "chrome/browser/extensions/extension_uninstall_dialog.h"
class AppListControllerDelegate;
class Profile;
// ExtensionUninstaller runs the extension uninstall flow. It shows the
// extension uninstall dialog and wait for user to confirm or cancel the
// uninstall.
class ExtensionUninstaller
: public extensions::ExtensionUninstallDialog::Delegate {
public:
ExtensionUninstaller(Profile* profile,
const std::string& extension_id,
AppListControllerDelegate* controller);
~ExtensionUninstaller() override;
void Run();
private:
// Overridden from ExtensionUninstallDialog::Delegate:
void OnExtensionUninstallDialogClosed(bool did_start_uninstall,
const base::string16& error) override;
void CleanUp();
Profile* profile_;
std::string app_id_;
AppListControllerDelegate* controller_;
std::unique_ptr<extensions::ExtensionUninstallDialog> dialog_;
DISALLOW_COPY_AND_ASSIGN(ExtensionUninstaller);
};
#endif // CHROME_BROWSER_UI_APP_LIST_EXTENSION_UNINSTALLER_H_
| null | null | null | null | 61,723 |
32,121 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 32,121 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2017 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 "third_party/blink/renderer/core/css/properties/longhands/stroke_opacity.h"
#include "third_party/blink/renderer/core/css/parser/css_property_parser_helpers.h"
#include "third_party/blink/renderer/core/style/computed_style.h"
namespace blink {
class CSSParserLocalContext;
namespace CSSLonghand {
const CSSValue* StrokeOpacity::ParseSingleValue(
CSSParserTokenRange& range,
const CSSParserContext& context,
const CSSParserLocalContext&) const {
return CSSPropertyParserHelpers::ConsumeNumber(range, kValueRangeAll);
}
const CSSValue* StrokeOpacity::CSSValueFromComputedStyleInternal(
const ComputedStyle&,
const SVGComputedStyle& svg_style,
const LayoutObject*,
Node*,
bool allow_visited_style) const {
return CSSPrimitiveValue::Create(svg_style.StrokeOpacity(),
CSSPrimitiveValue::UnitType::kNumber);
}
} // namespace CSSLonghand
} // namespace blink
| null | null | null | null | 28,984 |
67,964 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 67,964 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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 REMOTING_PROTOCOL_CLIENT_VIDEO_STATE_DISPATCHER_H_
#define REMOTING_PROTOCOL_CLIENT_VIDEO_STATE_DISPATCHER_H_
#include <list>
#include "base/compiler_specific.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "remoting/base/constants.h"
#include "remoting/protocol/channel_dispatcher_base.h"
#include "third_party/webrtc/modules/desktop_capture/desktop_geometry.h"
namespace remoting {
namespace protocol {
class VideoStatsStub;
class ClientVideoStatsDispatcher : public ChannelDispatcherBase {
public:
ClientVideoStatsDispatcher(const std::string& stream_name,
VideoStatsStub* video_stats_stub);
~ClientVideoStatsDispatcher() override;
private:
void OnIncomingMessage(std::unique_ptr<CompoundBuffer> message) override;
VideoStatsStub* video_stats_stub_;
DISALLOW_COPY_AND_ASSIGN(ClientVideoStatsDispatcher);
};
} // namespace protocol
} // namespace remoting
#endif // REMOTING_PROTOCOL_CLIENT_VIDEO_STATE_DISPATCHER_H_
| null | null | null | null | 64,827 |
2,705 | null |
train_val
|
04b570817b2b38e35675b17328239746212f4c3f
| 155,762 |
FFmpeg
| 0 |
https://github.com/FFmpeg/FFmpeg
|
2018-06-01 01:23:12+05:30
|
/*
* Copyright (c) 2015 Zhou Xiaoyong <[email protected]>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVCODEC_MIPS_H264PRED_MIPS_H
#define AVCODEC_MIPS_H264PRED_MIPS_H
#include "constants.h"
#include "libavcodec/h264pred.h"
void ff_pred16x16_vertical_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred16x16_horizontal_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred16x16_dc_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred8x8l_top_dc_8_mmi(uint8_t *src, int has_topleft, int has_topright,
ptrdiff_t stride);
void ff_pred8x8l_dc_8_mmi(uint8_t *src, int has_topleft, int has_topright,
ptrdiff_t stride);
void ff_pred8x8l_vertical_8_mmi(uint8_t *src, int has_topleft,
int has_topright, ptrdiff_t stride);
void ff_pred4x4_dc_8_mmi(uint8_t *src, const uint8_t *topright,
ptrdiff_t stride);
void ff_pred8x8_vertical_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred8x8_horizontal_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred16x16_plane_svq3_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred16x16_plane_rv40_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred16x16_plane_h264_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred8x8_top_dc_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred8x8_dc_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred8x16_vertical_8_mmi(uint8_t *src, ptrdiff_t stride);
void ff_pred8x16_horizontal_8_mmi(uint8_t *src, ptrdiff_t stride);
#endif /* AVCODEC_MIPS_H264PRED_MIPS_H */
| null | null | null | null | 71,817 |
46,274 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 46,274 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2013 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 "ash/accelerators/debug_commands.h"
#include "ash/accelerators/accelerator_commands.h"
#include "ash/public/cpp/ash_switches.h"
#include "ash/root_window_controller.h"
#include "ash/shell.h"
#include "ash/system/toast/toast_data.h"
#include "ash/system/toast/toast_manager.h"
#include "ash/touch/touch_devices_controller.h"
#include "ash/wallpaper/wallpaper_controller.h"
#include "ash/wm/tablet_mode/tablet_mode_controller.h"
#include "ash/wm/widget_finder.h"
#include "ash/wm/window_properties.h"
#include "ash/wm/window_util.h"
#include "base/command_line.h"
#include "base/metrics/user_metrics.h"
#include "base/metrics/user_metrics_action.h"
#include "base/strings/utf_string_conversions.h"
#include "ui/compositor/debug_utils.h"
#include "ui/compositor/layer.h"
#include "ui/display/manager/display_manager.h"
#include "ui/gfx/canvas.h"
#include "ui/gfx/image/image_skia.h"
#include "ui/gfx/image/image_skia_rep.h"
#include "ui/views/debug_utils.h"
#include "ui/views/widget/widget.h"
namespace ash {
namespace debug {
namespace {
void HandlePrintLayerHierarchy() {
for (aura::Window* root : Shell::Get()->GetAllRootWindows()) {
ui::Layer* layer = root->layer();
if (layer)
ui::PrintLayerHierarchy(
layer,
RootWindowController::ForWindow(root)->GetLastMouseLocationInRoot());
}
}
void HandlePrintViewHierarchy() {
aura::Window* active_window = wm::GetActiveWindow();
if (!active_window)
return;
views::Widget* widget = GetInternalWidgetForWindow(active_window);
if (!widget)
return;
views::PrintViewHierarchy(widget->GetRootView());
}
void PrintWindowHierarchy(const aura::Window* active_window,
aura::Window* window,
int indent,
std::ostringstream* out) {
std::string indent_str(indent, ' ');
std::string name(window->GetName());
if (name.empty())
name = "\"\"";
*out << indent_str << name << " (" << window << ")"
<< " type=" << window->type()
<< ((window == active_window) ? " [active] " : " ")
<< (window->IsVisible() ? " visible " : " ")
<< window->bounds().ToString()
<< (window->GetProperty(kSnapChildrenToPixelBoundary) ? " [snapped] "
: "")
<< ", subpixel offset="
<< window->layer()->subpixel_position_offset().ToString() << '\n';
for (aura::Window* child : window->children())
PrintWindowHierarchy(active_window, child, indent + 3, out);
}
void HandlePrintWindowHierarchy() {
aura::Window* active_window = wm::GetActiveWindow();
aura::Window::Windows roots = Shell::Get()->GetAllRootWindows();
for (size_t i = 0; i < roots.size(); ++i) {
std::ostringstream out;
out << "RootWindow " << i << ":\n";
PrintWindowHierarchy(active_window, roots[i], 0, &out);
// Error so logs can be collected from end-users.
LOG(ERROR) << out.str();
}
}
gfx::ImageSkia CreateWallpaperImage(SkColor fill, SkColor rect) {
// TODO(oshima): Consider adding a command line option to control wallpaper
// images for testing. The size is randomly picked.
gfx::Size image_size(1366, 768);
SkBitmap bitmap;
bitmap.allocN32Pixels(image_size.width(), image_size.height(), true);
SkCanvas canvas(bitmap);
canvas.drawColor(fill);
SkPaint paint;
paint.setColor(rect);
paint.setStrokeWidth(10);
paint.setStyle(SkPaint::kStroke_Style);
paint.setBlendMode(SkBlendMode::kSrcOver);
canvas.drawRoundRect(gfx::RectToSkRect(gfx::Rect(image_size)), 100.f, 100.f,
paint);
return gfx::ImageSkia(gfx::ImageSkiaRep(std::move(bitmap), 1.f));
}
void HandleToggleWallpaperMode() {
static int index = 0;
WallpaperController* wallpaper_controller =
Shell::Get()->wallpaper_controller();
WallpaperInfo info("", WALLPAPER_LAYOUT_STRETCH, DEFAULT,
base::Time::Now().LocalMidnight());
switch (++index % 4) {
case 0:
wallpaper_controller->ShowDefaultWallpaperForTesting();
break;
case 1:
wallpaper_controller->ShowWallpaperImage(
CreateWallpaperImage(SK_ColorRED, SK_ColorBLUE), info,
false /*preview_mode=*/);
break;
case 2:
info.layout = WALLPAPER_LAYOUT_CENTER;
wallpaper_controller->ShowWallpaperImage(
CreateWallpaperImage(SK_ColorBLUE, SK_ColorGREEN), info,
false /*preview_mode=*/);
break;
case 3:
info.layout = WALLPAPER_LAYOUT_CENTER_CROPPED;
wallpaper_controller->ShowWallpaperImage(
CreateWallpaperImage(SK_ColorGREEN, SK_ColorRED), info,
false /*preview_mode=*/);
break;
}
}
void HandleToggleTouchpad() {
base::RecordAction(base::UserMetricsAction("Accel_Toggle_Touchpad"));
Shell::Get()->touch_devices_controller()->ToggleTouchpad();
}
void HandleToggleTouchscreen() {
base::RecordAction(base::UserMetricsAction("Accel_Toggle_Touchscreen"));
TouchDevicesController* controller = Shell::Get()->touch_devices_controller();
controller->SetTouchscreenEnabled(
!controller->GetTouchscreenEnabled(TouchDeviceEnabledSource::USER_PREF),
TouchDeviceEnabledSource::USER_PREF);
}
void HandleToggleTabletMode() {
TabletModeController* controller = Shell::Get()->tablet_mode_controller();
controller->EnableTabletModeWindowManager(
!controller->IsTabletModeWindowManagerEnabled());
}
void HandleTriggerCrash() {
CHECK(false) << "Intentional crash via debug accelerator.";
}
} // namespace
void PrintUIHierarchies() {
// This is a separate command so the user only has to hit one key to generate
// all the logs. Developers use the individual dumps repeatedly, so keep
// those as separate commands to avoid spamming their logs.
HandlePrintLayerHierarchy();
HandlePrintWindowHierarchy();
HandlePrintViewHierarchy();
}
bool DebugAcceleratorsEnabled() {
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAshDebugShortcuts);
}
bool DeveloperAcceleratorsEnabled() {
return base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kAshDeveloperShortcuts);
}
void PerformDebugActionIfEnabled(AcceleratorAction action) {
if (!DebugAcceleratorsEnabled())
return;
switch (action) {
case DEBUG_PRINT_LAYER_HIERARCHY:
HandlePrintLayerHierarchy();
break;
case DEBUG_PRINT_VIEW_HIERARCHY:
HandlePrintViewHierarchy();
break;
case DEBUG_PRINT_WINDOW_HIERARCHY:
HandlePrintWindowHierarchy();
break;
case DEBUG_SHOW_TOAST:
Shell::Get()->toast_manager()->Show(
ToastData("id", base::ASCIIToUTF16("Toast"), 5000 /* duration_ms */,
base::ASCIIToUTF16("Dismiss")));
break;
case DEBUG_TOGGLE_DEVICE_SCALE_FACTOR:
Shell::Get()->display_manager()->ToggleDisplayScaleFactor();
break;
case DEBUG_TOGGLE_TOUCH_PAD:
HandleToggleTouchpad();
break;
case DEBUG_TOGGLE_TOUCH_SCREEN:
HandleToggleTouchscreen();
break;
case DEBUG_TOGGLE_TABLET_MODE:
HandleToggleTabletMode();
break;
case DEBUG_TOGGLE_WALLPAPER_MODE:
HandleToggleWallpaperMode();
break;
case DEBUG_TRIGGER_CRASH:
HandleTriggerCrash();
break;
default:
break;
}
}
} // namespace debug
} // namespace ash
| null | null | null | null | 43,137 |
60,312 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 60,312 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2016 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/page_load_metrics/observers/no_state_prefetch_page_load_metrics_observer.h"
#include <memory>
#include "chrome/browser/prerender/prerender_manager.h"
#include "chrome/browser/prerender/prerender_manager_factory.h"
#include "content/public/browser/navigation_handle.h"
#include "content/public/browser/web_contents.h"
#include "net/http/http_response_headers.h"
// static
std::unique_ptr<NoStatePrefetchPageLoadMetricsObserver>
NoStatePrefetchPageLoadMetricsObserver::CreateIfNeeded(
content::WebContents* web_contents) {
prerender::PrerenderManager* manager =
prerender::PrerenderManagerFactory::GetForBrowserContext(
web_contents->GetBrowserContext());
if (!manager)
return nullptr;
return std::make_unique<NoStatePrefetchPageLoadMetricsObserver>(manager);
}
NoStatePrefetchPageLoadMetricsObserver::NoStatePrefetchPageLoadMetricsObserver(
prerender::PrerenderManager* manager)
: is_no_store_(false), was_hidden_(false), prerender_manager_(manager) {
DCHECK(prerender_manager_);
}
NoStatePrefetchPageLoadMetricsObserver::
~NoStatePrefetchPageLoadMetricsObserver() {}
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
NoStatePrefetchPageLoadMetricsObserver::OnCommit(
content::NavigationHandle* navigation_handle,
ukm::SourceId source_id) {
const net::HttpResponseHeaders* response_headers =
navigation_handle->GetResponseHeaders();
is_no_store_ = response_headers &&
response_headers->HasHeaderValue("cache-control", "no-store");
return CONTINUE_OBSERVING;
}
void NoStatePrefetchPageLoadMetricsObserver::OnFirstContentfulPaintInPage(
const page_load_metrics::mojom::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& extra_info) {
DCHECK(timing.paint_timing->first_contentful_paint.has_value());
prerender_manager_->RecordNoStateFirstContentfulPaint(
extra_info.start_url, is_no_store_, was_hidden_,
*timing.paint_timing->first_contentful_paint);
}
page_load_metrics::PageLoadMetricsObserver::ObservePolicy
NoStatePrefetchPageLoadMetricsObserver::OnHidden(
const page_load_metrics::mojom::PageLoadTiming& timing,
const page_load_metrics::PageLoadExtraInfo& extra_info) {
was_hidden_ = true;
return CONTINUE_OBSERVING;
}
| null | null | null | null | 57,175 |
800 | null |
train_val
|
31e986bc171719c9e6d40d0c2cb1501796a69e6c
| 259,755 |
php-src
| 0 |
https://github.com/php/php-src
|
2016-10-24 10:37:20+01:00
|
/*
* "streamable kanji code filter and converter"
* Copyright (c) 1998-2002 HappySize, Inc. All rights reserved.
*
* LICENSE NOTICES
*
* This file is part of "streamable kanji code filter and converter",
* which is distributed under the terms of GNU Lesser General Public
* License (version 2) as published by the Free Software Foundation.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with "streamable kanji code filter and converter";
* if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* The author of this file:
*
*/
/*
* The source code included in this files was separated from mbfilter.c
* by Moriyoshi Koizumi <[email protected]> on 4 Dec 2002. The file
* mbfilter.c is included in this package .
*
*/
#ifndef MBFL_MBFILTER_BYTE4_H
#define MBFL_MBFILTER_BYTE4_H
extern const mbfl_encoding mbfl_encoding_byte4be;
extern const mbfl_encoding mbfl_encoding_byte4le;
extern const struct mbfl_convert_vtbl vtbl_byte4be_wchar;
extern const struct mbfl_convert_vtbl vtbl_wchar_byte4be;
extern const struct mbfl_convert_vtbl vtbl_byte4le_wchar;
extern const struct mbfl_convert_vtbl vtbl_wchar_byte4le;
int mbfl_filt_conv_wchar_byte4be(int c, mbfl_convert_filter *filter);
int mbfl_filt_conv_byte4be_wchar(int c, mbfl_convert_filter *filter);
int mbfl_filt_conv_wchar_byte4le(int c, mbfl_convert_filter *filter);
int mbfl_filt_conv_byte4le_wchar(int c, mbfl_convert_filter *filter);
#endif /* MBFL_MBFILTER_BYTE4_H */
| null | null | null | null | 119,676 |
34,808 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 199,803 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
em28xx-cards.c - driver for Empia EM2800/EM2820/2840 USB
video capture devices
Copyright (C) 2005 Ludovico Cavedon <[email protected]>
Markus Rechberger <[email protected]>
Mauro Carvalho Chehab <[email protected]>
Sascha Sommer <[email protected]>
Copyright (C) 2012 Frank Schäfer <[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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "em28xx.h"
#include <linux/init.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/delay.h>
#include <linux/i2c.h>
#include <linux/usb.h>
#include <media/tuner.h>
#include <media/drv-intf/msp3400.h>
#include <media/i2c/saa7115.h>
#include <dt-bindings/media/tvp5150.h>
#include <media/i2c/tvaudio.h>
#include <media/i2c-addr.h>
#include <media/tveeprom.h>
#include <media/v4l2-common.h>
#include <sound/ac97_codec.h>
#define DRIVER_NAME "em28xx"
static int tuner = -1;
module_param(tuner, int, 0444);
MODULE_PARM_DESC(tuner, "tuner type");
static unsigned int disable_ir;
module_param(disable_ir, int, 0444);
MODULE_PARM_DESC(disable_ir, "disable infrared remote support");
static unsigned int disable_usb_speed_check;
module_param(disable_usb_speed_check, int, 0444);
MODULE_PARM_DESC(disable_usb_speed_check,
"override min bandwidth requirement of 480M bps");
static unsigned int card[] = {[0 ... (EM28XX_MAXBOARDS - 1)] = -1U };
module_param_array(card, int, NULL, 0444);
MODULE_PARM_DESC(card, "card type");
static int usb_xfer_mode = -1;
module_param(usb_xfer_mode, int, 0444);
MODULE_PARM_DESC(usb_xfer_mode,
"USB transfer mode for frame data (-1 = auto, 0 = prefer isoc, 1 = prefer bulk)");
/* Bitmask marking allocated devices from 0 to EM28XX_MAXBOARDS - 1 */
static DECLARE_BITMAP(em28xx_devused, EM28XX_MAXBOARDS);
struct em28xx_hash_table {
unsigned long hash;
unsigned int model;
unsigned int tuner;
};
static void em28xx_pre_card_setup(struct em28xx *dev);
/*
* Reset sequences for analog/digital modes
*/
/* Reset for the most [analog] boards */
static struct em28xx_reg_seq default_analog[] = {
{EM2820_R08_GPIO_CTRL, 0x6d, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Reset for the most [digital] boards */
static struct em28xx_reg_seq default_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x6e, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Board Hauppauge WinTV HVR 900 analog */
static struct em28xx_reg_seq hauppauge_wintv_hvr_900_analog[] = {
{EM2820_R08_GPIO_CTRL, 0x2d, ~EM_GPIO_4, 10},
{ 0x05, 0xff, 0x10, 10},
{ -1, -1, -1, -1},
};
/* Board Hauppauge WinTV HVR 900 digital */
static struct em28xx_reg_seq hauppauge_wintv_hvr_900_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x2e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x04, 0x0f, 10},
{EM2880_R04_GPO, 0x0c, 0x0f, 10},
{ -1, -1, -1, -1},
};
/* Board Hauppauge WinTV HVR 900 (R2) digital */
static struct em28xx_reg_seq hauppauge_wintv_hvr_900R2_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x2e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x0c, 0x0f, 10},
{ -1, -1, -1, -1},
};
/* Boards - EM2880 MSI DIGIVOX AD and EM2880_BOARD_MSI_DIGIVOX_AD_II */
static struct em28xx_reg_seq em2880_msi_digivox_ad_analog[] = {
{EM2820_R08_GPIO_CTRL, 0x69, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Boards - EM2880 MSI DIGIVOX AD and EM2880_BOARD_MSI_DIGIVOX_AD_II */
/* Board - EM2870 Kworld 355u
Analog - No input analog */
/* Board - EM2882 Kworld 315U digital */
static struct em28xx_reg_seq em2882_kworld_315u_digital[] = {
{EM2820_R08_GPIO_CTRL, 0xff, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0xfe, 0xff, 10},
{EM2880_R04_GPO, 0x04, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0x7e, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq em2882_kworld_315u_tuner_gpio[] = {
{EM2880_R04_GPO, 0x08, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq kworld_330u_analog[] = {
{EM2820_R08_GPIO_CTRL, 0x6d, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x00, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq kworld_330u_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{ -1, -1, -1, -1},
};
/* Evga inDtube
GPIO0 - Enable digital power (s5h1409) - low to enable
GPIO1 - Enable analog power (tvp5150/emp202) - low to enable
GPIO4 - xc3028 reset
GOP3 - s5h1409 reset
*/
static struct em28xx_reg_seq evga_indtube_analog[] = {
{EM2820_R08_GPIO_CTRL, 0x79, 0xff, 60},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq evga_indtube_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x7a, 0xff, 1},
{EM2880_R04_GPO, 0x04, 0xff, 10},
{EM2880_R04_GPO, 0x0c, 0xff, 1},
{ -1, -1, -1, -1},
};
/*
* KWorld PlusTV 340U, UB435-Q and UB435-Q V2 (ATSC) GPIOs map:
* EM_GPIO_0 - currently unknown
* EM_GPIO_1 - LED disable/enable (1 = off, 0 = on)
* EM_GPIO_2 - currently unknown
* EM_GPIO_3 - currently unknown
* EM_GPIO_4 - TDA18271HD/C1 tuner (1 = active, 0 = in reset)
* EM_GPIO_5 - LGDT3304 ATSC/QAM demod (1 = active, 0 = in reset)
* EM_GPIO_6 - currently unknown
* EM_GPIO_7 - currently unknown
*/
static struct em28xx_reg_seq kworld_a340_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x6d, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq kworld_ub435q_v3_digital[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xfe, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xbe, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xfe, 0xff, 100},
{ -1, -1, -1, -1},
};
/* Pinnacle Hybrid Pro eb1a:2881 */
static struct em28xx_reg_seq pinnacle_hybrid_pro_analog[] = {
{EM2820_R08_GPIO_CTRL, 0xfd, ~EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq pinnacle_hybrid_pro_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x04, 0xff, 100},/* zl10353 reset */
{EM2880_R04_GPO, 0x0c, 0xff, 1},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq terratec_cinergy_USB_XS_FR_analog[] = {
{EM2820_R08_GPIO_CTRL, 0x6d, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x00, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq terratec_cinergy_USB_XS_FR_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{ -1, -1, -1, -1},
};
/* PCTV HD Mini (80e) GPIOs
0-5: not used
6: demod reset, active low
7: LED on, active high */
static struct em28xx_reg_seq em2874_pctv_80e_digital[] = {
{EM28XX_R06_I2C_CLK, 0x45, 0xff, 10}, /*400 KHz*/
{EM2874_R80_GPIO_P0_CTRL, 0x00, 0xff, 100},/*Demod reset*/
{EM2874_R80_GPIO_P0_CTRL, 0x40, 0xff, 10},
{ -1, -1, -1, -1},
};
/* eb1a:2868 Reddo DVB-C USB TV Box
GPIO4 - CU1216L NIM
Other GPIOs seems to be don't care. */
static struct em28xx_reg_seq reddo_dvb_c_usb_box[] = {
{EM2820_R08_GPIO_CTRL, 0xfe, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0xde, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0xfe, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0xff, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0x7f, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0x6f, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0xff, 0xff, 10},
{ -1, -1, -1, -1},
};
/* Callback for the most boards */
static struct em28xx_reg_seq default_tuner_gpio[] = {
{EM2820_R08_GPIO_CTRL, EM_GPIO_4, EM_GPIO_4, 10},
{EM2820_R08_GPIO_CTRL, 0, EM_GPIO_4, 10},
{EM2820_R08_GPIO_CTRL, EM_GPIO_4, EM_GPIO_4, 10},
{ -1, -1, -1, -1},
};
/* Mute/unmute */
static struct em28xx_reg_seq compro_unmute_tv_gpio[] = {
{EM2820_R08_GPIO_CTRL, 5, 7, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq compro_unmute_svid_gpio[] = {
{EM2820_R08_GPIO_CTRL, 4, 7, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq compro_mute_gpio[] = {
{EM2820_R08_GPIO_CTRL, 6, 7, 10},
{ -1, -1, -1, -1},
};
/* Terratec AV350 */
static struct em28xx_reg_seq terratec_av350_mute_gpio[] = {
{EM2820_R08_GPIO_CTRL, 0xff, 0x7f, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq terratec_av350_unmute_gpio[] = {
{EM2820_R08_GPIO_CTRL, 0xff, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq silvercrest_reg_seq[] = {
{EM2820_R08_GPIO_CTRL, 0xff, 0xff, 10},
{EM2820_R08_GPIO_CTRL, 0x01, 0xf7, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq vc211a_enable[] = {
{EM2820_R08_GPIO_CTRL, 0xff, 0x07, 10},
{EM2820_R08_GPIO_CTRL, 0xff, 0x0f, 10},
{EM2820_R08_GPIO_CTRL, 0xff, 0x0b, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq dikom_dk300_digital[] = {
{EM2820_R08_GPIO_CTRL, 0x6e, ~EM_GPIO_4, 10},
{EM2880_R04_GPO, 0x08, 0xff, 10},
{ -1, -1, -1, -1},
};
/* Reset for the most [digital] boards */
static struct em28xx_reg_seq leadership_digital[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x70, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq leadership_reset[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xf0, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xb0, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xf0, 0xff, 10},
{ -1, -1, -1, -1},
};
/* 2013:024f PCTV nanoStick T2 290e
* GPIO_6 - demod reset
* GPIO_7 - LED
*/
static struct em28xx_reg_seq pctv_290e[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x00, 0xff, 80},
{EM2874_R80_GPIO_P0_CTRL, 0x40, 0xff, 80}, /* GPIO_6 = 1 */
{EM2874_R80_GPIO_P0_CTRL, 0xc0, 0xff, 80}, /* GPIO_7 = 1 */
{ -1, -1, -1, -1},
};
#if 0
static struct em28xx_reg_seq terratec_h5_gpio[] = {
{EM2820_R08_GPIO_CTRL, 0xff, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xf6, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xf2, 0xff, 50},
{EM2874_R80_GPIO_P0_CTRL, 0xf6, 0xff, 50},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq terratec_h5_digital[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xf6, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xe6, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xa6, 0xff, 10},
{ -1, -1, -1, -1},
};
#endif
/* 2013:024f PCTV DVB-S2 Stick 460e
* GPIO_0 - POWER_ON
* GPIO_1 - BOOST
* GPIO_2 - VUV_LNB (red LED)
* GPIO_3 - EXT_12V
* GPIO_4 - INT_DEM (DEMOD GPIO_0)
* GPIO_5 - INT_LNB
* GPIO_6 - RESET_DEM
* GPIO_7 - LED (green LED)
*/
static struct em28xx_reg_seq pctv_460e[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x01, 0xff, 50},
{ 0x0d, 0xff, 0xff, 50},
{EM2874_R80_GPIO_P0_CTRL, 0x41, 0xff, 50}, /* GPIO_6=1 */
{ 0x0d, 0x42, 0xff, 50},
{EM2874_R80_GPIO_P0_CTRL, 0x61, 0xff, 50}, /* GPIO_5=1 */
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq c3tech_digital_duo_digital[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xfd, 0xff, 10}, /* xc5000 reset */
{EM2874_R80_GPIO_P0_CTRL, 0xf9, 0xff, 35},
{EM2874_R80_GPIO_P0_CTRL, 0xfd, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xfe, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xbe, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xfe, 0xff, 20},
{ -1, -1, -1, -1},
};
/*
* 2013:0258 PCTV DVB-S2 Stick (461e)
* GPIO 0 = POWER_ON
* GPIO 1 = BOOST
* GPIO 2 = VUV_LNB (red LED)
* GPIO 3 = #EXT_12V
* GPIO 4 = INT_DEM
* GPIO 5 = INT_LNB
* GPIO 6 = #RESET_DEM
* GPIO 7 = P07_LED (green LED)
*/
static struct em28xx_reg_seq pctv_461e[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x7f, 0xff, 0},
{0x0d, 0xff, 0xff, 0},
{EM2874_R80_GPIO_P0_CTRL, 0x3f, 0xff, 100}, /* reset demod */
{EM2874_R80_GPIO_P0_CTRL, 0x7f, 0xff, 200}, /* reset demod */
{0x0d, 0x42, 0xff, 0},
{EM2874_R80_GPIO_P0_CTRL, 0xeb, 0xff, 0},
{EM2874_R5F_TS_ENABLE, 0x84, 0x84, 0}, /* parallel? | null discard */
{ -1, -1, -1, -1},
};
#if 0
static struct em28xx_reg_seq hauppauge_930c_gpio[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x6f, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0x4f, 0xff, 10}, /* xc5000 reset */
{EM2874_R80_GPIO_P0_CTRL, 0x6f, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0x4f, 0xff, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq hauppauge_930c_digital[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xf6, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xe6, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xa6, 0xff, 10},
{ -1, -1, -1, -1},
};
#endif
/* 1b80:e425 MaxMedia UB425-TC
* 1b80:e1cc Delock 61959
* GPIO_6 - demod reset, 0=active
* GPIO_7 - LED, 0=active
*/
static struct em28xx_reg_seq maxmedia_ub425_tc[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x83, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xc3, 0xff, 100}, /* GPIO_6 = 1 */
{EM2874_R80_GPIO_P0_CTRL, 0x43, 0xff, 000}, /* GPIO_7 = 0 */
{ -1, -1, -1, -1},
};
/* 2304:0242 PCTV QuatroStick (510e)
* GPIO_2: decoder reset, 0=active
* GPIO_4: decoder suspend, 0=active
* GPIO_6: demod reset, 0=active
* GPIO_7: LED, 1=active
*/
static struct em28xx_reg_seq pctv_510e[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x10, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0x14, 0xff, 100}, /* GPIO_2 = 1 */
{EM2874_R80_GPIO_P0_CTRL, 0x54, 0xff, 050}, /* GPIO_6 = 1 */
{ -1, -1, -1, -1},
};
/* 2013:0251 PCTV QuatroStick nano (520e)
* GPIO_2: decoder reset, 0=active
* GPIO_4: decoder suspend, 0=active
* GPIO_6: demod reset, 0=active
* GPIO_7: LED, 1=active
*/
static struct em28xx_reg_seq pctv_520e[] = {
{EM2874_R80_GPIO_P0_CTRL, 0x10, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0x14, 0xff, 100}, /* GPIO_2 = 1 */
{EM2874_R80_GPIO_P0_CTRL, 0x54, 0xff, 050}, /* GPIO_6 = 1 */
{EM2874_R80_GPIO_P0_CTRL, 0xd4, 0xff, 000}, /* GPIO_7 = 1 */
{ -1, -1, -1, -1},
};
/* 1ae7:9003/9004 SpeedLink Vicious And Devine Laplace webcam
* reg 0x80/0x84:
* GPIO_0: capturing LED, 0=on, 1=off
* GPIO_2: AV mute button, 0=pressed, 1=unpressed
* GPIO 3: illumination button, 0=pressed, 1=unpressed
* GPIO_6: illumination/flash LED, 0=on, 1=off
* reg 0x81/0x85:
* GPIO_7: snapshot button, 0=pressed, 1=unpressed
*/
static struct em28xx_reg_seq speedlink_vad_laplace_reg_seq[] = {
{EM2820_R08_GPIO_CTRL, 0xf7, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xb2, 10},
{ -1, -1, -1, -1},
};
static struct em28xx_reg_seq pctv_292e[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 0},
{0x0d, 0xff, 0xff, 950},
{EM2874_R80_GPIO_P0_CTRL, 0xbd, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xfd, 0xff, 410},
{EM2874_R80_GPIO_P0_CTRL, 0x7d, 0xff, 300},
{EM2874_R80_GPIO_P0_CTRL, 0x7c, 0xff, 60},
{0x0d, 0x42, 0xff, 50},
{EM2874_R5F_TS_ENABLE, 0x85, 0xff, 0},
{-1, -1, -1, -1},
};
static struct em28xx_reg_seq terratec_t2_stick_hd[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 0},
{0x0d, 0xff, 0xff, 600},
{EM2874_R80_GPIO_P0_CTRL, 0xfc, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xbc, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xfc, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0x00, 0xff, 300},
{EM2874_R80_GPIO_P0_CTRL, 0xf8, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xfc, 0xff, 300},
{0x0d, 0x42, 0xff, 1000},
{EM2874_R5F_TS_ENABLE, 0x85, 0xff, 0},
{-1, -1, -1, -1},
};
static struct em28xx_reg_seq plex_px_bcud[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 0},
{0x0d, 0xff, 0xff, 0},
{EM2874_R50_IR_CONFIG, 0x01, 0xff, 0},
{EM28XX_R06_I2C_CLK, 0x40, 0xff, 0},
{EM2874_R80_GPIO_P0_CTRL, 0xfd, 0xff, 100},
{EM28XX_R12_VINENABLE, 0x20, 0x20, 0},
{0x0d, 0x42, 0xff, 1000},
{EM2874_R80_GPIO_P0_CTRL, 0xfc, 0xff, 10},
{EM2874_R80_GPIO_P0_CTRL, 0xfd, 0xff, 10},
{0x73, 0xfd, 0xff, 100},
{-1, -1, -1, -1},
};
/*
* 2040:0265 Hauppauge WinTV-dualHD DVB
* 2040:026d Hauppauge WinTV-dualHD ATSC/QAM
* reg 0x80/0x84:
* GPIO_0: Yellow LED tuner 1, 0=on, 1=off
* GPIO_1: Green LED tuner 1, 0=on, 1=off
* GPIO_2: Yellow LED tuner 2, 0=on, 1=off
* GPIO_3: Green LED tuner 2, 0=on, 1=off
* GPIO_5: Reset #2, 0=active
* GPIO_6: Reset #1, 0=active
*/
static struct em28xx_reg_seq hauppauge_dualhd_dvb[] = {
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 0},
{0x0d, 0xff, 0xff, 200},
{0x50, 0x04, 0xff, 300},
{EM2874_R80_GPIO_P0_CTRL, 0xbf, 0xff, 100}, /* demod 1 reset */
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 100},
{EM2874_R80_GPIO_P0_CTRL, 0xdf, 0xff, 100}, /* demod 2 reset */
{EM2874_R80_GPIO_P0_CTRL, 0xff, 0xff, 100},
{EM2874_R5F_TS_ENABLE, 0x44, 0xff, 50},
{EM2874_R5D_TS1_PKT_SIZE, 0x05, 0xff, 50},
{EM2874_R5E_TS2_PKT_SIZE, 0x05, 0xff, 50},
{-1, -1, -1, -1},
};
/*
* Button definitions
*/
static struct em28xx_button std_snapshot_button[] = {
{
.role = EM28XX_BUTTON_SNAPSHOT,
.reg_r = EM28XX_R0C_USBSUSP,
.reg_clearing = EM28XX_R0C_USBSUSP,
.mask = EM28XX_R0C_USBSUSP_SNAPSHOT,
.inverted = 0,
},
{-1, 0, 0, 0, 0},
};
static struct em28xx_button speedlink_vad_laplace_buttons[] = {
{
.role = EM28XX_BUTTON_SNAPSHOT,
.reg_r = EM2874_R85_GPIO_P1_STATE,
.mask = 0x80,
.inverted = 1,
},
{
.role = EM28XX_BUTTON_ILLUMINATION,
.reg_r = EM2874_R84_GPIO_P0_STATE,
.mask = 0x08,
.inverted = 1,
},
{-1, 0, 0, 0, 0},
};
/*
* LED definitions
*/
static struct em28xx_led speedlink_vad_laplace_leds[] = {
{
.role = EM28XX_LED_ANALOG_CAPTURING,
.gpio_reg = EM2874_R80_GPIO_P0_CTRL,
.gpio_mask = 0x01,
.inverted = 1,
},
{
.role = EM28XX_LED_ILLUMINATION,
.gpio_reg = EM2874_R80_GPIO_P0_CTRL,
.gpio_mask = 0x40,
.inverted = 1,
},
{-1, 0, 0, 0},
};
static struct em28xx_led kworld_ub435q_v3_leds[] = {
{
.role = EM28XX_LED_DIGITAL_CAPTURING,
.gpio_reg = EM2874_R80_GPIO_P0_CTRL,
.gpio_mask = 0x80,
.inverted = 1,
},
{-1, 0, 0, 0},
};
static struct em28xx_led pctv_80e_leds[] = {
{
.role = EM28XX_LED_DIGITAL_CAPTURING,
.gpio_reg = EM2874_R80_GPIO_P0_CTRL,
.gpio_mask = 0x80,
.inverted = 0,
},
{-1, 0, 0, 0},
};
static struct em28xx_led terratec_grabby_leds[] = {
{
.role = EM28XX_LED_ANALOG_CAPTURING,
.gpio_reg = EM2820_R08_GPIO_CTRL,
.gpio_mask = EM_GPIO_3,
.inverted = 1,
},
{-1, 0, 0, 0},
};
static struct em28xx_led hauppauge_dualhd_leds[] = {
{
.role = EM28XX_LED_DIGITAL_CAPTURING,
.gpio_reg = EM2874_R80_GPIO_P0_CTRL,
.gpio_mask = EM_GPIO_1,
.inverted = 1,
},
{
.role = EM28XX_LED_DIGITAL_CAPTURING_TS2,
.gpio_reg = EM2874_R80_GPIO_P0_CTRL,
.gpio_mask = EM_GPIO_3,
.inverted = 1,
},
{-1, 0, 0, 0},
};
/*
* Board definitions
*/
struct em28xx_board em28xx_boards[] = {
[EM2750_BOARD_UNKNOWN] = {
.name = "EM2710/EM2750/EM2751 webcam grabber",
.xclk = EM28XX_XCLK_FREQUENCY_20MHZ,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = silvercrest_reg_seq,
} },
},
[EM2800_BOARD_UNKNOWN] = {
.name = "Unknown EM2800 video grabber",
.is_em2800 = 1,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_UNKNOWN] = {
.name = "Unknown EM2750/28xx video grabber",
.tuner_type = TUNER_ABSENT,
.is_webcam = 1, /* To enable sensor probe */
},
[EM2750_BOARD_DLCW_130] = {
/* Beijing Huaqi Information Digital Technology Co., Ltd */
.name = "Huaqi DLCW-130",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.xclk = EM28XX_XCLK_FREQUENCY_48MHZ,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2820_BOARD_KWORLD_PVRTV2800RF] = {
.name = "Kworld PVR TV 2800 RF",
.tuner_type = TUNER_TEMIC_PAL,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_GADMEI_TVR200] = {
.name = "Gadmei TVR200",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_TERRATEC_CINERGY_250] = {
.name = "Terratec Cinergy 250 USB",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.has_ir_i2c = 1,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PINNACLE_USB_2] = {
.name = "Pinnacle PCTV USB 2",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.has_ir_i2c = 1,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_HAUPPAUGE_WINTV_USB_2] = {
.name = "Hauppauge WinTV USB 2",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.decoder = EM28XX_TVP5150,
.has_msp34xx = 1,
.has_ir_i2c = 1,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = MSP_INPUT_DEFAULT,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = MSP_INPUT(MSP_IN_SCART1, MSP_IN_TUNER1,
MSP_DSP_IN_SCART, MSP_DSP_IN_SCART),
} },
},
[EM2820_BOARD_DLINK_USB_TV] = {
.name = "D-Link DUB-T210 TV Tuner",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_HERCULES_SMART_TV_USB2] = {
.name = "Hercules Smart TV USB 2.0",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PINNACLE_USB_2_FM1216ME] = {
.name = "Pinnacle PCTV USB 2 (Philips FM1216ME)",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_GADMEI_UTV310] = {
.name = "Gadmei UTV310",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_TNF_5335MF,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_LEADTEK_WINFAST_USBII_DELUXE] = {
.name = "Leadtek Winfast USB II Deluxe",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_PHILIPS_FM1216ME_MK3,
.has_ir_i2c = 1,
.tvaudio_addr = 0x58,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT2_ACTIVE |
TDA9887_QSS,
.decoder = EM28XX_SAA711X,
.adecoder = EM28XX_TVAUDIO,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE4,
.amux = EM28XX_AMUX_AUX,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE5,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
.radio = {
.type = EM28XX_RADIO,
.amux = EM28XX_AMUX_AUX,
}
},
[EM2820_BOARD_VIDEOLOGY_20K14XUSB] = {
.name = "Videology 20K14XUSB USB2.0",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2820_BOARD_SILVERCREST_WEBCAM] = {
.name = "Silvercrest Webcam 1.3mpix",
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = silvercrest_reg_seq,
} },
},
[EM2821_BOARD_SUPERCOMP_USB_2] = {
.name = "Supercomp USB 2.0 TV",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2821_BOARD_USBGEAR_VD204] = {
.name = "Usbgear VD204v9",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_NETGMBH_CAM] = {
/* Beijing Huaqi Information Digital Technology Co., Ltd */
.name = "NetGMBH Cam",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = 0,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2860_BOARD_TYPHOON_DVD_MAKER] = {
.name = "Typhoon DVD Maker",
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT, /* Capture only device */
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_GADMEI_UTV330] = {
.name = "Gadmei UTV330",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_TNF_5335MF,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2861_BOARD_GADMEI_UTV330PLUS] = {
.name = "Gadmei UTV330+",
.tuner_type = TUNER_TNF_5335MF,
.tda9887_conf = TDA9887_PRESENT,
.ir_codes = RC_MAP_GADMEI_RM008Z,
.decoder = EM28XX_SAA711X,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_TERRATEC_HYBRID_XS] = {
.name = "Terratec Cinergy A Hybrid XS",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2861_BOARD_KWORLD_PVRTV_300U] = {
.name = "KWorld PVRTV 300U",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2861_BOARD_YAKUMO_MOVIE_MIXER] = {
.name = "Yakumo MovieMixer",
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_TVP5150_REFERENCE_DESIGN] = {
.name = "EM2860/TVP5150 Reference Design",
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2861_BOARD_PLEXTOR_PX_TV100U] = {
.name = "Plextor ConvertX PX-TV100U",
.tuner_type = TUNER_TNF_5335MF,
.xclk = EM28XX_XCLK_I2S_MSB_TIMING |
EM28XX_XCLK_FREQUENCY_12MHZ,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_TVP5150,
.has_msp34xx = 1,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
} },
},
/* Those boards with em2870 are DVB Only*/
[EM2870_BOARD_TERRATEC_XS] = {
.name = "Terratec Cinergy T XS",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
},
[EM2870_BOARD_TERRATEC_XS_MT2060] = {
.name = "Terratec Cinergy T XS (MT2060)",
.xclk = EM28XX_XCLK_IR_RC5_MODE |
EM28XX_XCLK_FREQUENCY_12MHZ,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE,
.tuner_type = TUNER_ABSENT, /* MT2060 */
.has_dvb = 1,
.tuner_gpio = default_tuner_gpio,
},
[EM2870_BOARD_KWORLD_350U] = {
.name = "Kworld 350 U DVB-T",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
},
[EM2870_BOARD_KWORLD_355U] = {
.name = "Kworld 355 U DVB-T",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = default_tuner_gpio,
.has_dvb = 1,
.dvb_gpio = default_digital,
},
[EM2870_BOARD_PINNACLE_PCTV_DVB] = {
.name = "Pinnacle PCTV DVB-T",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* MT2060 */
/* djh - I have serious doubts this is right... */
.xclk = EM28XX_XCLK_IR_RC5_MODE |
EM28XX_XCLK_FREQUENCY_10MHZ,
},
[EM2870_BOARD_COMPRO_VIDEOMATE] = {
.name = "Compro, VideoMate U3",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_ABSENT, /* MT2060 */
},
[EM2880_BOARD_TERRATEC_HYBRID_XS_FR] = {
.name = "Terratec Hybrid XS Secam",
.has_msp34xx = 1,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = terratec_cinergy_USB_XS_FR_digital,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = terratec_cinergy_USB_XS_FR_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = terratec_cinergy_USB_XS_FR_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = terratec_cinergy_USB_XS_FR_analog,
} },
},
[EM2884_BOARD_TERRATEC_H5] = {
.name = "Terratec Cinergy H5",
.has_dvb = 1,
#if 0
.tuner_type = TUNER_PHILIPS_TDA8290,
.tuner_addr = 0x41,
.dvb_gpio = terratec_h5_digital, /* FIXME: probably wrong */
.tuner_gpio = terratec_h5_gpio,
#else
.tuner_type = TUNER_ABSENT,
#endif
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
[EM2884_BOARD_HAUPPAUGE_WINTV_HVR_930C] = {
.name = "Hauppauge WinTV HVR 930C",
.has_dvb = 1,
#if 0 /* FIXME: Add analog support */
.tuner_type = TUNER_XC5000,
.tuner_addr = 0x41,
.dvb_gpio = hauppauge_930c_digital,
.tuner_gpio = hauppauge_930c_gpio,
#else
.tuner_type = TUNER_ABSENT,
#endif
.ir_codes = RC_MAP_HAUPPAUGE,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
[EM2884_BOARD_C3TECH_DIGITAL_DUO] = {
.name = "C3 Tech Digital Duo HDTV/SDTV USB",
.has_dvb = 1,
/* FIXME: Add analog support - need a saa7136 driver */
.tuner_type = TUNER_ABSENT, /* Digital-only TDA18271HD */
.ir_codes = RC_MAP_EMPTY,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE,
.dvb_gpio = c3tech_digital_duo_digital,
},
[EM2884_BOARD_CINERGY_HTC_STICK] = {
.name = "Terratec Cinergy HTC Stick",
.has_dvb = 1,
.ir_codes = RC_MAP_NEC_TERRATEC_CINERGY_XS,
.tuner_type = TUNER_ABSENT,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
[EM2884_BOARD_ELGATO_EYETV_HYBRID_2008] = {
.name = "Elgato EyeTV Hybrid 2008 INT",
.has_dvb = 1,
.ir_codes = RC_MAP_NEC_TERRATEC_CINERGY_XS,
.tuner_type = TUNER_ABSENT,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
[EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900] = {
.name = "Hauppauge WinTV HVR 900",
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_HAUPPAUGE,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2] = {
.name = "Hauppauge WinTV HVR 900 (R2)",
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900R2_digital,
.ir_codes = RC_MAP_HAUPPAUGE,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850] = {
.name = "Hauppauge WinTV HVR 850",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_HAUPPAUGE,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950] = {
.name = "Hauppauge WinTV HVR 950",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_HAUPPAUGE,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_PINNACLE_PCTV_HD_PRO] = {
.name = "Pinnacle PCTV HD Pro Stick",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_AMD_ATI_TV_WONDER_HD_600] = {
.name = "AMD ATI TV Wonder HD 600",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_ATI_TV_WONDER_HD_600,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2880_BOARD_TERRATEC_HYBRID_XS] = {
.name = "Terratec Hybrid XS",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = default_digital,
.ir_codes = RC_MAP_TERRATEC_CINERGY_XS,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ, /* NEC IR */
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
/* maybe there's a reason behind it why Terratec sells the Hybrid XS
as Prodigy XS with a different PID, let's keep it separated for now
maybe we'll need it lateron */
[EM2880_BOARD_TERRATEC_PRODIGY_XS] = {
.name = "Terratec Prodigy XS",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2820_BOARD_MSI_VOX_USB_2] = {
.name = "MSI VOX USB 2.0",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT |
TDA9887_PORT1_ACTIVE |
TDA9887_PORT2_ACTIVE,
.max_range_640_480 = 1,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE4,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_TERRATEC_CINERGY_200] = {
.name = "Terratec Cinergy 200 USB",
.is_em2800 = 1,
.has_ir_i2c = 1,
.tuner_type = TUNER_LG_TALN,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_GRABBEEX_USB2800] = {
.name = "eMPIA Technology, Inc. GrabBeeX+ Video Encoder",
.is_em2800 = 1,
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT, /* capture only board */
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_VC211A] = {
.name = "Actionmaster/LinXcel/Digitus VC211A",
.is_em2800 = 1,
.tuner_type = TUNER_ABSENT, /* Capture-only board */
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = vc211a_enable,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = vc211a_enable,
} },
},
[EM2800_BOARD_LEADTEK_WINFAST_USBII] = {
.name = "Leadtek Winfast USB II",
.is_em2800 = 1,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_KWORLD_USB2800] = {
.name = "Kworld USB2800",
.is_em2800 = 1,
.tuner_type = TUNER_PHILIPS_FCV1236D,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PINNACLE_DVC_90] = {
.name = "Pinnacle Dazzle DVC 90/100/101/107 / Kaiser Baas Video to DVD maker / Kworld DVD Maker 2 / Plextor ConvertX PX-AV100U",
.tuner_type = TUNER_ABSENT, /* capture only board */
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2800_BOARD_VGEAR_POCKETTV] = {
.name = "V-Gear PocketTV",
.is_em2800 = 1,
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PROLINK_PLAYTV_BOX4_USB2] = {
.name = "Pixelview PlayTV Box 4 USB 2.0",
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_YMEC_TVF_5533MF,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
.aout = EM28XX_AOUT_MONO | /* I2S */
EM28XX_AOUT_MASTER, /* Line out pin */
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_PROLINK_PLAYTV_USB2] = {
.name = "SIIG AVTuner-PVR / Pixelview Prolink PlayTV USB 2.0",
.buttons = std_snapshot_button,
.tda9887_conf = TDA9887_PRESENT,
.tuner_type = TUNER_YMEC_TVF_5533MF,
.tuner_addr = 0x60,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
.aout = EM28XX_AOUT_MONO | /* I2S */
EM28XX_AOUT_MASTER, /* Line out pin */
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2860_BOARD_SAA711X_REFERENCE_DESIGN] = {
.name = "EM2860/SAA711X Reference Design",
.buttons = std_snapshot_button,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
} },
},
[EM2874_BOARD_LEADERSHIP_ISDBT] = {
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_100_KHZ,
.xclk = EM28XX_XCLK_FREQUENCY_10MHZ,
.name = "EM2874 Leadership ISDBT",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = leadership_reset,
.dvb_gpio = leadership_digital,
.has_dvb = 1,
},
[EM2880_BOARD_MSI_DIGIVOX_AD] = {
.name = "MSI DigiVox A/D",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
} },
},
[EM2880_BOARD_MSI_DIGIVOX_AD_II] = {
.name = "MSI DigiVox A/D II",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2880_msi_digivox_ad_analog,
} },
},
[EM2880_BOARD_KWORLD_DVB_305U] = {
.name = "KWorld DVB-T 305U",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2880_BOARD_KWORLD_DVB_310U] = {
.name = "KWorld DVB-T 310U",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.has_dvb = 1,
.dvb_gpio = default_digital,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, { /* S-video has not been tested yet */
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2882_BOARD_KWORLD_ATSC_315U] = {
.name = "KWorld ATSC 315U HDTV TV Box",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_THOMSON_DTT761X,
.tuner_gpio = em2882_kworld_315u_tuner_gpio,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_SAA711X,
.has_dvb = 1,
.dvb_gpio = em2882_kworld_315u_digital,
.ir_codes = RC_MAP_KWORLD_315U,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE,
/* Analog mode - still not ready */
/*.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = SAA7115_COMPOSITE2,
.amux = EM28XX_AMUX_VIDEO,
.gpio = em2882_kworld_315u_analog,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2882_kworld_315u_analog1,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = em2882_kworld_315u_analog1,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
} }, */
},
[EM2880_BOARD_EMPIRE_DUAL_TV] = {
.name = "Empire dual TV",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.has_dvb = 1,
.dvb_gpio = default_digital,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2881_BOARD_DNT_DA2_HYBRID] = {
.name = "DNT DA2 Hybrid",
.valid = EM28XX_BOARD_NOT_VALIDATED,
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = default_analog,
} },
},
[EM2881_BOARD_PINNACLE_HYBRID_PRO] = {
.name = "Pinnacle Hybrid Pro",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = pinnacle_hybrid_pro_digital,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = pinnacle_hybrid_pro_analog,
} },
},
[EM2882_BOARD_PINNACLE_HYBRID_PRO_330E] = {
.name = "Pinnacle Hybrid Pro (330e)",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900R2_digital,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2882_BOARD_KWORLD_VS_DVBT] = {
.name = "Kworld VS-DVB-T 323UR",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = kworld_330u_digital,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ, /* NEC IR */
.ir_codes = RC_MAP_KWORLD_315U,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2882_BOARD_TERRATEC_HYBRID_XS] = {
.name = "Terratec Cinnergy Hybrid T USB XS (em2882)",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.has_dvb = 1,
.dvb_gpio = hauppauge_wintv_hvr_900_digital,
.ir_codes = RC_MAP_TERRATEC_CINERGY_XS,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = hauppauge_wintv_hvr_900_analog,
} },
},
[EM2882_BOARD_DIKOM_DK300] = {
.name = "Dikom DK300",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = dikom_dk300_digital,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = default_analog,
} },
},
[EM2883_BOARD_KWORLD_HYBRID_330U] = {
.name = "Kworld PlusTV HD Hybrid 330",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = kworld_330u_digital,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_EEPROM_ON_BOARD |
EM28XX_I2C_EEPROM_KEY_VALID,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = kworld_330u_analog,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = kworld_330u_analog,
.aout = EM28XX_AOUT_PCM_IN | EM28XX_AOUT_PCM_STEREO,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = kworld_330u_analog,
} },
},
[EM2820_BOARD_COMPRO_VIDEOMATE_FORYOU] = {
.name = "Compro VideoMate ForYou/Stereo",
.tuner_type = TUNER_LG_PAL_NEW_TAPC,
.tvaudio_addr = 0xb0,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_TVP5150,
.adecoder = EM28XX_TVAUDIO,
.mute_gpio = compro_mute_gpio,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = compro_unmute_tv_gpio,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = compro_unmute_svid_gpio,
} },
},
[EM2860_BOARD_KAIOMY_TVNPC_U2] = {
.name = "Kaiomy TVnPC U2",
.vchannels = 3,
.tuner_type = TUNER_XC2028,
.tuner_addr = 0x61,
.mts_firmware = 1,
.decoder = EM28XX_TVP5150,
.tuner_gpio = default_tuner_gpio,
.ir_codes = RC_MAP_KAIOMY,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
.radio = {
.type = EM28XX_RADIO,
.amux = EM28XX_AMUX_LINE_IN,
}
},
[EM2860_BOARD_EASYCAP] = {
.name = "Easy Cap Capture DC-60",
.vchannels = 2,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2820_BOARD_IODATA_GVMVP_SZ] = {
.name = "IO-DATA GV-MVP/SZ",
.tuner_type = TUNER_PHILIPS_FM1236_MK3,
.tuner_gpio = default_tuner_gpio,
.tda9887_conf = TDA9887_PRESENT,
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
}, { /* Composite has not been tested yet */
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_VIDEO,
}, { /* S-video has not been tested yet */
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_VIDEO,
} },
},
[EM2860_BOARD_TERRATEC_GRABBY] = {
.name = "Terratec Grabby",
.vchannels = 2,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
.buttons = std_snapshot_button,
.leds = terratec_grabby_leds,
},
[EM2860_BOARD_TERRATEC_AV350] = {
.name = "Terratec AV350",
.vchannels = 2,
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_TVP5150,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ,
.mute_gpio = terratec_av350_mute_gpio,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AUDIO_SRC_LINE,
.gpio = terratec_av350_unmute_gpio,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AUDIO_SRC_LINE,
.gpio = terratec_av350_unmute_gpio,
} },
},
[EM2860_BOARD_ELGATO_VIDEO_CAPTURE] = {
.name = "Elgato Video Capture",
.decoder = EM28XX_SAA711X,
.tuner_type = TUNER_ABSENT, /* Capture only device */
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
[EM2882_BOARD_EVGA_INDTUBE] = {
.name = "Evga inDtube",
.tuner_type = TUNER_XC2028,
.tuner_gpio = default_tuner_gpio,
.decoder = EM28XX_TVP5150,
.xclk = EM28XX_XCLK_FREQUENCY_12MHZ, /* NEC IR */
.mts_firmware = 1,
.has_dvb = 1,
.dvb_gpio = evga_indtube_digital,
.ir_codes = RC_MAP_EVGA_INDTUBE,
.input = { {
.type = EM28XX_VMUX_TELEVISION,
.vmux = TVP5150_COMPOSITE0,
.amux = EM28XX_AMUX_VIDEO,
.gpio = evga_indtube_analog,
}, {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = evga_indtube_analog,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
.gpio = evga_indtube_analog,
} },
},
/* eb1a:2868 Empia EM2870 + Philips CU1216L NIM (Philips TDA10023 +
Infineon TUA6034) */
[EM2870_BOARD_REDDO_DVB_C_USB_BOX] = {
.name = "Reddo DVB-C USB TV Box",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = reddo_dvb_c_usb_box,
.has_dvb = 1,
},
/* 1b80:a340 - Empia EM2870, NXP TDA18271HD and LG DT3304, sold
* initially as the KWorld PlusTV 340U, then as the UB435-Q.
* Early variants have a TDA18271HD/C1, later ones a TDA18271HD/C2 */
[EM2870_BOARD_KWORLD_A340] = {
.name = "KWorld PlusTV 340U or UB435-Q (ATSC)",
.tuner_type = TUNER_ABSENT, /* Digital-only TDA18271HD */
.has_dvb = 1,
.dvb_gpio = kworld_a340_digital,
.tuner_gpio = default_tuner_gpio,
},
/* 2013:024f PCTV nanoStick T2 290e.
* Empia EM28174, Sony CXD2820R and NXP TDA18271HD/C2 */
[EM28174_BOARD_PCTV_290E] = {
.name = "PCTV nanoStick T2 290e",
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE | EM28XX_I2C_FREQ_100_KHZ,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = pctv_290e,
.has_dvb = 1,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
},
/* 2013:024f PCTV DVB-S2 Stick 460e
* Empia EM28174, NXP TDA10071, Conexant CX24118A and Allegro A8293 */
[EM28174_BOARD_PCTV_460E] = {
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE | EM28XX_I2C_FREQ_400_KHZ,
.name = "PCTV DVB-S2 Stick (460e)",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = pctv_460e,
.has_dvb = 1,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
},
/* eb1a:5006 Honestech VIDBOX NW03
* Empia EM2860, Philips SAA7113, Empia EMP202, No Tuner */
[EM2860_BOARD_HT_VIDBOX_NW03] = {
.name = "Honestech Vidbox NW03",
.tuner_type = TUNER_ABSENT,
.decoder = EM28XX_SAA711X,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = SAA7115_COMPOSITE0,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = SAA7115_SVIDEO3, /* S-VIDEO needs confirming */
.amux = EM28XX_AMUX_LINE_IN,
} },
},
/* 1b80:e425 MaxMedia UB425-TC
* Empia EM2874B + Micronas DRX 3913KA2 + NXP TDA18271HDC2 */
[EM2874_BOARD_MAXMEDIA_UB425_TC] = {
.name = "MaxMedia UB425-TC",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = maxmedia_ub425_tc,
.has_dvb = 1,
.ir_codes = RC_MAP_REDDO,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
/* 2304:0242 PCTV QuatroStick (510e)
* Empia EM2884 + Micronas DRX 3926K + NXP TDA18271HDC2 */
[EM2884_BOARD_PCTV_510E] = {
.name = "PCTV QuatroStick (510e)",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = pctv_510e,
.has_dvb = 1,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
/* 2013:0251 PCTV QuatroStick nano (520e)
* Empia EM2884 + Micronas DRX 3926K + NXP TDA18271HDC2 */
[EM2884_BOARD_PCTV_520E] = {
.name = "PCTV QuatroStick nano (520e)",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = pctv_520e,
.has_dvb = 1,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
[EM2884_BOARD_TERRATEC_HTC_USB_XS] = {
.name = "Terratec Cinergy HTC USB XS",
.has_dvb = 1,
.ir_codes = RC_MAP_NEC_TERRATEC_CINERGY_XS,
.tuner_type = TUNER_ABSENT,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
/* 1b80:e1cc Delock 61959
* Empia EM2874B + Micronas DRX 3913KA2 + NXP TDA18271HDC2
* mostly the same as MaxMedia UB-425-TC but different remote */
[EM2874_BOARD_DELOCK_61959] = {
.name = "Delock 61959",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = maxmedia_ub425_tc,
.has_dvb = 1,
.ir_codes = RC_MAP_DELOCK_61959,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
},
/*
* 1b80:e346 KWorld USB ATSC TV Stick UB435-Q V2
* Empia EM2874B + LG DT3305 + NXP TDA18271HDC2
*/
[EM2874_BOARD_KWORLD_UB435Q_V2] = {
.name = "KWorld USB ATSC TV Stick UB435-Q V2",
.tuner_type = TUNER_ABSENT,
.has_dvb = 1,
.dvb_gpio = kworld_a340_digital,
.tuner_gpio = default_tuner_gpio,
.def_i2c_bus = 1,
},
/*
* 1b80:e34c KWorld USB ATSC TV Stick UB435-Q V3
* Empia EM2874B + LG DT3305 + NXP TDA18271HDC2
*/
[EM2874_BOARD_KWORLD_UB435Q_V3] = {
.name = "KWorld USB ATSC TV Stick UB435-Q V3",
.tuner_type = TUNER_ABSENT,
.has_dvb = 1,
.tuner_gpio = kworld_ub435q_v3_digital,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_100_KHZ,
.leds = kworld_ub435q_v3_leds,
},
[EM2874_BOARD_PCTV_HD_MINI_80E] = {
.name = "Pinnacle PCTV HD Mini",
.tuner_type = TUNER_ABSENT,
.has_dvb = 1,
.dvb_gpio = em2874_pctv_80e_digital,
.decoder = EM28XX_NODECODER,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
.leds = pctv_80e_leds,
},
/* 1ae7:9003/9004 SpeedLink Vicious And Devine Laplace webcam
* Empia EM2765 + OmniVision OV2640 */
[EM2765_BOARD_SPEEDLINK_VAD_LAPLACE] = {
.name = "SpeedLink Vicious And Devine Laplace webcam",
.xclk = EM28XX_XCLK_FREQUENCY_24MHZ,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_100_KHZ,
.def_i2c_bus = 1,
.tuner_type = TUNER_ABSENT,
.is_webcam = 1,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.amux = EM28XX_AMUX_VIDEO,
.gpio = speedlink_vad_laplace_reg_seq,
} },
.buttons = speedlink_vad_laplace_buttons,
.leds = speedlink_vad_laplace_leds,
},
/* 2013:0258 PCTV DVB-S2 Stick (461e)
* Empia EM28178, Montage M88DS3103, Montage M88TS2022, Allegro A8293 */
[EM28178_BOARD_PCTV_461E] = {
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE | EM28XX_I2C_FREQ_400_KHZ,
.name = "PCTV DVB-S2 Stick (461e)",
.tuner_type = TUNER_ABSENT,
.tuner_gpio = pctv_461e,
.has_dvb = 1,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
},
/* 2013:025f PCTV tripleStick (292e).
* Empia EM28178, Silicon Labs Si2168, Silicon Labs Si2157 */
[EM28178_BOARD_PCTV_292E] = {
.name = "PCTV tripleStick (292e)",
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE | EM28XX_I2C_FREQ_400_KHZ,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = pctv_292e,
.has_dvb = 1,
.ir_codes = RC_MAP_PINNACLE_PCTV_HD,
},
[EM2861_BOARD_LEADTEK_VC100] = {
.name = "Leadtek VC100",
.tuner_type = TUNER_ABSENT, /* Capture only device */
.decoder = EM28XX_TVP5150,
.input = { {
.type = EM28XX_VMUX_COMPOSITE,
.vmux = TVP5150_COMPOSITE1,
.amux = EM28XX_AMUX_LINE_IN,
}, {
.type = EM28XX_VMUX_SVIDEO,
.vmux = TVP5150_SVIDEO,
.amux = EM28XX_AMUX_LINE_IN,
} },
},
/* eb1a:8179 Terratec Cinergy T2 Stick HD.
* Empia EM28178, Silicon Labs Si2168, Silicon Labs Si2146 */
[EM28178_BOARD_TERRATEC_T2_STICK_HD] = {
.name = "Terratec Cinergy T2 Stick HD",
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE | EM28XX_I2C_FREQ_400_KHZ,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = terratec_t2_stick_hd,
.has_dvb = 1,
.ir_codes = RC_MAP_TERRATEC_SLIM_2,
},
/*
* 3275:0085 PLEX PX-BCUD.
* Empia EM28178, TOSHIBA TC90532XBG, Sharp QM1D1C0042
*/
[EM28178_BOARD_PLEX_PX_BCUD] = {
.name = "PLEX PX-BCUD",
.xclk = EM28XX_XCLK_FREQUENCY_4_3MHZ,
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = plex_px_bcud,
.has_dvb = 1,
},
/*
* 2040:0265 Hauppauge WinTV-dualHD (DVB version).
* Empia EM28274, 2x Silicon Labs Si2168, 2x Silicon Labs Si2157
*/
[EM28174_BOARD_HAUPPAUGE_WINTV_DUALHD_DVB] = {
.name = "Hauppauge WinTV-dualHD DVB",
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = hauppauge_dualhd_dvb,
.has_dvb = 1,
.ir_codes = RC_MAP_HAUPPAUGE,
.leds = hauppauge_dualhd_leds,
},
/*
* 2040:026d Hauppauge WinTV-dualHD (model 01595 - ATSC/QAM).
* Empia EM28274, 2x LG LGDT3306A, 2x Silicon Labs Si2157
*/
[EM28174_BOARD_HAUPPAUGE_WINTV_DUALHD_01595] = {
.name = "Hauppauge WinTV-dualHD 01595 ATSC/QAM",
.def_i2c_bus = 1,
.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_400_KHZ,
.tuner_type = TUNER_ABSENT,
.tuner_gpio = hauppauge_dualhd_dvb,
.has_dvb = 1,
.ir_codes = RC_MAP_HAUPPAUGE,
.leds = hauppauge_dualhd_leds,
},
};
EXPORT_SYMBOL_GPL(em28xx_boards);
static const unsigned int em28xx_bcount = ARRAY_SIZE(em28xx_boards);
/* table of devices that work with this driver */
struct usb_device_id em28xx_id_table[] = {
{ USB_DEVICE(0xeb1a, 0x2750),
.driver_info = EM2750_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2751),
.driver_info = EM2750_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2800),
.driver_info = EM2800_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2710),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2820),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2821),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2860),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2861),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2862),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2863),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2870),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2881),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2883),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2868),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2875),
.driver_info = EM2820_BOARD_UNKNOWN },
{ USB_DEVICE(0xeb1a, 0x2885), /* MSI Digivox Trio */
.driver_info = EM2884_BOARD_TERRATEC_H5 },
{ USB_DEVICE(0xeb1a, 0xe300),
.driver_info = EM2861_BOARD_KWORLD_PVRTV_300U },
{ USB_DEVICE(0xeb1a, 0xe303),
.driver_info = EM2860_BOARD_KAIOMY_TVNPC_U2 },
{ USB_DEVICE(0xeb1a, 0xe305),
.driver_info = EM2880_BOARD_KWORLD_DVB_305U },
{ USB_DEVICE(0xeb1a, 0xe310),
.driver_info = EM2880_BOARD_MSI_DIGIVOX_AD },
{ USB_DEVICE(0xeb1a, 0xa313),
.driver_info = EM2882_BOARD_KWORLD_ATSC_315U },
{ USB_DEVICE(0xeb1a, 0xa316),
.driver_info = EM2883_BOARD_KWORLD_HYBRID_330U },
{ USB_DEVICE(0xeb1a, 0xe320),
.driver_info = EM2880_BOARD_MSI_DIGIVOX_AD_II },
{ USB_DEVICE(0xeb1a, 0xe323),
.driver_info = EM2882_BOARD_KWORLD_VS_DVBT },
{ USB_DEVICE(0xeb1a, 0xe350),
.driver_info = EM2870_BOARD_KWORLD_350U },
{ USB_DEVICE(0xeb1a, 0xe355),
.driver_info = EM2870_BOARD_KWORLD_355U },
{ USB_DEVICE(0xeb1a, 0x2801),
.driver_info = EM2800_BOARD_GRABBEEX_USB2800 },
{ USB_DEVICE(0xeb1a, 0xe357),
.driver_info = EM2870_BOARD_KWORLD_355U },
{ USB_DEVICE(0xeb1a, 0xe359),
.driver_info = EM2870_BOARD_KWORLD_355U },
{ USB_DEVICE(0x1b80, 0xe302),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 }, /* Kaiser Baas Video to DVD maker */
{ USB_DEVICE(0x1b80, 0xe304),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 }, /* Kworld DVD Maker 2 */
{ USB_DEVICE(0x0ccd, 0x0036),
.driver_info = EM2820_BOARD_TERRATEC_CINERGY_250 },
{ USB_DEVICE(0x0ccd, 0x004c),
.driver_info = EM2880_BOARD_TERRATEC_HYBRID_XS_FR },
{ USB_DEVICE(0x0ccd, 0x004f),
.driver_info = EM2860_BOARD_TERRATEC_HYBRID_XS },
{ USB_DEVICE(0x0ccd, 0x005e),
.driver_info = EM2882_BOARD_TERRATEC_HYBRID_XS },
{ USB_DEVICE(0x0ccd, 0x0042),
.driver_info = EM2882_BOARD_TERRATEC_HYBRID_XS },
{ USB_DEVICE(0x0ccd, 0x0043),
.driver_info = EM2870_BOARD_TERRATEC_XS_MT2060 },
{ USB_DEVICE(0x0ccd, 0x008e), /* Cinergy HTC USB XS Rev. 1 */
.driver_info = EM2884_BOARD_TERRATEC_HTC_USB_XS },
{ USB_DEVICE(0x0ccd, 0x00ac), /* Cinergy HTC USB XS Rev. 2 */
.driver_info = EM2884_BOARD_TERRATEC_HTC_USB_XS },
{ USB_DEVICE(0x0ccd, 0x10a2), /* H5 Rev. 1 */
.driver_info = EM2884_BOARD_TERRATEC_H5 },
{ USB_DEVICE(0x0ccd, 0x10ad), /* H5 Rev. 2 */
.driver_info = EM2884_BOARD_TERRATEC_H5 },
{ USB_DEVICE(0x0ccd, 0x10b6), /* H5 Rev. 3 */
.driver_info = EM2884_BOARD_TERRATEC_H5 },
{ USB_DEVICE(0x0ccd, 0x0084),
.driver_info = EM2860_BOARD_TERRATEC_AV350 },
{ USB_DEVICE(0x0ccd, 0x0096),
.driver_info = EM2860_BOARD_TERRATEC_GRABBY },
{ USB_DEVICE(0x0ccd, 0x10AF),
.driver_info = EM2860_BOARD_TERRATEC_GRABBY },
{ USB_DEVICE(0x0ccd, 0x00b2),
.driver_info = EM2884_BOARD_CINERGY_HTC_STICK },
{ USB_DEVICE(0x0fd9, 0x0018),
.driver_info = EM2884_BOARD_ELGATO_EYETV_HYBRID_2008 },
{ USB_DEVICE(0x0fd9, 0x0033),
.driver_info = EM2860_BOARD_ELGATO_VIDEO_CAPTURE },
{ USB_DEVICE(0x185b, 0x2870),
.driver_info = EM2870_BOARD_COMPRO_VIDEOMATE },
{ USB_DEVICE(0x185b, 0x2041),
.driver_info = EM2820_BOARD_COMPRO_VIDEOMATE_FORYOU },
{ USB_DEVICE(0x2040, 0x4200),
.driver_info = EM2820_BOARD_HAUPPAUGE_WINTV_USB_2 },
{ USB_DEVICE(0x2040, 0x4201),
.driver_info = EM2820_BOARD_HAUPPAUGE_WINTV_USB_2 },
{ USB_DEVICE(0x2040, 0x6500),
.driver_info = EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900 },
{ USB_DEVICE(0x2040, 0x6502),
.driver_info = EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2 },
{ USB_DEVICE(0x2040, 0x6513), /* HCW HVR-980 */
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950 },
{ USB_DEVICE(0x2040, 0x6517), /* HP HVR-950 */
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950 },
{ USB_DEVICE(0x2040, 0x651b), /* RP HVR-950 */
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950 },
{ USB_DEVICE(0x2040, 0x651f),
.driver_info = EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850 },
{ USB_DEVICE(0x2040, 0x0265),
.driver_info = EM28174_BOARD_HAUPPAUGE_WINTV_DUALHD_DVB },
{ USB_DEVICE(0x2040, 0x026d),
.driver_info = EM28174_BOARD_HAUPPAUGE_WINTV_DUALHD_01595 },
{ USB_DEVICE(0x0438, 0xb002),
.driver_info = EM2880_BOARD_AMD_ATI_TV_WONDER_HD_600 },
{ USB_DEVICE(0x2001, 0xf112),
.driver_info = EM2820_BOARD_DLINK_USB_TV },
{ USB_DEVICE(0x2304, 0x0207),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 },
{ USB_DEVICE(0x2304, 0x0208),
.driver_info = EM2820_BOARD_PINNACLE_USB_2 },
{ USB_DEVICE(0x2304, 0x021a),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 },
{ USB_DEVICE(0x2304, 0x0226),
.driver_info = EM2882_BOARD_PINNACLE_HYBRID_PRO_330E },
{ USB_DEVICE(0x2304, 0x0227),
.driver_info = EM2880_BOARD_PINNACLE_PCTV_HD_PRO },
{ USB_DEVICE(0x2304, 0x023f),
.driver_info = EM2874_BOARD_PCTV_HD_MINI_80E },
{ USB_DEVICE(0x0413, 0x6023),
.driver_info = EM2800_BOARD_LEADTEK_WINFAST_USBII },
{ USB_DEVICE(0x093b, 0xa003),
.driver_info = EM2820_BOARD_PINNACLE_DVC_90 },
{ USB_DEVICE(0x093b, 0xa005),
.driver_info = EM2861_BOARD_PLEXTOR_PX_TV100U },
{ USB_DEVICE(0x04bb, 0x0515),
.driver_info = EM2820_BOARD_IODATA_GVMVP_SZ },
{ USB_DEVICE(0xeb1a, 0x50a6),
.driver_info = EM2860_BOARD_GADMEI_UTV330 },
{ USB_DEVICE(0x1b80, 0xa340),
.driver_info = EM2870_BOARD_KWORLD_A340 },
{ USB_DEVICE(0x1b80, 0xe346),
.driver_info = EM2874_BOARD_KWORLD_UB435Q_V2 },
{ USB_DEVICE(0x1b80, 0xe34c),
.driver_info = EM2874_BOARD_KWORLD_UB435Q_V3 },
{ USB_DEVICE(0x2013, 0x024f),
.driver_info = EM28174_BOARD_PCTV_290E },
{ USB_DEVICE(0x2013, 0x024c),
.driver_info = EM28174_BOARD_PCTV_460E },
{ USB_DEVICE(0x2040, 0x1605),
.driver_info = EM2884_BOARD_HAUPPAUGE_WINTV_HVR_930C },
{ USB_DEVICE(0x1b80, 0xe755),
.driver_info = EM2884_BOARD_C3TECH_DIGITAL_DUO },
{ USB_DEVICE(0xeb1a, 0x5006),
.driver_info = EM2860_BOARD_HT_VIDBOX_NW03 },
{ USB_DEVICE(0x1b80, 0xe309), /* Sveon STV40 */
.driver_info = EM2860_BOARD_EASYCAP },
{ USB_DEVICE(0x1b80, 0xe425),
.driver_info = EM2874_BOARD_MAXMEDIA_UB425_TC },
{ USB_DEVICE(0x2304, 0x0242),
.driver_info = EM2884_BOARD_PCTV_510E },
{ USB_DEVICE(0x2013, 0x0251),
.driver_info = EM2884_BOARD_PCTV_520E },
{ USB_DEVICE(0x1b80, 0xe1cc),
.driver_info = EM2874_BOARD_DELOCK_61959 },
{ USB_DEVICE(0x1ae7, 0x9003),
.driver_info = EM2765_BOARD_SPEEDLINK_VAD_LAPLACE },
{ USB_DEVICE(0x1ae7, 0x9004),
.driver_info = EM2765_BOARD_SPEEDLINK_VAD_LAPLACE },
{ USB_DEVICE(0x2013, 0x0258),
.driver_info = EM28178_BOARD_PCTV_461E },
{ USB_DEVICE(0x2013, 0x025f),
.driver_info = EM28178_BOARD_PCTV_292E },
{ USB_DEVICE(0x2040, 0x0264), /* Hauppauge WinTV-soloHD */
.driver_info = EM28178_BOARD_PCTV_292E },
{ USB_DEVICE(0x0413, 0x6f07),
.driver_info = EM2861_BOARD_LEADTEK_VC100 },
{ USB_DEVICE(0xeb1a, 0x8179),
.driver_info = EM28178_BOARD_TERRATEC_T2_STICK_HD },
{ USB_DEVICE(0x3275, 0x0085),
.driver_info = EM28178_BOARD_PLEX_PX_BCUD },
{ },
};
MODULE_DEVICE_TABLE(usb, em28xx_id_table);
/*
* EEPROM hash table for devices with generic USB IDs
*/
static struct em28xx_hash_table em28xx_eeprom_hash[] = {
/* P/N: SA 60002070465 Tuner: TVF7533-MF */
{0x6ce05a8f, EM2820_BOARD_PROLINK_PLAYTV_USB2, TUNER_YMEC_TVF_5533MF},
{0x72cc5a8b, EM2820_BOARD_PROLINK_PLAYTV_BOX4_USB2, TUNER_YMEC_TVF_5533MF},
{0x966a0441, EM2880_BOARD_KWORLD_DVB_310U, TUNER_XC2028},
{0x166a0441, EM2880_BOARD_EMPIRE_DUAL_TV, TUNER_XC2028},
{0xcee44a99, EM2882_BOARD_EVGA_INDTUBE, TUNER_XC2028},
{0xb8846b20, EM2881_BOARD_PINNACLE_HYBRID_PRO, TUNER_XC2028},
{0x63f653bd, EM2870_BOARD_REDDO_DVB_C_USB_BOX, TUNER_ABSENT},
{0x4e913442, EM2882_BOARD_DIKOM_DK300, TUNER_XC2028},
};
/* I2C devicelist hash table for devices with generic USB IDs */
static struct em28xx_hash_table em28xx_i2c_hash[] = {
{0xb06a32c3, EM2800_BOARD_TERRATEC_CINERGY_200, TUNER_LG_PAL_NEW_TAPC},
{0xf51200e3, EM2800_BOARD_VGEAR_POCKETTV, TUNER_LG_PAL_NEW_TAPC},
{0x1ba50080, EM2860_BOARD_SAA711X_REFERENCE_DESIGN, TUNER_ABSENT},
{0x77800080, EM2860_BOARD_TVP5150_REFERENCE_DESIGN, TUNER_ABSENT},
{0xc51200e3, EM2820_BOARD_GADMEI_TVR200, TUNER_LG_PAL_NEW_TAPC},
{0x4ba50080, EM2861_BOARD_GADMEI_UTV330PLUS, TUNER_TNF_5335MF},
{0x6b800080, EM2874_BOARD_LEADERSHIP_ISDBT, TUNER_ABSENT},
};
/* NOTE: introduce a separate hash table for devices with 16 bit eeproms */
int em28xx_tuner_callback(void *ptr, int component, int command, int arg)
{
struct em28xx_i2c_bus *i2c_bus = ptr;
struct em28xx *dev = i2c_bus->dev;
int rc = 0;
if (dev->tuner_type != TUNER_XC2028 && dev->tuner_type != TUNER_XC5000)
return 0;
if (command != XC2028_TUNER_RESET && command != XC5000_TUNER_RESET)
return 0;
rc = em28xx_gpio_set(dev, dev->board.tuner_gpio);
return rc;
}
EXPORT_SYMBOL_GPL(em28xx_tuner_callback);
static inline void em28xx_set_model(struct em28xx *dev)
{
dev->board = em28xx_boards[dev->model];
/* Those are the default values for the majority of boards
Use those values if not specified otherwise at boards entry
*/
if (!dev->board.xclk)
dev->board.xclk = EM28XX_XCLK_IR_RC5_MODE |
EM28XX_XCLK_FREQUENCY_12MHZ;
if (!dev->board.i2c_speed)
dev->board.i2c_speed = EM28XX_I2C_CLK_WAIT_ENABLE |
EM28XX_I2C_FREQ_100_KHZ;
/* Should be initialized early, for I2C to work */
dev->def_i2c_bus = dev->board.def_i2c_bus;
}
/* Wait until AC97_RESET reports the expected value reliably before proceeding.
* We also check that two unrelated registers accesses don't return the same
* value to avoid premature return.
* This procedure helps ensuring AC97 register accesses are reliable.
*/
static int em28xx_wait_until_ac97_features_equals(struct em28xx *dev,
int expected_feat)
{
unsigned long timeout = jiffies + msecs_to_jiffies(2000);
int feat, powerdown;
while (time_is_after_jiffies(timeout)) {
feat = em28xx_read_ac97(dev, AC97_RESET);
if (feat < 0)
return feat;
powerdown = em28xx_read_ac97(dev, AC97_POWERDOWN);
if (powerdown < 0)
return powerdown;
if (feat == expected_feat && feat != powerdown)
return 0;
msleep(50);
}
dev_warn(&dev->intf->dev, "AC97 registers access is not reliable !\n");
return -ETIMEDOUT;
}
/* Since em28xx_pre_card_setup() requires a proper dev->model,
* this won't work for boards with generic PCI IDs
*/
static void em28xx_pre_card_setup(struct em28xx *dev)
{
/* Set the initial XCLK and I2C clock values based on the board
definition */
em28xx_write_reg(dev, EM28XX_R0F_XCLK, dev->board.xclk & 0x7f);
if (!dev->board.is_em2800)
em28xx_write_reg(dev, EM28XX_R06_I2C_CLK, dev->board.i2c_speed);
msleep(50);
/* request some modules */
switch (dev->model) {
case EM2861_BOARD_PLEXTOR_PX_TV100U:
/* Sets the msp34xx I2S speed */
dev->i2s_speed = 2048000;
break;
case EM2861_BOARD_KWORLD_PVRTV_300U:
case EM2880_BOARD_KWORLD_DVB_305U:
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0x6d);
msleep(10);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0x7d);
msleep(10);
break;
case EM2870_BOARD_COMPRO_VIDEOMATE:
/* TODO: someone can do some cleanup here...
not everything's needed */
em28xx_write_reg(dev, EM2880_R04_GPO, 0x00);
msleep(10);
em28xx_write_reg(dev, EM2880_R04_GPO, 0x01);
msleep(10);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfd);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfc);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xdc);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfc);
mdelay(70);
break;
case EM2870_BOARD_TERRATEC_XS_MT2060:
/* this device needs some gpio writes to get the DVB-T
demod work */
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfe);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xde);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfe);
mdelay(70);
break;
case EM2870_BOARD_PINNACLE_PCTV_DVB:
/* this device needs some gpio writes to get the
DVB-T demod work */
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfe);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xde);
mdelay(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfe);
mdelay(70);
break;
case EM2820_BOARD_GADMEI_UTV310:
case EM2820_BOARD_MSI_VOX_USB_2:
/* enables audio for that devices */
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfd);
break;
case EM2882_BOARD_KWORLD_ATSC_315U:
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xff);
msleep(10);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfe);
msleep(10);
em28xx_write_reg(dev, EM2880_R04_GPO, 0x00);
msleep(10);
em28xx_write_reg(dev, EM2880_R04_GPO, 0x08);
msleep(10);
break;
case EM2860_BOARD_KAIOMY_TVNPC_U2:
em28xx_write_regs(dev, EM28XX_R0F_XCLK, "\x07", 1);
em28xx_write_regs(dev, EM28XX_R06_I2C_CLK, "\x40", 1);
em28xx_write_regs(dev, 0x0d, "\x42", 1);
em28xx_write_regs(dev, 0x08, "\xfd", 1);
msleep(10);
em28xx_write_regs(dev, 0x08, "\xff", 1);
msleep(10);
em28xx_write_regs(dev, 0x08, "\x7f", 1);
msleep(10);
em28xx_write_regs(dev, 0x08, "\x6b", 1);
break;
case EM2860_BOARD_EASYCAP:
em28xx_write_regs(dev, 0x08, "\xf8", 1);
break;
case EM2820_BOARD_IODATA_GVMVP_SZ:
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xff);
msleep(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xf7);
msleep(10);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfe);
msleep(70);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfd);
msleep(70);
break;
case EM2860_BOARD_TERRATEC_GRABBY:
/* HACK?: Ensure AC97 register reading is reliable before
* proceeding. In practice, this will wait about 1.6 seconds.
*/
em28xx_wait_until_ac97_features_equals(dev, 0x6a90);
break;
}
em28xx_gpio_set(dev, dev->board.tuner_gpio);
em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
/* Unlock device */
em28xx_set_mode(dev, EM28XX_SUSPEND);
}
static int em28xx_hint_board(struct em28xx *dev)
{
int i;
if (dev->board.is_webcam) {
if (dev->em28xx_sensor == EM28XX_MT9V011) {
dev->model = EM2820_BOARD_SILVERCREST_WEBCAM;
} else if (dev->em28xx_sensor == EM28XX_MT9M001 ||
dev->em28xx_sensor == EM28XX_MT9M111) {
dev->model = EM2750_BOARD_UNKNOWN;
}
/* FIXME: IMPROVE ! */
return 0;
}
/* HINT method: EEPROM
*
* This method works only for boards with eeprom.
* Uses a hash of all eeprom bytes. The hash should be
* unique for a vendor/tuner pair.
* There are a high chance that tuners for different
* video standards produce different hashes.
*/
for (i = 0; i < ARRAY_SIZE(em28xx_eeprom_hash); i++) {
if (dev->hash == em28xx_eeprom_hash[i].hash) {
dev->model = em28xx_eeprom_hash[i].model;
dev->tuner_type = em28xx_eeprom_hash[i].tuner;
dev_err(&dev->intf->dev,
"Your board has no unique USB ID.\n"
"A hint were successfully done, based on eeprom hash.\n"
"This method is not 100%% failproof.\n"
"If the board were missdetected, please email this log to:\n"
"\tV4L Mailing List <[email protected]>\n"
"Board detected as %s\n",
em28xx_boards[dev->model].name);
return 0;
}
}
/* HINT method: I2C attached devices
*
* This method works for all boards.
* Uses a hash of i2c scanned devices.
* Devices with the same i2c attached chips will
* be considered equal.
* This method is less precise than the eeprom one.
*/
/* user did not request i2c scanning => do it now */
if (!dev->i2c_hash)
em28xx_do_i2c_scan(dev, dev->def_i2c_bus);
for (i = 0; i < ARRAY_SIZE(em28xx_i2c_hash); i++) {
if (dev->i2c_hash == em28xx_i2c_hash[i].hash) {
dev->model = em28xx_i2c_hash[i].model;
dev->tuner_type = em28xx_i2c_hash[i].tuner;
dev_err(&dev->intf->dev,
"Your board has no unique USB ID.\n"
"A hint were successfully done, based on i2c devicelist hash.\n"
"This method is not 100%% failproof.\n"
"If the board were missdetected, please email this log to:\n"
"\tV4L Mailing List <[email protected]>\n"
"Board detected as %s\n",
em28xx_boards[dev->model].name);
return 0;
}
}
dev_err(&dev->intf->dev,
"Your board has no unique USB ID and thus need a hint to be detected.\n"
"You may try to use card=<n> insmod option to workaround that.\n"
"Please send an email with this log to:\n"
"\tV4L Mailing List <[email protected]>\n"
"Board eeprom hash is 0x%08lx\n"
"Board i2c devicelist hash is 0x%08lx\n",
dev->hash, dev->i2c_hash);
dev_err(&dev->intf->dev,
"Here is a list of valid choices for the card=<n> insmod option:\n");
for (i = 0; i < em28xx_bcount; i++) {
dev_err(&dev->intf->dev,
" card=%d -> %s\n", i, em28xx_boards[i].name);
}
return -1;
}
static void em28xx_card_setup(struct em28xx *dev)
{
/*
* If the device can be a webcam, seek for a sensor.
* If sensor is not found, then it isn't a webcam.
*/
if (dev->board.is_webcam) {
if (em28xx_detect_sensor(dev) < 0)
dev->board.is_webcam = 0;
}
switch (dev->model) {
case EM2750_BOARD_UNKNOWN:
case EM2820_BOARD_UNKNOWN:
case EM2800_BOARD_UNKNOWN:
/*
* The K-WORLD DVB-T 310U is detected as an MSI Digivox AD.
*
* This occurs because they share identical USB vendor and
* product IDs.
*
* What we do here is look up the EEPROM hash of the K-WORLD
* and if it is found then we decide that we do not have
* a DIGIVOX and reset the device to the K-WORLD instead.
*
* This solution is only valid if they do not share eeprom
* hash identities which has not been determined as yet.
*/
if (em28xx_hint_board(dev) < 0)
dev_err(&dev->intf->dev, "Board not discovered\n");
else {
em28xx_set_model(dev);
em28xx_pre_card_setup(dev);
}
break;
default:
em28xx_set_model(dev);
}
dev_info(&dev->intf->dev, "Identified as %s (card=%d)\n",
dev->board.name, dev->model);
dev->tuner_type = em28xx_boards[dev->model].tuner_type;
/* request some modules */
switch (dev->model) {
case EM2820_BOARD_HAUPPAUGE_WINTV_USB_2:
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900:
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2:
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850:
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950:
case EM2884_BOARD_HAUPPAUGE_WINTV_HVR_930C:
case EM28174_BOARD_HAUPPAUGE_WINTV_DUALHD_DVB:
case EM28174_BOARD_HAUPPAUGE_WINTV_DUALHD_01595:
{
struct tveeprom tv;
if (dev->eedata == NULL)
break;
#if defined(CONFIG_MODULES) && defined(MODULE)
request_module("tveeprom");
#endif
/* Call first TVeeprom */
dev->i2c_client[dev->def_i2c_bus].addr = 0xa0 >> 1;
tveeprom_hauppauge_analog(&dev->i2c_client[dev->def_i2c_bus], &tv, dev->eedata);
dev->tuner_type = tv.tuner_type;
if (tv.audio_processor == TVEEPROM_AUDPROC_MSP) {
dev->i2s_speed = 2048000;
dev->board.has_msp34xx = 1;
}
break;
}
case EM2882_BOARD_KWORLD_ATSC_315U:
em28xx_write_reg(dev, 0x0d, 0x42);
msleep(10);
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xfd);
msleep(10);
break;
case EM2820_BOARD_KWORLD_PVRTV2800RF:
/* GPIO enables sound on KWORLD PVR TV 2800RF */
em28xx_write_reg(dev, EM2820_R08_GPIO_CTRL, 0xf9);
break;
case EM2820_BOARD_UNKNOWN:
case EM2800_BOARD_UNKNOWN:
/*
* The K-WORLD DVB-T 310U is detected as an MSI Digivox AD.
*
* This occurs because they share identical USB vendor and
* product IDs.
*
* What we do here is look up the EEPROM hash of the K-WORLD
* and if it is found then we decide that we do not have
* a DIGIVOX and reset the device to the K-WORLD instead.
*
* This solution is only valid if they do not share eeprom
* hash identities which has not been determined as yet.
*/
case EM2880_BOARD_MSI_DIGIVOX_AD:
if (!em28xx_hint_board(dev))
em28xx_set_model(dev);
/* In cases where we had to use a board hint, the call to
em28xx_set_mode() in em28xx_pre_card_setup() was a no-op,
so make the call now so the analog GPIOs are set properly
before probing the i2c bus. */
em28xx_gpio_set(dev, dev->board.tuner_gpio);
em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
break;
/*
* The Dikom DK300 is detected as an Kworld VS-DVB-T 323UR.
*
* This occurs because they share identical USB vendor and
* product IDs.
*
* What we do here is look up the EEPROM hash of the Dikom
* and if it is found then we decide that we do not have
* a Kworld and reset the device to the Dikom instead.
*
* This solution is only valid if they do not share eeprom
* hash identities which has not been determined as yet.
*/
case EM2882_BOARD_KWORLD_VS_DVBT:
if (!em28xx_hint_board(dev))
em28xx_set_model(dev);
/* In cases where we had to use a board hint, the call to
em28xx_set_mode() in em28xx_pre_card_setup() was a no-op,
so make the call now so the analog GPIOs are set properly
before probing the i2c bus. */
em28xx_gpio_set(dev, dev->board.tuner_gpio);
em28xx_set_mode(dev, EM28XX_ANALOG_MODE);
break;
}
if (dev->board.valid == EM28XX_BOARD_NOT_VALIDATED) {
dev_err(&dev->intf->dev,
"\n\n"
"The support for this board weren't valid yet.\n"
"Please send a report of having this working\n"
"not to V4L mailing list (and/or to other addresses)\n\n");
}
/* Free eeprom data memory */
kfree(dev->eedata);
dev->eedata = NULL;
/* Allow override tuner type by a module parameter */
if (tuner >= 0)
dev->tuner_type = tuner;
}
void em28xx_setup_xc3028(struct em28xx *dev, struct xc2028_ctrl *ctl)
{
memset(ctl, 0, sizeof(*ctl));
ctl->fname = XC2028_DEFAULT_FIRMWARE;
ctl->max_len = 64;
ctl->mts = em28xx_boards[dev->model].mts_firmware;
switch (dev->model) {
case EM2880_BOARD_EMPIRE_DUAL_TV:
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900:
case EM2882_BOARD_TERRATEC_HYBRID_XS:
ctl->demod = XC3028_FE_ZARLINK456;
break;
case EM2880_BOARD_TERRATEC_HYBRID_XS:
case EM2880_BOARD_TERRATEC_HYBRID_XS_FR:
case EM2881_BOARD_PINNACLE_HYBRID_PRO:
ctl->demod = XC3028_FE_ZARLINK456;
break;
case EM2880_BOARD_HAUPPAUGE_WINTV_HVR_900_R2:
case EM2882_BOARD_PINNACLE_HYBRID_PRO_330E:
ctl->demod = XC3028_FE_DEFAULT;
break;
case EM2880_BOARD_AMD_ATI_TV_WONDER_HD_600:
ctl->demod = XC3028_FE_DEFAULT;
ctl->fname = XC3028L_DEFAULT_FIRMWARE;
break;
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_850:
case EM2883_BOARD_HAUPPAUGE_WINTV_HVR_950:
case EM2880_BOARD_PINNACLE_PCTV_HD_PRO:
/* FIXME: Better to specify the needed IF */
ctl->demod = XC3028_FE_DEFAULT;
break;
case EM2883_BOARD_KWORLD_HYBRID_330U:
case EM2882_BOARD_DIKOM_DK300:
case EM2882_BOARD_KWORLD_VS_DVBT:
ctl->demod = XC3028_FE_CHINA;
ctl->fname = XC2028_DEFAULT_FIRMWARE;
break;
case EM2882_BOARD_EVGA_INDTUBE:
ctl->demod = XC3028_FE_CHINA;
ctl->fname = XC3028L_DEFAULT_FIRMWARE;
break;
default:
ctl->demod = XC3028_FE_OREN538;
}
}
EXPORT_SYMBOL_GPL(em28xx_setup_xc3028);
static void request_module_async(struct work_struct *work)
{
struct em28xx *dev = container_of(work,
struct em28xx, request_module_wk);
/*
* The em28xx extensions can be modules or builtin. If the
* modules are already loaded or are built in, those extensions
* can be initialised right now. Otherwise, the module init
* code will do it.
*/
/*
* Devicdes with an audio-only interface also have a V4L/DVB/RC
* interface. Don't register extensions twice on those devices.
*/
if (dev->is_audio_only) {
#if defined(CONFIG_MODULES) && defined(MODULE)
request_module("em28xx-alsa");
#endif
return;
}
em28xx_init_extension(dev);
#if defined(CONFIG_MODULES) && defined(MODULE)
if (dev->has_video)
request_module("em28xx-v4l");
if (dev->usb_audio_type == EM28XX_USB_AUDIO_CLASS)
request_module("snd-usb-audio");
else if (dev->usb_audio_type == EM28XX_USB_AUDIO_VENDOR)
request_module("em28xx-alsa");
if (dev->board.has_dvb)
request_module("em28xx-dvb");
if (dev->board.buttons ||
((dev->board.ir_codes || dev->board.has_ir_i2c) && !disable_ir))
request_module("em28xx-rc");
#endif /* CONFIG_MODULES */
}
static void request_modules(struct em28xx *dev)
{
INIT_WORK(&dev->request_module_wk, request_module_async);
schedule_work(&dev->request_module_wk);
}
static void flush_request_modules(struct em28xx *dev)
{
flush_work(&dev->request_module_wk);
}
static int em28xx_media_device_init(struct em28xx *dev,
struct usb_device *udev)
{
#ifdef CONFIG_MEDIA_CONTROLLER
struct media_device *mdev;
mdev = kzalloc(sizeof(*mdev), GFP_KERNEL);
if (!mdev)
return -ENOMEM;
if (udev->product)
media_device_usb_init(mdev, udev, udev->product);
else if (udev->manufacturer)
media_device_usb_init(mdev, udev, udev->manufacturer);
else
media_device_usb_init(mdev, udev, dev_name(&dev->intf->dev));
dev->media_dev = mdev;
#endif
return 0;
}
static void em28xx_unregister_media_device(struct em28xx *dev)
{
#ifdef CONFIG_MEDIA_CONTROLLER
if (dev->media_dev) {
media_device_unregister(dev->media_dev);
media_device_cleanup(dev->media_dev);
kfree(dev->media_dev);
dev->media_dev = NULL;
}
#endif
}
/*
* em28xx_release_resources()
* unregisters the v4l2,i2c and usb devices
* called when the device gets disconnected or at module unload
*/
static void em28xx_release_resources(struct em28xx *dev)
{
struct usb_device *udev = interface_to_usbdev(dev->intf);
/*FIXME: I2C IR should be disconnected */
mutex_lock(&dev->lock);
em28xx_unregister_media_device(dev);
if (dev->def_i2c_bus)
em28xx_i2c_unregister(dev, 1);
em28xx_i2c_unregister(dev, 0);
usb_put_dev(udev);
/* Mark device as unused */
clear_bit(dev->devno, em28xx_devused);
mutex_unlock(&dev->lock);
};
/**
* em28xx_free_device() - Free em28xx device
*
* @ref: struct kref for em28xx device
*
* This is called when all extensions and em28xx core unregisters a device
*/
void em28xx_free_device(struct kref *ref)
{
struct em28xx *dev = kref_to_dev(ref);
dev_info(&dev->intf->dev, "Freeing device\n");
if (!dev->disconnected)
em28xx_release_resources(dev);
kfree(dev->alt_max_pkt_size_isoc);
kfree(dev);
}
EXPORT_SYMBOL_GPL(em28xx_free_device);
/*
* em28xx_init_dev()
* allocates and inits the device structs, registers i2c bus and v4l device
*/
static int em28xx_init_dev(struct em28xx *dev, struct usb_device *udev,
struct usb_interface *interface,
int minor)
{
int retval;
const char *chip_name = NULL;
dev->intf = interface;
mutex_init(&dev->ctrl_urb_lock);
spin_lock_init(&dev->slock);
dev->em28xx_write_regs = em28xx_write_regs;
dev->em28xx_read_reg = em28xx_read_reg;
dev->em28xx_read_reg_req_len = em28xx_read_reg_req_len;
dev->em28xx_write_regs_req = em28xx_write_regs_req;
dev->em28xx_read_reg_req = em28xx_read_reg_req;
dev->board.is_em2800 = em28xx_boards[dev->model].is_em2800;
em28xx_set_model(dev);
dev->wait_after_write = 5;
/* Based on the Chip ID, set the device configuration */
retval = em28xx_read_reg(dev, EM28XX_R0A_CHIPID);
if (retval > 0) {
dev->chip_id = retval;
switch (dev->chip_id) {
case CHIP_ID_EM2800:
chip_name = "em2800";
break;
case CHIP_ID_EM2710:
chip_name = "em2710";
break;
case CHIP_ID_EM2750:
chip_name = "em2750";
break;
case CHIP_ID_EM2765:
chip_name = "em2765";
dev->wait_after_write = 0;
dev->is_em25xx = 1;
dev->eeprom_addrwidth_16bit = 1;
break;
case CHIP_ID_EM2820:
chip_name = "em2710/2820";
if (le16_to_cpu(udev->descriptor.idVendor) == 0xeb1a) {
__le16 idProd = udev->descriptor.idProduct;
if (le16_to_cpu(idProd) == 0x2710)
chip_name = "em2710";
else if (le16_to_cpu(idProd) == 0x2820)
chip_name = "em2820";
}
/* NOTE: the em2820 is used in webcams, too ! */
break;
case CHIP_ID_EM2840:
chip_name = "em2840";
break;
case CHIP_ID_EM2860:
chip_name = "em2860";
break;
case CHIP_ID_EM2870:
chip_name = "em2870";
dev->wait_after_write = 0;
break;
case CHIP_ID_EM2874:
chip_name = "em2874";
dev->wait_after_write = 0;
dev->eeprom_addrwidth_16bit = 1;
break;
case CHIP_ID_EM28174:
chip_name = "em28174";
dev->wait_after_write = 0;
dev->eeprom_addrwidth_16bit = 1;
break;
case CHIP_ID_EM28178:
chip_name = "em28178";
dev->wait_after_write = 0;
dev->eeprom_addrwidth_16bit = 1;
break;
case CHIP_ID_EM2883:
chip_name = "em2882/3";
dev->wait_after_write = 0;
break;
case CHIP_ID_EM2884:
chip_name = "em2884";
dev->wait_after_write = 0;
dev->eeprom_addrwidth_16bit = 1;
break;
}
}
if (!chip_name)
dev_info(&dev->intf->dev,
"unknown em28xx chip ID (%d)\n", dev->chip_id);
else
dev_info(&dev->intf->dev, "chip ID is %s\n", chip_name);
em28xx_media_device_init(dev, udev);
if (dev->is_audio_only) {
retval = em28xx_audio_setup(dev);
if (retval)
return -ENODEV;
em28xx_init_extension(dev);
return 0;
}
em28xx_pre_card_setup(dev);
if (!dev->board.is_em2800) {
/* Resets I2C speed */
retval = em28xx_write_reg(dev, EM28XX_R06_I2C_CLK, dev->board.i2c_speed);
if (retval < 0) {
dev_err(&dev->intf->dev,
"%s: em28xx_write_reg failed! retval [%d]\n",
__func__, retval);
return retval;
}
}
rt_mutex_init(&dev->i2c_bus_lock);
/* register i2c bus 0 */
if (dev->board.is_em2800)
retval = em28xx_i2c_register(dev, 0, EM28XX_I2C_ALGO_EM2800);
else
retval = em28xx_i2c_register(dev, 0, EM28XX_I2C_ALGO_EM28XX);
if (retval < 0) {
dev_err(&dev->intf->dev,
"%s: em28xx_i2c_register bus 0 - error [%d]!\n",
__func__, retval);
return retval;
}
/* register i2c bus 1 */
if (dev->def_i2c_bus) {
if (dev->is_em25xx)
retval = em28xx_i2c_register(dev, 1,
EM28XX_I2C_ALGO_EM25XX_BUS_B);
else
retval = em28xx_i2c_register(dev, 1,
EM28XX_I2C_ALGO_EM28XX);
if (retval < 0) {
dev_err(&dev->intf->dev,
"%s: em28xx_i2c_register bus 1 - error [%d]!\n",
__func__, retval);
em28xx_i2c_unregister(dev, 0);
return retval;
}
}
/* Do board specific init and eeprom reading */
em28xx_card_setup(dev);
return 0;
}
/* high bandwidth multiplier, as encoded in highspeed endpoint descriptors */
#define hb_mult(wMaxPacketSize) (1 + (((wMaxPacketSize) >> 11) & 0x03))
/*
* em28xx_usb_probe()
* checks for supported devices
*/
static int em28xx_usb_probe(struct usb_interface *interface,
const struct usb_device_id *id)
{
struct usb_device *udev;
struct em28xx *dev = NULL;
int retval;
bool has_vendor_audio = false, has_video = false, has_dvb = false;
int i, nr, try_bulk;
const int ifnum = interface->altsetting[0].desc.bInterfaceNumber;
char *speed;
udev = usb_get_dev(interface_to_usbdev(interface));
/* Check to see next free device and mark as used */
do {
nr = find_first_zero_bit(em28xx_devused, EM28XX_MAXBOARDS);
if (nr >= EM28XX_MAXBOARDS) {
/* No free device slots */
dev_err(&interface->dev,
"Driver supports up to %i em28xx boards.\n",
EM28XX_MAXBOARDS);
retval = -ENOMEM;
goto err_no_slot;
}
} while (test_and_set_bit(nr, em28xx_devused));
/* Don't register audio interfaces */
if (interface->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
dev_err(&interface->dev,
"audio device (%04x:%04x): interface %i, class %i\n",
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
interface->altsetting[0].desc.bInterfaceClass);
retval = -ENODEV;
goto err;
}
/* allocate memory for our device state and initialize it */
dev = kzalloc(sizeof(*dev), GFP_KERNEL);
if (dev == NULL) {
retval = -ENOMEM;
goto err;
}
/* compute alternate max packet sizes */
dev->alt_max_pkt_size_isoc =
kmalloc(sizeof(dev->alt_max_pkt_size_isoc[0]) *
interface->num_altsetting, GFP_KERNEL);
if (dev->alt_max_pkt_size_isoc == NULL) {
kfree(dev);
retval = -ENOMEM;
goto err;
}
/* Get endpoints */
for (i = 0; i < interface->num_altsetting; i++) {
int ep;
for (ep = 0; ep < interface->altsetting[i].desc.bNumEndpoints; ep++) {
const struct usb_endpoint_descriptor *e;
int sizedescr, size;
e = &interface->altsetting[i].endpoint[ep].desc;
sizedescr = le16_to_cpu(e->wMaxPacketSize);
size = sizedescr & 0x7ff;
if (udev->speed == USB_SPEED_HIGH)
size = size * hb_mult(sizedescr);
if (usb_endpoint_dir_in(e)) {
switch (e->bEndpointAddress) {
case 0x82:
has_video = true;
if (usb_endpoint_xfer_isoc(e)) {
dev->analog_ep_isoc =
e->bEndpointAddress;
dev->alt_max_pkt_size_isoc[i] = size;
} else if (usb_endpoint_xfer_bulk(e)) {
dev->analog_ep_bulk =
e->bEndpointAddress;
}
break;
case 0x83:
if (usb_endpoint_xfer_isoc(e)) {
has_vendor_audio = true;
} else {
dev_err(&interface->dev,
"error: skipping audio endpoint 0x83, because it uses bulk transfers !\n");
}
break;
case 0x84:
if (has_video &&
(usb_endpoint_xfer_bulk(e))) {
dev->analog_ep_bulk =
e->bEndpointAddress;
} else {
if (usb_endpoint_xfer_isoc(e)) {
if (size > dev->dvb_max_pkt_size_isoc) {
has_dvb = true; /* see NOTE (~) */
dev->dvb_ep_isoc = e->bEndpointAddress;
dev->dvb_max_pkt_size_isoc = size;
dev->dvb_alt_isoc = i;
}
} else {
has_dvb = true;
dev->dvb_ep_bulk = e->bEndpointAddress;
}
}
break;
}
}
/* NOTE:
* Old logic with support for isoc transfers only was:
* 0x82 isoc => analog
* 0x83 isoc => audio
* 0x84 isoc => digital
*
* New logic with support for bulk transfers
* 0x82 isoc => analog
* 0x82 bulk => analog
* 0x83 isoc* => audio
* 0x84 isoc => digital
* 0x84 bulk => analog or digital**
* (*: audio should always be isoc)
* (**: analog, if ep 0x82 is isoc, otherwise digital)
*
* The new logic preserves backwards compatibility and
* reflects the endpoint configurations we have seen
* so far. But there might be devices for which this
* logic is not sufficient...
*/
/*
* NOTE (~): some manufacturers (e.g. Terratec) disable
* endpoints by setting wMaxPacketSize to 0 bytes for
* all alt settings. So far, we've seen this for
* DVB isoc endpoints only.
*/
}
}
if (!(has_vendor_audio || has_video || has_dvb)) {
retval = -ENODEV;
goto err_free;
}
switch (udev->speed) {
case USB_SPEED_LOW:
speed = "1.5";
break;
case USB_SPEED_UNKNOWN:
case USB_SPEED_FULL:
speed = "12";
break;
case USB_SPEED_HIGH:
speed = "480";
break;
default:
speed = "unknown";
}
dev_err(&interface->dev,
"New device %s %s @ %s Mbps (%04x:%04x, interface %d, class %d)\n",
udev->manufacturer ? udev->manufacturer : "",
udev->product ? udev->product : "",
speed,
le16_to_cpu(udev->descriptor.idVendor),
le16_to_cpu(udev->descriptor.idProduct),
ifnum,
interface->altsetting->desc.bInterfaceNumber);
/*
* Make sure we have 480 Mbps of bandwidth, otherwise things like
* video stream wouldn't likely work, since 12 Mbps is generally
* not enough even for most Digital TV streams.
*/
if (udev->speed != USB_SPEED_HIGH && disable_usb_speed_check == 0) {
dev_err(&interface->dev, "Device initialization failed.\n");
dev_err(&interface->dev,
"Device must be connected to a high-speed USB 2.0 port.\n");
retval = -ENODEV;
goto err_free;
}
dev->devno = nr;
dev->model = id->driver_info;
dev->alt = -1;
dev->is_audio_only = has_vendor_audio && !(has_video || has_dvb);
dev->has_video = has_video;
dev->ifnum = ifnum;
if (has_vendor_audio) {
dev_err(&interface->dev,
"Audio interface %i found (Vendor Class)\n", ifnum);
dev->usb_audio_type = EM28XX_USB_AUDIO_VENDOR;
}
/* Checks if audio is provided by a USB Audio Class interface */
for (i = 0; i < udev->config->desc.bNumInterfaces; i++) {
struct usb_interface *uif = udev->config->interface[i];
if (uif->altsetting[0].desc.bInterfaceClass == USB_CLASS_AUDIO) {
if (has_vendor_audio)
dev_err(&interface->dev,
"em28xx: device seems to have vendor AND usb audio class interfaces !\n"
"\t\tThe vendor interface will be ignored. Please contact the developers <[email protected]>\n");
dev->usb_audio_type = EM28XX_USB_AUDIO_CLASS;
break;
}
}
if (has_video)
dev_err(&interface->dev, "Video interface %i found:%s%s\n",
ifnum,
dev->analog_ep_bulk ? " bulk" : "",
dev->analog_ep_isoc ? " isoc" : "");
if (has_dvb)
dev_err(&interface->dev, "DVB interface %i found:%s%s\n",
ifnum,
dev->dvb_ep_bulk ? " bulk" : "",
dev->dvb_ep_isoc ? " isoc" : "");
dev->num_alt = interface->num_altsetting;
if ((unsigned)card[nr] < em28xx_bcount)
dev->model = card[nr];
/* save our data pointer in this interface device */
usb_set_intfdata(interface, dev);
/* allocate device struct and check if the device is a webcam */
mutex_init(&dev->lock);
retval = em28xx_init_dev(dev, udev, interface, nr);
if (retval) {
goto err_free;
}
if (usb_xfer_mode < 0) {
if (dev->board.is_webcam)
try_bulk = 1;
else
try_bulk = 0;
} else {
try_bulk = usb_xfer_mode > 0;
}
/* Disable V4L2 if the device doesn't have a decoder */
if (has_video &&
dev->board.decoder == EM28XX_NODECODER && !dev->board.is_webcam) {
dev_err(&interface->dev,
"Currently, V4L2 is not supported on this model\n");
has_video = false;
dev->has_video = false;
}
/* Select USB transfer types to use */
if (has_video) {
if (!dev->analog_ep_isoc || (try_bulk && dev->analog_ep_bulk))
dev->analog_xfer_bulk = 1;
dev_err(&interface->dev, "analog set to %s mode.\n",
dev->analog_xfer_bulk ? "bulk" : "isoc");
}
if (has_dvb) {
if (!dev->dvb_ep_isoc || (try_bulk && dev->dvb_ep_bulk))
dev->dvb_xfer_bulk = 1;
dev_err(&interface->dev, "dvb set to %s mode.\n",
dev->dvb_xfer_bulk ? "bulk" : "isoc");
}
kref_init(&dev->ref);
request_modules(dev);
/*
* Do it at the end, to reduce dynamic configuration changes during
* the device init. Yet, as request_modules() can be async, the
* topology will likely change after the load of the em28xx subdrivers.
*/
#ifdef CONFIG_MEDIA_CONTROLLER
retval = media_device_register(dev->media_dev);
#endif
return 0;
err_free:
kfree(dev->alt_max_pkt_size_isoc);
kfree(dev);
err:
clear_bit(nr, em28xx_devused);
err_no_slot:
usb_put_dev(udev);
return retval;
}
/*
* em28xx_usb_disconnect()
* called when the device gets disconnected
* video device will be unregistered on v4l2_close in case it is still open
*/
static void em28xx_usb_disconnect(struct usb_interface *interface)
{
struct em28xx *dev;
dev = usb_get_intfdata(interface);
usb_set_intfdata(interface, NULL);
if (!dev)
return;
dev->disconnected = 1;
dev_err(&dev->intf->dev, "Disconnecting\n");
flush_request_modules(dev);
em28xx_close_extension(dev);
em28xx_release_resources(dev);
kref_put(&dev->ref, em28xx_free_device);
}
static int em28xx_usb_suspend(struct usb_interface *interface,
pm_message_t message)
{
struct em28xx *dev;
dev = usb_get_intfdata(interface);
if (!dev)
return 0;
em28xx_suspend_extension(dev);
return 0;
}
static int em28xx_usb_resume(struct usb_interface *interface)
{
struct em28xx *dev;
dev = usb_get_intfdata(interface);
if (!dev)
return 0;
em28xx_resume_extension(dev);
return 0;
}
static struct usb_driver em28xx_usb_driver = {
.name = "em28xx",
.probe = em28xx_usb_probe,
.disconnect = em28xx_usb_disconnect,
.suspend = em28xx_usb_suspend,
.resume = em28xx_usb_resume,
.reset_resume = em28xx_usb_resume,
.id_table = em28xx_id_table,
};
module_usb_driver(em28xx_usb_driver);
| null | null | null | null | 108,150 |
19,412 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 19,412 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// 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.
#include "components/variations/variations_seed_store.h"
#include <memory>
#include <utility>
#include "base/base64.h"
#include "base/macros.h"
#include "base/test/histogram_tester.h"
#include "base/time/time.h"
#include "base/version.h"
#include "build/build_config.h"
#include "components/prefs/testing_pref_service.h"
#include "components/variations/client_filterable_state.h"
#include "components/variations/pref_names.h"
#include "components/variations/proto/study.pb.h"
#include "components/variations/proto/variations_seed.pb.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/zlib/google/compression_utils.h"
#if defined(OS_ANDROID)
#include "components/variations/android/variations_seed_bridge.h"
#endif // OS_ANDROID
namespace variations {
namespace {
// The below seed and signature pair were generated using the server's private
// key.
const char kUncompressedBase64SeedData[] =
"CigxZDI5NDY0ZmIzZDc4ZmYxNTU2ZTViNTUxYzY0NDdjYmM3NGU1ZmQwEr0BCh9VTUEtVW5p"
"Zm9ybWl0eS1UcmlhbC0xMC1QZXJjZW50GICckqUFOAFCB2RlZmF1bHRKCwoHZGVmYXVsdBAB"
"SgwKCGdyb3VwXzAxEAFKDAoIZ3JvdXBfMDIQAUoMCghncm91cF8wMxABSgwKCGdyb3VwXzA0"
"EAFKDAoIZ3JvdXBfMDUQAUoMCghncm91cF8wNhABSgwKCGdyb3VwXzA3EAFKDAoIZ3JvdXBf"
"MDgQAUoMCghncm91cF8wORAB";
const char kBase64SeedSignature[] =
"MEQCIDD1IVxjzWYncun+9IGzqYjZvqxxujQEayJULTlbTGA/AiAr0oVmEgVUQZBYq5VLOSvy"
"96JkMYgzTkHPwbv7K/CmgA==";
// The sentinel value that may be stored as the latest variations seed value in
// prefs to indicate that the latest seed is identical to the safe seed.
// Note: This constant is intentionally duplicated in the test because it is
// persisted to disk. In order to maintain backward-compatibility, it's
// important that code continue to correctly handle this specific constant, even
// if the constant used internally in the implementation changes.
constexpr char kIdenticalToSafeSeedSentinel[] = "safe_seed_content";
class TestVariationsSeedStore : public VariationsSeedStore {
public:
explicit TestVariationsSeedStore(PrefService* local_state)
: VariationsSeedStore(local_state) {}
~TestVariationsSeedStore() override {}
bool StoreSeedForTesting(const std::string& seed_data) {
return StoreSeedData(seed_data, std::string(), std::string(),
base::Time::Now(), false, false, false, nullptr);
}
bool SignatureVerificationEnabled() override { return false; }
private:
DISALLOW_COPY_AND_ASSIGN(TestVariationsSeedStore);
};
// Signature verification is disabled on Android and iOS for performance
// reasons. This class re-enables it for tests, which don't mind the (small)
// performance penalty.
class SignatureVerifyingVariationsSeedStore : public VariationsSeedStore {
public:
explicit SignatureVerifyingVariationsSeedStore(PrefService* local_state)
: VariationsSeedStore(local_state) {}
~SignatureVerifyingVariationsSeedStore() override {}
bool SignatureVerificationEnabled() override { return true; }
private:
DISALLOW_COPY_AND_ASSIGN(SignatureVerifyingVariationsSeedStore);
};
// Creates a base::Time object from the corresponding raw value. The specific
// implementation is not important; it's only important that distinct inputs map
// to distinct outputs.
base::Time WrapTime(int64_t time) {
return base::Time::FromDeltaSinceWindowsEpoch(
base::TimeDelta::FromMicroseconds(time));
}
// Populates |seed| with simple test data. The resulting seed will contain one
// study called "test", which contains one experiment called "abc" with
// probability weight 100. |seed|'s study field will be cleared before adding
// the new study.
VariationsSeed CreateTestSeed() {
VariationsSeed seed;
Study* study = seed.add_study();
study->set_name("test");
study->set_default_experiment_name("abc");
Study_Experiment* experiment = study->add_experiment();
experiment->set_name("abc");
experiment->set_probability_weight(100);
seed.set_serial_number("123");
return seed;
}
// Returns a ClientFilterableState with all fields set to "interesting" values
// for testing.
std::unique_ptr<ClientFilterableState> CreateTestClientFilterableState() {
std::unique_ptr<ClientFilterableState> client_state =
std::make_unique<ClientFilterableState>();
client_state->locale = "es-MX";
client_state->reference_date = WrapTime(1234554321);
client_state->version = base::Version("1.2.3.4");
client_state->channel = Study::CANARY;
client_state->form_factor = Study::PHONE;
client_state->platform = Study::PLATFORM_MAC;
client_state->hardware_class = "mario";
client_state->is_low_end_device = true;
client_state->session_consistency_country = "mx";
client_state->permanent_consistency_country = "br";
return client_state;
}
// Serializes |seed| to protobuf binary format.
std::string SerializeSeed(const VariationsSeed& seed) {
std::string serialized_seed;
seed.SerializeToString(&serialized_seed);
return serialized_seed;
}
// Compresses |data| using Gzip compression and returns the result.
std::string Compress(const std::string& data) {
std::string compressed;
const bool result = compression::GzipCompress(data, &compressed);
EXPECT_TRUE(result);
return compressed;
}
// Serializes |seed| to compressed base64-encoded protobuf binary format.
std::string SerializeSeedBase64(const VariationsSeed& seed) {
std::string serialized_seed = SerializeSeed(seed);
std::string base64_serialized_seed;
base::Base64Encode(Compress(serialized_seed), &base64_serialized_seed);
return base64_serialized_seed;
}
// Sets all seed-related prefs to non-default values. Used to verify whether
// pref values were cleared.
void SetAllSeedPrefsToNonDefaultValues(PrefService* prefs) {
prefs->SetString(prefs::kVariationsCompressedSeed, "a");
prefs->SetString(prefs::kVariationsSafeCompressedSeed, "b");
prefs->SetString(prefs::kVariationsSafeSeedLocale, "c");
prefs->SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "d");
prefs->SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "e");
prefs->SetString(prefs::kVariationsSafeSeedSignature, "f");
prefs->SetString(prefs::kVariationsSeedSignature, "g");
const base::Time now = base::Time::Now();
const base::TimeDelta delta = base::TimeDelta::FromDays(1);
prefs->SetTime(prefs::kVariationsSafeSeedDate, now - delta);
prefs->SetTime(prefs::kVariationsSafeSeedFetchTime, now - delta * 2);
prefs->SetTime(prefs::kVariationsSeedDate, now - delta * 3);
}
// Checks whether the pref with name |pref_name| is at its default value in
// |prefs|.
bool PrefHasDefaultValue(const TestingPrefServiceSimple& prefs,
const char* pref_name) {
return prefs.FindPreference(pref_name)->IsDefaultValue();
}
} // namespace
TEST(VariationsSeedStoreTest, LoadSeed_ValidSeed) {
// Store good seed data to test if loading from prefs works.
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a test signature, ignored.";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string loaded_base64_seed_signature;
// Check that loading a seed works correctly.
EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&loaded_base64_seed_signature));
// Check that the loaded data is the same as the original.
EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed));
EXPECT_EQ(SerializeSeed(seed), loaded_seed_data);
EXPECT_EQ(base64_seed_signature, loaded_base64_seed_signature);
// Make sure the pref hasn't been changed.
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
EXPECT_EQ(base64_seed, prefs.GetString(prefs::kVariationsCompressedSeed));
}
TEST(VariationsSeedStoreTest, LoadSeed_InvalidSeed) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
SetAllSeedPrefsToNonDefaultValues(&prefs);
prefs.SetString(prefs::kVariationsCompressedSeed, "this should fail");
// Loading an invalid seed should return false and clear all associated prefs.
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string loaded_base64_seed_signature;
EXPECT_FALSE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&loaded_base64_seed_signature));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedDate));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedSignature));
// However, only the latest seed prefs should be cleared; the safe seed prefs
// should not be modified.
EXPECT_FALSE(
PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale));
EXPECT_FALSE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_FALSE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedSignature));
}
TEST(VariationsSeedStoreTest, LoadSeed_InvalidSignature) {
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a deeply compromised signature.";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
SetAllSeedPrefsToNonDefaultValues(&prefs);
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
// Loading a valid seed with an invalid signature should return false and
// clear all associated prefs when signature verification is enabled.
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string loaded_base64_seed_signature;
EXPECT_FALSE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&loaded_base64_seed_signature));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedDate));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedSignature));
// However, only the latest seed prefs should be cleared; the safe seed prefs
// should not be modified.
EXPECT_FALSE(
PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale));
EXPECT_FALSE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_FALSE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedSignature));
}
TEST(VariationsSeedStoreTest, LoadSeed_EmptySeed) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
// Loading an empty seed should return false.
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string loaded_base64_seed_signature;
EXPECT_FALSE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&loaded_base64_seed_signature));
}
TEST(VariationsSeedStoreTest, LoadSeed_IdenticalToSafeSeed) {
// Store good seed data to the safe seed prefs, and store a sentinel value to
// the latest seed pref, to verify that loading via the alias works.
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a test signature, ignored.";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed,
kIdenticalToSafeSeedSentinel);
prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string loaded_base64_seed_signature;
// Check that loading the seed works correctly.
EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&loaded_base64_seed_signature));
// Check that the loaded data is the same as the original.
EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed));
EXPECT_EQ(SerializeSeed(seed), loaded_seed_data);
EXPECT_EQ(base64_seed_signature, loaded_base64_seed_signature);
}
TEST(VariationsSeedStoreTest, StoreSeedData) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
EXPECT_TRUE(seed_store.StoreSeedForTesting(serialized_seed));
// Make sure the pref was actually set.
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
std::string loaded_compressed_seed =
prefs.GetString(prefs::kVariationsCompressedSeed);
std::string decoded_compressed_seed;
ASSERT_TRUE(base::Base64Decode(loaded_compressed_seed,
&decoded_compressed_seed));
// Make sure the stored seed from pref is the same as the seed we created.
EXPECT_EQ(Compress(serialized_seed), decoded_compressed_seed);
// Check if trying to store a bad seed leaves the pref unchanged.
prefs.ClearPref(prefs::kVariationsCompressedSeed);
EXPECT_FALSE(seed_store.StoreSeedForTesting("should fail"));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
}
TEST(VariationsSeedStoreTest, StoreSeedData_ParsedSeed) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed parsed_seed;
EXPECT_TRUE(seed_store.StoreSeedData(serialized_seed, std::string(),
std::string(), base::Time::Now(), false,
false, false, &parsed_seed));
EXPECT_EQ(serialized_seed, SerializeSeed(parsed_seed));
}
TEST(VariationsSeedStoreTest, StoreSeedData_CountryCode) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
// Test with a valid header value.
std::string seed = SerializeSeed(CreateTestSeed());
EXPECT_TRUE(seed_store.StoreSeedData(seed, std::string(), "test_country",
base::Time::Now(), false, false, false,
nullptr));
EXPECT_EQ("test_country", prefs.GetString(prefs::kVariationsCountry));
// Test with no country code specified - which should preserve the old value.
EXPECT_TRUE(seed_store.StoreSeedData(seed, std::string(), std::string(),
base::Time::Now(), false, false, false,
nullptr));
EXPECT_EQ("test_country", prefs.GetString(prefs::kVariationsCountry));
}
TEST(VariationsSeedStoreTest, StoreSeedData_GzippedSeed) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
std::string compressed_seed;
ASSERT_TRUE(compression::GzipCompress(serialized_seed, &compressed_seed));
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed parsed_seed;
EXPECT_TRUE(seed_store.StoreSeedData(compressed_seed, std::string(),
std::string(), base::Time::Now(), false,
true, false, &parsed_seed));
EXPECT_EQ(serialized_seed, SerializeSeed(parsed_seed));
}
TEST(VariationsSeedStoreTest, StoreSeedData_IdenticalToSafeSeed) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
const std::string base64_seed = SerializeSeedBase64(seed);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed);
TestVariationsSeedStore seed_store(&prefs);
EXPECT_TRUE(seed_store.StoreSeedForTesting(serialized_seed));
// Verify that the pref has a sentinel value, rather than the full string.
EXPECT_EQ(kIdenticalToSafeSeedSentinel,
prefs.GetString(prefs::kVariationsCompressedSeed));
// Verify that loading the stored seed returns the original seed value.
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string unused_loaded_base64_seed_signature;
EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&unused_loaded_base64_seed_signature));
EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed));
EXPECT_EQ(SerializeSeed(seed), loaded_seed_data);
}
TEST(VariationsSeedStoreTest, LoadSafeSeed_ValidSeed) {
// Store good seed data to test if loading from prefs works.
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a test signature, ignored.";
const base::Time reference_date = base::Time::Now();
const base::Time fetch_time = reference_date - base::TimeDelta::FromDays(3);
const std::string locale = "en-US";
const std::string permanent_consistency_country = "us";
const std::string session_consistency_country = "ca";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSafeSeedSignature, base64_seed_signature);
prefs.SetTime(prefs::kVariationsSafeSeedDate, reference_date);
prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, fetch_time);
prefs.SetString(prefs::kVariationsSafeSeedLocale, locale);
prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry,
permanent_consistency_country);
prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry,
session_consistency_country);
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::unique_ptr<ClientFilterableState> client_state =
CreateTestClientFilterableState();
base::Time loaded_fetch_time;
EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_seed, client_state.get(),
&loaded_fetch_time));
// Check that the loaded data is the same as the original.
EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed));
EXPECT_EQ(locale, client_state->locale);
EXPECT_EQ(reference_date, client_state->reference_date);
EXPECT_EQ(permanent_consistency_country,
client_state->permanent_consistency_country);
EXPECT_EQ(session_consistency_country,
client_state->session_consistency_country);
EXPECT_EQ(fetch_time, loaded_fetch_time);
// Make sure that other data in the |client_state| hasn't been changed.
std::unique_ptr<ClientFilterableState> original_state =
CreateTestClientFilterableState();
EXPECT_EQ(original_state->version, client_state->version);
EXPECT_EQ(original_state->channel, client_state->channel);
EXPECT_EQ(original_state->form_factor, client_state->form_factor);
EXPECT_EQ(original_state->platform, client_state->platform);
EXPECT_EQ(original_state->hardware_class, client_state->hardware_class);
EXPECT_EQ(original_state->is_low_end_device, client_state->is_low_end_device);
// Make sure the pref hasn't been changed.
EXPECT_FALSE(
PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed));
EXPECT_EQ(base64_seed, prefs.GetString(prefs::kVariationsSafeCompressedSeed));
}
TEST(VariationsSeedStoreTest, LoadSafeSeed_InvalidSeed) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
SetAllSeedPrefsToNonDefaultValues(&prefs);
prefs.SetString(prefs::kVariationsSafeCompressedSeed, "this should fail");
// Loading an invalid seed should return false and clear all associated prefs.
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::unique_ptr<ClientFilterableState> client_state =
CreateTestClientFilterableState();
base::Time fetch_time;
EXPECT_FALSE(
seed_store.LoadSafeSeed(&loaded_seed, client_state.get(), &fetch_time));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale));
EXPECT_TRUE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_TRUE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedSignature));
// However, only the safe seed prefs should be cleared; the latest seed prefs
// should not be modified.
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedDate));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedSignature));
// Moreover, loading an invalid seed should leave the |client_state|
// unmodified.
std::unique_ptr<ClientFilterableState> original_state =
CreateTestClientFilterableState();
EXPECT_EQ(original_state->locale, client_state->locale);
EXPECT_EQ(original_state->reference_date, client_state->reference_date);
EXPECT_EQ(original_state->session_consistency_country,
client_state->session_consistency_country);
EXPECT_EQ(original_state->permanent_consistency_country,
client_state->permanent_consistency_country);
}
TEST(VariationsSeedStoreTest, LoadSafeSeed_InvalidSignature) {
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a deeply compromised signature.";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
SetAllSeedPrefsToNonDefaultValues(&prefs);
prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSafeSeedSignature, base64_seed_signature);
// Loading a valid seed with an invalid signature should return false and
// clear all associated prefs when signature verification is enabled.
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
std::unique_ptr<ClientFilterableState> client_state =
CreateTestClientFilterableState();
base::Time fetch_time;
EXPECT_FALSE(
seed_store.LoadSafeSeed(&loaded_seed, client_state.get(), &fetch_time));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeCompressedSeed));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedDate));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedFetchTime));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedLocale));
EXPECT_TRUE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_TRUE(PrefHasDefaultValue(
prefs, prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsSafeSeedSignature));
// However, only the safe seed prefs should be cleared; the latest seed prefs
// should not be modified.
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedDate));
EXPECT_FALSE(PrefHasDefaultValue(prefs, prefs::kVariationsSeedSignature));
// Moreover, the passed-in |client_state| should remain unmodified.
std::unique_ptr<ClientFilterableState> original_state =
CreateTestClientFilterableState();
EXPECT_EQ(original_state->locale, client_state->locale);
EXPECT_EQ(original_state->reference_date, client_state->reference_date);
EXPECT_EQ(original_state->session_consistency_country,
client_state->session_consistency_country);
EXPECT_EQ(original_state->permanent_consistency_country,
client_state->permanent_consistency_country);
}
TEST(VariationsSeedStoreTest, LoadSafeSeed_EmptySeed) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
// Loading an empty seed should return false.
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed loaded_seed;
ClientFilterableState client_state;
base::Time fetch_time;
EXPECT_FALSE(
seed_store.LoadSafeSeed(&loaded_seed, &client_state, &fetch_time));
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_ValidSeed) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
const std::string signature = "a completely ignored signature";
ClientFilterableState client_state;
client_state.locale = "en-US";
client_state.reference_date = WrapTime(12345);
client_state.session_consistency_country = "US";
client_state.permanent_consistency_country = "CA";
const base::Time fetch_time = WrapTime(99999);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_seed, signature, client_state,
fetch_time));
// Verify the stored data.
std::string loaded_compressed_seed =
prefs.GetString(prefs::kVariationsSafeCompressedSeed);
std::string decoded_compressed_seed;
ASSERT_TRUE(
base::Base64Decode(loaded_compressed_seed, &decoded_compressed_seed));
EXPECT_EQ(Compress(serialized_seed), decoded_compressed_seed);
EXPECT_EQ(signature, prefs.GetString(prefs::kVariationsSafeSeedSignature));
EXPECT_EQ("en-US", prefs.GetString(prefs::kVariationsSafeSeedLocale));
EXPECT_EQ(WrapTime(12345), prefs.GetTime(prefs::kVariationsSafeSeedDate));
EXPECT_EQ(WrapTime(99999),
prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
EXPECT_EQ("US", prefs.GetString(
prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_EQ("CA", prefs.GetString(
prefs::kVariationsSafeSeedPermanentConsistencyCountry));
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::SUCCESS, 1);
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_EmptySeed) {
const std::string serialized_seed;
const std::string signature = "a completely ignored signature";
ClientFilterableState client_state;
client_state.locale = "en-US";
client_state.reference_date = WrapTime(54321);
client_state.session_consistency_country = "US";
client_state.permanent_consistency_country = "CA";
base::Time fetch_time = WrapTime(99999);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, "a seed");
prefs.SetString(prefs::kVariationsSafeSeedSignature, "a signature");
prefs.SetString(prefs::kVariationsSafeSeedLocale, "en-US");
prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "CA");
prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "US");
prefs.SetTime(prefs::kVariationsSafeSeedDate, WrapTime(12345));
prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(34567));
TestVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_FALSE(seed_store.StoreSafeSeed(serialized_seed, signature,
client_state, fetch_time));
// Verify that none of the prefs were overwritten.
EXPECT_EQ("a seed", prefs.GetString(prefs::kVariationsSafeCompressedSeed));
EXPECT_EQ("a signature",
prefs.GetString(prefs::kVariationsSafeSeedSignature));
EXPECT_EQ("en-US", prefs.GetString(prefs::kVariationsSafeSeedLocale));
EXPECT_EQ("CA", prefs.GetString(
prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_EQ("US", prefs.GetString(
prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_EQ(WrapTime(12345), prefs.GetTime(prefs::kVariationsSafeSeedDate));
EXPECT_EQ(WrapTime(34567),
prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result",
StoreSeedResult::FAILED_EMPTY_GZIP_CONTENTS, 1);
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_InvalidSeed) {
const std::string serialized_seed = "a nonsense seed";
const std::string signature = "a completely ignored signature";
ClientFilterableState client_state;
client_state.locale = "en-US";
client_state.reference_date = WrapTime(12345);
client_state.session_consistency_country = "US";
client_state.permanent_consistency_country = "CA";
base::Time fetch_time = WrapTime(54321);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, "a previous seed");
prefs.SetString(prefs::kVariationsSafeSeedSignature, "a previous signature");
prefs.SetString(prefs::kVariationsSafeSeedLocale, "en-CA");
prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "IN");
prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "MX");
prefs.SetTime(prefs::kVariationsSafeSeedDate, WrapTime(67890));
prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(13579));
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_FALSE(seed_store.StoreSafeSeed(serialized_seed, signature,
client_state, fetch_time));
// Verify that none of the prefs were overwritten.
EXPECT_EQ("a previous seed",
prefs.GetString(prefs::kVariationsSafeCompressedSeed));
EXPECT_EQ("a previous signature",
prefs.GetString(prefs::kVariationsSafeSeedSignature));
EXPECT_EQ("en-CA", prefs.GetString(prefs::kVariationsSafeSeedLocale));
EXPECT_EQ("IN", prefs.GetString(
prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_EQ("MX", prefs.GetString(
prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_EQ(WrapTime(67890), prefs.GetTime(prefs::kVariationsSafeSeedDate));
EXPECT_EQ(WrapTime(13579),
prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::FAILED_PARSE,
1);
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_InvalidSignature) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
// A valid signature, but for a different seed.
const std::string signature = kBase64SeedSignature;
ClientFilterableState client_state;
client_state.locale = "en-US";
client_state.reference_date = WrapTime(12345);
client_state.session_consistency_country = "US";
client_state.permanent_consistency_country = "CA";
const base::Time fetch_time = WrapTime(34567);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, "a previous seed");
prefs.SetString(prefs::kVariationsSafeSeedSignature, "a previous signature");
prefs.SetString(prefs::kVariationsSafeSeedLocale, "en-CA");
prefs.SetString(prefs::kVariationsSafeSeedPermanentConsistencyCountry, "IN");
prefs.SetString(prefs::kVariationsSafeSeedSessionConsistencyCountry, "MX");
prefs.SetTime(prefs::kVariationsSafeSeedDate, WrapTime(67890));
prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(24680));
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_FALSE(seed_store.StoreSafeSeed(serialized_seed, signature,
client_state, fetch_time));
// Verify that none of the prefs were overwritten.
EXPECT_EQ("a previous seed",
prefs.GetString(prefs::kVariationsSafeCompressedSeed));
EXPECT_EQ("a previous signature",
prefs.GetString(prefs::kVariationsSafeSeedSignature));
EXPECT_EQ("en-CA", prefs.GetString(prefs::kVariationsSafeSeedLocale));
EXPECT_EQ("IN", prefs.GetString(
prefs::kVariationsSafeSeedPermanentConsistencyCountry));
EXPECT_EQ("MX", prefs.GetString(
prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_EQ(WrapTime(67890), prefs.GetTime(prefs::kVariationsSafeSeedDate));
EXPECT_EQ(WrapTime(24680),
prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result",
StoreSeedResult::FAILED_SIGNATURE, 1);
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.SignatureValidity",
VerifySignatureResult::INVALID_SEED, 1);
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_ValidSignature) {
std::string serialized_seed;
ASSERT_TRUE(
base::Base64Decode(kUncompressedBase64SeedData, &serialized_seed));
const std::string signature = kBase64SeedSignature;
ClientFilterableState client_state;
client_state.locale = "en-US";
client_state.reference_date = WrapTime(12345);
client_state.session_consistency_country = "US";
client_state.permanent_consistency_country = "CA";
const base::Time fetch_time = WrapTime(34567);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_seed, signature, client_state,
fetch_time));
// Verify the stored data.
std::string loaded_compressed_seed =
prefs.GetString(prefs::kVariationsSafeCompressedSeed);
std::string decoded_compressed_seed;
ASSERT_TRUE(
base::Base64Decode(loaded_compressed_seed, &decoded_compressed_seed));
EXPECT_EQ(Compress(serialized_seed), decoded_compressed_seed);
EXPECT_EQ(signature, prefs.GetString(prefs::kVariationsSafeSeedSignature));
EXPECT_EQ("en-US", prefs.GetString(prefs::kVariationsSafeSeedLocale));
EXPECT_EQ(WrapTime(12345), prefs.GetTime(prefs::kVariationsSafeSeedDate));
EXPECT_EQ(WrapTime(34567),
prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
EXPECT_EQ("US", prefs.GetString(
prefs::kVariationsSafeSeedSessionConsistencyCountry));
EXPECT_EQ("CA", prefs.GetString(
prefs::kVariationsSafeSeedPermanentConsistencyCountry));
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::SUCCESS, 1);
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.SignatureValidity",
VerifySignatureResult::VALID_SIGNATURE, 1);
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_IdenticalToLatestSeed) {
const VariationsSeed seed = CreateTestSeed();
const std::string serialized_seed = SerializeSeed(seed);
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string signature = "a completely ignored signature";
ClientFilterableState unused_client_state;
const base::Time fetch_time = WrapTime(12345);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed);
prefs.SetTime(prefs::kVariationsLastFetchTime, WrapTime(99999));
TestVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_seed, signature,
unused_client_state, fetch_time));
// Verify the latest seed value was migrated to a sentinel value, rather than
// the full string.
EXPECT_EQ(kIdenticalToSafeSeedSentinel,
prefs.GetString(prefs::kVariationsCompressedSeed));
// Verify that loading the stored seed returns the original seed value.
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string unused_loaded_base64_seed_signature;
EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&unused_loaded_base64_seed_signature));
EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_seed));
EXPECT_EQ(SerializeSeed(seed), loaded_seed_data);
// Verify that the safe seed prefs indeed contain the serialized seed value
// and that the last fetch time was copied from the latest seed.
EXPECT_EQ(base64_seed, prefs.GetString(prefs::kVariationsSafeCompressedSeed));
VariationsSeed loaded_safe_seed;
base::Time loaded_fetch_time;
EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_safe_seed, &unused_client_state,
&loaded_fetch_time));
EXPECT_EQ(SerializeSeed(seed), SerializeSeed(loaded_safe_seed));
EXPECT_EQ(WrapTime(99999), loaded_fetch_time);
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::SUCCESS, 1);
}
TEST(VariationsSeedStoreTest, StoreSafeSeed_PreviouslyIdenticalToLatestSeed) {
// Create two distinct seeds: an old one saved as both the safe and the latest
// seed value, and a new one that should overwrite only the stored safe seed
// value.
const VariationsSeed old_seed = CreateTestSeed();
VariationsSeed new_seed = CreateTestSeed();
new_seed.set_serial_number("12345678");
ASSERT_NE(SerializeSeed(old_seed), SerializeSeed(new_seed));
const std::string serialized_old_seed = SerializeSeed(old_seed);
const std::string base64_old_seed = SerializeSeedBase64(old_seed);
const std::string serialized_new_seed = SerializeSeed(new_seed);
const std::string base64_new_seed = SerializeSeedBase64(new_seed);
const std::string signature = "a completely ignored signature";
const base::Time fetch_time = WrapTime(12345);
ClientFilterableState unused_client_state;
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, base64_old_seed);
prefs.SetString(prefs::kVariationsCompressedSeed,
kIdenticalToSafeSeedSentinel);
TestVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
EXPECT_TRUE(seed_store.StoreSafeSeed(serialized_new_seed, signature,
unused_client_state, fetch_time));
// Verify the latest seed value was copied before the safe seed was
// overwritten.
EXPECT_EQ(base64_old_seed, prefs.GetString(prefs::kVariationsCompressedSeed));
// Verify that loading the stored seed returns the old seed value.
VariationsSeed loaded_seed;
std::string loaded_seed_data;
std::string unused_loaded_base64_seed_signature;
EXPECT_TRUE(seed_store.LoadSeed(&loaded_seed, &loaded_seed_data,
&unused_loaded_base64_seed_signature));
EXPECT_EQ(SerializeSeed(old_seed), SerializeSeed(loaded_seed));
EXPECT_EQ(SerializeSeed(old_seed), loaded_seed_data);
// Verify that the safe seed prefs indeed contain the new seed's serialized
// value.
EXPECT_EQ(base64_new_seed,
prefs.GetString(prefs::kVariationsSafeCompressedSeed));
VariationsSeed loaded_safe_seed;
base::Time loaded_fetch_time;
EXPECT_TRUE(seed_store.LoadSafeSeed(&loaded_safe_seed, &unused_client_state,
&loaded_fetch_time));
EXPECT_EQ(SerializeSeed(new_seed), SerializeSeed(loaded_safe_seed));
EXPECT_EQ(fetch_time, loaded_fetch_time);
// Verify metrics.
histogram_tester.ExpectUniqueSample(
"Variations.SafeMode.StoreSafeSeed.Result", StoreSeedResult::SUCCESS, 1);
}
TEST(VariationsSeedStoreTest, StoreSeedData_GzippedEmptySeed) {
std::string empty_seed;
std::string compressed_seed;
ASSERT_TRUE(compression::GzipCompress(empty_seed, &compressed_seed));
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
VariationsSeed parsed_seed;
EXPECT_FALSE(seed_store.StoreSeedData(compressed_seed, std::string(),
std::string(), base::Time::Now(), false,
true, false, &parsed_seed));
}
TEST(VariationsSeedStoreTest, VerifySeedSignature) {
// A valid seed and signature pair generated using the server's private key.
const std::string uncompressed_base64_seed_data = kUncompressedBase64SeedData;
const std::string base64_seed_signature = kBase64SeedSignature;
std::string seed_data;
ASSERT_TRUE(base::Base64Decode(uncompressed_base64_seed_data, &seed_data));
VariationsSeed seed;
ASSERT_TRUE(seed.ParseFromString(seed_data));
std::string base64_seed_data = SerializeSeedBase64(seed);
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
// The above inputs should be valid.
{
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed_data);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
VariationsSeed seed;
std::string seed_data;
std::string base64_seed_signature;
EXPECT_TRUE(seed_store.LoadSeed(&seed, &seed_data, &base64_seed_signature));
histogram_tester.ExpectUniqueSample(
"Variations.LoadSeedSignature",
static_cast<base::HistogramBase::Sample>(
VerifySignatureResult::VALID_SIGNATURE),
1);
}
// If there's no signature, the corresponding result should be returned.
{
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed_data);
prefs.SetString(prefs::kVariationsSeedSignature, std::string());
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
VariationsSeed seed;
std::string seed_data;
std::string base64_seed_signature;
EXPECT_FALSE(
seed_store.LoadSeed(&seed, &seed_data, &base64_seed_signature));
histogram_tester.ExpectUniqueSample(
"Variations.LoadSeedSignature",
static_cast<base::HistogramBase::Sample>(
VerifySignatureResult::MISSING_SIGNATURE),
1);
}
// Using non-base64 encoded value as signature should fail.
{
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed_data);
prefs.SetString(prefs::kVariationsSeedSignature,
"not a base64-encoded string");
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
std::string seed_data;
std::string base64_seed_signature;
EXPECT_FALSE(
seed_store.LoadSeed(&seed, &seed_data, &base64_seed_signature));
histogram_tester.ExpectUniqueSample(
"Variations.LoadSeedSignature",
static_cast<base::HistogramBase::Sample>(
VerifySignatureResult::DECODE_FAILED),
1);
}
// Using a different signature (e.g. the base64 seed data) should fail.
// OpenSSL doesn't distinguish signature decode failure from the
// signature not matching.
{
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed_data);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_data);
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
VariationsSeed seed;
std::string seed_data;
std::string base64_seed_signature;
EXPECT_FALSE(
seed_store.LoadSeed(&seed, &seed_data, &base64_seed_signature));
histogram_tester.ExpectUniqueSample(
"Variations.LoadSeedSignature",
static_cast<base::HistogramBase::Sample>(
VerifySignatureResult::INVALID_SEED),
1);
}
// Using a different seed should not match the signature.
{
VariationsSeed wrong_seed;
ASSERT_TRUE(wrong_seed.ParseFromString(seed_data));
(*wrong_seed.mutable_study(0)->mutable_name())[0] = 'x';
std::string base64_wrong_seed_data = SerializeSeedBase64(wrong_seed);
prefs.SetString(prefs::kVariationsCompressedSeed, base64_wrong_seed_data);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
SignatureVerifyingVariationsSeedStore seed_store(&prefs);
base::HistogramTester histogram_tester;
std::string seed_data;
std::string base64_seed_signature;
EXPECT_FALSE(
seed_store.LoadSeed(&seed, &seed_data, &base64_seed_signature));
histogram_tester.ExpectUniqueSample(
"Variations.LoadSeedSignature",
static_cast<base::HistogramBase::Sample>(
VerifySignatureResult::INVALID_SEED),
1);
}
}
TEST(VariationsSeedStoreTest, ApplyDeltaPatch) {
// Sample seeds and the server produced delta between them to verify that the
// client code is able to decode the deltas produced by the server.
const std::string base64_before_seed_data =
"CigxN2E4ZGJiOTI4ODI0ZGU3ZDU2MGUyODRlODY1ZDllYzg2NzU1MTE0ElgKDFVNQVN0YWJp"
"bGl0eRjEyomgBTgBQgtTZXBhcmF0ZUxvZ0oLCgdEZWZhdWx0EABKDwoLU2VwYXJhdGVMb2cQ"
"ZFIVEgszNC4wLjE4MDEuMCAAIAEgAiADEkQKIFVNQS1Vbmlmb3JtaXR5LVRyaWFsLTEwMC1Q"
"ZXJjZW50GIDjhcAFOAFCCGdyb3VwXzAxSgwKCGdyb3VwXzAxEAFgARJPCh9VTUEtVW5pZm9y"
"bWl0eS1UcmlhbC01MC1QZXJjZW50GIDjhcAFOAFCB2RlZmF1bHRKDAoIZ3JvdXBfMDEQAUoL"
"CgdkZWZhdWx0EAFgAQ==";
const std::string base64_after_seed_data =
"CigyNGQzYTM3ZTAxYmViOWYwNWYzMjM4YjUzNWY3MDg1ZmZlZWI4NzQwElgKDFVNQVN0YWJp"
"bGl0eRjEyomgBTgBQgtTZXBhcmF0ZUxvZ0oLCgdEZWZhdWx0EABKDwoLU2VwYXJhdGVMb2cQ"
"ZFIVEgszNC4wLjE4MDEuMCAAIAEgAiADEpIBCh9VTUEtVW5pZm9ybWl0eS1UcmlhbC0yMC1Q"
"ZXJjZW50GIDjhcAFOAFCB2RlZmF1bHRKEQoIZ3JvdXBfMDEQARijtskBShEKCGdyb3VwXzAy"
"EAEYpLbJAUoRCghncm91cF8wMxABGKW2yQFKEQoIZ3JvdXBfMDQQARimtskBShAKB2RlZmF1"
"bHQQARiitskBYAESWAofVU1BLVVuaWZvcm1pdHktVHJpYWwtNTAtUGVyY2VudBiA44XABTgB"
"QgdkZWZhdWx0Sg8KC25vbl9kZWZhdWx0EAFKCwoHZGVmYXVsdBABUgQoACgBYAE=";
const std::string base64_delta_data =
"KgooMjRkM2EzN2UwMWJlYjlmMDVmMzIzOGI1MzVmNzA4NWZmZWViODc0MAAqW+4BkgEKH1VN"
"QS1Vbmlmb3JtaXR5LVRyaWFsLTIwLVBlcmNlbnQYgOOFwAU4AUIHZGVmYXVsdEoRCghncm91"
"cF8wMRABGKO2yQFKEQoIZ3JvdXBfMDIQARiktskBShEKCGdyb3VwXzAzEAEYpbbJAUoRCghn"
"cm91cF8wNBABGKa2yQFKEAoHZGVmYXVsdBABGKK2yQFgARJYCh9VTUEtVW5pZm9ybWl0eS1U"
"cmlhbC01MC1QZXJjZW50GIDjhcAFOAFCB2RlZmF1bHRKDwoLbm9uX2RlZmF1bHQQAUoLCgdk"
"ZWZhdWx0EAFSBCgAKAFgAQ==";
std::string before_seed_data;
std::string after_seed_data;
std::string delta_data;
EXPECT_TRUE(base::Base64Decode(base64_before_seed_data, &before_seed_data));
EXPECT_TRUE(base::Base64Decode(base64_after_seed_data, &after_seed_data));
EXPECT_TRUE(base::Base64Decode(base64_delta_data, &delta_data));
std::string output;
EXPECT_TRUE(VariationsSeedStore::ApplyDeltaPatch(before_seed_data, delta_data,
&output));
EXPECT_EQ(after_seed_data, output);
}
TEST(VariationsSeedStoreTest, LastFetchTime_DistinctSeeds) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed, "one");
prefs.SetString(prefs::kVariationsSafeCompressedSeed, "not one");
prefs.SetTime(prefs::kVariationsLastFetchTime, WrapTime(1));
prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(0));
base::Time start_time = base::Time::Now();
TestVariationsSeedStore seed_store(&prefs);
seed_store.RecordLastFetchTime();
// Verify that the last fetch time was updated.
const base::Time last_fetch_time =
prefs.GetTime(prefs::kVariationsLastFetchTime);
EXPECT_NE(WrapTime(1), last_fetch_time);
EXPECT_GE(last_fetch_time, start_time);
// Verify that the safe seed's fetch time was *not* updated.
EXPECT_EQ(WrapTime(0), prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
}
TEST(VariationsSeedStoreTest, LastFetchTime_IdenticalSeeds) {
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsSafeCompressedSeed, "some seed");
prefs.SetString(prefs::kVariationsCompressedSeed,
kIdenticalToSafeSeedSentinel);
prefs.SetTime(prefs::kVariationsLastFetchTime, WrapTime(1));
prefs.SetTime(prefs::kVariationsSafeSeedFetchTime, WrapTime(0));
base::Time start_time = base::Time::Now();
TestVariationsSeedStore seed_store(&prefs);
seed_store.RecordLastFetchTime();
// Verify that the last fetch time was updated.
const base::Time last_fetch_time =
prefs.GetTime(prefs::kVariationsLastFetchTime);
EXPECT_NE(WrapTime(1), last_fetch_time);
EXPECT_GE(last_fetch_time, start_time);
// Verify that the safe seed's fetch time *was* also updated.
EXPECT_EQ(last_fetch_time,
prefs.GetTime(prefs::kVariationsSafeSeedFetchTime));
}
TEST(VariationsSeedStoreTest, GetLatestSerialNumber_LoadsInitialValue) {
// Store good seed data to test if loading from prefs works.
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a completely ignored signature";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
TestVariationsSeedStore seed_store(&prefs);
EXPECT_EQ("123", seed_store.GetLatestSerialNumber());
}
TEST(VariationsSeedStoreTest, GetLatestSerialNumber_EmptyWhenNoSeedIsSaved) {
// Start with empty prefs.
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
TestVariationsSeedStore seed_store(&prefs);
EXPECT_EQ(std::string(), seed_store.GetLatestSerialNumber());
}
// Verifies that the cached serial number is correctly updated when a new seed
// is saved.
TEST(VariationsSeedStoreTest, GetLatestSerialNumber_UpdatedWithNewStoredSeed) {
// Store good seed data initially.
const VariationsSeed seed = CreateTestSeed();
const std::string base64_seed = SerializeSeedBase64(seed);
const std::string base64_seed_signature = "a completely ignored signature";
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed, base64_seed);
prefs.SetString(prefs::kVariationsSeedSignature, base64_seed_signature);
// Call GetLatestSerialNumber() once to prime the cached value.
TestVariationsSeedStore seed_store(&prefs);
EXPECT_EQ("123", seed_store.GetLatestSerialNumber());
VariationsSeed new_seed = CreateTestSeed();
new_seed.set_serial_number("456");
seed_store.StoreSeedForTesting(SerializeSeed(new_seed));
EXPECT_EQ("456", seed_store.GetLatestSerialNumber());
}
TEST(VariationsSeedStoreTest, GetLatestSerialNumber_ClearsPrefsOnFailure) {
// Store corrupted seed data to test that prefs are cleared when loading
// fails.
TestingPrefServiceSimple prefs;
VariationsSeedStore::RegisterPrefs(prefs.registry());
prefs.SetString(prefs::kVariationsCompressedSeed, "complete garbage");
prefs.SetString(prefs::kVariationsSeedSignature, "an unused signature");
TestVariationsSeedStore seed_store(&prefs);
EXPECT_EQ(std::string(), seed_store.GetLatestSerialNumber());
EXPECT_TRUE(PrefHasDefaultValue(prefs, prefs::kVariationsCompressedSeed));
}
#if defined(OS_ANDROID)
TEST(VariationsSeedStoreTest, ImportFirstRunJavaSeed) {
const std::string test_seed_data = "raw_seed_data_test";
const std::string test_seed_signature = "seed_signature_test";
const std::string test_seed_country = "seed_country_code_test";
const std::string test_response_date = "seed_response_date_test";
const bool test_is_gzip_compressed = true;
android::SetJavaFirstRunPrefsForTesting(test_seed_data, test_seed_signature,
test_seed_country, test_response_date,
test_is_gzip_compressed);
std::string seed_data;
std::string seed_signature;
std::string seed_country;
std::string response_date;
bool is_gzip_compressed;
android::GetVariationsFirstRunSeed(&seed_data, &seed_signature, &seed_country,
&response_date, &is_gzip_compressed);
EXPECT_EQ(test_seed_data, seed_data);
EXPECT_EQ(test_seed_signature, seed_signature);
EXPECT_EQ(test_seed_country, seed_country);
EXPECT_EQ(test_response_date, response_date);
EXPECT_EQ(test_is_gzip_compressed, is_gzip_compressed);
android::ClearJavaFirstRunPrefs();
android::GetVariationsFirstRunSeed(&seed_data, &seed_signature, &seed_country,
&response_date, &is_gzip_compressed);
EXPECT_EQ("", seed_data);
EXPECT_EQ("", seed_signature);
EXPECT_EQ("", seed_country);
EXPECT_EQ("", response_date);
EXPECT_FALSE(is_gzip_compressed);
}
#endif // OS_ANDROID
} // namespace variations
| null | null | null | null | 16,275 |
35,331 | null |
train_val
|
e4311ee51d1e2676001b2d8fcefd92bdd79aad85
| 200,326 |
linux
| 0 |
https://github.com/torvalds/linux
|
2017-05-12 08:32:58+10:00
|
/*
* Elonics E4000 silicon tuner driver
*
* Copyright (C) 2012 Antti Palosaari <[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.
*/
#ifndef E4000_H
#define E4000_H
#include "dvb_frontend.h"
/*
* I2C address
* 0x64, 0x65, 0x66, 0x67
*/
struct e4000_config {
/*
* frontend
*/
struct dvb_frontend *fe;
/*
* clock
*/
u32 clock;
};
#endif
| null | null | null | null | 108,673 |
25,040 | null |
train_val
|
796a0e014bc3985709c0a35538d606ef1da31e1b
| 25,040 |
Chrome
| 0 |
https://github.com/chromium/chromium
|
2018-04-07 23:43:03+00:00
|
// Copyright 2015 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 EXTENSIONS_RENDERER_GUEST_VIEW_EXTENSIONS_GUEST_VIEW_CONTAINER_DISPATCHER_H_
#define EXTENSIONS_RENDERER_GUEST_VIEW_EXTENSIONS_GUEST_VIEW_CONTAINER_DISPATCHER_H_
#include "base/macros.h"
#include "components/guest_view/renderer/guest_view_container_dispatcher.h"
namespace extensions {
class ExtensionsGuestViewContainerDispatcher
: public guest_view::GuestViewContainerDispatcher {
public:
ExtensionsGuestViewContainerDispatcher();
~ExtensionsGuestViewContainerDispatcher() override;
private:
// guest_view::GuestViewContainerDispatcher implementation.
bool HandlesMessage(const IPC::Message& message) override;
DISALLOW_COPY_AND_ASSIGN(ExtensionsGuestViewContainerDispatcher);
};
} // namespace extensions
#endif // EXTENSIONS_RENDERER_GUEST_VIEW_EXTENSIONS_GUEST_VIEW_CONTAINER_DISPATCHER_H_
| null | null | null | null | 21,903 |
Subsets and Splits
CWE Frequency in Train Set
Provides a count of vulnerabilities grouped by CWE ID, highlighting the most frequent types of vulnerabilities in the dataset.