hexsha
stringlengths
40
40
size
int64
22
2.4M
ext
stringclasses
5 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
260
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
78
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
3
260
max_issues_repo_name
stringlengths
5
109
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
3
260
max_forks_repo_name
stringlengths
5
109
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
22
2.4M
avg_line_length
float64
5
169k
max_line_length
int64
5
786k
alphanum_fraction
float64
0.06
0.95
matches
listlengths
1
11
bb5e6426463de0f0cfbe957978107671af483844
59,773
c
C
cloudfsapi.c
TurboGit/hubicfuse
788b9db6c0768136a0323a0f0f88a07d70897d45
[ "MIT" ]
319
2015-01-06T12:09:30.000Z
2021-05-26T12:37:30.000Z
cloudfsapi.c
TurboGit/hubicfuse
788b9db6c0768136a0323a0f0f88a07d70897d45
[ "MIT" ]
124
2015-01-04T17:42:44.000Z
2021-12-14T02:37:20.000Z
cloudfsapi.c
TurboGit/hubicfuse
788b9db6c0768136a0323a0f0f88a07d70897d45
[ "MIT" ]
72
2015-01-04T16:34:29.000Z
2021-08-31T01:47:07.000Z
#define _GNU_SOURCE #include <stdio.h> #include <magic.h> #include <string.h> #include <stdarg.h> #include <stdlib.h> #include <sys/stat.h> #include <fcntl.h> #ifdef __linux__ #include <alloca.h> #endif #include <pthread.h> #include <time.h> #include <unistd.h> #include <sys/types.h> #include <sys/time.h> #include <libxml/tree.h> #include <openssl/bio.h> #include <openssl/evp.h> #include <json.h> #include <libxml/xpath.h> #include <libxml/xpathInternals.h> #include "commonfs.h" #include "cloudfsapi.h" #include "config.h" #define FUSE_USE_VERSION 30 #include <fuse.h> #define RHEL5_LIBCURL_VERSION 462597 #define RHEL5_CERTIFICATE_FILE "/etc/pki/tls/certs/ca-bundle.crt" #define REQUEST_RETRIES 3 #define MAX_FILES 10000 // size of buffer for writing to disk look at ioblksize.h in coreutils // and try some values on your own system if you want the best performance #define DISK_BUFF_SIZE 32768 long segment_size; long segment_above; char* override_storage_url; char* public_container; static char storage_url[MAX_URL_SIZE]; static char storage_token[MAX_HEADER_SIZE]; static pthread_mutex_t pool_mut; static CURL* curl_pool[1024]; static int curl_pool_count = 0; extern int debug; extern int verify_ssl; extern bool option_get_extended_metadata; extern bool option_curl_verbose; extern int option_curl_progress_state; extern int option_cache_statfs_timeout; extern bool option_extensive_debug; extern bool option_enable_chown; extern bool option_enable_chmod; static int rhel5_mode = 0; static struct statvfs statcache = { .f_bsize = 4096, .f_frsize = 4096, .f_blocks = INT_MAX, .f_bfree = INT_MAX, .f_bavail = INT_MAX, .f_files = MAX_FILES, .f_ffree = 0, .f_favail = 0, .f_namemax = INT_MAX }; //used to compute statfs cache interval static time_t last_stat_read_time = 0; extern FuseOptions options; struct MemoryStruct { char* memory; size_t size; }; #ifdef HAVE_OPENSSL #include <openssl/crypto.h> static pthread_mutex_t* ssl_lockarray; static void lock_callback(int mode, int type, char* file, int line) { if (mode & CRYPTO_LOCK) pthread_mutex_lock(&(ssl_lockarray[type])); else pthread_mutex_unlock(&(ssl_lockarray[type])); } static unsigned long thread_id() { return (unsigned long)pthread_self(); } #endif static size_t xml_dispatch(void* ptr, size_t size, size_t nmemb, void* stream) { xmlParseChunk((xmlParserCtxtPtr)stream, (char*)ptr, size * nmemb, 0); return size * nmemb; } static CURL* get_connection(const char* path) { pthread_mutex_lock(&pool_mut); CURL* curl = curl_pool_count ? curl_pool[--curl_pool_count] : curl_easy_init(); if (!curl) { debugf(DBG_LEVEL_NORM, KRED"curl alloc failed"); pthread_mutex_unlock(&pool_mut); abort(); } pthread_mutex_unlock(&pool_mut); return curl; } static void return_connection(CURL* curl) { pthread_mutex_lock(&pool_mut); curl_pool[curl_pool_count++] = curl; pthread_mutex_unlock(&pool_mut); } static void add_header(curl_slist** headers, const char* name, const char* value) { char x_header[MAX_HEADER_SIZE]; char safe_value[256]; const char* value_ptr; debugf(DBG_LEVEL_EXT, "add_header(%s:%s)", name, value); if (strlen(value) > 256) { debugf(DBG_LEVEL_NORM, KRED"add_header: warning, value size > 256 (%s:%s) ", name, value); //hubic will throw an HTTP 400 error on X-Copy-To operation if X-Object-Meta-FilePath header value is larger than 256 chars //fix for issue #95 https://github.com/TurboGit/hubicfuse/issues/95 if (!strcasecmp(name, "X-Object-Meta-FilePath")) { debugf(DBG_LEVEL_NORM, KRED"add_header: trimming header (%s) value to max allowed", name); //trim header size to max allowed strncpy(safe_value, value, 256 - 1); safe_value[255] = '\0'; value_ptr = safe_value; } else value_ptr = value; } else value_ptr = value; snprintf(x_header, sizeof(x_header), "%s: %s", name, value_ptr); *headers = curl_slist_append(*headers, x_header); } static size_t header_dispatch(void* ptr, size_t size, size_t nmemb, void* dir_entry) { char* header = (char*)alloca(size * nmemb + 1); char* head = (char*)alloca(size * nmemb + 1); char* value = (char*)alloca(size * nmemb + 1); memcpy(header, (char*)ptr, size * nmemb); header[size * nmemb] = '\0'; if (sscanf(header, "%[^:]: %[^\r\n]", head, value) == 2) { if (!strncasecmp(head, "x-auth-token", size * nmemb)) strncpy(storage_token, value, sizeof(storage_token)); if (!strncasecmp(head, "x-storage-url", size * nmemb)) strncpy(storage_url, value, sizeof(storage_url)); if (!strncasecmp(head, "x-account-meta-quota", size * nmemb)) statcache.f_blocks = (unsigned long) (strtoull(value, NULL, 10) / statcache.f_frsize); if (!strncasecmp(head, "x-account-bytes-used", size * nmemb)) statcache.f_bfree = statcache.f_bavail = statcache.f_blocks - (unsigned long) ( strtoull(value, NULL, 10) / statcache.f_frsize); if (!strncasecmp(head, "x-account-object-count", size * nmemb)) { unsigned long object_count = strtoul(value, NULL, 10); statcache.f_ffree = MAX_FILES - object_count; statcache.f_favail = MAX_FILES - object_count; } } return size * nmemb; } static void header_set_time_from_str(char* time_str, struct timespec* time_entry) { char sec_value[TIME_CHARS] = { 0 }; char nsec_value[TIME_CHARS] = { 0 }; time_t sec; long nsec; sscanf(time_str, "%[^.].%[^\n]", sec_value, nsec_value); sec = strtoll(sec_value, NULL, 10);//to allow for larger numbers nsec = atol(nsec_value); debugf(DBG_LEVEL_EXTALL, "Received time=%s.%s / %li.%li, existing=%li.%li", sec_value, nsec_value, sec, nsec, time_entry->tv_sec, time_entry->tv_nsec); if (sec != time_entry->tv_sec || nsec != time_entry->tv_nsec) { debugf(DBG_LEVEL_EXTALL, "Time changed, setting new time=%li.%li, existing was=%li.%li", sec, nsec, time_entry->tv_sec, time_entry->tv_nsec); time_entry->tv_sec = sec; time_entry->tv_nsec = nsec; char time_str_local[TIME_CHARS] = ""; get_time_as_string((time_t)sec, nsec, time_str_local, sizeof(time_str_local)); debugf(DBG_LEVEL_EXTALL, "header_set_time_from_str received time=[%s]", time_str_local); get_timespec_as_str(time_entry, time_str_local, sizeof(time_str_local)); debugf(DBG_LEVEL_EXTALL, "header_set_time_from_str set time=[%s]", time_str_local); } } static size_t header_get_meta_dispatch(void* ptr, size_t size, size_t nmemb, void* userdata) { char* header = (char*)alloca(size * nmemb + 1); char* head = (char*)alloca(size * nmemb + 1); char* value = (char*)alloca(size * nmemb + 1); memcpy(header, (char*)ptr, size * nmemb); header[size * nmemb] = '\0'; static char storage[MAX_HEADER_SIZE]; if (sscanf(header, "%[^:]: %[^\r\n]", head, value) == 2) { strncpy(storage, head, sizeof(storage)); dir_entry* de = (dir_entry*)userdata; if (de != NULL) { if (!strncasecmp(head, HEADER_TEXT_ATIME, size * nmemb)) header_set_time_from_str(value, &de->atime); if (!strncasecmp(head, HEADER_TEXT_CTIME, size * nmemb)) header_set_time_from_str(value, &de->ctime); if (!strncasecmp(head, HEADER_TEXT_MTIME, size * nmemb)) header_set_time_from_str(value, &de->mtime); if (!strncasecmp(head, HEADER_TEXT_CHMOD, size * nmemb)) de->chmod = atoi(value); if (!strncasecmp(head, HEADER_TEXT_GID, size * nmemb)) de->gid = atoi(value); if (!strncasecmp(head, HEADER_TEXT_UID, size * nmemb)) de->uid = atoi(value); } else debugf(DBG_LEVEL_EXT, "Unexpected NULL dir_entry on header(%s), file should be in cache already", storage); } else { //debugf(DBG_LEVEL_NORM, "Received unexpected header line"); } return size * nmemb; } static size_t rw_callback(size_t (*rw)(void*, size_t, size_t, FILE*), void* ptr, size_t size, size_t nmemb, void* userp) { struct segment_info* info = (struct segment_info*)userp; size_t mem = size * nmemb; if (mem < 1 || info->size < 1) return 0; size_t amt_read = rw(ptr, 1, info->size < mem ? info->size : mem, info->fp); info->size -= amt_read; return amt_read; } size_t fwrite2(void* ptr, size_t size, size_t nmemb, FILE* filep) { return fwrite((const void*)ptr, size, nmemb, filep); } static size_t read_callback(void* ptr, size_t size, size_t nmemb, void* userp) { return rw_callback(fread, ptr, size, nmemb, userp); } static size_t write_callback(void* ptr, size_t size, size_t nmemb, void* userp) { return rw_callback(fwrite2, ptr, size, nmemb, userp); } //http://curl.haxx.se/libcurl/c/CURLOPT_XFERINFOFUNCTION.html int progress_callback_xfer(void* clientp, curl_off_t dltotal, curl_off_t dlnow, curl_off_t ultotal, curl_off_t ulnow) { struct curl_progress* myp = (struct curl_progress*)clientp; CURL* curl = myp->curl; double curtime = 0; double dspeed = 0, uspeed = 0; curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &curtime); curl_easy_getinfo(curl, CURLINFO_SPEED_DOWNLOAD, &dspeed); curl_easy_getinfo(curl, CURLINFO_SPEED_UPLOAD, &uspeed); /* under certain circumstances it may be desirable for certain functionality to only run every N seconds, in order to do this the transaction time can be used */ //http://curl.haxx.se/cvssource/src/tool_cb_prg.c if ((curtime - myp->lastruntime) >= MINIMAL_PROGRESS_FUNCTIONALITY_INTERVAL) { myp->lastruntime = curtime; curl_off_t total; curl_off_t point; double frac, percent; total = dltotal + ultotal; point = dlnow + ulnow; frac = (double)point / (double)total; percent = frac * 100.0f; debugf(DBG_LEVEL_EXT, "TOTAL TIME: %.0f sec Down=%.0f Kbps UP=%.0f Kbps", curtime, dspeed / 1024, uspeed / 1024); debugf(DBG_LEVEL_EXT, "UP: %lld of %lld DOWN: %lld/%lld Completion %.1f %%", ulnow, ultotal, dlnow, dltotal, percent); } return 0; } //http://curl.haxx.se/libcurl/c/CURLOPT_PROGRESSFUNCTION.html int progress_callback(void* clientp, double dltotal, double dlnow, double ultotal, double ulnow) { return progress_callback_xfer(clientp, (curl_off_t)dltotal, (curl_off_t)dlnow, (curl_off_t)ultotal, (curl_off_t)ulnow); } //get the response from HTTP requests, mostly for debug purposes // http://stackoverflow.com/questions/2329571/c-libcurl-get-output-into-a-string // http://curl.haxx.se/libcurl/c/getinmemory.html size_t writefunc_callback(void* contents, size_t size, size_t nmemb, void* userp) { size_t realsize = size * nmemb; struct MemoryStruct* mem = (struct MemoryStruct*)userp; mem->memory = realloc(mem->memory, mem->size + realsize + 1); if (mem->memory == NULL) { /* out of memory! */ debugf(DBG_LEVEL_NORM, KRED"writefunc_callback: realloc() failed"); return 0; } memcpy(&(mem->memory[mem->size]), contents, realsize); mem->size += realsize; mem->memory[mem->size] = 0; return realsize; } // de_cached_entry must be NULL when the file is already in global cache // otherwise point to a new dir_entry that will be added to the cache (usually happens on first dir load) static int send_request_size(const char* method, const char* path, void* fp, xmlParserCtxtPtr xmlctx, curl_slist* extra_headers, off_t file_size, int is_segment, dir_entry* de_cached_entry, const char* unencoded_path) { debugf(DBG_LEVEL_EXT, "send_request_size(%s) (%s)", method, path); char url[MAX_URL_SIZE]; char orig_path[MAX_URL_SIZE]; char header_data[MAX_HEADER_SIZE]; char* slash; long response = -1; int tries = 0; //needed to keep the response data, for debug purposes struct MemoryStruct chunk; if (!storage_url[0]) { debugf(DBG_LEVEL_NORM, KRED"send_request with no storage_url?"); abort(); } //char *encoded_path = curl_escape(path, 0); while ((slash = strstr(path, "%2F")) || (slash = strstr(path, "%2f"))) { *slash = '/'; memmove(slash + 1, slash + 3, strlen(slash + 3) + 1); } while (*path == '/') path++; snprintf(url, sizeof(url), "%s/%s", storage_url, path); snprintf(orig_path, sizeof(orig_path), "/%s", path); // retry on failures for (tries = 0; tries < REQUEST_RETRIES; tries++) { chunk.memory = malloc(1); /* will be grown as needed by the realloc above */ chunk.size = 0; /* no data at this point */ CURL* curl = get_connection(path); if (rhel5_mode) curl_easy_setopt(curl, CURLOPT_CAINFO, RHEL5_CERTIFICATE_FILE); curl_slist* headers = NULL; curl_easy_setopt(curl, CURLOPT_URL, url); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); //reversed logic, 0=to enable curl progress curl_easy_setopt(curl, CURLOPT_NOPROGRESS, option_curl_progress_state ? 0 : 1); curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, verify_ssl ? 1 : 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); curl_easy_setopt(curl, CURLOPT_VERBOSE, option_curl_verbose ? 1 : 0); add_header(&headers, "X-Auth-Token", storage_token); dir_entry* de; if (de_cached_entry == NULL) de = check_path_info(unencoded_path); else { // updating metadata on a file about to be added to cache (for x-copy, dest meta = src meta) de = de_cached_entry; debugf(DBG_LEVEL_EXTALL, "send_request_size: using param dir_entry(%s)", orig_path); } if (!de) debugf(DBG_LEVEL_EXTALL, "send_request_size: "KYEL"file not in cache (%s)(%s)(%s)", orig_path, path, unencoded_path); else { // add headers to save utimens attribs only on upload if (!strcasecmp(method, "PUT") || !strcasecmp(method, "MKDIR")) { debugf(DBG_LEVEL_EXTALL, "send_request_size: Saving utimens for file %s", orig_path); debugf(DBG_LEVEL_EXTALL, "send_request_size: Cached utime for path=%s ctime=%li.%li mtime=%li.%li atime=%li.%li", orig_path, de->ctime.tv_sec, de->ctime.tv_nsec, de->mtime.tv_sec, de->mtime.tv_nsec, de->atime.tv_sec, de->atime.tv_nsec); char atime_str_nice[TIME_CHARS] = "", mtime_str_nice[TIME_CHARS] = "", ctime_str_nice[TIME_CHARS] = ""; get_timespec_as_str(&(de->atime), atime_str_nice, sizeof(atime_str_nice)); debugf(DBG_LEVEL_EXTALL, KCYN"send_request_size: atime=[%s]", atime_str_nice); get_timespec_as_str(&(de->mtime), mtime_str_nice, sizeof(mtime_str_nice)); debugf(DBG_LEVEL_EXTALL, KCYN"send_request_size: mtime=[%s]", mtime_str_nice); get_timespec_as_str(&(de->ctime), ctime_str_nice, sizeof(ctime_str_nice)); debugf(DBG_LEVEL_EXTALL, KCYN"send_request_size: ctime=[%s]", ctime_str_nice); char mtime_str[TIME_CHARS], atime_str[TIME_CHARS], ctime_str[TIME_CHARS]; char string_float[TIME_CHARS]; snprintf(mtime_str, TIME_CHARS, "%lu.%lu", de->mtime.tv_sec, de->mtime.tv_nsec); snprintf(atime_str, TIME_CHARS, "%lu.%lu", de->atime.tv_sec, de->atime.tv_nsec); snprintf(ctime_str, TIME_CHARS, "%lu.%lu", de->ctime.tv_sec, de->ctime.tv_nsec); add_header(&headers, HEADER_TEXT_FILEPATH, orig_path); add_header(&headers, HEADER_TEXT_MTIME, mtime_str); add_header(&headers, HEADER_TEXT_ATIME, atime_str); add_header(&headers, HEADER_TEXT_CTIME, ctime_str); add_header(&headers, HEADER_TEXT_MTIME_DISPLAY, mtime_str_nice); add_header(&headers, HEADER_TEXT_ATIME_DISPLAY, atime_str_nice); add_header(&headers, HEADER_TEXT_CTIME_DISPLAY, ctime_str_nice); char gid_str[INT_CHAR_LEN], uid_str[INT_CHAR_LEN], chmod_str[INT_CHAR_LEN]; snprintf(gid_str, INT_CHAR_LEN, "%d", de->gid); snprintf(uid_str, INT_CHAR_LEN, "%d", de->uid); snprintf(chmod_str, INT_CHAR_LEN, "%d", de->chmod); add_header(&headers, HEADER_TEXT_GID, gid_str); add_header(&headers, HEADER_TEXT_UID, uid_str); add_header(&headers, HEADER_TEXT_CHMOD, chmod_str); } else debugf(DBG_LEVEL_EXTALL, "send_request_size: not setting utimes (%s)", orig_path); } if (!strcasecmp(method, "MKDIR")) { curl_easy_setopt(curl, CURLOPT_UPLOAD, 1); curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0); add_header(&headers, "Content-Type", "application/directory"); } else if (!strcasecmp(method, "MKLINK") && fp) { rewind(fp); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1); curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size); curl_easy_setopt(curl, CURLOPT_READDATA, fp); add_header(&headers, "Content-Type", "application/link"); } else if (!strcasecmp(method, "PUT")) { //http://blog.chmouel.com/2012/02/06/anatomy-of-a-swift-put-query-to-object-server/ debugf(DBG_LEVEL_EXT, "send_request_size: PUT (%s)", orig_path); curl_easy_setopt(curl, CURLOPT_UPLOAD, 1); if (fp) { curl_easy_setopt(curl, CURLOPT_INFILESIZE, file_size); curl_easy_setopt(curl, CURLOPT_READDATA, fp); } else curl_easy_setopt(curl, CURLOPT_INFILESIZE, 0); if (is_segment) curl_easy_setopt(curl, CURLOPT_READFUNCTION, read_callback); //enable progress reporting //http://curl.haxx.se/libcurl/c/progressfunc.html struct curl_progress prog; prog.lastruntime = 0; prog.curl = curl; curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); /* pass the struct pointer into the progress function */ curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog); //get the response for debug purposes /* send all data to this function */ curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc_callback); /* we pass our 'chunk' struct to the callback function */ curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void*)&chunk); } else if (!strcasecmp(method, "GET")) { if (is_segment) { debugf(DBG_LEVEL_EXT, "send_request_size: GET SEGMENT (%s)", orig_path); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_callback); curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); } else if (fp) { debugf(DBG_LEVEL_EXT, "send_request_size: GET FP (%s)", orig_path); rewind(fp); // make sure the file is ready for a-writin' fflush(fp); if (ftruncate(fileno(fp), 0) < 0) { debugf(DBG_LEVEL_NORM, KRED"ftruncate failed. I don't know what to do about that."); abort(); } curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_get_meta_dispatch); // sample by UThreadCurl.cpp, https://bitbucket.org/pamungkas5/bcbcurl/src // and http://www.codeproject.com/Articles/838366/BCBCurl-a-LibCurl-based-download-manager curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)de); struct curl_progress prog; prog.lastruntime = 0; prog.curl = curl; curl_easy_setopt(curl, CURLOPT_PROGRESSFUNCTION, progress_callback); curl_easy_setopt(curl, CURLOPT_PROGRESSDATA, &prog); } else if (xmlctx) { debugf(DBG_LEVEL_EXT, "send_request_size: GET XML (%s)", orig_path); curl_easy_setopt(curl, CURLOPT_WRITEDATA, xmlctx); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, &xml_dispatch); } else { //asumming retrieval of headers only debugf(DBG_LEVEL_EXT, "send_request_size: GET HEADERS only(%s)"); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_get_meta_dispatch); curl_easy_setopt(curl, CURLOPT_HEADERDATA, (void*)de); curl_easy_setopt(curl, CURLOPT_NOBODY, 1); } } else { debugf(DBG_LEVEL_EXT, "send_request_size: catch_all (%s)"); // this posts an HEAD request (e.g. for statfs) curl_easy_setopt(curl, CURLOPT_CUSTOMREQUEST, method); curl_easy_setopt(curl, CURLOPT_HEADERFUNCTION, &header_dispatch); } /* add the headers from extra_headers if any */ curl_slist* extra; for (extra = extra_headers; extra; extra = extra->next) { debugf(DBG_LEVEL_EXT, "adding header: %s", extra->data); headers = curl_slist_append(headers, extra->data); } curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); debugf(DBG_LEVEL_EXT, "status: send_request_size(%s) started HTTP REQ:%s", orig_path, url); curl_easy_perform(curl); double total_time; char* effective_url; curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response); curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &effective_url); curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &total_time); debugf(DBG_LEVEL_EXT, "status: send_request_size(%s) completed HTTP REQ:%s total_time=%.1f seconds", orig_path, effective_url, total_time); curl_slist_free_all(headers); curl_easy_reset(curl); return_connection(curl); if (response != 404 && (response >= 400 || response < 200)) { /* Now, our chunk.memory points to a memory block that is chunk.size bytes big and contains the remote file. */ debugf(DBG_LEVEL_NORM, KRED"send_request_size: error message, size=%lu, [HTTP %d] (%s)(%s)", (long)chunk.size, response, method, path); debugf(DBG_LEVEL_NORM, KRED"send_request_size: error message=[%s]", chunk.memory); } free(chunk.memory); if ((response >= 200 && response < 400) || (!strcasecmp(method, "DELETE") && response == 409)) { debugf(DBG_LEVEL_NORM, "exit 0: send_request_size(%s) speed=%.1f sec "KCYN"(%s) "KGRN"[HTTP OK]", orig_path, total_time, method); return response; } //handle cases when file is not found, no point in retrying, will exit if (response == 404) { debugf(DBG_LEVEL_NORM, "send_request_size: not found error for (%s)(%s), ignored "KYEL"[HTTP 404].", method, path); return response; } else { debugf(DBG_LEVEL_NORM, "send_request_size: httpcode=%d (%s)(%s), retrying "KRED"[HTTP ERR]", response, method, path); //todo: try to list response content for debug purposes sleep(8 << tries); // backoff } if (response == 401 && !cloudfs_connect()) { // re-authenticate on 401s debugf(DBG_LEVEL_NORM, KYEL"exit 1: send_request_size(%s) (%s) [HTTP REAUTH]", path, method); return response; } if (xmlctx) xmlCtxtResetPush(xmlctx, NULL, 0, NULL, NULL); } debugf(DBG_LEVEL_NORM, "exit 2: send_request_size(%s)"KCYN"(%s) response=%d", path, method, response); return response; } int send_request(char* method, const char* path, FILE* fp, xmlParserCtxtPtr xmlctx, curl_slist* extra_headers, dir_entry* de_cached_entry, const char* unencoded_path) { long flen = 0; if (fp) { // if we don't flush the size will probably be zero fflush(fp); flen = cloudfs_file_size(fileno(fp)); } return send_request_size(method, path, fp, xmlctx, extra_headers, flen, 0, de_cached_entry, unencoded_path); } //thread that downloads or uploads large file segments void* upload_segment(void* seginfo) { struct segment_info* info = (struct segment_info*)seginfo; char seg_path[MAX_URL_SIZE] = { 0 }; //set pointer to the segment start index in the complete large file (several threads will write to same large file) fseek(info->fp, info->part * info->segment_size, SEEK_SET); setvbuf(info->fp, NULL, _IOFBF, DISK_BUFF_SIZE); snprintf(seg_path, MAX_URL_SIZE, "%s%08i", info->seg_base, info->part); char* encoded = curl_escape(seg_path, 0); debugf(DBG_LEVEL_EXT, KCYN"upload_segment(%s) part=%d size=%d seg_size=%d %s", info->method, info->part, info->size, info->segment_size, seg_path); int response = send_request_size(info->method, encoded, info, NULL, NULL, info->size, 1, NULL, seg_path); if (!(response >= 200 && response < 300)) fprintf(stderr, "Segment upload %s failed with response %d", seg_path, response); curl_free(encoded); fclose(info->fp); pthread_exit(NULL); } // segment_size is the globabl config variable and size_of_segment is local //TODO: return whether the upload/download failed or not void run_segment_threads(const char* method, int segments, int full_segments, int remaining, FILE* fp, char* seg_base, int size_of_segments) { debugf(DBG_LEVEL_EXT, "run_segment_threads(%s)", method); char file_path[PATH_MAX] = { 0 }; struct segment_info* info = (struct segment_info*) malloc(segments * sizeof(struct segment_info)); pthread_t* threads = (pthread_t*)malloc(segments * sizeof(pthread_t)); #ifdef __linux__ snprintf(file_path, PATH_MAX, "/proc/self/fd/%d", fileno(fp)); debugf(DBG_LEVEL_NORM, "On run segment filepath=%s", file_path); #else //TODO: I haven't actually tested this if (fcntl(fileno(fp), F_GETPATH, file_path) == -1) fprintf(stderr, "couldn't get the path name\n"); #endif int i, ret; for (i = 0; i < segments; i++) { info[i].method = method; info[i].fp = fopen(file_path, method[0] == 'G' ? "r+" : "r"); info[i].part = i; info[i].segment_size = size_of_segments; info[i].size = i < full_segments ? size_of_segments : remaining; info[i].seg_base = seg_base; pthread_create(&threads[i], NULL, upload_segment, (void*) & (info[i])); } for (i = 0; i < segments; i++) { if ((ret = pthread_join(threads[i], NULL)) != 0) fprintf(stderr, "error waiting for thread %d, status = %d\n", i, ret); } free(info); free(threads); debugf(DBG_LEVEL_EXT, "exit: run_segment_threads(%s)", method); } void split_path(const char* path, char* seg_base, char* container, char* object) { char* string = strdup(path); snprintf(seg_base, MAX_URL_SIZE, "%s", strsep(&string, "/")); strncat(container, strsep(&string, "/"), MAX_URL_SIZE - strnlen(container, MAX_URL_SIZE)); char* _object = strsep(&string, "/"); char* remstr; while (remstr = strsep(&string, "/")) { strncat(container, "/", MAX_URL_SIZE - strnlen(container, MAX_URL_SIZE)); strncat(container, _object, MAX_URL_SIZE - strnlen(container, MAX_URL_SIZE)); _object = remstr; } //fixed: when removing root folders this will generate a segfault //issue #83, https://github.com/TurboGit/hubicfuse/issues/83 if (_object == NULL) _object = object; else strncpy(object, _object, MAX_URL_SIZE); free(string); } //checks on the cloud if this file (seg_path) have an associated segment folder int internal_is_segmented(const char* seg_path, const char* object, const char* parent_path) { debugf(DBG_LEVEL_EXT, "internal_is_segmented(%s)", seg_path); //try to avoid an additional http request for small files bool potentially_segmented; dir_entry* de = check_path_info(parent_path); if (!de) { //when files in folders are first loaded the path will not be yet in cache, so need //to force segment meta download for segmented files potentially_segmented = true; } else { //potentially segmented, assumption is that 0 size files are potentially segmented //while size>0 is for sure not segmented, so no point in making an expensive HTTP GET call potentially_segmented = (de->size == 0 && !de->isdir) ? true : false; } debugf(DBG_LEVEL_EXT, "internal_is_segmented: potentially segmented=%d", potentially_segmented); dir_entry* seg_dir; if (potentially_segmented && cloudfs_list_directory(seg_path, &seg_dir)) { if (seg_dir && seg_dir->isdir) { do { if (!strncmp(seg_dir->name, object, MAX_URL_SIZE)) { debugf(DBG_LEVEL_EXT, "exit 0: internal_is_segmented(%s) "KGRN"TRUE", seg_path); return 1; } } while ((seg_dir = seg_dir->next)); } } debugf(DBG_LEVEL_EXT, "exit 1: internal_is_segmented(%s) "KYEL"FALSE", seg_path); return 0; } int is_segmented(const char* path) { debugf(DBG_LEVEL_EXT, "is_segmented(%s)", path); char container[MAX_URL_SIZE] = { 0 }; char object[MAX_URL_SIZE] = { 0 }; char seg_base[MAX_URL_SIZE] = { 0 }; split_path(path, seg_base, container, object); char seg_path[MAX_URL_SIZE]; snprintf(seg_path, MAX_URL_SIZE, "%s/%s_segments", seg_base, container); return internal_is_segmented(seg_path, object, path); } //returns segmented file properties by parsing and retrieving the folder structure on the cloud //added totalsize as parameter to return the file size on list directory for segmented files //old implementation returns file size=0 (issue #91) int format_segments(const char* path, char* seg_base, long* segments, long* full_segments, long* remaining, long* size_of_segments, long* total_size) { debugf(DBG_LEVEL_EXT, "format_segments(%s)", path); char container[MAX_URL_SIZE] = ""; char object[MAX_URL_SIZE] = ""; split_path(path, seg_base, container, object); char seg_path[MAX_URL_SIZE]; snprintf(seg_path, MAX_URL_SIZE, "%s/%s_segments", seg_base, container); if (internal_is_segmented(seg_path, object, path)) { char manifest[MAX_URL_SIZE]; dir_entry* seg_dir; snprintf(manifest, MAX_URL_SIZE, "%s/%s", seg_path, object); debugf(DBG_LEVEL_EXT, KMAG"format_segments manifest(%s)", manifest); if (!cloudfs_list_directory(manifest, &seg_dir)) { debugf(DBG_LEVEL_EXT, "exit 0: format_segments(%s)", path); return 0; } // snprintf seesaw between manifest and seg_path to get // the total_size and the segment size as well as the actual objects char* timestamp = seg_dir->name; snprintf(seg_path, MAX_URL_SIZE, "%s/%s", manifest, timestamp); debugf(DBG_LEVEL_EXT, KMAG"format_segments seg_path(%s)", seg_path); if (!cloudfs_list_directory(seg_path, &seg_dir)) { debugf(DBG_LEVEL_EXT, "exit 1: format_segments(%s)", path); return 0; } char* str_size = seg_dir->name; snprintf(manifest, MAX_URL_SIZE, "%s/%s", seg_path, str_size); debugf(DBG_LEVEL_EXT, KMAG"format_segments manifest2(%s) size=%s", manifest, str_size); if (!cloudfs_list_directory(manifest, &seg_dir)) { debugf(DBG_LEVEL_EXT, "exit 2: format_segments(%s)", path); return 0; } //following folder name actually represents the parent file size char* str_segment = seg_dir->name; snprintf(seg_path, MAX_URL_SIZE, "%s/%s", manifest, str_segment); debugf(DBG_LEVEL_EXT, KMAG"format_segments seg_path2(%s)", seg_path); //here is where we get a list with all segment files composing the parent large file if (!cloudfs_list_directory(seg_path, &seg_dir)) { debugf(DBG_LEVEL_EXT, "exit 3: format_segments(%s)", path); return 0; } *total_size = strtoll(str_size, NULL, 10); *size_of_segments = strtoll(str_segment, NULL, 10); *remaining = *total_size % *size_of_segments; *full_segments = *total_size / *size_of_segments; *segments = *full_segments + (*remaining > 0); snprintf(manifest, MAX_URL_SIZE, "%s_segments/%s/%s/%s/%s/", container, object, timestamp, str_size, str_segment); char tmp[MAX_URL_SIZE]; strncpy(tmp, seg_base, MAX_URL_SIZE); snprintf(seg_base, MAX_URL_SIZE, "%s/%s", tmp, manifest); debugf(DBG_LEVEL_EXT, KMAG"format_segments seg_base(%s)", seg_base); debugf(DBG_LEVEL_EXT, KMAG"exit 4: format_segments(%s) total=%d size_of_segments=%d remaining=%d, full_segments=%d segments=%d", path, &total_size, &size_of_segments, &remaining, &full_segments, &segments); return 1; } else { debugf(DBG_LEVEL_EXT, KMAG"exit 5: format_segments(%s) not segmented?", path); return 0; } } /* Public interface */ void cloudfs_init() { LIBXML_TEST_VERSION xmlXPathInit(); curl_global_init(CURL_GLOBAL_ALL); pthread_mutex_init(&pool_mut, NULL); curl_version_info_data* cvid = curl_version_info(CURLVERSION_NOW); // CentOS/RHEL 5 get stupid mode, because they have a broken libcurl if (cvid->version_num == RHEL5_LIBCURL_VERSION) { debugf(DBG_LEVEL_NORM, "RHEL5 mode enabled."); rhel5_mode = 1; } if (!strncasecmp(cvid->ssl_version, "openssl", 7)) { #ifdef HAVE_OPENSSL int i; ssl_lockarray = (pthread_mutex_t*)OPENSSL_malloc(CRYPTO_num_locks() * sizeof(pthread_mutex_t)); for (i = 0; i < CRYPTO_num_locks(); i++) pthread_mutex_init(&(ssl_lockarray[i]), NULL); CRYPTO_set_id_callback((unsigned long (*)())thread_id); CRYPTO_set_locking_callback((void (*)())lock_callback); #endif } else if (!strncasecmp(cvid->ssl_version, "nss", 3)) { // allow https to continue working after forking (for RHEL/CentOS 6) setenv("NSS_STRICT_NOFORK", "DISABLED", 1); } } void cloudfs_free() { debugf(DBG_LEVEL_EXT, "Destroy mutex"); pthread_mutex_destroy(&pool_mut); int n; for (n = 0; n < curl_pool_count; ++n) { debugf(DBG_LEVEL_EXT, "Cleaning curl conn %d", n); curl_easy_cleanup(curl_pool[n]); } } int file_is_readable(const char* fname) { FILE* file; if ( file = fopen( fname, "r" ) ) { fclose( file ); return 1; } return 0; } const char* get_file_mimetype ( const char* path ) { if ( file_is_readable( path ) == 1 ) { magic_t magic; const char* mime; magic = magic_open( MAGIC_MIME_TYPE ); magic_load( magic, NULL ); magic_compile( magic, NULL ); mime = magic_file( magic, path ); magic_close( magic ); return mime; } const char* error = "application/octet-stream"; return error; } int cloudfs_object_read_fp(const char* path, FILE* fp) { debugf(DBG_LEVEL_EXT, "cloudfs_object_read_fp(%s)", path); long flen; fflush(fp); const char* filemimetype = get_file_mimetype( path ); // determine the size of the file and segment if it is above the threshhold fseek(fp, 0, SEEK_END); flen = ftell(fp); // delete the previously uploaded segments if (is_segmented(path)) { if (!cloudfs_delete_object(path)) debugf(DBG_LEVEL_NORM, KRED"cloudfs_object_read_fp: couldn't delete existing file"); else debugf(DBG_LEVEL_EXT, KYEL"cloudfs_object_read_fp: deleted existing file"); } struct timespec now; if (flen >= segment_above) { int i; long remaining = flen % segment_size; int full_segments = flen / segment_size; int segments = full_segments + (remaining > 0); // The best we can do here is to get the current time that way tools that // use the mtime can at least check if the file was changing after now clock_gettime(CLOCK_REALTIME, &now); char string_float[TIME_CHARS]; snprintf(string_float, TIME_CHARS, "%lu.%lu", now.tv_sec, now.tv_nsec); char meta_mtime[TIME_CHARS]; snprintf(meta_mtime, TIME_CHARS, "%f", atof(string_float)); char seg_base[MAX_URL_SIZE] = ""; char container[MAX_URL_SIZE] = ""; char object[MAX_URL_SIZE] = ""; split_path(path, seg_base, container, object); char manifest[MAX_URL_SIZE]; snprintf(manifest, MAX_URL_SIZE, "%s_segments", container); // create the segments container cloudfs_create_directory(manifest); // reusing manifest // TODO: check how addition of meta_mtime in manifest impacts utimens implementation snprintf(manifest, MAX_URL_SIZE, "%s_segments/%s/%s/%ld/%ld/", container, object, meta_mtime, flen, segment_size); char tmp[MAX_URL_SIZE]; strncpy(tmp, seg_base, MAX_URL_SIZE); snprintf(seg_base, MAX_URL_SIZE, "%s/%s", tmp, manifest); run_segment_threads("PUT", segments, full_segments, remaining, fp, seg_base, segment_size); char* encoded = curl_escape(path, 0); curl_slist* headers = NULL; add_header(&headers, "x-object-manifest", manifest); add_header(&headers, "Content-Length", "0"); add_header(&headers, "Content-Type", filemimetype); int response = send_request_size("PUT", encoded, NULL, NULL, headers, 0, 0, NULL, path); curl_slist_free_all(headers); curl_free(encoded); debugf(DBG_LEVEL_EXT, "exit 0: cloudfs_object_read_fp(%s) uploaded ok, response=%d", path, response); return (response >= 200 && response < 300); } else { // assume enters here when file is composed of only one segment (small files) debugf(DBG_LEVEL_EXT, "cloudfs_object_read_fp(%s) "KYEL"unknown state", path); } rewind(fp); char* encoded = curl_escape(path, 0); dir_entry* de = path_info(path); if (!de) debugf(DBG_LEVEL_EXT, "cloudfs_object_read_fp(%s) not in cache", path); else debugf(DBG_LEVEL_EXT, "cloudfs_object_read_fp(%s) found in cache", path); int response = send_request("PUT", encoded, fp, NULL, NULL, NULL, path); curl_free(encoded); debugf(DBG_LEVEL_EXT, "exit 1: cloudfs_object_read_fp(%s)", path); return (response >= 200 && response < 300); } //write file downloaded from cloud to local file int cloudfs_object_write_fp(const char* path, FILE* fp) { debugf(DBG_LEVEL_EXT, "cloudfs_object_write_fp(%s)", path); char* encoded = curl_escape(path, 0); char seg_base[MAX_URL_SIZE] = ""; long segments; long full_segments; long remaining; long size_of_segments; long total_size; //checks if this file is a segmented one if (format_segments(path, seg_base, &segments, &full_segments, &remaining, &size_of_segments, &total_size)) { rewind(fp); fflush(fp); if (ftruncate(fileno(fp), 0) < 0) { debugf(DBG_LEVEL_NORM, KRED"ftruncate failed. I don't know what to do about that."); abort(); } run_segment_threads("GET", segments, full_segments, remaining, fp, seg_base, size_of_segments); debugf(DBG_LEVEL_EXT, "exit 0: cloudfs_object_write_fp(%s)", path); return 1; } int response = send_request("GET", encoded, fp, NULL, NULL, NULL, path); curl_free(encoded); fflush(fp); if ((response >= 200 && response < 300) || ftruncate(fileno(fp), 0)) { debugf(DBG_LEVEL_EXT, "exit 1: cloudfs_object_write_fp(%s)", path); return 1; } rewind(fp); debugf(DBG_LEVEL_EXT, "exit 2: cloudfs_object_write_fp(%s)", path); return 0; } int cloudfs_object_truncate(const char* path, off_t size) { char* encoded = curl_escape(path, 0); int response; if (size == 0) { FILE* fp = fopen("/dev/null", "r"); response = send_request("PUT", encoded, fp, NULL, NULL, NULL, path); fclose(fp); } else { //TODO: this is busted response = send_request("GET", encoded, NULL, NULL, NULL, NULL, path); } curl_free(encoded); return (response >= 200 && response < 300); } //get metadata from cloud, like time attribs. create new entry if not cached yet. void get_file_metadata(dir_entry* de) { if (de->size == 0 && !de->isdir && !de->metadata_downloaded) { //this can be a potential segmented file, try to read segments size debugf(DBG_LEVEL_EXT, KMAG"ZERO size file=%s", de->full_name); char seg_base[MAX_URL_SIZE] = ""; long segments; long full_segments; long remaining; long size_of_segments; long total_size; if (format_segments(de->full_name, seg_base, &segments, &full_segments, &remaining, &size_of_segments, &total_size)) de->size = total_size; } if (option_get_extended_metadata) { debugf(DBG_LEVEL_EXT, KCYN "get_file_metadata(%s)", de->full_name); //retrieve additional file metadata with a quick HEAD query char* encoded = curl_escape(de->full_name, 0); de->metadata_downloaded = true; int response = send_request("GET", encoded, NULL, NULL, NULL, de, de->full_name); curl_free(encoded); debugf(DBG_LEVEL_EXT, KCYN "exit: get_file_metadata(%s)", de->full_name); } return; } //get list of folders from cloud // return 1 for OK, 0 for error int cloudfs_list_directory(const char* path, dir_entry** dir_list) { debugf(DBG_LEVEL_EXT, "cloudfs_list_directory(%s)", path); char container[MAX_PATH_SIZE * 3] = ""; char object[MAX_PATH_SIZE] = ""; char last_subdir[MAX_PATH_SIZE] = ""; int prefix_length = 0; int response = 0; int retval = 0; int entry_count = 0; *dir_list = NULL; xmlNode* onode = NULL, *anode = NULL, *text_node = NULL; xmlParserCtxtPtr xmlctx = xmlCreatePushParserCtxt(NULL, NULL, "", 0, NULL); if (!strcmp(path, "") || !strcmp(path, "/")) { path = ""; strncpy(container, "/?format=xml", sizeof(container)); } else { sscanf(path, "/%[^/]/%[^\n]", container, object); char* encoded_container = curl_escape(container, 0); char* encoded_object = curl_escape(object, 0); // The empty path doesn't get a trailing slash, everything else does char* trailing_slash; prefix_length = strlen(object); if (object[0] == 0) trailing_slash = ""; else { trailing_slash = "/"; prefix_length++; } snprintf(container, sizeof(container), "%s?format=xml&delimiter=/&prefix=%s%s", encoded_container, encoded_object, trailing_slash); curl_free(encoded_container); curl_free(encoded_object); } if ((!strcmp(path, "") || !strcmp(path, "/")) && *override_storage_url) response = 404; else { // this was generating 404 err on non segmented files (small files) response = send_request("GET", container, NULL, xmlctx, NULL, NULL, path); } if (response >= 200 && response < 300) xmlParseChunk(xmlctx, "", 0, 1); if (response >= 200 && response < 300 && xmlctx->wellFormed ) { xmlNode* root_element = xmlDocGetRootElement(xmlctx->myDoc); for (onode = root_element->children; onode; onode = onode->next) { if (onode->type != XML_ELEMENT_NODE) continue; char is_object = !strcasecmp((const char*)onode->name, "object"); char is_container = !strcasecmp((const char*)onode->name, "container"); char is_subdir = !strcasecmp((const char*)onode->name, "subdir"); if (is_object || is_container || is_subdir) { entry_count++; dir_entry* de = init_dir_entry(); // useful docs on nodes here: http://developer.openstack.org/api-ref-objectstorage-v1.html if (is_container || is_subdir) de->content_type = strdup("application/directory"); for (anode = onode->children; anode; anode = anode->next) { char* content = "<?!?>"; for (text_node = anode->children; text_node; text_node = text_node->next) { if (text_node->type == XML_TEXT_NODE) { content = (char*)text_node->content; //debugf(DBG_LEVEL_NORM, "List dir anode=%s content=%s", (const char *)anode->name, content); } else { //debugf(DBG_LEVEL_NORM, "List dir anode=%s", (const char *)anode->name); } } if (!strcasecmp((const char*)anode->name, "name")) { de->name = strdup(content + prefix_length); // Remove trailing slash char* slash = strrchr(de->name, '/'); if (slash && (0 == *(slash + 1))) *slash = 0; if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0) de->full_name = NULL; } if (!strcasecmp((const char*)anode->name, "bytes")) de->size = strtoll(content, NULL, 10); if (!strcasecmp((const char*)anode->name, "content_type")) { de->content_type = strdup(content); char* semicolon = strchr(de->content_type, ';'); if (semicolon) *semicolon = '\0'; } if (!strcasecmp((const char*)anode->name, "hash")) de->md5sum = strdup(content); if (!strcasecmp((const char*)anode->name, "last_modified")) { time_t last_modified_t = get_time_from_str_as_gmt(content); char local_time_str[64]; time_t local_time_t = get_time_as_local(last_modified_t, local_time_str, sizeof(local_time_str)); de->last_modified = local_time_t; de->ctime.tv_sec = local_time_t; de->ctime.tv_nsec = 0; //initialise all fields with hubic last modified date in case the file does not have extended attributes set de->mtime.tv_sec = local_time_t; de->mtime.tv_nsec = 0; de->atime.tv_sec = local_time_t; de->atime.tv_nsec = 0; //todo: how can we retrieve and set nanoseconds, are stored by hubic? } } de->isdir = de->content_type && ((strstr(de->content_type, "application/folder") != NULL) || (strstr(de->content_type, "application/directory") != NULL)); de->islink = de->content_type && ((strstr(de->content_type, "application/link") != NULL)); if (de->isdir) { //i guess this will remove a dir_entry from cache if is there already if (!strncasecmp(de->name, last_subdir, sizeof(last_subdir))) { //todo: check why is needed and if memory is freed properly, seems to generate many missed delete operations //cloudfs_free_dir_list(de); debugf(DBG_LEVEL_EXT, "cloudfs_list_directory: "KYEL"ignore "KNRM"cloudfs_free_dir_list(%s) command", de->name); continue; } strncpy(last_subdir, de->name, sizeof(last_subdir)); } de->next = *dir_list; *dir_list = de; char time_str[TIME_CHARS] = { 0 }; get_timespec_as_str(&(de->mtime), time_str, sizeof(time_str)); debugf(DBG_LEVEL_EXT, KCYN"new dir_entry %s size=%d %s dir=%d lnk=%d mod=[%s]", de->full_name, de->size, de->content_type, de->isdir, de->islink, time_str); } else debugf(DBG_LEVEL_EXT, "unknown element: %s", onode->name); } retval = 1; } else if ((!strcmp(path, "") || !strcmp(path, "/")) && *override_storage_url) { entry_count = 1; debugf(DBG_LEVEL_NORM, "Init cache entry container=[%s]", public_container); dir_entry* de = init_dir_entry(); de->name = strdup(public_container); struct tm last_modified; //todo: check what this default time means? strptime("1388434648.01238", "%FT%T", &last_modified); de->last_modified = mktime(&last_modified); de->content_type = strdup("application/directory"); if (asprintf(&(de->full_name), "%s/%s", path, de->name) < 0) de->full_name = NULL; de->isdir = 1; de->islink = 0; de->size = 4096; de->next = *dir_list; *dir_list = de; retval = 1; } xmlFreeDoc(xmlctx->myDoc); xmlFreeParserCtxt(xmlctx); debugf(DBG_LEVEL_EXT, "exit: cloudfs_list_directory(%s)", path); return retval; } int cloudfs_delete_object(const char* path) { debugf(DBG_LEVEL_EXT, "cloudfs_delete_object(%s)", path); char seg_base[MAX_URL_SIZE] = ""; long segments; long full_segments; long remaining; long size_of_segments; long total_size; if (format_segments(path, seg_base, &segments, &full_segments, &remaining, &size_of_segments, &total_size)) { int response; int i; char seg_path[MAX_URL_SIZE] = ""; for (i = 0; i < segments; i++) { snprintf(seg_path, MAX_URL_SIZE, "%s%08i", seg_base, i); char* encoded = curl_escape(seg_path, 0); response = send_request("DELETE", encoded, NULL, NULL, NULL, NULL, seg_path); if (response < 200 || response >= 300) { debugf(DBG_LEVEL_EXT, "exit 1: cloudfs_delete_object(%s) response=%d", path, response); return 0; } } } char* encoded = curl_escape(path, 0); int response = send_request("DELETE", encoded, NULL, NULL, NULL, NULL, path); curl_free(encoded); int ret = (response >= 200 && response < 300); debugf(DBG_LEVEL_EXT, "status: cloudfs_delete_object(%s) response=%d", path, response); if (response == 409) { debugf(DBG_LEVEL_EXT, "status: cloudfs_delete_object(%s) NOT EMPTY", path); ret = -1; } return ret; } //fixme: this op does not preserve src attributes (e.g. will make rsync not work well) // https://ask.openstack.org/en/question/14307/is-there-a-way-to-moverename-an-object/ // this operation also causes an HTTP 400 error if X-Object-Meta-FilePath value is larger than 256 chars int cloudfs_copy_object(const char* src, const char* dst) { debugf(DBG_LEVEL_EXT, "cloudfs_copy_object(%s, %s) lensrc=%d, lendst=%d", src, dst, strlen(src), strlen(dst)); char* dst_encoded = curl_escape(dst, 0); char* src_encoded = curl_escape(src, 0); //convert encoded string (slashes are encoded as well) to encoded string with slashes char* slash; while ((slash = strstr(src_encoded, "%2F")) || (slash = strstr(src_encoded, "%2f"))) { *slash = '/'; memmove(slash + 1, slash + 3, strlen(slash + 3) + 1); } curl_slist* headers = NULL; add_header(&headers, "X-Copy-From", src_encoded); add_header(&headers, "Content-Length", "0"); //get source file entry dir_entry* de_src = check_path_info(src); if (de_src) debugf(DBG_LEVEL_EXT, "status cloudfs_copy_object(%s, %s): src file found", src, dst); else debugf(DBG_LEVEL_NORM, KRED"status cloudfs_copy_object(%s, %s): src file NOT found", src, dst); //pass src metadata so that PUT will set time attributes of the src file int response = send_request("PUT", dst_encoded, NULL, NULL, headers, de_src, dst); curl_free(dst_encoded); curl_free(src_encoded); curl_slist_free_all(headers); debugf(DBG_LEVEL_EXT, "exit: cloudfs_copy_object(%s,%s) response=%d", src, dst, response); return (response >= 200 && response < 300); } // http://developer.openstack.org/api-ref-objectstorage-v1.html#updateObjectMeta int cloudfs_update_meta(dir_entry* de) { int response = cloudfs_copy_object(de->full_name, de->full_name); return response; } //optimised with cache int cloudfs_statfs(const char* path, struct statvfs* stat) { time_t now = get_time_now(); int lapsed = now - last_stat_read_time; if (lapsed > option_cache_statfs_timeout) { //todo: check why stat head request is always set to /, why not path? int response = send_request("HEAD", "/", NULL, NULL, NULL, NULL, "/"); *stat = statcache; debugf(DBG_LEVEL_EXT, "exit: cloudfs_statfs (new recent values, was cached since %d seconds)", lapsed); last_stat_read_time = now; return (response >= 200 && response < 300); } else { debugf(DBG_LEVEL_EXT, "exit: cloudfs_statfs (old values, cached since %d seconds)", lapsed); return 1; } } int cloudfs_create_symlink(const char* src, const char* dst) { char* dst_encoded = curl_escape(dst, 0); FILE* lnk = tmpfile(); fwrite(src, 1, strlen(src), lnk); fwrite("\0", 1, 1, lnk); int response = send_request("MKLINK", dst_encoded, lnk, NULL, NULL, NULL, dst); curl_free(dst_encoded); fclose(lnk); return (response >= 200 && response < 300); } int cloudfs_create_directory(const char* path) { debugf(DBG_LEVEL_EXT, "cloudfs_create_directory(%s)", path); char* encoded = curl_escape(path, 0); int response = send_request("MKDIR", encoded, NULL, NULL, NULL, NULL, path); curl_free(encoded); debugf(DBG_LEVEL_EXT, "cloudfs_create_directory(%s) response=%d", path, response); return (response >= 200 && response < 300); } off_t cloudfs_file_size(int fd) { struct stat buf; fstat(fd, &buf); return buf.st_size; } void cloudfs_verify_ssl(int vrfy) { verify_ssl = vrfy ? 2 : 0; } void cloudfs_option_get_extended_metadata(int option) { option_get_extended_metadata = option ? true : false; } void cloudfs_option_curl_verbose(int option) { option_curl_verbose = option ? true : false; } static struct { char client_id [MAX_HEADER_SIZE]; char client_secret[MAX_HEADER_SIZE]; char refresh_token[MAX_HEADER_SIZE]; } reconnect_args; void cloudfs_set_credentials(char* client_id, char* client_secret, char* refresh_token) { strncpy(reconnect_args.client_id , client_id , sizeof(reconnect_args.client_id )); strncpy(reconnect_args.client_secret, client_secret, sizeof(reconnect_args.client_secret)); strncpy(reconnect_args.refresh_token, refresh_token, sizeof(reconnect_args.refresh_token)); } struct htmlString { char* text; size_t size; }; static size_t writefunc_string(void* contents, size_t size, size_t nmemb, void* data) { struct htmlString* mem = (struct htmlString*) data; size_t realsize = size * nmemb; mem->text = realloc(mem->text, mem->size + realsize + 1); if (mem->text == NULL) /* out of memory! */ { perror(__FILE__); exit(EXIT_FAILURE); } memcpy(&(mem->text[mem->size]), contents, realsize); mem->size += realsize; return realsize; } char* htmlStringGet(CURL* curl) { struct htmlString chunk; chunk.text = malloc(sizeof(char)); chunk.size = 0; chunk.text[0] = '\0';//added to avoid valgrind unitialised warning curl_easy_setopt(curl, CURLOPT_WRITEDATA, &chunk); do { curl_easy_perform(curl); } while (chunk.size == 0); chunk.text[chunk.size] = '\0'; return chunk.text; } /* thanks to http://devenix.wordpress.com */ char* unbase64(unsigned char* input, int length) { BIO* b64, *bmem; char* buffer = (char*)malloc(length); memset(buffer, 0, length); b64 = BIO_new(BIO_f_base64()); bmem = BIO_new_mem_buf(input, length); bmem = BIO_push(b64, bmem); BIO_set_flags(bmem, BIO_FLAGS_BASE64_NO_NL); BIO_read(bmem, buffer, length); BIO_free_all(bmem); return buffer; } int safe_json_string(json_object* jobj, char* buffer, char* name) { int result = 0; if (jobj) { json_object* o; int found; found = json_object_object_get_ex(jobj, name, &o); if (found) { strcpy (buffer, json_object_get_string(o)); result = 1; } } if (!result) debugf(DBG_LEVEL_NORM, KRED"HUBIC cannot get json field '%s'\n", name); return result; } int cloudfs_connect() { #define HUBIC_TOKEN_URL "https://api.hubic.com/oauth/token" #define HUBIC_CRED_URL "https://api.hubic.com/1.0/account/credentials" #define HUBIC_CLIENT_ID (reconnect_args.client_id) #define HUBIC_CLIENT_SECRET (reconnect_args.client_secret) #define HUBIC_REFRESH_TOKEN (reconnect_args.refresh_token) #define HUBIC_OPTIONS_SIZE 2048 long response = -1; char url[HUBIC_OPTIONS_SIZE]; char payload[HUBIC_OPTIONS_SIZE]; struct json_object* json_obj; pthread_mutex_lock(&pool_mut); debugf(DBG_LEVEL_NORM, "Authenticating... (client_id = '%s')", HUBIC_CLIENT_ID); storage_token[0] = storage_url[0] = '\0'; CURL* curl = curl_easy_init(); /* curl default options */ curl_easy_setopt(curl, CURLOPT_VERBOSE, debug); curl_easy_setopt(curl, CURLOPT_USERAGENT, USER_AGENT); curl_easy_setopt(curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, verify_ssl ? 1 : 0); curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, verify_ssl); curl_easy_setopt(curl, CURLOPT_TIMEOUT, 10); curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10); curl_easy_setopt(curl, CURLOPT_FORBID_REUSE, 1); curl_easy_setopt(curl, CURLOPT_VERBOSE, 0L); curl_easy_setopt(curl, CURLOPT_POST, 0L); curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 0); curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writefunc_string); /* Step 1 : request a token - Not needed anymore with refresh_token */ /* Step 2 : get request code - Not needed anymore with refresh_token */ /* Step 3 : get access token */ sprintf(payload, "refresh_token=%s&grant_type=refresh_token", HUBIC_REFRESH_TOKEN); curl_easy_setopt(curl, CURLOPT_URL, HUBIC_TOKEN_URL); curl_easy_setopt(curl, CURLOPT_POST, 1L); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_POSTFIELDS, payload); curl_easy_setopt(curl, CURLOPT_POSTFIELDSIZE, strlen(payload)); curl_easy_setopt(curl, CURLOPT_USERNAME, HUBIC_CLIENT_ID); curl_easy_setopt(curl, CURLOPT_PASSWORD, HUBIC_CLIENT_SECRET); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC); char* json_str = htmlStringGet(curl); json_obj = json_tokener_parse(json_str); debugf(DBG_LEVEL_NORM, "HUBIC TOKEN_URL result: '%s'\n", json_str); free(json_str); char access_token[HUBIC_OPTIONS_SIZE]; char token_type[HUBIC_OPTIONS_SIZE]; int expire_sec; int found; json_object* o; if (!safe_json_string(json_obj, access_token, "access_token")) goto error; if (!safe_json_string(json_obj, token_type, "token_type")) goto error; found = json_object_object_get_ex(json_obj, "expires_in", &o); expire_sec = json_object_get_int(o); debugf(DBG_LEVEL_NORM, "HUBIC Access token: %s\n", access_token); debugf(DBG_LEVEL_NORM, "HUBIC Token type : %s\n", token_type); debugf(DBG_LEVEL_NORM, "HUBIC Expire in : %d\n", expire_sec); /* Step 4 : request OpenStack storage URL */ curl_easy_setopt(curl, CURLOPT_URL, HUBIC_CRED_URL); curl_easy_setopt(curl, CURLOPT_POST, 0L); curl_easy_setopt(curl, CURLOPT_HEADER, 0); curl_easy_setopt(curl, CURLOPT_HTTPAUTH, CURLAUTH_NONE); /* create the Bearer authentication header */ curl_slist* headers = NULL; sprintf (payload, "Bearer %s", access_token); add_header(&headers, "Authorization", payload); curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers); char token[HUBIC_OPTIONS_SIZE]; char endpoint[HUBIC_OPTIONS_SIZE]; char expires[HUBIC_OPTIONS_SIZE]; json_str = htmlStringGet(curl); json_obj = json_tokener_parse(json_str); debugf(DBG_LEVEL_NORM, "CRED_URL result: '%s'\n", json_str); free(json_str); if (!safe_json_string(json_obj, token, "token")) goto error; if (!safe_json_string(json_obj, endpoint, "endpoint")) goto error; if (!safe_json_string(json_obj, expires, "expires")) goto error; /* set the global storage_url and storage_token, the only parameters needed for swift */ strcpy (storage_url, endpoint); strcpy (storage_token, token); curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response); curl_easy_cleanup(curl); pthread_mutex_unlock(&pool_mut); return (response >= 200 && response < 300 && storage_token[0] && storage_url[0]); error: pthread_mutex_unlock(&pool_mut); return 0; }
34.873396
127
0.659361
[ "object" ]
bb65c7faf21ebda356c04f150f898a9171bf68f7
3,525
h
C
tests/Test_Utilities/Functional_Utilities/MissionCommandTests.h
loonwerks/case-ta6-experimental-platform-OpenUxAS
2db8b04b12f34d4c43119740cd665be554e85b95
[ "NASA-1.3" ]
6
2020-09-14T09:03:30.000Z
2022-03-03T02:20:55.000Z
tests/Test_Utilities/Functional_Utilities/MissionCommandTests.h
loonwerks/case-ta6-experimental-platform-OpenUxAS
2db8b04b12f34d4c43119740cd665be554e85b95
[ "NASA-1.3" ]
3
2019-06-10T06:10:52.000Z
2020-07-21T16:10:41.000Z
tests/Test_Utilities/Functional_Utilities/MissionCommandTests.h
loonwerks/case-ta6-experimental-platform-OpenUxAS
2db8b04b12f34d4c43119740cd665be554e85b95
[ "NASA-1.3" ]
3
2021-01-12T02:42:53.000Z
2021-07-12T00:42:38.000Z
// =============================================================================== // Authors: AFRL/RQQA // Organization: Air Force Research Laboratory, Aerospace Systems Directorate, Power and Control Division // // Copyright (c) 2017 Government of the United State of America, as represented by // the Secretary of the Air Force. No copyright is claimed in the United States under // Title 17, U.S. Code. All Other Rights Reserved. // =============================================================================== /* * File: MissionCommandTests.h * Author: jon * * Created on October 23, 2018, 10:46 AM */ #ifndef MISSIONCOMMANDTESTS_H #define MISSIONCOMMANDTESTS_H #include "LoggedMessage.h" #include <string> #include <vector> #include <SQLiteCpp/Database.h> #include <SQLiteCpp/SQLiteCpp.h> #include "afrl/cmasi/MissionCommand.h" #include <iostream> #include "../GtestuxastestserviceServiceManagerStartAndRun.h" #include <algorithm> #include "XmlHelper.h" #include "DbHelper.h" #include <map> class MissionCommandTests{ public: MissionCommandTests(std::string dbLogPath) : dbHelper(dbLogPath) { //get the logged unique automation request messages auto loggedMissionCommands = dbHelper.GetLoggedMessagesByDescriptor(descriptor); for(auto loggedMessage : loggedMissionCommands) { auto lmcpObj = std::shared_ptr<avtas::lmcp::Object>(avtas::lmcp::xml::readXML(loggedMessage->GetXml())); auto missionCommandMessage = std::static_pointer_cast<afrl::cmasi::MissionCommand>(lmcpObj); timeVsMissionCommandMap[loggedMessage->GetTime()] = missionCommandMessage; } } //checks for the first waypoint must match a waypoint's number in the mission command's waypoint list bool DoesFirstWaypointMatchWaypointInWaypointList() { for(auto const& timeVsMissionCommandItem : timeVsMissionCommandMap) { bool isMatchingWaypoint = false; int64_t firstWaypointId = timeVsMissionCommandItem.second->getFirstWaypoint(); for(auto const& waypoint : timeVsMissionCommandItem.second->getWaypointList()) { if(waypoint->getNumber() == firstWaypointId) { isMatchingWaypoint = true; break; } } if(!isMatchingWaypoint){ return false; } } return true; } //checks for the CommandID must be unique to each mission command bool AreCommandIdsUnique(){ for (auto const& timeVsMissionCommandItem : timeVsMissionCommandMap){ int count = 0; for(auto const& checkedTimeVsMissionCommandItem : timeVsMissionCommandMap){ if(timeVsMissionCommandItem.second->getCommandID() == checkedTimeVsMissionCommandItem.second->getCommandID()){ count++; } if(count > 1){ return false; } } } return true; } private: //the descriptor the for this message type const std::string descriptor = afrl::cmasi::MissionCommand::Subscription; //store a map with time : uniqueAutomationReuqest? std::map<int64_t, std::shared_ptr<afrl::cmasi::MissionCommand>> timeVsMissionCommandMap; //the helper that pulls data from the db DbHelper dbHelper; }; #endif /* MISSIONCOMMANDTESTS_H */
34.223301
126
0.615887
[ "object", "vector" ]
bb676bc5c45b8ab457610013d6b90f81ed5f1896
4,825
h
C
Thirdparty/Gc/Algo/Geometry/DistanceTransform.h
ITISFoundation/osparc-iseg
6f38924120b3a3e7a0292914d2c17f24c735309b
[ "MIT" ]
32
2018-03-26T12:39:19.000Z
2022-03-22T20:54:22.000Z
Thirdparty/Gc/Algo/Geometry/DistanceTransform.h
dyollb/osparc-iseg
6f38924120b3a3e7a0292914d2c17f24c735309b
[ "MIT" ]
10
2018-04-03T15:54:22.000Z
2022-02-01T14:32:36.000Z
Thirdparty/Gc/Algo/Geometry/DistanceTransform.h
dyollb/osparc-iseg
6f38924120b3a3e7a0292914d2c17f24c735309b
[ "MIT" ]
11
2018-03-08T13:11:28.000Z
2021-02-01T10:43:39.000Z
/* This file is part of Graph Cut (Gc) combinatorial optimization library. Copyright (C) 2008-2010 Centre for Biomedical Image Analysis (CBIA) Copyright (C) 2008-2010 Ondrej Danek 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 3 of the License, or (at your option) any later version. Gc 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 Graph Cut library. If not, see <http://www.gnu.org/licenses/>. */ /** @file Distance transform algorithms. @author Ondrej Danek <ondrej.danek@gmail.com> @date 2010 */ #ifndef GC_ALGO_GEOMETRY_DISTANCETRANSFORM_H #define GC_ALGO_GEOMETRY_DISTANCETRANSFORM_H #include "../../Core.h" #include "../../Type.h" #include "../../System/Collection/Array.h" namespace Gc { namespace Algo { /** Digital geometry algorithms. */ namespace Geometry { /** Distance transform algorithms. */ namespace DistanceTransform { /** Compute distance transform of given mask using the city-block metric. The computed distance is measured in voxels, no resolution is taken into account. @param[in] mask Mask image. @param[in] zero_val Intensity value in the mask image with zero distance. Distance to the nearest \c zero_val voxel will be computed for all other voxels. @param[out] map The final distance map. The distance of \c zero_val voxels is set to zero. */ template <Size N, class DATA, class T> void GC_DLL_EXPORT CityBlock(const System::Collection::Array<N, DATA> & mask, DATA zero_val, System::Collection::Array<N, T> & map); /** Compute distance transform of given mask using the chess-board metric. The computed distance is measured in voxels, no resolution is taken into account. @param[in] mask Mask image. @param[in] zero_val Intensity value in the mask image with zero distance. Distance to the nearest \c zero_val voxel will be computed for all other voxels. @param[out] map The final distance map. The distance of \c zero_val voxels is set to zero. */ template <Size N, class DATA, class T> void GC_DLL_EXPORT ChessBoard(const System::Collection::Array<N, DATA> & mask, DATA zero_val, System::Collection::Array<N, T> & map); /** Compute local distance transform of given mask using the city-block metric. The computed distance is measured in voxels, no resolution is taken into account. @param[in] mask Mask image. @param[in] val Intensity value in the mask image for which their distance from the nearest voxel with intensity different from \c val is computed. @param[out] map The final distance map. Its size must be set before computation. The distance of voxels with intensity different from \c val is left unchanged. */ template <Size N, class DATA, class T> void GC_DLL_EXPORT CityBlockLocal(const System::Collection::Array<N, DATA> & mask, DATA val, System::Collection::Array<N, T> & map); /** Compute local distance transform of given mask using the chess-board metric. The computed distance is measured in voxels, no resolution is taken into account. @param[in] mask Mask image. @param[in] val Intensity value in the mask image for which their distance from the nearest voxel with intensity different from \c val is computed. @param[out] map The final distance map. Its size must be set before computation. The distance of voxels with intensity different from \c val is left unchanged. */ template <Size N, class DATA, class T> void GC_DLL_EXPORT ChessBoardLocal(const System::Collection::Array<N, DATA> & mask, DATA val, System::Collection::Array<N, T> & map); } // namespace DistanceTransform } // namespace Geometry } } // namespace Gc::Algo #endif
44.266055
102
0.624249
[ "geometry", "transform" ]
bb74436a85cfa49ee0904ee9371cd5b990977b13
1,787
h
C
src/ClientOSG/Client.h
ttfractal44/MechSandbox
75ac111b094ba1a93e77908048704a98afb72deb
[ "MIT" ]
null
null
null
src/ClientOSG/Client.h
ttfractal44/MechSandbox
75ac111b094ba1a93e77908048704a98afb72deb
[ "MIT" ]
null
null
null
src/ClientOSG/Client.h
ttfractal44/MechSandbox
75ac111b094ba1a93e77908048704a98afb72deb
[ "MIT" ]
null
null
null
/* * Client.h * * Created on: Feb 4, 2015 * Author: theron */ #ifndef CLIENT_H_ #define CLIENT_H_ #include <GL/glew.h> #include <SDL2/SDL.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <osgViewer/Viewer> #include <osgUtil/SceneView> #include <osg/Camera> #include <osgViewer/Renderer> #include <osgGA/TrackballManipulator> #include <osgGA/FirstPersonManipulator> #include <osgViewer/ViewerEventHandlers> #include <string> #include <assert.h> #include "CustomViewer.h" #include "Camera.h" #include "rendering.h" #include "input.h" #include "interface.h" #include "../misc/strings.h" #include "../misc/utils.h" namespace Client { extern int updateFPSInterval; extern bool printFPS; extern SDL_Window* sdlWindow; extern SDL_GLContext sdlglContext; extern GtkWidget *gtkWindow; /*extern GLuint interfaceTexture; extern GLuint interfaceShaderProgram; extern GLuint interfaceVertexArrayId; extern GLuint interfaceVertexBufferId;*/ extern GdkPixbuf *gtkWindowPixbuf; extern osgViewer::Viewer* osg_viewer; extern osg::Camera* sceneCamera; extern Camera* camera; extern osgViewer::GraphicsWindowEmbedded* osg_graphicsWindow; extern osg::Camera* interfaceCamera; extern osg::Geode* interfaceGeode; extern osg::Geometry* interfaceGeometry; extern osg::Texture2D* interfaceTexture; extern osg::Image* interfaceImage; extern osg::Group* sceneRoot; extern bool runloop; extern bool captureMouse; extern int controlStyle; extern float cameraSensitivity; extern float movementSpeed; extern int windowWidth; extern int windowHeight; //extern World::Camera* viewCamera; //extern World::Camera* controlledCamera; void initialize(); void step(); void run(); void resize(int w, int h); void setSceneData(osg::Group* scene); } /* namespace Client */ #endif /* CLIENT_H_ */
21.27381
61
0.771125
[ "geometry" ]
bb7b483f5c50611aa484e9c309d5fc5b9cde8ef7
11,500
h
C
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/net/http/ElastosHttpClient.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/net/http/ElastosHttpClient.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/Base/Core/inc/elastos/droid/net/http/ElastosHttpClient.h
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // 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. //========================================================================= #ifndef __ELASTOS_DROID_NET_HTTP_ELASTOSHTTPCLIENT_H__ #define __ELASTOS_DROID_NET_HTTP_ELASTOSHTTPCLIENT_H__ #include <Elastos.CoreLibrary.Apache.h> #include "Elastos.Droid.Net.h" #include "elastos/droid/ext/frameworkext.h" #include <elastos/core/Object.h> // TODO: Waiting for DefaultHttpClient // #include <org/apache/http/impl/client/DefaultHttpClient.h> using Elastos::Droid::Content::IContentResolver; using Elastos::Droid::Content::IContext; using Elastos::IO::IInputStream; using Org::Apache::Http::Client::IHttpClient; using Org::Apache::Http::Client::IResponseHandler; using Org::Apache::Http::Client::Methods::IHttpUriRequest; using Org::Apache::Http::Conn::IClientConnectionManager; using Org::Apache::Http::Entity::IAbstractHttpEntity; using Org::Apache::Http::IHttpEntity; using Org::Apache::Http::IHttpHost; using Org::Apache::Http::IHttpRequest; using Org::Apache::Http::IHttpRequestInterceptor; using Org::Apache::Http::IHttpResponse; // using Org::Apache::Http::Impl::Client::DefaultHttpClient; using Org::Apache::Http::Params::IHttpParams; using Org::Apache::Http::Protocol::IBasicHttpProcessor; using Org::Apache::Http::Protocol::IHttpContext; namespace Elastos { namespace Droid { namespace Net { namespace Http { /** * Implementation of the Apache {@link DefaultHttpClient} that is configured with * reasonable default settings and registered schemes for Android. * Don't create this directly, use the {@link #newInstance} factory method. * * <p>This client processes cookies but does not retain them by default. * To retain cookies, simply add a cookie store to the HttpContext:</p> * * <pre>context.setAttribute(ClientContext.COOKIE_STORE, cookieStore);</pre> */ class ElastosHttpClient : public Object , public IHttpClient , public IElastosHttpClient { private: /** * Logging tag and level. */ class LoggingConfiguration : public Object { private: LoggingConfiguration( /* [in] */ const String& tag, /* [in] */ Int32 level); /** * Returns true if logging is turned on for this configuration. */ CARAPI_(Boolean) IsLoggable(); /** * Prints a message using this configuration. */ CARAPI Println( /* [in] */ const String& message); const String TAG; const Int32 LEVEL; friend class ElastosHttpClient; }; /** * Logs cURL commands equivalent to requests. */ class CurlLogger : public Object , public IHttpRequestInterceptor { public: CAR_INTERFACE_DECL() CARAPI Process( /* [in] */ IHttpRequest* request, /* [in] */ IHttpContext* context); }; class InnerSub_HttpRequestInterceptor : public Object , public IHttpRequestInterceptor { public: CAR_INTERFACE_DECL() CARAPI Process( /* [in] */ IHttpRequest* request, /* [in] */ IHttpContext* context); }; class InnerSub_DefaultHttpClient #if 0 // TODO: Waiting for DefaultHttpClient : public DefaultHttpClient #else : public Object #endif { public: // @Override CARAPI CreateHttpProcessor( /* [out] */ IBasicHttpProcessor** processor); CARAPI CreateHttpContext( /* [out] */ IHttpContext** context); }; public: CAR_INTERFACE_DECL() ElastosHttpClient(); // @Override // finalize(); virtual ~ElastosHttpClient(); // Gzip of data shorter than this probably won't be worthwhile static CARAPI GetDEFAULT_SYNC_MIN_GZIP_BYTES( /* [out] */ Int64* result); static CARAPI SetDEFAULT_SYNC_MIN_GZIP_BYTES( /* [in] */ Int64 DEFAULT_SYNC_MIN_GZIP_BYTES); /** * Create a new HttpClient with reasonable defaults (which you can update). * * @param userAgent to report in your HTTP requests * @param context to use for caching SSL sessions (may be null for no caching) * @return AndroidHttpClient for you to use for all your requests. */ static CARAPI NewInstance( /* [in] */ const String& userAgent, /* [in] */ IContext* context, /* [out] */ IElastosHttpClient** result); /** * Create a new HttpClient with reasonable defaults (which you can update). * @param userAgent to report in your HTTP requests. * @return AndroidHttpClient for you to use for all your requests. */ static CARAPI NewInstance( /* [in] */ const String& userAgent, /* [out] */ IElastosHttpClient** result); /** * Modifies a request to indicate to the server that we would like a * gzipped response. (Uses the "Accept-Encoding" HTTP header.) * @param request the request to modify * @see #getUngzippedContent */ static CARAPI ModifyRequestToAcceptGzipResponse( /* [in] */ IHttpRequest* request); /** * Gets the input stream from a response entity. If the entity is gzipped * then this will get a stream over the uncompressed data. * * @param entity the entity whose content should be read * @return the input stream to read from * @throws IOException */ static CARAPI GetUngzippedContent( /* [in] */ IHttpEntity* entity, /* [out] */ IInputStream** result); /** * Release resources associated with this client. You must call this, * or significant resources (sockets and memory) may be leaked. */ CARAPI Close(); CARAPI GetParams( /* [out] */ IHttpParams** result); CARAPI GetConnectionManager( /* [out] */ IClientConnectionManager** result); CARAPI Execute( /* [in] */ IHttpUriRequest* request, /* [out] */ IHttpResponse** result); CARAPI Execute( /* [in] */ IHttpUriRequest* request, /* [in] */ IHttpContext* context, /* [out] */ IHttpResponse** result); CARAPI Execute( /* [in] */ IHttpHost* target, /* [in] */ IHttpRequest* request, /* [out] */ IHttpResponse** result); CARAPI Execute( /* [in] */ IHttpHost* target, /* [in] */ IHttpRequest* request, /* [in] */ IHttpContext* context, /* [out] */ IHttpResponse** result); CARAPI Execute( /* [in] */ IHttpUriRequest* request, /* [in] */ IResponseHandler* responseHandler, /* [out] */ IInterface** result); CARAPI Execute( /* [in] */ IHttpUriRequest* request, /* [in] */ IResponseHandler* responseHandler, /* [in] */ IHttpContext* context, /* [out] */ IInterface** result); CARAPI Execute( /* [in] */ IHttpHost* target, /* [in] */ IHttpRequest* request, /* [in] */ IResponseHandler* responseHandler, /* [out] */ IInterface** result); CARAPI Execute( /* [in] */ IHttpHost* target, /* [in] */ IHttpRequest* request, /* [in] */ IResponseHandler* responseHandler, /* [in] */ IHttpContext* context, /* [out] */ IInterface** result); /** * Compress data to send to server. * Creates a Http Entity holding the gzipped data. * The data will not be compressed if it is too short. * @param data The bytes to compress * @return Entity holding the data */ static CARAPI GetCompressedEntity( /* [in] */ ArrayOf<Byte>* data, /* [in] */ IContentResolver* resolver, /* [out] */ IAbstractHttpEntity** result); /** * Retrieves the minimum size for compressing data. * Shorter data will not be compressed. */ static CARAPI GetMinGzipSize( /* [in] */ IContentResolver* resolver, /* [out] */ Int64* result); /** * Enables cURL request logging for this client. * * @param name to log messages with * @param level at which to log messages (see {@link android.util.Log}) */ CARAPI EnableCurlLogging( /* [in] */ const String& name, /* [in] */ Int32 level); /** * Disables cURL logging for this client. */ CARAPI DisableCurlLogging(); /** * Returns the date of the given HTTP date string. This method can identify * and parse the date formats emitted by common HTTP servers, such as * <a href="http://www.ietf.org/rfc/rfc0822.txt">RFC 822</a>, * <a href="http://www.ietf.org/rfc/rfc0850.txt">RFC 850</a>, * <a href="http://www.ietf.org/rfc/rfc1036.txt">RFC 1036</a>, * <a href="http://www.ietf.org/rfc/rfc1123.txt">RFC 1123</a> and * <a href="http://www.opengroup.org/onlinepubs/007908799/xsh/asctime.html">ANSI * C's asctime()</a>. * * @return the number of milliseconds since Jan. 1, 1970, midnight GMT. * @throws IllegalArgumentException if {@code dateString} is not a date or * of an unsupported format. */ static CARAPI ParseDate( /* [in] */ const String& dateString, /* [out] */ Int64* result); // Gzip of data shorter than this probably won't be worthwhile static Int64 DEFAULT_SYNC_MIN_GZIP_BYTES; private: static CARAPI_(AutoPtr<ArrayOf<String> >) InitTextContentTypes(); static CARAPI_(AutoPtr<IHttpRequestInterceptor>) InitThreadCheckInterceptor(); CARAPI constructor( /* [in] */ IClientConnectionManager* ccm, /* [in] */ IHttpParams* params); CARAPI_(Boolean) IsMmsRequest(); CARAPI_(Boolean) CheckMmsOps(); CARAPI_(String) GetMethod( /* [in] */ IHttpUriRequest* request); CARAPI_(String) GetMethod( /* [in] */ IHttpRequest* request); CARAPI_(Boolean) CheckMmsSendPermission( /* [in] */ const String& method); /** * Generates a cURL command equivalent to the given request. */ static CARAPI_(String) ToCurl( /* [in] */ IHttpUriRequest* request, /* [in] */ Boolean logAuthToken); static CARAPI_(Boolean) IsBinaryContent( /* [in] */ IHttpUriRequest* request); private: // Default connection and socket timeout of 60 seconds. Tweak to taste. static const Int32 SOCKET_OPERATION_TIMEOUT; static const String TAG; static AutoPtr<ArrayOf<String> > sTextContentTypes; AutoPtr<IHttpClient> mDelegate; Boolean mLeakedException; /** cURL logging configuration. */ /* volatile */ AutoPtr<LoggingConfiguration> mCurlConfiguration; /** Interceptor throws an exception if the executing thread is blocked */ static const AutoPtr<IHttpRequestInterceptor> sThreadCheckInterceptor; }; } // namespace Http } // namespace Net } // namespace Droid } // namespace Elastos #endif // __ELASTOS_DROID_NET_HTTP_ELASTOSHTTPCLIENT_H__
31.25
84
0.631565
[ "object" ]
bb7decebd5da551131cf37658d4f1f7b66dd932f
1,784
h
C
src/thinblockbuilder.h
WestonReed/bitcoinxt
ac5b611797cb83226b7abce53cc50d48cb2a0c16
[ "MIT" ]
515
2015-01-03T03:44:52.000Z
2022-02-11T18:37:43.000Z
src/thinblockbuilder.h
WestonReed/bitcoinxt
ac5b611797cb83226b7abce53cc50d48cb2a0c16
[ "MIT" ]
427
2015-01-20T15:15:26.000Z
2020-08-31T10:48:30.000Z
src/thinblockbuilder.h
WestonReed/bitcoinxt
ac5b611797cb83226b7abce53cc50d48cb2a0c16
[ "MIT" ]
192
2015-02-15T01:23:16.000Z
2021-11-04T16:42:20.000Z
#ifndef BITCOIN_THINBLOCKBUILDER_H #define BITCOIN_THINBLOCKBUILDER_H #include "thinblock.h" #include "primitives/block.h" #include "random.h" #include <unordered_set> #include <unordered_map> #include <vector> class CTransaction; class CMerkleBlock; class XThinBlock; class IdkHasher { public: IdkHasher() : nonce(GetRand(std::numeric_limits<uint64_t>::max())) { } size_t operator()(const std::pair<uint64_t, uint64_t>& h) const { return h.first ^ h.second ^ nonce; } private: uint64_t nonce; }; // Assembles a block from it's merkle block and the individual transactions. class ThinBlockBuilder { public: ThinBlockBuilder(const CBlockHeader&, const std::vector<ThinTx>& txs, const TxFinder&); enum TXAddRes { TX_ADDED, TX_UNWANTED, TX_DUP }; TXAddRes addTransaction(const CTransaction& tx); int numTxsMissing() const; std::vector<std::pair<int, ThinTx> > getTxsMissing() const; // If builder has uint256 hashes in wantedTxs list, // this will do nothing. // // If builder has uin64_t hashes, and uint256 are provided, // they will be replaced. void replaceWantedTx(const std::vector<ThinTx>& tx); // Tries to build the block. Throws thinblock_error if it fails. // Returns the block (and invalidates this object) CBlock finishBlock(); private: CBlock thinBlock; std::vector<ThinTx> wanted; std::unordered_set<std::pair<uint64_t, uint64_t>, IdkHasher> wantedIdks; std::unordered_map<uint64_t, std::vector<ThinTx>::iterator> wantedIndex; size_t missing; void updateWantedIndex(); }; #endif
27.030303
80
0.642377
[ "object", "vector" ]
153f6c51ad77445da061b7207026df7735542bd9
61,788
h
C
tests/engines/mvtree_oid_test_data.h
xuning97/pmemkv
5b1b6c9df945272fc08eb888345113dc0c7206f5
[ "BSD-3-Clause" ]
null
null
null
tests/engines/mvtree_oid_test_data.h
xuning97/pmemkv
5b1b6c9df945272fc08eb888345113dc0c7206f5
[ "BSD-3-Clause" ]
null
null
null
tests/engines/mvtree_oid_test_data.h
xuning97/pmemkv
5b1b6c9df945272fc08eb888345113dc0c7206f5
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2017-2018, Intel Corporation * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * * Neither the name of the copyright holder 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 <vector> #include <string> class MVOidTestData { public: std::vector<std::string> items = { "n01950731_11432.JPEG", "n01950731_3712.JPEG ", "n01950731_344.JPEG", "n01950731_12614.JPEG", "n01950731_14730.JPEG", "n01950731_2425.JPEG", "n01950731_13765.JPEG", "n01950731_8413.JPEG", "n01950731_10425.JPEG", "n01950731_12448.JPEG", "n01950731_8179.JPEG", "n01950731_4601.JPEG", "n01950731_8969.JPEG", "n01950731_12933.JPEG", "n01950731_11736.JPEG", "n01950731_2016.JPEG", "n01950731_13225.JPEG", "n01950731_2268.JPEG", "n01950731_2157.JPEG", "n01950731_728.JPEG", "n01950731_12167.JPEG", "n01950731_12610.JPEG", "n01950731_5002.JPEG", "n01950731_16869.JPEG", "n01950731_7906.JPEG", "n01950731_22717.JPEG", "n01950731_15680.JPEG", "n01950731_2727.JPEG", "n01950731_16418.JPEG", "n01950731_13447.JPEG", "n01950731_12661.JPEG", "n01950731_13992.JPEG", "n01950731_14347.JPEG", "n01950731_14203.JPEG", "n01950731_22795.JPEG", "n01950731_15462.JPEG", "n01950731_12996.JPEG", "n01950731_9661.JPEG", "n01950731_4133.JPEG", "n01950731_4376.JPEG", "n01950731_10431.JPEG", "n01950731_13433.JPEG", "n01950731_13188.JPEG", "n01950731_5054.JPEG", "n01950731_2848.JPEG", "n01950731_12859.JPEG", "n01950731_19865.JPEG", "n01950731_12513.JPEG", "n01950731_16906.JPEG", "n01950731_13723.JPEG", "n01950731_12605.JPEG", "n01950731_8445.JPEG", "n01950731_23528.JPEG", "n01950731_16379.JPEG", "n01950731_15784.JPEG", "n01950731_2560.JPEG", "n01950731_3240.JPEG", "n01950731_12482.JPEG", "n01950731_16004.JPEG", "n01950731_15732.JPEG", "n01950731_16556.JPEG", "n01950731_23520.JPEG", "n01950731_17543.JPEG", "n01950731_10361.JPEG", "n01950731_15817.JPEG", "n01950731_28650.JPEG", "n01950731_10662.JPEG", "n01950731_12724.JPEG", "n01950731_28627.JPEG", "n01950731_9370.JPEG", "n01950731_12121.JPEG", "n01950731_4250.JPEG", "n01950731_21421.JPEG", "n01950731_21428.JPEG", "n01950731_13350.JPEG", "n01950731_11759.JPEG", "n01950731_8905.JPEG", "n01950731_9356.JPEG", "n01950731_11644.JPEG", "n01950731_2131.JPEG", "n01950731_21332.JPEG", "n01950731_10245.JPEG", "n01950731_8923.JPEG", "n01950731_13802.JPEG", "n01950731_13457.JPEG", "n01950731_20767.JPEG", "n01950731_9232.JPEG", "n01950731_15655.JPEG", "n01950731_13048.JPEG", "n01950731_14388.JPEG", "n01950731_171.JPEG", "n01950731_16381.JPEG", "n01950731_8291.JPEG", "n01950731_11745.JPEG", "n01950731_10150.JPEG", "n01950731_18103.JPEG", "n01950731_651.JPEG", "n01950731_1936.JPEG", "n01950731_16139.JPEG", "n01950731_13698.JPEG", "n01950731_5652.JPEG", "n01950731_3264.JPEG", "n01950731_33840.JPEG", "n01950731_15823.JPEG", "n01950731_8536.JPEG", "n01950731_11743.JPEG", "n01950731_399.JPEG", "n01950731_1638.JPEG", "n01950731_14977.JPEG", "n01950731_12745.JPEG", "n01950731_9817.JPEG", "n01950731_16398.JPEG", "n01950731_5126.JPEG", "n01950731_15796.JPEG", "n01950731_11079.JPEG", "n01950731_14091.JPEG", "n01950731_15389.JPEG", "n01950731_6654.JPEG", "n01950731_14208.JPEG", "n01950731_16103.JPEG", "n01950731_12013.JPEG", "n01950731_13563.JPEG", "n01950731_16693.JPEG", "n01950731_33114.JPEG", "n01950731_17974.JPEG", "n01950731_16544.JPEG", "n01950731_2291.JPEG", "n01950731_8517.JPEG", "n01950731_8093.JPEG", "n01950731_10695.JPEG", "n01950731_21212.JPEG", "n01950731_141.JPEG", "n01950731_17768.JPEG", "n01950731_12912.JPEG", "n01950731_23310.JPEG", "n01950731_3595.JPEG", "n01950731_4663.JPEG", "n01950731_12904.JPEG", "n01950731_10174.JPEG", "n01950731_9098.JPEG", "n01950731_18145.JPEG", "n01950731_11086.JPEG", "n01950731_1096.JPEG", "n01950731_4722.JPEG", "n01950731_16414.JPEG", "n01950731_13959.JPEG", "n01950731_21003.JPEG", "n01950731_1533.JPEG", "n01950731_17603.JPEG", "n01950731_4046.JPEG", "n01950731_15157.JPEG", "n01950731_13094.JPEG", "n01950731_4998.JPEG", "n01950731_1335.JPEG", "n01950731_20980.JPEG", "n01950731_6396.JPEG", "n01950731_22546.JPEG", "n01950731_8596.JPEG", "n01950731_4399.JPEG", "n01950731_14466.JPEG", "n01950731_6412.JPEG", "n01950731_11842.JPEG", "n01950731_14154.JPEG", "n01950731_7578.JPEG", "n01950731_10520.JPEG", "n01950731_26161.JPEG", "n01950731_13996.JPEG", "n01950731_13091.JPEG", "n01950731_12932.JPEG", "n01950731_17641.JPEG", "n01950731_6403.JPEG", "n01950731_11822.JPEG", "n01950731_17474.JPEG", "n01950731_12921.JPEG", "n01950731_7424.JPEG", "n01950731_12223.JPEG", "n01950731_2601.JPEG", "n01950731_10261.JPEG", "n01950731_9317.JPEG", "n01950731_17432.JPEG", "n01950731_6978.JPEG", "n01950731_21393.JPEG", "n01950731_9505.JPEG", "n01950731_968.JPEG", "n01950731_15621.JPEG", "n01950731_11614.JPEG", "n01950731_4152.JPEG", "n01950731_12998.JPEG", "n01950731_9951.JPEG", "n01950731_7573.JPEG", "n01950731_14574.JPEG", "n01950731_20029.JPEG", "n01950731_1180.JPEG", "n01950731_5888.JPEG", "n01950731_15052.JPEG", "n01950731_14317.JPEG", "n01950731_24023.JPEG", "n01950731_30122.JPEG", "n01950731_12205.JPEG", "n01950731_7396.JPEG", "n01950731_13243.JPEG", "b01950731_12223.JPEG", "b01950731_2601.JPEG", "b01950731_10261.JPEG", "b01950731_9317.JPEG", "b01950731_17432.JPEG", "b01950731_6978.JPEG", "b01950731_21393.JPEG", "b01950731_9505.JPEG", "b01950731_968.JPEG", "b01950731_15621.JPEG", "b01950731_11614.JPEG", "b01950731_4152.JPEG", "b01950731_12998.JPEG", "b01950731_9951.JPEG", "b01950731_7573.JPEG", "b01950731_14574.JPEG", "b01950731_20029.JPEG", "b01950731_1180.JPEG", "b01950731_5888.JPEG", "b01950731_15052.JPEG", "b01950731_14317.JPEG", "b01950731_24023.JPEG", "b01950731_30122.JPEG", "b01950731_12205.JPEG", "b01950731_7396.JPEG", "b01950731_13243.JPEG", "c01950731_12223.JPEG", "c01950731_2601.JPEG", "c01950731_10261.JPEG", "c01950731_9317.JPEG", "c01950731_17432.JPEG", "c01950731_6978.JPEG", "c01950731_21393.JPEG", "c01950731_9505.JPEG", "c01950731_968.JPEG", "c01950731_15621.JPEG", "c01950731_11614.JPEG", "c01950731_4152.JPEG", "c01950731_12998.JPEG", "c01950731_9951.JPEG", "c01950731_7573.JPEG", "c01950731_14574.JPEG", "c01950731_20029.JPEG", "c01950731_1180.JPEG", "c01950731_5888.JPEG", "c01950731_15052.JPEG", "c01950731_14317.JPEG", "c01950731_24023.JPEG", "c01950731_30122.JPEG", "c01950731_12205.JPEG", "c01950731_7396.JPEG", "c01950731_13243.JPEG", "d01950731_12223.JPEG", "d01950731_2601.JPEG", "d01950731_10261.JPEG", "d01950731_9317.JPEG", "d01950731_17432.JPEG", "d01950731_6978.JPEG", "d01950731_21393.JPEG", "d01950731_9505.JPEG", "d01950731_968.JPEG", "d01950731_15621.JPEG", "d01950731_11614.JPEG", "d01950731_4152.JPEG", "d01950731_12998.JPEG", "d01950731_9951.JPEG", "d01950731_7573.JPEG", "d01950731_14574.JPEG", "d01950731_20029.JPEG", "d01950731_1180.JPEG", "d01950731_5888.JPEG", "d01950731_15052.JPEG", "d01950731_14317.JPEG", "d01950731_24023.JPEG", "d01950731_30122.JPEG", "d01950731_12205.JPEG", "d01950731_7396.JPEG", "d01950731_13243.JPEG", "e01950731_11432.JPEG", "e01950731_3712.JPEG ", "e01950731_344.JPEG", "e01950731_12614.JPEG", "e01950731_14730.JPEG", "e01950731_2425.JPEG", "e01950731_13765.JPEG", "e01950731_8413.JPEG", "e01950731_10425.JPEG", "e01950731_12448.JPEG", "e01950731_8179.JPEG", "e01950731_4601.JPEG", "e01950731_8969.JPEG", "e01950731_12933.JPEG", "e01950731_11736.JPEG", "e01950731_2016.JPEG", "e01950731_13225.JPEG", "e01950731_2268.JPEG", "e01950731_2157.JPEG", "e01950731_728.JPEG", "e01950731_12167.JPEG", "e01950731_12610.JPEG", "e01950731_5002.JPEG", "e01950731_16869.JPEG", "e01950731_7906.JPEG", "e01950731_22717.JPEG", "e01950731_15680.JPEG", "e01950731_2727.JPEG", "e01950731_16418.JPEG", "e01950731_13447.JPEG", "e01950731_12661.JPEG", "e01950731_13992.JPEG", "e01950731_14347.JPEG", "e01950731_14203.JPEG", "e01950731_22795.JPEG", "e01950731_15462.JPEG", "e01950731_12996.JPEG", "e01950731_9661.JPEG", "e01950731_4133.JPEG", "e01950731_4376.JPEG", "e01950731_10431.JPEG", "e01950731_13433.JPEG", "e01950731_13188.JPEG", "e01950731_5054.JPEG", "e01950731_2848.JPEG", "e01950731_12859.JPEG", "e01950731_19865.JPEG", "e01950731_12513.JPEG", "e01950731_16906.JPEG", "e01950731_13723.JPEG", "e01950731_12605.JPEG", "e01950731_8445.JPEG", "e01950731_23528.JPEG", "e01950731_16379.JPEG", "e01950731_15784.JPEG", "e01950731_2560.JPEG", "e01950731_3240.JPEG", "e01950731_12482.JPEG", "e01950731_16004.JPEG", "e01950731_15732.JPEG", "e01950731_16556.JPEG", "e01950731_23520.JPEG", "e01950731_17543.JPEG", "e01950731_10361.JPEG", "e01950731_15817.JPEG", "e01950731_28650.JPEG", "e01950731_10662.JPEG", "e01950731_12724.JPEG", "e01950731_28627.JPEG", "e01950731_9370.JPEG", "e01950731_12121.JPEG", "e01950731_4250.JPEG", "e01950731_21421.JPEG", "e01950731_21428.JPEG", "e01950731_13350.JPEG", "e01950731_11759.JPEG", "e01950731_8905.JPEG", "e01950731_9356.JPEG", "e01950731_11644.JPEG", "e01950731_2131.JPEG", "e01950731_21332.JPEG", "e01950731_10245.JPEG", "e01950731_8923.JPEG", "e01950731_13802.JPEG", "e01950731_13457.JPEG", "e01950731_20767.JPEG", "e01950731_9232.JPEG", "e01950731_15655.JPEG", "e01950731_13048.JPEG", "e01950731_14388.JPEG", "e01950731_171.JPEG", "e01950731_16381.JPEG", "e01950731_8291.JPEG", "e01950731_11745.JPEG", "e01950731_10150.JPEG", "e01950731_18103.JPEG", "e01950731_651.JPEG", "e01950731_1936.JPEG", "e01950731_16139.JPEG", "e01950731_13698.JPEG", "e01950731_5652.JPEG", "e01950731_3264.JPEG", "e01950731_33840.JPEG", "e01950731_15823.JPEG", "e01950731_8536.JPEG", "e01950731_11743.JPEG", "e01950731_399.JPEG", "e01950731_1638.JPEG", "e01950731_14977.JPEG", "e01950731_12745.JPEG", "e01950731_9817.JPEG", "e01950731_16398.JPEG", "e01950731_5126.JPEG", "e01950731_15796.JPEG", "e01950731_11079.JPEG", "e01950731_14091.JPEG", "e01950731_15389.JPEG", "e01950731_6654.JPEG", "e01950731_14208.JPEG", "e01950731_16103.JPEG", "e01950731_12013.JPEG", "e01950731_13563.JPEG", "e01950731_16693.JPEG", "e01950731_33114.JPEG", "e01950731_17974.JPEG", "e01950731_16544.JPEG", "e01950731_2291.JPEG", "e01950731_8517.JPEG", "e01950731_8093.JPEG", "e01950731_10695.JPEG", "e01950731_21212.JPEG", "e01950731_141.JPEG", "e01950731_17768.JPEG", "e01950731_12912.JPEG", "e01950731_23310.JPEG", "e01950731_3595.JPEG", "e01950731_4663.JPEG", "e01950731_12904.JPEG", "e01950731_10174.JPEG", "e01950731_9098.JPEG", "e01950731_18145.JPEG", "e01950731_11086.JPEG", "e01950731_1096.JPEG", "e01950731_4722.JPEG", "e01950731_16414.JPEG", "e01950731_13959.JPEG", "e01950731_21003.JPEG", "e01950731_1533.JPEG", "e01950731_17603.JPEG", "e01950731_4046.JPEG", "e01950731_15157.JPEG", "e01950731_13094.JPEG", "e01950731_4998.JPEG", "e01950731_1335.JPEG", "e01950731_20980.JPEG", "e01950731_6396.JPEG", "e01950731_22546.JPEG", "e01950731_8596.JPEG", "e01950731_4399.JPEG", "e01950731_14466.JPEG", "e01950731_6412.JPEG", "e01950731_11842.JPEG", "e01950731_14154.JPEG", "e01950731_7578.JPEG", "e01950731_10520.JPEG", "e01950731_26161.JPEG", "e01950731_13996.JPEG", "e01950731_13091.JPEG", "e01950731_12932.JPEG", "e01950731_17641.JPEG", "e01950731_6403.JPEG", "e01950731_11822.JPEG", "e01950731_17474.JPEG", "e01950731_12921.JPEG", "e01950731_7424.JPEG", "e01950731_12223.JPEG", "e01950731_2601.JPEG", "e01950731_10261.JPEG", "e01950731_9317.JPEG", "e01950731_17432.JPEG", "e01950731_6978.JPEG", "e01950731_21393.JPEG", "e01950731_9505.JPEG", "e01950731_968.JPEG", "e01950731_15621.JPEG", "e01950731_11614.JPEG", "e01950731_4152.JPEG", "e01950731_12998.JPEG", "e01950731_9951.JPEG", "e01950731_7573.JPEG", "e01950731_14574.JPEG", "e01950731_20029.JPEG", "e01950731_1180.JPEG", "e01950731_5888.JPEG", "e01950731_15052.JPEG", "e01950731_14317.JPEG", "e01950731_24023.JPEG", "e01950731_30122.JPEG", "e01950731_12205.JPEG", "e01950731_7396.JPEG", "e01950731_13243.JPEG", "f01950731_11432.JPEG", "f01950731_3712.JPEG ", "f01950731_344.JPEG", "f01950731_12614.JPEG", "f01950731_14730.JPEG", "f01950731_2425.JPEG", "f01950731_13765.JPEG", "f01950731_8413.JPEG", "f01950731_10425.JPEG", "f01950731_12448.JPEG", "f01950731_8179.JPEG", "f01950731_4601.JPEG", "f01950731_8969.JPEG", "f01950731_12933.JPEG", "f01950731_11736.JPEG", "f01950731_2016.JPEG", "f01950731_13225.JPEG", "f01950731_2268.JPEG", "f01950731_2157.JPEG", "f01950731_728.JPEG", "f01950731_12167.JPEG", "f01950731_12610.JPEG", "f01950731_5002.JPEG", "f01950731_16869.JPEG", "f01950731_7906.JPEG", "f01950731_22717.JPEG", "f01950731_15680.JPEG", "f01950731_2727.JPEG", "f01950731_16418.JPEG", "f01950731_13447.JPEG", "f01950731_12661.JPEG", "f01950731_13992.JPEG", "f01950731_14347.JPEG", "f01950731_14203.JPEG", "f01950731_22795.JPEG", "f01950731_15462.JPEG", "f01950731_12996.JPEG", "f01950731_9661.JPEG", "f01950731_4133.JPEG", "f01950731_4376.JPEG", "f01950731_10431.JPEG", "f01950731_13433.JPEG", "f01950731_13188.JPEG", "f01950731_5054.JPEG", "f01950731_2848.JPEG", "f01950731_12859.JPEG", "f01950731_19865.JPEG", "f01950731_12513.JPEG", "f01950731_16906.JPEG", "f01950731_13723.JPEG", "f01950731_12605.JPEG", "f01950731_8445.JPEG", "f01950731_23528.JPEG", "f01950731_16379.JPEG", "f01950731_15784.JPEG", "f01950731_2560.JPEG", "f01950731_3240.JPEG", "f01950731_12482.JPEG", "f01950731_16004.JPEG", "f01950731_15732.JPEG", "f01950731_16556.JPEG", "f01950731_23520.JPEG", "f01950731_17543.JPEG", "f01950731_10361.JPEG", "f01950731_15817.JPEG", "f01950731_28650.JPEG", "f01950731_10662.JPEG", "f01950731_12724.JPEG", "f01950731_28627.JPEG", "f01950731_9370.JPEG", "f01950731_12121.JPEG", "f01950731_4250.JPEG", "f01950731_21421.JPEG", "f01950731_21428.JPEG", "f01950731_13350.JPEG", "f01950731_11759.JPEG", "f01950731_8905.JPEG", "f01950731_9356.JPEG", "f01950731_11644.JPEG", "f01950731_2131.JPEG", "f01950731_21332.JPEG", "f01950731_10245.JPEG", "f01950731_8923.JPEG", "f01950731_13802.JPEG", "f01950731_13457.JPEG", "f01950731_20767.JPEG", "f01950731_9232.JPEG", "f01950731_15655.JPEG", "f01950731_13048.JPEG", "f01950731_14388.JPEG", "f01950731_171.JPEG", "f01950731_16381.JPEG", "f01950731_8291.JPEG", "f01950731_11745.JPEG", "f01950731_10150.JPEG", "f01950731_18103.JPEG", "f01950731_651.JPEG", "f01950731_1936.JPEG", "f01950731_16139.JPEG", "f01950731_13698.JPEG", "f01950731_5652.JPEG", "f01950731_3264.JPEG", "f01950731_33840.JPEG", "f01950731_15823.JPEG", "f01950731_8536.JPEG", "f01950731_11743.JPEG", "f01950731_399.JPEG", "f01950731_1638.JPEG", "f01950731_14977.JPEG", "f01950731_12745.JPEG", "f01950731_9817.JPEG", "f01950731_16398.JPEG", "f01950731_5126.JPEG", "f01950731_15796.JPEG", "f01950731_11079.JPEG", "f01950731_14091.JPEG", "f01950731_15389.JPEG", "f01950731_6654.JPEG", "f01950731_14208.JPEG", "f01950731_16103.JPEG", "f01950731_12013.JPEG", "f01950731_13563.JPEG", "f01950731_16693.JPEG", "f01950731_33114.JPEG", "f01950731_17974.JPEG", "f01950731_16544.JPEG", "f01950731_2291.JPEG", "f01950731_8517.JPEG", "f01950731_8093.JPEG", "f01950731_10695.JPEG", "f01950731_21212.JPEG", "f01950731_141.JPEG", "f01950731_17768.JPEG", "f01950731_12912.JPEG", "f01950731_23310.JPEG", "f01950731_3595.JPEG", "f01950731_4663.JPEG", "f01950731_12904.JPEG", "f01950731_10174.JPEG", "f01950731_9098.JPEG", "f01950731_18145.JPEG", "f01950731_11086.JPEG", "f01950731_1096.JPEG", "f01950731_4722.JPEG", "f01950731_16414.JPEG", "f01950731_13959.JPEG", "f01950731_21003.JPEG", "f01950731_1533.JPEG", "f01950731_17603.JPEG", "f01950731_4046.JPEG", "f01950731_15157.JPEG", "f01950731_13094.JPEG", "f01950731_4998.JPEG", "f01950731_1335.JPEG", "f01950731_20980.JPEG", "f01950731_6396.JPEG", "f01950731_22546.JPEG", "f01950731_8596.JPEG", "f01950731_4399.JPEG", "f01950731_14466.JPEG", "f01950731_6412.JPEG", "f01950731_11842.JPEG", "f01950731_14154.JPEG", "f01950731_7578.JPEG", "f01950731_10520.JPEG", "f01950731_26161.JPEG", "f01950731_13996.JPEG", "f01950731_13091.JPEG", "f01950731_12932.JPEG", "f01950731_17641.JPEG", "f01950731_6403.JPEG", "f01950731_11822.JPEG", "f01950731_17474.JPEG", "f01950731_12921.JPEG", "f01950731_7424.JPEG", "f01950731_12223.JPEG", "f01950731_2601.JPEG", "f01950731_10261.JPEG", "f01950731_9317.JPEG", "f01950731_17432.JPEG", "f01950731_6978.JPEG", "f01950731_21393.JPEG", "f01950731_9505.JPEG", "f01950731_968.JPEG", "f01950731_15621.JPEG", "f01950731_11614.JPEG", "f01950731_4152.JPEG", "f01950731_12998.JPEG", "f01950731_9951.JPEG", "f01950731_7573.JPEG", "f01950731_14574.JPEG", "f01950731_20029.JPEG", "f01950731_1180.JPEG", "f01950731_5888.JPEG", "f01950731_15052.JPEG", "f01950731_14317.JPEG", "f01950731_24023.JPEG", "f01950731_30122.JPEG", "f01950731_12205.JPEG", "f01950731_7396.JPEG", "f01950731_13243.JPEG", "f01950731_12223.JPEG", "f01950731_2601.JPEG", "f01950731_10261.JPEG", "f01950731_9317.JPEG", "f01950731_17432.JPEG", "f01950731_6978.JPEG", "f01950731_21393.JPEG", "f01950731_9505.JPEG", "f01950731_968.JPEG", "f01950731_15621.JPEG", "f01950731_11614.JPEG", "f01950731_4152.JPEG", "f01950731_12998.JPEG", "f01950731_9951.JPEG", "f01950731_7573.JPEG", "f01950731_14574.JPEG", "f01950731_20029.JPEG", "f01950731_1180.JPEG", "f01950731_5888.JPEG", "f01950731_15052.JPEG", "f01950731_14317.JPEG", "f01950731_24023.JPEG", "f01950731_30122.JPEG", "f01950731_12205.JPEG", "f01950731_7396.JPEG", "f01950731_13243.JPEG", "f01950731_12223.JPEG", "f01950731_2601.JPEG", "f01950731_10261.JPEG", "f01950731_9317.JPEG", "f01950731_17432.JPEG", "f01950731_6978.JPEG", "f01950731_21393.JPEG", "f01950731_9505.JPEG", "f01950731_968.JPEG", "f01950731_15621.JPEG", "f01950731_11614.JPEG", "f01950731_4152.JPEG", "f01950731_12998.JPEG", "f01950731_9951.JPEG", "f01950731_7573.JPEG", "f01950731_14574.JPEG", "f01950731_20029.JPEG", "f01950731_1180.JPEG", "f01950731_5888.JPEG", "f01950731_15052.JPEG", "f01950731_14317.JPEG", "f01950731_24023.JPEG", "f01950731_30122.JPEG", "f01950731_12205.JPEG", "f01950731_7396.JPEG", "f01950731_13243.JPEG", "f01950731_12223.JPEG", "f01950731_2601.JPEG", "f01950731_10261.JPEG", "f01950731_9317.JPEG", "f01950731_17432.JPEG", "f01950731_6978.JPEG", "f01950731_21393.JPEG", "f01950731_9505.JPEG", "f01950731_968.JPEG", "f01950731_15621.JPEG", "f01950731_11614.JPEG", "f01950731_4152.JPEG", "f01950731_12998.JPEG", "f01950731_9951.JPEG", "f01950731_7573.JPEG", "f01950731_14574.JPEG", "f01950731_20029.JPEG", "f01950731_1180.JPEG", "f01950731_5888.JPEG", "f01950731_15052.JPEG", "f01950731_14317.JPEG", "f01950731_24023.JPEG", "f01950731_30122.JPEG", "f01950731_12205.JPEG", "f01950731_7396.JPEG", "f01950731_13243.JPEG", "g01950731_12482.JPEG", "g01950731_16004.JPEG", "g01950731_15732.JPEG", "g01950731_16556.JPEG", "g01950731_23520.JPEG", "g01950731_17543.JPEG", "g01950731_10361.JPEG", "g01950731_15817.JPEG", "g01950731_28650.JPEG", "g01950731_10662.JPEG", "g01950731_12724.JPEG", "g01950731_28627.JPEG", "g01950731_9370.JPEG", "g01950731_12121.JPEG", "g01950731_4250.JPEG", "g01950731_21421.JPEG", "g01950731_21428.JPEG", "g01950731_13350.JPEG", "g01950731_11759.JPEG", "g01950731_8905.JPEG", "g01950731_9356.JPEG", "g01950731_11644.JPEG", "g01950731_2131.JPEG", "g01950731_21332.JPEG", "g01950731_10245.JPEG", "g01950731_8923.JPEG", "g01950731_13802.JPEG", "g01950731_13457.JPEG", "g01950731_20767.JPEG", "g01950731_9232.JPEG", "g01950731_15655.JPEG", "g01950731_13048.JPEG", "g01950731_14388.JPEG", "g01950731_171.JPEG", "g01950731_16381.JPEG", "g01950731_8291.JPEG", "g01950731_11745.JPEG", "g01950731_10150.JPEG", "g01950731_18103.JPEG", "g01950731_651.JPEG", "g01950731_1936.JPEG", "g01950731_16139.JPEG", "g01950731_13698.JPEG", "g01950731_5652.JPEG", "g01950731_3264.JPEG", "g01950731_33840.JPEG", "g01950731_15823.JPEG", "g01950731_8536.JPEG", "g01950731_11743.JPEG", "g01950731_399.JPEG", "g01950731_1638.JPEG", "g01950731_14977.JPEG", "g01950731_12745.JPEG", "g01950731_9817.JPEG", "g01950731_16398.JPEG", "g01950731_5126.JPEG", "g01950731_15796.JPEG", "g01950731_11079.JPEG", "g01950731_14091.JPEG", "g01950731_15389.JPEG", "g01950731_6654.JPEG", "g01950731_14208.JPEG", "g01950731_16103.JPEG", "g01950731_12013.JPEG", "g01950731_13563.JPEG", "g01950731_16693.JPEG", "g01950731_33114.JPEG", "g01950731_17974.JPEG", "g01950731_16544.JPEG", "g01950731_2291.JPEG", "g01950731_8517.JPEG", "g01950731_8093.JPEG", "g01950731_10695.JPEG", "g01950731_21212.JPEG", "g01950731_141.JPEG", "g01950731_17768.JPEG", "g01950731_12912.JPEG", "g01950731_23310.JPEG", "g01950731_3595.JPEG", "g01950731_4663.JPEG", "g01950731_12904.JPEG", "g01950731_10174.JPEG", "g01950731_9098.JPEG", "g01950731_18145.JPEG", "g01950731_11086.JPEG", "g01950731_1096.JPEG", "g01950731_4722.JPEG", "g01950731_16414.JPEG", "g01950731_13959.JPEG", "g01950731_21003.JPEG", "g01950731_1533.JPEG", "g01950731_17603.JPEG", "g01950731_4046.JPEG", "g01950731_15157.JPEG", "g01950731_13094.JPEG", "g01950731_4998.JPEG", "g01950731_1335.JPEG", "g01950731_20980.JPEG", "g01950731_6396.JPEG", "g01950731_22546.JPEG", "g01950731_8596.JPEG", "g01950731_4399.JPEG", "g01950731_14466.JPEG", "g01950731_6412.JPEG", "g01950731_11842.JPEG", "g01950731_14154.JPEG", "g01950731_7578.JPEG", "g01950731_10520.JPEG", "g01950731_26161.JPEG", "g01950731_13996.JPEG", "g01950731_13091.JPEG", "g01950731_12932.JPEG", "g01950731_17641.JPEG", "g01950731_6403.JPEG", "g01950731_11822.JPEG", "g01950731_17474.JPEG", "g01950731_12921.JPEG", "g01950731_7424.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_11432.JPEG", "g01950731_3712.JPEG ", "g01950731_344.JPEG", "g01950731_12614.JPEG", "g01950731_14730.JPEG", "g01950731_2425.JPEG", "g01950731_13765.JPEG", "g01950731_8413.JPEG", "g01950731_10425.JPEG", "g01950731_12448.JPEG", "g01950731_8179.JPEG", "g01950731_4601.JPEG", "g01950731_8969.JPEG", "g01950731_12933.JPEG", "g01950731_11736.JPEG", "g01950731_2016.JPEG", "g01950731_13225.JPEG", "g01950731_2268.JPEG", "g01950731_2157.JPEG", "g01950731_728.JPEG", "g01950731_12167.JPEG", "g01950731_12610.JPEG", "g01950731_5002.JPEG", "g01950731_16869.JPEG", "g01950731_7906.JPEG", "g01950731_22717.JPEG", "g01950731_15680.JPEG", "g01950731_2727.JPEG", "g01950731_16418.JPEG", "g01950731_13447.JPEG", "g01950731_12661.JPEG", "g01950731_13992.JPEG", "g01950731_14347.JPEG", "g01950731_14203.JPEG", "g01950731_22795.JPEG", "g01950731_15462.JPEG", "g01950731_12996.JPEG", "g01950731_9661.JPEG", "g01950731_4133.JPEG", "g01950731_4376.JPEG", "g01950731_10431.JPEG", "g01950731_13433.JPEG", "g01950731_13188.JPEG", "g01950731_5054.JPEG", "g01950731_2848.JPEG", "g01950731_12859.JPEG", "g01950731_19865.JPEG", "g01950731_12513.JPEG", "g01950731_16906.JPEG", "g01950731_13723.JPEG", "g01950731_12605.JPEG", "g01950731_8445.JPEG", "g01950731_23528.JPEG", "g01950731_16379.JPEG", "g01950731_15784.JPEG", "g01950731_2560.JPEG", "g01950731_3240.JPEG", "g01950731_12482.JPEG", "g01950731_16004.JPEG", "g01950731_15732.JPEG", "g01950731_16556.JPEG", "g01950731_23520.JPEG", "g01950731_17543.JPEG", "g01950731_10361.JPEG", "g01950731_15817.JPEG", "g01950731_28650.JPEG", "g01950731_10662.JPEG", "g01950731_12724.JPEG", "g01950731_28627.JPEG", "g01950731_9370.JPEG", "g01950731_12121.JPEG", "g01950731_4250.JPEG", "g01950731_21421.JPEG", "g01950731_21428.JPEG", "g01950731_13350.JPEG", "g01950731_11759.JPEG", "g01950731_8905.JPEG", "g01950731_9356.JPEG", "g01950731_11644.JPEG", "g01950731_2131.JPEG", "g01950731_21332.JPEG", "g01950731_10245.JPEG", "g01950731_8923.JPEG", "g01950731_13802.JPEG", "g01950731_13457.JPEG", "g01950731_20767.JPEG", "g01950731_9232.JPEG", "g01950731_15655.JPEG", "g01950731_13048.JPEG", "g01950731_14388.JPEG", "g01950731_171.JPEG", "g01950731_16381.JPEG", "g01950731_8291.JPEG", "g01950731_11745.JPEG", "g01950731_10150.JPEG", "g01950731_18103.JPEG", "g01950731_651.JPEG", "g01950731_1936.JPEG", "g01950731_16139.JPEG", "g01950731_13698.JPEG", "g01950731_5652.JPEG", "g01950731_3264.JPEG", "g01950731_33840.JPEG", "g01950731_15823.JPEG", "g01950731_8536.JPEG", "g01950731_11743.JPEG", "g01950731_399.JPEG", "g01950731_1638.JPEG", "g01950731_14977.JPEG", "g01950731_12745.JPEG", "g01950731_9817.JPEG", "g01950731_16398.JPEG", "g01950731_5126.JPEG", "g01950731_15796.JPEG", "g01950731_11079.JPEG", "g01950731_14091.JPEG", "g01950731_15389.JPEG", "g01950731_6654.JPEG", "g01950731_14208.JPEG", "g01950731_16103.JPEG", "g01950731_12013.JPEG", "g01950731_13563.JPEG", "g01950731_16693.JPEG", "g01950731_33114.JPEG", "g01950731_17974.JPEG", "g01950731_16544.JPEG", "g01950731_2291.JPEG", "g01950731_8517.JPEG", "g01950731_8093.JPEG", "g01950731_10695.JPEG", "g01950731_21212.JPEG", "g01950731_141.JPEG", "g01950731_17768.JPEG", "g01950731_12912.JPEG", "g01950731_23310.JPEG", "g01950731_3595.JPEG", "g01950731_4663.JPEG", "g01950731_12904.JPEG", "g01950731_10174.JPEG", "g01950731_9098.JPEG", "g01950731_18145.JPEG", "g01950731_11086.JPEG", "g01950731_1096.JPEG", "g01950731_4722.JPEG", "g01950731_16414.JPEG", "g01950731_13959.JPEG", "g01950731_21003.JPEG", "g01950731_1533.JPEG", "g01950731_17603.JPEG", "g01950731_4046.JPEG", "g01950731_15157.JPEG", "g01950731_13094.JPEG", "g01950731_4998.JPEG", "g01950731_1335.JPEG", "g01950731_20980.JPEG", "g01950731_6396.JPEG", "g01950731_22546.JPEG", "g01950731_8596.JPEG", "g01950731_4399.JPEG", "g01950731_14466.JPEG", "g01950731_6412.JPEG", "g01950731_11842.JPEG", "g01950731_14154.JPEG", "g01950731_7578.JPEG", "g01950731_10520.JPEG", "g01950731_26161.JPEG", "g01950731_13996.JPEG", "g01950731_13091.JPEG", "g01950731_12932.JPEG", "g01950731_17641.JPEG", "g01950731_6403.JPEG", "g01950731_11822.JPEG", "g01950731_17474.JPEG", "g01950731_12921.JPEG", "g01950731_7424.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_11432.JPEG", "g01950731_3712.JPEG ", "g01950731_344.JPEG", "g01950731_12614.JPEG", "g01950731_14730.JPEG", "g01950731_2425.JPEG", "g01950731_13765.JPEG", "g01950731_8413.JPEG", "g01950731_10425.JPEG", "g01950731_12448.JPEG", "g01950731_8179.JPEG", "g01950731_4601.JPEG", "g01950731_8969.JPEG", "g01950731_12933.JPEG", "g01950731_11736.JPEG", "g01950731_2016.JPEG", "g01950731_13225.JPEG", "g01950731_2268.JPEG", "g01950731_2157.JPEG", "g01950731_728.JPEG", "g01950731_12167.JPEG", "g01950731_12610.JPEG", "g01950731_5002.JPEG", "g01950731_16869.JPEG", "g01950731_7906.JPEG", "g01950731_22717.JPEG", "g01950731_15680.JPEG", "g01950731_2727.JPEG", "g01950731_16418.JPEG", "g01950731_13447.JPEG", "g01950731_12661.JPEG", "g01950731_13992.JPEG", "g01950731_14347.JPEG", "g01950731_14203.JPEG", "g01950731_22795.JPEG", "g01950731_15462.JPEG", "g01950731_12996.JPEG", "g01950731_9661.JPEG", "g01950731_4133.JPEG", "g01950731_4376.JPEG", "g01950731_10431.JPEG", "g01950731_13433.JPEG", "g01950731_13188.JPEG", "g01950731_5054.JPEG", "g01950731_2848.JPEG", "g01950731_12859.JPEG", "g01950731_19865.JPEG", "g01950731_12513.JPEG", "g01950731_16906.JPEG", "g01950731_13723.JPEG", "g01950731_12605.JPEG", "g01950731_8445.JPEG", "g01950731_23528.JPEG", "g01950731_16379.JPEG", "g01950731_15784.JPEG", "g01950731_2560.JPEG", "g01950731_3240.JPEG", "g01950731_12482.JPEG", "g01950731_16004.JPEG", "g01950731_15732.JPEG", "g01950731_16556.JPEG", "g01950731_23520.JPEG", "g01950731_17543.JPEG", "g01950731_10361.JPEG", "g01950731_15817.JPEG", "g01950731_28650.JPEG", "g01950731_10662.JPEG", "g01950731_12724.JPEG", "g01950731_28627.JPEG", "g01950731_9370.JPEG", "g01950731_12121.JPEG", "g01950731_4250.JPEG", "g01950731_21421.JPEG", "g01950731_21428.JPEG", "g01950731_13350.JPEG", "g01950731_11759.JPEG", "g01950731_8905.JPEG", "g01950731_9356.JPEG", "g01950731_11644.JPEG", "g01950731_2131.JPEG", "g01950731_21332.JPEG", "g01950731_10245.JPEG", "g01950731_8923.JPEG", "g01950731_13802.JPEG", "g01950731_13457.JPEG", "g01950731_20767.JPEG", "g01950731_9232.JPEG", "g01950731_15655.JPEG", "g01950731_13048.JPEG", "g01950731_14388.JPEG", "g01950731_171.JPEG", "g01950731_16381.JPEG", "g01950731_8291.JPEG", "g01950731_11745.JPEG", "g01950731_10150.JPEG", "g01950731_18103.JPEG", "g01950731_651.JPEG", "g01950731_1936.JPEG", "g01950731_16139.JPEG", "g01950731_13698.JPEG", "g01950731_5652.JPEG", "g01950731_3264.JPEG", "g01950731_33840.JPEG", "g01950731_15823.JPEG", "g01950731_8536.JPEG", "g01950731_11743.JPEG", "g01950731_399.JPEG", "g01950731_1638.JPEG", "g01950731_14977.JPEG", "g01950731_12745.JPEG", "g01950731_9817.JPEG", "g01950731_16398.JPEG", "g01950731_5126.JPEG", "g01950731_15796.JPEG", "g01950731_11079.JPEG", "g01950731_14091.JPEG", "g01950731_15389.JPEG", "g01950731_6654.JPEG", "g01950731_14208.JPEG", "g01950731_16103.JPEG", "g01950731_12013.JPEG", "g01950731_13563.JPEG", "g01950731_16693.JPEG", "g01950731_33114.JPEG", "g01950731_17974.JPEG", "g01950731_16544.JPEG", "g01950731_2291.JPEG", "g01950731_8517.JPEG", "g01950731_8093.JPEG", "g01950731_10695.JPEG", "g01950731_21212.JPEG", "g01950731_141.JPEG", "g01950731_17768.JPEG", "g01950731_12912.JPEG", "g01950731_23310.JPEG", "g01950731_3595.JPEG", "g01950731_4663.JPEG", "g01950731_12904.JPEG", "g01950731_10174.JPEG", "g01950731_9098.JPEG", "g01950731_18145.JPEG", "g01950731_11086.JPEG", "g01950731_1096.JPEG", "g01950731_4722.JPEG", "g01950731_16414.JPEG", "g01950731_13959.JPEG", "g01950731_21003.JPEG", "g01950731_1533.JPEG", "g01950731_17603.JPEG", "g01950731_4046.JPEG", "g01950731_15157.JPEG", "g01950731_13094.JPEG", "g01950731_4998.JPEG", "g01950731_1335.JPEG", "g01950731_20980.JPEG", "g01950731_6396.JPEG", "g01950731_22546.JPEG", "g01950731_8596.JPEG", "g01950731_4399.JPEG", "g01950731_14466.JPEG", "g01950731_6412.JPEG", "g01950731_11842.JPEG", "g01950731_14154.JPEG", "g01950731_7578.JPEG", "g01950731_10520.JPEG", "g01950731_26161.JPEG", "g01950731_13996.JPEG", "g01950731_13091.JPEG", "g01950731_12932.JPEG", "g01950731_17641.JPEG", "g01950731_6403.JPEG", "g01950731_11822.JPEG", "g01950731_17474.JPEG", "g01950731_12921.JPEG", "g01950731_7424.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "g01950731_12223.JPEG", "g01950731_2601.JPEG", "g01950731_10261.JPEG", "g01950731_9317.JPEG", "g01950731_17432.JPEG", "g01950731_6978.JPEG", "g01950731_21393.JPEG", "g01950731_9505.JPEG", "g01950731_968.JPEG", "g01950731_15621.JPEG", "g01950731_11614.JPEG", "g01950731_4152.JPEG", "g01950731_12998.JPEG", "g01950731_9951.JPEG", "g01950731_7573.JPEG", "g01950731_14574.JPEG", "g01950731_20029.JPEG", "g01950731_1180.JPEG", "g01950731_5888.JPEG", "g01950731_15052.JPEG", "g01950731_14317.JPEG", "g01950731_24023.JPEG", "g01950731_30122.JPEG", "g01950731_12205.JPEG", "g01950731_7396.JPEG", "g01950731_13243.JPEG", "h01950731_12167.JPEG", "h01950731_12610.JPEG", "h01950731_5002.JPEG", "h01950731_16869.JPEG", "h01950731_7906.JPEG", "h01950731_22717.JPEG", "h01950731_15680.JPEG", "h01950731_2727.JPEG", "h01950731_16418.JPEG", "h01950731_13447.JPEG", "h01950731_12661.JPEG", "h01950731_13992.JPEG", "h01950731_14347.JPEG", "h01950731_14203.JPEG", "h01950731_22795.JPEG", "h01950731_15462.JPEG", "h01950731_12996.JPEG", "h01950731_9661.JPEG", "h01950731_4133.JPEG", "h01950731_4376.JPEG", "h01950731_10431.JPEG", "h01950731_13433.JPEG", "h01950731_13188.JPEG", "h01950731_5054.JPEG", "h01950731_2848.JPEG", "h01950731_12859.JPEG", "h01950731_19865.JPEG", "h01950731_12513.JPEG", "h01950731_16906.JPEG", "h01950731_13723.JPEG", "h01950731_12605.JPEG", "h01950731_8445.JPEG", "h01950731_23528.JPEG", "h01950731_16379.JPEG", "h01950731_15784.JPEG", "h01950731_2560.JPEG", "h01950731_3240.JPEG", "h01950731_12482.JPEG", "h01950731_16004.JPEG", "h01950731_15732.JPEG", "h01950731_16556.JPEG", "h01950731_23520.JPEG", "h01950731_17543.JPEG", "h01950731_10361.JPEG", "h01950731_15817.JPEG", "h01950731_28650.JPEG", "h01950731_10662.JPEG", "h01950731_12724.JPEG", "h01950731_28627.JPEG", "h01950731_9370.JPEG", "h01950731_12121.JPEG", "h01950731_4250.JPEG", "h01950731_21421.JPEG", "h01950731_21428.JPEG", "h01950731_13350.JPEG", "h01950731_11759.JPEG", "h01950731_8905.JPEG", "h01950731_9356.JPEG", "h01950731_11644.JPEG", "h01950731_2131.JPEG", "h01950731_21332.JPEG", "h01950731_10245.JPEG", "h01950731_8923.JPEG", "h01950731_13802.JPEG", "h01950731_13457.JPEG", "h01950731_20767.JPEG", "h01950731_9232.JPEG", "h01950731_15655.JPEG", "h01950731_13048.JPEG", "h01950731_14388.JPEG", "h01950731_171.JPEG", "h01950731_16381.JPEG", "h01950731_8291.JPEG", "h01950731_11745.JPEG", "h01950731_10150.JPEG", "h01950731_18103.JPEG", "h01950731_651.JPEG", "h01950731_1936.JPEG", "h01950731_16139.JPEG", "h01950731_13698.JPEG", "h01950731_5652.JPEG", "h01950731_3264.JPEG", "h01950731_33840.JPEG", "h01950731_15823.JPEG", "h01950731_8536.JPEG", "h01950731_11743.JPEG", "h01950731_399.JPEG", "h01950731_1638.JPEG", "h01950731_14977.JPEG", "h01950731_12745.JPEG", "h01950731_9817.JPEG", "h01950731_16398.JPEG", "h01950731_5126.JPEG", "h01950731_15796.JPEG", "h01950731_11079.JPEG", "h01950731_14091.JPEG", "h01950731_15389.JPEG", "h01950731_6654.JPEG", "h01950731_14208.JPEG", "h01950731_16103.JPEG", "h01950731_12013.JPEG", "h01950731_13563.JPEG", "h01950731_16693.JPEG", "h01950731_33114.JPEG", "h01950731_17974.JPEG", "h01950731_16544.JPEG", "h01950731_2291.JPEG", "h01950731_8517.JPEG", "h01950731_8093.JPEG", "h01950731_10695.JPEG", "h01950731_21212.JPEG", "h01950731_141.JPEG", "h01950731_17768.JPEG", "h01950731_12912.JPEG", "h01950731_23310.JPEG", "h01950731_3595.JPEG", "h01950731_4663.JPEG", "h01950731_12904.JPEG", "h01950731_10174.JPEG", "h01950731_9098.JPEG", "h01950731_18145.JPEG", "h01950731_11086.JPEG", "h01950731_1096.JPEG", "h01950731_4722.JPEG", "h01950731_16414.JPEG", "h01950731_13959.JPEG", "h01950731_21003.JPEG", "h01950731_1533.JPEG", "h01950731_17603.JPEG", "h01950731_4046.JPEG", "h01950731_15157.JPEG", "h01950731_13094.JPEG", "h01950731_4998.JPEG", "h01950731_1335.JPEG", "h01950731_20980.JPEG", "h01950731_6396.JPEG", "h01950731_22546.JPEG", "h01950731_8596.JPEG", "h01950731_4399.JPEG", "h01950731_14466.JPEG", "h01950731_6412.JPEG", "h01950731_11842.JPEG", "h01950731_14154.JPEG", "h01950731_7578.JPEG", "h01950731_10520.JPEG", "h01950731_26161.JPEG", "h01950731_13996.JPEG", "h01950731_13091.JPEG", "h01950731_12932.JPEG", "h01950731_17641.JPEG", "h01950731_6403.JPEG", "h01950731_11822.JPEG", "h01950731_17474.JPEG", "h01950731_12921.JPEG", "h01950731_7424.JPEG", "h01950731_12223.JPEG", "h01950731_2601.JPEG", "h01950731_10261.JPEG", "h01950731_9317.JPEG", "h01950731_17432.JPEG", "h01950731_6978.JPEG", "h01950731_21393.JPEG", "h01950731_9505.JPEG", "h01950731_968.JPEG", "h01950731_15621.JPEG", "h01950731_11614.JPEG", "h01950731_4152.JPEG", "h01950731_12998.JPEG", "h01950731_9951.JPEG", "h01950731_7573.JPEG", "h01950731_14574.JPEG", "h01950731_20029.JPEG", "h01950731_1180.JPEG", "h01950731_5888.JPEG", "h01950731_15052.JPEG", "h01950731_14317.JPEG", "h01950731_24023.JPEG", "h01950731_30122.JPEG", "h01950731_12205.JPEG", "h01950731_7396.JPEG", "h01950731_13243.JPEG", "k01950731_11432.JPEG", "k01950731_3712.JPEG ", "k01950731_344.JPEG", "k01950731_12614.JPEG", "k01950731_14730.JPEG", "k01950731_2425.JPEG", "k01950731_13765.JPEG", "k01950731_8413.JPEG", "k01950731_10425.JPEG", "k01950731_12448.JPEG", "k01950731_8179.JPEG", "k01950731_4601.JPEG", "k01950731_8969.JPEG", "k01950731_12933.JPEG", "k01950731_11736.JPEG", "k01950731_2016.JPEG", "k01950731_13225.JPEG", "k01950731_2268.JPEG", "k01950731_2157.JPEG", "k01950731_728.JPEG", "k01950731_12167.JPEG", "k01950731_12610.JPEG", "k01950731_5002.JPEG", "k01950731_16869.JPEG", "k01950731_7906.JPEG", "k01950731_22717.JPEG", "k01950731_15680.JPEG", "k01950731_2727.JPEG", "k01950731_16418.JPEG", "k01950731_13447.JPEG", "k01950731_12661.JPEG", "k01950731_13992.JPEG", "k01950731_14347.JPEG", "k01950731_14203.JPEG", "k01950731_22795.JPEG", "k01950731_15462.JPEG", "k01950731_12996.JPEG", "k01950731_9661.JPEG", "k01950731_4133.JPEG", "k01950731_4376.JPEG", "k01950731_10431.JPEG", "k01950731_13433.JPEG", "k01950731_13188.JPEG", "k01950731_5054.JPEG", "k01950731_2848.JPEG", "k01950731_12859.JPEG", "k01950731_19865.JPEG", "k01950731_12513.JPEG", "k01950731_16906.JPEG", "k01950731_13723.JPEG", "k01950731_12605.JPEG", "k01950731_8445.JPEG", "k01950731_23528.JPEG", "k01950731_16379.JPEG", "k01950731_15784.JPEG", "k01950731_2560.JPEG", "k01950731_3240.JPEG", "k01950731_11432.JPEG", "k01950731_3712.JPEG ", "k01950731_344.JPEG", "k01950731_12614.JPEG", "k01950731_14730.JPEG", "k01950731_2425.JPEG", "k01950731_13765.JPEG", "k01950731_8413.JPEG", "k01950731_10425.JPEG", "k01950731_12448.JPEG", "k01950731_8179.JPEG", "k01950731_4601.JPEG", "k01950731_8969.JPEG", "k01950731_12933.JPEG", "k01950731_11736.JPEG", "k01950731_2016.JPEG", "k01950731_13225.JPEG", "k01950731_2268.JPEG", "k01950731_2157.JPEG", "k01950731_728.JPEG", "k01950731_12167.JPEG", "k01950731_12610.JPEG", "k01950731_5002.JPEG", "k01950731_16869.JPEG", "k01950731_7906.JPEG", "k01950731_22717.JPEG", "k01950731_15680.JPEG", "k01950731_2727.JPEG", "k01950731_16418.JPEG", "k01950731_13447.JPEG", "k01950731_12661.JPEG", "k01950731_13992.JPEG", "k01950731_14347.JPEG", "k01950731_14203.JPEG", "k01950731_22795.JPEG", "k01950731_15462.JPEG", "k01950731_12996.JPEG", "k01950731_9661.JPEG", "k01950731_4133.JPEG", "k01950731_4376.JPEG", "k01950731_10431.JPEG", "k01950731_13433.JPEG", "k01950731_13188.JPEG", "k01950731_5054.JPEG", "k01950731_2848.JPEG", "k01950731_12859.JPEG", "k01950731_19865.JPEG", "k01950731_12513.JPEG", "k01950731_16906.JPEG", "k01950731_13723.JPEG", "k01950731_12605.JPEG", "k01950731_8445.JPEG", "k01950731_23528.JPEG", "k01950731_16379.JPEG", "k01950731_15784.JPEG", "k01950731_2560.JPEG", "k01950731_3240.JPEG", "k01950731_12482.JPEG", "k01950731_16004.JPEG", "k01950731_15732.JPEG", "k01950731_16556.JPEG", "k01950731_23520.JPEG", "k01950731_17543.JPEG", "k01950731_10361.JPEG", "k01950731_15817.JPEG", "k01950731_28650.JPEG", "k01950731_10662.JPEG", "k01950731_12724.JPEG", "k01950731_28627.JPEG", "k01950731_9370.JPEG", "k01950731_12121.JPEG", "k01950731_4250.JPEG", "k01950731_21421.JPEG", "k01950731_21428.JPEG", "k01950731_13350.JPEG", "k01950731_11759.JPEG", "k01950731_8905.JPEG", "k01950731_9356.JPEG", "k01950731_11644.JPEG", "k01950731_2131.JPEG", "k01950731_21332.JPEG", "k01950731_10245.JPEG", "k01950731_8923.JPEG", "k01950731_13802.JPEG", "k01950731_13457.JPEG", "k01950731_20767.JPEG", "k01950731_9232.JPEG", "k01950731_15655.JPEG", "k01950731_13048.JPEG", "k01950731_14388.JPEG", "k01950731_171.JPEG", "k01950731_16381.JPEG", "k01950731_8291.JPEG", "k01950731_11745.JPEG", "k01950731_10150.JPEG", "k01950731_18103.JPEG", "k01950731_651.JPEG", "k01950731_1936.JPEG", "k01950731_16139.JPEG", "k01950731_13698.JPEG", "k01950731_5652.JPEG", "k01950731_3264.JPEG", "k01950731_33840.JPEG", "k01950731_15823.JPEG", "k01950731_8536.JPEG", "k01950731_11743.JPEG", "k01950731_399.JPEG", "k01950731_1638.JPEG", "k01950731_14977.JPEG", "k01950731_12745.JPEG", "k01950731_9817.JPEG", "k01950731_16398.JPEG", "k01950731_5126.JPEG", "k01950731_15796.JPEG", "k01950731_11079.JPEG", "k01950731_14091.JPEG", "k01950731_15389.JPEG", "k01950731_6654.JPEG", "k01950731_14208.JPEG", "k01950731_16103.JPEG", "k01950731_12013.JPEG", "k01950731_13563.JPEG", "k01950731_16693.JPEG", "k01950731_33114.JPEG", "k01950731_17974.JPEG", "k01950731_16544.JPEG", "k01950731_2291.JPEG", "k01950731_8517.JPEG", "k01950731_8093.JPEG", "k01950731_10695.JPEG", "k01950731_21212.JPEG", "k01950731_141.JPEG", "k01950731_17768.JPEG", "k01950731_12912.JPEG", "k01950731_23310.JPEG", "k01950731_3595.JPEG", "k01950731_4663.JPEG", "k01950731_12904.JPEG", "k01950731_10174.JPEG", "k01950731_9098.JPEG", "k01950731_18145.JPEG", "k01950731_11086.JPEG", "k01950731_1096.JPEG", "k01950731_4722.JPEG", "k01950731_16414.JPEG", "k01950731_13959.JPEG", "k01950731_21003.JPEG", "k01950731_1533.JPEG", "k01950731_17603.JPEG", "k01950731_4046.JPEG", "k01950731_15157.JPEG", "k01950731_13094.JPEG", "k01950731_4998.JPEG", "k01950731_1335.JPEG", "k01950731_20980.JPEG", "k01950731_6396.JPEG", "k01950731_22546.JPEG", "k01950731_8596.JPEG", "k01950731_4399.JPEG", "k01950731_14466.JPEG", "k01950731_6412.JPEG", "k01950731_11842.JPEG", "k01950731_14154.JPEG", "k01950731_7578.JPEG", "k01950731_10520.JPEG", "k01950731_26161.JPEG", "k01950731_13996.JPEG", "k01950731_13091.JPEG", "k01950731_12932.JPEG", "k01950731_17641.JPEG", "k01950731_6403.JPEG", "k01950731_11822.JPEG", "k01950731_17474.JPEG", "k01950731_12921.JPEG", "k01950731_7424.JPEG", "k01950731_12223.JPEG", "k01950731_2601.JPEG", "k01950731_10261.JPEG", "k01950731_9317.JPEG", "k01950731_17432.JPEG", "k01950731_6978.JPEG", "k01950731_21393.JPEG", "k01950731_9505.JPEG", "k01950731_968.JPEG", "k01950731_15621.JPEG", "k01950731_11614.JPEG", "k01950731_4152.JPEG", "k01950731_12998.JPEG", "k01950731_9951.JPEG", "k01950731_7573.JPEG", "k01950731_14574.JPEG", "k01950731_20029.JPEG", "k01950731_1180.JPEG", "k01950731_5888.JPEG", "k01950731_15052.JPEG", "k01950731_14317.JPEG", "k01950731_24023.JPEG", "k01950731_30122.JPEG", "k01950731_12205.JPEG", "k01950731_7396.JPEG", "k01950731_13243.JPEG", "l01950731_11432.JPEG", "l01950731_3712.JPEG ", "l01950731_344.JPEG", "l01950731_12614.JPEG", "l01950731_14730.JPEG", "l01950731_2425.JPEG", "l01950731_13765.JPEG", "l01950731_8413.JPEG", "l01950731_10425.JPEG", "l01950731_12448.JPEG", "l01950731_8179.JPEG", "l01950731_4601.JPEG", "l01950731_8969.JPEG", "l01950731_12933.JPEG", "l01950731_11736.JPEG", "l01950731_2016.JPEG", "l01950731_13225.JPEG", "l01950731_2268.JPEG", "l01950731_2157.JPEG", "l01950731_728.JPEG", "l01950731_12167.JPEG", "l01950731_12610.JPEG", "l01950731_5002.JPEG", "l01950731_16869.JPEG", "l01950731_7906.JPEG", "l01950731_22717.JPEG", "l01950731_15680.JPEG", "l01950731_2727.JPEG", "l01950731_16418.JPEG", "l01950731_13447.JPEG", "l01950731_12661.JPEG", "l01950731_13992.JPEG", "l01950731_14347.JPEG", "l01950731_14203.JPEG", "l01950731_22795.JPEG", "l01950731_15462.JPEG", "l01950731_12996.JPEG", "l01950731_9661.JPEG", "l01950731_4133.JPEG", "l01950731_4376.JPEG", "l01950731_10431.JPEG", "l01950731_13433.JPEG", "l01950731_13188.JPEG", "l01950731_5054.JPEG", "l01950731_2848.JPEG", "l01950731_12859.JPEG", "l01950731_19865.JPEG", "l01950731_12513.JPEG", "l01950731_16906.JPEG", "l01950731_13723.JPEG", "l01950731_12605.JPEG", "l01950731_8445.JPEG", "l01950731_23528.JPEG", "l01950731_16379.JPEG", "l01950731_15784.JPEG", "l01950731_2560.JPEG", "l01950731_3240.JPEG", "l01950731_12482.JPEG", "l01950731_16004.JPEG", "l01950731_15732.JPEG", "l01950731_16556.JPEG", "l01950731_23520.JPEG", "l01950731_17543.JPEG", "l01950731_10361.JPEG", "l01950731_15817.JPEG", "l01950731_28650.JPEG", "l01950731_10662.JPEG", "l01950731_12724.JPEG", "l01950731_28627.JPEG", "l01950731_9370.JPEG", "l01950731_12121.JPEG", "l01950731_4250.JPEG", "l01950731_21421.JPEG", "l01950731_21428.JPEG", "l01950731_13350.JPEG", "l01950731_11759.JPEG", "l01950731_8905.JPEG", "l01950731_9356.JPEG", "l01950731_11644.JPEG", "l01950731_2131.JPEG", "l01950731_21332.JPEG", "l01950731_10245.JPEG", "l01950731_8923.JPEG", "l01950731_13802.JPEG", "l01950731_13457.JPEG", "l01950731_20767.JPEG", "l01950731_9232.JPEG", "l01950731_15655.JPEG", "l01950731_13048.JPEG", "l01950731_14388.JPEG", "l01950731_171.JPEG", "l01950731_16381.JPEG", "l01950731_8291.JPEG", "l01950731_11745.JPEG", "l01950731_10150.JPEG", "l01950731_18103.JPEG", "l01950731_651.JPEG", "l01950731_1936.JPEG", "l01950731_16139.JPEG", "l01950731_13698.JPEG", "l01950731_5652.JPEG", "l01950731_3264.JPEG", "l01950731_33840.JPEG", "l01950731_15823.JPEG", "l01950731_8536.JPEG", "l01950731_11743.JPEG", "l01950731_399.JPEG", "l01950731_1638.JPEG", "l01950731_14977.JPEG", "l01950731_12745.JPEG", "l01950731_9817.JPEG", "l01950731_16398.JPEG", "l01950731_5126.JPEG", "l01950731_15796.JPEG", "l01950731_11079.JPEG", "l01950731_14091.JPEG", "l01950731_15389.JPEG", "l01950731_6654.JPEG", "l01950731_14208.JPEG", "l01950731_16103.JPEG", "l01950731_12013.JPEG", "l01950731_13563.JPEG", "l01950731_16693.JPEG", "l01950731_33114.JPEG", "l01950731_17974.JPEG", "l01950731_16544.JPEG", "l01950731_2291.JPEG", "l01950731_8517.JPEG", "l01950731_8093.JPEG", "l01950731_10695.JPEG", "l01950731_21212.JPEG", "l01950731_141.JPEG", "l01950731_17768.JPEG", "l01950731_12912.JPEG", "l01950731_23310.JPEG", "l01950731_3595.JPEG", "l01950731_4663.JPEG", "l01950731_12904.JPEG", "l01950731_10174.JPEG", "l01950731_9098.JPEG", "l01950731_18145.JPEG", "l01950731_11086.JPEG", "l01950731_1096.JPEG", "l01950731_4722.JPEG", "l01950731_16414.JPEG", "l01950731_13959.JPEG", "l01950731_21003.JPEG", "l01950731_1533.JPEG", "l01950731_17603.JPEG", "l01950731_4046.JPEG", "l01950731_15157.JPEG", "l01950731_13094.JPEG", "l01950731_4998.JPEG", "l01950731_1335.JPEG", "l01950731_20980.JPEG", "l01950731_6396.JPEG", "l01950731_22546.JPEG", "l01950731_8596.JPEG", "l01950731_4399.JPEG", "l01950731_14466.JPEG", "l01950731_6412.JPEG", "l01950731_11842.JPEG", "l01950731_14154.JPEG", "l01950731_7578.JPEG", "l01950731_10520.JPEG", "l01950731_26161.JPEG", "l01950731_13996.JPEG", "l01950731_13091.JPEG", "l01950731_12932.JPEG", "l01950731_17641.JPEG", "l01950731_6403.JPEG", "l01950731_11822.JPEG", "l01950731_17474.JPEG", "l01950731_12921.JPEG", "l01950731_7424.JPEG", "l01950731_12223.JPEG", "l01950731_2601.JPEG", "l01950731_10261.JPEG", "l01950731_9317.JPEG", "l01950731_17432.JPEG", "l01950731_6978.JPEG", "l01950731_21393.JPEG", "l01950731_9505.JPEG", "l01950731_968.JPEG", "l01950731_15621.JPEG", "l01950731_11614.JPEG", "l01950731_4152.JPEG", "l01950731_12998.JPEG", "l01950731_9951.JPEG", "l01950731_7573.JPEG", "l01950731_14574.JPEG", "l01950731_20029.JPEG", "l01950731_1180.JPEG", "l01950731_5888.JPEG", "l01950731_15052.JPEG", "l01950731_14317.JPEG", "l01950731_24023.JPEG", "l01950731_30122.JPEG", "l01950731_12205.JPEG", "l01950731_7396.JPEG", "l01950731_13243.JPEG" }; };
28.832478
74
0.653023
[ "vector" ]
1541923caa921bd47b629420825f3d7d15cdee45
10,933
c
C
mex/include/sisl-4.5.0/src/sh1375.c
sangyoonHan/extern
a3c874538a7262b895b60d3c4d493e5b34cf81f8
[ "BSD-2-Clause" ]
null
null
null
mex/include/sisl-4.5.0/src/sh1375.c
sangyoonHan/extern
a3c874538a7262b895b60d3c4d493e5b34cf81f8
[ "BSD-2-Clause" ]
null
null
null
mex/include/sisl-4.5.0/src/sh1375.c
sangyoonHan/extern
a3c874538a7262b895b60d3c4d493e5b34cf81f8
[ "BSD-2-Clause" ]
null
null
null
//=========================================================================== // SISL - SINTEF Spline Library, version 4.5.0. // Definition and interrogation of NURBS curves and surfaces. // // Copyright (C) 2000-2005, 2010 SINTEF ICT, Applied Mathematics, Norway. // // 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, write to the Free Software // Foundation, Inc., // 59 Temple Place - Suite 330, // Boston, MA 02111-1307, USA. // // Contact information: E-mail: tor.dokken@sintef.no // SINTEF ICT, Department of Applied Mathematics, // P.O. Box 124 Blindern, // 0314 Oslo, Norway. // // Other licenses are also available for this software, notably licenses // for: // - Building commercial software. // - Building software whose source code you wish to keep private. //=========================================================================== #include "sisl-copyright.h" /* * * $Id: sh1375.c,v 1.2 2001-03-19 15:59:03 afr Exp $ * */ #define SH1375 #include "sislP.h" #if defined(SISLNEEDPROTOTYPES) void sh1375(SISLCurve *pc1,double ecentr[],double enorm[],double abigr, double asmalr,int idim,double aepsco,double aepsge, int trackflag,int *jtrack,SISLTrack ***wtrack, int *jpt,double **gpar,int **pretop,int *jcrv,SISLIntcurve ***wcurve,int *jstat) #else void sh1375(pc1,ecentr,enorm,abigr,asmalr,idim,aepsco,aepsge, trackflag,jtrack,wtrack,jpt,gpar,pretop,jcrv,wcurve,jstat) SISLCurve *pc1; double ecentr[]; double enorm[]; double abigr; double asmalr; int idim; double aepsco; double aepsge; int trackflag; int *jtrack; SISLTrack ***wtrack; int *jpt; double **gpar; int **pretop; int *jcrv; SISLIntcurve ***wcurve; int *jstat; #endif /* ********************************************************************* * ********************************************************************* * * PURPOSE : Find all intersections between a curve and a torus. * * INPUT : pc1 - Pointer to the curve. * ecentr - The center of the torus (lying in the symmetri plane) * enorm - Normal of symmetri plane * abigr - Distance fro ecentr to center circle of torus * asmalr - The radius of the torus surface * idim - Dimension of the space in which the plane/line * lies. idim should be equal to two or three. * aepsco - Computational resolution. * aepsge - Geometry resolution. * trackflag - If true, create tracks. * * * * OUTPUT : jtrack - Number of tracks created * wtrack - Array of pointers to tracks * jpt - Number of single intersection points. * gpar - Array containing the parameter values of the * single intersection points in the parameter * interval of the curve. The points lie continuous. * Intersection curves are stored in wcurve. * pretop - Topology info. for single intersection points. * *jcrv - Number of intersection curves. * wcurve - Array containing descriptions of the intersection * curves. The curves are only described by points * in the parameter interval. The curve-pointers points * to nothing. (See description of Intcurve * in intcurve.dcl). * jstat - status messages * > 0 : warning * = 0 : ok * < 0 : error * * * METHOD : The vertices of the curve is put into the equation of the * torus achieving a curve in the one-dimentional space of order * 4*(ik-1) + 1, when the order of the original curve is ik. * The zeroes of this curve are found. * * * REFERENCES : * *- * CALLS : sh1761 - Find point/curve intersections. * hp_s1880 - Put intersections into output format. * s1377 - Put curve into torus equation * make_cv_kreg - Ensure k-regularity of input curve. * newCurve - Create new curve. * newPoint - Create new point. * newObject - Create new object. * freeObject - Free the space occupied by a given object. * freeIntdat - Free the space occupied by intersection result. * * WRITTEN BY : Tor Dokken, SI, 88-05. * REWRITTEN BY : Bjoern Olav Hoset, SI, 89-06. * ********************************************************************* */ { double *nullp = SISL_NULL; int kstat = 0; /* Local status variable. */ int kpos = 0; /* Position of error. */ int kdim=1; /* Dimension of curve in curve/point intersection.*/ int kdeg = 1001; /* Code that the implict surface is a torus */ double simpli[8]; /* Array for represetnation of torus surface */ double snorm[3]; /* Normalized normal vector */ double spoint[1]; /* SISLPoint in curve/point intersection. */ double *spar = SISL_NULL; /* Values of intersections in the parameter area of the second object. Empty in this case. */ SISLCurve *qc = SISL_NULL; /* Pointer to curve in curve/point intersection. */ SISLPoint *qp = SISL_NULL; /* Pointer to point in curve/point intersection. */ SISLObject *qo1 = SISL_NULL; /* Pointer to object in object/point intersection.*/ SISLObject *qo2 = SISL_NULL; /* Pointer to object in object/point intersection.*/ SISLIntdat *qintdat = SISL_NULL; /* Pointer to intersection data */ int ksurf=0; /* Dummy number of Intsurfs. */ SISLIntsurf **wsurf=0; /* Dummy array of Intsurfs. */ SISLObject *track_obj=SISL_NULL; SISLCurve *qkreg=SISL_NULL; /* Input surface ensured k-regularity. */ /* -------------------------------------------------------- */ if (pc1->cuopen == SISL_CRV_PERIODIC) { /* Cyclic curve. */ make_cv_kreg(pc1,&qkreg,&kstat); if (kstat < 0) goto error; } else qkreg = pc1; /* * Create new object and connect curve to object. * ------------------------------------------------ */ if (!(track_obj = newObject (SISLCURVE))) goto err101; track_obj->c1 = pc1; /* * Check dimension. * ---------------- */ *jpt = 0; *jcrv = 0; *jtrack = 0; if (idim != 3) goto err104; if (qkreg -> idim != idim) goto err103; /* * Normalize normal vector * ---------------------- */ (void)s6norm(enorm,idim,snorm,&kstat); if (kstat<0) goto error; /* * Put the information concerning the torus in the following sequence * into simpli: Center, normal, big radius, small radius * ------------------------------------------------------------------ */ memcopy(simpli,ecentr,3,DOUBLE); memcopy(simpli+3,snorm,3,DOUBLE); simpli[6] = abigr; simpli[7] = asmalr; /* * Put curve into torus equation * ----------------------------- */ s1377(qkreg,simpli,kdeg,idim,&qc,&kstat); if (kstat<0) goto error; /* * Create new object and connect curve to object. * ---------------------------------------------- */ if (!(qo1 = newObject(SISLCURVE))) goto err101; qo1 -> c1 = qc; qo1 -> o1 = qo1; /* * Create new object and connect point to object. * ---------------------------------------------- */ if (!(qo2 = newObject(SISLPOINT))) goto err101; spoint[0] = DZERO; if (!(qp = newPoint(spoint,kdim,1))) goto err101; qo2 -> p1 = qp; /* * Find intersections. * ------------------- */ sh1761(qo1,qo2,aepsge,&qintdat,&kstat); if (kstat < 0) goto error; /* Join periodic curves */ int_join_per( &qintdat,track_obj,track_obj,nullp,2000,aepsge,&kstat); if (kstat < 0) goto error; /* Create tracks */ if (trackflag && qintdat) { make_tracks (qo1, qo2, 0, nullp, qintdat->ilist, qintdat->vlist, jtrack, wtrack, aepsge, &kstat); if (kstat < 0) goto error; } /* * Express intersections on output format. * --------------------------------------- */ if (qintdat)/* Only if there were intersections found */ { hp_s1880(track_obj, track_obj, 2000, 1,0,qintdat,jpt,gpar,&spar,pretop,jcrv,wcurve,&ksurf,&wsurf,&kstat); if (kstat < 0) goto error; } /* * Intersections found. * -------------------- */ *jstat = 0; goto out; /* Error in space allocation. */ err101: *jstat = -101; s6err("sh1375",*jstat,kpos); goto out; /* Dimensions conflicting. */ err103: *jstat = -103; s6err("sh1375",*jstat,kpos); goto out; /* Dimension not equal to two or three. */ err104: *jstat = -104; s6err("sh1375",*jstat,kpos); goto out; /* Error in lower level routine. */ error : *jstat = kstat; s6err("sh1375",*jstat,kpos); goto out; out: /* Free allocated space. */ if (spar) freearray(spar); if (qo1) freeObject(qo1); if (qo2) freeObject(qo2); if (qintdat) freeIntdat(qintdat); if (track_obj) { track_obj->c1 = SISL_NULL; freeObject(track_obj); } /* Free local curve. */ if (qkreg != SISL_NULL && qkreg != pc1) freeCurve(qkreg); return; }
32.930723
81
0.50279
[ "geometry", "object", "vector" ]
1549250b80bfabcb0cfdbc897ecde0ffc4c122d1
231
h
C
Event.h
ryuichiueda/IAS14_CODE
4f4df0b6afe234fda60f3438ab5d28388f7186e2
[ "MIT" ]
null
null
null
Event.h
ryuichiueda/IAS14_CODE
4f4df0b6afe234fda60f3438ab5d28388f7186e2
[ "MIT" ]
null
null
null
Event.h
ryuichiueda/IAS14_CODE
4f4df0b6afe234fda60f3438ab5d28388f7186e2
[ "MIT" ]
null
null
null
#ifndef __EVENT__H_ #define __EVENT__H_ #include <string> #include <vector> using namespace std; class Event{ public: Event(int trial_no); vector<int> sensor_values; int reward; string action; int trial_number; }; #endif
12.833333
27
0.744589
[ "vector" ]
154d96b14e497bef6d572d06a0c745eae02ddf02
5,228
h
C
chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
76
2020-09-02T03:05:41.000Z
2022-03-30T04:40:55.000Z
chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
45
2020-09-02T03:21:37.000Z
2022-03-31T22:19:45.000Z
chrome/browser/ui/views/tabs/tab_group_editor_bubble_view.h
zealoussnow/chromium
fd8a8914ca0183f0add65ae55f04e287543c7d4a
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2020-07-22T18:49:18.000Z
2022-02-08T10:27:16.000Z
// Copyright 2019 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_VIEWS_TABS_TAB_GROUP_EDITOR_BUBBLE_VIEW_H_ #define CHROME_BROWSER_UI_VIEWS_TABS_TAB_GROUP_EDITOR_BUBBLE_VIEW_H_ #include <string> #include "chrome/browser/ui/views/tabs/tab_group_header.h" #include "components/tab_groups/tab_group_color.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/views/bubble/bubble_dialog_delegate_view.h" #include "ui/views/controls/button/label_button.h" #include "ui/views/controls/button/toggle_button.h" #include "ui/views/controls/textfield/textfield.h" #include "ui/views/controls/textfield/textfield_controller.h" class Browser; namespace tab_groups { enum class TabGroupColorId; class TabGroupId; } // namespace tab_groups namespace views { class ToggleButton; } // namespace views class ColorPickerView; class TabGroupHeader; // A dialog for changing a tab group's visual parameters. class TabGroupEditorBubbleView : public views::BubbleDialogDelegateView { public: METADATA_HEADER(TabGroupEditorBubbleView); DECLARE_CLASS_ELEMENT_IDENTIFIER_VALUE(TabGroupEditorBubbleView, kEditorBubbleIdentifier); static constexpr int TAB_GROUP_HEADER_CXMENU_SAVE_GROUP = 13; static constexpr int TAB_GROUP_HEADER_CXMENU_NEW_TAB_IN_GROUP = 14; static constexpr int TAB_GROUP_HEADER_CXMENU_UNGROUP = 15; static constexpr int TAB_GROUP_HEADER_CXMENU_CLOSE_GROUP = 16; static constexpr int TAB_GROUP_HEADER_CXMENU_MOVE_GROUP_TO_NEW_WINDOW = 17; static constexpr int TAB_GROUP_HEADER_CXMENU_FEEDBACK = 18; using Colors = std::vector<std::pair<tab_groups::TabGroupColorId, std::u16string>>; // Shows the editor for |group|. Returns a *non-owning* pointer to the // bubble's widget. static views::Widget* Show( const Browser* browser, const tab_groups::TabGroupId& group, TabGroupHeader* header_view, absl::optional<gfx::Rect> anchor_rect = absl::nullopt, // If not provided, will be set to |header_view|. views::View* anchor_view = nullptr, bool stop_context_menu_propagation = false); // views::BubbleDialogDelegateView: views::View* GetInitiallyFocusedView() override; gfx::Rect GetAnchorRect() const override; // This needs to be added as it does not know the correct theme color until it // is added to widget. void AddedToWidget() override; private: TabGroupEditorBubbleView(const Browser* browser, const tab_groups::TabGroupId& group, views::View* anchor_view, absl::optional<gfx::Rect> anchor_rect, TabGroupHeader* header_view, bool stop_context_menu_propagation); ~TabGroupEditorBubbleView() override; void UpdateGroup(); void OnSaveTogglePressed(); void NewTabInGroupPressed(); void UngroupPressed(TabGroupHeader* header_view); void CloseGroupPressed(); void MoveGroupToNewWindowPressed(); void SendFeedbackPressed(); void OnBubbleClose(); const Browser* const browser_; const tab_groups::TabGroupId group_; class TitleFieldController : public views::TextfieldController { public: explicit TitleFieldController(TabGroupEditorBubbleView* parent) : parent_(parent) {} ~TitleFieldController() override = default; // views::TextfieldController: void ContentsChanged(views::Textfield* sender, const std::u16string& new_contents) override; bool HandleKeyEvent(views::Textfield* sender, const ui::KeyEvent& key_event) override; private: TabGroupEditorBubbleView* const parent_; }; TitleFieldController title_field_controller_; class TitleField : public views::Textfield { public: METADATA_HEADER(TitleField); explicit TitleField(bool stop_context_menu_propagation) : stop_context_menu_propagation_(stop_context_menu_propagation) {} ~TitleField() override = default; // views::Textfield: void ShowContextMenu(const gfx::Point& p, ui::MenuSourceType source_type) override; private: // Whether the context menu should be hidden the first time it shows. // Needed because there is no easy way to stop the propagation of a // ShowContextMenu event, which is sometimes used to open the bubble // itself. bool stop_context_menu_propagation_; }; TitleField* title_field_; Colors colors_; ColorPickerView* color_selector_; views::ToggleButton* save_group_toggle_ = nullptr; views::LabelButton* move_menu_item_ = nullptr; // If true will use the |anchor_rect_| provided in the constructor, otherwise // fall back to using the anchor view bounds. const bool use_set_anchor_rect_; // Creates the set of tab group colors to display and returns the color that // is initially selected. tab_groups::TabGroupColorId InitColorSet(); std::u16string title_at_opening_; }; #endif // CHROME_BROWSER_UI_VIEWS_TABS_TAB_GROUP_EDITOR_BUBBLE_VIEW_H_
35.087248
80
0.737758
[ "vector" ]
154f6d8a318ac8b04198db8b9b008455b5a64595
2,578
h
C
visa/iga/GEDLibrary/GED_external/build/autogen-intel64/ged_enum_interpreters.h
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
visa/iga/GEDLibrary/GED_external/build/autogen-intel64/ged_enum_interpreters.h
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
visa/iga/GEDLibrary/GED_external/build/autogen-intel64/ged_enum_interpreters.h
dkurt/intel-graphics-compiler
247cfb9ca64bc187ee9cf3b437ad184fb2d5c471
[ "MIT" ]
null
null
null
/*===================== begin_copyright_notice ================================== Copyright (c) 2017 Intel Corporation Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice 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. ======================= end_copyright_notice ==================================*/ /* * !!! DO NOT EDIT THIS FILE !!! * * This file was automagically crafted by GED's model parser. */ #ifndef GED_ENUM_INTERPRETERS_H #define GED_ENUM_INTERPRETERS_H #include "common/ged_types_internal.h" /*! * This is an enumeration of all the reinterpreted string enumerations available for queries by GED. It is a consolidated list of all * interpreters from all supported models. * * @note Some interpreters may not be available on all models. */ typedef enum { GED_REINTERPRETED_ENUM_OperandWidth, ///< The operand width, based on its data type. /*! * The numeric type in which to display an operand, based on its data type. Relevant only for immediate operands. */ GED_REINTERPRETED_ENUM_OperandNumericType, /*! * * Nibble Control. This field is used in some instructions along with QtrCtrl. See the description of * ExecMaskOffsetCtrl. * NibCtrl is only used for SIMD4 instructions. * */ GED_REINTERPRETED_ENUM_NibCtrl } GED_REINTERPRETED_ENUM; extern const ged_unsigned_table_t EnumInterpretersTable0[3]; extern const ged_unsigned_table_t EnumInterpretersTable1[3]; extern const ged_unsigned_table_t EnumInterpretersTable2[3]; extern const ged_unsigned_table_t EnumInterpretersTable3[3]; #endif // GED_ENUM_INTERPRETERS_H
37.911765
133
0.730799
[ "model" ]
155b6aa1344580be7aed36e5607eb1e8561a7237
1,963
h
C
XmlDocModel/Display/Display.h
vafaabdul/XML-Document-Model
ecbe1184f87139a731432c7b136f944442633d63
[ "Unlicense" ]
null
null
null
XmlDocModel/Display/Display.h
vafaabdul/XML-Document-Model
ecbe1184f87139a731432c7b136f944442633d63
[ "Unlicense" ]
null
null
null
XmlDocModel/Display/Display.h
vafaabdul/XML-Document-Model
ecbe1184f87139a731432c7b136f944442633d63
[ "Unlicense" ]
null
null
null
#ifndef DISPLAY_H #define DISPLAY_H /////////////////////////////////////////////////////////////////////////////// // Display.h - Shows results of the XML Document Operations // // version 1.0 // // Application: Project #2, CSE687 - Object Oriented Design, Spring 2015 // // Platform: HP Pavillion g6, Win 7 Pro, Visual Studio 2013 // // Author: Abdulvafa Choudhary, SUID :671290061 // // aachoudh@syr.edu // /////////////////////////////////////////////////////////////////////////////// /* * Package Operations: * ------------------- * - Demonstrates the functionality of XML Document class. * - Displays the internal tree reprsentation. * - Displays elements found based on tag name and id. * - Demonstrates adding and removing child element to the XML document. * - Demonstrates adding and removing attribute to the XML element. * - Displays the attributes of a given element. * - Adds root to an empty Document Tree. * * * Required Files: * --------------- * Tokenizer.h, Tokenizer.cpp, XmlDocument.h, XmlDocument.cpp, Display.h * xmlElementParts.h, xmlElementParts.cpp, XmlElement.h, XmlElement.cpp, Utilities.h, Utilities.cpp * * Build Process: * -------------- * devenv XmlDocModel.sln /debug rebuild * * Maintenance History: * -------------------- * - Ver 1 : 21 Mar 2015 * first release */ #include "../XmlDocument/XmlDocument/XmlDocument.h" #include <memory> class Display{ public: Display::Display(XmlProcessing::XmlDocument& doc); void demoTreeRep(); void demoElemById(); void demoElemByTag(); void demoAddChild(); void demoRemoveChild(); void demoAddRoot(); void demoChildElem(); void demoFindAttribs(); void demoAddAttrib(); void demoRemoveAttrib(); void demoWriteXML(); void demoMoveOperations(); private: XmlProcessing::XmlDocument& doc_; }; #endif
31.66129
98
0.58431
[ "object" ]
155bd8b72664f8e1e134bf9810ff1285ab142428
6,798
c
C
src/map/lapack2flamec/f2c/c/zpptri.c
haampie/libflame
a6b27af9b7ef91ec2724b52c7c09b681379a3470
[ "BSD-3-Clause" ]
199
2015-02-06T06:05:32.000Z
2022-03-18T05:20:33.000Z
src/map/lapack2flamec/f2c/c/zpptri.c
haampie/libflame
a6b27af9b7ef91ec2724b52c7c09b681379a3470
[ "BSD-3-Clause" ]
44
2015-05-10T18:14:52.000Z
2022-02-22T08:22:10.000Z
src/map/lapack2flamec/f2c/c/zpptri.c
haampie/libflame
a6b27af9b7ef91ec2724b52c7c09b681379a3470
[ "BSD-3-Clause" ]
70
2015-02-07T04:53:03.000Z
2022-03-18T05:20:36.000Z
/* ../netlib/zpptri.f -- translated by f2c (version 20100827). You must link the resulting object file with libf2c: on Microsoft Windows system, link with libf2c.lib; on Linux or Unix systems, link with .../path/to/libf2c.a -lm or, if you install libf2c.a in a standard place, with -lf2c -lm -- in that order, at the end of the command line, as in cc *.o -lf2c -lm Source for libf2c is in /netlib/f2c/libf2c.zip, e.g., http://www.netlib.org/f2c/libf2c.zip */ #include "FLA_f2c.h" /* Table of constant values */ static doublereal c_b8 = 1.; static integer c__1 = 1; /* > \brief \b ZPPTRI */ /* =========== DOCUMENTATION =========== */ /* Online html documentation available at */ /* http://www.netlib.org/lapack/explore-html/ */ /* > \htmlonly */ /* > Download ZPPTRI + dependencies */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.tgz?format=tgz&filename=/lapack/lapack_routine/zpptri. f"> */ /* > [TGZ]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.zip?format=zip&filename=/lapack/lapack_routine/zpptri. f"> */ /* > [ZIP]</a> */ /* > <a href="http://www.netlib.org/cgi-bin/netlibfiles.txt?format=txt&filename=/lapack/lapack_routine/zpptri. f"> */ /* > [TXT]</a> */ /* > \endhtmlonly */ /* Definition: */ /* =========== */ /* SUBROUTINE ZPPTRI( UPLO, N, AP, INFO ) */ /* .. Scalar Arguments .. */ /* CHARACTER UPLO */ /* INTEGER INFO, N */ /* .. */ /* .. Array Arguments .. */ /* COMPLEX*16 AP( * ) */ /* .. */ /* > \par Purpose: */ /* ============= */ /* > */ /* > \verbatim */ /* > */ /* > ZPPTRI computes the inverse of a complex Hermitian positive definite */ /* > matrix A using the Cholesky factorization A = U**H*U or A = L*L**H */ /* > computed by ZPPTRF. */ /* > \endverbatim */ /* Arguments: */ /* ========== */ /* > \param[in] UPLO */ /* > \verbatim */ /* > UPLO is CHARACTER*1 */ /* > = 'U': Upper triangular factor is stored in AP; */ /* > = 'L': Lower triangular factor is stored in AP. */ /* > \endverbatim */ /* > */ /* > \param[in] N */ /* > \verbatim */ /* > N is INTEGER */ /* > The order of the matrix A. N >= 0. */ /* > \endverbatim */ /* > */ /* > \param[in,out] AP */ /* > \verbatim */ /* > AP is COMPLEX*16 array, dimension (N*(N+1)/2) */ /* > On entry, the triangular factor U or L from the Cholesky */ /* > factorization A = U**H*U or A = L*L**H, packed columnwise as */ /* > a linear array. The j-th column of U or L is stored in the */ /* > array AP as follows: */ /* > if UPLO = 'U', AP(i + (j-1)*j/2) = U(i,j) for 1<=i<=j; */ /* > if UPLO = 'L', AP(i + (j-1)*(2n-j)/2) = L(i,j) for j<=i<=n. */ /* > */ /* > On exit, the upper or lower triangle of the (Hermitian) */ /* > inverse of A, overwriting the input factor U or L. */ /* > \endverbatim */ /* > */ /* > \param[out] INFO */ /* > \verbatim */ /* > INFO is INTEGER */ /* > = 0: successful exit */ /* > < 0: if INFO = -i, the i-th argument had an illegal value */ /* > > 0: if INFO = i, the (i,i) element of the factor U or L is */ /* > zero, and the inverse could not be computed. */ /* > \endverbatim */ /* Authors: */ /* ======== */ /* > \author Univ. of Tennessee */ /* > \author Univ. of California Berkeley */ /* > \author Univ. of Colorado Denver */ /* > \author NAG Ltd. */ /* > \date November 2011 */ /* > \ingroup complex16OTHERcomputational */ /* ===================================================================== */ /* Subroutine */ int zpptri_(char *uplo, integer *n, doublecomplex *ap, integer *info) { /* System generated locals */ integer i__1, i__2, i__3; doublereal d__1; doublecomplex z__1; /* Local variables */ integer j, jc, jj; doublereal ajj; integer jjn; extern /* Subroutine */ int zhpr_(char *, integer *, doublereal *, doublecomplex *, integer *, doublecomplex *); extern logical lsame_(char *, char *); extern /* Double Complex */ VOID zdotc_f2c_(doublecomplex *, integer *, doublecomplex *, integer *, doublecomplex *, integer *); logical upper; extern /* Subroutine */ int ztpmv_(char *, char *, char *, integer *, doublecomplex *, doublecomplex *, integer *), xerbla_(char *, integer *), zdscal_(integer *, doublereal *, doublecomplex *, integer *), ztptri_(char *, char *, integer *, doublecomplex *, integer *); /* -- LAPACK computational routine (version 3.4.0) -- */ /* -- LAPACK is a software package provided by Univ. of Tennessee, -- */ /* -- Univ. of California Berkeley, Univ. of Colorado Denver and NAG Ltd..-- */ /* November 2011 */ /* .. Scalar Arguments .. */ /* .. */ /* .. Array Arguments .. */ /* .. */ /* ===================================================================== */ /* .. Parameters .. */ /* .. */ /* .. Local Scalars .. */ /* .. */ /* .. External Functions .. */ /* .. */ /* .. External Subroutines .. */ /* .. */ /* .. Intrinsic Functions .. */ /* .. */ /* .. Executable Statements .. */ /* Test the input parameters. */ /* Parameter adjustments */ --ap; /* Function Body */ *info = 0; upper = lsame_(uplo, "U"); if (! upper && ! lsame_(uplo, "L")) { *info = -1; } else if (*n < 0) { *info = -2; } if (*info != 0) { i__1 = -(*info); xerbla_("ZPPTRI", &i__1); return 0; } /* Quick return if possible */ if (*n == 0) { return 0; } /* Invert the triangular Cholesky factor U or L. */ ztptri_(uplo, "Non-unit", n, &ap[1], info); if (*info > 0) { return 0; } if (upper) { /* Compute the product inv(U) * inv(U)**H. */ jj = 0; i__1 = *n; for (j = 1; j <= i__1; ++j) { jc = jj + 1; jj += j; if (j > 1) { i__2 = j - 1; zhpr_("Upper", &i__2, &c_b8, &ap[jc], &c__1, &ap[1]); } i__2 = jj; ajj = ap[i__2].r; zdscal_(&j, &ajj, &ap[jc], &c__1); /* L10: */ } } else { /* Compute the product inv(L)**H * inv(L). */ jj = 1; i__1 = *n; for (j = 1; j <= i__1; ++j) { jjn = jj + *n - j + 1; i__2 = jj; i__3 = *n - j + 1; zdotc_f2c_(&z__1, &i__3, &ap[jj], &c__1, &ap[jj], &c__1); d__1 = z__1.r; ap[i__2].r = d__1; ap[i__2].i = 0.; // , expr subst if (j < *n) { i__2 = *n - j; ztpmv_("Lower", "Conjugate transpose", "Non-unit", &i__2, &ap[ jjn], &ap[jj + 1], &c__1); } jj = jjn; /* L20: */ } } return 0; /* End of ZPPTRI */ } /* zpptri_ */
32.84058
292
0.497499
[ "object" ]
155db00fda4de906b9504193fa947a197f1164fa
19,888
c
C
usr/bash/bash.c
razvan9310/barrelfish
8067d416823d7cc4d96381f736d7b09747ef054c
[ "MIT" ]
7
2016-11-08T15:51:54.000Z
2021-07-27T08:44:27.000Z
usr/bash/bash.c
razvan9310/barrelfish
8067d416823d7cc4d96381f736d7b09747ef054c
[ "MIT" ]
null
null
null
usr/bash/bash.c
razvan9310/barrelfish
8067d416823d7cc4d96381f736d7b09747ef054c
[ "MIT" ]
9
2016-10-05T08:41:38.000Z
2020-10-22T18:09:47.000Z
/* * Copyright (c) 2016, ETH Zurich. * All rights reserved. * * This file is distributed under the terms in the attached LICENSE file. * If you do not find this file, copies can be found by writing to: * ETH Zurich D-INFK, Haldeneggsteig 4, CH-8092 Zurich. Attn: Systems Group. */ #include <stdio.h> #include <errno.h> #include <stdlib.h> #include <fs/dirent.h> #include <aos/aos.h> #include <aos/aos_rpc.h> #include "bash.h" #include <fs/fs.h> #include <fs/ramfs.h> #include <aos/inthandler.h> #include <aos/waitset.h> // Some global variable char *input; // User Input String char *wd; // Working directory uint64_t max_len_wd = 20; // Current Max Length of working directory uint64_t pos_wd = 0; // Current Length of working directory uint64_t buf_size = 16; // Buffer size of input array uint64_t pos = 0; // Current size of buffer array uint32_t inputRedirect = 0; // Input Redirection Bit uint32_t outputRedirect = 0; // Output Redirection Bit FILE *fout; // File out FILE *fin; // File in // BIG TODO: CHANGE ALL FUNCTION DEFINITION TO ERRVAL_T // Better error handling mechanisms // Extra Challenges // [OK] Move IRQ CAP to BASH Process // [OK] Redirect Input/Output to File // [] Pipe Commands // [OK] Tab to autocomplete static struct command_handler_entry commands[] = {{.name = "mkdir", .handler = (void*) handle_mkdir}, {.name = "rmdir", .handler = (void*) handle_rmdir}, {.name = "help", .handler = (void*) handle_help}, {.name = "led", .handler = (void*) handle_light_led}, {.name = "oncore", .handler = (void*) handle_oncore}, {.name = "threads", .handler = (void*) handle_threads}, {.name = "cd", .handler = (void*) handle_cd}, {.name = "ls", .handler = (void*) handle_ls}, {.name = "memtest", .handler = (void*) handle_memtest}, {.name = "echo", .handler = (void*) handle_echo}, {.name = "ps", .handler = (void*) handle_ps}, {.name = "pwd", .handler = (void*) handle_pwd}, {.name = "cat", .handler = (void*) handle_cat}, {.name = "wc", .handler = (void*) handle_wc}, {.name = "grep", .handler = (void*) handle_grep}, {.name = "rm", .handler = (void*) handle_rm}}; // Helper Functions: char** get_suggestion(char *command) { char **result; result = malloc(16*sizeof(char *)); uint32_t commands_size = sizeof(commands)/sizeof(commands[0]); uint32_t len = strlen(command); uint32_t j = 0; for(int i=0; i<commands_size; i++) { if(strncmp(command, commands[i].name, len-1) == 0) { result[j] = commands[i].name; j++; } } return result; } void do_backslash(void) { aos_rpc_serial_putchar(get_init_rpc(), '\b'); aos_rpc_serial_putchar(get_init_rpc(), ' '); aos_rpc_serial_putchar(get_init_rpc(), '\b'); } bool is_space(char c) { if(c == ' ') return true; else if(c == '\t') return true; else if(c == '\n') return true; else if(c == '\r') return true; return false; } void clean_buffer(void) { free(input); pos = 0; if(inputRedirect>0) fclose(fin); if(outputRedirect>0) fclose(fout); inputRedirect = 0; outputRedirect = 0; buf_size = 16; input = malloc(buf_size); fout = stdout; fin = stdin; } static void terminal_read_handler(void *params) { aos_rpc_serial_getchar(get_init_rpc(), (input+pos)); if(*(input+pos) == '\r') { *(input+pos) = 0; sanitize_input(input); }else { if(*(input+pos) != '\t'){ if(*(input+pos) == 127) { if(pos) { do_backslash(); pos--; }else { printf("%c", '\a'); fflush(stdout); } }else { aos_rpc_serial_putchar(get_init_rpc(), *(input+pos)); pos++; } if(pos == buf_size) { input = realloc(input, 2*buf_size); buf_size = 2*buf_size; } }else { printf("\n"); printf("\033[2K\r"); char **result; result = get_suggestion(input); uint32_t mov_r = 4+strlen(input)+1; uint32_t mov_l = 0; while(*result){ SHELL_PRINTF(fout, "%s ", *result); mov_l+=(strlen(*result)+2); result++; } printf("\033[1A"); printf("\033[%dD", mov_l); printf("\033[%dC", mov_r); fflush(stdout); } } } errval_t handle_echo(char *argc[], int argv) { for(int i=1; i<argv; i++) { SHELL_PRINTF(fout, "%s ", argc[i]); } SHELL_PRINTF(fout, "\n"); return SYS_ERR_OK; } errval_t handle_ps(char *argc[], int argv) { domainid_t *pids_core0; size_t pid_count_core0; domainid_t *pids_core1; size_t pid_count_core1; coreid_t core = 0; errval_t err; CHECK("Err in getting all the pids", aos_rpc_process_get_all_pids(get_init_rpc(),core, &pids_core0, &pid_count_core0)); char *name; SHELL_PRINTF(fout, "Core Pids Process Name\n"); SHELL_PRINTF(fout, "================================\n"); for(int i=0; i<pid_count_core0; i++) { aos_rpc_process_get_name(get_init_rpc(), *pids_core0, core, &name); SHELL_PRINTF(fout, "%d %d %s \n", core, *pids_core0, name); pids_core0++; } core = 1; err = aos_rpc_process_get_all_pids(get_init_rpc(),core, &pids_core1, &pid_count_core1); if(err_is_fail(err)) { DEBUG_ERR(err, "Getting all pids"); } for(int i=0; i<pid_count_core1; i++) { aos_rpc_process_get_name(get_init_rpc(), *pids_core1, core, &name); SHELL_PRINTF(fout, "%d %d %s \n", core, *pids_core1, name); pids_core1++; } return SYS_ERR_OK; } static void pesudo_task(void) { // char *a = malloc(10); // a = "hello"; // printf("%s\n", a); SHELL_PRINTF(fout, "###### Hello World from a new thread &&&&&&\n"); //SHELL_PRINTF("My id is: %d\n", thread_get_id(thread_self())); } errval_t handle_threads(char *argc[], int argv) { if(argv != 2) { printf("Syntax error: threads <number of threads>\n"); return BASH_ERR_SYNTAX; } int num_threads = atoi(argc[1]); struct thread *t[num_threads]; for(int i=0; i<num_threads; i++) { t[i] = thread_create((thread_func_t) pesudo_task, NULL); } for(int i=0; i<num_threads; i++) { thread_join(t[i], NULL); } return SYS_ERR_OK; } static void thread_handle_memtest(void *params) { size_t *size = (size_t *)params; char *a = malloc(*size); for(int i=0; i<*size; i++) { *(a+i) = 'J'; } SHELL_PRINTF(fout, "Result of memtest: %s\n", a); } errval_t handle_memtest(char *argc[], int argv) { size_t *size = malloc(sizeof(size_t)); *size = atoi(argc[1]); struct thread *t = thread_create((thread_func_t) thread_handle_memtest, (void*)size); thread_join(t, NULL); return SYS_ERR_OK; } errval_t handle_light_led(char *argc[], int argv) { if(argv != 2) { printf("Syntax error: led on/off\n"); return BASH_ERR_SYNTAX; } uintptr_t status = 0; coreid_t core = 0; if(strncmp(argc[1], "on", 2) == 0) status = 1; else if(strncmp(argc[1], "off", 3) == 0) status = 2; else { printf("Syntax error: led on/off\n"); return BASH_ERR_SYNTAX; } CHECK("ERR in aos_rpc_light_led", aos_rpc_light_led(get_init_rpc(), status, core)); return SYS_ERR_OK; } errval_t handle_pwd(char *argc[], int argv) { SHELL_PRINTF(fout, "Current directory is: %s\n", wd); return SYS_ERR_OK; } errval_t handle_ls(char *argc[], int argv) { fs_dirhandle_t ent; opendir(wd, &ent); char *name; while((readdir(ent, &name)) == SYS_ERR_OK) { SHELL_PRINTF(fout, "%s\n", name); } return SYS_ERR_OK; } errval_t handle_mkdir(char *argc[], int argv) { CHECK("Error in creating directory\n", mkdir(argc[1])); return SYS_ERR_OK; } errval_t handle_rm(char *argc[], int argv) { CHECK("Error in deleting file\n", rm(argc[1])); return SYS_ERR_OK; } errval_t handle_rmdir(char *argc[], int argv) { CHECK("Error in deleting folder\n", rmdir(argc[1])); return SYS_ERR_OK; } errval_t handle_cd(char *argc[], int argv) { if(argv != 2) { printf("Correct Syntax for cd is: cd <name of directory>\n"); return BASH_ERR_SYNTAX; } if(strlen(wd)+strlen(argc[1]) >= (max_len_wd-1)) { max_len_wd = max(2*max_len_wd, strlen(wd)+strlen(argc[1])); wd = realloc(wd, 2*max_len_wd); } if(strncmp(argc[1], "..", 2) == 0) { if (pos_wd == 1) return SYS_ERR_OK; pos_wd-=2; wd[pos_wd] = '\0'; pos_wd--; while(wd[pos_wd] != '/') { wd[pos_wd] = '\0'; pos_wd--; } pos_wd++; }else { strcat(wd, argc[1]); pos_wd+=strlen(argc[1]); if(wd[pos_wd] != '/') { wd[pos_wd] = '/'; pos_wd++; } pos_wd++; } //strcat(wd, argc[1]); return SYS_ERR_OK; } static errval_t private_cd(char *name) { if(strlen(wd)+strlen(name) >= (max_len_wd-1)) { max_len_wd = max(2*max_len_wd, strlen(wd)+strlen(name)); wd = realloc(wd, 2*max_len_wd); } if(strncmp(name, "..", 2) == 0) { if (pos_wd == 1) return SYS_ERR_OK; pos_wd-=2; wd[pos_wd] = '\0'; pos_wd--; while(wd[pos_wd] != '/') { wd[pos_wd] = '\0'; pos_wd--; } pos_wd++; }else { strcat(wd, name); pos_wd+=strlen(name); if(wd[pos_wd] != '/') { wd[pos_wd] = '/'; pos_wd++; } pos_wd++; } //strcat(wd, name); return SYS_ERR_OK; } errval_t handle_cat(char *argc[], int argv) { FILE *fp; int c = 0; fp = fopen(argc[1], "r"); if(fp == NULL) { printf("No file named %s\n", argc[1]); return BASH_ERR_FILE_NOT_FOUND; } while ((c = fgetc(fp)) != EOF) { SHELL_PRINTF(fout, "%c", c); } fclose(fp); return SYS_ERR_OK; } errval_t handle_wc(char *argc[], int argv) { if(argv != 2) { printf("Correct Syntax for cat is : wc <name of the file>\n"); return BASH_ERR_SYNTAX; } FILE *fp; fp = fopen(argc[1], "r"); if(fp == NULL) { printf("No file named %s\n", argc[1]); return BASH_ERR_FILE_NOT_FOUND; } int tot_chars = 0; /* total characters */ int tot_lines = 0; /* total lines */ int tot_words = 0; /* total words */ int in_space = 1; int c, last = '\n'; while ((c = fgetc(fp)) != EOF) { last = c; tot_chars++; if (is_space(c)) { in_space = 1; if (c == '\n') { tot_lines++; } } else { tot_words += in_space; in_space = 0; } } if (last != '\n') { /* count last line if not linefeed terminated */ tot_lines++; } SHELL_PRINTF(fout, "Lines, Words, Characters\n"); SHELL_PRINTF(fout, "%3d %3d %3d\n", tot_lines, tot_words, tot_chars); fclose(fp); return SYS_ERR_OK; } int grep(char*, FILE*, char*); int match(char*, char*); int matchhere(char*, char*); int matchstar(int, char*, char*); /* grep: search for regexp in file */ int grep(char *regexp, FILE *f, char *name) { int n, nmatch; char buf[1024]; nmatch = 0; while (fgets(buf, sizeof buf, f) != NULL) { n = strlen(buf); if (n > 0 && buf[n-1] == '\n') buf[n-1] = '\0'; if (match(regexp, buf)) { nmatch++; if (name != NULL) SHELL_PRINTF(fout, "%s: ", name); SHELL_PRINTF(fout, "%s\n", buf); } } return nmatch; } /* matchhere: search for regexp at beginning of text */ int matchhere(char *regexp, char *text) { if (regexp[0] == '\0') return 1; if (regexp[1] == '*') return matchstar(regexp[0], regexp+2, text); if (regexp[0] == '$' && regexp[1] == '\0') return *text == '\0'; if (*text!='\0' && (regexp[0]=='.' || regexp[0]==*text)) return matchhere(regexp+1, text+1); return 0; } /* match: search for regexp anywhere in text */ int match(char *regexp, char *text) { if (regexp[0] == '^') return matchhere(regexp+1, text); do { /* must look even if string is empty */ if (matchhere(regexp, text)) return 1; } while (*text++ != '\0'); return 0; } /* matchstar: search for c*regexp at beginning of text */ int matchstar(int c, char *regexp, char *text) { do { /* a * matches zero or more instances */ if (matchhere(regexp, text)) return 1; } while (*text != '\0' && (*text++ == c || c == '.')); return 0; } errval_t handle_grep(char *argc[], int argv) { if(strncmp(argc[1], "-r", 2) == 0){ fs_dirhandle_t ent; CHECK("Open pwd", opendir(wd, &ent)); char *name; while((readdir(ent, &name)) == SYS_ERR_OK) { private_cd(name); fs_dirhandle_t temp; errval_t err = opendir(wd, &temp); if(err == SYS_ERR_OK) { handle_grep(argc, argv); }else { FILE *fp; wd[pos_wd-2] = '\0'; fp = fopen(wd, "r"); if(fp == NULL) { printf("No file named: %s\n", wd); return BASH_ERR_FILE_NOT_FOUND; } grep(argc[2], fp, wd); fclose(fp); wd[pos_wd-2] = '/'; } private_cd(".."); } }else { FILE *fp; fp = fopen(argc[2], "r"); if(fp == NULL) { printf("No file named: %s\n", argc[2]); return BASH_ERR_FILE_NOT_FOUND; } grep(argc[1], fp, argc[2]); fclose(fp); } return SYS_ERR_OK; } errval_t handle_oncore(char *argc[], int argv) { domainid_t newpid; if(argv <= 2) { printf("Correct Syntax for oncore is oncore <coreid> <proc_name> <proc_args>\n"); return BASH_ERR_SYNTAX; }else if(argv == 3) { coreid_t core = atoi(argc[1]); CHECK("Trying to spawn with arguments", aos_rpc_process_spawn(get_init_rpc(), argc[2], core, &newpid)); }else { coreid_t core = atoi(argc[1]); uint32_t all_args = 0; for(int i=2; i<argv; i++) { all_args += strlen(argc[i]); } char *proc_name = malloc(all_args+(argv-1)); memset(proc_name, 0, all_args+(argv-1)); strncpy(proc_name, argc[2], strlen(argc[2])); strcat(proc_name, " "); for(int i=3; i<argv; i++) { strcat(proc_name, argc[i]); strcat(proc_name, " "); } CHECK("Trying to spawn with arguments", aos_rpc_process_spawn_args(get_init_rpc(), proc_name, core, &newpid)); free(proc_name); } return SYS_ERR_OK; } errval_t handle_spawn(char *argc[], int argv) { domainid_t newpid; if(argv == 1) { coreid_t core = 0; CHECK("Trying to spawn with arguments", aos_rpc_process_spawn(get_init_rpc(), argc[0], core, &newpid)); }else { coreid_t core = 0; uint32_t all_args = 0; for(int i=1; i<argv; i++) { all_args += strlen(argc[i]); } char *proc_name = malloc(all_args+(argv-1)); memset(proc_name, 0, all_args+(argv-1)); strncpy(proc_name, argc[0], strlen(argc[0])); strcat(proc_name, " "); for(int i=1; i<argv; i++) { strcat(proc_name, argc[i]); strcat(proc_name, " "); } CHECK("Trying to spawn with arguments", aos_rpc_process_spawn_args(get_init_rpc(), proc_name, core, &newpid)); free(proc_name); } return SYS_ERR_OK; } errval_t handle_help(char *argc[], int argv) { SHELL_PRINTF(fout, "List of available commands are:\n"); SHELL_PRINTF(fout, "echo\n"); SHELL_PRINTF(fout, "led on/off\n"); SHELL_PRINTF(fout, "threads <number of threads>\n"); SHELL_PRINTF(fout, "memtest <size of memory>\n"); SHELL_PRINTF(fout, "oncore <coreid> <process name>\n"); SHELL_PRINTF(fout, "ps\n"); SHELL_PRINTF(fout, "help\n"); SHELL_PRINTF(fout, "pwd\n"); SHELL_PRINTF(fout, "cd <name of folder>\n"); SHELL_PRINTF(fout, "ls\n"); SHELL_PRINTF(fout, "cat <name of file>\n"); SHELL_PRINTF(fout, "wc <name of file>\n"); SHELL_PRINTF(fout, "grep <pattern> <name of file>\n"); SHELL_PRINTF(fout, "mkdir <name of new folder>\n"); SHELL_PRINTF(fout, "rmdir <name of new folder>\n"); SHELL_PRINTF(fout, "rm <name of file>\n"); return SYS_ERR_OK; } errval_t handle_clear(char *argc[], int argv) { printf("\033[2J"); return SYS_ERR_OK; } errval_t sanitize_input(char *ip) { int argc_size = 5; int argv = 0; char **argc; argc = malloc(argc_size*sizeof(char*)); int i = 0; while(is_space(ip[i])) i++; while(ip[i]) { argc[argv] = &ip[i]; argv++; if(argv == argc_size) { argc = realloc(argc, 2*argc_size*sizeof(char*)); argc_size = 2*argc_size; } while(!is_space(ip[i]) && ip[i]) i++; while(is_space(ip[i]) && ip[i]) i++; if(ip[i]) ip[i-1] = '\0'; } aos_rpc_serial_putchar(get_init_rpc(), '\n'); for(int j=0; j<argv; j++) { if(strncmp(argc[j], "<", 1) == 0) { inputRedirect = 1; if((j+1) == argv) { SHELL_PRINTF(fout, "Input Redirection File Missing\n"); return BASH_ERR_SYNTAX; }else { fin = fopen(argc[j+1], "r"); } }else if(strncmp(argc[j], "<<", 2) == 0) { inputRedirect = 2; if((j+1) == argv) { SHELL_PRINTF(fout, "Input Redirection File Missing\n"); return BASH_ERR_SYNTAX; }else { fin = fopen(argc[j+1], "r"); } }else if(strncmp(argc[j], ">", 1) == 0) { outputRedirect = 1; if((j+1) == argv) { SHELL_PRINTF(fout, "Output Redirection File Missing\n"); return BASH_ERR_SYNTAX; }else { fout = fopen(argc[j+1], "w+"); } }else if(strncmp(argc[j], ">>", 1) == 0) { outputRedirect = 2; if((j+1) == argv) { SHELL_PRINTF(fout, "Output Redirection File Missing\n"); return BASH_ERR_SYNTAX; }else { fout = fopen(argc[j+1], "a"); int t = fseek(fout, -1, SEEK_END); printf("%d\n", t); if(fout == NULL) { printf("Fuck me!!\n"); } } } } execute_command(argc, argv); clean_buffer(); printf("\n"); SHELL_PRINTF(fout, "$bash>"); fflush(stdout); return SYS_ERR_OK; } void execute_command(char *argc[], int argv) { /* List of commands - [OK] echo - [OK] led - [OK] threads - [OK] memtest - [OK] oncore - [OK] ps - [OK] help - [OK] pwd - [OK] cd - [OK] ls - [OK] cat - [Ok] wc - [OK] grep - [OK] mkdir - [OK] rmdir - [OK] rm */ if(argv > 0) { if(strncmp(argc[0], "echo", 4) == 0) { handle_echo(argc, argv); }else if(strncmp(argc[0], "led", 3) == 0){ handle_light_led(argc, argv); }else if(strncmp(argc[0], "threads", 7) == 0){ handle_threads(argc, argv); }else if(strncmp(argc[0], "memtest", 7) == 0){ handle_memtest(argc, argv); }else if(strncmp(argc[0], "oncore", 6) == 0){ handle_oncore(argc, argv); }else if(strncmp(argc[0], "ps", 2) == 0){ handle_ps(argc, argv); }else if(strncmp(argc[0], "help", 4) == 0){ handle_help(argc, argv); }else if(strncmp(argc[0], "pwd", 3) == 0){ handle_pwd(argc, argv); }else if(strncmp(argc[0], "cd", 2) == 0){ handle_cd(argc, argv); }else if(strncmp(argc[0], "ls", 2) == 0){ handle_ls(argc, argv); }else if(strncmp(argc[0], "cat", 3) == 0){ handle_cat(argc, argv); }else if(strncmp(argc[0], "wc", 2) == 0){ handle_wc(argc, argv); }else if(strncmp(argc[0], "grep", 4) == 0){ handle_grep(argc, argv); }else if(strncmp(argc[0], "mkdir", 5) == 0){ handle_mkdir(argc, argv); }else if(strncmp(argc[0], "clear", 5) == 0){ handle_clear(argc, argv); }else if(strncmp(argc[0], "rmdir", 5) == 0){ handle_rmdir(argc, argv); }else if(strncmp(argc[0], "rm", 2) == 0){ handle_rm(argc, argv); }else{ handle_spawn(argc, argv); } } } int main(int argc, char *argv[]) { debug_printf("size of commands %d\n", sizeof(commands)/sizeof(commands[0])); filesystem_init(); fin = stdin; fout = stdout; wd = malloc(max_len_wd); input = malloc(buf_size); wd[0] = '/'; wd[1] = '\0'; pos_wd++; FILE *fp; fp = fopen("/file.txt", "w+"); fprintf(fp, "%s %s\n", "Hello", "World"); fprintf(fp, "%s %s\n", "Hello1", "World"); fclose(fp); mkdir("/hello"); fp = fopen("/hello/file1.txt", "w+"); fprintf(fp, "%s %s\n", "Hello new", "World"); fprintf(fp, "%s %s\n", "Hello1 new", "World"); fclose(fp); errval_t err; err = aos_rpc_get_irq_cap(get_init_rpc(), &cap_irq); if (err_is_fail(err)) { USER_PANIC_ERR(err, "bash_get_irq_cap failed"); } err = inthandler_setup_arm(terminal_read_handler, NULL, 106); DEBUG_ERR(err, "Setting up inthandler_setup_arm\n"); printf("\033[2J"); printf("Starting bash\n"); printf("Hello from the bash\n"); SHELL_PRINTF(fout, "$bash>"); fflush(stdout); // domainid_t newpid; // aos_rpc_process_spawn(get_init_rpc(), "hello", 0, &newpid); // aos_rpc_process_spawn(get_init_rpc(), "byebye", 0, &newpid); // struct thread *t = thread_create((thread_func_t) pesudo_task, NULL); // struct thread *t1 = thread_create((thread_func_t) pesudo_task, NULL); // struct thread *t2 = thread_create((thread_func_t) pesudo_task, NULL); // thread_join(t, NULL); // thread_join(t1, NULL); // thread_join(t2, NULL); struct waitset *default_ws = get_default_waitset(); while(true) { err = event_dispatch(default_ws); if (err_is_fail(err)) { DEBUG_ERR(err, "in event_dispatch"); abort(); } } return 0; }
25.206591
87
0.613988
[ "3d" ]
155ee3f924fe0875f07d7df36d5f533ea75d920e
31,284
c
C
pg_log_userqueries.c
gleu/pg_log_userqueries
e2b2ffd07cff580657b18b3696fb5d487e15203d
[ "0BSD" ]
9
2018-07-05T14:36:17.000Z
2022-02-08T04:04:30.000Z
pg_log_userqueries.c
gleu/pg_log_userqueries
e2b2ffd07cff580657b18b3696fb5d487e15203d
[ "0BSD" ]
17
2015-09-10T20:46:16.000Z
2022-03-29T11:58:16.000Z
pg_log_userqueries.c
gleu/pg_log_userqueries
e2b2ffd07cff580657b18b3696fb5d487e15203d
[ "0BSD" ]
8
2016-09-23T09:08:38.000Z
2022-03-31T10:33:44.000Z
/*------------------------------------------------------------------------- * * pg_log_userqueries.c * Log statement according to the user. * * * Copyright (c) 2011-2021, Guillaume Lelarge (Dalibo), * guillaume.lelarge@dalibo.com * *------------------------------------------------------------------------- */ #include "postgres.h" #include <unistd.h> #include <regex.h> #include <syslog.h> #include <sys/stat.h> #include <time.h> /* to log statement duration */ #include <utils/timestamp.h> #include <access/xact.h> #include <storage/proc.h> /* * We won't use PostgreSQL regexps, * and as they redefine some system regexps types, we make sure we don't * redefine them */ #define _REGEX_H_ #include "funcapi.h" #include "tcop/utility.h" #include "libpq/libpq-be.h" /* For Port▸▸ ▸ ▸ ▸ ▸ */ #include "miscadmin.h" /* For MyProcPort▸ ▸ ▸ ▸ */ PG_MODULE_MAGIC; #ifndef PG_SYSLOG_LIMIT #define PG_SYSLOG_LIMIT 1024 #endif /*---- Local variables ----*/ static const struct config_enum_entry server_message_level_options[] = { {"debug", DEBUG2, true}, {"debug5", DEBUG5, false}, {"debug4", DEBUG4, false}, {"debug3", DEBUG3, false}, {"debug2", DEBUG2, false}, {"debug1", DEBUG1, false}, {"info", INFO, false}, {"notice", NOTICE, false}, {"warning", WARNING, false}, {"error", ERROR, false}, {"log", LOG, false}, {"fatal", FATAL, false}, {"panic", PANIC, false}, {NULL, 0, false} }; static const struct config_enum_entry log_destination_options[] = { {"stderr", 1, false}, {"syslog", 2, false}, {NULL, 0} }; static const struct config_enum_entry syslog_facility_options[] = { {"local0", LOG_LOCAL0, false}, {"local1", LOG_LOCAL1, false}, {"local2", LOG_LOCAL2, false}, {"local3", LOG_LOCAL3, false}, {"local4", LOG_LOCAL4, false}, {"local5", LOG_LOCAL5, false}, {"local6", LOG_LOCAL6, false}, {"local7", LOG_LOCAL7, false}, {NULL, 0} }; static int log_level = WARNING; static char * log_label = NULL; static char * log_user = NULL; static char * log_user_blacklist = NULL; static char * log_db = NULL; static char * log_db_blacklist = NULL; static char * log_addr = NULL; static char * log_addr_blacklist = NULL; static char * log_query = NULL; static char * log_query_blacklist = NULL; static char * log_app = NULL; static char * log_app_blacklist = NULL; static bool log_superusers = false; static int regex_flags = REG_NOSUB; static regex_t usr_regexv; static regex_t usr_bl_regexv; static regex_t db_regexv; static regex_t db_bl_regexv; static regex_t addr_regexv; static regex_t addr_bl_regexv; static regex_t app_regexv; static regex_t app_bl_regexv; static regex_t query_regexv; static regex_t query_bl_regexv; static bool openlog_done = false; static char * syslog_ident = NULL; static int log_destination = 1; /* aka stderr */ static int syslog_facility = LOG_LOCAL0; static int syslog_level = LOG_NOTICE; static time_t ref_time = 0; static char * file_switchoff = NULL; static bool switch_off = false; static int time_switchoff = 300; static bool match_all = false; static bool enable_log_duration = false; /* Saved hook values in case of unload */ static ExecutorEnd_hook_type prev_ExecutorEnd = NULL; #if PG_VERSION_NUM >= 90000 static ProcessUtility_hook_type prev_ProcessUtility = NULL; #endif /*---- Function declarations ----*/ void _PG_init(void); void _PG_fini(void); static void pgluq_ExecutorEnd(QueryDesc *queryDesc); #if PG_VERSION_NUM >= 130000 static void pgluq_ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc); #elif PG_VERSION_NUM >= 100000 static void pgluq_ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag); #elif PG_VERSION_NUM >= 90300 static void pgluq_ProcessUtility(Node *parsetree, const char *queryString, ProcessUtilityContext context, ParamListInfo params, DestReceiver *dest, char *completionTag); #elif PG_VERSION_NUM >= 90000 static void pgluq_ProcessUtility(Node *parsetree, const char *queryString, ParamListInfo params, bool isTopLevel, DestReceiver *dest, char *completionTag); #endif static bool pgluq_check_log(void); static void pgluq_log(const char *query); static void write_syslog(int level, char *line); static char *log_prefix(const char *query); static bool check_switchoff(void); static bool check_time_switch(void); extern char *get_database_name(Oid dbid); extern int pg_mbcliplen(const char *mbstr, int len, int limit); static bool pgluq_checkitem(const char *item, const char *log_wl, regex_t *regex_wl, const char *log_bl, regex_t *regex_bl); /* * Module load callback */ void _PG_init(void) { /* * In order to create our shared memory area, we have to be loaded via * shared_preload_libraries. If not, fall out without hooking into any of * the main system. (We don't throw error here because it seems useful to * allow the pgluq_log functions to be created even when the module * isn't active. The functions must protect themselves against * being called then, however.) */ if (!process_shared_preload_libraries_in_progress) return; /* * Define (or redefine) custom GUC variables. */ DefineCustomStringVariable( "pg_log_userqueries.log_label", "Label in front of the user query.", NULL, &log_label, "pg_log_userqueries", PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomEnumVariable( "pg_log_userqueries.log_level", "Selects level of log (same options than log_min_messages).", NULL, &log_level, log_level, server_message_level_options, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomStringVariable( "pg_log_userqueries.log_user", "Log statement according to the given user.", NULL, &log_user, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_user_blacklist", "Do not log statement from user in this list.", NULL, &log_user_blacklist, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_db", "Log statement according to the given database.", NULL, &log_db, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_db_blacklist", "Do not log statement in databases in this list.", NULL, &log_db_blacklist, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_addr", "Log statement according to the given client IP address.", NULL, &log_addr, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_addr_blacklist", "Do not log statement from addresses in this list.", NULL, &log_addr_blacklist, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_app", "Log statement according to the given application name.", NULL, &log_app, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomStringVariable( "pg_log_userqueries.log_app_blacklist", "Do not log statement from the applications in this list.", NULL, &log_app_blacklist, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomEnumVariable( "pg_log_userqueries.log_destination", "Selects log destination (either stderr or syslog).", NULL, &log_destination, log_destination, log_destination_options, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomEnumVariable( "pg_log_userqueries.syslog_facility", "Selects syslog level of log (same options than PostgreSQL syslog_facility).", NULL, &syslog_facility, syslog_facility, syslog_facility_options, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomStringVariable( "pg_log_userqueries.syslog_ident", "Select syslog program identity name.", NULL, &syslog_ident, "pg_log_userqueries", PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomBoolVariable( "pg_log_userqueries.log_superusers", "Enable log of superusers.", NULL, &log_superusers, false, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomStringVariable( "pg_log_userqueries.file_switchoff", "If file exists, owned by root with the right properties, switch off the trace log.", NULL, &file_switchoff, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomIntVariable( "pg_log_userqueries.time_switchoff", "Time interval between file_switchoff existence checks.", NULL, &time_switchoff, 300, /* 5 min by default */ 30, 3600, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomStringVariable( "pg_log_userqueries.log_query", "Log statement according to the given regular expression.", NULL, &log_query, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomBoolVariable( "pg_log_userqueries.match_all", "Log statement only when all defined conditions for log_user, log_db, log_addr, log_app and log_query match.", NULL, &match_all, false, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); DefineCustomStringVariable( "pg_log_userqueries.log_query_blacklist", "Do not log statement in this list.", NULL, &log_query_blacklist, NULL, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL ); DefineCustomBoolVariable( "pg_log_userqueries.log_duration", "Enable log of query duration.", NULL, &enable_log_duration, false, PGC_POSTMASTER, 0, #if PG_VERSION_NUM >= 90100 NULL, #endif NULL, NULL); /* Add support to extended regex search */ regex_flags |= REG_EXTENDED; /* Compile regexp for user name */ if (log_user != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_user) + 5)); sprintf(tmp, "^(%s)$", log_user); if (regcomp(&usr_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid user pattern %s", tmp))); log_user = NULL; } pfree(tmp); } /* Compile regexp for user name blacklist */ if (log_user_blacklist != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_user_blacklist) + 5)); sprintf(tmp, "^(%s)$", log_user_blacklist); if (regcomp(&usr_bl_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid user blacklist pattern %s", tmp))); log_user_blacklist = NULL; } pfree(tmp); } /* Compile regexp for db name */ if (log_db != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_db) + 5)); sprintf(tmp, "^(%s)$", log_db); if (regcomp(&db_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid database pattern %s", tmp))); log_db = NULL; } pfree(tmp); } /* Compile regexp for db name blacklist */ if (log_db_blacklist != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_db_blacklist) + 5)); sprintf(tmp, "^(%s)$", log_db_blacklist); if (regcomp(&db_bl_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid database blacklist pattern %s", tmp))); log_db_blacklist = NULL; } pfree(tmp); } /* Compile regexp for inet addr */ if (log_addr != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_addr) + 5)); sprintf(tmp, "^(%s)$", log_addr); if (regcomp(&addr_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid address pattern %s", tmp))); log_addr = NULL; } pfree(tmp); } /* Compile regexp for inet addr blacklist */ if (log_addr_blacklist != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_addr_blacklist) + 5)); sprintf(tmp, "^(%s)$", log_addr_blacklist); if (regcomp(&addr_bl_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid address blacklist pattern %s", tmp))); log_addr_blacklist = NULL; } pfree(tmp); } /* Compile regexp for application name */ if (log_app != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_app) + 5)); sprintf(tmp, "^(%s)$", log_app); if (regcomp(&app_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid application name pattern %s", tmp))); log_app = NULL; } pfree(tmp); } /* Compile regexp for application name blacklist */ if (log_app_blacklist != NULL) { char *tmp; tmp = palloc(sizeof(char) * (strlen(log_app_blacklist) + 5)); sprintf(tmp, "^(%s)$", log_app_blacklist); if (regcomp(&app_bl_regexv, tmp, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid application name blacklist pattern %s", tmp))); log_app_blacklist = NULL; } pfree(tmp); } /* Compile rexgep to log statement */ if (log_query != NULL) { if (regcomp(&query_regexv, log_query, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid statement regexp pattern %s", log_query))); log_query = NULL; } } /* Compile rexgep from the log statement blacklist */ if (log_query_blacklist != NULL) { if (regcomp(&query_bl_regexv, log_query_blacklist, regex_flags) != 0) { ereport(ERROR, (errcode(ERRCODE_OBJECT_NOT_IN_PREREQUISITE_STATE), errmsg("pg_log_userqueries: invalid statement regexp blacklist pattern %s", log_query_blacklist))); log_query_blacklist = NULL; } } /* Open syslog descriptor, if required */ if (log_destination == 2 /* aka syslog */) { /* Find syslog_level according to the user log_level setting */ switch (log_level) { case DEBUG5: case DEBUG4: case DEBUG3: case DEBUG2: case DEBUG1: syslog_level = LOG_DEBUG; break; case LOG: case COMMERROR: case INFO: syslog_level = LOG_INFO; break; case NOTICE: case WARNING: syslog_level = LOG_NOTICE; break; case ERROR: syslog_level = LOG_WARNING; break; case FATAL: syslog_level = LOG_ERR; break; case PANIC: default: syslog_level = LOG_CRIT; break; } /* Open syslog descriptor */ openlog(syslog_ident, LOG_PID | LOG_NDELAY | LOG_NOWAIT, syslog_facility); openlog_done = true; } /* * Install hooks. */ prev_ExecutorEnd = ExecutorEnd_hook; ExecutorEnd_hook = pgluq_ExecutorEnd; #if PG_VERSION_NUM >= 90000 prev_ProcessUtility = ProcessUtility_hook; ProcessUtility_hook = pgluq_ProcessUtility; #endif } /* * Module unload callback */ void _PG_fini(void) { /* Close syslog descriptor, if required */ if (openlog_done) { closelog(); openlog_done = false; } /* Uninstall hooks. */ ExecutorEnd_hook = prev_ExecutorEnd; #if PG_VERSION_NUM >= 90000 ProcessUtility_hook = prev_ProcessUtility; #endif /* free the memory allocated by regcomp. * This is safe since we made sure the log_* parameters where reset * to NULL in case regcomp fails. */ if (log_user != NULL) regfree(&usr_regexv); if (log_user_blacklist != NULL) regfree(&usr_bl_regexv); if (log_db != NULL) regfree(&db_regexv); if (log_db_blacklist != NULL) regfree(&db_bl_regexv); if (log_addr != NULL) regfree(&addr_regexv); if (log_addr_blacklist != NULL) regfree(&addr_bl_regexv); if (log_app != NULL) regfree(&app_regexv); if (log_app_blacklist != NULL) regfree(&app_bl_regexv); if (log_query != NULL) regfree(&query_regexv); if (log_query_blacklist != NULL) regfree(&query_bl_regexv); } /* * ExecutorEnd hook: store results if needed */ static void pgluq_ExecutorEnd(QueryDesc *queryDesc) { if (pgluq_check_log()) pgluq_log(queryDesc->sourceText); if (prev_ExecutorEnd) prev_ExecutorEnd(queryDesc); else standard_ExecutorEnd(queryDesc); } /* * ProcessUtility hook * (only available from 9.0 releases) */ #if PG_VERSION_NUM >= 130000 static void pgluq_ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, QueryCompletion *qc) { PG_TRY(); { if (prev_ProcessUtility) prev_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, qc); else standard_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, qc); } PG_CATCH(); { PG_RE_THROW(); } PG_END_TRY(); if (pgluq_check_log()) pgluq_log(queryString); } #elif PG_VERSION_NUM >= 100000 static void pgluq_ProcessUtility(PlannedStmt *pstmt, const char *queryString, ProcessUtilityContext context, ParamListInfo params, QueryEnvironment *queryEnv, DestReceiver *dest, char *completionTag) { PG_TRY(); { if (prev_ProcessUtility) prev_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, completionTag); else standard_ProcessUtility(pstmt, queryString, context, params, queryEnv, dest, completionTag); } PG_CATCH(); { PG_RE_THROW(); } PG_END_TRY(); if (pgluq_check_log()) pgluq_log(queryString); } #elif PG_VERSION_NUM >= 90300 static void pgluq_ProcessUtility(Node *parsetree, const char *queryString, ProcessUtilityContext context, ParamListInfo params, DestReceiver *dest, char *completionTag) { PG_TRY(); { if (prev_ProcessUtility) prev_ProcessUtility(parsetree, queryString, context, params, dest, completionTag); else standard_ProcessUtility(parsetree, queryString, context, params, dest, completionTag); } PG_CATCH(); { PG_RE_THROW(); } PG_END_TRY(); if (pgluq_check_log()) pgluq_log(queryString); } #elif PG_VERSION_NUM >= 90000 static void pgluq_ProcessUtility(Node *parsetree, const char *queryString, ParamListInfo params, bool isTopLevel, DestReceiver *dest, char *completionTag) { PG_TRY(); { if (prev_ProcessUtility) prev_ProcessUtility(parsetree, queryString, params, isTopLevel, dest, completionTag); else standard_ProcessUtility(parsetree, queryString, params, isTopLevel, dest, completionTag); } PG_CATCH(); { PG_RE_THROW(); } PG_END_TRY(); if (pgluq_check_log()) pgluq_log(queryString); } #endif /* * Check an item */ static bool pgluq_checkitem(const char *item, const char *log_wl, regex_t *regex_wl, const char *log_bl, regex_t *regex_bl) { bool has_passed_wl = true; bool has_passed_bl = true; if ((log_wl != NULL) && (regexec(regex_wl, item, 0, 0, 0) != 0)) has_passed_wl = false; if ((log_bl != NULL) && (regexec(regex_bl, item, 0, 0, 0) == 0)) has_passed_bl= false; if (! has_passed_wl || ! has_passed_bl) { return false; } return true; } /* * Check if we should log */ static bool pgluq_check_log() { /* object's name */ char *dbname = NULL; char *username = NULL; char *addr = NULL; char *appname = NULL; bool ret = false; bool rc; if (check_switchoff()) return false; #if PG_VERSION_NUM >= 90602 /* * We don't want to log the activity of background workers. */ if (MyProc->isBackgroundWorker) return false; #endif /* Get the user name */ #if PG_VERSION_NUM >= 90500 username = GetUserNameFromId(GetUserId(), false); #else username = GetUserNameFromId(GetUserId()); #endif /* Get the database name */ dbname = get_database_name(MyDatabaseId); if (MyProcPort) appname = application_name; #if PG_VERSION_NUM < 90602 /* * If there are no username and dbname set, it's a background worker * and we don't want to log that kind of activity */ if (!username && !dbname && !appname) return false; #endif /* * Default behavior * log only superuser queries */ if ((log_db == NULL) && (log_db_blacklist == NULL) && (log_user == NULL) && (log_user_blacklist == NULL) && (log_addr == NULL) && (log_app_blacklist == NULL) && (log_app == NULL) && (log_addr_blacklist == NULL) && (log_query == NULL) &&(log_query_blacklist == NULL) && superuser()) return true; /* * New behaviour if superuser and log_superuser are true, then log * if log_db, log_db_blacklist, log_user, log_user_blacklist, log_addr, * log_addr_blacklist, log_app or log_app_blacklist is set, then log if * regexp matches */ /* Check superuser */ if (log_superusers && superuser()) { if (match_all == false) return true; else ret = true; } /* Check the user name */ if (log_user != NULL || log_user_blacklist != NULL) { rc = pgluq_checkitem( username, log_user, &usr_regexv, log_user_blacklist, &usr_bl_regexv); if (match_all) { if (rc) ret = true; else return false; } else { if (rc) return true; } } /* Check the database name */ if (log_db != NULL || log_db_blacklist != NULL) { rc =pgluq_checkitem( dbname, log_db, &db_regexv, log_db_blacklist, &db_bl_regexv); if (match_all) { if (rc) ret = true; else return false; } else { if (rc) return true; } } /* Check the application name */ if (log_app != NULL || log_app_blacklist != NULL) { rc = pgluq_checkitem( appname, log_app, &app_regexv, log_app_blacklist, &app_bl_regexv); if (match_all) { if (rc) ret = true; else return false; } else { if (rc) return true; } } /* Check the inet address */ if ((log_addr != NULL || log_addr_blacklist != NULL) && MyProcPort) { addr = MyProcPort->remote_host; rc = pgluq_checkitem( addr, log_addr, &addr_regexv, log_addr_blacklist, &addr_bl_regexv); if (match_all) { if (rc) ret = true; else return false; } else { if (rc) return true; } } /* Didn't find any interesting condition */ return ret; } /* * Log statement according to the user that launched the statement. */ static void pgluq_log(const char *query) { char *tmp_log_query = NULL; Assert(query != NULL); /* Filter querries according to the white and black list*/ if (log_query != NULL || log_query_blacklist != NULL) { if ( ! pgluq_checkitem( query, log_query, &query_regexv, log_query_blacklist, &query_bl_regexv)) return; } tmp_log_query = log_prefix(query); if (tmp_log_query != NULL) { /* * Write a message line to syslog or elog * depending on the fact that we opened syslog at the beginning */ if (openlog_done) write_syslog(syslog_level, tmp_log_query); else ereport(log_level, (errmsg("%s", tmp_log_query), errhidestmt(true))); /* Free the string */ pfree(tmp_log_query); } } /* * Format tag info for log lines; append to the provided buffer. */ static char * log_prefix(const char *query) { int i; int format_len; char *tmp_log_query = NULL; char pid[10]; char duration_msg[60]; /* Log duration if available */ if (enable_log_duration) { long secs; int usecs; int msecs; TimestampDifference(GetCurrentStatementStartTimestamp(), GetCurrentTimestamp(), &secs, &usecs); msecs = usecs / 1000; snprintf(duration_msg, 60, "duration: %ld.%03d ms statement: ",secs * 1000 + msecs, usecs % 1000); } else strcpy(duration_msg, "statement: "); /* Allocate the new log string */ tmp_log_query = palloc(strlen(log_label) + strlen(duration_msg) + strlen(query) + 4096); if (tmp_log_query == NULL) return NULL; /* not sure why this is needed */ tmp_log_query[0] = '\0'; /* Parse the log_label string */ format_len = strlen(log_label); for (i = 0; i < format_len; i++) { if (log_label[i] != '%') { /* literal char, just copy */ strncat(tmp_log_query, log_label+i, 1); continue; } /* go to char after '%' */ i++; if (i >= format_len) break; /* format error - ignore it */ /* process the option */ switch (log_label[i]) { #if PG_VERSION_NUM >= 90000 case 'a': if (MyProcPort) { const char *appname = application_name; if (appname == NULL || *appname == '\0') appname = _("[unknown]"); strncat(tmp_log_query, appname, strlen(appname)); } break; #endif case 'u': if (MyProcPort) { #if PG_VERSION_NUM >= 90500 const char *username = GetUserNameFromId(GetUserId(), false); #else const char *username = GetUserNameFromId(GetUserId()); #endif if (username == NULL || *username == '\0') username = _("[unknown]"); strncat(tmp_log_query, username, strlen(username)); } break; case 'd': if (MyProcPort) { const char *dbname = get_database_name(MyDatabaseId); if (dbname == NULL || *dbname == '\0') dbname = _("[unknown]"); strncat(tmp_log_query, dbname, strlen(dbname)); } break; case 'p': sprintf(pid, "%d", MyProcPid); strcat(tmp_log_query, pid); break; case '%': strcat(tmp_log_query, "%"); break; default: /* format error - ignore it */ break; } } /* Check if there's a space at the end, and add one if there isn't */ if (strlen(tmp_log_query) > 0 && strcmp(&tmp_log_query[strlen(tmp_log_query)-1], " ")) strcat(tmp_log_query, " "); /* add duration information if available */ if (strlen(duration_msg) > 0) strcat(tmp_log_query, duration_msg); /* Add the query at the end */ strcat(tmp_log_query, query); /* Return the whole string */ return tmp_log_query; } /* * Write a message line to syslog */ static void write_syslog(int level, char *line) { static unsigned long seq = 0; int len; const char *nlpos; /* * We add a sequence number to each log message to suppress "same" * messages. */ seq++; /* * Our problem here is that many syslog implementations don't handle long * messages in an acceptable manner. While this function doesn't help that * fact, it does work around by splitting up messages into smaller pieces. * * We divide into multiple syslog() calls if message is too long or if the * message contains embedded newline(s). */ len = strlen(line); nlpos = strchr(line, '\n'); if (len > PG_SYSLOG_LIMIT || nlpos != NULL) { int chunk_nr = 0; while (len > 0) { char buf[PG_SYSLOG_LIMIT + 1]; int buflen; int i; /* if we start at a newline, move ahead one char */ if (line[0] == '\n') { line++; len--; /* we need to recompute the next newline's position, too */ nlpos = strchr(line, '\n'); continue; } /* copy one line, or as much as will fit, to buf */ if (nlpos != NULL) buflen = nlpos - line; else buflen = len; buflen = Min(buflen, PG_SYSLOG_LIMIT); memcpy(buf, line, buflen); buf[buflen] = '\0'; /* trim to multibyte letter boundary */ buflen = pg_mbcliplen(buf, buflen, buflen); if (buflen <= 0) return; buf[buflen] = '\0'; /* already word boundary? */ if (line[buflen] != '\0' && !isspace((unsigned char) line[buflen])) { /* try to divide at word boundary */ i = buflen - 1; while (i > 0 && !isspace((unsigned char) buf[i])) i--; /* else couldn't divide word boundary */ if (i > 0) { buflen = i; buf[i] = '\0'; } } chunk_nr++; syslog(level, "[%lu-%d] %s", seq, chunk_nr, buf); line += buflen; len -= buflen; } } else { /* message short enough */ syslog(level, "[%lu] %s", seq, line); } } /* * Check if we have reached the time interval defined (time_switchoff) * Default value is 300 seconds (if not set or out of range) * Valid range is from 30 to 3600 seconds */ static bool check_time_switch(void) { bool time2check = false; time_t cur_time; int save_errno; if (time(&cur_time) == -1) { save_errno = errno; elog(log_level, "Unable to get current time: %s (%d).", #if PG_VERSION_NUM >= 120000 pg_strerror(save_errno), #else strerror(save_errno), #endif save_errno); } if ((int)(cur_time-ref_time) > time_switchoff) { time2check = true; ref_time = cur_time; } return time2check; } /* * Function to determine if pg_log_userqueries needs to be de/re-activated on the fly. * Allows to switch off/on the function without restarting PostgreSQL. * Check if file_switchoff string has been set and exists. * This check is done at server startup and every time_switchoff interval. * This means that if the file is created, each new connection will be affected. * Others will have to wait the time interval change for detection. */ static bool check_switchoff(void) { struct stat stat_file_switchoff; int r_stat; int save_errno; if (file_switchoff == NULL) return false; if (check_time_switch()) { if ((r_stat = stat(file_switchoff, &stat_file_switchoff)) < 0 ) { if (errno != 2) { save_errno = errno; elog(WARNING, "Unable to get switchoff file stats (%s): %s (%d).", file_switchoff, #if PG_VERSION_NUM >= 120000 pg_strerror(save_errno), #else strerror(errno), #endif save_errno); } if (switch_off) /* write once */ elog(NOTICE, "Switch off file unfound. Switching on pg_log_userqueries."); switch_off = false; } else /* Permissions checking */ { if (stat_file_switchoff.st_uid != 0 || /* owner root */ stat_file_switchoff.st_gid != 0 || /* group root */ !S_ISREG(stat_file_switchoff.st_mode) || /* regular file */ (stat_file_switchoff.st_mode & (S_IXOTH|S_IWOTH|S_IROTH|S_IXGRP|S_IWGRP|S_IRGRP))) { /* No permissions for group and others: there is a security risk */ elog(WARNING, "File %s found with incorrect owner or permission.\n" "It should belong to root.root, be regular, and have no permission for group/others.", file_switchoff ); switch_off = false; } else { if (!switch_off) /* write once */ elog(NOTICE, "Switch off file found. Switching off pg_log_userqueries."); switch_off = true; } } } return switch_off; }
24.652482
169
0.669256
[ "object" ]
156bfecf78c12ac7ee95432df35bad6c777987a7
2,421
h
C
Include/cpio.h
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
9
2016-05-27T01:00:39.000Z
2021-04-01T08:54:46.000Z
Include/cpio.h
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
1
2016-03-03T22:54:08.000Z
2016-03-03T22:54:08.000Z
Include/cpio.h
mfaithfull/QOR
0fa51789344da482e8c2726309265d56e7271971
[ "BSL-1.0" ]
4
2016-05-27T01:00:43.000Z
2018-08-19T08:47:49.000Z
//cpio.h // Copyright Querysoft Limited 2015 // // Permission is hereby granted, free of charge, to any person or organization // obtaining a copy of the software and accompanying documentation covered by // this license (the "Software") to use, reproduce, display, distribute, // execute, and transmit the Software, and to prepare derivative works of the // Software, and to permit third-parties to whom the Software is furnished to // do so, all subject to the following: // // The copyright notices in the Software and this entire statement, including // the above license grant, this restriction and the following disclaimer, // must be included in all copies of the Software, in whole or in part, and // all derivative works of the Software, unless such copies or derivative // works are solely in the form of machine-executable object code generated by // a source language processor. // // 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT // SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE // FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, // ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #ifndef QOR_CPIO_H_3 #define QOR_CPIO_H_3 #include "SystemQOR.h" #include QOR_SYS_PLATFORMTYPES(cpio) # define C_IRUSR 0000400 //Read by owner # define C_IWUSR 0000200 //Write by owner # define C_IXUSR 0000100 //Execute by owner # define C_IRGRP 0000040 //Read by group # define C_IWGRP 0000020 //Write by group # define C_IXGRP 0000010 //Execute by group # define C_IROTH 0000004 //Read by others # define C_IWOTH 0000002 //Write by others # define C_IXOTH 0000001 //Execute by others # define C_ISUID 0004000 //Set user ID # define C_ISGID 0002000 //Set group ID # define C_ISVTX 0001000 //On directories, restricted deletion flag # define C_ISDIR 0040000 //Directory # define C_ISFIFO 0010000 //FIFO # define C_ISREG 0100000 //Regular file # define C_ISBLK 0060000 //Block special # define C_ISCHR 0020000 //Character special # define C_ISCTG 0110000 //Reserved # define C_ISLNK 0120000 //Symbolic link # define C_ISSOCK 0140000 //Socket # define MAGIC "070707" #endif//QOR_CPIO_H_3
42.473684
78
0.759603
[ "object" ]
156cc1827b0f959e9451d28b24caf87ec16216f3
1,031
h
C
MovieDb/UI/Views/MovieDbTableViewCell.h
wisesabre/MovieDbExample
9ee084a27054a8edcd62cda1dcc372bc5e9da19c
[ "Unlicense" ]
null
null
null
MovieDb/UI/Views/MovieDbTableViewCell.h
wisesabre/MovieDbExample
9ee084a27054a8edcd62cda1dcc372bc5e9da19c
[ "Unlicense" ]
null
null
null
MovieDb/UI/Views/MovieDbTableViewCell.h
wisesabre/MovieDbExample
9ee084a27054a8edcd62cda1dcc372bc5e9da19c
[ "Unlicense" ]
null
null
null
// // MovieDbTableViewCell.h // MovieDb // // Created by Saqib Saud on 13/02/2015. // Copyright (c) 2015 Saqib Saud. All rights reserved. // #import <UIKit/UIKit.h> @interface MovieDbTableViewCell : UITableViewCell @property (weak, nonatomic) IBOutlet UIImageView *thumnail; @property (weak, nonatomic) IBOutlet UILabel *name; @property (weak, nonatomic) IBOutlet UILabel *year; @property (weak, nonatomic) IBOutlet UILabel *popularity; /** * Returns UINib file initialized for this cell * * @return The initialized `UINib` object or `nil` if there were errors during * initialization or the nib file could not be located. */ + (UINib *)nib; /** * Returns the default string used to identify a reusable cell for text message items. * * @return The string used to identify a reusable cell. */ + (NSString *)cellReuseIdentifier; /** * * * @param movie CDMovie object to load cell properties */ - (void) setMovie:(CDMovie *) movie; /** * * * @return Height of cell */ + (CGFloat)heightForCell; @end
21.93617
87
0.703201
[ "object" ]
1570d4e592124749d983ec6116631547c6e6513f
3,354
h
C
MenuOption.h
blascarr/MVCino
ed8d6a8516d9e31360f374783451eccf41dace8b
[ "MIT" ]
null
null
null
MenuOption.h
blascarr/MVCino
ed8d6a8516d9e31360f374783451eccf41dace8b
[ "MIT" ]
null
null
null
MenuOption.h
blascarr/MVCino
ed8d6a8516d9e31360f374783451eccf41dace8b
[ "MIT" ]
null
null
null
/* Design and created by Victor LiquidMVC Author : ZGZMakerSpace Description: LiquidMVC.h version : 1.0 ZGZMakerSpace invests time and resources providing this open source code like some other libraries, please respect the job and support open-source software. Written by Victor for Zaragoza Maker Space */ #ifndef MENUOPTION_H #define MENUOPTION_H #include <limits.h> typedef void (*CallbackFunction)(void); class MenuOption{ public: enum class Type { NONE, INT_NUMBER, CALLBACK, LINK, TIMER }; MenuOption(char* name, Type type = Type::NONE): _name(name), _type(type){ } char* getName(void){ return _name; } Type getType(void){ return _type; } String getTypeName(void){ switch(_type) { case Type::INT_NUMBER: return "INT_VALUE"; break; case Type::CALLBACK: return "CALLBACK"; break; case Type::LINK: return "LINK"; break; case Type::NONE: default: return "NONE"; break; } } private: //const String _name; const char* _name; const Type _type; }; //--------------------------------------------------------// //-------------Definition Type for MenuMVC----------------// //--------------------------------------------------------// typedef Vector<MenuOption* > _menuMVC; typedef Vector<_menuMVC* > _systemMVC; //--------------------------------------------------------// //--------------Option Models for Menu--------------------// //--------------------------------------------------------// class MenuOptionIntValue: public MenuOption{ public: int _minValue; int _maxValue; int& _value; MenuOptionIntValue(char* name, int &value, int min = INT_MIN, int max = INT_MAX): MenuOption(name, Type::INT_NUMBER), _value(value), _minValue(min), _maxValue(max){ _v = value; } int* getValuePtr(void){ return _value; } int getValue(void){ return _v; } void dumpvalue(){ Serial.println("DUMP INT VALUES"); Serial.print("Intern VAL: "); Serial.println( _value ); Serial.print("\tReal VAL: "); Serial.println(_v); Serial.print("MIN VALUE "); Serial.println(_minValue); Serial.print("MAX VALUE "); Serial.println(_maxValue); Serial.println(); } private: int _v; }; class MenuOptionAction: public MenuOption{ public: MenuOptionAction(char* name, CallbackFunction function): MenuOption(name, Type::CALLBACK), _function(function){ } void ExecuteCallback(void){ if(_function != NULL) { _function(); } } private: CallbackFunction _function; }; // TODO: implement behaviour class MenuOptionLink: public MenuOption { public: _menuMVC* _link; MenuOptionLink(char* name): MenuOption(name, Type::LINK) { } MenuOptionLink(char* name, _menuMVC lnk ): MenuOption(name, Type::LINK), _link( &lnk ) { } void dumplink(){ Serial.println("Hola, soy un link a otro submenu"); } private: }; #endif
19.729412
110
0.524747
[ "vector" ]
1580524e0557f7a6767e8bd1ec47b81544f7dbec
2,794
h
C
src/geom/Vector2D.h
projectitis/mac
ea3d23f3352f6e193f23ffb7e3f296f4485e8501
[ "MIT" ]
1
2022-03-26T22:10:18.000Z
2022-03-26T22:10:18.000Z
src/geom/Vector2D.h
projectitis/mac
ea3d23f3352f6e193f23ffb7e3f296f4485e8501
[ "MIT" ]
52
2021-05-26T08:10:45.000Z
2022-03-30T07:23:51.000Z
src/geom/Vector2D.h
projectitis/mac
ea3d23f3352f6e193f23ffb7e3f296f4485e8501
[ "MIT" ]
null
null
null
/** * Vector functions for "mac/μac" * Author: Peter "Projectitis" Vullings <peter@projectitis.com> * Distributed under the MIT licence * * MIT LICENCE * ----------- * 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. */ /** * Vector2D physics functions **/ #pragma once #ifndef _MAC_VECTOR2D_H #define _MAC_VECTOR2D_H 1 namespace mac{ /** * Floating point Vector2D class */ class Vector2F { public: /** * Constructor */ Vector2F(); Vector2F( float_t x, float_t y ); /** * Angle in radians */ float_t a; /** * Magnitude */ float_t m; /** * Vector X */ float_t x; /** * Vector y */ float_t y; /** * Set the vector by angle and magnitude */ void set( float_t x, float_t y ); /** * Calculate the angle and magnitude based on x and y. Note that this * is done automatically after any of the methods that adust x and y, and * should only be called if you have manually changed x or y. */ void calc(); /** * Calculate the x and y based on angle and magnitude. Note that this * is done automatically after any of the methods that adust the angle or * magnitude, and should only be called if you have manually changed these. */ void calcXY(); /** * Add a vector to this one */ void add( Vector2F* v ); Vector2F* getAdded( Vector2F* v ); /** * Subtract a vector from this one */ void subtract( Vector2F* v ); Vector2F* getSubtracted( Vector2F* v ); /** * Normalise the vector */ void normalize(); Vector2F* getNormalized(); /** * Rotate the vector */ void rotate( float_t a ); Vector2F* getRotated( float_t a ); }; } // ns:mac #endif
22.901639
78
0.658196
[ "vector" ]
1581069a4ec4bb8d24b5182d9fd6a0e6a68c7cfa
792
h
C
src/omv/modules/py_tf.h
jiskra/openmv
a0f321836f77f94d8118910598dcdb79eb784d58
[ "MIT" ]
15
2021-06-15T08:01:41.000Z
2022-02-18T11:07:31.000Z
src/omv/modules/py_tf.h
jiskra/openmv
a0f321836f77f94d8118910598dcdb79eb784d58
[ "MIT" ]
null
null
null
src/omv/modules/py_tf.h
jiskra/openmv
a0f321836f77f94d8118910598dcdb79eb784d58
[ "MIT" ]
5
2021-07-02T00:48:33.000Z
2022-02-10T02:23:21.000Z
/* * This file is part of the OpenMV project. * * Copyright (c) 2013-2021 Ibrahim Abdelkader <iabdalkader@openmv.io> * Copyright (c) 2013-2021 Kwabena W. Agyeman <kwagyeman@openmv.io> * * This work is licensed under the MIT license, see the file LICENSE for details. * * Python Tensorflow library wrapper. */ #ifndef __PY_TF_H__ #define __PY_TF_H__ // PyTF model object handle typedef struct py_tf_model_obj { mp_obj_base_t base; unsigned char *model_data; unsigned int model_data_len, height, width, channels; bool signed_or_unsigned; bool is_float; } py_tf_model_obj_t; // Log buffer stuff #define PY_TF_PUTCHAR_BUFFER_LEN 1023 extern char *py_tf_putchar_buffer; extern size_t py_tf_putchar_buffer_len; void py_tf_alloc_putchar_buffer(); #endif // __PY_TF_H__
28.285714
81
0.765152
[ "object", "model" ]
1581d7afe821d4e99c093a561878616ce6dd4f15
1,630
h
C
lolnub/NubItemView.h
silljays/lolnubapp
553c2c4fdb6e0d449c8e2ee1dde9326b779a275d
[ "Apache-2.0" ]
null
null
null
lolnub/NubItemView.h
silljays/lolnubapp
553c2c4fdb6e0d449c8e2ee1dde9326b779a275d
[ "Apache-2.0" ]
1
2015-11-15T18:26:32.000Z
2015-11-15T18:26:32.000Z
lolnub/NubItemView.h
silljays/lolnubapp
553c2c4fdb6e0d449c8e2ee1dde9326b779a275d
[ "Apache-2.0" ]
null
null
null
// // NubItemView.h // lolnub // // Created by Anonymous on 10/31/13. // Copyright (c) 2014 lolnub.com developers All rights reserved. // #import <Cocoa/Cocoa.h> #import "NubItem.h" #import "NubItemCell.h" extern NSString *const NubItemViewSelectionDidChangeNotification; @interface NubItemView : NSView { NSPointArray gridPoints; NSInteger gridCols; NSInteger gridRows; } @property (weak) IBOutlet id delegate; @property (nonatomic, weak) IBOutlet id dataSource; @property (strong) NSColor *backgroundColor; @property BOOL dragging; @property NSPoint lastDragPoint; @property NSRect dragRect; @property NSPoint lastMouseDownPoint; @property NSTimeInterval lastMouseDownTime; @property (strong) NSMutableArray *selectedItems; // reset the entire view - (void)reloadData; // reset just the visual aspects of the view (ie. grid/icons) - (void)reloadLayout; // select all items - (void)selectAll:(id)sender; - (void)openSelected:(id)sender; @end @protocol NubItemViewDataSource // the items a view should render - (NSArray *)items; // how many pixels the items should be previewed at - (CGFloat)previewSize; @optional - (void)openSelectedItems:(id)sender; - (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)local; - (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender; - (BOOL)performDragOperation:(id <NSDraggingInfo>)sender; @end
25.46875
71
0.644785
[ "render" ]
158c322c38d48519eb2f44a40c2a256368016f9e
1,193
h
C
src/Sir.h
Lucas001/Simulator
2a66a1415004f90b2b58a69bc40ed98fe3717276
[ "MIT" ]
1
2018-10-11T20:33:00.000Z
2018-10-11T20:33:00.000Z
src/Sir.h
lucasbsimao/simVSSS
2a66a1415004f90b2b58a69bc40ed98fe3717276
[ "MIT" ]
null
null
null
src/Sir.h
lucasbsimao/simVSSS
2a66a1415004f90b2b58a69bc40ed98fe3717276
[ "MIT" ]
null
null
null
/*The MIT License (MIT) Copyright (c) 2016 Lucas Borsatto Simão 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. */ #ifndef SIR_H_ #define SIR_H_ #include "Header.h" //Standard colors of the simulator struct Color{ float r; float g; float b; Color(){} Color(float r0, float g0, float b0):r(r0),g(g0),b(b0){} }; //All rigid bodies are searched by the vector of BulletObject struct BulletObject{ int id; string name; Color clr; bool hit; btRigidBody* body; btVector3 halfExt; //Used only for compound shapes BulletObject(btRigidBody* b,string n,Color clr0) : name(n),body(b),clr(clr0),id(-1),hit(false),halfExt(btVector3(0,0,0)) {} }; #endif
27.744186
127
0.740151
[ "vector" ]
1593e909655713667e51a442b70b53601cb1f2b1
6,145
h
C
weex_core/Source/android/bridge/platform/android_side.h
sunshl/incubator-weex
40ae49e40c3dd725d6c546451075bd6e90001c9d
[ "Apache-2.0" ]
2
2017-10-18T01:36:31.000Z
2018-05-07T23:00:21.000Z
weex_core/Source/android/bridge/platform/android_side.h
sunshl/incubator-weex
40ae49e40c3dd725d6c546451075bd6e90001c9d
[ "Apache-2.0" ]
12
2019-07-09T05:55:28.000Z
2019-07-31T01:12:28.000Z
weex_core/Source/android/bridge/platform/android_side.h
sunshl/incubator-weex
40ae49e40c3dd725d6c546451075bd6e90001c9d
[ "Apache-2.0" ]
5
2019-05-28T11:48:42.000Z
2020-05-15T07:31:55.000Z
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ #ifndef WEEX_PROJECT_PLATFORM_SIDE_INSIMPLE_H #define WEEX_PROJECT_PLATFORM_SIDE_INSIMPLE_H #include "android/wrap/wx_bridge.h" #include "base/common.h" #include "core/bridge/platform_bridge.h" namespace WeexCore { class WMLBridge; class AndroidSide : public PlatformBridge::PlatformSide { public: AndroidSide(); virtual ~AndroidSide(); WXCoreSize InvokeMeasureFunction(const char* page_id, long render_ptr, float width, int width_measure_mode, float height, int height_measure_mode) override; void InvokeLayoutBefore(const char* page_id, long render_ptr) override; void InvokeLayoutPlatform(const char* page_id, long render_ptr) override; void InvokeLayoutAfter(const char* page_id, long render_ptr, float width, float height) override; void TriggerVSync(const char* page_id) override; void SetJSVersion(const char* version) override; void ReportException(const char* page_id, const char* func, const char* exception_string) override; void ReportServerCrash(const char* instance_id) override; void ReportNativeInitStatus(const char* status_code, const char* error_msg) override; int CallNative(const char* page_id, const char* task, const char* callback) override; std::unique_ptr<ValueWithType> CallNativeModule( const char* page_ld, const char* module, const char* method, const char* arguments, int arguments_length, const char* options, int options_length) override; void CallNativeComponent(const char* page_id, const char* ref, const char* method, const char* arguments, int arguments_length, const char* options, int options_length) override; void SetTimeout(const char* callback_id, const char* time) override; void NativeLog(const char* str_array) override; int UpdateFinish(const char* page_id, const char* task, int taskLen, const char* callback, int callbackLen) override; int RefreshFinish(const char* page_id, const char* task, const char* callback) override; int AddEvent(const char* page_id, const char* ref, const char* event) override; int RemoveEvent(const char* page_id, const char* ref, const char* event) override; int CreateBody(const char* pageId, const char* componentType, const char* ref, std::map<std::string, std::string>* styles, std::map<std::string, std::string>* attributes, std::set<std::string>* events, const WXCoreMargin& margins, const WXCorePadding& paddings, const WXCoreBorderWidth& borders) override; int AddElement(const char* pageId, const char* componentType, const char* ref, int& index, const char* parentRef, std::map<std::string, std::string>* styles, std::map<std::string, std::string>* attributes, std::set<std::string>* events, const WXCoreMargin& margins, const WXCorePadding& paddings, const WXCoreBorderWidth& borders, bool willLayout) override; int Layout(const char* page_id, const char* ref, float top, float bottom, float left, float right, float height, float width, bool isRTL, int index) override; int UpdateStyle( const char* pageId, const char* ref, std::vector<std::pair<std::string, std::string>>* style, std::vector<std::pair<std::string, std::string>>* margin, std::vector<std::pair<std::string, std::string>>* padding, std::vector<std::pair<std::string, std::string>>* border) override; int UpdateAttr( const char* pageId, const char* ref, std::vector<std::pair<std::string, std::string>>* attrs) override; int CreateFinish(const char* pageId) override; int RenderSuccess(const char* pageId) override; int RemoveElement(const char* pageId, const char* ref) override; int MoveElement(const char* pageId, const char* ref, const char* parentRef, int index) override; int AppendTreeCreateFinish(const char* pageId, const char* ref) override; int HasTransitionPros( const char* pageId, const char* ref, std::vector<std::pair<std::string, std::string>>* style) override; void PostMessage(const char* vm_id, const char* data, int dataLength) override; void DispatchMessage(const char* client_id, const char* data, int dataLength, const char* callback, const char* vm_id) override; std::unique_ptr<WeexJSResult> DispatchMessageSync(const char* client_id, const char* data, int dataLength, const char* vm_id) override; void OnReceivedResult(long callback_id, std::unique_ptr<WeexJSResult>& result) override; jobject getMeasureFunc(const char* pageId, jlong renderObjectPtr); private: WMLBridge* wml_bridge_; WXBridge* wx_bridge_; DISALLOW_COPY_AND_ASSIGN(AndroidSide); }; } // namespace WeexCore #endif // WEEX_PROJECT_PLATFORM_SIDE_INSIMPLE_H
47.635659
107
0.665256
[ "vector" ]
159ca862782dffbab9fe9bb9c26d65b845ebf287
821
c
C
fixture/SrcMLForCpp/input_code/mul_mv.c
exKAZUu/ParserTests
609cfc62b70c8d04d5a2ced25a213a8d601e7011
[ "Apache-2.0" ]
null
null
null
fixture/SrcMLForCpp/input_code/mul_mv.c
exKAZUu/ParserTests
609cfc62b70c8d04d5a2ced25a213a8d601e7011
[ "Apache-2.0" ]
null
null
null
fixture/SrcMLForCpp/input_code/mul_mv.c
exKAZUu/ParserTests
609cfc62b70c8d04d5a2ced25a213a8d601e7011
[ "Apache-2.0" ]
null
null
null
#include <stdio.h> int main(void) { int i, j; double x[3] = {-33.0, 9.0, 6.0}; double a[3][3] = {{2.0, 4.0, 6.0}, {3.0, 8.0, 7.0}, {5.0, 7.0, 12345678901234567890.0}}; double y[3]; /* print matrix and vector */ printf("x = \n"); for (i=0; i<3; i++) { printf("%6.2f\n", x[i]); } printf("A = \n"); for (i=0; i<3; i++) { for (j=0; j<3; j++) { printf(" %6.5f", a[i][j]); } printf("\n"); } /* multiplication */ for(i=0; i<3; i++){ y[i] = 0.0; for(j=0; j<3; j++){ y[i] += a[i][j]*x[j]; } } /* print answer */ printf("A*x = \n"); for(i=0; i<3; i++){ printf("%6.2f\n", y[i]); } return 0; }
17.468085
58
0.337393
[ "vector" ]
15a02bf35b20ef97a9fcdfe772cd55d5bc1a779c
604
h
C
src/goto-programs/remove_instanceof.h
lucasccordeiro/cbmc
9ae35de4db89e59e6bdbdfe5b2f77229d7f82eda
[ "BSD-4-Clause" ]
1
2021-09-09T06:09:03.000Z
2021-09-09T06:09:03.000Z
src/goto-programs/remove_instanceof.h
polgreen/cbmc
dd42ef89dabcd010ed63e089ced04f9a7b6f1199
[ "BSD-4-Clause" ]
39
2017-11-07T16:48:51.000Z
2017-12-04T15:24:01.000Z
src/goto-programs/remove_instanceof.h
danpoe/cbmc
9ae35de4db89e59e6bdbdfe5b2f77229d7f82eda
[ "BSD-4-Clause" ]
null
null
null
/*******************************************************************\ Module: Remove Instance-of Operators Author: Chris Smowton, chris.smowton@diffblue.com \*******************************************************************/ /// \file /// Remove Instance-of Operators #ifndef CPROVER_GOTO_PROGRAMS_REMOVE_INSTANCEOF_H #define CPROVER_GOTO_PROGRAMS_REMOVE_INSTANCEOF_H #include <util/symbol_table.h> #include "goto_functions.h" #include "goto_model.h" void remove_instanceof( symbol_tablet &symbol_table, goto_functionst &goto_functions); void remove_instanceof(goto_modelt &model); #endif
23.230769
69
0.622517
[ "model" ]
15a04ca7b675be01474fcebc49f2a56c243eae1b
19,124
c
C
N_Body_Simulation_Barnes_Hut_Algo/nbody.c
sagar-garg/Parallel-Programming
9de557fb136f408ef24fa437e53e850853928ac2
[ "MIT" ]
null
null
null
N_Body_Simulation_Barnes_Hut_Algo/nbody.c
sagar-garg/Parallel-Programming
9de557fb136f408ef24fa437e53e850853928ac2
[ "MIT" ]
null
null
null
N_Body_Simulation_Barnes_Hut_Algo/nbody.c
sagar-garg/Parallel-Programming
9de557fb136f408ef24fa437e53e850853928ac2
[ "MIT" ]
null
null
null
#include <stdbool.h> #include <stdint.h> #include <stdlib.h> #include <stdio.h> #include <math.h> #include <mpi.h> #include <mpi.h> #include "gui.h" #include "nbody.h" static uint64_t rand_state = 0xd1620b2a7a243d4bull; uint64_t random_u64() { uint64_t x = rand_state; x ^= x >> 12; x ^= x << 25; x ^= x >> 27; rand_state = x; return x * 0x2545f4914f6cdd1dull; } uint64_t random_u64_seed(uint64_t seed) { uint64_t x = 0xd1620b2a7a243d4bull ^ seed; x ^= x >> 12; x ^= x << 25; x ^= x >> 27; return x * 0x2545f4914f6cdd1dull; } float random_float() { return random_u64() / 18446744073709551616.f; } float random_float_normal() { // Ok, this is cheating. return random_float() + random_float() + random_float() + random_float() + random_float() + random_float() + random_float() + random_float() + random_float() + random_float() + random_float() + random_float() - 6.f; } void node_update_low_res_single(Node* node) { if (node->is_leaf) { // This is not an error, as in the parallel case there are some leaves for which we do not // need to high-resolution data at all. In that case the low-resulution data is transmitted // via MPI. if (node->timestamp_low_res > node->leaf.timestamp_high_res) return; node->low_res_x = 0.f; node->low_res_y = 0.f; node->low_res_mass = 0.f; for (int i = 0; i < node->leaf.count; ++i) { node->low_res_x += node->leaf.x[i] * node->leaf.mass[i]; node->low_res_y += node->leaf.y[i] * node->leaf.mass[i]; node->low_res_mass += node->leaf.mass[i]; } if (node->low_res_mass > 0.001f) { node->low_res_x /= node->low_res_mass; node->low_res_y /= node->low_res_mass; } node->timestamp_low_res = node->leaf.timestamp_high_res; } else { if ( node->tree.lower_left ->timestamp_low_res != node->tree.lower_right->timestamp_low_res || node->tree.lower_right->timestamp_low_res != node->tree.upper_left ->timestamp_low_res || node->tree.upper_left ->timestamp_low_res != node->tree.upper_right->timestamp_low_res) { fprintf(stderr, "Error: while combining data of for tree node %d\n", node->id); fprintf(stderr, "Error: mismatching timestamps for low-resolution data (%d, %d, %d, %d)\n", node->tree.lower_left->timestamp_low_res, node->tree.lower_right->timestamp_low_res, node->tree.upper_left->timestamp_low_res, node->tree.upper_right->timestamp_low_res); exit(15); } node->low_res_x = node->tree.lower_left ->low_res_x * node->tree.lower_left ->low_res_mass + node->tree.lower_right->low_res_x * node->tree.lower_right->low_res_mass + node->tree.upper_left ->low_res_x * node->tree.upper_left ->low_res_mass + node->tree.upper_right->low_res_x * node->tree.upper_right->low_res_mass; node->low_res_y = node->tree.lower_left ->low_res_y * node->tree.lower_left ->low_res_mass + node->tree.lower_right->low_res_y * node->tree.lower_right->low_res_mass + node->tree.upper_left ->low_res_y * node->tree.upper_left ->low_res_mass + node->tree.upper_right->low_res_y * node->tree.upper_right->low_res_mass; node->low_res_mass = node->tree.lower_left->low_res_mass + node->tree.lower_right->low_res_mass + node->tree.upper_left->low_res_mass + node->tree.upper_right->low_res_mass; if (node->low_res_mass > 0.001f) { node->low_res_x /= node->low_res_mass; node->low_res_y /= node->low_res_mass; } node->timestamp_low_res = node->tree.lower_left->timestamp_low_res; } } void node_leaf_ensure_capacity(Node* node, int capacity) { if (node->leaf.capacity < capacity) { node->leaf.capacity = 2 * node->leaf.capacity; if (node->leaf.capacity < capacity) node->leaf.capacity = capacity; node->leaf.x = realloc(node->leaf.x, sizeof(float) * node->leaf.capacity); node->leaf.y = realloc(node->leaf.y, sizeof(float) * node->leaf.capacity); node->leaf.vx = realloc(node->leaf.vx, sizeof(float) * node->leaf.capacity); node->leaf.vy = realloc(node->leaf.vy, sizeof(float) * node->leaf.capacity); node->leaf.mass = realloc(node->leaf.mass, sizeof(float) * node->leaf.capacity); } } void node_leaf_append_object(Node* node, float x, float y, float vx, float vy, float mass) { node_leaf_ensure_capacity(node, node->leaf.count + 1); node->leaf.x [node->leaf.count] = x; node->leaf.y [node->leaf.count] = y; node->leaf.vx [node->leaf.count] = vx; node->leaf.vy [node->leaf.count] = vy; node->leaf.mass[node->leaf.count] = mass; node->leaf.count += 1; } Node* node_create_helper(int num_leaves, int points, Node* parent, float x0, float y0, float x1, float y1, int* id_leaf, int* id_tree) { Node* node = calloc(1, sizeof(Node)); node->parent = parent; node->x0 = x0; node->y0 = y0; node->x1 = x1; node->y1 = y1; if ((num_leaves - 1) % 3 != 0) { fprintf(stderr, "Error: You are trying to run the program using %d threads, which is not" " one plus a multiple of three.\n", num_leaves); exit(12); } else if (num_leaves == 1) { node->is_leaf = true; node->id = (*id_leaf)++; int actual_points = points * (1.f + 0.2f * random_float_normal()); if (actual_points < points / 4) actual_points = points / 4; for (int i = 0; i < actual_points; ++i) { node_leaf_append_object(node, random_float() * (x1 - x0) + x0, random_float() * (y1 - y0) + y0, random_float_normal()*0.01f, random_float_normal()*0.01f, fabsf(random_float_normal()) + 1.f ); float vx = node->leaf.x[i] - 500.f; float vy = node->leaf.y[i] - 500.f; node->leaf.vx[i] += -vy / 2000.f; node->leaf.vy[i] += vx / 2000.f; } } else { node->is_leaf = false; node->id = (*id_tree)++; int f[4] = {1, 1, 1, 1}; num_leaves -= 4; while (num_leaves > 0) { f[random_u64() % 4] += 3; num_leaves -= 3; } node->tree.lower_left = node_create_helper(f[0], points, node, x0, y0, 0.5f*(x0 + x1), 0.5f*(y0 + y1), id_leaf, id_tree); node->tree.lower_right = node_create_helper(f[1], points, node, 0.5f*(x0 + x1), y0, x1, 0.5f*(y0 + y1), id_leaf, id_tree); node->tree.upper_left = node_create_helper(f[2], points, node, x0, 0.5f*(y0 + y1), 0.5f*(x0 + x1), y1, id_leaf, id_tree); node->tree.upper_right = node_create_helper(f[3], points, node, 0.5f*(x0 + x1), 0.5f*(y0 + y1), x1, y1, id_leaf, id_tree); } node_update_low_res_single(node); return node; } Node* node_create(int num_leaves, int points) { rand_state = 0xd1620b2a7a243d4bull; int id_leaf = 0; int id_tree = num_leaves; return node_create_helper(num_leaves, points, NULL, 0.f, 0.f, 1000.f, 1000.f, &id_leaf, &id_tree); } void node_draw_svg_helper(Node* node, FILE* file) { fprintf(file, "<circle cx=\"%f\" cy=\"%f\" r=\"%f\" fill=\"#f0f0ff\" stroke=\"none\" />\n", node->low_res_x, node->low_res_y, sqrtf(node->low_res_mass)); if (node->is_leaf) { int r = random_u64_seed(node->id) % 175 + 10; int g = random_u64_seed(node->id) % 177 + 10; int b = random_u64_seed(node->id) % 179 + 10; for (int i = 0; i < node->leaf.count; ++i) { fprintf(file, "<circle cx=\"%f\" cy=\"%f\" r=\"%f\" fill=\"#%02x%02x%02x\" stroke=\"none\" />\n", node->leaf.x[i], node->leaf.y[i], sqrtf(node->leaf.mass[i]), r, g, b); } fprintf(file, "<rect x=\"%f\" y=\"%f\" width=\"%f\" height=\"%f\" stroke-width=\"2\" stroke=\"#f0f0f0\" fill=\"none\" />\n", node->x0, node->y0, node->x1 - node->x0, node->y1 - node->y0); } else { node_draw_svg_helper(node->tree.lower_left, file); node_draw_svg_helper(node->tree.lower_right, file); node_draw_svg_helper(node->tree.upper_left, file); node_draw_svg_helper(node->tree.upper_right, file); } } void node_draw_svg(Node* node, char* file_name) { FILE* file = fopen(file_name, "w"); if (file == NULL) { perror(""); fprintf(stderr, "Error: Could not open file %s for writing\n", file_name); exit(16); } fprintf(file, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n"); fprintf(file, "<svg xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\" viewBox=\"-5 -5 1010 1010\">\n"); fprintf(file, "<rect x=\"-5\" y=\"-5\" width=\"1010\" height=\"1010\" fill=\"white\" stroke=\"none\" />\n"); node_draw_svg_helper(node, file); fprintf(file, "</svg>\n"); fclose(file); } void node_draw_circles(Node* node, float** circles, int* circles_count, int* circles_capacity) { if (node->is_leaf) { if (*circles_count + node->leaf.count >= *circles_capacity) { *circles_capacity = 2 * *circles_capacity; if (*circles_capacity < *circles_count + node->leaf.count) *circles_capacity = *circles_count + node->leaf.count + 16; *circles = realloc(*circles, *circles_capacity * sizeof(float) * 3); } for (int i = 0; i < node->leaf.count; ++i) { (*circles)[3 * *circles_count ] = node->leaf.x[i]; (*circles)[3 * *circles_count + 1] = node->leaf.y[i]; (*circles)[3 * *circles_count + 2] = sqrtf(node->leaf.mass[i]); ++*circles_count; } } else { node_draw_circles(node->tree.lower_left, circles, circles_count, circles_capacity); node_draw_circles(node->tree.lower_right, circles, circles_count, circles_capacity); node_draw_circles(node->tree.upper_left, circles, circles_count, circles_capacity); node_draw_circles(node->tree.upper_right, circles, circles_count, circles_capacity); } } void node_check_almost_equal(Node* a, Node* b, float max_err) { float x = a->low_res_x - b->low_res_x; float y = a->low_res_y - b->low_res_y; float mass = a->low_res_mass - b->low_res_mass; float err = fmaxf(sqrtf(x*x+y*y), abs(mass)); if (err > max_err) { fprintf(stderr, "Error while doing unit test. You should inpect the generated SVG files to debug the differences.\n"); exit(1); } } float distance_point_point(float x0, float y0, float px, float py) { return sqrtf((x0-px)*(x0-px)+(y0-py)*(y0-py)); } float distance_rectangle_point(float x0, float y0, float x1, float y1, float px, float py) { if (x0 <= px && px <= x1) { if (y0 <= py && py <= y1) { return 0.f; } else if (py < y0) { return y0 - py; } else { return py - y1; } } else if (px < x0) { if (y0 <= py && py <= y1) { return x0 - px; } else if (py < y0) { return distance_point_point(x0, y0, px, py); } else { return distance_point_point(x0, y1, px, py); } } else { if (y0 < py && py < y1) { return px - x1; } else if (py < y0) { return distance_point_point(x1, y0, px, py); } else { return distance_point_point(x1, y1, px, py); } } } float distance_rectangle_rectangle(float x0, float y0, float x1, float y1, float px0, float py0, float px1, float py1) { // Note that the rectangles are either non-overlapping, or one is a subset of the other float f1 = distance_rectangle_point(x0, y0, x1, y1, px0, py0); float f2 = distance_rectangle_point(x0, y0, x1, y1, px1, py0); float f3 = distance_rectangle_point(x0, y0, x1, y1, px0, py1); float f4 = distance_rectangle_point(x0, y0, x1, y1, px1, py1); float f5 = distance_rectangle_point(px0, py0, px1, py1, x0, y0); float f6 = distance_rectangle_point(px0, py0, px1, py1, x1, y0); float f7 = distance_rectangle_point(px0, py0, px1, py1, x0, y1); float f8 = distance_rectangle_point(px0, py0, px1, py1, x1, y1); return fminf(fminf(fminf(f1, f2), fminf(f3, f4)), fminf(fminf(f5, f6), fminf(f7, f8))); } float distance_node_node(Node* node0, Node* node1) { return distance_rectangle_rectangle(node0->x0, node0->y0, node0->x1, node0->y1, node1->x0, node1->y0, node1->x1, node1->y1); } float global_timestep = 0.01f; void compute_acceleration_point(Node* node, float px, float py, float pmass) { for (int j = 0; j < node->leaf.count; ++j) { float dx = px - node->leaf.x[j]; float dy = py - node->leaf.y[j]; // Ok, if there are any physicists here, please do not look too closely at this line. It is // numerically stable, anyways. float d = sqrtf(dx*dx + dy*dy) + 1.f; float acc = pmass / (d*d) * global_timestep; node->leaf.vx[j] += acc * dx / d; node->leaf.vy[j] += acc * dy / d; } } void compute_acceleration(Node* node, Node* source) { if (!node->is_leaf) { compute_acceleration(node->tree.lower_left, source); compute_acceleration(node->tree.lower_right, source); compute_acceleration(node->tree.upper_left, source); compute_acceleration(node->tree.upper_right, source); return; } if (distance_node_node(node, source) <= DISTANCE_CUTOFF) { if (source->is_leaf) { if (source->leaf.timestamp_high_res != node->leaf.timestamp_high_res) { fprintf(stderr, "Error: mismatching high-res timestamps for nodes %d and %d (timestamps %d, %d)\n", node->id, source->id, source->leaf.timestamp_high_res, node->leaf.timestamp_high_res); fprintf(stderr, "Error: did you forget to transfer high-res data to neighbours between timesteps?\n"); exit(17); } for (int i = 0; i < source->leaf.count; ++i) { compute_acceleration_point(node, source->leaf.x[i], source->leaf.y[i], source->leaf.mass[i]); } } else { compute_acceleration(node, source->tree.lower_left); compute_acceleration(node, source->tree.lower_right); compute_acceleration(node, source->tree.upper_left); compute_acceleration(node, source->tree.upper_right); } } else { if (source->timestamp_low_res != node->leaf.timestamp_high_res) { fprintf(stderr, "Error: mismatching timestamps for nodes %d and %d\n", node->id, source->id); fprintf(stderr, "Error: did you forget to transfer low-res data to neighbours between timesteps?\n"); exit(18); } compute_acceleration_point(node, source->low_res_x, source->low_res_y, source->low_res_mass); } } void node_find_nearby(Node** nearby, int* nearby_count, Node* root, Node* other) { if (other->is_leaf) { if (root->id != other->id && distance_node_node(root, other) <= DISTANCE_CUTOFF) { nearby[*nearby_count] = other; ++*nearby_count; } } else { node_find_nearby(nearby, nearby_count, root, other->tree.lower_left); node_find_nearby(nearby, nearby_count, root, other->tree.lower_right); node_find_nearby(nearby, nearby_count, root, other->tree.upper_left); node_find_nearby(nearby, nearby_count, root, other->tree.upper_right); } } bool node_contains_point(Node* node, float px, float py) { return node->x0 <= px && px <= node->x1 && node->y0 <= py && py <= node->y1; } void node_update_low_res(Node* node) { if (!node->is_leaf) { // Recursively update the children. node_update_low_res(node->tree.lower_left); node_update_low_res(node->tree.lower_right); node_update_low_res(node->tree.upper_left); node_update_low_res(node->tree.upper_right); } node_update_low_res_single(node); } int move_objects_helper(Node* node, float* leaving) { int left = 0; if (node->is_leaf) { // Update the positions for (int i = 0; i < node->leaf.count; ++i) { node->leaf.x[i] += node->leaf.vx[i]; node->leaf.y[i] += node->leaf.vy[i]; } // Check whether any object have left the rectangle for (int i = 0; i < node->leaf.count; ++i) { if (!node_contains_point(node, node->leaf.x[i], node->leaf.y[i])) { // Write the object into the leaving array leaving[5*left] = node->leaf.x[i]; leaving[5*left+1] = node->leaf.y[i]; leaving[5*left+2] = node->leaf.vx[i]; leaving[5*left+3] = node->leaf.vy[i]; leaving[5*left+4] = node->leaf.mass[i]; ++left; // Remove it from the node node->leaf.x[i] = node->leaf.x[node->leaf.count-1]; node->leaf.y[i] = node->leaf.y[node->leaf.count-1]; node->leaf.vx[i] = node->leaf.vx[node->leaf.count-1]; node->leaf.vy[i] = node->leaf.vy[node->leaf.count-1]; node->leaf.mass[i] = node->leaf.mass[node->leaf.count-1]; --node->leaf.count; --i; } } ++node->leaf.timestamp_high_res; } else { // Recursively update the children. left += move_objects_helper(node->tree.lower_left, leaving + 5*left); left += move_objects_helper(node->tree.lower_right, leaving + 5*left); left += move_objects_helper(node->tree.upper_left, leaving + 5*left); left += move_objects_helper(node->tree.upper_right, leaving + 5*left); } if (left+1 >= MAX_LEAVING) { // This should never happen... fprintf(stderr, "Error: No enough buffer for leaving nodes (have %d, need at least %d)\n", MAX_LEAVING, left); exit(13); } return left; } float* global_circles; int global_circles_count, global_circles_capacity; bool global_show_gui; int move_objects(Node* node, float* leaving) { if (global_show_gui) { global_circles_count = 0; node_draw_circles(node, &global_circles, &global_circles_count, &global_circles_capacity); gui_draw(global_circles, global_circles_count); } return move_objects_helper(node, leaving); } Node* node_find(Node* root, int id) { if (root->id == id) { return root; } else if (root->is_leaf) { return NULL; } else { Node* node; if ((node = node_find(root->tree.lower_left, id))) return node; if ((node = node_find(root->tree.lower_right, id))) return node; if ((node = node_find(root->tree.upper_left, id))) return node; if ((node = node_find(root->tree.upper_right, id))) return node; return NULL; } }
43.365079
274
0.592292
[ "object" ]
15a257c86a8e45884e763eefd89f5f25804fa16d
10,061
h
C
src/animated_quantity.h
MarkGillespie/SurfaceSchroedingerSmoke
6a1fbce7b52147283017964d81111d6d2aad1581
[ "MIT" ]
2
2021-11-19T06:56:21.000Z
2021-12-25T13:22:14.000Z
src/animated_quantity.h
MarkGillespie/SurfaceSchroedingerSmoke
6a1fbce7b52147283017964d81111d6d2aad1581
[ "MIT" ]
null
null
null
src/animated_quantity.h
MarkGillespie/SurfaceSchroedingerSmoke
6a1fbce7b52147283017964d81111d6d2aad1581
[ "MIT" ]
1
2021-11-19T06:57:00.000Z
2021-11-19T06:57:00.000Z
#pragma once #include "polyscope/affine_remapper.h" #include "polyscope/histogram.h" #include "polyscope/render/color_maps.h" #include "polyscope/render/engine.h" #include "polyscope/surface_mesh.h" namespace polyscope { // Assuming that our values are uniformly spaced keyframes in [0, 1], // returns the first frame before t, and the coefficient to interpolate // along the way to the next frame std::tuple<size_t, double> interpolate(double t, size_t N); class SurfaceAnimatedScalarQuantity : public SurfaceMeshQuantity { public: SurfaceAnimatedScalarQuantity(std::string name, SurfaceMesh& mesh_, std::string definedOn, DataType dataType); virtual void draw() override; virtual void buildCustomUI() override; virtual std::string niceName() override; virtual void geometryChanged() override; virtual void writeToFile(std::string filename = ""); // === Members const DataType dataType; // === Get/set visualization parameters // The color map SurfaceAnimatedScalarQuantity* setColorMap(std::string val); std::string getColorMap(); // Data limits mapped in to colormap SurfaceAnimatedScalarQuantity* setMapRange(std::pair<double, double> val); std::pair<double, double> getMapRange(); SurfaceAnimatedScalarQuantity* resetMapRange(); // reset to full range SurfaceAnimatedScalarQuantity* setTime(double t); double getTime(); protected: // === Visualization parameters // Affine data maps and limits std::pair<float, float> vizRange; std::pair<double, double> dataRange; Histogram hist; // UI internals PersistentValue<float> time; PersistentValue<std::string> cMap; const std::string definedOn; std::shared_ptr<render::ShaderProgram> program; // Helpers virtual void fillColorBuffers(render::ShaderProgram& p, bool update = false) = 0; virtual void createProgram() = 0; void setProgramUniforms(render::ShaderProgram& program); }; // ======================================================== // ========== Vertex Scalar ========== // ======================================================== class SurfaceAnimatedVertexScalarQuantity : public SurfaceAnimatedScalarQuantity { public: SurfaceAnimatedVertexScalarQuantity( std::string name, std::vector<std::vector<double>> values_, SurfaceMesh& mesh_, DataType dataType_ = DataType::STANDARD); virtual void createProgram() override; virtual void fillColorBuffers(render::ShaderProgram& p, bool update = false) override; void buildVertexInfoGUI(size_t vInd) override; virtual void writeToFile(std::string filename = "") override; // === Members std::vector<std::vector<double>> values; }; SurfaceAnimatedVertexScalarQuantity* addAnimatedVertexScalarQuantityImpl( SurfaceMesh& mesh, std::string name, const std::vector<std::vector<double>>& data, DataType type = DataType::STANDARD); template <typename T> SurfaceAnimatedVertexScalarQuantity* addAnimatedVertexScalarQuantity(SurfaceMesh& mesh, std::string name, const std::vector<T>& data, DataType type = DataType::STANDARD) { std::vector<std::vector<double>> standardizedData; for (const T& frame : data) { validateSize(frame, mesh.vertexDataSize, "vertex scalar quantity " + name); standardizedData.push_back(standardizeArray<double, T>(frame)); } return addAnimatedVertexScalarQuantityImpl(mesh, name, standardizedData, type); } // ==== Common base class // Represents a general vector field associated with a surface mesh, including // R3 fields in the ambient space and R2 fields embedded in the surface class SurfaceAnimatedVectorQuantity : public SurfaceMeshQuantity { public: SurfaceAnimatedVectorQuantity( std::string name, SurfaceMesh& mesh_, MeshElement definedOn_, VectorType vectorType_ = VectorType::STANDARD); virtual void draw() override; virtual void buildCustomUI() override; // Allow children to append to the UI virtual void drawSubUI(); // === Members // Note: these vectors are not the raw vectors passed in by the user, but // have been rescaled such that the longest has length 1 (unless type is // VectorType::Ambient) const VectorType vectorType; std::vector<glm::vec3> vectorRoots; std::vector<glm::vec3> vectors; // === Option accessors // The vectors will be scaled such that the longest vector is this long SurfaceAnimatedVectorQuantity* setVectorLengthScale(double newLength, bool isRelative = true); double getVectorLengthScale(); // The radius of the vectors SurfaceAnimatedVectorQuantity* setVectorRadius(double val, bool isRelative = true); double getVectorRadius(); // The color of the vectors SurfaceAnimatedVectorQuantity* setVectorColor(glm::vec3 color); glm::vec3 getVectorColor(); // Material SurfaceAnimatedVectorQuantity* setMaterial(std::string name); std::string getMaterial(); // Enable the ribbon visualization SurfaceAnimatedVectorQuantity* setRibbonEnabled(bool newVal); bool isRibbonEnabled(); virtual void recomputeVectors() = 0; SurfaceAnimatedVectorQuantity* setTime(double t); double getTime(); protected: // === Visualization options PersistentValue<ScaledValue<float>> vectorLengthMult; PersistentValue<ScaledValue<float>> vectorRadius; PersistentValue<glm::vec3> vectorColor; PersistentValue<std::string> material; PersistentValue<float> time; // The map that takes values to [0,1] for drawing AffineRemapper<glm::vec3> mapper; MeshElement definedOn; // A ribbon viz that is appropriate for some fields std::unique_ptr<RibbonArtist> ribbonArtist; PersistentValue<bool> ribbonEnabled; // GL things void prepareProgram(); std::shared_ptr<render::ShaderProgram> program; // Set up the mapper for vectors void prepareVectorMapper(); }; // ==== Intrinsic vectors at faces class SurfaceAnimatedFaceIntrinsicVectorQuantity : public SurfaceAnimatedVectorQuantity { public: SurfaceAnimatedFaceIntrinsicVectorQuantity( std::string name, std::vector<std::vector<glm::vec2>> vectors_, SurfaceMesh& mesh_, int nSym = 1, VectorType vectorType_ = VectorType::STANDARD); int nSym; std::vector<std::vector<glm::vec2>> vectorField; virtual void recomputeVectors() override; virtual void draw() override; void drawSubUI() override; virtual std::string niceName() override; void buildFaceInfoGUI(size_t fInd) override; }; SurfaceAnimatedFaceIntrinsicVectorQuantity* addAnimatedFaceIntrinsicVectorQuantityImpl( SurfaceMesh& mesh, std::string name, const std::vector<std::vector<glm::vec2>>& data, int nSym = 1, VectorType type = VectorType::STANDARD); template <typename T> SurfaceAnimatedFaceIntrinsicVectorQuantity* addAnimatedFaceIntrinsicVectorQuantity(SurfaceMesh& mesh, std::string name, const std::vector<T>& data, int nSym = 1, VectorType type = VectorType::STANDARD) { std::vector<std::vector<glm::vec2>> standardizedData; for (const T& frame : data) { validateSize(frame, mesh.faceDataSize, "face intrinsic vector quantity " + name); standardizedData.push_back(standardizeVectorArray<glm::vec2, 2>(frame)); } return addAnimatedFaceIntrinsicVectorQuantityImpl( mesh, name, standardizedData, nSym, type); } class SurfaceAnimatedColorQuantity : public SurfaceMeshQuantity { public: SurfaceAnimatedColorQuantity(std::string name, SurfaceMesh& mesh_, std::string definedOn); virtual void draw() override; virtual void buildCustomUI() override; virtual std::string niceName() override; virtual void geometryChanged() override; SurfaceAnimatedColorQuantity* setTime(double t); double getTime(); protected: // UI internals PersistentValue<float> time; const std::string definedOn; std::shared_ptr<render::ShaderProgram> program; // Helpers virtual void createProgram() = 0; virtual void fillColorBuffers(render::ShaderProgram& p) = 0; }; // ======================================================== // ========== Vertex Color ========== // ======================================================== class SurfaceAnimatedVertexColorQuantity : public SurfaceAnimatedColorQuantity { public: SurfaceAnimatedVertexColorQuantity( std::string name, std::vector<std::vector<glm::vec3>> values_, SurfaceMesh& mesh_); virtual void createProgram() override; virtual void fillColorBuffers(render::ShaderProgram& p) override; void buildVertexInfoGUI(size_t vInd) override; // === Members std::vector<std::vector<glm::vec3>> values; }; SurfaceAnimatedVertexColorQuantity* addAnimatedVertexColorQuantityImpl( SurfaceMesh& mesh, std::string name, const std::vector<std::vector<glm::vec3>>& data); template <typename T> SurfaceAnimatedVertexColorQuantity* addAnimatedVertexColorQuantity(SurfaceMesh& mesh, std::string name, const std::vector<T>& data) { std::vector<std::vector<glm::vec3>> standardizedData; for (const T& frame : data) { validateSize(frame, mesh.vertexDataSize, "vertex color quantity " + name); standardizedData.push_back(standardizeVectorArray<glm::vec3, 3>(frame)); } return addAnimatedVertexColorQuantityImpl(mesh, name, standardizedData); } } // namespace polyscope
33.095395
80
0.665043
[ "mesh", "render", "vector" ]
15a4842fcc4dd5863b623cc24094cbad16322361
2,050
h
C
SpaceCadetPinball/midi.h
Nixola/SpaceCadetPinball
7ee508118c124b2ac889eadc0e1b81ecc3e9830f
[ "MIT" ]
null
null
null
SpaceCadetPinball/midi.h
Nixola/SpaceCadetPinball
7ee508118c124b2ac889eadc0e1b81ecc3e9830f
[ "MIT" ]
null
null
null
SpaceCadetPinball/midi.h
Nixola/SpaceCadetPinball
7ee508118c124b2ac889eadc0e1b81ecc3e9830f
[ "MIT" ]
null
null
null
#pragma once constexpr uint32_t SwapByteOrderInt(uint32_t val) { return (val >> 24) | ((val << 8) & 0x00FF0000) | ((val >> 8) & 0x0000FF00) | (val << 24); } constexpr uint16_t SwapByteOrderShort(uint16_t val) { return static_cast<uint16_t>((val >> 8) | (val << 8)); } #pragma pack(push) #pragma pack(1) struct riff_block { DWORD TkStart; DWORD CbBuffer; char AData[4]; }; struct riff_data { DWORD Data; DWORD DataSize; DWORD BlocksPerChunk; riff_block Blocks[1]; }; struct riff_header { DWORD Riff; DWORD FileSize; DWORD Mids; DWORD Fmt; DWORD FmtSize; DWORD dwTimeFormat; DWORD cbMaxBuffer; DWORD dwFlags; riff_data Data; }; struct midi_event { DWORD iTicks; DWORD iEvent; }; struct midi_header { explicit midi_header(uint16_t tickdiv) : tickdiv(tickdiv) { } const char MThd[4]{'M', 'T', 'h', 'd'}; const uint32_t chunklen = SwapByteOrderInt(6); const int16_t format = SwapByteOrderShort(0); const uint16_t ntracks = SwapByteOrderShort(1); uint16_t tickdiv; }; struct midi_track { explicit midi_track(uint32_t chunklen) : chunklen(chunklen) { } const char MTrk[4]{'M', 'T', 'r', 'k'}; uint32_t chunklen; }; static_assert(sizeof(riff_block) == 0xC, "Wrong size of riff_block"); static_assert(sizeof(riff_data) == 0x18, "Wrong size of riff_data"); static_assert(sizeof(riff_header) == 0x38, "Wrong size of riff_header"); static_assert(sizeof(midi_event) == 8, "Wrong size of midi_event2"); static_assert(sizeof(midi_header) == 14, "Wrong size of midi_header"); static_assert(sizeof(midi_track) == 8, "Wrong size of midi_track"); #pragma pack(pop) class midi { public: static int play_pb_theme(); static int music_stop(); static int music_init(); static void music_shutdown(); private: static std::vector<Mix_Music*> LoadedTracks; static Mix_Music *track1, *track2, *track3, *active_track, *NextTrack; static bool SetNextTrackFlag; static Mix_Music* load_track(std::string fileName); static bool play_track(Mix_Music* midi); static std::vector<uint8_t>* MdsToMidi(std::string file); };
20.29703
72
0.719024
[ "vector" ]
15ac12175182df241bb053ff5cb2d954c815fb39
9,355
h
C
Oem/DWFTK/develop/global/src/dwfcore/MonitoredInputStream.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
2
2017-04-19T01:38:30.000Z
2020-07-31T03:05:32.000Z
Oem/DWFTK/develop/global/src/dwfcore/MonitoredInputStream.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
null
null
null
Oem/DWFTK/develop/global/src/dwfcore/MonitoredInputStream.h
achilex/MgDev
f7baf680a88d37659af32ee72b9a2046910b00d8
[ "PHP-3.0" ]
1
2021-12-29T10:46:12.000Z
2021-12-29T10:46:12.000Z
// // Copyright (c) 2003-2006 by Autodesk, Inc. // // By using this code, you are agreeing to the terms and conditions of // the License Agreement included in the documentation for this code. // // AUTODESK MAKES NO WARRANTIES, EXPRESS OR IMPLIED, // AS TO THE CORRECTNESS OF THIS CODE OR ANY DERIVATIVE // WORKS WHICH INCORPORATE IT. // // AUTODESK PROVIDES THE CODE ON AN "AS-IS" BASIS // AND EXPLICITLY DISCLAIMS ANY LIABILITY, INCLUDING // CONSEQUENTIAL AND INCIDENTAL DAMAGES FOR ERRORS, // OMISSIONS, AND OTHER PROBLEMS IN THE CODE. // // Use, duplication, or disclosure by the U.S. Government is subject to // restrictions set forth in FAR 52.227-19 (Commercial Computer Software // Restricted Rights) and DFAR 252.227-7013(c)(1)(ii) (Rights in Technical // Data and Computer Software), as applicable. // #ifndef _DWFCORE_MONITORED_INPUT_STREAM_H #define _DWFCORE_MONITORED_INPUT_STREAM_H /// ///\file dwfcore/MonitoredInputStream.h ///\brief This header contains the declaration for the DWFMonitoredInputStream class. /// #include "dwfcore/InputStream.h" #include "dwfcore/OutputStream.h" namespace DWFCore { /// ///\class DWFMonitoredInputStream dwfcore/MonitoredInputStream.h "dwfcore/MonitoredInputStream.h" ///\brief An input stream whose read operation can be "watched". ///\since 1.0.1 /// /// This implementation of the DWFInputStream is useful when it is /// desriable for one entity to passively receive the same data /// as the active stream reader. There are two mechanisms provided for hooking /// into the stream: an object may implement the Monitor interface, /// or DWFOutputStream. In both cases, whatever data was obtained during /// the \a read() operation will be either posted to the monitor or written /// into the output stream. /// /// Example 1: Use a monitor to show progress: /// \code /// class ProgressMonitor : public DWFMonitoredInputStream::Monitor /// { /// ProgressMonitor( size_t nTotalBytesInStream ) /// : _nTotalBytes( nTotalBytesInStream ) /// , _nBytesReadSoFar( 0 ) /// {;} /// /// void notify( const void* const pBuffer, /// size_t nBytesRequested, /// size_t nBytesRead ) /// throw( DWFException ) /// { /// _nBytesReadSoFar += nBytesRead; /// float nProgress = 100.0 * (float)(_nBytesReadSoFar / _nTotalBytesInStream); /// /// _send_progress_function( nProgress ); /// } /// }; /// \endcode /// /// Example 2: Copy a stream into a temporary file. /// \code /// DWFString zTemplate( L"_dwfcore_" ); /// /// // /// // passing true as the second parameter will result in the /// // temporary disk file being deleted when the DWFTempFile /// // object is destroyed. /// // /// DWFTempFile* pTempFile = DWFTempFile::Create( zTemplate, true ); /// DWFOutputStream* pTempFileStream = pTempFile->getOuputStream(); /// /// // /// // passing true here tells the monitor stream to assume /// // ownership of the file stream and delete it when /// // he is deleted himself /// // /// pMonitorStream->attachMonitor( pTempFileStream, true ); /// /// ... read from the monitor stream ... /// /// DWFCORE_FREE_OBJECT( pMonitorStream ); /// DWFCORE_FREE_OBJECT( pTempFile ); /// \endcode /// class DWFMonitoredInputStream : virtual public DWFCoreMemory , public DWFInputStream { public: /// ///\interface Monitor dwfcore/MonitoredInputStream.h "dwfcore/MonitoredInputStream.h" ///\brief Callback interface for watching DWFMonitoredInputStream objects. ///\since 1.0.1 ///\todo Add notification method for stream seek. /// class Monitor { public: /// /// Destructor /// ///\throw None /// _DWFCORE_API virtual ~Monitor() throw() {;} /// /// Post-read data notification callback. /// ///\param pBuffer The data returned from the \a read() operation. ///\param nBytesRequested The number of bytes originally requested to be read from the stream. ///\param nBytesRead The number of bytes actually read from the stream; and the size of /// the data in \a pBuffer. ///\throw DWFException /// _DWFCORE_API virtual void notify( const void* const pBuffer, size_t nBytesRequested, size_t nBytesRead ) throw( DWFException ) = 0; protected: /// /// Constructor /// ///\throw None /// _DWFCORE_API Monitor() throw() {;} }; public: /// /// Constructor /// ///\param pStream The source data stream to be monitored. ///\param bOwnStream If \e true, this object will assume ownership of \a pInputStream /// and delete it as necessary using \b DWFCORE_FREE_OBJECT. /// If \e false, the caller retains ownership of \a pInputStream /// and is responsible for deleting it. ///\throw None /// _DWFCORE_API DWFMonitoredInputStream( DWFInputStream* pStream, bool bOwnStream ) throw(); /// /// Destructor /// ///\throw None /// _DWFCORE_API virtual ~DWFMonitoredInputStream() throw(); /// /// Binds a monitor to the stream. Any data obtained /// from a \a read() call will result in this /// monitor's \a notify() method being invoked. /// Any previously bound monitor will be replaced; and /// deleted if this stream currently owns it. /// ///\param pMonitor The monitor to which read data will be posted. ///\param bOwnMonitor If \e true, this object will assume ownership of \a pMonitor /// and delete it as necessary using \b DWFCORE_FREE_OBJECT. /// If \e false, the caller retains ownership of \a pMonitor /// and is responsible for deleting it. ///\throw None /// _DWFCORE_API void attach( Monitor* pMonitor, bool bOwnMonitor ) throw( DWFException ); /// /// Binds a monitoring stream to the stream. Any data obtained /// from a \a read() call will result in this /// stream's \a write() method being invoked. /// Any previously bound monitor will be replaced; and /// deleted if this stream currently owns it. /// ///\param pMonitor The stream to which read data will be written. ///\param bOwnMonitor If \e true, this object will assume ownership of \a pMonitor /// and delete it as necessary using \b DWFCORE_FREE_OBJECT. /// If \e false, the caller retains ownership of \a pMonitor /// and is responsible for deleting it. ///\throw None /// _DWFCORE_API void attach( DWFOutputStream* pMonitor, bool bOwnMonitor ) throw( DWFException ); /// /// Unbinds any monitors from the stream. /// All owned monitors will be deleted. /// ///\throw None /// _DWFCORE_API void detach() throw( DWFException ); /// ///\copydoc DWFInputStream::available() /// _DWFCORE_API size_t available() const throw( DWFException ); /// ///\copydoc DWFInputStream::read() /// _DWFCORE_API size_t read( void* pBuffer, size_t nBytesToRead ) throw( DWFException ); /// ///\copydoc DWFInputStream::seek() /// _DWFCORE_API off_t seek( int eOrigin, off_t nOffset ) throw( DWFException ); private: DWFInputStream* _pStream; Monitor* _pMonitor; DWFOutputStream* _pMonitorStream; bool _bOwnStream; bool _bOwnMonitor; bool _bOwnMonitorStream; private: // // Unimplemented methods // DWFMonitoredInputStream( const DWFMonitoredInputStream& ); DWFMonitoredInputStream& operator=( const DWFMonitoredInputStream& ); }; } #endif
33.651079
109
0.537467
[ "object" ]
15ad9542adb724ab2e33d53c160d282891214837
3,496
h
C
WSEExternal/include/Physics/Utilities/CharacterControl/CharacterRigidBody/hkpCharacterRigidBodyCinfo.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
WSEExternal/include/Physics/Utilities/CharacterControl/CharacterRigidBody/hkpCharacterRigidBodyCinfo.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
WSEExternal/include/Physics/Utilities/CharacterControl/CharacterRigidBody/hkpCharacterRigidBodyCinfo.h
Swyter/wse
3ad901f1a463139b320c30ea08bdc343358ea6b6
[ "WTFPL" ]
null
null
null
/* * * Confidential Information of Telekinesys Research Limited (t/a Havok). Not for disclosure or distribution without Havok's * prior written consent. This software contains code, techniques and know-how which is confidential and proprietary to Havok. * Level 2 and Level 3 source code contains trade secrets of Havok. Havok Software (C) Copyright 1999-2009 Telekinesys Research Limited t/a Havok. All Rights Reserved. Use of this software is subject to the terms of an end user license agreement. * */ #ifndef HK_CHARACTER_RIGID_BODY_CINFO__H #define HK_CHARACTER_RIGID_BODY_CINFO__H /// Character controller cinfo struct hkpCharacterRigidBodyCinfo { HK_DECLARE_NONVIRTUAL_CLASS_ALLOCATOR( HK_MEMORY_CLASS_CHARACTER, hkpCharacterRigidBodyCinfo ); // // Values used to set up rigid body // /// The collision filter info /// See hkRigidBodyCinfo for details hkUint32 m_collisionFilterInfo; /// The shape /// See hkRigidBodyCinfo for details hkpShape* m_shape; /// Initial position /// See hkRigidBodyCinfo for details hkVector4 m_position; /// Initial rotation /// See hkRigidBodyCinfo for details hkQuaternion m_rotation; /// The mass of character /// See hkRigidBodyCinfo for details hkReal m_mass; /// Set friction of character /// See hkRigidBodyCinfo for details hkReal m_friction; /// Set maximal linear velocity /// See hkRigidBodyCinfo for details hkReal m_maxLinearVelocity; /// Set maximal allowed penetration depth /// See hkRigidBodyCinfo for details hkReal m_allowedPenetrationDepth; // // Character controller specific values // /// Set up direction hkVector4 m_up; /// Set maximal slope hkReal m_maxSlope; /// Set maximal force of character hkReal m_maxForce; // // Parameters used by checkSupport // /// Set maximal speed for simplex solver hkReal m_maxSpeedForSimplexSolver; /// A character is considered supported if it is less than this distance above its supporting planes. hkReal m_supportDistance; /// A character should keep falling until it is this distance or less from its supporting planes. hkReal m_hardSupportDistance; /// Set color of character for the visual debugger hkInt32 m_vdbColor; /// Constructor. Sets some defaults. hkpCharacterRigidBodyCinfo() { m_mass = 100.0f; m_maxForce = 1000.0f; m_friction = 0.0f; m_maxSlope = HK_REAL_PI / 3.0f; m_up.set( 0,1,0 ); m_maxLinearVelocity = 20.0f; m_allowedPenetrationDepth = -0.1f; m_maxSpeedForSimplexSolver = 10.0f; m_collisionFilterInfo = 0; m_position.setZero4(); m_rotation.setIdentity(); m_supportDistance = 0.1f; m_hardSupportDistance = 0.0f; m_vdbColor = 0xA0FF0000; } }; #endif // HK_CHARACTER_RIGID_BODY_CINFO__H /* * Havok SDK - NO SOURCE PC DOWNLOAD, BUILD(#20090704) * * Confidential Information of Havok. (C) Copyright 1999-2009 * Telekinesys Research Limited t/a Havok. All Rights Reserved. The Havok * Logo, and the Havok buzzsaw logo are trademarks of Havok. Title, ownership * rights, and intellectual property rights in the Havok software remain in * Havok and/or its suppliers. * * Use of this software for evaluation purposes is subject to and indicates * acceptance of the End User licence Agreement for this product. A copy of * the license is included with this software and is also available at www.havok.com/tryhavok. * */
29.133333
247
0.727689
[ "shape" ]
15c1f60ac49b4c32362c257400057c9ac147e9b4
32,229
c
C
src/cmd/cc/cc.c
ap98nb26u/retrobsd
593f6eaeb09e84f257587fe1166174bf6e396fe4
[ "BSD-3-Clause" ]
null
null
null
src/cmd/cc/cc.c
ap98nb26u/retrobsd
593f6eaeb09e84f257587fe1166174bf6e396fe4
[ "BSD-3-Clause" ]
null
null
null
src/cmd/cc/cc.c
ap98nb26u/retrobsd
593f6eaeb09e84f257587fe1166174bf6e396fe4
[ "BSD-3-Clause" ]
null
null
null
/* * Front-end to the C compiler. * * Brief description of its syntax: * - Files that end with .c are passed via cpp->ccom->as->ld * - Files that end with .i are passed via ccom->as->ld * - Files that end with .s are passed as->ld * - Files that end with .S are passed via cpp->as->ld * - Files that end with .o are passed directly to ld * - Multiple files may be given on the command line. * - Unrecognized options are all sent directly to ld. * -c or -S cannot be combined with -o if multiple files are given. * * This file should be rewritten readable. * * Copyright(C) Caldera International Inc. 2001-2002. 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 and documentation 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 conditionsand the following disclaimer in the * documentation and/or other materials provided with the distribution. * All advertising materials mentioning features or use of this software * must display the following acknowledgement: * This product includes software developed or owned by Caldera * International, Inc. * Neither the name of Caldera International, Inc. nor the names of other * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * USE OF THE SOFTWARE PROVIDED FOR UNDER THIS LICENSE BY CALDERA * INTERNATIONAL, INC. 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 CALDERA INTERNATIONAL, INC. 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 OFLIABILITY, 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 <sys/types.h> #include <sys/wait.h> #include <ctype.h> #include <fcntl.h> #include <signal.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #ifdef CROSS # include </usr/include/stdio.h> # include </usr/include/errno.h> #else # include <stdio.h> # include <errno.h> #endif #define MKS(x) _MKS(x) #define _MKS(x) #x /* * Many specific definitions, should be declared elsewhere. */ /* avoid problems with cygpath in msys environment. see Makefile also. */ #ifdef __MSYS__ #define STDINC "/include" #define LIBDIR "/lib" #define LIBEXECDIR "/libexec" #define CRT0FILE "/lib/crt0.o" #define CRT0FILE_PROFILE "/lib/mcrt0.o" #endif #ifndef STDINC #define STDINC "/usr/include" #endif #ifndef LIBDIR #define LIBDIR "/usr/lib" #endif #ifndef LIBEXECDIR #define LIBEXECDIR "/usr/libexec" #endif #ifndef PREPROCESSOR #define PREPROCESSOR "cpp" #endif #ifndef COMPILER #define COMPILER "ccom" #endif #ifndef ASSEMBLER #define ASSEMBLER "as" #endif #ifndef LINKER #define LINKER "ld" #endif #define MAXFIL 1000 #define MAXLIB 1000 #define MAXAV 1000 #define MAXOPT 100 char *tmp_as; char *tmp_cpp; char *outfile, *ermfile; char *Bprefix(char *); char *copy(char *, int); char *setsuf(char *, char); int getsuf(char *); int main(int, char *[]); void error(char *, ...); void errorx(int, char *, ...); int callsys(char [], char *[]); int cunlink(char *); void dexit(int); void idexit(int); char *gettmp(void); void *ccmalloc(int size); char *av[MAXAV]; char *clist[MAXFIL]; char *olist[MAXFIL]; char *llist[MAXLIB]; char *aslist[MAXAV]; char *cpplist[MAXAV]; char alist[20]; char *xlist[100]; int xnum; char *mlist[100]; char *flist[100]; char *wlist[100]; char *idirafter; char *progname; int nm; int nf; int nw; int sspflag; int dflag; int pflag; int sflag; int cflag; int eflag; int gflag; int rflag; int vflag; int tflag; int Eflag; int Oflag; int kflag; /* generate PIC/pic code */ #define F_PIC 1 #define F_pic 2 int Mflag; /* dependencies only */ int pgflag; int exfail; int Xflag; int Wallflag; int Wflag; int nostartfiles, Bstatic, shared; int nostdinc, nostdlib; int onlyas; int pthreads; int xcflag; int ascpp; char *passp = "/bin/" PREPROCESSOR; char *pass0 = LIBEXECDIR "/" COMPILER; char *as = ASSEMBLER; char *ld = LINKER; char *Bflag; enum { MODE_LCC, MODE_PCC, MODE_SMALLC, MODE_SMALLERC, } mode; /* common cpp predefines */ char *cppadd[] = { "-D__LCC__", "-D__unix__", "-D__BSD__", "-D__RETROBSD__", NULL }; #ifdef __mips__ # define CPPMDADD { "-D__mips__", NULL, } #endif #ifdef __i386__ # define CPPMDADD { "-D__i386__", NULL, } #endif #ifdef DYNLINKER char *dynlinker[] = DYNLINKER; #endif #ifdef CRT0FILE char *crt0file = CRT0FILE; #endif #ifdef CRT0FILE_PROFILE char *crt0file_profile = CRT0FILE_PROFILE; #endif #ifdef STARTFILES char *startfiles[] = STARTFILES; char *endfiles[] = ENDFILES; #endif #ifdef STARTFILES_T char *startfiles_T[] = STARTFILES_T; char *endfiles_T[] = ENDFILES_T; #endif #ifdef STARTFILES_S char *startfiles_S[] = STARTFILES_S; char *endfiles_S[] = ENDFILES_S; #endif #ifdef MULTITARGET char *mach = DEFMACH; struct cppmd { char *mach; char *cppmdadd[MAXCPPMDARGS]; }; struct cppmd cppmds[] = CPPMDADDS; #else char *cppmdadd[] = CPPMDADD; #endif #ifdef LIBCLIBS char *libclibs[] = LIBCLIBS; #else char *libclibs[] = { "-lc", NULL }; #endif #ifdef LIBCLIBS_PROFILE char *libclibs_profile[] = LIBCLIBS_PROFILE; #else char *libclibs_profile[] = { "-lc_p", NULL }; #endif #ifndef STARTLABEL #define STARTLABEL "_start" #endif char *incdir = STDINC; char *libdir = LIBDIR; char *altincdir; char *pccincdir; char *pcclibdir; /* handle gcc warning emulations */ struct Wflags { char *name; int flags; #define INWALL 1 #define NEGATIVE 2 } Wflags[] = { { "-Wtruncate", 0 }, { "-Wno-truncate", NEGATIVE }, { "-Werror", 0 }, { "-Wshadow", 0 }, { "-Wno-shadow", NEGATIVE }, { "-Wpointer-sign", INWALL }, { "-Wno-pointer-sign", NEGATIVE }, { "-Wsign-compare", 0 }, { "-Wno-sign-compare", NEGATIVE }, { "-Wunknown-pragmas", INWALL }, { "-Wno-unknown-pragmas", NEGATIVE }, { "-Wunreachable-code", 0 }, { "-Wno-unreachable-code", NEGATIVE }, { 0, 0 }, }; #define SZWFL (sizeof(Wflags)/sizeof(Wflags[0])) #ifndef USHORT /* copied from mip/manifest.h */ #define USHORT 5 #define INT 6 #define UNSIGNED 7 #endif /* * Wide char defines. */ #define WCT "short unsigned int" #define WCM "65535U" #define WCS 2 #ifdef GCC_COMPAT #ifndef REGISTER_PREFIX #define REGISTER_PREFIX "" #endif #ifndef USER_LABEL_PREFIX #define USER_LABEL_PREFIX "" #endif #endif #ifndef PCC_PTRDIFF_TYPE #define PCC_PTRDIFF_TYPE "long int" #endif /* * Copy src to string dst of size siz. At most siz-1 characters * will be copied. Always NUL terminates (unless siz == 0). * Returns strlen(src); if retval >= siz, truncation occurred. */ size_t strlcpy(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; /* Copy as many bytes as will fit */ if (n != 0 && --n != 0) { do { if ((*d++ = *s++) == 0) break; } while (--n != 0); } /* Not enough room in dst, add NUL and traverse rest of src */ if (n == 0) { if (siz != 0) *d = '\0'; /* NUL-terminate dst */ while (*s++) ; } return(s - src - 1); /* count does not include NUL */ } /* * Appends src to string dst of size siz (unlike strncat, siz is the * full size of dst, not space left). At most siz-1 characters * will be copied. Always NUL terminates (unless siz <= strlen(dst)). * Returns strlen(initial dst) + strlen(src); if retval >= siz, * truncation occurred. */ size_t strlcat(char *dst, const char *src, size_t siz) { char *d = dst; const char *s = src; size_t n = siz; size_t dlen; /* Find the end of dst and adjust bytes left but don't go past end */ while (n-- != 0 && *d != '\0') d++; dlen = d - dst; n = siz - dlen; if (n == 0) return(dlen + strlen(s)); while (*s != '\0') { if (n != 1) { *d++ = *s; n--; } s++; } *d = '\0'; return(dlen + (s - src)); /* count does not include NUL */ } void usage() { printf("Usage: %s [options] file...\n", progname); printf("Options:\n"); printf(" -h Display this information\n"); printf(" --version Display compiler version information\n"); printf(" -c Compile and assemble, but do not link\n"); printf(" -S Compile only; do not assemble or link\n"); printf(" -E Preprocess only; do not compile, assemble or link\n"); printf(" -P Preprocess to .i output file\n"); printf(" -o <file> Place the output into <file>\n"); printf(" -O, -O0 Enable, disable optimization\n"); printf(" -g Create debug output\n"); printf(" -v Display the programs invoked by the compiler\n"); if (mode == MODE_LCC || mode == MODE_PCC) { printf(" -k Generate position-independent code\n"); printf(" -Wall Enable gcc-compatible warnings\n"); printf(" -WW Enable all warnings\n"); printf(" -p, -pg Generate profiled code\n"); printf(" -r Generate relocatable code\n"); } printf(" -t Use traditional preprocessor syntax\n"); printf(" -C <option> Pass preprocessor option\n"); printf(" -Dname=val Define preprocessor symbol\n"); printf(" -Uname Undefine preprocessor symbol\n"); printf(" -Ipath Add a directory to preprocessor path\n"); printf(" -x <language> Specify the language of the following input files\n"); printf(" Permissible languages include: c assembler-with-cpp\n"); if (mode == MODE_LCC || mode == MODE_PCC) { printf(" -B <directory> Add <directory> to the compiler's search paths\n"); printf(" -m<option> Target-dependent options\n"); printf(" -f<option> GCC-compatible flags: -fPI -fpicC -fsigned-char\n"); printf(" -fno-signed-char -funsigned-char -fno-unsigned-char\n"); printf(" -fstack-protector -fstack-protector-all\n"); printf(" -fno-stack-protector -fno-stack-protector-all\n"); } printf(" -isystem dir Add a system include directory\n"); printf(" -include dir Add an include directory\n"); printf(" -idirafter dir Set a last include directory\n"); printf(" -nostdinc Disable standard include directories\n"); printf(" -nostdlib Disable standard libraries and start files\n"); printf(" -nostartfiles Disable standard start files\n"); printf(" -Wa,<options> Pass comma-separated <options> on to the assembler\n"); printf(" -Wp,<options> Pass comma-separated <options> on to the preprocessor\n"); printf(" -Wl,<options> Pass comma-separated <options> on to the linker\n"); printf(" -Wc,<options> Pass comma-separated <options> on to the compiler\n"); printf(" -M Output a list of dependencies\n"); printf(" -X Leave temporary files\n"); //printf(" -d Debug mode ???\n"); exit(0); } int main(int argc, char *argv[]) { struct Wflags *Wf; char *t, *u; char *assource; char **pv, *ptemp[MAXOPT], **pvt; int nc, nl, nas, ncpp, i, j, c, nxo, na; #ifdef MULTITARGET int k; #endif #ifdef INCLUDEDIR altincdir = INCLUDEDIR "pcc/"; #endif #ifdef PCCINCDIR pccincdir = PCCINCDIR; #endif #ifdef PCCLIBDIR pcclibdir = PCCLIBDIR; #endif progname = strrchr (argv[0], '/'); progname = progname ? progname+1 : argv[0]; /* * Select a compiler mode. */ if (strcmp ("pcc", progname) == 0) { /* PCC: portable C compiler. */ mode = MODE_PCC; cppadd[0] = "-D__PCC__"; pass0 = LIBEXECDIR "/ccom"; } else if (strcmp ("scc", progname) == 0) { /* SmallC. */ mode = MODE_SMALLC; cppadd[0] = "-D__SMALLC__"; pass0 = LIBEXECDIR "/smallc"; incdir = STDINC "/smallc"; } else if (strcmp ("lcc", progname) == 0) { /* LCC: retargetable C compiler. */ mode = MODE_LCC; cppadd[0] = "-D__LCC__"; pass0 = LIBEXECDIR "/lccom"; } else { /* Smaller C. */ mode = MODE_SMALLERC; cppadd[0] = "-D__SMALLER_C__"; pass0 = LIBEXECDIR "/smlrc"; } if (argc == 1) usage(); i = nc = nl = nas = ncpp = nxo = 0; pv = ptemp; while(++i < argc) { if (argv[i][0] == '-') { switch (argv[i][1]) { default: goto passa; case 'h': usage(); #ifdef notyet /* must add library options first (-L/-l/...) */ error("unrecognized option `-%c'", argv[i][1]); break; #endif case '-': /* double -'s */ if (strcmp(argv[i], "--version") == 0) { printf("%s\n", VERSSTR); return 0; } else if (strcmp(argv[i], "--param") == 0) /* NOTHING YET */; else goto passa; break; case 'B': /* other search paths for binaries */ Bflag = &argv[i][2]; break; #ifdef MULTITARGET case 'b': t = &argv[i][2]; if (*t == '\0' && i + 1 < argc) { t = argv[i+1]; i++; } if (strncmp(t, "?", 1) == 0) { /* show machine targets */ printf("Available machine targets:"); for (j=0; cppmds[j].mach; j++) printf(" %s",cppmds[j].mach); printf("\n"); exit(0); } for (j=0; cppmds[j].mach; j++) if (strcmp(t, cppmds[j].mach) == 0) { mach = cppmds[j].mach; break; } if (cppmds[j].mach == NULL) errorx(1, "unknown target arch %s", t); break; #endif case 'X': Xflag++; break; case 'W': /* Ignore (most of) W-flags */ if (strncmp(argv[i], "-Wl,", 4) == 0) { /* options to the linker */ t = &argv[i][4]; while ((u = strchr(t, ','))) { *u++ = 0; llist[nl++] = t; t = u; } llist[nl++] = t; } else if (strncmp(argv[i], "-Wa,", 4) == 0) { /* options to the assembler */ t = &argv[i][4]; while ((u = strchr(t, ','))) { *u++ = 0; aslist[nas++] = t; t = u; } aslist[nas++] = t; } else if (strncmp(argv[i], "-Wc,", 4) == 0) { /* options to ccom */ t = &argv[i][4]; while ((u = strchr(t, ','))) { *u++ = 0; wlist[nw++] = t; t = u; } wlist[nw++] = t; } else if (strncmp(argv[i], "-Wp,", 4) == 0) { /* preprocessor */ t = &argv[i][4]; while ((u = strchr(t, ','))) { *u++ = 0; cpplist[ncpp++] = t; t = u; } cpplist[ncpp++] = t; } else if (strcmp(argv[i], "-Wall") == 0) { Wallflag = 1; } else if (strcmp(argv[i], "-WW") == 0) { Wflag = 1; } else { /* check and set if available */ for (Wf = Wflags; Wf->name; Wf++) { if (strcmp(argv[i], Wf->name)) continue; wlist[nw++] = Wf->name; } } break; case 'f': /* GCC compatibility flags */ if (strcmp(argv[i], "-fPIC") == 0) kflag = F_PIC; else if (strcmp(argv[i], "-fpic") == 0) kflag = F_pic; else if (strcmp(argv[i], "-fsigned-char") == 0) flist[nf++] = argv[i]; else if (strcmp(argv[i], "-fno-signed-char") == 0) flist[nf++] = argv[i]; else if (strcmp(argv[i], "-funsigned-char") == 0) flist[nf++] = argv[i]; else if (strcmp(argv[i], "-fno-unsigned-char") == 0) flist[nf++] = argv[i]; else if (strcmp(argv[i], "-fstack-protector") == 0) { flist[nf++] = argv[i]; sspflag++; } else if (strcmp(argv[i], "-fstack-protector-all") == 0) { flist[nf++] = argv[i]; sspflag++; } else if (strcmp(argv[i], "-fno-stack-protector") == 0) { flist[nf++] = argv[i]; sspflag = 0; } else if (strcmp(argv[i], "-fno-stack-protector-all") == 0) { flist[nf++] = argv[i]; sspflag = 0; } /* silently ignore the rest */ break; case 'g': /* create debug output */ gflag++; break; case 'i': if (strcmp(argv[i], "-isystem") == 0) { *pv++ = "-S"; *pv++ = argv[++i]; } else if (strcmp(argv[i], "-include") == 0) { *pv++ = "-i"; *pv++ = argv[++i]; } else if (strcmp(argv[i], "-idirafter") == 0) { idirafter = argv[++i]; } else goto passa; break; case 'k': /* generate PIC code */ kflag = F_pic; break; case 'm': /* target-dependent options */ mlist[nm++] = argv[i]; break; case 'n': /* handle -n flags */ if (strcmp(argv[i], "-nostdinc") == 0) nostdinc++; else if (strcmp(argv[i], "-nostdlib") == 0) { nostdlib++; nostartfiles++; } else if (strcmp(argv[i], "-nostartfiles") == 0) nostartfiles = 1; else goto passa; break; case 'p': if (strcmp(argv[i], "-pg") == 0 || strcmp(argv[i], "-p") == 0) pgflag++; else if (strcmp(argv[i], "-pthread") == 0) pthreads++; else if (strcmp(argv[i], "-pipe") == 0) /* NOTHING YET */; else if (strcmp(argv[i], "-pedantic") == 0) /* NOTHING YET */; else if (strcmp(argv[i], "-print-prog-name=ld") == 0) { printf("%s\n", LINKER); return 0; } else errorx(1, "unknown option %s", argv[i]); break; case 'r': rflag = 1; break; case 'x': t = &argv[i][2]; if (*t == 0) t = argv[++i]; if (strcmp(t, "c") == 0) xcflag = 1; /* default */ else if (strcmp(t, "assembler-with-cpp") == 0) ascpp = 1; #ifdef notyet else if (strcmp(t, "c++") == 0) cxxflag++; #endif else xlist[xnum++] = argv[i]; break; case 't': tflag++; break; case 'S': sflag++; cflag++; break; case 'o': if (outfile) errorx(8, "too many -o"); outfile = argv[++i]; break; case 'O': if (argv[i][2] == '0') Oflag = 0; else Oflag++; break; case 'E': Eflag++; break; case 'P': pflag++; *pv++ = argv[i]; case 'c': cflag++; break; #if 0 case '2': if(argv[i][2] == '\0') pref = "/lib/crt2.o"; else { pref = "/lib/crt20.o"; } break; #endif case 'C': cpplist[ncpp++] = argv[i]; break; case 'D': case 'I': case 'U': *pv++ = argv[i]; if (argv[i][2] == 0) *pv++ = argv[++i]; if (pv >= ptemp+MAXOPT) { error("Too many DIU options"); --pv; } break; case 'M': Mflag++; break; case 'd': if (strcmp(argv[i], "-d") == 0) { dflag++; strlcpy(alist, argv[i], sizeof (alist)); } break; case 'v': printf("%s\n", VERSSTR); vflag++; break; case 's': if (strcmp(argv[i], "-shared") == 0) { shared = 1; nostdlib = 1; } else if (strcmp(argv[i], "-static") == 0) { Bstatic = 1; } else if (strncmp(argv[i], "-std", 4) == 0) { /* ignore gcc -std= */; } else goto passa; break; } } else { passa: t = argv[i]; if (*argv[i] == '-' && argv[i][1] == 'L') ; else if((c=getsuf(t))=='c' || c=='S' || c=='i' || c=='s'|| Eflag || xcflag) { clist[nc++] = t; if (nc>=MAXFIL) { error("Too many source files"); exit(1); } } /* Check for duplicate .o files. */ for (j = getsuf(t) == 'o' ? 0 : nl; j < nl; j++) { if (strcmp(llist[j], t) == 0) break; } if ((c=getsuf(t))!='c' && c!='S' && c!='s' && c!='i' && j==nl) { llist[nl++] = t; if (nl >= MAXLIB) { error("Too many object/library files"); exit(1); } if (getsuf(t)=='o') nxo++; } } } /* Sanity checking */ if (nc == 0 && nl == 0) errorx(8, "no input files"); if (outfile && (cflag || sflag || Eflag) && nc > 1) errorx(8, "-o given with -c || -E || -S and more than one file"); if (outfile && clist[0] && strcmp(outfile, clist[0]) == 0) errorx(8, "output file will be clobbered"); if (nc==0) goto nocom; if (pflag==0) { if (!sflag) tmp_as = gettmp(); tmp_cpp = gettmp(); } if (Bflag) { if (altincdir) altincdir = Bflag; if (pccincdir) pccincdir = Bflag; if (pcclibdir) pcclibdir = Bflag; } if (signal(SIGINT, SIG_IGN) != SIG_IGN) /* interrupt */ signal(SIGINT, idexit); if (signal(SIGTERM, SIG_IGN) != SIG_IGN) /* terminate */ signal(SIGTERM, idexit); #ifdef MULTITARGET pass0 = copy(LIBEXECDIR "/ccom_", k = strlen(mach)); strlcat(pass0, mach, sizeof(LIBEXECDIR "/ccom_") + k); #endif pvt = pv; for (i=0; i<nc; i++) { /* * C preprocessor */ if (nc>1 && !Eflag) printf("%s:\n", clist[i]); onlyas = 0; assource = tmp_as; if (getsuf(clist[i])=='S') ascpp = 1; if (getsuf(clist[i])=='i') { if(Eflag) continue; goto com; } else if (ascpp) { onlyas = 1; } else if (getsuf(clist[i])=='s') { assource = clist[i]; goto assemble; } if (pflag) tmp_cpp = setsuf(clist[i], 'i'); na = 0; av[na++] = "cpp"; if (vflag) av[na++] = "-v"; if (mode == MODE_PCC) { av[na++] = "-D__PCC__=" MKS(PCC_MAJOR); av[na++] = "-D__PCC_MINOR__=" MKS(PCC_MINOR); av[na++] = "-D__PCC_MINORMINOR__=" MKS(PCC_MINORMINOR); } #ifdef GCC_COMPAT av[na++] = "-D__GNUC__=4"; av[na++] = "-D__GNUC_MINOR__=3"; av[na++] = "-D__GNUC_PATCHLEVEL__=1"; av[na++] = "-D__GNUC_STDC_INLINE__=1"; #endif if (ascpp) av[na++] = "-D__ASSEMBLER__"; if (sspflag) av[na++] = "-D__SSP__=1"; if (pthreads) av[na++] = "-D_PTHREADS"; if (Mflag) av[na++] = "-M"; if (Oflag) av[na++] = "-D__OPTIMIZE__"; #ifdef GCC_COMPAT av[na++] = "-D__REGISTER_PREFIX__=" REGISTER_PREFIX; av[na++] = "-D__USER_LABEL_PREFIX__=" USER_LABEL_PREFIX; if (Oflag) av[na++] = "-D__OPTIMIZE__"; #endif if (dflag) av[na++] = alist; for (j = 0; cppadd[j]; j++) av[na++] = cppadd[j]; for (j = 0; j < ncpp; j++) av[na++] = cpplist[j]; av[na++] = "-D__STDC_ISO_10646__=200009L"; av[na++] = "-D__WCHAR_TYPE__=" WCT; av[na++] = "-D__SIZEOF_WCHAR_T__=" MKS(WCS); av[na++] = "-D__WCHAR_MAX__=" WCM; av[na++] = "-D__WINT_TYPE__=unsigned int"; av[na++] = "-D__SIZE_TYPE__=unsigned long"; av[na++] = "-D__PTRDIFF_TYPE__=" PCC_PTRDIFF_TYPE; av[na++] = "-D__SIZEOF_WINT_T__=4"; #ifdef MULTITARGET for (k = 0; cppmds[k].mach; k++) { if (strcmp(cppmds[k].mach, mach) != 0) continue; for (j = 0; cppmds[k].cppmdadd[j]; j++) av[na++] = cppmds[k].cppmdadd[j]; break; } #else for (j = 0; cppmdadd[j]; j++) av[na++] = cppmdadd[j]; #endif if (tflag) av[na++] = "-t"; for(pv=ptemp; pv <pvt; pv++) av[na++] = *pv; if (!nostdinc) { if (altincdir) av[na++] = "-S", av[na++] = altincdir; av[na++] = "-S", av[na++] = incdir; if (pccincdir) av[na++] = "-S", av[na++] = pccincdir; } if (idirafter) { av[na++] = "-I"; av[na++] = idirafter; } av[na++] = clist[i]; if (!Eflag && !Mflag) av[na++] = tmp_cpp; if ((Eflag || Mflag) && outfile) ermfile = av[na++] = outfile; av[na++]=0; if (callsys(passp, av)) { exfail++; eflag++; } if (Eflag || Mflag) continue; if (onlyas) { assource = tmp_cpp; goto assemble; } /* * C compiler */ com: na = 0; av[na++]= "ccom"; if (Wallflag) { /* Set only the same flags as gcc */ for (Wf = Wflags; Wf->name; Wf++) { if (Wf->flags != INWALL) continue; av[na++] = Wf->name; } } if (Wflag) { /* set all positive flags */ for (Wf = Wflags; Wf->name; Wf++) { if (Wf->flags == NEGATIVE) continue; av[na++] = Wf->name; } } for (j = 0; j < nw; j++) av[na++] = wlist[j]; for (j = 0; j < nf; j++) av[na++] = flist[j]; if (vflag) av[na++] = "-v"; if (pgflag) av[na++] = "-p"; if (gflag) av[na++] = "-g"; if (kflag) av[na++] = "-k"; if (Oflag) { av[na++] = "-xtemps"; av[na++] = "-xdeljumps"; av[na++] = "-xinline"; } for (j = 0; j < xnum; j++) av[na++] = xlist[j]; for (j = 0; j < nm; j++) av[na++] = mlist[j]; if (getsuf(clist[i])=='i') av[na++] = clist[i]; else av[na++] = tmp_cpp; /* created by cpp */ if (pflag || exfail) { cflag++; continue; } if (sflag) { if (outfile) tmp_as = outfile; else tmp_as = setsuf(clist[i], 's'); } ermfile = av[na++] = tmp_as; #if 0 if (proflag) { av[3] = "-XP"; av[4] = 0; } else av[3] = 0; #endif av[na++] = NULL; if (callsys(pass0, av)) { cflag++; eflag++; continue; } if (sflag) continue; /* * Assembler */ assemble: na = 0; av[na++] = as; for (j = 0; j < nas; j++) av[na++] = aslist[j]; if (vflag) av[na++] = "-v"; if (kflag) av[na++] = "-k"; av[na++] = "-o"; if (outfile && cflag) ermfile = av[na++] = outfile; else if (cflag) ermfile = av[na++] = olist[i] = setsuf(clist[i], 'o'); else ermfile = av[na++] = olist[i] = gettmp(); av[na++] = assource; if (dflag) av[na++] = alist; av[na++] = 0; if (callsys(as, av)) { cflag++; eflag++; if (ascpp) cunlink(tmp_cpp); continue; } if (ascpp) cunlink(tmp_cpp); } if (Eflag || Mflag) dexit(eflag); /* * Linker */ nocom: if (cflag==0 && nc+nl != 0) { j = 0; av[j++] = ld; if (vflag) av[j++] = "-v"; av[j++] = "-X"; if (shared) { av[j++] = "-shared"; } else { av[j++] = "-d"; if (rflag) { av[j++] = "-r"; } else { av[j++] = "-e"; av[j++] = STARTLABEL; } if (Bstatic == 0) { /* Dynamic linkage */ #ifdef DYNLINKER for (i = 0; dynlinker[i]; i++) av[j++] = dynlinker[i]; #endif } else { av[j++] = "-Bstatic"; } } if (outfile) { av[j++] = "-o"; av[j++] = outfile; } #ifdef STARTFILES_S if (shared) { if (!nostartfiles) { for (i = 0; startfiles_S[i]; i++) av[j++] = Bprefix(startfiles_S[i]); } } else #endif { if (!nostartfiles) { #ifdef CRT0FILE_PROFILE if (pgflag) { av[j++] = Bprefix(crt0file_profile); } else #endif { #ifdef CRT0FILE av[j++] = Bprefix(crt0file); #endif } #ifdef STARTFILES_T if (Bstatic) { for (i = 0; startfiles_T[i]; i++) av[j++] = Bprefix(startfiles_T[i]); } else #endif { #ifdef STARTFILES for (i = 0; startfiles[i]; i++) av[j++] = Bprefix(startfiles[i]); #endif } } } i = 0; while (i<nc) { av[j++] = olist[i++]; if (j >= MAXAV) error("Too many ld options"); } i = 0; while(i<nl) { av[j++] = llist[i++]; if (j >= MAXAV) error("Too many ld options"); } if (gflag) av[j++] = "-g"; #if 0 if (gflag) av[j++] = "-lg"; #endif if (pthreads) av[j++] = "-lpthread"; if (!nostdlib) { #define DL "-L" char *s; if (pcclibdir) { s = copy(DL, i = strlen(pcclibdir)); strlcat(s, pcclibdir, sizeof(DL) + i); av[j++] = s; } if (pgflag) { for (i = 0; libclibs_profile[i]; i++) av[j++] = Bprefix(libclibs_profile[i]); } else { for (i = 0; libclibs[i]; i++) av[j++] = Bprefix(libclibs[i]); } } if (!nostartfiles) { #ifdef STARTFILES_S if (shared) { for (i = 0; endfiles_S[i]; i++) av[j++] = Bprefix(endfiles_S[i]); } else #endif { #ifdef STARTFILES_T if (Bstatic) { for (i = 0; endfiles_T[i]; i++) av[j++] = Bprefix(endfiles_T[i]); } else #endif { #ifdef STARTFILES for (i = 0; endfiles[i]; i++) av[j++] = Bprefix(endfiles[i]); #endif } } } av[j++] = 0; eflag |= callsys(ld, av); if (nc==1 && nxo==1 && eflag==0) cunlink(olist[0]); else if (nc > 0 && eflag == 0) { /* remove .o files XXX ugly */ for (i = 0; i < nc; i++) cunlink(olist[i]); } } dexit(eflag); return 0; } /* * exit and cleanup after interrupt. */ void idexit(int arg) { dexit(100); } /* * exit and cleanup. */ void dexit(int eval) { if (!pflag && !Xflag) { if (sflag==0) cunlink(tmp_as); cunlink(tmp_cpp); } if (exfail || eflag) cunlink(ermfile); if (eval == 100) _exit(eval); exit(eval); } static void ccerror(char *s, va_list ap) { vfprintf(Eflag ? stderr : stdout, s, ap); putc('\n', Eflag? stderr : stdout); exfail++; cflag++; eflag++; } /* * complain a bit. */ void error(char *s, ...) { va_list ap; va_start(ap, s); ccerror(s, ap); va_end(ap); } /* * complain a bit and then exit. */ void errorx(int eval, char *s, ...) { va_list ap; va_start(ap, s); ccerror(s, ap); va_end(ap); dexit(eval); } char * Bprefix(char *s) { char *suffix; char *str; int i; if (Bflag == NULL || s[0] != '/') return s; suffix = strrchr(s, '/'); if (suffix == NULL) suffix = s; str = copy(Bflag, i = strlen(suffix)); strlcat(str, suffix, strlen(Bflag) + i + 1); return str; } int getsuf(char *s) { register char *p; if ((p = strrchr(s, '.')) && p[1] != '\0' && p[2] == '\0') return p[1]; return(0); } /* * Get basename of string s and change its suffix to ch. */ char * setsuf(char *s, char ch) { char *p, *lastp; int len; /* Strip trailing slashes, if any. */ lastp = s + strlen(s) - 1; while (lastp != s && *lastp == '/') lastp--; /* Now find the beginning of this (final) component. */ p = lastp; while (p != s && *(p - 1) != '/') p--; /* ...and copy the result into the result buffer. */ len = (lastp - p) + 1; s = ccmalloc(len + 3); memcpy(s, p, len); s[len] = '\0'; /* Find and change a suffix */ p = strrchr(s, '.'); if (! p) { p = s + len; p[0] = '.'; } p[1] = ch; p[2] = '\0'; return(s); } int callsys(char *f, char *v[]) { int t, status = 0; pid_t p; char *s; char * volatile a = NULL; volatile size_t len; if (vflag) { fprintf(stderr, "%s ", f); for (t = 1; v[t]; t++) fprintf(stderr, "%s ", v[t]); fprintf(stderr, "\n"); } if (Bflag) { len = strlen(Bflag) + 8; a = malloc(len); } #ifdef HAVE_VFORK if ((p = vfork()) == 0) { #else if ((p = fork()) == 0) { #endif if (Bflag) { if (a == NULL) { error("callsys: malloc failed"); exit(1); } if ((s = strrchr(f, '/'))) { strlcpy(a, Bflag, len); strlcat(a, s, len); execv(a, v); } } execvp(f, v); if ((s = strrchr(f, '/'))) execvp(s+1, v); fprintf(stderr, "Can't find %s\n", f); _exit(100); } if (p == -1) { fprintf(stderr, "fork() failed, try again\n"); return(100); } if (Bflag) { free(a); } while (waitpid(p, &status, 0) == -1 && errno == EINTR) ; if (WIFEXITED(status)) return (WEXITSTATUS(status)); if (WIFSIGNALED(status)) dexit(eflag ? eflag : 1); errorx(8, "Fatal error in %s", f); return 0; } /* * Make a copy of string as, mallocing extra bytes in the string. */ char * copy(char *s, int extra) { int len = strlen(s)+1; char *rv; rv = ccmalloc(len+extra); strlcpy(rv, s, len); return rv; } int cunlink(char *f) { if (f==0 || Xflag) return(0); return (unlink(f)); } char * gettmp(void) { char *sfn = copy("/tmp/ctm.XXXXXX", 0); int fd = -1; if ((fd = mkstemp(sfn)) == -1) { fprintf(stderr, "%s: %s\n", sfn, strerror(errno)); exit(8); } close(fd); return sfn; } void * ccmalloc(int size) { void *rv; if ((rv = malloc(size)) == NULL) error("malloc failed"); return rv; }
22.506285
86
0.541314
[ "object" ]
15c22f06aa84247708d43bb870a169d3a04052c6
2,066
h
C
FrameworkLib/WinRTAppController.h
DashW/Ingenuity
f7944a9e8063beaa3dda31e8372d18b4147782e2
[ "Zlib" ]
null
null
null
FrameworkLib/WinRTAppController.h
DashW/Ingenuity
f7944a9e8063beaa3dda31e8372d18b4147782e2
[ "Zlib" ]
null
null
null
FrameworkLib/WinRTAppController.h
DashW/Ingenuity
f7944a9e8063beaa3dda31e8372d18b4147782e2
[ "Zlib" ]
null
null
null
#pragma once #include "RealtimeApp.h" namespace Ingenuity { namespace WinRT { ref class AppController sealed : public Windows::ApplicationModel::Core::IFrameworkView { public: AppController(); // IFrameworkView Methods virtual void Initialize(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView); virtual void SetWindow(Windows::UI::Core::CoreWindow^ window); virtual void Load(Platform::String^ entryPoint); virtual void Run(); virtual void Uninitialize(); __int64 GetTimeStamp(); protected: // Event Handlers void OnActivated(Windows::ApplicationModel::Core::CoreApplicationView^ applicationView, Windows::ApplicationModel::Activation::IActivatedEventArgs^ args); void OnSuspending(Platform::Object^ sender, Windows::ApplicationModel::SuspendingEventArgs^ args); void OnResuming(Platform::Object^ sender, Platform::Object^ args); void OnWindowClosed(Windows::UI::Core::CoreWindow^ sender, Windows::UI::Core::CoreWindowEventArgs^ args); void OnPointerPressed(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args); void OnPointerReleased(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args); void OnPointerMoved(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::PointerEventArgs ^ args); void OnKeyDown(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args); void OnKeyUp(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::KeyEventArgs ^ args); void OnCharacterRecieved(Windows::UI::Core::CoreWindow ^ sender, Windows::UI::Core::CharacterReceivedEventArgs ^ args); void OnUnhandledException(Platform::Object ^ sender, Windows::UI::Xaml::UnhandledExceptionEventArgs ^ args); private: RealtimeApp* app; bool windowClosed; bool windowActivated; }; ref class AppSource sealed : Windows::ApplicationModel::Core::IFrameworkViewSource { public: virtual Windows::ApplicationModel::Core::IFrameworkView^ CreateView(); }; struct AppDeadDrop { static RealtimeApp* app; }; } // namespace WinRT } // namespace Ingenuity
35.62069
155
0.773959
[ "object" ]
15c575880f34936e4016c86d93fff675315c12fd
12,675
h
C
src/ToolBarButtonContainer.h
TimoKunze/ToolBarControls
409625a0e8541d7cea7a108951699970953af757
[ "MIT" ]
1
2019-12-12T08:12:14.000Z
2019-12-12T08:12:14.000Z
src/ToolBarButtonContainer.h
TimoKunze/ToolBarControls
409625a0e8541d7cea7a108951699970953af757
[ "MIT" ]
null
null
null
src/ToolBarButtonContainer.h
TimoKunze/ToolBarControls
409625a0e8541d7cea7a108951699970953af757
[ "MIT" ]
2
2018-05-05T02:30:05.000Z
2021-12-09T18:20:38.000Z
////////////////////////////////////////////////////////////////////// /// \class ToolBarButtonContainer /// \author Timo "TimoSoft" Kunze /// \brief <em>Manages a collection of \c ToolBarButton objects</em> /// /// This class provides easy access to collections of \c ToolBarButton objects. While a /// \c ToolBarButtons object is used to group tool bar buttons that have certain properties in common, a /// \c ToolBarButtonContainer object is used to group any buttons and acts more like a clipboard. /// /// \if UNICODE /// \sa TBarCtlsLibU::IToolBarButtonContainer, ToolBarButton, ToolBarButtons, ToolBar /// \else /// \sa TBarCtlsLibA::IToolBarButtonContainer, ToolBarButton, ToolBarButtons, ToolBar /// \endif ////////////////////////////////////////////////////////////////////// #pragma once #include "res/resource.h" #ifdef UNICODE #include "TBarCtlsU.h" #else #include "TBarCtlsA.h" #endif #include "_IToolBarButtonContainerEvents_CP.h" #include "IButtonContainer.h" #include "helpers.h" #include "ToolBar.h" #include "ToolBarButton.h" class ATL_NO_VTABLE ToolBarButtonContainer : public CComObjectRootEx<CComSingleThreadModel>, public CComCoClass<ToolBarButtonContainer, &CLSID_ToolBarButtonContainer>, public ISupportErrorInfo, public IConnectionPointContainerImpl<ToolBarButtonContainer>, public Proxy_IToolBarButtonContainerEvents<ToolBarButtonContainer>, public IEnumVARIANT, #ifdef UNICODE public IDispatchImpl<IToolBarButtonContainer, &IID_IToolBarButtonContainer, &LIBID_TBarCtlsLibU, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR>, #else public IDispatchImpl<IToolBarButtonContainer, &IID_IToolBarButtonContainer, &LIBID_TBarCtlsLibA, /*wMajor =*/ VERSION_MAJOR, /*wMinor =*/ VERSION_MINOR>, #endif public IButtonContainer { friend class ToolBar; friend class ToolBarButtonContainer; public: /// \brief <em>The constructor of this class</em> /// /// Used to generate and set this object's ID. /// /// \sa ~ToolBarButtonContainer ToolBarButtonContainer(); /// \brief <em>The destructor of this class</em> /// /// Used to deregister the container. /// /// \sa ToolBarButtonContainer ~ToolBarButtonContainer(); #ifndef DOXYGEN_SHOULD_SKIP_THIS DECLARE_REGISTRY_RESOURCEID(IDR_TOOLBARBUTTONCONTAINER) BEGIN_COM_MAP(ToolBarButtonContainer) COM_INTERFACE_ENTRY(IToolBarButtonContainer) COM_INTERFACE_ENTRY(IDispatch) COM_INTERFACE_ENTRY(ISupportErrorInfo) COM_INTERFACE_ENTRY(IConnectionPointContainer) COM_INTERFACE_ENTRY(IEnumVARIANT) END_COM_MAP() BEGIN_CONNECTION_POINT_MAP(ToolBarButtonContainer) CONNECTION_POINT_ENTRY(__uuidof(_IToolBarButtonContainerEvents)) END_CONNECTION_POINT_MAP() DECLARE_PROTECT_FINAL_CONSTRUCT() #endif ////////////////////////////////////////////////////////////////////// /// \name Implementation of ISupportErrorInfo /// //@{ /// \brief <em>Retrieves whether an interface supports the \c IErrorInfo interface</em> /// /// \param[in] interfaceToCheck The IID of the interface to check. /// /// \return \c S_OK if the interface identified by \c interfaceToCheck supports \c IErrorInfo; /// otherwise \c S_FALSE. /// /// \sa <a href="https://msdn.microsoft.com/en-us/library/ms221233.aspx">IErrorInfo</a> virtual HRESULT STDMETHODCALLTYPE InterfaceSupportsErrorInfo(REFIID interfaceToCheck); //@} ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// \name Implementation of IEnumVARIANT /// //@{ /// \brief <em>Clones the \c VARIANT iterator used to iterate the buttons</em> /// /// Clones the \c VARIANT iterator including its current state. This iterator is used to iterate /// the \c ToolBarButton objects managed by this collection object. /// /// \param[out] ppEnumerator Receives the clone's \c IEnumVARIANT implementation. /// /// \return An \c HRESULT error code. /// /// \sa Next, Reset, Skip, /// <a href="https://msdn.microsoft.com/en-us/library/ms221053.aspx">IEnumVARIANT</a>, /// <a href="https://msdn.microsoft.com/en-us/library/ms690336.aspx">IEnumXXXX::Clone</a> virtual HRESULT STDMETHODCALLTYPE Clone(IEnumVARIANT** ppEnumerator); /// \brief <em>Retrieves the next x buttons</em> /// /// Retrieves the next \c numberOfMaxButtons buttons from the iterator. /// /// \param[in] numberOfMaxButtons The maximum number of buttons the array identified by \c pButtons can /// contain. /// \param[in,out] pButtons An array of \c VARIANT values. On return, each \c VARIANT will contain /// the pointer to an button's \c IToolBarButton implementation. /// \param[out] pNumberOfButtonsReturned The number of buttons that actually were copied to the array /// identified by \c pButtons. /// /// \return An \c HRESULT error code. /// /// \sa Clone, Reset, Skip, ToolBarButton, /// <a href="https://msdn.microsoft.com/en-us/library/ms695273.aspx">IEnumXXXX::Next</a> virtual HRESULT STDMETHODCALLTYPE Next(ULONG numberOfMaxButtons, VARIANT* pButtons, ULONG* pNumberOfButtonsReturned); /// \brief <em>Resets the \c VARIANT iterator</em> /// /// Resets the \c VARIANT iterator so that the next call of \c Next or \c Skip starts at the first /// button in the collection. /// /// \return An \c HRESULT error code. /// /// \sa Clone, Next, Skip, /// <a href="https://msdn.microsoft.com/en-us/library/ms693414.aspx">IEnumXXXX::Reset</a> virtual HRESULT STDMETHODCALLTYPE Reset(void); /// \brief <em>Skips the next x buttons</em> /// /// Instructs the \c VARIANT iterator to skip the next \c numberOfButtonsToSkip buttons. /// /// \param[in] numberOfButtonsToSkip The number of buttons to skip. /// /// \return An \c HRESULT error code. /// /// \sa Clone, Next, Reset, /// <a href="https://msdn.microsoft.com/en-us/library/ms690392.aspx">IEnumXXXX::Skip</a> virtual HRESULT STDMETHODCALLTYPE Skip(ULONG numberOfButtonsToSkip); //@} ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// \name Implementation of IToolBarButtonContainer /// //@{ /// \brief <em>Retrieves a \c ToolBarButton object from the collection</em> /// /// Retrieves a \c ToolBarButton object from the collection that wraps the tool bar button identified /// by \c buttonID. /// /// \param[in] buttonID The unique ID of the tool bar button to retrieve. /// \param[out] ppButton Receives the item's \c IToolBarButton implementation. /// /// \return An \c HRESULT error code. /// /// \remarks This property is read-only. /// /// \sa ToolBarButton::get_ID, Add, Remove virtual HRESULT STDMETHODCALLTYPE get_Item(LONG buttonID, IToolBarButton** ppButton); /// \brief <em>Retrieves a \c VARIANT enumerator</em> /// /// Retrieves a \c VARIANT enumerator that may be used to iterate the \c ToolBarButton objects /// managed by this collection object. This iterator is used by Visual Basic's \c For...Each /// construct. /// /// \param[out] ppEnumerator Receives the iterator's \c IEnumVARIANT implementation. /// /// \return An \c HRESULT error code. /// /// \remarks This property is read-only and hidden. /// /// \sa <a href="https://msdn.microsoft.com/en-us/library/ms221053.aspx">IEnumVARIANT</a> virtual HRESULT STDMETHODCALLTYPE get__NewEnum(IUnknown** ppEnumerator); /// \brief <em>Adds the specified button(s) to the collection</em> /// /// \param[in] buttonsToAdd The button(s) to add. May be either a button ID, a \c ToolBarButton object or /// a \c ToolBarButtons collection. /// /// \return An \c HRESULT error code. /// /// \sa ToolBarButton::get_ID, Count, Remove, RemoveAll virtual HRESULT STDMETHODCALLTYPE Add(VARIANT buttonsToAdd); /// \brief <em>Clones the collection object</em> /// /// Retrieves an exact copy of the collection. /// /// \param[out] ppClone Receives the clone's \c IToolBarButtonContainer implementation. /// /// \return An \c HRESULT error code. /// /// \sa ToolBar::CreateButtonContainer virtual HRESULT STDMETHODCALLTYPE Clone(IToolBarButtonContainer** ppClone); /// \brief <em>Counts the buttons in the collection</em> /// /// Retrieves the number of \c ToolBarButton objects in the collection. /// /// \param[out] pValue The number of elements in the collection. /// /// \return An \c HRESULT error code. /// /// \sa Add, Remove, RemoveAll virtual HRESULT STDMETHODCALLTYPE Count(LONG* pValue); /// \brief <em>Retrieves an imagelist containing the buttons' common drag image</em> /// /// Retrieves the handle to an imagelist containing a bitmap that can be used to visualize /// dragging of the buttons of this collection. /// /// \param[out] pXUpperLeft The x-coordinate (in pixels) of the drag image's upper-left corner relative /// to the control's upper-left corner. /// \param[out] pYUpperLeft The y-coordinate (in pixels) of the drag image's upper-left corner relative /// to the control's upper-left corner. /// \param[out] phImageList The handle to the imagelist. /// /// \return An \c HRESULT error code. /// /// \remarks The caller is responsible for destroying the imagelist. /// /// \sa ToolBar::CreateLegacyDragImage virtual HRESULT STDMETHODCALLTYPE CreateDragImage(OLE_XPOS_PIXELS* pXUpperLeft = NULL, OLE_YPOS_PIXELS* pYUpperLeft = NULL, OLE_HANDLE* phImageList = NULL); /// \brief <em>Removes the specified button from the collection</em> /// /// \param[in] buttonID The unique ID of the tool bar button to remove. /// \param[in] removePhysically If \c VARIANT_TRUE, the button is removed from the control, too. /// /// \return An \c HRESULT error code. /// /// \sa ToolBarButton::get_ID, Add, Count, RemoveAll virtual HRESULT STDMETHODCALLTYPE Remove(LONG buttonID, VARIANT_BOOL removePhysically = VARIANT_FALSE); /// \brief <em>Removes all buttons from the collection</em> /// /// \param[in] removePhysically If \c VARIANT_TRUE, the buttons get removed from the control, too. /// /// \return An \c HRESULT error code. /// /// \sa Add, Count, Remove virtual HRESULT STDMETHODCALLTYPE RemoveAll(VARIANT_BOOL removePhysically = VARIANT_FALSE); //@} ////////////////////////////////////////////////////////////////////// /// \brief <em>Sets the owner of this collection</em> /// /// \param[in] pOwner The owner to set. /// /// \sa Properties::pOwnerTBar void SetOwner(__in_opt ToolBar* pOwner); protected: ////////////////////////////////////////////////////////////////////// /// \name Implementation of IButtonContainer /// //@{ /// \brief <em>A button was removed and the button container should check its content</em> /// /// \param[in] buttonID The unique ID of the removed button. If -1, all buttons were removed. /// /// \sa ToolBar::RemoveButtonFromButtonContainers void RemovedButton(LONG buttonID); /// \brief <em>Retrieves the container's ID used to identify it</em> /// /// \return The container's ID. /// /// \sa ToolBar::DeregisterButtonContainer, containerID DWORD GetID(void); /// \brief <em>Holds the container's ID</em> DWORD containerID; //@} ////////////////////////////////////////////////////////////////////// /// \brief <em>Holds the object's properties' settings</em> struct Properties { /// \brief <em>The \c ToolBar object that owns this collection</em> ToolBar* pOwnerTBar; #ifdef USE_STL /// \brief <em>Holds the buttons that this object contains</em> std::vector<LONG> buttons; #else /// \brief <em>Holds the buttons that this object contains</em> //CAtlArray<LONG> buttons; #endif /// \brief <em>Points to the next enumerated button</em> int nextEnumeratedButton; Properties() { pOwnerTBar = NULL; nextEnumeratedButton = 0; } ~Properties(); /// \brief <em>Retrieves the owning tool bar's window handle</em> /// /// \return The window handle of the tool bar that contains the buttons in this collection. /// /// \sa pOwnerTBar HWND GetTBarHWnd(void); } properties; /* TODO: If we move this one into the Properties struct, the compiler complains that the private = operator of CAtlArray cannot be accessed?! */ #ifndef USE_STL /// \brief <em>Holds the buttons that this object contains</em> CAtlArray<LONG> buttons; #endif /// \brief <em>Incremented by the constructor and used as the constructed object's ID</em> /// /// \sa ToolBarButtonContainer, containerID static DWORD nextID; }; // ToolBarButtonContainer OBJECT_ENTRY_AUTO(__uuidof(ToolBarButtonContainer), ToolBarButtonContainer)
38.761468
158
0.675582
[ "object", "vector" ]
15c58ce2c33a795e53cd1221376e80bb9775eb00
2,973
h
C
CalibCalorimetry/EcalLaserAnalyzer/interface/TFParams.h
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
CalibCalorimetry/EcalLaserAnalyzer/interface/TFParams.h
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
CalibCalorimetry/EcalLaserAnalyzer/interface/TFParams.h
Purva-Chaudhari/cmssw
32e5cbfe54c4d809d60022586cf200b7c3020bcf
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#ifndef TFParams_h #define TFParams_h #include "TROOT.h" #include "TObject.h" #include "TArrayI.h" #include "TArrayD.h" #include "TArrayC.h" #include "TCanvas.h" #include "TDirectory.h" #include "TPaveLabel.h" #include "TF1.h" #include <ctime> #include "TGraph.h" #include <cstdio> #include <cmath> #include "TH2.h" #include "TH1.h" #include "TStyle.h" #include "TCanvas.h" #include "TPaveText.h" #include "TPaveLabel.h" #include "TProfile.h" #include "TVirtualX.h" #include "TObject.h" //#include "TMatrixD.h" struct matrice { int nb_lignes; int nb_colonnes; double **coeff; }; typedef struct matrice matrice; matrice cree_mat(int, int); matrice cree_mat_prod(matrice, matrice); void fill_mat(matrice, matrice); matrice fill_mat_int(matrice, matrice, matrice); class TFParams : public TObject { public: static constexpr unsigned int dimmat = 30; static constexpr unsigned int dimout = 10; static constexpr unsigned int nbmax_cell = 1000; static constexpr int SDIM2 = 10; static constexpr int PLSHDIM = 650; private: int ns; // number of samples int nsmin; // beginning of fit int nsmax; // end of fit int nevtmax; // number of events to fit double a1ini; // value of alpha at starting point double a2ini; // value of alpha_prim/beta at starting point double a3ini; // value of beta/alpha_prim at starting point double step_shape; double adclu[26]; double weight_matrix[10][10]; int METHODE; public: /* number of samples for cristal */ /* size of the pulse shape array */ TFParams(int size = SDIM2, int size_sh = PLSHDIM); ~TFParams() override{}; double fitpj(double **, double *, double **, double noise_val, int debug); void set_const(int, int, int, double, double, int); void produit_mat(matrice, matrice, matrice); void produit_mat_int(matrice, matrice, matrice); void diff_mat(matrice, matrice, matrice); void somme_mat_int(matrice, matrice); void somme_mat_int_scale(matrice, matrice, double); void print_mat_nk(matrice, int); void print_mat(matrice); void transpose_mat(matrice, matrice); void inverse_mat(matrice, matrice); void copie_colonne_mat(matrice, matrice, int); char name_mat[10]; void zero_mat(matrice); void zero_mat_nk(matrice, int); double f3deg(int, double parom[dimout], double mask[dimmat], double adcpj[dimmat], double errpj[dimmat][dimmat]); double parab(double *, Int_t, Int_t, double *); Double_t polfit(Int_t ns, Int_t imax, Double_t par3d[dimout], Double_t errpj[dimmat][dimmat], double *); double inverpj(int, double g[dimmat][dimmat], double ginv[dimmat][dimmat]); double inv3x3(double a[3][3], double b[3][3]); double pulseShapepj(Double_t *, Double_t *); double pulseShapepj2(Double_t *, Double_t *); double lastShape(Double_t *, Double_t *); double lastShape2(Double_t *, Double_t *); double mixShape(Double_t *, Double_t *); double computePulseWidth(int, double, double); ClassDefOverride(TFParams, 0) }; #endif
31.62766
115
0.72183
[ "shape" ]
15c92c5524c38ace76057510d7b05e44a86cd562
6,829
h
C
PYTHIA8/AliPythia8/AliTPythia8.h
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
1
2017-04-27T17:28:15.000Z
2017-04-27T17:28:15.000Z
PYTHIA8/AliPythia8/AliTPythia8.h
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
3
2017-07-13T10:54:50.000Z
2018-04-17T19:04:16.000Z
PYTHIA8/AliPythia8/AliTPythia8.h
zwound40/AliRoot
2eeb196e31e59937df6705c3b7fca0e6da4a8cb2
[ "BSD-3-Clause" ]
5
2017-03-29T12:21:12.000Z
2018-01-15T15:52:24.000Z
#ifndef ALITPYTHIA8_H #define ALITPYTHIA8_H /* Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * See cxx source for full Copyright notice */ /* $Id$ */ //////////////////////////////////////////////////////////////////////////////// // // // TPythia8 // // // // TPythia is an interface class to C++ version of Pythia 8.1 // // event generators, written by T.Sjostrand. // //////////////////////////////////////////////////////////////////////////////// /* *------------------------------------------------------------------------------------* | | | *------------------------------------------------------------------------------* | | | | | | | | | | | PPP Y Y TTTTT H H III A Welcome to the Lund Monte Carlo! | | | | P P Y Y T H H I A A This is PYTHIA version 8.100 | | | | PPP Y T HHHHH I AAAAA Last date of change: 20 Oct 2007 | | | | P Y T H H I A A | | | | P Y T H H III A A Now is 27 Oct 2007 at 18:26:53 | | | | | | | | Main author: Torbjorn Sjostrand; CERN/PH, CH-1211 Geneva, Switzerland, | | | | and Department of Theoretical Physics, Lund University, Lund, Sweden; | | | | phone: + 41 - 22 - 767 82 27; e-mail: torbjorn@thep.lu.se | | | | Author: Stephen Mrenna; Computing Division, Simulations Group, | | | | Fermi National Accelerator Laboratory, MS 234, Batavia, IL 60510, USA; | | | | phone: + 1 - 630 - 840 - 2556; e-mail: mrenna@fnal.gov | | | | Author: Peter Skands; CERN/PH, CH-1211 Geneva, Switzerland, | | | | and Theoretical Physics Department, | | | | Fermi National Accelerator Laboratory, MS 106, Batavia, IL 60510, USA; | | | | phone: + 41 - 22 - 767 24 59; e-mail: skands@fnal.gov | | | | | | | | The main program reference is the 'Brief Introduction to PYTHIA 8.1', | | | | T. Sjostrand, S. Mrenna and P. Skands, arXiv:0710.3820 | | | | | | | | The main physics reference is the 'PYTHIA 6.4 Physics and Manual', | | | | T. Sjostrand, S. Mrenna and P. Skands, JHEP05 (2006) 026 [hep-ph/0603175]. | | | | | | | | An archive of program versions and documentation is found on the web: | | | | http://www.thep.lu.se/~torbjorn/Pythia.html | | | | | | | | This program is released under the GNU General Public Licence version 2. | | | | Please respect the MCnet Guidelines for Event Generator Authors and Users. | | | | | | | | Disclaimer: this program comes without any guarantees. | | | | Beware of errors and use common sense when interpreting results. | | | | | | | | Copyright (C) 2007 Torbjorn Sjostrand | | | | | | | | | | | *------------------------------------------------------------------------------* | | | *------------------------------------------------------------------------------------* */ #include "TGenerator.h" #include "Pythia8/Pythia.h" class TClonesArray; class TObjArray; class TH1; class AliTPythia8 : public TGenerator { public: AliTPythia8(); AliTPythia8(const char *xmlDir); virtual ~AliTPythia8(); static AliTPythia8 *Instance(); static void SetXmldocPath(char* path) {fgXmldocPath = path;} Pythia8::Pythia *Pythia8() {return fPythia;} // Interface virtual void GenerateEvent(); virtual Int_t ImportParticles(TClonesArray *particles, Option_t *option=""); virtual TObjArray *ImportParticles(Option_t *option=""); // Others void ReadString(const char* string) const; void ReadConfigFile(const char* string) const; Bool_t Initialize(Int_t idAin, Int_t idBin, Double_t ecms); void PrintStatistics() const; void EventListing() const; Int_t GetN() const; void SetPythiaSeed(UInt_t seed); void ActivateEventSuperposition(TH1 *histNcoll); Pythia8::Pythia* GetPythiaPartonLevel(); protected: AliTPythia8(const AliTPythia8&); AliTPythia8 operator=(const AliTPythia8&); static AliTPythia8 *fgInstance; //! singleton instance static char *fgXmldocPath; //! path to xmldoc Pythia8::Pythia *fPythia; //! The pythia8 instance Pythia8::Pythia *fPythiaPartonLevel; //! The pythia8 instance for the parton level object (used for superposition of events) Int_t fNumberOfParticles; //! Number of particles TH1 *fSuperPositionNcoll; //! Ncoll distribution for superposition mode Int_t fLastNMPI; //! last number of MPI Int_t fLastNSuperposition; //! last randomized superpositions void AddEvent(Pythia8::Pythia* target, Pythia8::Pythia* source); Bool_t CheckEvent(Pythia8::Event); private: void AddParticlesToPdgDataBase() const; ClassDef(AliTPythia8, 3) // Interface class of Pythia8 }; #endif
56.908333
139
0.39713
[ "object" ]
15cadac3cb752df270f89a376b1ff5bc8aa9b340
13,561
h
C
quantum/quantum_context.h
c4rlo/quantum
f68cf6369d491d3be629673cbd4feaa1d096a0e6
[ "Apache-2.0" ]
417
2018-07-16T20:16:47.000Z
2022-03-29T23:47:02.000Z
quantum/quantum_context.h
c4rlo/quantum
f68cf6369d491d3be629673cbd4feaa1d096a0e6
[ "Apache-2.0" ]
26
2018-08-06T21:50:14.000Z
2021-11-29T18:57:50.000Z
quantum/quantum_context.h
c4rlo/quantum
f68cf6369d491d3be629673cbd4feaa1d096a0e6
[ "Apache-2.0" ]
67
2018-07-12T19:43:14.000Z
2022-03-29T23:47:15.000Z
/* ** Copyright 2018 Bloomberg Finance L.P. ** ** 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. */ #ifndef BLOOMBERG_QUANTUM_CONTEXT_H #define BLOOMBERG_QUANTUM_CONTEXT_H #include <quantum/quantum_promise.h> #include <quantum/quantum_task.h> #include <quantum/quantum_io_task.h> #include <quantum/quantum_dispatcher_core.h> #include <quantum/quantum_traits.h> #include <iterator> namespace Bloomberg { namespace quantum { //============================================================================================== // class Context //============================================================================================== /// @class Context /// @brief Concrete class representing a coroutine or a thread context. /// @note For internal use only. See interfaces ICoroContext and IThreadContext for usage details. template <class RET> class Context : public IThreadContext<RET>, public ICoroContext<RET>, public ITaskAccessor, public std::enable_shared_from_this<Context<RET>> { friend struct Util; friend class Task; friend class Dispatcher; template <class OTHER_RET> friend class Context; public: using Ptr = std::shared_ptr<Context<RET>>; using ThreadCtx = IThreadContext<RET>; using CoroCtx = ICoroContext<RET>; //=================================== // D'TOR //=================================== ~Context(); //=================================== // ITERMINATE //=================================== void terminate() final; //=================================== // ITASKACCESSOR //=================================== void setTask(ITask::Ptr task) final; ITask::Ptr getTask() const final; bool isBlocked() const final; bool isSleeping(bool updateTimer = false) final; //=================================== // ICONTEXTBASE //=================================== TaskId taskId() const final; bool valid() const final; bool validAt(int num) const final; int setException(std::exception_ptr ex) final; //=================================== // ITHREADCONTEXTBASE //=================================== void waitAt(int num) const final; std::future_status waitForAt(int num, std::chrono::milliseconds timeMs) const final; void wait() const final; std::future_status waitFor(std::chrono::milliseconds timeMs) const final; void waitAll() const final; //=================================== // ITHREADCONTEXT //=================================== template <class V = RET> NonBufferRetType<V> get(); template <class V = RET> const NonBufferRetType<V>& getRef() const; template <class V, class = NonBufferType<RET,V>> int set(V&& value); template <class V, class = BufferType<RET,V>> void push(V&& value); template <class V = RET> BufferRetType<V> pull(bool& isBufferClosed); template <class OTHER_RET> NonBufferRetType<OTHER_RET> getAt(int num); template <class OTHER_RET> const NonBufferRetType<OTHER_RET>& getRefAt(int num) const; //=================================== // ICOROCONTEXTBASE //=================================== void waitAt(int num, ICoroSync::Ptr sync) const final; std::future_status waitForAt(int num, ICoroSync::Ptr sync, std::chrono::milliseconds timeMs) const final; void wait(ICoroSync::Ptr sync) const final; std::future_status waitFor(ICoroSync::Ptr sync, std::chrono::milliseconds timeMs) const final; void waitAll(ICoroSync::Ptr sync) const final; //=================================== // ICOROCONTEXT //=================================== template <class V = RET> NonBufferRetType<V> get(ICoroSync::Ptr sync); template <class V = RET> const NonBufferRetType<V>& getRef(ICoroSync::Ptr sync) const; template <class V, class = NonBufferType<RET,V>> int set(ICoroSync::Ptr sync, V&& value); template <class V, class = BufferType<RET,V>> void push(ICoroSync::Ptr sync, V&& value); template <class V = RET> BufferRetType<V> pull(ICoroSync::Ptr sync, bool& isBufferClosed); template <class OTHER_RET> NonBufferRetType<OTHER_RET> getAt(int num, ICoroSync::Ptr sync); template <class OTHER_RET> const NonBufferRetType<OTHER_RET>& getRefAt(int num, ICoroSync::Ptr sync) const; template <class OTHER_RET> NonBufferRetType<OTHER_RET> getPrev(ICoroSync::Ptr sync); template <class OTHER_RET> const NonBufferRetType<OTHER_RET>& getPrevRef(ICoroSync::Ptr sync); //=================================== // ICOROSYNC //=================================== void setYieldHandle(Traits::Yield& yield) final; Traits::Yield& getYieldHandle() final; void yield() final; std::atomic_int& signal() final; void sleep(const std::chrono::milliseconds& timeMs) final; void sleep(const std::chrono::microseconds& timeUs) final; //=================================== // MISC IMPLEMENTATIONS //=================================== template <class V = RET, class = BufferRetType<V>> int closeBuffer(); template <class V = RET, class = BufferRetType<V>> int closeBuffer(ICoroSync::Ptr sync); int getNumCoroutineThreads() const; int getNumIoThreads() const; const std::pair<int, int>& getCoroQueueIdRangeForAny() const; //=================================== // TASK CONTINUATIONS //=================================== template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr post(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr post2(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr post(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr post2(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr postFirst(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr postFirst2(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr postFirst(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr postFirst2(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr then(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr then2(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr onError(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr onError2(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr finally(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr finally2(FUNC&& func, ARGS&&... args); Ptr end(); //=================================== // BLOCKING IO //=================================== template <class OTHER_RET, class FUNC, class ... ARGS> CoroFuturePtr<OTHER_RET> postAsyncIo(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> CoroFuturePtr<OTHER_RET> postAsyncIo2(FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> CoroFuturePtr<OTHER_RET> postAsyncIo(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> CoroFuturePtr<OTHER_RET> postAsyncIo2(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); //=================================== // FOR EACH //=================================== template <class OTHER_RET, class INPUT_IT, class FUNC, class = Traits::IsInputIterator<INPUT_IT>> typename Context<std::vector<OTHER_RET>>::Ptr forEach(INPUT_IT first, INPUT_IT last, FUNC&& func); template <class OTHER_RET, class INPUT_IT, class FUNC> typename Context<std::vector<OTHER_RET>>::Ptr forEach(INPUT_IT first, size_t num, FUNC&& func); template <class OTHER_RET, class INPUT_IT, class FUNC, class = Traits::IsInputIterator<INPUT_IT>> typename Context<std::vector<std::vector<OTHER_RET>>>::Ptr forEachBatch(INPUT_IT first, INPUT_IT last, FUNC&& func); template <class OTHER_RET, class INPUT_IT, class FUNC> typename Context<std::vector<std::vector<OTHER_RET>>>::Ptr forEachBatch(INPUT_IT first, size_t num, FUNC&& func); //=================================== // MAP REDUCE //=================================== template <class KEY, class MAPPED_TYPE, class REDUCED_TYPE, class INPUT_IT, class = Traits::IsInputIterator<INPUT_IT>> typename Context<std::map<KEY, REDUCED_TYPE>>::Ptr mapReduce(INPUT_IT first, INPUT_IT last, Functions::MapFunc<KEY, MAPPED_TYPE, INPUT_IT> mapper, Functions::ReduceFunc<KEY, MAPPED_TYPE, REDUCED_TYPE> reducer); template <class KEY, class MAPPED_TYPE, class REDUCED_TYPE, class INPUT_IT> typename Context<std::map<KEY, REDUCED_TYPE>>::Ptr mapReduce(INPUT_IT first, size_t num, Functions::MapFunc<KEY, MAPPED_TYPE, INPUT_IT> mapper, Functions::ReduceFunc<KEY, MAPPED_TYPE, REDUCED_TYPE> reducer); template <class KEY, class MAPPED_TYPE, class REDUCED_TYPE, class INPUT_IT, class = Traits::IsInputIterator<INPUT_IT>> typename Context<std::map<KEY, REDUCED_TYPE>>::Ptr mapReduceBatch(INPUT_IT first, INPUT_IT last, Functions::MapFunc<KEY, MAPPED_TYPE, INPUT_IT> mapper, Functions::ReduceFunc<KEY, MAPPED_TYPE, REDUCED_TYPE> reducer); template <class KEY, class MAPPED_TYPE, class REDUCED_TYPE, class INPUT_IT> typename Context<std::map<KEY, REDUCED_TYPE>>::Ptr mapReduceBatch(INPUT_IT first, size_t num, Functions::MapFunc<KEY, MAPPED_TYPE, INPUT_IT> mapper, Functions::ReduceFunc<KEY, MAPPED_TYPE, REDUCED_TYPE> reducer); //=================================== // NEW / DELETE //=================================== static void* operator new(size_t size); static void operator delete(void* p); static void deleter(Context<RET>* p); private: explicit Context(DispatcherCore& dispatcher); template <class OTHER_RET> Context(Context<OTHER_RET>& other); Context(IContextBase& other); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr thenImpl(ITask::Type type, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> typename Context<OTHER_RET>::Ptr postImpl(int queueId, bool isHighPriority, ITask::Type type, FUNC&& func, ARGS&&... args); template <class OTHER_RET, class FUNC, class ... ARGS> CoroFuturePtr<OTHER_RET> postAsyncIoImpl(int queueId, bool isHighPriority, FUNC&& func, ARGS&&... args); int index(int num) const; void validateTaskType(ITask::Type type) const; //throws void validateContext(ICoroSync::Ptr sync) const; //throws //Members ITask::Ptr _task; std::vector<IPromiseBase::Ptr> _promises; DispatcherCore* _dispatcher; std::atomic_bool _terminated; std::atomic_int _signal; Traits::Yield* _yield; std::chrono::microseconds _sleepDuration; std::chrono::steady_clock::time_point _sleepTimestamp; }; template <class RET> using ContextPtr = typename Context<RET>::Ptr; }} #include <quantum/interface/quantum_icontext.h> #include <quantum/impl/quantum_context_impl.h> #endif //BLOOMBERG_QUANTUM_CONTEXT_H
38.416431
109
0.582774
[ "vector" ]
15cbabc3d76c6caaee68d2190554b5bf12f02131
10,352
h
C
src/timer.h
cartoonist/gcsa-locate
1cc6ba3762a42229926091fdd2f7fcee046dcc88
[ "MIT" ]
null
null
null
src/timer.h
cartoonist/gcsa-locate
1cc6ba3762a42229926091fdd2f7fcee046dcc88
[ "MIT" ]
null
null
null
src/timer.h
cartoonist/gcsa-locate
1cc6ba3762a42229926091fdd2f7fcee046dcc88
[ "MIT" ]
null
null
null
/** * @file timer.h * @brief Timer class. * * Timer class to measure running time. * * @author Ali Ghaffaari (\@cartoonist), <ali.ghaffaari@mpi-inf.mpg.de> * * @internal * Created: Sun Oct 15, 2017 22:55 * Organization: Max-Planck-Institut fuer Informatik * Copyright: Copyright (c) 2017, Ali Ghaffaari * * This source code is released under the terms of the MIT License. * See LICENSE file for more information. */ #ifndef TIMER_H__ #define TIMER_H__ #include <chrono> #include <unordered_map> template< typename TSpec > class TimerTraits; typedef clock_t CpuClock; typedef std::chrono::steady_clock SteadyClock; template< > class TimerTraits< std::chrono::steady_clock > { public: /* ==================== MEMBER TYPES ======================================= */ typedef std::chrono::steady_clock clock_type; typedef std::chrono::microseconds duration_type; typedef duration_type::rep rep_type; /* ==================== DATA MEMBERS ======================================= */ constexpr static const char* unit_repr = "us"; constexpr static const duration_type zero_duration = std::chrono::duration_cast< duration_type >( clock_type::duration::zero() ); constexpr static const rep_type zero_duration_rep = TimerTraits::zero_duration.count(); /* ==================== METHODS ======================================= */ static inline duration_type duration( clock_type::time_point end, clock_type::time_point start ) { return std::chrono::duration_cast< duration_type >( end - start ); } static inline rep_type duration_rep( clock_type::time_point end, clock_type::time_point start ) { return TimerTraits::duration( end, start ).count(); } static inline std::string duration_str( clock_type::time_point end, clock_type::time_point start ) { return std::to_string( TimerTraits::duration_rep( end, start ) ) + " " + TimerTraits::unit_repr; } }; template< > class TimerTraits< clock_t > { public: /* ==================== MEMBER TYPES ======================================= */ typedef struct { typedef clock_t time_point; static inline time_point now() { return clock(); } } clock_type; typedef float duration_type; typedef duration_type rep_type; /* ==================== DATA MEMBERS ======================================= */ constexpr static const char* unit_repr = "s"; constexpr static const duration_type zero_duration = 0; constexpr static const rep_type zero_duration_rep = 0; /* ==================== METHODS ======================================= */ static inline duration_type duration( clock_type::time_point end, clock_type::time_point start ) { return static_cast< float >( end - start ) / CLOCKS_PER_SEC; } static inline rep_type duration_rep( clock_type::time_point end, clock_type::time_point start ) { return TimerTraits::duration( end, start ); } static inline std::string duration_str( clock_type::time_point end, clock_type::time_point start ) { return std::to_string( TimerTraits::duration_rep( end, start ) ) + " " + TimerTraits::unit_repr; } }; /** * @brief Timers for measuring execution time. * * Measure the time period between its instantiation and destruction. The timers are * kept in static table hashed by the timer name. */ template< typename TClock=clock_t > class Timer { public: /* ==================== MEMBER TYPES ======================================= */ typedef TimerTraits< TClock > trait_type; typedef typename trait_type::clock_type clock_type; typedef typename trait_type::duration_type duration_type; typedef typename trait_type::rep_type rep_type; struct TimePeriod { typename clock_type::time_point start; typename clock_type::time_point end; }; /* ==================== STATIC DATA ======================================= */ constexpr static const char* unit_repr = trait_type::unit_repr; constexpr static const duration_type zero_duration = trait_type::zero_duration; constexpr static const rep_type zero_duration_rep = trait_type::zero_duration_rep; /* ==================== LIFECYCLE ======================================= */ /** * @brief Timer constructor. * * @param name The name of the timer to start. * * If timer does not exist it will be created. */ Timer( const std::string& name ) { this->timer_name = name; get_timers()[ this->timer_name ].start = clock_type::now(); } /* ----- end of method Timer (constructor) ----- */ /** * @brief Timer destructor. * * Stop the timer as the Timer object dies. */ ~Timer() { get_timers()[ this->timer_name ].end = clock_type::now(); } /* ----- end of method ~Timer (destructor) ----- */ /* ==================== METHODS ======================================= */ /** * @brief static getter function for static timers. */ static inline std::unordered_map< std::string, TimePeriod >& get_timers( ) { static std::unordered_map< std::string, TimePeriod > timers; return timers; } /* ----- end of method get_timers ----- */ /** * @brief Get the timer duration by name. * * @param name The name of the timer to start. * @return the duration represented by requested timer. * * Get the duration represented by the timer. */ static inline duration_type get_duration( const std::string& name ) { return trait_type::duration( get_timers()[ name ].end, get_timers()[ name ].start ); } /* ----- end of method get_duration ----- */ /** * @brief Get the timer duration (arithmetic representation) by name. * * @param name The name of the timer to start. * @return arithmetic representation of the requested timer duration. * * Get the arithmetic representation of the requested timer duration. */ static inline rep_type get_duration_rep( const std::string& name ) { return trait_type::duration_rep( get_timers()[ name ].end, get_timers()[ name ].start ); } /* ----- end of method get_duration ----- */ /** * @brief Get the timer duration (string representation) by name. * * @param name The name of the timer to start. * @return string representation of the requested timer duration. * * Get the string representation of the requested timer duration. */ static inline std::string get_duration_str( const std::string& name ) { return trait_type::duration_str( get_timers()[ name ].end, get_timers()[ name ].start ); } /* ----- end of method get_duration ----- */ /** * @brief Get time lap for an ongoing timer. * * @param name The name of the timer. * @return the duration since 'start' to 'now' if the timer is not finished; * otherwise it returns the duration of the timer by calling method * `get_duration`. * * It first checks if the timer specified by its `name` is finished or not. If * so, it return the duration by calling `get_duration` method. Otherwise, it * returns the duration between start time to 'now'. */ static inline duration_type get_lap( const std::string& name ) { if ( get_timers()[ name ].end > get_timers()[ name ].start ) { return get_duration( name ); } return trait_type::duration( clock_type::now(), get_timers()[ name ].start ); } /* ----- end of method get_lap ----- */ /** * @brief Get time lap for an ongoing timer. * * @param name The name of the timer. * @return the duration since 'start' to 'now' if the timer is not finished; * otherwise it returns the duration of the timer by calling method * `get_duration`. * * It first checks if the timer specified by its `name` is finished or not. If * so, it return the duration by calling `get_duration` method. Otherwise, it * returns the duration between start time to 'now'. */ static inline rep_type get_lap_rep( const std::string& name ) { if ( get_timers()[ name ].end > get_timers()[ name ].start ) { return get_duration_rep( name ); } return trait_type::duration_rep( clock_type::now(), get_timers()[ name ].start ); } /* ----- end of method get_lap ----- */ /** * @brief Get time lap for an ongoing timer. * * @param name The name of the timer. * @return the duration since 'start' to 'now' if the timer is not finished; * otherwise it returns the duration of the timer by calling method * `get_duration`. * * It first checks if the timer specified by its `name` is finished or not. If * so, it return the duration by calling `get_duration` method. Otherwise, it * returns the duration between start time to 'now'. */ static inline std::string get_lap_str( const std::string& name ) { if ( get_timers()[ name ].end > get_timers()[ name ].start ) { return get_duration_str( name ); } return trait_type::duration_str( clock_type::now(), get_timers()[ name ].start ); } /* ----- end of method get_lap ----- */ protected: /* ==================== DATA MEMBERS ======================================= */ std::string timer_name; /**< @brief The timer name of the current instance. */ }; /* ----- end of class Timer ----- */ #endif // end of TIMER_H__
37.643636
89
0.558153
[ "object" ]
15cf6a60cab629d9712fcffbbb0b50d4cc05d4d8
10,536
h
C
trunk/win/Source/Includes/QtIncludes/src/xmlpatterns/data/qatomiccomparators_p.h
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
trunk/win/Source/Includes/QtIncludes/src/xmlpatterns/data/qatomiccomparators_p.h
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
24
2016-11-07T04:59:49.000Z
2022-03-14T06:34:12.000Z
trunk/win/Source/Includes/QtIncludes/src/xmlpatterns/data/qatomiccomparators_p.h
dyzmapl/BumpTop
1329ea41411c7368516b942d19add694af3d602f
[ "Apache-2.0" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
/**************************************************************************** ** ** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies). ** All rights reserved. ** Contact: Nokia Corporation (qt-info@nokia.com) ** ** This file is part of the QtXmlPatterns module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL$ ** GNU Lesser General Public License Usage ** This file may be used under the terms of the GNU Lesser General Public ** License version 2.1 as published by the Free Software Foundation and ** appearing in the file LICENSE.LGPL included in the packaging of this ** file. Please review the following information to ensure the GNU Lesser ** General Public License version 2.1 requirements will be met: ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Nokia gives you certain additional ** rights. These rights are described in the Nokia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** GNU General Public License Usage ** Alternatively, this file may be used under the terms of the GNU General ** Public License version 3.0 as published by the Free Software Foundation ** and appearing in the file LICENSE.GPL included in the packaging of this ** file. Please review the following information to ensure the GNU General ** Public License version 3.0 requirements will be met: ** http://www.gnu.org/copyleft/gpl.html. ** ** Other Usage ** Alternatively, this file may be used in accordance with the terms and ** conditions contained in a signed written agreement between you and Nokia. ** ** ** ** ** ** $QT_END_LICENSE$ ** ****************************************************************************/ // // W A R N I N G // ------------- // // This file is not part of the Qt API. It exists purely as an // implementation detail. This header file may change from version to // version without notice, or even be removed. // // We mean it. #ifndef Patternist_AtomicComparators_H #define Patternist_AtomicComparators_H #include "qabstractfloat_p.h" #include "qatomiccomparator_p.h" #include "qprimitives_p.h" /** * @file * @short Contains all the classes implementing comparisons between atomic values. */ QT_BEGIN_HEADER QT_BEGIN_NAMESPACE namespace QPatternist { /** * @short Performs case @em sensitive string comparison * between @c xs:anyUri, @c xs:string, and @c xs:untypedAtomic. * * @ingroup Patternist_xdm * @author Frans Englich <frans.englich@nokia.com> */ class StringComparator : public AtomicComparator { public: /** * Compares two strings, and returns the appropriate AtomicComparator::ComparisonResult enum. This * is a bit simplified version of string comparison as defined in the XPath specifications, * since this does not take any string collations into account(which an implementation neither * is required to do). * * @see <a href="http://www.w3.org/TR/xpath-functions/#string-compare">XQuery 1.0 and XPath * 2.0 Functions and Operators, 7.3 ValueComparison::Equality and Comparison of Strings</a> */ virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; /** * Compares two strings, and returns @c true if they are considered equal as per * an ordinary string comparison. In other words, this is an implementation with * the Unicode code point collation. * * @see <a href="http://www.w3.org/TR/xpath-functions/#string-compare">XQuery 1.0 and XPath * 2.0 Functions and Operators, 7.3 ValueComparison::Equality and Comparison of Strings</a> */ virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Performs case @em insensitive string comparison * between @c xs:anyUri, @c xs:string, and @c xs:untypedAtomic. * * @ingroup Patternist_xdm * @author Frans Englich <frans.englich@nokia.com> */ class CaseInsensitiveStringComparator : public AtomicComparator { public: /** * Converts both string values to upper case and afterwards compare them. */ virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; /** * Converts both string values case insensitively. */ virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares @c xs:base64Binary and @c xs:hexBinary values. * * @author Frans Englich <frans.englich@nokia.com> */ class BinaryDataComparator : public AtomicComparator { public: virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares @c xs:boolean values. * * This is done via the object's Boolean::evaluteEBV() function. * * @author Frans Englich <frans.englich@nokia.com> */ class BooleanComparator : public AtomicComparator { public: virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares @c xs:double values. * * @todo Add docs about numeric promotion * * @author Frans Englich <frans.englich@nokia.com> */ class AbstractFloatComparator : public AtomicComparator { public: virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares @c xs:double values for the purpose of sorting. * * @todo Add docs about numeric promotion * * @author Frans Englich <frans.englich@nokia.com> */ template<const AtomicComparator::Operator t_op> class AbstractFloatSortComparator : public AbstractFloatComparator { public: virtual ComparisonResult compare(const Item &o1, const AtomicComparator::Operator op, const Item &o2) const { Q_ASSERT_X(t_op == OperatorLessThanNaNLeast || t_op == OperatorLessThanNaNGreatest, Q_FUNC_INFO, "Can only be instantiated with those two."); Q_ASSERT(op == t_op); Q_UNUSED(op); /* Needed when building in release mode. */ const xsDouble v1 = o1.template as<Numeric>()->toDouble(); const xsDouble v2 = o2.template as<Numeric>()->toDouble(); if(qIsNaN(v1) && !qIsNaN(v2)) return t_op == OperatorLessThanNaNLeast ? LessThan : GreaterThan; if(!qIsNaN(v1) && qIsNaN(v2)) return t_op == OperatorLessThanNaNLeast ? GreaterThan : LessThan; if(Double::isEqual(v1, v2)) return Equal; else if(v1 < v2) return LessThan; else return GreaterThan; } }; /** * @short Compares @c xs:decimal values. * * @author Frans Englich <frans.englich@nokia.com> */ class DecimalComparator : public AtomicComparator { public: virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares @c xs:integer values. * * @author Frans Englich <frans.englich@nokia.com> */ class IntegerComparator : public AtomicComparator { public: virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares @c xs:QName values. * * @author Frans Englich <frans.englich@nokia.com> */ class QNameComparator : public AtomicComparator { public: virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares sub-classes of AbstractDateTime. * * @author Frans Englich <frans.englich@nokia.com> */ class AbstractDateTimeComparator : public AtomicComparator { public: virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; virtual bool equals(const Item &op1, const Item &op2) const; }; /** * @short Compares sub-classes of AbstractDuration. * * @author Frans Englich <frans.englich@nokia.com> */ class AbstractDurationComparator : public AtomicComparator { public: virtual ComparisonResult compare(const Item &op1, const AtomicComparator::Operator op, const Item &op2) const; virtual bool equals(const Item &op1, const Item &op2) const; private: static inline QDateTime addDurationToDateTime(const QDateTime &dateTime, const AbstractDuration *const duration); }; } QT_END_NAMESPACE QT_END_HEADER #endif
35.237458
109
0.566629
[ "object" ]
15d4c1eb971997569d453c1e5f87a00d35f849ff
5,649
h
C
btas/generic/swap.h
BTAS/BTAS
bddd55080447dd19eacf9a374e312a7bc2fd06e2
[ "BSD-3-Clause" ]
22
2015-02-20T21:14:15.000Z
2020-09-29T13:04:01.000Z
btas/generic/swap.h
BTAS/BTAS
bddd55080447dd19eacf9a374e312a7bc2fd06e2
[ "BSD-3-Clause" ]
20
2015-01-10T19:58:34.000Z
2020-12-07T19:54:47.000Z
btas/generic/swap.h
BTAS/BTAS
bddd55080447dd19eacf9a374e312a7bc2fd06e2
[ "BSD-3-Clause" ]
12
2015-01-09T22:23:06.000Z
2020-08-28T21:19:36.000Z
#ifndef BTAS_SWAP_H #define BTAS_SWAP_H #ifdef BTAS_HAS_INTEL_MKL #include <vector> #include <mkl_trans.h> #include <btas/error.h> #include <btas/range_traits.h> //***IMPORTANT***// // do not use swap to first then use swap to back // swap to first preserves order while swap to back does not // If you use swap to first, to undo the transpositions // make is_in_front = true and same goes for swap to back // do not mix swap to first and swap to back namespace btas { /// Swaps the nth mode of an Nth order tensor to the front preserving the /// order of the other modes. \n /// swap_to_first(A, I3, false, false) = /// A(I1, I2, I3, I4, I5) --> A(I3, I1, I2, I4, I5) /// \param[in, out] A In: An order-N tensor. Out: the order-N tensor with mode \c mode permuted. /// \param[in] mode The mode of \c A one wishes to permute to the front. /// \param[in] is_in_front \c Mode of \c A has already been permuted to the /// front. Default = false. \param[in] for_ALS_update Different indexing is /// required for the ALS, if making a general swap this should be false. template<typename Tensor> void swap_to_first(Tensor &A, size_t mode, bool is_in_front = false, bool for_ALS_update = true) { using ind_t = typename Tensor::range_type::index_type::value_type; using ord_t = typename range_traits<typename Tensor::range_type>::ordinal_type; auto ndim = A.rank(); // If the mode of interest is the the first mode you are done. if (mode > ndim) { BTAS_EXCEPTION("Mode index is greater than tensor rank"); } if (mode == 0) return; // Build the resize vector for reference tensor to update dimensions std::vector<ind_t> aug_dims; ord_t size = A.range().area(); for (size_t i = 0; i < ndim; i++) { aug_dims.push_back(A.extent(i)); } // Special indexing for ALS update if (for_ALS_update) { auto temp = aug_dims[0]; aug_dims[0] = aug_dims[mode]; aug_dims[mode] = temp; } // Order preserving swap of indices. else { auto temp = (is_in_front) ? aug_dims[0] : aug_dims[mode]; auto erase = (is_in_front) ? aug_dims.begin() : aug_dims.begin() + mode; auto begin = (is_in_front) ? aug_dims.begin() + mode : aug_dims.begin(); aug_dims.erase(erase); aug_dims.insert(begin, temp); } ord_t rows = 1; ord_t cols = 1; ind_t step = 1; // The last mode is an easier swap, make all dimensions before last, row // dimension Last dimension is column dimension, then permute. if (mode == ndim - 1) { rows = (is_in_front) ? A.extent(0) : size / A.extent(mode); cols = (is_in_front) ? size / A.extent(0) : A.extent(mode); double *data_ptr = A.data(); mkl_dimatcopy('R', 'T', rows, cols, 1.0, data_ptr, cols, rows); } // All other dimension not so easy all indices up to mode of interest row // dimension all othrs column dimension, then swap. After swapping, there are // row dimension many smaller tensors of size column dimension do row // dimension many swaps with inner row dimension = between the outer row // dimension and the last dimension and inner col dimension = last dimension, // now the mode of interest. Swapping the rows and columns back at the end // will preserve order of the dimensions. else { for (size_t i = 0; i <= mode; i++) rows *= A.extent(i); cols = size / rows; double *data_ptr = A.data(); mkl_dimatcopy('R', 'T', rows, cols, 1.0, data_ptr, cols, rows); step = rows; ind_t in_rows = (is_in_front) ? A.extent(0) : rows / A.extent(mode); ind_t in_cols = (is_in_front) ? rows / A.extent(0) : A.extent(mode); for (ind_t i = 0; i < cols; i++) { data_ptr = A.data() + i * step; mkl_dimatcopy('R', 'T', in_rows, in_cols, 1.0, data_ptr, in_cols, in_rows); } data_ptr = A.data(); mkl_dimatcopy('R', 'T', cols, rows, 1.0, data_ptr, rows, cols); } A.resize(aug_dims); } /// Swaps the nth order of an Nth order tensor to the end. /// Does not preserve order.\n /// swap_to_back(T, I2, false) = /// T(I1, I2, I3) --> T(I3, I1, I2) /// \param[in, out] A In: An order-N tensor. Out: the order-N tensor with mode \c mode permuted. /// \param[in] mode The mode of \c A one wishes to permute to the back. /// \param[in] is_in_back \c Mode of \c A has already been permuted to the /// back. Default = false. template<typename Tensor> void swap_to_back(Tensor &A, size_t mode, bool is_in_back = false) { using ind_t = typename Tensor::range_type::index_type::value_type; using ord_t = typename range_traits<typename Tensor::range_type>::ordinal_type; auto ndim = A.rank(); if (mode > ndim) BTAS_EXCEPTION_MESSAGE(__FILE__, __LINE__, "mode > A.rank(), mode out of range"); if (mode == ndim - 1) return; ord_t rows = 1; ord_t cols = 1; // counts the modes up to and including the mode of interest, these are stored // in rows counts all the modes beyond the mode of interest, these are stored // as columns auto midpoint = (is_in_back) ? ndim - 1 - mode : mode + 1; std::vector<ind_t> aug_dims; for (size_t i = midpoint; i < ndim; i++) { aug_dims.push_back(A.extent(i)); cols *= A.extent(i); } for (size_t i = 0; i < midpoint; i++) { aug_dims.push_back(A.extent(i)); rows *= A.extent(i); } // Permutes the rows and columns double *data_ptr = A.data(); mkl_dimatcopy('R', 'T', rows, cols, 1.0, data_ptr, cols, rows); // resized to the new correct order. A.resize(aug_dims); return; } } // namespace btas #endif //BTAS_HAS_INTEL_MKL #endif // BTAS_SWAP_H
34.03012
97
0.648433
[ "vector" ]
15d4d5dcb0a0100005f5db6633f299003a47fc5d
4,139
h
C
LibGraphics/Wm4Graphics.h
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
3
2021-08-02T04:03:03.000Z
2022-01-04T07:31:20.000Z
LibGraphics/Wm4Graphics.h
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
null
null
null
LibGraphics/Wm4Graphics.h
wjezxujian/WildMagic4
249a17f8c447cf57c6283408e01009039810206a
[ "BSL-1.0" ]
5
2019-10-13T02:44:19.000Z
2021-08-02T04:03:10.000Z
// Geometric Tools, Inc. // http://www.geometrictools.com // Copyright (c) 1998-2006. All Rights Reserved // // The Wild Magic Version 4 Restricted Libraries source code is supplied // under the terms of the license agreement // http://www.geometrictools.com/License/Wm4RestrictedLicense.pdf // and may not be copied or disclosed except in accordance with the terms // of that agreement. #ifndef WM4GRAPHICSPCH_H #define WM4GRAPHICSPCH_H // collision #include "Wm4BoundingVolumeTree.h" #include "Wm4BoxBVTree.h" #include "Wm4CollisionGroup.h" #include "Wm4CollisionRecord.h" #include "Wm4SphereBVTree.h" // controllers #include "Wm4Controller.h" #include "Wm4IKController.h" #include "Wm4IKGoal.h" #include "Wm4IKJoint.h" #include "Wm4KeyframeController.h" #include "Wm4MorphController.h" #include "Wm4ParticleController.h" #include "Wm4PointController.h" #include "Wm4SkinController.h" // curves #include "Wm4CurveMesh.h" #include "Wm4CurveSegment.h" // details #include "Wm4BillboardNode.h" #include "Wm4ClodMesh.h" #include "Wm4CollapseRecord.h" #include "Wm4CreateClodMesh.h" #include "Wm4DlodNode.h" #include "Wm4SwitchNode.h" // effects #include "Wm4DefaultShaderEffect.h" #include "Wm4Effect.h" #include "Wm4LightingEffect.h" #include "Wm4MaterialEffect.h" #include "Wm4MaterialTextureEffect.h" #include "Wm4MultitextureEffect.h" #include "Wm4PlanarReflectionEffect.h" #include "Wm4PlanarShadowEffect.h" #include "Wm4TextureEffect.h" #include "Wm4VertexColor3Effect.h" #include "Wm4VertexColor4Effect.h" // object system #include "Wm4ImageVersion.h" #include "Wm4Main.h" #include "Wm4Object.h" #include "Wm4Rtti.h" #include "Wm4SmartPointer.h" #include "Wm4Stream.h" #include "Wm4StreamVersion.h" #include "Wm4StringTree.h" // rendering #include "Wm4AlphaState.h" #include "Wm4Bindable.h" #include "Wm4Camera.h" #include "Wm4CullState.h" #include "Wm4FrameBuffer.h" #include "Wm4GlobalState.h" #include "Wm4Image.h" #include "Wm4Light.h" #include "Wm4MaterialState.h" #include "Wm4PolygonOffsetState.h" #include "Wm4Renderer.h" #include "Wm4StencilState.h" #include "Wm4Texture.h" #include "Wm4WireframeState.h" #include "Wm4ZBufferState.h" // scene graph #include "Wm4BoundingVolume.h" #include "Wm4BoxBV.h" #include "Wm4CameraNode.h" #include "Wm4Culler.h" #include "Wm4Geometry.h" #include "Wm4LightNode.h" #include "Wm4Node.h" #include "Wm4Particles.h" #include "Wm4Polyline.h" #include "Wm4Polypoint.h" #include "Wm4Spatial.h" #include "Wm4SphereBV.h" #include "Wm4StandardMesh.h" #include "Wm4Transformation.h" #include "Wm4TriMesh.h" #include "Wm4VisibleObject.h" #include "Wm4VisibleSet.h" // shaders #include "Wm4Attributes.h" #include "Wm4ImageCatalog.h" #include "Wm4IndexBuffer.h" #include "Wm4NumericalConstant.h" #include "Wm4PixelProgram.h" #include "Wm4PixelProgramCatalog.h" #include "Wm4PixelShader.h" #include "Wm4Program.h" #include "Wm4RendererConstant.h" #include "Wm4SamplerInformation.h" #include "Wm4Shader.h" #include "Wm4ShaderEffect.h" #include "Wm4UserConstant.h" #include "Wm4VertexBuffer.h" #include "Wm4VertexProgram.h" #include "Wm4VertexProgramCatalog.h" #include "Wm4VertexShader.h" // shared arrays #include "Wm4ColorRGBAArray.h" #include "Wm4ColorRGBArray.h" #include "Wm4DoubleArray.h" #include "Wm4FloatArray.h" #include "Wm4IntArray.h" #include "Wm4Matrix2Array.h" #include "Wm4Matrix3Array.h" #include "Wm4Matrix4Array.h" #include "Wm4Plane3Array.h" #include "Wm4QuaternionArray.h" #include "Wm4TSharedArray.h" #include "Wm4Vector2Array.h" #include "Wm4Vector3Array.h" #include "Wm4Vector4Array.h" // sorting #include "Wm4BspNode.h" #include "Wm4ConvexRegion.h" #include "Wm4ConvexRegionManager.h" #include "Wm4CRMCuller.h" #include "Wm4Portal.h" // surfaces #include "Wm4BoxSurface.h" #include "Wm4BSplineSurfacePatch.h" #include "Wm4RectangleSurface.h" #include "Wm4RevolutionSurface.h" #include "Wm4SurfaceMesh.h" #include "Wm4SurfacePatch.h" #include "Wm4TubeSurface.h" // terrain #include "Wm4ClodTerrain.h" #include "Wm4ClodTerrainBlock.h" #include "Wm4ClodTerrainPage.h" #include "Wm4ClodTerrainVertex.h" #include "Wm4Terrain.h" #include "Wm4TerrainPage.h" #endif
25.392638
73
0.780865
[ "object" ]
e9f3b9a3c358e792acf47fde8ff4a6231ce0baf4
3,812
h
C
tools/EtherExtractor/include/rlp.h
amany9000/EtherBeat
7a591ead81e8a312ad637cb3c0ed908220a3c74b
[ "Apache-2.0" ]
58
2017-11-28T17:13:07.000Z
2022-03-11T07:32:58.000Z
tools/EtherExtractor/include/rlp.h
amany9000/EtherBeat
7a591ead81e8a312ad637cb3c0ed908220a3c74b
[ "Apache-2.0" ]
12
2017-05-24T07:54:57.000Z
2020-03-07T08:10:49.000Z
tools/EtherExtractor/include/rlp.h
amany9000/EtherBeat
7a591ead81e8a312ad637cb3c0ed908220a3c74b
[ "Apache-2.0" ]
89
2017-05-06T15:52:38.000Z
2021-02-22T11:41:31.000Z
/* * Adapted from PA193_test_parser_Ethereum on 5/19/18. */ #ifndef TOOLS_ETHEREXTRACTOR_INCLUDE_RLP_H_ #define TOOLS_ETHEREXTRACTOR_INCLUDE_RLP_H_ #include <cstdint> #include <exception> #include <vector> /** * Used for serializing data fields using the Recursive length prefix algorithm */ struct RLPField { std::vector<std::uint8_t> bytes; /** vector of bytes to be serialized */ bool isSerialized; /** indicates whether the vector of bytes represents already serialized data */ }; /** * Provides layout of data serialized using the Recursive length prefix algorithm */ class RLP { const std::vector<std::uint8_t> &_contents; std::size_t _prefixOff; std::size_t _dataOff; std::size_t _totalLen; std::size_t _dataLen; std::vector<RLP> _items; public: /** * RLP constructor * Creates RLP object representing the layout of fields in the serialized data * @param contents byte vector of data serialized using RLP */ explicit RLP(const std::vector<std::uint8_t> &contents); /** * RLP constructor * Creates RLP representing the layout of fields in the serialized data * @param contents byte vector of serialized data * @param offest offset to the serialized data * @param maxLength maximum length of the serialized data */ RLP(const std::vector<std::uint8_t> &contents, std::size_t offset, std::size_t maxLength); /** * @return the length of the data field, including its prefix */ std::size_t totalLength() const { return _totalLen; } /** * @return the length of the data field, excluding its prefix */ std::size_t dataLength() const { return _dataLen; } /** * Accesses a nested serialized item layout * @param index index of the serialized item * @return RLP object representing the layout of a nested item */ const RLP &operator[](unsigned int index) const { return _items[index]; } /** * Accesses a nested serialized item layout with boundary checking * @param index index of the serialized item * @return RLP object representing the layout of a nested item */ const RLP &at(unsigned int index) const { return _items.at(index); } /** * Returns the number of nested items * @return the number of nested items */ unsigned int numItems() const { return _items.size(); } /** * Offset to the data field in the underlying byte vector * @return offset */ std::size_t dataOffset() const { return _dataOff; } /** * Offset to the prefix of the data field in the underlying vector * @return offset */ std::size_t prefixOffset() const { return _prefixOff; } /** * Serialize data items using the RLP algorithm * @param dataFields vector data fields to be serialized * @return byte vector of serialized data */ static std::vector<std::uint8_t> serialize( const std::vector<RLPField> &dataFields); /** * Get RLP encoded data * @return RLP encoded data */ std::vector<std::uint8_t> serializedData() const { int start = prefixOffset(); return std::vector<uint8_t>(_contents.begin() + start, _contents.begin() + start + totalLength()); } private: void parseDataLength(std::size_t dataLengthSize); void parseItems(); }; /** Indicates error in parsing serialized data */ class BadRLPFormat : public std::exception { public: virtual const char *what() const noexcept { return "Bad RLP format"; } }; /** * Converts a number to byte vector using big endian and the minimum number of * bytes needed to represent it. */ std::vector<std::uint8_t> numberToVector(std::size_t input); #endif // TOOLS_ETHEREXTRACTOR_INCLUDE_RLP_H_
28.661654
106
0.66999
[ "object", "vector" ]
e9f8f1a3205275fd2bbc1884ef3e90e5bace84c7
1,644
h
C
doc/legacy/libnet/p2p_socket_data.h
frstrtr/cp2pool
13a65a8c809fe559a52c6ca270b3646b38941a30
[ "MIT" ]
1
2020-02-01T12:39:08.000Z
2020-02-01T12:39:08.000Z
doc/legacy/libnet/p2p_socket_data.h
frstrtr/cpool
13a65a8c809fe559a52c6ca270b3646b38941a30
[ "MIT" ]
null
null
null
doc/legacy/libnet/p2p_socket_data.h
frstrtr/cpool
13a65a8c809fe559a52c6ca270b3646b38941a30
[ "MIT" ]
null
null
null
#pragma once #include <libcoind/data.h> #include <libp2p/socket_data.h> struct P2PWriteSocketData : public WriteSocketData { P2PWriteSocketData() : WriteSocketData() { } P2PWriteSocketData(char *_data, int32_t _len) : WriteSocketData(_data, _len) { } P2PWriteSocketData(std::shared_ptr<Message> msg) : WriteSocketData() { from_message(msg); } void from_message(std::shared_ptr<Message> msg) override { PackStream value; //command [+] auto command = new char[12]{'\0'}; memcpy(command, msg->command.c_str(), msg->command.size()); PackStream s_command(command, 12); value << s_command; delete[] command; //----- PackStream payload_stream; payload_stream << *msg; //len [+] IntType(32) unpacked_len(payload_stream.size()); value << unpacked_len; //checksum [+] PackStream payload_checksum_stream; payload_checksum_stream << *msg; auto __checksum = coind::data::hash256(payload_checksum_stream); IntType(256) checksum_full(__checksum); PackStream _packed_checksum; _packed_checksum << checksum_full; //TODO: почему результат реверснутый? vector<unsigned char> packed_checksum(_packed_checksum.data.end() - 4, _packed_checksum.data.end()); std::reverse(packed_checksum.begin(), packed_checksum.end()); PackStream checksum(packed_checksum); value << checksum; //payload [+] value << payload_stream; //result data = new char[value.size()]; memcpy(data, value.bytes(), value.size()); len = value.size(); } };
28.344828
108
0.643552
[ "vector" ]
e9f9fb06b055ea10eee2ec2f1ba0e082b147d3af
9,952
c
C
src/events.c
dixyes/parallel
453cfbf292368d595221237cdb02578f88c12211
[ "PHP-3.01" ]
null
null
null
src/events.c
dixyes/parallel
453cfbf292368d595221237cdb02578f88c12211
[ "PHP-3.01" ]
null
null
null
src/events.c
dixyes/parallel
453cfbf292368d595221237cdb02578f88c12211
[ "PHP-3.01" ]
1
2022-03-09T08:31:43.000Z
2022-03-09T08:31:43.000Z
/* +----------------------------------------------------------------------+ | parallel | +----------------------------------------------------------------------+ | Copyright (c) Joe Watkins 2019 | +----------------------------------------------------------------------+ | 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 | | license@php.net so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: krakjoe | +----------------------------------------------------------------------+ */ #ifndef HAVE_PARALLEL_EVENTS #define HAVE_PARALLEL_EVENTS #include "parallel.h" #include "poll.h" #include "loop.h" zend_class_entry* php_parallel_events_ce; zend_object_handlers php_parallel_events_handlers; static zend_object* php_parallel_events_create(zend_class_entry *type) { php_parallel_events_t *events = (php_parallel_events_t*) ecalloc(1, sizeof(php_parallel_events_t) + zend_object_properties_size(type)); zend_object_std_init(&events->std, type); events->std.handlers = &php_parallel_events_handlers; zend_hash_init( &events->targets, 32, NULL, ZVAL_PTR_DTOR, 0); events->timeout = -1; events->blocking = 1; ZVAL_UNDEF(&events->input); return &events->std; } static zend_always_inline zend_bool php_parallel_events_add(php_parallel_events_t *events, zend_string *name, zval *object, zend_string **key) { if(instanceof_function(Z_OBJCE_P(object), php_parallel_channel_ce)) { php_parallel_channel_t *channel = (php_parallel_channel_t*) php_parallel_channel_from(object); name = php_parallel_link_name(channel->link); } else { name = php_parallel_copy_string_interned(name); } *key = name; if (!zend_hash_add(&events->targets, name, object)) { return 0; } Z_ADDREF_P(object); return 1; } static zend_always_inline zend_bool php_parallel_events_remove(php_parallel_events_t *events, zend_string *name) { return zend_hash_del(&events->targets, name) == SUCCESS; } static void php_parallel_events_destroy(zend_object *zo) { php_parallel_events_t *events = php_parallel_events_fetch(zo); if (!Z_ISUNDEF(events->input)) { zval_ptr_dtor(&events->input); } zend_hash_destroy(&events->targets); zend_object_std_dtor(zo); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(php_parallel_events_set_input_arginfo, 0, 1, IS_VOID, 0) ZEND_ARG_OBJ_INFO(0, input, \\parallel\\Events\\Input, 0) ZEND_END_ARG_INFO() PHP_METHOD(Events, setInput) { php_parallel_events_t *events = php_parallel_events_from(getThis()); zval *input; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJECT_OF_CLASS(input, php_parallel_events_input_ce); ZEND_PARSE_PARAMETERS_END(); if (Z_TYPE(events->input) == IS_OBJECT) { zval_ptr_dtor(&events->input); } ZVAL_COPY(&events->input, input); } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(php_parallel_events_add_channel_arginfo, 0, 1, IS_VOID, 0) ZEND_ARG_OBJ_INFO(0, channel, \\parallel\\Channel, 0) ZEND_END_ARG_INFO() PHP_METHOD(Events, addChannel) { php_parallel_events_t *events = php_parallel_events_from(getThis()); zval *target = NULL; zend_string *key = NULL; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_OBJECT_OF_CLASS(target, php_parallel_channel_ce) ZEND_PARSE_PARAMETERS_END(); if (!php_parallel_events_add(events, NULL, target, &key)) { php_parallel_exception_ex( php_parallel_events_error_existence_ce, "target named \"%s\" already added", ZSTR_VAL(key)); } } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(php_parallel_events_add_future_arginfo, 0, 2, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, name, IS_STRING, 0) ZEND_ARG_OBJ_INFO(0, future, \\parallel\\Future, 0) ZEND_END_ARG_INFO() PHP_METHOD(Events, addFuture) { php_parallel_events_t *events = php_parallel_events_from(getThis()); zval *target = NULL; zend_string *name = NULL; zend_string *key = NULL; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_STR(name) Z_PARAM_OBJECT_OF_CLASS(target, php_parallel_future_ce) ZEND_PARSE_PARAMETERS_END(); if (!php_parallel_events_add(events, name, target, &key)) { php_parallel_exception_ex( php_parallel_events_error_existence_ce, "target named \"%s\" already added", ZSTR_VAL(key)); } } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(php_parallel_events_remove_arginfo, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, target, IS_STRING, 0) ZEND_END_ARG_INFO() PHP_METHOD(Events, remove) { php_parallel_events_t *events = php_parallel_events_from(getThis()); zend_string *target = NULL; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_STR(target) ZEND_PARSE_PARAMETERS_END(); if (!php_parallel_events_remove(events, target)) { php_parallel_exception_ex( php_parallel_events_error_existence_ce, "target named \"%s\" not found", ZSTR_VAL(target)); } } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(php_parallel_events_set_timeout_arginfo, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, timeout, IS_LONG, 0) ZEND_END_ARG_INFO() PHP_METHOD(Events, setTimeout) { php_parallel_events_t *events = php_parallel_events_from(getThis()); zend_long timeout = -1; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_LONG(timeout) ZEND_PARSE_PARAMETERS_END(); if (!events->blocking) { php_parallel_exception_ex( php_parallel_events_error_ce, "cannot set timeout on loop in non-blocking mode"); return; } events->timeout = timeout; } ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(php_parallel_events_set_blocking_arginfo, 0, 1, IS_VOID, 0) ZEND_ARG_TYPE_INFO(0, blocking, _IS_BOOL, 0) ZEND_END_ARG_INFO() PHP_METHOD(Events, setBlocking) { php_parallel_events_t *events = php_parallel_events_from(getThis()); zend_bool blocking; ZEND_PARSE_PARAMETERS_START(1, 1) Z_PARAM_BOOL(blocking) ZEND_PARSE_PARAMETERS_END(); if (events->timeout > -1) { php_parallel_exception_ex( php_parallel_events_error_ce, "cannot set blocking mode on loop with timeout"); return; } events->blocking = blocking; } ZEND_BEGIN_ARG_WITH_RETURN_OBJ_INFO_EX(php_parallel_events_poll_arginfo, 0, 0, \\parallel\\Events\\Event, 1) ZEND_END_ARG_INFO() PHP_METHOD(Events, poll) { php_parallel_events_t *events = php_parallel_events_from(getThis()); PARALLEL_PARAMETERS_NONE(return); php_parallel_events_poll(events, return_value); } #ifdef ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_TYPE_INFO_EX ZEND_BEGIN_ARG_WITH_TENTATIVE_RETURN_TYPE_INFO_EX(php_parallel_events_count_arginfo, 0, 0, IS_LONG, 0) #else ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO(php_parallel_events_count_arginfo, IS_LONG, 0) #endif ZEND_END_ARG_INFO() PHP_METHOD(Events, count) { php_parallel_events_t *events = php_parallel_events_from(getThis()); PARALLEL_PARAMETERS_NONE(return); RETURN_LONG(zend_hash_num_elements(&events->targets)); } zend_function_entry php_parallel_events_methods[] = { PHP_ME(Events, setInput, php_parallel_events_set_input_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, addChannel, php_parallel_events_add_channel_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, addFuture, php_parallel_events_add_future_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, remove, php_parallel_events_remove_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, setBlocking, php_parallel_events_set_blocking_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, setTimeout, php_parallel_events_set_timeout_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, poll, php_parallel_events_poll_arginfo, ZEND_ACC_PUBLIC) PHP_ME(Events, count, php_parallel_events_count_arginfo, ZEND_ACC_PUBLIC) PHP_FE_END }; PHP_MINIT_FUNCTION(PARALLEL_EVENTS) { zend_class_entry ce; memcpy( &php_parallel_events_handlers, php_parallel_standard_handlers(), sizeof(zend_object_handlers)); php_parallel_events_handlers.offset = XtOffsetOf(php_parallel_events_t, std); php_parallel_events_handlers.free_obj = php_parallel_events_destroy; INIT_NS_CLASS_ENTRY(ce, "parallel", "Events", php_parallel_events_methods); php_parallel_events_ce = zend_register_internal_class(&ce); php_parallel_events_ce->create_object = php_parallel_events_create; php_parallel_events_ce->get_iterator = php_parallel_events_loop_create; php_parallel_events_ce->ce_flags |= ZEND_ACC_FINAL; #ifdef ZEND_ACC_NOT_SERIALIZABLE php_parallel_events_ce->ce_flags |= ZEND_ACC_NOT_SERIALIZABLE; #else php_parallel_events_ce->serialize = zend_class_serialize_deny; php_parallel_events_ce->unserialize = zend_class_unserialize_deny; #endif zend_class_implements(php_parallel_events_ce, 1, zend_ce_countable); PHP_MINIT(PARALLEL_EVENTS_EVENT)(INIT_FUNC_ARGS_PASSTHRU); PHP_MINIT(PARALLEL_EVENTS_INPUT)(INIT_FUNC_ARGS_PASSTHRU); return SUCCESS; } PHP_MSHUTDOWN_FUNCTION(PARALLEL_EVENTS) { PHP_MSHUTDOWN(PARALLEL_EVENTS_EVENT)(INIT_FUNC_ARGS_PASSTHRU); PHP_MSHUTDOWN(PARALLEL_EVENTS_INPUT)(INIT_FUNC_ARGS_PASSTHRU); return SUCCESS; } #endif
32.844884
144
0.696041
[ "object" ]
e9fcedf8c7afdce67c69d0c77cf1544955322487
398
h
C
Overworld/Start.h
NoahKittleson/RPG-Engine
e7ce30973b5d1eed09e3d5acfd89f549c2feffd8
[ "MIT", "Unlicense" ]
4
2016-06-30T19:55:40.000Z
2020-01-10T21:03:00.000Z
Overworld/Start.h
NoahKittleson/RPG-Engine
e7ce30973b5d1eed09e3d5acfd89f549c2feffd8
[ "MIT", "Unlicense" ]
null
null
null
Overworld/Start.h
NoahKittleson/RPG-Engine
e7ce30973b5d1eed09e3d5acfd89f549c2feffd8
[ "MIT", "Unlicense" ]
null
null
null
// // StartingZone.h // Overworld // // Created by Noah Kittleson on 7/31/16. // Copyright © 2016 Noah. All rights reserved. // #pragma once #include "MapSection.h" #include "BattleState.h" class Start: public MapSection { public: Start(const ResourceHolder& resources, const std::vector<Condition>& activeConds); ~Start() { std::cout << "Start Zone deleted.\n"; } private: };
18.090909
86
0.670854
[ "vector" ]
18038bb400387181bba0a44f58e21e5e13984ebe
716
h
C
aws-cpp-sdk-application-insights/include/aws/application-insights/model/SeverityLevel.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-application-insights/include/aws/application-insights/model/SeverityLevel.h
Neusoft-Technology-Solutions/aws-sdk-cpp
88c041828b0dbee18a297c3cfe98c5ecd0706d0b
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-application-insights/include/aws/application-insights/model/SeverityLevel.h
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #pragma once #include <aws/application-insights/ApplicationInsights_EXPORTS.h> #include <aws/core/utils/memory/stl/AWSString.h> namespace Aws { namespace ApplicationInsights { namespace Model { enum class SeverityLevel { NOT_SET, Low, Medium, High }; namespace SeverityLevelMapper { AWS_APPLICATIONINSIGHTS_API SeverityLevel GetSeverityLevelForName(const Aws::String& name); AWS_APPLICATIONINSIGHTS_API Aws::String GetNameForSeverityLevel(SeverityLevel value); } // namespace SeverityLevelMapper } // namespace Model } // namespace ApplicationInsights } // namespace Aws
21.69697
91
0.769553
[ "model" ]
180a797d31aba40b96de46486d76e506309bae2b
3,432
h
C
Pods/Headers/Public/YDIMKit/YDChatBaseViewController.h
zhoushaowen/YDRongCloudChatDemo
c43cc27c0e761fca84adfc4f1f022c2bbbae84e5
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/YDIMKit/YDChatBaseViewController.h
zhoushaowen/YDRongCloudChatDemo
c43cc27c0e761fca84adfc4f1f022c2bbbae84e5
[ "Apache-2.0" ]
null
null
null
Pods/Headers/Public/YDIMKit/YDChatBaseViewController.h
zhoushaowen/YDRongCloudChatDemo
c43cc27c0e761fca84adfc4f1f022c2bbbae84e5
[ "Apache-2.0" ]
null
null
null
// // YDChatBaseViewController.h // Chat // // Created by 周少文 on 2016/10/24. // Copyright © 2016年 周少文. All rights reserved. // #import <UIKit/UIKit.h> #import "YDActionItemProtocol.h" #import "YDMessageProtocol.h" #import "YDAudioPressShortView.h" #import "YDCancelSendView.h" #import "YDRecordingView.h" typedef NS_ENUM(NSUInteger, YDChatInputStyle) { YDChatInputStyleVoice,//语音 YDChatInputStyleText,//文本 }; @interface YDChatBaseViewController : UIViewController<UITableViewDelegate,UITableViewDataSource,UITableViewDataSourcePrefetching,UIImagePickerControllerDelegate,UINavigationControllerDelegate> /** 设置初始化的消息数据 @param dataArray 消息数组 */ - (void)setInitializedDataArray:(NSArray<id<YDMessageProtocol>> *)dataArray; /** 分页加载的消息个数,默认值是15 */ @property (nonatomic) NSInteger numberOfPageCount; @property (nonatomic,strong,readonly) UITableView *chatTableView; @property (nonatomic,strong) UIColor *chatTableViewBackgroundColor; @property (nonatomic,strong) UIColor *chatToolBarBackgroundColor; @property (nonatomic,strong) UIColor *inputViewBackgroundColor; @property (nonatomic,strong,readonly) UIButton *voiceButton; @property (nonatomic,strong) UIColor *emojiSendBtnBackgroundColor; @property (nonatomic,strong,readonly) YDAudioPressShortView *audioPressShortView; @property (nonatomic,strong,readonly) YDCancelSendView *cancelSendView; @property (nonatomic,strong,readonly) YDRecordingView *recordingView; /** 设置默认的输入方式,默认一开始的输入方式是语音 */ @property (nonatomic) YDChatInputStyle defaultInputStyle; /** 默认数组中有4个item */ @property (nonatomic,strong) NSArray<id<YDActionItemProtocol>> *actionItems; /** 为某个类型的消息注册某个类型的cell @param messageClass 消息的model类型 @param cellClass 展示的cell类型 */ - (void)registerMessageClass:(Class)messageClass forCellClass:(Class)cellClass; /** 调用tableView的cellForRow方法的时候就会把数据传给这个方法 @param cell 当前的cell @param model 当前cell对应的数据模型 @param index 当前索引 */ - (void)ydConversationCell:(UITableViewCell *)cell forMessageModel:(id<YDMessageProtocol>)model atIndex:(NSInteger)index; /** 添加一条消息,内部会自动向dataArray中添加一个数据,并刷新UI @param message 消息实例 */ - (void)chatControllerAddMessage:(id<YDMessageProtocol>)message; /** 根据某个索引删除一条消息,内部会自动从dataArray中删除一个数据,并刷新UI @param index 消息的索引 */ - (void)chatControllerDeleteMessageAtIndex:(NSInteger)index; /** 删除一条消息,内部会自动从dataArray中删除一个数据,并刷新UI @param message 消息实例 */ - (void)chatControllerDeleteMessage:(id<YDMessageProtocol>)message; - (void)chatControllerDeleteMessages:(NSArray<id<YDMessageProtocol>> *)messages; - (void)chatControllerReplaceMessageWithNewMessage:(id<YDMessageProtocol>)newMessage atIndex:(NSInteger)index; - (void)chatControllerClearAllMessages; /** 开始发送文本消息 @param text 要发送到文本 */ - (void)chatControllerBeginSendText:(NSString *)text; - (void)chatControllerActionItemClick:(id<YDActionItemProtocol>)item; - (void)chatControllerDidFinishPickingImage:(UIImage *)image; /** 下拉刷新会触发此方法,子类重写此方法获取之前的消息,获取到消息之后不要忘了调用completionHandler @param completionHandler 获取完之后之后需要手动调用的block */ - (void)chatControllerBeginPullToRefreshCompletionHandler:(void(^)(NSArray<id<YDMessageProtocol>> *newMessages))completionHandler; /** 开始录音 */ - (void)chatControllerStartRecording; /** 暂停录音 */ - (void)chatControllerSuspendRecording; /** 继续录音 */ - (void)chatControllerContinueRecording; /** 取消录音 */ - (void)chatControllerCancelRecording; /** 完成录音 */ - (void)chatControllerCompleteRecording; @end
23.668966
193
0.793124
[ "model" ]
181006b43dbc69e40a1d6d5f167093074fe751b9
6,548
c
C
head/contrib/diff/lib/xmalloc.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
4
2016-08-22T22:02:55.000Z
2017-03-04T22:56:44.000Z
head/contrib/diff/lib/xmalloc.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
21
2016-08-11T09:43:43.000Z
2017-01-29T12:52:56.000Z
head/contrib/diff/lib/xmalloc.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
/* xmalloc.c -- malloc with out of memory checking Copyright (C) 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 2003, 1999, 2000, 2002, 2003 Free Software Foundation, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ #if HAVE_CONFIG_H # include <config.h> #endif #include "xalloc.h" #include <stdlib.h> #include <string.h> #include "gettext.h" #define _(msgid) gettext (msgid) #define N_(msgid) msgid #include "error.h" #include "exitfail.h" #ifndef SIZE_MAX # define SIZE_MAX ((size_t) -1) #endif #ifndef HAVE_MALLOC "you must run the autoconf test for a GNU libc compatible malloc" #endif #ifndef HAVE_REALLOC "you must run the autoconf test for a GNU libc compatible realloc" #endif /* If non NULL, call this function when memory is exhausted. */ void (*xalloc_fail_func) (void) = 0; /* If XALLOC_FAIL_FUNC is NULL, or does return, display this message before exiting when memory is exhausted. Goes through gettext. */ char const xalloc_msg_memory_exhausted[] = N_("memory exhausted"); void xalloc_die (void) { if (xalloc_fail_func) (*xalloc_fail_func) (); error (exit_failure, 0, "%s", _(xalloc_msg_memory_exhausted)); /* The `noreturn' cannot be given to error, since it may return if its first argument is 0. To help compilers understand the xalloc_die does terminate, call abort. */ abort (); } /* Allocate an array of N objects, each with S bytes of memory, dynamically, with error checking. S must be nonzero. */ static inline void * xnmalloc_inline (size_t n, size_t s) { void *p; if (xalloc_oversized (n, s) || ! (p = malloc (n * s))) xalloc_die (); return p; } void * xnmalloc (size_t n, size_t s) { return xnmalloc_inline (n, s); } /* Allocate N bytes of memory dynamically, with error checking. */ void * xmalloc (size_t n) { return xnmalloc_inline (n, 1); } /* Change the size of an allocated block of memory P to an array of N objects each of S bytes, with error checking. S must be nonzero. */ static inline void * xnrealloc_inline (void *p, size_t n, size_t s) { if (xalloc_oversized (n, s) || ! (p = realloc (p, n * s))) xalloc_die (); return p; } void * xnrealloc (void *p, size_t n, size_t s) { return xnrealloc_inline (p, n, s); } /* Change the size of an allocated block of memory P to N bytes, with error checking. */ void * xrealloc (void *p, size_t n) { return xnrealloc_inline (p, n, 1); } /* If P is null, allocate a block of at least *PN such objects; otherwise, reallocate P so that it contains more than *PN objects each of S bytes. *PN must be nonzero unless P is null, and S must be nonzero. Set *PN to the new number of objects, and return the pointer to the new block. *PN is never set to zero, and the returned pointer is never null. Repeated reallocations are guaranteed to make progress, either by allocating an initial block with a nonzero size, or by allocating a larger block. In the following implementation, nonzero sizes are doubled so that repeated reallocations have O(N log N) overall cost rather than O(N**2) cost, but the specification for this function does not guarantee that sizes are doubled. Here is an example of use: int *p = NULL; size_t used = 0; size_t allocated = 0; void append_int (int value) { if (used == allocated) p = x2nrealloc (p, &allocated, sizeof *p); p[used++] = value; } This causes x2nrealloc to allocate a block of some nonzero size the first time it is called. To have finer-grained control over the initial size, set *PN to a nonzero value before calling this function with P == NULL. For example: int *p = NULL; size_t used = 0; size_t allocated = 0; size_t allocated1 = 1000; void append_int (int value) { if (used == allocated) { p = x2nrealloc (p, &allocated1, sizeof *p); allocated = allocated1; } p[used++] = value; } */ static inline void * x2nrealloc_inline (void *p, size_t *pn, size_t s) { size_t n = *pn; if (! p) { if (! n) { /* The approximate size to use for initial small allocation requests, when the invoking code specifies an old size of zero. 64 bytes is the largest "small" request for the GNU C library malloc. */ enum { DEFAULT_MXFAST = 64 }; n = DEFAULT_MXFAST / s; n += !n; } } else { if (SIZE_MAX / 2 / s < n) xalloc_die (); n *= 2; } *pn = n; return xrealloc (p, n * s); } void * x2nrealloc (void *p, size_t *pn, size_t s) { return x2nrealloc_inline (p, pn, s); } /* If P is null, allocate a block of at least *PN bytes; otherwise, reallocate P so that it contains more than *PN bytes. *PN must be nonzero unless P is null. Set *PN to the new block's size, and return the pointer to the new block. *PN is never set to zero, and the returned pointer is never null. */ void * x2realloc (void *p, size_t *pn) { return x2nrealloc_inline (p, pn, 1); } /* Allocate S bytes of zeroed memory dynamically, with error checking. There's no need for xnzalloc (N, S), since it would be equivalent to xcalloc (N, S). */ void * xzalloc (size_t s) { return memset (xmalloc (s), 0, s); } /* Allocate zeroed memory for N elements of S bytes, with error checking. S must be nonzero. */ void * xcalloc (size_t n, size_t s) { void *p; /* Test for overflow, since some calloc implementations don't have proper overflow checks. */ if (xalloc_oversized (n, s) || ! (p = calloc (n, s))) xalloc_die (); return p; } /* Clone an object P of size S, with error checking. There's no need for xnclone (P, N, S), since xclone (P, N * S) works without any need for an arithmetic overflow check. */ void * xclone (void const *p, size_t s) { return memcpy (xmalloc (s), p, s); }
25.578125
76
0.670739
[ "object" ]
182004606957c20785b513613540e49d6e079845
855
c
C
2DCode/main.c
evalseth/DG-RAIN
f4765de2050adedfbe57ea25437c54de1f05ca9c
[ "Apache-2.0" ]
1
2021-10-05T12:23:11.000Z
2021-10-05T12:23:11.000Z
2DCode/main.c
evalseth/DG-RAIN
f4765de2050adedfbe57ea25437c54de1f05ca9c
[ "Apache-2.0" ]
null
null
null
2DCode/main.c
evalseth/DG-RAIN
f4765de2050adedfbe57ea25437c54de1f05ca9c
[ "Apache-2.0" ]
2
2019-06-18T02:50:05.000Z
2020-04-03T20:59:00.000Z
#include <stdio.h> #include <stdlib.h> #include <string.h> #include "MeshAttributes.h" #include "SimulationSteps.h" extern void extractPointstoPlot(int NumElx); int main(int argc, char **argv) { if (argc != 2) { printf("Usage: ./Simulation 'Fort.14'\n"); printf("Fort.14: Mesh that includes the entire domain\n"); exit(EXIT_FAILURE); } char *FullMesh = argv[1]; //create EltoVert, EdgtoEls and EdgtoVert store_mesh(FullMesh); extract_mesh_attributes(); int NumElx = 96; //extractPointstoPlot(NumElx); double FinalTime; printf("Enter the time you would like to run the simulation till:\n"); scanf("%lf", &FinalTime); // initialize initialize(); // Impose boundary conditions and couple the channels to the junction boundary_conditions(); // Step through time time_evolution(FinalTime); return(0); }
15.833333
71
0.694737
[ "mesh" ]
182040c6b78266bf406916badc80581a8f5f0269
520,608
c
C
drivers/staging/prima/CORE/SME/src/sme_common/sme_Api.c
CaelestisZ/AetherAura
1b30acb7e6921042722bc4aff160dc63a975abc2
[ "MIT" ]
1
2021-07-15T06:44:32.000Z
2021-07-15T06:44:32.000Z
drivers/staging/prima/CORE/SME/src/sme_common/sme_Api.c
CaelestisZ/AetherAura
1b30acb7e6921042722bc4aff160dc63a975abc2
[ "MIT" ]
null
null
null
drivers/staging/prima/CORE/SME/src/sme_common/sme_Api.c
CaelestisZ/AetherAura
1b30acb7e6921042722bc4aff160dc63a975abc2
[ "MIT" ]
4
2020-05-26T12:40:11.000Z
2021-07-15T06:46:33.000Z
/* * Copyright (c) 2012-2016 The Linux Foundation. All rights reserved. * * Previously licensed under the ISC license by Qualcomm Atheros, Inc. * * * Permission to use, copy, modify, and/or distribute this software for * any purpose with or without fee is hereby granted, provided that the * above copyright notice and this permission notice appear in all * copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL * WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE * AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL * DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR * PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER * TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR * PERFORMANCE OF THIS SOFTWARE. */ /* * This file was originally distributed by Qualcomm Atheros, Inc. * under proprietary terms before Copyright ownership was assigned * to the Linux Foundation. */ /**========================================================================= \file smeApi.c \brief Definitions for SME APIs ========================================================================*/ /*=========================================================================== EDIT HISTORY FOR FILE This section contains comments describing changes made to the module. Notice that changes are listed in reverse chronological order. when who what, where, why ---------- --- -------------------------------------------------------- 06/03/10 js Added support to hostapd driven * deauth/disassoc/mic failure ===========================================================================*/ /*-------------------------------------------------------------------------- Include Files ------------------------------------------------------------------------*/ #include "smsDebug.h" #include "sme_Api.h" #include "csrInsideApi.h" #include "smeInside.h" #include "csrInternal.h" #include "wlan_qct_wda.h" #include "halMsgApi.h" #include "vos_trace.h" #include "sme_Trace.h" #include "vos_types.h" #include "vos_trace.h" #include "sapApi.h" #include "macTrace.h" #include "vos_utils.h" extern tSirRetStatus uMacPostCtrlMsg(void* pSirGlobal, tSirMbMsg* pMb); #include <wlan_qct_pal_api.h> #define LOG_SIZE 256 #define READ_MEMORY_DUMP_CMD 9 #define TL_INIT_STATE 0 #define CSR_ACTIVE_LIST_CMD_TIMEOUT_VALUE 1000*30 //30s // TxMB Functions extern eHalStatus pmcPrepareCommand( tpAniSirGlobal pMac, eSmeCommandType cmdType, void *pvParam, tANI_U32 size, tSmeCmd **ppCmd ); extern void pmcReleaseCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand ); extern void qosReleaseCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand ); extern void csrReleaseRocReqCommand( tpAniSirGlobal pMac); extern eHalStatus p2pProcessRemainOnChannelCmd(tpAniSirGlobal pMac, tSmeCmd *p2pRemainonChn); extern eHalStatus sme_remainOnChnRsp( tpAniSirGlobal pMac, tANI_U8 *pMsg); extern eHalStatus sme_remainOnChnReady( tHalHandle hHal, tANI_U8* pMsg); extern eHalStatus sme_sendActionCnf( tHalHandle hHal, tANI_U8* pMsg); extern eHalStatus p2pProcessNoAReq(tpAniSirGlobal pMac, tSmeCmd *pNoACmd); static eHalStatus initSmeCmdList(tpAniSirGlobal pMac); static void smeAbortCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand, tANI_BOOLEAN fStopping ); eCsrPhyMode sme_GetPhyMode(tHalHandle hHal); eHalStatus sme_HandleChangeCountryCode(tpAniSirGlobal pMac, void *pMsgBuf); void sme_DisconnectConnectedSessions(tpAniSirGlobal pMac); eHalStatus sme_HandleGenericChangeCountryCode(tpAniSirGlobal pMac, void *pMsgBuf); eHalStatus sme_HandlePreChannelSwitchInd(tHalHandle hHal); eHalStatus sme_HandlePostChannelSwitchInd(tHalHandle hHal); #ifdef FEATURE_WLAN_LFR tANI_BOOLEAN csrIsScanAllowed(tpAniSirGlobal pMac); #endif #ifdef WLAN_FEATURE_11W eHalStatus sme_UnprotectedMgmtFrmInd( tHalHandle hHal, tpSirSmeUnprotMgmtFrameInd pSmeMgmtFrm ); #endif //Internal SME APIs eHalStatus sme_AcquireGlobalLock( tSmeStruct *psSme) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; if(psSme) { if( VOS_IS_STATUS_SUCCESS( vos_lock_acquire( &psSme->lkSmeGlobalLock) ) ) { status = eHAL_STATUS_SUCCESS; } } return (status); } eHalStatus sme_ReleaseGlobalLock( tSmeStruct *psSme) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; if(psSme) { if( VOS_IS_STATUS_SUCCESS( vos_lock_release( &psSme->lkSmeGlobalLock) ) ) { status = eHAL_STATUS_SUCCESS; } } return (status); } static eHalStatus initSmeCmdList(tpAniSirGlobal pMac) { eHalStatus status; tSmeCmd *pCmd; tANI_U32 cmd_idx; VOS_STATUS vosStatus; vos_timer_t* cmdTimeoutTimer = NULL; pMac->sme.totalSmeCmd = SME_TOTAL_COMMAND; if (!HAL_STATUS_SUCCESS(status = csrLLOpen(pMac->hHdd, &pMac->sme.smeCmdActiveList))) goto end; if (!HAL_STATUS_SUCCESS(status = csrLLOpen(pMac->hHdd, &pMac->sme.smeCmdPendingList))) goto end; if (!HAL_STATUS_SUCCESS(status = csrLLOpen(pMac->hHdd, &pMac->sme.smeScanCmdActiveList))) goto end; if (!HAL_STATUS_SUCCESS(status = csrLLOpen(pMac->hHdd, &pMac->sme.smeScanCmdPendingList))) goto end; if (!HAL_STATUS_SUCCESS(status = csrLLOpen(pMac->hHdd, &pMac->sme.smeCmdFreeList))) goto end; pCmd = (tSmeCmd *) vos_mem_vmalloc(sizeof(tSmeCmd) * pMac->sme.totalSmeCmd); if ( NULL == pCmd ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("fail to allocate memory %lu"), (unsigned long)(sizeof(tSmeCmd) * pMac->sme.totalSmeCmd)); status = eHAL_STATUS_FAILURE; } else { status = eHAL_STATUS_SUCCESS; vos_mem_set(pCmd, sizeof(tSmeCmd) * pMac->sme.totalSmeCmd, 0); pMac->sme.pSmeCmdBufAddr = pCmd; for (cmd_idx = 0; cmd_idx < pMac->sme.totalSmeCmd; cmd_idx++) { csrLLInsertTail(&pMac->sme.smeCmdFreeList, &pCmd[cmd_idx].Link, LL_ACCESS_LOCK); } } /* This timer is only to debug the active list command timeout */ cmdTimeoutTimer = (vos_timer_t*)vos_mem_malloc(sizeof(vos_timer_t)); if (cmdTimeoutTimer) { pMac->sme.smeCmdActiveList.cmdTimeoutTimer = cmdTimeoutTimer; vosStatus = vos_timer_init( pMac->sme.smeCmdActiveList.cmdTimeoutTimer, VOS_TIMER_TYPE_SW, activeListCmdTimeoutHandle, (void*) pMac); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "Init Timer fail for active list command process time out"); vos_mem_free(pMac->sme.smeCmdActiveList.cmdTimeoutTimer); } else { pMac->sme.smeCmdActiveList.cmdTimeoutDuration = CSR_ACTIVE_LIST_CMD_TIMEOUT_VALUE; } } end: if (!HAL_STATUS_SUCCESS(status)) smsLog(pMac, LOGE, "failed to initialize sme command list:%d\n", status); return (status); } void smeReleaseCommand(tpAniSirGlobal pMac, tSmeCmd *pCmd) { pCmd->command = eSmeNoCommand; csrLLInsertTail(&pMac->sme.smeCmdFreeList, &pCmd->Link, LL_ACCESS_LOCK); } static void smeReleaseCmdList(tpAniSirGlobal pMac, tDblLinkList *pList) { tListElem *pEntry; tSmeCmd *pCommand; while((pEntry = csrLLRemoveHead(pList, LL_ACCESS_LOCK)) != NULL) { //TODO: base on command type to call release functions //reinitialize different command types so they can be reused pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); smeAbortCommand(pMac, pCommand, eANI_BOOLEAN_TRUE); } } static void purgeSmeCmdList(tpAniSirGlobal pMac) { //release any out standing commands back to free command list smeReleaseCmdList(pMac, &pMac->sme.smeCmdPendingList); smeReleaseCmdList(pMac, &pMac->sme.smeCmdActiveList); smeReleaseCmdList(pMac, &pMac->sme.smeScanCmdPendingList); smeReleaseCmdList(pMac, &pMac->sme.smeScanCmdActiveList); } void purgeSmeSessionCmdList(tpAniSirGlobal pMac, tANI_U32 sessionId, tDblLinkList *pList, bool flush_all) { //release any out standing commands back to free command list tListElem *pEntry, *pNext; tSmeCmd *pCommand; tDblLinkList localList; vos_mem_zero(&localList, sizeof(tDblLinkList)); if(!HAL_STATUS_SUCCESS(csrLLOpen(pMac->hHdd, &localList))) { smsLog(pMac, LOGE, FL(" failed to open list")); return; } csrLLLock(pList); pEntry = csrLLPeekHead(pList, LL_ACCESS_NOLOCK); while(pEntry != NULL) { pNext = csrLLNext(pList, pEntry, LL_ACCESS_NOLOCK); pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); if (!flush_all && csr_is_disconnect_full_power_cmd(pCommand)) { smsLog(pMac, LOGW, FL(" Ignore disconnect")); pEntry = pNext; continue; } if(pCommand->sessionId == sessionId) { if(csrLLRemoveEntry(pList, pEntry, LL_ACCESS_NOLOCK)) { csrLLInsertTail(&localList, pEntry, LL_ACCESS_NOLOCK); } } pEntry = pNext; } csrLLUnlock(pList); while( (pEntry = csrLLRemoveHead(&localList, LL_ACCESS_NOLOCK)) ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); smeAbortCommand(pMac, pCommand, eANI_BOOLEAN_TRUE); } csrLLClose(&localList); } static eHalStatus freeSmeCmdList(tpAniSirGlobal pMac) { eHalStatus status = eHAL_STATUS_SUCCESS; purgeSmeCmdList(pMac); csrLLClose(&pMac->sme.smeCmdPendingList); csrLLClose(&pMac->sme.smeCmdActiveList); csrLLClose(&pMac->sme.smeScanCmdPendingList); csrLLClose(&pMac->sme.smeScanCmdActiveList); csrLLClose(&pMac->sme.smeCmdFreeList); /*destroy active list command time out timer */ vos_timer_destroy(pMac->sme.smeCmdActiveList.cmdTimeoutTimer); vos_mem_free(pMac->sme.smeCmdActiveList.cmdTimeoutTimer); pMac->sme.smeCmdActiveList.cmdTimeoutTimer = NULL; status = vos_lock_acquire(&pMac->sme.lkSmeGlobalLock); if(status != eHAL_STATUS_SUCCESS) { smsLog(pMac, LOGE, FL("Failed to acquire the lock status = %d"), status); goto done; } if(NULL != pMac->sme.pSmeCmdBufAddr) { vos_mem_vfree(pMac->sme.pSmeCmdBufAddr); pMac->sme.pSmeCmdBufAddr = NULL; } status = vos_lock_release(&pMac->sme.lkSmeGlobalLock); if(status != eHAL_STATUS_SUCCESS) { smsLog(pMac, LOGE, FL("Failed to release the lock status = %d"), status); } done: return (status); } void dumpCsrCommandInfo(tpAniSirGlobal pMac, tSmeCmd *pCmd) { switch( pCmd->command ) { case eSmeCommandScan: smsLog( pMac, LOGE, " scan command reason is %d", pCmd->u.scanCmd.reason ); break; case eSmeCommandRoam: smsLog( pMac, LOGE, " roam command reason is %d", pCmd->u.roamCmd.roamReason ); break; case eSmeCommandWmStatusChange: smsLog( pMac, LOGE, " WMStatusChange command type is %d", pCmd->u.wmStatusChangeCmd.Type ); break; case eSmeCommandSetKey: smsLog( pMac, LOGE, " setKey command auth(%d) enc(%d)", pCmd->u.setKeyCmd.authType, pCmd->u.setKeyCmd.encType ); break; case eSmeCommandRemoveKey: smsLog( pMac, LOGE, " removeKey command auth(%d) enc(%d)", pCmd->u.removeKeyCmd.authType, pCmd->u.removeKeyCmd.encType ); break; default: smsLog( pMac, LOGE, " default: Unhandled command %d", pCmd->command); break; } } tSmeCmd *smeGetCommandBuffer( tpAniSirGlobal pMac ) { tSmeCmd *pRetCmd = NULL, *pTempCmd = NULL; tListElem *pEntry; static int smeCommandQueueFull = 0; pEntry = csrLLRemoveHead( &pMac->sme.smeCmdFreeList, LL_ACCESS_LOCK ); // If we can get another MS Msg buffer, then we are ok. Just link // the entry onto the linked list. (We are using the linked list // to keep track of tfhe message buffers). if ( pEntry ) { pRetCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); /* reset when free list is available */ smeCommandQueueFull = 0; } else { int idx = 1; //Cannot change pRetCmd here since it needs to return later. pEntry = csrLLPeekHead( &pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK ); if( pEntry ) { pTempCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); } smsLog( pMac, LOGE, "Out of command buffer.... command (0x%X) stuck", (pTempCmd) ? pTempCmd->command : eSmeNoCommand ); if(pTempCmd) { if( eSmeCsrCommandMask & pTempCmd->command ) { //CSR command is stuck. See what the reason code is for that command dumpCsrCommandInfo(pMac, pTempCmd); } } //if(pTempCmd) //dump what is in the pending queue csrLLLock(&pMac->sme.smeCmdPendingList); pEntry = csrLLPeekHead( &pMac->sme.smeCmdPendingList, LL_ACCESS_NOLOCK ); while(pEntry && !smeCommandQueueFull) { pTempCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); /* Print only 1st five commands from pending queue. */ if (idx <= 5) smsLog( pMac, LOGE, "Out of command buffer.... SME pending command #%d (0x%X)", idx, pTempCmd->command ); idx++; if( eSmeCsrCommandMask & pTempCmd->command ) { //CSR command is stuck. See what the reason code is for that command dumpCsrCommandInfo(pMac, pTempCmd); } pEntry = csrLLNext( &pMac->sme.smeCmdPendingList, pEntry, LL_ACCESS_NOLOCK ); } csrLLUnlock(&pMac->sme.smeCmdPendingList); idx = 1; //There may be some more command in CSR's own pending queue csrLLLock(&pMac->roam.roamCmdPendingList); pEntry = csrLLPeekHead( &pMac->roam.roamCmdPendingList, LL_ACCESS_NOLOCK ); while(pEntry && !smeCommandQueueFull) { pTempCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); /* Print only 1st five commands from CSR pending queue */ if (idx <= 5) smsLog( pMac, LOGE, "Out of command buffer...CSR pending command #%d (0x%X)", idx, pTempCmd->command ); idx++; dumpCsrCommandInfo(pMac, pTempCmd); pEntry = csrLLNext( &pMac->roam.roamCmdPendingList, pEntry, LL_ACCESS_NOLOCK ); } /* * Increament static variable so that it prints pending command * only once */ smeCommandQueueFull++; csrLLUnlock(&pMac->roam.roamCmdPendingList); vos_state_info_dump_all(); if (pMac->roam.configParam.enableFatalEvent) { vos_fatal_event_logs_req(WLAN_LOG_TYPE_FATAL, WLAN_LOG_INDICATOR_HOST_DRIVER, WLAN_LOG_REASON_SME_OUT_OF_CMD_BUF, FALSE, FALSE); } else { /* Trigger SSR */ vos_wlanRestart(); } } if( pRetCmd ) { vos_mem_set((tANI_U8 *)&pRetCmd->command, sizeof(pRetCmd->command), 0); vos_mem_set((tANI_U8 *)&pRetCmd->sessionId, sizeof(pRetCmd->sessionId), 0); vos_mem_set((tANI_U8 *)&pRetCmd->u, sizeof(pRetCmd->u), 0); } return( pRetCmd ); } void smePushCommand( tpAniSirGlobal pMac, tSmeCmd *pCmd, tANI_BOOLEAN fHighPriority ) { if (!SME_IS_START(pMac)) { smsLog( pMac, LOGE, FL("Sme in stop state")); return; } if ( fHighPriority ) { csrLLInsertHead( &pMac->sme.smeCmdPendingList, &pCmd->Link, LL_ACCESS_LOCK ); } else { csrLLInsertTail( &pMac->sme.smeCmdPendingList, &pCmd->Link, LL_ACCESS_LOCK ); } // process the command queue... smeProcessPendingQueue( pMac ); return; } static eSmeCommandType smeIsFullPowerNeeded( tpAniSirGlobal pMac, tSmeCmd *pCommand ) { eSmeCommandType pmcCommand = eSmeNoCommand; tANI_BOOLEAN fFullPowerNeeded = eANI_BOOLEAN_FALSE; tPmcState pmcState; eHalStatus status; do { pmcState = pmcGetPmcState(pMac); status = csrIsFullPowerNeeded( pMac, pCommand, NULL, &fFullPowerNeeded ); if( !HAL_STATUS_SUCCESS(status) ) { //PMC state is not right for the command, drop it return ( eSmeDropCommand ); } if( fFullPowerNeeded ) break; fFullPowerNeeded = ( ( eSmeCommandAddTs == pCommand->command ) || ( eSmeCommandDelTs == pCommand->command ) ); if( fFullPowerNeeded ) break; #ifdef FEATURE_OEM_DATA_SUPPORT fFullPowerNeeded = (pmcState == IMPS && eSmeCommandOemDataReq == pCommand->command); if(fFullPowerNeeded) break; #endif fFullPowerNeeded = (pmcState == IMPS && eSmeCommandRemainOnChannel == pCommand->command); if(fFullPowerNeeded) break; } while(0); if( fFullPowerNeeded ) { switch( pmcState ) { case IMPS: case STANDBY: pmcCommand = eSmeCommandExitImps; break; case BMPS: pmcCommand = eSmeCommandExitBmps; break; case UAPSD: pmcCommand = eSmeCommandExitUapsd; break; case WOWL: pmcCommand = eSmeCommandExitWowl; break; default: break; } } return ( pmcCommand ); } //For commands that need to do extra cleanup. static void smeAbortCommand( tpAniSirGlobal pMac, tSmeCmd *pCommand, tANI_BOOLEAN fStopping ) { if( eSmePmcCommandMask & pCommand->command ) { pmcAbortCommand( pMac, pCommand, fStopping ); } else if ( eSmeCsrCommandMask & pCommand->command ) { csrAbortCommand( pMac, pCommand, fStopping ); } else { switch( pCommand->command ) { case eSmeCommandRemainOnChannel: if (NULL != pCommand->u.remainChlCmd.callback) { remainOnChanCallback callback = pCommand->u.remainChlCmd.callback; /* process the msg */ if( callback ) { callback(pMac, pCommand->u.remainChlCmd.callbackCtx, eCSR_SCAN_ABORT ); } } smeReleaseCommand( pMac, pCommand ); break; default: smeReleaseCommand( pMac, pCommand ); break; } } } tListElem *csrGetCmdToProcess(tpAniSirGlobal pMac, tDblLinkList *pList, tANI_U8 sessionId, tANI_BOOLEAN fInterlocked) { tListElem *pCurEntry = NULL; tSmeCmd *pCommand; /* Go through the list and return the command whose session id is not * matching with the current ongoing scan cmd sessionId */ pCurEntry = csrLLPeekHead( pList, LL_ACCESS_LOCK ); while (pCurEntry) { pCommand = GET_BASE_ADDR(pCurEntry, tSmeCmd, Link); if (pCommand->sessionId != sessionId) { smsLog(pMac, LOG1, "selected the command with different sessionId"); return pCurEntry; } pCurEntry = csrLLNext(pList, pCurEntry, fInterlocked); } smsLog(pMac, LOG1, "No command pending with different sessionId"); return NULL; } tANI_BOOLEAN smeProcessScanQueue(tpAniSirGlobal pMac) { tListElem *pEntry; tSmeCmd *pCommand; tListElem *pSmeEntry; tSmeCmd *pSmeCommand; tANI_BOOLEAN status = eANI_BOOLEAN_TRUE; csrLLLock( &pMac->sme.smeScanCmdActiveList ); if (csrLLIsListEmpty( &pMac->sme.smeScanCmdActiveList, LL_ACCESS_NOLOCK )) { if (!csrLLIsListEmpty(&pMac->sme.smeScanCmdPendingList, LL_ACCESS_LOCK)) { pEntry = csrLLPeekHead( &pMac->sme.smeScanCmdPendingList, LL_ACCESS_LOCK ); if (pEntry) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); //We cannot execute any command in wait-for-key state until setKey is through. if (CSR_IS_WAIT_FOR_KEY( pMac, pCommand->sessionId)) { if (!CSR_IS_SET_KEY_COMMAND(pCommand)) { smsLog(pMac, LOGE, " Cannot process command(%d) while waiting for key", pCommand->command); status = eANI_BOOLEAN_FALSE; goto end; } } if ((!csrLLIsListEmpty(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK ))) { pSmeEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK); if (pEntry) { pSmeCommand = GET_BASE_ADDR(pEntry, tSmeCmd, Link) ; /* if scan is running on one interface and SME recei ves the next command on the same interface then dont the allow the command to be queued to smeCmdPendingList. If next scan is allowed on the same interface the CSR state machine will get screwed up. */ if (pSmeCommand->sessionId == pCommand->sessionId) { status = eANI_BOOLEAN_FALSE; goto end; } } } if ( csrLLRemoveEntry( &pMac->sme.smeScanCmdPendingList, pEntry, LL_ACCESS_LOCK ) ) { csrLLInsertHead( &pMac->sme.smeScanCmdActiveList, &pCommand->Link, LL_ACCESS_NOLOCK ); switch (pCommand->command) { case eSmeCommandScan: smsLog(pMac, LOG1, " Processing scan offload command "); csrProcessScanCommand( pMac, pCommand ); break; default: smsLog(pMac, LOGE, " Something wrong, wrong command enqueued" " to smeScanCmdPendingList"); pEntry = csrLLRemoveHead( &pMac->sme.smeScanCmdActiveList, LL_ACCESS_NOLOCK ); pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); smeReleaseCommand( pMac, pCommand ); break; } } } } } end: csrLLUnlock(&pMac->sme.smeScanCmdActiveList); return status; } eHalStatus smeProcessPnoCommand(tpAniSirGlobal pMac, tSmeCmd *pCmd) { tpSirPNOScanReq pnoReqBuf; tSirMsgQ msgQ; pnoReqBuf = vos_mem_malloc(sizeof(tSirPNOScanReq)); if ( NULL == pnoReqBuf ) { smsLog(pMac, LOGE, FL("failed to allocate memory")); return eHAL_STATUS_FAILURE; } vos_mem_copy(pnoReqBuf, &(pCmd->u.pnoInfo), sizeof(tSirPNOScanReq)); smsLog(pMac, LOG1, FL("post WDA_SET_PNO_REQ comamnd")); msgQ.type = WDA_SET_PNO_REQ; msgQ.reserved = 0; msgQ.bodyptr = pnoReqBuf; msgQ.bodyval = 0; wdaPostCtrlMsg( pMac, &msgQ); return eHAL_STATUS_SUCCESS; } /** * sme_process_set_max_tx_power() - Set the Maximum Transmit Power * * @pMac: mac pointer. * @command: cmd param containing bssid, self mac * and power in db * * Set the maximum transmit power dynamically. * * Return: eHalStatus * */ eHalStatus sme_process_set_max_tx_power(tpAniSirGlobal pMac, tSmeCmd *command) { vos_msg_t msg; tMaxTxPowerParams *max_tx_params = NULL; max_tx_params = vos_mem_malloc(sizeof(*max_tx_params)); if (NULL == max_tx_params) { smsLog(pMac, LOGE, FL("fail to allocate memory for max_tx_params")); return eHAL_STATUS_FAILURE; } vos_mem_copy(max_tx_params->bssId, command->u.set_tx_max_pwr.bssid, SIR_MAC_ADDR_LENGTH); vos_mem_copy(max_tx_params->selfStaMacAddr, command->u.set_tx_max_pwr.self_sta_mac_addr, SIR_MAC_ADDR_LENGTH); max_tx_params->power = command->u.set_tx_max_pwr.power; msg.type = WDA_SET_MAX_TX_POWER_REQ; msg.reserved = 0; msg.bodyptr = max_tx_params; if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { smsLog(pMac, LOGE, FL("Not able to post WDA_SET_MAX_TX_POWER_REQ message to WDA")); vos_mem_free(max_tx_params); return eHAL_STATUS_FAILURE; } return eHAL_STATUS_SUCCESS; } static void smeProcessNanReq(tpAniSirGlobal pMac, tSmeCmd *pCommand ) { tSirMsgQ msgQ; tSirRetStatus retCode = eSIR_SUCCESS; msgQ.type = WDA_NAN_REQUEST; msgQ.reserved = 0; msgQ.bodyptr = pCommand->u.pNanReq; msgQ.bodyval = 0; retCode = wdaPostCtrlMsg( pMac, &msgQ ); if( eSIR_SUCCESS != retCode) { vos_mem_free(pCommand->u.pNanReq); smsLog( pMac, LOGE, FL("Posting WDA_NAN_REQUEST to WDA failed, reason=%X"), retCode ); } else { smsLog(pMac, LOG1, FL("posted WDA_NAN_REQUEST command")); } } tANI_BOOLEAN smeProcessCommand( tpAniSirGlobal pMac ) { tANI_BOOLEAN fContinue = eANI_BOOLEAN_FALSE; eHalStatus status = eHAL_STATUS_SUCCESS; tListElem *pEntry; tSmeCmd *pCommand; tListElem *pSmeEntry; tSmeCmd *pSmeCommand; eSmeCommandType pmcCommand = eSmeNoCommand; // if the ActiveList is empty, then nothing is active so we can process a // pending command... //alwasy lock active list before locking pending list csrLLLock( &pMac->sme.smeCmdActiveList ); if ( csrLLIsListEmpty( &pMac->sme.smeCmdActiveList, LL_ACCESS_NOLOCK ) ) { if(!csrLLIsListEmpty(&pMac->sme.smeCmdPendingList, LL_ACCESS_LOCK)) { /* If scan command is pending in the smeScanCmdActive list * then pick the command from smeCmdPendingList which is * not matching with the scan command session id. * At any point of time only one command will be allowed * on a single session. */ if ((pMac->fScanOffload) && (!csrLLIsListEmpty(&pMac->sme.smeScanCmdActiveList, LL_ACCESS_LOCK))) { pSmeEntry = csrLLPeekHead(&pMac->sme.smeScanCmdActiveList, LL_ACCESS_LOCK); if (pSmeEntry) { pSmeCommand = GET_BASE_ADDR(pSmeEntry, tSmeCmd, Link); pEntry = csrGetCmdToProcess(pMac, &pMac->sme.smeCmdPendingList, pSmeCommand->sessionId, LL_ACCESS_LOCK); goto sme_process_cmd; } } //Peek the command pEntry = csrLLPeekHead( &pMac->sme.smeCmdPendingList, LL_ACCESS_LOCK ); sme_process_cmd: if( pEntry ) { pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); /* Allow only disconnect command * in wait-for-key state until setKey is through. */ if( CSR_IS_WAIT_FOR_KEY( pMac, pCommand->sessionId ) && !CSR_IS_DISCONNECT_COMMAND( pCommand ) ) { if( !CSR_IS_SET_KEY_COMMAND( pCommand ) ) { csrLLUnlock( &pMac->sme.smeCmdActiveList ); smsLog(pMac, LOGE, FL("SessionId %d: Cannot process " "command(%d) while waiting for key"), pCommand->sessionId, pCommand->command); fContinue = eANI_BOOLEAN_FALSE; goto sme_process_scan_queue; } } pmcCommand = smeIsFullPowerNeeded( pMac, pCommand ); if( eSmeDropCommand == pmcCommand ) { //This command is not ok for current PMC state if( csrLLRemoveEntry( &pMac->sme.smeCmdPendingList, pEntry, LL_ACCESS_LOCK ) ) { smeAbortCommand( pMac, pCommand, eANI_BOOLEAN_FALSE ); } csrLLUnlock( &pMac->sme.smeCmdActiveList ); //tell caller to continue fContinue = eANI_BOOLEAN_TRUE; goto sme_process_scan_queue; } else if( eSmeNoCommand != pmcCommand ) { tExitBmpsInfo exitBmpsInfo; void *pv = NULL; tANI_U32 size = 0; tSmeCmd *pPmcCmd = NULL; if( eSmeCommandExitBmps == pmcCommand ) { exitBmpsInfo.exitBmpsReason = eSME_REASON_OTHER; pv = (void *)&exitBmpsInfo; size = sizeof(tExitBmpsInfo); } //pmcCommand has to be one of the exit power save command status = pmcPrepareCommand( pMac, pmcCommand, pv, size, &pPmcCmd ); if( HAL_STATUS_SUCCESS( status ) && pPmcCmd ) { /* Set the time out to 30 sec */ pMac->sme.smeCmdActiveList.cmdTimeoutDuration = CSR_ACTIVE_LIST_CMD_TIMEOUT_VALUE; //Force this command to wake up the chip csrLLInsertHead( &pMac->sme.smeCmdActiveList, &pPmcCmd->Link, LL_ACCESS_NOLOCK ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_COMMAND,pPmcCmd->sessionId, pPmcCmd->command)); csrLLUnlock( &pMac->sme.smeCmdActiveList ); fContinue = pmcProcessCommand( pMac, pPmcCmd ); if( fContinue ) { //The command failed, remove it if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pPmcCmd->Link, LL_ACCESS_NOLOCK ) ) { pmcReleaseCommand( pMac, pPmcCmd ); } } } else { csrLLUnlock( &pMac->sme.smeCmdActiveList ); smsLog( pMac, LOGE, FL( "Cannot issue command(0x%X) to wake up the chip. Status = %d"), pmcCommand, status ); //Let it retry fContinue = eANI_BOOLEAN_TRUE; } goto sme_process_scan_queue; } if ( csrLLRemoveEntry( &pMac->sme.smeCmdPendingList, pEntry, LL_ACCESS_LOCK ) ) { // we can reuse the pCommand /* For ROC set timeot to 30 *3 as Supplicant can retry * P2P Invitation Request 120 times with 500ms interval. * For roam command set timeout to 30 * 2 sec. * There are cases where we try to connect to different * APs with same SSID one by one until sucessfully conneted * and thus roam command might take more time if connection * is rejected by too many APs. */ if (eSmeCommandRemainOnChannel == pCommand->command) pMac->sme.smeCmdActiveList.cmdTimeoutDuration = CSR_ACTIVE_LIST_CMD_TIMEOUT_VALUE * 3; else if ((eSmeCommandRoam == pCommand->command) && (eCsrHddIssued == pCommand->u.roamCmd.roamReason)) pMac->sme.smeCmdActiveList.cmdTimeoutDuration = CSR_ACTIVE_LIST_CMD_TIMEOUT_VALUE * 2; else pMac->sme.smeCmdActiveList.cmdTimeoutDuration = CSR_ACTIVE_LIST_CMD_TIMEOUT_VALUE; // Insert the command onto the ActiveList... csrLLInsertHead( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_NOLOCK ); if( pMac->deferImps ) { /* IMPS timer is already running so stop it and * it will get restarted when no command is pending */ csrScanStopIdleScanTimer( pMac ); pMac->scan.fRestartIdleScan = eANI_BOOLEAN_TRUE; pMac->deferImps = eANI_BOOLEAN_FALSE; } // .... and process the command. MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_COMMAND, pCommand->sessionId, pCommand->command)); switch ( pCommand->command ) { case eSmeCommandScan: csrLLUnlock( &pMac->sme.smeCmdActiveList ); status = csrProcessScanCommand( pMac, pCommand ); break; case eSmeCommandRoam: csrLLUnlock( &pMac->sme.smeCmdActiveList ); status = csrRoamProcessCommand( pMac, pCommand ); if(!HAL_STATUS_SUCCESS(status)) { if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { csrReleaseCommandRoam( pMac, pCommand ); } } break; case eSmeCommandWmStatusChange: csrLLUnlock( &pMac->sme.smeCmdActiveList ); csrRoamProcessWmStatusChangeCommand(pMac, pCommand); break; case eSmeCommandSetKey: csrLLUnlock( &pMac->sme.smeCmdActiveList ); status = csrRoamProcessSetKeyCommand( pMac, pCommand ); if(!HAL_STATUS_SUCCESS(status)) { if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { csrReleaseCommandSetKey( pMac, pCommand ); } } break; case eSmeCommandRemoveKey: csrLLUnlock( &pMac->sme.smeCmdActiveList ); status = csrRoamProcessRemoveKeyCommand( pMac, pCommand ); if(!HAL_STATUS_SUCCESS(status)) { if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { csrReleaseCommandRemoveKey( pMac, pCommand ); } } break; case eSmeCommandAddStaSession: csrLLUnlock( &pMac->sme.smeCmdActiveList ); csrProcessAddStaSessionCommand( pMac, pCommand ); break; case eSmeCommandDelStaSession: csrLLUnlock( &pMac->sme.smeCmdActiveList ); csrProcessDelStaSessionCommand( pMac, pCommand ); break; case eSmeCommandMacSpoofRequest: csrLLUnlock( &pMac->sme.smeCmdActiveList ); csrProcessMacAddrSpoofCommand( pMac, pCommand ); //We need to re-run the command fContinue = eANI_BOOLEAN_TRUE; // No Rsp expected, free cmd from active list if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { csrReleaseCommand( pMac, pCommand ); } break; case eSmeCommandGetFrameLogRequest: csrLLUnlock( &pMac->sme.smeCmdActiveList ); csrProcessGetFrameLogCommand( pMac, pCommand ); //We need to re-run the command fContinue = eANI_BOOLEAN_TRUE; // No Rsp expected, free cmd from active list if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { csrReleaseCommand( pMac, pCommand ); } break; case eSmeCommandSetMaxTxPower: csrLLUnlock(&pMac->sme.smeCmdActiveList); sme_process_set_max_tx_power(pMac, pCommand); /* We need to re-run the command */ fContinue = eANI_BOOLEAN_TRUE; /* No Rsp expected, free cmd from active list */ if(csrLLRemoveEntry(&pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK)) { csrReleaseCommand(pMac, pCommand); } break; #ifdef FEATURE_OEM_DATA_SUPPORT case eSmeCommandOemDataReq: csrLLUnlock(&pMac->sme.smeCmdActiveList); oemData_ProcessOemDataReqCommand(pMac, pCommand); break; #endif case eSmeCommandRemainOnChannel: csrLLUnlock(&pMac->sme.smeCmdActiveList); p2pProcessRemainOnChannelCmd(pMac, pCommand); break; case eSmeCommandNoAUpdate: csrLLUnlock( &pMac->sme.smeCmdActiveList ); p2pProcessNoAReq(pMac,pCommand); case eSmeCommandEnterImps: case eSmeCommandExitImps: case eSmeCommandEnterBmps: case eSmeCommandExitBmps: case eSmeCommandEnterUapsd: case eSmeCommandExitUapsd: case eSmeCommandEnterWowl: case eSmeCommandExitWowl: csrLLUnlock( &pMac->sme.smeCmdActiveList ); fContinue = pmcProcessCommand( pMac, pCommand ); if( fContinue ) { //The command failed, remove it if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { pmcReleaseCommand( pMac, pCommand ); } } break; //Treat standby differently here because caller may not be able to handle //the failure so we do our best here case eSmeCommandEnterStandby: if( csrIsConnStateDisconnected( pMac, pCommand->sessionId ) ) { //It can continue csrLLUnlock( &pMac->sme.smeCmdActiveList ); fContinue = pmcProcessCommand( pMac, pCommand ); if( fContinue ) { //The command failed, remove it if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { pmcReleaseCommand( pMac, pCommand ); } } } else { //Need to issue a disconnect first before processing this command tSmeCmd *pNewCmd; //We need to re-run the command fContinue = eANI_BOOLEAN_TRUE; //Pull off the standby command first if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_NOLOCK ) ) { csrLLUnlock( &pMac->sme.smeCmdActiveList ); //Need to call CSR function here because the disconnect command //is handled by CSR pNewCmd = csrGetCommandBuffer( pMac ); if( NULL != pNewCmd ) { //Put the standby command to the head of the pending list first csrLLInsertHead( &pMac->sme.smeCmdPendingList, &pCommand->Link, LL_ACCESS_LOCK ); pNewCmd->command = eSmeCommandRoam; pNewCmd->u.roamCmd.roamReason = eCsrForcedDisassoc; //Put the disassoc command before the standby command csrLLInsertHead( &pMac->sme.smeCmdPendingList, &pNewCmd->Link, LL_ACCESS_LOCK ); } else { //Continue the command here fContinue = pmcProcessCommand( pMac, pCommand ); if( fContinue ) { //The command failed, remove it if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK ) ) { pmcReleaseCommand( pMac, pCommand ); } } } } else { csrLLUnlock( &pMac->sme.smeCmdActiveList ); smsLog( pMac, LOGE, FL(" failed to remove standby command") ); VOS_ASSERT(0); } } break; case eSmeCommandPnoReq: csrLLUnlock( &pMac->sme.smeCmdActiveList ); status = smeProcessPnoCommand(pMac, pCommand); if (!HAL_STATUS_SUCCESS(status)){ smsLog(pMac, LOGE, FL("failed to post SME PNO SCAN %d"), status); } //We need to re-run the command fContinue = eANI_BOOLEAN_TRUE; if (csrLLRemoveEntry(&pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK)) { csrReleaseCommand(pMac, pCommand); } break; case eSmeCommandAddTs: case eSmeCommandDelTs: csrLLUnlock( &pMac->sme.smeCmdActiveList ); #ifndef WLAN_MDM_CODE_REDUCTION_OPT fContinue = qosProcessCommand( pMac, pCommand ); if( fContinue ) { //The command failed, remove it if( csrLLRemoveEntry( &pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_NOLOCK ) ) { //#ifndef WLAN_MDM_CODE_REDUCTION_OPT qosReleaseCommand( pMac, pCommand ); //#endif /* WLAN_MDM_CODE_REDUCTION_OPT*/ } } #endif break; #ifdef FEATURE_WLAN_TDLS case eSmeCommandTdlsSendMgmt: case eSmeCommandTdlsAddPeer: case eSmeCommandTdlsDelPeer: case eSmeCommandTdlsLinkEstablish: case eSmeCommandTdlsChannelSwitch: // tdlsoffchan smsLog(pMac, LOG1, FL("sending TDLS Command 0x%x to PE"), pCommand->command); csrLLUnlock(&pMac->sme.smeCmdActiveList); status = csrTdlsProcessCmd(pMac, pCommand); if(!HAL_STATUS_SUCCESS(status)) { if(csrLLRemoveEntry(&pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK)) csrReleaseCommand(pMac, pCommand); } break ; #endif case eSmeCommandNanReq: csrLLUnlock( &pMac->sme.smeCmdActiveList ); smeProcessNanReq( pMac, pCommand ); if (csrLLRemoveEntry(&pMac->sme.smeCmdActiveList, &pCommand->Link, LL_ACCESS_LOCK)) { csrReleaseCommand(pMac, pCommand); } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "eSmeCommandNanReq processed"); fContinue = eANI_BOOLEAN_TRUE; break; default: //something is wrong //remove it from the active list smsLog(pMac, LOGE, " csrProcessCommand processes an unknown command %d", pCommand->command); pEntry = csrLLRemoveHead( &pMac->sme.smeCmdActiveList, LL_ACCESS_NOLOCK ); csrLLUnlock( &pMac->sme.smeCmdActiveList ); pCommand = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); smeReleaseCommand( pMac, pCommand ); status = eHAL_STATUS_FAILURE; break; } if(!HAL_STATUS_SUCCESS(status)) { fContinue = eANI_BOOLEAN_TRUE; } }//if(pEntry) else { //This is odd. Some one else pull off the command. csrLLUnlock( &pMac->sme.smeCmdActiveList ); } } else { csrLLUnlock( &pMac->sme.smeCmdActiveList ); } } else { //No command waiting csrLLUnlock( &pMac->sme.smeCmdActiveList ); //This is only used to restart an idle mode scan, it means at least one other idle scan has finished. if(pMac->scan.fRestartIdleScan && eANI_BOOLEAN_FALSE == pMac->scan.fCancelIdleScan) { tANI_U32 nTime = 0; pMac->scan.fRestartIdleScan = eANI_BOOLEAN_FALSE; if(!HAL_STATUS_SUCCESS(csrScanTriggerIdleScan(pMac, &nTime))) { csrScanStartIdleScanTimer(pMac, nTime); } } } } else { csrLLUnlock( &pMac->sme.smeCmdActiveList ); } sme_process_scan_queue: if (pMac->fScanOffload && !(smeProcessScanQueue(pMac))) fContinue = eANI_BOOLEAN_FALSE; return ( fContinue ); } void smeProcessPendingQueue( tpAniSirGlobal pMac ) { while( smeProcessCommand( pMac ) ); } tANI_BOOLEAN smeCommandPending(tpAniSirGlobal pMac) { return ( !csrLLIsListEmpty( &pMac->sme.smeCmdActiveList, LL_ACCESS_NOLOCK ) || !csrLLIsListEmpty(&pMac->sme.smeCmdPendingList, LL_ACCESS_NOLOCK) ); } //Global APIs /*-------------------------------------------------------------------------- \brief sme_Open() - Initialze all SME modules and put them at idle state The function initializes each module inside SME, PMC, CCM, CSR, etc. . Upon successfully return, all modules are at idle state ready to start. smeOpen must be called before any other SME APIs can be involved. smeOpen must be called after macOpen. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME is successfully initialized. Other status means SME is failed to be initialized \sa --------------------------------------------------------------------------*/ eHalStatus sme_Open(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); do { pMac->sme.state = SME_STATE_STOP; pMac->sme.currDeviceMode = VOS_STA_MODE; if( !VOS_IS_STATUS_SUCCESS( vos_lock_init( &pMac->sme.lkSmeGlobalLock ) ) ) { smsLog( pMac, LOGE, "sme_Open failed init lock" ); status = eHAL_STATUS_FAILURE; break; } status = ccmOpen(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "ccmOpen failed during initialization with status=%d", status ); break; } status = csrOpen(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrOpen failed during initialization with status=%d", status ); break; } status = pmcOpen(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "pmcOpen failed during initialization with status=%d", status ); break; } #ifdef FEATURE_WLAN_TDLS pMac->isTdlsPowerSaveProhibited = 0; #endif #ifndef WLAN_MDM_CODE_REDUCTION_OPT status = sme_QosOpen(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "Qos open failed during initialization with status=%d", status ); break; } status = btcOpen(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "btcOpen open failed during initialization with status=%d", status ); break; } #endif #ifdef FEATURE_OEM_DATA_SUPPORT status = oemData_OemDataReqOpen(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog(pMac, LOGE, "oemData_OemDataReqOpen failed during initialization with status=%d", status ); break; } #endif if(!HAL_STATUS_SUCCESS((status = initSmeCmdList(pMac)))) break; { v_PVOID_t pvosGCtx = vos_get_global_context(VOS_MODULE_ID_SAP, NULL); if ( NULL == pvosGCtx ){ smsLog( pMac, LOGE, "WLANSAP_Open open failed during initialization"); status = eHAL_STATUS_FAILURE; break; } status = WLANSAP_Open( pvosGCtx ); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "WLANSAP_Open open failed during initialization with status=%d", status ); break; } } #if defined WLAN_FEATURE_VOWIFI status = rrmOpen(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "rrmOpen open failed during initialization with status=%d", status ); break; } #endif #if defined WLAN_FEATURE_VOWIFI_11R sme_FTOpen(pMac); #endif sme_p2pOpen(pMac); smeTraceInit(pMac); sme_register_debug_callback(); }while (0); return status; } /*-------------------------------------------------------------------------- \brief sme_set11dinfo() - Set the 11d information about valid channels and there power using information from nvRAM This function is called only for AP. This is a synchronous call \param hHal - The handle returned by macOpen. \Param pSmeConfigParams - a pointer to a caller allocated object of typedef struct _smeConfigParams. \return eHAL_STATUS_SUCCESS - SME update the config parameters successfully. Other status means SME is failed to update the config parameters. \sa --------------------------------------------------------------------------*/ eHalStatus sme_set11dinfo(tHalHandle hHal, tpSmeConfigParams pSmeConfigParams) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SET_11DINFO, NO_SESSION, 0)); if (NULL == pSmeConfigParams ) { smsLog( pMac, LOGE, "Empty config param structure for SME, nothing to update"); return status; } status = csrSetChannels(hHal, &pSmeConfigParams->csrConfig ); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrChangeDefaultConfigParam failed with status=%d", status ); } return status; } /*-------------------------------------------------------------------------- \brief sme_getSoftApDomain() - Get the current regulatory domain of softAp. This is a synchronous call \param hHal - The handle returned by HostapdAdapter. \Param v_REGDOMAIN_t - The current Regulatory Domain requested for SoftAp. \return eHAL_STATUS_SUCCESS - SME successfully completed the request. Other status means, failed to get the current regulatory domain. \sa --------------------------------------------------------------------------*/ eHalStatus sme_getSoftApDomain(tHalHandle hHal, v_REGDOMAIN_t *domainIdSoftAp) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_GET_SOFTAP_DOMAIN, NO_SESSION, 0)); if (NULL == domainIdSoftAp ) { smsLog( pMac, LOGE, "Uninitialized domain Id"); return status; } *domainIdSoftAp = pMac->scan.domainIdCurrent; status = eHAL_STATUS_SUCCESS; return status; } eHalStatus sme_setRegInfo(tHalHandle hHal, tANI_U8 *apCntryCode) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SET_REGINFO, NO_SESSION, 0)); if (NULL == apCntryCode ) { smsLog( pMac, LOGE, "Empty Country Code, nothing to update"); return status; } status = csrSetRegInfo(hHal, apCntryCode ); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrSetRegInfo failed with status=%d", status ); } return status; } #ifdef FEATURE_WLAN_SCAN_PNO /*-------------------------------------------------------------------------- \brief sme_UpdateChannelConfig() - Update channel configuration in RIVA. It is used at driver start up to inform RIVA of the default channel configuration. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update the channel config successfully. Other status means SME is failed to update the channel config. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateChannelConfig(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_UPDATE_CHANNEL_CONFIG, NO_SESSION, 0)); pmcUpdateScanParams( pMac, &(pMac->roam.configParam), &pMac->scan.base20MHzChannels, FALSE); return eHAL_STATUS_SUCCESS; } #endif // FEATURE_WLAN_SCAN_PNLO eHalStatus sme_UpdateChannelList(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = csrUpdateChannelList(pMac); if (eHAL_STATUS_SUCCESS != status) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "failed to update the supported channel list"); } return status; } /*-------------------------------------------------------------------------- \brief sme_UpdateConfig() - Change configurations for all SME moduels The function updates some configuration for modules in SME, CCM, CSR, etc during SMEs close open sequence. Modules inside SME apply the new configuration at the next transaction. This is a synchronous call \param hHal - The handle returned by macOpen. \Param pSmeConfigParams - a pointer to a caller allocated object of typedef struct _smeConfigParams. \return eHAL_STATUS_SUCCESS - SME update the config parameters successfully. Other status means SME is failed to update the config parameters. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateConfig(tHalHandle hHal, tpSmeConfigParams pSmeConfigParams) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_UPDATE_CONFIG, NO_SESSION, 0)); if (NULL == pSmeConfigParams ) { smsLog( pMac, LOGE, "Empty config param structure for SME, nothing to update"); return status; } status = csrChangeDefaultConfigParam(pMac, &pSmeConfigParams->csrConfig); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrChangeDefaultConfigParam failed with status=%d", status ); } #if defined WLAN_FEATURE_P2P_INTERNAL status = p2pChangeDefaultConfigParam(pMac, &pSmeConfigParams->p2pConfig); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "p2pChangeDefaultConfigParam failed with status=%d", status ); } #endif #if defined WLAN_FEATURE_VOWIFI status = rrmChangeDefaultConfigParam(hHal, &pSmeConfigParams->rrmConfig); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "rrmChangeDefaultConfigParam failed with status=%d", status ); } #endif //For SOC, CFG is set before start //We don't want to apply global CFG in connect state because that may cause some side affect if( csrIsAllSessionDisconnected( pMac) ) { csrSetGlobalCfgs(pMac); } /* update the directed scan offload setting */ pMac->fScanOffload = pSmeConfigParams->fScanOffload; if (pMac->fScanOffload) { /* If scan offload is enabled then lim has allow the sending of scan request to firmware even in powersave mode. The firmware has to take care of exiting from power save mode */ status = ccmCfgSetInt(hHal, WNI_CFG_SCAN_IN_POWERSAVE, eANI_BOOLEAN_TRUE, NULL, eANI_BOOLEAN_FALSE); if (eHAL_STATUS_SUCCESS != status) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "Could not pass on WNI_CFG_SCAN_IN_POWERSAVE to CCM"); } } pMac->isCoalesingInIBSSAllowed = pSmeConfigParams->csrConfig.isCoalesingInIBSSAllowed; pMac->fEnableDebugLog = pSmeConfigParams->fEnableDebugLog; pMac->fDeferIMPSTime = pSmeConfigParams->fDeferIMPSTime; pMac->fBtcEnableIndTimerVal = pSmeConfigParams->fBtcEnableIndTimerVal; return status; } #ifdef WLAN_FEATURE_GTK_OFFLOAD void sme_ProcessGetGtkInfoRsp( tHalHandle hHal, tpSirGtkOffloadGetInfoRspParams pGtkOffloadGetInfoRsp) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return ; } if (pMac->pmc.GtkOffloadGetInfoCB == NULL) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: HDD callback is null", __func__); return ; } pMac->pmc.GtkOffloadGetInfoCB(pMac->pmc.GtkOffloadGetInfoCBContext, pGtkOffloadGetInfoRsp); } #endif /* --------------------------------------------------------------------------- \fn sme_ChangeConfigParams \brief The SME API exposed for HDD to provide config params to SME during SMEs stop -> start sequence. If HDD changed the domain that will cause a reset. This function will provide the new set of 11d information for the new domain. Currrently this API provides info regarding 11d only at reset but we can extend this for other params (PMC, QoS) which needs to be initialized again at reset. This is a synchronous call \param hHal - The handle returned by macOpen. \Param pUpdateConfigParam - a pointer to a structure (tCsrUpdateConfigParam) that currently provides 11d related information like Country code, Regulatory domain, valid channel list, Tx power per channel, a list with active/passive scan allowed per valid channel. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_ChangeConfigParams(tHalHandle hHal, tCsrUpdateConfigParam *pUpdateConfigParam) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (NULL == pUpdateConfigParam ) { smsLog( pMac, LOGE, "Empty config param structure for SME, nothing to reset"); return status; } status = csrChangeConfigParams(pMac, pUpdateConfigParam); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrUpdateConfigParam failed with status=%d", status ); } return status; } /*-------------------------------------------------------------------------- \brief sme_HDDReadyInd() - SME sends eWNI_SME_SYS_READY_IND to PE to inform that the NIC is ready tio run. The function is called by HDD at the end of initialization stage so PE/HAL can enable the NIC to running state. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - eWNI_SME_SYS_READY_IND is sent to PE successfully. Other status means SME failed to send the message to PE. \sa --------------------------------------------------------------------------*/ eHalStatus sme_HDDReadyInd(tHalHandle hHal) { tSirSmeReadyReq Msg; eHalStatus status = eHAL_STATUS_FAILURE; tPmcPowerState powerState; tPmcSwitchState hwWlanSwitchState; tPmcSwitchState swWlanSwitchState; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_HDDREADYIND, NO_SESSION, 0)); do { Msg.messageType = eWNI_SME_SYS_READY_IND; Msg.length = sizeof( tSirSmeReadyReq ); if (eSIR_FAILURE != uMacPostCtrlMsg( hHal, (tSirMbMsg*)&Msg )) { status = eHAL_STATUS_SUCCESS; } else { smsLog( pMac, LOGE, "uMacPostCtrlMsg failed to send eWNI_SME_SYS_READY_IND"); break; } status = pmcQueryPowerState( hHal, &powerState, &hwWlanSwitchState, &swWlanSwitchState ); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "pmcQueryPowerState failed with status=%d", status ); break; } if ( (ePMC_SWITCH_OFF != hwWlanSwitchState) && (ePMC_SWITCH_OFF != swWlanSwitchState) ) { status = csrReady(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrReady failed with status=%d", status ); break; } status = pmcReady(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "pmcReady failed with status=%d", status ); break; } #ifndef WLAN_MDM_CODE_REDUCTION_OPT if(VOS_STATUS_SUCCESS != btcReady(hHal)) { status = eHAL_STATUS_FAILURE; smsLog( pMac, LOGE, "btcReady failed"); break; } #endif #if defined WLAN_FEATURE_VOWIFI if(VOS_STATUS_SUCCESS != rrmReady(hHal)) { status = eHAL_STATUS_FAILURE; smsLog( pMac, LOGE, "rrmReady failed"); break; } #endif } pMac->sme.state = SME_STATE_READY; } while( 0 ); return status; } /** * sme_set_allowed_action_frames() - Set allowed action frames to FW * * @hal: Handler to HAL * * This function conveys the list of action frames that needs to be forwarded * to driver by FW. Rest of the action frames can be dropped in FW.Bitmask is * set with ALLOWED_ACTION_FRAMES_BITMAP * * Return: None */ static void sme_set_allowed_action_frames(tHalHandle hal) { eHalStatus status; tpAniSirGlobal mac = PMAC_STRUCT(hal); vos_msg_t vos_message; VOS_STATUS vos_status; struct sir_allowed_action_frames *sir_allowed_action_frames; sir_allowed_action_frames = vos_mem_malloc(sizeof(*sir_allowed_action_frames)); if (!sir_allowed_action_frames) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "Not able to allocate memory for WDA_SET_ALLOWED_ACTION_FRAMES_IND"); return; } vos_mem_zero(sir_allowed_action_frames, sizeof(*sir_allowed_action_frames)); sir_allowed_action_frames->bitmask = ALLOWED_ACTION_FRAMES_BITMAP; sir_allowed_action_frames->reserved = 0; status = sme_AcquireGlobalLock(&mac->sme); if (status == eHAL_STATUS_SUCCESS) { /* serialize the req through MC thread */ vos_message.bodyptr = sir_allowed_action_frames; vos_message.type = WDA_SET_ALLOWED_ACTION_FRAMES_IND; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vos_message.type)); vos_status = vos_mq_post_message(VOS_MQ_ID_WDA, &vos_message); if (!VOS_IS_STATUS_SUCCESS(vos_status)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "Not able to post WDA_SET_ALLOWED_ACTION_FRAMES_IND message to HAL"); vos_mem_free(sir_allowed_action_frames); } sme_ReleaseGlobalLock( &mac->sme ); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(sir_allowed_action_frames); } return; } /*-------------------------------------------------------------------------- \brief sme_Start() - Put all SME modules at ready state. The function starts each module in SME, PMC, CCM, CSR, etc. . Upon successfully return, all modules are ready to run. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME is ready. Other status means SME is failed to start \sa --------------------------------------------------------------------------*/ eHalStatus sme_Start(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); do { status = csrStart(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrStart failed during smeStart with status=%d", status ); break; } status = pmcStart(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "pmcStart failed during smeStart with status=%d", status ); break; } status = WLANSAP_Start(vos_get_global_context(VOS_MODULE_ID_SAP, NULL)); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "WLANSAP_Start failed during smeStart with status=%d", status ); break; } pMac->sme.state = SME_STATE_START; }while (0); sme_set_allowed_action_frames(hHal); return status; } #ifdef WLAN_FEATURE_PACKET_FILTERING /****************************************************************************** * * Name: sme_PCFilterMatchCountResponseHandler * * Description: * Invoke Packet Coalescing Filter Match Count callback routine * * Parameters: * hHal - HAL handle for device * pMsg - Pointer to tRcvFltPktMatchRsp structure * * Returns: eHalStatus * ******************************************************************************/ eHalStatus sme_PCFilterMatchCountResponseHandler(tHalHandle hHal, void* pMsg) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tpSirRcvFltPktMatchRsp pRcvFltPktMatchRsp = (tpSirRcvFltPktMatchRsp)pMsg; if (NULL == pMsg) { smsLog(pMac, LOGE, "in %s msg ptr is NULL", __func__); status = eHAL_STATUS_FAILURE; } else { smsLog(pMac, LOG2, "SME: entering " "sme_FilterMatchCountResponseHandler"); /* Call Packet Coalescing Filter Match Count callback routine. */ if (pMac->pmc.FilterMatchCountCB != NULL) pMac->pmc.FilterMatchCountCB(pMac->pmc.FilterMatchCountCBContext, pRcvFltPktMatchRsp); smsLog(pMac, LOG1, "%s: status=0x%x", __func__, pRcvFltPktMatchRsp->status); pMac->pmc.FilterMatchCountCB = NULL; pMac->pmc.FilterMatchCountCBContext = NULL; } return(status); } #endif // WLAN_FEATURE_PACKET_FILTERING #ifdef WLAN_FEATURE_11W /*------------------------------------------------------------------ * * Handle the unprotected management frame indication from LIM and * forward it to HDD. * *------------------------------------------------------------------*/ eHalStatus sme_UnprotectedMgmtFrmInd( tHalHandle hHal, tpSirSmeUnprotMgmtFrameInd pSmeMgmtFrm) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tCsrRoamInfo pRoamInfo = {0}; tANI_U32 SessionId = pSmeMgmtFrm->sessionId; pRoamInfo.nFrameLength = pSmeMgmtFrm->frameLen; pRoamInfo.pbFrames = pSmeMgmtFrm->frameBuf; pRoamInfo.frameType = pSmeMgmtFrm->frameType; /* forward the mgmt frame to HDD */ csrRoamCallCallback(pMac, SessionId, &pRoamInfo, 0, eCSR_ROAM_UNPROT_MGMT_FRAME_IND, 0); return status; } #endif #ifdef WLAN_FEATURE_AP_HT40_24G /* --------------------------------------------------------------------------- \fn sme_HT2040CoexInfoInd \brief a Send 20/40 Coex info to SAP layer \param tpSirHT2040CoexInfoInd - 20/40 Coex info param \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_HT2040CoexInfoInd( tHalHandle hHal, tpSirHT2040CoexInfoInd pSmeHT2040CoexInfoInd) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U32 SessionId = pSmeHT2040CoexInfoInd->sessionId; tCsrRoamInfo roamInfo = {0}; roamInfo.pSmeHT2040CoexInfoInd = pSmeHT2040CoexInfoInd; smsLog(pMac, LOGW, FL("HT40MHzIntolerant: %d HT20MHzBssWidthReq: %d"), roamInfo.pSmeHT2040CoexInfoInd->HT40MHzIntolerant, roamInfo.pSmeHT2040CoexInfoInd->HT20MHzBssWidthReq); smsLog(pMac, LOGW, FL("Total Intolerant Channel: %d"), roamInfo.pSmeHT2040CoexInfoInd->channel_num); /* forward the 20/40 BSS Coex information to HDD */ smsLog(pMac, LOGW, FL("Sending eCSR_ROAM_2040_COEX_INFO_IND" " to WLANSAP_RoamCallback ")); csrRoamCallCallback(pMac, SessionId, &roamInfo, 0, eCSR_ROAM_2040_COEX_INFO_IND, 0); return status; } #endif #if defined(FEATURE_WLAN_ESE) && defined(FEATURE_WLAN_ESE_UPLOAD) /*------------------------------------------------------------------ * * Handle the tsm ie indication from LIM and forward it to HDD. * *------------------------------------------------------------------*/ eHalStatus sme_TsmIeInd(tHalHandle hHal, tSirSmeTsmIEInd *pSmeTsmIeInd) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tCsrRoamInfo pRoamInfo = {0}; tANI_U32 SessionId = pSmeTsmIeInd->sessionId; pRoamInfo.tsmIe.tsid= pSmeTsmIeInd->tsmIe.tsid; pRoamInfo.tsmIe.state= pSmeTsmIeInd->tsmIe.state; pRoamInfo.tsmIe.msmt_interval= pSmeTsmIeInd->tsmIe.msmt_interval; /* forward the tsm ie information to HDD */ csrRoamCallCallback(pMac, SessionId, &pRoamInfo, 0, eCSR_ROAM_TSM_IE_IND, 0); return status; } /* --------------------------------------------------------------------------- \fn sme_SetCCKMIe \brief function to store the CCKM IE passed from supplicant and use it while packing reassociation request \param hHal - HAL handle for device \param pCckmIe - pointer to CCKM IE data \param pCckmIeLen - length of the CCKM IE \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_SetCCKMIe(tHalHandle hHal, tANI_U8 sessionId, tANI_U8 *pCckmIe, tANI_U8 cckmIeLen) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { csrSetCCKMIe(pMac, sessionId, pCckmIe, cckmIeLen); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_SetEseBeaconRequest \brief function to set Ese beacon request parameters \param hHal - HAL handle for device \param sessionId - Session id \param pEseBcnReq - pointer to Ese beacon request \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_SetEseBeaconRequest(tHalHandle hHal, const tANI_U8 sessionId, const tCsrEseBeaconReq* pEseBcnReq) { eHalStatus status = eSIR_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tpSirBeaconReportReqInd pSmeBcnReportReq = NULL; tCsrEseBeaconReqParams *pBeaconReq = NULL; tANI_U8 counter = 0; tCsrRoamSession *pSession = CSR_GET_SESSION(pMac, sessionId); tpRrmSMEContext pSmeRrmContext = &pMac->rrm.rrmSmeContext; /* Store the info in RRM context */ vos_mem_copy(&pSmeRrmContext->eseBcnReqInfo, pEseBcnReq, sizeof(tCsrEseBeaconReq)); //Prepare the request to send to SME. pSmeBcnReportReq = vos_mem_malloc(sizeof( tSirBeaconReportReqInd )); if(NULL == pSmeBcnReportReq) { smsLog(pMac, LOGP, "Memory Allocation Failure!!! Ese BcnReq Ind to SME"); return eSIR_FAILURE; } smsLog(pMac, LOGE, "Sending Beacon Report Req to SME"); vos_mem_zero( pSmeBcnReportReq, sizeof( tSirBeaconReportReqInd )); pSmeBcnReportReq->messageType = eWNI_SME_BEACON_REPORT_REQ_IND; pSmeBcnReportReq->length = sizeof( tSirBeaconReportReqInd ); vos_mem_copy( pSmeBcnReportReq->bssId, pSession->connectedProfile.bssid, sizeof(tSirMacAddr) ); pSmeBcnReportReq->channelInfo.channelNum = 255; pSmeBcnReportReq->channelList.numChannels = pEseBcnReq->numBcnReqIe; pSmeBcnReportReq->msgSource = eRRM_MSG_SOURCE_ESE_UPLOAD; for (counter = 0; counter < pEseBcnReq->numBcnReqIe; counter++) { pBeaconReq = (tCsrEseBeaconReqParams *)&pEseBcnReq->bcnReq[counter]; pSmeBcnReportReq->fMeasurementtype[counter] = pBeaconReq->scanMode; pSmeBcnReportReq->measurementDuration[counter] = SYS_TU_TO_MS(pBeaconReq->measurementDuration); pSmeBcnReportReq->channelList.channelNumber[counter] = pBeaconReq->channel; } sme_RrmProcessBeaconReportReqInd(pMac, pSmeBcnReportReq); vos_mem_free(pSmeBcnReportReq); return status; } #endif /* FEATURE_WLAN_ESE && FEATURE_WLAN_ESE_UPLOAD */ #ifdef WLAN_FEATURE_RMC eHalStatus sme_IbssPeerInfoResponseHandleer( tHalHandle hHal, tpSirIbssGetPeerInfoRspParams pIbssPeerInfoParams) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return eHAL_STATUS_FAILURE; } if (pMac->sme.peerInfoParams.peerInfoCbk == NULL) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: HDD callback is null", __func__); return eHAL_STATUS_FAILURE; } pMac->sme.peerInfoParams.peerInfoCbk(pMac->sme.peerInfoParams.pUserData, &pIbssPeerInfoParams->ibssPeerInfoRspParams); return eHAL_STATUS_SUCCESS; } #endif /* WLAN_FEATURE_RMC */ /* --------------------------------------------------------------------------- \fn sme_getBcnMissRate \brief function sends 'WDA_GET_BCN_MISS_RATE_REQ' to WDA layer, \param hHal - HAL handle for device. \param sessionId - session ID. \- return Success or Failure. -------------------------------------------------------------------------*/ eHalStatus sme_getBcnMissRate(tHalHandle hHal, tANI_U8 sessionId, void *callback, void *data) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE; vos_msg_t vosMessage; tSirBcnMissRateReq *pMsg; tCsrRoamSession *pSession; if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { pSession = CSR_GET_SESSION( pMac, sessionId ); if (!pSession) { smsLog(pMac, LOGE, FL("session %d not found"), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg = (tSirBcnMissRateReq *) vos_mem_malloc(sizeof(tSirBcnMissRateReq)); if (NULL == pMsg) { smsLog(pMac, LOGE, FL("failed to allocated memory")); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } vos_mem_copy(pMsg->bssid, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); pMsg->msgLen = sizeof(tSirBcnMissRateReq); pMsg->callback = callback; pMsg->data = data; vosMessage.type = WDA_GET_BCN_MISS_RATE_REQ; vosMessage.bodyptr = pMsg; vosMessage.reserved = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, sessionId, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post Set TM Level MSG fail", __func__); vos_mem_free(pMsg); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme); return eHAL_STATUS_SUCCESS; } return eHAL_STATUS_FAILURE; } eHalStatus sme_EncryptMsgResponseHandler(tHalHandle hHal, tpSirEncryptedDataRspParams pEncRspParams) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return eHAL_STATUS_FAILURE; } if (pMac->sme.pEncMsgInfoParams.pEncMsgCbk == NULL) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: HDD callback is null", __func__); return eHAL_STATUS_FAILURE; } pMac->sme.pEncMsgInfoParams.pEncMsgCbk(pMac->sme.pEncMsgInfoParams.pUserData, &pEncRspParams->encryptedDataRsp); return eHAL_STATUS_SUCCESS; } eHalStatus sme_UpdateMaxRateInd(tHalHandle hHal, tSirSmeUpdateMaxRateParams *pSmeUpdateMaxRateParams) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U8 sessionId = pSmeUpdateMaxRateParams->smeSessionId; /* forward the information to HDD */ status = csrRoamCallCallback(pMac, sessionId, NULL, 0, eCSR_ROAM_UPDATE_MAX_RATE_IND, pSmeUpdateMaxRateParams->maxRateFlag); return status; } /*-------------------------------------------------------------------------- \brief sme_ProcessMsg() - The main message processor for SME. The function is called by a message dispatcher when to process a message targeted for SME. This is a synchronous call \param hHal - The handle returned by macOpen. \param pMsg - A pointer to a caller allocated object of tSirMsgQ. \return eHAL_STATUS_SUCCESS - SME successfully process the message. Other status means SME failed to process the message to HAL. \sa --------------------------------------------------------------------------*/ eHalStatus sme_ProcessMsg(tHalHandle hHal, vos_msg_t* pMsg) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (pMsg == NULL) { smsLog( pMac, LOGE, "Empty message for SME, nothing to process"); return status; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( SME_IS_START(pMac) ) { switch (pMsg->type) { // TODO: Will be modified to do a range check for msgs instead of having cases for each msgs case eWNI_PMC_ENTER_BMPS_RSP: case eWNI_PMC_EXIT_BMPS_RSP: case eWNI_PMC_EXIT_BMPS_IND: case eWNI_PMC_ENTER_IMPS_RSP: case eWNI_PMC_EXIT_IMPS_RSP: case eWNI_PMC_SMPS_STATE_IND: case eWNI_PMC_ENTER_UAPSD_RSP: case eWNI_PMC_EXIT_UAPSD_RSP: case eWNI_PMC_ENTER_WOWL_RSP: case eWNI_PMC_EXIT_WOWL_RSP: //PMC if (pMsg->bodyptr) { pmcMessageProcessor(hHal, pMsg->bodyptr); status = eHAL_STATUS_SUCCESS; vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for PMC, nothing to process"); } break; case WNI_CFG_SET_CNF: case WNI_CFG_DNLD_CNF: case WNI_CFG_GET_RSP: case WNI_CFG_ADD_GRP_ADDR_CNF: case WNI_CFG_DEL_GRP_ADDR_CNF: //CCM if (pMsg->bodyptr) { ccmCfgCnfMsgHandler(hHal, pMsg->bodyptr); status = eHAL_STATUS_SUCCESS; vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for CCM, nothing to process"); } break; case eWNI_SME_ADDTS_RSP: case eWNI_SME_DELTS_RSP: case eWNI_SME_DELTS_IND: #ifdef WLAN_FEATURE_VOWIFI_11R case eWNI_SME_FT_AGGR_QOS_RSP: #endif //QoS if (pMsg->bodyptr) { #ifndef WLAN_MDM_CODE_REDUCTION_OPT status = sme_QosMsgProcessor(pMac, pMsg->type, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); #endif } else { smsLog( pMac, LOGE, "Empty rsp message for QoS, nothing to process"); } break; #if defined WLAN_FEATURE_VOWIFI case eWNI_SME_NEIGHBOR_REPORT_IND: case eWNI_SME_BEACON_REPORT_REQ_IND: #if defined WLAN_VOWIFI_DEBUG smsLog( pMac, LOGE, "Received RRM message. Message Id = %d", pMsg->type ); #endif if ( pMsg->bodyptr ) { status = sme_RrmMsgProcessor( pMac, pMsg->type, pMsg->bodyptr ); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty message for RRM, nothing to process"); } break; #endif #ifdef FEATURE_OEM_DATA_SUPPORT //Handle the eWNI_SME_OEM_DATA_RSP: case eWNI_SME_OEM_DATA_RSP: if(pMsg->bodyptr) { status = sme_HandleOemDataRsp(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for oemData_ (eWNI_SME_OEM_DATA_RSP), nothing to process"); } smeProcessPendingQueue( pMac ); break; #endif case eWNI_SME_ADD_STA_SELF_RSP: if(pMsg->bodyptr) { status = csrProcessAddStaSessionRsp(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for meas (eWNI_SME_ADD_STA_SELF_RSP), nothing to process"); } break; case eWNI_SME_DEL_STA_SELF_RSP: if(pMsg->bodyptr) { status = csrProcessDelStaSessionRsp(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for meas (eWNI_SME_DEL_STA_SELF_RSP), nothing to process"); } break; case eWNI_SME_REMAIN_ON_CHN_RSP: if(pMsg->bodyptr) { status = sme_remainOnChnRsp(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for meas (eWNI_SME_REMAIN_ON_CHN_RSP), nothing to process"); } break; case eWNI_SME_REMAIN_ON_CHN_RDY_IND: if(pMsg->bodyptr) { status = sme_remainOnChnReady(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for meas (eWNI_SME_REMAIN_ON_CHN_RDY_IND), nothing to process"); } break; #ifdef WLAN_FEATURE_AP_HT40_24G case eWNI_SME_2040_COEX_IND: if(pMsg->bodyptr) { sme_HT2040CoexInfoInd(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for meas (eWNI_SME_2040_COEX_IND), nothing to process"); } break; #endif case eWNI_SME_ACTION_FRAME_SEND_CNF: if(pMsg->bodyptr) { status = sme_sendActionCnf(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for meas (eWNI_SME_ACTION_FRAME_SEND_CNF), nothing to process"); } break; case eWNI_SME_COEX_IND: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if(pMsg->bodyptr) { tSirSmeCoexInd *pSmeCoexInd = (tSirSmeCoexInd *)pMsg->bodyptr; if (pSmeCoexInd->coexIndType == SIR_COEX_IND_TYPE_DISABLE_AGGREGATION_IN_2p4) { smsLog( pMac, LOG1, FL("SIR_COEX_IND_TYPE_DISABLE_AGGREGATION_IN_2p4")); sme_RequestFullPower(hHal, NULL, NULL, eSME_REASON_OTHER); pMac->isCoexScoIndSet = 1; } else if (pSmeCoexInd->coexIndType == SIR_COEX_IND_TYPE_ENABLE_AGGREGATION_IN_2p4) { smsLog( pMac, LOG1, FL("SIR_COEX_IND_TYPE_ENABLE_AGGREGATION_IN_2p4")); pMac->isCoexScoIndSet = 0; sme_RequestBmps(hHal, NULL, NULL); } status = btcHandleCoexInd((void *)pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for meas (eWNI_SME_COEX_IND), nothing to process"); } break; #ifdef FEATURE_WLAN_SCAN_PNO case eWNI_SME_PREF_NETWORK_FOUND_IND: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if(pMsg->bodyptr) { status = sme_PreferredNetworkFoundInd((void *)pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for meas (eWNI_SME_PREF_NETWORK_FOUND_IND), nothing to process"); } break; #endif // FEATURE_WLAN_SCAN_PNO case eWNI_SME_TX_PER_HIT_IND: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMac->sme.pTxPerHitCallback) { pMac->sme.pTxPerHitCallback(pMac->sme.pTxPerHitCbContext); } break; case eWNI_SME_CHANGE_COUNTRY_CODE: if(pMsg->bodyptr) { status = sme_HandleChangeCountryCode((void *)pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for message (eWNI_SME_CHANGE_COUNTRY_CODE), nothing to process"); } break; case eWNI_SME_GENERIC_CHANGE_COUNTRY_CODE: if (pMsg->bodyptr) { status = sme_HandleGenericChangeCountryCode((void *)pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for message (eWNI_SME_GENERIC_CHANGE_COUNTRY_CODE), nothing to process"); } break; #ifdef WLAN_FEATURE_PACKET_FILTERING case eWNI_PMC_PACKET_COALESCING_FILTER_MATCH_COUNT_RSP: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if(pMsg->bodyptr) { status = sme_PCFilterMatchCountResponseHandler((void *)pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for meas " "(PACKET_COALESCING_FILTER_MATCH_COUNT_RSP), nothing to process"); } break; #endif // WLAN_FEATURE_PACKET_FILTERING case eWNI_SME_PRE_SWITCH_CHL_IND: { status = sme_HandlePreChannelSwitchInd(pMac); break; } case eWNI_SME_POST_SWITCH_CHL_IND: { status = sme_HandlePostChannelSwitchInd(pMac); break; } #ifdef WLAN_WAKEUP_EVENTS case eWNI_SME_WAKE_REASON_IND: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if(pMsg->bodyptr) { status = sme_WakeReasonIndCallback((void *)pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for meas (eWNI_SME_WAKE_REASON_IND), nothing to process"); } break; #endif // WLAN_WAKEUP_EVENTS #ifdef FEATURE_WLAN_TDLS /* * command rescived from PE, SME tdls msg processor shall be called * to process commands recieved from PE */ case eWNI_SME_TDLS_SEND_MGMT_RSP: case eWNI_SME_TDLS_ADD_STA_RSP: case eWNI_SME_TDLS_DEL_STA_RSP: case eWNI_SME_TDLS_DEL_STA_IND: case eWNI_SME_TDLS_DEL_ALL_PEER_IND: case eWNI_SME_MGMT_FRM_TX_COMPLETION_IND: case eWNI_SME_TDLS_LINK_ESTABLISH_RSP: case eWNI_SME_TDLS_CHANNEL_SWITCH_RSP: { if (pMsg->bodyptr) { status = tdlsMsgProcessor(pMac, pMsg->type, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for TDLS, \ nothing to process"); } break; } #endif #ifdef WLAN_FEATURE_11W case eWNI_SME_UNPROT_MGMT_FRM_IND: if (pMsg->bodyptr) { sme_UnprotectedMgmtFrmInd(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for meas (eWNI_SME_UNPROT_MGMT_FRM_IND), nothing to process"); } break; #endif #if defined(FEATURE_WLAN_ESE) && defined(FEATURE_WLAN_ESE_UPLOAD) case eWNI_SME_TSM_IE_IND: { if (pMsg->bodyptr) { sme_TsmIeInd(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for (eWNI_SME_TSM_IE_IND), nothing to process"); } break; } #endif /* FEATURE_WLAN_ESE && FEATURE_WLAN_ESE_UPLOAD */ #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD case eWNI_SME_ROAM_SCAN_OFFLOAD_RSP: status = csrRoamOffloadScanRspHdlr((void *)pMac, pMsg->bodyval); break; #endif // WLAN_FEATURE_ROAM_SCAN_OFFLOAD #ifdef WLAN_FEATURE_GTK_OFFLOAD case eWNI_PMC_GTK_OFFLOAD_GETINFO_RSP: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMsg->bodyptr) { sme_ProcessGetGtkInfoRsp(pMac, pMsg->bodyptr); vos_mem_zero(pMsg->bodyptr, sizeof(tSirGtkOffloadGetInfoRspParams)); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for (eWNI_PMC_GTK_OFFLOAD_GETINFO_RSP), nothing to process"); } break ; #endif #ifdef FEATURE_WLAN_LPHB /* LPHB timeout indication arrived, send IND to client */ case eWNI_SME_LPHB_IND: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMac->sme.pLphbIndCb) { pMac->sme.pLphbIndCb(pMac->pAdapter, pMsg->bodyptr); } vos_mem_free(pMsg->bodyptr); break; #endif /* FEATURE_WLAN_LPHB */ #ifdef WLAN_FEATURE_RMC case eWNI_SME_IBSS_PEER_INFO_RSP: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMsg->bodyptr) { sme_IbssPeerInfoResponseHandleer(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for (eWNI_SME_IBSS_PEER_INFO_RSP)," " nothing to process"); } break ; #endif /* WLAN_FEATURE_RMC */ #ifdef FEATURE_WLAN_CH_AVOID /* LPHB timeout indication arrived, send IND to client */ case eWNI_SME_CH_AVOID_IND: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMac->sme.pChAvoidNotificationCb) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: CH avoid notification", __func__); pMac->sme.pChAvoidNotificationCb(pMac->pAdapter, pMsg->bodyptr); } vos_mem_free(pMsg->bodyptr); break; #endif /* FEATURE_WLAN_CH_AVOID */ case eWNI_SME_ENCRYPT_MSG_RSP: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMsg->bodyptr) { sme_EncryptMsgResponseHandler(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty rsp message for (eWNI_SME_ENCRYPT_MSG_RSP)," " nothing to process"); } break ; case eWNI_SME_UPDATE_MAX_RATE_IND: if (pMsg->bodyptr) { sme_UpdateMaxRateInd(pMac, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty message for (eWNI_SME_UPDATE_MAX_RATE_IND)," " nothing to process"); } break; case eWNI_SME_NAN_EVENT: MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_WDA_MSG, NO_SESSION, pMsg->type)); if (pMsg->bodyptr) { sme_NanEvent(hHal, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog(pMac, LOGE, "Empty message for (eWNI_SME_NAN_EVENT)," " nothing to process"); } break; default: if ( ( pMsg->type >= eWNI_SME_MSG_TYPES_BEGIN ) && ( pMsg->type <= eWNI_SME_MSG_TYPES_END ) ) { //CSR if (pMsg->bodyptr) { status = csrMsgProcessor(hHal, pMsg->bodyptr); vos_mem_free(pMsg->bodyptr); } else { smsLog( pMac, LOGE, "Empty rsp message for CSR, nothing to process"); } } else { smsLog( pMac, LOGW, "Unknown message type %d, nothing to process", pMsg->type); if (pMsg->bodyptr) { vos_mem_free(pMsg->bodyptr); } } }//switch } //SME_IS_START else { smsLog( pMac, LOGW, "message type %d in stop state ignored", pMsg->type); if (pMsg->bodyptr) { vos_mem_free(pMsg->bodyptr); } } sme_ReleaseGlobalLock( &pMac->sme ); } else { smsLog( pMac, LOGW, "Locking failed, bailing out"); if (pMsg->bodyptr) { vos_mem_free(pMsg->bodyptr); } } return status; } //No need to hold the global lock here because this function can only be called //after sme_Stop. v_VOID_t sme_FreeMsg( tHalHandle hHal, vos_msg_t* pMsg ) { if( pMsg ) { if (pMsg->bodyptr) { vos_mem_free(pMsg->bodyptr); } } } /*-------------------------------------------------------------------------- \brief sme_Stop() - Stop all SME modules and put them at idle state The function stops each module in SME, PMC, CCM, CSR, etc. . Upon return, all modules are at idle state ready to start. This is a synchronous call \param hHal - The handle returned by macOpen \param tHalStopType - reason for stopping \return eHAL_STATUS_SUCCESS - SME is stopped. Other status means SME is failed to stop but caller should still consider SME is stopped. \sa --------------------------------------------------------------------------*/ eHalStatus sme_Stop(tHalHandle hHal, tHalStopType stopType) { eHalStatus status = eHAL_STATUS_FAILURE; eHalStatus fail_status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = WLANSAP_Stop(vos_get_global_context(VOS_MODULE_ID_SAP, NULL)); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "WLANSAP_Stop failed during smeStop with status=%d", status ); fail_status = status; } p2pStop(hHal); status = pmcStop(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "pmcStop failed during smeStop with status=%d", status ); fail_status = status; } status = csrStop(pMac, stopType); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrStop failed during smeStop with status=%d", status ); fail_status = status; } ccmStop(hHal); purgeSmeCmdList(pMac); if (!HAL_STATUS_SUCCESS( fail_status )) { status = fail_status; } pMac->sme.state = SME_STATE_STOP; return status; } /*-------------------------------------------------------------------------- \brief sme_Close() - Release all SME modules and their resources. The function release each module in SME, PMC, CCM, CSR, etc. . Upon return, all modules are at closed state. No SME APIs can be involved after smeClose except smeOpen. smeClose must be called before macClose. This is a synchronous call \param hHal - The handle returned by macOpen \return eHAL_STATUS_SUCCESS - SME is successfully close. Other status means SME is failed to be closed but caller still cannot call any other SME functions except smeOpen. \sa --------------------------------------------------------------------------*/ eHalStatus sme_Close(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; eHalStatus fail_status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = csrClose(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "csrClose failed during sme close with status=%d", status ); fail_status = status; } status = WLANSAP_Close(vos_get_global_context(VOS_MODULE_ID_SAP, NULL)); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "WLANSAP_close failed during sme close with status=%d", status ); fail_status = status; } #ifndef WLAN_MDM_CODE_REDUCTION_OPT status = btcClose(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "BTC close failed during sme close with status=%d", status ); fail_status = status; } status = sme_QosClose(pMac); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "Qos close failed during sme close with status=%d", status ); fail_status = status; } #endif #ifdef FEATURE_OEM_DATA_SUPPORT status = oemData_OemDataReqClose(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "OEM DATA REQ close failed during sme close with status=%d", status ); fail_status = status; } #endif status = ccmClose(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "ccmClose failed during sme close with status=%d", status ); fail_status = status; } status = pmcClose(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "pmcClose failed during sme close with status=%d", status ); fail_status = status; } #if defined WLAN_FEATURE_VOWIFI status = rrmClose(hHal); if ( ! HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, "RRM close failed during sme close with status=%d", status ); fail_status = status; } #endif #if defined WLAN_FEATURE_VOWIFI_11R sme_FTClose(hHal); #endif sme_p2pClose(hHal); freeSmeCmdList(pMac); if( !VOS_IS_STATUS_SUCCESS( vos_lock_destroy( &pMac->sme.lkSmeGlobalLock ) ) ) { fail_status = eHAL_STATUS_FAILURE; } if (!HAL_STATUS_SUCCESS( fail_status )) { status = fail_status; } pMac->sme.state = SME_STATE_STOP; return status; } v_VOID_t sme_PreClose(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if(!pMac) return; smsLog(pMac, LOGW, FL("Stopping Active CMD List Timer")); vos_timer_stop( pMac->sme.smeCmdActiveList.cmdTimeoutTimer ); } #ifdef FEATURE_WLAN_LFR tANI_BOOLEAN csrIsScanAllowed(tpAniSirGlobal pMac) { #if 0 switch(pMac->roam.neighborRoamInfo.neighborRoamState) { case eCSR_NEIGHBOR_ROAM_STATE_REPORT_SCAN: case eCSR_NEIGHBOR_ROAM_STATE_PREAUTHENTICATING: case eCSR_NEIGHBOR_ROAM_STATE_PREAUTH_DONE: case eCSR_NEIGHBOR_ROAM_STATE_REASSOCIATING: return eANI_BOOLEAN_FALSE; default: return eANI_BOOLEAN_TRUE; } #else /* * TODO: always return TRUE for now until * we figure out why we could be stuck in * one of the roaming states forever. */ return eANI_BOOLEAN_TRUE; #endif } #endif /* --------------------------------------------------------------------------- \fn sco_isScanAllowed \brief check for scan interface connection status \param pMac - Pointer to the global MAC parameter structure \param pScanReq - scan request structure. \return tANI_BOOLEAN TRUE to allow scan otherwise FALSE ---------------------------------------------------------------------------*/ tANI_BOOLEAN sco_isScanAllowed(tpAniSirGlobal pMac, tCsrScanRequest *pscanReq) { tANI_BOOLEAN ret; if (pscanReq->p2pSearch) ret = csrIsP2pSessionConnected(pMac); else ret = csrIsStaSessionConnected(pMac); return !ret; } /* --------------------------------------------------------------------------- \fn sme_ScanRequest \brief a wrapper function to Request a 11d or full scan from CSR. This is an asynchronous call \param pScanRequestID - pointer to an object to get back the request ID \param callback - a callback function that scan calls upon finish, will not be called if csrScanRequest returns error \param pContext - a pointer passed in for the callback \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_ScanRequest(tHalHandle hHal, tANI_U8 sessionId, tCsrScanRequest *pscanReq, tANI_U32 *pScanRequestID, csrScanCompleteCallback callback, void *pContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_REQ, sessionId, pscanReq->scanType)); smsLog(pMac, LOG2, FL("enter")); do { if(pMac->scan.fScanEnable && (pMac->isCoexScoIndSet ? sco_isScanAllowed(pMac, pscanReq) : TRUE)) { status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { { #ifdef FEATURE_WLAN_LFR if(csrIsScanAllowed(pMac)) { #endif status = csrScanRequest( hHal, sessionId, pscanReq, pScanRequestID, callback, pContext ); if ( !HAL_STATUS_SUCCESS( status ) ) { smsLog(pMac, LOGE, FL("csrScanRequest failed" " SId=%d"), sessionId); } #ifdef FEATURE_WLAN_LFR } else { smsLog(pMac, LOGE, FL("Scan denied in state %s" "(sub-state %s)"), macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState), macTraceGetcsrRoamSubState( pMac->roam.curSubState[sessionId])); /*HandOff is in progress. So schedule this scan later*/ status = eHAL_STATUS_RESOURCES; } #endif } sme_ReleaseGlobalLock( &pMac->sme ); } //sme_AcquireGlobalLock success else { smsLog(pMac, LOGE, FL("sme_AcquireGlobalLock failed")); } } //if(pMac->scan.fScanEnable) else { smsLog(pMac, LOGE, FL("fScanEnable %d isCoexScoIndSet: %d "), pMac->scan.fScanEnable, pMac->isCoexScoIndSet); status = eHAL_STATUS_RESOURCES; } } while( 0 ); return (status); } /* --------------------------------------------------------------------------- \fn sme_ScanGetResult \brief a wrapper function to request scan results from CSR. This is a synchronous call \param pFilter - If pFilter is NULL, all cached results are returned \param phResult - an object for the result. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_ScanGetResult(tHalHandle hHal, tANI_U8 sessionId, tCsrScanResultFilter *pFilter, tScanResultHandle *phResult) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_GET_RESULTS, sessionId,0 )); smsLog(pMac, LOG2, FL("enter")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanGetResult( hHal, pFilter, phResult ); sme_ReleaseGlobalLock( &pMac->sme ); } smsLog(pMac, LOG2, FL("exit status %d"), status); return (status); } /* --------------------------------------------------------------------------- \fn sme_ScanFlushResult \brief a wrapper function to request CSR to clear scan results. This is a synchronous call \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_ScanFlushResult(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_FLUSH_RESULTS, sessionId,0 )); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanFlushResult( hHal ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_FilterScanResults \brief a wrapper function to request CSR to clear scan results. This is a synchronous call \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_FilterScanResults(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(macTraceNew(pMac, VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_FLUSH_RESULTS, sessionId,0 )); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { csrScanFilterResults(pMac); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* * --------------------------------------------------------------------------- * \fn sme_FilterScanDFSResults * \brief a wrapper function to request CSR to filter BSSIDs on DFS channels * from the scan results. * \return eHalStatus *--------------------------------------------------------------------------- */ eHalStatus sme_FilterScanDFSResults(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { csrScanFilterDFSResults(pMac); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } eHalStatus sme_ScanFlushP2PResult(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_FLUSH_P2PRESULTS, sessionId,0 )); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanFlushSelectiveResult( hHal, VOS_TRUE ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_ScanResultGetFirst \brief a wrapper function to request CSR to returns the first element of scan result. This is a synchronous call \param hScanResult - returned from csrScanGetResult \return tCsrScanResultInfo * - NULL if no result ---------------------------------------------------------------------------*/ tCsrScanResultInfo *sme_ScanResultGetFirst(tHalHandle hHal, tScanResultHandle hScanResult) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tCsrScanResultInfo *pRet = NULL; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_RESULT_GETFIRST, NO_SESSION,0 )); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pRet = csrScanResultGetFirst( pMac, hScanResult ); sme_ReleaseGlobalLock( &pMac->sme ); } return (pRet); } /* --------------------------------------------------------------------------- \fn sme_ScanResultGetNext \brief a wrapper function to request CSR to returns the next element of scan result. It can be called without calling csrScanResultGetFirst first This is a synchronous call \param hScanResult - returned from csrScanGetResult \return Null if no result or reach the end ---------------------------------------------------------------------------*/ tCsrScanResultInfo *sme_ScanResultGetNext(tHalHandle hHal, tScanResultHandle hScanResult) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tCsrScanResultInfo *pRet = NULL; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pRet = csrScanResultGetNext( pMac, hScanResult ); sme_ReleaseGlobalLock( &pMac->sme ); } return (pRet); } /* --------------------------------------------------------------------------- \fn sme_ScanSetBGScanparams \brief a wrapper function to request CSR to set BG scan params in PE This is a synchronous call \param pScanReq - BG scan request structure \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_ScanSetBGScanparams(tHalHandle hHal, tANI_U8 sessionId, tCsrBGScanRequest *pScanReq) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if( NULL != pScanReq ) { status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanSetBGScanparams( hHal, pScanReq ); sme_ReleaseGlobalLock( &pMac->sme ); } } return (status); } /* --------------------------------------------------------------------------- \fn sme_ScanResultPurge \brief a wrapper function to request CSR to remove all items(tCsrScanResult) in the list and free memory for each item This is a synchronous call \param hScanResult - returned from csrScanGetResult. hScanResult is considered gone by calling this function and even before this function reutrns. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_ScanResultPurge(tHalHandle hHal, tScanResultHandle hScanResult) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_SCAN_RESULT_PURGE, NO_SESSION,0 )); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanResultPurge( hHal, hScanResult ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_ScanGetPMKIDCandidateList \brief a wrapper function to return the PMKID candidate list This is a synchronous call \param pPmkidList - caller allocated buffer point to an array of tPmkidCandidateInfo \param pNumItems - pointer to a variable that has the number of tPmkidCandidateInfo allocated when retruning, this is either the number needed or number of items put into pPmkidList \return eHalStatus - when fail, it usually means the buffer allocated is not big enough and pNumItems has the number of tPmkidCandidateInfo. \Note: pNumItems is a number of tPmkidCandidateInfo, not sizeof(tPmkidCandidateInfo) * something ---------------------------------------------------------------------------*/ eHalStatus sme_ScanGetPMKIDCandidateList(tHalHandle hHal, tANI_U8 sessionId, tPmkidCandidateInfo *pPmkidList, tANI_U32 *pNumItems ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanGetPMKIDCandidateList( pMac, sessionId, pPmkidList, pNumItems ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /*---------------------------------------------------------------------------- \fn sme_RoamRegisterLinkQualityIndCallback \brief a wrapper function to allow HDD to register a callback handler with CSR for link quality indications. Only one callback may be registered at any time. In order to deregister the callback, a NULL cback may be provided. Registration happens in the task context of the caller. \param callback - Call back being registered \param pContext - user data DEPENDENCIES: After CSR open \return eHalStatus -----------------------------------------------------------------------------*/ eHalStatus sme_RoamRegisterLinkQualityIndCallback(tHalHandle hHal, tANI_U8 sessionId, csrRoamLinkQualityIndCallback callback, void *pContext) { return(csrRoamRegisterLinkQualityIndCallback((tpAniSirGlobal)hHal, callback, pContext)); } /* --------------------------------------------------------------------------- \fn sme_RoamRegisterCallback \brief a wrapper function to allow HDD to register a callback with CSR. Unlike scan, roam has one callback for all the roam requests \param callback - a callback function that roam calls upon when state changes \param pContext - a pointer passed in for the callback \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_RoamRegisterCallback(tHalHandle hHal, csrRoamCompleteCallback callback, void *pContext) { return(csrRoamRegisterCallback((tpAniSirGlobal)hHal, callback, pContext)); } eCsrPhyMode sme_GetPhyMode(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); return pMac->roam.configParam.phyMode; } /* --------------------------------------------------------------------------- \fn sme_GetChannelBondingMode5G \brief get the channel bonding mode for 5G band \param hHal - HAL handle \return channel bonding mode for 5G ---------------------------------------------------------------------------*/ tANI_U32 sme_GetChannelBondingMode5G(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tSmeConfigParams smeConfig; sme_GetConfigParam(pMac, &smeConfig); return smeConfig.csrConfig.channelBondingMode5GHz; } #ifdef WLAN_FEATURE_AP_HT40_24G /* --------------------------------------------------------------------------- \fn sme_GetChannelBondingMode24G \brief get the channel bonding mode for 2.4G band \param hHal - HAL handle \return channel bonding mode for 2.4G ---------------------------------------------------------------------------*/ tANI_U32 sme_GetChannelBondingMode24G(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tSmeConfigParams smeConfig; sme_GetConfigParam(pMac, &smeConfig); return smeConfig.csrConfig.channelBondingAPMode24GHz; } /* --------------------------------------------------------------------------- \fn sme_UpdateChannelBondingMode24G \brief update the channel bonding mode for 2.4G band \param hHal - HAL handle \param cbMode - channel bonding mode \return ---------------------------------------------------------------------------*/ void sme_UpdateChannelBondingMode24G(tHalHandle hHal, tANI_U8 cbMode) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tSmeConfigParams smeConfig; vos_mem_zero(&smeConfig, sizeof (tSmeConfigParams)); sme_GetConfigParam(pMac, &smeConfig); VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO, FL("Previous Channel Bonding : = %d"), smeConfig.csrConfig.channelBondingAPMode24GHz); smeConfig.csrConfig.channelBondingAPMode24GHz = cbMode; sme_UpdateConfig(hHal, &smeConfig); VOS_TRACE( VOS_MODULE_ID_SAP, VOS_TRACE_LEVEL_INFO, FL("New Channel Bonding : = %d"), sme_GetChannelBondingMode24G(hHal)); return; } /* --------------------------------------------------------------------------- \fn sme_SetHT2040Mode \brief To update HT Operation beacon IE & Channel Bonding. \param \return eHalStatus SUCCESS FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_SetHT2040Mode(tHalHandle hHal, tANI_U8 sessionId, tANI_U8 cbMode) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL("Channel Bonding =%d"), cbMode); status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { status = csrSetHT2040Mode(pMac, sessionId, cbMode); sme_ReleaseGlobalLock(&pMac->sme ); } return (status); } #endif /* --------------------------------------------------------------------------- \fn sme_RoamConnect \brief a wrapper function to request CSR to inititiate an association This is an asynchronous call. \param sessionId - the sessionId returned by sme_OpenSession. \param pProfile - description of the network to which to connect \param hBssListIn - a list of BSS descriptor to roam to. It is returned from csrScanGetResult \param pRoamId - to get back the request ID \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_RoamConnect(tHalHandle hHal, tANI_U8 sessionId, tCsrRoamProfile *pProfile, tANI_U32 *pRoamId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (!pMac) { return eHAL_STATUS_FAILURE; } MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_CONNECT, sessionId, 0)); smsLog(pMac, LOG2, FL("enter")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamConnect( pMac, sessionId, pProfile, NULL, pRoamId ); } else { smsLog(pMac, LOGE, FL("invalid sessionID %d"), sessionId); status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } else { smsLog(pMac, LOGE, FL("sme_AcquireGlobalLock failed")); } return (status); } /* --------------------------------------------------------------------------- \fn sme_SetPhyMode \brief Changes the PhyMode. \param hHal - The handle returned by macOpen. \param phyMode new phyMode which is to set \return eHalStatus SUCCESS. -------------------------------------------------------------------------------*/ eHalStatus sme_SetPhyMode(tHalHandle hHal, eCsrPhyMode phyMode) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: invalid context", __func__); return eHAL_STATUS_FAILURE; } pMac->roam.configParam.phyMode = phyMode; pMac->roam.configParam.uCfgDot11Mode = csrGetCfgDot11ModeFromCsrPhyMode(NULL, pMac->roam.configParam.phyMode, pMac->roam.configParam.ProprietaryRatesEnabled); return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn sme_RoamReassoc \brief a wrapper function to request CSR to inititiate a re-association \param pProfile - can be NULL to join the currently connected AP. In that case modProfileFields should carry the modified field(s) which could trigger reassoc \param modProfileFields - fields which are part of tCsrRoamConnectedProfile that might need modification dynamically once STA is up & running and this could trigger a reassoc \param pRoamId - to get back the request ID \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_RoamReassoc(tHalHandle hHal, tANI_U8 sessionId, tCsrRoamProfile *pProfile, tCsrRoamModifyProfileFields modProfileFields, tANI_U32 *pRoamId, v_BOOL_t fForce) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ROAM_REASSOC, sessionId, 0)); smsLog(pMac, LOG2, FL("enter")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { if((NULL == pProfile) && (fForce == 1)) { tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); /* to force the AP initiate fresh 802.1x authentication need to clear * the PMKID cache for that set the following boolean. this is needed * by the HS 2.0 passpoint certification 5.2.a and b testcases */ pSession->fIgnorePMKIDCache = TRUE; status = csrReassoc( pMac, sessionId, &modProfileFields, pRoamId , fForce); } else { status = csrRoamReassoc( pMac, sessionId, pProfile, modProfileFields, pRoamId ); } } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamConnectToLastProfile \brief a wrapper function to request CSR to disconnect and reconnect with the same profile This is an asynchronous call. \return eHalStatus. It returns fail if currently connected ---------------------------------------------------------------------------*/ eHalStatus sme_RoamConnectToLastProfile(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamConnectToLastProfile( pMac, sessionId ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamDisconnect \brief a wrapper function to request CSR to disconnect from a network This is an asynchronous call. \param reason -- To indicate the reason for disconnecting. Currently, only eCSR_DISCONNECT_REASON_MIC_ERROR is meanful. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_RoamDisconnect(tHalHandle hHal, tANI_U8 sessionId, eCsrRoamDisconnectReason reason) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ROAM_DISCONNECT, sessionId, reason)); smsLog(pMac, LOG2, FL("enter")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamDisconnect( pMac, sessionId, reason ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn.sme_abortConnection \brief a wrapper function to request CSR to stop from connecting a network \retun void. ---------------------------------------------------------------------------*/ void sme_abortConnection(tHalHandle hHal, tANI_U8 sessionId) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_FAILURE; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { csr_abortConnection( pMac, sessionId); } sme_ReleaseGlobalLock( &pMac->sme ); } return; } /* sme_dhcp_done_ind() - send dhcp done ind * @hal: hal context * @session_id: session id * * Return: void. */ void sme_dhcp_done_ind(tHalHandle hal, uint8_t session_id) { tpAniSirGlobal mac_ctx = PMAC_STRUCT(hal); tCsrRoamSession *session; if (!mac_ctx) return; session = CSR_GET_SESSION(mac_ctx, session_id); if(!session) { smsLog(mac_ctx, LOGE, FL(" session %d not found "), session_id); return; } session->dhcp_done = true; } /* --------------------------------------------------------------------------- \fn sme_RoamStopBss \brief To stop BSS for Soft AP. This is an asynchronous API. \param hHal - Global structure \param sessionId - sessionId of SoftAP \return eHalStatus SUCCESS Roam callback will be called to indicate actual results -------------------------------------------------------------------------------*/ eHalStatus sme_RoamStopBss(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); smsLog(pMac, LOG2, FL("enter")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamIssueStopBssCmd( pMac, sessionId, eANI_BOOLEAN_FALSE ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamDisconnectSta \brief To disassociate a station. This is an asynchronous API. \param hHal - Global structure \param sessionId - sessionId of SoftAP \param pPeerMacAddr - Caller allocated memory filled with peer MAC address (6 bytes) \return eHalStatus SUCCESS Roam callback will be called to indicate actual results -------------------------------------------------------------------------------*/ eHalStatus sme_RoamDisconnectSta(tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tANI_U8 *pPeerMacAddr #else tANI_U8 *pPeerMacAddr #endif ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if ( NULL == pMac ) { VOS_ASSERT(0); return status; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamIssueDisassociateStaCmd( pMac, sessionId, pPeerMacAddr, eSIR_MAC_DEAUTH_LEAVING_BSS_REASON); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamDeauthSta \brief To disassociate a station. This is an asynchronous API. \param hHal - Global structure \param sessionId - sessionId of SoftAP \param pDelStaParams -Pointer to parameters of the station to deauthenticate \return eHalStatus SUCCESS Roam callback will be called to indicate actual results -------------------------------------------------------------------------------*/ eHalStatus sme_RoamDeauthSta(tHalHandle hHal, tANI_U8 sessionId, struct tagCsrDelStaParams *pDelStaParams) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if ( NULL == pMac ) { VOS_ASSERT(0); return status; } MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_MSG_DEAUTH_STA, sessionId, pDelStaParams->reason_code)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamIssueDeauthStaCmd( pMac, sessionId, pDelStaParams); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamTKIPCounterMeasures \brief To start or stop TKIP counter measures. This is an asynchronous API. \param sessionId - sessionId of SoftAP \param pPeerMacAddr - Caller allocated memory filled with peer MAC address (6 bytes) \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_RoamTKIPCounterMeasures(tHalHandle hHal, tANI_U8 sessionId, tANI_BOOLEAN bEnable) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if ( NULL == pMac ) { VOS_ASSERT(0); return status; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamIssueTkipCounterMeasures( pMac, sessionId, bEnable); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetAssociatedStas \brief To probe the list of associated stations from various modules of CORE stack. \This is an asynchronous API. \param sessionId - sessionId of SoftAP \param modId - Module from whom list of associtated stations is to be probed. If an invalid module is passed then by default VOS_MODULE_ID_PE will be probed \param pUsrContext - Opaque HDD context \param pfnSapEventCallback - Sap event callback in HDD \param pAssocBuf - Caller allocated memory to be filled with associatd stations info \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_RoamGetAssociatedStas(tHalHandle hHal, tANI_U8 sessionId, VOS_MODULE_ID modId, void *pUsrContext, void *pfnSapEventCallback, tANI_U8 *pAssocStasBuf) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if ( NULL == pMac ) { VOS_ASSERT(0); return status; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetAssociatedStas( pMac, sessionId, modId, pUsrContext, pfnSapEventCallback, pAssocStasBuf ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetWpsSessionOverlap \brief To get the WPS PBC session overlap information. \This is an asynchronous API. \param sessionId - sessionId of SoftAP \param pUsrContext - Opaque HDD context \param pfnSapEventCallback - Sap event callback in HDD \pRemoveMac - pointer to Mac address which needs to be removed from session \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_RoamGetWpsSessionOverlap(tHalHandle hHal, tANI_U8 sessionId, void *pUsrContext, void *pfnSapEventCallback, v_MACADDR_t pRemoveMac) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if ( NULL == pMac ) { VOS_ASSERT(0); return status; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetWpsSessionOverlap( pMac, sessionId, pUsrContext, pfnSapEventCallback, pRemoveMac); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetConnectState \brief a wrapper function to request CSR to return the current connect state of Roaming This is a synchronous call. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_RoamGetConnectState(tHalHandle hHal, tANI_U8 sessionId, eCsrConnectState *pState) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetConnectState( pMac, sessionId, pState ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetConnectProfile \brief a wrapper function to request CSR to return the current connect profile. Caller must call csrRoamFreeConnectProfile after it is done and before reuse for another csrRoamGetConnectProfile call. This is a synchronous call. \param pProfile - pointer to a caller allocated structure tCsrRoamConnectedProfile \return eHalStatus. Failure if not connected ---------------------------------------------------------------------------*/ eHalStatus sme_RoamGetConnectProfile(tHalHandle hHal, tANI_U8 sessionId, tCsrRoamConnectedProfile *pProfile) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ROAM_GET_CONNECTPROFILE, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetConnectProfile( pMac, sessionId, pProfile ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamFreeConnectProfile \brief a wrapper function to request CSR to free and reinitialize the profile returned previously by csrRoamGetConnectProfile. This is a synchronous call. \param pProfile - pointer to a caller allocated structure tCsrRoamConnectedProfile \return eHalStatus. ---------------------------------------------------------------------------*/ eHalStatus sme_RoamFreeConnectProfile(tHalHandle hHal, tCsrRoamConnectedProfile *pProfile) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ROAM_FREE_CONNECTPROFILE, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrRoamFreeConnectProfile( pMac, pProfile ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamSetPMKIDCache \brief a wrapper function to request CSR to return the PMKID candidate list This is a synchronous call. \param pPMKIDCache - caller allocated buffer point to an array of tPmkidCacheInfo \param numItems - a variable that has the number of tPmkidCacheInfo allocated when retruning, this is either the number needed or number of items put into pPMKIDCache \param update_entire_cache - this bool value specifies if the entire pmkid cache should be overwritten or should it be updated entry by entry. \return eHalStatus - when fail, it usually means the buffer allocated is not big enough and pNumItems has the number of tPmkidCacheInfo. \Note: pNumItems is a number of tPmkidCacheInfo, not sizeof(tPmkidCacheInfo) * something ---------------------------------------------------------------------------*/ eHalStatus sme_RoamSetPMKIDCache( tHalHandle hHal, tANI_U8 sessionId, tPmkidCacheInfo *pPMKIDCache, tANI_U32 numItems, tANI_BOOLEAN update_entire_cache ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ROAM_SET_PMKIDCACHE, sessionId, numItems)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamSetPMKIDCache( pMac, sessionId, pPMKIDCache, numItems, update_entire_cache ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } eHalStatus sme_RoamDelPMKIDfromCache( tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tANI_U8 *pBSSId, #else tANI_U8 *pBSSId, #endif tANI_BOOLEAN flush_cache ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ROAM_DEL_PMKIDCACHE, sessionId, flush_cache)); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamDelPMKIDfromCache( pMac, sessionId, pBSSId, flush_cache ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetSecurityReqIE \brief a wrapper function to request CSR to return the WPA or RSN or WAPI IE CSR passes to PE to JOIN request or START_BSS request This is a synchronous call. \param pLen - caller allocated memory that has the length of pBuf as input. Upon returned, *pLen has the needed or IE length in pBuf. \param pBuf - Caller allocated memory that contain the IE field, if any, upon return \param secType - Specifies whether looking for WPA/WPA2/WAPI IE \return eHalStatus - when fail, it usually means the buffer allocated is not big enough ---------------------------------------------------------------------------*/ eHalStatus sme_RoamGetSecurityReqIE(tHalHandle hHal, tANI_U8 sessionId, tANI_U32 *pLen, tANI_U8 *pBuf, eCsrSecurityType secType) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetWpaRsnReqIE( hHal, sessionId, pLen, pBuf ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetSecurityRspIE \brief a wrapper function to request CSR to return the WPA or RSN or WAPI IE from the beacon or probe rsp if connected This is a synchronous call. \param pLen - caller allocated memory that has the length of pBuf as input. Upon returned, *pLen has the needed or IE length in pBuf. \param pBuf - Caller allocated memory that contain the IE field, if any, upon return \param secType - Specifies whether looking for WPA/WPA2/WAPI IE \return eHalStatus - when fail, it usually means the buffer allocated is not big enough ---------------------------------------------------------------------------*/ eHalStatus sme_RoamGetSecurityRspIE(tHalHandle hHal, tANI_U8 sessionId, tANI_U32 *pLen, tANI_U8 *pBuf, eCsrSecurityType secType) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetWpaRsnRspIE( pMac, sessionId, pLen, pBuf ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetNumPMKIDCache \brief a wrapper function to request CSR to return number of PMKID cache entries This is a synchronous call. \return tANI_U32 - the number of PMKID cache entries ---------------------------------------------------------------------------*/ tANI_U32 sme_RoamGetNumPMKIDCache(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_U32 numPmkidCache = 0; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { numPmkidCache = csrRoamGetNumPMKIDCache( pMac, sessionId ); status = eHAL_STATUS_SUCCESS; } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (numPmkidCache); } /* --------------------------------------------------------------------------- \fn sme_RoamGetPMKIDCache \brief a wrapper function to request CSR to return PMKID cache from CSR This is a synchronous call. \param pNum - caller allocated memory that has the space of the number of pBuf tPmkidCacheInfo as input. Upon returned, *pNum has the needed or actually number in tPmkidCacheInfo. \param pPmkidCache - Caller allocated memory that contains PMKID cache, if any, upon return \return eHalStatus - when fail, it usually means the buffer allocated is not big enough ---------------------------------------------------------------------------*/ eHalStatus sme_RoamGetPMKIDCache(tHalHandle hHal, tANI_U8 sessionId, tANI_U32 *pNum, tPmkidCacheInfo *pPmkidCache) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrRoamGetPMKIDCache( pMac, sessionId, pNum, pPmkidCache ); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetConfigParam \brief a wrapper function that HDD calls to get the global settings currently maintained by CSR. This is a synchronous call. \param pParam - caller allocated memory \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetConfigParam(tHalHandle hHal, tSmeConfigParams *pParam) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_CONFIGPARAM, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetConfigParam(pMac, &pParam->csrConfig); if (status != eHAL_STATUS_SUCCESS) { smsLog( pMac, LOGE, "%s csrGetConfigParam failed", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return status; } #if defined WLAN_FEATURE_P2P_INTERNAL status = p2pGetConfigParam(pMac, &pParam->p2pConfig); if (status != eHAL_STATUS_SUCCESS) { smsLog( pMac, LOGE, "%s p2pGetConfigParam failed", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return status; } #endif pParam->fBtcEnableIndTimerVal = pMac->fBtcEnableIndTimerVal; sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_CfgSetInt \brief a wrapper function that HDD calls to set parameters in CFG. This is a synchronous call. \param cfgId - Configuration Parameter ID (type) for STA. \param ccmValue - The information related to Configuration Parameter ID which needs to be saved in CFG \param callback - To be registered by CSR with CCM. Once the CFG done with saving the information in the database, it notifies CCM & then the callback will be invoked to notify. \param toBeSaved - To save the request for future reference \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_CfgSetInt(tHalHandle hHal, tANI_U32 cfgId, tANI_U32 ccmValue, tCcmCfgSetCallback callback, eAniBoolean toBeSaved) { return(ccmCfgSetInt(hHal, cfgId, ccmValue, callback, toBeSaved)); } /* --------------------------------------------------------------------------- \fn sme_CfgSetStr \brief a wrapper function that HDD calls to set parameters in CFG. This is a synchronous call. \param cfgId - Configuration Parameter ID (type) for STA. \param pStr - Pointer to the byte array which carries the information needs to be saved in CFG \param length - Length of the data to be saved \param callback - To be registered by CSR with CCM. Once the CFG done with saving the information in the database, it notifies CCM & then the callback will be invoked to notify. \param toBeSaved - To save the request for future reference \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_CfgSetStr(tHalHandle hHal, tANI_U32 cfgId, tANI_U8 *pStr, tANI_U32 length, tCcmCfgSetCallback callback, eAniBoolean toBeSaved) { return(ccmCfgSetStr(hHal, cfgId, pStr, length, callback, toBeSaved)); } /* --------------------------------------------------------------------------- \fn sme_GetModifyProfileFields \brief HDD or SME - QOS calls this function to get the current values of connected profile fields, changing which can cause reassoc. This function must be called after CFG is downloaded and STA is in connected state. Also, make sure to call this function to get the current profile fields before calling the reassoc. So that pModifyProfileFields will have all the latest values plus the one(s) has been updated as part of reassoc request. \param pModifyProfileFields - pointer to the connected profile fields changing which can cause reassoc \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_GetModifyProfileFields(tHalHandle hHal, tANI_U8 sessionId, tCsrRoamModifyProfileFields * pModifyProfileFields) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_MODPROFFIELDS, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { status = csrGetModifyProfileFields(pMac, sessionId, pModifyProfileFields); } else { status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_HT40StopOBSSScan \brief HDD or SME - Command to stop the OBSS scan THis is implemented only for debugging purpose. As per spec while operating in 2.4GHz OBSS scan shouldnt be stopped. \param sessionId - sessionId changing which can cause reassoc \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_HT40StopOBSSScan(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); smsLog(pMac, LOG2, FL("enter")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if( CSR_IS_SESSION_VALID( pMac, sessionId ) ) { csrHT40StopOBSSScan( pMac, sessionId ); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Invalid session sessionId %d", __func__,sessionId); status = eHAL_STATUS_INVALID_PARAMETER; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /*-------------------------------------------------------------------------- \fn sme_SetConfigPowerSave \brief Wrapper fn to change power save configuration in SME (PMC) module. For BMPS related configuration, this function also updates the CFG and sends a message to FW to pick up the new values. Note: Calling this function only updates the configuration and does not enable the specified power save mode. \param hHal - The handle returned by macOpen. \param psMode - Power Saving mode being modified \param pConfigParams - a pointer to a caller allocated object of type tPmcSmpsConfigParams or tPmcBmpsConfigParams or tPmcImpsConfigParams \return eHalStatus --------------------------------------------------------------------------*/ eHalStatus sme_SetConfigPowerSave(tHalHandle hHal, tPmcPowerSavingMode psMode, void *pConfigParams) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_CONFIG_PWRSAVE, NO_SESSION, 0)); if (NULL == pConfigParams ) { smsLog( pMac, LOGE, "Empty config param structure for PMC, " "nothing to update"); return eHAL_STATUS_FAILURE; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcSetConfigPowerSave(hHal, psMode, pConfigParams); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /*-------------------------------------------------------------------------- \fn sme_GetConfigPowerSave \brief Wrapper fn to retrieve power save configuration in SME (PMC) module \param hHal - The handle returned by macOpen. \param psMode - Power Saving mode \param pConfigParams - a pointer to a caller allocated object of type tPmcSmpsConfigParams or tPmcBmpsConfigParams or tPmcImpsConfigParams \return eHalStatus --------------------------------------------------------------------------*/ eHalStatus sme_GetConfigPowerSave(tHalHandle hHal, tPmcPowerSavingMode psMode, void *pConfigParams) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_CONFIG_PWRSAVE, NO_SESSION, 0)); if (NULL == pConfigParams ) { smsLog( pMac, LOGE, "Empty config param structure for PMC, " "nothing to update"); return eHAL_STATUS_FAILURE; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcGetConfigPowerSave(hHal, psMode, pConfigParams); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_SignalPowerEvent \brief Signals to PMC that a power event has occurred. Used for putting the chip into deep sleep mode. \param hHal - The handle returned by macOpen. \param event - the event that has occurred \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SignalPowerEvent (tHalHandle hHal, tPmcPowerEvent event) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcSignalPowerEvent(hHal, event); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_EnablePowerSave \brief Enables one of the power saving modes. \param hHal - The handle returned by macOpen. \param psMode - The power saving mode to enable. If BMPS mode is enabled while the chip is operating in Full Power, PMC will start a timer that will try to put the chip in BMPS mode after expiry. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_EnablePowerSave (tHalHandle hHal, tPmcPowerSavingMode psMode) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ENABLE_PWRSAVE, NO_SESSION, psMode)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcEnablePowerSave(hHal, psMode); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_DisablePowerSave \brief Disables one of the power saving modes. \param hHal - The handle returned by macOpen. \param psMode - The power saving mode to disable. Disabling does not imply that device will be brought out of the current PS mode. This is purely a configuration API. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_DisablePowerSave (tHalHandle hHal, tPmcPowerSavingMode psMode) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_DISABLE_PWRSAVE, NO_SESSION, psMode)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcDisablePowerSave(hHal, psMode); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- + \fn sme_SetHostPowerSave + \brief Enables BMPS logic to be controlled by User level apps + \param hHal - The handle returned by macOpen. + \param psMode - The power saving mode to disable. Disabling does not imply + that device will be brought out of the current PS mode. This + is purely a configuration API. + \return eHalStatus + ---------------------------------------------------------------------------*/ eHalStatus sme_SetHostPowerSave (tHalHandle hHal, v_BOOL_t psMode) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); pMac->pmc.isHostPsEn = psMode; return (status); } /* --------------------------------------------------------------------------- \fn sme_StartAutoBmpsTimer \brief Starts a timer that periodically polls all the registered module for entry into Bmps mode. This timer is started only if BMPS is enabled and whenever the device is in full power. \param hHal - The handle returned by macOpen. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_StartAutoBmpsTimer ( tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_START_AUTO_BMPSTIMER, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcStartAutoBmpsTimer(hHal); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_StopAutoBmpsTimer \brief Stops the Auto BMPS Timer that was started using sme_startAutoBmpsTimer Stopping the timer does not cause a device state change. Only the timer is stopped. If "Full Power" is desired, use the sme_RequestFullPower API \param hHal - The handle returned by macOpen. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_StopAutoBmpsTimer ( tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_STOP_AUTO_BMPSTIMER, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcStopAutoBmpsTimer(hHal); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_QueryPowerState \brief Returns the current power state of the device. \param hHal - The handle returned by macOpen. \param pPowerState - pointer to location to return power state (LOW or HIGH) \param pSwWlanSwitchState - ptr to location to return SW WLAN Switch state \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_QueryPowerState ( tHalHandle hHal, tPmcPowerState *pPowerState, tPmcSwitchState *pSwWlanSwitchState) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcQueryPowerState (hHal, pPowerState, NULL, pSwWlanSwitchState); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_IsPowerSaveEnabled \brief Checks if the device is able to enter a particular power save mode This does not imply that the device is in a particular PS mode \param hHal - The handle returned by macOpen. \param psMode - the power saving mode \return eHalStatus ---------------------------------------------------------------------------*/ tANI_BOOLEAN sme_IsPowerSaveEnabled (tHalHandle hHal, tPmcPowerSavingMode psMode) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_BOOLEAN result = false; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_IS_PWRSAVE_ENABLED, NO_SESSION, psMode)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { result = pmcIsPowerSaveEnabled(hHal, psMode); sme_ReleaseGlobalLock( &pMac->sme ); return result; } return false; } /* --------------------------------------------------------------------------- \fn sme_RequestFullPower \brief Request that the device be brought to full power state. When the device enters Full Power PMC will start a BMPS timer if BMPS PS mode is enabled. On timer expiry PMC will attempt to put the device in BMPS mode if following holds true: - BMPS mode is enabled - Polling of all modules through the Power Save Check routine passes - STA is associated to an access point \param hHal - The handle returned by macOpen. \param - callbackRoutine Callback routine invoked in case of success/failure \return eHalStatus - status eHAL_STATUS_SUCCESS - device brought to full power state eHAL_STATUS_FAILURE - device cannot be brought to full power state eHAL_STATUS_PMC_PENDING - device is being brought to full power state, ---------------------------------------------------------------------------*/ eHalStatus sme_RequestFullPower ( tHalHandle hHal, void (*callbackRoutine) (void *callbackContext, eHalStatus status), void *callbackContext, tRequestFullPowerReason fullPowerReason) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_REQUEST_FULLPOWER, NO_SESSION, fullPowerReason)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRequestFullPower(hHal, callbackRoutine, callbackContext, fullPowerReason); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RequestBmps \brief Request that the device be put in BMPS state. Request will be accepted only if BMPS mode is enabled and power save check routine passes. \param hHal - The handle returned by macOpen. \param - callbackRoutine Callback routine invoked in case of success/failure \return eHalStatus eHAL_STATUS_SUCCESS - device is in BMPS state eHAL_STATUS_FAILURE - device cannot be brought to BMPS state eHAL_STATUS_PMC_PENDING - device is being brought to BMPS state ---------------------------------------------------------------------------*/ eHalStatus sme_RequestBmps ( tHalHandle hHal, void (*callbackRoutine) (void *callbackContext, eHalStatus status), void *callbackContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_REQUEST_BMPS, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRequestBmps(hHal, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_SetDHCPTillPowerActiveFlag \brief Sets/Clears DHCP related flag in PMC to disable/enable auto BMPS entry by PMC \param hHal - The handle returned by macOpen. ---------------------------------------------------------------------------*/ void sme_SetDHCPTillPowerActiveFlag(tHalHandle hHal, tANI_U8 flag) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_DHCP_FLAG, NO_SESSION, flag)); // Set/Clear the DHCP flag which will disable/enable auto BMPS entery by PMC pMac->pmc.remainInPowerActiveTillDHCP = flag; } /* --------------------------------------------------------------------------- \fn sme_StartUapsd \brief Request that the device be put in UAPSD state. If the device is in Full Power it will be put in BMPS mode first and then into UAPSD mode. \param hHal - The handle returned by macOpen. \param - callbackRoutine Callback routine invoked in case of success/failure eHAL_STATUS_SUCCESS - device is in UAPSD state eHAL_STATUS_FAILURE - device cannot be brought to UAPSD state eHAL_STATUS_PMC_PENDING - device is being brought to UAPSD state eHAL_STATUS_PMC_DISABLED - UAPSD is disabled or BMPS mode is disabled \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_StartUapsd ( tHalHandle hHal, void (*callbackRoutine) (void *callbackContext, eHalStatus status), void *callbackContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcStartUapsd(hHal, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_StopUapsd \brief Request that the device be put out of UAPSD state. Device will be put in in BMPS state after stop UAPSD completes. \param hHal - The handle returned by macOpen. \return eHalStatus eHAL_STATUS_SUCCESS - device is put out of UAPSD and back in BMPS state eHAL_STATUS_FAILURE - device cannot be brought out of UAPSD state ---------------------------------------------------------------------------*/ eHalStatus sme_StopUapsd (tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcStopUapsd(hHal); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RequestStandby \brief Request that the device be put in standby. It is HDD's responsibility to bring the chip to full power and do a disassoc before calling this API. \param hHal - The handle returned by macOpen. \param - callbackRoutine Callback routine invoked in case of success/failure \return eHalStatus eHAL_STATUS_SUCCESS - device is in Standby mode eHAL_STATUS_FAILURE - device cannot be put in standby mode eHAL_STATUS_PMC_PENDING - device is being put in standby mode ---------------------------------------------------------------------------*/ eHalStatus sme_RequestStandby ( tHalHandle hHal, void (*callbackRoutine) (void *callbackContext, eHalStatus status), void *callbackContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_REQUEST_STANDBY, NO_SESSION, 0)); smsLog( pMac, LOG1, FL(" called") ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRequestStandby(hHal, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RegisterPowerSaveCheck \brief Register a power save check routine that is called whenever the device is about to enter one of the power save modes. \param hHal - The handle returned by macOpen. \param checkRoutine - Power save check routine to be registered \return eHalStatus eHAL_STATUS_SUCCESS - successfully registered eHAL_STATUS_FAILURE - not successfully registered ---------------------------------------------------------------------------*/ eHalStatus sme_RegisterPowerSaveCheck ( tHalHandle hHal, tANI_BOOLEAN (*checkRoutine) (void *checkContext), void *checkContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRegisterPowerSaveCheck (hHal, checkRoutine, checkContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_Register11dScanDoneCallback \brief Register a routine of type csrScanCompleteCallback which is called whenever an 11d scan is done \param hHal - The handle returned by macOpen. \param callback - 11d scan complete routine to be registered \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_Register11dScanDoneCallback ( tHalHandle hHal, csrScanCompleteCallback callback) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); pMac->scan.callback11dScanDone = callback; return (status); } /* --------------------------------------------------------------------------- \fn sme_DeregisterPowerSaveCheck \brief Deregister a power save check routine \param hHal - The handle returned by macOpen. \param checkRoutine - Power save check routine to be deregistered \return eHalStatus eHAL_STATUS_SUCCESS - successfully deregistered eHAL_STATUS_FAILURE - not successfully deregistered ---------------------------------------------------------------------------*/ eHalStatus sme_DeregisterPowerSaveCheck ( tHalHandle hHal, tANI_BOOLEAN (*checkRoutine) (void *checkContext)) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcDeregisterPowerSaveCheck (hHal, checkRoutine); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RegisterDeviceStateUpdateInd \brief Register a callback routine that is called whenever the device enters a new device state (Full Power, BMPS, UAPSD) \param hHal - The handle returned by macOpen. \param callbackRoutine - Callback routine to be registered \param callbackContext - Cookie to be passed back during callback \return eHalStatus eHAL_STATUS_SUCCESS - successfully registered eHAL_STATUS_FAILURE - not successfully registered ---------------------------------------------------------------------------*/ eHalStatus sme_RegisterDeviceStateUpdateInd ( tHalHandle hHal, void (*callbackRoutine) (void *callbackContext, tPmcState pmcState), void *callbackContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRegisterDeviceStateUpdateInd (hHal, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_DeregisterDeviceStateUpdateInd \brief Deregister a routine that was registered for device state changes \param hHal - The handle returned by macOpen. \param callbackRoutine - Callback routine to be deregistered \return eHalStatus eHAL_STATUS_SUCCESS - successfully deregistered eHAL_STATUS_FAILURE - not successfully deregistered ---------------------------------------------------------------------------*/ eHalStatus sme_DeregisterDeviceStateUpdateInd ( tHalHandle hHal, void (*callbackRoutine) (void *callbackContext, tPmcState pmcState)) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcDeregisterDeviceStateUpdateInd (hHal, callbackRoutine); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_WowlAddBcastPattern \brief Add a pattern for Pattern Byte Matching in Wowl mode. Firmware will do a pattern match on these patterns when Wowl is enabled during BMPS mode. Note that Firmware performs the pattern matching only on broadcast frames and while Libra is in BMPS mode. \param hHal - The handle returned by macOpen. \param pattern - Pattern to be added \return eHalStatus eHAL_STATUS_FAILURE Cannot add pattern eHAL_STATUS_SUCCESS Request accepted. ---------------------------------------------------------------------------*/ eHalStatus sme_WowlAddBcastPattern ( tHalHandle hHal, tpSirWowlAddBcastPtrn pattern, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_WOWL_ADDBCAST_PATTERN, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcWowlAddBcastPattern (hHal, pattern, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_WowlDelBcastPattern \brief Delete a pattern that was added for Pattern Byte Matching. \param hHal - The handle returned by macOpen. \param pattern - Pattern to be deleted \return eHalStatus eHAL_STATUS_FAILURE Cannot delete pattern eHAL_STATUS_SUCCESS Request accepted. ---------------------------------------------------------------------------*/ eHalStatus sme_WowlDelBcastPattern ( tHalHandle hHal, tpSirWowlDelBcastPtrn pattern, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_WOWL_DELBCAST_PATTERN, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcWowlDelBcastPattern (hHal, pattern, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_EnterWowl \brief This is the SME API exposed to HDD to request enabling of WOWL mode. WoWLAN works on top of BMPS mode. If the device is not in BMPS mode, SME will will cache the information that WOWL has been enabled and attempt to put the device in BMPS. On entry into BMPS, SME will enable the WOWL mode. Note 1: If we exit BMPS mode (someone requests full power), we will NOT resume WOWL when we go back to BMPS again. Request for full power (while in WOWL mode) means disable WOWL and go to full power. Note 2: Both UAPSD and WOWL work on top of BMPS. On entry into BMPS, SME will give priority to UAPSD and enable only UAPSD if both UAPSD and WOWL are required. Currently there is no requirement or use case to support UAPSD and WOWL at the same time. \param hHal - The handle returned by macOpen. \param enterWowlCallbackRoutine - Callback routine provided by HDD. Used for success/failure notification by SME \param enterWowlCallbackContext - A cookie passed by HDD, that is passed back to HDD at the time of callback. \param wakeReasonIndCB - Callback routine provided by HDD. Used for Wake Reason Indication by SME \param wakeReasonIndCBContext - A cookie passed by HDD, that is passed back to HDD at the time of callback. \return eHalStatus eHAL_STATUS_SUCCESS Device is already in WoWLAN mode eHAL_STATUS_FAILURE Device cannot enter WoWLAN mode. eHAL_STATUS_PMC_PENDING Request accepted. SME will enable WOWL after BMPS mode is entered. ---------------------------------------------------------------------------*/ eHalStatus sme_EnterWowl ( tHalHandle hHal, void (*enterWowlCallbackRoutine) (void *callbackContext, eHalStatus status), void *enterWowlCallbackContext, #ifdef WLAN_WAKEUP_EVENTS void (*wakeIndicationCB) (void *callbackContext, tpSirWakeReasonInd pWakeReasonInd), void *wakeIndicationCBContext, #endif // WLAN_WAKEUP_EVENTS tpSirSmeWowlEnterParams wowlEnterParams, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ENTER_WOWL, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcEnterWowl (hHal, enterWowlCallbackRoutine, enterWowlCallbackContext, #ifdef WLAN_WAKEUP_EVENTS wakeIndicationCB, wakeIndicationCBContext, #endif // WLAN_WAKEUP_EVENTS wowlEnterParams, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_ExitWowl \brief This is the SME API exposed to HDD to request exit from WoWLAN mode. SME will initiate exit from WoWLAN mode and device will be put in BMPS mode. \param hHal - The handle returned by macOpen. \return eHalStatus eHAL_STATUS_FAILURE Device cannot exit WoWLAN mode. eHAL_STATUS_SUCCESS Request accepted to exit WoWLAN mode. ---------------------------------------------------------------------------*/ eHalStatus sme_ExitWowl (tHalHandle hHal, tWowlExitSource wowlExitSrc) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXIT_WOWL, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcExitWowl (hHal, wowlExitSrc); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamSetKey \brief To set encryption key. This function should be called only when connected This is an asynchronous API. \param pSetKeyInfo - pointer to a caller allocated object of tCsrSetContextInfo \param pRoamId Upon success return, this is the id caller can use to identify the request in roamcallback \return eHalStatus SUCCESS Roam callback will be called indicate actually results FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_RoamSetKey(tHalHandle hHal, tANI_U8 sessionId, tCsrRoamSetKey *pSetKey, tANI_U32 *pRoamId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_U32 roamId; tANI_U32 i; tCsrRoamSession *pSession = NULL; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_KEY, sessionId, 0)); if (pSetKey->keyLength > CSR_MAX_KEY_LEN) { smsLog(pMac, LOGE, FL("Invalid key length %d"), pSetKey->keyLength); return eHAL_STATUS_FAILURE; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { roamId = GET_NEXT_ROAM_ID(&pMac->roam); if(pRoamId) { *pRoamId = roamId; } smsLog(pMac, LOG2, FL("keyLength %d"), pSetKey->keyLength); for(i=0; i<pSetKey->keyLength; i++) smsLog(pMac, LOG2, FL("%02x"), pSetKey->Key[i]); smsLog(pMac, LOG2, "\n sessionId=%d roamId=%d", sessionId, roamId); pSession = CSR_GET_SESSION(pMac, sessionId); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } if(CSR_IS_INFRA_AP(&pSession->connectedProfile)) { if(pSetKey->keyDirection == eSIR_TX_DEFAULT) { if ( ( eCSR_ENCRYPT_TYPE_WEP40 == pSetKey->encType ) || ( eCSR_ENCRYPT_TYPE_WEP40_STATICKEY == pSetKey->encType )) { pSession->pCurRoamProfile->negotiatedUCEncryptionType = eCSR_ENCRYPT_TYPE_WEP40_STATICKEY; } if ( ( eCSR_ENCRYPT_TYPE_WEP104 == pSetKey->encType ) || ( eCSR_ENCRYPT_TYPE_WEP104_STATICKEY == pSetKey->encType )) { pSession->pCurRoamProfile->negotiatedUCEncryptionType = eCSR_ENCRYPT_TYPE_WEP104_STATICKEY; } } } status = csrRoamSetKey ( pMac, sessionId, pSetKey, roamId ); sme_ReleaseGlobalLock( &pMac->sme ); } if (pMac->roam.configParam.roamDelayStatsEnabled) { //Store sent PTK key time if(pSetKey->keyDirection == eSIR_TX_RX) { vos_record_roam_event(e_HDD_SET_PTK_REQ, NULL, 0); } else if(pSetKey->keyDirection == eSIR_RX_ONLY) { vos_record_roam_event(e_HDD_SET_GTK_REQ, NULL, 0); } else { return (status); } } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamRemoveKey \brief To set encryption key. This is an asynchronous API. \param pRemoveKey - pointer to a caller allocated object of tCsrRoamRemoveKey \param pRoamId Upon success return, this is the id caller can use to identify the request in roamcallback \return eHalStatus SUCCESS Roam callback will be called indicate actually results FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_RoamRemoveKey(tHalHandle hHal, tANI_U8 sessionId, tCsrRoamRemoveKey *pRemoveKey, tANI_U32 *pRoamId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_U32 roamId; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_REMOVE_KEY, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { roamId = GET_NEXT_ROAM_ID(&pMac->roam); if(pRoamId) { *pRoamId = roamId; } status = csrRoamIssueRemoveKeyCommand( pMac, sessionId, pRemoveKey, roamId ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetRssi \brief a wrapper function that client calls to register a callback to get RSSI \param callback - SME sends back the requested stats using the callback \param staId - The station ID for which the stats is requested for \param pContext - user context to be passed back along with the callback \param pVosContext - vos context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetRssi(tHalHandle hHal, tCsrRssiCallback callback, tANI_U8 staId, tCsrBssid bssId, void *pContext, void* pVosContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetRssi( pMac, callback, staId, bssId, pContext, pVosContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetSnr \brief a wrapper function that client calls to register a callback to get SNR \param callback - SME sends back the requested stats using the callback \param staId - The station ID for which the stats is requested for \param pContext - user context to be passed back along with the callback \param pVosContext - vos context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetSnr(tHalHandle hHal, tCsrSnrCallback callback, tANI_U8 staId, tCsrBssid bssId, void *pContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetSnr(pMac, callback, staId, bssId, pContext); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } #if defined WLAN_FEATURE_VOWIFI_11R || defined FEATURE_WLAN_ESE || defined(FEATURE_WLAN_LFR) /* --------------------------------------------------------------------------- \fn sme_GetRoamRssi \brief a wrapper function that client calls to register a callback to get Roam RSSI \param callback - SME sends back the requested stats using the callback \param staId - The station ID for which the stats is requested for \param pContext - user context to be passed back along with the callback \param pVosContext - vos context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetRoamRssi(tHalHandle hHal, tCsrRssiCallback callback, tANI_U8 staId, tCsrBssid bssId, void *pContext, void* pVosContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetRoamRssi( pMac, callback, staId, bssId, pContext, pVosContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif #if defined(FEATURE_WLAN_ESE) && defined(FEATURE_WLAN_ESE_UPLOAD) /* --------------------------------------------------------------------------- \fn sme_GetTsmStats \brief a wrapper function that client calls to register a callback to get TSM Stats \param callback - SME sends back the requested stats using the callback \param staId - The station ID for which the stats is requested for \param pContext - user context to be passed back along with the callback \param pVosContext - vos context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetTsmStats(tHalHandle hHal, tCsrTsmStatsCallback callback, tANI_U8 staId, tCsrBssid bssId, void *pContext, void* pVosContext, tANI_U8 tid) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetTsmStats( pMac, callback, staId, bssId, pContext, pVosContext, tid); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif /* --------------------------------------------------------------------------- \fn sme_GetStatistics \brief a wrapper function that client calls to register a callback to get different PHY level statistics from CSR. \param requesterId - different client requesting for statistics, HDD, UMA/GAN etc \param statsMask - The different category/categories of stats requester is looking for \param callback - SME sends back the requested stats using the callback \param periodicity - If requester needs periodic update in millisec, 0 means it's an one time request \param cache - If requester is happy with cached stats \param staId - The station ID for which the stats is requested for \param pContext - user context to be passed back along with the callback \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetStatistics(tHalHandle hHal, eCsrStatsRequesterType requesterId, tANI_U32 statsMask, tCsrStatsCallback callback, tANI_U32 periodicity, tANI_BOOLEAN cache, tANI_U8 staId, void *pContext) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_STATS, NO_SESSION, periodicity)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetStatistics( pMac, requesterId , statsMask, callback, periodicity, cache, staId, pContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } eHalStatus sme_GetFwStats(tHalHandle hHal, tANI_U32 stats, void *pContext, tSirFWStatsCallback callback) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t msg; tSirFWStatsGetReq *pGetFWStatsReq; smsLog(pMac, LOG1, FL(" ENTER stats = %d "),stats); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme )) { pGetFWStatsReq = (tSirFWStatsGetReq *)vos_mem_malloc(sizeof(tSirFWStatsGetReq)); if ( NULL == pGetFWStatsReq) { smsLog(pMac, LOGE, FL("Not able to allocate memory for " "WDA_FW_STATS_GET_REQ")); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pGetFWStatsReq->stats = stats; pGetFWStatsReq->callback = (tSirFWStatsCallback)callback; pGetFWStatsReq->data = pContext; msg.type = WDA_FW_STATS_GET_REQ; msg.reserved = 0; msg.bodyptr = pGetFWStatsReq; if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_WDA, &msg)) { smsLog(pMac, LOGE, FL("Not able to post WDA_FW_STATS_GET_REQ message to HAL")); vos_mem_free(pGetFWStatsReq); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_SUCCESS; } return eHAL_STATUS_FAILURE; } /* --------------------------------------------------------------------------- \fn smeGetTLSTAState \helper function to get the TL STA State whenever the function is called. \param staId - The staID to be passed to the TL to get the relevant TL STA State \return the state as tANI_U16 ---------------------------------------------------------------------------*/ tANI_U16 smeGetTLSTAState(tHalHandle hHal, tANI_U8 staId) { tANI_U16 tlSTAState = TL_INIT_STATE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_FAILURE; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { tlSTAState = csrGetTLSTAState( pMac, staId); sme_ReleaseGlobalLock( &pMac->sme ); } return tlSTAState; } /* --------------------------------------------------------------------------- \fn sme_GetCountryCode \brief To return the current country code. If no country code is applied, default country code is used to fill the buffer. If 11d supported is turned off, an error is return and the last applied/default country code is used. This is a synchronous API. \param pBuf - pointer to a caller allocated buffer for returned country code. \param pbLen For input, this parameter indicates how big is the buffer. Upon return, this parameter has the number of bytes for country. If pBuf doesn't have enough space, this function returns fail status and this parameter contains the number that is needed. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_GetCountryCode(tHalHandle hHal, tANI_U8 *pBuf, tANI_U8 *pbLen) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_CNTRYCODE, NO_SESSION, 0)); return ( csrGetCountryCode( pMac, pBuf, pbLen ) ); } /* --------------------------------------------------------------------------- \fn sme_SetCountryCode \brief To change the current/default country code. If 11d supported is turned off, an error is return. This is a synchronous API. \param pCountry - pointer to a caller allocated buffer for the country code. \param pfRestartNeeded A pointer to caller allocated memory, upon successful return, it indicates whether a reset is required. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_SetCountryCode(tHalHandle hHal, tANI_U8 *pCountry, tANI_BOOLEAN *pfRestartNeeded) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_CNTRYCODE, NO_SESSION, 0)); return ( csrSetCountryCode( pMac, pCountry, pfRestartNeeded ) ); } /* --------------------------------------------------------------------------- \fn sme_ResetCountryCodeInformation \brief this function is to reset the country code current being used back to EEPROM default this includes channel list and power setting. This is a synchronous API. \param pfRestartNeeded - pointer to a caller allocated space. Upon successful return, it indicates whether a restart is needed to apply the change \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_ResetCountryCodeInformation(tHalHandle hHal, tANI_BOOLEAN *pfRestartNeeded) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return ( csrResetCountryCodeInformation( pMac, pfRestartNeeded ) ); } /* --------------------------------------------------------------------------- \fn sme_GetSupportedCountryCode \brief this function is to get a list of the country code current being supported \param pBuf - Caller allocated buffer with at least 3 bytes, upon success return, this has the country code list. 3 bytes for each country code. This may be NULL if caller wants to know the needed byte count. \param pbLen - Caller allocated, as input, it indicates the length of pBuf. Upon success return, this contains the length of the data in pBuf. If pbuf is NULL, as input, *pbLen should be 0. \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_GetSupportedCountryCode(tHalHandle hHal, tANI_U8 *pBuf, tANI_U32 *pbLen) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return ( csrGetSupportedCountryCode( pMac, pBuf, pbLen ) ); } /* --------------------------------------------------------------------------- \fn sme_GetCurrentRegulatoryDomain \brief this function is to get the current regulatory domain. This is a synchronous API. This function must be called after CFG is downloaded and all the band/mode setting already passed into SME. The function fails if 11d support is turned off. \param pDomain - Caller allocated buffer to return the current domain. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_GetCurrentRegulatoryDomain(tHalHandle hHal, v_REGDOMAIN_t *pDomain) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; if( pDomain ) { if( csrIs11dSupported( pMac ) ) { *pDomain = csrGetCurrentRegulatoryDomain( pMac ); status = eHAL_STATUS_SUCCESS; } else { status = eHAL_STATUS_FAILURE; } } return ( status ); } /* --------------------------------------------------------------------------- \fn sme_SetRegulatoryDomain \brief this function is to set the current regulatory domain. This function must be called after CFG is downloaded and all the band/mode setting already passed into SME. This is a synchronous API. \param domainId - indicate the domain (defined in the driver) needs to set to. See v_REGDOMAIN_t for definition \param pfRestartNeeded - pointer to a caller allocated space. Upon successful return, it indicates whether a restart is needed to apply the change \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_SetRegulatoryDomain(tHalHandle hHal, v_REGDOMAIN_t domainId, tANI_BOOLEAN *pfRestartNeeded) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return ( csrSetRegulatoryDomain( pMac, domainId, pfRestartNeeded ) ); } /* --------------------------------------------------------------------------- \fn sme_GetRegulatoryDomainForCountry \brief To return a regulatory domain base on a country code. This is a synchronous API. \param pCountry - pointer to a caller allocated buffer for input country code. \param pDomainId Upon successful return, it is the domain that country belongs to. If it is NULL, returning success means that the country code is known. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_GetRegulatoryDomainForCountry(tHalHandle hHal, tANI_U8 *pCountry, v_REGDOMAIN_t *pDomainId) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return csrGetRegulatoryDomainForCountry(pMac, pCountry, pDomainId, COUNTRY_QUERY); } /* --------------------------------------------------------------------------- \fn sme_GetSupportedRegulatoryDomains \brief To return a list of supported regulatory domains. This is a synchronous API. \param pDomains - pointer to a caller allocated buffer for returned regulatory domains. \param pNumDomains For input, this parameter indicates howm many domains pDomains can hold. Upon return, this parameter has the number for supported domains. If pDomains doesn't have enough space for all the supported domains, this function returns fail status and this parameter contains the number that is needed. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_GetSupportedRegulatoryDomains(tHalHandle hHal, v_REGDOMAIN_t *pDomains, tANI_U32 *pNumDomains) { eHalStatus status = eHAL_STATUS_INVALID_PARAMETER; //We support all domains for now if( pNumDomains ) { if( NUM_REG_DOMAINS <= *pNumDomains ) { status = eHAL_STATUS_SUCCESS; } *pNumDomains = NUM_REG_DOMAINS; } if( HAL_STATUS_SUCCESS( status ) ) { if( pDomains ) { pDomains[0] = REGDOMAIN_FCC; pDomains[1] = REGDOMAIN_ETSI; pDomains[2] = REGDOMAIN_JAPAN; pDomains[3] = REGDOMAIN_WORLD; pDomains[4] = REGDOMAIN_N_AMER_EXC_FCC; pDomains[5] = REGDOMAIN_APAC; pDomains[6] = REGDOMAIN_KOREA; pDomains[7] = REGDOMAIN_HI_5GHZ; pDomains[8] = REGDOMAIN_NO_5GHZ; } else { status = eHAL_STATUS_INVALID_PARAMETER; } } return ( status ); } //some support functions tANI_BOOLEAN sme_Is11dSupported(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return ( csrIs11dSupported( pMac ) ); } tANI_BOOLEAN sme_Is11hSupported(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return ( csrIs11hSupported( pMac ) ); } tANI_BOOLEAN sme_IsWmmSupported(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return ( csrIsWmmSupported( pMac ) ); } //Upper layer to get the list of the base channels to scan for passively 11d info from csr eHalStatus sme_ScanGetBaseChannels( tHalHandle hHal, tCsrChannelInfo * pChannelInfo ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return(csrScanGetBaseChannels(pMac,pChannelInfo) ); } /* --------------------------------------------------------------------------- \fn sme_ChangeCountryCode \brief Change Country code from upperlayer during WLAN driver operation. This is a synchronous API. \param hHal - The handle returned by macOpen. \param pCountry New Country Code String \param sendRegHint If we want to send reg hint to nl80211 \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_ChangeCountryCode( tHalHandle hHal, tSmeChangeCountryCallback callback, tANI_U8 *pCountry, void *pContext, void* pVosContext, tAniBool countryFromUserSpace, tAniBool sendRegHint ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t msg; tAniChangeCountryCodeReq *pMsg; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CHANGE_CNTRYCODE, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { smsLog(pMac, LOG1, FL(" called")); if ((pMac->roam.configParam.Is11dSupportEnabledOriginal == true) && (!pMac->roam.configParam.fSupplicantCountryCodeHasPriority)) { smsLog(pMac, LOGW, "Set Country Code Fail since the STA is associated and userspace does not have priority "); sme_ReleaseGlobalLock( &pMac->sme ); status = eHAL_STATUS_FAILURE; return status; } pMsg = vos_mem_malloc(sizeof(tAniChangeCountryCodeReq)); if ( NULL == pMsg ) { smsLog(pMac, LOGE, " csrChangeCountryCode: failed to allocate mem for req"); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->msgType = pal_cpu_to_be16((tANI_U16)eWNI_SME_CHANGE_COUNTRY_CODE); pMsg->msgLen = (tANI_U16)sizeof(tAniChangeCountryCodeReq); vos_mem_copy(pMsg->countryCode, pCountry, 3); pMsg->countryFromUserSpace = countryFromUserSpace; pMsg->sendRegHint = sendRegHint; pMsg->changeCCCallback = callback; pMsg->pDevContext = pContext; pMsg->pVosContext = pVosContext; msg.type = eWNI_SME_CHANGE_COUNTRY_CODE; msg.bodyptr = pMsg; msg.reserved = 0; if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_SME, &msg)) { smsLog(pMac, LOGE, " sme_ChangeCountryCode failed to post msg to self "); vos_mem_free((void *)pMsg); status = eHAL_STATUS_FAILURE; } smsLog(pMac, LOG1, FL(" returned")); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /*-------------------------------------------------------------------------- \fn sme_GenericChangeCountryCode \brief Change Country code from upperlayer during WLAN driver operation. This is a synchronous API. \param hHal - The handle returned by macOpen. \param pCountry New Country Code String \param reg_domain regulatory domain \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -----------------------------------------------------------------------------*/ eHalStatus sme_GenericChangeCountryCode( tHalHandle hHal, tANI_U8 *pCountry, v_REGDOMAIN_t reg_domain) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t msg; tAniGenericChangeCountryCodeReq *pMsg; if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return status; } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { smsLog(pMac, LOG1, FL(" called")); pMsg = vos_mem_malloc(sizeof(tAniGenericChangeCountryCodeReq)); if (NULL == pMsg) { smsLog(pMac, LOGE, " sme_GenericChangeCountryCode: failed to allocate mem for req"); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->msgType = pal_cpu_to_be16((tANI_U16)eWNI_SME_GENERIC_CHANGE_COUNTRY_CODE); pMsg->msgLen = (tANI_U16)sizeof(tAniGenericChangeCountryCodeReq); vos_mem_copy(pMsg->countryCode, pCountry, 2); pMsg->countryCode[2] = ' '; /* For ASCII space */ pMsg->domain_index = reg_domain; msg.type = eWNI_SME_GENERIC_CHANGE_COUNTRY_CODE; msg.bodyptr = pMsg; msg.reserved = 0; if (VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_SME, &msg)) { smsLog(pMac, LOGE, "sme_GenericChangeCountryCode failed to post msg to self"); vos_mem_free(pMsg); status = eHAL_STATUS_FAILURE; } smsLog(pMac, LOG1, FL(" returned")); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_InitChannels \brief Used to initialize CSR channel lists while driver loading \param hHal - global pMac structure \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_InitChannels(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return status; } status = csrInitChannels(pMac); return status; } #ifdef CONFIG_ENABLE_LINUX_REG /*------------------------------------------------------------------------- \fn sme_InitChannelsForCC \brief Used to issue regulatory hint to user \param hHal - global pMac structure \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. --------------------------------------------------------------------------*/ eHalStatus sme_InitChannelsForCC(tHalHandle hHal, driver_load_type init) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return status; } status = csrInitChannelsForCC(pMac, init); return status; } #endif /* --------------------------------------------------------------------------- \fn sme_DHCPStartInd \brief API to signal the FW about the DHCP Start event. \param hHal - HAL handle for device. \param device_mode - mode(AP,SAP etc) of the device. \param macAddr - MAC address of the device. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. --------------------------------------------------------------------------*/ eHalStatus sme_DHCPStartInd( tHalHandle hHal, tANI_U8 device_mode, tANI_U8 sessionId ) { eHalStatus status; VOS_STATUS vosStatus; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t vosMessage; tAniDHCPInd *pMsg; tCsrRoamSession *pSession; status = sme_AcquireGlobalLock(&pMac->sme); if ( eHAL_STATUS_SUCCESS == status) { pSession = CSR_GET_SESSION( pMac, sessionId ); if (!pSession) { smsLog(pMac, LOGE, FL("session %d not found "), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg = (tAniDHCPInd*)vos_mem_malloc(sizeof(tAniDHCPInd)); if (NULL == pMsg) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for dhcp start", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->msgType = WDA_DHCP_START_IND; pMsg->msgLen = (tANI_U16)sizeof(tAniDHCPInd); pMsg->device_mode = device_mode; vos_mem_copy(pMsg->macAddr, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); vosMessage.type = WDA_DHCP_START_IND; vosMessage.bodyptr = pMsg; vosMessage.reserved = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, sessionId, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post DHCP Start MSG fail", __func__); vos_mem_free(pMsg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_DHCPStopInd \brief API to signal the FW about the DHCP complete event. \param hHal - HAL handle for device. \param device_mode - mode(AP, SAP etc) of the device. \param macAddr - MAC address of the device. \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. --------------------------------------------------------------------------*/ eHalStatus sme_DHCPStopInd( tHalHandle hHal, tANI_U8 device_mode, tANI_U8 sessionId ) { eHalStatus status; VOS_STATUS vosStatus; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t vosMessage; tAniDHCPInd *pMsg; tCsrRoamSession *pSession; status = sme_AcquireGlobalLock(&pMac->sme); if ( eHAL_STATUS_SUCCESS == status) { pSession = CSR_GET_SESSION( pMac, sessionId ); if (!pSession) { smsLog(pMac, LOGE, FL("session %d not found "), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg = (tAniDHCPInd*)vos_mem_malloc(sizeof(tAniDHCPInd)); if (NULL == pMsg) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for dhcp stop", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->msgType = WDA_DHCP_STOP_IND; pMsg->msgLen = (tANI_U16)sizeof(tAniDHCPInd); pMsg->device_mode = device_mode; vos_mem_copy(pMsg->macAddr, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); vosMessage.type = WDA_DHCP_STOP_IND; vosMessage.bodyptr = pMsg; vosMessage.reserved = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, sessionId, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post DHCP Stop MSG fail", __func__); vos_mem_free(pMsg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #ifdef WLAN_FEATURE_RMC /*--------------------------------------------------------------------------- \fn sme_TXFailMonitorStopInd \brief API to signal the FW to start monitoring TX failures \return eHalStatus SUCCESS. FAILURE or RESOURCES The API finished and failed. --------------------------------------------------------------------------*/ eHalStatus sme_TXFailMonitorStartStopInd(tHalHandle hHal, tANI_U8 tx_fail_count, void * txFailIndCallback) { eHalStatus status; VOS_STATUS vosStatus; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tAniTXFailMonitorInd *pMsg; status = sme_AcquireGlobalLock(&pMac->sme); if ( eHAL_STATUS_SUCCESS == status) { pMsg = (tAniTXFailMonitorInd*) vos_mem_malloc(sizeof(tAniTXFailMonitorInd)); if (NULL == pMsg) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Failed to allocate memory", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->msgType = WDA_TX_FAIL_MONITOR_IND; pMsg->msgLen = (tANI_U16)sizeof(tAniTXFailMonitorInd); //tx_fail_count = 0 should disable the Monitoring in FW pMsg->tx_fail_count = tx_fail_count; pMsg->txFailIndCallback = txFailIndCallback; vosMessage.type = WDA_TX_FAIL_MONITOR_IND; vosMessage.bodyptr = pMsg; vosMessage.reserved = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post TX Fail monitor Start MSG fail", __func__); vos_mem_free(pMsg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif /* WLAN_FEATURE_RMC */ #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD void sme_PERRoamScanStartStop(void *hHal, tANI_U8 start) { eHalStatus status; VOS_STATUS vosStatus; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tPERRoamScanStart *pMsg; status = sme_AcquireGlobalLock(&pMac->sme); if ( eHAL_STATUS_SUCCESS == status) { pMsg = (tPERRoamScanStart *) vos_mem_malloc(sizeof(tPERRoamScanStart)); if (NULL == pMsg) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Failed to allocate memory", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return; } pMsg->msgType = WDA_PER_ROAM_SCAN_TRIGGER_REQ; pMsg->msgLen = (tANI_U16)sizeof(*pMsg); pMsg->start = start; vosMessage.type = WDA_PER_ROAM_SCAN_TRIGGER_REQ; vosMessage.bodyptr = pMsg; vosMessage.reserved = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post TX Fail monitor Start MSG fail", __func__); vos_mem_free(pMsg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } } /* sme_set_per_roam_rxconfig : set PER config for Rx monitoring * @hHal: hal pointer * @staId: station id * @minRate : rate at which to start monitoring * @maxRate : Rate at which to stop monitoring * @minPercentage: minimum % of packets required in minRate to trigger a scan * @minPktRequired: minimum number of packets required to trigger a scan * @waitPeriodForNextPERScan: time to wait before start monitoring again once * roam scan is triggered * */ VOS_STATUS sme_set_per_roam_rxconfig (tHalHandle hHal, v_U8_t staId, v_U16_t minRate, v_U16_t maxRate, v_U8_t minPercentage, v_U16_t minPktRequired, v_U64_t waitPeriodForNextPERScan) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); v_VOID_t * pVosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); WLANTL_StartRxRateMonitor(pVosContext, staId, minRate, maxRate, minPercentage, minPktRequired, (void *) hHal, waitPeriodForNextPERScan, sme_PERRoamScanStartStop); pMac->PERroamCandidatesCnt = 0; return eHAL_STATUS_SUCCESS; } /* sme_unset_per_roam_rxconfig : unset PER config for Rx monitoring * */ VOS_STATUS sme_unset_per_roam_rxconfig (tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); v_VOID_t * pVosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); vos_mem_set(pMac->previousRoamApInfo, sizeof(tSirRoamAPInfo) * SIR_PER_ROAM_MAX_CANDIDATE_CNT, 0); WLANTL_StopRxRateMonitor(pVosContext); return eHAL_STATUS_SUCCESS; } #endif /* --------------------------------------------------------------------------- \fn sme_BtcSignalBtEvent \brief API to signal Bluetooth (BT) event to the WLAN driver. Based on the BT event type and the current operating mode of Libra (full power, BMPS, UAPSD etc), appropriate Bluetooth Coexistence (BTC) strategy would be employed. \param hHal - The handle returned by macOpen. \param pBtEvent - Pointer to a caller allocated object of type tSmeBtEvent Caller owns the memory and is responsible for freeing it. \return VOS_STATUS VOS_STATUS_E_FAILURE BT Event not passed to HAL. This can happen if BTC execution mode is set to BTC_WLAN_ONLY or BTC_PTA_ONLY. VOS_STATUS_SUCCESS BT Event passed to HAL ---------------------------------------------------------------------------*/ VOS_STATUS sme_BtcSignalBtEvent (tHalHandle hHal, tpSmeBtEvent pBtEvent) { VOS_STATUS status = VOS_STATUS_E_FAILURE; #ifndef WLAN_MDM_CODE_REDUCTION_OPT tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_BTC_SIGNALEVENT, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { status = btcSignalBTEvent (hHal, pBtEvent); sme_ReleaseGlobalLock( &pMac->sme ); } #endif return (status); } /* --------------------------------------------------------------------------- \fn sme_BtcSetConfig \brief API to change the current Bluetooth Coexistence (BTC) configuration This function should be invoked only after CFG download has completed. Calling it after sme_HDDReadyInd is recommended. \param hHal - The handle returned by macOpen. \param pSmeBtcConfig - Pointer to a caller allocated object of type tSmeBtcConfig. Caller owns the memory and is responsible for freeing it. \return VOS_STATUS VOS_STATUS_E_FAILURE Config not passed to HAL. VOS_STATUS_SUCCESS Config passed to HAL ---------------------------------------------------------------------------*/ VOS_STATUS sme_BtcSetConfig (tHalHandle hHal, tpSmeBtcConfig pSmeBtcConfig) { VOS_STATUS status = VOS_STATUS_E_FAILURE; #ifndef WLAN_MDM_CODE_REDUCTION_OPT tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_BTC_SETCONFIG, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { status = btcSetConfig (hHal, pSmeBtcConfig); sme_ReleaseGlobalLock( &pMac->sme ); } #endif return (status); } /* --------------------------------------------------------------------------- \fn sme_BtcGetConfig \brief API to retrieve the current Bluetooth Coexistence (BTC) configuration \param hHal - The handle returned by macOpen. \param pSmeBtcConfig - Pointer to a caller allocated object of type tSmeBtcConfig. Caller owns the memory and is responsible for freeing it. \return VOS_STATUS VOS_STATUS_E_FAILURE - failure VOS_STATUS_SUCCESS success ---------------------------------------------------------------------------*/ VOS_STATUS sme_BtcGetConfig (tHalHandle hHal, tpSmeBtcConfig pSmeBtcConfig) { VOS_STATUS status = VOS_STATUS_E_FAILURE; #ifndef WLAN_MDM_CODE_REDUCTION_OPT tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_BTC_GETCONFIG, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { status = btcGetConfig (hHal, pSmeBtcConfig); sme_ReleaseGlobalLock( &pMac->sme ); } #endif return (status); } /* --------------------------------------------------------------------------- \fn sme_SetCfgPrivacy \brief API to set configure privacy parameters \param hHal - The handle returned by macOpen. \param pProfile - Pointer CSR Roam profile. \param fPrivacy - This parameter indicates status of privacy \return void ---------------------------------------------------------------------------*/ void sme_SetCfgPrivacy( tHalHandle hHal, tCsrRoamProfile *pProfile, tANI_BOOLEAN fPrivacy ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_CFGPRIVACY, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { csrSetCfgPrivacy(pMac, pProfile, fPrivacy); sme_ReleaseGlobalLock( &pMac->sme ); } } #if defined WLAN_FEATURE_VOWIFI /* --------------------------------------------------------------------------- \fn sme_NeighborReportRequest \brief API to request neighbor report. \param hHal - The handle returned by macOpen. \param pRrmNeighborReq - Pointer to a caller allocated object of type tRrmNeighborReq. Caller owns the memory and is responsible for freeing it. \return VOS_STATUS VOS_STATUS_E_FAILURE - failure VOS_STATUS_SUCCESS success ---------------------------------------------------------------------------*/ VOS_STATUS sme_NeighborReportRequest (tHalHandle hHal, tANI_U8 sessionId, tpRrmNeighborReq pRrmNeighborReq, tpRrmNeighborRspCallbackInfo callbackInfo) { VOS_STATUS status = VOS_STATUS_E_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_NEIGHBOR_REPORTREQ, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { status = sme_RrmNeighborReportRequest (hHal, sessionId, pRrmNeighborReq, callbackInfo); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif //The following are debug APIs to support direct read/write register/memory //They are placed in SME because HW cannot be access when in LOW_POWER state //AND not connected. The knowledge and synchronization is done in SME //sme_DbgReadRegister //Caller needs to validate the input values VOS_STATUS sme_DbgReadRegister(tHalHandle hHal, v_U32_t regAddr, v_U32_t *pRegValue) { VOS_STATUS status = VOS_STATUS_E_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tPmcPowerState PowerState; tANI_U32 sessionId = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_DBG_READREG, NO_SESSION, 0)); /* 1) To make Quarky work in FTM mode **************************************/ if(eDRIVER_TYPE_MFG == pMac->gDriverType) { if (eWLAN_PAL_STATUS_SUCCESS == wpalDbgReadRegister(regAddr, pRegValue)) { return VOS_STATUS_SUCCESS; } return VOS_STATUS_E_FAILURE; } /* 2) NON FTM mode driver *************************************************/ /* Acquire SME global lock */ if (eHAL_STATUS_SUCCESS != sme_AcquireGlobalLock(&pMac->sme)) { return VOS_STATUS_E_FAILURE; } if(HAL_STATUS_SUCCESS(pmcQueryPowerState(pMac, &PowerState, NULL, NULL))) { /* Are we not in IMPS mode? Or are we in connected? Then we're safe*/ if(!csrIsConnStateDisconnected(pMac, sessionId) || (ePMC_LOW_POWER != PowerState)) { if (eWLAN_PAL_STATUS_SUCCESS == wpalDbgReadRegister(regAddr, pRegValue)) { status = VOS_STATUS_SUCCESS; } else { status = VOS_STATUS_E_FAILURE; } } else { status = VOS_STATUS_E_FAILURE; } } /* This is a hack for Qualky/pttWniSocket Current implementation doesn't allow pttWniSocket to inform Qualky an error */ if ( VOS_STATUS_SUCCESS != status ) { *pRegValue = 0xDEADBEEF; status = VOS_STATUS_SUCCESS; } /* Release SME global lock */ sme_ReleaseGlobalLock(&pMac->sme); return (status); } //sme_DbgWriteRegister //Caller needs to validate the input values VOS_STATUS sme_DbgWriteRegister(tHalHandle hHal, v_U32_t regAddr, v_U32_t regValue) { VOS_STATUS status = VOS_STATUS_E_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tPmcPowerState PowerState; tANI_U32 sessionId = 0; /* 1) To make Quarky work in FTM mode **************************************/ MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_DBG_WRITEREG, NO_SESSION, 0)); if(eDRIVER_TYPE_MFG == pMac->gDriverType) { if (eWLAN_PAL_STATUS_SUCCESS == wpalDbgWriteRegister(regAddr, regValue)) { return VOS_STATUS_SUCCESS; } return VOS_STATUS_E_FAILURE; } /* 2) NON FTM mode driver *************************************************/ /* Acquire SME global lock */ if (eHAL_STATUS_SUCCESS != sme_AcquireGlobalLock(&pMac->sme)) { return VOS_STATUS_E_FAILURE; } if(HAL_STATUS_SUCCESS(pmcQueryPowerState(pMac, &PowerState, NULL, NULL))) { /* Are we not in IMPS mode? Or are we in connected? Then we're safe*/ if(!csrIsConnStateDisconnected(pMac, sessionId) || (ePMC_LOW_POWER != PowerState)) { if (eWLAN_PAL_STATUS_SUCCESS == wpalDbgWriteRegister(regAddr, regValue)) { status = VOS_STATUS_SUCCESS; } else { status = VOS_STATUS_E_FAILURE; } } else { status = VOS_STATUS_E_FAILURE; } } /* Release SME global lock */ sme_ReleaseGlobalLock(&pMac->sme); return (status); } //sme_DbgReadMemory //Caller needs to validate the input values //pBuf caller allocated buffer has the length of nLen VOS_STATUS sme_DbgReadMemory(tHalHandle hHal, v_U32_t memAddr, v_U8_t *pBuf, v_U32_t nLen) { VOS_STATUS status = VOS_STATUS_E_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tPmcPowerState PowerState; tANI_U32 sessionId = 0; tANI_U32 cmd = READ_MEMORY_DUMP_CMD; tANI_U32 arg1 = memAddr; tANI_U32 arg2 = nLen/4; tANI_U32 arg3 = 4; tANI_U32 arg4 = 0; /* 1) To make Quarky work in FTM mode **************************************/ MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_DBG_READMEM, NO_SESSION, 0)); if(eDRIVER_TYPE_MFG == pMac->gDriverType) { if (VOS_STATUS_SUCCESS == WDA_HALDumpCmdReq(pMac, cmd, arg1, arg2, arg3, arg4, (tANI_U8*)pBuf, 0)) { return VOS_STATUS_SUCCESS; } return VOS_STATUS_E_FAILURE; } /* 2) NON FTM mode driver *************************************************/ /* Acquire SME global lock */ if (eHAL_STATUS_SUCCESS != sme_AcquireGlobalLock(&pMac->sme)) { return VOS_STATUS_E_FAILURE; } if(HAL_STATUS_SUCCESS(pmcQueryPowerState(pMac, &PowerState, NULL, NULL))) { /* Are we not in IMPS mode? Or are we in connected? Then we're safe*/ if(!csrIsConnStateDisconnected(pMac, sessionId) || (ePMC_LOW_POWER != PowerState)) { if (VOS_STATUS_SUCCESS == WDA_HALDumpCmdReq(pMac, cmd, arg1, arg2, arg3, arg4, (tANI_U8 *)pBuf, 0)) { status = VOS_STATUS_SUCCESS; } else { status = VOS_STATUS_E_FAILURE; } } else { status = VOS_STATUS_E_FAILURE; } } /* This is a hack for Qualky/pttWniSocket Current implementation doesn't allow pttWniSocket to inform Qualky an error */ if (VOS_STATUS_SUCCESS != status) { vos_mem_set(pBuf, nLen, 0xCD); status = VOS_STATUS_SUCCESS; smsLog(pMac, LOGE, FL(" filled with 0xCD because it cannot access the hardware")); } /* Release SME lock */ sme_ReleaseGlobalLock(&pMac->sme); return (status); } //sme_DbgWriteMemory //Caller needs to validate the input values VOS_STATUS sme_DbgWriteMemory(tHalHandle hHal, v_U32_t memAddr, v_U8_t *pBuf, v_U32_t nLen) { VOS_STATUS status = VOS_STATUS_E_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tPmcPowerState PowerState; tANI_U32 sessionId = 0; /* 1) To make Quarky work in FTM mode **************************************/ MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_DBG_WRITEMEM, NO_SESSION, 0)); if(eDRIVER_TYPE_MFG == pMac->gDriverType) { { return VOS_STATUS_SUCCESS; } return VOS_STATUS_E_FAILURE; } /* 2) NON FTM mode driver *************************************************/ /* Acquire SME global lock */ if (eHAL_STATUS_SUCCESS != sme_AcquireGlobalLock(&pMac->sme)) { return VOS_STATUS_E_FAILURE; } if(HAL_STATUS_SUCCESS(pmcQueryPowerState(pMac, &PowerState, NULL, NULL))) { /* Are we not in IMPS mode? Or are we in connected? Then we're safe*/ if(!csrIsConnStateDisconnected(pMac, sessionId) || (ePMC_LOW_POWER != PowerState)) { if (eWLAN_PAL_STATUS_SUCCESS == wpalDbgWriteMemory(memAddr, (void *)pBuf, nLen)) { status = VOS_STATUS_SUCCESS; } else { status = VOS_STATUS_E_FAILURE; } } else { status = VOS_STATUS_E_FAILURE; } } /* Release Global lock */ sme_ReleaseGlobalLock(&pMac->sme); return (status); } void pmcLog(tpAniSirGlobal pMac, tANI_U32 loglevel, const char *pString, ...) { VOS_TRACE_LEVEL vosDebugLevel; char logBuffer[LOG_SIZE]; va_list marker; /* getting proper Debug level */ vosDebugLevel = getVosDebugLevel(loglevel); /* extracting arguments from pstring */ va_start( marker, pString ); vsnprintf(logBuffer, LOG_SIZE, pString, marker); VOS_TRACE(VOS_MODULE_ID_PMC, vosDebugLevel, "%s", logBuffer); va_end( marker ); } void smsLog(tpAniSirGlobal pMac, tANI_U32 loglevel, const char *pString,...) { #ifdef WLAN_DEBUG // Verify against current log level if ( loglevel > pMac->utils.gLogDbgLevel[LOG_INDEX_FOR_MODULE( SIR_SMS_MODULE_ID )] ) return; else { va_list marker; va_start( marker, pString ); /* Initialize variable arguments. */ logDebug(pMac, SIR_SMS_MODULE_ID, loglevel, pString, marker); va_end( marker ); /* Reset variable arguments. */ } #endif } /* --------------------------------------------------------------------------- \fn sme_GetWcnssWlanCompiledVersion \brief This API returns the version of the WCNSS WLAN API with which the HOST driver was built \param hHal - The handle returned by macOpen. \param pVersion - Points to the Version structure to be filled \return VOS_STATUS VOS_STATUS_E_INVAL - failure VOS_STATUS_SUCCESS success ---------------------------------------------------------------------------*/ VOS_STATUS sme_GetWcnssWlanCompiledVersion(tHalHandle hHal, tSirVersionType *pVersion) { VOS_STATUS status = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); v_CONTEXT_t vosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { if( pVersion != NULL ) { status = WDA_GetWcnssWlanCompiledVersion(vosContext, pVersion); } else { status = VOS_STATUS_E_INVAL; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetWcnssWlanReportedVersion \brief This API returns the version of the WCNSS WLAN API with which the WCNSS driver reports it was built \param hHal - The handle returned by macOpen. \param pVersion - Points to the Version structure to be filled \return VOS_STATUS VOS_STATUS_E_INVAL - failure VOS_STATUS_SUCCESS success ---------------------------------------------------------------------------*/ VOS_STATUS sme_GetWcnssWlanReportedVersion(tHalHandle hHal, tSirVersionType *pVersion) { VOS_STATUS status = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); v_CONTEXT_t vosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { if( pVersion != NULL ) { status = WDA_GetWcnssWlanReportedVersion(vosContext, pVersion); } else { status = VOS_STATUS_E_INVAL; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetWcnssSoftwareVersion \brief This API returns the version string of the WCNSS driver \param hHal - The handle returned by macOpen. \param pVersion - Points to the Version string buffer to be filled \param versionBufferSize - THe size of the Version string buffer \return VOS_STATUS VOS_STATUS_E_INVAL - failure VOS_STATUS_SUCCESS success ---------------------------------------------------------------------------*/ VOS_STATUS sme_GetWcnssSoftwareVersion(tHalHandle hHal, tANI_U8 *pVersion, tANI_U32 versionBufferSize) { VOS_STATUS status = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); v_CONTEXT_t vosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { if( pVersion != NULL ) { status = WDA_GetWcnssSoftwareVersion(vosContext, pVersion, versionBufferSize); } else { status = VOS_STATUS_E_INVAL; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetWcnssHardwareVersion \brief This API returns the version string of the WCNSS hardware \param hHal - The handle returned by macOpen. \param pVersion - Points to the Version string buffer to be filled \param versionBufferSize - THe size of the Version string buffer \return VOS_STATUS VOS_STATUS_E_INVAL - failure VOS_STATUS_SUCCESS success ---------------------------------------------------------------------------*/ VOS_STATUS sme_GetWcnssHardwareVersion(tHalHandle hHal, tANI_U8 *pVersion, tANI_U32 versionBufferSize) { VOS_STATUS status = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); v_CONTEXT_t vosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { if( pVersion != NULL ) { status = WDA_GetWcnssHardwareVersion(vosContext, pVersion, versionBufferSize); } else { status = VOS_STATUS_E_INVAL; } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #ifdef FEATURE_WLAN_WAPI /* --------------------------------------------------------------------------- \fn sme_RoamSetBKIDCache \brief The SME API exposed to HDD to allow HDD to provde SME the BKID candidate list. \param hHal - Handle to the HAL. The HAL handle is returned by the HAL after it is opened (by calling halOpen). \param pBKIDCache - caller allocated buffer point to an array of tBkidCacheInfo \param numItems - a variable that has the number of tBkidCacheInfo allocated when retruning, this is the number of items put into pBKIDCache \return eHalStatus - when fail, it usually means the buffer allocated is not big enough and pNumItems has the number of tBkidCacheInfo. ---------------------------------------------------------------------------*/ eHalStatus sme_RoamSetBKIDCache( tHalHandle hHal, tANI_U32 sessionId, tBkidCacheInfo *pBKIDCache, tANI_U32 numItems ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrRoamSetBKIDCache( pMac, sessionId, pBKIDCache, numItems ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetBKIDCache \brief The SME API exposed to HDD to allow HDD to request SME to return its BKID cache. \param hHal - Handle to the HAL. The HAL handle is returned by the HAL after it is opened (by calling halOpen). \param pNum - caller allocated memory that has the space of the number of tBkidCacheInfo as input. Upon returned, *pNum has the needed number of entries in SME cache. \param pBkidCache - Caller allocated memory that contains BKID cache, if any, upon return \return eHalStatus - when fail, it usually means the buffer allocated is not big enough. ---------------------------------------------------------------------------*/ eHalStatus sme_RoamGetBKIDCache(tHalHandle hHal, tANI_U32 *pNum, tBkidCacheInfo *pBkidCache) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { smsLog(pMac, LOGE, FL(" !!!!!!!!!!!!!!!!!!SessionId is hardcoded")); status = csrRoamGetBKIDCache( pMac, 0, pNum, pBkidCache ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamGetNumBKIDCache \brief The SME API exposed to HDD to allow HDD to request SME to return the number of BKID cache entries. \param hHal - Handle to the HAL. The HAL handle is returned by the HAL after it is opened (by calling halOpen). \return tANI_U32 - the number of BKID cache entries. ---------------------------------------------------------------------------*/ tANI_U32 sme_RoamGetNumBKIDCache(tHalHandle hHal, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_U32 numBkidCache = 0; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { numBkidCache = csrRoamGetNumBKIDCache( pMac, sessionId ); sme_ReleaseGlobalLock( &pMac->sme ); } return (numBkidCache); } /* --------------------------------------------------------------------------- \fn sme_ScanGetBKIDCandidateList \brief a wrapper function to return the BKID candidate list \param pBkidList - caller allocated buffer point to an array of tBkidCandidateInfo \param pNumItems - pointer to a variable that has the number of tBkidCandidateInfo allocated when retruning, this is either the number needed or number of items put into pPmkidList \return eHalStatus - when fail, it usually means the buffer allocated is not big enough and pNumItems has the number of tBkidCandidateInfo. \Note: pNumItems is a number of tBkidCandidateInfo, not sizeof(tBkidCandidateInfo) * something ---------------------------------------------------------------------------*/ eHalStatus sme_ScanGetBKIDCandidateList(tHalHandle hHal, tANI_U32 sessionId, tBkidCandidateInfo *pBkidList, tANI_U32 *pNumItems ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrScanGetBKIDCandidateList( pMac, sessionId, pBkidList, pNumItems ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif /* FEATURE_WLAN_WAPI */ #ifdef FEATURE_OEM_DATA_SUPPORT /***************************************************************************** OEM DATA related modifications and function additions *****************************************************************************/ /* --------------------------------------------------------------------------- \fn sme_getOemDataRsp \brief a wrapper function to obtain the OEM DATA RSP \param pOemDataRsp - A pointer to the response object \param pContext - a pointer passed in for the callback \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_getOemDataRsp(tHalHandle hHal, tOemDataRsp **pOemDataRsp) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); do { //acquire the lock for the sme object status = sme_AcquireGlobalLock(&pMac->sme); if(!HAL_STATUS_SUCCESS(status)) { break; } if(pMac->oemData.pOemDataRsp != NULL) { *pOemDataRsp = pMac->oemData.pOemDataRsp; } else { status = eHAL_STATUS_FAILURE; } //release the lock for the sme object sme_ReleaseGlobalLock( &pMac->sme ); } while(0); return status; } /* --------------------------------------------------------------------------- \fn sme_OemDataReq \brief a wrapper function for OEM DATA REQ \param sessionId - session id to be used. \param pOemDataReqId - pointer to an object to get back the request ID \param callback - a callback function that is called upon finish \param pContext - a pointer passed in for the callback \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_OemDataReq(tHalHandle hHal, tANI_U8 sessionId, tOemDataReqConfig *pOemDataReqConfig, tANI_U32 *pOemDataReqID, oemData_OemDataReqCompleteCallback callback, void *pContext) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); do { //acquire the lock for the sme object status = sme_AcquireGlobalLock(&pMac->sme); if(HAL_STATUS_SUCCESS(status)) { tANI_U32 lOemDataReqId = pMac->oemData.oemDataReqID++; //let it wrap around if(pOemDataReqID) { *pOemDataReqID = lOemDataReqId; } else { sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } status = oemData_OemDataReq(hHal, sessionId, pOemDataReqConfig, pOemDataReqID, callback, pContext); //release the lock for the sme object sme_ReleaseGlobalLock( &pMac->sme ); } } while(0); smsLog(pMac, LOGW, "exiting function %s", __func__); return(status); } /* --------------------------------------------------------------------------- \fn sme_OemDataReqNew \brief a wrapper function for OEM DATA REQ NEW \param pOemDataReqNewConfig - Data to be passed to FW ---------------------------------------------------------------------------*/ void sme_OemDataReqNew(tHalHandle hHal, tOemDataReqNewConfig *pOemDataReqNewConfig) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tOemDataReqNewConfig *pLocalOemDataReqNewConfig; vos_msg_t vosMessage = {0}; pLocalOemDataReqNewConfig = vos_mem_malloc(sizeof(*pLocalOemDataReqNewConfig)); if (!pLocalOemDataReqNewConfig) { smsLog(pMac, LOGE, "Failed to allocate memory for WDA_START_OEM_DATA_REQ_IND_NEW"); return; } vos_mem_zero(pLocalOemDataReqNewConfig, sizeof(tOemDataReqNewConfig)); vos_mem_copy(pLocalOemDataReqNewConfig, pOemDataReqNewConfig, sizeof(tOemDataReqNewConfig)); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pLocalOemDataReqNewConfig; vosMessage.type = WDA_START_OEM_DATA_REQ_IND_NEW; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:" "Failed to post WDA_START_OEM_DATA_REQ_IND_NEW msg to WDA", __func__); vos_mem_free(pLocalOemDataReqNewConfig); } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pLocalOemDataReqNewConfig); } } #endif /*FEATURE_OEM_DATA_SUPPORT*/ /*-------------------------------------------------------------------------- \brief sme_OpenSession() - Open a session for scan/roam operation. This is a synchronous API. \param hHal - The handle returned by macOpen. \param callback - A pointer to the function caller specifies for roam/connect status indication \param pContext - The context passed with callback \param pSelfMacAddr - Caller allocated memory filled with self MAC address (6 bytes) \param pbSessionId - pointer to a caller allocated buffer for returned session ID \return eHAL_STATUS_SUCCESS - session is opened. sessionId returned. Other status means SME is failed to open the session. eHAL_STATUS_RESOURCES - no more session available. \sa --------------------------------------------------------------------------*/ eHalStatus sme_OpenSession(tHalHandle hHal, csrRoamCompleteCallback callback, void *pContext, tANI_U8 *pSelfMacAddr, tANI_U8 *pbSessionId) { eHalStatus status; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if( NULL == pbSessionId ) { status = eHAL_STATUS_INVALID_PARAMETER; } else { status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrRoamOpenSession(pMac, callback, pContext, pSelfMacAddr, pbSessionId); sme_ReleaseGlobalLock( &pMac->sme ); } } if( NULL != pbSessionId ) MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_OPEN_SESSION,*pbSessionId, 0)); return ( status ); } /*-------------------------------------------------------------------------- \brief sme_CloseSession() - Open a session for scan/roam operation. This is a synchronous API. \param hHal - The handle returned by macOpen. \param sessionId - A previous opened session's ID. \return eHAL_STATUS_SUCCESS - session is closed. Other status means SME is failed to open the session. eHAL_STATUS_INVALID_PARAMETER - session is not opened. \sa --------------------------------------------------------------------------*/ eHalStatus sme_CloseSession(tHalHandle hHal, tANI_U8 sessionId, tANI_BOOLEAN fSync, tANI_U8 bPurgeSmeCmdList, csrRoamSessionCloseCallback callback, void *pContext) { eHalStatus status; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CLOSE_SESSION, sessionId, 0)); status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { status = csrRoamCloseSession(pMac, sessionId, fSync, bPurgeSmeCmdList, callback, pContext); sme_ReleaseGlobalLock( &pMac->sme ); } return ( status ); } /* --------------------------------------------------------------------------- \fn sme_RoamUpdateAPWPSIE \brief To update AP's WPS IE. This function should be called after SME AP session is created This is an asynchronous API. \param pAPWPSIES - pointer to a caller allocated object of tSirAPWPSIEs \return eHalStatus – SUCCESS – FAILURE or RESOURCES – The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_RoamUpdateAPWPSIE(tHalHandle hHal, tANI_U8 sessionId, tSirAPWPSIEs *pAPWPSIES) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrRoamUpdateAPWPSIE( pMac, sessionId, pAPWPSIES ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_RoamUpdateAPWPARSNIEs \brief To update AP's WPA/RSN IEs. This function should be called after SME AP session is created This is an asynchronous API. \param pAPSirRSNie - pointer to a caller allocated object of tSirRSNie with WPS/RSN IEs \return eHalStatus – SUCCESS – FAILURE or RESOURCES – The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_RoamUpdateAPWPARSNIEs(tHalHandle hHal, tANI_U8 sessionId, tSirRSNie * pAPSirRSNie) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrRoamUpdateWPARSNIEs( pMac, sessionId, pAPSirRSNie); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_ChangeMCCBeaconInterval \brief To update P2P-GO beaconInterval. This function should be called after disassociating all the station is done This is an asynchronous API. \param \return eHalStatus SUCCESS FAILURE or RESOURCES The API finished and failed. -------------------------------------------------------------------------------*/ eHalStatus sme_ChangeMCCBeaconInterval(tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); smsLog(pMac, LOG1, FL("Update Beacon PARAMS ")); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrSendChngMCCBeaconInterval( pMac, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /*-------------------------------------------------------------------------------* \fn sme_sendBTAmpEvent \brief to receive the coex priorty request from BT-AMP PAL and send the BT_AMP link state to HAL \param btAmpEvent - btAmpEvent \return eHalStatus: SUCCESS : BTAmp event successfully sent to HAL FAILURE: API failed -------------------------------------------------------------------------------*/ eHalStatus sme_sendBTAmpEvent(tHalHandle hHal, tSmeBtAmpEvent btAmpEvent) { vos_msg_t msg; tpSmeBtAmpEvent ptrSmeBtAmpEvent = NULL; eHalStatus status = eHAL_STATUS_FAILURE; ptrSmeBtAmpEvent = vos_mem_malloc(sizeof(tSmeBtAmpEvent)); if (NULL == ptrSmeBtAmpEvent) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "Not able to allocate memory for BTAmp event", __func__); return status; } vos_mem_copy(ptrSmeBtAmpEvent, (void*)&btAmpEvent, sizeof(tSmeBtAmpEvent)); msg.type = WDA_SIGNAL_BTAMP_EVENT; msg.reserved = 0; msg.bodyptr = ptrSmeBtAmpEvent; //status = halFW_SendBTAmpEventMesg(pMac, event); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "Not able to post SIR_HAL_SIGNAL_BTAMP_EVENT message to HAL", __func__); vos_mem_free(ptrSmeBtAmpEvent); return status; } return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn smeIssueFastRoamNeighborAPEvent \brief API to trigger fast BSS roam independent of RSSI triggers \param hHal - The handle returned by macOpen. \param bssid - Pointer to the BSSID to roam to. \param fastRoamTrig - Trigger to Scan or roam \param channel - channel number on which fastroam is requested \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus smeIssueFastRoamNeighborAPEvent (tHalHandle hHal, tANI_U8 *bssid, tSmeFastRoamTrigger fastRoamTrig, tANI_U8 channel) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: invoked", __func__); if (eSME_ROAM_TRIGGER_SCAN == fastRoamTrig) { smsLog(pMac, LOG1, FL("CFG Channel list scan... ")); pNeighborRoamInfo->cfgRoamEn = eSME_ROAM_TRIGGER_SCAN; vos_mem_copy((void *)(&pNeighborRoamInfo->cfgRoambssId), (void *)bssid, sizeof(tSirMacAddr)); smsLog(pMac, LOG1, "Calling Roam Look Up down Event BSSID" MAC_ADDRESS_STR, MAC_ADDR_ARRAY(pNeighborRoamInfo->cfgRoambssId)); /* * As FastReassoc is based on assumption that roamable AP should be * present into the occupied channel list.We shd add i/p channel * in occupied channel list if roamable-ap(BSSID in fastreassoc cmd) * aged out prior to connection and there is no scan from aged out * to till connection indication. */ csrAddChannelToOccupiedChannelList(pMac, channel); vosStatus = csrNeighborRoamTransitToCFGChanScan(pMac); if (VOS_STATUS_SUCCESS != vosStatus) { smsLog(pMac, LOGE, FL("CFG Channel list scan state failed with status %d "), vosStatus); } } else if (eSME_ROAM_TRIGGER_FAST_ROAM == fastRoamTrig) { vos_mem_copy((void *)(&pNeighborRoamInfo->cfgRoambssId), (void *)bssid, sizeof(tSirMacAddr)); pNeighborRoamInfo->cfgRoamEn = eSME_ROAM_TRIGGER_FAST_ROAM; smsLog(pMac, LOG1, "Roam to BSSID "MAC_ADDRESS_STR, MAC_ADDR_ARRAY(pNeighborRoamInfo->cfgRoambssId)); vosStatus = csrNeighborRoamReassocIndCallback(pMac->roam.gVosContext, 0, pMac, 0); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { smsLog(pMac, LOGE, FL(" Call to csrNeighborRoamReassocIndCallback failed, status = %d"), vosStatus); } } sme_ReleaseGlobalLock( &pMac->sme ); } return vosStatus; } /* --------------------------------------------------------------------------- \fn sme_SetHostOffload \brief API to set the host offload feature. \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the offload request. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetHostOffload (tHalHandle hHal, tANI_U8 sessionId, tpSirHostOffloadReq pRequest) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_FAILURE; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_HOSTOFFLOAD, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { #ifdef WLAN_NS_OFFLOAD if(SIR_IPV6_NS_OFFLOAD == pRequest->offloadType) { status = pmcSetNSOffload( hHal, pRequest, sessionId); } else #endif //WLAN_NS_OFFLOAD { status = pmcSetHostOffload (hHal, pRequest, sessionId); } sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #ifdef WLAN_FEATURE_GTK_OFFLOAD /* --------------------------------------------------------------------------- \fn sme_SetGTKOffload \brief API to set GTK offload information. \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the GTK offload request. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetGTKOffload (tHalHandle hHal, tpSirGtkOffloadParams pRequest, tANI_U8 sessionId) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_GTKOFFLOAD, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { status = pmcSetGTKOffload( hHal, pRequest, sessionId ); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_GetGTKOffload \brief API to get GTK offload information. \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the GTK offload response. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetGTKOffload (tHalHandle hHal, GTKOffloadGetInfoCallback callbackRoutine, void *callbackContext, tANI_U8 sessionId ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_GTKOFFLOAD, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { pmcGetGTKOffload(hHal, callbackRoutine, callbackContext, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif // WLAN_FEATURE_GTK_OFFLOAD /* --------------------------------------------------------------------------- \fn sme_SetKeepAlive \brief API to set the Keep Alive feature. \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the Keep Alive request. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetKeepAlive (tHalHandle hHal, tANI_U8 sessionId, tpSirKeepAliveReq pRequest) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { status = pmcSetKeepAlive (hHal, pRequest, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #ifdef FEATURE_WLAN_SCAN_PNO /* --------------------------------------------------------------------------- \fn sme_SetPreferredNetworkList \brief API to set the Preferred Network List Offload feature. \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the offload request. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetPreferredNetworkList (tHalHandle hHal, tpSirPNOScanReq pRequest, tANI_U8 sessionId, void (*callbackRoutine) (void *callbackContext, tSirPrefNetworkFoundInd *pPrefNetworkFoundInd), void *callbackContext ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_PREF_NET_LIST, sessionId, pRequest->ucNetworksCount)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { pmcSetPreferredNetworkList(hHal, pRequest, sessionId, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } eHalStatus sme_SetRSSIFilter(tHalHandle hHal, v_U8_t rssiThreshold) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { pmcSetRssiFilter(hHal, rssiThreshold); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } #endif // FEATURE_WLAN_SCAN_PNO eHalStatus sme_SetPowerParams(tHalHandle hHal, tSirSetPowerParamsReq* pwParams, tANI_BOOLEAN forced) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_POWERPARAMS, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { pmcSetPowerParams(hHal, pwParams, forced); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_AbortMacScan \brief API to cancel MAC scan. \param hHal - The handle returned by macOpen. \param sessionId - sessionId on which we need to abort scan. \param reason - Reason to abort the scan. \return tSirAbortScanStatus Abort scan status ---------------------------------------------------------------------------*/ tSirAbortScanStatus sme_AbortMacScan(tHalHandle hHal, tANI_U8 sessionId, eCsrAbortReason reason) { tSirAbortScanStatus scanAbortStatus = eSIR_ABORT_SCAN_FAILURE; eHalStatus status; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_ABORT_MACSCAN, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { scanAbortStatus = csrScanAbortMacScan(pMac, sessionId, reason); sme_ReleaseGlobalLock( &pMac->sme ); } return ( scanAbortStatus ); } /* ---------------------------------------------------------------------------- \fn sme_GetOperationChannel \brief API to get current channel on which STA is parked this function gives channel information only of infra station or IBSS station \param hHal, pointer to memory location and sessionId \returns eHAL_STATUS_SUCCESS eHAL_STATUS_FAILURE -------------------------------------------------------------------------------*/ eHalStatus sme_GetOperationChannel(tHalHandle hHal, tANI_U32 *pChannel, tANI_U8 sessionId) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tCsrRoamSession *pSession; if (CSR_IS_SESSION_VALID( pMac, sessionId )) { pSession = CSR_GET_SESSION( pMac, sessionId ); if(( pSession->connectedProfile.BSSType == eCSR_BSS_TYPE_INFRASTRUCTURE ) || ( pSession->connectedProfile.BSSType == eCSR_BSS_TYPE_IBSS ) || ( pSession->connectedProfile.BSSType == eCSR_BSS_TYPE_INFRA_AP ) || ( pSession->connectedProfile.BSSType == eCSR_BSS_TYPE_START_IBSS )) { *pChannel =pSession->connectedProfile.operationChannel; return eHAL_STATUS_SUCCESS; } } return eHAL_STATUS_FAILURE; }// sme_GetOperationChannel ends here /** * sme_register_mgmt_frame_ind_callback() - Register a callback for * management frame indication to PE. * @hHal: hal pointer * @callback: callback pointer to be registered * * This function is used to register a callback for management * frame indication to PE. * * Return: Success if msg is posted to PE else Failure. */ eHalStatus sme_register_mgmt_frame_ind_callback(tHalHandle hHal, sir_mgmt_frame_ind_callback callback) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); struct sir_sme_mgmt_frame_cb_req *msg; eHalStatus status = eHAL_STATUS_SUCCESS; smsLog(pMac, LOG1, FL(": ENTER")); if (eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock(&pMac->sme)) { msg = vos_mem_malloc(sizeof(*msg)); if (NULL == msg) { smsLog(pMac, LOGE, FL("Not able to allocate memory for eWNI_SME_REGISTER_MGMT_FRAME_CB")); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } vos_mem_set(msg, sizeof(*msg), 0); msg->message_type = eWNI_SME_REGISTER_MGMT_FRAME_CB; msg->length = sizeof(*msg); msg->callback = callback; status = palSendMBMessage(pMac->hHdd, msg); sme_ReleaseGlobalLock( &pMac->sme ); return status; } return eHAL_STATUS_FAILURE; } /* --------------------------------------------------------------------------- \fn sme_RegisterMgtFrame \brief To register managment frame of specified type and subtype. \param frameType - type of the frame that needs to be passed to HDD. \param matchData - data which needs to be matched before passing frame to HDD. \param matchDataLen - Length of matched data. \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_RegisterMgmtFrame(tHalHandle hHal, tANI_U8 sessionId, tANI_U16 frameType, tANI_U8* matchData, tANI_U16 matchLen) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_REGISTER_MGMTFR, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { tSirRegisterMgmtFrame *pMsg; tANI_U16 len; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } if( !pSession->sessionActive ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s Invalid Sessionid", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } len = sizeof(tSirRegisterMgmtFrame) + matchLen; pMsg = vos_mem_malloc(len); if ( NULL == pMsg ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pMsg, len, 0); pMsg->messageType = eWNI_SME_REGISTER_MGMT_FRAME_REQ; pMsg->length = len; pMsg->sessionId = sessionId; pMsg->registerFrame = VOS_TRUE; pMsg->frameType = frameType; pMsg->matchLen = matchLen; vos_mem_copy(pMsg->matchData, matchData, matchLen); status = palSendMBMessage(pMac->hHdd, pMsg); } sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_DeregisterMgtFrame \brief To De-register managment frame of specified type and subtype. \param frameType - type of the frame that needs to be passed to HDD. \param matchData - data which needs to be matched before passing frame to HDD. \param matchDataLen - Length of matched data. \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_DeregisterMgmtFrame(tHalHandle hHal, tANI_U8 sessionId, tANI_U16 frameType, tANI_U8* matchData, tANI_U16 matchLen) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_DEREGISTER_MGMTFR, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { tSirRegisterMgmtFrame *pMsg; tANI_U16 len; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } if( !pSession->sessionActive ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s Invalid Sessionid", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } len = sizeof(tSirRegisterMgmtFrame) + matchLen; pMsg = vos_mem_malloc(len); if ( NULL == pMsg ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pMsg, len, 0); pMsg->messageType = eWNI_SME_REGISTER_MGMT_FRAME_REQ; pMsg->length = len; pMsg->registerFrame = VOS_FALSE; pMsg->frameType = frameType; pMsg->matchLen = matchLen; vos_mem_copy(pMsg->matchData, matchData, matchLen); status = palSendMBMessage(pMac->hHdd, pMsg); } sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_RemainOnChannel \brief API to request remain on channel for 'x' duration. used in p2p in listen state \param hHal - The handle returned by macOpen. \param pRequest - channel \param duration - duration in ms \param callback - HDD registered callback to process reaminOnChannelRsp \param context - HDD Callback param \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_RemainOnChannel(tHalHandle hHal, tANI_U8 sessionId, tANI_U8 channel, tANI_U32 duration, remainOnChanCallback callback, void *pContext, tANI_U8 isP2PProbeReqAllowed) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_REMAIN_ONCHAN, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { status = p2pRemainOnChannel (hHal, sessionId, channel, duration, callback, pContext, isP2PProbeReqAllowed #ifdef WLAN_FEATURE_P2P_INTERNAL , eP2PRemainOnChnReasonUnknown #endif ); sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_ReportProbeReq \brief API to enable/disable forwarding of probeReq to apps in p2p. \param hHal - The handle returned by macOpen. \param falg: to set the Probe request forarding to wpa_supplicant in listen state in p2p \return eHalStatus ---------------------------------------------------------------------------*/ #ifndef WLAN_FEATURE_CONCURRENT_P2P eHalStatus sme_ReportProbeReq(tHalHandle hHal, tANI_U8 flag) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); do { //acquire the lock for the sme object status = sme_AcquireGlobalLock(&pMac->sme); if(HAL_STATUS_SUCCESS(status)) { /* call set in context */ pMac->p2pContext.probeReqForwarding = flag; //release the lock for the sme object sme_ReleaseGlobalLock( &pMac->sme ); } } while(0); smsLog(pMac, LOGW, "exiting function %s", __func__); return(status); } /* --------------------------------------------------------------------------- \fn sme_updateP2pIe \brief API to set the P2p Ie in p2p context \param hHal - The handle returned by macOpen. \param p2pIe - Ptr to p2pIe from HDD. \param p2pIeLength: length of p2pIe \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_updateP2pIe(tHalHandle hHal, void *p2pIe, tANI_U32 p2pIeLength) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); //acquire the lock for the sme object status = sme_AcquireGlobalLock(&pMac->sme); if(HAL_STATUS_SUCCESS(status)) { if(NULL != pMac->p2pContext.probeRspIe){ vos_mem_free(pMac->p2pContext.probeRspIe); pMac->p2pContext.probeRspIeLength = 0; } pMac->p2pContext.probeRspIe = vos_mem_malloc(p2pIeLength); if (NULL == pMac->p2pContext.probeRspIe) { smsLog(pMac, LOGE, "%s: Unable to allocate P2P IE", __func__); pMac->p2pContext.probeRspIeLength = 0; status = eHAL_STATUS_FAILURE; } else { pMac->p2pContext.probeRspIeLength = p2pIeLength; sirDumpBuf( pMac, SIR_LIM_MODULE_ID, LOG2, pMac->p2pContext.probeRspIe, pMac->p2pContext.probeRspIeLength ); vos_mem_copy((tANI_U8 *)pMac->p2pContext.probeRspIe, p2pIe, p2pIeLength); } //release the lock for the sme object sme_ReleaseGlobalLock( &pMac->sme ); } smsLog(pMac, LOG2, "exiting function %s", __func__); return(status); } #endif /* --------------------------------------------------------------------------- \fn sme_sendAction \brief API to send action frame from supplicant. \param hHal - The handle returned by macOpen. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_sendAction(tHalHandle hHal, tANI_U8 sessionId, const tANI_U8 *pBuf, tANI_U32 len, tANI_U16 wait, tANI_BOOLEAN noack) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SEND_ACTION, sessionId, 0)); //acquire the lock for the sme object status = sme_AcquireGlobalLock(&pMac->sme); if(HAL_STATUS_SUCCESS(status)) { p2pSendAction(hHal, sessionId, pBuf, len, wait, noack); //release the lock for the sme object sme_ReleaseGlobalLock( &pMac->sme ); } smsLog(pMac, LOGW, "exiting function %s", __func__); return(status); } eHalStatus sme_CancelRemainOnChannel(tHalHandle hHal, tANI_U8 sessionId ) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CANCEL_REMAIN_ONCHAN, sessionId, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { status = p2pCancelRemainOnChannel (hHal, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } //Power Save Related eHalStatus sme_p2pSetPs(tHalHandle hHal, tP2pPsConfig * data) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { status = p2pSetPs (hHal, data); sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_GetFramesLog \brief a wrapper function that client calls to register a callback to get mgmt frames logged \param flag - flag tells to clear OR send the frame log buffer \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_GetFramesLog(tHalHandle hHal, tANI_U8 flag) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pGetFrameLogCmd; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pGetFrameLogCmd = csrGetCommandBuffer(pMac); if (pGetFrameLogCmd) { pGetFrameLogCmd->command = eSmeCommandGetFrameLogRequest; pGetFrameLogCmd->u.getFramelogCmd.getFrameLogCmdFlag= flag; status = csrQueueSmeCommand(pMac, pGetFrameLogCmd, eANI_BOOLEAN_TRUE); if ( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL("fail to send msg status = %d\n"), status ); csrReleaseCommandScan(pMac, pGetFrameLogCmd); } } else { //log error smsLog(pMac, LOGE, FL("can not obtain a common buffer\n")); status = eHAL_STATUS_RESOURCES; } sme_ReleaseGlobalLock( &pMac->sme); } return (status); } /* --------------------------------------------------------------------------- \fn sme_InitMgmtFrameLogging \brief SME will pass this request to lower mac to initialize Frame Logging. \param hHal - The handle returned by macOpen. wlanFWLoggingInitParam - Params to initialize frame logging \return eHalStatus --------------------------------------------------------------------------- */ eHalStatus sme_InitMgmtFrameLogging( tHalHandle hHal, tSirFWLoggingInitParam *wlanFWLoggingInitParam) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tpSirFWLoggingInitParam msg; msg = vos_mem_malloc(sizeof(tSirFWLoggingInitParam)); if (NULL == msg) { smsLog(pMac, LOGE, FL("Failed to alloc mem of size %zu for msg"), sizeof(*msg)); return eHAL_STATUS_FAILED_ALLOC; } *msg = *wlanFWLoggingInitParam; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { /* serialize the req through MC thread */ vosMessage.bodyptr = msg; vosMessage.type = WDA_MGMT_LOGGING_INIT_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { vos_mem_free(msg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } else { smsLog(pMac, LOGE, FL("sme_AcquireGlobalLock error")); vos_mem_free(msg); } return(status); } /* --------------------------------------------------------------------------- \fn sme_StartRssiMonitoring \brief SME will pass this request to lower mac to start monitoring rssi range on a bssid. \param hHal - The handle returned by macOpen. tSirRssiMonitorReq req- depict the monitor req params. \return eHalStatus --------------------------------------------------------------------------- */ eHalStatus sme_StartRssiMonitoring( tHalHandle hHal, tSirRssiMonitorReq *req) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { /* serialize the req through MC thread */ vosMessage.bodyptr = req; vosMessage.type = WDA_START_RSSI_MONITOR_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_StopRssiMonitoring \brief SME will pass this request to lower mac to stop monitoring rssi range on a bssid. \param hHal - The handle returned by macOpen. tSirRssiMonitorReq req- depict the monitor req params. \return eHalStatus --------------------------------------------------------------------------- */ eHalStatus sme_StopRssiMonitoring(tHalHandle hHal, tSirRssiMonitorReq *req) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { /* serialize the req through MC thread */ vosMessage.bodyptr = req; vosMessage.type = WDA_STOP_RSSI_MONITOR_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_ConfigureRxpFilter \brief SME will pass this request to lower mac to set/reset the filter on RXP for multicast & broadcast traffic. \param hHal - The handle returned by macOpen. filterMask- Currently the API takes a 1 or 0 (set or reset) as filter. Basically to enable/disable the filter (to filter "all" mcbc traffic) based on this param. In future we can use this as a mask to set various types of filters as suggested below: FILTER_ALL_MULTICAST: FILTER_ALL_BROADCAST: FILTER_ALL_MULTICAST_BROADCAST: \return eHalStatus --------------------------------------------------------------------------- */ eHalStatus sme_ConfigureRxpFilter( tHalHandle hHal, tpSirWlanSetRxpFilters wlanRxpFilterParam) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CONFIG_RXPFIL, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { /* serialize the req through MC thread */ vosMessage.bodyptr = wlanRxpFilterParam; vosMessage.type = WDA_CFG_RXP_FILTER_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_ConfigureSuspendInd \brief SME will pass this request to lower mac to Indicate that the wlan needs to be suspended \param hHal - The handle returned by macOpen. wlanSuspendParam- Depicts the wlan suspend params \return eHalStatus --------------------------------------------------------------------------- */ eHalStatus sme_ConfigureSuspendInd( tHalHandle hHal, tpSirWlanSuspendParam wlanSuspendParam) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CONFIG_SUSPENDIND, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { /* serialize the req through MC thread */ vosMessage.bodyptr = wlanSuspendParam; vosMessage.type = WDA_WLAN_SUSPEND_IND; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_ConfigureResumeReq \brief SME will pass this request to lower mac to Indicate that the wlan needs to be Resumed \param hHal - The handle returned by macOpen. wlanResumeParam- Depicts the wlan resume params \return eHalStatus --------------------------------------------------------------------------- */ eHalStatus sme_ConfigureResumeReq( tHalHandle hHal, tpSirWlanResumeParam wlanResumeParam) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CONFIG_RESUMEREQ, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { /* serialize the req through MC thread */ vosMessage.bodyptr = wlanResumeParam; vosMessage.type = WDA_WLAN_RESUME_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /* --------------------------------------------------------------------------- \fn sme_GetInfraSessionId \brief To get the session ID for infra session, if connected This is a synchronous API. \param hHal - The handle returned by macOpen. \return sessionid, -1 if infra session is not connected -------------------------------------------------------------------------------*/ tANI_S8 sme_GetInfraSessionId(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tANI_S8 sessionid = -1; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { sessionid = csrGetInfraSessionId( pMac); sme_ReleaseGlobalLock( &pMac->sme ); } return (sessionid); } tANI_U32 sme_get_sessionid_from_activeList(tpAniSirGlobal mac) { tListElem *entry = NULL; tSmeCmd *command = NULL; tANI_U32 session_id = 0; entry = csrLLPeekHead( &mac->sme.smeCmdActiveList, LL_ACCESS_LOCK ); if ( entry ) { command = GET_BASE_ADDR( entry, tSmeCmd, Link ); session_id = command->sessionId; } return (session_id); } /* --------------------------------------------------------------------------- \fn sme_GetInfraOperationChannel \brief To get the operating channel for infra session, if connected This is a synchronous API. \param hHal - The handle returned by macOpen. \param sessionId - the sessionId returned by sme_OpenSession. \return operating channel, 0 if infra session is not connected -------------------------------------------------------------------------------*/ tANI_U8 sme_GetInfraOperationChannel( tHalHandle hHal, tANI_U8 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_U8 channel = 0; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { channel = csrGetInfraOperationChannel( pMac, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return (channel); } //This routine will return poerating channel on which other BSS is operating to be used for concurrency mode. //If other BSS is not up or not connected it will return 0 tANI_U8 sme_GetConcurrentOperationChannel( tHalHandle hHal ) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tANI_U8 channel = 0; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { channel = csrGetConcurrentOperationChannel( pMac ); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO_HIGH, "%s: " " Other Concurrent Channel = %d", __func__,channel); sme_ReleaseGlobalLock( &pMac->sme ); } return (channel); } #ifdef FEATURE_WLAN_SCAN_PNO /****************************************************************************** * * Name: sme_PreferredNetworkFoundInd * * Description: * Invoke Preferred Network Found Indication * * Parameters: * hHal - HAL handle for device * pMsg - found network description * * Returns: eHalStatus * ******************************************************************************/ eHalStatus sme_PreferredNetworkFoundInd (tHalHandle hHal, void* pMsg) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tSirPrefNetworkFoundInd *pPrefNetworkFoundInd = (tSirPrefNetworkFoundInd *)pMsg; v_U8_t dumpSsId[SIR_MAC_MAX_SSID_LENGTH + 1]; tANI_U8 ssIdLength = 0; if (NULL == pMsg) { smsLog(pMac, LOGE, "in %s msg ptr is NULL", __func__); status = eHAL_STATUS_FAILURE; } else { if (pPrefNetworkFoundInd->ssId.length > 0) { ssIdLength = CSR_MIN(SIR_MAC_MAX_SSID_LENGTH, pPrefNetworkFoundInd->ssId.length); vos_mem_copy(dumpSsId, pPrefNetworkFoundInd->ssId.ssId, ssIdLength); dumpSsId[ssIdLength] = 0; smsLog(pMac, LOG1, FL(" SSID=%s frame length %d"), dumpSsId, pPrefNetworkFoundInd->frameLength); /* Flush scan results, So as to avoid indication/updation of * stale entries, which may not have aged out during APPS collapse */ sme_ScanFlushResult(hHal,0); //Save the frame to scan result if (pPrefNetworkFoundInd->mesgLen > sizeof(tSirPrefNetworkFoundInd)) { //we may have a frame status = csrScanSavePreferredNetworkFound(pMac, pPrefNetworkFoundInd); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL(" fail to save preferred network")); } } else { smsLog(pMac, LOGE, FL(" not enough data length %u needed %zu"), pPrefNetworkFoundInd->mesgLen, sizeof(tSirPrefNetworkFoundInd)); } /* Call Preferred Netowrk Found Indication callback routine. */ if (HAL_STATUS_SUCCESS(status) && (pMac->pmc.prefNetwFoundCB != NULL)) { pMac->pmc.prefNetwFoundCB( pMac->pmc.preferredNetworkFoundIndCallbackContext, pPrefNetworkFoundInd); } } else { smsLog(pMac, LOGE, "%s: callback failed - SSID is NULL", __func__); status = eHAL_STATUS_FAILURE; } } return(status); } #endif // FEATURE_WLAN_SCAN_PNO eHalStatus sme_GetCfgValidChannels(tHalHandle hHal, tANI_U8 *aValidChannels, tANI_U32 *len) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrGetCfgValidChannels(pMac, aValidChannels, len); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } eHalStatus sme_SetCfgScanControlList(tHalHandle hHal, tANI_U8 *countryCode, tCsrChannel *pChannelList) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { csrSetCfgScanControlList(pMac, countryCode, pChannelList); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_SetTxPerTracking \brief Set Tx PER tracking configuration parameters \param hHal - The handle returned by macOpen. \param pTxPerTrackingConf - Tx PER configuration parameters \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_SetTxPerTracking(tHalHandle hHal, void (*pCallbackfn) (void *pCallbackContext), void *pCallbackContext, tpSirTxPerTrackingParam pTxPerTrackingParam) { vos_msg_t msg; tpSirTxPerTrackingParam pTxPerTrackingParamReq = NULL; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme ) ) { pMac->sme.pTxPerHitCallback = pCallbackfn; pMac->sme.pTxPerHitCbContext = pCallbackContext; sme_ReleaseGlobalLock( &pMac->sme ); } // free this memory in failure case or WDA request callback function pTxPerTrackingParamReq = vos_mem_malloc(sizeof(tSirTxPerTrackingParam)); if (NULL == pTxPerTrackingParamReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for tSirTxPerTrackingParam", __func__); return eHAL_STATUS_FAILURE; } vos_mem_copy(pTxPerTrackingParamReq, (void*)pTxPerTrackingParam, sizeof(tSirTxPerTrackingParam)); msg.type = WDA_SET_TX_PER_TRACKING_REQ; msg.reserved = 0; msg.bodyptr = pTxPerTrackingParamReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to post WDA_SET_TX_PER_TRACKING_REQ message to WDA", __func__); vos_mem_free(pTxPerTrackingParamReq); return eHAL_STATUS_FAILURE; } return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn sme_HandleChangeCountryCode \brief Change Country code, Reg Domain and channel list \details Country Code Priority 0 = 11D > Configured Country > NV 1 = Configured Country > 11D > NV If Supplicant country code is priority than 11d is disabled. If 11D is enabled, we update the country code after every scan. Hence when Supplicant country code is priority, we don't need 11D info. Country code from Supplicant is set as current courtry code. User can send reset command XX (instead of country code) to reset the country code to default values which is read from NV. In case of reset, 11D is enabled and default NV code is Set as current country code If 11D is priority, Than Supplicant country code code is set to default code. But 11D code is set as current country code \param pMac - The handle returned by macOpen. \param pMsgBuf - MSG Buffer \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_HandleChangeCountryCode(tpAniSirGlobal pMac, void *pMsgBuf) { eHalStatus status = eHAL_STATUS_SUCCESS; tAniChangeCountryCodeReq *pMsg; v_REGDOMAIN_t domainIdIoctl; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; static uNvTables nvTables; pMsg = (tAniChangeCountryCodeReq *)pMsgBuf; if (pMac->scan.fcc_constraint) { pMac->scan.fcc_constraint = false; if (VOS_TRUE== vos_mem_compare(pMac->scan.countryCodeCurrent, pMsg->countryCode, 2)) { csrInitGetChannels(pMac); csrResetCountryInformation(pMac, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); csrScanFilterResults(pMac); return status ; } } /* if the reset Supplicant country code command is triggered, enable 11D, reset the NV country code and return */ if( VOS_TRUE == vos_mem_compare(pMsg->countryCode, SME_INVALID_COUNTRY_CODE, 2) ) { pMac->roam.configParam.Is11dSupportEnabled = pMac->roam.configParam.Is11dSupportEnabledOriginal; vosStatus = vos_nv_readDefaultCountryTable( &nvTables ); /* read the country code from NV and use it */ if ( VOS_IS_STATUS_SUCCESS(vosStatus) ) { vos_mem_copy(pMsg->countryCode, nvTables.defaultCountryTable.countryCode, WNI_CFG_COUNTRY_CODE_LEN); } else { status = eHAL_STATUS_FAILURE; return status; } /* Update the 11d country to default country from NV bin so that when * callback is received for this default country, driver will not * disable the 11d taking it as valid country by user. */ smsLog(pMac, LOG1, FL("Set default country code (%c%c) from NV as invalid country received"), pMsg->countryCode[0],pMsg->countryCode[1]); vos_mem_copy(pMac->scan.countryCode11d, pMsg->countryCode, WNI_CFG_COUNTRY_CODE_LEN); } else { /* if Supplicant country code has priority, disable 11d */ if(pMac->roam.configParam.fSupplicantCountryCodeHasPriority && pMsg->countryFromUserSpace) { pMac->roam.configParam.Is11dSupportEnabled = eANI_BOOLEAN_FALSE; } } /* WEXT set country code means * 11D should be supported? * 11D Channel should be enforced? * 11D Country code should be matched? * 11D Reg Domian should be matched? * Country string changed */ if(pMac->roam.configParam.Is11dSupportEnabled && pMac->roam.configParam.fEnforce11dChannels && pMac->roam.configParam.fEnforceCountryCodeMatch && pMac->roam.configParam.fEnforceDefaultDomain && !csrSave11dCountryString(pMac, pMsg->countryCode, eANI_BOOLEAN_TRUE)) { /* All 11D related options are already enabled * Country string is not changed * Do not need do anything for country code change request */ return eHAL_STATUS_SUCCESS; } /* Set Current Country code and Current Regulatory domain */ status = csrSetCountryCode(pMac, pMsg->countryCode, NULL); if(eHAL_STATUS_SUCCESS != status) { /* Supplicant country code failed. So give 11D priority */ pMac->roam.configParam.Is11dSupportEnabled = pMac->roam.configParam.Is11dSupportEnabledOriginal; smsLog(pMac, LOGE, "Set Country Code Fail %d", status); return status; } /* overwrite the defualt country code */ vos_mem_copy(pMac->scan.countryCodeDefault, pMac->scan.countryCodeCurrent, WNI_CFG_COUNTRY_CODE_LEN); /* Get Domain ID from country code */ status = csrGetRegulatoryDomainForCountry(pMac, pMac->scan.countryCodeCurrent, (v_REGDOMAIN_t *) &domainIdIoctl, COUNTRY_QUERY); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to get regId %d"), domainIdIoctl ); return status; } else if (REGDOMAIN_WORLD == domainIdIoctl) { /* Supplicant country code is invalid, so we are on world mode now. So give 11D chance to update */ pMac->roam.configParam.Is11dSupportEnabled = pMac->roam.configParam.Is11dSupportEnabledOriginal; smsLog(pMac, LOG1, FL("Country Code unrecognized by driver")); } status = WDA_SetRegDomain(pMac, domainIdIoctl, pMsg->sendRegHint); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to set regId %d"), domainIdIoctl ); return status; } else { //if 11d has priority, clear currentCountryBssid & countryCode11d to get //set again if we find AP with 11d info during scan status = csrSetRegulatoryDomain(pMac, domainIdIoctl, NULL); if (status != eHAL_STATUS_SUCCESS) { smsLog( pMac, LOGE, FL("fail to set regId.status : %d"), status); } if (!pMac->roam.configParam.fSupplicantCountryCodeHasPriority) { smsLog( pMac, LOGW, FL("Clearing currentCountryBssid, countryCode11d")); vos_mem_zero(&pMac->scan.currentCountryBssid, sizeof(tCsrBssid)); vos_mem_zero( pMac->scan.countryCode11d, sizeof( pMac->scan.countryCode11d ) ); } } #ifndef CONFIG_ENABLE_LINUX_REG /* set to default domain ID */ pMac->scan.domainIdDefault = pMac->scan.domainIdCurrent; /* get the channels based on new cc */ status = csrInitGetChannels( pMac ); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to get Channels ")); return status; } /* reset info based on new cc, and we are done */ csrResetCountryInformation(pMac, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); /* Country code Changed, Purge Only scan result * which does not have channel number belong to 11d * channel list */ csrScanFilterResults(pMac); #endif if( pMsg->changeCCCallback ) { ((tSmeChangeCountryCallback)(pMsg->changeCCCallback))((void *)pMsg->pDevContext); } return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn sme_HandleChangeCountryCodeByUser \brief Change Country code, Reg Domain and channel list If Supplicant country code is priority than 11d is disabled. If 11D is enabled, we update the country code after every scan. Hence when Supplicant country code is priority, we don't need 11D info. Country code from Supplicant is set as current country code. \param pMac - The handle returned by macOpen. \param pMsg - Carrying new CC & domain set in kernel by user \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_HandleChangeCountryCodeByUser(tpAniSirGlobal pMac, tAniGenericChangeCountryCodeReq *pMsg) { eHalStatus status = eHAL_STATUS_SUCCESS; v_REGDOMAIN_t reg_domain_id; v_BOOL_t is11dCountry = VOS_FALSE; smsLog(pMac, LOG1, FL(" called")); reg_domain_id = (v_REGDOMAIN_t)pMsg->domain_index; if (memcmp(pMsg->countryCode, pMac->scan.countryCode11d, VOS_COUNTRY_CODE_LEN) == 0) { is11dCountry = VOS_TRUE; } smsLog( pMac, LOG1, FL("pMsg->countryCode : %c%c," "pMac->scan.countryCode11d : %c%c\n"), pMsg->countryCode[0], pMsg->countryCode[1], pMac->scan.countryCode11d[0], pMac->scan.countryCode11d[1]); /* Set the country code given by userspace when 11dOriginal is FALSE * when 11doriginal is True,is11dCountry =0 and * fSupplicantCountryCodeHasPriority = 0, then revert the country code, * and return failure */ if (pMac->roam.configParam.Is11dSupportEnabledOriginal == true) { if ((!is11dCountry) && (!pMac->roam.configParam.fSupplicantCountryCodeHasPriority)&& (!pMac->roam.configParam.fEnforceCountryCode) ) { smsLog( pMac, LOGW, FL(" incorrect country being set, nullify this request")); status = csrGetRegulatoryDomainForCountry(pMac, pMac->scan.countryCode11d, (v_REGDOMAIN_t *) &reg_domain_id, COUNTRY_IE); return eHAL_STATUS_FAILURE; } } /* if Supplicant country code has priority, disable 11d */ if ((!is11dCountry) && (pMac->roam.configParam.fSupplicantCountryCodeHasPriority) && (!pMac->roam.configParam.fEnforceCountryCode)) { pMac->roam.configParam.Is11dSupportEnabled = eANI_BOOLEAN_FALSE; smsLog( pMac, LOG1, FL(" 11d is being disabled")); } pMac->roam.configParam.fEnforceCountryCode = eANI_BOOLEAN_FALSE; vos_mem_copy(pMac->scan.countryCodeCurrent, pMsg->countryCode, WNI_CFG_COUNTRY_CODE_LEN); vos_mem_copy(pMac->scan.countryCode11d, pMsg->countryCode, WNI_CFG_COUNTRY_CODE_LEN); status = csrSetRegulatoryDomain(pMac, reg_domain_id, NULL); if (status != eHAL_STATUS_SUCCESS) { smsLog( pMac, LOGE, FL("fail to set regId.status : %d"), status); } status = WDA_SetRegDomain(pMac, reg_domain_id, eSIR_TRUE); if (VOS_FALSE == is11dCountry ) { /* overwrite the defualt country code */ vos_mem_copy(pMac->scan.countryCodeDefault, pMac->scan.countryCodeCurrent, WNI_CFG_COUNTRY_CODE_LEN); /* set to default domain ID */ pMac->scan.domainIdDefault = pMac->scan.domainIdCurrent; } if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to set regId %d"), reg_domain_id ); return status; } else { //if 11d has priority, clear currentCountryBssid & countryCode11d to get //set again if we find AP with 11d info during scan if((!pMac->roam.configParam.fSupplicantCountryCodeHasPriority) && (VOS_FALSE == is11dCountry )) { smsLog( pMac, LOGW, FL("Clearing currentCountryBssid, countryCode11d")); vos_mem_zero(&pMac->scan.currentCountryBssid, sizeof(tCsrBssid)); vos_mem_zero( pMac->scan.countryCode11d, sizeof( pMac->scan.countryCode11d ) ); } } /* get the channels based on new cc */ status = csrInitGetChannels(pMac); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to get Channels ")); return status; } /* reset info based on new cc, and we are done */ csrResetCountryInformation(pMac, eANI_BOOLEAN_TRUE, eANI_BOOLEAN_TRUE); if (VOS_TRUE == is11dCountry) { pMac->scan.f11dInfoApplied = eANI_BOOLEAN_TRUE; pMac->scan.f11dInfoReset = eANI_BOOLEAN_FALSE; } /* Country code Changed, Purge Only scan result * which does not have channel number belong to 11d * channel list */ csrScanFilterResults(pMac); // Do active scans after the country is set by User hints or Country IE pMac->scan.curScanType = eSIR_ACTIVE_SCAN; sme_DisconnectConnectedSessions(pMac); smsLog(pMac, LOG1, FL(" returned")); return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn sme_HandleChangeCountryCodeByCore \brief Update Country code in the driver if set by kernel as world If 11D is enabled, we update the country code after every scan & notify kernel. This is to make sure kernel & driver are in sync in case of CC found in driver but not in kernel database \param pMac - The handle returned by macOpen. \param pMsg - Carrying new CC set in kernel \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_HandleChangeCountryCodeByCore(tpAniSirGlobal pMac, tAniGenericChangeCountryCodeReq *pMsg) { eHalStatus status; smsLog(pMac, LOG1, FL(" called")); //this is to make sure kernel & driver are in sync in case of CC found in //driver but not in kernel database if (('0' == pMsg->countryCode[0]) && ('0' == pMsg->countryCode[1])) { smsLog( pMac, LOGW, FL("Setting countryCode11d & countryCodeCurrent to world CC")); vos_mem_copy(pMac->scan.countryCode11d, pMsg->countryCode, WNI_CFG_COUNTRY_CODE_LEN); vos_mem_copy(pMac->scan.countryCodeCurrent, pMsg->countryCode, WNI_CFG_COUNTRY_CODE_LEN); } status = WDA_SetRegDomain(pMac, REGDOMAIN_WORLD, eSIR_TRUE); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to set regId") ); return status; } else { status = csrSetRegulatoryDomain(pMac, REGDOMAIN_WORLD, NULL); if (status != eHAL_STATUS_SUCCESS) { smsLog( pMac, LOGE, FL("fail to set regId.status : %d"), status); } status = csrInitGetChannels(pMac); if ( status != eHAL_STATUS_SUCCESS ) { smsLog( pMac, LOGE, FL(" fail to get Channels ")); } else { csrInitChannelList(pMac); } } /* Country code Changed, Purge Only scan result * which does not have channel number belong to 11d * channel list */ csrScanFilterResults(pMac); smsLog(pMac, LOG1, FL(" returned")); return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn sme_DisconnectConnectedSessions \brief Disconnect STA and P2P client session if channel is not supported If new country code does not support the channel on which STA/P2P client is connetced, it sends the disconnect to the AP/P2P GO \param pMac - The handle returned by macOpen \return eHalStatus -------------------------------------------------------------------------------*/ void sme_DisconnectConnectedSessions(tpAniSirGlobal pMac) { v_U8_t i, sessionId, isChanFound = false; tANI_U8 currChannel; for (sessionId=0; sessionId < CSR_ROAM_SESSION_MAX; sessionId++) { if (csrIsSessionClientAndConnected(pMac, sessionId)) { isChanFound = false; //Session is connected.Check the channel currChannel = csrGetInfraOperationChannel(pMac, sessionId); smsLog(pMac, LOGW, "Current Operating channel : %d, session :%d", currChannel, sessionId); for (i=0; i < pMac->scan.base20MHzChannels.numChannels; i++) { if (pMac->scan.base20MHzChannels.channelList[i] == currChannel) { isChanFound = true; break; } } if (!isChanFound) { for (i=0; i < pMac->scan.base40MHzChannels.numChannels; i++) { if (pMac->scan.base40MHzChannels.channelList[i] == currChannel) { isChanFound = true; break; } } } if (!isChanFound) { smsLog(pMac, LOGW, "%s : Disconnect Session :%d", __func__, sessionId); csrRoamDisconnect(pMac, sessionId, eCSR_DISCONNECT_REASON_UNSPECIFIED); } } } } /* --------------------------------------------------------------------------- \fn sme_HandleGenericChangeCountryCode \brief Change Country code, Reg Domain and channel list If Supplicant country code is priority than 11d is disabled. If 11D is enabled, we update the country code after every scan. Hence when Supplicant country code is priority, we don't need 11D info. Country code from kernel is set as current country code. \param pMac - The handle returned by macOpen. \param pMsgBuf - message buffer \return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_HandleGenericChangeCountryCode(tpAniSirGlobal pMac, void *pMsgBuf) { tAniGenericChangeCountryCodeReq *pMsg; v_REGDOMAIN_t reg_domain_id; smsLog(pMac, LOG1, FL(" called")); pMsg = (tAniGenericChangeCountryCodeReq *)pMsgBuf; reg_domain_id = (v_REGDOMAIN_t)pMsg->domain_index; if (REGDOMAIN_COUNT == reg_domain_id) { sme_HandleChangeCountryCodeByCore(pMac, pMsg); } else { sme_HandleChangeCountryCodeByUser(pMac, pMsg); } smsLog(pMac, LOG1, FL(" returned")); return eHAL_STATUS_SUCCESS; } #ifdef WLAN_FEATURE_PACKET_FILTERING eHalStatus sme_8023MulticastList (tHalHandle hHal, tANI_U8 sessionId, tpSirRcvFltMcAddrList pMulticastAddrs) { tpSirRcvFltMcAddrList pRequestBuf; vos_msg_t msg; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tCsrRoamSession *pSession = NULL; VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: " "ulMulticastAddrCnt=%d, multicastAddr[0]=%p", __func__, pMulticastAddrs->ulMulticastAddrCnt, pMulticastAddrs->multicastAddr[0]); /* *Find the connected Infra / P2P_client connected session */ if (CSR_IS_SESSION_VALID(pMac, sessionId) && csrIsConnStateInfra(pMac, sessionId)) { pSession = CSR_GET_SESSION( pMac, sessionId ); } if(pSession == NULL ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Unable to find " "the right session", __func__); return eHAL_STATUS_FAILURE; } pRequestBuf = vos_mem_malloc(sizeof(tSirRcvFltMcAddrList)); if (NULL == pRequestBuf) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to " "allocate memory for 8023 Multicast List request", __func__); return eHAL_STATUS_FAILED_ALLOC; } if( !csrIsConnStateConnectedInfra (pMac, sessionId )) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Ignoring the " "indication as we are not connected", __func__); vos_mem_free(pRequestBuf); return eHAL_STATUS_FAILURE; } vos_mem_copy(pRequestBuf, pMulticastAddrs, sizeof(tSirRcvFltMcAddrList)); vos_mem_copy(pRequestBuf->selfMacAddr, pSession->selfMacAddr, sizeof(tSirMacAddr)); vos_mem_copy(pRequestBuf->bssId, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); msg.type = WDA_8023_MULTICAST_LIST_REQ; msg.reserved = 0; msg.bodyptr = pRequestBuf; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, sessionId, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to " "post WDA_8023_MULTICAST_LIST message to WDA", __func__); vos_mem_free(pRequestBuf); return eHAL_STATUS_FAILURE; } return eHAL_STATUS_SUCCESS; } eHalStatus sme_ReceiveFilterSetFilter(tHalHandle hHal, tpSirRcvPktFilterCfgType pRcvPktFilterCfg, tANI_U8 sessionId) { tpSirRcvPktFilterCfgType pRequestBuf; v_SINT_t allocSize; vos_msg_t msg; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); v_U8_t idx=0; VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: filterType=%d, " "filterId = %d", __func__, pRcvPktFilterCfg->filterType, pRcvPktFilterCfg->filterId); allocSize = sizeof(tSirRcvPktFilterCfgType); pRequestBuf = vos_mem_malloc(allocSize); if (NULL == pRequestBuf) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to " "allocate memory for Receive Filter Set Filter request", __func__); return eHAL_STATUS_FAILED_ALLOC; } if( NULL == pSession ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Session Not found ", __func__); vos_mem_free(pRequestBuf); return eHAL_STATUS_FAILURE; } vos_mem_copy(pRcvPktFilterCfg->selfMacAddr, pSession->selfMacAddr, sizeof(tSirMacAddr)); vos_mem_copy(pRcvPktFilterCfg->bssId, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); vos_mem_copy(pRequestBuf, pRcvPktFilterCfg, allocSize); msg.type = WDA_RECEIVE_FILTER_SET_FILTER_REQ; msg.reserved = 0; msg.bodyptr = pRequestBuf; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, sessionId, msg.type)); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "Pkt Flt Req : " "FT %d FID %d ", pRequestBuf->filterType, pRequestBuf->filterId); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "Pkt Flt Req : " "params %d CT %d", pRequestBuf->numFieldParams, pRequestBuf->coalesceTime); for (idx=0; idx<pRequestBuf->numFieldParams; idx++) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "Proto %d Comp Flag %d ", pRequestBuf->paramsData[idx].protocolLayer, pRequestBuf->paramsData[idx].cmpFlag); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "Data Offset %d Data Len %d", pRequestBuf->paramsData[idx].dataOffset, pRequestBuf->paramsData[idx].dataLength); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "CData: %d:%d:%d:%d:%d:%d", pRequestBuf->paramsData[idx].compareData[0], pRequestBuf->paramsData[idx].compareData[1], pRequestBuf->paramsData[idx].compareData[2], pRequestBuf->paramsData[idx].compareData[3], pRequestBuf->paramsData[idx].compareData[4], pRequestBuf->paramsData[idx].compareData[5]); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "MData: %d:%d:%d:%d:%d:%d", pRequestBuf->paramsData[idx].dataMask[0], pRequestBuf->paramsData[idx].dataMask[1], pRequestBuf->paramsData[idx].dataMask[2], pRequestBuf->paramsData[idx].dataMask[3], pRequestBuf->paramsData[idx].dataMask[4], pRequestBuf->paramsData[idx].dataMask[5]); } if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to post " "WDA_RECEIVE_FILTER_SET_FILTER message to WDA", __func__); vos_mem_free(pRequestBuf); return eHAL_STATUS_FAILURE; } return eHAL_STATUS_SUCCESS; } eHalStatus sme_GetFilterMatchCount(tHalHandle hHal, FilterMatchCountCallback callbackRoutine, void *callbackContext, tANI_U8 sessionId) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "+%s", __func__); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme))) { pmcGetFilterMatchCount(hHal, callbackRoutine, callbackContext, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "-%s", __func__); return (status); } eHalStatus sme_ReceiveFilterClearFilter(tHalHandle hHal, tpSirRcvFltPktClearParam pRcvFltPktClearParam, tANI_U8 sessionId) { tpSirRcvFltPktClearParam pRequestBuf; vos_msg_t msg; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: filterId = %d", __func__, pRcvFltPktClearParam->filterId); pRequestBuf = vos_mem_malloc(sizeof(tSirRcvFltPktClearParam)); if (NULL == pRequestBuf) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for Receive Filter " "Clear Filter request", __func__); return eHAL_STATUS_FAILED_ALLOC; } if( NULL == pSession ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Session Not find ", __func__); vos_mem_free(pRequestBuf); return eHAL_STATUS_FAILURE; } vos_mem_copy(pRcvFltPktClearParam->selfMacAddr, pSession->selfMacAddr, sizeof(tSirMacAddr)); vos_mem_copy(pRcvFltPktClearParam->bssId, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); vos_mem_copy(pRequestBuf, pRcvFltPktClearParam, sizeof(tSirRcvFltPktClearParam)); msg.type = WDA_RECEIVE_FILTER_CLEAR_FILTER_REQ; msg.reserved = 0; msg.bodyptr = pRequestBuf; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, sessionId, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to post " "WDA_RECEIVE_FILTER_CLEAR_FILTER message to WDA", __func__); vos_mem_free(pRequestBuf); return eHAL_STATUS_FAILURE; } return eHAL_STATUS_SUCCESS; } #endif // WLAN_FEATURE_PACKET_FILTERING /* --------------------------------------------------------------------------- \fn sme_PreChannelSwitchIndFullPowerCB \brief call back function for the PMC full power request because of pre channel switch. \param callbackContext \param status ---------------------------------------------------------------------------*/ void sme_PreChannelSwitchIndFullPowerCB(void *callbackContext, eHalStatus status) { tpAniSirGlobal pMac = (tpAniSirGlobal)callbackContext; tSirMbMsg *pMsg; tANI_U16 msgLen; msgLen = (tANI_U16)(sizeof( tSirMbMsg )); pMsg = vos_mem_malloc(msgLen); if ( NULL != pMsg ) { vos_mem_set(pMsg, msgLen, 0); pMsg->type = pal_cpu_to_be16((tANI_U16)eWNI_SME_PRE_CHANNEL_SWITCH_FULL_POWER); pMsg->msgLen = pal_cpu_to_be16(msgLen); status = palSendMBMessage(pMac->hHdd, pMsg); } return; } /* --------------------------------------------------------------------------- \fn sme_HandlePreChannelSwitchInd \brief Processes the indcation from PE for pre-channel switch. \param hHal \- The handle returned by macOpen. return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_HandlePreChannelSwitchInd(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRequestFullPower(hHal, sme_PreChannelSwitchIndFullPowerCB, pMac, eSME_FULL_PWR_NEEDED_BY_CHANNEL_SWITCH); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_HandlePostChannelSwitchInd \brief Processes the indcation from PE for post-channel switch. \param hHal \- The handle returned by macOpen. return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_HandlePostChannelSwitchInd(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = pmcRequestBmps(hHal, NULL, NULL); sme_ReleaseGlobalLock( &pMac->sme ); } return (status); } /* --------------------------------------------------------------------------- \fn sme_IsChannelValid \brief To check if the channel is valid for currently established domain This is a synchronous API. \param hHal - The handle returned by macOpen. \param channel - channel to verify \return TRUE/FALSE, TRUE if channel is valid -------------------------------------------------------------------------------*/ tANI_BOOLEAN sme_IsChannelValid(tHalHandle hHal, tANI_U8 channel) { eHalStatus status = eHAL_STATUS_FAILURE; tANI_BOOLEAN valid = FALSE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { valid = csrRoamIsChannelValid( pMac, channel); sme_ReleaseGlobalLock( &pMac->sme ); } return (valid); } /* --------------------------------------------------------------------------- \fn sme_SetFreqBand \brief Used to set frequency band. \param hHal \eBand band value to be configured \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_SetFreqBand(tHalHandle hHal, eCsrBand eBand) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrSetBand(hHal, eBand); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_GetFreqBand \brief Used to get the current band settings. \param hHal \pBand pointer to hold band value \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_GetFreqBand(tHalHandle hHal, eCsrBand *pBand) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { *pBand = csrGetCurrentBand( hHal ); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } #ifdef WLAN_WAKEUP_EVENTS /****************************************************************************** \fn sme_WakeReasonIndCallback \brief a callback function called when SME received eWNI_SME_WAKE_REASON_IND event from WDA \param hHal - HAL handle for device \param pMsg - Message body passed from WDA; includes Wake Reason Indication parameter \return eHalStatus ******************************************************************************/ eHalStatus sme_WakeReasonIndCallback (tHalHandle hHal, void* pMsg) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tSirWakeReasonInd *pWakeReasonInd = (tSirWakeReasonInd *)pMsg; if (NULL == pMsg) { smsLog(pMac, LOGE, "in %s msg ptr is NULL", __func__); status = eHAL_STATUS_FAILURE; } else { smsLog(pMac, LOG2, "SME: entering sme_WakeReasonIndCallback"); /* Call Wake Reason Indication callback routine. */ if (pMac->pmc.wakeReasonIndCB != NULL) pMac->pmc.wakeReasonIndCB(pMac->pmc.wakeReasonIndCBContext, pWakeReasonInd); smsLog(pMac, LOG1, "Wake Reason Indication in %s(), reason=%d", __func__, pWakeReasonInd->ulReason); } return(status); } #endif // WLAN_WAKEUP_EVENTS /** * sme_SetMaxTxPower() - Set the Maximum Transmit Power * * @hHal: hal pointer. * @bssid: bssid to set the power cap for * @self_mac_addr:self mac address * @db: power to set in dB * * Set the maximum transmit power dynamically. * * Return: eHalStatus * */ eHalStatus sme_SetMaxTxPower(tHalHandle hHal, tSirMacAddr bssid, tSirMacAddr self_mac_addr, v_S7_t db) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *set_max_tx_pwr; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_MAXTXPOW, NO_SESSION, 0)); smsLog(pMac, LOG1, FL("bssid :" MAC_ADDRESS_STR " self addr: "MAC_ADDRESS_STR" power %d Db"), MAC_ADDR_ARRAY(bssid), MAC_ADDR_ARRAY(self_mac_addr), db); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { set_max_tx_pwr = csrGetCommandBuffer(pMac); if (set_max_tx_pwr) { set_max_tx_pwr->command = eSmeCommandSetMaxTxPower; vos_mem_copy(set_max_tx_pwr->u.set_tx_max_pwr.bssid, bssid, SIR_MAC_ADDR_LENGTH); vos_mem_copy(set_max_tx_pwr->u.set_tx_max_pwr.self_sta_mac_addr, self_mac_addr, SIR_MAC_ADDR_LENGTH); set_max_tx_pwr->u.set_tx_max_pwr.power = db; status = csrQueueSmeCommand(pMac, set_max_tx_pwr, eANI_BOOLEAN_TRUE); if ( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL("fail to send msg status = %d"), status ); csrReleaseCommandScan(pMac, set_max_tx_pwr); } } else { smsLog(pMac, LOGE, FL("can not obtain a common buffer")); status = eHAL_STATUS_RESOURCES; } sme_ReleaseGlobalLock( &pMac->sme); } return (status); } /* --------------------------------------------------------------------------- \fn sme_SetMaxTxPowerPerBand \brief Set the Maximum Transmit Power specific to band dynamically. Note: this setting will not persist over reboots. \param band \param power to set in dB \- return eHalStatus ----------------------------------------------------------------------------*/ eHalStatus sme_SetMaxTxPowerPerBand(eCsrBand band, v_S7_t dB) { vos_msg_t msg; tpMaxTxPowerPerBandParams pMaxTxPowerPerBandParams = NULL; pMaxTxPowerPerBandParams = vos_mem_malloc(sizeof(tMaxTxPowerPerBandParams)); if (NULL == pMaxTxPowerPerBandParams) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:Not able to allocate memory for pMaxTxPowerPerBandParams", __func__); return eHAL_STATUS_FAILURE; } pMaxTxPowerPerBandParams->power = dB; pMaxTxPowerPerBandParams->bandInfo = band; msg.type = WDA_SET_MAX_TX_POWER_PER_BAND_REQ; msg.reserved = 0; msg.bodyptr = pMaxTxPowerPerBandParams; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if (VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:Not able to post WDA_SET_MAX_TX_POWER_PER_BAND_REQ", __func__); vos_mem_free(pMaxTxPowerPerBandParams); return eHAL_STATUS_FAILURE; } return eHAL_STATUS_SUCCESS; } /* --------------------------------------------------------------------------- \fn sme_SetTxPower \brief Set Transmit Power dynamically. Note: this setting will not persist over reboots. \param hHal \param sessionId Target Session ID \param mW power to set in mW \- return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_SetTxPower(tHalHandle hHal, v_U8_t sessionId, v_U8_t mW) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_TXPOW, NO_SESSION, 0)); smsLog(pMac, LOG1, FL("set tx power %dmW"), mW); status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { status = csrSetTxPower(pMac, sessionId, mW); sme_ReleaseGlobalLock(&pMac->sme); } return status; } /* --------------------------------------------------------------------------- \fn sme_HideSSID \brief hide/show SSID dynamically. Note: this setting will not persist over reboots. \param hHal \param sessionId \param ssidHidden 0 - Broadcast SSID, 1 - Disable broadcast SSID \- return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_HideSSID(tHalHandle hHal, v_U8_t sessionId, v_U8_t ssidHidden) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tANI_U16 len; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { tpSirUpdateParams pMsg; tCsrRoamSession *pSession = CSR_GET_SESSION( pMac, sessionId ); if(!pSession) { smsLog(pMac, LOGE, FL(" session %d not found "), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } if( !pSession->sessionActive ) VOS_ASSERT(0); /* Create the message and send to lim */ len = sizeof(tSirUpdateParams); pMsg = vos_mem_malloc(len); if ( NULL == pMsg ) status = eHAL_STATUS_FAILURE; else { vos_mem_set(pMsg, sizeof(tSirUpdateParams), 0); pMsg->messageType = eWNI_SME_HIDE_SSID_REQ; pMsg->length = len; /* Data starts from here */ pMsg->sessionId = sessionId; pMsg->ssidHidden = ssidHidden; status = palSendMBMessage(pMac->hHdd, pMsg); } sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_SetTmLevel \brief Set Thermal Mitigation Level to RIVA \param hHal - The handle returned by macOpen. \param newTMLevel - new Thermal Mitigation Level \param tmMode - Thermal Mitigation handle mode, default 0 \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetTmLevel(tHalHandle hHal, v_U16_t newTMLevel, v_U16_t tmMode) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tAniSetTmLevelReq *setTmLevelReq = NULL; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_TMLEVEL, NO_SESSION, 0)); if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ) ) ) { setTmLevelReq = (tAniSetTmLevelReq *)vos_mem_malloc(sizeof(tAniSetTmLevelReq)); if (NULL == setTmLevelReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for sme_SetTmLevel", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } setTmLevelReq->tmMode = tmMode; setTmLevelReq->newTmLevel = newTMLevel; /* serialize the req through MC thread */ vosMessage.bodyptr = setTmLevelReq; vosMessage.type = WDA_SET_TM_LEVEL_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post Set TM Level MSG fail", __func__); vos_mem_free(setTmLevelReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return(status); } /*--------------------------------------------------------------------------- \brief sme_featureCapsExchange() - SME interface to exchange capabilities between Host and FW. \param hHal - HAL handle for device \return NONE ---------------------------------------------------------------------------*/ void sme_featureCapsExchange( tHalHandle hHal) { v_CONTEXT_t vosContext = vos_get_global_context(VOS_MODULE_ID_SME, NULL); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_CAPS_EXCH, NO_SESSION, 0)); WDA_featureCapsExchange(vosContext); } /*--------------------------------------------------------------------------- \brief sme_disableFeatureCapablity() - SME interface to disable Active mode offload capablity in Host. \param hHal - HAL handle for device \return NONE ---------------------------------------------------------------------------*/ void sme_disableFeatureCapablity(tANI_U8 feature_index) { WDA_disableCapablityFeature(feature_index); } /* --------------------------------------------------------------------------- \fn sme_GetDefaultCountryCode \brief Get the default country code from NV \param hHal \param pCountry \- return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_GetDefaultCountryCodeFrmNv(tHalHandle hHal, tANI_U8 *pCountry) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_DEFCCNV, NO_SESSION, 0)); return csrGetDefaultCountryCodeFrmNv(pMac, pCountry); } /* --------------------------------------------------------------------------- \fn sme_GetCurrentCountryCode \brief Get the current country code \param hHal \param pCountry \- return eHalStatus -------------------------------------------------------------------------------*/ eHalStatus sme_GetCurrentCountryCode(tHalHandle hHal, tANI_U8 *pCountry) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_CURCC, NO_SESSION, 0)); return csrGetCurrentCountryCode(pMac, pCountry); } /* --------------------------------------------------------------------------- \fn sme_transportDebug \brief Dynamically monitoring Transport channels Private IOCTL will querry transport channel status if driver loaded \param hHal Upper MAC context \param displaySnapshot Display transport channel snapshot option \param toggleStallDetect Enable stall detect feature This feature will take effect to data performance Not integrate till fully verification \- return NONE -------------------------------------------------------------------------*/ void sme_transportDebug(tHalHandle hHal, v_BOOL_t displaySnapshot, v_BOOL_t toggleStallDetect) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: invalid context", __func__); return; } WDA_TransportChannelDebug(pMac, displaySnapshot, toggleStallDetect); } /* --------------------------------------------------------------------------- \fn sme_ResetPowerValuesFor5G \brief Reset the power values for 5G band with NV power values. \param hHal - HAL handle for device \- return NONE -------------------------------------------------------------------------*/ void sme_ResetPowerValuesFor5G (tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT (hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_RESET_PW5G, NO_SESSION, 0)); csrSaveChannelPowerForBand(pMac, eANI_BOOLEAN_TRUE); csrApplyPower2Current(pMac); // Store the channel+power info in the global place: Cfg } #if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_ESE) || defined(FEATURE_WLAN_LFR) /* --------------------------------------------------------------------------- \fn sme_UpdateRoamPrefer5GHz \brief enable/disable Roam prefer 5G runtime option This function is called through dynamic setConfig callback function to configure the Roam prefer 5G runtime option \param hHal - HAL handle for device \param nRoamPrefer5GHz Enable/Disable Roam prefer 5G runtime option \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_UpdateRoamPrefer5GHz(tHalHandle hHal, v_BOOL_t nRoamPrefer5GHz) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_UPDATE_RP5G, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: gRoamPrefer5GHz is changed from %d to %d", __func__, pMac->roam.configParam.nRoamPrefer5GHz, nRoamPrefer5GHz); pMac->roam.configParam.nRoamPrefer5GHz = nRoamPrefer5GHz; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_setRoamIntraBand \brief enable/disable Intra band roaming This function is called through dynamic setConfig callback function to configure the intra band roaming \param hHal - HAL handle for device \param nRoamIntraBand Enable/Disable Intra band roaming \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_setRoamIntraBand(tHalHandle hHal, const v_BOOL_t nRoamIntraBand) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_ROAMIBAND, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: gRoamIntraBand is changed from %d to %d", __func__, pMac->roam.configParam.nRoamIntraBand, nRoamIntraBand); pMac->roam.configParam.nRoamIntraBand = nRoamIntraBand; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_UpdateRoamScanNProbes \brief function to update roam scan N probes This function is called through dynamic setConfig callback function to update roam scan N probes \param hHal - HAL handle for device \param nProbes number of probe requests to be sent out \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_UpdateRoamScanNProbes(tHalHandle hHal, const v_U8_t nProbes) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: gRoamScanNProbes is changed from %d to %d", __func__, pMac->roam.configParam.nProbes, nProbes); pMac->roam.configParam.nProbes = nProbes; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_NPROBES_CHANGED); } #endif return status ; } /* --------------------------------------------------------------------------- \fn sme_UpdateRoamScanHomeAwayTime \brief function to update roam scan Home away time This function is called through dynamic setConfig callback function to update roam scan home away time \param hHal - HAL handle for device \param nRoamScanAwayTime Scan home away time \param bSendOffloadCmd If TRUE then send offload command to firmware If FALSE then command is not sent to firmware \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_UpdateRoamScanHomeAwayTime(tHalHandle hHal, const v_U16_t nRoamScanHomeAwayTime, const eAniBoolean bSendOffloadCmd) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: gRoamScanHomeAwayTime is changed from %d to %d", __func__, pMac->roam.configParam.nRoamScanHomeAwayTime, nRoamScanHomeAwayTime); pMac->roam.configParam.nRoamScanHomeAwayTime = nRoamScanHomeAwayTime; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled && bSendOffloadCmd) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_HOME_AWAY_TIME_CHANGED); } #endif return status; } /* --------------------------------------------------------------------------- \fn sme_getRoamIntraBand \brief get Intra band roaming \param hHal - HAL handle for device \- return Success or failure -------------------------------------------------------------------------*/ v_BOOL_t sme_getRoamIntraBand(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_GET_ROAMIBAND, NO_SESSION, 0)); return pMac->roam.configParam.nRoamIntraBand; } /* --------------------------------------------------------------------------- \fn sme_getRoamScanNProbes \brief get N Probes \param hHal - HAL handle for device \- return Success or failure -------------------------------------------------------------------------*/ v_U8_t sme_getRoamScanNProbes(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.nProbes; } /* --------------------------------------------------------------------------- \fn sme_getRoamScanHomeAwayTime \brief get Roam scan home away time \param hHal - HAL handle for device \- return Success or failure -------------------------------------------------------------------------*/ v_U16_t sme_getRoamScanHomeAwayTime(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.nRoamScanHomeAwayTime; } /* --------------------------------------------------------------------------- \fn sme_UpdateImmediateRoamRssiDiff \brief Update nImmediateRoamRssiDiff This function is called through dynamic setConfig callback function to configure nImmediateRoamRssiDiff Usage: adb shell iwpriv wlan0 setConfig gImmediateRoamRssiDiff=[0 .. 125] \param hHal - HAL handle for device \param nImmediateRoamRssiDiff - minimum rssi difference between potential candidate and current AP. \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_UpdateImmediateRoamRssiDiff(tHalHandle hHal, v_U8_t nImmediateRoamRssiDiff) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_UPDATE_IMMRSSIDIFF, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set immediate roam rssi diff to" "%d - old value is %d - roam state is %s", nImmediateRoamRssiDiff, pMac->roam.configParam.nImmediateRoamRssiDiff, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.nImmediateRoamRssiDiff = nImmediateRoamRssiDiff; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_UpdateRoamRssiDiff \brief Update RoamRssiDiff This function is called through dynamic setConfig callback function to configure RoamRssiDiff Usage: adb shell iwpriv wlan0 setConfig RoamRssiDiff=[0 .. 125] \param hHal - HAL handle for device \param RoamRssiDiff - minimum rssi difference between potential candidate and current AP. \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_UpdateRoamRssiDiff(tHalHandle hHal, v_U8_t RoamRssiDiff) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_UPDATE_RSSIDIFF, NO_SESSION, 0)); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set roam rssi diff to %d" " - old value is %d - roam state is %s", RoamRssiDiff, pMac->roam.configParam.RoamRssiDiff, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.RoamRssiDiff = RoamRssiDiff; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_RSSI_DIFF_CHANGED); } #endif return status ; } /*-------------------------------------------------------------------------- \brief sme_UpdateFastTransitionEnabled() - enable/disable Fast Transition support at runtime It is used at in the REG_DYNAMIC_VARIABLE macro definition of isFastTransitionEnabled. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update isFastTransitionEnabled config successfully. Other status means SME is failed to update isFastTransitionEnabled. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateFastTransitionEnabled(tHalHandle hHal, v_BOOL_t isFastTransitionEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_UPDATE_FTENABLED, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: FastTransitionEnabled is changed from %d to %d", __func__, pMac->roam.configParam.isFastTransitionEnabled, isFastTransitionEnabled); pMac->roam.configParam.isFastTransitionEnabled = isFastTransitionEnabled; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_UpdateWESMode \brief Update WES Mode This function is called through dynamic setConfig callback function to configure isWESModeEnabled \param hHal - HAL handle for device \return eHAL_STATUS_SUCCESS - SME update isWESModeEnabled config successfully. Other status means SME is failed to update isWESModeEnabled. -------------------------------------------------------------------------*/ eHalStatus sme_UpdateWESMode(tHalHandle hHal, v_BOOL_t isWESModeEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set WES Mode to %d" "- old value is %d - roam state is %s", isWESModeEnabled, pMac->roam.configParam.isWESModeEnabled, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.isWESModeEnabled = isWESModeEnabled; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_SetRoamScanControl \brief Set roam scan control This function is called to set roam scan control if roam scan control is set to 0, roaming scan cache is cleared any value other than 0 is treated as invalid value \param hHal - HAL handle for device \return eHAL_STATUS_SUCCESS - SME update config successfully. Other status means SME failure to update -------------------------------------------------------------------------*/ eHalStatus sme_SetRoamScanControl(tHalHandle hHal, v_BOOL_t roamScanControl) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_SET_SCANCTRL, NO_SESSION, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set roam scan control to %d" " - old value is %d - roam state is %s", roamScanControl, pMac->roam.configParam.nRoamScanControl, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.nRoamScanControl = roamScanControl; if ( 0 == roamScanControl) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully cleared roam scan cache"); csrFlushCfgBgScanRoamChannelList(pMac); #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_FLUSH_CHANNEL_LIST); } #endif } sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } #endif /* (WLAN_FEATURE_VOWIFI_11R) || (FEATURE_WLAN_ESE) || (FEATURE_WLAN_LFR) */ #ifdef FEATURE_WLAN_LFR /*-------------------------------------------------------------------------- \brief sme_UpdateIsFastRoamIniFeatureEnabled() - enable/disable LFR support at runtime It is used at in the REG_DYNAMIC_VARIABLE macro definition of isFastRoamIniFeatureEnabled. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update isFastRoamIniFeatureEnabled config successfully. Other status means SME is failed to update isFastRoamIniFeatureEnabled. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateIsFastRoamIniFeatureEnabled(tHalHandle hHal, const v_BOOL_t isFastRoamIniFeatureEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (pMac->roam.configParam.isFastRoamIniFeatureEnabled == isFastRoamIniFeatureEnabled) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: FastRoam is already enabled or disabled, nothing to do (returning) old(%d) new(%d)", __func__, pMac->roam.configParam.isFastRoamIniFeatureEnabled, isFastRoamIniFeatureEnabled); return eHAL_STATUS_SUCCESS; } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: FastRoamEnabled is changed from %d to %d", __func__, pMac->roam.configParam.isFastRoamIniFeatureEnabled, isFastRoamIniFeatureEnabled); pMac->roam.configParam.isFastRoamIniFeatureEnabled = isFastRoamIniFeatureEnabled; csrNeighborRoamUpdateFastRoamingEnabled(pMac, isFastRoamIniFeatureEnabled); return eHAL_STATUS_SUCCESS; } /*-------------------------------------------------------------------------- \brief sme_ConfigFwrRoaming() - enable/disable LFR support at runtime When Supplicant issue enabled / disable fwr based roaming on the basis of the Bssid modification in network block ( e.g. AutoJoin mody N/W block) This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME (enabled/disabled) offload scan successfully. Other status means SME is failed to (enabled/disabled) offload scan. \sa --------------------------------------------------------------------------*/ eHalStatus sme_ConfigFwrRoaming(tHalHandle hHal, const v_BOOL_t isFastRoamEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (!pMac->roam.configParam.isFastRoamIniFeatureEnabled) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: FastRoam is disabled through ini", __func__); return eHAL_STATUS_FAILURE; } csrNeighborRoamUpdateFastRoamingEnabled(pMac, isFastRoamEnabled); return eHAL_STATUS_SUCCESS; } /*-------------------------------------------------------------------------- \brief sme_UpdateIsMAWCIniFeatureEnabled() - Enable/disable LFR MAWC support at runtime It is used at in the REG_DYNAMIC_VARIABLE macro definition of isMAWCIniFeatureEnabled. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update MAWCEnabled config successfully. Other status means SME is failed to update MAWCEnabled. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateIsMAWCIniFeatureEnabled(tHalHandle hHal, const v_BOOL_t MAWCEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: MAWCEnabled is changed from %d to %d", __func__, pMac->roam.configParam.MAWCEnabled, MAWCEnabled); pMac->roam.configParam.MAWCEnabled = MAWCEnabled; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD /*-------------------------------------------------------------------------- \brief sme_UpdateEnableFastRoamInConcurrency() - enable/disable LFR if Concurrent session exists This is a synchronuous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS Other status means SME is failed \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateEnableFastRoamInConcurrency(tHalHandle hHal, v_BOOL_t bFastRoamInConIniFeatureEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pMac->roam.configParam.bFastRoamInConIniFeatureEnabled = bFastRoamInConIniFeatureEnabled; if (0 == pMac->roam.configParam.isRoamOffloadScanEnabled) { pMac->roam.configParam.bFastRoamInConIniFeatureEnabled = 0; } sme_ReleaseGlobalLock( &pMac->sme ); } return status; } #endif #endif /* FEATURE_WLAN_LFR */ #ifdef FEATURE_WLAN_ESE /*-------------------------------------------------------------------------- \brief sme_UpdateIsEseFeatureEnabled() - enable/disable Ese support at runtime It is used at in the REG_DYNAMIC_VARIABLE macro definition of isEseIniFeatureEnabled. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update isEseIniFeatureEnabled config successfully. Other status means SME is failed to update isEseIniFeatureEnabled. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateIsEseFeatureEnabled(tHalHandle hHal, const v_BOOL_t isEseIniFeatureEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (pMac->roam.configParam.isEseIniFeatureEnabled == isEseIniFeatureEnabled) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: Ese Mode is already enabled or disabled, nothing to do (returning) old(%d) new(%d)", __func__, pMac->roam.configParam.isEseIniFeatureEnabled, isEseIniFeatureEnabled); return eHAL_STATUS_SUCCESS; } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: EseEnabled is changed from %d to %d", __func__, pMac->roam.configParam.isEseIniFeatureEnabled, isEseIniFeatureEnabled); pMac->roam.configParam.isEseIniFeatureEnabled = isEseIniFeatureEnabled; csrNeighborRoamUpdateEseModeEnabled(pMac, isEseIniFeatureEnabled); if(TRUE == isEseIniFeatureEnabled) { sme_UpdateFastTransitionEnabled(hHal, TRUE); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_ESE_INI_CFG_CHANGED); } #endif return eHAL_STATUS_SUCCESS; } #endif /* FEATURE_WLAN_ESE */ /*-------------------------------------------------------------------------- \brief sme_UpdateConfigFwRssiMonitoring() - enable/disable firmware RSSI Monitoring at runtime It is used at in the REG_DYNAMIC_VARIABLE macro definition of fEnableFwRssiMonitoring. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update fEnableFwRssiMonitoring. config successfully. Other status means SME is failed to update fEnableFwRssiMonitoring. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateConfigFwRssiMonitoring(tHalHandle hHal, v_BOOL_t fEnableFwRssiMonitoring) { eHalStatus halStatus = eHAL_STATUS_SUCCESS; if (ccmCfgSetInt(hHal, WNI_CFG_PS_ENABLE_RSSI_MONITOR, fEnableFwRssiMonitoring, NULL, eANI_BOOLEAN_FALSE)==eHAL_STATUS_FAILURE) { halStatus = eHAL_STATUS_FAILURE; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "Failure: Could not pass on WNI_CFG_PS_RSSI_MONITOR configuration info to CCM"); } return (halStatus); } #ifdef WLAN_FEATURE_NEIGHBOR_ROAMING /*-------------------------------------------------------------------------- \brief sme_setNeighborLookupRssiThreshold() - update neighbor lookup rssi threshold This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ eHalStatus sme_setNeighborLookupRssiThreshold(tHalHandle hHal, v_U8_t neighborLookupRssiThreshold) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrNeighborRoamSetLookupRssiThreshold(pMac, neighborLookupRssiThreshold); if (HAL_STATUS_SUCCESS(status)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set Lookup threshold to %d" " - old value is %d - roam state is %s", neighborLookupRssiThreshold, pMac->roam.configParam.neighborRoamConfig.nNeighborLookupRssiThreshold, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nNeighborLookupRssiThreshold = neighborLookupRssiThreshold; } sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /*-------------------------------------------------------------------------- \brief sme_setNeighborReassocRssiThreshold() - update neighbor reassoc rssi threshold This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ eHalStatus sme_setNeighborReassocRssiThreshold(tHalHandle hHal, v_U8_t neighborReassocRssiThreshold) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set Reassoc threshold to %d" "- old value is %d - roam state is %s", neighborReassocRssiThreshold, pMac->roam.configParam.neighborRoamConfig.nNeighborReassocRssiThreshold, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nNeighborReassocRssiThreshold = neighborReassocRssiThreshold; pMac->roam.neighborRoamInfo.cfgParams.neighborReassocThreshold = neighborReassocRssiThreshold; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /*-------------------------------------------------------------------------- \brief sme_getNeighborLookupRssiThreshold() - get neighbor lookup rssi threshold This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ v_U8_t sme_getNeighborLookupRssiThreshold(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.neighborRoamConfig.nNeighborLookupRssiThreshold; } /*-------------------------------------------------------------------------- \brief sme_setNeighborScanRefreshPeriod() - set neighbor scan results refresh period This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ eHalStatus sme_setNeighborScanRefreshPeriod(tHalHandle hHal, v_U16_t neighborScanResultsRefreshPeriod) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set roam scan refresh period to %d" " - old value is %d - roam state is %s", neighborScanResultsRefreshPeriod, pMac->roam.configParam.neighborRoamConfig.nNeighborResultsRefreshPeriod, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nNeighborResultsRefreshPeriod = neighborScanResultsRefreshPeriod; pMac->roam.neighborRoamInfo.cfgParams.neighborResultsRefreshPeriod = neighborScanResultsRefreshPeriod; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_NEIGHBOR_SCAN_REFRESH_PERIOD_CHANGED); } #endif return status ; } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD /*-------------------------------------------------------------------------- \brief sme_UpdateRoamScanOffloadEnabled() - enable/disable roam scan offload feaure It is used at in the REG_DYNAMIC_VARIABLE macro definition of gRoamScanOffloadEnabled. This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successfully. Other status means SME is failed to update. \sa --------------------------------------------------------------------------*/ eHalStatus sme_UpdateRoamScanOffloadEnabled(tHalHandle hHal, v_BOOL_t nRoamScanOffloadEnabled) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: gRoamScanOffloadEnabled is changed from %d to %d", __func__, pMac->roam.configParam.isRoamOffloadScanEnabled, nRoamScanOffloadEnabled); pMac->roam.configParam.isRoamOffloadScanEnabled = nRoamScanOffloadEnabled; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } #endif /*-------------------------------------------------------------------------- \brief sme_getNeighborScanRefreshPeriod() - get neighbor scan results refresh period This is a synchronous call \param hHal - The handle returned by macOpen. \return v_U16_t - Neighbor scan results refresh period value \sa --------------------------------------------------------------------------*/ v_U16_t sme_getNeighborScanRefreshPeriod(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.neighborRoamConfig.nNeighborResultsRefreshPeriod; } /*-------------------------------------------------------------------------- \brief sme_getEmptyScanRefreshPeriod() - get empty scan refresh period This is a synchronuous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ v_U16_t sme_getEmptyScanRefreshPeriod(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.neighborRoamConfig.nEmptyScanRefreshPeriod; } /* --------------------------------------------------------------------------- \fn sme_UpdateEmptyScanRefreshPeriod \brief Update nEmptyScanRefreshPeriod This function is called through dynamic setConfig callback function to configure nEmptyScanRefreshPeriod Usage: adb shell iwpriv wlan0 setConfig nEmptyScanRefreshPeriod=[0 .. 60] \param hHal - HAL handle for device \param nEmptyScanRefreshPeriod - scan period following empty scan results. \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_UpdateEmptyScanRefreshPeriod(tHalHandle hHal, v_U16_t nEmptyScanRefreshPeriod) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set roam scan period to %d -" "old value is %d - roam state is %s", nEmptyScanRefreshPeriod, pMac->roam.configParam.neighborRoamConfig.nEmptyScanRefreshPeriod, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nEmptyScanRefreshPeriod = nEmptyScanRefreshPeriod; pMac->roam.neighborRoamInfo.cfgParams.emptyScanRefreshPeriod = nEmptyScanRefreshPeriod; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_EMPTY_SCAN_REF_PERIOD_CHANGED); } #endif return status ; } /* --------------------------------------------------------------------------- \fn sme_setNeighborScanMinChanTime \brief Update nNeighborScanMinChanTime This function is called through dynamic setConfig callback function to configure gNeighborScanChannelMinTime Usage: adb shell iwpriv wlan0 setConfig gNeighborScanChannelMinTime=[0 .. 60] \param hHal - HAL handle for device \param nNeighborScanMinChanTime - Channel minimum dwell time \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_setNeighborScanMinChanTime(tHalHandle hHal, const v_U16_t nNeighborScanMinChanTime) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set channel min dwell time to %d" " - old value is %d - roam state is %s", nNeighborScanMinChanTime, pMac->roam.configParam.neighborRoamConfig.nNeighborScanMinChanTime, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nNeighborScanMinChanTime = nNeighborScanMinChanTime; pMac->roam.neighborRoamInfo.cfgParams.minChannelScanTime = nNeighborScanMinChanTime; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_setNeighborScanMaxChanTime \brief Update nNeighborScanMaxChanTime This function is called through dynamic setConfig callback function to configure gNeighborScanChannelMaxTime Usage: adb shell iwpriv wlan0 setConfig gNeighborScanChannelMaxTime=[0 .. 60] \param hHal - HAL handle for device \param nNeighborScanMinChanTime - Channel maximum dwell time \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_setNeighborScanMaxChanTime(tHalHandle hHal, const v_U16_t nNeighborScanMaxChanTime) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set channel max dwell time to %d" " - old value is %d - roam state is %s", nNeighborScanMaxChanTime, pMac->roam.configParam.neighborRoamConfig.nNeighborScanMaxChanTime, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nNeighborScanMaxChanTime = nNeighborScanMaxChanTime; pMac->roam.neighborRoamInfo.cfgParams.maxChannelScanTime = nNeighborScanMaxChanTime; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_SCAN_CH_TIME_CHANGED); } #endif return status ; } /* --------------------------------------------------------------------------- \fn sme_getNeighborScanMinChanTime \brief get neighbor scan min channel time \param hHal - The handle returned by macOpen. \return v_U16_t - channel min time value -------------------------------------------------------------------------*/ v_U16_t sme_getNeighborScanMinChanTime(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.neighborRoamInfo.cfgParams.minChannelScanTime; } /* --------------------------------------------------------------------------- \fn sme_getNeighborScanMaxChanTime \brief get neighbor scan max channel time \param hHal - The handle returned by macOpen. \return v_U16_t - channel max time value -------------------------------------------------------------------------*/ v_U16_t sme_getNeighborScanMaxChanTime(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.neighborRoamInfo.cfgParams.maxChannelScanTime; } /* --------------------------------------------------------------------------- \fn sme_setNeighborScanPeriod \brief Update nNeighborScanPeriod This function is called through dynamic setConfig callback function to configure nNeighborScanPeriod Usage: adb shell iwpriv wlan0 setConfig nNeighborScanPeriod=[0 .. 1000] \param hHal - HAL handle for device \param nNeighborScanPeriod - neighbor scan period \- return Success or failure -------------------------------------------------------------------------*/ eHalStatus sme_setNeighborScanPeriod(tHalHandle hHal, const v_U16_t nNeighborScanPeriod) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set neighbor scan period to %d" " - old value is %d - roam state is %s", nNeighborScanPeriod, pMac->roam.configParam.neighborRoamConfig.nNeighborScanTimerPeriod, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); pMac->roam.configParam.neighborRoamConfig.nNeighborScanTimerPeriod = nNeighborScanPeriod; pMac->roam.neighborRoamInfo.cfgParams.neighborScanPeriod = nNeighborScanPeriod; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_SCAN_HOME_TIME_CHANGED); } #endif return status ; } /* --------------------------------------------------------------------------- \fn sme_getNeighborScanPeriod \brief get neighbor scan period \param hHal - The handle returned by macOpen. \return v_U16_t - neighbor scan period -------------------------------------------------------------------------*/ v_U16_t sme_getNeighborScanPeriod(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.neighborRoamInfo.cfgParams.neighborScanPeriod; } #endif #if defined (WLAN_FEATURE_VOWIFI_11R) || defined (FEATURE_WLAN_ESE) || defined(FEATURE_WLAN_LFR) /*-------------------------------------------------------------------------- \brief sme_getRoamRssiDiff() - get Roam rssi diff This is a synchronous call \param hHal - The handle returned by macOpen. \return v_U16_t - Rssi diff value \sa --------------------------------------------------------------------------*/ v_U8_t sme_getRoamRssiDiff(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.RoamRssiDiff; } /*-------------------------------------------------------------------------- \brief sme_ChangeRoamScanChannelList() - Change roam scan channel list This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ eHalStatus sme_ChangeRoamScanChannelList(tHalHandle hHal, tANI_U8 *pChannelList, tANI_U8 numChannels) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo; tANI_U8 oldChannelList[WNI_CFG_VALID_CHANNEL_LIST_LEN*2] = {0}; tANI_U8 newChannelList[WNI_CFG_VALID_CHANNEL_LIST_LEN*2] = {0}; tANI_U8 i = 0, j = 0; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if (NULL != pNeighborRoamInfo->cfgParams.channelInfo.ChannelList) { for (i = 0; i < pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels; i++) { if (j < sizeof(oldChannelList)) { j += snprintf(oldChannelList + j, sizeof(oldChannelList) - j," %d", pNeighborRoamInfo->cfgParams.channelInfo.ChannelList[i]); } else { break; } } } csrFlushCfgBgScanRoamChannelList(pMac); csrCreateBgScanRoamChannelList(pMac, pChannelList, numChannels); sme_SetRoamScanControl(hHal, 1); if (NULL != pNeighborRoamInfo->cfgParams.channelInfo.ChannelList) { j = 0; for (i = 0; i < pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels; i++) { if (j < sizeof(oldChannelList)) { j += snprintf(newChannelList + j, sizeof(newChannelList) - j," %d", pNeighborRoamInfo->cfgParams.channelInfo.ChannelList[i]); } else { break; } } } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set roam scan channels to %s" "- old value is %s - roam state is %s", newChannelList, oldChannelList, macTraceGetNeighbourRoamState( pMac->roam.neighborRoamInfo.neighborRoamState)); sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_CHANNEL_LIST_CHANGED); } #endif return status ; } #ifdef FEATURE_WLAN_ESE_UPLOAD /*-------------------------------------------------------------------------- \brief sme_SetEseRoamScanChannelList() - set ese roam scan channel list This is a synchronuous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ eHalStatus sme_SetEseRoamScanChannelList(tHalHandle hHal, tANI_U8 *pChannelList, tANI_U8 numChannels) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo; tpCsrChannelInfo currChannelListInfo = &pNeighborRoamInfo->roamChannelInfo.currentChannelListInfo; tANI_U8 oldChannelList[WNI_CFG_VALID_CHANNEL_LIST_LEN*2] = {0}; tANI_U8 newChannelList[128] = {0}; tANI_U8 i = 0, j = 0; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if (NULL != currChannelListInfo->ChannelList) { for (i = 0; i < currChannelListInfo->numOfChannels; i++) { j += snprintf(oldChannelList + j, sizeof(oldChannelList) - j," %d", currChannelListInfo->ChannelList[i]); } } status = csrCreateRoamScanChannelList(pMac, pChannelList, numChannels, csrGetCurrentBand(hHal)); if ( HAL_STATUS_SUCCESS( status )) { if (NULL != currChannelListInfo->ChannelList) { j = 0; for (i = 0; i < currChannelListInfo->numOfChannels; i++) { j += snprintf(newChannelList + j, sizeof(newChannelList) - j," %d", currChannelListInfo->ChannelList[i]); } } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "ESE roam scan channel list successfully set to %s - old value is %s - roam state is %s", newChannelList, oldChannelList, macTraceGetNeighbourRoamState(pMac->roam.neighborRoamInfo.neighborRoamState)); } sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (pMac->roam.configParam.isRoamOffloadScanEnabled) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_CHANNEL_LIST_CHANGED); } #endif return status ; } #endif /*-------------------------------------------------------------------------- \brief sme_getRoamScanChannelList() - get roam scan channel list This is a synchronous call \param hHal - The handle returned by macOpen. \return eHAL_STATUS_SUCCESS - SME update config successful. Other status means SME is failed to update \sa --------------------------------------------------------------------------*/ eHalStatus sme_getRoamScanChannelList(tHalHandle hHal, tANI_U8 *pChannelList, tANI_U8 *pNumChannels) { int i = 0; tANI_U8 *pOutPtr = pChannelList; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tpCsrNeighborRoamControlInfo pNeighborRoamInfo = &pMac->roam.neighborRoamInfo; eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { if (NULL == pNeighborRoamInfo->cfgParams.channelInfo.ChannelList) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_WARN, "Roam Scan channel list is NOT yet initialized"); *pNumChannels = 0; sme_ReleaseGlobalLock( &pMac->sme ); return status; } *pNumChannels = pNeighborRoamInfo->cfgParams.channelInfo.numOfChannels; for (i = 0; i < (*pNumChannels); i++) { pOutPtr[i] = pNeighborRoamInfo->cfgParams.channelInfo.ChannelList[i]; } pOutPtr[i] = '\0'; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /*-------------------------------------------------------------------------- \brief sme_getIsEseFeatureEnabled() - get Ese feature enabled or not This is a synchronuous call \param hHal - The handle returned by macOpen. \return TRUE (1) - if the Ese feature is enabled FALSE (0) - if feature is disabled (compile or runtime) \sa --------------------------------------------------------------------------*/ tANI_BOOLEAN sme_getIsEseFeatureEnabled(tHalHandle hHal) { #ifdef FEATURE_WLAN_ESE tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return csrRoamIsEseIniFeatureEnabled(pMac); #else return eANI_BOOLEAN_FALSE; #endif } /*-------------------------------------------------------------------------- \brief sme_GetWESMode() - get WES Mode This is a synchronous call \param hHal - The handle returned by macOpen \return v_U8_t - WES Mode Enabled(1)/Disabled(0) \sa --------------------------------------------------------------------------*/ v_BOOL_t sme_GetWESMode(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.isWESModeEnabled; } /*-------------------------------------------------------------------------- \brief sme_GetRoamScanControl() - get scan control This is a synchronous call \param hHal - The handle returned by macOpen. \return v_BOOL_t - Enabled(1)/Disabled(0) \sa --------------------------------------------------------------------------*/ v_BOOL_t sme_GetRoamScanControl(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.nRoamScanControl; } #endif /*-------------------------------------------------------------------------- \brief sme_getIsLfrFeatureEnabled() - get LFR feature enabled or not This is a synchronuous call \param hHal - The handle returned by macOpen. \return TRUE (1) - if the feature is enabled FALSE (0) - if feature is disabled (compile or runtime) \sa --------------------------------------------------------------------------*/ tANI_BOOLEAN sme_getIsLfrFeatureEnabled(tHalHandle hHal) { #ifdef FEATURE_WLAN_LFR tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.isFastRoamIniFeatureEnabled; #else return eANI_BOOLEAN_FALSE; #endif } /*-------------------------------------------------------------------------- \brief sme_getIsFtFeatureEnabled() - get FT feature enabled or not This is a synchronuous call \param hHal - The handle returned by macOpen. \return TRUE (1) - if the feature is enabled FALSE (0) - if feature is disabled (compile or runtime) \sa --------------------------------------------------------------------------*/ tANI_BOOLEAN sme_getIsFtFeatureEnabled(tHalHandle hHal) { #ifdef WLAN_FEATURE_VOWIFI_11R tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->roam.configParam.isFastTransitionEnabled; #else return eANI_BOOLEAN_FALSE; #endif } /* --------------------------------------------------------------------------- \fn sme_IsFeatureSupportedByFW \brief Check if a feature is enabled by FW \param featEnumValue - Enumeration value from placeHolderInCapBitmap \- return 1/0 (TRUE/FALSE) -------------------------------------------------------------------------*/ tANI_U8 sme_IsFeatureSupportedByFW(tANI_U8 featEnumValue) { return IS_FEATURE_SUPPORTED_BY_FW(featEnumValue); } /* --------------------------------------------------------------------------- \fn sme_IsFeatureSupportedByDriver \brief Check if a feature is enabled by Driver \param featEnumValue - Enumeration value from placeHolderInCapBitmap \- return 1/0 (TRUE/FALSE) -------------------------------------------------------------------------*/ tANI_U8 sme_IsFeatureSupportedByDriver(tANI_U8 featEnumValue) { return IS_FEATURE_SUPPORTED_BY_DRIVER(featEnumValue); } #ifdef FEATURE_WLAN_TDLS /* --------------------------------------------------------------------------- \fn sme_SendTdlsMgmtFrame \brief API to send TDLS management frames. \param peerMac - peer's Mac Adress. \param tdlsLinkEstablishParams - TDLS Peer Link Establishment Parameters \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ VOS_STATUS sme_SendTdlsLinkEstablishParams(tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tSirMacAddr peerMac, #else tSirMacAddr peerMac, #endif tCsrTdlsLinkEstablishParams *tdlsLinkEstablishParams) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_TDLS_LINK_ESTABLISH_PARAM, sessionId, tdlsLinkEstablishParams->isOffChannelSupported)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrTdlsSendLinkEstablishParams(hHal, sessionId, peerMac, tdlsLinkEstablishParams) ; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } // tdlsoffchan /* --------------------------------------------------------------------------- \fn sme_SendTdlsChanSwitchReq \brief API to send TDLS management frames. \param peerMac - peer's Mac Adress. \param tdlsLinkEstablishParams - TDLS Peer Link Establishment Parameters \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ VOS_STATUS sme_SendTdlsChanSwitchReq(tHalHandle hHal, tANI_U8 sessionId, tSirMacAddr peerMac, tANI_S32 tdlsOffCh, tANI_S32 tdlsOffChBwOffset, tANI_U8 tdlsSwMode) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_TDLS_CHAN_SWITCH_REQ, sessionId, tdlsOffCh)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrTdlsSendChanSwitchReq(hHal, sessionId, peerMac, tdlsOffCh, tdlsOffChBwOffset, tdlsSwMode); } sme_ReleaseGlobalLock( &pMac->sme ); return status ; } /* --------------------------------------------------------------------------- \fn sme_SendTdlsMgmtFrame \brief API to send TDLS management frames. \param peerMac - peer's Mac Adress. \param frame_type - Type of TDLS mgmt frame to be sent. \param dialog - dialog token used in the frame. \param status - status to be incuded in the frame. \param peerCapability - peer cpabilities \param buf - additional IEs to be included \param len - lenght of additional Ies \param responder - Tdls request type \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ VOS_STATUS sme_SendTdlsMgmtFrame(tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tSirMacAddr peerMac, #else tSirMacAddr peerMac, #endif tANI_U8 frame_type, tANI_U8 dialog, tANI_U16 statusCode, tANI_U32 peerCapability, tANI_U8 *buf, tANI_U8 len, tANI_U8 responder) { eHalStatus status = eHAL_STATUS_SUCCESS; tCsrTdlsSendMgmt sendTdlsReq = {{0}} ; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_TDLS_SEND_MGMT_FRAME, sessionId, statusCode)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { vos_mem_copy(sendTdlsReq.peerMac, peerMac, sizeof(tSirMacAddr)) ; sendTdlsReq.frameType = frame_type; sendTdlsReq.buf = buf; sendTdlsReq.len = len; sendTdlsReq.dialog = dialog; sendTdlsReq.statusCode = statusCode; sendTdlsReq.responder = responder; sendTdlsReq.peerCapability = peerCapability; status = csrTdlsSendMgmtReq(hHal, sessionId, &sendTdlsReq) ; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_ChangeTdlsPeerSta \brief API to Update TDLS peer sta parameters. \param peerMac - peer's Mac Adress. \param staParams - Peer Station Parameters \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ VOS_STATUS sme_ChangeTdlsPeerSta(tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tSirMacAddr peerMac, #else tSirMacAddr peerMac, #endif tCsrStaParams *pstaParams) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (NULL == pstaParams) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s :pstaParams is NULL",__func__); return eHAL_STATUS_FAILURE; } MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_TDLS_CHANGE_PEER_STA, sessionId, pstaParams->capability)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrTdlsChangePeerSta(hHal, sessionId, peerMac, pstaParams); sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_AddTdlsPeerSta \brief API to Add TDLS peer sta entry. \param peerMac - peer's Mac Adress. \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ VOS_STATUS sme_AddTdlsPeerSta(tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tSirMacAddr peerMac #else tSirMacAddr peerMac #endif ) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_TDLS_ADD_PEER_STA, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrTdlsAddPeerSta(hHal, sessionId, peerMac); sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_DeleteTdlsPeerSta \brief API to Delete TDLS peer sta entry. \param peerMac - peer's Mac Adress. \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ VOS_STATUS sme_DeleteTdlsPeerSta(tHalHandle hHal, tANI_U8 sessionId, #if (LINUX_VERSION_CODE >= KERNEL_VERSION(3,18,0)) const tSirMacAddr peerMac #else tSirMacAddr peerMac #endif ) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_TDLS_DEL_PEER_STA, sessionId, 0)); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { status = csrTdlsDelPeerSta(hHal, sessionId, peerMac) ; sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } /* --------------------------------------------------------------------------- \fn sme_SetTdlsPowerSaveProhibited \API to set/reset the isTdlsPowerSaveProhibited. \- return void -------------------------------------------------------------------------*/ void sme_SetTdlsPowerSaveProhibited(tHalHandle hHal, v_BOOL_t val) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); pMac->isTdlsPowerSaveProhibited = val; smsLog(pMac, LOG1, FL("isTdlsPowerSaveProhibited is %d"), pMac->isTdlsPowerSaveProhibited); return; } #endif /* --------------------------------------------------------------------------- \fn sme_IsPmcBmps \API to Check if PMC state is BMPS. \- return v_BOOL_t -------------------------------------------------------------------------*/ v_BOOL_t sme_IsPmcBmps(tHalHandle hHal) { return (BMPS == pmcGetPmcState(hHal)); } eHalStatus sme_UpdateDfsSetting(tHalHandle hHal, tANI_U8 fUpdateEnableDFSChnlScan) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); smsLog(pMac, LOG2, FL("enter")); if (pMac->fActiveScanOnDFSChannels) { smsLog(pMac, LOG1, FL("Skip updating fEnableDFSChnlScan" " as DFS feature is triggered")); return (status); } status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pMac->scan.fEnableDFSChnlScan = fUpdateEnableDFSChnlScan; sme_ReleaseGlobalLock( &pMac->sme ); } smsLog(pMac, LOG2, FL("exit status %d"), status); return (status); } /* --------------------------------------------------------------------------- \fn sme_UpdateDFSRoamMode \brief Update DFS roam scan mode This function is called to configure allowDFSChannelRoam dynamically \param hHal - HAL handle for device \param allowDFSChannelRoam - DFS roaming scan mode mode 0 disable roam scan on DFS channels mode 1 enables roam scan (passive/active) on DFS channels \return eHAL_STATUS_SUCCESS - SME update DFS roaming scan config successfully. Other status means SME failed to update DFS roaming scan config. \sa -------------------------------------------------------------------------*/ eHalStatus sme_UpdateDFSRoamMode(tHalHandle hHal, tANI_U8 allowDFSChannelRoam) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "LFR runtime successfully set AllowDFSChannelRoam Mode to " "%d - old value is %d", allowDFSChannelRoam, pMac->roam.configParam.allowDFSChannelRoam); pMac->roam.configParam.allowDFSChannelRoam = allowDFSChannelRoam; sme_ReleaseGlobalLock( &pMac->sme ); } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD if (csrRoamIsRoamOffloadScanEnabled(pMac)) { csrRoamOffloadScan(pMac, ROAM_SCAN_OFFLOAD_UPDATE_CFG, REASON_CHANNEL_LIST_CHANGED); } #endif return status ; } /* --------------------------------------------------------------------------- \fn sme_UpdateDFSScanMode \brief Update DFS scan mode This function is called to configure fEnableDFSChnlScan. \param hHal - HAL handle for device \param dfsScanMode - DFS scan mode mode 0 disable scan on DFS channels mode 1 enables passive scan on DFS channels mode 2 enables active scan on DFS channels for static list \return eHAL_STATUS_SUCCESS - SME update DFS roaming scan config successfully. Other status means SME failed to update DFS scan config. \sa -------------------------------------------------------------------------*/ eHalStatus sme_UpdateDFSScanMode(tHalHandle hHal, tANI_U8 dfsScanMode) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "DFS scan Mode changed to %d, old value is %d ", dfsScanMode, pMac->scan.fEnableDFSChnlScan); pMac->scan.fEnableDFSChnlScan = dfsScanMode; sme_ReleaseGlobalLock( &pMac->sme ); } sme_FilterScanDFSResults(hHal); sme_UpdateChannelList( hHal ); return status ; } /*-------------------------------------------------------------------------- \brief sme_GetDFSScanMode() - get DFS scan mode \param hHal - The handle returned by macOpen. \return DFS scan mode mode 0 disable scan on DFS channels mode 1 enables passive scan on DFS channels mode 2 enables active scan on DFS channels for static list \sa --------------------------------------------------------------------------*/ v_U8_t sme_GetDFSScanMode(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); return pMac->scan.fEnableDFSChnlScan; } /* --------------------------------------------------------------------------- \fn sme_HandleDFSChanScan \brief Gets Valid channel list and updates scan control list according to dfsScanMode \param hHal - HAL handle for device \return eHAL_STATUS_FAILURE when failed to get valid channel list Otherwise eHAL_STATUS_SUCCESS - \sa -------------------------------------------------------------------------*/ eHalStatus sme_HandleDFSChanScan(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; tCsrChannel ChannelList; /* * Set Flag to block driver scan type conversion from active to passive * and vice versa in case if fEnableDFSChnlScan is * DFS_CHNL_SCAN_ENABLED_ACTIVE */ if (DFS_CHNL_SCAN_ENABLED_ACTIVE == pMac->scan.fEnableDFSChnlScan) pMac->fActiveScanOnDFSChannels = 1; else pMac->fActiveScanOnDFSChannels = 0; ChannelList.numChannels = sizeof(ChannelList.channelList); status = sme_GetCfgValidChannels(hHal, (tANI_U8 *)ChannelList.channelList, (tANI_U32*)&ChannelList.numChannels); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, LOGE, FL("Failed to get valid channel list (err=%d)"), status); return status; } smsLog(pMac, LOG1, FL("Valid Channel list:")); VOS_TRACE_HEX_DUMP(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, ChannelList.channelList, ChannelList.numChannels); sme_SetCfgScanControlList(hHal, pMac->scan.countryCodeCurrent, &ChannelList); return status ; } /* * SME API to enable/disable WLAN driver initiated SSR */ void sme_UpdateEnableSSR(tHalHandle hHal, tANI_BOOLEAN enableSSR) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_DEBUG, "SSR level is changed %d", enableSSR); /* not serializing this messsage, as this is only going * to set a variable in WDA/WDI */ WDA_SetEnableSSR(enableSSR); sme_ReleaseGlobalLock(&pMac->sme); } return; } /* * SME API to stringify bonding mode. (hostapd convention) */ static const char* sme_CBMode2String( tANI_U32 mode) { switch (mode) { case eCSR_INI_SINGLE_CHANNEL_CENTERED: return "HT20"; case eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY: return "HT40-"; /* lower secondary channel */ case eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY: return "HT40+"; /* upper secondary channel */ #ifdef WLAN_FEATURE_11AC case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_LOW: return "VHT80+40+"; /* upper secondary channels */ case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_LOW: return "VHT80+40-"; /* 1 lower and 2 upper secondary channels */ case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_HIGH: return "VHT80-40+"; /* 2 lower and 1 upper secondary channels */ case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_HIGH: return "VHT80-40-"; /* lower secondary channels */ #endif default: VOS_ASSERT(0); return "Unknown"; } } /* * SME API to adjust bonding mode to regulatory .. etc. * */ static VOS_STATUS sme_AdjustCBMode(tAniSirGlobal* pMac, tSmeConfigParams *smeConfig, tANI_U8 channel) { const tANI_U8 step = SME_START_CHAN_STEP; tANI_U8 i, startChan = channel, chanCnt = 0, chanBitmap = 0; tANI_BOOLEAN violation = VOS_FALSE; tANI_U32 newMode, mode; tANI_U8 centerChan = channel; /* to validate 40MHz channels against the regulatory domain */ tANI_BOOLEAN ht40PhyMode = VOS_FALSE; /* get the bonding mode */ mode = (channel <= 14) ? smeConfig->csrConfig.channelBondingMode24GHz : smeConfig->csrConfig.channelBondingMode5GHz; newMode = mode; /* get the channels */ switch (mode) { case eCSR_INI_SINGLE_CHANNEL_CENTERED: startChan = channel; chanCnt = 1; break; case eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY: startChan = channel - step; chanCnt = 2; centerChan = channel - CSR_CB_CENTER_CHANNEL_OFFSET; ht40PhyMode = VOS_TRUE; break; case eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY: startChan = channel; chanCnt=2; centerChan = channel + CSR_CB_CENTER_CHANNEL_OFFSET; ht40PhyMode = VOS_TRUE; break; #ifdef WLAN_FEATURE_11AC case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_LOW: startChan = channel; chanCnt = 4; break; case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_LOW: startChan = channel - step; chanCnt = 4; break; case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_HIGH: startChan = channel - 2*step; chanCnt = 4; break; case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_HIGH: startChan = channel - 3*step; chanCnt = 4; break; #endif default: VOS_ASSERT(0); return VOS_STATUS_E_FAILURE; } /* find violation; also map valid channels to a bitmap */ for (i = 0; i < chanCnt; i++) { if (csrIsValidChannel(pMac, (startChan + (i * step))) == eHAL_STATUS_SUCCESS) chanBitmap = chanBitmap | 1 << i; else violation = VOS_TRUE; } /* validate if 40MHz channel is allowed */ if (ht40PhyMode) { if (!csrRoamIsValid40MhzChannel(pMac, centerChan)) violation = VOS_TRUE; } /* no channels are valid */ if (chanBitmap == 0) { /* never be in this case */ VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("channel %d %s is not supported"), channel, sme_CBMode2String(mode)); return VOS_STATUS_E_INVAL; } /* fix violation */ if (violation) { const tANI_U8 lowerMask = 0x03, upperMask = 0x0c; /* fall back to single channel in all exception cases */ newMode = eCSR_INI_SINGLE_CHANNEL_CENTERED; switch (mode) { case eCSR_INI_SINGLE_CHANNEL_CENTERED: /* fall thru */ case eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY: /* fall thru */ case eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY: break; #ifdef WLAN_FEATURE_11AC case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_LOW: if ((chanBitmap & lowerMask) == lowerMask) newMode = eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY; break; case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_LOW: if ((chanBitmap & lowerMask) == lowerMask) newMode = eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY; break; case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_HIGH: if ((chanBitmap & upperMask) == upperMask) newMode = eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY; break; case eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_HIGH: if ((chanBitmap & upperMask) == upperMask) newMode = eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY; break; #endif default: return VOS_STATUS_E_NOSUPPORT; break; } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_WARN, FL("bonding mode adjust: %s to %s"), sme_CBMode2String(mode), sme_CBMode2String(newMode)); } /* check for mode change */ if (newMode != mode) { if (channel <= 14) smeConfig->csrConfig.channelBondingMode24GHz = newMode; else smeConfig->csrConfig.channelBondingMode5GHz = newMode; } return VOS_STATUS_SUCCESS; } /* * SME API to determine the channel bonding mode */ VOS_STATUS sme_SelectCBMode(tHalHandle hHal, eCsrPhyMode eCsrPhyMode, tANI_U8 channel) { tSmeConfigParams smeConfig; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); #ifdef WLAN_FEATURE_11AC tANI_U8 vht80Allowed; #endif if ( #ifdef WLAN_FEATURE_11AC eCSR_DOT11_MODE_11ac != eCsrPhyMode && eCSR_DOT11_MODE_11ac_ONLY != eCsrPhyMode && #endif eCSR_DOT11_MODE_11n != eCsrPhyMode && eCSR_DOT11_MODE_11n_ONLY != eCsrPhyMode && eCSR_DOT11_MODE_11a != eCsrPhyMode && eCSR_DOT11_MODE_11a_ONLY != eCsrPhyMode && eCSR_DOT11_MODE_abg != eCsrPhyMode ) { return VOS_STATUS_SUCCESS; } vos_mem_zero(&smeConfig, sizeof (tSmeConfigParams)); sme_GetConfigParam(pMac, &smeConfig); /* If channel bonding mode is not required */ #ifdef WLAN_FEATURE_AP_HT40_24G if ( !pMac->roam.configParam.channelBondingMode5GHz && !smeConfig.csrConfig.apHT40_24GEnabled ) { #else if ( !pMac->roam.configParam.channelBondingMode5GHz ) { #endif return VOS_STATUS_SUCCESS; } #ifdef WLAN_FEATURE_11AC if ( eCSR_DOT11_MODE_11ac == eCsrPhyMode || eCSR_DOT11_MODE_11ac_ONLY == eCsrPhyMode ) { /* Check if VHT80 is allowed for the channel*/ vht80Allowed = vos_is_channel_valid_for_vht80(channel); if (vht80Allowed) { if (channel== 36 || channel == 52 || channel == 100 || channel == 116 || channel == 149) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_LOW; } else if (channel == 40 || channel == 56 || channel == 104 || channel == 120 || channel == 153) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_LOW; } else if (channel == 44 || channel == 60 || channel == 108 || channel == 124 || channel == 157) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_LOW_40MHZ_HIGH; } else if (channel == 48 || channel == 64 || channel == 112 || channel == 128 || channel == 144 || channel == 161) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_QUADRUPLE_CHANNEL_20MHZ_HIGH_40MHZ_HIGH; } else if (channel == 165) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_SINGLE_CHANNEL_CENTERED; } } else /* Set VHT40 */ { if (channel== 40 || channel == 48 || channel == 56 || channel == 64 || channel == 104 || channel == 112 || channel == 120 || channel == 128 || channel == 136 || channel == 144 || channel == 153 || channel == 161) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY; } else if (channel== 36 || channel == 44 || channel == 52 || channel == 60 || channel == 100 || channel == 108 || channel == 116 || channel == 124 || channel == 132 || channel == 140 || channel == 149 || channel == 157) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY; } else if (channel == 165) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_SINGLE_CHANNEL_CENTERED; } } #ifdef WLAN_FEATURE_AP_HT40_24G if (smeConfig.csrConfig.apHT40_24GEnabled) { if (channel >= 1 && channel <= 7) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY; else if (channel >= 8 && channel <= 13) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY; else if (channel ==14) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_SINGLE_CHANNEL_CENTERED; } #endif } #endif if ( eCSR_DOT11_MODE_11n == eCsrPhyMode || eCSR_DOT11_MODE_11n_ONLY == eCsrPhyMode ) { if ( channel== 40 || channel == 48 || channel == 56 || channel == 64 || channel == 104 || channel == 112 || channel == 120 || channel == 128 || channel == 136 || channel == 144 || channel == 153 || channel == 161 ) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY; } else if ( channel== 36 || channel == 44 || channel == 52 || channel == 60 || channel == 100 || channel == 108 || channel == 116 || channel == 124 || channel == 132 || channel == 140 || channel == 149 || channel == 157 ) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY; } else if ( channel == 165 ) { smeConfig.csrConfig.channelBondingMode5GHz = eCSR_INI_SINGLE_CHANNEL_CENTERED; } #ifdef WLAN_FEATURE_AP_HT40_24G if (smeConfig.csrConfig.apHT40_24GEnabled) { if (channel >= 1 && channel <= 7) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_DOUBLE_CHANNEL_LOW_PRIMARY; else if (channel >= 8 && channel <= 13) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_DOUBLE_CHANNEL_HIGH_PRIMARY; else if (channel ==14) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_SINGLE_CHANNEL_CENTERED; } #endif } /* for 802.11a phy mode, channel bonding should be zero. From default config, it is set as PHY_DOUBLE_CHANNEL_HIGH_PRIMARY = 3 through csrChangeDefaultConfigParam function. We will override this value here. */ if ( eCSR_DOT11_MODE_11a == eCsrPhyMode || eCSR_DOT11_MODE_11a_ONLY == eCsrPhyMode || eCSR_DOT11_MODE_abg == eCsrPhyMode) { smeConfig.csrConfig.channelBondingMode5GHz = 0; #ifdef WLAN_FEATURE_AP_HT40_24G } else if ( eCSR_DOT11_MODE_11g_ONLY == eCsrPhyMode) smeConfig.csrConfig.channelBondingAPMode24GHz = eCSR_INI_SINGLE_CHANNEL_CENTERED; #else } #endif sme_AdjustCBMode(pMac, &smeConfig, channel); #ifdef WLAN_FEATURE_AP_HT40_24G VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("%s cbmode selected=%d bonding mode:%s"), (channel <= 14) ? "2G" : "5G", (channel <= 14) ? smeConfig.csrConfig.channelBondingAPMode24GHz : smeConfig.csrConfig.channelBondingMode5GHz, (channel <= 14) ? sme_CBMode2String(smeConfig.csrConfig.channelBondingAPMode24GHz) : sme_CBMode2String(smeConfig.csrConfig.channelBondingMode5GHz)); #else VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_WARN, "cbmode selected=%d", smeConfig.csrConfig.channelBondingMode5GHz); #endif sme_UpdateConfig (pMac, &smeConfig); return VOS_STATUS_SUCCESS; } /*-------------------------------------------------------------------------- \brief sme_SetCurrDeviceMode() - Sets the current operating device mode. \param hHal - The handle returned by macOpen. \param currDeviceMode - Current operating device mode. --------------------------------------------------------------------------*/ void sme_SetCurrDeviceMode (tHalHandle hHal, tVOS_CON_MODE currDeviceMode) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); pMac->sme.currDeviceMode = currDeviceMode; return; } #ifdef WLAN_FEATURE_ROAM_SCAN_OFFLOAD /*-------------------------------------------------------------------------- \brief sme_HandoffRequest() - a wrapper function to Request a handoff from CSR. This is a synchronous call \param hHal - The handle returned by macOpen \param pHandoffInfo - info provided by HDD with the handoff request (namely: BSSID, channel etc.) \return eHAL_STATUS_SUCCESS - SME passed the request to CSR successfully. Other status means SME is failed to send the request. \sa --------------------------------------------------------------------------*/ eHalStatus sme_HandoffRequest(tHalHandle hHal, tCsrHandoffRequest *pHandoffInfo) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: invoked", __func__); status = csrHandoffRequest(pMac, pHandoffInfo); sme_ReleaseGlobalLock( &pMac->sme ); } return status ; } #endif /* * SME API to check if there is any infra station or * P2P client is connected */ VOS_STATUS sme_isSta_p2p_clientConnected(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if(csrIsInfraConnected(pMac)) { return VOS_STATUS_SUCCESS; } return VOS_STATUS_E_FAILURE; } /* * SME API to check if any sessoion connected. */ VOS_STATUS sme_is_any_session_connected(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if(csrIsAnySessionConnected(pMac)) { return VOS_STATUS_SUCCESS; } return VOS_STATUS_E_FAILURE; } #ifdef FEATURE_WLAN_LPHB /* --------------------------------------------------------------------------- \fn sme_LPHBConfigReq \API to make configuration LPHB within FW. \param hHal - The handle returned by macOpen \param lphdReq - LPHB request argument by client \param pCallbackfn - LPHB timeout notification callback function pointer \- return Configuration message posting status, SUCCESS or Fail -------------------------------------------------------------------------*/ eHalStatus sme_LPHBConfigReq ( tHalHandle hHal, tSirLPHBReq *lphdReq, void (*pCallbackfn)(void *pAdapter, void *indParam) ) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_LPHB_CONFIG_REQ, NO_SESSION, lphdReq->cmd)); status = sme_AcquireGlobalLock(&pMac->sme); if (eHAL_STATUS_SUCCESS == status) { if ((LPHB_SET_EN_PARAMS_INDID == lphdReq->cmd) && (NULL == pCallbackfn) && (NULL == pMac->sme.pLphbIndCb)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Indication Call back did not registered", __func__); sme_ReleaseGlobalLock(&pMac->sme); return eHAL_STATUS_FAILURE; } else if (NULL != pCallbackfn) { pMac->sme.pLphbIndCb = pCallbackfn; } /* serialize the req through MC thread */ vosMessage.bodyptr = lphdReq; vosMessage.type = WDA_LPHB_CONF_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post Config LPHB MSG fail", __func__); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } return(status); } #endif /* FEATURE_WLAN_LPHB */ /*-------------------------------------------------------------------------- \brief sme_enable_disable_split_scan() - a wrapper function to set the split scan parameter. This is a synchronous call \param hHal - The handle returned by macOpen \return NONE. \sa --------------------------------------------------------------------------*/ void sme_enable_disable_split_scan (tHalHandle hHal, tANI_U8 nNumStaChan, tANI_U8 nNumP2PChan) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); pMac->roam.configParam.nNumStaChanCombinedConc = nNumStaChan; pMac->roam.configParam.nNumP2PChanCombinedConc = nNumP2PChan; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: SCAN nNumStaChanCombinedConc : %d," "nNumP2PChanCombinedConc : %d ", __func__, nNumStaChan, nNumP2PChan); return; } /** * sme_AddPeriodicTxPtrn() - Add Periodic TX Pattern * @hal: global hal handle * @addPeriodicTxPtrnParams: request message * * Return: eHalStatus enumeration */ eHalStatus sme_AddPeriodicTxPtrn(tHalHandle hal, struct sSirAddPeriodicTxPtrn *addPeriodicTxPtrnParams) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vos_status = VOS_STATUS_SUCCESS; tpAniSirGlobal mac = PMAC_STRUCT(hal); struct sSirAddPeriodicTxPtrn *req_msg; vos_msg_t msg; smsLog(mac, LOG1, FL("enter")); req_msg = vos_mem_malloc(sizeof(*req_msg)); if (!req_msg) { smsLog(mac, LOGE, FL("vos_mem_malloc failed")); return eHAL_STATUS_FAILED_ALLOC; } *req_msg = *addPeriodicTxPtrnParams; status = sme_AcquireGlobalLock(&mac->sme); if (status != eHAL_STATUS_SUCCESS) { smsLog(mac, LOGE, FL("sme_AcquireGlobalLock failed!(status=%d)"), status); vos_mem_free(req_msg); return status; } /* Serialize the req through MC thread */ msg.bodyptr = req_msg; msg.type = WDA_ADD_PERIODIC_TX_PTRN_IND; vos_status = vos_mq_post_message(VOS_MQ_ID_WDA, &msg); if (!VOS_IS_STATUS_SUCCESS(vos_status)) { smsLog(mac, LOGE, FL("vos_mq_post_message failed!(err=%d)"), vos_status); vos_mem_free(req_msg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&mac->sme); return status; } /** * sme_DelPeriodicTxPtrn() - Delete Periodic TX Pattern * @hal: global hal handle * @delPeriodicTxPtrnParams: request message * * Return: eHalStatus enumeration */ eHalStatus sme_DelPeriodicTxPtrn(tHalHandle hal, struct sSirDelPeriodicTxPtrn *delPeriodicTxPtrnParams) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vos_status = VOS_STATUS_SUCCESS; tpAniSirGlobal mac = PMAC_STRUCT(hal); struct sSirDelPeriodicTxPtrn *req_msg; vos_msg_t msg; smsLog(mac, LOG1, FL("enter")); req_msg = vos_mem_malloc(sizeof(*req_msg)); if (!req_msg) { smsLog(mac, LOGE, FL("vos_mem_malloc failed")); return eHAL_STATUS_FAILED_ALLOC; } *req_msg = *delPeriodicTxPtrnParams; status = sme_AcquireGlobalLock(&mac->sme); if (status != eHAL_STATUS_SUCCESS) { smsLog(mac, LOGE, FL("sme_AcquireGlobalLock failed!(status=%d)"), status); vos_mem_free(req_msg); return status; } /* Serialize the req through MC thread */ msg.bodyptr = req_msg; msg.type = WDA_DEL_PERIODIC_TX_PTRN_IND; vos_status = vos_mq_post_message(VOS_MQ_ID_WDA, &msg); if (!VOS_IS_STATUS_SUCCESS(vos_status)) { smsLog(mac, LOGE, FL("vos_mq_post_message failed!(err=%d)"), vos_status); vos_mem_free(req_msg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&mac->sme); return status; } #ifdef WLAN_FEATURE_RMC /* --------------------------------------------------------------------------- \fn sme_EnableRMC \brief Used to enable RMC setting will not persist over reboots \param hHal \param sessionId \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_EnableRMC(tHalHandle hHal, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); smsLog(pMac, LOG1, FL("enable RMC")); status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { status = csrEnableRMC(pMac, sessionId); sme_ReleaseGlobalLock(&pMac->sme); } return status; } /* --------------------------------------------------------------------------- \fn sme_DisableRMC \brief Used to disable RMC setting will not persist over reboots \param hHal \param sessionId \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_DisableRMC(tHalHandle hHal, tANI_U32 sessionId) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); smsLog(pMac, LOG1, FL("disable RMC")); status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { status = csrDisableRMC(pMac, sessionId); sme_ReleaseGlobalLock(&pMac->sme); } return status; } #endif /* WLAN_FEATURE_RMC */ /* --------------------------------------------------------------------------- \fn sme_SendRateUpdateInd \brief API to Update rate \param hHal - The handle returned by macOpen \param rateUpdateParams - Pointer to rate update params \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SendRateUpdateInd(tHalHandle hHal, tSirRateUpdateInd *rateUpdateParams) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status; vos_msg_t msg; if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { msg.type = WDA_RATE_UPDATE_IND; msg.bodyptr = rateUpdateParams; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if (!VOS_IS_STATUS_SUCCESS(vos_mq_post_message(VOS_MODULE_ID_WDA, &msg))) { VOS_TRACE( VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR,"%s: Not able " "to post WDA_SET_RMC_RATE_IND to WDA!", __func__); sme_ReleaseGlobalLock(&pMac->sme); return eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); return eHAL_STATUS_SUCCESS; } return status; } #ifdef WLAN_FEATURE_RMC /* --------------------------------------------------------------------------- \fn sme_GetIBSSPeerInfo \brief Used to disable RMC setting will not persist over reboots \param hHal \param ibssPeerInfoReq multicast Group IP address \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_RequestIBSSPeerInfo(tHalHandle hHal, void *pUserData, pIbssPeerInfoCb peerInfoCbk, tANI_BOOLEAN allPeerInfoReqd, tANI_U8 staIdx) { eHalStatus status = eHAL_STATUS_FAILURE; VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t vosMessage; tSirIbssGetPeerInfoReqParams *pIbssInfoReqParams; status = sme_AcquireGlobalLock(&pMac->sme); if ( eHAL_STATUS_SUCCESS == status) { pMac->sme.peerInfoParams.peerInfoCbk = peerInfoCbk; pMac->sme.peerInfoParams.pUserData = pUserData; pIbssInfoReqParams = (tSirIbssGetPeerInfoReqParams *) vos_mem_malloc(sizeof(tSirIbssGetPeerInfoReqParams)); if (NULL == pIbssInfoReqParams) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for dhcp start", __func__); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pIbssInfoReqParams->allPeerInfoReqd = allPeerInfoReqd; pIbssInfoReqParams->staIdx = staIdx; vosMessage.type = WDA_GET_IBSS_PEER_INFO_REQ; vosMessage.bodyptr = pIbssInfoReqParams; vosMessage.reserved = 0; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( VOS_STATUS_SUCCESS != vosStatus ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Post WDA_GET_IBSS_PEER_INFO_REQ MSG failed", __func__); vos_mem_free(pIbssInfoReqParams); vosStatus = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } return (vosStatus); } #endif void smeGetCommandQStatus( tHalHandle hHal ) { tSmeCmd *pTempCmd = NULL; tListElem *pEntry; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return; } pEntry = csrLLPeekHead( &pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK ); if( pEntry ) { pTempCmd = GET_BASE_ADDR( pEntry, tSmeCmd, Link ); } smsLog( pMac, LOGE, "Currently smeCmdActiveList has command (0x%X)", (pTempCmd) ? pTempCmd->command : eSmeNoCommand ); if(pTempCmd) { if( eSmeCsrCommandMask & pTempCmd->command ) { //CSR command is stuck. See what the reason code is for that command dumpCsrCommandInfo(pMac, pTempCmd); } } //if(pTempCmd) smsLog( pMac, LOGE, "Currently smeCmdPendingList has %d commands", csrLLCount(&pMac->sme.smeCmdPendingList)); smsLog( pMac, LOGE, "Currently roamCmdPendingList has %d commands", csrLLCount(&pMac->roam.roamCmdPendingList)); return; } #ifdef FEATURE_WLAN_BATCH_SCAN /* --------------------------------------------------------------------------- \fn sme_SetBatchScanReq \brief API to set batch scan request in FW \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the batch request. \param sessionId - session ID \param callbackRoutine - HDD callback which needs to be invoked after getting set batch scan response from FW \param callbackContext - pAdapter context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetBatchScanReq ( tHalHandle hHal, tSirSetBatchScanReq *pRequest, tANI_U8 sessionId, void (*callbackRoutine) (void *callbackCtx, tSirSetBatchScanRsp *pRsp), void *callbackContext ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; if (!pMac) { return eHAL_STATUS_FAILURE; } if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { status = pmcSetBatchScanReq(hHal, pRequest, sessionId, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_TriggerBatchScanResultInd \brief API to trigger batch scan result indications from FW \param hHal - The handle returned by macOpen. \param pRequest - Pointer to get batch request. \param sessionId - session ID \param callbackRoutine - HDD callback which needs to be invoked after getting batch scan result indication from FW \param callbackContext - pAdapter context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_TriggerBatchScanResultInd ( tHalHandle hHal, tSirTriggerBatchScanResultInd *pRequest, tANI_U8 sessionId, void (*callbackRoutine) (void *callbackCtx, void *pRsp), void *callbackContext ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { status = pmcTriggerBatchScanResultInd(hHal, pRequest, sessionId, callbackRoutine, callbackContext); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_StopBatchScanInd \brief API to stop batch scan request in FW \param hHal - The handle returned by macOpen. \param pRequest - Pointer to the batch request. \param sessionId - session ID \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_StopBatchScanInd ( tHalHandle hHal, tSirStopBatchScanInd *pRequest, tANI_U8 sessionId ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { status = pmcStopBatchScanInd(hHal, pRequest, sessionId); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } #endif void activeListCmdTimeoutHandle(void *userData) { tHalHandle hHal= (tHalHandle) userData; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); tListElem *pEntry; tSmeCmd *pTempCmd = NULL; if (NULL == pMac) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_FATAL, "%s: pMac is null", __func__); return; } /* Return if no cmd pending in active list as * in this case we should not be here. */ if ((NULL == userData) || (0 == csrLLCount(&pMac->sme.smeCmdActiveList))) return; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Active List command timeout Cmd List Count %d", __func__, csrLLCount(&pMac->sme.smeCmdActiveList) ); smeGetCommandQStatus(hHal); vos_state_info_dump_all(); pEntry = csrLLPeekHead(&pMac->sme.smeCmdActiveList, LL_ACCESS_LOCK); if (pEntry) { pTempCmd = GET_BASE_ADDR(pEntry, tSmeCmd, Link); } /* If user initiated scan took more than active list timeout * abort it. */ if (pTempCmd && (eSmeCommandScan == pTempCmd->command) && (eCsrScanUserRequest == pTempCmd->u.scanCmd.reason)) { sme_AbortMacScan(hHal, pTempCmd->sessionId, eCSR_SCAN_ABORT_DEFAULT); return; } else if (pTempCmd && (eSmeCommandRemainOnChannel == pTempCmd->command)) { /* Ignore if ROC took more than 120 sec */ return; } if (pMac->roam.configParam.enableFatalEvent) { vos_fatal_event_logs_req(WLAN_LOG_TYPE_FATAL, WLAN_LOG_INDICATOR_HOST_DRIVER, WLAN_LOG_REASON_SME_COMMAND_STUCK, FALSE, FALSE); } else { /* Initiate SSR to recover */ if (!(vos_isLoadUnloadInProgress() || vos_is_logp_in_progress(VOS_MODULE_ID_SME, NULL))) { vos_wlanRestart(); } } } #ifdef FEATURE_WLAN_CH_AVOID /* --------------------------------------------------------------------------- \fn sme_AddChAvoidCallback \brief Used to plug in callback function Which notify channel may not be used with SAP or P2PGO mode. Notification come from FW. \param hHal \param pCallbackfn : callback function pointer should be plugged in \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_AddChAvoidCallback ( tHalHandle hHal, void (*pCallbackfn)(void *pAdapter, void *indParam) ) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: Plug in CH AVOID CB", __func__); status = sme_AcquireGlobalLock(&pMac->sme); if (eHAL_STATUS_SUCCESS == status) { if (NULL != pCallbackfn) { pMac->sme.pChAvoidNotificationCb = pCallbackfn; } sme_ReleaseGlobalLock(&pMac->sme); } return(status); } #endif /* FEATURE_WLAN_CH_AVOID */ /** * sme_set_rssi_threshold_breached_cb() - set rssi threshold breached callback * @hal: global hal handle * @cb: callback function pointer * * This function stores the rssi threshold breached callback function. * * Return: eHalStatus enumeration. */ eHalStatus sme_set_rssi_threshold_breached_cb(tHalHandle hal, void (*cb)(void *, struct rssi_breach_event *)) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal mac = PMAC_STRUCT(hal); status = sme_AcquireGlobalLock(&mac->sme); if (status != eHAL_STATUS_SUCCESS) { smsLog(mac, LOGE, FL("sme_AcquireGlobalLock failed!(status=%d)"), status); return status; } mac->sme.rssiThresholdBreachedCb = cb; sme_ReleaseGlobalLock(&mac->sme); return status; } #ifdef WLAN_FEATURE_LINK_LAYER_STATS /* --------------------------------------------------------------------------- \fn sme_LLStatsSetReq \brief API to set link layer stats request to FW \param hHal - The handle returned by macOpen. \Param pStatsReq - a pointer to a caller allocated object of typedef struct tSirLLStatsSetReq, signifying the parameters to link layer stats set. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_LLStatsSetReq(tHalHandle hHal, tSirLLStatsSetReq *pLinkLayerStatsSetReq) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t msg; eHalStatus status = eHAL_STATUS_FAILURE; tSirLLStatsSetReq *plinkLayerSetReq; plinkLayerSetReq = vos_mem_malloc(sizeof(*plinkLayerSetReq)); if ( !plinkLayerSetReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_LINK_LAYER_STATS_SET_REQ", __func__); return eHAL_STATUS_FAILURE; } *plinkLayerSetReq = *pLinkLayerStatsSetReq; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { msg.type = WDA_LINK_LAYER_STATS_SET_REQ; msg.reserved = 0; msg.bodyptr = plinkLayerSetReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "Not able to post SIR_HAL_LL_STATS_SET message to HAL", __func__); vos_mem_free(plinkLayerSetReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(plinkLayerSetReq); status = eHAL_STATUS_FAILURE; } return status; } /* --------------------------------------------------------------------------- \fn sme_LLStatsGetReq \brief API to get link layer stats request to FW \param hHal - The handle returned by macOpen. \Param pStatsReq - a pointer to a caller allocated object of typedef struct tSirLLStatsGetReq, signifying the parameters to link layer stats get. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_LLStatsGetReq(tHalHandle hHal, tSirLLStatsGetReq *pLinkLayerStatsGetReq) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t msg; eHalStatus status = eHAL_STATUS_FAILURE; tSirLLStatsGetReq *pGetStatsReq; pGetStatsReq = vos_mem_malloc(sizeof(*pGetStatsReq)); if ( !pGetStatsReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_LINK_LAYER_STATS_GET_REQ", __func__); return eHAL_STATUS_FAILURE; } *pGetStatsReq = *pLinkLayerStatsGetReq; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { msg.type = WDA_LINK_LAYER_STATS_GET_REQ; msg.reserved = 0; msg.bodyptr = pGetStatsReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "Not able to post SIR_HAL_LL_STATS_GET message to HAL", __func__); vos_mem_free(pGetStatsReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pGetStatsReq); status = eHAL_STATUS_FAILURE; } return status; } /* --------------------------------------------------------------------------- \fn sme_LLStatsClearReq \brief API to clear link layer stats request to FW \param hHal - The handle returned by macOpen. \Param pStatsReq - a pointer to a caller allocated object of typedef struct tSirLLStatsClearReq, signifying the parameters to link layer stats clear. \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_LLStatsClearReq(tHalHandle hHal, tSirLLStatsClearReq *pLinkLayerStatsClear) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); vos_msg_t msg; eHalStatus status = eHAL_STATUS_FAILURE; tSirLLStatsClearReq *pClearStatsReq; pClearStatsReq = vos_mem_malloc(sizeof(*pClearStatsReq)); if ( !pClearStatsReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_LINK_LAYER_STATS_CLEAR_REQ", __func__); return eHAL_STATUS_FAILURE; } *pClearStatsReq = *pLinkLayerStatsClear; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { msg.type = WDA_LINK_LAYER_STATS_CLEAR_REQ; msg.reserved = 0; msg.bodyptr = pClearStatsReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "Not able to post SIR_HAL_LL_STATS_CLEAR message to HAL", __func__); vos_mem_free(pClearStatsReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pClearStatsReq); status = eHAL_STATUS_FAILURE; } return status; } /* --------------------------------------------------------------------------- \fn sme_SetLinkLayerStatsIndCB \brief API to trigger Link Layer Statistic indications from FW \param hHal - The handle returned by macOpen. \param sessionId - session ID \param callbackRoutine - HDD callback which needs to be invoked after getting Link Layer Statistics from FW \param callbackContext - pAdapter context \return eHalStatus ---------------------------------------------------------------------------*/ eHalStatus sme_SetLinkLayerStatsIndCB ( tHalHandle hHal, void (*callbackRoutine) (void *callbackCtx, int indType, void *pRsp, tANI_U8 *macAddr) ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status; if ( eHAL_STATUS_SUCCESS == ( status = sme_AcquireGlobalLock( &pMac->sme ))) { if (NULL != callbackRoutine) { pMac->sme.pLinkLayerStatsIndCallback = callbackRoutine; } sme_ReleaseGlobalLock( &pMac->sme ); } return status; } #endif /* WLAN_FEATURE_LINK_LAYER_STATS */ eHalStatus sme_UpdateConnectDebug(tHalHandle hHal, tANI_U32 set_value) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); pMac->fEnableDebugLog = set_value; return (status); } VOS_STATUS sme_UpdateDSCPtoUPMapping( tHalHandle hHal, sme_QosWmmUpType *dscpmapping, v_U8_t sessionId ) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); eHalStatus status = eHAL_STATUS_SUCCESS; v_U8_t i, j, peSessionId; tCsrRoamSession *pCsrSession = NULL; tpPESession pSession = NULL; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pCsrSession = CSR_GET_SESSION( pMac, sessionId ); if (pCsrSession == NULL) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: CSR Session lookup fails %u", __func__, sessionId); sme_ReleaseGlobalLock( &pMac->sme); return eHAL_STATUS_FAILURE; } if (!CSR_IS_SESSION_VALID( pMac, sessionId )) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Invalid session Id %u", __func__, sessionId); sme_ReleaseGlobalLock( &pMac->sme); return eHAL_STATUS_FAILURE; } pSession = peFindSessionByBssid( pMac, pCsrSession->connectedProfile.bssid, &peSessionId ); if (pSession == NULL) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Session lookup fails for BSSID", __func__); sme_ReleaseGlobalLock( &pMac->sme); return eHAL_STATUS_FAILURE; } if ( !pSession->QosMapSet.present ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: QOS Mapping IE not present", __func__); sme_ReleaseGlobalLock( &pMac->sme); return eHAL_STATUS_FAILURE; } else { for (i = 0; i < SME_QOS_WMM_UP_MAX; i++) { for (j = pSession->QosMapSet.dscp_range[i][0]; j <= pSession->QosMapSet.dscp_range[i][1]; j++) { if ((pSession->QosMapSet.dscp_range[i][0] == 255) && (pSession->QosMapSet.dscp_range[i][1] == 255)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: User Priority %d is not used in mapping", __func__, i); break; } else { dscpmapping[j]= i; } } } for (i = 0; i< pSession->QosMapSet.num_dscp_exceptions; i++) { if (pSession->QosMapSet.dscp_exceptions[i][0] != 255) { dscpmapping[pSession->QosMapSet.dscp_exceptions[i][0] ] = pSession->QosMapSet.dscp_exceptions[i][1]; } } } } sme_ReleaseGlobalLock( &pMac->sme); return status; } tANI_BOOLEAN sme_Is11dCountrycode(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); if (VOS_TRUE == vos_mem_compare(pMac->scan.countryCodeCurrent, pMac->scan.countryCode11d, 2)) { return eANI_BOOLEAN_TRUE; } else { return eANI_BOOLEAN_FALSE; } } eHalStatus sme_SpoofMacAddrReq(tHalHandle hHal, v_MACADDR_t *macaddr) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tSmeCmd *pMacSpoofCmd; status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { pMacSpoofCmd = csrGetCommandBuffer(pMac); if (pMacSpoofCmd) { pMacSpoofCmd->command = eSmeCommandMacSpoofRequest; vos_mem_set(&pMacSpoofCmd->u.macAddrSpoofCmd, sizeof(tSirSpoofMacAddrReq), 0); vos_mem_copy(pMacSpoofCmd->u.macAddrSpoofCmd.macAddr, macaddr->bytes, VOS_MAC_ADDRESS_LEN); status = csrQueueSmeCommand(pMac, pMacSpoofCmd, false); if ( !HAL_STATUS_SUCCESS( status ) ) { smsLog( pMac, LOGE, FL("fail to send msg status = %d\n"), status ); csrReleaseCommand(pMac, pMacSpoofCmd); } } else { //log error smsLog(pMac, LOGE, FL("can not obtain a common buffer\n")); status = eHAL_STATUS_RESOURCES; } sme_ReleaseGlobalLock( &pMac->sme); } return (status); } #ifdef WLAN_FEATURE_EXTSCAN /* --------------------------------------------------------------------------- \fn sme_GetValidChannelsByBand \brief SME API to fetch all valid channel filtered by band \param hHal \param wifiBand: RF band information \param aValidChannels: Array to store channel info \param len: number of channels \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_GetValidChannelsByBand (tHalHandle hHal, tANI_U8 wifiBand, tANI_U32 *aValidChannels, tANI_U8 *pNumChannels) { eHalStatus status = eHAL_STATUS_SUCCESS; tANI_U8 chanList[WNI_CFG_VALID_CHANNEL_LIST_LEN] = {0}; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tANI_U8 numChannels = 0; tANI_U8 i = 0; tANI_U32 totValidChannels = WNI_CFG_VALID_CHANNEL_LIST_LEN; if (!aValidChannels || !pNumChannels) { smsLog(pMac, VOS_TRACE_LEVEL_ERROR, FL("Output channel list/NumChannels is NULL")); return eHAL_STATUS_INVALID_PARAMETER; } if ((wifiBand < WIFI_BAND_UNSPECIFIED) || (wifiBand >= WIFI_BAND_MAX)) { smsLog(pMac, VOS_TRACE_LEVEL_ERROR, FL("Invalid wifiBand (%d)"), wifiBand); return eHAL_STATUS_INVALID_PARAMETER; } status = sme_GetCfgValidChannels(hHal, &chanList[0], &totValidChannels); if (!HAL_STATUS_SUCCESS(status)) { smsLog(pMac, VOS_TRACE_LEVEL_ERROR, FL("Failed to get valid channel list (err=%d)"), status); return status; } switch (wifiBand) { case WIFI_BAND_UNSPECIFIED: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("Unspecified wifiBand, " "return all (%d) valid channels"), totValidChannels); numChannels = totValidChannels; for (i = 0; i < numChannels; i++) aValidChannels[i] = vos_chan_to_freq(chanList[i]); break; case WIFI_BAND_BG: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("WIFI_BAND_BG (2.4 GHz)")); for (i = 0; i < totValidChannels; i++) if (CSR_IS_CHANNEL_24GHZ(chanList[i])) aValidChannels[numChannels++] = vos_chan_to_freq(chanList[i]); break; case WIFI_BAND_A: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("WIFI_BAND_A (5 GHz without DFS)")); for (i = 0; i < totValidChannels; i++) if (CSR_IS_CHANNEL_5GHZ(chanList[i]) && !CSR_IS_CHANNEL_DFS(chanList[i])) aValidChannels[numChannels++] = vos_chan_to_freq(chanList[i]); break; case WIFI_BAND_ABG: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("WIFI_BAND_ABG (2.4 GHz + 5 GHz; no DFS)")); for (i = 0; i < totValidChannels; i++) if ((CSR_IS_CHANNEL_24GHZ(chanList[i]) || CSR_IS_CHANNEL_5GHZ(chanList[i])) && !CSR_IS_CHANNEL_DFS(chanList[i])) aValidChannels[numChannels++] = vos_chan_to_freq(chanList[i]); break; case WIFI_BAND_A_DFS_ONLY: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("WIFI_BAND_A_DFS (5 GHz DFS only)")); for (i = 0; i < totValidChannels; i++) if (CSR_IS_CHANNEL_5GHZ(chanList[i]) && CSR_IS_CHANNEL_DFS(chanList[i])) aValidChannels[numChannels++] = vos_chan_to_freq(chanList[i]); break; case WIFI_BAND_A_WITH_DFS: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("WIFI_BAND_A_WITH_DFS (5 GHz with DFS)")); for (i = 0; i < totValidChannels; i++) if (CSR_IS_CHANNEL_5GHZ(chanList[i])) aValidChannels[numChannels++] = vos_chan_to_freq(chanList[i]); break; case WIFI_BAND_ABG_WITH_DFS: smsLog(pMac, VOS_TRACE_LEVEL_INFO, FL("WIFI_BAND_ABG_WITH_DFS (2.4 GHz + 5 GHz with DFS)")); for (i = 0; i < totValidChannels; i++) if (CSR_IS_CHANNEL_24GHZ(chanList[i]) || CSR_IS_CHANNEL_5GHZ(chanList[i])) aValidChannels[numChannels++] = vos_chan_to_freq(chanList[i]); break; default: smsLog(pMac, VOS_TRACE_LEVEL_ERROR, FL("Unknown wifiBand (%d))"), wifiBand); return eHAL_STATUS_INVALID_PARAMETER; break; } *pNumChannels = numChannels; return status; } /* --------------------------------------------------------------------------- \fn sme_EXTScanGetCapabilities \brief SME API to fetch Extended Scan capabilities \param hHal \param pReq: Extended Scan capabilities structure \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_EXTScanGetCapabilities (tHalHandle hHal, tSirGetEXTScanCapabilitiesReqParams *pReq) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tSirGetEXTScanCapabilitiesReqParams *pGetEXTScanCapabilitiesReq; pGetEXTScanCapabilitiesReq = vos_mem_malloc(sizeof(*pGetEXTScanCapabilitiesReq)); if ( !pGetEXTScanCapabilitiesReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_EXTSCAN_GET_CAPABILITIES_REQ", __func__); return eHAL_STATUS_FAILURE; } *pGetEXTScanCapabilitiesReq = *pReq; if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pGetEXTScanCapabilitiesReq; vosMessage.type = WDA_EXTSCAN_GET_CAPABILITIES_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "failed to post WDA_EXTSCAN_GET_CAPABILITIES_REQ ", __func__); vos_mem_free(pGetEXTScanCapabilitiesReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pGetEXTScanCapabilitiesReq); status = eHAL_STATUS_FAILURE; } return(status); } /* --------------------------------------------------------------------------- \fn sme_EXTScanStart \brief SME API to issue Extended Scan start \param hHal \param pStartCmd: Extended Scan start structure \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_EXTScanStart (tHalHandle hHal, tSirEXTScanStartReqParams *pStartCmd) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tSirEXTScanStartReqParams *pextScanStartReq; pextScanStartReq = vos_mem_malloc(sizeof(*pextScanStartReq)); if ( !pextScanStartReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_EXTSCAN_START_REQ", __func__); return eHAL_STATUS_FAILURE; } *pextScanStartReq = *pStartCmd; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_START, NO_SESSION, 0)); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pextScanStartReq; vosMessage.type = WDA_EXTSCAN_START_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: failed to post WDA_EXTSCAN_START_REQ", __func__); vos_mem_free(pextScanStartReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pextScanStartReq); status = eHAL_STATUS_FAILURE; } return(status); } /* --------------------------------------------------------------------------- \fn sme_EXTScanStop \brief SME API to issue Extended Scan stop \param hHal \param pStopReq: Extended Scan stop structure \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_EXTScanStop(tHalHandle hHal, tSirEXTScanStopReqParams *pStopReq) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tSirEXTScanStopReqParams *pEXTScanStopReq; pEXTScanStopReq = vos_mem_malloc(sizeof(*pEXTScanStopReq)); if ( !pEXTScanStopReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_EXTSCAN_STOP_REQ", __func__); return eHAL_STATUS_FAILURE; } *pEXTScanStopReq = *pStopReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_STOP, NO_SESSION, 0)); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pEXTScanStopReq; vosMessage.type = WDA_EXTSCAN_STOP_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: failed to post WDA_EXTSCAN_STOP_REQ", __func__); vos_mem_free(pEXTScanStopReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pEXTScanStopReq); status = eHAL_STATUS_FAILURE; } return(status); } /* --------------------------------------------------------------------------- \fn sme_SetBssHotlist \brief SME API to set BSSID hotlist \param hHal \param pSetHotListReq: Extended Scan set hotlist structure \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_SetBssHotlist (tHalHandle hHal, tSirEXTScanSetBssidHotListReqParams *pSetHotListReq) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tSirEXTScanSetBssidHotListReqParams *pEXTScanSetBssidHotlistReq; pEXTScanSetBssidHotlistReq = vos_mem_malloc(sizeof(*pEXTScanSetBssidHotlistReq)); if ( !pEXTScanSetBssidHotlistReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_EXTSCAN_SET_BSSID_HOTLIST_REQ", __func__); return eHAL_STATUS_FAILURE; } *pEXTScanSetBssidHotlistReq = *pSetHotListReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_SET_BSS_HOTLIST, NO_SESSION, 0)); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pEXTScanSetBssidHotlistReq; vosMessage.type = WDA_EXTSCAN_SET_BSSID_HOTLIST_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: failed to post WDA_EXTSCAN_STOP_REQ", __func__); vos_mem_free(pEXTScanSetBssidHotlistReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pEXTScanSetBssidHotlistReq); status = eHAL_STATUS_FAILURE; } return(status); } /* --------------------------------------------------------------------------- \fn sme_ResetBssHotlist \brief SME API to reset BSSID hotlist \param hHal \param pSetHotListReq: Extended Scan set hotlist structure \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_ResetBssHotlist (tHalHandle hHal, tSirEXTScanResetBssidHotlistReqParams *pResetReq) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tSirEXTScanResetBssidHotlistReqParams *pEXTScanHotlistResetReq; pEXTScanHotlistResetReq = vos_mem_malloc(sizeof(*pEXTScanHotlistResetReq)); if ( !pEXTScanHotlistResetReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_EXTSCAN_RESET_BSSID_HOTLIST_REQ", __func__); return eHAL_STATUS_FAILURE; } *pEXTScanHotlistResetReq = *pResetReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_RESET_BSS_HOTLIST, NO_SESSION, 0)); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pEXTScanHotlistResetReq; vosMessage.type = WDA_EXTSCAN_RESET_BSSID_HOTLIST_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: failed to post WDA_EXTSCAN_RESET_BSSID_HOTLIST_REQ", __func__); vos_mem_free(pEXTScanHotlistResetReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pEXTScanHotlistResetReq); status = eHAL_STATUS_FAILURE; } return(status); } /** * sme_set_ssid_hotlist() - Set the SSID hotlist * @hal: SME handle * @request: set ssid hotlist request * * Return: eHalStatus */ eHalStatus sme_set_ssid_hotlist(tHalHandle hal, tSirEXTScanSetSsidHotListReqParams *request) { eHalStatus status; VOS_STATUS vstatus; tpAniSirGlobal mac = PMAC_STRUCT(hal); vos_msg_t vos_message; tSirEXTScanSetSsidHotListReqParams *set_req; int i; set_req = vos_mem_malloc(sizeof(*set_req)); if (!set_req) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for WDA_EXTSCAN_SET_SSID_HOTLIST_REQ", __func__); return eHAL_STATUS_FAILURE; } *set_req = *request; for( i = 0; i < set_req->ssid_count; i++){ VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: SSID %s \n length: %d", __func__, set_req->ssid[i].ssid.ssId, set_req->ssid[i].ssid.length); } MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_SET_SSID_HOTLIST, NO_SESSION, 0)); status = sme_AcquireGlobalLock(&mac->sme); if (eHAL_STATUS_SUCCESS == status) { /* Serialize the req through MC thread */ vos_message.bodyptr = set_req; vos_message.type = WDA_EXTSCAN_SET_SSID_HOTLIST_REQ; vstatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vos_message); sme_ReleaseGlobalLock(&mac->sme); if (!VOS_IS_STATUS_SUCCESS(vstatus)) { vos_mem_free(set_req); status = eHAL_STATUS_FAILURE; } } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: sme_AcquireGlobalLock error", __func__); vos_mem_free(set_req); status = eHAL_STATUS_FAILURE; } return status; } /** * sme_reset_ssid_hotlist() - Set the SSID hotlist * @hal: SME handle * @request: reset ssid hotlist request * * Return: eHalStatus */ eHalStatus sme_reset_ssid_hotlist(tHalHandle hal, tSirEXTScanResetSsidHotlistReqParams *request) { eHalStatus status; VOS_STATUS vstatus; tpAniSirGlobal mac = PMAC_STRUCT(hal); vos_msg_t vos_message; tSirEXTScanResetSsidHotlistReqParams *set_req; set_req = vos_mem_malloc(sizeof(*set_req)); if (!set_req) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for WDA_EXTSCAN_SET_SSID_HOTLIST_REQ", __func__); return eHAL_STATUS_FAILURE; } *set_req = *request; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_RESET_SSID_HOTLIST, NO_SESSION, 0)); status = sme_AcquireGlobalLock(&mac->sme); if (eHAL_STATUS_SUCCESS == status) { /* Serialize the req through MC thread */ vos_message.bodyptr = set_req; vos_message.type = WDA_EXTSCAN_RESET_SSID_HOTLIST_REQ; vstatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vos_message); sme_ReleaseGlobalLock(&mac->sme); if (!VOS_IS_STATUS_SUCCESS(vstatus)) { vos_mem_free(set_req); status = eHAL_STATUS_FAILURE; } } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: sme_AcquireGlobalLock error", __func__); vos_mem_free(set_req); status = eHAL_STATUS_FAILURE; } return status; } /* --------------------------------------------------------------------------- \fn sme_getCachedResults \brief SME API to get cached results \param hHal \param pCachedResultsReq: Extended Scan get cached results structure \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_getCachedResults (tHalHandle hHal, tSirEXTScanGetCachedResultsReqParams *pCachedResultsReq) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; tSirEXTScanGetCachedResultsReqParams *pEXTScanCachedResultsReq; pEXTScanCachedResultsReq = vos_mem_malloc(sizeof(*pEXTScanCachedResultsReq)); if ( !pEXTScanCachedResultsReq) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "WDA_EXTSCAN_GET_CACHED_RESULTS_REQ", __func__); return eHAL_STATUS_FAILURE; } *pEXTScanCachedResultsReq = *pCachedResultsReq; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_RX_HDD_EXTSCAN_GET_CACHED_RESULTS, NO_SESSION, 0)); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = pEXTScanCachedResultsReq; vosMessage.type = WDA_EXTSCAN_GET_CACHED_RESULTS_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: failed tp post WDA_EXTSCAN_GET_CACHED_RESULTS_REQ", __func__); vos_mem_free(pEXTScanCachedResultsReq); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Failed to acquire SME Global Lock")); vos_mem_free(pEXTScanCachedResultsReq); status = eHAL_STATUS_FAILURE; } return(status); } eHalStatus sme_EXTScanRegisterCallback (tHalHandle hHal, void (*pEXTScanIndCb)(void *, const tANI_U16, void *), void *callbackContext) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { pMac->sme.pEXTScanIndCb = pEXTScanIndCb; pMac->sme.pEXTScanCallbackContext = callbackContext; sme_ReleaseGlobalLock(&pMac->sme); } return(status); } #ifdef FEATURE_OEM_DATA_SUPPORT eHalStatus sme_OemDataRegisterCallback (tHalHandle hHal, void (*pOemDataIndCb)(void *, const tANI_U16, void *, tANI_U32), void *callbackContext) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { pMac->sme.pOemDataIndCb = pOemDataIndCb; pMac->sme.pOemDataCallbackContext = callbackContext; sme_ReleaseGlobalLock(&pMac->sme); } return(status); } #endif void sme_SetMiracastMode (tHalHandle hHal,tANI_U8 mode) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; vos_msg_t vosMessage = {0}; tSirHighPriorityDataInfoInd *phighPriorityDataInfo; pMac->miracast_mode = mode; VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: miracast_mode: %d", __func__, mode); phighPriorityDataInfo = vos_mem_malloc(sizeof(*phighPriorityDataInfo)); if ( !phighPriorityDataInfo) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:" "Failed to allocate memory for WDA_HIGH_PRIORITY_DATA_INFO_IND", __func__); return; } if (mode) phighPriorityDataInfo->pause = TRUE; else phighPriorityDataInfo->pause = FALSE; if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { /* Serialize the req through MC thread */ vosMessage.bodyptr = phighPriorityDataInfo; vosMessage.type = WDA_HIGH_PRIORITY_DATA_INFO_IND; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s:" "Failed to post WDA_HIGH_PRIORITY_DATA_INFO_IND msg to WDA", __func__); vos_mem_free(phighPriorityDataInfo); } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(phighPriorityDataInfo); } } #endif /* WLAN_FEATURE_EXTSCAN */ void sme_resetCoexEevent(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); if (pMac == NULL) { printk("btc: %s pMac is NULL \n",__func__); return; } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL("isCoexScoIndSet: %d"), pMac->isCoexScoIndSet); if (pMac->isCoexScoIndSet) { pMac->isCoexScoIndSet = 0; ccmCfgSetInt(pMac, WNI_CFG_DEL_ALL_RX_TX_BA_SESSIONS_2_4_G_BTC, 0, NULL, eANI_BOOLEAN_FALSE); } return; } void sme_disable_dfs_channel(tHalHandle hHal, bool disbale_dfs) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); pMac->scan.fEnableDFSChnlScan = !disbale_dfs; csrDisableDfsChannel(pMac); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: Modified fEnableDFSChnlScan: %d", __func__, pMac->scan.fEnableDFSChnlScan); } /* --------------------------------------------------------------------------- \fn sme_Encryptmsgsend \brief SME API to issue encrypt message request \param hHal \param pCmd: Data to be encrypted \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_Encryptmsgsend (tHalHandle hHal, u8 *pCmd, int length, pEncryptMsgRSPCb encMsgCbk) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t vosMessage; u8 *pEncryptMsg; pEncryptMsg = vos_mem_malloc(length); if ( !pEncryptMsg) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Not able to allocate memory for " "SIR_HAL_ENCRYPT_MSG_REQ", __func__); return eHAL_STATUS_FAILURE; } vos_mem_copy(pEncryptMsg, pCmd, length); if (eHAL_STATUS_SUCCESS == (status = sme_AcquireGlobalLock(&pMac->sme))) { pMac->sme.pEncMsgInfoParams.pEncMsgCbk = encMsgCbk; pMac->sme.pEncMsgInfoParams.pUserData = hHal; /* Serialize the req through MC thread */ vosMessage.bodyptr = pEncryptMsg; vosMessage.type = SIR_HAL_ENCRYPT_MSG_REQ; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, vosMessage.type)); vosStatus = vos_mq_post_message(VOS_MQ_ID_WDA, &vosMessage); if (!VOS_IS_STATUS_SUCCESS(vosStatus)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: failed to post SIR_HAL_ENCRYPT_MSG_REQ", __func__); vos_mem_free(pEncryptMsg); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); vos_mem_free(pEncryptMsg); status = eHAL_STATUS_FAILURE; } return(status); } /* --------------------------------------------------------------------------- \fn sme_RegisterBtCoexTDLSCallback \brief Used to plug in callback function Which notify btcoex on or off. Notification come from FW. \param hHal \param pCallbackfn : callback function pointer should be plugged in \- return eHalStatus -------------------------------------------------------------------------*/ eHalStatus sme_RegisterBtCoexTDLSCallback ( tHalHandle hHal, void (*pCallbackfn)(void *pAdapter, int ) ) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: Plug in BtCoex TDLS CB", __func__); status = sme_AcquireGlobalLock(&pMac->sme); if (eHAL_STATUS_SUCCESS == status) { if (NULL != pCallbackfn) { pMac->sme.pBtCoexTDLSNotification = pCallbackfn; } sme_ReleaseGlobalLock(&pMac->sme); } return(status); } /* --------------------------------------------------------------------------- \fn smeNeighborMiddleOfRoaming \brief This function is a wrapper to call csrNeighborMiddleOfRoaming \param hHal - The handle returned by macOpen. \return eANI_BOOLEAN_TRUE if reassoc in progress, eANI_BOOLEAN_FALSE otherwise ---------------------------------------------------------------------------*/ tANI_BOOLEAN smeNeighborMiddleOfRoaming(tHalHandle hHal) { return (csrNeighborMiddleOfRoaming(PMAC_STRUCT(hHal))); } /* --------------------------------------------------------------------------- \fn sme_IsTdlsOffChannelValid \brief To check if the channel is valid for currently established domain This is a synchronous API. \param hHal - The handle returned by macOpen. \param channel - channel to verify \return TRUE/FALSE, TRUE if channel is valid -------------------------------------------------------------------------------*/ tANI_BOOLEAN sme_IsTdlsOffChannelValid(tHalHandle hHal, tANI_U8 channel) { eHalStatus status = eHAL_STATUS_FAILURE; tANI_BOOLEAN valid = FALSE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { /* check whether off channel is valid and non DFS */ if (csrRoamIsChannelValid(pMac, channel)) { if (!CSR_IS_CHANNEL_DFS(channel)) valid = TRUE; else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: configured channel is DFS", __func__); } } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: configured channel is not valid", __func__); } sme_ReleaseGlobalLock( &pMac->sme ); } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: current country code %c%c channel %d valid %d", __func__, pMac->scan.countryCodeCurrent[0], pMac->scan.countryCodeCurrent[1], channel, valid); return (valid); } tANI_BOOLEAN sme_IsCoexScoIndicationSet(tHalHandle hHal) { eHalStatus status = eHAL_STATUS_FAILURE; tANI_BOOLEAN valid = FALSE; tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); status = sme_AcquireGlobalLock( &pMac->sme ); if ( HAL_STATUS_SUCCESS( status ) ) { valid = pMac->isCoexScoIndSet; } sme_ReleaseGlobalLock( &pMac->sme ); return (valid); } eHalStatus sme_SetMiracastVendorConfig(tHalHandle hHal, tANI_U32 iniNumBuffAdvert , tANI_U32 set_value) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tANI_U8 mcsSet[SIZE_OF_SUPPORTED_MCS_SET]; tANI_U32 val = SIZE_OF_SUPPORTED_MCS_SET; if (ccmCfgGetStr(hHal, WNI_CFG_SUPPORTED_MCS_SET, mcsSet, &val) != eHAL_STATUS_SUCCESS) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("failed to get ini param, WNI_CFG_SUPPORTED_MCS_SET")); return eHAL_STATUS_FAILURE; } if (set_value) { if (pMac->miracastVendorConfig) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL(" Miracast tuning already enabled!!")); return eHAL_STATUS_SUCCESS; } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL("Enable Miracast tuning by disabling 64QAM rates, setting 4 blocks for aggregation and disabling probe response for broadcast probe in P2P-GO mode")); if (ccmCfgSetInt(hHal, WNI_CFG_NUM_BUFF_ADVERT, 4, NULL, eANI_BOOLEAN_FALSE) == eHAL_STATUS_FAILURE) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Failure: Could not set WNI_CFG_NUM_BUFF_ADVERT")); return eHAL_STATUS_FAILURE; } /* Disable 64QAM rates ie (MCS 5,6 and 7) */ mcsSet[0]=0x1F; } else { if (!pMac->miracastVendorConfig) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL(" Miracast tuning already disabled!!")); return eHAL_STATUS_SUCCESS; } VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, FL("Disable Miracast tuning by enabling all MCS rates, setting %d blocks for aggregation and enabling probe response for broadcast probe in P2P-GO mode"), iniNumBuffAdvert); if (ccmCfgSetInt(hHal, WNI_CFG_NUM_BUFF_ADVERT, iniNumBuffAdvert, NULL, eANI_BOOLEAN_FALSE) == eHAL_STATUS_FAILURE) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Failure: Could not set WNI_CFG_NUM_BUFF_ADVERT")); return eHAL_STATUS_FAILURE; } /* Enable all MCS rates) */ mcsSet[0]=0xFF; } if (ccmCfgSetStr(hHal, WNI_CFG_SUPPORTED_MCS_SET, mcsSet, val, NULL, eANI_BOOLEAN_FALSE) == eHAL_STATUS_FAILURE) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Failure: Could not set WNI_CFG_SUPPORTED_MCS_SET")); return eHAL_STATUS_FAILURE; } pMac->miracastVendorConfig = set_value; return eHAL_STATUS_SUCCESS; } void sme_SetDefDot11Mode(tHalHandle hHal) { tpAniSirGlobal pMac = PMAC_STRUCT( hHal ); csrSetDefaultDot11Mode(pMac); } /* --------------------------------------------------------------------------- \fn sme_SetTdls2040BSSCoexistence \brief API to enable or disable 20_40 BSS Coexistence IE in TDLS frames. \param isEnabled - Enable or Disable. \- return VOS_STATUS_SUCCES -------------------------------------------------------------------------*/ eHalStatus sme_SetTdls2040BSSCoexistence(tHalHandle hHal, tANI_S32 isTdls2040BSSCoexEnabled) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t msg; tAniSetTdls2040BSSCoex *pMsg; status = sme_AcquireGlobalLock( &pMac->sme ); if (HAL_STATUS_SUCCESS( status )) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "%s: is2040BSSCoexEnabled %d ", __func__, isTdls2040BSSCoexEnabled); pMsg = vos_mem_malloc(sizeof(tAniSetTdls2040BSSCoex)); if (NULL == pMsg ) { smsLog(pMac, LOGE, "failed to allocate mem for SetTdls2040BSSCoex"); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->msgType = pal_cpu_to_be16( (tANI_U16)eWNI_SME_SET_TDLS_2040_BSSCOEX_REQ); pMsg->msgLen = (tANI_U16)sizeof(tAniSetTdls2040BSSCoex); pMsg->SetTdls2040BSSCoex = isTdls2040BSSCoexEnabled; msg.type = eWNI_SME_SET_TDLS_2040_BSSCOEX_REQ; msg.reserved = 0; msg.bodyptr = pMsg; msg.bodyval = 0; if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_PE, &msg)) { smsLog(pMac, LOGE, "sme_SetTdls2040BSSCoexistence failed to post msg to PE "); vos_mem_free((void *)pMsg); status = eHAL_STATUS_FAILURE; } smsLog(pMac, LOG1, FL(" returned")); sme_ReleaseGlobalLock( &pMac->sme ); } return status; } /* --------------------------------------------------------------------------- \fn sme_SetRtsCtsHtVht \brief API to to enable/disable RTS/CTS for different modes. \param set_value - Bit mask value to enable RTS/CTS for different modes. \- return VOS_STATUS_SUCCES if INdication is posted to WDA else return eHAL_STATUS_FAILURE -------------------------------------------------------------------------*/ eHalStatus sme_SetRtsCtsHtVht(tHalHandle hHal, tANI_U32 set_value) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t msg; smsLog(pMac, LOG1, FL(" set_value = %d"), set_value); if (ccmCfgSetInt(hHal, WNI_CFG_ENABLE_RTSCTS_HTVHT, set_value, NULL, eANI_BOOLEAN_FALSE) == eHAL_STATUS_FAILURE) { smsLog(pMac, LOGE, FL("Failure: Could not set WNI_CFG_ENABLE_RTSCTS_HTVHT")); return eHAL_STATUS_FAILURE; } if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme )) { vos_mem_zero(&msg, sizeof(vos_msg_t)); msg.type = WDA_SET_RTS_CTS_HTVHT; msg.reserved = 0; msg.bodyval = set_value; if (VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MQ_ID_WDA, &msg)) { smsLog(pMac, LOGE, FL("Not able to post WDA_SET_RTS_CTS_HTVHT message to HAL")); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_SUCCESS; } return eHAL_STATUS_FAILURE; } /* --------------------------------------------------------------------------- \fn sme_fatal_event_logs_req \brief API to to send flush log command to FW.. \param hHal - Mac Context Handle \- return VOS_STATUS_SUCCES if command is posted to WDA else return eHAL_STATUS_FAILURE -------------------------------------------------------------------------*/ eHalStatus sme_fatal_event_logs_req(tHalHandle hHal, tANI_U32 is_fatal, tANI_U32 indicator, tANI_U32 reason_code, tANI_BOOLEAN dump_vos_trace) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t msg; eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus = VOS_STATUS_SUCCESS; tpSirFatalEventLogsReqParam pFatalEventLogsReqParams; /* Dump last 500 VosTrace */ if (dump_vos_trace) vosTraceDumpAll(pMac, 0, 0, 500, 0); if (WLAN_LOG_INDICATOR_HOST_ONLY == indicator) { vos_flush_host_logs_for_fatal(); return VOS_STATUS_SUCCESS; } if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme )) { pFatalEventLogsReqParams = vos_mem_malloc(sizeof(*pFatalEventLogsReqParams)); if(NULL == pFatalEventLogsReqParams) { smsLog(pMac, LOGE, FL("vos_mem_alloc failed ")); return eHAL_STATUS_FAILED_ALLOC; } vos_mem_set(pFatalEventLogsReqParams, sizeof(*pFatalEventLogsReqParams), 0); pFatalEventLogsReqParams->reason_code = reason_code; vos_mem_zero(&msg, sizeof(vos_msg_t)); msg.type = WDA_FATAL_EVENT_LOGS_REQ; msg.reserved = 0; msg.bodyptr = pFatalEventLogsReqParams; msg.bodyval = 0; vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &msg); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { vos_mem_free(pFatalEventLogsReqParams); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); return status; } return eHAL_STATUS_FAILURE; } /** * sme_handleSetFccChannel() - handle fcc constraint request * @hal: HAL pointer * @fcc_constraint: whether to apply or remove fcc constraint * * Return: tANI_BOOLEAN. */ tANI_BOOLEAN sme_handleSetFccChannel(tHalHandle hHal, tANI_U8 fcc_constraint, v_U32_t scan_pending) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); status = sme_AcquireGlobalLock(&pMac->sme); if (eHAL_STATUS_SUCCESS == status && (!sme_Is11dSupported(hHal)) ) { pMac->scan.fcc_constraint = !fcc_constraint; if (scan_pending == TRUE) { pMac->scan.defer_update_channel_list = true; } else { /* update the channel list to the firmware */ csrUpdateChannelList(pMac); } } sme_ReleaseGlobalLock(&pMac->sme); return status; } eHalStatus sme_enableDisableChanAvoidIndEvent(tHalHandle hHal, tANI_U8 set_value) { eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t msg; smsLog(pMac, LOG1, FL("set_value: %d"), set_value); if ( eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock( &pMac->sme )) { vos_mem_zero(&msg, sizeof(vos_msg_t)); msg.type = WDA_SEND_FREQ_RANGE_CONTROL_IND; msg.reserved = 0; msg.bodyval = set_value; vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &msg); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); return status; } return eHAL_STATUS_FAILURE; } eHalStatus sme_DeleteAllTDLSPeers(tHalHandle hHal, uint8_t sessionId) { tSirDelAllTdlsPeers *pMsg; eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); tCsrRoamSession *pSession = CSR_GET_SESSION(pMac, sessionId); pMsg = vos_mem_malloc(sizeof(tSirDelAllTdlsPeers)); if (NULL == pMsg) { smsLog(pMac, LOGE, FL("memory alloc failed")); return eHAL_STATUS_FAILURE; } vos_mem_set(pMsg, sizeof( tSirDelAllTdlsPeers ), 0); pMsg->mesgType = pal_cpu_to_be16((tANI_U16)eWNI_SME_DEL_ALL_TDLS_PEERS); pMsg->mesgLen = pal_cpu_to_be16((tANI_U16)sizeof( tSirDelAllTdlsPeers )); vos_mem_copy(pMsg->bssid, pSession->connectedProfile.bssid, sizeof(tSirMacAddr)); status = palSendMBMessage( pMac->hHdd, pMsg ); return status; } /** * sme_FwMemDumpReq() - Send Fwr mem Dump Request * @hal: HAL pointer * * Return: eHalStatus */ eHalStatus sme_FwMemDumpReq(tHalHandle hHal, tAniFwrDumpReq *recv_req) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t msg; tAniFwrDumpReq * send_req; send_req = vos_mem_malloc(sizeof(*send_req)); if(!send_req) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Mem allo failed for FW_MEM_DUMP")); return eHAL_STATUS_FAILURE; } send_req->fwMemDumpReqCallback = recv_req->fwMemDumpReqCallback; send_req->fwMemDumpReqContext = recv_req->fwMemDumpReqContext; if (eHAL_STATUS_SUCCESS == sme_AcquireGlobalLock(&pMac->sme)) { msg.bodyptr = send_req; msg.type = WDA_FW_MEM_DUMP_REQ; msg.reserved = 0; if (VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Not able to post WDA_FW_MEM_DUMP")); vos_mem_free(send_req); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock(&pMac->sme); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, FL("Failed to acquire SME Global Lock")); vos_mem_free(send_req); status = eHAL_STATUS_FAILURE; } return status; } eHalStatus sme_set_wificonfig_params(tHalHandle hHal, tSetWifiConfigParams *req) { eHalStatus status = eHAL_STATUS_SUCCESS; tpAniSirGlobal pMac = PMAC_STRUCT(hHal); vos_msg_t msg; status = sme_AcquireGlobalLock(&pMac->sme); if (eHAL_STATUS_SUCCESS == status){ /* serialize the req through MC thread */ msg.type = WDA_WIFI_CONFIG_REQ; msg.reserved = 0; msg.bodyptr = req; MTRACE(vos_trace(VOS_MODULE_ID_SME, TRACE_CODE_SME_TX_WDA_MSG, NO_SESSION, msg.type)); if(VOS_STATUS_SUCCESS != vos_mq_post_message(VOS_MODULE_ID_WDA, &msg)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "Not able to post SIR_HAL_WIFI_CONFIG_PARAMS message to HAL", __func__); status = eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme ); } else { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: " "sme_AcquireGlobalLock error", __func__); } return status; } eHalStatus sme_getRegInfo(tHalHandle hHal, tANI_U8 chanId, tANI_U32 *regInfo1, tANI_U32 *regInfo2) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status; tANI_U8 i; eAniBoolean found = false; status = sme_AcquireGlobalLock(&pMac->sme); *regInfo1 = 0; *regInfo2 = 0; if (HAL_STATUS_SUCCESS(status)) { for (i = 0 ; i < WNI_CFG_VALID_CHANNEL_LIST_LEN; i++) { if (pMac->scan.defaultPowerTable[i].chanId == chanId) { SME_SET_CHANNEL_REG_POWER(*regInfo1, pMac->scan.defaultPowerTable[i].pwr); SME_SET_CHANNEL_MAX_TX_POWER(*regInfo2, pMac->scan.defaultPowerTable[i].pwr); found = true; break; } } if (!found) status = eHAL_STATUS_FAILURE; sme_ReleaseGlobalLock(&pMac->sme); } return status; } eHalStatus sme_GetCurrentAntennaIndex(tHalHandle hHal, tCsrAntennaIndexCallback callback, void *pContext, tANI_U8 sessionId) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; tSirAntennaDiversitySelectionReq *pMsg; tCsrRoamSession *pSession; VOS_STATUS vosStatus = VOS_STATUS_E_FAILURE; vos_msg_t vosMessage; status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { pSession = CSR_GET_SESSION( pMac, sessionId ); if (!pSession) { smsLog(pMac, LOGE, FL("session %d not found"), sessionId); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg = (tSirAntennaDiversitySelectionReq*)vos_mem_malloc(sizeof(*pMsg)); if (NULL == pMsg) { smsLog(pMac, LOGE, FL("failed to allocated memory")); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->callback = callback; pMsg->data = pContext; vosMessage.type = WDA_ANTENNA_DIVERSITY_SELECTION_REQ; vosMessage.bodyptr = pMsg; vosMessage.reserved = 0; vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &vosMessage ); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_ERROR, "%s: Failed to post message to WDA", __func__); vos_mem_free(pMsg); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } sme_ReleaseGlobalLock( &pMac->sme); return eHAL_STATUS_SUCCESS; } return eHAL_STATUS_FAILURE; } eHalStatus sme_setBcnMissPenaltyCount(tHalHandle hHal, tModifyRoamParamsReqParams *pModifyRoamReqParams) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; VOS_STATUS vosStatus; tModifyRoamParamsReqParams *pMsg; vos_msg_t msg; status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { pMsg = (tModifyRoamParamsReqParams*)vos_mem_malloc(sizeof(*pMsg)); if (NULL == pMsg) { smsLog(pMac, LOGE, FL("failed to allocated memory")); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } if (NULL == pModifyRoamReqParams) { smsLog(pMac, LOGE, FL("Invalid memory")); vos_mem_free(pMsg); sme_ReleaseGlobalLock( &pMac->sme ); return eHAL_STATUS_FAILURE; } pMsg->param = pModifyRoamReqParams->param; pMsg->value = pModifyRoamReqParams->value; vos_mem_zero(&msg, sizeof(vos_msg_t)); msg.type = WDA_MODIFY_ROAM_PARAMS_IND; msg.reserved = 0; msg.bodyptr = pMsg; vosStatus = vos_mq_post_message( VOS_MQ_ID_WDA, &msg); if ( !VOS_IS_STATUS_SUCCESS(vosStatus) ) { status = eHAL_STATUS_FAILURE; vos_mem_free(pMsg); } sme_ReleaseGlobalLock( &pMac->sme ); return status; } return eHAL_STATUS_FAILURE; } /** * sme_remove_bssid_from_scan_list() - wrapper to remove the bssid from * scan list * @hal: hal context. * @bssid: bssid to be removed * * This function remove the given bssid from scan list. * * Return: hal status. */ eHalStatus sme_remove_bssid_from_scan_list(tHalHandle hal, tSirMacAddr bssid) { eHalStatus status = eHAL_STATUS_FAILURE; tpAniSirGlobal pMac = PMAC_STRUCT(hal); status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { csr_remove_bssid_from_scan_list(pMac, bssid); sme_ReleaseGlobalLock(&pMac->sme); } return status; } /** * sme_set_mgmt_frm_via_wq5() - Set INI params sendMgmtPktViaWQ5 to WDA. * @hal: HAL pointer * @sendMgmtPktViaWQ5: INI params to enable/disable sending mgmt pkt via WQ5. * * Return: void */ void sme_set_mgmt_frm_via_wq5(tHalHandle hHal, tANI_BOOLEAN sendMgmtPktViaWQ5) { tpAniSirGlobal pMac = PMAC_STRUCT(hHal); eHalStatus status = eHAL_STATUS_SUCCESS; status = sme_AcquireGlobalLock(&pMac->sme); if (HAL_STATUS_SUCCESS(status)) { VOS_TRACE(VOS_MODULE_ID_SME, VOS_TRACE_LEVEL_INFO, "sendMgmtPktViaWQ5 is %d", sendMgmtPktViaWQ5); /* not serializing this messsage, as this is only going * to set a variable in WDA/WDI */ WDA_SetMgmtPktViaWQ5(sendMgmtPktViaWQ5); sme_ReleaseGlobalLock(&pMac->sme); } return; }
36.259089
221
0.582098
[ "object" ]
1822975898582ae3153bb9fbeb2757e3ba6b2b60
1,386
h
C
src/common/CoordinateConverter.h
fmidev/smartmet-library-grid-files
c68d271e12e3404cd805a423fe6c5b6c467f00e6
[ "MIT" ]
null
null
null
src/common/CoordinateConverter.h
fmidev/smartmet-library-grid-files
c68d271e12e3404cd805a423fe6c5b6c467f00e6
[ "MIT" ]
null
null
null
src/common/CoordinateConverter.h
fmidev/smartmet-library-grid-files
c68d271e12e3404cd805a423fe6c5b6c467f00e6
[ "MIT" ]
null
null
null
#pragma once #include "Typedefs.h" #include "AutoThreadLock.h" #include <ogr_spatialref.h> #include <macgyver/Exception.h> namespace SmartMet { class CoordinateConverter { public: CoordinateConverter() { transformation = nullptr; sr1 = nullptr; sr2 = nullptr; } CoordinateConverter(const CoordinateConverter& rec) { sr1 = rec.sr1->Clone(); sr2 = rec.sr2->Clone(); transformation = OGRCreateCoordinateTransformation(sr1,sr2); } CoordinateConverter(const OGRSpatialReference *sr_from,const OGRSpatialReference *sr_to) { sr1 = sr_from->Clone(); sr2 = sr_to->Clone(); transformation = OGRCreateCoordinateTransformation(sr1,sr2); } ~CoordinateConverter() { if (transformation != nullptr) OCTDestroyCoordinateTransformation(transformation); if (sr1 != nullptr) OGRSpatialReference::DestroySpatialReference(sr1); if (sr2 != nullptr) OGRSpatialReference::DestroySpatialReference(sr2); } bool convert(int nCount,double *x,double *y) { AutoThreadLock lock(&threadLock); if (transformation->Transform(nCount,x,y)) return true; return false; } protected: OGRCoordinateTransformation *transformation; OGRSpatialReference *sr1; OGRSpatialReference *sr2; ThreadLock threadLock; }; }
20.382353
92
0.665945
[ "transform" ]
1823b390f5b6484e61224952562c5eefb512588f
3,981
h
C
include/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.h
Cozdemir/spitfire
0d1713f5f7bd7d5803895a1cc48a97bf27bef9e1
[ "Apache-2.0" ]
1
2022-03-23T19:48:24.000Z
2022-03-23T19:48:24.000Z
include/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.h
Cozdemir/spitfire
0d1713f5f7bd7d5803895a1cc48a97bf27bef9e1
[ "Apache-2.0" ]
null
null
null
include/third_party/blink/renderer/bindings/tests/results/core/v8_test_special_operations.h
Cozdemir/spitfire
0d1713f5f7bd7d5803895a1cc48a97bf27bef9e1
[ "Apache-2.0" ]
null
null
null
// 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/interface.h.tmpl // by the script code_generator_v8.py. // DO NOT MODIFY! // clang-format off #ifndef THIRD_PARTY_BLINK_RENDERER_BINDINGS_TESTS_RESULTS_CORE_V8_TEST_SPECIAL_OPERATIONS_H_ #define THIRD_PARTY_BLINK_RENDERER_BINDINGS_TESTS_RESULTS_CORE_V8_TEST_SPECIAL_OPERATIONS_H_ #include "third_party/blink/renderer/bindings/core/v8/generated_code_helper.h" #include "third_party/blink/renderer/bindings/core/v8/native_value_traits.h" #include "third_party/blink/renderer/bindings/core/v8/node_or_node_list.h" #include "third_party/blink/renderer/bindings/core/v8/to_v8_for_core.h" #include "third_party/blink/renderer/bindings/core/v8/v8_binding_for_core.h" #include "third_party/blink/renderer/bindings/tests/idls/core/test_special_operations.h" #include "third_party/blink/renderer/core/core_export.h" #include "third_party/blink/renderer/platform/bindings/script_wrappable.h" #include "third_party/blink/renderer/platform/bindings/v8_dom_wrapper.h" #include "third_party/blink/renderer/platform/bindings/wrapper_type_info.h" #include "third_party/blink/renderer/platform/heap/handle.h" namespace blink { CORE_EXPORT extern const WrapperTypeInfo v8_test_special_operations_wrapper_type_info; class V8TestSpecialOperations { STATIC_ONLY(V8TestSpecialOperations); public: CORE_EXPORT static bool HasInstance(v8::Local<v8::Value>, v8::Isolate*); static v8::Local<v8::Object> FindInstanceInPrototypeChain(v8::Local<v8::Value>, v8::Isolate*); CORE_EXPORT static v8::Local<v8::FunctionTemplate> DomTemplate(v8::Isolate*, const DOMWrapperWorld&); static TestSpecialOperations* ToImpl(v8::Local<v8::Object> object) { return ToScriptWrappable(object)->ToImpl<TestSpecialOperations>(); } CORE_EXPORT static TestSpecialOperations* ToImplWithTypeCheck(v8::Isolate*, v8::Local<v8::Value>); CORE_EXPORT static constexpr const WrapperTypeInfo* GetWrapperTypeInfo() { return &v8_test_special_operations_wrapper_type_info; } static constexpr int kInternalFieldCount = kV8DefaultWrapperInternalFieldCount; // Callback functions CORE_EXPORT static void NamedItemMethodCallback(const v8::FunctionCallbackInfo<v8::Value>&); CORE_EXPORT static void NamedPropertyGetterCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value>&); CORE_EXPORT static void NamedPropertySetterCallback(v8::Local<v8::Name>, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&); CORE_EXPORT static void NamedPropertyQueryCallback(v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer>&); CORE_EXPORT static void NamedPropertyEnumeratorCallback(const v8::PropertyCallbackInfo<v8::Array>&); CORE_EXPORT static void IndexedPropertyGetterCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&); CORE_EXPORT static void IndexedPropertySetterCallback(uint32_t index, v8::Local<v8::Value>, const v8::PropertyCallbackInfo<v8::Value>&); CORE_EXPORT static void IndexedPropertyDescriptorCallback(uint32_t index, const v8::PropertyCallbackInfo<v8::Value>&); static void InstallRuntimeEnabledFeaturesOnTemplate( v8::Isolate*, const DOMWrapperWorld&, v8::Local<v8::FunctionTemplate> interface_template); }; template <> struct NativeValueTraits<TestSpecialOperations> : public NativeValueTraitsBase<TestSpecialOperations> { CORE_EXPORT static TestSpecialOperations* NativeValue(v8::Isolate*, v8::Local<v8::Value>, ExceptionState&); CORE_EXPORT static TestSpecialOperations* NullValue() { return nullptr; } }; template <> struct V8TypeOf<TestSpecialOperations> { typedef V8TestSpecialOperations Type; }; } // namespace blink #endif // THIRD_PARTY_BLINK_RENDERER_BINDINGS_TESTS_RESULTS_CORE_V8_TEST_SPECIAL_OPERATIONS_H_
50.392405
141
0.812108
[ "object" ]
1829443242c47233973a24a96e5dbb521d994e69
20,641
c
C
Tools/unix/cpmtools/device_win32.c
davidknoll/RomWBW
8a7bc97fea27bf10a23c61ee508522a60e2909c6
[ "DOC", "MIT" ]
194
2015-08-20T03:18:01.000Z
2022-03-27T02:25:00.000Z
Tools/unix/cpmtools/device_win32.c
davidknoll/RomWBW
8a7bc97fea27bf10a23c61ee508522a60e2909c6
[ "DOC", "MIT" ]
234
2017-03-30T10:59:54.000Z
2022-03-26T20:05:52.000Z
Tools/unix/cpmtools/device_win32.c
davidknoll/RomWBW
8a7bc97fea27bf10a23c61ee508522a60e2909c6
[ "DOC", "MIT" ]
68
2016-12-18T18:20:12.000Z
2022-03-20T16:02:40.000Z
/* #includes */ /*{{{C}}}*//*{{{*/ #include "config.h" #include <assert.h> #include <ctype.h> #include <errno.h> #include <stdio.h> #include "cpmdir.h" #include "cpmfs.h" #ifdef USE_DMALLOC #include <dmalloc.h> #endif /*}}}*/ /* types */ /*{{{*/ #define PHYSICAL_SECTOR_1 1 /* First physical sector */ /* Use the INT13 interface rather than INT25/INT26. This appears to * improve performance, but is less well tested. */ #define USE_INT13 /* Windows 95 disk I/O functions - based on Stan Mitchell's DISKDUMP.C */ #define VWIN32_DIOC_DOS_IOCTL 1 /* DOS ioctl calls 4400h-4411h */ #define VWIN32_DIOC_DOS_INT25 2 /* absolute disk read, DOS int 25h */ #define VWIN32_DIOC_DOS_INT26 3 /* absolute disk write, DOS int 26h */ #define VWIN32_DIOC_DOS_INT13 4 /* BIOS INT13 functions */ typedef struct _DIOC_REGISTERS { DWORD reg_EBX; DWORD reg_EDX; DWORD reg_ECX; DWORD reg_EAX; DWORD reg_EDI; DWORD reg_ESI; DWORD reg_Flags; } DIOC_REGISTERS, *PDIOC_REGISTERS; #define LEVEL0_LOCK 0 #define LEVEL1_LOCK 1 #define LEVEL2_LOCK 2 #define LEVEL3_LOCK 3 #define LEVEL1_LOCK_MAX_PERMISSION 0x0001 #define DRIVE_IS_REMOTE 0x1000 #define DRIVE_IS_SUBST 0x8000 /********************************************************* **** Note: all MS-DOS data structures must be packed **** **** on a one-byte boundary. **** *********************************************************/ #pragma pack(1) typedef struct _DISKIO { DWORD diStartSector; /* sector number to start at */ WORD diSectors; /* number of sectors */ DWORD diBuffer; /* address of buffer */ } DISKIO, *PDISKIO; typedef struct MID { WORD midInfoLevel; /* information level, must be 0 */ DWORD midSerialNum; /* serial number for the medium */ char midVolLabel[11]; /* volume label for the medium */ char midFileSysType[8]; /* type of file system as 8-byte ASCII */ } MID, *PMID; typedef struct driveparams { /* Disk geometry */ BYTE special; BYTE devicetype; WORD deviceattrs; WORD cylinders; BYTE mediatype; /* BPB starts here */ WORD bytespersector; BYTE sectorspercluster; WORD reservedsectors; BYTE numberofFATs; WORD rootdirsize; WORD totalsectors; BYTE mediaid; WORD sectorsperfat; WORD sectorspertrack; WORD heads; DWORD hiddensectors; DWORD bigtotalsectors; BYTE reserved[6]; /* BPB ends here */ WORD sectorcount; WORD sectortable[80]; } DRIVEPARAMS, *PDRIVEPARAMS; /*}}}*/ static char *strwin32error(void) /*{{{*/ { static char buffer[1024]; FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, GetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), /* Default language */ (LPTSTR)buffer, 1023, NULL); return buffer; } /*}}}*/ static BOOL LockVolume( HANDLE hDisk ) /*{{{*/ { DWORD ReturnedByteCount; return DeviceIoControl( hDisk, FSCTL_LOCK_VOLUME, NULL, 0, NULL, 0, &ReturnedByteCount, NULL ); } /*}}}*/ static BOOL UnlockVolume( HANDLE hDisk ) /*{{{*/ { DWORD ReturnedByteCount; return DeviceIoControl( hDisk, FSCTL_UNLOCK_VOLUME, NULL, 0, NULL, 0, &ReturnedByteCount, NULL ); } /*}}}*/ static BOOL DismountVolume( HANDLE hDisk ) /*{{{*/ { DWORD ReturnedByteCount; return DeviceIoControl( hDisk, FSCTL_DISMOUNT_VOLUME, NULL, 0, NULL, 0, &ReturnedByteCount, NULL ); } /*}}}*/ static int GetDriveParams( HANDLE hVWin32Device, int volume, DRIVEPARAMS* pParam ) /*{{{*/ { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; reg.reg_EAX = 0x440d; /* IOCTL for block device */ reg.reg_EBX = volume; /* one-based drive number */ reg.reg_ECX = 0x0860; /* Get Device params */ reg.reg_EDX = (DWORD)pParam; reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( hVWin32Device, VWIN32_DIOC_DOS_IOCTL, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); if ( !bResult || (reg.reg_Flags & 1) ) return (reg.reg_EAX & 0xffff); return 0; } /*}}}*/ static int SetDriveParams( HANDLE hVWin32Device, int volume, DRIVEPARAMS* pParam ) /*{{{*/ { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; reg.reg_EAX = 0x440d; /* IOCTL for block device */ reg.reg_EBX = volume; /* one-based drive number */ reg.reg_ECX = 0x0840; /* Set Device params */ reg.reg_EDX = (DWORD)pParam; reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( hVWin32Device, VWIN32_DIOC_DOS_IOCTL, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); if ( !bResult || (reg.reg_Flags & 1) ) return (reg.reg_EAX & 0xffff); return 0; } /*}}}*/ static int GetMediaID( HANDLE hVWin32Device, int volume, MID* pMid ) /*{{{*/ { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; reg.reg_EAX = 0x440d; /* IOCTL for block device */ reg.reg_EBX = volume; /* one-based drive number */ reg.reg_ECX = 0x0866; /* Get Media ID */ reg.reg_EDX = (DWORD)pMid; reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( hVWin32Device, VWIN32_DIOC_DOS_IOCTL, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); if ( !bResult || (reg.reg_Flags & 1) ) return (reg.reg_EAX & 0xffff); return 0; } /*}}}*/ static int VolumeCheck(HANDLE hVWin32Device, int volume, WORD* flags ) /*{{{*/ { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; reg.reg_EAX = 0x4409; /* Is Drive Remote */ reg.reg_EBX = volume; /* one-based drive number */ reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( hVWin32Device, VWIN32_DIOC_DOS_IOCTL, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); if ( !bResult || (reg.reg_Flags & 1) ) return (reg.reg_EAX & 0xffff); *flags = (WORD)(reg.reg_EDX & 0xffff); return 0; } /*}}}*/ static int LockLogicalVolume(HANDLE hVWin32Device, int volume, int lock_level, int permissions) /*{{{*/ { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; reg.reg_EAX = 0x440d; /* generic IOCTL */ reg.reg_ECX = 0x084a; /* lock logical volume */ reg.reg_EBX = volume | (lock_level << 8); reg.reg_EDX = permissions; reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( hVWin32Device, VWIN32_DIOC_DOS_IOCTL, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); if ( !bResult || (reg.reg_Flags & 1) ) return (reg.reg_EAX & 0xffff); return 0; } /*}}}*/ static int UnlockLogicalVolume( HANDLE hVWin32Device, int volume ) /*{{{*/ { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; reg.reg_EAX = 0x440d; reg.reg_ECX = 0x086a; /* lock logical volume */ reg.reg_EBX = volume; reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( hVWin32Device, VWIN32_DIOC_DOS_IOCTL, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); if ( !bResult || (reg.reg_Flags & 1) ) return -1; return 0; } /*}}}*/ static int w32mode(int mode) /*{{{*/ { switch(mode) { case O_RDONLY: return GENERIC_READ; case O_WRONLY: return GENERIC_WRITE; } return GENERIC_READ | GENERIC_WRITE; } /*}}}*/ /* Device_open -- Open an image file */ /*{{{*/ const char *Device_open(struct Device *sb, const char *filename, int mode, const char *deviceOpts) { /* Windows 95/NT: floppy drives using handles */ if (strlen(filename) == 2 && filename[1] == ':') /* Drive name */ { char vname[20]; DWORD dwVers; sb->fd = -1; dwVers = GetVersion(); if (dwVers & 0x80000000L) /* Win32s (3.1) or Win32c (Win95) */ { int lock, driveno, res, permissions; unsigned short drive_flags; MID media; vname[0] = toupper(filename[0]); driveno = vname[0] - 'A' + 1; /* 1=A: 2=B: */ sb->drvtype = CPMDRV_WIN95; sb->hdisk = CreateFile( "\\\\.\\vwin32", 0, 0, NULL, 0, FILE_FLAG_DELETE_ON_CLOSE, NULL ); if (!sb->hdisk) { return "Failed to open VWIN32 driver."; } if (VolumeCheck(sb->hdisk, driveno, &drive_flags)) { CloseHandle(sb->hdisk); return "Invalid drive"; } res = GetMediaID( sb->hdisk, driveno, &media ); if ( res ) { const char *lboo = NULL; if ( res == ERROR_INVALID_FUNCTION && (drive_flags & DRIVE_IS_REMOTE )) lboo = "Network drive"; else if (res == ERROR_ACCESS_DENIED) lboo = "Access denied"; /* nb: It's perfectly legitimate for GetMediaID() to fail; most CP/M */ /* CP/M disks won't have a media ID. */ if (lboo != NULL) { CloseHandle(sb->hdisk); return lboo; } } if (!res && (!memcmp( media.midFileSysType, "CDROM", 5 ) || !memcmp( media.midFileSysType, "CD001", 5 ) || !memcmp( media.midFileSysType, "CDAUDIO", 5 ))) { CloseHandle(sb->hdisk); return "CD-ROM drive"; } if (w32mode(mode) & GENERIC_WRITE) { lock = LEVEL0_LOCK; /* Exclusive access */ permissions = 0; } else { lock = LEVEL1_LOCK; /* Allow other processes access */ permissions = LEVEL1_LOCK_MAX_PERMISSION; } if (LockLogicalVolume( sb->hdisk, driveno, lock, permissions)) { CloseHandle(sb->hdisk); return "Could not acquire a lock on the drive."; } sb->fd = driveno; /* 1=A: 2=B: etc - we will need this later */ } else { sprintf(vname, "\\\\.\\%s", filename); sb->drvtype = CPMDRV_WINNT; sb->hdisk = CreateFile(vname, /* Name */ w32mode(mode), /* Access mode */ FILE_SHARE_READ|FILE_SHARE_WRITE, /*Sharing*/ NULL, /* Security attributes */ OPEN_EXISTING, /* See MSDN */ 0, /* Flags & attributes */ NULL); /* Template file */ if (sb->hdisk != INVALID_HANDLE_VALUE) { sb->fd = 1; /* Arbitrary value >0 */ if (LockVolume(sb->hdisk) == FALSE) /* Lock drive */ { char *lboo = strwin32error(); CloseHandle(sb->hdisk); sb->fd = -1; return lboo; } } else return strwin32error(); } sb->opened = 1; return NULL; } /* Not a floppy. Treat it as a normal file */ mode |= O_BINARY; sb->fd = open(filename, mode); if (sb->fd == -1) return strerror(errno); sb->drvtype = CPMDRV_FILE; sb->opened = 1; return NULL; } /*}}}*/ /* Device_setGeometry -- Set disk geometry */ /*{{{*/ const char * Device_setGeometry(struct Device *this, int secLength, int sectrk, int tracks, off_t offset, const char *libdskGeometry) { int n; this->secLength=secLength; this->sectrk=sectrk; this->tracks=tracks; // Bill Buckels - add this->offset this->offset=offset; // Bill Buckels - not sure what to do here if (this->drvtype == CPMDRV_WIN95) { DRIVEPARAMS drvp; memset(&drvp, 0, sizeof(drvp)); if (GetDriveParams( this->hdisk, this->fd, &drvp )) return "GetDriveParams failed"; drvp.bytespersector = secLength; drvp.sectorspertrack = sectrk; drvp.totalsectors = sectrk * tracks; /* Guess the cylinder/head configuration from the track count. This will * get single-sided 80-track discs wrong, but it's that or double-sided * 40-track (or add cylinder/head counts to diskdefs) */ if (tracks < 44) { drvp.cylinders = tracks; drvp.heads = 1; } else { drvp.cylinders = tracks / 2; drvp.heads = 2; } /* Set up "reasonable" values for the other members */ drvp.sectorspercluster = 1024 / secLength; drvp.reservedsectors = 1; drvp.numberofFATs = 2; drvp.sectorcount = sectrk; drvp.rootdirsize = 64; drvp.mediaid = 0xF0; drvp.hiddensectors = 0; drvp.sectorsperfat = 3; for (n = 0; n < sectrk; n++) { drvp.sectortable[n*2] = n + PHYSICAL_SECTOR_1; /* Physical sector numbers */ drvp.sectortable[n*2+1] = secLength; } drvp.special = 6; /* We have not set: drvp.mediatype drvp.devicetype drvp.deviceattrs which should have been read correctly by GetDriveParams(). */ SetDriveParams( this->hdisk, this->fd, &drvp ); } return NULL; } /*}}}*/ /* Device_close -- Close an image file */ /*{{{*/ const char *Device_close(struct Device *sb) { sb->opened = 0; switch(sb->drvtype) { case CPMDRV_WIN95: UnlockLogicalVolume(sb->hdisk, sb->fd ); if (!CloseHandle( sb->hdisk )) return strwin32error(); return NULL; case CPMDRV_WINNT: DismountVolume(sb->hdisk); UnlockVolume(sb->hdisk); if (!CloseHandle(sb->hdisk)) return strwin32error(); return NULL; } if (close(sb->fd)) return strerror(errno); return NULL; } /*}}}*/ /* Device_readSector -- read a physical sector */ /*{{{*/ const char *Device_readSector(const struct Device *drive, int track, int sector, char *buf) { int res; off_t offset; assert(sector>=0); assert(sector<drive->sectrk); assert(track>=0); assert(track<drive->tracks); offset = ((sector+track*drive->sectrk)*drive->secLength); if (drive->drvtype == CPMDRV_WINNT) { LPVOID iobuffer; DWORD bytesread; // Bill Buckels - add drive->offset if (SetFilePointer(drive->hdisk, offset+drive->offset, NULL, FILE_BEGIN) == INVALID_FILE_SIZE) { return strwin32error(); } iobuffer = VirtualAlloc(NULL, drive->secLength, MEM_COMMIT, PAGE_READWRITE); if (!iobuffer) { return strwin32error(); } res = ReadFile(drive->hdisk, iobuffer, drive->secLength, &bytesread, NULL); if (!res) { char *lboo = strwin32error(); VirtualFree(iobuffer, drive->secLength, MEM_RELEASE); return lboo; } memcpy(buf, iobuffer, drive->secLength); VirtualFree(iobuffer, drive->secLength, MEM_RELEASE); if (bytesread < (unsigned)drive->secLength) { memset(buf + bytesread, 0, drive->secLength - bytesread); } return NULL; } // Bill Buckels - not sure what to do here if (drive->drvtype == CPMDRV_WIN95) { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; #ifdef USE_INT13 int cyl, head; if (drive->tracks < 44) { cyl = track; head = 0; } else { cyl = track/2; head = track & 1; } reg.reg_EAX = 0x0201; /* Read 1 sector */ reg.reg_EBX = (DWORD)buf; reg.reg_ECX = (cyl << 8) | (sector + PHYSICAL_SECTOR_1); reg.reg_EDX = (head << 8) | (drive->fd - 1); reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( drive->hdisk, VWIN32_DIOC_DOS_INT13, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); #else DISKIO di; reg.reg_EAX = drive->fd - 1; /* zero-based volume number */ reg.reg_EBX = (DWORD)&di; reg.reg_ECX = 0xffff; /* use DISKIO structure */ reg.reg_Flags = 1; /* preset the carry flag */ di.diStartSector = sector+track*drive->sectrk; di.diSectors = 1; di.diBuffer = (DWORD)buf; bResult = DeviceIoControl( drive->hdisk, VWIN32_DIOC_DOS_INT25, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); #endif if ( !bResult || (reg.reg_Flags & 1) ) { if (GetLastError()) return strwin32error(); return "Unknown read error."; } return 0; } // Bill Buckels - add drive->offset if (lseek(drive->fd,offset+drive->offset,SEEK_SET)==-1) { return strerror(errno); } if ((res=read(drive->fd, buf, drive->secLength)) != drive->secLength) { if (res==-1) { return strerror(errno); } else memset(buf+res,0,drive->secLength-res); /* hit end of disk image */ } return NULL; } /*}}}*/ /* Device_writeSector -- write physical sector */ /*{{{*/ const char *Device_writeSector(const struct Device *drive, int track, int sector, const char *buf) { off_t offset; int res; assert(sector>=0); assert(sector<drive->sectrk); assert(track>=0); assert(track<drive->tracks); offset = ((sector+track*drive->sectrk)*drive->secLength); if (drive->drvtype == CPMDRV_WINNT) { LPVOID iobuffer; DWORD byteswritten; // Bill Buckels - add drive->offset if (SetFilePointer(drive->hdisk, offset+drive->offset, NULL, FILE_BEGIN) == INVALID_FILE_SIZE) { return strwin32error(); } iobuffer = VirtualAlloc(NULL, drive->secLength, MEM_COMMIT, PAGE_READWRITE); if (!iobuffer) { return strwin32error(); } memcpy(iobuffer, buf, drive->secLength); res = WriteFile(drive->hdisk, iobuffer, drive->secLength, &byteswritten, NULL); if (!res || (byteswritten < (unsigned)drive->secLength)) { char *lboo = strwin32error(); VirtualFree(iobuffer, drive->secLength, MEM_RELEASE); return lboo; } VirtualFree(iobuffer, drive->secLength, MEM_RELEASE); return NULL; } // Bill Buckels - not sure what to do here if (drive->drvtype == CPMDRV_WIN95) { DIOC_REGISTERS reg; BOOL bResult; DWORD cb; #ifdef USE_INT13 int cyl, head; if (drive->tracks < 44) { cyl = track; head = 0; } else { cyl = track/2; head = track & 1; } reg.reg_EAX = 0x0301; /* Write 1 sector */ reg.reg_EBX = (DWORD)buf; reg.reg_ECX = (cyl << 8) | (sector + PHYSICAL_SECTOR_1); reg.reg_EDX = (head << 8) | (drive->fd - 1); reg.reg_Flags = 1; /* preset the carry flag */ bResult = DeviceIoControl( drive->hdisk, VWIN32_DIOC_DOS_INT13, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); #else DISKIO di; reg.reg_EAX = drive->fd - 1; /* zero-based volume number */ reg.reg_EBX = (DWORD)&di; reg.reg_ECX = 0xffff; /* use DISKIO structure */ reg.reg_Flags = 1; /* preset the carry flag */ di.diStartSector = sector+track*drive->sectrk; di.diSectors = 1; di.diBuffer = (DWORD)buf; bResult = DeviceIoControl( drive->hdisk, VWIN32_DIOC_DOS_INT26, &reg, sizeof( reg ), &reg, sizeof( reg ), &cb, 0 ); #endif if ( !bResult || (reg.reg_Flags & 1) ) { if (GetLastError()) return strwin32error(); return "Unknown write error."; } return NULL; } // Bill Buckels - add drive->offset if (lseek(drive->fd,offset+drive->offset, SEEK_SET)==-1) { return strerror(errno); } if (write(drive->fd, buf, drive->secLength) == drive->secLength) return NULL; return strerror(errno); } /*}}}*/
30.76155
133
0.544499
[ "geometry" ]
182950f2e66a537d77a54dde5a080f50a36f3748
3,633
h
C
src/variorum/Intel/Skylake_55.h
amarathe84/variorum
d6cbf40d6154ffc8b8579cb6c10c387287720919
[ "MIT" ]
null
null
null
src/variorum/Intel/Skylake_55.h
amarathe84/variorum
d6cbf40d6154ffc8b8579cb6c10c387287720919
[ "MIT" ]
null
null
null
src/variorum/Intel/Skylake_55.h
amarathe84/variorum
d6cbf40d6154ffc8b8579cb6c10c387287720919
[ "MIT" ]
null
null
null
// Copyright 2019 Lawrence Livermore National Security, LLC and other // Variorum Project Developers. See the top-level LICENSE file for details. // // SPDX-License-Identifier: MIT #ifndef SKYLAKE_55_H_INCLUDE #define SKYLAKE_55_H_INCLUDE #include <sys/types.h> /// @brief List of unique addresses for Skylake Family/Model 55H. struct skylake_55_offsets { /// @brief Address for MSR_PLATFORM_INFO. const off_t msr_platform_info; /// @brief Address for IA32_TIME_STAMP_COUNTER. const off_t ia32_time_stamp_counter; /// @brief Address for IA32_PERF_CTL. const off_t ia32_perf_ctl; /// @brief Address for IA32_PERF_STATUS. const off_t ia32_perf_status; /// @brief Address for IA32_THERM_INTERRUPT. const off_t ia32_therm_interrupt; /// @brief Address for IA32_THERM_STATUS. const off_t ia32_therm_status; /// @brief Address for THERM2_CTL. const off_t msr_therm2_ctl; /// @brief Address for IA32_MISC_ENABLE. const off_t ia32_misc_enable; /// @brief Address for TEMPERATURE_TARGET. const off_t msr_temperature_target; /// @brief Address for TURBO_RATIO_LIMIT. const off_t msr_turbo_ratio_limit; /// @brief Address for TURBO_RATIO_LIMIT1. const off_t msr_turbo_ratio_limit1; /// @brief Address for TURBO_RATIO_LIMIT2. const off_t msr_turbo_ratio_limit2; /// @brief Address for IA32_PACKAGE_THERM_STATUS. const off_t ia32_package_therm_status; /// @brief Address for IA32_PACKAGE_THERM_INTERRUPT. const off_t ia32_package_therm_interrupt; /// @brief Address for IA32_FIXED_CTR_CTRL. const off_t ia32_fixed_ctr_ctrl; /// @brief Address for IA32_PERF_GLOBAL_STATUS. const off_t ia32_perf_global_status; /// @brief Address for IA32_PERF_GLOBAL_CTRL. const off_t ia32_perf_global_ctrl; /// @brief Address for IA32_PERF_GLOBAL_OVF_CTRL. const off_t ia32_perf_global_ovf_ctrl; /// @brief Address for RAPL_POWER_UNIT. const off_t msr_rapl_power_unit; /// @brief Address for PKG_POWER_LIMIT. const off_t msr_pkg_power_limit; /// @brief Address for PKG_ENERGY_STATUS. const off_t msr_pkg_energy_status; /// @brief Address for PKG_PERF_STATUS. const off_t msr_pkg_perf_status; /// @brief Address for PKG_POWER_INFO. const off_t msr_pkg_power_info; /// @brief Address for DRAM_POWER_LIMIT. const off_t msr_dram_power_limit; /// @brief Address for DRAM_ENERGY_STATUS. const off_t msr_dram_energy_status; /// @brief Address for DRAM_PERF_STATUS. const off_t msr_dram_perf_status; /// @brief Address for TURBO_ACTIVATION_RATIO. const off_t msr_turbo_activation_ratio; /// @brief Address for IA32_MPERF. const off_t ia32_mperf; /// @brief Address for IA32_APERF. const off_t ia32_aperf; /// @brief Array of unique addresses for fixed counters. off_t ia32_fixed_counters[3]; /// @brief Array of unique addresses for perfmon counters. off_t ia32_perfmon_counters[8]; /// @brief Array of unique addresses for perfevtsel counters. off_t ia32_perfevtsel_counters[8]; /// @brief Array of unique addresses for pmon evtsel. off_t msrs_pcu_pmon_evtsel[4]; }; int fm_06_55_get_power_limits(int long_ver); int fm_06_55_set_power_limits(int package_power_limit); int fm_06_55_get_features(void); int fm_06_55_get_thermals(int long_ver); int fm_06_55_get_counters(int long_ver); int fm_06_55_get_clocks(int long_ver); int fm_06_55_get_power(int long_ver); int fm_06_55_poll_power(FILE *output); int fm_06_55_monitoring(FILE *output); int fm_06_55_set_frequency(int core_freq_mhz); #endif
35.271845
75
0.752546
[ "model" ]
182b790ef55711075d267b9fe6507a15511e05c8
7,275
h
C
include/algorithms/boosting/logitboost_model.h
mgkwill/daal
6ddb4bafad6cc65a7f474a00aecd3ebb6b25c187
[ "Apache-2.0" ]
1
2021-04-05T19:16:21.000Z
2021-04-05T19:16:21.000Z
include/algorithms/boosting/logitboost_model.h
mgkwill/daal
6ddb4bafad6cc65a7f474a00aecd3ebb6b25c187
[ "Apache-2.0" ]
null
null
null
include/algorithms/boosting/logitboost_model.h
mgkwill/daal
6ddb4bafad6cc65a7f474a00aecd3ebb6b25c187
[ "Apache-2.0" ]
null
null
null
/* file: logitboost_model.h */ /******************************************************************************* * Copyright 2014-2017 Intel Corporation * All Rights Reserved. * * If this software was obtained under the Intel Simplified Software License, * the following terms apply: * * The source code, information and material ("Material") contained herein is * owned by Intel Corporation or its suppliers or licensors, and title to such * Material remains with Intel Corporation or its suppliers or licensors. The * Material contains proprietary information of Intel or its suppliers and * licensors. The Material is protected by worldwide copyright laws and treaty * provisions. No part of the Material may be used, copied, reproduced, * modified, published, uploaded, posted, transmitted, distributed or disclosed * in any way without Intel's prior express written permission. No license under * any patent, copyright or other intellectual property rights in the Material * is granted to or conferred upon you, either expressly, by implication, * inducement, estoppel or otherwise. Any license under such intellectual * property rights must be express and approved by Intel in writing. * * Unless otherwise agreed by Intel in writing, you may not remove or alter this * notice or any other notice embedded in Materials by Intel or Intel's * suppliers or licensors in any way. * * * If this software was obtained under the Apache License, Version 2.0 (the * "License"), the following terms apply: * * 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. *******************************************************************************/ /* //++ // Implementation of class defining LogitBoost model. //-- */ #ifndef __LOGIT_BOOST_MODEL_H__ #define __LOGIT_BOOST_MODEL_H__ #include "algorithms/algorithm.h" #include "data_management/data/homogen_numeric_table.h" #include "algorithms/boosting/boosting_model.h" namespace daal { namespace algorithms { /** * \brief Contains classes for the LogitBoost classification algorithm */ namespace logitboost { /** * \brief Contains version 1.0 of Intel(R) Data Analytics Acceleration Library (Intel(R) DAAL) interface. */ namespace interface1 { /** * @ingroup logitboost * @{ */ /** * <a name="DAAL-STRUCT-ALGORITHMS__LOGITBOOST__PARAMETER"></a> * \brief LogitBoost algorithm parameters * * \snippet boosting/brownboost_model.h Parameter source code */ /* [Parameter source code] */ struct DAAL_EXPORT Parameter : public boosting::Parameter { /** Default constructor */ Parameter(); /** * Constructs LogitBoost parameter structure * \param[in] wlTrainForParameter Pointer to the training algorithm of the weak learner * \param[in] wlPredictForParameter Pointer to the prediction algorithm of the weak learner * \param[in] acc Accuracy of the LogitBoost training algorithm * \param[in] maxIter Maximal number of terms in additive regression * \param[in] nC Number of classes in the training data set * \param[in] wThr Threshold to avoid degenerate cases when calculating weights W * \param[in] zThr Threshold to avoid degenerate cases when calculating responses Z */ Parameter(const services::SharedPtr<weak_learner::training::Batch>& wlTrainForParameter, const services::SharedPtr<weak_learner::prediction::Batch>& wlPredictForParameter, double acc = 0.0, size_t maxIter = 10, size_t nC = 0, double wThr = 1e-10, double zThr = 1e-10); double accuracyThreshold; /*!< Accuracy of the LogitBoost training algorithm */ size_t maxIterations; /*!< Maximal number of terms in additive regression */ size_t nClasses; /*!< Number of classes */ double weightsDegenerateCasesThreshold; /*!< Threshold to avoid degenerate cases when calculating weights W */ double responsesDegenerateCasesThreshold; /*!< Threshold to avoid degenerate cases when calculating responses Z */ services::Status check() const DAAL_C11_OVERRIDE; }; /* [Parameter source code] */ /** * <a name="DAAL-CLASS-ALGORITHMS__LOGITBOOST__MODEL"></a> * \brief %Model of the classifier trained by the logitboost::training::Batch algorithm. * * \par References * - \ref training::interface1::Batch "training::Batch" class * - \ref prediction::interface1::Batch "prediction::Batch" class */ class DAAL_EXPORT Model : public boosting::Model { public: DECLARE_MODEL(Model, classifier::Model) /** * Constructs the LogitBoost model * \tparam modelFPType Data type to store LogitBoost model data, double or float * \param[in] nFeatures Number of features in the dataset * \param[in] par Pointer to the parameter structure of the LogitBoost algorithm * \param[in] dummy Dummy variable for the templated constructor * \DAAL_DEPRECATED_USE{ Model::create } */ template <typename modelFPType> DAAL_EXPORT Model(size_t nFeatures, const Parameter *par, modelFPType dummy); /** * Empty constructor for deserialization * \DAAL_DEPRECATED_USE{ Model::create } */ Model() : boosting::Model(), _nIterations(0) { } /** * Constructs the LogitBoost model * \param[in] nFeatures Number of features in the dataset * \param[in] par Pointer to the parameter structure of the LogitBoost algorithm * \param[out] stat Status of the model construction */ static services::SharedPtr<Model> create(size_t nFeatures, const Parameter *par, services::Status *stat = NULL); virtual ~Model() { } /** * Sets the number of iterations for the algorithm * @param nIterations Number of iterations */ void setIterations(size_t nIterations); /** * Returns the number of iterations done by the training algorithm * \return The number of iterations done by the training algorithm */ size_t getIterations() const; protected: size_t _nIterations; template<typename Archive, bool onDeserialize> services::Status serialImpl(Archive *arch) { services::Status st = boosting::Model::serialImpl<Archive, onDeserialize>(arch); if (!st) return st; arch->set(_nIterations); return st; } Model(size_t nFeatures, const Parameter *par, services::Status &st); }; typedef services::SharedPtr<Model> ModelPtr; /** @} */ } // namespace interface1 using interface1::Parameter; using interface1::Model; using interface1::ModelPtr; } // namespace daal::algorithms::logitboost } } // namespace daal #endif
38.289474
121
0.678763
[ "model" ]
183a8b836d31f5153145f13fa1b57154ad29fbf7
22,170
c
C
natus/engines/SpiderMonkey.c
Natus/natus
4074619edd45f1bb62a5561d08a64e9960b3d9e8
[ "MIT" ]
1
2015-11-05T03:19:22.000Z
2015-11-05T03:19:22.000Z
natus/engines/SpiderMonkey.c
Natus/natus
4074619edd45f1bb62a5561d08a64e9960b3d9e8
[ "MIT" ]
null
null
null
natus/engines/SpiderMonkey.c
Natus/natus
4074619edd45f1bb62a5561d08a64e9960b3d9e8
[ "MIT" ]
null
null
null
/* * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com> * * 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. * */ #include <assert.h> #include <string.h> #include <jsapi.h> typedef JSContext* natusEngCtx; typedef jsval* natusEngVal; #define NATUS_ENGINE_TYPES_DEFINED #define I_ACKNOWLEDGE_THAT_NATUS_IS_NOT_STABLE #include <natus-engine.h> static void sm_val_unlock(natusEngCtx ctx, natusEngVal val); static void sm_val_free(natusEngVal val); static natusValueType sm_get_type(const natusEngCtx ctx, const natusEngVal val); static natusEngVal mkjsval(JSContext *ctx, jsval val) { jsval *v = malloc(sizeof(jsval)); if (!v) return NULL; *v = val; JSVAL_LOCK(ctx, *v); return v; } static void obj_finalize(JSContext *ctx, JSObject *obj); static natusPrivate * get_private(JSContext *ctx, JSObject *obj) { if (!ctx || !obj) return NULL; if (JS_IsArrayObject(ctx, obj)) return NULL; if (JS_ObjectIsFunction(ctx, obj)) { jsval privval; if (!JS_GetReservedSlot(ctx, obj, 0, &privval) || !JSVAL_IS_OBJECT(privval)) return NULL; obj = JSVAL_TO_OBJECT(privval); } JSClass *cls = JS_GetClass(ctx, obj); if (!cls || cls->finalize != obj_finalize) return NULL; return JS_GetPrivate(ctx, obj); } static JSBool property_handler(JSContext *ctx, JSObject *object, jsid id, jsval *vp, natusPropertyAction act) { natusPrivate *priv = get_private(ctx, object); if (!priv) return JS_FALSE; jsval key; if (act & ~natusPropertyActionEnumerate) { if (!JS_IdToValue(ctx, id, &key)) return JS_FALSE; assert(JSVAL_IS_STRING(key) || JSVAL_IS_NUMBER(key)); } natusEngValFlags flags = natusEngValFlagNone; natusEngVal obj = mkjsval(ctx, OBJECT_TO_JSVAL(object)); natusEngVal idx = (act & ~natusPropertyActionEnumerate) ? mkjsval(ctx, key) : NULL; natusEngVal val = (act & natusPropertyActionSet) ? mkjsval(ctx, *vp) : NULL; natusEngVal res = natus_handle_property(act, obj, priv, idx, val, &flags); if (flags & natusEngValFlagException) { if (!res || JSVAL_IS_VOID(*res)) { if ((flags & natusEngValFlagUnlock) && res) sm_val_unlock(ctx, res); if ((flags & natusEngValFlagFree) && res) sm_val_free(res); return JS_TRUE; } JS_SetPendingException(ctx, *res); if (flags & natusEngValFlagUnlock) sm_val_unlock(ctx, res); if (flags & natusEngValFlagFree) sm_val_free(res); return JS_FALSE; } if (act == natusPropertyActionGet) *vp = *res; if (flags & natusEngValFlagUnlock) sm_val_unlock(ctx, res); if (flags & natusEngValFlagFree) sm_val_free(res); return JS_TRUE; } static inline JSBool call_handler(JSContext *ctx, uintN argc, jsval *vp, bool constr) { // Allocate our array of arguments JSObject *arga = JS_NewArrayObject(ctx, argc, JS_ARGV(ctx, vp)); if (!arga) return JS_FALSE; // Get the private natusPrivate *priv = get_private(ctx, JSVAL_TO_OBJECT(JS_CALLEE(ctx, vp))); if (!priv) return JS_FALSE; // Do the call natusEngValFlags flags; natusEngVal obj = mkjsval(ctx, JS_CALLEE(ctx, vp)); natusEngVal ths = mkjsval(ctx, constr ? JSVAL_VOID : JS_THIS(ctx, vp)); natusEngVal arg = mkjsval(ctx, OBJECT_TO_JSVAL(arga)); natusEngVal res = natus_handle_call(obj, priv, ths, arg, &flags); // Handle the results if (flags & natusEngValFlagException) { JS_SetPendingException(ctx, res ? *res : JSVAL_VOID); if ((flags & natusEngValFlagUnlock) && res) sm_val_unlock(ctx, res); if ((flags & natusEngValFlagFree) && res) sm_val_free(res); return JS_FALSE; } JS_SET_RVAL(ctx, vp, *res); if (flags & natusEngValFlagUnlock) sm_val_unlock(ctx, res); if (flags & natusEngValFlagFree) sm_val_free(res); return JS_TRUE; } static void obj_finalize(JSContext *ctx, JSObject *obj) { natus_private_free(get_private(ctx, obj)); } static JSBool obj_del(JSContext *ctx, JSObject *object, jsid id, jsval *vp) { return property_handler(ctx, object, id, vp, natusPropertyActionDelete); } static JSBool obj_get(JSContext *ctx, JSObject *object, jsid id, jsval *vp) { return property_handler(ctx, object, id, vp, natusPropertyActionGet); } static JSBool obj_set(JSContext *ctx, JSObject *object, jsid id, JSBool strict, jsval *vp) { return property_handler(ctx, object, id, vp, natusPropertyActionSet); } static JSBool obj_enum(JSContext *ctx, JSObject *object, JSIterateOp enum_op, jsval *statep, jsid *idp) { jsuint len; jsval step; if (enum_op == JSENUMERATE_NEXT) { assert(statep && idp); // Get our length and the current step if (!JS_GetArrayLength(ctx, JSVAL_TO_OBJECT(*statep), &len)) return JS_FALSE; if (!JS_GetProperty(ctx, JSVAL_TO_OBJECT(*statep), "step", &step)) return JS_FALSE; // If we have finished our iteration, end if ((jsuint) JSVAL_TO_INT(step) >= len) { JSVAL_UNLOCK(ctx, *statep); *statep = JSVAL_NULL; return JS_TRUE; } // Get the item jsval item; if (!JS_GetElement(ctx, JSVAL_TO_OBJECT(*statep), JSVAL_TO_INT(step), &item)) return JS_FALSE; JS_ValueToId(ctx, item, idp); // Increment to the next step step = INT_TO_JSVAL(JSVAL_TO_INT(step) + 1); if (!JS_SetProperty(ctx, JSVAL_TO_OBJECT(*statep), "step", &step)) return JS_FALSE; return JS_TRUE; } else if (enum_op == JSENUMERATE_DESTROY) { assert(statep); JSVAL_UNLOCK(ctx, *statep); return JS_TRUE; } assert(enum_op == JSENUMERATE_INIT); assert(statep); // Handle the results jsval res = JSVAL_VOID; step = INT_TO_JSVAL(0); if (!property_handler(ctx, object, 0, &res, natusPropertyActionEnumerate) || sm_get_type(ctx, &res) != natusValueTypeArray || !JS_GetArrayLength(ctx, JSVAL_TO_OBJECT(res), &len) || !JS_SetProperty(ctx, JSVAL_TO_OBJECT(res), "step", &step)) return JS_FALSE; // Keep the jsval, but dispose of the wrapper *statep = res; JSVAL_LOCK(ctx, *statep); if (idp) *idp = INT_TO_JSVAL(len); return JS_TRUE; } static JSBool obj_call(JSContext *ctx, uintN argc, jsval *vp) { return call_handler(ctx, argc, vp, false); } static JSBool obj_new(JSContext *ctx, uintN argc, jsval *vp) { return call_handler(ctx, argc, vp, true); } static JSBool fnc_call(JSContext *ctx, uintN argc, jsval *vp) { return call_handler(ctx, argc, vp, JS_IsConstructing(ctx, vp)); } static JSClass glbdef = { "GlobalObject", JSCLASS_GLOBAL_FLAGS | JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, obj_finalize, }; static JSClass fncdef = { "NativeFunction", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, obj_finalize, }; static JSClass objdef = { "NativeObject", JSCLASS_HAS_PRIVATE, JS_PropertyStub, JS_PropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, obj_finalize, }; static void report_error(JSContext *cx, const char *message, JSErrorReport *report) { fprintf(stderr, "%s:%u:%s\n", report->filename ? report->filename : "<no filename>", (unsigned int) report->lineno, message); } static void sm_ctx_free(natusEngCtx ctx) { JSRuntime *run = JS_GetRuntime(ctx); JS_GC(ctx); JS_DestroyContext(ctx); JS_DestroyRuntime(run); } static void sm_val_unlock(natusEngCtx ctx, natusEngVal val) { JSVAL_UNLOCK(ctx, *val); } static natusEngVal sm_val_duplicate(natusEngCtx ctx, natusEngVal val) { return mkjsval(ctx, *val); } static void sm_val_free(natusEngVal val) { free(val); } static natusEngVal sm_new_global(natusEngCtx ctx, natusEngVal val, natusPrivate *priv, natusEngCtx *newctx, natusEngValFlags *flags) { bool freectx = false; JSObject *glb = NULL; /* Reuse existing runtime and context */ if (ctx && val) { *newctx = ctx; glb = JS_NewGlobalObject(ctx, &glbdef); /* Create a new runtime and context */ } else { freectx = true; JSRuntime *run = JS_NewRuntime(1024 * 1024); if (!run) return NULL; *newctx = JS_NewContext(run, 1024 * 1024); if (!*newctx) { JS_DestroyRuntime(run); return NULL; } JS_SetOptions(*newctx, JSOPTION_VAROBJFIX | JSOPTION_DONT_REPORT_UNCAUGHT | JSOPTION_XML | JSOPTION_UNROOTED_GLOBAL); JS_SetVersion(*newctx, JSVERSION_LATEST); JS_SetErrorReporter(*newctx, report_error); glb = JS_NewCompartmentAndGlobalObject(*newctx, &glbdef, NULL); } if (!glb || !JS_InitStandardClasses(*newctx, glb)) { if (freectx && *newctx) { JSRuntime *run = JS_GetRuntime(*newctx); JS_DestroyContext(*newctx); JS_DestroyRuntime(run); } return NULL; } if (!JS_SetPrivate(ctx, glb, priv)) { natus_private_free(priv); if (freectx && *newctx) { JSRuntime *run = JS_GetRuntime(*newctx); JS_DestroyContext(*newctx); JS_DestroyRuntime(run); } return NULL; } natusEngVal v = mkjsval(*newctx, OBJECT_TO_JSVAL(glb)); if (!v) { if (freectx && *newctx) { JSRuntime *run = JS_GetRuntime(*newctx); JS_DestroyContext(*newctx); JS_DestroyRuntime(run); } return NULL; } return v; } static natusEngVal sm_new_bool(const natusEngCtx ctx, bool b, natusEngValFlags *flags) { return mkjsval(ctx, BOOLEAN_TO_JSVAL(b)); } static natusEngVal sm_new_number(const natusEngCtx ctx, double n, natusEngValFlags *flags) { jsval v = JSVAL_VOID; if (!JS_NewNumberValue(ctx, n, &v)) { v = JSVAL_VOID; if (JS_IsExceptionPending(ctx) && JS_GetPendingException(ctx, &v)) *flags |= natusEngValFlagException; } return mkjsval(ctx, v); } static natusEngVal sm_new_string_utf8(const natusEngCtx ctx, const char *str, size_t len, natusEngValFlags *flags) { jsval v = JSVAL_VOID; JSString *s = JS_NewStringCopyN(ctx, str, len); if (s) v = STRING_TO_JSVAL(s); else { if (JS_IsExceptionPending(ctx) && JS_GetPendingException(ctx, &v)) *flags |= natusEngValFlagException; } return mkjsval(ctx, STRING_TO_JSVAL(s)); } static natusEngVal sm_new_string_utf16(const natusEngCtx ctx, const natusChar *str, size_t len, natusEngValFlags *flags) { jsval v = JSVAL_VOID; JSString *s = JS_NewUCStringCopyN(ctx, str, len); if (s) v = STRING_TO_JSVAL(s); else { if (JS_IsExceptionPending(ctx) && JS_GetPendingException(ctx, &v)) *flags |= natusEngValFlagException; } return mkjsval(ctx, STRING_TO_JSVAL(s)); } static natusEngVal sm_new_array(const natusEngCtx ctx, const natusEngVal *array, size_t len, natusEngValFlags *flags) { jsval *valv = calloc(len, sizeof(jsval)); if (!valv) return NULL; int i; for (i = 0; i < len; i++) valv[i] = *array[i]; JSObject* obj = JS_NewArrayObject(ctx, i, valv); free(valv); jsval v; if (obj) v = OBJECT_TO_JSVAL(obj); else if (JS_IsExceptionPending(ctx) && JS_GetPendingException(ctx, &v)) *flags |= natusEngValFlagException; return mkjsval(ctx, v); } static natusEngVal sm_new_function(const natusEngCtx ctx, const char *name, natusPrivate *priv, natusEngValFlags *flags) { JSFunction *fnc = JS_NewFunction(ctx, fnc_call, 0, JSFUN_CONSTRUCTOR, NULL, name); JSObject *obj = JS_GetFunctionObject(fnc); JSObject *prv = JS_NewObject(ctx, &fncdef, NULL, NULL); jsval v = JSVAL_VOID; if (fnc && obj && prv && JS_SetReservedSlot(ctx, obj, 0, OBJECT_TO_JSVAL(prv)) && JS_SetPrivate(ctx, prv, priv)) v = OBJECT_TO_JSVAL(obj); else { natus_private_free(priv); if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &v)) return NULL; *flags |= natusEngValFlagException; } return mkjsval(ctx, v); } static natusEngVal sm_new_object(const natusEngCtx ctx, natusClass *cls, natusPrivate *priv, natusEngValFlags *flags) { JSClass *jscls = NULL; if (cls) { jscls = malloc(sizeof(JSClass)); if (!jscls) goto error; memset(jscls, 0, sizeof(JSClass)); jscls->name = cls->call ? "NativeFunction" : "NativeObject"; jscls->flags = cls->enumerate ? JSCLASS_HAS_PRIVATE | JSCLASS_NEW_ENUMERATE : JSCLASS_HAS_PRIVATE; jscls->addProperty = JS_PropertyStub; jscls->delProperty = cls->del ? obj_del : JS_PropertyStub; jscls->getProperty = cls->get ? obj_get : JS_PropertyStub; jscls->setProperty = cls->set ? obj_set : JS_StrictPropertyStub; jscls->enumerate = cls->enumerate ? (JSEnumerateOp) obj_enum : JS_EnumerateStub; jscls->resolve = JS_ResolveStub; jscls->convert = JS_ConvertStub; jscls->finalize = obj_finalize; jscls->call = cls->call ? obj_call : NULL; jscls->construct = cls->call ? obj_new : NULL; if (!natus_private_push(priv, jscls, free)) goto error; } // Build the object jsval v = JSVAL_VOID; JSObject* obj = JS_NewObject(ctx, jscls ? jscls : &objdef, NULL, NULL); if (obj && JS_SetPrivate(ctx, obj, priv)) v = OBJECT_TO_JSVAL(obj); else { if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &v)) goto error; *flags |= natusEngValFlagException; natus_private_free(priv); } return mkjsval(ctx, v); error: natus_private_free(priv); return NULL; } static natusEngVal sm_new_null(const natusEngCtx ctx, natusEngValFlags *flags) { return mkjsval(ctx, JSVAL_NULL); } static natusEngVal sm_new_undefined(const natusEngCtx ctx, natusEngValFlags *flags) { return mkjsval(ctx, JSVAL_VOID); } static bool sm_to_bool(const natusEngCtx ctx, const natusEngVal val) { return JSVAL_TO_BOOLEAN(*val); } static double sm_to_double(const natusEngCtx ctx, const natusEngVal val) { double d; JS_ValueToNumber(ctx, *val, &d); return d; } static char * sm_to_string_utf8(const natusEngCtx ctx, const natusEngVal val, size_t *len) { JSString *str = JS_ValueToString(ctx, *val); *len = JS_GetStringLength(str); size_t bufflen = JS_GetStringEncodingLength(ctx, str); char *buff = calloc(bufflen + 1, sizeof(char)); if (!buff) return NULL; memset(buff, 0, sizeof(char) * (bufflen + 1)); *len = JS_EncodeStringToBuffer(str, buff, bufflen); if (*len >= 0 && *len <= bufflen) return buff; free(buff); return NULL; } static natusChar * sm_to_string_utf16(const natusEngCtx ctx, const natusEngVal val, size_t *len) { JSString *str = JS_ValueToString(ctx, *val); *len = JS_GetStringLength(str); const jschar *jschars = JS_GetStringCharsAndLength(ctx, str, len); natusChar *ntchars = calloc(*len + 1, sizeof(natusChar)); if (jschars && ntchars) { memset(ntchars, 0, sizeof(natusChar) * (*len + 1)); memcpy(ntchars, jschars, sizeof(natusChar) * *len); return ntchars; } free(ntchars); return NULL; } natusEngVal sm_del(const natusEngCtx ctx, natusEngVal val, const natusEngVal id, natusEngValFlags *flags) { jsid vid; jsval rval = JSVAL_VOID; JS_ValueToId(ctx, *id, &vid); if (JS_DeletePropertyById(ctx, JSVAL_TO_OBJECT(*val), vid)) rval = BOOLEAN_TO_JSVAL(true); else { *flags |= natusEngValFlagException; if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &rval)) return NULL; } return mkjsval(ctx, rval); } natusEngVal sm_get(const natusEngCtx ctx, natusEngVal val, const natusEngVal id, natusEngValFlags *flags) { jsid vid; JS_ValueToId(ctx, *id, &vid); jsval rval = JSVAL_VOID; if (!JS_GetPropertyById(ctx, JSVAL_TO_OBJECT(*val), vid, &rval)) { *flags |= natusEngValFlagException; if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &rval)) return NULL; } return mkjsval(ctx, rval); } natusEngVal sm_set(const natusEngCtx ctx, natusEngVal val, const natusEngVal id, const natusEngVal value, natusPropAttr attrs, natusEngValFlags *flags) { jsint attr = (attrs & natusPropAttrDontEnum) ? 0 : JSPROP_ENUMERATE; attr |= (attrs & natusPropAttrReadOnly) ? JSPROP_READONLY : 0; attr |= (attrs & natusPropAttrDontDelete) ? JSPROP_PERMANENT : 0; jsid vid; JS_ValueToId(ctx, *id, &vid); jsval rval = *value; if (JS_SetPropertyById(ctx, JSVAL_TO_OBJECT(*val), vid, &rval)) { BOOLEAN_TO_JSVAL(true); if (JSID_IS_STRING(vid)) { size_t len; JSBool found; JSString *str = JSID_TO_STRING(vid); const jschar *chars = JS_GetStringCharsAndLength(ctx, str, &len); JS_SetUCPropertyAttributes(ctx, JSVAL_TO_OBJECT(*val), chars, len, attr, &found); } } else { *flags |= natusEngValFlagException; if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &rval)) return NULL; } return mkjsval(ctx, rval); } natusEngVal sm_enumerate(const natusEngCtx ctx, natusEngVal val, natusEngValFlags *flags) { jsint i; JSIdArray* na = JS_Enumerate(ctx, JSVAL_TO_OBJECT(*val)); if (!na) return NULL; jsval *vals = calloc(na->length, sizeof(jsval)); if (!vals) { JS_DestroyIdArray(ctx, na); return NULL; } for (i = 0; i < na->length; i++) assert(JS_IdToValue (ctx, na->vector[i], &vals[i])); JSObject *array = JS_NewArrayObject(ctx, na->length, vals); JS_DestroyIdArray(ctx, na); free(vals); if (!array) return NULL; return mkjsval(ctx, OBJECT_TO_JSVAL(array)); } static natusEngVal sm_call(const natusEngCtx ctx, natusEngVal func, natusEngVal ths, natusEngVal args, natusEngValFlags *flags) { // Convert to jsval array jsuint i, len; if (!JS_GetArrayLength(ctx, JSVAL_TO_OBJECT(*args), &len)) return NULL; jsval *argv = calloc(len, sizeof(jsval)); if (!argv) return NULL; for (i = 0; i < len; i++) { jsid id; if (!JS_NewNumberValue(ctx, i, &argv[i]) || !JS_ValueToId(ctx, argv[i], &id) || !JS_GetPropertyById(ctx, JSVAL_TO_OBJECT(*args), id, &argv[i])) { free(argv); return NULL; } } // Call the function jsval rval = JSVAL_VOID; if (JSVAL_IS_VOID(*ths)) { JSObject *obj = JS_New(ctx, JSVAL_TO_OBJECT(*func), len, argv); if (obj) rval = OBJECT_TO_JSVAL(obj); else { *flags |= natusEngValFlagException; if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &rval)) { free(argv); return NULL; } } } else { if (!JS_CallFunctionValue(ctx, JSVAL_TO_OBJECT(*ths), *func, len, argv, &rval)) { *flags |= natusEngValFlagException; if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &rval)) { free(argv); return NULL; } } } free(argv); return mkjsval(ctx, rval); } static natusEngVal sm_evaluate(const natusEngCtx ctx, natusEngVal ths, const natusEngVal jscript, const natusEngVal filename, unsigned int lineno, natusEngValFlags *flags) { size_t jslen = 0, fnlen = 0; const jschar *jschars = JS_GetStringCharsAndLength(ctx, JS_ValueToString(ctx, *jscript), &jslen); char *fnchars = sm_to_string_utf8(ctx, filename, &fnlen); jsval rval; if (!JS_EvaluateUCScript(ctx, JSVAL_TO_OBJECT(*ths), jschars, jslen, fnchars, lineno, &rval)) { *flags |= natusEngValFlagException; if (!JS_IsExceptionPending(ctx) || !JS_GetPendingException(ctx, &rval)) { free(fnchars); return NULL; } } free(fnchars); return mkjsval(ctx, rval); } static natusPrivate * sm_get_private(const natusEngCtx ctx, const natusEngVal val) { return get_private(ctx, JSVAL_TO_OBJECT(*val)); } static natusEngVal sm_get_global(const natusEngCtx ctx, const natusEngVal val, natusEngValFlags *flags) { JSObject *obj = NULL; JS_ValueToObject(ctx, *val, &obj); if (obj) obj = JS_GetGlobalForObject(ctx, obj); if (!obj) obj = JS_GetGlobalForScopeChain(ctx); if (!obj) obj = JS_GetGlobalObject(ctx); return mkjsval(ctx, OBJECT_TO_JSVAL(obj)); } static natusValueType sm_get_type(const natusEngCtx ctx, const natusEngVal val) { if (JSVAL_IS_BOOLEAN(*val)) return natusValueTypeBoolean; else if (JSVAL_IS_NULL(*val)) return natusValueTypeNull; else if (JSVAL_IS_NUMBER(*val)) return natusValueTypeNumber; else if (JSVAL_IS_STRING(*val)) return natusValueTypeString; else if (JSVAL_IS_VOID(*val)) return natusValueTypeUndefined; else if (JSVAL_IS_OBJECT(*val)) { if (JS_IsArrayObject(ctx, JSVAL_TO_OBJECT(*val))) return natusValueTypeArray; else if (JS_ObjectIsFunction(ctx, JSVAL_TO_OBJECT(*val))) return natusValueTypeFunction; else return natusValueTypeObject; } return natusValueTypeUnknown; } static bool sm_borrow_context(natusEngCtx ctx, natusEngVal val, void **context, void **value) { *context = ctx; *value = val; return true; } static bool sm_equal(const natusEngCtx ctx, const natusEngVal val1, const natusEngVal val2, bool strict) { JSBool eql = false; if (strict) { if (!JS_StrictlyEqual(ctx, *val1, *val2, &eql)) eql = false; } else { #if 1 if (!JS_StrictlyEqual(ctx, *val1, *val2, &eql)) #else if (!JS_LooselyEqual(ctx, *val1, *val2, &eql)) #endif eql = false; } return eql; } __attribute__((constructor)) static void _init() { JS_SetCStringsAreUTF8(); } __attribute__((destructor)) static void _fini() { JS_ShutDown(); } NATUS_ENGINE("SpiderMonkey", "JS_GetProperty", sm);
27.302956
204
0.697023
[ "object", "vector" ]
183ad6ea07ae61f5f8eb88a0197c94017a3cde64
2,258
h
C
plugins/datatools/src/table/TableProcessorBase.h
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
49
2017-08-23T13:24:24.000Z
2022-03-16T09:10:58.000Z
plugins/datatools/src/table/TableProcessorBase.h
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
200
2018-07-20T15:18:26.000Z
2022-03-31T11:01:44.000Z
plugins/datatools/src/table/TableProcessorBase.h
xge/megamol
1e298dd3d8b153d7468ed446f6b2ed3ac49f0d5b
[ "BSD-3-Clause" ]
31
2017-07-31T16:19:29.000Z
2022-02-14T23:41:03.000Z
/* * TableProcessorBase.h * * Copyright (C) 2019 Visualisierungsinstitut der Universität Stuttgart * Alle Rechte vorbehalten. */ #pragma once #include "mmcore/CalleeSlot.h" #include "mmcore/CallerSlot.h" #include "mmcore/Module.h" #include "mmcore/param/ParamSlot.h" #include "datatools/table/TableDataCall.h" namespace megamol { namespace datatools { namespace table { /** * A base class for modules processing table data. */ class TableProcessorBase : public core::Module { public: /** * Finalises an instance. */ virtual ~TableProcessorBase(void) = default; protected: typedef megamol::datatools::table::TableDataCall::ColumnInfo ColumnInfo; /** * Initialises a new instance. */ TableProcessorBase(void); /** * Computes the combined hash from the hash of the local state and the * hash of the input * * @return The hash of the data currently stored in the module. */ inline std::size_t getHash(void) { auto retval = this->inputHash; retval ^= this->localHash + 0x9e3779b9 + (retval << 6) + (retval >> 2); return retval; } /** * Prepares the data requested by 'call'. * * @param src The call providing the data. * @param frameID The ID of the frame requested by the caller. * * @return true in case of suceess, false otherwise. */ virtual bool prepareData(TableDataCall& src, const unsigned int frameID) = 0; /** Holds the columns of the (filtered) table. */ std::vector<ColumnInfo> columns; /** Holds the ID of the current frame. */ unsigned int frameID; /** Holds the hash of the data as reported by the input module. */ std::size_t inputHash; /** Holds a hash representing the current state of the processor. */ std::size_t localHash; /** The slot providing the input data. */ core::CallerSlot slotInput; /** The slot allowing for retrieval of the output data. */ core::CalleeSlot slotOutput; /** The actual values. */ std::vector<float> values; private: bool getData(core::Call& call); bool getHash(core::Call& call); }; } /* end namespace table */ } /* end namespace datatools */ } /* end namespace megamol */
24.021277
81
0.652347
[ "vector" ]
183dd46b95aed78b97fe4389b0563615e22226dc
1,224
h
C
bethe-xxz/xxz-base.h
robhagemans/bethe-solver
77b217c6cc23842b284ecd2d7b01fe28310cc32e
[ "MIT" ]
null
null
null
bethe-xxz/xxz-base.h
robhagemans/bethe-solver
77b217c6cc23842b284ecd2d7b01fe28310cc32e
[ "MIT" ]
null
null
null
bethe-xxz/xxz-base.h
robhagemans/bethe-solver
77b217c6cc23842b284ecd2d7b01fe28310cc32e
[ "MIT" ]
null
null
null
#ifndef XXZ_BASE_H #define XXZ_BASE_H #include "base.h" class XXZ_Base: public Base { public: XXZ_Base (const Chain* const on_chain, const BaseData& base_data); // these constructors create a base with a given structure and number of holes XXZ_Base (const Chain* const on_chain, const vector<int>& structure, const int number_holes=0); // do same; calculate the first element of the base from the given number down // NOTE: caller must supply a dummy first base element in structure! XXZ_Base (const Chain* const on_chain, const int new_number_down, const vector<int>& structure, const int new_number_holes); // create a state with only particles in the 1+interval and no holes (ground state base) XXZ_Base (const Chain* const on_chain, const int the_number_down); // copy constructor XXZ_Base (const Base& original): Base(original) { if (original.p_chain->delta() >= 1.0 || original.p_chain->delta() <= 0.0 ) throw Exception("XXZBase copy", exc_CopyMismatch); }; // destructor virtual ~XXZ_Base (void) {}; // clone virtual Base* clone(void) const { return new XXZ_Base(*this); }; // ceil(2*I_max) limit == maximum +1 virtual vector<int> limQuantumNumbers (void) const; }; #endif
42.206897
133
0.727124
[ "vector" ]
1840bb71b9d2bc9bfc25b8c0a915c35c0229d353
5,025
h
C
source/Lib/TLibCommon/TComHash.h
starxiang/HM-16.19-SCM-8.8
15e42dea8d478380b46e6a5a2306b47a419d52a0
[ "BSD-3-Clause" ]
1
2021-05-10T04:11:48.000Z
2021-05-10T04:11:48.000Z
source/Lib/TLibCommon/TComHash.h
starxiang/HM-16.19-SCM-8.8
15e42dea8d478380b46e6a5a2306b47a419d52a0
[ "BSD-3-Clause" ]
null
null
null
source/Lib/TLibCommon/TComHash.h
starxiang/HM-16.19-SCM-8.8
15e42dea8d478380b46e6a5a2306b47a419d52a0
[ "BSD-3-Clause" ]
null
null
null
/* The copyright in this software is being made available under the BSD * License, included below. This software may be subject to other third party * and contributor rights, including patent rights, and no such rights are * granted under this license. * * Copyright (c) 2010-2017, ITU/ISO/IEC * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * Neither the name of the ITU/ISO/IEC nor the names of its contributors may * be used to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ /** \file TComHash.h \brief common Hash class (header) */ #ifndef __TCOMHASH__ #define __TCOMHASH__ // Include files #include "CommonDef.h" #include "TComPicSym.h" #include "TComPicYuv.h" #include <vector> //! \ingroup TLibEncoder //! \{ struct BlockHash { Short x; Short y; UInt hashValue2; }; typedef vector<BlockHash>::iterator MapIterator; // ==================================================================================================================== // Class definitions // ==================================================================================================================== class TCRCCalculatorLight { public: TCRCCalculatorLight( UInt bits, UInt truncPoly ); ~TCRCCalculatorLight(); public: Void processData( UChar* pData, UInt dataLength ); Void reset() { m_remainder = 0; } UInt getCRC() { return m_remainder & m_finalResultMask; } private: Void xInitTable(); private: UInt m_remainder; UInt m_truncPoly; UInt m_bits; UInt m_table[256]; UInt m_finalResultMask; }; class TComHash { public: TComHash(); ~TComHash(); Void create(); Void clearAll(); Void addToTable( UInt hashValue, const BlockHash& blockHash ); Int count( UInt hashValue ); Int count( UInt hashValue ) const; MapIterator getFirstIterator( UInt hashValue ); const MapIterator getFirstIterator( UInt hashValue ) const; Bool hasExactMatch( UInt hashValue1, UInt hashValue2 ); Void generateBlock2x2HashValue( TComPicYuv* pPicYuv, Int picWidth, Int picHeight, const BitDepths bitDepths, UInt* picBlockHash[2], Bool* picBlockSameInfo[3]); Void generateBlockHashValue( Int picWidth, Int picHeight, Int width, Int height, UInt* srcPicBlockHash[2], UInt* dstPicBlockHash[2], Bool* srcPicBlockSameInfo[3], Bool* dstPicBlockSameInfo[3]); Void addToHashMapByRowWithPrecalData( UInt* srcHash[2], Bool* srcIsSame, Int picWidth, Int picHeight, Int width, Int height); public: static UInt getCRCValue1( UChar* p, Int length ); static UInt getCRCValue2( UChar* p, Int length ); static Void getPixelsIn1DCharArrayByBlock2x2(const TComPicYuv* const pPicYuv, UChar* pPixelsIn1D, Int xStart, Int yStart, const BitDepths& bitDepths, Bool includeAllComponent = true); static Bool isBlock2x2RowSameValue(UChar* p, Bool includeAllComponent = true); static Bool isBlock2x2ColSameValue(UChar* p, Bool includeAllComponent = true); static Bool isHorizontalPerfect( TComPicYuv* pPicYuv, Int width, Int height, Int xStart, Int yStart, Bool includeAllComponent = true ); static Bool isVerticalPerfect ( TComPicYuv* pPicYuv, Int width, Int height, Int xStart, Int yStart, Bool includeAllComponent = true ); static Bool getBlockHashValue( const TComPicYuv* const pPicYuv, Int width, Int height, Int xStart, Int yStart, const BitDepths bitDepths, UInt& hashValue1, UInt& hashValue2 ); static Void initBlockSizeToIndex(); private: vector<BlockHash>** m_pLookupTable; private: static const Int m_CRCBits = 16; static const Int m_blockSizeBits = 2; static Int m_blockSizeToIndex[65][65]; static TCRCCalculatorLight m_crcCalculator1; static TCRCCalculatorLight m_crcCalculator2; }; //! \} #endif // __TCOMHASH__
38.358779
195
0.721194
[ "vector" ]
1850614415830f1ce08207057c0d1193fd978d0a
708
h
C
src/Solver.h
77LL/prime_factor
ce55cb43a8c8c99ad3e0abddabf848224c8476b2
[ "MIT" ]
null
null
null
src/Solver.h
77LL/prime_factor
ce55cb43a8c8c99ad3e0abddabf848224c8476b2
[ "MIT" ]
null
null
null
src/Solver.h
77LL/prime_factor
ce55cb43a8c8c99ad3e0abddabf848224c8476b2
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <utility> #include <chrono> using namespace std; template<class T> class Solver { public: virtual void solve(T num) = 0; void calc(T num){ chrono::system_clock::time_point start, end; start = chrono::system_clock::now(); solve(num); end = chrono::system_clock::now(); time = static_cast<double>(chrono::duration_cast<chrono::microseconds>(end - start).count()) * 0.000001; } void show(ostream& os){ for( auto &val : result ){ os << "prim: " << val.first << ", order: " << val.second << endl; } } void showTime(ostream& os){ os << "time: " << time << "[s]" << endl; } protected: vector< pair< T, T > > result; double time; };
20.823529
106
0.629944
[ "vector" ]
1854357b67549390794cab3fdc1f1b5ee7817a80
4,489
h
C
src/mx/tasking/worker.h
jnhu76/mxtasking
83794a600610564b0bb74856a0ec159421d1f838
[ "MIT" ]
6
2022-01-04T12:28:13.000Z
2022-03-21T06:52:35.000Z
src/mx/tasking/worker.h
jnhu76/mxtasking
83794a600610564b0bb74856a0ec159421d1f838
[ "MIT" ]
null
null
null
src/mx/tasking/worker.h
jnhu76/mxtasking
83794a600610564b0bb74856a0ec159421d1f838
[ "MIT" ]
2
2022-01-04T12:29:03.000Z
2022-01-14T23:53:49.000Z
#pragma once #include "channel.h" #include "config.h" #include "profiling/statistic.h" #include "task.h" #include "task_stack.h" #include <atomic> #include <cstddef> #include <memory> #include <mx/memory/reclamation/epoch_manager.h> #include <mx/util/maybe_atomic.h> #include <variant> #include <vector> namespace mx::tasking { /** * The worker executes tasks from his own channel, until the "running" flag is false. */ class alignas(64) Worker { public: Worker(std::uint16_t id, std::uint16_t target_core_id, std::uint16_t target_numa_node_id, const util::maybe_atomic<bool> &is_running, std::uint16_t prefetch_distance, memory::reclamation::LocalEpoch &local_epoch, const std::atomic<memory::reclamation::epoch_t> &global_epoch, profiling::Statistic &statistic) noexcept; ~Worker() noexcept = default; /** * Starts the worker (typically in its own thread). */ void execute(); /** * @return Id of the logical core this worker runs on. */ [[nodiscard]] std::uint16_t core_id() const noexcept { return _target_core_id; } [[nodiscard]] Channel &channel() noexcept { return _channel; } [[nodiscard]] const Channel &channel() const noexcept { return _channel; } private: // Id of the logical core. const std::uint16_t _target_core_id; // Distance of prefetching tasks. const std::uint16_t _prefetch_distance; std::int32_t _channel_size{0U}; // Stack for persisting tasks in optimistic execution. Optimistically // executed tasks may fail and be restored after execution. alignas(64) TaskStack _task_stack; // Channel where tasks are stored for execution. alignas(64) Channel _channel; // Local epoch of this worker. memory::reclamation::LocalEpoch &_local_epoch; // Global epoch. const std::atomic<memory::reclamation::epoch_t> &_global_epoch; // Statistics container. profiling::Statistic &_statistic; // Flag for "running" state of MxTasking. const util::maybe_atomic<bool> &_is_running; /** * Analyzes the given task and chooses the execution method regarding synchronization. * @param task Task to be executed. * @return Synchronization method. */ static synchronization::primitive synchronization_primitive(TaskInterface *task) noexcept { return task->has_resource_annotated() ? task->annotated_resource().synchronization_primitive() : synchronization::primitive::None; } /** * Executes a task with a latch. * @param core_id Id of the core. * @param channel_id Id of the channel. * @param task Task to be executed. * @return Task to be scheduled after execution. */ static TaskResult execute_exclusive_latched(std::uint16_t core_id, std::uint16_t channel_id, TaskInterface *task); /** * Executes a task with a reader/writer latch. * @param core_id Id of the core. * @param channel_id Id of the channel. * @param task Task to be executed. * @return Task to be scheduled after execution. */ static TaskResult execute_reader_writer_latched(std::uint16_t core_id, std::uint16_t channel_id, TaskInterface *task); /** * Executes the task optimistically. * @param core_id Id of the core. * @param channel_id Id of the channel. * @param task Task to be executed. * @return Task to be scheduled after execution. */ TaskResult execute_optimistic(std::uint16_t core_id, std::uint16_t channel_id, TaskInterface *task); /** * Executes the task using olfit protocol. * @param core_id Id of the core. * @param channel_id Id of the channel. * @param task Task to be executed. * @return Task to be scheduled after execution. */ TaskResult execute_olfit(std::uint16_t core_id, std::uint16_t channel_id, TaskInterface *task); /** * Executes the read-only task optimistically. * @param core_id Id of the core. * @param channel_id Id of the channel. * @param resource Resource the task reads. * @param task Task to be executed. * @return Task to be scheduled after execution. */ TaskResult execute_optimistic_read(std::uint16_t core_id, std::uint16_t channel_id, resource::ResourceInterface *resource, TaskInterface *task); }; } // namespace mx::tasking
34.530769
119
0.671196
[ "vector" ]
1856e78101a7bdee74ca9bc658ca36c22533ba53
16,287
h
C
applications/mne_analyze/plugins/rawdataviewer/fiffrawview.h
Youssef-Zarca/mne-cpp
a4b4c7219873b1af4e0275e967447e68f97e5c14
[ "BSD-3-Clause" ]
null
null
null
applications/mne_analyze/plugins/rawdataviewer/fiffrawview.h
Youssef-Zarca/mne-cpp
a4b4c7219873b1af4e0275e967447e68f97e5c14
[ "BSD-3-Clause" ]
null
null
null
applications/mne_analyze/plugins/rawdataviewer/fiffrawview.h
Youssef-Zarca/mne-cpp
a4b4c7219873b1af4e0275e967447e68f97e5c14
[ "BSD-3-Clause" ]
null
null
null
//============================================================================================================= /** * @file fiffrawview.h * @author Lorenz Esch <lesch@mgh.harvard.edu>; * Lars Debor <Lars.Debor@tu-ilmenau.de>; * Simon Heinke <Simon.Heinke@tu-ilmenau.de>; * Gabriel Motta <gbmotta@mgh.harvard.edu> * @since 0.1.0 * @date July, 2018 * * @section LICENSE * * Copyright (C) 2018, Lorenz Esch, Lars Debor, Simon Heinke, Gabriel Motta. 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 MNE-CPP authors 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. * * * @brief Declaration of the FiffRawView Class. * */ #ifndef FIFFRAWVIEW_H #define FIFFRAWVIEW_H //============================================================================================================= // INCLUDES //============================================================================================================= #include "rawdataviewer_global.h" #include <disp/viewers/abstractview.h> //============================================================================================================= // QT INCLUDES //============================================================================================================= #include <QSharedPointer> #include <QWidget> #include <QPointer> #include <QMap> #include <QMenu> #include <QScroller> //============================================================================================================= // Eigen INCLUDES //============================================================================================================= //============================================================================================================= // FORWARD DECLARATIONS //============================================================================================================= namespace ANSHAREDLIB { class FiffRawViewModel; } namespace RTPROCESSINGLIB { class FilterKernel; } class QTableView; class QLabel; //============================================================================================================= // DEFINE NAMESPACE RAWDATAVIEWERPLUGIN //============================================================================================================= namespace RAWDATAVIEWERPLUGIN { //============================================================================================================= // RAWDATAVIEWERPLUGIN FORWARD DECLARATIONS //============================================================================================================= class FiffRawViewDelegate; //============================================================================================================= /** * TableView for Fiff data. */ class RAWDATAVIEWERSHARED_EXPORT FiffRawView : public DISPLIB::AbstractView { Q_OBJECT public: typedef QSharedPointer<FiffRawView> SPtr; /**< Shared pointer type for FiffRawView. */ typedef QSharedPointer<const FiffRawView> ConstSPtr; /**< Const shared pointer type for FiffRawView. */ //========================================================================================================= /** * Constructs a FiffRawView which is a child of parent. * * @param [in] parent The parent of widget. */ FiffRawView(QWidget *parent = nullptr); //========================================================================================================= /** * Destructor. */ virtual ~FiffRawView(); //========================================================================================================= /** * Resets the view to its default settings. */ void reset(); //========================================================================================================= /** * Returns the currently set delegate */ QSharedPointer<FiffRawViewDelegate> getDelegate(); //========================================================================================================= /** * Setups the delegate of this view. * * @param [in] pDelegate The new delegate. */ void setDelegate(const QSharedPointer<FiffRawViewDelegate>& pDelegate); //========================================================================================================= /** * Returns the currently set model */ QSharedPointer<ANSHAREDLIB::FiffRawViewModel> getModel(); //========================================================================================================= /** * Setups the model of this view. * * @param [in] pModel The new model. */ void setModel(const QSharedPointer<ANSHAREDLIB::FiffRawViewModel>& pModel); //========================================================================================================= /** * Broadcast channel scaling * * @param [in] scaleMap QMap with scaling values which is to be broadcasted to the model. */ void setScalingMap(const QMap<qint32, float>& scaleMap); //========================================================================================================= /** * Set the signal color. * * @param [in] signalColor The new signal color. */ void setSignalColor(const QColor& signalColor); //========================================================================================================= /** * Broadcast the background color changes made in the QuickControl widget * * @param [in] backgroundColor The new background color. */ void setBackgroundColor(const QColor& backgroundColor); //========================================================================================================= /** * Sets new zoom factor * * @param [in] dZoomFac time window size; */ void setZoom(double dZoomFac); //========================================================================================================= /** * Sets new time window size * * @param [in] iT time window size; */ void setWindowSize(int iT); //========================================================================================================= /** * distanceTimeSpacerChanged changes the distance of the time spacers * * @param iValue the new distance for the time spacers */ void setDistanceTimeSpacer(int iValue); //========================================================================================================= /** * Call this slot whenever you want to make a screenshot current view. * * @param[in] imageType The current iamge type: png, svg. */ void onMakeScreenshot(const QString& imageType); //========================================================================================================= /** * Brings up a menu for interacting with data annotations * @param[in] pos Position on screen where the menu will show up */ void customContextMenuRequested(const QPoint &pos); //========================================================================================================= /** * Create a new annotation * * @param[in] con Whether a new annotaton should be created; */ void addTimeMark(bool con); //========================================================================================================= /** * Controls toggling of annotation data * * @param[in] iToggle Sets toggle: 0 - don't show, 1+ - show */ void toggleDisplayEvent(const int& iToggle); //========================================================================================================= /** * Triggers a redraw of the data viewer */ void updateView(); //========================================================================================================= /** * Moves data viewer to a position where the selected annotation is in the middle of the viewer. */ void updateScrollPositionToAnnotation(); //========================================================================================================= /** * Filter parameters changed * * @param[in] filterData the currently active filter */ void setFilter(const RTPROCESSINGLIB::FilterKernel &filterData); //========================================================================================================= /** * Filter avtivated * * @param[in] state filter on/off flag */ void setFilterActive(bool state); //========================================================================================================= /** * Sets the type of channel which are to be filtered * * @param[in] channelType the channel type which is to be filtered (EEG, MEG, All) */ void setFilterChannelType(const QString& channelType); //========================================================================================================= /** * Saves all important settings of this view via QSettings. */ void saveSettings(); //========================================================================================================= /** * Loads and inits all important settings of this view via QSettings. */ void loadSettings(); //========================================================================================================= /** * Update the views GUI based on the set GuiMode (Clinical=0, Research=1). * * @param mode The new mode (Clinical=0, Research=1). */ void updateGuiMode(GuiMode mode); //========================================================================================================= /** * Update the views GUI based on the set ProcessingMode (RealTime=0, Offline=1). * * @param mode The new mode (RealTime=0, Offline=1). */ void updateProcessingMode(ProcessingMode mode); //========================================================================================================= /** * Shows channels based on input selectedChannelsIndexes * * @param [in] selectedChannelsIndexes list of channels to be shown */ void showSelectedChannelsOnly(const QList<int> selectedChannelsIndexes); //========================================================================================================= /** * Shows all channels in the view */ void showAllChannels(); //========================================================================================================= /** * Clears the view */ void clearView(); signals: //========================================================================================================= /** * Emits sample number to be added aan annotation * * @param [in] iSample sample number to be added */ void sendSamplePos(int iSample); private: //========================================================================================================= /** * resizeEvent reimplemented virtual function to handle resize events of the data dock window */ void resizeEvent(QResizeEvent* event); //========================================================================================================= /** * Catches events to performa specific action handling * * @param [in, out] object pointer to object the event pertains to * @param [in] event type of object with associated data * * @return true if handled by custom event handling, false if not */ bool eventFilter(QObject *object, QEvent *event); //========================================================================================================= /** * Creates the lables for sample/time values displayed beneath the data view */ void createLabels(); //========================================================================================================= /** * Triggers the update of the update label based on the data viewer horizontal positon (not on iValue) * * @param [in] iValue Horizontal scroll bar position (unused) */ void updateLabels(int iValue); //========================================================================================================= /** * Disconnects the model from the view's scrollbar and resizing */ void disconnectModel(); //========================================================================================================= /** * This tells the model where the view currently is vertically. * * @param newScrollPosition Absolute sample number. */ void updateVerticalScrollPosition(qint32 newScrollPosition); QPointer<QTableView> m_pTableView; /**< Pointer to table view ui element */ QSharedPointer<ANSHAREDLIB::FiffRawViewModel> m_pModel; /**< Pointer to associated Model */ QSharedPointer<FiffRawViewDelegate> m_pDelegate; /**< Pointer to associated Delegate */ QMap<qint32,float> m_qMapChScaling; /**< Channel scaling values. */ float m_fDefaultSectionSize; /**< Default row height */ float m_fZoomFactor; /**< Zoom factor */ float m_fLastClickedSample; /**< Stores last clicked sample on screen */ qint32 m_iT; /**< Display window size in seconds */ QScroller* m_pKineticScroller; /**< Used for kinetic scrolling through data view */ QLabel* m_pLeftLabel; /**< Left 'Sample | Seconds' display label */ QLabel* m_pRightLabel; /**< Right 'Sample | Seconds' display label */ signals: void tableViewDataWidthChanged(int iWidth); }; //============================================================================================================= // INLINE DEFINITIONS //============================================================================================================= } // NAMESPACE RAWDATAVIEWERPLUGIN #endif // FIFFRAWVIEW_H
40.922111
140
0.40167
[ "object", "model" ]
1862ec19555482551734706f37241f17a9d2c5b7
2,746
h
C
Game/Source/App.h
Vinskky/PlatformerGame
e1d6c2db6bd812b95b8f2e44386be3e625cb82fa
[ "MIT" ]
null
null
null
Game/Source/App.h
Vinskky/PlatformerGame
e1d6c2db6bd812b95b8f2e44386be3e625cb82fa
[ "MIT" ]
null
null
null
Game/Source/App.h
Vinskky/PlatformerGame
e1d6c2db6bd812b95b8f2e44386be3e625cb82fa
[ "MIT" ]
null
null
null
#ifndef __APP_H__ #define __APP_H__ #include "Module.h" #include "List.h" #include "PugiXml/src/pugixml.hpp" #include "Timer.h" #include "PerfTimer.h" // Modules class Window; class Input; class Render; class Textures; class Audio; class Scene; class Map; class PathFinding; class EntityManager; class Collisions; class Transition; class GuiManager; class Fonts; class App { public: // Constructor App(int argc, char* args[]); // Destructor virtual ~App(); // Called before render is available bool Awake(); // Called before the first frame bool Start(); // Called each loop iteration bool Update(); // Called before quitting bool CleanUp(); // Add a new module to handle void AddModule(Module* module); // Exposing some properties for reading int GetArgc() const; const char* GetArgv(int index) const; const char* GetTitle() const; const char* GetOrganization() const; // L02: TODO 1: Create methods to request Load / Save void LoadRequest(const char* filename); void SaveRequest(const char* filename); bool IsLoading() const; int GetFrameCount(); private: // Load config file bool LoadConfig(); // Call modules before each loop iteration void PrepareUpdate(); // Call modules before each loop iteration void FinishUpdate(); // Call modules before each loop iteration bool PreUpdate(); // Call modules on each loop iteration bool DoUpdate(); // Call modules after each loop iteration bool PostUpdate(); // L02: TODO 5: Declare methods to load/save game bool LoadGame(); bool SaveGame() const; public: // Modules Window* win; Input* input; Render* render; Textures* tex; Audio* audio; Scene* scene; Map* map; PathFinding* pathfinding; Collisions* collision; Transition* fade; EntityManager* enManager; GuiManager* guiManager; Fonts* font; private: int argc; char** args; SString title; SString organization; List<Module*> modules; // L01: DONE 2: Create new variables from pugui namespace: // xml_document to store the config file and // xml_node(s) to read specific branches of the xml pugi::xml_document configFile; pugi::xml_node config; pugi::xml_node configApp; uint frames; // L02: TODO 1: Create required variables to request load / save and // the filename for save / load bool loadRequest = false; mutable bool saveRequest = false; SString loadFileName; mutable SString saveFileName; // FRAME CAP SHENANIGANS PerfTimer pTimer; uint64 frameCount = 0; const uint32 fps = 60; const uint32 frameDelay = 1000 / fps; Timer startupTime; Timer frameTime; Timer lastSecFrameTime; uint32 lastSecFrameCount = 0; uint32 prevLastSecFrameCount = 0; float dt = 0.0f; bool changeFps = false; }; extern App* app; #endif // __APP_H__
18.680272
70
0.726147
[ "render" ]
186f154275d1a8fe1facf7f2fd5a5086687a79dd
2,724
h
C
Marlin-RC_Deltaprintr/Marlin/pins_MEGATRONICS_2.h
lordjoe/DeltaPrintRFirmware
c94fbcb1e3b82c495e5fddd7f43409e25fcddf71
[ "Apache-2.0" ]
2
2018-08-17T07:16:42.000Z
2018-08-17T07:16:54.000Z
firmware/Marlin/not_used/pins_MEGATRONICS_2.h
polygontwist/alu_slider
0e648a732dd32789f9a72f116da08ed585e71feb
[ "MIT" ]
null
null
null
firmware/Marlin/not_used/pins_MEGATRONICS_2.h
polygontwist/alu_slider
0e648a732dd32789f9a72f116da08ed585e71feb
[ "MIT" ]
null
null
null
/** * Marlin 3D Printer Firmware * Copyright (C) 2016 MarlinFirmware [https://github.com/MarlinFirmware/Marlin] * * Based on Sprinter and grbl. * Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /** * MegaTronics v2.0 pin assignments */ #ifndef __AVR_ATmega2560__ #error Oops! Make sure you have 'Arduino Mega' selected from the 'Tools -> Boards' menu. #endif #define LARGE_FLASH true #define X_STEP_PIN 26 #define X_DIR_PIN 27 #define X_ENABLE_PIN 25 #define X_MIN_PIN 37 #define X_MAX_PIN 40 #define Y_STEP_PIN 4 // A6 #define Y_DIR_PIN 54 // A0 #define Y_ENABLE_PIN 5 #define Y_MIN_PIN 41 #define Y_MAX_PIN 38 #define Z_STEP_PIN 56 // A2 #define Z_DIR_PIN 60 // A6 #define Z_ENABLE_PIN 55 // A1 #define Z_MIN_PIN 18 #define Z_MAX_PIN 19 #define E0_STEP_PIN 35 #define E0_DIR_PIN 36 #define E0_ENABLE_PIN 34 #define E1_STEP_PIN 29 #define E1_DIR_PIN 39 #define E1_ENABLE_PIN 28 #define E2_STEP_PIN 23 #define E2_DIR_PIN 24 #define E2_ENABLE_PIN 22 #define SDPOWER -1 #define SDSS 53 #define LED_PIN 13 #define FAN_PIN 7 #define FAN2_PIN 6 #define PS_ON_PIN 12 #define KILL_PIN -1 #define HEATER_0_PIN 9 // EXTRUDER 1 #define HEATER_1_PIN 8 // EXTRUDER 2 #define HEATER_2_PIN -1 #if TEMP_SENSOR_0 == -1 #define TEMP_0_PIN 4 // ANALOG NUMBERING #else #define TEMP_0_PIN 13 // ANALOG NUMBERING #endif #if TEMP_SENSOR_1 == -1 #define TEMP_1_PIN 8 // ANALOG NUMBERING #else #define TEMP_1_PIN 15 // ANALOG NUMBERING #endif #define TEMP_2_PIN -1 // ANALOG NUMBERING #define HEATER_BED_PIN 10 // BED #if TEMP_SENSOR_BED == -1 #define TEMP_BED_PIN 8 // ANALOG NUMBERING #else #define TEMP_BED_PIN 14 // ANALOG NUMBERING #endif #define BEEPER_PIN 64 #define LCD_PINS_RS 14 #define LCD_PINS_ENABLE 15 #define LCD_PINS_D4 30 #define LCD_PINS_D5 31 #define LCD_PINS_D6 32 #define LCD_PINS_D7 33 // Buttons are directly attached using keypad #define BTN_EN1 61 #define BTN_EN2 59 #define BTN_ENC 43 //the click #define BLEN_C 2 #define BLEN_B 1 #define BLEN_A 0 #define SD_DETECT_PIN -1 // Megatronics doesn't use this
22.7
91
0.750734
[ "3d" ]
187040882e6572ccc181b78d684679d318ada774
5,399
h
C
be/src/storage/rowset/beta_rowset_writer.h
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
1
2022-03-08T09:13:32.000Z
2022-03-08T09:13:32.000Z
be/src/storage/rowset/beta_rowset_writer.h
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
null
null
null
be/src/storage/rowset/beta_rowset_writer.h
stephen-shelby/starrocks
67932670efddbc8c56e2aaf5d3758724dcb44b0a
[ "Zlib", "PSF-2.0", "BSD-2-Clause", "Apache-2.0", "ECL-2.0", "BSD-3-Clause-Clear" ]
null
null
null
// This file is made available under Elastic License 2.0. // This file is based on code available under the Apache license here: // https://github.com/apache/incubator-doris/blob/master/be/src/olap/rowset/beta_rowset_writer.h // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #pragma once #include <mutex> #include <vector> #include "common/statusor.h" #include "gen_cpp/olap_file.pb.h" #include "runtime/global_dict/types.h" #include "storage/rowset/rowset_writer.h" #include "storage/rowset/segment_writer.h" namespace starrocks { class SegmentWriter; class WritableFile; enum class FlushChunkState { UNKNOWN, UPSERT, DELETE, MIXED }; class BetaRowsetWriter : public RowsetWriter { public: explicit BetaRowsetWriter(const RowsetWriterContext& context); ~BetaRowsetWriter() override = default; Status init() override; StatusOr<RowsetSharedPtr> build() override; Version version() override { return _context.version; } int64_t num_rows() override { return _num_rows_written; } int64_t total_data_size() override { return _total_data_size; } RowsetId rowset_id() override { return _context.rowset_id; } const vectorized::DictColumnsValidMap& global_dict_columns_valid_info() const override { return _global_dict_columns_valid_info; } protected: Status flush_src_rssids(uint32_t segment_id); RowsetWriterContext _context; std::shared_ptr<FileSystem> _fs; std::shared_ptr<RowsetMeta> _rowset_meta; std::unique_ptr<TabletSchema> _rowset_schema; std::unique_ptr<RowsetTxnMetaPB> _rowset_txn_meta_pb; SegmentWriterOptions _writer_options; int _num_segment{0}; int _num_delfile{0}; vector<std::string> _tmp_segment_files; // mutex lock for vectorized add chunk and flush std::mutex _lock; // counters and statistics maintained during data write int64_t _num_rows_written; int64_t _num_rows_del; int64_t _total_row_size; int64_t _total_data_size; int64_t _total_index_size; // used for updatable tablet's compaction std::unique_ptr<vector<uint32_t>> _src_rssids; bool _is_pending = false; bool _already_built = false; FlushChunkState _flush_chunk_state = FlushChunkState::UNKNOWN; vectorized::DictColumnsValidMap _global_dict_columns_valid_info; }; // Chunk contains all schema columns data. class HorizontalBetaRowsetWriter final : public BetaRowsetWriter { public: explicit HorizontalBetaRowsetWriter(const RowsetWriterContext& context); ~HorizontalBetaRowsetWriter() override; Status add_chunk(const vectorized::Chunk& chunk) override; Status add_chunk_with_rssid(const vectorized::Chunk& chunk, const vector<uint32_t>& rssid) override; Status flush_chunk(const vectorized::Chunk& chunk) override; Status flush_chunk_with_deletes(const vectorized::Chunk& upserts, const vectorized::Column& deletes) override; // add rowset by create hard link Status add_rowset(RowsetSharedPtr rowset) override; Status add_rowset_for_linked_schema_change(RowsetSharedPtr rowset, const SchemaMapping& schema_mapping) override; Status flush() override; StatusOr<RowsetSharedPtr> build() override; private: StatusOr<std::unique_ptr<SegmentWriter>> _create_segment_writer(); Status _flush_segment_writer(std::unique_ptr<SegmentWriter>* segment_writer); Status _final_merge(); Status _flush_chunk(const vectorized::Chunk& chunk); std::string _dump_mixed_segment_delfile_not_supported(); std::unique_ptr<SegmentWriter> _segment_writer; }; // Chunk contains partial columns data corresponding to column_indexes. class VerticalBetaRowsetWriter final : public BetaRowsetWriter { public: explicit VerticalBetaRowsetWriter(const RowsetWriterContext& context); ~VerticalBetaRowsetWriter() override; Status add_columns(const vectorized::Chunk& chunk, const std::vector<uint32_t>& column_indexes, bool is_key) override; Status add_columns_with_rssid(const vectorized::Chunk& chunk, const std::vector<uint32_t>& column_indexes, const std::vector<uint32_t>& rssid) override; Status flush_columns() override; Status final_flush() override; private: StatusOr<std::unique_ptr<SegmentWriter>> _create_segment_writer(const std::vector<uint32_t>& column_indexes, bool is_key); Status _flush_columns(std::unique_ptr<SegmentWriter>* segment_writer); std::vector<std::unique_ptr<SegmentWriter>> _segment_writers; size_t _current_writer_index = 0; }; } // namespace starrocks
35.287582
117
0.750509
[ "vector" ]
18710ce627a60e85315b115f44324181d73623de
3,957
h
C
common/graphics/gl_context_switch.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
13
2020-08-09T10:30:50.000Z
2021-09-06T18:26:05.000Z
common/graphics/gl_context_switch.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
155
2020-11-30T09:16:59.000Z
2022-03-29T09:40:55.000Z
common/graphics/gl_context_switch.h
onix39/engine
ec66a45a3a7d5b9dfc2e0feab8965db7a91027cc
[ "BSD-3-Clause" ]
22
2020-11-25T10:58:46.000Z
2022-01-25T09:45:25.000Z
// Copyright 2013 The Flutter 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 FLUTTER_COMMON_GRAPHICS_GL_CONTEXT_SWITCH_H_ #define FLUTTER_COMMON_GRAPHICS_GL_CONTEXT_SWITCH_H_ #include <functional> #include <memory> #include <vector> #include "flutter/fml/logging.h" #include "flutter/fml/macros.h" namespace flutter { // This interface represents a gl context that can be switched by // |GLContextSwitch|. // // The implementation should wrap a "Context" object inside this class. For // example, in iOS while using a GL rendering surface, the implementation should // wrap an |EAGLContext|. class SwitchableGLContext { public: SwitchableGLContext(); virtual ~SwitchableGLContext(); // Implement this to set the context wrapped by this |SwitchableGLContext| // object to the current context. virtual bool SetCurrent() = 0; // Implement this to remove the context wrapped by this |SwitchableGLContext| // object from current context; virtual bool RemoveCurrent() = 0; FML_DISALLOW_COPY_AND_ASSIGN(SwitchableGLContext); }; // Represents the result of setting a gl context. // // This class exists because context results are used in places applies to all // the platforms. On certain platforms(for example lower end iOS devices that // uses gl), a |GLContextSwitch| is required to protect flutter's gl contect // from being polluted by other programs(embedded platform views). A // |GLContextSwitch| is a subclass of |GLContextResult|, which can be returned // on platforms that requires context switching. A |GLContextDefaultResult| is // also a subclass of |GLContextResult|, which can be returned on platforms // that doesn't require context switching. class GLContextResult { public: GLContextResult(); virtual ~GLContextResult(); //---------------------------------------------------------------------------- // Returns true if the gl context is set successfully. bool GetResult(); protected: GLContextResult(bool static_result); bool result_; FML_DISALLOW_COPY_AND_ASSIGN(GLContextResult); }; //------------------------------------------------------------------------------ /// The default implementation of |GLContextResult|. /// /// Use this class on platforms that doesn't require gl context switching. /// * See also |GLContextSwitch| if the platform requires gl context switching. class GLContextDefaultResult : public GLContextResult { public: //---------------------------------------------------------------------------- /// Constructs a |GLContextDefaultResult| with a static result. /// /// Used this on platforms that doesn't require gl context switching. (For /// example, metal on iOS) /// /// @param static_result a static value that will be returned from /// |GetResult| GLContextDefaultResult(bool static_result); ~GLContextDefaultResult() override; FML_DISALLOW_COPY_AND_ASSIGN(GLContextDefaultResult); }; //------------------------------------------------------------------------------ /// Switches the gl context to the a context that is passed in the /// constructor. /// /// In destruction, it should restore the current context to what was /// before the construction of this switch. class GLContextSwitch final : public GLContextResult { public: //---------------------------------------------------------------------------- /// Constructs a |GLContextSwitch|. /// /// @param context The context that is going to be set as the current /// context. The |GLContextSwitch| should not outlive the owner of the gl /// context wrapped inside the `context`. GLContextSwitch(std::unique_ptr<SwitchableGLContext> context); ~GLContextSwitch() override; private: std::unique_ptr<SwitchableGLContext> context_; FML_DISALLOW_COPY_AND_ASSIGN(GLContextSwitch); }; } // namespace flutter #endif // FLUTTER_COMMON_GRAPHICS_GL_CONTEXT_SWITCH_H_
34.408696
80
0.682082
[ "object", "vector" ]
1871c78712a10987c79cb83e0fe68d86915c8569
5,692
h
C
modules/audio_device/android/audio_track_jni.h
yuxw75/temp
ab2fd478821e6c98ff10f2976ce43f617250cff6
[ "DOC", "BSD-3-Clause" ]
null
null
null
modules/audio_device/android/audio_track_jni.h
yuxw75/temp
ab2fd478821e6c98ff10f2976ce43f617250cff6
[ "DOC", "BSD-3-Clause" ]
null
null
null
modules/audio_device/android/audio_track_jni.h
yuxw75/temp
ab2fd478821e6c98ff10f2976ce43f617250cff6
[ "DOC", "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. * * Use of this source code is governed by a BSD-style license * that can be found in the LICENSE file in the root of the source * tree. An additional intellectual property rights grant can be found * in the file PATENTS. All contributing project authors may * be found in the AUTHORS file in the root of the source tree. */ #ifndef WEBRTC_MODULES_AUDIO_DEVICE_ANDROID_AUDIO_TRACK_JNI_H_ #define WEBRTC_MODULES_AUDIO_DEVICE_ANDROID_AUDIO_TRACK_JNI_H_ #include <jni.h> #include "webrtc/system_wrappers/interface/critical_section_wrapper.h" #include "webrtc/modules/audio_device/android/audio_common.h" #include "webrtc/modules/audio_device/include/audio_device_defines.h" #include "webrtc/modules/audio_device/audio_device_generic.h" namespace webrtc { class EventWrapper; class ThreadWrapper; const uint32_t N_PLAY_SAMPLES_PER_SEC = 16000; // Default is 16 kHz const uint32_t N_PLAY_CHANNELS = 1; // default is mono playout class AudioTrackJni : public PlayoutDelayProvider { public: static int32_t SetAndroidAudioDeviceObjects(void* javaVM, void* env, void* context); static void ClearAndroidAudioDeviceObjects(); explicit AudioTrackJni(const int32_t id); virtual ~AudioTrackJni(); // Main initializaton and termination int32_t Init(); int32_t Terminate(); bool Initialized() const { return _initialized; } // Device enumeration int16_t PlayoutDevices() { return 1; } // There is one device only. int32_t PlayoutDeviceName(uint16_t index, char name[kAdmMaxDeviceNameSize], char guid[kAdmMaxGuidSize]); // Device selection int32_t SetPlayoutDevice(uint16_t index); int32_t SetPlayoutDevice( AudioDeviceModule::WindowsDeviceType device); // Audio transport initialization int32_t PlayoutIsAvailable(bool& available); // NOLINT int32_t InitPlayout(); bool PlayoutIsInitialized() const { return _playIsInitialized; } // Audio transport control int32_t StartPlayout(); int32_t StopPlayout(); bool Playing() const { return _playing; } // Audio mixer initialization int32_t InitSpeaker(); bool SpeakerIsInitialized() const { return _speakerIsInitialized; } // Speaker volume controls int32_t SpeakerVolumeIsAvailable(bool& available); // NOLINT int32_t SetSpeakerVolume(uint32_t volume); int32_t SpeakerVolume(uint32_t& volume) const; // NOLINT int32_t MaxSpeakerVolume(uint32_t& maxVolume) const; // NOLINT int32_t MinSpeakerVolume(uint32_t& minVolume) const; // NOLINT int32_t SpeakerVolumeStepSize(uint16_t& stepSize) const; // NOLINT // Speaker mute control int32_t SpeakerMuteIsAvailable(bool& available); // NOLINT int32_t SetSpeakerMute(bool enable); int32_t SpeakerMute(bool& enabled) const; // NOLINT // Stereo support int32_t StereoPlayoutIsAvailable(bool& available); // NOLINT int32_t SetStereoPlayout(bool enable); int32_t StereoPlayout(bool& enabled) const; // NOLINT // Delay information and control int32_t SetPlayoutBuffer(const AudioDeviceModule::BufferType type, uint16_t sizeMS); int32_t PlayoutBuffer(AudioDeviceModule::BufferType& type, // NOLINT uint16_t& sizeMS) const; int32_t PlayoutDelay(uint16_t& delayMS) const; // NOLINT // Attach audio buffer void AttachAudioBuffer(AudioDeviceBuffer* audioBuffer); int32_t SetPlayoutSampleRate(const uint32_t samplesPerSec); // Error and warning information bool PlayoutWarning() const; bool PlayoutError() const; void ClearPlayoutWarning(); void ClearPlayoutError(); // Speaker audio routing int32_t SetLoudspeakerStatus(bool enable); int32_t GetLoudspeakerStatus(bool& enable) const; // NOLINT protected: // TODO(henrika): improve this estimate. virtual int PlayoutDelayMs() { return 0; } private: void Lock() EXCLUSIVE_LOCK_FUNCTION(_critSect) { _critSect.Enter(); } void UnLock() UNLOCK_FUNCTION(_critSect) { _critSect.Leave(); } int32_t InitJavaResources(); int32_t InitSampleRate(); static bool PlayThreadFunc(void*); bool PlayThreadProcess(); // TODO(leozwang): Android holds only one JVM, all these jni handling // will be consolidated into a single place to make it consistant and // reliable. Chromium has a good example at base/android. static JavaVM* globalJvm; static JNIEnv* globalJNIEnv; static jobject globalContext; static jclass globalScClass; JavaVM* _javaVM; // denotes a Java VM JNIEnv* _jniEnvPlay; // The JNI env for playout thread jclass _javaScClass; // AudioDeviceAndroid class jobject _javaScObj; // AudioDeviceAndroid object jobject _javaPlayBuffer; void* _javaDirectPlayBuffer; // Direct buffer pointer to play buffer jmethodID _javaMidPlayAudio; // Method ID of play in AudioDeviceAndroid AudioDeviceBuffer* _ptrAudioBuffer; CriticalSectionWrapper& _critSect; int32_t _id; bool _initialized; EventWrapper& _timeEventPlay; EventWrapper& _playStartStopEvent; ThreadWrapper* _ptrThreadPlay; uint32_t _playThreadID; bool _playThreadIsInitialized; bool _shutdownPlayThread; bool _playoutDeviceIsSpecified; bool _playing; bool _playIsInitialized; bool _speakerIsInitialized; bool _startPlay; uint16_t _playWarning; uint16_t _playError; uint16_t _delayPlayout; uint16_t _samplingFreqOut; // Sampling frequency for Speaker uint32_t _maxSpeakerVolume; // The maximum speaker volume value bool _loudSpeakerOn; }; } // namespace webrtc #endif // WEBRTC_MODULES_AUDIO_DEVICE_ANDROID_AUDIO_TRACK_JNI_H_
32.340909
73
0.751054
[ "object" ]
1873d1ca68dbaf3def7edbc42874540337755a82
93,221
h
C
include/ftstab.h
kernsuite-debian/tirific
05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9
[ "MIT" ]
4
2015-07-01T12:07:09.000Z
2018-01-04T08:22:01.000Z
include/ftstab.h
gigjozsa/tirific
462a58a8312ce437ac5e2c87060cde751774f1de
[ "MIT" ]
2
2017-02-24T12:40:08.000Z
2019-08-20T06:37:26.000Z
include/ftstab.h
kernsuite-debian/tirific
05fddee80e715dfee5d0f4e2f994b2f17c5d2ca9
[ "MIT" ]
3
2017-08-28T03:17:38.000Z
2022-01-03T15:02:35.000Z
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @file ftstab.h @brief Module to create and change long fits tables The module has been created for use in the tirific environment. It is designed to guarantee io of the corresponding fits tables. As it is held quite general, it may serve other purposes as well. The main feature is that the io of the tables is held at a file io level, meaning that the functions are slow, but large tables up to 2GB can be accessed. Most of the functions can be called from fortran. To do that, declare the function in Fortran and call it. Exchange between Fortran and c takes place via the use of pointers, while the function call in Fortran has to be with the variables (as of course there are no pointers). The underscored functions are those which take as an input only pointers, and thus are called from Fortran if calling the function without underscore. The organisation of the module is as follows. The user has access to one fits table at a time. To get this access, precautions have to take place. Four control structures that are private to the module steer the io of the table. In principle, it is not difficult to get the module to deliver access to a lot of files at the same time. For that, the only thing is to pack all the global variables into one struct, make two functions, one that constructs and one that destructs this struct, and add as a parameter the pointer to this struct to every function in this module. Each global variable (exclusively marked with an underscore) has to be replaced with a struct -> variable in the functions. This is the work of one or two hours. The current version has the benifit of one less parameter for each function. Each table column gets a number of keywords attached in the header: TFORMi is the numerical type (fits required keyword) of the column i TITLEi is the name of the column i TTYPEi is the physical type of the column i, e.g. VELO for velocity (has to be fits conform) TUNITi is the unit of the column i TSCALi describes the multiplicative factor with which the single values are multiplied to get to the real value in the column i (has to be fits conform) TZEROi describes the additional constant which is added to the single values to get to the real value in the column i (has to be fits conform) RADIi is the radius (double accuracy) of the column i (free keyword) GRIDi is the grid (accuracy adjusted to TTYPEi) of the column i (free keyword) TMAXi is the maximum (accuracy adjusted to TTYPEi) of the column i (free keyword) TMINi is the minimum (accuracy adjusted to TTYPEi) of the column i (free keyword) The keywords TTYPEi, TUNITi, TSCALi, TZEROi are tied to TITLEi, as a TITLEi gets a title number and the rest of the keywords is tied to the TITLE in a header item list (hdl). The hdl contains some predefined standard tuples. However, it can always be completely changed and analysed with the functions: ftstab_putlcoltitl(), ftstab_putlcolunit(), ftstab_putlcoltype(), ftstab_putcolunit(), ftstab_putcoltype(), ftstab_putcoltitl(), ftstab_gtitln_(), ftstab_glunit(), ftstab_gtzero(), ftstab_gtscal(), ftstab_gunit(), ftstab_gltype(), ftstab_gltitl(), ftstab_gtitl(), ftstab_hdlreset_(), ftstab_hdladditem() The second structure that controls the io is the column descriptor array (cda), in which the keywords TFORMi, TITLEi, RADIi, GRIDi, TMAXi, TMINi are controlled. For the creation of a new table or the controlled opening of a table, the cda has to be initialised with the function ftstab_inithd(), specifying the number of columns of the table. It can be filled and accessed with the functions ftstab_findminmax(), ftstab_get_colmin(), ftstab_get_colmax(), ftstab_get_colgrd(), ftstab_get_colrad(), ftstab_get_coltyp(), ftstab_get_coltit(), ftstab_get_maxi_(), ftstab_get_mini_(), ftstab_get_radi_(), ftstab_get_grid_(), ftstab_get_type_(), ftstab_get_title_(), ftstab_fillhd(), ftstab_inithd() The third and fourth structure are qfits header structures that contain the "real" headers that are put to the file. One is the main header that belongs to the currrently adressed extension, one is a "history header" that is always attached to the end of the file if initialised. While the cda changes with the acquirement of the table, i.e. if the table is enlarged, minimum and maximum is changed, the data header will not be changed with respect to the minimum and maximum. Before the table gets closed, the current maximum and minimum can be updated in the main header. Additionally, the possibility exists to directly change the headers and append or change cards, which comes convenient for saving comments. The functions to adress headers are: ftstab_genhd(), ftstab_clearhd(), ftstab_getcard(), ftstab_putcard(), ftstab_putminmax_() The function ftstab_fopen() opens a table in various ways depending on the creation and acquisision of the control objects in the module (see the description there). In any case a check against the possible header titles will take place in case of trying to open an existent extension. This functionality might seem ridiculous but is useful when files shall be handled in a single environment that should be checked against erroneous data. The function takes care of the blocking mechanism, that is, if a file is endangered to become corrupted in case of an addition of an item, a table row, or a header item, this operation is not allowed. If ftstab_fopen encounters a file in which the last extension is meant to be read, and it proves that this last extension does not comply with the header information concerning the number of rows this number will be corrected if possible. This means, if ftstab.c is aborted in the course of action, it is likely that the resulting file contains as many rows as have been written up to that point, but this information is not written in the header. ftstab_fopen recognizes such a case and corrects for this error. A history header, however will be lost with an abort of the program. Once opened the user has the possibility to read from and write to the table. The functions ftstab_appendrow_(), ftstab_putrow(), ftstab_putval(), ftstab_get_row(), ftstab_get_value() serve at a low level for these purposes, while there are three functions that change the table in a more complex way. Mark that all functions adress data "as is" without scaling according to tscal and tzero. ftstab_heapsort() sorts the table with a heapsort algorithm, ftstab_histo() and ftstab_histo_2d() create fits images with a histogram of one or two rows rearranging the table. To get information about the status of the table, number of rows, columns, extension adressed, use: ftstab_get_rownr_() ,ftstab_get_colnr_(), ftstab_get_extnr_() The function ftstab_close() closes the stream caring for the right format of the output stream, putting the current header(s) to the file. If one wants to adress two different extensions in a file the file has to be reopened, i.e. you have to call close(). With close(), however, not all information is "lost". All the control structures are kept, which affects a possible ftstab_fopen() call. To reset the module to its original status, the function ftstab_flush() can be used. All acquired information is forgotten. Two functions can be used to directly change an opened file or copy a file: ftstab_copytohere_() makes a partial copy of the fits file, ftstab_deleterest_() deletes the complete information that follows the current extension in the file. The functions ftstab_get_intarr() and ftstab_get_dblarr() deliver int or double arrays of the length of a row. The functions ftstab_get_curlength_() and ftstab_get_byteperow_() serve to have control over the size of the table. Compilation of qfits to be used with this module: tar zxvf qfits-4.3.7-mod.tar.gz cd qfits-4.3.7-mod configure make The underscored functions are safe to use in a fortran code. They require a (pointer) variable once. It is not necessary to maintain the variable. Code example in testftstab.c $Source: /Volumes/DATA_J_II/data/CVS/tirific/include/ftstab.h,v $ $Date: 2009/05/26 07:56:39 $ $Revision: 1.28 $ $Author: jozsa $ $Log: ftstab.h,v $ Revision 1.28 2009/05/26 07:56:39 jozsa Left work Revision 1.27 2007/08/22 15:58:34 gjozsa Left work Revision 1.26 2005/03/25 18:17:19 gjozsa Left work Revision 1.25 2005/02/21 11:23:44 gjozsa Added the recover functionality to checkin, now finished until some additional thing is needed Revision 1.23 2005/02/21 09:44:24 gjozsa Stable, tested, and nearly final version, added histogram functions Revision 1.22 2005/02/16 18:55:32 gjozsa Left work Revision 1.21 2005/02/16 13:30:26 gjozsa Largely debugged and tested, added histogram function Revision 1.20 2005/02/15 18:00:34 gjozsa Left work Revision 1.19 2005/02/15 15:37:11 gjozsa Left work Revision 1.18 2005/02/11 17:37:13 gjozsa Left work Revision 1.17 2005/02/10 17:57:42 gjozsa Left work Revision 1.16 2005/02/10 12:29:09 gjozsa Implemented and tested heapsort Revision 1.15 2005/02/09 17:52:19 gjozsa Left work Revision 1.14 2005/02/08 11:37:14 gjozsa Added and tested putval and putrow functions Revision 1.13 2005/02/07 16:05:49 gjozsa Quite tested version, added lots of functionality Revision 1.12 2005/02/04 18:01:12 gjozsa Left work Revision 1.11 2005/02/03 17:23:55 gjozsa Left work Revision 1.9 2005/02/01 17:45:53 gjozsa Left work Revision 1.8 2005/02/01 14:51:20 gjozsa Left work Revision 1.7 2005/01/28 17:29:23 gjozsa Tested and debugged Revision 1.6 2005/01/27 17:44:43 gjozsa Left work Revision 1.5 2005/01/26 17:26:14 gjozsa Left work Revision 1.4 2005/01/26 17:10:04 gjozsa First stable and tested version Revision 1.3 2005/01/24 15:48:45 gjozsa Left work Revision 1.1 2005/01/17 12:16:04 gjozsa added to cvs control */ /* ------------------------------------------------------------ */ /* Include guard */ #ifndef FTSTAB_H #define FTSTAB_H /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* EXTERNAL INCLUDES */ /* ------------------------------------------------------------ */ #include <stdio.h> /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* INTERNAL INCLUDES */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* SYMBOLIC CONSTANTS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @def COLTYPE_DEFAULT @brief Default value for the Column type */ /* ------------------------------------------------------------ */ #define COLTYPE_DEFAULT 0 #define COLTYPE_FLOAT 1 #define COLTYPE_CHAR 2 #define COLTYPE_INT 3 #define COLTYPE_DOUBLE 4 /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @def COLRADI_DEFAULT @brief Default values for the Column radius */ /* ------------------------------------------------------------ */ #define COLRADI_DEFAULT -1.0 #define COLRADI_FLOAT -1.0 #define COLRADI_CHAR -1 #define COLRADI_INT -1 #define COLRADI_DOUBLE -1.0 /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @def COLGRID_DEFAULT @brief Default value for the Column delta */ /* ------------------------------------------------------------ */ #define COLGRID_DEFAULT 0.0 #define COLGRID_FLOAT 0.0 #define COLGRID_CHAR 0 #define COLGRID_INT 0 #define COLGRID_DOUBLE 0.0 /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* MACROS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* TYPEDEFS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* STRUCTS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* FUNCTION DECLARATIONS */ /* ------------------------------------------------------------ */ /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_hdladditem(char *titl, char *ttype, char *tunit, double tzero, double tscal); @brief Modify the header item list The header item list contains the allowed names to put into the header and also the context, i.e. the fits ttype, tunit, tscal, tzero that is tied to the name in this module. The function searches the list for the item. If it does not find the item, it appends it to the list. Whitespaces are fully interpreted as characters. @param titl (char *) The title (name of the item) (18 chars regarded) @param ttype (char *) The ttype belonging to item (18 chars regarded) @param tunit (char *) The tunit belonging to item (18 chars regarded) @param tzero (double) The tzero belonging to item @param tscal (double) The tscale belonging to item @return (success) int ftstab_hdladditem: Item number (error) -1 in case of wrong input */ /* ------------------------------------------------------------ */ int ftstab_hdladditem(char *titl, char *ttype, char *tunit, double tzero, double tscal); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_hdlreset(void); @brief Resets the hdllist Refreshes the header item list, i.e., puts it to the default values. @return (success) int ftstab_hdlreset: 1 (error) 0 if the item does not exist */ /* ------------------------------------------------------------ */ int ftstab_hdlreset_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn char *ftstab_gtitl(int titl) @brief Get a char array belonging to the COLTITL titl Returns an allocated char array with the title string @return char *gtitl: Char array with the title string */ /* ------------------------------------------------------------ */ char *ftstab_gtitl(int titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn char *ftstab_gltitl(int titl) @brief Get a char array belonging to the COLTITL titl Returns an allocated char array with the full title string as is in the fits header. @return char *gtitl: Char array with the title string */ /* ------------------------------------------------------------ */ char *ftstab_gltitl(int titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn char *ftstab_gtype(int titl) @brief Get a char array belonging to the COLTITL titl Returns an allocated char array with the type string @return char *gtitl: Char array with the type string */ /* ------------------------------------------------------------ */ char *ftstab_gtype(int titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn char *ftstab_gltype(int titl) @brief Get a char array belonging to the COLTITL titl Returns an allocated char array with the full type string as is in the fits header. @return char *gltype: Char array with the type string */ /* ------------------------------------------------------------ */ char *ftstab_gltype(int titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn char *ftstab_gunit(int titl) @brief Get a char array belonging to the COLTITL titl Returns an allocated char array with the unit string @return char *gunit: Char array with the unit string */ /* ------------------------------------------------------------ */ char *ftstab_gunit(int titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn double ftstab_gtscal(int coltitle) @brief Get a tscale belonging to the COLTITL titl @return (success) double gtscal: The scale belonging to the titl (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_gtscal(int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn double ftstab_gtscal_(int _coltitle) @brief Get a tscale belonging to the COLTITL titl @return (success) double gtscal: The scale belonging to the titl (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_gtscal_(int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn double ftstab_gtzero(int coltitle) @brief Get a tzero belonging to the COLTITL titl @return (success) double gtzero: The zero belonging to the titl (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_gtzero(int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn double ftstab_gtzero_(int *coltitle) @brief Get a tscale belonging to the COLTITL titl @return (success) double gtzero: The zero belonging to the titl (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_gtzero_(int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn char *ftstab_glunit(int titl) @brief Get a char array belonging to the COLTITL titl Returns an allocated char array with the full unit string as is in the fits header. @return char *gunit: Char array with the unit string */ /* ------------------------------------------------------------ */ char *ftstab_glunit(int titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_gtitln_(char *titl) @brief Get COLTITL number from string Returns the number belonging to the short title string @return int gtitln: Number belonging to the title string */ /* ------------------------------------------------------------ */ int ftstab_gtitln_(char *titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_gltitln_(char *titl) @brief Get COLTITL number from string Returns the number belonging to the title string as found in a header @return int gtitln: Number belonging to the title string */ /* ------------------------------------------------------------ */ int ftstab_gltitln_(char *titl); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putcoltitl(char *key, int coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key. @param key (char *) the string to put the string @param colname (int) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putcoltitl(char *key, int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putcoltitl(char *key, int *coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key. @param key (char *) The string to put the string @param colname (int *) Integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putcoltitl_(char *key, int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putcoltype(char *key, int coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key. @param key (char *) the string to put the string @param colname (int) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putcoltype(char *key, int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putcoltype_(char *key, int *coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key. @param key (char *) the string to put the string @param colname (int *) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putcoltype_(char *key, int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putcolunit(char *key, int coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key. @param key (char *) the string to put the string @param colname (int) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putcolunit(char *key, int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putcolunit(char *key, int *coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key. @param key (char *) the string to put the string @param colname (int *) integer defined by the symbolic constants in the .h @return (success) int putcoltitle_: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putcolunit_(char *key, int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putlcoltype(char *key, int coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key, as is in the fits header. @param key (char *) the string to put the string @param colname (int) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putlcoltype(char *key, int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putlcoltype_(char *key, int *coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key, as is in the fits header. @param key (char *) the string to put the string @param colname (int *) integer defined by the symbolic constants in the .h @return (success) int ftstab_putlcoltype: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putlcoltype_(char *key, int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putlcolunit(char *key, int coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key, as is in the fits header. @param key (char *) the string to put the string @param colname (int) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putlcolunit(char *key, int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putlcolunit_(char *key, int *coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key, as is in the fits header. @param key (char *) the string to put the string @param colname (int *) integer defined by the symbolic constants in the .h @return (success) int ftstab_putlcolunit_: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putlcolunit_(char *key, int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putlcoltitl(char *key, int coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key, as is in the fits header. @param key (char *) the string to put the string @param colname (int) integer defined by the symbolic constants in the .h @return (success) int putcoltitle: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putlcoltitl(char *key, int coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /* @fn int ftstab_putlcoltitl_(char *key, int *coltitle) @brief Puts the string that belongs to coltitle into key In the fitstable each column gets a title according to the symbolic constants defined in the .h. This function puts the string according to the number given by the symbolic constant into the string key, as is in the fits header. @param key (char *) the string to put the string @param colname (int *) integer defined by the symbolic constants in the .h @return (success) int ftstab_putlcoltitl_: coltitle\n (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_putlcoltitl_(char *key, int *coltitle); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_inithd(int numberofcols) @brief Reserves space for the header descriptor Initialises the internal struct that contains the information about the columns of the table to contain the description of numberofcols columns. @param numberofcols (int) The number of columns in the table @return (success) int initftstbl 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_inithd(int numberofcols); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_inithd_(int *numberofcols) @brief Reserves space for the header descriptor Initialises the internal struct that contains the information about the columns of the table to contain the description of numberofcols columns. This function works with a pointer instead of a given direct input. No care has to be taken of the pointer after the function call, as it will nevertheless produce a local copy before working with the parameter(s). @param numberofcols (int *) The number of columns in the table @return (success) int initftstbl 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_inithd_(int *numberofcols); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_fillhd(int column, int title, int type, double radius, double grid) @brief Fills column column of the table description object with the given values Tries to fill column column of the table description object with the given values for the name, type, radius, and grid spacing in the table. Name and type are given by integers defined in the corresponding symbolic constants. Returns 0 if not successful, i.e. the structure has not been initialised, or if the column is non-existent. The change of the numerical type is dangerous if a table is open. The module is not safe with respect to that. @param column (int) Column number (starting at 0) @param title (int) Name of column @param type (int) Numerical type of column, CHAR, INT, FLOAT, DOUBLE @param radius (double) Radius of column @param grid (double) Grid spacing of column @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_fillhd(int column, int title, int type, double radius, double grid); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_fillhd_(int *column, int *name, int *type, double *radius, double *grid) @brief Fills column column of the table description object with the given values Tries to fill column column of the table description object with the given values for the name, type, radius, and grid spacing in the table. Name and type are given by integers defined in the corresponding symbolic constants. Returns 0 if not successful, i.e. the structure has not been initialised, or if the column is non-existent. This function works with a pointer instead of a given direct input. No care has to be taken of the pointer after the function call, as it will nevertheless produce a local copy before working with the parameter(s). @param column (int *) Column number (starting at 0) @param name (int *) Name of column @param type (int *) Numerical type of column, CHAR, INT, FLOAT, DOUBLE @param radius (double *) Radius of column @param grid (double *) Grid spacing of column @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_fillhd_(int *column, int *titl, int *type, double *radius, double *grid); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_title_(int *array) @brief Get the titles of the columns into an array The tilte shortcuts as defined above are put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_intarr(). @param array (int *) An array large enough to contain ftstab_get_colnr_() numbers @return int ftstab_get_title_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_title_(int *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_type_(int *array) @brief Get the numerical types of the columns into an array The type shortcuts as defined above are put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_intarr(). @param array (int *) An array large enough to contain ftstab_get_colnr_() numbers @return int ftstab_get_type_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_type_(int *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_radi_(double *array) @brief Get the radii of the columns into an array The radii of a column are put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_dblarr(). @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return int ftstab_get_radi_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_radi_(double *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_grid_(double *array) @brief Get the grid spacing of the columns into an array The grid spacings of a column are put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_dblarr(). @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return int ftstab_get_grid_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_grid_(double *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_maxi_(double *array) @brief Get the maxima of the columns into an array The maxima of a column are put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_dblarr(). @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return int ftstab_get_maxi_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_maxi_(double *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_mini_(double *array) @brief Get the radii of the columns into an array The minima of a column are put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_dblarr(). @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return int ftstab_get_mini_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_mini_(double *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_coltit(int column) @brief Get the title number of column column @param column (int) The column (start with 1) @return (success) int ftstab_get_coltit_: Number of column (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_get_coltit(int column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_coltit_(int *column) @brief Get the title number of column column @param column (int *) The column (start with 1) @return (success) int ftstab_get_coltit_: Number of column (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_get_coltit_(int *column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_coltyp(int column) @brief Get the identifier of the numerical type of column column @param column (int) The column (start with 1) @return (success) int ftstab_get_coltyp: Numerical type of column (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_get_coltyp(int column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_coltyp_(int *column) @brief Get the identifier of the numerical type of column column @param column (int) The column (start with 1) @return (success) int ftstab_get_coltyp_: Numerical type of column (error) -1 */ /* ------------------------------------------------------------ */ int ftstab_get_coltyp_(int *column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colrad(int column) @brief Get the radius of column column @param column (int) The column (start with 1) @return (success) double ftstab_get_colrad: Radius of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colrad(int column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colrad_(int *column) @brief Get the radius of column column @param column (int *) The column (start with 1) @return (success) double ftstab_get_colrad: Radius of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colrad_(int *column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colgrd(int column) @brief Get the grid of column column @param column (int) The column (start with 1) @return (success) double ftstab_get_colgrd: Grid of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colgrd(int column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colgrd_(int *column) @brief Get the grid of column column @param column (int *) The column (start with 1) @return (success) double ftstab_get_colgrd: Grid of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colgrd_(int *column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colmax(int column) @brief Get the current maximum of column column The function returnst the current maximum of the column. To be sure that this is the right value, call ftstab_get_minmax(). @param column (int) The column (start with 1) @return (success) double ftstab_get_colmax: Maximum of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colmax(int column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colmax_(int *column) @brief Get the current maximum of column column The function returnst the current maximum of the column. To be sure that this is the right value, call ftstab_get_minmax(). @param column (int *) The column (start with 1) @return (success) double ftstab_get_colmax: Maximum of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colmax_(int *column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colmin(int column) @brief Get the current minimum of column column The function returnst the current maximum of the column. To be sure that this is the right value, call ftstab_get_minmax(). @param column (int) The column (start with 1) @return (success) double ftstab_get_colmin: Minimum of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colmin(int column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn double ftstab_get_colmin_(int *column) @brief Get the current minimum of column column The function returnst the current minimum of the column. To be sure that this is the right value, call ftstab_get_minmax(). @param column (int *) The column (start with 1) @return (success) double ftstab_get_colmin: Minimum of column (error) DBL_MAX */ /* ------------------------------------------------------------ */ double ftstab_get_colmin_(int *column); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_findminmax(long begin, long end) @brief Correct the minima and the maxima towards the minima and maxima between begin and end row Searches the minima and maxima for each row in-between begin and end (starting with 1) and puts the found values in the header description array. They are not applied to the header. ftstab_clearhd(0) should follow if one wants to apply the information to the file. @param start (long) Start row @param end (long) End row @return (success) int int ftstab_findminmax: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_findminmax(long start, long end); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_findminmax_(long *begin, long *end) @brief Correct the minima and the maxima towards the minima and maxima between begin and end row Searches the minima and maxima for each row in-between begin and end (starting with 1) and puts the found values in the header description array. They are not applied to the header. ftstab_clearhd(0) should follow if one wants to apply the information to the file. @param start (long) Start row @param end (long) End row @return (success) int int ftstab_findminmax_: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_findminmax_(long *start, long *end); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_genhd(char n) @brief Generate a header Generates a header not yet attached to a file that can be manipulated. If n is 0, the header will be generated from the information passed with ftstab_inithd and ftstab_fillhd to be set before the bintable. If n is not 0, a default header will be generated that is appropriate to append to the file to store additional information. Both headers can be manipulated with ftstab_addcard(). It is strongly recommended not to do so if information after the header (a table, other hdu's) is present. If a header is already present this will be an error and no changes are applied. @param n (char) header to adress, main (0), appendix (1) @return (success) int genhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_genhd(char n); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_genhd_(char *n) @brief Generate a header Generates a header not yet attached to a file that can be manipulated. If *n is 0, the header will be generated from the information passed with ftstab_inithd and ftstab_fillhd to be set before the bintable. If *n is 1, a default header will be generated that is appropriate to append to the file to store additional information. Both headers can be manipulated with ftstab_addcard(). It is strongly recommended not to do so if information after the header (a table, other hdu's) is present. @param n (char *) header to adress, main (0), appendix (1) @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_genhd_(char *n); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_clearhd(char n) @brief Destroys or updates a header if possible Deletes a header if possible. If n is 0, then the main header will be deleted if possible. If the header is blocked, it will be updated with all information contained in the header description object, but no cards are deleted. If n is 1, the history header will be deleted. @param n (char) header to adress, main (0), appendix (1) @return (success) int ftstab_clearhd: 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_clearhd(char n); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_clearhd_(char *n) @brief Destroys or updates a header if possible Deletes a header if possible. If n is 0, then the main header will be deleted if possible. If the header is blocked, it will be updated with all information contained in the header description object, but no cards are deleted. If n is 1, the history header will be deleted. @param n (char *) header to adress, main (0), appendix (1) @return (success) int ftstab_clearhd: 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_clearhd_(char *n); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_getcard(char n, char *key, char *string, int what) @brief Get a full card image from a header Returns the content of a header card image. string should have reserved space to contain 81 characters (80 + terminator). what can be: 0: whole line, 1: value, 2: comment @param n (char) header to check for, main (0), appendix (other) @param key (char *) The key @param string (char *) a char array to write the card in @param what (int) The desired information @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_getcard(char n, char *key, char *string, int what); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_getcard_(char *n, char *string) @brief Generate a header Returns the content of a header card image. string should have reserved space to contain 81 characters (80 + terminator). what can be: 0: whole line, 1: value, 2: comment @param n (char *) header to check for, main (0), appendix (other) @param key (char *) The key @param string (char *) a char array to write the card in @param what (int) The desired information @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_getcard_(char *n, char *key, char *string, int *what); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putcard(char n, char *key, char *value) @brief Add a card to a header Adds a card to a header with the value contained in value. Except for a blank HISTORY or COMMENT key, the function will update header items if they are already present. For a blank, HISTORY, or COMMENT key, the values are appended. In case of a blank, HISTORY, or COMMENT key, the value may contain 70 characters, in all other cases, it may contain 20 characters. For this the user has to care. For a blocked header, appending a card is not possible (see ftstab_fopen). @param n (char *) header to check for, main (0), appendix (1) @param string (char *) a char array to write the card in @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putcard(char n, char *keyl, char *valuel); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putcard_(char *n, char *key, char *value) @brief Add a card to a header Adds a card to a header with the value contained in value. Except for a blank HISTORY or COMMENT key, the function will update header items if they are already present. For a blank, HISTORY, or COMMENT key, the values are appended. In case of a blank, HISTORY, or COMMENT key, the value may contain 70 characters, in all other cases, it may contain 20 characters. For this the user has to care. For a blocked header, appending a card is not possible. @param n (char *) header to check for, main (0), appendix (1) @keyl (char *) the key to put in @param string (char *) a char array to write the card in @return (success) int fillhd 1 \n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putcard_(char *n, char *keyl, char *valuel); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putminmax_(void) @brief Changes the minmax information to the current value in the header of an open fits table Puts the minimum and maximum information for each column in the table as it is tracked actually to the header. @return (success) int putminmax_; 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putminmax_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_fopen(char *filename, int next, char mode, char hheader) @brief Opens a table fits file for ftstab use Depending on the stage of the information that has already been acquired, this function acts differently. The basic function is to open a stream for reading and writing an ftstab fits table. Mode can be 0, 1, 2, 3, 4. If no file with the given name is present ftstab_fopen will create one, provided no other file is processed (i.e., if ftstab_fopen() has not been called before without calling ftstab_close_() afterwards) and enough information is present (At least one successful call of ftstab_inithd() without calling ftstab_flush_()). If a file with the filename is present, the function will act in four ways: mode 0: "nothing" ftstab_fopen returns 0. mode 1: "overwrite" Try creating a new file overwriting the old one. If this is not possible, return 0 and leave the file untouched. mode 2: "append" If information is already present (call of ftstab_inithd() and subsequent calls of ftstab_fillhd()) the file will be checked against the information present in the file. If the requested extension is not present (see also documentation on the hheader parameter) in the file, the extension will be created, if possible (call of ftstab_inithd() without calling ftstab_flush_()), while then being the last extension of the file, except for a possible history extension that is attached. So, a very high extension number (or an impossible extension number) results in the attachment of the new extension. To load a present extension, the file must contain the same number of columns, the same types and names of columns, the same radii and grid spacings in the same order. If the file doesn't match these criteria, no changes will be applied and a 5 is returned. If it does it will be opened for read and write access. If no information is present (no call of ftstab_inithd() or call of ftstab_flush), the information will be possibly created from the file and the file will be opened. Additional incoming rows will be placed at the end of the file according to fits rules. In case of appending rows to a intermediate extension, follow-up extensions will maybe be overwritten and destroyed, destroying the file. mode 3: "append enforce write" acts like "append", with the additive that in the case of a mismatch betweeen a present description of the table and the file content, the file will be destroyed and a new file will be created. mode 4: "append enforce" acts like "append", with the additive that in the case of a mismatch betweeen a present description of the table and the extension header content, the file information following the extension adressed (except maybe a history header) will be destroyed and a new extension will be created at the requested place. There is the possibility of a history header to append to the file. Aswell, a history header could already be existent at the end of a file to open. The keyword hheader controls how to behave if a history header (an image extension with naxis=0 and no attached data) is present. If 0, the last extension will be treated like a normal extension. If not 0, ftstab_fopen updates the header with possible information in the present history header (if none was created, nothing will be updated) and stores it as the history header. Furthermore ftstab_fopen acts as if the last header was not present. For the write access to tables, the functionality that enlarges the content of an item, header, or table, is disabled, if the resulting fits file is endangered to be corrupted. If the opened extension is not the last one, the table and the header can be changed, but no items can be added. If the opened extension is the last one (minus possibly a history header), the header will be blocked if there is data in the table, while the table can be enlarged, otherways, everything is writeable. @param filename (char *) The filename @param next (int) The extension number @param mode (char) Mode to start ftstab_fopen with. @param hheader (char) Treatment of a history header @return (success) int ftstab_fopen_: 0\n (error) 1: stream already opened with a file\n 2: Couldn't open a new file: No header descriptor object or not possible\n 3: Couldn't overwrite a file: No header descriptor object or not possible\n 4: None of the accepted modes was given\n 5: mode2, but there are inconsistencies: No real table object adressed or wrong column number\n 6: mode2, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong\n 7: mode2, but there are inconsistencies: table does have ftstab format but doesn't comply with the header descriptor information\n 8: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 9: mode3, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong and overwriting failed\n 10: mode3, but there are inconsistencies: table does have ftstab format but doesn't comply with the header descriptor information and overwriting failed\n 11: mode3, but there are inconsistencies: No real table object adressed or wrong column number and overwriting failed\n 12: mode3, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong, no further information was given\n 13: mode3: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 14: mode3, but there are inconsistencies: No real table object adressed or wrong column number and no further information\n 15: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 16: mode4, but there are inconsistencies: table doesn't have ftstab format and overwriting failed : Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 17: mode4, but there are inconsistencies: table does have ftstab format but doesn't comply with the header descriptor information and overwriting failed : Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 18: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 19: mode4, but there are inconsistencies: No real table object adressed or wrong column number and no further information\n 20: mode4, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong, no further information was given\n 21: mode4: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 22: No header item description table could be allocated, sure sign for not enough memory */ /* ------------------------------------------------------------ */ int ftstab_fopen(char *filename, int next, char mode, char hheader); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_fopen_(char *filename, int *next, char *mode, char *hheader) @brief Opens a table fits file for ftstab use Depending on the stage of the information that has already been acquired, this function acts differently. The basic function is to open a stream for reading and writing an ftstab fits table. Mode can be 0, 1, 2, 3, 4. If no file with the given name is present ftstab_fopen will create one, provided no other file is processed (i.e., if ftstab_fopen() has not been called before without calling ftstab_close_() afterwards) and enough information is present (At least one successful call of ftstab_inithd() without calling ftstab_flush_()). If a file with the filename is present, the function will act in four ways: mode 0: "nothing" ftstab_fopen returns 0. mode 1: "overwrite" Try creating a new file overwriting the old one. If this is not possible, return 0 and leave the file untouched. mode 2: "append" If information is already present (call of ftstab_inithd() and subsequent calls of ftstab_fillhd()) the file will be checked against the information present in the file. If the requested extension is not present (see also documentation on the hheader parameter) in the file, the extension will be created, if possible (call of ftstab_inithd() without calling ftstab_flush_()), while then being the last extension of the file, except for a possible history extension that is attached. So, a very high extension number (or an impossible extension number) results in the attachment of the new extension. To load a present extension, the file must contain the same number of columns, the same types and names of columns, the same radii and grid spacings in the same order. If the file doesn't match these criteria, no changes will be applied and a 5 is returned. If it does it will be opened for read and write access. If no information is present (no call of ftstab_inithd() or call of ftstab_flush), the information will be possibly created from the file and the file will be opened. Additional incoming rows will be placed at the end of the file according to fits rules. In case of appending rows to a intermediate extension, follow-up extensions will maybe be overwritten and destroyed, destroying the file. mode 3: "append enforce write" acts like "append", with the additive that in the case of a mismatch betweeen a present description of the table and the file content, the file will be destroyed and a new file will be created. mode 4: "append enforce" acts like "append", with the additive that in the case of a mismatch betweeen a present description of the table and the extension header content, the file information following the extension adressed (except maybe a history header) will be destroyed and a new extension will be created at the requested place. There is the possibility of a history header to append to the file. Aswell, a history header could already be existent at the end of a file to open. The keyword hheader controls how to behave if a history header (an image extension with naxis=0 and no attached data) is present. If 0, the last extension will be treated like a normal extension. If not 0, ftstab_fopen updates the header with possible information in the present history header (if none was created, nothing will be updated) and stores it as the history header. Furthermore ftstab_fopen acts as if the last header was not present. For the write access to tables, the functionality that enlarges the content of an item, header, or table, is disabled, if the resulting fits file is endangered to be corrupted. If the opened extension is not the last one, the table and the header can be changed, but no items can be added. If the opened extension is the last one (minus possibly a history header), the header will be blocked if there is data in the table, while the table can be enlarged, otherways, everything is writeable. @param filename (char *) The filename @param next (int *) The extension number @param mode (char *) Mode to start ftstab_fopen with. @param hheader (char *) Treatment of a history header @return (success) int ftstab_fopen_: 0\n (error) 1: stream already opened with a file or file present with mode 0\n 2: Couldn't open a new file: No header descriptor object or not possible\n 3: Couldn't overwrite a file: No header descriptor object or not possible\n 4: None of the accepted modes was given\n 5: mode2, but there are inconsistencies: No real table object adressed or wrong column number\n 6: mode2, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong\n 7: mode2, but there are inconsistencies: table does have ftstab format but doesn't comply with the header descriptor information\n 8: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 9: mode3, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong and overwriting failed\n 10: mode3, but there are inconsistencies: table does have ftstab format but doesn't comply with the header descriptor information and overwriting failed\n 11: mode3, but there are inconsistencies: No real table object adressed or wrong column number and overwriting failed\n 12: mode3, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong, no further information was given\n 13: mode3: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 14: mode3, but there are inconsistencies: No real table object adressed or wrong column number and no further information\n 15: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 16: mode4, but there are inconsistencies: table doesn't have ftstab format and overwriting failed : Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 17: mode4, but there are inconsistencies: table does have ftstab format but doesn't comply with the header descriptor information and overwriting failed : Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 18: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 19: mode4, but there are inconsistencies: No real table object adressed or wrong column number and no further information\n 20: mode4, but there are inconsistencies: table doesn't have ftstab format or NAXIS1 (bytes per row) wrong, no further information was given\n 21: mode4: Allocation error or error opening the file: Some present information can be destroyed, ftsttab_flush and filling everything again recommended\n 22: No header item description table could be allocated, sure sign for not enough memory */ /* ------------------------------------------------------------ */ int ftstab_fopen_(char *filename, int *next, char *mode, char *hheader); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_appendrow_(double *row) @brief Append a row to an open table Appends a row in binary format to an opened table (initialisation be opencolfts) that is private to the module. All input values are double format while they will be stored in the user predefined numerical type. The specification of the content of a column is done by fillhd or fillhd_ respectively. The user has to care that row contains the number of fields specified by initftstbl. The function does not work if the table is blocked. @param row (double *) A double array with the contents of the row @return (success) int appendrow_; 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_appendrow_(double *row); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putrow(long rownumber, double *row) @brief Change a row in an open table Changes a row in binary format in an opened table (initialisation by opencolfts) that is private to the module. All input values are double format while they will be stored as the user predefined type. The specification of the content of a column is done by fillhd or fillhd_ respectively. The user has to care that row contains the number of fields specified by initftstbl. @param row (double *) A double array with the contents of the row @param rownumber (long) The number of the row to be changed @return (success) int putrow: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putrow(long rownumber, double *row); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putval(long rownumber, double *row, double value) @brief Change a row in an open table Changes a value in an opened table (initialisation by opencolfts) that is private to the module. All input values are double format while they will be stored as the user predefined type. The specification of the content of a column is done by fillhd or fillhd_ respectively. The user has to care that row contains the number of fields specified by initftstbl. @param value (double) The new value @param rownumber (long) The number of the row to be changed @param colnumber (int) The number of the column to be changed @return (success) int putval; 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putval(long rownumber, int colnumber, double value); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putval_(long *rownumber, int *colnumber, double *value) @brief Change a row in an open table Changes a value in an opened table (initialisation by opencolfts) that is private to the module. All input values are double format while they will be stored as the user predefined type. The specification of the content of a column is done by fillhd or fillhd_ respectively. The user has to care that row contains the number of fields specified by initftstbl. @param value (double *) The new value @param rownumber (long *) The number of the row to be changed @param colnumber (int *) The number of the column to be changed @return (success) int putrow_; 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putval_(long *rownumber, int *colnumber, double *value); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_putrow_(long *rownumber, double *row) @brief Change a row in an open table Changes a row in binary format in an opened table (initialisation by opencolfts) that is private to the module. All input values are double format while they will be stored as the user predefined type. The specification of the content of a column is done by fillhd or fillhd_ respectively. The user has to care that row contains the number of fields specified by initftstbl. @param row (double *) A double array with the contents of the row @param rownumber (long *) The number of the row to be changed @return (success) int putrow_; 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_putrow_(long *rownumber, double *row); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_row(long rownr, double *row) @brief Get a whole row into an array A row is put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_dblarr(). @param rownr (long) The number of desired row, starting with 1 @param buffer(double *) An array large enough to contain ftstab_get_colnr_() numbers @return (success) int ftstab_get_row_: Number of columns (error) 0 (if the row dowsn't exist) */ /* ------------------------------------------------------------ */ int ftstab_get_row(long rownr, double *row); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_row_(long *rownr, double *array) @brief Get a whole row into an array A row is put into an array that has to be of length ftstab_get_colnr_(), as can be allocated using ftstab_get_dblarr(). @param rownr (long) The number of desired row, starting with 1 @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return (success) int ftstab_get_row_: Number of columns (error) 0 (if the row dowsn't exist) */ /* ------------------------------------------------------------ */ int ftstab_get_row_(long *rownr, double *array); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_value(long rownr, int colnr, double *val) @brief Get a value of a single field as double Put the value of the field specified by rownr and colnr into val. @param rownr (long) The number of desired row, starting with 1 @param colnr (long) The number of desired column, starting with 1 @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return (success) int ftstab_get_value_: Number of columns (error) 0 (if the row or column doesn't exist) */ /* ------------------------------------------------------------ */ int ftstab_get_value(long rownr, int colnr, double *val); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_value_(long *rownr, int *colnr, double *val) @brief Get a value of a single field as double Put the value of the field specified by rownr and colnr into val. @param rownr (long *) The number of desired row, starting with 1 @param colnr (long *) The number of desired column, starting with 1 @param array (double *) An array large enough to contain ftstab_get_colnr_() numbers @return (success) int ftstab_get_value_: Number of columns (error) 0 (if the row or column doesn't exist) */ /* ------------------------------------------------------------ */ int ftstab_get_value_(long *rownr, int *colnr, double *val); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_heapsort(int column, long start, long end) @brief Sorts ascending the rows in-between begin and end depending on the value of column This function works directly on the stream and may be slow. On the other hand, memory requirements are not given and handed to the operating system. The row and column number starting with 1. @param column (int) The column to sort @param start (long) The start row @param end (long) The end row @return (success) int ftstab_heapsort: 1 (error) 0 in case of wrong input */ /* ------------------------------------------------------------ */ int ftstab_heapsort(int column, long start, long end); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_heapsort_(int *column, long *start, long *end) @brief Sorts ascending the rows in-between begin and end depending on the value of column This function works directly on the stream and may be slow. On the other hand, memory requirements are not given and handed to the operating system. The row and column number starting with 1. @param column (int *) The column to sort @param start (long *) The start row @param end (long *) The end row @return (success) int ftstab_heapsort: 1 (error) 0 in case of wrong input */ /* ------------------------------------------------------------ */ int ftstab_heapsort_(int *column, long *start, long *end); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_histogram(char *filename, int column, long startrow, long endrow, double min, double max, long bins, double delta, int repet) @brief Makes a fits image containing a histogram of a column The function will try to open the file filename and checks if it is a fits file. If it is not, the file will be deleted and an empty file with the name will be opened. If it is, the function checks whether the last header in the file is a history header (An empty image with no axes), saves it locally and deletes it if it is. Then, an fits image is attached to the file that contains a histogram in the following way: Along one axis the image contains the histogram of the column with the number column, this axis will be repeated along the other axis repet times (e.g. for access with the Karma software chose 2), such that more than repet = 1 is in principle not necessary. The histogram will be carried out between startrow and endrow and takes into account only values in-between min and max. If startrow > endrow, the whole table will be taken into account. If min > max, then the minimum and the maximum of the specified rows are calculated and taken as min and max. If bins is specified, then the length of a bin delta is calculated from bins and min and max, min-max being 0 requires a delta to be set. If bins = 0 then the number of the bins is calculated from the bin size delta. If bins = 0 and delta = 0 bins is set to 100. With a call of this function the table will be rearranged if successful and the min and max values will be changed in any case. The user has to be aware of the factand take either precautions or has to be able to rearrange the table properly with the access functions in this module. CAUTION: In this function the header will be created in a way that the scaling and the zero value of the item are taken into account. If you don't want this, set it to 1.0, or 0.0 respectively with ftstab_hdladditem(). @param filename (char *) The output fits file @param column (int) The column number of the column to make the histogram of (start with 1) @param startrow (long) The start row number (start with 1) @param endrow (long) The end row number @param min (double) The minimum value to take into account @param max (double) The maximum value to take into account @param bins (long) The number of bins @param delta (double) The bin size @param repeti (int) The number of repetitions of the histogram along the second axis. @return (success) int ftstab_histogram: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_histogram(char *filename, int column, long startrow, long endrow, double min, double max, long bins, double delta, int repet); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_histogram_2d(char *filename, long startrow1, long endrow1, int column1, double min1, double max1, long bins1, double delta1, int column2, double min2, double max2, long bins2, double delta2) @brief Makes a fits image containing a 2d histogram of a column The function will try to open the file filename and checks if it is a fits file. If it is not, the file will be deleted and an empty file with the name will be opened. If it is, the function checks whether the last header in the file is a history header (An empty image with no axes), saves it locally and deletes it if it is. Then, an fits image is attached to the file that contains a histogram in the following way: Along axis1 and axis2 the image contains the histogram of column1 and column2. The histogram will be carried out between startrow and endrow and takes into account only values in-between min1/2 and max1/2. If startrow > endrow, the whole table will be taken into account. If min1/2 > max1/2, then the minimum and the maximum of the specified rows are calculated and taken as min and max. If bins is specified, then the length of a bin delta is calculated from bins and min and max, min1/2-max1/2 being 0 requires a delta1/2 to be set.. If bins1/2 = 0 then the number of the bins is calculated from the bin size delta1/2. If bins1/2 = 0 and delta1/2 = 0 bins is set to 100. With a call of this function the table will be rearranged if successful and the min and max values will be changed in any case. The user has to be aware of the fact and take either precautions or has to be able to rearrange the table properly with the access functions in this module. CAUTION: In this function the header will be created in a way that the scaling and the zero value of the item are taken into account. If you don't want this, set it to 1.0, or 0.0 respectively with ftstab_hdladditem(). @param filename (char *) The output fits file @param startrow (long) The start row number (start with 1) @param endrow (long) The end row number @param column1 (int) The column number of the first column to make the histogram of (start with 1) @param min1 (double) The minimum value to take into account for first column @param max1 (double) The maximum value to take into account for first column @param bins1 (long) The number of bins for first column @param delta1 (double) The bin size for first column @param column2 (int) The column number of the second column to make the histogram of (start with 1) @param min2 (double) The minimum value to take into account for second column @param max2 (double) The maximum value to take into account for second column @param bins2 (long) The number of bins for second column @param delta2 (double) The bin size for second column @return (success) int ftstab_histogram: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_histogram_2d(char *filename, long startrow1, long endrow1, int column1, double min1, double max1, long bins1, double delta1, int column2, double min2, double max2, long bins2, double delta2); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_histogram_(char *filename, int *column, long *startrow, long *endrow, double *min, double *max, long *bins, double *delta, int *repet) @brief Makes a fits image containing a histogram of a column The function will try to open the file filename and checks if it is a fits file. If it is not, the file will be deleted and an empty file with the name will be opened. If it is, the function checks whether the last header in the file is a history header (An empty image with no axes), saves it locally and deletes it if it is. Then, an fits image is attached to the file that contains a histogram in the following way: Along one axis the image contains the histogram of the column with the number column, this axis will be repeated along the other axis repet times (e.g. for access with the Karma software chose 2), such that more than repet = 1 is in principle not necessary. The histogram will be carried out between startrow and endrow and takes into account only values in-between min and max. If startrow > endrow, the whole table will be taken into account. If min > max, then the minimum and the maximum of the specified rows are calculated and taken as min and max. If bins is specified, then the length of a bin delta is calculated from bins and min and max, min-max being 0 requires a delta to be set. If bins = 0 then the number of the bins is calculated from the bin size delta. If bins = 0 and delta = 0 bins is set to 100. With a call of this function the table will be rearranged if successful and the min and max values will be changed in any case. The user has to be aware of the fact and take either precautions or has to be able to rearrange the table properly with the access functions in this module. CAUTION: In this function the header will be created in a way that the scaling and the zero value of the item are taken into account. If you don't want this, set it to 1.0, or 0.0 respectively with ftstab_hdladditem(). @param filename (char *) The output fits file @param column (int *) The column number of the column to make the histogram of (start with 1) @param startrow (long *) The start row number (start with 1) @param endrow (long *) The end row number @param min (double *) The minimum value to take into account @param max (double *) The maximum value to take into account @param bins (long *) The number of bins @param delta (double *) The bin size @param repeti (int *) The number of repetitions of the histogram along the second axis. @return (success) int ftstab_histogram: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_histogram_(char *filename, int *column, long *startrow, long *endrow, double *min, double *max, long *bins, double *delta, int *repet); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_histogram_2d_(char *filename, long *startrow1, long *endrow1, int *column1, double *min1, double *max1, long *bins1, double *delta1, int *column2, double *min2, double *max2, long *bins2, double *delta2) @brief Makes a fits image containing a 2d histogram of a column The function will try to open the file filename and checks if it is a fits file. If it is not, the file will be deleted and an empty file with the name will be opened. If it is, the function checks whether the last header in the file is a history header (An empty image with no axes), saves it locally and deletes it if it is. Then, an fits image is attached to the file that contains a histogram in the following way: Along axis1 and axis2 the image contains the histogram of column1 and column2. The histogram will be carried out between startrow and endrow and takes into account only values in-between min1/2 and max1/2. If startrow > endrow, the whole table will be taken into account. If min1/2 > max1/2, then the minimum and the maximum of the specified rows are calculated and taken as min and max. If bins is specified, then the length of a bin delta is calculated from bins and min and max, min1/2-max1/2 being 0 requires a delta1/2 to be set.. If bins1/2 = 0 then the number of the bins is calculated from the bin size delta1/2. If bins1/2 = 0 and delta1/2 = 0 bins is set to 100. With a call of this function the table will be rearranged if successful and the min and max values will be changed in any case. The user has to be aware of the fact and take either precautions or has to be able to rearrange the table properly with the access functions in this module. CAUTION: In this function the header will be created in a way that the scaling and the zero value of the item are taken into account. If you don't want this, set it to 1.0, or 0.0 respectively with ftstab_hdladditem(). @param filename (char *) The output fits file @param startrow (long *) The start row number (start with 1) @param endrow (long *) The end row number @param column1 (int *) The column number of the first column to make the histogram of (start with 1) @param min1 (double *) The minimum value to take into account for first column @param max1 (double *) The maximum value to take into account for first column @param bins1 (long *) The number of bins for first column @param delta1 (double *) The bin size for first column @param column2 (int *) The column number of the second column to make the histogram of (start with 1) @param min2 (double *) The minimum value to take into account for second column @param max2 (double *) The maximum value to take into account for second column @param bins2 (long *) The number of bins for second column @param delta2 (double *) The bin size for second column @return (success) int ftstab_histogram_: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_histogram_2d_(char *filename, long *startrow1, long *endrow1, int *column1, double *min1, double *max1, long *bins1, double *delta1, int *column2, double *min2, double *max2, long *bins2, double *delta2); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn long ftstab_get_rownr_(void) @brief Get the number of rows @return long ftstab_get_rownr_: Number of rows */ /* ------------------------------------------------------------ */ long ftstab_get_rownr_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_colnr_(void) @brief Get the number of columns @return int ftstab_getcolnr_: Number of columns */ /* ------------------------------------------------------------ */ int ftstab_get_colnr_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_extnr_(void) @brief Get the number of the current extension Returns the extension number of the extension in procession. @return (success) int ftstab_get_extnr_: Extension number\n (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_get_extnr_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_close_(void) @brief Puts the open stream containing a table in a final condition This function appends a number of zeros to the private stream making it fits conforming. @return (success) int ftstab_close_: 1 (error) 0 */ /* ------------------------------------------------------------ */ int ftstab_close_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn void ftstab_flush_(void) @brief Closes the table stream and destroys all information Closes the table stream and destroys all information. Puts the module in a status like before the first call. @return void */ /* ------------------------------------------------------------ */ void ftstab_flush_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_deleterest_(void) @brief Delete all subsequent extensions All subsequent extensions are deleted from the file and the permissions to attach items (table or header) are adjusted. An hheader will still be attached, if present. @return (success) int ftstab_copytohere: 1 (error) 0 in case of wrong input */ /* ------------------------------------------------------------ */ int ftstab_deleterest_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_copytohere_(char *newfilename) @brief Make a copy of the file in process to the current extension Will output a file with the name newfilename that is identical with the file that would be put out if ftstab_close() is called, except that all extensions after the current one are deleted. However if an hheader is present, it will be attached to the file. @param newfilename (char *) The filename of the file to copy to. @return (success) int ftstab_copytohere: 1 (error) 0 in case of wrong input */ /* ------------------------------------------------------------ */ int ftstab_copytohere_(char *newfilename); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int *ftstab_get_intarr(void) @brief Delivers an int array of the length of the column number The array has to be freed with free @return (success) int *ftstab_get_intarr: Number of columns\n (error) NULL */ /* ------------------------------------------------------------ */ int *ftstab_get_intarr(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int *ftstab_get_dblarr(void) @brief Delivers a double array of the length of the column number The array has to be freed with free @return (success) int *ftstab_get_dblarr: Number of columns (error) NULL */ /* ------------------------------------------------------------ */ double *ftstab_get_dblarr(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn long ftstab_get_curlength_(void) @brief Returns the current length of the table @return long ftstab_get_curlength_: Current length of table */ /* ------------------------------------------------------------ */ long ftstab_get_curlength_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */ /** @fn int ftstab_get_byteperow_(void) @brief Returns the length of a row @return long ftstab_get_byteperow_: Current length of a row */ /* ------------------------------------------------------------ */ int ftstab_get_byteperow_(void); /* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ $Log: ftstab.h,v $ Revision 1.28 2009/05/26 07:56:39 jozsa Left work Revision 1.27 2007/08/22 15:58:34 gjozsa Left work Revision 1.26 2005/03/25 18:17:19 gjozsa Left work Revision 1.25 2005/02/21 11:23:44 gjozsa Added the recover functionality to checkin, now finished until some additional thing is needed Revision 1.23 2005/02/21 09:44:24 gjozsa Stable, tested, and nearly final version, added histogram functions Revision 1.22 2005/02/16 18:55:32 gjozsa Left work Revision 1.21 2005/02/16 13:30:26 gjozsa Largely debugged and tested, added histogram function Revision 1.20 2005/02/15 18:00:34 gjozsa Left work Revision 1.19 2005/02/15 15:37:11 gjozsa Left work Revision 1.18 2005/02/11 17:37:13 gjozsa Left work Revision 1.17 2005/02/10 17:57:42 gjozsa Left work Revision 1.16 2005/02/10 12:29:09 gjozsa Implemented and tested heapsort Revision 1.15 2005/02/09 17:52:19 gjozsa Left work Revision 1.14 2005/02/08 11:37:14 gjozsa Added and tested putval and putrow functions Revision 1.13 2005/02/07 16:05:49 gjozsa Quite tested version, added lots of functionality Revision 1.12 2005/02/04 18:01:12 gjozsa Left work Revision 1.11 2005/02/03 17:23:55 gjozsa Left work Revision 1.9 2005/02/01 17:45:53 gjozsa Left work Revision 1.8 2005/02/01 14:51:20 gjozsa Left work Revision 1.7 2005/01/28 17:29:23 gjozsa Tested and debugged Revision 1.6 2005/01/27 17:44:43 gjozsa Left work Revision 1.5 2005/01/26 17:26:14 gjozsa Left work Revision 1.4 2005/01/26 17:10:04 gjozsa First stable and tested version Revision 1.3 2005/01/24 15:48:45 gjozsa Left work Revision 1.1 2005/01/17 12:16:04 gjozsa added to cvs control ------------------------------------------------------------ */ /* Include guard */ #endif
36.34347
259
0.615527
[ "object" ]
187b89db2a02e1c7ba3b686e9b262e62403027d7
1,441
h
C
src/include/storage/table_factory.h
17zhangw/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
[ "Apache-2.0" ]
3
2018-01-08T01:06:17.000Z
2019-06-17T23:14:36.000Z
src/include/storage/table_factory.h
17zhangw/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
[ "Apache-2.0" ]
1
2017-04-04T17:03:59.000Z
2017-04-04T17:03:59.000Z
src/include/storage/table_factory.h
17zhangw/peloton
484d76df9344cb5c153a2c361c5d5018912d4cf4
[ "Apache-2.0" ]
3
2018-02-25T23:30:33.000Z
2018-04-08T10:11:42.000Z
//===----------------------------------------------------------------------===// // // Peloton // // table_factory.h // // Identification: src/include/storage/table_factory.h // // Copyright (c) 2015-16, Carnegie Mellon University Database Group // //===----------------------------------------------------------------------===// #pragma once #include <string> #include "catalog/manager.h" #include "common/internal_types.h" #include "storage/data_table.h" #include "storage/temp_table.h" namespace peloton { namespace storage { /** * Magic Table Factory!! */ class TableFactory { public: /** * For a given Schema, instantiate a DataTable object and return it */ static DataTable *GetDataTable(oid_t database_id, oid_t table_id, catalog::Schema *schema, std::string table_name, size_t tuples_per_tile_group_count, bool own_schema, bool adapt_table, bool is_catalog = false, peloton::LayoutType layout_type = peloton::LayoutType::ROW); static TempTable *GetTempTable(catalog::Schema *schema, bool own_schema); /** * For a given table name, drop the table from database */ static bool DropDataTable(oid_t database_oid, oid_t table_oid); }; } // namespace storage } // namespace peloton
28.254902
93
0.539903
[ "object" ]
187c8528c320a700980240a5eee0d65e77eef33d
4,257
h
C
services/audio/stream_factory.h
zipated/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
2,151
2020-04-18T07:31:17.000Z
2022-03-31T08:39:18.000Z
services/audio/stream_factory.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
395
2020-04-18T08:22:18.000Z
2021-12-08T13:04:49.000Z
services/audio/stream_factory.h
cangulcan/src
2b8388091c71e442910a21ada3d97ae8bc1845d3
[ "BSD-3-Clause" ]
338
2020-04-18T08:03:10.000Z
2022-03-29T12:33:22.000Z
// 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 SERVICES_AUDIO_STREAM_FACTORY_H_ #define SERVICES_AUDIO_STREAM_FACTORY_H_ #include <memory> #include <string> #include <vector> #include "base/callback.h" #include "base/containers/flat_set.h" #include "base/containers/unique_ptr_adapters.h" #include "base/macros.h" #include "base/sequence_checker.h" #include "media/mojo/interfaces/audio_logging.mojom.h" #include "media/mojo/interfaces/audio_output_stream.mojom.h" #include "mojo/public/cpp/bindings/binding_set.h" #include "services/audio/group_coordinator.h" #include "services/audio/public/mojom/stream_factory.mojom.h" #include "services/audio/traced_service_ref.h" namespace base { class UnguessableToken; } namespace media { class AudioManager; class AudioParameters; } // namespace media namespace audio { class InputStream; class LocalMuter; class LoopbackStream; class OutputStream; // This class is used to provide the StreamFactory interface. It will typically // be instantiated when needed and remain for the lifetime of the service. // Destructing the factory will also destroy all the streams it has created. // |audio_manager| must outlive the factory. class StreamFactory final : public mojom::StreamFactory { public: explicit StreamFactory(media::AudioManager* audio_manager); ~StreamFactory() final; void Bind(mojom::StreamFactoryRequest request, TracedServiceRef context_ref); // StreamFactory implementation. void CreateInputStream(media::mojom::AudioInputStreamRequest stream_request, media::mojom::AudioInputStreamClientPtr client, media::mojom::AudioInputStreamObserverPtr observer, media::mojom::AudioLogPtr log, const std::string& device_id, const media::AudioParameters& params, uint32_t shared_memory_count, bool enable_agc, mojo::ScopedSharedBufferHandle key_press_count_buffer, CreateInputStreamCallback created_callback) final; void AssociateInputAndOutputForAec( const base::UnguessableToken& input_stream_id, const std::string& output_device_id) final; void CreateOutputStream( media::mojom::AudioOutputStreamRequest stream_request, media::mojom::AudioOutputStreamObserverAssociatedPtrInfo observer_info, media::mojom::AudioLogPtr log, const std::string& output_device_id, const media::AudioParameters& params, const base::UnguessableToken& group_id, CreateOutputStreamCallback created_callback) final; void BindMuter(mojom::LocalMuterAssociatedRequest request, const base::UnguessableToken& group_id) final; void CreateLoopbackStream( media::mojom::AudioInputStreamRequest stream_request, media::mojom::AudioInputStreamClientPtr client, media::mojom::AudioInputStreamObserverPtr observer, const media::AudioParameters& params, uint32_t shared_memory_count, const base::UnguessableToken& group_id, CreateLoopbackStreamCallback created_callback) final; private: using InputStreamSet = base::flat_set<std::unique_ptr<InputStream>, base::UniquePtrComparator>; using OutputStreamSet = base::flat_set<std::unique_ptr<OutputStream>, base::UniquePtrComparator>; void DestroyInputStream(InputStream* stream); void DestroyOutputStream(OutputStream* stream); void DestroyMuter(LocalMuter* muter); void DestroyLoopbackStream(LoopbackStream* stream); SEQUENCE_CHECKER(owning_sequence_); media::AudioManager* const audio_manager_; mojo::BindingSet<mojom::StreamFactory, TracedServiceRef> bindings_; // Order of the following members is important for a clean shutdown. GroupCoordinator coordinator_; std::vector<std::unique_ptr<LocalMuter>> muters_; std::vector<std::unique_ptr<LoopbackStream>> loopback_streams_; InputStreamSet input_streams_; OutputStreamSet output_streams_; DISALLOW_COPY_AND_ASSIGN(StreamFactory); }; } // namespace audio #endif // SERVICES_AUDIO_STREAM_FACTORY_H_
36.698276
79
0.748179
[ "vector" ]
187cb07747e3c7617a0c0de97f0bd31e4948c53d
2,306
h
C
src/ast/factory.h
eokas/eokas-lang
e1d98acfbbc6e696993e945dead0e7900f785198
[ "MIT" ]
3
2021-07-06T03:49:39.000Z
2021-10-09T09:55:56.000Z
src/ast/factory.h
eokas/eokas
e1d98acfbbc6e696993e945dead0e7900f785198
[ "MIT" ]
null
null
null
src/ast/factory.h
eokas/eokas
e1d98acfbbc6e696993e945dead0e7900f785198
[ "MIT" ]
1
2021-09-09T07:35:19.000Z
2021-09-09T07:35:19.000Z
#ifndef _EOKAS_AST_FACTORY_H_ #define _EOKAS_AST_FACTORY_H_ #include "header.h" namespace eokas { class ast_factory_t { public: ast_factory_t(); virtual ~ast_factory_t(); public: ast_type_ref_t* create_type_ref(ast_node_t* parent); ast_type_array_t* create_type_array(ast_node_t* parent); ast_type_generic_t* create_type_generic(ast_node_t* parent); ast_expr_trinary_t* create_expr_trinary(ast_node_t* parent); ast_expr_binary_type_t* create_expr_binary_type(ast_node_t* parent); ast_expr_binary_value_t* create_expr_binary_value(ast_node_t* parent); ast_expr_unary_t* create_expr_unary(ast_node_t* parent); ast_expr_int_t* create_expr_int(ast_node_t* parent); ast_expr_float_t* create_expr_float(ast_node_t* parent); ast_expr_bool_t* create_expr_bool(ast_node_t* parent); ast_expr_string_t* create_expr_string(ast_node_t* parent); ast_expr_symbol_ref_t* create_expr_symbol_ref(ast_node_t* parent); ast_expr_func_def_t* create_expr_func_def(ast_node_t* parent); ast_expr_func_ref_t* create_expr_func_ref(ast_node_t* parent); ast_expr_array_def_t* create_expr_array_def(ast_node_t* parent); ast_expr_index_ref_t* create_expr_index_ref(ast_node_t* parent); ast_expr_object_def_t* create_expr_object_def(ast_node_t* parent); ast_expr_object_ref_t* create_expr_object_ref(ast_node_t* parent); ast_expr_module_ref_t* create_expr_module_ref(ast_node_t* parent); ast_stmt_struct_member_t* create_stmt_struct_member(ast_node_t* parent); ast_stmt_struct_def_t* create_stmt_struct_def(ast_node_t* parent); ast_stmt_proc_def_t* create_stmt_proc_def(ast_node_t* parent); ast_stmt_symbol_def_t* create_stmt_symbol_def(ast_node_t* parent); ast_stmt_break_t* create_stmt_break(ast_node_t* parent); ast_stmt_continue_t* create_stmt_continue(ast_node_t* parent); ast_stmt_return_t* create_stmt_return(ast_node_t* parent); ast_stmt_if_t* create_stmt_if(ast_node_t* parent); ast_stmt_while_t* create_stmt_while(ast_node_t* parent); ast_stmt_for_t* create_stmt_for(ast_node_t* parent); ast_stmt_block_t* create_stmt_block(ast_node_t* parent); ast_stmt_call_t* create_stmt_call(ast_node_t* parent); ast_stmt_assign_t* create_stmt_assign(ast_node_t* parent); private: std::vector<ast_node_t*> nodes; }; } #endif //_EOKAS_AST_FACTORY_H_
40.45614
74
0.825672
[ "vector" ]
9b86a507d6787b5446044234c23b6dec0a0dc539
49,920
c
C
drivers/video/ms/3dlabs/perm2/disp/fillpath.c
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
drivers/video/ms/3dlabs/perm2/disp/fillpath.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
drivers/video/ms/3dlabs/perm2/disp/fillpath.c
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
/******************************Module*Header**********************************\ * * ******************* * * GDI SAMPLE CODE * * ******************* * * Module Name: fillpath.c * * Copyright (c) 1994-1998 3Dlabs Inc. Ltd. All rights reserved. * Copyright (c) 1995-1999 Microsoft Corporation. All rights reserved. \*****************************************************************************/ // LATER identify convex polygons and special-case? // LATER identify vertical edges and special-case? // LATER move pointed-to variables into automatics in search loops // LATER punt to the engine with segmented framebuffer callbacks // LATER handle complex clipping // LATER coalesce rectangles #include "precomp.h" #include "log.h" #include "gdi.h" #include "clip.h" #define ALLOC_TAG ALLOC_TAG_IF2P //-----------------------------Public*Routine---------------------------------- // // DrvFillPath // // This function fills the specified path with the specified brush and ROP. // This function detects single convex polygons, and will call to separate // faster convex polygon code for those cases. This routine also detects // polygons that are really rectangles, and handles those separately as well. // // Parameters // pso---------Points to a SURFOBJ structure that defines the surface on which // to draw. // ppo---------Points to a PATHOBJ structure that defines the path to be filled // The PATHOBJ_Xxx service routines are provided to enumerate the // lines, Bezier curves, and other data that make up the path. // pco---------Points to a CLIPOBJ structure. The CLIPOBJ_Xxx service routines // are provided to enumerate the clip region as a set of rectangles. // pbo---------Points to a BRUSHOBJ structure that defines the pattern and // colors to fill with. // pptlBrushOrg-Points to a POINTL structure that defines the brush origin, // which is used to align the brush pattern on the device. // mix---------Defines the foreground and background raster operations to use // for the brush. // flOptions---Specifies either FP_WINDINGMODE, indicating that a winding mode // fill should be performed, or FP_ALTERNATEMODE, indicating that // an alternating mode fill should be performed. All other flags // should be ignored. // // Return Value // The return value is TRUE if the driver is able to fill the path. If the // path or clipping is too complex to be handled by the driver and should be // handled by GDI, the return value is FALSE, and an error code is not logged. // If the driver encounters an unexpected error, such as not being able to // realize the brush, the return value is DDI_ERROR, and an error code is // logged. // // Comments // GDI can call DrvFillPath to fill a path on a device-managed surface. When // deciding whether to call this function, GDI compares the fill requirements // with the following flags in the flGraphicsCaps member of the DEVINFO // structure: GCAPS_BEZIERS, GCAPS_ALTERNATEFILL, and GCAPS_WINDINGFILL. // // The mix mode defines how the incoming pattern should be mixed with the data // already on the device surface. The MIX data type consists of two ROP2 values // packed into a single ULONG. The low-order byte defines the foreground raster // operation; the next byte defines the background raster operation. // // Multiple polygons in a path cannot be treated as being disjoint; The fill // must consider all the points in the path. That is, if the path contains // multiple polygons, you cannot simply draw one polygon after the other // (unless they don't overlap). // // This function is an optional entry point for the driver. but is recommended // for good performance. To get GDI to call this function, not only do you // have to HOOK_FILLPATH, you have to set GCAPS_ALTERNATEFILL and/or // GCAPS_WINDINGFILL. // //----------------------------------------------------------------------------- BOOL DrvFillPath(SURFOBJ* pso, PATHOBJ* ppo, CLIPOBJ* pco, BRUSHOBJ* pbo, POINTL* pptlBrush, MIX mix, FLONG flOptions) { GFNPB pb; BYTE jClipping; // Clipping type EDGE* pCurrentEdge; EDGE AETHead; // Dummy head/tail node & sentinel for Active Edge // Table EDGE* pAETHead; // Pointer to AETHead EDGE GETHead; // Dummy head/tail node & sentinel for Global Edge // Table EDGE* pGETHead; // Pointer to GETHead EDGE* pFreeEdges = NULL; // Pointer to memory free for use to store edges ULONG ulNumRects; // # of rectangles to draw currently in rectangle // list RECTL* prclRects; // Pointer to start of rectangle draw list INT iCurrentY; // Scan line for which we're currently scanning out // the fill BOOL bMore; PATHDATA pd; RECTL ClipRect; PDev* ppdev; BOOL bRetVal=FALSE; // FALSE until proven TRUE BOOL bMemAlloced=FALSE; // FALSE until proven TRUE FLONG flFirstRecord; POINTFIX* pPtFxTmp; ULONG ulPtFxTmp; POINTFIX aptfxBuf[NUM_BUFFER_POINTS]; ULONG ulRop4; DBG_GDI((6, "DrvFillPath called")); pb.psurfDst = (Surf*)pso->dhsurf; pb.pco = pco; ppdev = pb.psurfDst->ppdev; pb.ppdev = ppdev; pb.ulRop4 = gaMix[mix & 0xFF] | (gaMix[mix >> 8] << 8); ulRop4 = pb.ulRop4; //@@BEGIN_DDKSPLIT #if MULTITHREADED if(pb.ppdev->ulLockCount) { DBG_GDI((MT_LOG_LEVEL, "DrvBitBlt: re-entered! %d", pb.ppdev->ulLockCount)); } EngAcquireSemaphore(pb.ppdev->hsemLock); pb.ppdev->ulLockCount++; #endif //@@END_DDKSPLIT vCheckGdiContext(ppdev); // // There's nothing to do if there are only one or two points // if ( ppo->cCurves <= 2 ) { goto ReturnTrue; } // // Pass the surface off to GDI if it's a device bitmap that we've uploaded // to the system memory. // if ( pb.psurfDst->flags == SF_SM ) { DBG_GDI((1, "dest surface is in system memory. Punt it back")); //@@BEGIN_DDKSPLIT #if MULTITHREADED pb.ppdev->ulLockCount--; EngReleaseSemaphore(pb.ppdev->hsemLock); #endif //@@END_DDKSPLIT return ( EngFillPath(pso, ppo, pco, pbo, pptlBrush, mix, flOptions)); } // // Set up the clipping // if ( pco == (CLIPOBJ*)NULL ) { // // No CLIPOBJ provided, so we don't have to worry about clipping // jClipping = DC_TRIVIAL; } else { // // Use the CLIPOBJ-provided clipping // jClipping = pco->iDComplexity; } // // Now we are sure the surface we are going to draw is in the video memory // // Set default fill as solid fill // pb.pgfn = vSolidFillWithRop; pb.solidColor = 0; //Assume we don't need a pattern pb.prbrush = NULL; // // It is too difficult to determine interaction between // multiple paths, if there is more than one, skip this // PATHOBJ_vEnumStart(ppo); bMore = PATHOBJ_bEnum(ppo, &pd); // // First we need to check if we need a pattern or not // if ( (((ulRop4 & 0xff00) >> 8) != (ulRop4 & 0x00ff)) || ((((ulRop4 >> 4) ^ (ulRop4)) & 0xf0f) != 0) ) { pb.solidColor = pbo->iSolidColor; // // Check to see if it is a non-solid brush (-1) // if ( pbo->iSolidColor == -1 ) { // // Get the driver's realized brush // pb.prbrush = (RBrush*)pbo->pvRbrush; // // If it hasn't been realized, do it // Note: GDI will call DrvRealizeBrsuh to fullfill this task. So the // driver should have this function ready // if ( pb.prbrush == NULL ) { DBG_GDI((7, "Realizing brush")); pb.prbrush = (RBrush*)BRUSHOBJ_pvGetRbrush(pbo); if ( pb.prbrush == NULL ) { // // If we can't realize it, nothing we can do // //@@BEGIN_DDKSPLIT #if MULTITHREADED pb.ppdev->ulLockCount--; EngReleaseSemaphore(pb.ppdev->hsemLock); #endif //@@END_DDKSPLIT return(FALSE); } DBG_GDI((7, "Brsuh realizing done")); }// Realize brush pb.pptlBrush = pptlBrush; // // Check if brush pattern is 1 BPP or not // Note: This is set in DrvRealizeBrush // if ( pb.prbrush->fl & RBRUSH_2COLOR ) { // // 1 BPP pattern. Do a Mono fill // pb.pgfn = vMonoPatFill; } else { // // Pattern is more than 1 BPP. Do color pattern fill // pb.pgfn = vPatFill; DBG_GDI((7, "Skip Fast Fill Color Pattern")); // // P2 can not handle fast filled patterns // goto SkipFastFill; } }// Handle non-solid brush }// Blackness check // // For solid brush, we can use FastFill // if ( bMore ) { // // FastFill only knows how to take a single contiguous buffer // of points. Unfortunately, GDI sometimes hands us paths // that are split over multiple path data records. Convex // figures such as Ellipses, Pies and RoundRects are almost // always given in multiple records. Since probably 90% of // multiple record paths could still be done by FastFill, for // those cases we simply copy the points into a contiguous // buffer... // // First make sure that the entire path would fit in the // temporary buffer, and make sure the path isn't comprised // of more than one subpath: // if ( (ppo->cCurves >= NUM_BUFFER_POINTS) ||(pd.flags & PD_ENDSUBPATH) ) { goto SkipFastFill; } pPtFxTmp = &aptfxBuf[0]; // // Copy one vertex over to pPtFxTmp from pd(path data) // RtlCopyMemory(pPtFxTmp, pd.pptfx, sizeof(POINTFIX) * pd.count); // // Move the memory pointer over to next structure // pPtFxTmp += pd.count; ulPtFxTmp = pd.count; flFirstRecord = pd.flags; // Remember PD_BEGINSUBPATH flag // // Loop to get all the vertex info. After the loop, all the vertex info // will be in array aptfxBuf[] // do { bMore = PATHOBJ_bEnum(ppo, &pd); RtlCopyMemory(pPtFxTmp, pd.pptfx, sizeof(POINTFIX) * pd.count); ulPtFxTmp += pd.count; pPtFxTmp += pd.count; } while ( !(pd.flags & PD_ENDSUBPATH) ); // // Fake up the path data record // pd.pptfx = &aptfxBuf[0]; pd.count = ulPtFxTmp; pd.flags |= flFirstRecord; // // If there's more than one subpath, we can't call FastFill // DBG_GDI((7, "More than one subpath!")); if ( bMore ) { goto SkipFastFill; } }// if ( bMore ) // // Fast polygon fill // if ( bFillPolygon(ppdev, (Surf*)pso->dhsurf, pd.count, pd.pptfx, pb.solidColor, ulRop4, pco, pb.prbrush, pptlBrush) ) { DBG_GDI((7, "Fast Fill Succeeded")); InputBufferFlush(ppdev); //@@BEGIN_DDKSPLIT #if MULTITHREADED pb.ppdev->ulLockCount--; EngReleaseSemaphore(pb.ppdev->hsemLock); #endif //@@END_DDKSPLIT return (TRUE); } SkipFastFill: DBG_GDI((7, "Fast Fill Skipped")); if ( jClipping != DC_TRIVIAL ) { if ( jClipping != DC_RECT ) { DBG_GDI((7, "Complex Clipping")); // // There is complex clipping; let GDI fill the path // goto ReturnFalse; } // // Clip to the clip rectangle // ClipRect = pco->rclBounds; } else { // // So the y-clipping code doesn't do any clipping // We don't blow the values out when we scale up to GIQ // ClipRect.top = (LONG_MIN + 1) / 16; // +1 to avoid compiler problem ClipRect.bottom = LONG_MAX / 16; } // // Set up working storage in the temporary buffer, storage for list of // rectangles to draw // Note: ppdev->pvTmpBuffer is allocated in DrvEnableSurface() in enable.c // The purpose of using ppdev->pvTmpBuffer is to save us from having to // allocate and free the temp space inside high frequency calls. It was // allocated for TMP_BUFFER_SIZE bytes and will be freed in // DrvDeleteSurface() // prclRects = (RECTL*)ppdev->pvTmpBuffer; if ( !bMore ) { RECTL* pTmpRect; INT cPoints = pd.count; // // The count can't be less than three, because we got all the edges // in this subpath, and above we checked that there were at least // three edges // // If the count is four, check to see if the polygon is really a // rectangle since we can really speed that up. We'll also check for // five with the first and last points the same. // // ??? we have already done the memcpy for the pd data. shall we use it // if ( ( cPoints == 4 ) ||( ( cPoints == 5 ) &&(pd.pptfx[0].x == pd.pptfx[4].x) &&(pd.pptfx[0].y == pd.pptfx[4].y) ) ) { // // Get storage space for this temp rectangle // pTmpRect = prclRects; // // We have to start somewhere to assume that most // applications specify the top left point first // We want to check that the first two points are // either vertically or horizontally aligned. If // they are then we check that the last point [3] // is either horizontally or vertically aligned, // and finally that the 3rd point [2] is aligned // with both the first point and the last point // pTmpRect->top = pd.pptfx[0].y - 1 & FIX_MASK; pTmpRect->left = pd.pptfx[0].x - 1 & FIX_MASK; pTmpRect->right = pd.pptfx[1].x - 1 & FIX_MASK; // // Check if the first two points are vertically alligned // if ( pTmpRect->left ^ pTmpRect->right ) { // // The first two points are not vertically alligned // Let's see if these two points are horizontal alligned // if ( pTmpRect->top ^ (pd.pptfx[1].y - 1 & FIX_MASK) ) { // // The first two points are not horizontally alligned // So it is not a rectangle // goto not_rectangle; } // // Up to now, the first two points are horizontally alligned, // but not vertically alligned. We need to check if the first // point vertically alligned with the 4th point // if ( pTmpRect->left ^ (pd.pptfx[3].x - 1 & FIX_MASK) ) { // // The first point is not vertically alligned with the 4th // point either. So this is not a rectangle // goto not_rectangle; } // // Check if the 2nd point and the 3rd point are vertically aligned // if ( pTmpRect->right ^ (pd.pptfx[2].x - 1 & FIX_MASK) ) { // // The 2nd point and the 3rd point are not vertically aligned // So this is not a rectangle // goto not_rectangle; } // // Check to see if the 3rd and 4th points are horizontally // alligned. If not, then it is not a rectangle // pTmpRect->bottom = pd.pptfx[2].y - 1 & FIX_MASK; if ( pTmpRect->bottom ^ (pd.pptfx[3].y - 1 & FIX_MASK) ) { goto not_rectangle; } }// Check if the first two points are vertically alligned else { // // The first two points are vertically alligned. Now we need to // check if the 1st point and the 4th point are horizontally // aligned. If not, then this is not a rectangle // if ( pTmpRect->top ^ (pd.pptfx[3].y - 1 & FIX_MASK) ) { goto not_rectangle; } // // Check if the 2nd point and the 3rd point are horizontally // aligned. If not, then this is not a rectangle // pTmpRect->bottom = pd.pptfx[1].y - 1 & FIX_MASK; if ( pTmpRect->bottom ^ (pd.pptfx[2].y - 1 & FIX_MASK) ) { goto not_rectangle; } // // Check if the 3rd point and the 4th point are vertically // aligned. If not, then this is not a rectangle // pTmpRect->right = pd.pptfx[2].x - 1 & FIX_MASK; if ( pTmpRect->right ^ (pd.pptfx[3].x - 1 & FIX_MASK) ) { goto not_rectangle; } } // // We have a rectangle now. Do some adjustment here first // If the left is greater than the right then // swap them so the blt code won't have problem // if ( pTmpRect->left > pTmpRect->right ) { FIX temp; temp = pTmpRect->left; pTmpRect->left = pTmpRect->right; pTmpRect->right = temp; } else { // // If left == right there's nothing to draw // if ( pTmpRect->left == pTmpRect->right ) { DBG_GDI((7, "Nothing to draw")); goto ReturnTrue; } }// Adjust right and left edge // // Shift the values to get pixel coordinates // pTmpRect->left = (pTmpRect->left >> FIX_SHIFT) + 1; pTmpRect->right = (pTmpRect->right >> FIX_SHIFT) + 1; // // Adjust the top and bottom coordiantes if necessary // if ( pTmpRect->top > pTmpRect->bottom ) { FIX temp; temp = pTmpRect->top; pTmpRect->top = pTmpRect->bottom; pTmpRect->bottom = temp; } else { if ( pTmpRect->top == pTmpRect->bottom ) { DBG_GDI((7, "Nothing to draw")); goto ReturnTrue; } } // // Shift the values to get pixel coordinates // pTmpRect->top = (pTmpRect->top >> FIX_SHIFT) + 1; pTmpRect->bottom = (pTmpRect->bottom >> FIX_SHIFT) + 1; // // Finally, check for clipping // if ( jClipping == DC_RECT ) { // // Clip to the clip rectangle // if ( !bIntersect(pTmpRect, &ClipRect, pTmpRect) ) { // // Totally clipped, nothing to do // DBG_GDI((7, "Nothing to draw")); goto ReturnTrue; } } // // If we get here then the polygon is a rectangle, // set count to 1 and goto bottom to draw it // ulNumRects = 1; goto draw_remaining_rectangles; }// Check to see if it is a rectangle not_rectangle: ; }// if ( !bMore ) // // Do we have enough memory for all the edges? // LATER does cCurves include closure???? // if ( ppo->cCurves > MAX_EDGES ) { // // Try to allocate enough memory // pFreeEdges = (EDGE*)ENGALLOCMEM(0, (ppo->cCurves * sizeof(EDGE)), ALLOC_TAG); if ( pFreeEdges == NULL ) { DBG_GDI((1, "Can't allocate memory for %d edges", ppo->cCurves)); // // Too many edges; let GDI fill the path // goto ReturnFalse; } else { // // Set a flag to indicate that we have allocate the memory so that // we can free it later // bMemAlloced = TRUE; } }// if ( ppo->cCurves > MAX_EDGES ) else { // // If the total number of edges doesn't exceed the MAX_EDGES, then just // use our handy temporary buffer (it's big enough) // pFreeEdges = (EDGE*)((BYTE*)ppdev->pvTmpBuffer + RECT_BYTES); } // // Initialize an empty list of rectangles to fill // ulNumRects = 0; // // Enumerate the path edges and build a Global Edge Table (GET) from them // in YX-sorted order. // pGETHead = &GETHead; if ( !bConstructGET(pGETHead, pFreeEdges, ppo, &pd, bMore, &ClipRect) ) { DBG_GDI((7, "Outside Range")); goto ReturnFalse; // outside GDI's 2**27 range } // // Create an empty AET with the head node also a tail sentinel // pAETHead = &AETHead; AETHead.pNext = pAETHead; // Mark that the AET is empty AETHead.X = 0x7FFFFFFF; // This is greater than any valid X value, so // searches will always terminate // // Top scan of polygon is the top of the first edge we come to // iCurrentY = ((EDGE*)GETHead.pNext)->Y; // // Loop through all the scans in the polygon, adding edges from the GET to // the Active Edge Table (AET) as we come to their starts, and scanning out // the AET at each scan into a rectangle list. Each time it fills up, the // rectangle list is passed to the filling routine, and then once again at // the end if any rectangles remain undrawn. We continue so long as there // are edges to be scanned out // while ( 1 ) { // // Advance the edges in the AET one scan, discarding any that have // reached the end (if there are any edges in the AET) // if ( AETHead.pNext != pAETHead ) { vAdvanceAETEdges(pAETHead); } // // If the AET is empty, done if the GET is empty, else jump ahead to // the next edge in the GET; if the AET isn't empty, re-sort the AET // if ( AETHead.pNext == pAETHead ) { if ( GETHead.pNext == pGETHead ) { // // Done if there are no edges in either the AET or the GET // break; } // // There are no edges in the AET, so jump ahead to the next edge in // the GET // iCurrentY = ((EDGE*)GETHead.pNext)->Y; } else { // // Re-sort the edges in the AET by X coordinate, if there are at // least two edges in the AET (there could be one edge if the // balancing edge hasn't yet been added from the GET) // if ( ((EDGE*)AETHead.pNext)->pNext != pAETHead ) { vXSortAETEdges(pAETHead); } } // // Move any new edges that start on this scan from the GET to the AET; // bother calling only if there's at least one edge to add // if ( ((EDGE*)GETHead.pNext)->Y == iCurrentY ) { vMoveNewEdges(pGETHead, pAETHead, iCurrentY); } // // Scan the AET into rectangles to fill (there's always at least one // edge pair in the AET) // pCurrentEdge = (EDGE*)AETHead.pNext; // point to the first edge do { INT iLeftEdge; // // The left edge of any given edge pair is easy to find; it's just // wherever we happen to be currently // iLeftEdge = pCurrentEdge->X; // // Find the matching right edge according to the current fill rule // if ( (flOptions & FP_WINDINGMODE) != 0 ) { INT iWindingCount; // // Do winding fill; scan across until we've found equal numbers // of up and down edges // iWindingCount = pCurrentEdge->iWindingDirection; do { pCurrentEdge = (EDGE*)pCurrentEdge->pNext; iWindingCount += pCurrentEdge->iWindingDirection; } while ( iWindingCount != 0 ); } else { // // Odd-even fill; the next edge is the matching right edge // pCurrentEdge = (EDGE*)pCurrentEdge->pNext; } // // See if the resulting span encompasses at least one pixel, and // add it to the list of rectangles to draw if so // if ( iLeftEdge < pCurrentEdge->X ) { // // We've got an edge pair to add to the list to be filled; see // if there's room for one more rectangle // if ( ulNumRects >= MAX_PATH_RECTS ) { // // No more room; draw the rectangles in the list and reset // it to empty // pb.lNumRects = ulNumRects; pb.pRects = prclRects; pb.pgfn(&pb); // // Reset the list to empty // ulNumRects = 0; } // // Add the rectangle representing the current edge pair // if ( jClipping == DC_RECT ) { // // Clipped // Clip to left // prclRects[ulNumRects].left = max(iLeftEdge, ClipRect.left); // // Clip to right // prclRects[ulNumRects].right = min(pCurrentEdge->X, ClipRect.right); // // Draw only if not fully clipped // if ( prclRects[ulNumRects].left < prclRects[ulNumRects].right ) { prclRects[ulNumRects].top = iCurrentY; prclRects[ulNumRects].bottom = iCurrentY + 1; ulNumRects++; } } else { // // Unclipped // prclRects[ulNumRects].top = iCurrentY; prclRects[ulNumRects].bottom = iCurrentY + 1; prclRects[ulNumRects].left = iLeftEdge; prclRects[ulNumRects].right = pCurrentEdge->X; ulNumRects++; } } } while ( (pCurrentEdge = (EDGE*)pCurrentEdge->pNext) != pAETHead ); iCurrentY++; // next scan }// Loop through all the scans in the polygon // // Draw the remaining rectangles, if there are any // draw_remaining_rectangles: if ( ulNumRects > 0 ) { pb.lNumRects = ulNumRects; pb.pRects = prclRects; pb.pgfn(&pb); } ReturnTrue: DBG_GDI((7, "Drawn")); bRetVal = TRUE; // done successfully ReturnFalse: // // bRetVal is originally false. If you jumped to ReturnFalse from somewhere, // then it will remain false, and be returned. // if ( bMemAlloced ) { // // We did allocate memory, so release it // ENGFREEMEM(pFreeEdges); } DBG_GDI((6, "Returning %s", bRetVal ? "True" : "False")); InputBufferFlush(ppdev); //@@BEGIN_DDKSPLIT #if MULTITHREADED pb.ppdev->ulLockCount--; EngReleaseSemaphore(pb.ppdev->hsemLock); #endif //@@END_DDKSPLIT return (bRetVal); }// DrvFillPath() //----------------------------------------------------------------------------- // // void vAdvanceAETEdges(EDGE* pAETHead) // // Advance the edges in the AET to the next scan, dropping any for which we've // done all scans. Assumes there is at least one edge in the AET. // //----------------------------------------------------------------------------- VOID vAdvanceAETEdges(EDGE* pAETHead) { EDGE* pLastEdge; EDGE* pCurrentEdge; pLastEdge = pAETHead; pCurrentEdge = (EDGE*)pLastEdge->pNext; do { // // Count down this edge's remaining scans // if ( --pCurrentEdge->iScansLeft == 0 ) { // // We've done all scans for this edge; drop this edge from the AET // pLastEdge->pNext = pCurrentEdge->pNext; } else { // // Advance the edge's X coordinate for a 1-scan Y advance // Advance by the minimum amount // pCurrentEdge->X += pCurrentEdge->iXWhole; // // Advance the error term and see if we got one extra pixel this // time // pCurrentEdge->iErrorTerm += pCurrentEdge->iErrorAdjustUp; if ( pCurrentEdge->iErrorTerm >= 0 ) { // // The error term turned over, so adjust the error term and // advance the extra pixel // pCurrentEdge->iErrorTerm -= pCurrentEdge->iErrorAdjustDown; pCurrentEdge->X += pCurrentEdge->iXDirection; } pLastEdge = pCurrentEdge; } } while ((pCurrentEdge = (EDGE *)pLastEdge->pNext) != pAETHead); }// vAdvanceAETEdges() //----------------------------------------------------------------------------- // // VOID vXSortAETEdges(EDGE* pAETHead) // // X-sort the AET, because the edges may have moved around relative to // one another when we advanced them. We'll use a multipass bubble // sort, which is actually okay for this application because edges // rarely move relative to one another, so we usually do just one pass. // Also, this makes it easy to keep just a singly-linked list. Assumes there // are at least two edges in the AET. // //----------------------------------------------------------------------------- VOID vXSortAETEdges(EDGE *pAETHead) { BOOL bEdgesSwapped; EDGE* pLastEdge; EDGE* pCurrentEdge; EDGE* pNextEdge; do { bEdgesSwapped = FALSE; pLastEdge = pAETHead; pCurrentEdge = (EDGE *)pLastEdge->pNext; pNextEdge = (EDGE *)pCurrentEdge->pNext; do { if ( pNextEdge->X < pCurrentEdge->X ) { // // Next edge is to the left of the current edge; swap them // pLastEdge->pNext = pNextEdge; pCurrentEdge->pNext = pNextEdge->pNext; pNextEdge->pNext = pCurrentEdge; bEdgesSwapped = TRUE; // // Continue sorting before the edge we just swapped; it might // move farther yet // pCurrentEdge = pNextEdge; } pLastEdge = pCurrentEdge; pCurrentEdge = (EDGE *)pLastEdge->pNext; } while ( (pNextEdge = (EDGE*)pCurrentEdge->pNext) != pAETHead ); } while ( bEdgesSwapped ); }// vXSortAETEdges() //----------------------------------------------------------------------------- // // VOID vMoveNewEdges(EDGE* pGETHead, EDGE* pAETHead, INT iCurrentY) // // Moves all edges that start on the current scan from the GET to the AET in // X-sorted order. Parameters are pointer to head of GET and pointer to dummy // edge at head of AET, plus current scan line. Assumes there's at least one // edge to be moved. // //----------------------------------------------------------------------------- VOID vMoveNewEdges(EDGE* pGETHead, EDGE* pAETHead, INT iCurrentY) { EDGE* pCurrentEdge = pAETHead; EDGE* pGETNext = (EDGE*)pGETHead->pNext; do { // // Scan through the AET until the X-sorted insertion point for this // edge is found. We can continue from where the last search left // off because the edges in the GET are in X sorted order, as is // the AET. The search always terminates because the AET sentinel // is greater than any valid X // while ( pGETNext->X > ((EDGE *)pCurrentEdge->pNext)->X ) { pCurrentEdge = (EDGE*)pCurrentEdge->pNext; } // // We've found the insertion point; add the GET edge to the AET, and // remove it from the GET // pGETHead->pNext = pGETNext->pNext; pGETNext->pNext = pCurrentEdge->pNext; pCurrentEdge->pNext = pGETNext; pCurrentEdge = pGETNext; // continue insertion search for the next // GET edge after the edge we just added pGETNext = (EDGE*)pGETHead->pNext; } while (pGETNext->Y == iCurrentY); }// vMoveNewEdges() //----------------------------------------------------------------------------- // // BOOL (EDGE* pGETHead, EDGE* pAETHead, INT iCurrentY) // // Build the Global Edge Table from the path. There must be enough memory in // the free edge area to hold all edges. The GET is constructed in Y-X order, // and has a head/tail/sentinel node at pGETHead. // //----------------------------------------------------------------------------- BOOL bConstructGET(EDGE* pGETHead, EDGE* pFreeEdges, PATHOBJ* ppo, PATHDATA* pd, BOOL bMore, RECTL* pClipRect) { POINTFIX pfxPathStart; // point that started the current subpath POINTFIX pfxPathPrevious; // point before the current point in a subpath; // starts the current edge // // Create an empty GET with the head node also a tail sentinel // pGETHead->pNext = pGETHead; // mark that the GET is empty pGETHead->Y = 0x7FFFFFFF; // this is greater than any valid Y value, so // Searches will always terminate // // Note: PATHOBJ_vEnumStart is implicitly performed by engine // already and first path is enumerated by the caller // so here we don't need to call it again. // next_subpath: // // Make sure the PATHDATA is not empty (is this necessary)??? // if ( pd->count != 0 ) { // // If first point starts a subpath, remember it as such // and go on to the next point, so we can get an edge // if ( pd->flags & PD_BEGINSUBPATH ) { // // The first point starts the subpath; Remember it // pfxPathStart = *pd->pptfx; // the subpath starts here pfxPathPrevious = *pd->pptfx; // this point starts the next edge pd->pptfx++; // advance to the next point pd->count--; // count off this point } // // Add edges in PATHDATA to GET, in Y-X sorted order // while ( pd->count-- ) { if ( (pFreeEdges = pAddEdgeToGET(pGETHead, pFreeEdges, &pfxPathPrevious, pd->pptfx, pClipRect)) == NULL ) { goto ReturnFalse; } pfxPathPrevious = *pd->pptfx; // current point becomes previous pd->pptfx++; // advance to the next point }// Loop through all the points // // If last point ends the subpath, insert the edge that // connects to first point (is this built in already?) // if ( pd->flags & PD_ENDSUBPATH ) { if ( (pFreeEdges = pAddEdgeToGET(pGETHead, pFreeEdges, &pfxPathPrevious, &pfxPathStart, pClipRect)) == NULL ) { goto ReturnFalse; } } }// if ( pd->count != 0 ) // // The initial loop conditions preclude a do, while or for // if ( bMore ) { bMore = PATHOBJ_bEnum(ppo, pd); goto next_subpath; } return(TRUE); // done successfully ReturnFalse: return(FALSE); // failed }// bConstructGET() //----------------------------------------------------------------------------- // // EDGE* pAddEdgeToGET(EDGE* pGETHead, EDGE* pFreeEdge, POINTFIX* ppfxEdgeStart, // POINTFIX* ppfxEdgeEnd, RECTL* pClipRect) // // Adds the edge described by the two passed-in points to the Global Edge // Table (GET), if the edge spans at least one pixel vertically. // //----------------------------------------------------------------------------- EDGE* pAddEdgeToGET(EDGE* pGETHead, EDGE* pFreeEdge, POINTFIX* ppfxEdgeStart, POINTFIX* ppfxEdgeEnd, RECTL* pClipRect) { int iYStart; int iYEnd; int iXStart; int iXEnd; int iYHeight; int iXWidth; int yJump; int yTop; // // Set the winding-rule direction of the edge, and put the endpoints in // top-to-bottom order // iYHeight = ppfxEdgeEnd->y - ppfxEdgeStart->y; if ( iYHeight == 0 ) { // // Zero height; ignore this edge // return(pFreeEdge); } else if ( iYHeight > 0 ) { // // Top-to-bottom // iXStart = ppfxEdgeStart->x; iYStart = ppfxEdgeStart->y; iXEnd = ppfxEdgeEnd->x; iYEnd = ppfxEdgeEnd->y; pFreeEdge->iWindingDirection = 1; } else { iYHeight = -iYHeight; iXEnd = ppfxEdgeStart->x; iYEnd = ppfxEdgeStart->y; iXStart = ppfxEdgeEnd->x; iYStart = ppfxEdgeEnd->y; pFreeEdge->iWindingDirection = -1; } if ( iYHeight & 0x80000000 ) { // // Too large; outside 2**27 GDI range // return(NULL); } // // Set the error term and adjustment factors, all in GIQ coordinates for // now // iXWidth = iXEnd - iXStart; if ( iXWidth >= 0 ) { // // Left to right, so we change X as soon as we move at all // pFreeEdge->iXDirection = 1; pFreeEdge->iErrorTerm = -1; } else { // // Right to left, so we don't change X until we've moved a full GIQ // coordinate // iXWidth = -iXWidth; pFreeEdge->iXDirection = -1; pFreeEdge->iErrorTerm = -iYHeight; } if ( iXWidth & 0x80000000 ) { // // Too large; outside 2**27 GDI range // return(NULL); } if ( iXWidth >= iYHeight ) { // // Calculate base run length (minimum distance advanced in X for a 1- // scan advance in Y) // pFreeEdge->iXWhole = iXWidth / iYHeight; // // Add sign back into base run length if going right to left // if ( pFreeEdge->iXDirection == -1 ) { pFreeEdge->iXWhole = -pFreeEdge->iXWhole; } pFreeEdge->iErrorAdjustUp = iXWidth % iYHeight; } else { // // Base run length is 0, because line is closer to vertical than // horizontal // pFreeEdge->iXWhole = 0; pFreeEdge->iErrorAdjustUp = iXWidth; } pFreeEdge->iErrorAdjustDown = iYHeight; // // Calculate the number of pixels spanned by this edge, accounting for // clipping // // Top true pixel scan in GIQ coordinates // Shifting to divide and multiply by 16 is okay because the clip rect // always contains positive numbers // yTop = max(pClipRect->top << 4, (iYStart + 15) & ~0x0F); // // Initial scan line on which to fill edge // pFreeEdge->Y = yTop >> 4; // // Calculate # of scans to actually fill, accounting for clipping // if ( (pFreeEdge->iScansLeft = min(pClipRect->bottom, ((iYEnd + 15) >> 4)) - pFreeEdge->Y) <= 0 ) { // // No pixels at all are spanned, so we can ignore this edge // return(pFreeEdge); } // // If the edge doesn't start on a pixel scan (that is, it starts at a // fractional GIQ coordinate), advance it to the first pixel scan it // intersects. Ditto if there's top clipping. Also clip to the bottom if // needed // if ( iYStart != yTop ) { // // Jump ahead by the Y distance in GIQ coordinates to the first pixel // to draw // yJump = yTop - iYStart; // // Advance x the minimum amount for the number of scans traversed // iXStart += pFreeEdge->iXWhole * yJump; vAdjustErrorTerm(&pFreeEdge->iErrorTerm, pFreeEdge->iErrorAdjustUp, pFreeEdge->iErrorAdjustDown, yJump, &iXStart, pFreeEdge->iXDirection); } // // Turn the calculations into pixel rather than GIQ calculations // // Move the X coordinate to the nearest pixel, and adjust the error term // accordingly // Dividing by 16 with a shift is okay because X is always positive pFreeEdge->X = (iXStart + 15) >> 4; // convert from GIQ to pixel coordinates // // LATER adjust only if needed (if prestepped above)? // if ( pFreeEdge->iXDirection == 1 ) { // // Left to right // pFreeEdge->iErrorTerm -= pFreeEdge->iErrorAdjustDown * (((iXStart + 15) & ~0x0F) - iXStart); } else { // // Right to left // pFreeEdge->iErrorTerm -= pFreeEdge->iErrorAdjustDown * ((iXStart - 1) & 0x0F); } // // Scale the error term down 16 times to switch from GIQ to pixels. // Shifts work to do the multiplying because these values are always // non-negative // pFreeEdge->iErrorTerm >>= 4; // // Insert the edge into the GET in YX-sorted order. The search always ends // because the GET has a sentinel with a greater-than-possible Y value // while ( (pFreeEdge->Y > ((EDGE*)pGETHead->pNext)->Y) ||( (pFreeEdge->Y == ((EDGE*)pGETHead->pNext)->Y) &&(pFreeEdge->X > ((EDGE*)pGETHead->pNext)->X) ) ) { pGETHead = (EDGE*)pGETHead->pNext; } pFreeEdge->pNext = pGETHead->pNext; // link the edge into the GET pGETHead->pNext = pFreeEdge; // // Point to the next edge storage location for next time // return(++pFreeEdge); }// pAddEdgeToGET() //----------------------------------------------------------------------------- // // void vAdjustErrorTerm(int *pErrorTerm, int iErrorAdjustUp, // int iErrorAdjustDown, int yJump, int *pXStart, // int iXDirection) // Adjust the error term for a skip ahead in y. This is in ASM because there's // a multiply/divide that may involve a larger than 32-bit value. // //----------------------------------------------------------------------------- void vAdjustErrorTerm(int* pErrorTerm, int iErrorAdjustUp, int iErrorAdjustDown, int yJump, int* pXStart, int iXDirection) { #if defined(_X86_) || defined(i386) // // Adjust the error term up by the number of y coordinates we'll skip // *pErrorTerm += iErrorAdjustUp * yJump; // _asm mov ebx,pErrorTerm _asm mov eax,iErrorAdjustUp _asm mul yJump _asm add eax,[ebx] _asm adc edx,-1 // the error term starts out negative // // See if the error term turned over even once while skipping // _asm js short NoErrorTurnover // // # of times we'll turn over the error term and step an extra x // coordinate while skipping // NumAdjustDowns = (*pErrorTerm / iErrorAdjustDown) + 1; // _asm div iErrorAdjustDown _asm inc eax // // Note that EDX is the remainder; (EDX - iErrorAdjustDown) is where // the error term ends up ultimately // // Advance x appropriately for the # of times the error term // turned over // if (iXDirection == 1) // { // *pXStart += NumAdjustDowns; // } // else // { // *pXStart -= NumAdjustDowns; // } // _asm mov ecx,pXStart _asm cmp iXDirection,1 _asm jz short GoingRight _asm neg eax GoingRight: _asm add [ecx],eax // Adjust the error term down to its proper post-skip value // *pErrorTerm -= iErrorAdjustDown * NumAdjustDowns; _asm sub edx,iErrorAdjustDown _asm mov eax,edx // put into EAX for storing to pErrorTerm next NoErrorTurnover: _asm mov [ebx],eax #else // // LONGLONGS are 64 bit integers (We hope!) as the multiply could // overflow 32 bit integers. If 64 bit ints are unsupported, the // LONGLONG will end up as a double. Hopefully there will be no // noticable difference in accuracy. LONGLONG NumAdjustDowns; LONGLONG tmpError = *pErrorTerm; // // Adjust the error term up by the number of y coordinates we'll skip // tmpError += (LONGLONG)iErrorAdjustUp * (LONGLONG)yJump; // // See if the error term turned over even once while skipping // if ( tmpError >= 0 ) { // // # of times we'll turn over the error term and step an extra x // coordinate while skipping // NumAdjustDowns = (tmpError / (LONGLONG)iErrorAdjustDown) + 1; // // Advance x appropriately for the # of times the error term // turned over // if ( iXDirection == 1 ) { *pXStart += (LONG)NumAdjustDowns; } else { *pXStart -= (LONG) NumAdjustDowns; } // // Adjust the error term down to its proper post-skip value // tmpError -= (LONGLONG)iErrorAdjustDown * NumAdjustDowns; } *pErrorTerm = (LONG)tmpError; #endif // X86 }// vAdjustErrorTerm()
32.885375
86
0.49349
[ "solid" ]
9ba82cf111061934070cd8ab2eb3f03377e6af83
1,035
h
C
qqtw/qqheaders7.2/UnifyNameUtil.h
onezens/QQTweak
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
5
2018-02-20T14:24:17.000Z
2020-08-06T09:31:21.000Z
qqtw/qqheaders7.2/UnifyNameUtil.h
onezens/QQTweak
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
1
2020-06-10T07:49:16.000Z
2020-06-12T02:08:35.000Z
qqtw/qqheaders7.2/UnifyNameUtil.h
onezens/SmartQQ
04b9efd1d93eba8ef8fec5cf9a20276637765777
[ "MIT" ]
null
null
null
// // Generated by class-dump 3.5 (64 bit). // // class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard. // #import "NSObject.h" @class NSDictionary; @interface UnifyNameUtil : NSObject { NSDictionary *_ruleDic; } + (id)GetInstance; - (void).cxx_destruct; - (id)getCardDataByRule:(id)arg1 model:(id)arg2; - (id)getListDataByRule:(id)arg1 uin:(id)arg2 groupNick:(id)arg3 remark:(id)arg4 phoneNum:(id)arg5 autoRemark:(id)arg6 nick:(id)arg7; - (id)getUnifyName:(int)arg1 showType:(int)arg2 uin:(id)arg3 phoneNum:(id)arg4 groupCode:(id)arg5 discussGroupUin:(long long)arg6; - (id)getUnifyName:(int)arg1 showType:(int)arg2 uin:(id)arg3 phoneNum:(id)arg4 groupCode:(id)arg5 discussGroupUin:(long long)arg6 troopMemModel:(id)arg7; - (id)getValueByRuleKey:(id)arg1 uin:(unsigned long long)arg2 groupNick:(id)arg3 remark:(id)arg4 nick:(id)arg5 phoneNum:(id)arg6 autoRemark:(id)arg7 isMore:(_Bool)arg8; - (id)init; @property(retain, nonatomic) NSDictionary *ruleDic; // @synthesize ruleDic=_ruleDic; @end
36.964286
168
0.7343
[ "model" ]
9ba82e0d04ca231c717d4b4c947094ff3e8c4c10
1,012
h
C
vespalib/src/vespa/vespalib/websocket/request.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2018-12-30T05:42:18.000Z
2018-12-30T05:42:18.000Z
vespalib/src/vespa/vespalib/websocket/request.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2021-03-31T22:27:25.000Z
2021-03-31T22:27:25.000Z
vespalib/src/vespa/vespalib/websocket/request.h
amahussein/vespa
29d266ae1e5c95e25002b97822953fdd02b1451e
[ "Apache-2.0" ]
1
2020-02-01T07:21:28.000Z
2020-02-01T07:21:28.000Z
// Copyright 2017 Yahoo Holdings. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root. #pragma once #include "connection.h" #include <vespa/vespalib/stllike/string.h> #include <map> #include <vector> namespace vespalib { namespace ws { class Request { private: vespalib::string _method; vespalib::string _uri; vespalib::string _version; std::map<vespalib::string, vespalib::string> _headers; vespalib::string _empty; bool handle_header(vespalib::string &header_name, const vespalib::string &header_line); public: Request(); ~Request(); bool read_header(Connection &conn); bool is_get() const { return _method == "GET"; } const vespalib::string &get_header(const vespalib::string &name) const; bool has_connection_token(const vespalib::string &token) const; bool is_ws_upgrade() const; const vespalib::string &uri() const { return _uri; } }; } // namespace vespalib::ws } // namespace vespalib
25.948718
118
0.69664
[ "vector" ]
9bb4e6f2700d1ce4974e5af549c34d805d7a3975
1,227
h
C
libs/platform/cocoa/dispatcher.h
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
15
2017-10-18T05:08:16.000Z
2022-02-02T11:01:46.000Z
libs/platform/cocoa/dispatcher.h
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
null
null
null
libs/platform/cocoa/dispatcher.h
kdt3rd/gecko
756a4e4587eb5023495294d9b6c6d80ebd79ebde
[ "MIT" ]
1
2018-11-10T03:12:57.000Z
2018-11-10T03:12:57.000Z
// SPDX-License-Identifier: MIT // Copyright contributors to the gecko project. #pragma once #include "keyboard.h" #include "mouse.h" #include "platform.h" #include "window.h" #include <map> #include <memory> #include <platform/dispatcher.h> #include <vector> namespace platform { namespace cocoa { //////////////////////////////////////// /// @brief Cocoa implementation of dispatcher. class dispatcher : public ::platform::dispatcher { public: dispatcher( ::platform::system *s ); ~dispatcher( void ) override; int execute( void ) override; void exit( int code ) override; void add_waitable( const std::shared_ptr<waitable> &w ) override; void remove_waitable( const std::shared_ptr<waitable> &w ) override; void add_window( const std::shared_ptr<window> &w ); void remove_window( const std::shared_ptr<window> &w ); private: int _exit_code = 0; // bool _continue_running = true; std::shared_ptr<keyboard> _keyboard; std::shared_ptr<mouse> _mouse; std::map<void *, std::shared_ptr<window>> _windows; CGEventSourceRef _event_source; }; //////////////////////////////////////// } // namespace cocoa } // namespace platform
23.596154
72
0.635697
[ "vector" ]
9bb613474073a32fca23b6b87b7072166b70e9d7
8,384
h
C
src/content/content_instance.h
izaman/tizen-extensions-crosswalk
e1373788f4e4e271e39b0fee66c26210e40dd86f
[ "Apache-2.0", "BSD-3-Clause" ]
10
2015-01-16T16:14:35.000Z
2018-12-25T16:01:43.000Z
src/content/content_instance.h
liyingzh/tizen-extensions-crosswalk
5957945effafff02a507c35a4b7b4d5ee6ca14c1
[ "Apache-2.0", "BSD-3-Clause" ]
35
2015-01-04T02:11:22.000Z
2015-09-22T08:43:45.000Z
src/content/content_instance.h
liyingzh/tizen-extensions-crosswalk
5957945effafff02a507c35a4b7b4d5ee6ca14c1
[ "Apache-2.0", "BSD-3-Clause" ]
14
2015-02-03T04:38:19.000Z
2022-01-20T10:38:01.000Z
// Copyright (c) 2014 Intel Corporation. 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_CONTENT_INSTANCE_H_ #define CONTENT_CONTENT_INSTANCE_H_ #include <media_content.h> #include <string> #include <algorithm> #include <vector> #include "common/extension.h" #include "common/picojson.h" #include "tizen/tizen.h" namespace picojson { class value; } class ContentFolderList; class ContentItemList; class ContentInstance : public common::Instance { public: ContentInstance(); virtual ~ContentInstance(); private: // common::Instance implementation. virtual void HandleMessage(const char* msg); virtual void HandleSyncMessage(const char* msg); bool HandleUpdateRequest(const picojson::value& json); void HandleUpdateBatchRequest(const picojson::value& json); void HandleGetDirectoriesRequest(const picojson::value& json); void HandleGetDirectoriesReply(const picojson::value& json, ContentFolderList *); void HandleFindRequest(const picojson::value& json); void HandleFindReply(const picojson::value& json, ContentItemList *); void HandleScanFileRequest(const picojson::value& json); void HandleScanFileReply(const picojson::value& json); // Asynchronous message helpers void PostAsyncErrorReply(const picojson::value&, WebApiAPIErrors); void PostAsyncSuccessReply(const picojson::value&, picojson::value::object&); void PostAsyncSuccessReply(const picojson::value&, picojson::value&); void PostAsyncSuccessReply(const picojson::value&, WebApiAPIErrors); void PostAsyncSuccessReply(const picojson::value&); // Tizen CAPI helpers static bool MediaFolderCallback(media_folder_h handle, void *user_data); static bool MediaInfoCallback(media_info_h handle, void *user_data); static void MediaContentChangeCallback( media_content_error_e error, int pid, media_content_db_update_item_type_e update_item, media_content_db_update_type_e update_type, media_content_type_e media_type, char* uuid, char* path, char* mime_type, void* user_data); static unsigned m_instanceCount; }; class ContentFolder { public: void init(media_folder_h handle); // Getters & Getters const std::string& id() const { return id_; } void setID(const std::string& id) { id_ = id; } const std::string& directoryURI() const { return directoryURI_; } void setDirectoryURI(const std::string& uri) { directoryURI_ = uri; } const std::string& title() const { return title_; } void setTitle(const std::string& title) { title_ = title; } const std::string& storageType() const { return storageType_; } void setStorageType(const std::string& type) { storageType_ = type; } const std::string& modifiedDate() const { return modifiedDate_; } void setModifiedDate(const std::string& modifiedDate) { modifiedDate_ = modifiedDate; } #ifdef DEBUG_ITEM void print(void); #endif protected: std::string id_; std::string directoryURI_; std::string title_; std::string storageType_; std::string modifiedDate_; }; class ContentItem { public: ContentItem() : size_(0), rating_(0), bitrate_(0), track_number_(0), duration_(0), width_(0), height_(0), latitude_(DEFAULT_GEOLOCATION), longitude_(DEFAULT_GEOLOCATION) { editable_attributes_.push_back("name"); editable_attributes_.push_back("description"); editable_attributes_.push_back("rating"); editable_attributes_.push_back("geolocation"); editable_attributes_.push_back("orientation"); } void init(media_info_h handle); // Getters & Setters const std::vector<std::string>& editable_attributes() const { return editable_attributes_; } const std::string& id() const { return id_; } void set_id(const std::string& id) { id_ = id; } const std::string& name() const { return name_; } void set_name(const std::string& name) { name_ = name; } const std::string& type() const { return type_; } void set_type(const std::string& type) { type_ = type;} const std::string& mime_type() const { return mime_type_; } void set_mime_type(const std::string& mime_type) { mime_type_ = mime_type; } const std::string& title() const { return title_; } void set_title(const std::string& title) { title_ = title;} const std::string& content_uri() const { return content_uri_; } void set_content_uri(const std::string& uri) { content_uri_ = uri; } const std::string& thumbnail_uris() const { return thumbnail_uris_; } void set_thumbnail_uris(const std::string& uris) { thumbnail_uris_ = uris; } const std::string& release_date() const { return release_date_; } void set_release_date(const std::string release_date) { release_date_ = release_date; } const std::string& modified_date() const { return modified_date_; } void set_modified_date(const std::string& modified_date) { modified_date_ = modified_date; } uint64_t size() const { return size_; } void set_size(const uint64_t size) { size_ = size; } const std::string& description() const { return description_; } void set_description(const std::string& desc) { description_ = desc; } uint64_t rating() const { return rating_; } void set_rating(uint64_t rating) { rating_ = rating; } // type = AUDIO and VIDEO const std::string& album() const { return album_; } void set_album(const std::string& album) { album_ = album;} const std::string& genres() const { return genres_; } void set_genres(const std::string& genres) { genres_ = genres;} const std::string& artists() const { return artists_; } void set_artists(const std::string& artists) { artists_ = artists;} const std::string& composer() const { return composer_; } void set_composer(const std::string& composer) { composer_ = composer;} const std::string& copyright() const { return copyright_; } void set_copyright(const std::string& copyright) { copyright_ = copyright;} uint64_t bitrate() const { return bitrate_; } void set_bitrate(uint64_t bitrate) { bitrate_ = bitrate; } uint64_t track_number() const { return track_number_; } void set_track_number(uint64_t num) { track_number_ = num; } int duration() const { return duration_; } void set_duration(int duration) { duration_ = duration; } // type = IMAGE uint64_t width() const { return width_; } void set_width(uint64_t width) { width_ = width; } uint64_t height() const { return height_; } void set_height(uint64_t height) { height_ = height; } const std::string& orientation() const { return orientation_; } void set_orientation(const std::string& orintatin) {orientation_ = orintatin;} double latitude() const { return latitude_; } void set_latitude(double latitude) { latitude_ = latitude; } double longitude() const { return longitude_; } void set_longitude(double longitude) { longitude_ = longitude; } #ifdef DEBUG_ITEM void print(void); #endif protected: std::vector<std::string> editable_attributes_; std::string id_; std::string name_; std::string type_; std::string mime_type_; std::string title_; std::string content_uri_; std::string thumbnail_uris_; std::string release_date_; std::string modified_date_; uint64_t size_; std::string description_; uint64_t rating_; // type = AUDIO and VIDEO std::string album_; std::string genres_; std::string artists_; std::string composer_; std::string copyright_; uint64_t bitrate_; uint16_t track_number_; int duration_; // type = IMAGE uint64_t width_; uint64_t height_; double latitude_; double longitude_; std::string orientation_; const double DEFAULT_GEOLOCATION = -200; }; class ContentFolderList { public: ~ContentFolderList() { for (unsigned i = 0; i < m_folders.size(); i++) delete m_folders[i]; } void addFolder(ContentFolder* folder) { m_folders.push_back(folder); } const std::vector<ContentFolder*>& getAllItems() { return m_folders; } private: std::vector<ContentFolder*> m_folders; }; class ContentItemList { public: ~ContentItemList() { for (unsigned i = 0; i < m_items.size(); i++) delete m_items[i]; } void addItem(ContentItem* item) { m_items.push_back(item); } const std::vector<ContentItem*>& getAllItems() { return m_items; } private: std::vector<ContentItem*> m_items; }; #endif // CONTENT_CONTENT_INSTANCE_H_
34.360656
80
0.724117
[ "object", "vector" ]
9bb9db19f3fb5805806f32824f7290de88615c2d
1,766
h
C
Moon/src/Moon/Event/Event.h
TimsonL/moon_engine
f57f18f3aff1f6d9d34ec8a2747c9560bfb8fdd7
[ "Apache-2.0" ]
null
null
null
Moon/src/Moon/Event/Event.h
TimsonL/moon_engine
f57f18f3aff1f6d9d34ec8a2747c9560bfb8fdd7
[ "Apache-2.0" ]
null
null
null
Moon/src/Moon/Event/Event.h
TimsonL/moon_engine
f57f18f3aff1f6d9d34ec8a2747c9560bfb8fdd7
[ "Apache-2.0" ]
null
null
null
#pragma once #include "pch.h" namespace moon { class Event { public: using Data = std::unordered_map<std::string, boost::any>; Event() {} Event(Data&& data) : m_data(data) {} const boost::any& operator[](const std::string& key) const { auto it = m_data.find(key); if (it != m_data.end()) return it->second; MOON_CORE_ERROR("Event does not have the requested attribute"); assert(0); } protected: Data m_data; }; class EventCallback; class EventDispatcher { public: template<class EventT> void dispatch(const EventT* event) { auto it = m_callbacks.find(typeid(*event)); if (it != m_callbacks.end()) { for (auto& callback : it->second) callback->exec(event); } } template<class T, class EventT> void RegisterEventCallback(T* object, void(T::*memberFn)(const EventT*)) { std::type_index id = typeid(EventT); m_callbacks[id].push_back(std::make_unique<MemberCallback<T, EventT>>(object, memberFn)); } private: using Callbacks = std::map< std::type_index, std::vector<std::unique_ptr<EventCallback>>>; Callbacks m_callbacks; }; class EventCallback { public: void exec(const Event* event) { call(event); } private: virtual void call(const Event* event) = 0; }; template <class T, class EventT > class MemberCallback : public EventCallback { public: using MemberFunc = void(T::*)(const EventT*); MemberCallback(T* object, MemberFunc memFn) : m_object(object), m_callback(memFn) {}; void call(const Event* event) { (m_object->*m_callback)(static_cast<const EventT*>(event)); } private: T* m_object; MemberFunc m_callback; }; }
24.191781
95
0.625708
[ "object", "vector" ]
9bc0b35ddd744137a5f698682dbd7bb62ff529df
1,823
h
C
Sources/engine/vulkangfx/private/PipelineLayout.h
Zino2201/ZinoEngine
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
[ "MIT" ]
20
2019-12-22T20:40:22.000Z
2021-07-06T00:23:45.000Z
Sources/engine/vulkangfx/private/PipelineLayout.h
Zino2201/ZinoEngine
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
[ "MIT" ]
32
2020-07-11T15:51:13.000Z
2021-06-07T10:25:07.000Z
Sources/engine/vulkangfx/private/PipelineLayout.h
Zino2201/ZinoEngine
519d34a1d2b09412c8e2cba6b685b4556ec2c2ac
[ "MIT" ]
3
2019-12-19T17:04:04.000Z
2021-05-17T01:49:59.000Z
#pragma once #include "Vulkan.h" #include "gfx/Backend.h" #include <queue> #include <robin_hood.h> namespace ze::gfx::vulkan { class Device; class PipelineLayout { struct PoolEntry { uint32_t allocations; vk::UniqueDescriptorPool pool; PoolEntry(vk::UniqueDescriptorPool&& in_pool) : allocations(0), pool(std::move(in_pool)) {} }; struct SetEntry { static constexpr uint8_t max_set_lifetime = 10; ResourceHandle set; uint8_t lifetime; SetEntry(const ResourceHandle& in_set) : set(in_set), lifetime(0) {} ResourceHandle get_set() { lifetime = 0; return set; } }; public: PipelineLayout(Device& in_device, const PipelineLayoutCreateInfo& in_create_info); void new_frame(); static void update_layouts(); /** * Will allocate a set matching this pipeline layout * This function may recycle an already allocated descriptor set */ ResourceHandle allocate_set(const uint32_t in_set, const std::vector<Descriptor>& in_descriptors); void free_set(const uint32_t in_set_idx, const ResourceHandle& in_set); static PipelineLayout* get(const ResourceHandle& in_handle); ZE_FORCEINLINE bool is_valid() const { return !!layout && !descriptor_pools.empty(); } ZE_FORCEINLINE vk::PipelineLayout& get_layout() { return *layout; } private: void allocate_pool(); ResourceHandle allocate_set_internal(PoolEntry& in_pool, const uint32_t in_set); private: Device& device; vk::UniquePipelineLayout layout; std::vector<vk::UniqueDescriptorSetLayout> set_layouts; /** Desc set mgmt */ robin_hood::unordered_map<uint32_t, robin_hood::unordered_map<uint64_t, SetEntry>> descriptor_sets; robin_hood::unordered_map<uint32_t, std::queue<ResourceHandle>> free_descriptor_sets; std::vector<PoolEntry> descriptor_pools; std::vector<vk::DescriptorPoolSize> descriptor_pool_sizes; }; }
26.042857
100
0.760834
[ "vector" ]
9bca1bf2392698d310a329539d0d09962fbb1efb
3,975
h
C
GP/PalMark.h
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
4
2020-06-22T16:59:51.000Z
2020-06-28T19:35:23.000Z
GP/PalMark.h
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
59
2020-09-12T23:54:16.000Z
2022-03-24T18:51:43.000Z
GP/PalMark.h
wsu-cb/cbwindows
55d3797ed0c639b36fe3f677777fcc31e3449360
[ "MIT" ]
4
2020-06-22T13:37:40.000Z
2021-01-29T12:42:54.000Z
// PalMark.h : header file // // Copyright (c) 1994-2020 By Dale L. Larson, All Rights Reserved. // // 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 _PALMARK_H #define _PALMARK_H #ifndef _LBOXMARK_H #include "LBoxMark.h" #endif #ifndef _WSTATEGP_H #include "WStateGp.h" #endif ///////////////////////////////////////////////////////////////////////////// class CGamDoc; ///////////////////////////////////////////////////////////////////////////// // CMarkerPalette window - Marker palette's are part of the document object. class CMarkerPalette : public CWnd { DECLARE_DYNCREATE(CMarkerPalette) // Construction public: CMarkerPalette(); BOOL Create(CWnd* pOwnerWnd, DWORD dwStyle = 0, UINT nID = 0); // Attributes public: void SetDocument(CGamDoc *pDoc); // Operations public: size_t GetSelectedMarkerGroup(); void UpdatePaletteContents(); void SelectMarker(MarkID mid); void Serialize(CArchive &ar); CDockablePane* GetDockingFrame() { return m_pDockingFrame; } void SetDockingFrame(CDockablePane* pDockingFrame) { m_pDockingFrame = pDockingFrame; SetParent(pDockingFrame); } // Implementation protected: CGamDoc* m_pDoc; CRect m_rctPos; CDockablePane* m_pDockingFrame; // This dummy area only contains a single entry. It is used // when only single entry should be shown in the Tray listbox. // This is pretty much a hack but is was easier than reworking // CGrafixListBox to support this oddball situation. std::vector<MarkID> m_dummyArray; // Enclosed controls.... CComboBox m_comboMGrp; CMarkListBox m_listMark; void LoadMarkerNameList(); void UpdateMarkerList(); int FindMarkerGroupIndex(size_t nGroupNum); // Some temporary vars used during windows position restoration. // They are loaded during the de-serialization process. BOOL m_bStateVarsArmed; // Set so state restore is one-shot process int m_nComboIndex; int m_nListTopindex; int m_nListCurSel; int m_nComboHeight; CWinPlacement m_wndPlace; // Implementation public: virtual void PostNcDestroy(); // Generated message map functions protected: //{{AFX_MSG(CMarkerPalette) afx_msg BOOL OnEraseBkgnd(CDC* pDC); afx_msg void OnSize(UINT nType, int cx, int cy); afx_msg void OnDestroy(); afx_msg void OnWindowPosChanging(WINDOWPOS FAR* lpwndpos); afx_msg void OnMarkerNameCbnSelchange(); afx_msg LRESULT OnOverrideSelectedItem(WPARAM wParam, LPARAM lParam); afx_msg BOOL OnHelpInfo(HELPINFO* pHelpInfo); afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct); //}}AFX_MSG afx_msg LRESULT OnPaletteHide(WPARAM, LPARAM); afx_msg LRESULT OnMessageRestoreWinState(WPARAM, LPARAM); DECLARE_MESSAGE_MAP() }; ///////////////////////////////////////////////////////////////////////////// #endif
30.576923
95
0.682767
[ "object", "vector" ]
9bcaef5c5c057cfec4f2c41218bf58ba519d5877
7,037
h
C
HighJacked.spritebuilder/Source/libs/cocos2d-iphone/cocos2d-ui/CCControl.h
IkeyBenz/Hijack
c30f21cdcce1640d0423013399b3345d21da8081
[ "MIT" ]
985
2015-05-01T22:20:57.000Z
2022-02-25T06:59:29.000Z
HighJacked.spritebuilder/Source/libs/cocos2d-iphone/cocos2d-ui/CCControl.h
IkeyBenz/Hijack
c30f21cdcce1640d0423013399b3345d21da8081
[ "MIT" ]
192
2015-01-01T12:45:53.000Z
2015-02-20T20:34:22.000Z
HighJacked.spritebuilder/Source/libs/cocos2d-iphone/cocos2d-ui/CCControl.h
IkeyBenz/Hijack
c30f21cdcce1640d0423013399b3345d21da8081
[ "MIT" ]
366
2015-05-02T17:00:51.000Z
2022-03-13T14:19:28.000Z
/* * cocos2d for iPhone: http://www.cocos2d-iphone.org * * Copyright (c) 2013 Apportable 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 * 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. */ #import "CCNode.h" /** The possible states for a CCControl. */ typedef NS_ENUM(NSUInteger, CCControlState) { /** The normal, or default state of a control — that is, enabled but neither selected nor highlighted. */ CCControlStateNormal = 1 << 0, /** Highlighted state of a control. A control enters this state when a touch down, drag inside or drag enter is performed. You can retrieve and set this value through the highlighted property. */ CCControlStateHighlighted = 1 << 1, /** Disabled state of a control. This state indicates that the control is currently disabled. You can retrieve and set this value through the enabled property. */ CCControlStateDisabled = 1 << 2, /** Selected state of a control. This state indicates that the control is currently selected. You can retrieve and set this value through the selected property. */ CCControlStateSelected = 1 << 3 }; /** CCControl is the abstract base class of the Cocos2D GUI components. It handles touch/mouse events. Its subclasses use child nodes to draw themselves in the node hierarchy. You should not instantiate CCControl directly. Instead use one of its sub-classes: - CCButton - CCSlider - CCTextField If you need to create a new GUI control you should make it a subclass of CCControl. @note If you are subclassing CCControl you should `#import "CCControlSubclass.h"` in your subclass as it includes methods that are not publicly exposed. */ @interface CCControl : CCNode { /** Needs layout is set to true if the control has changed and needs to re-layout itself. */ BOOL _needsLayout; } /// ----------------------------------------------------------------------- /// @name Controlling Content Size /// ----------------------------------------------------------------------- /** The preferred (and minimum) size that the component will attempt to layout to. If its contents are larger it may have a larger size. */ @property (nonatomic,assign) CGSize preferredSize; /** The content size type that the preferredSize is using. Please refer to the CCNode documentation on how to use content size types. @see CCSizeType, CCSizeUnit */ @property (nonatomic,assign) CCSizeType preferredSizeType; /** The maximum size that the component will layout to, the component will not be larger than this size and will instead shrink its content if needed. */ @property (nonatomic,assign) CGSize maxSize; /** The content size type that the preferredSize is using. Please refer to the CCNode documentation on how to use content size types. @see CCSizeType, CCSizeUnit */ @property (nonatomic,assign) CCSizeType maxSizeType; /// ----------------------------------------------------------------------- /// @name Setting and Getting Control Attributes /// ----------------------------------------------------------------------- /** Sets or retrieves the current state of the control. @note This property is a bitmask. It's easier to use the enabled, highlighted and selected properties to indirectly set or read this property. @see CCControlState @see enabled, selected, highlighted */ @property (nonatomic,assign) CCControlState state; /** Determines if the control is currently enabled. */ @property (nonatomic,assign) BOOL enabled; /** Determines if the control is currently selected. E.g. this is used by toggle buttons to handle the on state. */ @property (nonatomic,assign) BOOL selected; /** Determines if the control is currently highlighted. E.g. this corresponds to the down state of a button */ @property (nonatomic,assign) BOOL highlighted; /** True if the control continously should generate events when it's value is changed. E.g. this can be used by slider controls to run the block/selector whenever the slider is moved. */ @property (nonatomic,assign) BOOL continuous; /// ----------------------------------------------------------------------- /// @name Accessing Control State /// ----------------------------------------------------------------------- /** True if the control is currently tracking touches or mouse events. That is, if the user has touched down in the component but not lifted his finger (the actual touch may be outside the component). */ @property (nonatomic,readonly) BOOL tracking; /** True if the control currently has a touch or a mouse event within its bounds. */ @property (nonatomic,readonly) BOOL touchInside; /// ----------------------------------------------------------------------- /// @name Receiving Action Callbacks /// ----------------------------------------------------------------------- /** A block that handles action callbacks sent by the control. The block runs when the control subclass is activated (ie slider moved, button tapped). The block must have the following signature: `void (^)(id sender)` where sender is the sending CCControl subclass. For example: control.block = ^(id sender) { NSLog(@"control activated by: %@", sender); }; @see setTarget:selector: */ @property (nonatomic,copy) void(^block)(id sender); /** Sets a target and selector that should be called when an action is triggered by the control. Actions are generated when buttons are clicked, sliders are dragged etc. The selector must have the following signature: `-(void) theSelector:(id)sender` where sender is the sending CCControl subclass. It is therefore legal to implement the selector more specifically as, for instance: -(void) onSliderDragged:(CCSlider*)slider { NSLog(@"sender: %@", slider); } Provided that this selector was assigned to a CCSlider instance. @param target The target object to which the message should be sent. @param selector Selector in target object receiving the message. @see block */ -(void) setTarget:(id)target selector:(SEL)selector; @end
43.98125
166
0.68154
[ "object" ]
9bce3d8324a5201137f165208e5077f54315504e
3,673
h
C
Sources/CasperSDKObjectiveC/CommonClasses/Public/CasperSDKObjectiveC/CLParsed.h
tqhuy2018/CSPR-Swift-SDK
427adfb7503953016c731c271bc143c4c1ffd6ab
[ "MIT" ]
2
2022-03-09T18:00:23.000Z
2022-03-16T14:34:36.000Z
Sources/CasperSDKObjectiveC/CommonClasses/Public/CasperSDKObjectiveC/CLParsed.h
tqhuy2018/Casper-ObjectiveC-sdk
1c38f002f325a92509f7d5aba1abc69552420c92
[ "MIT" ]
null
null
null
Sources/CasperSDKObjectiveC/CommonClasses/Public/CasperSDKObjectiveC/CLParsed.h
tqhuy2018/Casper-ObjectiveC-sdk
1c38f002f325a92509f7d5aba1abc69552420c92
[ "MIT" ]
null
null
null
#import <Foundation/Foundation.h> #ifndef CLParsed_h #define CLParsed_h #import "CLType.h" /**Class built for storing the parse value of a CLValue object. For example take this CLValue object { "bytes":"0400e1f505" "parsed":"100000000" "cl_type":"U512" } Then the parse will hold the value of 100000000. There are some more attributes in the object to store more information on the type of the parse (CLType), its value in String for later handle in serialization or show the information */ @interface CLParsed:NSObject @property CLType * itsCLType; ///Type in String, for example: type of CLParsedPBool will get value of Bool, CLParsedList will get value of List, CLParsedMap will get value of Map, CLParsedPInt32 will get value of Int32 and so on //@property NSString * itsCLTypeStr; @property NSString * itsPrimitiveValue; //This value is for CLType primitive value //For CLParse Result, itsValueStr = Ok or Err, for other type such as primitive bool, the value will be "true" or "false" @property NSString * itsValueStr; //This value is used for List and FixedList @property NSMutableArray * arrayValue; @property bool is_primitive; @property bool is_array_type; //innerParsed for compound types //For Tuple1, Result and Option CLType, innerParsed1 value is used //For Tuple2 CLType, innerParsed1,innerParsed2 value are used //For tuple3 CLType, innerParsed1,innerParsed2,innerParsed3 value are used //For map CLType, key is stored in innerParsed1, value is stored in innerParsed2 and the innerParsed1 is a ParseList with values stored in arrayValue @property CLParsed * innerParsed1; @property CLParsed * innerParsed2; @property CLParsed * innerParsed3; @property bool is_innerParsed1_exists; @property bool is_innerParsed2_exists; @property bool is_innerParsed3_exists; ///Generate the CLParse object from the JSON object fromObj with given clType +(CLParsed*) fromObjToCLParsed:(NSObject*) fromObj withCLType:(CLType*) clType; ///Generate the CLParse object of type primitive (such as bool, i32, i64, u8, u32, u64, u128, u266, u512, string, unit, publickey, key, ...) from the JSON object fromObj with given clType +(CLParsed*) fromObjToCLParsedPrimitive:(NSObject*) fromObj withCLType:(CLType*) clType; ///Generate the CLParse object of type compound (type with recursive CLValue inside its body, such as List, Map, Tuple , Result ,Option...) from the JSON object fromObj with given clType +(CLParsed*) fromObjToCLParsedCompound:(NSObject*) fromObj withCLType:(CLType*) clType; ///Generate the CLParse object with given information of Type and value +(CLParsed*) clParsedWithType:(NSString*) type andValue:(NSString*) value; ///Check if the CLParse from CLType primitive, type that has no recursive CLType inside (such as bool, i32, i64, u8, u32, u64, u128, u266, u512, string, unit, publickey, key, ...) -(bool) isPrimitive; /// Function to turn CLParsed object to Json string, used for account_put_deploy RPC method call. +(NSString *) toJsonString:(CLParsed *) fromCLParsed; /// Function to turn 1 CLParsed object of type CLType compound to Json string, used for account_put_deploy RPC method call. /// CLType of type compound is of type with recursive CLType inside its body, such as List, Option, Tuple1, Tuple2, Tuple3, Result, Map. +(NSString *) fromCompoundParsedToJsonString:(CLParsed *) fromCLParsed; /// Function to turn 1 CLType object of type primitive to Json string, used for account_put_deploy RPC method call. /// CLType of type compound is of type with no recursive CLType inside its body, such as Bool, U8, I32, I64, U32, U64, U128.... +(NSString *) fromPrimitiveParsedToJsonString:(CLParsed *) fromCLParsed; @end #endif
54.820896
200
0.774843
[ "object" ]
9bced85a417b812b1aed0db2584e5d27507af167
22,958
h
C
include/events/config.h
willst/libcaer
ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e
[ "BSD-2-Clause" ]
1
2018-12-05T16:42:26.000Z
2018-12-05T16:42:26.000Z
include/events/config.h
willst/libcaer
ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e
[ "BSD-2-Clause" ]
null
null
null
include/events/config.h
willst/libcaer
ff0e741fcfc0b59a41f87679d59620e3cc3b3a7e
[ "BSD-2-Clause" ]
null
null
null
/** * @file config.h * * Configuration Events format definition and handling functions. * This event contains information about the current configuration of * the device. By having configuration as a standardized event format, * it becomes host-software agnostic, and it also becomes part of the * event stream, enabling easy tracking of changes through time, by * putting them into the event stream at the moment they happen. * While the resolution of the timestamps for these events is in * microseconds for compatibility with all other event types, the * precision is in the order of ~1-20 milliseconds, given that these * events are generated and injected on the host-side. */ #ifndef LIBCAER_EVENTS_CONFIG_H_ #define LIBCAER_EVENTS_CONFIG_H_ #include "common.h" #ifdef __cplusplus extern "C" { #endif /** * Shift and mask values for the module address. * Module address is only 7 bits, since the eighth bit * is used device-side to differentiate reads from writes. * Here we can just re-use it for the validity mark. */ //@{ #define CONFIG_MODULE_ADDR_SHIFT 1 #define CONFIG_MODULE_ADDR_MASK 0x0000007F //@} /** * Configuration event data structure definition. * This contains the actual configuration module address, the * parameter address and the actual parameter content, as * well as the 32 bit event timestamp. * Signed integers are used for fields that are to be interpreted * directly, for compatibility with languages that do not have * unsigned integer types, such as Java. */ PACKED_STRUCT(struct caer_configuration_event { /// Configuration module address. First (also) because of valid mark. uint8_t moduleAddress; /// Configuration parameter address. uint8_t parameterAddress; /// Configuration parameter content (4 bytes). uint32_t parameter; /// Event timestamp. int32_t timestamp; }); /** * Type for pointer to configuration event data structure. */ typedef struct caer_configuration_event *caerConfigurationEvent; typedef const struct caer_configuration_event *caerConfigurationEventConst; /** * Configuration event packet data structure definition. * EventPackets are always made up of the common packet header, * followed by 'eventCapacity' events. Everything has to * be in one contiguous memory block. */ PACKED_STRUCT(struct caer_configuration_event_packet { /// The common event packet header. struct caer_event_packet_header packetHeader; /// The events array. struct caer_configuration_event events[]; }); /** * Type for pointer to configuration event packet data structure. */ typedef struct caer_configuration_event_packet *caerConfigurationEventPacket; typedef const struct caer_configuration_event_packet *caerConfigurationEventPacketConst; /** * Allocate a new configuration events packet. * Use free() to reclaim this memory. * * @param eventCapacity the maximum number of events this packet will hold. * @param eventSource the unique ID representing the source/generator of this packet. * @param tsOverflow the current timestamp overflow counter value for this packet. * * @return a valid ConfigurationEventPacket handle or NULL on error. */ static inline caerConfigurationEventPacket caerConfigurationEventPacketAllocate( int32_t eventCapacity, int16_t eventSource, int32_t tsOverflow) { return ((caerConfigurationEventPacket) caerEventPacketAllocate(eventCapacity, eventSource, tsOverflow, CONFIG_EVENT, sizeof(struct caer_configuration_event), offsetof(struct caer_configuration_event, timestamp))); } /** * Transform a generic event packet header into a Configuration event packet. * This takes care of proper casting and checks that the packet type really matches * the intended conversion type. * * @param header a valid event packet header pointer. Cannot be NULL. * @return a properly converted, typed event packet pointer. */ static inline caerConfigurationEventPacket caerConfigurationEventPacketFromPacketHeader(caerEventPacketHeader header) { if (caerEventPacketHeaderGetEventType(header) != CONFIG_EVENT) { return (NULL); } return ((caerConfigurationEventPacket) header); } /** * Transform a generic read-only event packet header into a read-only Configuration event packet. * This takes care of proper casting and checks that the packet type really matches * the intended conversion type. * * @param header a valid read-only event packet header pointer. Cannot be NULL. * @return a properly converted, read-only typed event packet pointer. */ static inline caerConfigurationEventPacketConst caerConfigurationEventPacketFromPacketHeaderConst( caerEventPacketHeaderConst header) { if (caerEventPacketHeaderGetEventType(header) != CONFIG_EVENT) { return (NULL); } return ((caerConfigurationEventPacketConst) header); } /** * Get the configuration event at the given index from the event packet. * * @param packet a valid ConfigurationEventPacket pointer. Cannot be NULL. * @param n the index of the returned event. Must be within [0,eventCapacity[ bounds. * * @return the requested configuration event. NULL on error. */ static inline caerConfigurationEvent caerConfigurationEventPacketGetEvent( caerConfigurationEventPacket packet, int32_t n) { // Check that we're not out of bounds. if (n < 0 || n >= caerEventPacketHeaderGetEventCapacity(&packet->packetHeader)) { caerLogEHO(CAER_LOG_CRITICAL, "Configuration Event", "Called caerConfigurationEventPacketGetEvent() with invalid event offset %" PRIi32 ", while maximum allowed value is %" PRIi32 ".", n, caerEventPacketHeaderGetEventCapacity(&packet->packetHeader) - 1); return (NULL); } // Return a pointer to the specified event. return (packet->events + n); } /** * Get the configuration event at the given index from the event packet. * This is a read-only event, do not change its contents in any way! * * @param packet a valid ConfigurationEventPacket pointer. Cannot be NULL. * @param n the index of the returned event. Must be within [0,eventCapacity[ bounds. * * @return the requested read-only configuration event. NULL on error. */ static inline caerConfigurationEventConst caerConfigurationEventPacketGetEventConst( caerConfigurationEventPacketConst packet, int32_t n) { // Check that we're not out of bounds. if (n < 0 || n >= caerEventPacketHeaderGetEventCapacity(&packet->packetHeader)) { caerLogEHO(CAER_LOG_CRITICAL, "Configuration Event", "Called caerConfigurationEventPacketGetEventConst() with invalid event offset %" PRIi32 ", while maximum allowed value is %" PRIi32 ".", n, caerEventPacketHeaderGetEventCapacity(&packet->packetHeader) - 1); return (NULL); } // Return a pointer to the specified event. return (packet->events + n); } /** * Get the 32bit event timestamp, in microseconds. * Be aware that this wraps around! You can either ignore this fact, * or handle the special 'TIMESTAMP_WRAP' event that is generated when * this happens, or use the 64bit timestamp which never wraps around. * See 'caerEventPacketHeaderGetEventTSOverflow()' documentation * for more details on the 64bit timestamp. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * * @return this event's 32bit microsecond timestamp. */ static inline int32_t caerConfigurationEventGetTimestamp(caerConfigurationEventConst event) { return (I32T(le32toh(U32T(event->timestamp)))); } /** * Get the 64bit event timestamp, in microseconds. * See 'caerEventPacketHeaderGetEventTSOverflow()' documentation * for more details on the 64bit timestamp. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param packet the ConfigurationEventPacket pointer for the packet containing this event. Cannot be NULL. * * @return this event's 64bit microsecond timestamp. */ static inline int64_t caerConfigurationEventGetTimestamp64( caerConfigurationEventConst event, caerConfigurationEventPacketConst packet) { return (I64T((U64T(caerEventPacketHeaderGetEventTSOverflow(&packet->packetHeader)) << TS_OVERFLOW_SHIFT) | U64T(caerConfigurationEventGetTimestamp(event)))); } /** * Set the 32bit event timestamp, the value has to be in microseconds. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param timestamp a positive 32bit microsecond timestamp. */ static inline void caerConfigurationEventSetTimestamp(caerConfigurationEvent event, int32_t timestamp) { if (timestamp < 0) { // Negative means using the 31st bit! caerLogEHO(CAER_LOG_CRITICAL, "Configuration Event", "Called caerConfigurationEventSetTimestamp() with negative value!"); return; } event->timestamp = I32T(htole32(U32T(timestamp))); } /** * Check if this configuration event is valid. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * * @return true if valid, false if not. */ static inline bool caerConfigurationEventIsValid(caerConfigurationEventConst event) { return (GET_NUMBITS8(event->moduleAddress, VALID_MARK_SHIFT, VALID_MARK_MASK)); } /** * Validate the current event by setting its valid bit to true * and increasing the event packet's event count and valid * event count. Only works on events that are invalid. * DO NOT CALL THIS AFTER HAVING PREVIOUSLY ALREADY * INVALIDATED THIS EVENT, the total count will be incorrect. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param packet the ConfigurationEventPacket pointer for the packet containing this event. Cannot be NULL. */ static inline void caerConfigurationEventValidate(caerConfigurationEvent event, caerConfigurationEventPacket packet) { if (!caerConfigurationEventIsValid(event)) { SET_NUMBITS8(event->moduleAddress, VALID_MARK_SHIFT, VALID_MARK_MASK, 1); // Also increase number of events and valid events. // Only call this on (still) invalid events! caerEventPacketHeaderSetEventNumber( &packet->packetHeader, caerEventPacketHeaderGetEventNumber(&packet->packetHeader) + 1); caerEventPacketHeaderSetEventValid( &packet->packetHeader, caerEventPacketHeaderGetEventValid(&packet->packetHeader) + 1); } else { caerLogEHO(CAER_LOG_CRITICAL, "Configuration Event", "Called caerConfigurationEventValidate() on already valid event."); } } /** * Invalidate the current event by setting its valid bit * to false and decreasing the number of valid events held * in the packet. Only works with events that are already * valid! * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param packet the ConfigurationEventPacket pointer for the packet containing this event. Cannot be NULL. */ static inline void caerConfigurationEventInvalidate(caerConfigurationEvent event, caerConfigurationEventPacket packet) { if (caerConfigurationEventIsValid(event)) { CLEAR_NUMBITS8(event->moduleAddress, VALID_MARK_SHIFT, VALID_MARK_MASK); // Also decrease number of valid events. Number of total events doesn't change. // Only call this on valid events! caerEventPacketHeaderSetEventValid( &packet->packetHeader, caerEventPacketHeaderGetEventValid(&packet->packetHeader) - 1); } else { caerLogEHO(CAER_LOG_CRITICAL, "Configuration Event", "Called caerConfigurationEventInvalidate() on already invalid event."); } } /** * Get the configuration event's module address. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * * @return configuration module address. */ static inline uint8_t caerConfigurationEventGetModuleAddress(caerConfigurationEventConst event) { return U8T(GET_NUMBITS8(event->moduleAddress, CONFIG_MODULE_ADDR_SHIFT, CONFIG_MODULE_ADDR_MASK)); } /** * Set the configuration event's module address. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param moduleAddress configuration module address. */ static inline void caerConfigurationEventSetModuleAddress(caerConfigurationEvent event, uint8_t moduleAddress) { CLEAR_NUMBITS8(event->moduleAddress, CONFIG_MODULE_ADDR_SHIFT, CONFIG_MODULE_ADDR_MASK); SET_NUMBITS8(event->moduleAddress, CONFIG_MODULE_ADDR_SHIFT, CONFIG_MODULE_ADDR_MASK, moduleAddress); } /** * Get the configuration event's parameter address. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * * @return configuration parameter address. */ static inline uint8_t caerConfigurationEventGetParameterAddress(caerConfigurationEventConst event) { return (event->parameterAddress); } /** * Set the configuration event's parameter address. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param parameterAddress configuration parameter address. */ static inline void caerConfigurationEventSetParameterAddress(caerConfigurationEvent event, uint8_t parameterAddress) { event->parameterAddress = parameterAddress; } /** * Get the configuration event's parameter. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * * @return configuration parameter. */ static inline uint32_t caerConfigurationEventGetParameter(caerConfigurationEventConst event) { return (I32T(le32toh(event->parameter))); } /** * Set the configuration event's parameter. * * @param event a valid ConfigurationEvent pointer. Cannot be NULL. * @param parameter configuration parameter. */ static inline void caerConfigurationEventSetParameter(caerConfigurationEvent event, uint32_t parameter) { event->parameter = I32T(htole32(parameter)); } /** * Iterator over all configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEvent. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_ITERATOR_ALL_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter = 0; \ caerConfigurationIteratorCounter \ < caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader); \ caerConfigurationIteratorCounter++) { \ caerConfigurationEvent caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEvent(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); /** * Const-Iterator over all configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current read-only event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEventConst. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_CONST_ITERATOR_ALL_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter = 0; \ caerConfigurationIteratorCounter \ < caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader); \ caerConfigurationIteratorCounter++) { \ caerConfigurationEventConst caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEventConst(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); /** * Iterator close statement. */ #define CAER_CONFIGURATION_ITERATOR_ALL_END } /** * Iterator over only the valid configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEvent. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_ITERATOR_VALID_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter = 0; \ caerConfigurationIteratorCounter \ < caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader); \ caerConfigurationIteratorCounter++) { \ caerConfigurationEvent caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEvent(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); \ if (!caerConfigurationEventIsValid(caerConfigurationIteratorElement)) { \ continue; \ } // Skip invalid configuration events. /** * Const-Iterator over only the valid configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current read-only event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEventConst. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_CONST_ITERATOR_VALID_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter = 0; \ caerConfigurationIteratorCounter \ < caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader); \ caerConfigurationIteratorCounter++) { \ caerConfigurationEventConst caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEventConst(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); \ if (!caerConfigurationEventIsValid(caerConfigurationIteratorElement)) { \ continue; \ } // Skip invalid configuration events. /** * Iterator close statement. */ #define CAER_CONFIGURATION_ITERATOR_VALID_END } /** * Reverse iterator over all configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEvent. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_REVERSE_ITERATOR_ALL_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter \ = caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader) - 1; \ caerConfigurationIteratorCounter >= 0; caerConfigurationIteratorCounter--) { \ caerConfigurationEvent caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEvent(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); /** * Const-Reverse iterator over all configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current read-only event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEventConst. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_CONST_REVERSE_ITERATOR_ALL_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter \ = caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader) - 1; \ caerConfigurationIteratorCounter >= 0; caerConfigurationIteratorCounter--) { \ caerConfigurationEventConst caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEventConst(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); /** * Reverse iterator close statement. */ #define CAER_CONFIGURATION_REVERSE_ITERATOR_ALL_END } /** * Reverse iterator over only the valid configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEvent. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_REVERSE_ITERATOR_VALID_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter \ = caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader) - 1; \ caerConfigurationIteratorCounter >= 0; caerConfigurationIteratorCounter--) { \ caerConfigurationEvent caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEvent(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); \ if (!caerConfigurationEventIsValid(caerConfigurationIteratorElement)) { \ continue; \ } // Skip invalid configuration events. /** * Const-Reverse iterator over only the valid configuration events in a packet. * Returns the current index in the 'caerConfigurationIteratorCounter' variable of type * 'int32_t' and the current read-only event in the 'caerConfigurationIteratorElement' variable * of type caerConfigurationEventConst. * * CONFIGURATION_PACKET: a valid ConfigurationEventPacket pointer. Cannot be NULL. */ #define CAER_CONFIGURATION_CONST_REVERSE_ITERATOR_VALID_START(CONFIGURATION_PACKET) \ for (int32_t caerConfigurationIteratorCounter \ = caerEventPacketHeaderGetEventNumber(&(CONFIGURATION_PACKET)->packetHeader) - 1; \ caerConfigurationIteratorCounter >= 0; caerConfigurationIteratorCounter--) { \ caerConfigurationEventConst caerConfigurationIteratorElement \ = caerConfigurationEventPacketGetEventConst(CONFIGURATION_PACKET, caerConfigurationIteratorCounter); \ if (!caerConfigurationEventIsValid(caerConfigurationIteratorElement)) { \ continue; \ } // Skip invalid configuration events. /** * Reverse iterator close statement. */ #define CAER_CONFIGURATION_REVERSE_ITERATOR_VALID_END } #ifdef __cplusplus } #endif #endif /* LIBCAER_EVENTS_CONFIG_H_ */
44.839844
120
0.728853
[ "transform" ]
63bc3e4c7acc22c34ac6990ca9b19f4465c9af5c
31,169
c
C
head/sys/dev/cxgb/ulp/iw_cxgb/iw_cxgb_provider.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/sys/dev/cxgb/ulp/iw_cxgb/iw_cxgb_provider.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
head/sys/dev/cxgb/ulp/iw_cxgb/iw_cxgb_provider.c
dplbsd/soc2013
c134f5e2a5725af122c94005c5b1af3720706ce3
[ "BSD-2-Clause" ]
null
null
null
/************************************************************************** Copyright (c) 2007, Chelsio 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: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Neither the name of the Chelsio Corporation 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 <sys/cdefs.h> __FBSDID("$FreeBSD: soc2013/dpl/head/sys/dev/cxgb/ulp/iw_cxgb/iw_cxgb_provider.c 240143 2012-08-06 18:51:14Z dim $"); #include "opt_inet.h" #ifdef TCP_OFFLOAD #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/bus.h> #include <sys/pciio.h> #include <sys/conf.h> #include <machine/bus.h> #include <machine/resource.h> #include <sys/bus_dma.h> #include <sys/rman.h> #include <sys/ioccom.h> #include <sys/mbuf.h> #include <sys/mutex.h> #include <sys/rwlock.h> #include <sys/linker.h> #include <sys/firmware.h> #include <sys/socket.h> #include <sys/sockio.h> #include <sys/smp.h> #include <sys/sysctl.h> #include <sys/syslog.h> #include <sys/queue.h> #include <sys/taskqueue.h> #include <sys/proc.h> #include <sys/queue.h> #include <netinet/in.h> #include <vm/vm.h> #include <vm/pmap.h> #include <rdma/ib_verbs.h> #include <rdma/ib_umem.h> #include <rdma/ib_user_verbs.h> #include <linux/idr.h> #include <ulp/iw_cxgb/iw_cxgb_ib_intfc.h> #include <cxgb_include.h> #include <ulp/iw_cxgb/iw_cxgb_wr.h> #include <ulp/iw_cxgb/iw_cxgb_hal.h> #include <ulp/iw_cxgb/iw_cxgb_provider.h> #include <ulp/iw_cxgb/iw_cxgb_cm.h> #include <ulp/iw_cxgb/iw_cxgb.h> #include <ulp/iw_cxgb/iw_cxgb_resource.h> #include <ulp/iw_cxgb/iw_cxgb_user.h> static int iwch_modify_port(struct ib_device *ibdev, u8 port, int port_modify_mask, struct ib_port_modify *props) { return (-ENOSYS); } static struct ib_ah * iwch_ah_create(struct ib_pd *pd, struct ib_ah_attr *ah_attr) { return ERR_PTR(-ENOSYS); } static int iwch_ah_destroy(struct ib_ah *ah) { return (-ENOSYS); } static int iwch_multicast_attach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid) { return (-ENOSYS); } static int iwch_multicast_detach(struct ib_qp *ibqp, union ib_gid *gid, u16 lid) { return (-ENOSYS); } static int iwch_process_mad(struct ib_device *ibdev, int mad_flags, u8 port_num, struct ib_wc *in_wc, struct ib_grh *in_grh, struct ib_mad *in_mad, struct ib_mad *out_mad) { return (-ENOSYS); } static int iwch_dealloc_ucontext(struct ib_ucontext *context) { struct iwch_dev *rhp = to_iwch_dev(context->device); struct iwch_ucontext *ucontext = to_iwch_ucontext(context); struct iwch_mm_entry *mm, *tmp; CTR2(KTR_IW_CXGB, "%s context %p", __FUNCTION__, context); TAILQ_FOREACH_SAFE(mm, &ucontext->mmaps, entry, tmp) { TAILQ_REMOVE(&ucontext->mmaps, mm, entry); cxfree(mm); } cxio_release_ucontext(&rhp->rdev, &ucontext->uctx); cxfree(ucontext); return 0; } static struct ib_ucontext * iwch_alloc_ucontext(struct ib_device *ibdev, struct ib_udata *udata) { struct iwch_ucontext *context; struct iwch_dev *rhp = to_iwch_dev(ibdev); CTR2(KTR_IW_CXGB, "%s ibdev %p", __FUNCTION__, ibdev); context = malloc(sizeof(*context), M_DEVBUF, M_ZERO|M_NOWAIT); if (!context) return ERR_PTR(-ENOMEM); cxio_init_ucontext(&rhp->rdev, &context->uctx); TAILQ_INIT(&context->mmaps); mtx_init(&context->mmap_lock, "ucontext mmap", NULL, MTX_DEF); return &context->ibucontext; } static int iwch_destroy_cq(struct ib_cq *ib_cq) { struct iwch_cq *chp; CTR2(KTR_IW_CXGB, "%s ib_cq %p", __FUNCTION__, ib_cq); chp = to_iwch_cq(ib_cq); remove_handle(chp->rhp, &chp->rhp->cqidr, chp->cq.cqid); mtx_lock(&chp->lock); if (--chp->refcnt) msleep(chp, &chp->lock, 0, "iwch_destroy_cq", 0); mtx_unlock(&chp->lock); cxio_destroy_cq(&chp->rhp->rdev, &chp->cq); cxfree(chp); return 0; } static struct ib_cq * iwch_create_cq(struct ib_device *ibdev, int entries, int vector, struct ib_ucontext *ib_context, struct ib_udata *udata) { struct iwch_dev *rhp; struct iwch_cq *chp; struct iwch_create_cq_resp uresp; struct iwch_create_cq_req ureq; struct iwch_ucontext *ucontext = NULL; static int warned; size_t resplen; CTR3(KTR_IW_CXGB, "%s ib_dev %p entries %d", __FUNCTION__, ibdev, entries); rhp = to_iwch_dev(ibdev); chp = malloc(sizeof(*chp), M_DEVBUF, M_NOWAIT|M_ZERO); if (!chp) { return ERR_PTR(-ENOMEM); } if (ib_context) { ucontext = to_iwch_ucontext(ib_context); if (!t3a_device(rhp)) { if (ib_copy_from_udata(&ureq, udata, sizeof (ureq))) { cxfree(chp); return ERR_PTR(-EFAULT); } chp->user_rptr_addr = (u32 /*__user */*)(unsigned long)ureq.user_rptr_addr; } } if (t3a_device(rhp)) { /* * T3A: Add some fluff to handle extra CQEs inserted * for various errors. * Additional CQE possibilities: * TERMINATE, * incoming RDMA WRITE Failures * incoming RDMA READ REQUEST FAILUREs * NOTE: We cannot ensure the CQ won't overflow. */ entries += 16; } entries = roundup_pow_of_two(entries); chp->cq.size_log2 = ilog2(entries); if (cxio_create_cq(&rhp->rdev, &chp->cq, !ucontext)) { cxfree(chp); return ERR_PTR(-ENOMEM); } chp->rhp = rhp; chp->ibcq.cqe = 1 << chp->cq.size_log2; mtx_init(&chp->lock, "cxgb cq", NULL, MTX_DEF|MTX_DUPOK); chp->refcnt = 1; if (insert_handle(rhp, &rhp->cqidr, chp, chp->cq.cqid)) { cxio_destroy_cq(&chp->rhp->rdev, &chp->cq); cxfree(chp); return ERR_PTR(-ENOMEM); } if (ucontext) { struct iwch_mm_entry *mm; mm = kmalloc(sizeof *mm, M_NOWAIT); if (!mm) { iwch_destroy_cq(&chp->ibcq); return ERR_PTR(-ENOMEM); } uresp.cqid = chp->cq.cqid; uresp.size_log2 = chp->cq.size_log2; mtx_lock(&ucontext->mmap_lock); uresp.key = ucontext->key; ucontext->key += PAGE_SIZE; mtx_unlock(&ucontext->mmap_lock); mm->key = uresp.key; mm->addr = vtophys(chp->cq.queue); if (udata->outlen < sizeof uresp) { if (!warned++) CTR1(KTR_IW_CXGB, "%s Warning - " "downlevel libcxgb3 (non-fatal).\n", __func__); mm->len = PAGE_ALIGN((1UL << uresp.size_log2) * sizeof(struct t3_cqe)); resplen = sizeof(struct iwch_create_cq_resp_v0); } else { mm->len = PAGE_ALIGN(((1UL << uresp.size_log2) + 1) * sizeof(struct t3_cqe)); uresp.memsize = mm->len; resplen = sizeof uresp; } if (ib_copy_to_udata(udata, &uresp, resplen)) { cxfree(mm); iwch_destroy_cq(&chp->ibcq); return ERR_PTR(-EFAULT); } insert_mmap(ucontext, mm); } CTR4(KTR_IW_CXGB, "created cqid 0x%0x chp %p size 0x%0x, dma_addr 0x%0llx", chp->cq.cqid, chp, (1 << chp->cq.size_log2), (unsigned long long) chp->cq.dma_addr); return &chp->ibcq; } static int iwch_resize_cq(struct ib_cq *cq __unused, int cqe __unused, struct ib_udata *udata __unused) { return (-ENOSYS); } static int iwch_arm_cq(struct ib_cq *ibcq, enum ib_cq_notify_flags flags) { struct iwch_dev *rhp; struct iwch_cq *chp; enum t3_cq_opcode cq_op; int err; u32 rptr; chp = to_iwch_cq(ibcq); rhp = chp->rhp; if ((flags & IB_CQ_SOLICITED_MASK) == IB_CQ_SOLICITED) cq_op = CQ_ARM_SE; else cq_op = CQ_ARM_AN; if (chp->user_rptr_addr) { if (copyin(&rptr, chp->user_rptr_addr, 4)) return (-EFAULT); mtx_lock(&chp->lock); chp->cq.rptr = rptr; } else mtx_lock(&chp->lock); CTR2(KTR_IW_CXGB, "%s rptr 0x%x", __FUNCTION__, chp->cq.rptr); err = cxio_hal_cq_op(&rhp->rdev, &chp->cq, cq_op, 0); mtx_unlock(&chp->lock); if (err < 0) log(LOG_ERR, "Error %d rearming CQID 0x%x\n", err, chp->cq.cqid); if (err > 0 && !(flags & IB_CQ_REPORT_MISSED_EVENTS)) err = 0; return err; } static int iwch_mmap(struct ib_ucontext *context __unused, struct vm_area_struct *vma __unused) { return (-ENOSYS); } static int iwch_deallocate_pd(struct ib_pd *pd) { struct iwch_dev *rhp; struct iwch_pd *php; php = to_iwch_pd(pd); rhp = php->rhp; CTR3(KTR_IW_CXGB, "%s ibpd %p pdid 0x%x", __FUNCTION__, pd, php->pdid); cxio_hal_put_pdid(rhp->rdev.rscp, php->pdid); cxfree(php); return 0; } static struct ib_pd *iwch_allocate_pd(struct ib_device *ibdev, struct ib_ucontext *context, struct ib_udata *udata) { struct iwch_pd *php; u32 pdid; struct iwch_dev *rhp; CTR2(KTR_IW_CXGB, "%s ibdev %p", __FUNCTION__, ibdev); rhp = (struct iwch_dev *) ibdev; pdid = cxio_hal_get_pdid(rhp->rdev.rscp); if (!pdid) return ERR_PTR(-EINVAL); php = malloc(sizeof(*php), M_DEVBUF, M_ZERO|M_NOWAIT); if (!php) { cxio_hal_put_pdid(rhp->rdev.rscp, pdid); return ERR_PTR(-ENOMEM); } php->pdid = pdid; php->rhp = rhp; if (context) { if (ib_copy_to_udata(udata, &php->pdid, sizeof (__u32))) { iwch_deallocate_pd(&php->ibpd); return ERR_PTR(-EFAULT); } } CTR3(KTR_IW_CXGB, "%s pdid 0x%0x ptr 0x%p", __FUNCTION__, pdid, php); return &php->ibpd; } static int iwch_dereg_mr(struct ib_mr *ib_mr) { struct iwch_dev *rhp; struct iwch_mr *mhp; u32 mmid; CTR2(KTR_IW_CXGB, "%s ib_mr %p", __FUNCTION__, ib_mr); /* There can be no memory windows */ if (atomic_load_acq_int(&ib_mr->usecnt.counter)) return (-EINVAL); mhp = to_iwch_mr(ib_mr); rhp = mhp->rhp; mmid = mhp->attr.stag >> 8; cxio_dereg_mem(&rhp->rdev, mhp->attr.stag, mhp->attr.pbl_size, mhp->attr.pbl_addr); iwch_free_pbl(mhp); remove_handle(rhp, &rhp->mmidr, mmid); if (mhp->kva) cxfree((void *) (unsigned long) mhp->kva); if (mhp->umem) ib_umem_release(mhp->umem); CTR3(KTR_IW_CXGB, "%s mmid 0x%x ptr %p", __FUNCTION__, mmid, mhp); cxfree(mhp); return 0; } static struct ib_mr *iwch_register_phys_mem(struct ib_pd *pd, struct ib_phys_buf *buffer_list, int num_phys_buf, int acc, u64 *iova_start) { __be64 *page_list; int shift; u64 total_size; int npages; struct iwch_dev *rhp; struct iwch_pd *php; struct iwch_mr *mhp; int ret; CTR2(KTR_IW_CXGB, "%s ib_pd %p", __FUNCTION__, pd); php = to_iwch_pd(pd); rhp = php->rhp; mhp = malloc(sizeof(*mhp), M_DEVBUF, M_ZERO|M_NOWAIT); if (!mhp) return ERR_PTR(-ENOMEM); mhp->rhp = rhp; /* First check that we have enough alignment */ if ((*iova_start & ~PAGE_MASK) != (buffer_list[0].addr & ~PAGE_MASK)) { ret = -EINVAL; goto err; } if (num_phys_buf > 1 && ((buffer_list[0].addr + buffer_list[0].size) & ~PAGE_MASK)) { ret = -EINVAL; goto err; } ret = build_phys_page_list(buffer_list, num_phys_buf, iova_start, &total_size, &npages, &shift, &page_list); if (ret) goto err; ret = iwch_alloc_pbl(mhp, npages); if (ret) { cxfree(page_list); goto err_pbl; } ret = iwch_write_pbl(mhp, page_list, npages, 0); cxfree(page_list); if (ret) goto err; mhp->attr.pdid = php->pdid; mhp->attr.zbva = 0; mhp->attr.perms = iwch_ib_to_tpt_access(acc); mhp->attr.va_fbo = *iova_start; mhp->attr.page_size = shift - 12; mhp->attr.len = (u32) total_size; mhp->attr.pbl_size = npages; ret = iwch_register_mem(rhp, php, mhp, shift); if (ret) goto err_pbl; return &mhp->ibmr; err_pbl: iwch_free_pbl(mhp); err: cxfree(mhp); return ERR_PTR(ret); } static int iwch_reregister_phys_mem(struct ib_mr *mr, int mr_rereg_mask, struct ib_pd *pd, struct ib_phys_buf *buffer_list, int num_phys_buf, int acc, u64 * iova_start) { struct iwch_mr mh, *mhp; struct iwch_pd *php; struct iwch_dev *rhp; __be64 *page_list = NULL; int shift = 0; u64 total_size; int npages = 0; int ret; CTR3(KTR_IW_CXGB, "%s ib_mr %p ib_pd %p", __FUNCTION__, mr, pd); /* There can be no memory windows */ if (atomic_load_acq_int(&mr->usecnt.counter)) return (-EINVAL); mhp = to_iwch_mr(mr); rhp = mhp->rhp; php = to_iwch_pd(mr->pd); /* make sure we are on the same adapter */ if (rhp != php->rhp) return (-EINVAL); memcpy(&mh, mhp, sizeof *mhp); if (mr_rereg_mask & IB_MR_REREG_PD) php = to_iwch_pd(pd); if (mr_rereg_mask & IB_MR_REREG_ACCESS) mh.attr.perms = iwch_ib_to_tpt_access(acc); if (mr_rereg_mask & IB_MR_REREG_TRANS) { ret = build_phys_page_list(buffer_list, num_phys_buf, iova_start, &total_size, &npages, &shift, &page_list); if (ret) return ret; } ret = iwch_reregister_mem(rhp, php, &mh, shift, npages); cxfree(page_list); if (ret) { return ret; } if (mr_rereg_mask & IB_MR_REREG_PD) mhp->attr.pdid = php->pdid; if (mr_rereg_mask & IB_MR_REREG_ACCESS) mhp->attr.perms = iwch_ib_to_tpt_access(acc); if (mr_rereg_mask & IB_MR_REREG_TRANS) { mhp->attr.zbva = 0; mhp->attr.va_fbo = *iova_start; mhp->attr.page_size = shift - 12; mhp->attr.len = (u32) total_size; mhp->attr.pbl_size = npages; } return 0; } static struct ib_mr *iwch_reg_user_mr(struct ib_pd *pd, u64 start, u64 length, u64 virt, int acc, struct ib_udata *udata) { __be64 *pages; int shift, i, n; int err = 0; struct ib_umem_chunk *chunk; struct iwch_dev *rhp; struct iwch_pd *php; struct iwch_mr *mhp; struct iwch_reg_user_mr_resp uresp; #ifdef notyet int j, k, len; #endif CTR2(KTR_IW_CXGB, "%s ib_pd %p", __FUNCTION__, pd); php = to_iwch_pd(pd); rhp = php->rhp; mhp = malloc(sizeof(*mhp), M_DEVBUF, M_NOWAIT|M_ZERO); if (!mhp) return ERR_PTR(-ENOMEM); mhp->rhp = rhp; mhp->umem = ib_umem_get(pd->uobject->context, start, length, acc, 0); if (IS_ERR(mhp->umem)) { err = PTR_ERR(mhp->umem); cxfree(mhp); return ERR_PTR(-err); } shift = ffs(mhp->umem->page_size) - 1; n = 0; list_for_each_entry(chunk, &mhp->umem->chunk_list, list) n += chunk->nents; err = iwch_alloc_pbl(mhp, n); if (err) goto err; pages = (__be64 *) kmalloc(n * sizeof(u64), M_NOWAIT); if (!pages) { err = -ENOMEM; goto err_pbl; } i = n = 0; #ifdef notyet TAILQ_FOREACH(chunk, &mhp->umem->chunk_list, entry) for (j = 0; j < chunk->nmap; ++j) { len = sg_dma_len(&chunk->page_list[j]) >> shift; for (k = 0; k < len; ++k) { pages[i++] = htobe64(sg_dma_address( &chunk->page_list[j]) + mhp->umem->page_size * k); if (i == PAGE_SIZE / sizeof *pages) { err = iwch_write_pbl(mhp, pages, i, n); if (err) goto pbl_done; n += i; i = 0; } } } #endif if (i) err = iwch_write_pbl(mhp, pages, i, n); #ifdef notyet pbl_done: #endif cxfree(pages); if (err) goto err_pbl; mhp->attr.pdid = php->pdid; mhp->attr.zbva = 0; mhp->attr.perms = iwch_ib_to_tpt_access(acc); mhp->attr.va_fbo = virt; mhp->attr.page_size = shift - 12; mhp->attr.len = (u32) length; err = iwch_register_mem(rhp, php, mhp, shift); if (err) goto err_pbl; if (udata && !t3a_device(rhp)) { uresp.pbl_addr = (mhp->attr.pbl_addr - rhp->rdev.rnic_info.pbl_base) >> 3; CTR2(KTR_IW_CXGB, "%s user resp pbl_addr 0x%x", __FUNCTION__, uresp.pbl_addr); if (ib_copy_to_udata(udata, &uresp, sizeof (uresp))) { iwch_dereg_mr(&mhp->ibmr); err = EFAULT; goto err; } } return &mhp->ibmr; err_pbl: iwch_free_pbl(mhp); err: ib_umem_release(mhp->umem); cxfree(mhp); return ERR_PTR(-err); } static struct ib_mr *iwch_get_dma_mr(struct ib_pd *pd, int acc) { struct ib_phys_buf bl; u64 kva; struct ib_mr *ibmr; CTR2(KTR_IW_CXGB, "%s ib_pd %p", __FUNCTION__, pd); /* * T3 only supports 32 bits of size. */ bl.size = 0xffffffff; bl.addr = 0; kva = 0; ibmr = iwch_register_phys_mem(pd, &bl, 1, acc, &kva); return ibmr; } static struct ib_mw *iwch_alloc_mw(struct ib_pd *pd) { struct iwch_dev *rhp; struct iwch_pd *php; struct iwch_mw *mhp; u32 mmid; u32 stag = 0; int ret; php = to_iwch_pd(pd); rhp = php->rhp; mhp = malloc(sizeof(*mhp), M_DEVBUF, M_ZERO|M_NOWAIT); if (!mhp) return ERR_PTR(-ENOMEM); ret = cxio_allocate_window(&rhp->rdev, &stag, php->pdid); if (ret) { cxfree(mhp); return ERR_PTR(-ret); } mhp->rhp = rhp; mhp->attr.pdid = php->pdid; mhp->attr.type = TPT_MW; mhp->attr.stag = stag; mmid = (stag) >> 8; mhp->ibmw.rkey = stag; if (insert_handle(rhp, &rhp->mmidr, mhp, mmid)) { cxio_deallocate_window(&rhp->rdev, mhp->attr.stag); cxfree(mhp); return ERR_PTR(-ENOMEM); } CTR4(KTR_IW_CXGB, "%s mmid 0x%x mhp %p stag 0x%x", __FUNCTION__, mmid, mhp, stag); return &(mhp->ibmw); } static int iwch_dealloc_mw(struct ib_mw *mw) { struct iwch_dev *rhp; struct iwch_mw *mhp; u32 mmid; mhp = to_iwch_mw(mw); rhp = mhp->rhp; mmid = (mw->rkey) >> 8; cxio_deallocate_window(&rhp->rdev, mhp->attr.stag); remove_handle(rhp, &rhp->mmidr, mmid); cxfree(mhp); CTR4(KTR_IW_CXGB, "%s ib_mw %p mmid 0x%x ptr %p", __FUNCTION__, mw, mmid, mhp); return 0; } static int iwch_destroy_qp(struct ib_qp *ib_qp) { struct iwch_dev *rhp; struct iwch_qp *qhp; struct iwch_qp_attributes attrs; struct iwch_ucontext *ucontext; qhp = to_iwch_qp(ib_qp); rhp = qhp->rhp; attrs.next_state = IWCH_QP_STATE_ERROR; iwch_modify_qp(rhp, qhp, IWCH_QP_ATTR_NEXT_STATE, &attrs, 0); mtx_lock(&qhp->lock); if (qhp->ep) msleep(qhp, &qhp->lock, 0, "iwch_destroy_qp1", 0); mtx_unlock(&qhp->lock); remove_handle(rhp, &rhp->qpidr, qhp->wq.qpid); mtx_lock(&qhp->lock); if (--qhp->refcnt) msleep(qhp, &qhp->lock, 0, "iwch_destroy_qp2", 0); mtx_unlock(&qhp->lock); ucontext = ib_qp->uobject ? to_iwch_ucontext(ib_qp->uobject->context) : NULL; cxio_destroy_qp(&rhp->rdev, &qhp->wq, ucontext ? &ucontext->uctx : &rhp->rdev.uctx); CTR4(KTR_IW_CXGB, "%s ib_qp %p qpid 0x%0x qhp %p", __FUNCTION__, ib_qp, qhp->wq.qpid, qhp); cxfree(qhp); return 0; } static struct ib_qp *iwch_create_qp(struct ib_pd *pd, struct ib_qp_init_attr *attrs, struct ib_udata *udata) { struct iwch_dev *rhp; struct iwch_qp *qhp; struct iwch_pd *php; struct iwch_cq *schp; struct iwch_cq *rchp; struct iwch_create_qp_resp uresp; int wqsize, sqsize, rqsize; struct iwch_ucontext *ucontext; CTR2(KTR_IW_CXGB, "%s ib_pd %p", __FUNCTION__, pd); if (attrs->qp_type != IB_QPT_RC) return ERR_PTR(-EINVAL); php = to_iwch_pd(pd); rhp = php->rhp; schp = get_chp(rhp, ((struct iwch_cq *) attrs->send_cq)->cq.cqid); rchp = get_chp(rhp, ((struct iwch_cq *) attrs->recv_cq)->cq.cqid); if (!schp || !rchp) return ERR_PTR(-EINVAL); /* The RQT size must be # of entries + 1 rounded up to a power of two */ rqsize = roundup_pow_of_two(attrs->cap.max_recv_wr); if (rqsize == attrs->cap.max_recv_wr) rqsize = roundup_pow_of_two(attrs->cap.max_recv_wr+1); /* T3 doesn't support RQT depth < 16 */ if (rqsize < 16) rqsize = 16; if (rqsize > T3_MAX_RQ_SIZE) return ERR_PTR(-EINVAL); if (attrs->cap.max_inline_data > T3_MAX_INLINE) return ERR_PTR(-EINVAL); /* * NOTE: The SQ and total WQ sizes don't need to be * a power of two. However, all the code assumes * they are. EG: Q_FREECNT() and friends. */ sqsize = roundup_pow_of_two(attrs->cap.max_send_wr); wqsize = roundup_pow_of_two(rqsize + sqsize); CTR4(KTR_IW_CXGB, "%s wqsize %d sqsize %d rqsize %d", __FUNCTION__, wqsize, sqsize, rqsize); qhp = malloc(sizeof(*qhp), M_DEVBUF, M_ZERO|M_NOWAIT); if (!qhp) return ERR_PTR(-ENOMEM); qhp->wq.size_log2 = ilog2(wqsize); qhp->wq.rq_size_log2 = ilog2(rqsize); qhp->wq.sq_size_log2 = ilog2(sqsize); ucontext = pd->uobject ? to_iwch_ucontext(pd->uobject->context) : NULL; if (cxio_create_qp(&rhp->rdev, !udata, &qhp->wq, ucontext ? &ucontext->uctx : &rhp->rdev.uctx)) { cxfree(qhp); return ERR_PTR(-ENOMEM); } attrs->cap.max_recv_wr = rqsize - 1; attrs->cap.max_send_wr = sqsize; attrs->cap.max_inline_data = T3_MAX_INLINE; qhp->rhp = rhp; qhp->attr.pd = php->pdid; qhp->attr.scq = ((struct iwch_cq *) attrs->send_cq)->cq.cqid; qhp->attr.rcq = ((struct iwch_cq *) attrs->recv_cq)->cq.cqid; qhp->attr.sq_num_entries = attrs->cap.max_send_wr; qhp->attr.rq_num_entries = attrs->cap.max_recv_wr; qhp->attr.sq_max_sges = attrs->cap.max_send_sge; qhp->attr.sq_max_sges_rdma_write = attrs->cap.max_send_sge; qhp->attr.rq_max_sges = attrs->cap.max_recv_sge; qhp->attr.state = IWCH_QP_STATE_IDLE; qhp->attr.next_state = IWCH_QP_STATE_IDLE; /* * XXX - These don't get passed in from the openib user * at create time. The CM sets them via a QP modify. * Need to fix... I think the CM should */ qhp->attr.enable_rdma_read = 1; qhp->attr.enable_rdma_write = 1; qhp->attr.enable_bind = 1; qhp->attr.max_ord = 1; qhp->attr.max_ird = 1; mtx_init(&qhp->lock, "cxgb qp", NULL, MTX_DEF|MTX_DUPOK); qhp->refcnt = 1; if (insert_handle(rhp, &rhp->qpidr, qhp, qhp->wq.qpid)) { cxio_destroy_qp(&rhp->rdev, &qhp->wq, ucontext ? &ucontext->uctx : &rhp->rdev.uctx); cxfree(qhp); return ERR_PTR(-ENOMEM); } if (udata) { struct iwch_mm_entry *mm1, *mm2; mm1 = kmalloc(sizeof *mm1, M_NOWAIT); if (!mm1) { iwch_destroy_qp(&qhp->ibqp); return ERR_PTR(-ENOMEM); } mm2 = kmalloc(sizeof *mm2, M_NOWAIT); if (!mm2) { cxfree(mm1); iwch_destroy_qp(&qhp->ibqp); return ERR_PTR(-ENOMEM); } uresp.qpid = qhp->wq.qpid; uresp.size_log2 = qhp->wq.size_log2; uresp.sq_size_log2 = qhp->wq.sq_size_log2; uresp.rq_size_log2 = qhp->wq.rq_size_log2; mtx_lock(&ucontext->mmap_lock); uresp.key = ucontext->key; ucontext->key += PAGE_SIZE; uresp.db_key = ucontext->key; ucontext->key += PAGE_SIZE; mtx_unlock(&ucontext->mmap_lock); if (ib_copy_to_udata(udata, &uresp, sizeof (uresp))) { cxfree(mm1); cxfree(mm2); iwch_destroy_qp(&qhp->ibqp); return ERR_PTR(-EFAULT); } mm1->key = uresp.key; mm1->addr = vtophys(qhp->wq.queue); mm1->len = PAGE_ALIGN(wqsize * sizeof (union t3_wr)); insert_mmap(ucontext, mm1); mm2->key = uresp.db_key; mm2->addr = qhp->wq.udb & PAGE_MASK; mm2->len = PAGE_SIZE; insert_mmap(ucontext, mm2); } qhp->ibqp.qp_num = qhp->wq.qpid; callout_init(&(qhp->timer), TRUE); CTR6(KTR_IW_CXGB, "sq_num_entries %d, rq_num_entries %d " "qpid 0x%0x qhp %p dma_addr 0x%llx size %d", qhp->attr.sq_num_entries, qhp->attr.rq_num_entries, qhp->wq.qpid, qhp, (unsigned long long) qhp->wq.dma_addr, 1 << qhp->wq.size_log2); return &qhp->ibqp; } static int iwch_ib_modify_qp(struct ib_qp *ibqp, struct ib_qp_attr *attr, int attr_mask, struct ib_udata *udata) { struct iwch_dev *rhp; struct iwch_qp *qhp; enum iwch_qp_attr_mask mask = 0; struct iwch_qp_attributes attrs; CTR2(KTR_IW_CXGB, "%s ib_qp %p", __FUNCTION__, ibqp); /* iwarp does not support the RTR state */ if ((attr_mask & IB_QP_STATE) && (attr->qp_state == IB_QPS_RTR)) attr_mask &= ~IB_QP_STATE; /* Make sure we still have something left to do */ if (!attr_mask) return 0; memset(&attrs, 0, sizeof attrs); qhp = to_iwch_qp(ibqp); rhp = qhp->rhp; attrs.next_state = iwch_convert_state(attr->qp_state); attrs.enable_rdma_read = (attr->qp_access_flags & IB_ACCESS_REMOTE_READ) ? 1 : 0; attrs.enable_rdma_write = (attr->qp_access_flags & IB_ACCESS_REMOTE_WRITE) ? 1 : 0; attrs.enable_bind = (attr->qp_access_flags & IB_ACCESS_MW_BIND) ? 1 : 0; mask |= (attr_mask & IB_QP_STATE) ? IWCH_QP_ATTR_NEXT_STATE : 0; mask |= (attr_mask & IB_QP_ACCESS_FLAGS) ? (IWCH_QP_ATTR_ENABLE_RDMA_READ | IWCH_QP_ATTR_ENABLE_RDMA_WRITE | IWCH_QP_ATTR_ENABLE_RDMA_BIND) : 0; return iwch_modify_qp(rhp, qhp, mask, &attrs, 0); } void iwch_qp_add_ref(struct ib_qp *qp) { CTR2(KTR_IW_CXGB, "%s ib_qp %p", __FUNCTION__, qp); mtx_lock(&to_iwch_qp(qp)->lock); to_iwch_qp(qp)->refcnt++; mtx_unlock(&to_iwch_qp(qp)->lock); } void iwch_qp_rem_ref(struct ib_qp *qp) { CTR2(KTR_IW_CXGB, "%s ib_qp %p", __FUNCTION__, qp); mtx_lock(&to_iwch_qp(qp)->lock); if (--to_iwch_qp(qp)->refcnt == 0) wakeup(to_iwch_qp(qp)); mtx_unlock(&to_iwch_qp(qp)->lock); } static struct ib_qp *iwch_get_qp(struct ib_device *dev, int qpn) { CTR3(KTR_IW_CXGB, "%s ib_dev %p qpn 0x%x", __FUNCTION__, dev, qpn); return (struct ib_qp *)get_qhp(to_iwch_dev(dev), qpn); } static int iwch_query_pkey(struct ib_device *ibdev, u8 port, u16 index, u16 * pkey) { CTR2(KTR_IW_CXGB, "%s ibdev %p", __FUNCTION__, ibdev); *pkey = 0; return 0; } static int iwch_query_gid(struct ib_device *ibdev, u8 port, int index, union ib_gid *gid) { struct iwch_dev *dev; struct port_info *pi; struct adapter *sc; CTR5(KTR_IW_CXGB, "%s ibdev %p, port %d, index %d, gid %p", __FUNCTION__, ibdev, port, index, gid); dev = to_iwch_dev(ibdev); sc = dev->rdev.adap; PANIC_IF(port == 0 || port > 2); pi = &sc->port[port - 1]; memset(&(gid->raw[0]), 0, sizeof(gid->raw)); memcpy(&(gid->raw[0]), pi->hw_addr, 6); return 0; } static int iwch_query_device(struct ib_device *ibdev, struct ib_device_attr *props) { struct iwch_dev *dev; struct adapter *sc; CTR2(KTR_IW_CXGB, "%s ibdev %p", __FUNCTION__, ibdev); dev = to_iwch_dev(ibdev); sc = dev->rdev.adap; memset(props, 0, sizeof *props); memcpy(&props->sys_image_guid, sc->port[0].hw_addr, 6); props->device_cap_flags = dev->device_cap_flags; props->page_size_cap = dev->attr.mem_pgsizes_bitmask; props->vendor_id = pci_get_vendor(sc->dev); props->vendor_part_id = pci_get_device(sc->dev); props->max_mr_size = dev->attr.max_mr_size; props->max_qp = dev->attr.max_qps; props->max_qp_wr = dev->attr.max_wrs; props->max_sge = dev->attr.max_sge_per_wr; props->max_sge_rd = 1; props->max_qp_rd_atom = dev->attr.max_rdma_reads_per_qp; props->max_qp_init_rd_atom = dev->attr.max_rdma_reads_per_qp; props->max_cq = dev->attr.max_cqs; props->max_cqe = dev->attr.max_cqes_per_cq; props->max_mr = dev->attr.max_mem_regs; props->max_pd = dev->attr.max_pds; props->local_ca_ack_delay = 0; return 0; } static int iwch_query_port(struct ib_device *ibdev, u8 port, struct ib_port_attr *props) { CTR2(KTR_IW_CXGB, "%s ibdev %p", __FUNCTION__, ibdev); memset(props, 0, sizeof(struct ib_port_attr)); props->max_mtu = IB_MTU_4096; props->active_mtu = IB_MTU_2048; props->state = IB_PORT_ACTIVE; props->port_cap_flags = IB_PORT_CM_SUP | IB_PORT_SNMP_TUNNEL_SUP | IB_PORT_REINIT_SUP | IB_PORT_DEVICE_MGMT_SUP | IB_PORT_VENDOR_CLASS_SUP | IB_PORT_BOOT_MGMT_SUP; props->gid_tbl_len = 1; props->pkey_tbl_len = 1; props->active_width = 2; props->active_speed = 2; props->max_msg_sz = -1; return 0; } int iwch_register_device(struct iwch_dev *dev) { int ret; struct adapter *sc = dev->rdev.adap; CTR2(KTR_IW_CXGB, "%s iwch_dev %p", __FUNCTION__, dev); strlcpy(dev->ibdev.name, "cxgb3_%d", IB_DEVICE_NAME_MAX); memset(&dev->ibdev.node_guid, 0, sizeof(dev->ibdev.node_guid)); memcpy(&dev->ibdev.node_guid, sc->port[0].hw_addr, 6); dev->device_cap_flags = (IB_DEVICE_LOCAL_DMA_LKEY | IB_DEVICE_MEM_WINDOW); dev->ibdev.uverbs_cmd_mask = (1ull << IB_USER_VERBS_CMD_GET_CONTEXT) | (1ull << IB_USER_VERBS_CMD_QUERY_DEVICE) | (1ull << IB_USER_VERBS_CMD_QUERY_PORT) | (1ull << IB_USER_VERBS_CMD_ALLOC_PD) | (1ull << IB_USER_VERBS_CMD_DEALLOC_PD) | (1ull << IB_USER_VERBS_CMD_REG_MR) | (1ull << IB_USER_VERBS_CMD_DEREG_MR) | (1ull << IB_USER_VERBS_CMD_CREATE_COMP_CHANNEL) | (1ull << IB_USER_VERBS_CMD_CREATE_CQ) | (1ull << IB_USER_VERBS_CMD_DESTROY_CQ) | (1ull << IB_USER_VERBS_CMD_REQ_NOTIFY_CQ) | (1ull << IB_USER_VERBS_CMD_CREATE_QP) | (1ull << IB_USER_VERBS_CMD_MODIFY_QP) | (1ull << IB_USER_VERBS_CMD_POLL_CQ) | (1ull << IB_USER_VERBS_CMD_DESTROY_QP) | (1ull << IB_USER_VERBS_CMD_POST_SEND) | (1ull << IB_USER_VERBS_CMD_POST_RECV); dev->ibdev.node_type = RDMA_NODE_RNIC; memcpy(dev->ibdev.node_desc, IWCH_NODE_DESC, sizeof(IWCH_NODE_DESC)); dev->ibdev.phys_port_cnt = sc->params.nports; dev->ibdev.num_comp_vectors = 1; dev->ibdev.dma_device = dev->rdev.adap->dev; dev->ibdev.query_device = iwch_query_device; dev->ibdev.query_port = iwch_query_port; dev->ibdev.modify_port = iwch_modify_port; dev->ibdev.query_pkey = iwch_query_pkey; dev->ibdev.query_gid = iwch_query_gid; dev->ibdev.alloc_ucontext = iwch_alloc_ucontext; dev->ibdev.dealloc_ucontext = iwch_dealloc_ucontext; dev->ibdev.mmap = iwch_mmap; dev->ibdev.alloc_pd = iwch_allocate_pd; dev->ibdev.dealloc_pd = iwch_deallocate_pd; dev->ibdev.create_ah = iwch_ah_create; dev->ibdev.destroy_ah = iwch_ah_destroy; dev->ibdev.create_qp = iwch_create_qp; dev->ibdev.modify_qp = iwch_ib_modify_qp; dev->ibdev.destroy_qp = iwch_destroy_qp; dev->ibdev.create_cq = iwch_create_cq; dev->ibdev.destroy_cq = iwch_destroy_cq; dev->ibdev.resize_cq = iwch_resize_cq; dev->ibdev.poll_cq = iwch_poll_cq; dev->ibdev.get_dma_mr = iwch_get_dma_mr; dev->ibdev.reg_phys_mr = iwch_register_phys_mem; dev->ibdev.rereg_phys_mr = iwch_reregister_phys_mem; dev->ibdev.reg_user_mr = iwch_reg_user_mr; dev->ibdev.dereg_mr = iwch_dereg_mr; dev->ibdev.alloc_mw = iwch_alloc_mw; dev->ibdev.bind_mw = iwch_bind_mw; dev->ibdev.dealloc_mw = iwch_dealloc_mw; dev->ibdev.attach_mcast = iwch_multicast_attach; dev->ibdev.detach_mcast = iwch_multicast_detach; dev->ibdev.process_mad = iwch_process_mad; dev->ibdev.req_notify_cq = iwch_arm_cq; dev->ibdev.post_send = iwch_post_send; dev->ibdev.post_recv = iwch_post_receive; dev->ibdev.uverbs_abi_ver = IWCH_UVERBS_ABI_VERSION; dev->ibdev.iwcm = kmalloc(sizeof(struct iw_cm_verbs), M_NOWAIT); if (!dev->ibdev.iwcm) return (ENOMEM); dev->ibdev.iwcm->connect = iwch_connect; dev->ibdev.iwcm->accept = iwch_accept_cr; dev->ibdev.iwcm->reject = iwch_reject_cr; dev->ibdev.iwcm->create_listen = iwch_create_listen; dev->ibdev.iwcm->destroy_listen = iwch_destroy_listen; dev->ibdev.iwcm->add_ref = iwch_qp_add_ref; dev->ibdev.iwcm->rem_ref = iwch_qp_rem_ref; dev->ibdev.iwcm->get_qp = iwch_get_qp; ret = ib_register_device(&dev->ibdev); if (ret) goto bail1; return (0); bail1: cxfree(dev->ibdev.iwcm); return (ret); } void iwch_unregister_device(struct iwch_dev *dev) { ib_unregister_device(&dev->ibdev); cxfree(dev->ibdev.iwcm); return; } #endif
26.916235
117
0.681125
[ "vector" ]
63bd86b72851138f5db963fc0e95f9a556380b59
767
h
C
include/utils.h
4n6ist/usn_analytics
ad84d93ba6e2be38a2db6ce1add453ed6bdb83b4
[ "Apache-2.0" ]
18
2018-01-25T02:28:02.000Z
2021-12-16T04:26:47.000Z
include/utils.h
4n6ist/usn_analytics
ad84d93ba6e2be38a2db6ce1add453ed6bdb83b4
[ "Apache-2.0" ]
3
2018-01-27T03:01:37.000Z
2018-01-28T03:01:37.000Z
include/utils.h
4n6ist/usn_analytics
ad84d93ba6e2be38a2db6ce1add453ed6bdb83b4
[ "Apache-2.0" ]
3
2018-02-21T15:56:50.000Z
2021-08-18T03:18:13.000Z
#ifndef _INCLUDE_UTILS_H #define _INCLUDE_UTILS_H #include <cstdint> #include <string> #include <vector> #include <ctime> #include <sys/stat.h> #include <sys/types.h> using namespace std; class timer { clock_t c_start; time_t t_start; public: timer(); ~timer(); }; bool is_empty_dir(const char *); uint64_t get_file_size(const char*); string parse_datetime(uint64_t, bool); string parse_datetime_iso8601(uint64_t, bool); string parse_datetimemicro(uint64_t, bool); string join(const vector<string>&, const char*); uint16_t parse_file_attr(uint32_t, string*); uint16_t parse_reason(uint32_t, string*); string UTF16toUTF8(char16_t*, int); bool is_valid_ts(uint64_t); bool is_valid_usn(uint64_t); string get_timezone_str (bool); #endif // _INCLUDE_UTILS_H
22.558824
48
0.769231
[ "vector" ]
63c0e343d3880793dd05fbf06c1e9ea592c3f10c
142,910
c
C
kernel/kernel-4.9/drivers/pci/host/pci-tegra.c
rubedos/l4t_R32.5.1_viper
6aed0062084d9031546f946e63fc74303555e0a6
[ "MIT" ]
null
null
null
kernel/kernel-4.9/drivers/pci/host/pci-tegra.c
rubedos/l4t_R32.5.1_viper
6aed0062084d9031546f946e63fc74303555e0a6
[ "MIT" ]
null
null
null
kernel/kernel-4.9/drivers/pci/host/pci-tegra.c
rubedos/l4t_R32.5.1_viper
6aed0062084d9031546f946e63fc74303555e0a6
[ "MIT" ]
null
null
null
/* * PCIe host controller driver for TEGRA SOCs * * Copyright (c) 2010, CompuLab, Ltd. * Author: Mike Rapoport <mike@compulab.co.il> * * Based on NVIDIA PCIe driver * Copyright (c) 2008-2018, NVIDIA Corporation. All rights reserved. * * Bits taken from arch/arm/mach-dove/pcie.c * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for * more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/debugfs.h> #include <linux/uaccess.h> #include <linux/pci.h> #include <linux/pci-aspm.h> #include <linux/interrupt.h> #include <linux/irq.h> #include <linux/irqdomain.h> #include <linux/clk.h> #include <linux/reset.h> #include <linux/delay.h> #include <linux/export.h> #include <linux/msi.h> #include <linux/slab.h> #include <linux/platform_device.h> #include <linux/regulator/consumer.h> #include <linux/workqueue.h> #include <linux/gpio.h> #include <linux/clk.h> #include <linux/async.h> #include <linux/vmalloc.h> #include <linux/pm_runtime.h> #include <soc/tegra/chip-id.h> #include <linux/of_device.h> #include <linux/of_address.h> #include <linux/of_gpio.h> #include <linux/of_pci.h> #include <linux/tegra_prod.h> #include <linux/pinctrl/pinctrl.h> #include <linux/pinctrl/consumer.h> #include <linux/platform/tegra/emc_bwmgr.h> #include <linux/pm_clock.h> #ifdef CONFIG_THERMAL #include <linux/thermal.h> #endif #include <asm/sizes.h> #include <asm/mach/pci.h> #include <asm/io.h> #include <linux/phy/phy.h> #include <linux/pci-tegra.h> #define PCI_CFG_SPACE_SIZE 256 #define PCI_EXT_CFG_SPACE_SIZE 4096 #define AFI_AXI_BAR0_SZ 0x00 #define AFI_AXI_BAR1_SZ 0x04 #define AFI_AXI_BAR2_SZ 0x08 #define AFI_AXI_BAR3_SZ 0x0c #define AFI_AXI_BAR4_SZ 0x10 #define AFI_AXI_BAR5_SZ 0x14 #define AFI_AXI_BAR0_START 0x18 #define AFI_AXI_BAR1_START 0x1c #define AFI_AXI_BAR2_START 0x20 #define AFI_AXI_BAR3_START 0x24 #define AFI_AXI_BAR4_START 0x28 #define AFI_AXI_BAR5_START 0x2c #define AFI_FPCI_BAR0 0x30 #define AFI_FPCI_BAR1 0x34 #define AFI_FPCI_BAR2 0x38 #define AFI_FPCI_BAR3 0x3c #define AFI_FPCI_BAR4 0x40 #define AFI_FPCI_BAR5 0x44 #define AFI_MSI_BAR_SZ 0x60 #define AFI_MSI_FPCI_BAR_ST 0x64 #define AFI_MSI_AXI_BAR_ST 0x68 #define AFI_MSI_VEC0_0 0x6c #define AFI_MSI_VEC1_0 0x70 #define AFI_MSI_VEC2_0 0x74 #define AFI_MSI_VEC3_0 0x78 #define AFI_MSI_VEC4_0 0x7c #define AFI_MSI_VEC5_0 0x80 #define AFI_MSI_VEC6_0 0x84 #define AFI_MSI_VEC7_0 0x88 #define AFI_MSI_EN_VEC0_0 0x8c #define AFI_MSI_EN_VEC1_0 0x90 #define AFI_MSI_EN_VEC2_0 0x94 #define AFI_MSI_EN_VEC3_0 0x98 #define AFI_MSI_EN_VEC4_0 0x9c #define AFI_MSI_EN_VEC5_0 0xa0 #define AFI_MSI_EN_VEC6_0 0xa4 #define AFI_MSI_EN_VEC7_0 0xa8 #define AFI_CONFIGURATION 0xac #define AFI_CONFIGURATION_EN_FPCI (1 << 0) #define AFI_CONFIGURATION_CLKEN_OVERRIDE (1 << 31) #define AFI_FPCI_ERROR_MASKS 0xb0 #define AFI_INTR_MASK 0xb4 #define AFI_INTR_MASK_INT_MASK (1 << 0) #define AFI_INTR_MASK_MSI_MASK (1 << 8) #define AFI_INTR_CODE 0xb8 #define AFI_INTR_CODE_MASK 0x1f #define AFI_INTR_MASTER_ABORT 4 #define AFI_INTR_LEGACY 6 #define AFI_INTR_PRSNT_SENSE 10 #define AFI_INTR_SIGNATURE 0xbc #define AFI_SM_INTR_ENABLE 0xc4 #define AFI_AFI_INTR_ENABLE 0xc8 #define AFI_INTR_EN_INI_SLVERR (1 << 0) #define AFI_INTR_EN_INI_DECERR (1 << 1) #define AFI_INTR_EN_TGT_SLVERR (1 << 2) #define AFI_INTR_EN_TGT_DECERR (1 << 3) #define AFI_INTR_EN_TGT_WRERR (1 << 4) #define AFI_INTR_EN_DFPCI_DECERR (1 << 5) #define AFI_INTR_EN_AXI_DECERR (1 << 6) #define AFI_INTR_EN_FPCI_TIMEOUT (1 << 7) #define AFI_PCIE_PME 0x0f0 #define AFI_PCIE_PME_TURN_OFF 0x101 #define AFI_PCIE_PME_ACK 0x420 #define AFI_PCIE_CONFIG 0x0f8 #define AFI_PCIE_CONFIG_PCIEC0_DISABLE_DEVICE (1 << 1) #define AFI_PCIE_CONFIG_PCIEC1_DISABLE_DEVICE (1 << 2) #define AFI_PCIE_CONFIG_PCIEC2_DISABLE_DEVICE (1 << 3) #define AFI_PCIE_CONFIG_XBAR_CONFIG_MASK (0xf << 20) #define AFI_PCIE_CONFIG_XBAR_CONFIG_X2_X1 (0x0 << 20) #define AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X1 (0x1 << 20) #define AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X0_X1 (0x0 << 20) #define AFI_PCIE_CONFIG_XBAR_CONFIG_X2_X1_X1 (0x1 << 20) #define AFI_PCIE_CONFIG_XBAR_CONFIG_X1_X1_X1 (0x2 << 20) #define AFI_PCIE_CONFIG_PCIEC0_CLKREQ_AS_GPIO BIT(29) #define AFI_PCIE_CONFIG_PCIEC1_CLKREQ_AS_GPIO BIT(30) #define AFI_PCIE_CONFIG_PCIEC2_CLKREQ_AS_GPIO BIT(31) #define AFI_FUSE 0x104 #define AFI_FUSE_PCIE_T0_GEN2_DIS (1 << 2) #define AFI_PEX0_CTRL 0x110 #define AFI_PEX1_CTRL 0x118 #define AFI_PEX2_CTRL 0x19C #define AFI_PEX_CTRL_RST (1 << 0) #define AFI_PEX_CTRL_CLKREQ_EN (1 << 1) #define AFI_PEX_CTRL_REFCLK_EN (1 << 3) #define AFI_PEX_CTRL_OVERRIDE_EN (1 << 4) #define AFI_PLLE_CONTROL 0x160 #define AFI_PLLE_CONTROL_BYPASS_PADS2PLLE_CONTROL (1 << 9) #define AFI_PLLE_CONTROL_BYPASS_PCIE2PLLE_CONTROL (1 << 8) #define AFI_PLLE_CONTROL_PADS2PLLE_CONTROL_EN (1 << 1) #define AFI_PLLE_CONTROL_PCIE2PLLE_CONTROL_EN (1 << 0) #define AFI_PEXBIAS_CTRL_0 0x168 #define AFI_WR_SCRATCH_0 0x120 #define AFI_WR_SCRATCH_0_RESET_VAL 0x00202020 #define AFI_WR_SCRATCH_0_DEFAULT_VAL 0x00000000 #define AFI_MSG_0 0x190 #define AFI_MSG_PM_PME_MASK 0x00100010 #define AFI_MSG_INTX_MASK 0x1f001f00 #define AFI_MSG_PM_PME0 (1 << 4) #define AFI_MSG_PM_PME1 (1 << 20) #define AFI_MSG_RP_INT_MASK 0x10001000 #define AFI_MSG_1_0 0x194 #define AFI_MSG_1_PM_PME_MASK 0x00000010 #define AFI_MSG_1_INTX_MASK 0x00001f00 #define AFI_MSG_1_PM_PME (1 << 4) #define RP_VEND_XP 0x00000F00 #define RP_VEND_XP_OPPORTUNISTIC_ACK (1 << 27) #define RP_VEND_XP_OPPORTUNISTIC_UPDATEFC (1 << 28) #define RP_VEND_XP_DL_UP (1 << 30) #define RP_VEND_XP_UPDATE_FC_THRESHOLD (0xFF << 18) #define RP_VEND_XP_PRBS_STAT (0xFFFF << 2) #define RP_VEND_XP_PRBS_EN (1 << 1) #define RP_LINK_CONTROL_STATUS 0x00000090 #define RP_LINK_CONTROL_STATUS_BW_MGMT_STATUS 0x40000000 #define RP_LINK_CONTROL_STATUS_DL_LINK_ACTIVE 0x20000000 #define RP_LINK_CONTROL_STATUS_LINKSTAT_MASK 0x3fff0000 #define RP_LINK_CONTROL_STATUS_NEG_LINK_WIDTH (0x3F << 20) #define RP_LINK_CONTROL_STATUS_LINK_SPEED (0xF << 16) #define RP_LINK_CONTROL_STATUS_L0s_ENABLED 0x00000001 #define RP_LINK_CONTROL_STATUS_L1_ENABLED 0x00000002 #define RP_LINK_CONTROL_STATUS_2 0x000000B0 #define RP_LINK_CONTROL_STATUS_2_TRGT_LNK_SPD_MASK 0x0000000F #define RP_LINK_CONTROL_STATUS_2_TRGT_LNK_SPD_GEN1 0x00000001 #define RP_LINK_CONTROL_STATUS_2_TRGT_LNK_SPD_GEN2 0x00000002 #define NV_PCIE2_RP_RSR 0x000000A0 #define NV_PCIE2_RP_RSR_PMESTAT (1 << 16) #define NV_PCIE2_RP_INTR_BCR 0x0000003C #define NV_PCIE2_RP_INTR_BCR_INTR_LINE (0xFF << 0) #define NV_PCIE2_RP_INTR_BCR_SB_RESET (0x1 << 22) #define NV_PCIE2_RP_PRIV_XP_DL 0x00000494 #define PCIE2_RP_PRIV_XP_DL_GEN2_UPD_FC_TSHOLD (0x1FF << 1) #define NV_PCIE2_RP_RX_HDR_LIMIT 0x00000E00 #define PCIE2_RP_RX_HDR_LIMIT_PW_MASK (0xFF00) #define PCIE2_RP_RX_HDR_LIMIT_PW (0x0E << 8) #define NV_PCIE2_RP_TX_HDR_LIMIT 0x00000E08 #define PCIE2_RP_TX_HDR_LIMIT_NPT_0 32 #define PCIE2_RP_TX_HDR_LIMIT_NPT_1 4 #define NV_PCIE2_RP_TIMEOUT0 0x00000E24 #define PCIE2_RP_TIMEOUT0_PAD_PWRUP_MASK (0xFF) #define PCIE2_RP_TIMEOUT0_PAD_PWRUP (0xA) #define PCIE2_RP_TIMEOUT0_PAD_PWRUP_CM_MASK (0xFFFF00) #define PCIE2_RP_TIMEOUT0_PAD_PWRUP_CM (0x180 << 8) #define PCIE2_RP_TIMEOUT0_PAD_SPDCHNG_GEN2_MASK (0xFF << 24) #define PCIE2_RP_TIMEOUT0_PAD_SPDCHNG_GEN2 (0xA << 24) #define NV_PCIE2_RP_TIMEOUT1 0x00000E28 #define PCIE2_RP_TIMEOUT1_RCVRY_SPD_SUCCESS_EIDLE_MASK (0xFF << 16) #define PCIE2_RP_TIMEOUT1_RCVRY_SPD_SUCCESS_EIDLE (0x10 << 16) #define PCIE2_RP_TIMEOUT1_RCVRY_SPD_UNSUCCESS_EIDLE_MASK (0xFF << 24) #define PCIE2_RP_TIMEOUT1_RCVRY_SPD_UNSUCCESS_EIDLE (0x74 << 24) #define NV_PCIE2_RP_PRBS 0x00000E34 #define PCIE2_RP_PRBS_LOCKED (1 << 16) #define NV_PCIE2_RP_LANE_PRBS_ERR_COUNT 0x00000E38 #define PCIE2_RP_LANE_PRBS_ERR_COUNT (1 << 16) #define PCIE2_RP_LANE_PRBS_ERR_SELECT (1 << 0) #define NV_PCIE2_RP_LTSSM_DBGREG 0x00000E44 #define PCIE2_RP_LTSSM_DBGREG_LINKFSM15 (1 << 15) #define PCIE2_RP_LTSSM_DBGREG_LINKFSM16 (1 << 16) #define PCIE2_RP_LTSSM_DBGREG_LINKFSM17 (1 << 17) #define NV_PCIE2_RP_LTSSM_TRACE_CONTROL 0x00000E50 #define LTSSM_TRACE_CONTROL_CLEAR_STORE_EN (1 << 0) #define LTSSM_TRACE_CONTROL_CLEAR_RAM (1 << 2) #define LTSSM_TRACE_CONTROL_TRIG_ON_EVENT (1 << 3) #define LTSSM_TRACE_CONTROL_TRIG_LTSSM_MAJOR_OFFSET 4 #define LTSSM_TRACE_CONTROL_TRIG_PTX_LTSSM_MINOR_OFFSET 8 #define LTSSM_TRACE_CONTROL_TRIG_PRX_LTSSM_MAJOR_OFFSET 11 #define NV_PCIE2_RP_LTSSM_TRACE_STATUS 0x00000E54 #define LTSSM_TRACE_STATUS_PRX_MINOR(reg) (((reg) >> 19) & 0x7) #define LTSSM_TRACE_STATUS_PTX_MINOR(reg) (((reg) >> 16) & 0x7) #define LTSSM_TRACE_STATUS_MAJOR(reg) (((reg) >> 12) & 0xf) #define LTSSM_TRACE_STATUS_READ_DATA_VALID(reg) (((reg) >> 11) & 0x1) #define LTSSM_TRACE_STATUS_READ_ADDR(reg) ((reg) << 6) #define LTSSM_TRACE_STATUS_WRITE_POINTER(reg) (((reg) >> 1) & 0x1f) #define LTSSM_TRACE_STATUS_RAM_FULL(reg) (reg & 0x1) #define NV_PCIE2_RP_XP_REF 0x00000F30 #define PCIE2_RP_XP_REF_MICROSECOND_LIMIT_MASK (0xFF) #define PCIE2_RP_XP_REF_MICROSECOND_LIMIT (0x14) #define PCIE2_RP_XP_REF_MICROSECOND_ENABLE (1 << 8) #define PCIE2_RP_XP_REF_CPL_TO_OVERRIDE (1 << 13) #define PCIE2_RP_XP_REF_CPL_TO_CUSTOM_VALUE_MASK (0x1FFFF << 14) #define PCIE2_RP_XP_REF_CPL_TO_CUSTOM_VALUE (0x1770 << 14) #define NV_PCIE2_RP_PRIV_MISC 0x00000FE0 #define PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_PRSNT (0xE << 0) #define PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_ABSNT (0xF << 0) #define PCIE2_RP_PRIV_MISC_CTLR_CLK_CLAMP_THRESHOLD (0xF << 16) #define PCIE2_RP_PRIV_MISC_CTLR_CLK_CLAMP_ENABLE (1 << 23) #define PCIE2_RP_PRIV_MISC_TMS_CLK_CLAMP_THRESHOLD (0xF << 24) #define PCIE2_RP_PRIV_MISC_TMS_CLK_CLAMP_ENABLE (1 << 31) #define NV_PCIE2_RP_VEND_XP1 0x00000F04 #define NV_PCIE2_RP_VEND_XP2 0x00000F08 #define NV_PCIE2_RP_VEND_XP_LINK_PVT_CTL_L1_ASPM_SUPPORT (1 << 21) #define NV_PCIE2_RP_VEND_XP1_RNCTRL_MAXWIDTH_MASK (0x3F << 0) #define NV_PCIE2_RP_VEND_XP1_RNCTRL_EN (1 << 7) #define NV_PCIE2_RP_VEND_CTL0 0x00000F44 #define PCIE2_RP_VEND_CTL0_DSK_RST_PULSE_WIDTH_MASK (0xF << 12) #define PCIE2_RP_VEND_CTL0_DSK_RST_PULSE_WIDTH (0x9 << 12) #define NV_PCIE2_RP_VEND_CTL1 0x00000F48 #define PCIE2_RP_VEND_CTL1_ERPT (1 << 13) #define NV_PCIE2_RP_VEND_XP_BIST 0x00000F4C #define PCIE2_RP_VEND_XP_BIST_GOTO_L1_L2_AFTER_DLLP_DONE (1 << 28) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN 0x00000F50 #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_L1_EN (1 << 0) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_DYNAMIC_EN (1 << 1) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_DISABLED_EN (1 << 2) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_L1_CLKREQ_EN (1 << 15) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_DYNAMIC_L1PP (3 << 5) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_L1_L1P (2 << 3) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_L1_L1PP (3 << 3) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_L1_CLKREQ_L1P (2 << 16) #define NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_L1_CLKREQ_L1PP (3 << 16) #define NV_PCIE2_RP_PRIV_XP_RX_L0S_ENTRY_COUNT 0x00000F8C #define NV_PCIE2_RP_PRIV_XP_TX_L0S_ENTRY_COUNT 0x00000F90 #define NV_PCIE2_RP_PRIV_XP_TX_L1_ENTRY_COUNT 0x00000F94 #define NV_PCIE2_RP_LTR_REP_VAL 0x00000C10 #define NV_PCIE2_RP_L1_1_ENTRY_COUNT 0x00000C14 #define PCIE2_RP_L1_1_ENTRY_COUNT_RESET (1 << 31) #define NV_PCIE2_RP_L1_2_ENTRY_COUNT 0x00000C18 #define PCIE2_RP_L1_2_ENTRY_COUNT_RESET (1 << 31) #define NV_PCIE2_RP_VEND_CTL2 0x00000FA8 #define PCIE2_RP_VEND_CTL2_PCA_ENABLE (1 << 7) #define NV_PCIE2_RP_PRIV_XP_CONFIG 0x00000FAC #define NV_PCIE2_RP_PRIV_XP_CONFIG_LOW_PWR_DURATION_MASK 0x3 #define NV_PCIE2_RP_PRIV_XP_DURATION_IN_LOW_PWR_100NS 0x00000FB0 #define NV_PCIE2_RP_XP_CTL_1 0x00000FEC #define PCIE2_RP_XP_CTL_1_OLD_IOBIST_EN_BIT25 (1 << 25) #define PCIE2_RP_XP_CTL_1_SPARE_BIT29 (1 << 29) #define NV_PCIE2_RP_L1_PM_SUBSTATES_CYA 0x00000C00 #define PCIE2_RP_L1_PM_SUBSTATES_CYA_CM_RTIME_MASK (0xFF << 8) #define PCIE2_RP_L1_PM_SUBSTATES_CYA_CM_RTIME_SHIFT (8) #define PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_SCL_MASK (0x3 << 16) #define PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_SCL_SHIFT (16) #define PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_VAL_MASK (0x1F << 19) #define PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_VAL_SHIFT (19) #define PCIE2_RP_L1_PM_SUBSTATES_CYA_HIDE_CAP (0x1 << 24) #define NV_PCIE2_RP_L1_PM_SUBSTATES_1_CYA 0x00000C04 #define PCIE2_RP_L1_PM_SUBSTATES_1_CYA_PWR_OFF_DLY_MASK (0x1FFF) #define PCIE2_RP_L1_PM_SUBSTATES_1_CYA_PWR_OFF_DLY (0x26) #define PCIE2_RP_L1SS_1_CYA_CLKREQ_ASSERTED_DLY_MASK (0x1FF << 13) #define PCIE2_RP_L1SS_1_CYA_CLKREQ_ASSERTED_DLY (0x27 << 13) #define NV_PCIE2_RP_L1_PM_SUBSTATES_2_CYA 0x00000C08 #define PCIE2_RP_L1_PM_SUBSTATES_2_CYA_T_L1_2_DLY_MASK (0x1FFF) #define PCIE2_RP_L1_PM_SUBSTATES_2_CYA_T_L1_2_DLY (0x4D) #define PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND_MASK (0xFF << 13) #define PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND (0x13 << 13) #define PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND_COMP_MASK (0xF << 21) #define PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND_COMP (0x2 << 21) #define PCIE2_RP_L1SS_SPARE 0xC24 #define PCIE2_RP_L1SS_SPARE_LTR_MSG_INT_EN (1 << 16) #define PCIE2_RP_L1SS_SPARE_LTR_MSG_RCV_STS (1 << 17) #define PCIE2_RP_L1_PM_SS_CONTROL 0x00000148 #define PCIE2_RP_L1_PM_SS_CONTROL_ASPM_L11_ENABLE 0x00000008 #define PCIE2_RP_L1_PM_SS_CONTROL_ASPM_L12_ENABLE 0x00000004 #define INT_PCI_MSI_NR (32 * 8) #define LINK_RETRAIN_TIMEOUT 100000 #define PCIE_LANES_X4_X1 0x14 #define DEBUG 0 #if DEBUG || defined(CONFIG_PCI_DEBUG) #define PR_FUNC_LINE pr_info("PCIE: %s(%d)\n", __func__, __LINE__) #else #define PR_FUNC_LINE do {} while (0) #endif struct pcie_dvfs { u32 afi_clk; u32 emc_clk; }; struct tegra_pcie_soc_data { unsigned int num_ports; char **pcie_regulator_names; int num_pcie_regulators; bool config_pex_io_dpd; bool program_uphy; bool program_clkreq_as_bi_dir; bool enable_wrap; bool mbist_war; bool RAW_violation_war; bool perf_war; bool updateFC_timer_expire_war; bool l1ss_rp_wakeup_war; bool link_speed_war; bool dvfs_mselect; bool dvfs_afi; bool update_clamp_threshold; struct pcie_dvfs dvfs_tbl[10][2]; }; struct tegra_msi { struct msi_controller chip; DECLARE_BITMAP(used, INT_PCI_MSI_NR); struct irq_domain *domain; struct mutex lock; void *virt; u64 phys; int irq; }; static inline struct tegra_msi *to_tegra_msi(struct msi_controller *chip) { return container_of(chip, struct tegra_msi, chip); } struct tegra_pcie { struct device *dev; struct pci_host_bridge *host; void __iomem *pads; void __iomem *afi; int irq; struct list_head buses; struct list_head sys; struct resource *cs; struct resource *afi_res; struct resource *pads_res; struct resource io; struct resource pio; struct resource mem; struct resource prefetch; struct resource busn; struct { resource_size_t mem; resource_size_t io; } offset; void __iomem *cfg_va_base; struct tegra_msi msi; struct reset_control *afi_rst; struct reset_control *pcie_rst; struct reset_control *pciex_rst; struct tegra_bwmgr_client *emc_bwmgr; #ifdef CONFIG_THERMAL struct thermal_cooling_device *cdev; atomic_t therm_state; struct completion completion; bool is_cooling_dev; #endif struct list_head ports; u32 xbar_config; int num_ports; int power_rails_enabled; int pcie_power_enabled; struct work_struct hotplug_detect; struct regulator **pcie_regulators; struct pinctrl *pex_pin; struct pinctrl_state *pex_io_dpd_en_state; struct pinctrl_state *pex_io_dpd_dis_state; struct tegra_pci_platform_data *plat_data; struct tegra_pcie_soc_data *soc_data; struct dentry *debugfs; struct delayed_work detect_delay; struct tegra_prod *prod_list; }; static int tegra_pcie_enable_msi(struct tegra_pcie *pcie, bool no_init); static void tegra_pcie_check_ports(struct tegra_pcie *pcie); static void tegra_pcie_link_speed(struct tegra_pcie *pcie); static int tegra_pcie_power_off(struct tegra_pcie *pcie); #define MAX_PWR_GPIOS 5 struct tegra_pcie_port { struct tegra_pcie *pcie; struct list_head list; struct resource regs; void __iomem *base; unsigned int index; unsigned int lanes; unsigned int num_lanes; unsigned int loopback_stat; int gpio_presence_detection; bool disable_clock_request; bool ep_status; int status; int rst_gpio; bool has_mxm_port; int pwr_gd_gpio; struct dentry *port_debugfs; struct phy **phy; struct device_node *np; int n_gpios; int *gpios; }; struct tegra_pcie_bus { struct list_head list; unsigned int nr; }; /* used to avoid successive hotplug disconnect or connect */ static bool hotplug_event; /* pcie mselect, xclk and emc rate */ static u16 bdf; static u16 config_offset; static u32 config_val; static u16 config_aspm_state; static inline void afi_writel(struct tegra_pcie *pcie, u32 value, unsigned long offset) { writel(value, offset + pcie->afi); } static inline u32 afi_readl(struct tegra_pcie *pcie, unsigned long offset) { return readl(offset + pcie->afi); } static inline void __maybe_unused pads_writel(struct tegra_pcie *pcie, u32 value, unsigned long offset) { writel(value, offset + pcie->pads); } static inline u32 __maybe_unused pads_readl(struct tegra_pcie *pcie, unsigned long offset) { return readl(offset + pcie->pads); } static inline void rp_writel(struct tegra_pcie_port *port, u32 value, unsigned long offset) { writel(value, offset + port->base); } static inline unsigned int rp_readl(struct tegra_pcie_port *port, unsigned long offset) { return readl(offset + port->base); } /* * The configuration space mapping on Tegra is somewhat similar to the ECAM * defined by PCIe. However it deviates a bit in how the 4 bits for extended * register accesses are mapped: * * [27:24] extended register number * [23:16] bus number * [15:11] device number * [10: 8] function number * [ 7: 0] register number * * Mapping the whole extended configuration space would required 256 MiB of * virtual address space, only a small part of which will actually be used. * To work around this, a 4K of region is used to generate required * configuration transaction with relevant B:D:F values. This is achieved by * dynamically programming base address and size of AFI_AXI_BAR used for * end point config space mapping to make sure that the address (access to * which generates correct config transaction) falls in this 4K region */ static struct tegra_pcie_bus *tegra_pcie_bus_alloc(struct tegra_pcie *pcie, unsigned int busnr) { struct tegra_pcie_bus *bus; PR_FUNC_LINE; bus = devm_kzalloc(pcie->dev, sizeof(*bus), GFP_KERNEL); if (!bus) return ERR_PTR(-ENOMEM); INIT_LIST_HEAD(&bus->list); bus->nr = busnr; if (!pcie->cfg_va_base) { pcie->cfg_va_base = ioremap(pcie->cs->start, SZ_4K); if (!pcie->cfg_va_base) { dev_err(pcie->dev, "failed to ioremap config space\n"); kfree(bus); bus = (struct tegra_pcie_bus *)-ENOMEM; } } return bus; } static void __iomem *tegra_pcie_conf_address(struct pci_bus *bus, unsigned int devfn, int where) { struct pci_host_bridge *host = pci_find_host_bridge(bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); void __iomem *addr = NULL; u32 val = 0; if (bus->number == 0) { unsigned int slot = PCI_SLOT(devfn); struct tegra_pcie_port *port; list_for_each_entry(port, &pcie->ports, list) { if ((port->index + 1 == slot) && port->status) { addr = port->base + (where & ~3); break; } } } else { addr = pcie->cfg_va_base; val = ((((u32)where & 0xf00) >> 8) << 24) | (bus->number << 16) | (PCI_SLOT(devfn) << 11) | (PCI_FUNC(devfn) << 8) | (where & 0xff); addr = (val & (SZ_4K - 1)) + addr; val = val & ~(SZ_4K - 1); afi_writel(pcie, pcie->cs->start - val, AFI_AXI_BAR0_START); afi_writel(pcie, (val + SZ_4K) >> 12, AFI_AXI_BAR0_SZ); } return addr; } static int tegra_pcie_read_conf(struct pci_bus *bus, unsigned int devfn, int where, int size, u32 *value) { struct pci_host_bridge *host = pci_find_host_bridge(bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); struct tegra_pcie_port *port = NULL; u32 rp = 0; struct pci_dev *dn_dev; if (bus->number) { if (bus->number == 1) { dn_dev = bus->self; rp = PCI_SLOT(dn_dev->devfn); list_for_each_entry(port, &pcie->ports, list) if (rp == port->index + 1) break; if (!port->ep_status) return PCIBIOS_DEVICE_NOT_FOUND; } return pci_generic_config_read(bus, devfn, where, size, value); } return pci_generic_config_read32(bus, devfn, where, size, value); } static int tegra_pcie_write_conf(struct pci_bus *bus, unsigned int devfn, int where, int size, u32 value) { struct pci_host_bridge *host = pci_find_host_bridge(bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); struct tegra_pcie_port *port = NULL; u32 rp = 0; struct pci_dev *dn_dev; if (bus->number) { if (bus->number == 1) { dn_dev = bus->self; rp = PCI_SLOT(dn_dev->devfn); list_for_each_entry(port, &pcie->ports, list) if (rp == port->index + 1) break; if (!port->ep_status) return PCIBIOS_DEVICE_NOT_FOUND; } return pci_generic_config_write(bus, devfn, where, size, value); } return pci_generic_config_write32(bus, devfn, where, size, value); } static void tegra_pcie_fixup_bridge(struct pci_dev *dev) { u16 reg; if ((dev->class >> 16) == PCI_BASE_CLASS_BRIDGE) { pci_read_config_word(dev, PCI_COMMAND, &reg); reg |= (PCI_COMMAND_IO | PCI_COMMAND_MEMORY | PCI_COMMAND_MASTER | PCI_COMMAND_SERR); pci_write_config_word(dev, PCI_COMMAND, reg); } } DECLARE_PCI_FIXUP_FINAL(PCI_ANY_ID, PCI_ANY_ID, tegra_pcie_fixup_bridge); /* Tegra PCIE root complex wrongly reports device class */ static void tegra_pcie_fixup_class(struct pci_dev *dev) { dev->class = PCI_CLASS_BRIDGE_PCI << 8; } DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA, 0x0e1c, tegra_pcie_fixup_class); DECLARE_PCI_FIXUP_EARLY(PCI_VENDOR_ID_NVIDIA, 0x0e1d, tegra_pcie_fixup_class); /* Tegra PCIE requires relaxed ordering */ static void tegra_pcie_relax_enable(struct pci_dev *dev) { pcie_capability_set_word(dev, PCI_EXP_DEVCTL, PCI_EXP_DEVCTL_RELAX_EN); } DECLARE_PCI_FIXUP_FINAL(PCI_ANY_ID, PCI_ANY_ID, tegra_pcie_relax_enable); static int tegra_pcie_request_resources(struct tegra_pcie *pcie) { struct pci_host_bridge *host = pci_host_bridge_from_priv(pcie); struct list_head *windows = &host->windows; struct device *dev = pcie->dev; int err; pci_add_resource_offset(windows, &pcie->pio, pcie->offset.io); pci_add_resource_offset(windows, &pcie->mem, pcie->offset.mem); pci_add_resource_offset(windows, &pcie->prefetch, pcie->offset.mem); pci_add_resource(windows, &pcie->busn); err = devm_request_pci_bus_resources(dev, windows); if (err < 0) { pci_free_resource_list(windows); return err; } pci_remap_iospace(&pcie->pio, pcie->io.start); return 0; } static void tegra_pcie_free_resources(struct tegra_pcie *pcie) { struct pci_host_bridge *host = pci_host_bridge_from_priv(pcie); struct list_head *windows = &host->windows; struct resource_entry *win, *tmp; pci_unmap_iospace(&pcie->pio); resource_list_for_each_entry_safe(win, tmp, &host->windows) { switch (resource_type(win->res)) { case IORESOURCE_IO: case IORESOURCE_MEM: devm_release_resource(pcie->dev, win->res); break; default: continue; } } pci_free_resource_list(windows); } static int tegra_pcie_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { struct pci_host_bridge *host = pci_find_host_bridge(dev->bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); return pcie->irq; } static int tegra_pcie_add_bus(struct pci_bus *bus) { struct tegra_pcie_bus *tbus; struct pci_host_bridge *host = pci_find_host_bridge(bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); PR_FUNC_LINE; /* bus 0 is root complex whose config space is already mapped */ if (!bus->number) return 0; if (IS_ENABLED(CONFIG_PCI_MSI)) bus->msi = &pcie->msi.chip; /* Allocate memory for new bus */ tbus = tegra_pcie_bus_alloc(pcie, bus->number); if (IS_ERR(tbus)) return 0; list_add_tail(&tbus->list, &pcie->buses); return 0; } static struct pci_ops tegra_pcie_ops = { .add_bus = tegra_pcie_add_bus, .map_bus = tegra_pcie_conf_address, .read = tegra_pcie_read_conf, .write = tegra_pcie_write_conf, }; static unsigned long tegra_pcie_port_get_pex_ctrl(struct tegra_pcie_port *port) { unsigned long ret = 0; switch (port->index) { case 0: ret = AFI_PEX0_CTRL; break; case 1: ret = AFI_PEX1_CTRL; break; case 2: ret = AFI_PEX2_CTRL; break; } return ret; } static void tegra_pcie_config_clkreq(struct tegra_pcie *pcie, u32 index, int bi_dir) { struct pinctrl *clkreq_pin = NULL; struct pinctrl_state *clkreq_dir = NULL; int ret = 0; PR_FUNC_LINE; clkreq_pin = devm_pinctrl_get(pcie->dev); if (IS_ERR(clkreq_pin)) { dev_err(pcie->dev, "config clkreq dir failed: %ld\n", PTR_ERR(clkreq_pin)); return; } switch (index) { case 0: if (bi_dir) clkreq_dir = pinctrl_lookup_state(clkreq_pin, "clkreq-0-bi-dir-enable"); else clkreq_dir = pinctrl_lookup_state(clkreq_pin, "clkreq-0-in-dir-enable"); break; case 1: if (bi_dir) clkreq_dir = pinctrl_lookup_state(clkreq_pin, "clkreq-1-bi-dir-enable"); else clkreq_dir = pinctrl_lookup_state(clkreq_pin, "clkreq-1-in-dir-enable"); break; default: return; } if (IS_ERR(clkreq_dir)) { dev_err(pcie->dev, "missing clkreq_dir_enable state: %ld\n", PTR_ERR(clkreq_dir)); return; } ret = pinctrl_select_state(clkreq_pin, clkreq_dir); if (ret < 0) dev_err(pcie->dev, "setting clkreq pin dir state failed: %d\n", ret); } #if defined(CONFIG_PCIEASPM) static void tegra_pcie_enable_ltr_support(void) { struct pci_dev *pdev = NULL; u16 val = 0; u32 data = 0, pos = 0; PR_FUNC_LINE; /* enable LTR mechanism for L1.2 support in end points */ for_each_pci_dev(pdev) { pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_L1SS); if (!pos) continue; pci_read_config_dword(pdev, pos + PCI_L1SS_CAP, &data); if (!((data & PCI_L1SS_CAP_ASPM_L12S) || (data & PCI_L1SS_CAP_PM_L12S))) continue; pcie_capability_read_dword(pdev, PCI_EXP_DEVCAP2, &data); if (data & PCI_EXP_DEVCAP2_LTR) { pcie_capability_read_word(pdev, PCI_EXP_DEVCTL2, &val); val |= PCI_EXP_DEVCTL2_LTR_EN; pcie_capability_write_word(pdev, PCI_EXP_DEVCTL2, val); } } } struct dev_ids { unsigned short vid; unsigned short did; }; static const struct pci_device_id aspm_l0s_blacklist[] = { { PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x4355), 0, 0, 0 }, { PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x43ef), 0, 0, 0 }, { PCI_DEVICE(PCI_VENDOR_ID_BROADCOM, 0x4354), 0, 0, 0 }, { PCI_DEVICE(PCI_VENDOR_ID_NEC, 0x0194), 0, 0, 0 }, { PCI_DEVICE(PCI_VENDOR_ID_TOSHIBA, 0x010f), 0, 0, 0 }, { PCI_DEVICE(PCI_VENDOR_ID_INTEL, 0x0953), 0, 0, 0 }, { 0 } }; /* Enable ASPM support of all devices based on it's capability */ static void tegra_pcie_configure_aspm(void) { struct pci_dev *pdev = NULL; struct tegra_pcie *pcie = NULL; struct pci_host_bridge *host = NULL; PR_FUNC_LINE; if (!pcie_aspm_support_enabled()) { pr_info("PCIE: ASPM not enabled\n"); return; } pdev = pci_get_device(PCI_ANY_ID, PCI_ANY_ID, NULL); host = pci_find_host_bridge(pdev->bus); pcie = pci_host_bridge_priv(host); pdev = NULL; /* disable ASPM-L0s for all links unless the endpoint * is a known device with proper ASPM-L0s functionality */ for_each_pci_dev(pdev) { struct pci_dev *parent = NULL; struct tegra_pcie_port *port = NULL; unsigned long ctrl = 0; u32 rp = 0, val = 0, i = 0; if ((pci_pcie_type(pdev) == PCI_EXP_TYPE_ROOT_PORT) || (pci_pcie_type(pdev) == PCI_EXP_TYPE_DOWNSTREAM)) continue; parent = pdev->bus->self; /* following needs to be done only for devices which are * directly connected to Tegra root ports */ if (parent->bus->self) continue; rp = PCI_SLOT(parent->devfn); list_for_each_entry(port, &pcie->ports, list) if (rp == port->index + 1) break; ctrl = tegra_pcie_port_get_pex_ctrl(port); /* AFI_PEX_STATUS is AFI_PEX_CTRL + 4 */ val = afi_readl(port->pcie, ctrl + 4); if ((val & 0x1) || (port->disable_clock_request)) { i |= PCIE_LINK_STATE_CLKPM; /* disable PADS2PLLE control */ val = afi_readl(port->pcie, AFI_PLLE_CONTROL); val &= ~AFI_PLLE_CONTROL_PADS2PLLE_CONTROL_EN; afi_writel(port->pcie, val, AFI_PLLE_CONTROL); } /* Disable ASPM-l0s for blacklisted devices */ if (pci_match_id(aspm_l0s_blacklist, pdev)) i |= PCIE_LINK_STATE_L0S; pci_disable_link_state_locked(pdev, i); if (port->disable_clock_request) continue; if (pcie->soc_data->program_clkreq_as_bi_dir) { /* check if L1SS capability is supported */ i = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_L1SS); if (!i) continue; /* avoid L1SS config if no support of L1SS feature */ pci_read_config_dword(pdev, i + PCI_L1SS_CAP, &val); if ((val & PCI_L1SS_CAP_L1PMS) || (val & PCI_L1SS_CAP_L1PM_MASK)) tegra_pcie_config_clkreq(pcie, port->index, 1); } } /* L1.2 specific common configuration */ tegra_pcie_enable_ltr_support(); } #endif static void tegra_pcie_postinit(void) { #if defined(CONFIG_PCIEASPM) tegra_pcie_configure_aspm(); #endif } #ifdef HOTPLUG_ON_SYSTEM_BOOT /* It enumerates the devices when dock is connected after system boot */ /* this is similar to pcibios_init_hw in bios32.c */ static void __init tegra_pcie_hotplug_init(void) { struct pci_sys_data *sys = NULL; int ret, nr; if (is_dock_conn_at_boot) return; PR_FUNC_LINE; tegra_pcie_preinit(); for (nr = 0; nr < tegra_pcie_hw.nr_controllers; nr++) { sys = kzalloc(sizeof(struct pci_sys_data), GFP_KERNEL); if (!sys) panic("PCI: unable to allocate sys data!"); #ifdef CONFIG_PCI_DOMAINS sys->domain = tegra_pcie_hw.domain; #endif sys->busnr = nr; sys->swizzle = tegra_pcie_hw.swizzle; sys->map_irq = tegra_pcie_hw.map_irq; INIT_LIST_HEAD(&sys->resources); ret = tegra_pcie_setup(nr, sys); if (ret > 0) { if (list_empty(&sys->resources)) { pci_add_resource_offset(&sys->resources, &ioport_resource, sys->io_offset); pci_add_resource_offset(&sys->resources, &iomem_resource, sys->mem_offset); } pci_create_root_bus(NULL, nr, &tegra_pcie_ops, sys, &sys->resources); } } is_dock_conn_at_boot = true; } #endif static void tegra_pcie_enable_aer(struct tegra_pcie_port *port, bool enable) { unsigned int data; PR_FUNC_LINE; data = rp_readl(port, NV_PCIE2_RP_VEND_CTL1); if (enable) data |= PCIE2_RP_VEND_CTL1_ERPT; else data &= ~PCIE2_RP_VEND_CTL1_ERPT; rp_writel(port, data, NV_PCIE2_RP_VEND_CTL1); } static int tegra_pcie_attach(struct tegra_pcie *pcie) { struct pci_bus *bus = NULL; struct tegra_pcie_port *port; PR_FUNC_LINE; if (!hotplug_event) return 0; /* rescan and recreate all pcie data structures */ while ((bus = pci_find_next_bus(bus)) != NULL) pci_rescan_bus(bus); /* unhide AER capability */ list_for_each_entry(port, &pcie->ports, list) if (port->status) tegra_pcie_enable_aer(port, true); hotplug_event = false; return 0; } static int tegra_pcie_detach(struct tegra_pcie *pcie) { struct pci_dev *pdev = NULL; struct tegra_pcie_port *port; PR_FUNC_LINE; if (hotplug_event) return 0; hotplug_event = true; /* hide AER capability to avoid log spew */ list_for_each_entry(port, &pcie->ports, list) if (port->status) tegra_pcie_enable_aer(port, false); /* remove all pcie data structures */ for_each_pci_dev(pdev) { pci_stop_and_remove_bus_device(pdev); break; } return 0; } static void tegra_pcie_prsnt_map_override(struct tegra_pcie_port *port, bool prsnt) { unsigned int data; PR_FUNC_LINE; /* currently only hotplug on root port 0 supported */ data = rp_readl(port, NV_PCIE2_RP_PRIV_MISC); data &= ~PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_ABSNT; if (prsnt) data |= PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_PRSNT; else data |= PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_ABSNT; rp_writel(port, data, NV_PCIE2_RP_PRIV_MISC); } static void work_hotplug_handler(struct work_struct *work) { struct tegra_pcie *pcie_driver = container_of(work, struct tegra_pcie, hotplug_detect); int val; PR_FUNC_LINE; if (pcie_driver->plat_data->gpio_hot_plug == -1) return; val = gpio_get_value(pcie_driver->plat_data->gpio_hot_plug); if (val == 0) { dev_info(pcie_driver->dev, "PCIE Hotplug: Connected\n"); tegra_pcie_attach(pcie_driver); } else { dev_info(pcie_driver->dev, "PCIE Hotplug: DisConnected\n"); tegra_pcie_detach(pcie_driver); } } static irqreturn_t gpio_pcie_detect_isr(int irq, void *arg) { struct tegra_pcie *pcie = arg; PR_FUNC_LINE; schedule_work(&pcie->hotplug_detect); return IRQ_HANDLED; } static void handle_sb_intr(struct tegra_pcie *pcie) { u32 mesg; PR_FUNC_LINE; /* Port 0 and 1 */ mesg = afi_readl(pcie, AFI_MSG_0); if (mesg & AFI_MSG_INTX_MASK) /* notify device isr for INTx messages from pcie devices */ dev_dbg(pcie->dev, "Legacy INTx interrupt occurred %x on port 0/1\n", mesg); else if (mesg & AFI_MSG_PM_PME_MASK) { struct tegra_pcie_port *port, *tmp; /* handle PME messages */ list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if ((port->index == 0) && (mesg & AFI_MSG_PM_PME0)) break; if ((port->index == 1) && (mesg & AFI_MSG_PM_PME1)) break; } mesg = rp_readl(port, NV_PCIE2_RP_RSR); mesg |= NV_PCIE2_RP_RSR_PMESTAT; rp_writel(port, mesg, NV_PCIE2_RP_RSR); } else afi_writel(pcie, mesg, AFI_MSG_0); if (pcie->soc_data->num_ports <= 2) return; /* Port 2 */ mesg = afi_readl(pcie, AFI_MSG_1_0); if (mesg & AFI_MSG_1_INTX_MASK) /* notify device isr for INTx messages from pcie devices */ dev_dbg(pcie->dev, "Legacy INTx interrupt occurred %x on port 2\n", mesg); else if (mesg & AFI_MSG_1_PM_PME_MASK) { struct tegra_pcie_port *port, *tmp; /* handle PME messages */ list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if ((port->index == 2) && (mesg & AFI_MSG_1_PM_PME)) break; } mesg = rp_readl(port, NV_PCIE2_RP_RSR); mesg |= NV_PCIE2_RP_RSR_PMESTAT; rp_writel(port, mesg, NV_PCIE2_RP_RSR); } else afi_writel(pcie, mesg, AFI_MSG_1_0); } static irqreturn_t tegra_pcie_isr(int irq, void *arg) { const char *err_msg[] = { "Unknown", "AXI slave error", "AXI decode error", "Target abort", "Master abort", "Invalid write", "", "Response decoding error", "AXI response decoding error", "Transcation timeout", "", "Slot Clock request change", "TMS Clock clamp change", "TMS power down", "Peer to Peer error", }; struct tegra_pcie *pcie = arg; u32 code, signature; PR_FUNC_LINE; code = afi_readl(pcie, AFI_INTR_CODE) & AFI_INTR_CODE_MASK; signature = afi_readl(pcie, AFI_INTR_SIGNATURE); if (code == AFI_INTR_LEGACY) handle_sb_intr(pcie); afi_writel(pcie, 0, AFI_INTR_CODE); afi_readl(pcie, AFI_INTR_CODE); /* read pushes write */ if (code >= ARRAY_SIZE(err_msg)) code = 0; /* * do not pollute kernel log with master abort reports since they * happen a lot during enumeration */ if (code == AFI_INTR_MASTER_ABORT) dev_dbg(pcie->dev, "PCIE: %s, signature: %08x\n", err_msg[code], signature); else if ((code != AFI_INTR_LEGACY) && (code != AFI_INTR_PRSNT_SENSE)) dev_err(pcie->dev, "PCIE: %s, signature: %08x\n", err_msg[code], signature); return IRQ_HANDLED; } /* * FPCI map is as follows: * - 0xfdfc000000: I/O space * - 0xfdfe000000: type 0 configuration space * - 0xfdff000000: type 1 configuration space * - 0xfe00000000: type 0 extended configuration space * - 0xfe10000000: type 1 extended configuration space */ static void tegra_pcie_setup_translations(struct tegra_pcie *pcie) { u32 fpci_bar, size, axi_address; /* Bar 0: type 1 extended configuration space */ fpci_bar = 0xfe100000; size = resource_size(pcie->cs); axi_address = pcie->cs->start; afi_writel(pcie, axi_address, AFI_AXI_BAR0_START); afi_writel(pcie, size >> 12, AFI_AXI_BAR0_SZ); afi_writel(pcie, fpci_bar, AFI_FPCI_BAR0); /* Bar 1: downstream IO bar */ fpci_bar = 0xfdfc0000; size = resource_size(&pcie->io); axi_address = pcie->io.start; afi_writel(pcie, axi_address, AFI_AXI_BAR1_START); afi_writel(pcie, size >> 12, AFI_AXI_BAR1_SZ); afi_writel(pcie, fpci_bar, AFI_FPCI_BAR1); /* Bar 2: prefetchable memory BAR */ fpci_bar = (((pcie->prefetch.start >> 12) & 0x0fffffff) << 4) | 0x1; size = resource_size(&pcie->prefetch); axi_address = pcie->prefetch.start; afi_writel(pcie, axi_address, AFI_AXI_BAR2_START); afi_writel(pcie, size >> 12, AFI_AXI_BAR2_SZ); afi_writel(pcie, fpci_bar, AFI_FPCI_BAR2); /* Bar 3: non prefetchable memory BAR */ fpci_bar = (((pcie->mem.start >> 12) & 0x0fffffff) << 4) | 0x1; size = resource_size(&pcie->mem); axi_address = pcie->mem.start; afi_writel(pcie, axi_address, AFI_AXI_BAR3_START); afi_writel(pcie, size >> 12, AFI_AXI_BAR3_SZ); afi_writel(pcie, fpci_bar, AFI_FPCI_BAR3); /* NULL out the remaining BARs as they are not used */ afi_writel(pcie, 0, AFI_AXI_BAR4_START); afi_writel(pcie, 0, AFI_AXI_BAR4_SZ); afi_writel(pcie, 0, AFI_FPCI_BAR4); afi_writel(pcie, 0, AFI_AXI_BAR5_START); afi_writel(pcie, 0, AFI_AXI_BAR5_SZ); afi_writel(pcie, 0, AFI_FPCI_BAR5); /* MSI translations are setup only when needed */ afi_writel(pcie, 0, AFI_MSI_FPCI_BAR_ST); afi_writel(pcie, 0, AFI_MSI_BAR_SZ); afi_writel(pcie, 0, AFI_MSI_AXI_BAR_ST); afi_writel(pcie, 0, AFI_MSI_BAR_SZ); } static int tegra_pcie_get_clocks(struct tegra_pcie *pcie) { int error; struct device *dev = pcie->dev; PR_FUNC_LINE; error = pm_clk_create(dev); if (error) { dev_err(dev, "pm_clk_create failed %d\n", error); return error; } error = pm_clk_add(dev, "afi"); if (error) { dev_err(dev, "missing afi clock"); return error; } error = pm_clk_add(dev, "pex"); if (error) { dev_err(dev, "missing pcie clock"); return error; } pcie->emc_bwmgr = tegra_bwmgr_register(TEGRA_BWMGR_CLIENT_PCIE); if (!pcie->emc_bwmgr) { dev_err(pcie->dev, "couldn't register with EMC BwMgr\n"); return -EINVAL; } return 0; } static void tegra_pcie_clocks_put(struct tegra_pcie *pcie) { pm_clk_destroy(pcie->dev); tegra_bwmgr_set_emc(pcie->emc_bwmgr, 0, TEGRA_BWMGR_SET_EMC_FLOOR); tegra_bwmgr_unregister(pcie->emc_bwmgr); } static int tegra_pcie_port_get_phy(struct tegra_pcie_port *port) { struct device *dev = port->pcie->dev; struct phy *phy; int err, i; char *name; port->phy = devm_kcalloc(dev, sizeof(phy), port->num_lanes, GFP_KERNEL); if (!port->phy) return -ENOMEM; for (i = 0; i < port->num_lanes; i++) { name = kasprintf(GFP_KERNEL, "pcie-%u", i); if (!name) return -ENOMEM; phy = devm_of_phy_get(dev, port->np, name); kfree(name); if (IS_ERR(phy)) { if (PTR_ERR(phy) == -EPROBE_DEFER) dev_info(dev, "PHY get deferred: %ld\n", PTR_ERR(phy)); else dev_err(dev, "failed to get PHY: %ld\n", PTR_ERR(phy)); return PTR_ERR(phy); } err = phy_init(phy); if (err < 0) { dev_err(dev, "failed to initialize PHY: %d\n", err); return err; } port->phy[i] = phy; } return 0; } static int tegra_pcie_phys_get(struct tegra_pcie *pcie) { struct tegra_pcie_port *port; int err; list_for_each_entry(port, &pcie->ports, list) { err = tegra_pcie_port_get_phy(port); if (err < 0) return err; } return 0; } static int tegra_pcie_phy_power_on(struct tegra_pcie *pcie) { struct tegra_pcie_port *port; int err, i; list_for_each_entry(port, &pcie->ports, list) { for (i = 0; i < port->num_lanes; i++) { err = phy_power_on(port->phy[i]); if (err < 0) return err; } } return 0; } static int tegra_pcie_phy_power_off(struct tegra_pcie *pcie) { struct tegra_pcie_port *port; int err, i; list_for_each_entry(port, &pcie->ports, list) { for (i = 0; i < port->num_lanes; i++) { err = phy_power_off(port->phy[i]); if (err < 0) return err; } } return 0; } static int tegra_pcie_phy_exit(struct tegra_pcie *pcie) { struct tegra_pcie_port *port; int err = 0, i; list_for_each_entry(port, &pcie->ports, list) { for (i = 0; i < port->num_lanes; i++) { if (port->phy && !IS_ERR_OR_NULL(port->phy[i])) err = phy_exit(port->phy[i]); if (err < 0) return err; } } return 0; } static int tegra_pcie_enable_pads(struct tegra_pcie *pcie, bool enable) { int err = 0; PR_FUNC_LINE; if (!tegra_platform_is_silicon()) return err; if (pcie->soc_data->program_uphy) { if (enable) err = tegra_pcie_phy_power_on(pcie); else err = tegra_pcie_phy_power_off(pcie); if (err) dev_err(pcie->dev, "UPHY operation failed\n"); } return err; } static void tegra_pcie_enable_wrap(void) { u32 val; void __iomem *msel_base; PR_FUNC_LINE; #define MSELECT_CONFIG_BASE 0x50060000 #define MSELECT_CONFIG_WRAP_TO_INCR_SLAVE1 BIT(28) #define MSELECT_CONFIG_ERR_RESP_EN_SLAVE1 BIT(24) /* Config MSELECT to support wrap trans for normal NC & GRE mapping */ msel_base = ioremap(MSELECT_CONFIG_BASE, 4); val = readl(msel_base); /* Enable WRAP_TO_INCR_SLAVE1 */ val |= MSELECT_CONFIG_WRAP_TO_INCR_SLAVE1; /* Disable ERR_RESP_EN_SLAVE1 */ val &= ~MSELECT_CONFIG_ERR_RESP_EN_SLAVE1; writel(val, msel_base); iounmap(msel_base); } static int tegra_pcie_enable_controller(struct tegra_pcie *pcie) { u32 val; struct tegra_pcie_port *port, *tmp; PR_FUNC_LINE; if (pcie->soc_data->enable_wrap) tegra_pcie_enable_wrap(); /* Enable PLL power down */ val = afi_readl(pcie, AFI_PLLE_CONTROL); val &= ~AFI_PLLE_CONTROL_BYPASS_PCIE2PLLE_CONTROL; val &= ~AFI_PLLE_CONTROL_BYPASS_PADS2PLLE_CONTROL; val |= AFI_PLLE_CONTROL_PADS2PLLE_CONTROL_EN; val |= AFI_PLLE_CONTROL_PCIE2PLLE_CONTROL_EN; list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if (port->disable_clock_request) { val &= ~AFI_PLLE_CONTROL_PADS2PLLE_CONTROL_EN; break; } } afi_writel(pcie, val, AFI_PLLE_CONTROL); afi_writel(pcie, 0, AFI_PEXBIAS_CTRL_0); /* Enable all PCIE controller and */ /* system management configuration of PCIE crossbar */ val = afi_readl(pcie, AFI_PCIE_CONFIG); val |= (AFI_PCIE_CONFIG_PCIEC0_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC1_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC2_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC0_CLKREQ_AS_GPIO | AFI_PCIE_CONFIG_PCIEC1_CLKREQ_AS_GPIO | AFI_PCIE_CONFIG_PCIEC2_CLKREQ_AS_GPIO); list_for_each_entry(port, &pcie->ports, list) { val &= ~(1 << (port->index + 1)); val &= ~(1 << (port->index + 29)); } /* Configure pcie mode */ val &= ~AFI_PCIE_CONFIG_XBAR_CONFIG_MASK; val |= pcie->xbar_config; afi_writel(pcie, val, AFI_PCIE_CONFIG); /* Enable Gen 2 capability of PCIE */ val = afi_readl(pcie, AFI_FUSE) & ~AFI_FUSE_PCIE_T0_GEN2_DIS; afi_writel(pcie, val, AFI_FUSE); /* Finally enable PCIe */ val = afi_readl(pcie, AFI_CONFIGURATION); val |= (AFI_CONFIGURATION_EN_FPCI | AFI_CONFIGURATION_CLKEN_OVERRIDE); afi_writel(pcie, val, AFI_CONFIGURATION); val = (AFI_INTR_EN_INI_SLVERR | AFI_INTR_EN_INI_DECERR | AFI_INTR_EN_TGT_SLVERR | AFI_INTR_EN_TGT_DECERR | AFI_INTR_EN_TGT_WRERR | AFI_INTR_EN_DFPCI_DECERR | AFI_INTR_EN_AXI_DECERR ); afi_writel(pcie, val, AFI_AFI_INTR_ENABLE); afi_writel(pcie, 0xffffffff, AFI_SM_INTR_ENABLE); /* FIXME: No MSI for now, only INT */ afi_writel(pcie, AFI_INTR_MASK_INT_MASK, AFI_INTR_MASK); /* Disable all execptions */ afi_writel(pcie, 0, AFI_FPCI_ERROR_MASKS); return 0; } static int tegra_pcie_enable_regulators(struct tegra_pcie *pcie) { int i; PR_FUNC_LINE; if (pcie->power_rails_enabled) return 0; pcie->power_rails_enabled = 1; dev_info(pcie->dev, "PCIE: Enable power rails\n"); for (i = 0; i < pcie->soc_data->num_pcie_regulators; i++) { if (pcie->pcie_regulators[i]) if (regulator_enable(pcie->pcie_regulators[i])) dev_err(pcie->dev, "%s: can't enable regulator %s\n", __func__, pcie->soc_data->pcie_regulator_names[i]); } return 0; } static int tegra_pcie_disable_regulators(struct tegra_pcie *pcie) { int i; PR_FUNC_LINE; if (pcie->power_rails_enabled == 0) return 0; for (i = 0; i < pcie->soc_data->num_pcie_regulators; i++) { if (pcie->pcie_regulators[i] != NULL) if (regulator_disable(pcie->pcie_regulators[i])) dev_err(pcie->dev, "%s: can't disable regulator %s\n", __func__, pcie->soc_data->pcie_regulator_names[i]); } pcie->power_rails_enabled = 0; dev_info(pcie->dev, "PCIE: Disable power rails\n"); return 0; } static int tegra_pcie_map_resources(struct tegra_pcie *pcie) { struct platform_device *pdev = to_platform_device(pcie->dev); struct resource *pads, *afi, *res; PR_FUNC_LINE; pads = platform_get_resource_byname(pdev, IORESOURCE_MEM, "pads"); pcie->pads_res = __devm_request_region(&pdev->dev, &iomem_resource, pads->start, resource_size(pads), "pcie-pads"); if (!pcie->pads_res) { dev_err(&pdev->dev, "PCIE: Failed to request region for pad registers\n"); return -EBUSY; } pcie->pads = devm_ioremap_nocache(&pdev->dev, pads->start, resource_size(pads)); if (!(pcie->pads)) { dev_err(pcie->dev, "PCIE: Failed to map PAD registers\n"); return -EADDRNOTAVAIL; } afi = platform_get_resource_byname(pdev, IORESOURCE_MEM, "afi"); pcie->afi_res = __devm_request_region(&pdev->dev, &iomem_resource, afi->start, resource_size(afi), "pcie-afi"); if (!pcie->afi_res) { dev_err(&pdev->dev, "PCIE: Failed to request region for afi registers\n"); return -EBUSY; } pcie->afi = devm_ioremap_nocache(&pdev->dev, afi->start, resource_size(afi)); if (!(pcie->afi)) { dev_err(pcie->dev, "PCIE: Failed to map AFI registers\n"); return -EADDRNOTAVAIL; } /* request configuration space, but remap later, on demand */ res = platform_get_resource_byname(pdev, IORESOURCE_MEM, "cs"); pcie->cs = __devm_request_region(&pdev->dev, &iomem_resource, res->start, resource_size(res), "pcie-config-space"); if (!pcie->cs) { dev_err(&pdev->dev, "PCIE: Failed to request region for CS registers\n"); return -EBUSY; } return 0; } static void tegra_pcie_unmap_resources(struct tegra_pcie *pcie) { struct platform_device *pdev = to_platform_device(pcie->dev); PR_FUNC_LINE; if (pcie->cs) __devm_release_region(&pdev->dev, &iomem_resource, pcie->cs->start, resource_size(pcie->cs)); if (pcie->afi_res) __devm_release_region(&pdev->dev, &iomem_resource, pcie->afi_res->start, resource_size(pcie->afi_res)); if (pcie->pads_res) __devm_release_region(&pdev->dev, &iomem_resource, pcie->pads_res->start, resource_size(pcie->pads_res)); if (pcie->pads) { devm_iounmap(&pdev->dev, pcie->pads); pcie->pads = NULL; } if (pcie->afi) { devm_iounmap(&pdev->dev, pcie->afi); pcie->afi = NULL; } } static int tegra_pcie_fpga_phy_init(struct tegra_pcie *pcie) { PR_FUNC_LINE; /* Do reset for FPGA pcie phy */ reset_control_deassert(pcie->afi_rst); afi_writel(pcie, AFI_WR_SCRATCH_0_RESET_VAL, AFI_WR_SCRATCH_0); udelay(10); afi_writel(pcie, AFI_WR_SCRATCH_0_DEFAULT_VAL, AFI_WR_SCRATCH_0); udelay(10); afi_writel(pcie, AFI_WR_SCRATCH_0_RESET_VAL, AFI_WR_SCRATCH_0); return 0; } static void tegra_pcie_pme_turnoff(struct tegra_pcie *pcie) { unsigned int data; PR_FUNC_LINE; if (tegra_platform_is_fpga()) return; data = afi_readl(pcie, AFI_PCIE_PME); data |= AFI_PCIE_PME_TURN_OFF; afi_writel(pcie, data, AFI_PCIE_PME); do { data = afi_readl(pcie, AFI_PCIE_PME); } while (!(data & AFI_PCIE_PME_ACK)); /* Required for PLL power down */ data = afi_readl(pcie, AFI_PLLE_CONTROL); data |= AFI_PLLE_CONTROL_BYPASS_PADS2PLLE_CONTROL; afi_writel(pcie, data, AFI_PLLE_CONTROL); } static int tegra_pcie_module_power_on(struct tegra_pcie *pcie) { int ret; struct device *dev; PR_FUNC_LINE; dev = pcie->dev; if (pcie->pcie_power_enabled) { dev_info(dev, "PCIE: Already powered on"); return 0; } pcie->pcie_power_enabled = 1; if (gpio_is_valid(pcie->plat_data->gpio_wake) && device_may_wakeup(dev)) { ret = disable_irq_wake(gpio_to_irq( pcie->plat_data->gpio_wake)); if (ret < 0) { dev_err(dev, "ID wake-up event failed with error %d\n", ret); return ret; } } else { ret = tegra_pcie_enable_regulators(pcie); if (ret) { dev_err(dev, "PCIE: Failed to enable regulators\n"); return ret; } } return ret; } static int tegra_pcie_module_power_off(struct tegra_pcie *pcie); static void tegra_pcie_config_plat(struct tegra_pcie *pcie, bool set) { struct tegra_pcie_port *port; int count; list_for_each_entry(port, &pcie->ports, list) { for (count = 0; count < port->n_gpios; ++count) gpiod_set_value(gpio_to_desc(port->gpios[count]), set); } } static int tegra_pcie_restore_device(struct device *dev) { int err = 0; struct tegra_pcie *pcie = dev_get_drvdata(dev); PR_FUNC_LINE; if (!pcie) return 0; tegra_pcie_config_plat(pcie, 1); pm_clk_resume(dev); err = tegra_pcie_module_power_on(pcie); if (err < 0) dev_err(dev, "power on failed: %d\n", err); if (pcie->soc_data->config_pex_io_dpd) { err = pinctrl_select_state(pcie->pex_pin, pcie->pex_io_dpd_dis_state); if (err < 0) { dev_err(dev, "disabling pex-io-dpd failed: %d\n", err); goto err_exit; } } err = tegra_pcie_map_resources(pcie); if (err) { dev_err(dev, "PCIE: Failed to map resources\n"); goto err_map_resource; } if (tegra_platform_is_fpga()) { err = tegra_pcie_fpga_phy_init(pcie); if (err) dev_err(dev, "PCIE: Failed to initialize FPGA Phy\n"); } tegra_pcie_enable_pads(pcie, true); reset_control_deassert(pcie->afi_rst); tegra_pcie_enable_controller(pcie); tegra_pcie_request_resources(pcie); tegra_pcie_setup_translations(pcie); /* Set up MSI registers, if MSI have been enabled */ tegra_pcie_enable_msi(pcie, true); reset_control_deassert(pcie->pcie_rst); tegra_pcie_check_ports(pcie); return 0; err_map_resource: if (pcie->soc_data->config_pex_io_dpd) { err = pinctrl_select_state(pcie->pex_pin, pcie->pex_io_dpd_en_state); if (err < 0) dev_err(dev, "enabling pex-io-dpd failed: %d\n", err); } err_exit: tegra_pcie_module_power_off(pcie); pm_clk_suspend(dev); return err; } static int tegra_pcie_power_on(struct tegra_pcie *pcie) { int err = 0; PR_FUNC_LINE; err = pm_runtime_get_sync(pcie->dev); if (err) { pm_runtime_put(pcie->dev); pcie->pcie_power_enabled = 0; } return err; } static int tegra_pcie_save_device(struct device *dev) { struct tegra_pcie *pcie = dev_get_drvdata(dev); struct tegra_pcie_port *port; int err = 0; PR_FUNC_LINE; if (!pcie) return 0; if (pcie->pcie_power_enabled == 0) { dev_info(dev, "PCIE: Already powered off"); return 0; } list_for_each_entry(port, &pcie->ports, list) { tegra_pcie_prsnt_map_override(port, false); } tegra_pcie_pme_turnoff(pcie); tegra_pcie_free_resources(pcie); tegra_pcie_enable_pads(pcie, false); tegra_pcie_unmap_resources(pcie); if (pcie->soc_data->config_pex_io_dpd) { err = pinctrl_select_state(pcie->pex_pin, pcie->pex_io_dpd_en_state); if (err < 0) dev_err(dev, "enabling pex-io-dpd failed: %d\n", err); } reset_control_assert(pcie->pciex_rst); reset_control_assert(pcie->pcie_rst); reset_control_assert(pcie->afi_rst); err = tegra_pcie_module_power_off(pcie); if (err < 0) dev_err(dev, "power off failed: %d\n", err); pm_clk_suspend(dev); tegra_pcie_config_plat(pcie, 0); return err; } static int tegra_pcie_module_power_off(struct tegra_pcie *pcie) { int ret; struct device *dev; PR_FUNC_LINE; dev = pcie->dev; /* configure PE_WAKE signal as wake sources */ if (gpio_is_valid(pcie->plat_data->gpio_wake) && device_may_wakeup(dev)) { ret = enable_irq_wake(gpio_to_irq( pcie->plat_data->gpio_wake)); if (ret < 0) { dev_err(dev, "ID wake-up event failed with error %d\n", ret); } } else { ret = tegra_pcie_disable_regulators(pcie); } pcie->pcie_power_enabled = 0; return ret; } static int tegra_pcie_power_off(struct tegra_pcie *pcie) { int err = 0; PR_FUNC_LINE; err = pm_runtime_put_sync(pcie->dev); if (err) goto err_exit; pcie->pcie_power_enabled = 0; err_exit: return err; } static int tegra_pcie_get_resets(struct tegra_pcie *pcie) { pcie->afi_rst = devm_reset_control_get(pcie->dev, "afi"); if (IS_ERR(pcie->afi_rst)) { dev_err(pcie->dev, "PCIE : afi reset is missing\n"); return PTR_ERR(pcie->afi_rst); } pcie->pcie_rst = devm_reset_control_get(pcie->dev, "pex"); if (IS_ERR(pcie->pcie_rst)) { dev_err(pcie->dev, "PCIE : pcie reset is missing\n"); return PTR_ERR(pcie->pcie_rst); } pcie->pciex_rst = devm_reset_control_get(pcie->dev, "pcie_x"); if (IS_ERR(pcie->pciex_rst)) { dev_err(pcie->dev, "PCIE : pcie-xclk reset is missing\n"); return PTR_ERR(pcie->pciex_rst); } return 0; } static int tegra_pcie_get_resources(struct tegra_pcie *pcie) { struct platform_device *pdev = to_platform_device(pcie->dev); int err; PR_FUNC_LINE; pcie->power_rails_enabled = 0; pcie->pcie_power_enabled = 0; err = tegra_pcie_get_clocks(pcie); if (err) { dev_err(pcie->dev, "PCIE: failed to get clocks: %d\n", err); goto err_clk_get; } err = tegra_pcie_get_resets(pcie); if (err) { dev_err(pcie->dev, "PCIE: failed to get resets: %d\n", err); goto err_reset_get; } err = tegra_pcie_enable_regulators(pcie); if (err) { dev_err(pcie->dev, "PCIE: Failed to enable regulators\n"); goto err_reset_get; } err = platform_get_irq_byname(pdev, "intr"); if (err < 0) { dev_err(pcie->dev, "failed to get IRQ: %d\n", err); goto err_irq; } pcie->irq = err; err = devm_request_irq(&pdev->dev, pcie->irq, tegra_pcie_isr, IRQF_SHARED, "PCIE", pcie); if (err) { dev_err(pcie->dev, "PCIE: Failed to register IRQ: %d\n", err); goto err_irq; } return 0; err_irq: tegra_pcie_disable_regulators(pcie); err_reset_get: tegra_pcie_clocks_put(pcie); err_clk_get: return err; } static void tegra_pcie_release_resources(struct tegra_pcie *pcie) { devm_free_irq(pcie->dev, pcie->irq, pcie); tegra_pcie_clocks_put(pcie); } static void tegra_pcie_port_reset(struct tegra_pcie_port *port) { unsigned long ctrl = tegra_pcie_port_get_pex_ctrl(port); unsigned long value; PR_FUNC_LINE; /* pulse reset signal */ /* assert PEX_RST_A */ if (gpio_is_valid(port->rst_gpio)) { gpio_set_value(port->rst_gpio, 0); } else { value = afi_readl(port->pcie, ctrl); value &= ~AFI_PEX_CTRL_RST; afi_writel(port->pcie, value, ctrl); } usleep_range(1000, 2000); /* deAssert PEX_RST_A */ if (gpio_is_valid(port->rst_gpio)) { gpio_set_value(port->rst_gpio, 1); } else { value = afi_readl(port->pcie, ctrl); value |= AFI_PEX_CTRL_RST; afi_writel(port->pcie, value, ctrl); } } static void tegra_pcie_port_enable(struct tegra_pcie_port *port) { unsigned long ctrl = tegra_pcie_port_get_pex_ctrl(port); unsigned long value; PR_FUNC_LINE; /* enable reference clock. Enable SW override so as to allow device to get enumerated. SW override will be removed after enumeration */ value = afi_readl(port->pcie, ctrl); value |= (AFI_PEX_CTRL_REFCLK_EN | AFI_PEX_CTRL_OVERRIDE_EN); /* t124 doesn't support pll power down due to RTL bug and some */ /* platforms don't support clkreq, both needs to disable clkreq and */ /* enable refclk override to have refclk always ON independent of EP */ if (port->disable_clock_request) value |= AFI_PEX_CTRL_CLKREQ_EN; else value &= ~AFI_PEX_CTRL_CLKREQ_EN; afi_writel(port->pcie, value, ctrl); tegra_pcie_port_reset(port); /* On platforms where MXM is not directly connected to Tegra root port, * 200 ms delay (worst case) is required after reset, to ensure linkup * between PCIe switch and MXM */ if (port->has_mxm_port) mdelay(200); } static void tegra_pcie_port_disable(struct tegra_pcie_port *port) { u32 data; PR_FUNC_LINE; data = afi_readl(port->pcie, AFI_PCIE_CONFIG); switch (port->index) { case 0: data |= (AFI_PCIE_CONFIG_PCIEC0_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC0_CLKREQ_AS_GPIO); break; case 1: data |= (AFI_PCIE_CONFIG_PCIEC1_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC1_CLKREQ_AS_GPIO); break; case 2: data |= (AFI_PCIE_CONFIG_PCIEC2_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC2_CLKREQ_AS_GPIO); break; } afi_writel(port->pcie, data, AFI_PCIE_CONFIG); } void tegra_pcie_port_enable_per_pdev(struct pci_dev *pdev) { struct pci_dev *parent = NULL; struct tegra_pcie_port *port = NULL; struct pci_host_bridge *host = pci_find_host_bridge(pdev->bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); u32 rp = 0; u32 data; PR_FUNC_LINE; parent = pdev->bus->self; rp = PCI_SLOT(parent->devfn); list_for_each_entry(port, &pcie->ports, list) if (rp == port->index + 1) break; data = afi_readl(port->pcie, AFI_PCIE_CONFIG); if (!((AFI_PCIE_CONFIG_PCIEC0_DISABLE_DEVICE << port->index) & data)) return; switch (port->index) { case 0: data &= ~(AFI_PCIE_CONFIG_PCIEC0_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC0_CLKREQ_AS_GPIO); break; case 1: data &= ~(AFI_PCIE_CONFIG_PCIEC1_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC1_CLKREQ_AS_GPIO); break; case 2: data &= ~(AFI_PCIE_CONFIG_PCIEC2_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC2_CLKREQ_AS_GPIO); break; } afi_writel(port->pcie, data, AFI_PCIE_CONFIG); } EXPORT_SYMBOL(tegra_pcie_port_enable_per_pdev); void tegra_pcie_port_disable_per_pdev(struct pci_dev *pdev) { struct pci_dev *parent = NULL; struct tegra_pcie_port *port = NULL; struct pci_host_bridge *host = pci_find_host_bridge(pdev->bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); u32 rp = 0; u32 data; PR_FUNC_LINE; parent = pdev->bus->self; rp = PCI_SLOT(parent->devfn); list_for_each_entry(port, &pcie->ports, list) if (rp == port->index + 1) break; data = afi_readl(port->pcie, AFI_PCIE_CONFIG); switch (port->index) { case 0: data |= (AFI_PCIE_CONFIG_PCIEC0_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC0_CLKREQ_AS_GPIO); break; case 1: data |= (AFI_PCIE_CONFIG_PCIEC1_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC1_CLKREQ_AS_GPIO); break; case 2: data |= (AFI_PCIE_CONFIG_PCIEC2_DISABLE_DEVICE | AFI_PCIE_CONFIG_PCIEC2_CLKREQ_AS_GPIO); break; } afi_writel(port->pcie, data, AFI_PCIE_CONFIG); } EXPORT_SYMBOL(tegra_pcie_port_disable_per_pdev); /* * FIXME: If there are no PCIe cards attached, then calling this function * can result in the increase of the bootup time as there are big timeout * loops. */ #define TEGRA_PCIE_LINKUP_TIMEOUT 200 /* up to 1.2 seconds */ static bool tegra_pcie_port_check_link(struct tegra_pcie_port *port) { struct device *dev = port->pcie->dev; unsigned int retries = 3; unsigned long value; /* override presence detection */ value = readl(port->base + NV_PCIE2_RP_PRIV_MISC); value &= ~PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_ABSNT; value |= PCIE2_RP_PRIV_MISC_PRSNT_MAP_EP_PRSNT; writel(value, port->base + NV_PCIE2_RP_PRIV_MISC); do { unsigned int timeout = TEGRA_PCIE_LINKUP_TIMEOUT; do { value = readl(port->base + RP_VEND_XP); if (value & RP_VEND_XP_DL_UP) break; usleep_range(1000, 2000); } while (--timeout); if (!timeout) { dev_info(dev, "link %u down, retrying\n", port->index); goto retry; } timeout = TEGRA_PCIE_LINKUP_TIMEOUT; do { value = readl(port->base + RP_LINK_CONTROL_STATUS); if (value & RP_LINK_CONTROL_STATUS_DL_LINK_ACTIVE) return true; usleep_range(1000, 2000); } while (--timeout); retry: tegra_pcie_port_reset(port); } while (--retries); return false; } static void tegra_pcie_apply_sw_war(struct tegra_pcie_port *port, bool enum_done) { unsigned int data; struct tegra_pcie *pcie = port->pcie; struct pci_dev *pdev = NULL; PR_FUNC_LINE; if (enum_done) { /* disable msi for port driver to avoid panic */ for_each_pci_dev(pdev) if (pci_pcie_type(pdev) == PCI_EXP_TYPE_ROOT_PORT) pdev->msi_enabled = 0; } else { /* Some of the old PCIe end points don't get enumerated * if RP advertises both Gen-1 and Gen-2 speeds. Hence, the * strategy followed here is to initially advertise only * Gen-1 and after link is up, check end point's capability * for Gen-2 and retrain link to Gen-2 speed */ data = rp_readl(port, RP_LINK_CONTROL_STATUS_2); data &= ~RP_LINK_CONTROL_STATUS_2_TRGT_LNK_SPD_MASK; data |= RP_LINK_CONTROL_STATUS_2_TRGT_LNK_SPD_GEN1; rp_writel(port, data, RP_LINK_CONTROL_STATUS_2); /* disable interrupts for LTR messages */ data = rp_readl(port, PCIE2_RP_L1SS_SPARE); data &= ~PCIE2_RP_L1SS_SPARE_LTR_MSG_INT_EN; data &= ~PCIE2_RP_L1SS_SPARE_LTR_MSG_RCV_STS; rp_writel(port, data, PCIE2_RP_L1SS_SPARE); /* Avoid warning during enumeration for invalid IRQ of RP */ data = rp_readl(port, NV_PCIE2_RP_INTR_BCR); data |= NV_PCIE2_RP_INTR_BCR_INTR_LINE; rp_writel(port, data, NV_PCIE2_RP_INTR_BCR); /* Power saving configuration for sleep / idle */ data = rp_readl(port, NV_PCIE2_RP_VEND_XP_PAD_PWRDN); data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_DISABLED_EN; data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_DYNAMIC_EN; data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_L1_EN; data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_L1_CLKREQ_EN; data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_DYNAMIC_L1PP; data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_L1_L1PP; data |= NV_PCIE2_RP_VEND_XP_PAD_PWRDN_SLEEP_MODE_L1_CLKREQ_L1PP; rp_writel(port, data, NV_PCIE2_RP_VEND_XP_PAD_PWRDN); /* resize buffers for better perf, bug#1447522 */ /* T210 WAR for perf bugs required when LPDDR4 */ /* memory is used with both ctlrs in X4_X1 config */ if (pcie->soc_data->perf_war && (pcie->xbar_config == AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X1) && (pcie->num_ports == pcie->soc_data->num_ports)) { struct tegra_pcie_port *temp_port; list_for_each_entry(temp_port, &pcie->ports, list) { data = rp_readl(temp_port, NV_PCIE2_RP_XP_CTL_1); data |= PCIE2_RP_XP_CTL_1_SPARE_BIT29; rp_writel(temp_port, data, NV_PCIE2_RP_XP_CTL_1); data = rp_readl(temp_port, NV_PCIE2_RP_TX_HDR_LIMIT); if (temp_port->index) data |= PCIE2_RP_TX_HDR_LIMIT_NPT_1; else data |= PCIE2_RP_TX_HDR_LIMIT_NPT_0; rp_writel(temp_port, data, NV_PCIE2_RP_TX_HDR_LIMIT); } } if (pcie->soc_data->l1ss_rp_wakeup_war) { /* Bug#1461732 WAR, set clkreq asserted delay greater than */ /* power off time (2us) to avoid RP wakeup in L1.2_ENTRY */ data = rp_readl(port, NV_PCIE2_RP_L1_PM_SUBSTATES_1_CYA); data &= ~PCIE2_RP_L1SS_1_CYA_CLKREQ_ASSERTED_DLY_MASK; data |= PCIE2_RP_L1SS_1_CYA_CLKREQ_ASSERTED_DLY; rp_writel(port, data, NV_PCIE2_RP_L1_PM_SUBSTATES_1_CYA); } if (pcie->soc_data->link_speed_war) { /* take care of link speed change error in corner cases */ data = rp_readl(port, NV_PCIE2_RP_VEND_CTL0); data &= ~PCIE2_RP_VEND_CTL0_DSK_RST_PULSE_WIDTH_MASK; data |= PCIE2_RP_VEND_CTL0_DSK_RST_PULSE_WIDTH; rp_writel(port, data, NV_PCIE2_RP_VEND_CTL0); } if (pcie->soc_data->updateFC_timer_expire_war) { data = rp_readl(port, RP_VEND_XP); data &= ~RP_VEND_XP_UPDATE_FC_THRESHOLD; data |= (0x60 << 18); rp_writel(port, data, RP_VEND_XP); } /* Do timer settings only if clk25m freq equal to 19.2 MHz */ if (clk_get_rate(devm_clk_get(pcie->dev, "clk_m")) != 19200000) return; data = rp_readl(port, NV_PCIE2_RP_TIMEOUT0); data &= ~PCIE2_RP_TIMEOUT0_PAD_PWRUP_MASK; data |= PCIE2_RP_TIMEOUT0_PAD_PWRUP; data &= ~PCIE2_RP_TIMEOUT0_PAD_PWRUP_CM_MASK; data |= PCIE2_RP_TIMEOUT0_PAD_PWRUP_CM; data &= ~PCIE2_RP_TIMEOUT0_PAD_SPDCHNG_GEN2_MASK; data |= PCIE2_RP_TIMEOUT0_PAD_SPDCHNG_GEN2; rp_writel(port, data, NV_PCIE2_RP_TIMEOUT0); data = rp_readl(port, NV_PCIE2_RP_TIMEOUT1); data &= ~PCIE2_RP_TIMEOUT1_RCVRY_SPD_SUCCESS_EIDLE_MASK; data |= PCIE2_RP_TIMEOUT1_RCVRY_SPD_SUCCESS_EIDLE; data &= ~PCIE2_RP_TIMEOUT1_RCVRY_SPD_UNSUCCESS_EIDLE_MASK; data |= PCIE2_RP_TIMEOUT1_RCVRY_SPD_UNSUCCESS_EIDLE; rp_writel(port, data, NV_PCIE2_RP_TIMEOUT1); data = rp_readl(port, NV_PCIE2_RP_XP_REF); data &= ~PCIE2_RP_XP_REF_MICROSECOND_LIMIT_MASK; data |= PCIE2_RP_XP_REF_MICROSECOND_LIMIT; data |= PCIE2_RP_XP_REF_MICROSECOND_ENABLE; data |= PCIE2_RP_XP_REF_CPL_TO_OVERRIDE; data &= ~PCIE2_RP_XP_REF_CPL_TO_CUSTOM_VALUE_MASK; data |= PCIE2_RP_XP_REF_CPL_TO_CUSTOM_VALUE; rp_writel(port, data, NV_PCIE2_RP_XP_REF); data = rp_readl(port, NV_PCIE2_RP_L1_PM_SUBSTATES_1_CYA); data &= ~PCIE2_RP_L1_PM_SUBSTATES_1_CYA_PWR_OFF_DLY_MASK; data |= PCIE2_RP_L1_PM_SUBSTATES_1_CYA_PWR_OFF_DLY; rp_writel(port, data, NV_PCIE2_RP_L1_PM_SUBSTATES_1_CYA); data = rp_readl(port, NV_PCIE2_RP_L1_PM_SUBSTATES_2_CYA); data &= ~PCIE2_RP_L1_PM_SUBSTATES_2_CYA_T_L1_2_DLY_MASK; data |= PCIE2_RP_L1_PM_SUBSTATES_2_CYA_T_L1_2_DLY; data &= ~PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND_MASK; data |= PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND; data &= ~PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND_COMP_MASK; data |= PCIE2_RP_L1_PM_SUBSTATES_2_CYA_MICROSECOND_COMP; rp_writel(port, data, NV_PCIE2_RP_L1_PM_SUBSTATES_2_CYA); if (pcie->soc_data->RAW_violation_war) { /* WAR for RAW violation on T124/T132 platforms */ data = rp_readl(port, NV_PCIE2_RP_RX_HDR_LIMIT); data &= ~PCIE2_RP_RX_HDR_LIMIT_PW_MASK; data |= PCIE2_RP_RX_HDR_LIMIT_PW; rp_writel(port, data, NV_PCIE2_RP_RX_HDR_LIMIT); data = rp_readl(port, NV_PCIE2_RP_PRIV_XP_DL); data |= PCIE2_RP_PRIV_XP_DL_GEN2_UPD_FC_TSHOLD; rp_writel(port, data, NV_PCIE2_RP_PRIV_XP_DL); data = rp_readl(port, RP_VEND_XP); data |= RP_VEND_XP_UPDATE_FC_THRESHOLD; rp_writel(port, data, RP_VEND_XP); } } } /* Enable various features of root port */ static void tegra_pcie_enable_rp_features(struct tegra_pcie_port *port) { unsigned int data; PR_FUNC_LINE; if (port->pcie->prod_list) { if (tegra_prod_set_by_name( &(port->pcie->pads), "prod_c_pad", port->pcie->prod_list)) { dev_dbg(port->pcie->dev, "pad prod settings are not found in DT\n"); } if (tegra_prod_set_by_name( &(port->base), "prod_c_rp", port->pcie->prod_list)) { dev_dbg(port->pcie->dev, "RP prod settings are not found in DT\n"); } } /* Optimal settings to enhance bandwidth */ data = rp_readl(port, RP_VEND_XP); data |= RP_VEND_XP_OPPORTUNISTIC_ACK; data |= RP_VEND_XP_OPPORTUNISTIC_UPDATEFC; rp_writel(port, data, RP_VEND_XP); /* Power mangagement settings */ /* Enable clock clamping by default and enable card detect */ data = rp_readl(port, NV_PCIE2_RP_PRIV_MISC); data |= PCIE2_RP_PRIV_MISC_CTLR_CLK_CLAMP_ENABLE | PCIE2_RP_PRIV_MISC_TMS_CLK_CLAMP_ENABLE; if (port->pcie->soc_data->update_clamp_threshold) { data |= PCIE2_RP_PRIV_MISC_CTLR_CLK_CLAMP_THRESHOLD | PCIE2_RP_PRIV_MISC_TMS_CLK_CLAMP_THRESHOLD; } rp_writel(port, data, NV_PCIE2_RP_PRIV_MISC); /* Enable ASPM - L1 state support by default */ data = rp_readl(port, NV_PCIE2_RP_VEND_XP1); data |= NV_PCIE2_RP_VEND_XP_LINK_PVT_CTL_L1_ASPM_SUPPORT; rp_writel(port, data, NV_PCIE2_RP_VEND_XP1); /* LTSSM wait for DLLP to finish before entering L1 or L2/L3 */ /* to avoid truncating of PM mesgs resulting in reciever errors */ data = rp_readl(port, NV_PCIE2_RP_VEND_XP_BIST); data |= PCIE2_RP_VEND_XP_BIST_GOTO_L1_L2_AFTER_DLLP_DONE; rp_writel(port, data, NV_PCIE2_RP_VEND_XP_BIST); /* unhide AER capability */ tegra_pcie_enable_aer(port, true); /* Disable L1SS capability advertisement if CLKREQ is not present */ if (port->disable_clock_request) { data = rp_readl(port, NV_PCIE2_RP_L1_PM_SUBSTATES_CYA); data |= PCIE2_RP_L1_PM_SUBSTATES_CYA_HIDE_CAP; rp_writel(port, data, NV_PCIE2_RP_L1_PM_SUBSTATES_CYA); } /* program timers for L1 substate support */ /* set cm_rtime = 30us and t_pwr_on = 70us as per HW team */ data = rp_readl(port, NV_PCIE2_RP_L1_PM_SUBSTATES_CYA); data &= ~PCIE2_RP_L1_PM_SUBSTATES_CYA_CM_RTIME_MASK; data |= (0x1E << PCIE2_RP_L1_PM_SUBSTATES_CYA_CM_RTIME_SHIFT); rp_writel(port, data, NV_PCIE2_RP_L1_PM_SUBSTATES_CYA); data = rp_readl(port, NV_PCIE2_RP_L1_PM_SUBSTATES_CYA); data &= ~(PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_SCL_MASK | PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_VAL_MASK); data |= (1 << PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_SCL_SHIFT) | (7 << PCIE2_RP_L1_PM_SUBSTATES_CYA_T_PWRN_VAL_SHIFT); rp_writel(port, data, NV_PCIE2_RP_L1_PM_SUBSTATES_CYA); tegra_pcie_apply_sw_war(port, false); } static void tegra_pcie_update_lane_width(struct tegra_pcie_port *port) { port->lanes = rp_readl(port, RP_LINK_CONTROL_STATUS); port->lanes = (port->lanes & RP_LINK_CONTROL_STATUS_NEG_LINK_WIDTH) >> 20; } static void tegra_pcie_update_pads2plle(struct tegra_pcie_port *port) { unsigned long ctrl = 0; u32 val = 0; ctrl = tegra_pcie_port_get_pex_ctrl(port); /* AFI_PEX_STATUS is AFI_PEX_CTRL + 4 */ val = afi_readl(port->pcie, ctrl + 4); if (val & 0x1) { val = afi_readl(port->pcie, AFI_PLLE_CONTROL); val &= ~AFI_PLLE_CONTROL_PADS2PLLE_CONTROL_EN; afi_writel(port->pcie, val, AFI_PLLE_CONTROL); } } static void mbist_war(struct tegra_pcie *pcie, bool apply) { struct tegra_pcie_port *port, *tmp; u32 data; list_for_each_entry_safe(port, tmp, &pcie->ports, list) { /* nature of MBIST bug is such that it needs to be applied * only for RootPort-0 even if there are no devices * connected to it */ if (port->index == 0) { data = rp_readl(port, NV_PCIE2_RP_VEND_CTL2); if (apply) data |= PCIE2_RP_VEND_CTL2_PCA_ENABLE; else data &= ~PCIE2_RP_VEND_CTL2_PCA_ENABLE; rp_writel(port, data, NV_PCIE2_RP_VEND_CTL2); } } } static int tegra_pcie_mxm_pwr_init(struct tegra_pcie_port *port) { mdelay(100); if (!(gpio_get_value(port->pwr_gd_gpio))) return 1; return 0; } static void tegra_pcie_check_ports(struct tegra_pcie *pcie) { struct tegra_pcie_port *port, *tmp; PR_FUNC_LINE; pcie->num_ports = 0; if (pcie->soc_data->mbist_war) mbist_war(pcie, true); list_for_each_entry_safe(port, tmp, &pcie->ports, list) { dev_info(pcie->dev, "probing port %u, using %u lanes\n", port->index, port->lanes); tegra_pcie_port_enable(port); tegra_pcie_enable_rp_features(port); /* override presence detection */ if (gpio_is_valid(port->gpio_presence_detection)) tegra_pcie_prsnt_map_override(port, !(gpio_get_value_cansleep( port->gpio_presence_detection))); else tegra_pcie_prsnt_map_override(port, true); } /* Wait for clock to latch (min of 100us) */ udelay(100); reset_control_deassert(pcie->pciex_rst); /* at this point in time, there is no end point which would * take more than 20 msec for root port to detect receiver and * set AUX_TX_RDET_STATUS bit. This would bring link up checking * time from its current value (around 200ms) to flat 20ms */ usleep_range(19000, 21000); list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if (tegra_pcie_port_check_link(port)) { port->status = 1; port->ep_status = 1; pcie->num_ports++; tegra_pcie_update_lane_width(port); tegra_pcie_update_pads2plle(port); continue; } port->ep_status = 0; dev_info(pcie->dev, "link %u down, ignoring\n", port->index); tegra_pcie_port_disable(port); } /* configure all links to gen2 speed by default */ tegra_pcie_link_speed(pcie); if (pcie->soc_data->mbist_war) mbist_war(pcie, false); } static int tegra_pcie_conf_gpios(struct tegra_pcie *pcie) { int irq, err = 0; struct tegra_pcie_port *port, *tmp; PR_FUNC_LINE; if (gpio_is_valid(pcie->plat_data->gpio_hot_plug)) { /* configure gpio for hotplug detection */ dev_info(pcie->dev, "acquiring hotplug_detect = %d\n", pcie->plat_data->gpio_hot_plug); err = devm_gpio_request(pcie->dev, pcie->plat_data->gpio_hot_plug, "pcie_hotplug_detect"); if (err < 0) { dev_err(pcie->dev, "%s: gpio_request failed %d\n", __func__, err); return err; } err = gpio_direction_input( pcie->plat_data->gpio_hot_plug); if (err < 0) { dev_err(pcie->dev, "%s: gpio_direction_input failed %d\n", __func__, err); return err; } irq = gpio_to_irq(pcie->plat_data->gpio_hot_plug); if (irq < 0) { dev_err(pcie->dev, "Unable to get irq for hotplug_detect\n"); return err; } err = devm_request_irq(pcie->dev, (unsigned int)irq, gpio_pcie_detect_isr, IRQF_TRIGGER_RISING | IRQF_TRIGGER_FALLING, "pcie_hotplug_detect", (void *)pcie); if (err < 0) { dev_err(pcie->dev, "Unable to claim irq for hotplug_detect\n"); return err; } } if (gpio_is_valid(pcie->plat_data->gpio_x1_slot)) { err = devm_gpio_request(pcie->dev, pcie->plat_data->gpio_x1_slot, "pcie_x1_slot"); if (err < 0) { dev_err(pcie->dev, "%s: pcie_x1_slot gpio_request failed %d\n", __func__, err); return err; } err = gpio_direction_output( pcie->plat_data->gpio_x1_slot, 1); if (err < 0) { dev_err(pcie->dev, "%s: pcie_x1_slot gpio_direction_output failed %d\n", __func__, err); return err; } gpio_set_value_cansleep( pcie->plat_data->gpio_x1_slot, 1); } if (gpio_is_valid(pcie->plat_data->gpio_wake)) { err = devm_gpio_request(pcie->dev, pcie->plat_data->gpio_wake, "pcie_wake"); if (err < 0) { dev_err(pcie->dev, "%s: pcie_wake gpio_request failed %d\n", __func__, err); return err; } err = gpio_direction_input( pcie->plat_data->gpio_wake); if (err < 0) { dev_err(pcie->dev, "%s: pcie_wake gpio_direction_input failed %d\n", __func__, err); return err; } } list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if (gpio_is_valid(port->gpio_presence_detection)) { err = devm_gpio_request_one(pcie->dev, port->gpio_presence_detection, GPIOF_DIR_IN, "pcie_presence_detection"); if (err < 0) { dev_err(pcie->dev, "%s: pcie_prsnt gpio_request failed %d\n", __func__, err); return err; } } } return 0; } static int tegra_pcie_scale_voltage(struct tegra_pcie *pcie) { struct tegra_pcie_port *port, *tmp; struct tegra_pcie_soc_data *sd = pcie->soc_data; int err = 0; u32 data = 0; u32 active_lanes = 0; bool is_gen2 = false; PR_FUNC_LINE; list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if (!port->status) continue; data = rp_readl(port, RP_LINK_CONTROL_STATUS); active_lanes += ((data & RP_LINK_CONTROL_STATUS_NEG_LINK_WIDTH) >> 20); if (((data & RP_LINK_CONTROL_STATUS_LINK_SPEED) >> 16) == 2) is_gen2 = true; } if (sd->dvfs_mselect) { struct clk *mselect_clk; active_lanes = 0; dev_dbg(pcie->dev, "mselect_clk is set @ %u\n", sd->dvfs_tbl[active_lanes][is_gen2].afi_clk); mselect_clk = devm_clk_get(pcie->dev, "mselect"); if (IS_ERR(mselect_clk)) { dev_err(pcie->dev, "mselect clk_get failed: %ld\n", PTR_ERR(mselect_clk)); return PTR_ERR(mselect_clk); } err = clk_set_rate(mselect_clk, sd->dvfs_tbl[active_lanes][is_gen2].afi_clk); if (err) { dev_err(pcie->dev, "setting mselect clk to %u failed : %d\n", sd->dvfs_tbl[active_lanes][is_gen2].afi_clk, err); return err; } } if (sd->dvfs_afi) { dev_dbg(pcie->dev, "afi_clk is set @ %u\n", sd->dvfs_tbl[active_lanes][is_gen2].afi_clk); err = clk_set_rate(devm_clk_get(pcie->dev, "afi"), sd->dvfs_tbl[active_lanes][is_gen2].afi_clk); if (err) { dev_err(pcie->dev, "setting afi clk to %u failed : %d\n", sd->dvfs_tbl[active_lanes][is_gen2].afi_clk, err); return err; } } dev_dbg(pcie->dev, "emc_clk is set @ %u\n", sd->dvfs_tbl[active_lanes][is_gen2].emc_clk); err = tegra_bwmgr_set_emc(pcie->emc_bwmgr, sd->dvfs_tbl[active_lanes][is_gen2].emc_clk, TEGRA_BWMGR_SET_EMC_FLOOR); if (err < 0) { dev_err(pcie->dev, "setting emc clk to %u failed : %d\n", sd->dvfs_tbl[active_lanes][is_gen2].emc_clk, err); return err; } return err; } static void tegra_pcie_change_link_speed(struct tegra_pcie *pcie) { struct device *dev = pcie->dev; struct tegra_pcie_port *port, *tmp; ktime_t deadline; u32 value; list_for_each_entry_safe(port, tmp, &pcie->ports, list) { /* * "Supported Link Speeds Vector" in "Link Capabilities 2" * is not supported by Tegra. tegra_pcie_change_link_speed() * is called only for Tegra chips which support Gen2. * So there no harm if supported link speed is not verified. */ value = readl(port->base + RP_LINK_CONTROL_STATUS_2); value &= ~PCI_EXP_LNKSTA_CLS; value |= PCI_EXP_LNKSTA_CLS_5_0GB; writel(value, port->base + RP_LINK_CONTROL_STATUS_2); /* * Poll until link comes back from recovery to avoid race * condition. */ deadline = ktime_add_us(ktime_get(), LINK_RETRAIN_TIMEOUT); while (ktime_before(ktime_get(), deadline)) { value = readl(port->base + RP_LINK_CONTROL_STATUS); if ((value & PCI_EXP_LNKSTA_LT) == 0) break; usleep_range(2000, 3000); } if (value & PCI_EXP_LNKSTA_LT) dev_warn(dev, "PCIe port %u link is in recovery\n", port->index); /* Clear BW Management Status */ value = readl(port->base + RP_LINK_CONTROL_STATUS); value |= RP_LINK_CONTROL_STATUS_BW_MGMT_STATUS; writel(value, port->base + RP_LINK_CONTROL_STATUS); /* Retrain the link */ value = readl(port->base + RP_LINK_CONTROL_STATUS); value |= PCI_EXP_LNKCTL_RL; writel(value, port->base + RP_LINK_CONTROL_STATUS); deadline = ktime_add_us(ktime_get(), LINK_RETRAIN_TIMEOUT); while (ktime_before(ktime_get(), deadline)) { value = readl(port->base + RP_LINK_CONTROL_STATUS); if (value & RP_LINK_CONTROL_STATUS_BW_MGMT_STATUS) break; usleep_range(2000, 3000); } if (value & PCI_EXP_LNKSTA_LT) dev_err(dev, "failed to retrain link of port %u\n", port->index); } } static void tegra_pcie_link_speed(struct tegra_pcie *pcie) { PR_FUNC_LINE; tegra_pcie_change_link_speed(pcie); tegra_pcie_scale_voltage(pcie); return; } static void tegra_pcie_enable_features(struct tegra_pcie *pcie) { struct tegra_pcie_port *port; PR_FUNC_LINE; list_for_each_entry(port, &pcie->ports, list) { if (port->status) tegra_pcie_apply_sw_war(port, true); } } static int tegra_pcie_enable_msi(struct tegra_pcie *, bool); static int tegra_pcie_disable_msi(struct tegra_pcie *pcie); static int tegra_pcie_init(struct tegra_pcie *pcie) { int err = 0; struct pci_bus *child; struct pci_host_bridge *host = pcie->host; PR_FUNC_LINE; INIT_WORK(&pcie->hotplug_detect, work_hotplug_handler); err = tegra_pcie_get_resources(pcie); if (err) { dev_err(pcie->dev, "PCIE: get resources failed\n"); return err; } err = tegra_pcie_power_on(pcie); if (err) { dev_err(pcie->dev, "PCIE: Failed to power on: %d\n", err); goto fail_release_resource; } err = tegra_pcie_conf_gpios(pcie); if (err) { dev_err(pcie->dev, "PCIE: configuring gpios failed\n"); goto fail_power_off; } if (!pcie->num_ports) { dev_info(pcie->dev, "PCIE: no end points detected\n"); err = -ENODEV; goto fail_power_off; } if (IS_ENABLED(CONFIG_PCI_MSI)) { err = tegra_pcie_enable_msi(pcie, false); if (err < 0) { dev_err(pcie->dev, "failed to enable MSI support: %d\n", err); goto fail_release_resource; } } pci_add_flags(PCI_REASSIGN_ALL_RSRC | PCI_REASSIGN_ALL_BUS); host->busnr = pcie->busn.start; host->dev.parent = pcie->dev; host->ops = &tegra_pcie_ops; err = pci_register_host_bridge(host); if (err < 0) { dev_err(pcie->dev, "failed to register host: %d\n", err); goto fail_power_off; } pci_scan_child_bus(host->bus); pci_fixup_irqs(pci_common_swizzle, tegra_pcie_map_irq); pci_bus_size_bridges(host->bus); pci_bus_assign_resources(host->bus); list_for_each_entry(child, &host->bus->children, node) pcie_bus_configure_settings(child); tegra_pcie_postinit(); tegra_pcie_enable_features(pcie); pci_bus_add_devices(host->bus); /* register pcie device as wakeup source */ device_init_wakeup(pcie->dev, true); return 0; fail_power_off: tegra_pcie_power_off(pcie); fail_release_resource: tegra_pcie_release_resources(pcie); return err; } /* 1:1 matching of these to the MSI vectors, 1 per bit */ /* and each mapping matches one of the available interrupts */ struct msi_map_entry { bool used; u8 index; int irq; }; /* hardware supports 256 max*/ #if (INT_PCI_MSI_NR > 256) #error "INT_PCI_MSI_NR too big" #endif static int tegra_msi_alloc(struct tegra_msi *chip) { int msi; PR_FUNC_LINE; mutex_lock(&chip->lock); msi = find_first_zero_bit(chip->used, INT_PCI_MSI_NR); if (msi < INT_PCI_MSI_NR) set_bit(msi, chip->used); else msi = -ENOSPC; mutex_unlock(&chip->lock); return msi; } static void tegra_msi_free(struct tegra_msi *chip, unsigned long irq) { struct device *dev = chip->chip.dev; PR_FUNC_LINE; mutex_lock(&chip->lock); if (!test_bit(irq, chip->used)) dev_err(dev, "trying to free unused MSI#%lu\n", irq); else clear_bit(irq, chip->used); mutex_unlock(&chip->lock); } static irqreturn_t tegra_pcie_msi_irq(int irq, void *data) { struct tegra_pcie *pcie = data; struct tegra_msi *msi = &pcie->msi; unsigned int i, processed = 0; PR_FUNC_LINE; for (i = 0; i < 8; i++) { unsigned long reg = afi_readl(pcie, AFI_MSI_VEC0_0 + i * 4); while (reg) { unsigned int offset = find_first_bit(&reg, 32); unsigned int index = i * 32 + offset; unsigned int irq_num; /* check if there are any interrupts in this reg */ if (offset == 32) break; /* clear the interrupt */ afi_writel(pcie, 1 << offset, AFI_MSI_VEC0_0 + i * 4); irq_num = irq_find_mapping(msi->domain, index); if (irq_num) { if (test_bit(index, msi->used)) generic_handle_irq(irq_num); else dev_info(pcie->dev, "unhandled MSI\n"); } else { /* * that's weird who triggered this? * just clear it */ dev_info(pcie->dev, "unexpected MSI\n"); } /* see if there's any more pending in this vector */ reg = afi_readl(pcie, AFI_MSI_VEC0_0 + i * 4); processed++; } } return processed > 0 ? IRQ_HANDLED : IRQ_NONE; } static int tegra_msi_setup_irq(struct msi_controller *chip, struct pci_dev *pdev, struct msi_desc *desc) { struct tegra_msi *msi = to_tegra_msi(chip); struct msi_msg msg; unsigned int irq; int hwirq; PR_FUNC_LINE; hwirq = tegra_msi_alloc(msi); if (hwirq < 0) return hwirq; irq = irq_create_mapping(msi->domain, hwirq); if (!irq) return -EINVAL; irq_set_msi_desc(irq, desc); msg.address_lo = lower_32_bits(msi->phys); #ifdef CONFIG_ARM64 msg.address_hi = upper_32_bits(msi->phys); #else msg.address_hi = 0; #endif msg.data = hwirq; write_msi_msg(irq, &msg); return 0; } static void tegra_msi_teardown_irq(struct msi_controller *chip, unsigned int irq) { struct tegra_msi *msi = to_tegra_msi(chip); struct irq_data *d = irq_get_irq_data(irq); PR_FUNC_LINE; tegra_msi_free(msi, d->hwirq); } static struct irq_chip tegra_msi_irq_chip = { .name = "Tegra PCIe MSI", .irq_enable = unmask_msi_irq, .irq_disable = mask_msi_irq, .irq_mask = mask_msi_irq, .irq_unmask = unmask_msi_irq, }; static int tegra_msi_map(struct irq_domain *domain, unsigned int irq, irq_hw_number_t hwirq) { PR_FUNC_LINE; irq_set_chip_and_handler(irq, &tegra_msi_irq_chip, handle_simple_irq); irq_set_chip_data(irq, domain->host_data); return 0; } static const struct irq_domain_ops msi_domain_ops = { .map = tegra_msi_map, }; static int tegra_pcie_enable_msi(struct tegra_pcie *pcie, bool no_init) { struct platform_device *pdev = to_platform_device(pcie->dev); struct tegra_msi *msi = &pcie->msi; int err; u32 reg; PR_FUNC_LINE; if (!msi->virt) { if (no_init) return true; mutex_init(&msi->lock); msi->chip.dev = pcie->dev; msi->chip.setup_irq = tegra_msi_setup_irq; msi->chip.teardown_irq = tegra_msi_teardown_irq; msi->domain = irq_domain_add_linear(pcie->dev->of_node, INT_PCI_MSI_NR, &msi_domain_ops, &msi->chip); if (!msi->domain) { dev_err(&pdev->dev, "failed to create IRQ domain\n"); return -ENOMEM; } err = platform_get_irq_byname(pdev, "msi"); if (err < 0) { dev_err(&pdev->dev, "failed to get IRQ: %d\n", err); goto free_irq_domain; } msi->irq = err; err = request_irq(msi->irq, tegra_pcie_msi_irq, IRQF_NO_THREAD, tegra_msi_irq_chip.name, pcie); if (err < 0) { dev_err(&pdev->dev, "failed to request IRQ: %d\n", err); goto free_irq_domain; } /* setup AFI/FPCI range */ err = dma_set_coherent_mask(pcie->dev, DMA_BIT_MASK(32)); if (err < 0) { dev_err(&pdev->dev, "dma_set_coherent_mask() failed: %d\n", err); goto free_irq; } msi->virt = dma_alloc_coherent(pcie->dev, PAGE_SIZE, &msi->phys, GFP_KERNEL); if (!msi->virt) { dev_err(&pdev->dev, "%s: failed to alloc dma mem\n", __func__); err = -ENOMEM; goto free_irq; } } afi_writel(pcie, msi->phys >> 8, AFI_MSI_FPCI_BAR_ST); afi_writel(pcie, msi->phys, AFI_MSI_AXI_BAR_ST); /* this register is in 4K increments */ afi_writel(pcie, 1, AFI_MSI_BAR_SZ); /* enable all MSI vectors */ afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC0_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC1_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC2_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC3_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC4_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC5_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC6_0); afi_writel(pcie, 0xffffffff, AFI_MSI_EN_VEC7_0); /* and unmask the MSI interrupt */ reg = afi_readl(pcie, AFI_INTR_MASK); reg |= AFI_INTR_MASK_MSI_MASK; afi_writel(pcie, reg, AFI_INTR_MASK); return 0; free_irq: free_irq(msi->irq, pcie); free_irq_domain: irq_domain_remove(msi->domain); return err; } static int tegra_pcie_disable_msi(struct tegra_pcie *pcie) { struct tegra_msi *msi = &pcie->msi; unsigned int i, irq; u32 value; PR_FUNC_LINE; if (pcie->pcie_power_enabled == 0) return 0; /* mask the MSI interrupt */ value = afi_readl(pcie, AFI_INTR_MASK); value &= ~AFI_INTR_MASK_MSI_MASK; afi_writel(pcie, value, AFI_INTR_MASK); /* disable all MSI vectors */ afi_writel(pcie, 0, AFI_MSI_EN_VEC0_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC1_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC2_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC3_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC4_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC5_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC6_0); afi_writel(pcie, 0, AFI_MSI_EN_VEC7_0); dma_free_coherent(pcie->dev, PAGE_SIZE, msi->virt, msi->phys); if (msi->irq > 0) free_irq(msi->irq, pcie); for (i = 0; i < INT_PCI_MSI_NR; i++) { irq = irq_find_mapping(msi->domain, i); if (irq > 0) irq_dispose_mapping(irq); } irq_domain_remove(msi->domain); return 0; } static void update_rp_lanes(struct tegra_pcie *pcie, u32 lanes) { struct tegra_pcie_port *port = NULL; list_for_each_entry(port, &pcie->ports, list) port->lanes = (lanes >> (port->index << 3)) & 0xFF; } static int tegra_pcie_get_xbar_config(struct tegra_pcie *pcie, u32 lanes, u32 *xbar) { struct device_node *np = pcie->dev->of_node; if (of_device_is_compatible(np, "nvidia,tegra210b01-pcie")) { switch (lanes) { case 0x0104: dev_info(pcie->dev, "4x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X1; return 0; default: dev_info(pcie->dev, "wrong configuration updated in DT, " "switching to default 4x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X1; update_rp_lanes(pcie, 0x0104); return 0; } } else if (of_device_is_compatible(np, "nvidia,tegra124-pcie") || of_device_is_compatible(np, "nvidia,tegra210-pcie")) { switch (lanes) { case 0x0104: dev_info(pcie->dev, "4x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X1; return 0; case 0x0102: dev_info(pcie->dev, "2x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X2_X1; return 0; default: dev_info(pcie->dev, "wrong configuration updated in DT, " "switching to default 4x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X1; update_rp_lanes(pcie, 0x0104); return 0; } } else if (of_device_is_compatible(np, "nvidia,tegra186-pcie")) { switch (lanes) { case 0x010004: dev_info(pcie->dev, "4x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X4_X0_X1; return 0; case 0x010102: dev_info(pcie->dev, "2x1, 1x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X2_X1_X1; return 0; case 0x010101: dev_info(pcie->dev, "1x1, 1x1, 1x1 configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X1_X1_X1; return 0; default: dev_info(pcie->dev, "wrong configuration updated in DT," " switching to default 2x1, 1x1, 1x1 " "configuration\n"); *xbar = AFI_PCIE_CONFIG_XBAR_CONFIG_X2_X1_X1; update_rp_lanes(pcie, 0x010102); return 0; } } return -EINVAL; } static void tegra_pcie_read_plat_data(struct tegra_pcie *pcie) { struct device_node *node = pcie->dev->of_node; PR_FUNC_LINE; of_property_read_u32(node, "nvidia,boot-detect-delay", &pcie->plat_data->boot_detect_delay); pcie->plat_data->gpio_hot_plug = of_get_named_gpio(node, "nvidia,hot-plug-gpio", 0); pcie->plat_data->gpio_wake = of_get_named_gpio(node, "nvidia,wake-gpio", 0); pcie->plat_data->gpio_x1_slot = of_get_named_gpio(node, "nvidia,x1-slot-gpio", 0); pcie->plat_data->has_memtype_lpddr4 = of_property_read_bool(node, "nvidia,has_memtype_lpddr4"); } static char *t124_rail_names[] = {"hvdd-pex", "hvdd-pex-pll-e", "dvddio-pex", "avddio-pex", "avdd-pex-pll", "vddio-pex-ctl"}; static char *t210_rail_names[] = { "avdd-pll-uerefe", "hvddio-pex", "dvddio-pex", "dvdd-pex-pll", "hvdd-pex-pll-e", "vddio-pex-ctl" }; static char *t186_rail_names[] = {"vddio-pexctl-aud"}; static const struct tegra_pcie_soc_data tegra186_pcie_data = { .num_ports = 3, .pcie_regulator_names = t186_rail_names, .num_pcie_regulators = sizeof(t186_rail_names) / sizeof(t186_rail_names[0]), .dvfs_afi = true, .update_clamp_threshold = true, .dvfs_tbl = { {{0, 0}, {0, 0} }, {{102000000, 480000000}, {102000000, 480000000} }, {{102000000, 480000000}, {204000000, 480000000} }, {{102000000, 480000000}, {204000000, 480000000} }, {{204000000, 480000000}, {408000000, 480000000} }, {{204000000, 480000000}, {408000000, 640000000} } }, }; static const struct tegra_pcie_soc_data tegra210b01_pcie_data = { .num_ports = 2, .pcie_regulator_names = t210_rail_names, .num_pcie_regulators = sizeof(t210_rail_names) / sizeof(t210_rail_names[0]), .program_uphy = true, .program_clkreq_as_bi_dir = true, .enable_wrap = true, .perf_war = true, .updateFC_timer_expire_war = true, .l1ss_rp_wakeup_war = true, .link_speed_war = true, .dvfs_mselect = true, .dvfs_tbl = { {{204000000, 102000000}, {408000000, 528000000} } }, }; static const struct tegra_pcie_soc_data tegra210_pcie_data = { .num_ports = 2, .pcie_regulator_names = t210_rail_names, .num_pcie_regulators = sizeof(t210_rail_names) / sizeof(t210_rail_names[0]), .config_pex_io_dpd = true, .program_uphy = true, .program_clkreq_as_bi_dir = true, .enable_wrap = true, .mbist_war = true, .perf_war = true, .updateFC_timer_expire_war = true, .l1ss_rp_wakeup_war = true, .link_speed_war = true, .dvfs_mselect = true, .update_clamp_threshold = true, .dvfs_tbl = { {{204000000, 102000000}, {408000000, 528000000} } }, }; static const struct tegra_pcie_soc_data tegra124_pcie_data = { .num_ports = 2, .pcie_regulator_names = t124_rail_names, .num_pcie_regulators = sizeof(t124_rail_names) / sizeof(t124_rail_names[0]), .RAW_violation_war = true, }; static struct of_device_id tegra_pcie_of_match[] = { { .compatible = "nvidia,tegra186-pcie", .data = &tegra186_pcie_data }, { .compatible = "nvidia,tegra210b01-pcie", .data = &tegra210b01_pcie_data }, { .compatible = "nvidia,tegra210-pcie", .data = &tegra210_pcie_data }, { .compatible = "nvidia,tegra124-pcie", .data = &tegra124_pcie_data }, { } }; MODULE_DEVICE_TABLE(of, tegra_pcie_of_match); static int tegra_pcie_parse_dt(struct tegra_pcie *pcie) { struct tegra_pcie_soc_data *soc = pcie->soc_data; struct device_node *np = pcie->dev->of_node, *port; struct of_pci_range_parser parser; struct of_pci_range range; u32 lanes = 0; struct resource res = {0}; int err; PR_FUNC_LINE; if (of_pci_range_parser_init(&parser, np)) { dev_err(pcie->dev, "missing \"ranges\" property\n"); return -EINVAL; } for_each_of_pci_range(&parser, &range) { err = of_pci_range_to_resource(&range, np, &res); if (err < 0) return err; switch (res.flags & IORESOURCE_TYPE_BITS) { case IORESOURCE_IO: /* Track the bus -> CPU I/O mapping offset. */ pcie->offset.io = res.start - range.pci_addr; memcpy(&pcie->pio, &res, sizeof(res)); pcie->pio.name = np->full_name; /* * The Tegra PCIe host bridge uses this to program the * mapping of the I/O space to the physical address, * so we override the .start and .end fields here that * of_pci_range_to_resource() converted to I/O space. * We also set the IORESOURCE_MEM type to clarify that * the resource is in the physical memory space. */ pcie->io.start = range.cpu_addr; pcie->io.end = range.cpu_addr + range.size - 1; pcie->io.flags = IORESOURCE_MEM; pcie->io.name = "I/O"; memcpy(&res, &pcie->io, sizeof(res)); break; case IORESOURCE_MEM: /* * Track the bus -> CPU memory mapping offset. This * assumes that the prefetchable and non-prefetchable * regions will be the last of type IORESOURCE_MEM in * the ranges property. * */ pcie->offset.mem = res.start - range.pci_addr; if (res.flags & IORESOURCE_PREFETCH) { memcpy(&pcie->prefetch, &res, sizeof(res)); pcie->prefetch.name = "prefetchable"; } else { memcpy(&pcie->mem, &res, sizeof(res)); pcie->mem.name = "non-prefetchable"; } break; } } err = of_pci_parse_bus_range(np, &pcie->busn); if (err < 0) { dev_err(pcie->dev, "failed to parse ranges property: %d\n", err); pcie->busn.name = np->name; pcie->busn.start = 0; pcie->busn.end = 0xff; pcie->busn.flags = IORESOURCE_BUS; } /* parse root ports */ for_each_child_of_node(np, port) { struct tegra_pcie_port *rp; unsigned int index; u32 value; #ifdef CONFIG_THERMAL if (!strncmp(port->name, "pcie-cool-dev", sizeof("pcie-cool-dev"))) pcie->is_cooling_dev = true; #endif if (strncmp(port->type, "pci", sizeof("pci"))) continue; err = of_pci_get_devfn(port); if (err < 0) { dev_err(pcie->dev, "failed to parse address: %d\n", err); return err; } index = PCI_SLOT(err); if (index < 1 || index > soc->num_ports) { dev_err(pcie->dev, "invalid port number: %d\n", index); return -EINVAL; } index--; err = of_property_read_u32(port, "nvidia,num-lanes", &value); if (err < 0) { dev_err(pcie->dev, "failed to parse # of lanes: %d\n", err); return err; } if (value > 16) { dev_err(pcie->dev, "invalid # of lanes: %u\n", value); return -EINVAL; } lanes |= value << (index << 3); if (!of_device_is_available(port)) { continue; } rp = devm_kzalloc(pcie->dev, sizeof(*rp), GFP_KERNEL); if (!rp) return -ENOMEM; err = of_address_to_resource(port, 0, &rp->regs); if (err < 0) { dev_err(pcie->dev, "failed to parse address: %d\n", err); return err; } rp->gpio_presence_detection = of_get_named_gpio(port, "nvidia,presence-detection-gpio", 0); INIT_LIST_HEAD(&rp->list); rp->index = index; rp->lanes = rp->num_lanes = value; rp->pcie = pcie; rp->np = port; rp->base = devm_ioremap_resource(pcie->dev, &rp->regs); if (!(rp->base)) return -EADDRNOTAVAIL; rp->disable_clock_request = of_property_read_bool(port, "nvidia,disable-clock-request"); rp->rst_gpio = of_get_named_gpio(port, "nvidia,rst-gpio", 0); if (gpio_is_valid(rp->rst_gpio)) { err = devm_gpio_request(pcie->dev, rp->rst_gpio, "pex_rst_gpio"); if (err < 0) { dev_err(pcie->dev, "%s: pex_rst_gpio request failed %d\n", __func__, err); return err; } err = gpio_direction_output(rp->rst_gpio, 0); if (err < 0) { dev_err(pcie->dev, "%s: pex_rst_gpio direction_output failed %d\n", __func__, err); return err; } } rp->has_mxm_port = of_property_read_bool(port, "nvidia,has-mxm-port"); if (rp->has_mxm_port) { rp->pwr_gd_gpio = of_get_named_gpio(port, "nvidia,pwr-gd-gpio", 0); if (gpio_is_valid(rp->pwr_gd_gpio)) { err = devm_gpio_request(pcie->dev, rp->pwr_gd_gpio, "pwr_gd_gpio"); if (err < 0) { dev_err(pcie->dev, "%s: pwr_gd_gpio request failed %d\n", __func__, err); return err; } err = gpio_direction_input(rp->pwr_gd_gpio); if (err < 0) { dev_err(pcie->dev, "%s: pwr_gd_gpio direction_input failed %d\n", __func__, err); } } } rp->n_gpios = of_gpio_named_count(port, "nvidia,plat-gpios"); if (rp->n_gpios > 0) { int count, gpio; enum of_gpio_flags flags; unsigned long f; rp->gpios = devm_kzalloc(pcie->dev, rp->n_gpios * sizeof(int), GFP_KERNEL); if (!rp->gpios) return -ENOMEM; for (count = 0; count < rp->n_gpios; ++count) { gpio = of_get_named_gpio_flags(port, "nvidia,plat-gpios", count, &flags); if (!gpio_is_valid(gpio)) return gpio; f = (flags & OF_GPIO_ACTIVE_LOW) ? (GPIOF_OUT_INIT_LOW | GPIOF_ACTIVE_LOW) : GPIOF_OUT_INIT_HIGH; err = devm_gpio_request_one(pcie->dev, gpio, f, NULL); if (err < 0) { dev_err(pcie->dev, "gpio %d request failed\n", gpio); return err; } rp->gpios[count] = gpio; } } list_add_tail(&rp->list, &pcie->ports); } err = tegra_pcie_get_xbar_config(pcie, lanes, &pcie->xbar_config); if (err < 0) { dev_err(pcie->dev, "invalid lane configuration\n"); return err; } return 0; } static int list_devices(struct seq_file *s, void *data) { struct pci_dev *pdev = NULL; u16 vendor, device, devclass, speed; bool pass = false; int ret = 0; for_each_pci_dev(pdev) { pass = true; ret = pci_read_config_word(pdev, PCI_VENDOR_ID, &vendor); if (ret) { pass = false; break; } ret = pci_read_config_word(pdev, PCI_DEVICE_ID, &device); if (ret) { pass = false; break; } ret = pci_read_config_word(pdev, PCI_CLASS_DEVICE, &devclass); if (ret) { pass = false; break; } pcie_capability_read_word(pdev, PCI_EXP_LNKSTA, &speed); seq_printf(s, "%s Vendor:%04x Device id:%04x ", kobject_name(&pdev->dev.kobj), vendor, device); seq_printf(s, "Class:%04x Speed:%s Driver:%s(%s)\n", devclass, ((speed & PCI_EXP_LNKSTA_CLS_5_0GB) == PCI_EXP_LNKSTA_CLS_5_0GB) ? "Gen2" : "Gen1", (pdev->driver) ? "enabled" : "disabled", (pdev->driver) ? pdev->driver->name : NULL); } if (!pass) seq_printf(s, "Couldn't read devices\n"); return ret; } static int apply_link_speed(struct seq_file *s, void *data) { struct tegra_pcie *pcie = (struct tegra_pcie *)(s->private); seq_puts(s, "Changing link speed to Gen2\n"); tegra_pcie_link_speed(pcie); seq_printf(s, "Done\n"); return 0; } static int check_d3hot(struct seq_file *s, void *data) { u16 val; struct pci_dev *pdev = NULL; /* Force all the devices (including RPs) in d3 hot state */ for_each_pci_dev(pdev) { if (pci_pcie_type(pdev) == PCI_EXP_TYPE_ROOT_PORT || pci_pcie_type(pdev) == PCI_EXP_TYPE_DOWNSTREAM) continue; /* First, keep Downstream component in D3_Hot */ pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &val); if ((val & PCI_PM_CTRL_STATE_MASK) == PCI_D3hot) seq_printf(s, "device[%x:%x] is already in D3_hot]\n", pdev->vendor, pdev->device); val &= ~PCI_PM_CTRL_STATE_MASK; val |= PCI_D3hot; pci_write_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, val); /* Keep corresponding upstream component in D3_Hot */ pci_read_config_word(pdev->bus->self, pdev->bus->self->pm_cap + PCI_PM_CTRL, &val); val &= ~PCI_PM_CTRL_STATE_MASK; val |= PCI_D3hot; pci_write_config_word(pdev->bus->self, pdev->bus->self->pm_cap + PCI_PM_CTRL, val); mdelay(100); /* check if they have changed their state */ pci_read_config_word(pdev, pdev->pm_cap + PCI_PM_CTRL, &val); if ((val & PCI_PM_CTRL_STATE_MASK) == PCI_D3hot) seq_printf(s, "device[%x:%x] transitioned to D3_hot]\n", pdev->vendor, pdev->device); else seq_printf(s, "device[%x:%x] couldn't transition to D3_hot]\n", pdev->vendor, pdev->device); pci_read_config_word(pdev->bus->self, pdev->bus->self->pm_cap + PCI_PM_CTRL, &val); if ((val & PCI_PM_CTRL_STATE_MASK) == PCI_D3hot) seq_printf(s, "device[%x:%x] transitioned to D3_hot]\n", pdev->bus->self->vendor, pdev->bus->self->device); else seq_printf(s, "device[%x:%x] couldn't transition to D3_hot]\n", pdev->bus->self->vendor, pdev->bus->self->device); } return 0; } static int dump_config_space(struct seq_file *s, void *data) { u8 val; int row, col; struct pci_dev *pdev = NULL; for_each_pci_dev(pdev) { int row_cnt = pci_is_pcie(pdev) ? PCI_EXT_CFG_SPACE_SIZE : PCI_CFG_SPACE_SIZE; seq_printf(s, "%s\n", kobject_name(&pdev->dev.kobj)); seq_printf(s, "%s\n", "------------"); for (row = 0; row < (row_cnt / 16); row++) { seq_printf(s, "%02x: ", (row * 16)); for (col = 0; col < 16; col++) { pci_read_config_byte(pdev, ((row * 16) + col), &val); seq_printf(s, "%02x ", val); } seq_printf(s, "\n"); } } return 0; } static int dump_afi_space(struct seq_file *s, void *data) { u32 val, offset; struct tegra_pcie_port *port = NULL; struct tegra_pcie *pcie = (struct tegra_pcie *)(s->private); list_for_each_entry(port, &pcie->ports, list) { seq_puts(s, "Offset: Values\n"); for (offset = 0; offset < 0x200; offset += 0x10) { val = afi_readl(port->pcie, offset); seq_printf(s, "%6x: %8x %8x %8x %8x\n", offset, afi_readl(port->pcie, offset), afi_readl(port->pcie, offset + 4), afi_readl(port->pcie, offset + 8), afi_readl(port->pcie, offset + 12)); } } return 0; } static int config_read(struct seq_file *s, void *data) { struct pci_dev *pdev = NULL; pdev = pci_get_bus_and_slot((bdf >> 8), (bdf & 0xFF)); if (!pdev) { seq_printf(s, "%02d:%02d.%02d : Doesn't exist\n", (bdf >> 8), PCI_SLOT(bdf), PCI_FUNC(bdf)); seq_printf(s, "Enter (bus<<8 | dev<<3 | func) value to bdf file\n"); goto end; } if (config_offset >= PCI_EXT_CFG_SPACE_SIZE) { seq_printf(s, "Config offset exceeds max (i.e %d) value\n", PCI_EXT_CFG_SPACE_SIZE); } if (!(config_offset & 0x3)) { u32 val; /* read 32 */ pci_read_config_dword(pdev, config_offset, &val); seq_printf(s, "%08x\n", val); config_val = val; } else if (!(config_offset & 0x1)) { u16 val; /* read 16 */ pci_read_config_word(pdev, config_offset, &val); seq_printf(s, "%04x\n", val); config_val = val; } else { u8 val; /* read 8 */ pci_read_config_byte(pdev, config_offset, &val); seq_printf(s, "%02x\n", val); config_val = val; } end: return 0; } static int config_write(struct seq_file *s, void *data) { struct pci_dev *pdev = NULL; pdev = pci_get_bus_and_slot((bdf >> 8), (bdf & 0xFF)); if (!pdev) { seq_printf(s, "%02d:%02d.%02d : Doesn't exist\n", (bdf >> 8), PCI_SLOT(bdf), PCI_FUNC(bdf)); seq_printf(s, "Enter (bus<<8 | dev<<3 | func) value to bdf file\n"); goto end; } if (config_offset >= PCI_EXT_CFG_SPACE_SIZE) { seq_printf(s, "Config offset exceeds max (i.e %d) value\n", PCI_EXT_CFG_SPACE_SIZE); } if (!(config_offset & 0x3)) { /* write 32 */ pci_write_config_dword(pdev, config_offset, config_val); } else if (!(config_offset & 0x1)) { /* write 16 */ pci_write_config_word(pdev, config_offset, (u16)(config_val & 0xFFFF)); } else { /* write 8 */ pci_write_config_byte(pdev, config_offset, (u8)(config_val & 0xFF)); } end: return 0; } static int power_down(struct seq_file *s, void *data) { struct tegra_pcie_port *port = NULL; struct tegra_pcie *pcie = (struct tegra_pcie *)(s->private); u32 val; bool pass = false; val = afi_readl(pcie, AFI_PCIE_PME); val |= AFI_PCIE_PME_TURN_OFF; afi_writel(pcie, val, AFI_PCIE_PME); do { val = afi_readl(pcie, AFI_PCIE_PME); } while(!(val & AFI_PCIE_PME_ACK)); mdelay(1000); list_for_each_entry(port, &pcie->ports, list) { val = rp_readl(port, NV_PCIE2_RP_LTSSM_DBGREG); if (val & PCIE2_RP_LTSSM_DBGREG_LINKFSM16) { pass = true; goto out; } } out: if (pass) seq_printf(s, "[pass: pcie_power_down]\n"); else seq_printf(s, "[fail: pcie_power_down]\n"); pr_info("PCIE power_down test END..\n"); return 0; } static int loopback(struct seq_file *s, void *data) { struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); unsigned int new, i, val; new = rp_readl(port, RP_LINK_CONTROL_STATUS); if (!(new & RP_LINK_CONTROL_STATUS_DL_LINK_ACTIVE)) { pr_info("PCIE port %d not active\n", port->index); return -EINVAL; } /* trigger trace ram on loopback states */ val = LTSSM_TRACE_CONTROL_CLEAR_STORE_EN | LTSSM_TRACE_CONTROL_TRIG_ON_EVENT | (0x08 << LTSSM_TRACE_CONTROL_TRIG_LTSSM_MAJOR_OFFSET) | (0x00 << LTSSM_TRACE_CONTROL_TRIG_PTX_LTSSM_MINOR_OFFSET) | (0x00 << LTSSM_TRACE_CONTROL_TRIG_PRX_LTSSM_MAJOR_OFFSET); rp_writel(port, val, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); /* clear trace ram */ val = rp_readl(port, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); val |= LTSSM_TRACE_CONTROL_CLEAR_RAM; rp_writel(port, val, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); val &= ~LTSSM_TRACE_CONTROL_CLEAR_RAM; rp_writel(port, val, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); /* reset and clear status */ port->loopback_stat = 0; new = rp_readl(port, RP_VEND_XP); new &= ~RP_VEND_XP_PRBS_EN; rp_writel(port, new, RP_VEND_XP); new = rp_readl(port, NV_PCIE2_RP_XP_CTL_1); new &= ~PCIE2_RP_XP_CTL_1_OLD_IOBIST_EN_BIT25; rp_writel(port, new, NV_PCIE2_RP_XP_CTL_1); rp_writel(port, 0x10000001, NV_PCIE2_RP_VEND_XP_BIST); rp_writel(port, 0, NV_PCIE2_RP_PRBS); mdelay(1); rp_writel(port, 0x90820001, NV_PCIE2_RP_VEND_XP_BIST); new = rp_readl(port, NV_PCIE2_RP_VEND_XP_BIST); new = rp_readl(port, NV_PCIE2_RP_XP_CTL_1); new |= PCIE2_RP_XP_CTL_1_OLD_IOBIST_EN_BIT25; rp_writel(port, new, NV_PCIE2_RP_XP_CTL_1); new = rp_readl(port, RP_VEND_XP); new |= RP_VEND_XP_PRBS_EN; rp_writel(port, new, RP_VEND_XP); mdelay(1000); new = rp_readl(port, RP_VEND_XP); port->loopback_stat = (new & RP_VEND_XP_PRBS_STAT) >> 2; pr_info("--- loopback status ---\n"); for (i = 0; i < port->lanes; ++i) pr_info("@lane %d: %s\n", i, (port->loopback_stat & 0x01 << i) ? "pass" : "fail"); new = rp_readl(port, NV_PCIE2_RP_PRBS); pr_info("--- PRBS pattern locked ---\n"); for (i = 0; i < port->lanes; ++i) pr_info("@lane %d: %s\n", i, (new >> 16 & 0x01 << i) ? "Y" : "N"); pr_info("--- err overflow bits ---\n"); for (i = 0; i < port->lanes; ++i) pr_info("@lane %d: %s\n", i, ((new & 0xffff) & 0x01 << i) ? "Y" : "N"); new = rp_readl(port, NV_PCIE2_RP_XP_CTL_1); new &= ~PCIE2_RP_XP_CTL_1_OLD_IOBIST_EN_BIT25; rp_writel(port, new, NV_PCIE2_RP_XP_CTL_1); pr_info("--- err counts ---\n"); for (i = 0; i < port->lanes; ++i) { rp_writel(port, i, NV_PCIE2_RP_LANE_PRBS_ERR_COUNT); new = rp_readl(port, NV_PCIE2_RP_LANE_PRBS_ERR_COUNT); pr_info("@lane %d: %u\n", i, new >> 16); } rp_writel(port, 0x90000001, NV_PCIE2_RP_VEND_XP_BIST); new = rp_readl(port, RP_VEND_XP); new &= ~RP_VEND_XP_PRBS_EN; rp_writel(port, new, RP_VEND_XP); mdelay(1); rp_writel(port, 0x92000001, NV_PCIE2_RP_VEND_XP_BIST); rp_writel(port, 0x90000001, NV_PCIE2_RP_VEND_XP_BIST); pr_info("pcie loopback test is done\n"); return 0; } static int apply_lane_width(struct seq_file *s, void *data) { unsigned int new; struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); if (port->lanes > 0x10) { seq_printf(s, "link width cannot be grater than 16\n"); new = rp_readl(port, RP_LINK_CONTROL_STATUS); port->lanes = (new & RP_LINK_CONTROL_STATUS_NEG_LINK_WIDTH) >> 20; return 0; } new = rp_readl(port, NV_PCIE2_RP_VEND_XP1); new &= ~NV_PCIE2_RP_VEND_XP1_RNCTRL_MAXWIDTH_MASK; new |= port->lanes | NV_PCIE2_RP_VEND_XP1_RNCTRL_EN; rp_writel(port, new, NV_PCIE2_RP_VEND_XP1); mdelay(1); new = rp_readl(port, RP_LINK_CONTROL_STATUS); new = (new & RP_LINK_CONTROL_STATUS_NEG_LINK_WIDTH) >> 20; if (new != port->lanes) seq_printf(s, "can't set link width %u, falling back to %u\n", port->lanes, new); else seq_printf(s, "lane width %d applied\n", new); port->lanes = new; return 0; } static int aspm_state_cnt(struct seq_file *s, void *data) { u32 val, cs; struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); cs = rp_readl(port, RP_LINK_CONTROL_STATUS); /* check if L0s is enabled on this port */ if (cs & RP_LINK_CONTROL_STATUS_L0s_ENABLED) { val = rp_readl(port, NV_PCIE2_RP_PRIV_XP_TX_L0S_ENTRY_COUNT); seq_printf(s, "Tx L0s entry count : %u\n", val); } else seq_printf(s, "Tx L0s entry count : %s\n", "disabled"); val = rp_readl(port, NV_PCIE2_RP_PRIV_XP_RX_L0S_ENTRY_COUNT); seq_printf(s, "Rx L0s entry count : %u\n", val); /* check if L1 is enabled on this port */ if (cs & RP_LINK_CONTROL_STATUS_L1_ENABLED) { val = rp_readl(port, NV_PCIE2_RP_PRIV_XP_TX_L1_ENTRY_COUNT); seq_printf(s, "Link L1 entry count : %u\n", val); } else seq_printf(s, "Link L1 entry count : %s\n", "disabled"); cs = rp_readl(port, PCIE2_RP_L1_PM_SS_CONTROL); /* RESETting the count value is not possible by any means because of HW Bug : 200034278 */ /* check if L1.1 is enabled */ if (cs & PCIE2_RP_L1_PM_SS_CONTROL_ASPM_L11_ENABLE) { val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); val |= PCIE2_RP_L1_1_ENTRY_COUNT_RESET; rp_writel(port, val, NV_PCIE2_RP_L1_1_ENTRY_COUNT); seq_printf(s, "Link L1.1 entry count : %u\n", (val & 0xFFFF)); } else seq_printf(s, "Link L1.1 entry count : %s\n", "disabled"); /* check if L1.2 is enabled */ if (cs & PCIE2_RP_L1_PM_SS_CONTROL_ASPM_L12_ENABLE) { val = rp_readl(port, NV_PCIE2_RP_L1_2_ENTRY_COUNT); val |= PCIE2_RP_L1_2_ENTRY_COUNT_RESET; rp_writel(port, val, NV_PCIE2_RP_L1_2_ENTRY_COUNT); seq_printf(s, "Link L1.2 entry count : %u\n", (val & 0xFFFF)); } else seq_printf(s, "Link L1.2 entry count : %s\n", "disabled"); return 0; } static char *aspm_states[] = { "Tx-L0s", "Rx-L0s", "L1", "IDLE ((Tx-L0s && Rx-L0s) + L1)" }; static int list_aspm_states(struct seq_file *s, void *data) { u32 i = 0; seq_printf(s, "----------------------------------------------------\n"); seq_printf(s, "Note: Duration of link's residency is calcualated\n"); seq_printf(s, " only for one of the ASPM states at a time\n"); seq_printf(s, "----------------------------------------------------\n"); seq_printf(s, "write(echo) number from below table corresponding to\n"); seq_printf(s, "one of the ASPM states for which link duration needs\n"); seq_printf(s, "to be calculated to 'config_aspm_state'\n"); seq_printf(s, "-----------------\n"); for (i = 0; i < ARRAY_SIZE(aspm_states); i++) seq_printf(s, "%d : %s\n", i, aspm_states[i]); seq_printf(s, "-----------------\n"); return 0; } static int apply_aspm_state(struct seq_file *s, void *data) { u32 val; struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); if (config_aspm_state >= ARRAY_SIZE(aspm_states)) { seq_printf(s, "Invalid ASPM state : %u\n", config_aspm_state); list_aspm_states(s, data); } else { val = rp_readl(port, NV_PCIE2_RP_PRIV_XP_CONFIG); val &= ~NV_PCIE2_RP_PRIV_XP_CONFIG_LOW_PWR_DURATION_MASK; val |= config_aspm_state; rp_writel(port, val, NV_PCIE2_RP_PRIV_XP_CONFIG); seq_printf(s, "Configured for ASPM-%s state...\n", aspm_states[config_aspm_state]); } return 0; } static int get_aspm_duration(struct seq_file *s, void *data) { u32 val; struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); val = rp_readl(port, NV_PCIE2_RP_PRIV_XP_DURATION_IN_LOW_PWR_100NS); /* 52.08 = 1000 / 19.2MHz is rounded to 52 */ seq_printf(s, "ASPM-%s duration = %d ns\n", aspm_states[config_aspm_state], (u32)((val * 100)/52)); return 0; } static int secondary_bus_reset(struct seq_file *s, void *data) { u32 val; struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); val = rp_readl(port, NV_PCIE2_RP_INTR_BCR); val |= NV_PCIE2_RP_INTR_BCR_SB_RESET; rp_writel(port, val, NV_PCIE2_RP_INTR_BCR); udelay(10); val = rp_readl(port, NV_PCIE2_RP_INTR_BCR); val &= ~NV_PCIE2_RP_INTR_BCR_SB_RESET; rp_writel(port, val, NV_PCIE2_RP_INTR_BCR); seq_printf(s, "Secondary Bus Reset applied successfully...\n"); return 0; } static void reset_l1ss_counter(struct tegra_pcie_port *port, u32 val, unsigned long offset) { int c = 0; if ((val & 0xFFFF) == 0xFFFF) { pr_info(" Trying reset L1ss entry count to 0\n"); while (val) { if (c++ > 50) { pr_info("Timeout: reset did not happen!\n"); break; } val |= PCIE2_RP_L1_1_ENTRY_COUNT_RESET; rp_writel(port, val, offset); mdelay(1); val = rp_readl(port, offset); } if (!val) pr_info("L1ss entry count reset to 0\n"); } } static int aspm_l11(struct seq_file *s, void *data) { struct pci_dev *pdev = NULL; u32 val = 0, pos = 0; struct tegra_pcie_port *port = NULL; struct tegra_pcie *pcie = (struct tegra_pcie *)(s->private); pr_info("\nPCIE aspm l1.1 test START..\n"); list_for_each_entry(port, &pcie->ports, list) { /* reset RP L1.1 counter */ val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); val |= PCIE2_RP_L1_1_ENTRY_COUNT_RESET; rp_writel(port, val, NV_PCIE2_RP_L1_1_ENTRY_COUNT); val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); pr_info("L1.1 Entry count before %x\n", val); reset_l1ss_counter(port, val, NV_PCIE2_RP_L1_1_ENTRY_COUNT); } /* disable automatic l1ss exit by gpu */ for_each_pci_dev(pdev) if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) { pci_write_config_dword(pdev, 0x658, 0); pci_write_config_dword(pdev, 0x150, 0xE0000015); } for_each_pci_dev(pdev) { u16 aspm; pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &aspm); aspm |= PCI_EXP_LNKCTL_ASPM_L1; pcie_capability_write_word(pdev, PCI_EXP_LNKCTL, aspm); pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_L1SS); pci_read_config_dword(pdev, pos + PCI_L1SS_CTRL1, &val); val &= ~PCI_L1SS_CAP_L1PM_MASK; val |= PCI_L1SS_CTRL1_ASPM_L11S; pci_write_config_dword(pdev, pos + PCI_L1SS_CTRL1, val); if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) break; } mdelay(2000); for_each_pci_dev(pdev) { pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_L1SS); pci_read_config_dword(pdev, pos + PCI_L1SS_CTRL1, &val); if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) break; } list_for_each_entry(port, &pcie->ports, list) { val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); pr_info("L1.1 Entry count after %x\n", val); } pr_info("PCIE aspm l1.1 test END..\n"); return 0; } static int aspm_l1ss(struct seq_file *s, void *data) { struct pci_dev *pdev = NULL; u32 val = 0, pos = 0; struct tegra_pcie_port *port = NULL; struct tegra_pcie *pcie = (struct tegra_pcie *)(s->private); pr_info("\nPCIE aspm l1ss test START..\n"); list_for_each_entry(port, &pcie->ports, list) { /* reset RP L1.1 L1.2 counters */ val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); val |= PCIE2_RP_L1_1_ENTRY_COUNT_RESET; rp_writel(port, val, NV_PCIE2_RP_L1_1_ENTRY_COUNT); val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); pr_info("L1.1 Entry count before %x\n", val); reset_l1ss_counter(port, val, NV_PCIE2_RP_L1_1_ENTRY_COUNT); val = rp_readl(port, NV_PCIE2_RP_L1_2_ENTRY_COUNT); val |= PCIE2_RP_L1_2_ENTRY_COUNT_RESET; rp_writel(port, val, NV_PCIE2_RP_L1_2_ENTRY_COUNT); val = rp_readl(port, NV_PCIE2_RP_L1_2_ENTRY_COUNT); pr_info("L1.2 Entry count before %x\n", val); reset_l1ss_counter(port, val, NV_PCIE2_RP_L1_2_ENTRY_COUNT); } /* disable automatic l1ss exit by gpu */ for_each_pci_dev(pdev) if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) { pci_write_config_dword(pdev, 0x658, 0); pci_write_config_dword(pdev, 0x150, 0xE0000015); } for_each_pci_dev(pdev) { u16 aspm; pcie_capability_read_word(pdev, PCI_EXP_LNKCTL, &aspm); aspm |= PCI_EXP_LNKCTL_ASPM_L1; pcie_capability_write_word(pdev, PCI_EXP_LNKCTL, aspm); pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_L1SS); pci_read_config_dword(pdev, pos + PCI_L1SS_CTRL1, &val); val &= ~PCI_L1SS_CAP_L1PM_MASK; val |= (PCI_L1SS_CTRL1_ASPM_L11S | PCI_L1SS_CTRL1_ASPM_L12S); pci_write_config_dword(pdev, pos + PCI_L1SS_CTRL1, val); if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) break; } mdelay(2000); for_each_pci_dev(pdev) { pos = pci_find_ext_capability(pdev, PCI_EXT_CAP_ID_L1SS); pci_read_config_dword(pdev, pos + PCI_L1SS_CTRL1, &val); if (pci_pcie_type(pdev) != PCI_EXP_TYPE_ROOT_PORT) break; } list_for_each_entry(port, &pcie->ports, list) { u32 ltr_val; val = rp_readl(port, NV_PCIE2_RP_L1_1_ENTRY_COUNT); pr_info("L1.1 Entry count after %x\n", val); val = rp_readl(port, NV_PCIE2_RP_L1_2_ENTRY_COUNT); pr_info("L1.2 Entry count after %x\n", val); val = rp_readl(port, NV_PCIE2_RP_LTR_REP_VAL); pr_info("LTR reproted by EP %x\n", val); ltr_val = (val & 0x1FF) * (1 << (5 * ((val & 0x1C00) >> 10))); if (ltr_val > (106 * 1000)) { pr_info("EP's LTR = %u ns is > RP's threshold = %u ns\n", ltr_val, 106 * 1000); pr_info("Hence only L1.2 entry allowed\n"); } else { pr_info("EP's LTR = %u ns is < RP's threshold = %u ns\n", ltr_val, 106 * 1000); pr_info("Hence only L1.1 entry allowed\n"); } } pr_info("PCIE aspm l1ss test END..\n"); return 0; } struct ltssm_major_state { const char *name; const char *minor[8]; }; struct ltssm_state { struct ltssm_major_state major[12]; }; static struct ltssm_state ltssm_state = { .major[0] = {"detect", {"quiet", "active", "retry", "wait", "entry"}}, .major[1] = {"polling", {"active", "config", "idle", NULL, "compliance", "cspeed"}}, .major[2] = {"config", {"link start", "link accept", "lane accept", "lane wait", "idle", "pwrup", "complete"}}, .major[3] = {NULL, {NULL}}, .major[4] = {"l0", {"normal", "l0s entry", "l0s idle", "l0s wait", "l0s fts", "pwrup"}}, .major[5] = {"l1", {"entry", "waitrx", "idle", "wait", "pwrup", "beacon entry", "beacon exit"}}, .major[6] = {"l2", {"entry", "waitrx", "transmitwake", "idle"}}, .major[7] = {"recovery", {"rcvrlock", "rcvrcfg", "speed", "idle", NULL, NULL, NULL, "finish pkt"}}, .major[8] = {"loopback", {"entry", "active", "idle", "exit", "speed", "pre speed"}}, .major[9] = {"hotreset", {NULL}}, .major[10] = {"disabled", {NULL}}, .major[11] = {"txchar", {NULL}}, }; static const char *ltssm_get_major(unsigned int major) { const char *state; state = ltssm_state.major[major].name; if (!state) return "unknown"; return state; } static const char *ltssm_get_minor(unsigned int major, unsigned int minor) { const char *state; state = ltssm_state.major[major].minor[minor]; if (!state) return "unknown"; return state; } static int dump_ltssm_trace(struct seq_file *s, void *data) { struct tegra_pcie_port *port = (struct tegra_pcie_port *)(s->private); unsigned int val, ridx, widx, entries; seq_printf(s, "LTSSM trace dump:\n"); val = rp_readl(port, NV_PCIE2_RP_LTSSM_TRACE_STATUS); widx = LTSSM_TRACE_STATUS_WRITE_POINTER(val); entries = LTSSM_TRACE_STATUS_RAM_FULL(val) ? 32 : widx; seq_printf(s, "LTSSM trace dump - %d entries:\n", entries); for (ridx = 0; ridx < entries; ridx++) { val = LTSSM_TRACE_STATUS_READ_ADDR(ridx); rp_writel(port, val, NV_PCIE2_RP_LTSSM_TRACE_STATUS); val = rp_readl(port, NV_PCIE2_RP_LTSSM_TRACE_STATUS); seq_printf(s, " [0x%08x] major: %-10s minor_tx: %-15s minor_rx: %s\n", val, ltssm_get_major(LTSSM_TRACE_STATUS_MAJOR(val)), ltssm_get_minor(LTSSM_TRACE_STATUS_MAJOR(val), LTSSM_TRACE_STATUS_PTX_MINOR(val)), ltssm_get_minor(LTSSM_TRACE_STATUS_MAJOR(val), LTSSM_TRACE_STATUS_PRX_MINOR(val))); } /* clear trace ram */ val = rp_readl(port, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); val |= LTSSM_TRACE_CONTROL_CLEAR_RAM; rp_writel(port, val, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); val &= ~LTSSM_TRACE_CONTROL_CLEAR_RAM; rp_writel(port, val, NV_PCIE2_RP_LTSSM_TRACE_CONTROL); return 0; } static struct dentry *create_tegra_pcie_debufs_file(char *name, const struct file_operations *ops, struct dentry *parent, void *data) { struct dentry *d; d = debugfs_create_file(name, S_IRUGO, parent, data, ops); if (!d) debugfs_remove_recursive(parent); return d; } #define DEFINE_ENTRY(__name) \ static int __name ## _open(struct inode *inode, struct file *file) \ { \ return single_open(file, __name, inode->i_private); \ } \ static const struct file_operations __name ## _fops = { \ .open = __name ## _open, \ .read = seq_read, \ .llseek = seq_lseek, \ .release = single_release, \ }; /* common */ DEFINE_ENTRY(list_devices) DEFINE_ENTRY(apply_link_speed) DEFINE_ENTRY(check_d3hot) DEFINE_ENTRY(dump_config_space) DEFINE_ENTRY(dump_afi_space) DEFINE_ENTRY(config_read) DEFINE_ENTRY(config_write) DEFINE_ENTRY(aspm_l11) DEFINE_ENTRY(aspm_l1ss) DEFINE_ENTRY(power_down) /* Port specific */ DEFINE_ENTRY(loopback) DEFINE_ENTRY(apply_lane_width) DEFINE_ENTRY(aspm_state_cnt) DEFINE_ENTRY(list_aspm_states) DEFINE_ENTRY(apply_aspm_state) DEFINE_ENTRY(get_aspm_duration) DEFINE_ENTRY(secondary_bus_reset) DEFINE_ENTRY(dump_ltssm_trace) static int tegra_pcie_port_debugfs_init(struct tegra_pcie_port *port) { struct dentry *d; char port_name[2] = {0}; snprintf(port_name, sizeof(port_name), "%d", port->index); port->port_debugfs = debugfs_create_dir(port_name, port->pcie->debugfs); if (!port->port_debugfs) return -ENOMEM; d = debugfs_create_u32("lane_width", S_IWUGO | S_IRUGO, port->port_debugfs, &(port->lanes)); if (!d) goto remove; d = debugfs_create_x32("loopback_status", S_IWUGO | S_IRUGO, port->port_debugfs, &(port->loopback_stat)); if (!d) goto remove; d = debugfs_create_file("loopback", S_IRUGO, port->port_debugfs, (void *)port, &loopback_fops); if (!d) goto remove; d = debugfs_create_file("apply_lane_width", S_IRUGO, port->port_debugfs, (void *)port, &apply_lane_width_fops); if (!d) goto remove; d = debugfs_create_file("aspm_state_cnt", S_IRUGO, port->port_debugfs, (void *)port, &aspm_state_cnt_fops); if (!d) goto remove; d = debugfs_create_u16("config_aspm_state", S_IWUGO | S_IRUGO, port->port_debugfs, &config_aspm_state); if (!d) goto remove; d = debugfs_create_file("apply_aspm_state", S_IRUGO, port->port_debugfs, (void *)port, &apply_aspm_state_fops); if (!d) goto remove; d = debugfs_create_file("list_aspm_states", S_IRUGO, port->port_debugfs, (void *)port, &list_aspm_states_fops); if (!d) goto remove; d = debugfs_create_file("dump_ltssm_trace", S_IRUGO, port->port_debugfs, (void *)port, &dump_ltssm_trace_fops); if (!d) goto remove; d = debugfs_create_file("get_aspm_duration", S_IRUGO, port->port_debugfs, (void *)port, &get_aspm_duration_fops); if (!d) goto remove; d = debugfs_create_file("secondary_bus_reset", S_IRUGO, port->port_debugfs, (void *)port, &secondary_bus_reset_fops); if (!d) goto remove; return 0; remove: debugfs_remove_recursive(port->port_debugfs); port->port_debugfs = NULL; return -ENOMEM; } static void *tegra_pcie_ports_seq_start(struct seq_file *s, loff_t *pos) { struct tegra_pcie *pcie = s->private; if (list_empty(&pcie->ports)) return NULL; seq_printf(s, "Index Status\n"); return seq_list_start(&pcie->ports, *pos); } static void *tegra_pcie_ports_seq_next(struct seq_file *s, void *v, loff_t *pos) { struct tegra_pcie *pcie = s->private; return seq_list_next(v, &pcie->ports, pos); } static void tegra_pcie_ports_seq_stop(struct seq_file *s, void *v) { } static int tegra_pcie_ports_seq_show(struct seq_file *s, void *v) { bool up = false, active = false; struct tegra_pcie_port *port; unsigned int value; port = list_entry(v, struct tegra_pcie_port, list); if (!port->status) return 0; value = readl(port->base + RP_VEND_XP); if (value & RP_VEND_XP_DL_UP) up = true; value = readl(port->base + RP_LINK_CONTROL_STATUS); if (value & RP_LINK_CONTROL_STATUS_DL_LINK_ACTIVE) active = true; seq_printf(s, "%2u ", port->index); if (up) seq_printf(s, "up"); if (active) { if (up) seq_printf(s, ", "); seq_printf(s, "active"); } seq_printf(s, "\n"); return 0; } static const struct seq_operations tegra_pcie_ports_seq_ops = { .start = tegra_pcie_ports_seq_start, .next = tegra_pcie_ports_seq_next, .stop = tegra_pcie_ports_seq_stop, .show = tegra_pcie_ports_seq_show, }; static int tegra_pcie_ports_open(struct inode *inode, struct file *file) { struct tegra_pcie *pcie = inode->i_private; struct seq_file *s; int err; err = seq_open(file, &tegra_pcie_ports_seq_ops); if (err) return err; s = file->private_data; s->private = pcie; return 0; } static const struct file_operations tegra_pcie_ports_ops = { .owner = THIS_MODULE, .open = tegra_pcie_ports_open, .read = seq_read, .llseek = seq_lseek, .release = seq_release, }; static void tegra_pcie_debugfs_exit(struct tegra_pcie *pcie) { if (pcie->debugfs) debugfs_remove_recursive(pcie->debugfs); } static int tegra_pcie_debugfs_init(struct tegra_pcie *pcie) { struct dentry *file, *d; struct tegra_pcie_port *port; pcie->debugfs = debugfs_create_dir("pcie", NULL); if (!pcie->debugfs) return -ENOMEM; file = debugfs_create_file("ports", S_IFREG | S_IRUGO, pcie->debugfs, pcie, &tegra_pcie_ports_ops); if (!file) goto remove; d = create_tegra_pcie_debufs_file("list_devices", &list_devices_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("apply_link_speed", &apply_link_speed_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("check_d3hot", &check_d3hot_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("power_down", &power_down_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("dump_config_space", &dump_config_space_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("dump_afi_space", &dump_afi_space_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = debugfs_create_u16("bus_dev_func", S_IWUGO | S_IRUGO, pcie->debugfs, &bdf); if (!d) goto remove; d = debugfs_create_u16("config_offset", S_IWUGO | S_IRUGO, pcie->debugfs, &config_offset); if (!d) goto remove; d = debugfs_create_u32("config_val", S_IWUGO | S_IRUGO, pcie->debugfs, &config_val); if (!d) goto remove; d = create_tegra_pcie_debufs_file("config_read", &config_read_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("config_write", &config_write_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("aspm_l11", &aspm_l11_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; d = create_tegra_pcie_debufs_file("aspm_l1ss", &aspm_l1ss_fops, pcie->debugfs, (void *)pcie); if (!d) goto remove; list_for_each_entry(port, &pcie->ports, list) { if (port->status) if (tegra_pcie_port_debugfs_init(port)) goto remove; } return 0; remove: tegra_pcie_debugfs_exit(pcie); pcie->debugfs = NULL; return -ENOMEM; } static int tegra_pcie_probe_complete(struct tegra_pcie *pcie) { int ret = 0; struct platform_device *pdev = to_platform_device(pcie->dev); PR_FUNC_LINE; ret = tegra_pcie_init(pcie); if (ret) return ret; if (IS_ENABLED(CONFIG_DEBUG_FS)) if (pcie->num_ports) { ret = tegra_pcie_debugfs_init(pcie); if (ret < 0) dev_err(&pdev->dev, "failed to setup debugfs: %d\n", ret); } return 0; } static void pcie_delayed_detect(struct work_struct *work) { struct tegra_pcie *pcie; struct platform_device *pdev; int ret = 0; pcie = container_of(work, struct tegra_pcie, detect_delay.work); pdev = to_platform_device(pcie->dev); #ifdef CONFIG_THERMAL if (pcie->is_cooling_dev) { dev_info(pcie->dev, "Going to wait till end point temp is above 0-C\n"); wait_for_completion_interruptible(&pcie->completion); dev_info(pcie->dev, "proceeding with PCIe hierarchy enumeraton\n"); } #endif ret = tegra_pcie_probe_complete(pcie); if (ret || !pcie->num_ports) { pm_runtime_put_sync(pcie->dev); goto release_regulators; } return; release_regulators: devm_kfree(pcie->dev, pcie->pcie_regulators); devm_kfree(pcie->dev, pcie->plat_data); pci_free_host_bridge(pcie->host); platform_set_drvdata(pdev, NULL); return; } #ifdef CONFIG_THERMAL #define TEGRA_PCIE_THERM_MAX_STATE 2 static int tegra_pcie_max_state(struct thermal_cooling_device *tcd, unsigned long *state) { struct tegra_pcie *pcie = tcd->devdata; dev_info(pcie->dev, "%s state=%d\n", __func__, pcie->therm_state.counter); *state = TEGRA_PCIE_THERM_MAX_STATE; return 0; } static int tegra_pcie_cur_state(struct thermal_cooling_device *tcd, unsigned long *state) { struct tegra_pcie *pcie = tcd->devdata; dev_info(pcie->dev, "%s state=%d\n", __func__, pcie->therm_state.counter); *state = (unsigned long)atomic_read(&pcie->therm_state); return 0; } static int tegra_pcie_set_state(struct thermal_cooling_device *tcd, unsigned long state) { struct tegra_pcie *pcie = tcd->devdata; if (state != (TEGRA_PCIE_THERM_MAX_STATE - 1)) { if ((unsigned long)atomic_read(&pcie->therm_state)) dev_err(pcie->dev, "dGPU temp is below zero...!\n"); else return 0; } else { atomic_set(&pcie->therm_state, state); complete(&pcie->completion); } return 0; } /* Cooling device support */ static struct thermal_cooling_device_ops pcie_cdev_ops = { .get_max_state = tegra_pcie_max_state, .get_cur_state = tegra_pcie_cur_state, .set_cur_state = tegra_pcie_set_state, }; static int pcie_therm_init(struct tegra_pcie *pcie) { pcie->cdev = thermal_cooling_device_register("tegra-pcie", pcie, &pcie_cdev_ops); if (IS_ERR(pcie->cdev)) return PTR_ERR(pcie->cdev); if (pcie->cdev == NULL) return -ENODEV; dev_info(pcie->dev, "PCIE cooling dev registered\n"); return 0; } #endif static int tegra_pcie_probe(struct platform_device *pdev) { int ret = 0; int i; const struct of_device_id *match; struct tegra_pcie *pcie; struct tegra_pcie_port *port, *tmp; struct pci_host_bridge *host; PR_FUNC_LINE; host = pci_alloc_host_bridge(sizeof(*pcie)); if (!host) return -ENOMEM; pcie = pci_host_bridge_priv(host); platform_set_drvdata(pdev, pcie); pcie->dev = &pdev->dev; pcie->host = host; /* use DT way to init platform data */ pcie->plat_data = devm_kzalloc(pcie->dev, sizeof(*(pcie->plat_data)), GFP_KERNEL); if (!(pcie->plat_data)) { dev_err(pcie->dev, "memory alloc failed\n"); ret = -ENOMEM; goto release_drvdata; } tegra_pcie_read_plat_data(pcie); match = of_match_device(tegra_pcie_of_match, &pdev->dev); if (!match) { ret = -ENODEV; goto release_platdata; } pcie->soc_data = (struct tegra_pcie_soc_data *)match->data; if (pcie->soc_data->config_pex_io_dpd) { pcie->pex_pin = devm_pinctrl_get(pcie->dev); if (IS_ERR(pcie->pex_pin)) { ret = PTR_ERR(pcie->pex_pin); dev_err(pcie->dev, "pex io-dpd config failed: %d\n", ret); return ret; } pcie->pex_io_dpd_en_state = pinctrl_lookup_state(pcie->pex_pin, "pex-io-dpd-en"); if (IS_ERR(pcie->pex_io_dpd_en_state)) { ret = PTR_ERR(pcie->pex_io_dpd_en_state); dev_err(pcie->dev, "missing pex-io-dpd en state: %d\n", ret); return ret; } pcie->pex_io_dpd_dis_state = pinctrl_lookup_state(pcie->pex_pin, "pex-io-dpd-dis"); if (IS_ERR(pcie->pex_io_dpd_dis_state)) { ret = PTR_ERR(pcie->pex_io_dpd_dis_state); dev_err(pcie->dev, "missing pex-io-dpd dis state:%ld\n", PTR_ERR(pcie->pex_io_dpd_dis_state)); return ret; } } pcie->pcie_regulators = devm_kzalloc(pcie->dev, pcie->soc_data->num_pcie_regulators * sizeof(struct regulator *), GFP_KERNEL); for (i = 0; i < pcie->soc_data->num_pcie_regulators; i++) { pcie->pcie_regulators[i] = devm_regulator_get(pcie->dev, pcie->soc_data->pcie_regulator_names[i]); if (IS_ERR(pcie->pcie_regulators[i])) { dev_err(pcie->dev, "%s: unable to get regulator %s\n", __func__, pcie->soc_data->pcie_regulator_names[i]); pcie->pcie_regulators[i] = NULL; ret = IS_ERR(pcie->pcie_regulators[i]); goto release_regulators; } } INIT_LIST_HEAD(&pcie->buses); INIT_LIST_HEAD(&pcie->ports); INIT_LIST_HEAD(&pcie->sys); INIT_DELAYED_WORK(&pcie->detect_delay, pcie_delayed_detect); ret = tegra_pcie_parse_dt(pcie); if (ret < 0) goto release_regulators; if (pcie->soc_data->program_uphy) { ret = tegra_pcie_phys_get(pcie); if (ret < 0) { if (ret == -EPROBE_DEFER) dev_info(pcie->dev, "failed to get PHYs: %d\n", ret); else dev_err(pcie->dev, "failed to get PHYs: %d\n", ret); goto release_regulators; } } pcie->prod_list = devm_tegra_prod_get(pcie->dev); if (IS_ERR(pcie->prod_list)) { dev_info(pcie->dev, "No prod values found\n"); pcie->prod_list = NULL; } list_for_each_entry_safe(port, tmp, &pcie->ports, list) { if (port->has_mxm_port) { if (tegra_pcie_mxm_pwr_init(port)) dev_info(pcie->dev, "pwr_good is down for port %d, ignoring\n", port->index); } if (pcie->soc_data->program_clkreq_as_bi_dir) { /* set clkreq as input to avoid root port control it */ tegra_pcie_config_clkreq(pcie, port->index, 0); } } /* Enable Runtime PM for PCIe, TODO: Need to add PCIe host device */ pm_runtime_enable(pcie->dev); #ifdef CONFIG_THERMAL if (pcie->is_cooling_dev) { init_completion(&pcie->completion); /* register cooling device */ ret = pcie_therm_init(pcie); if (ret != 0) { dev_err(pcie->dev, "unable to register cooling device err: %d\n", ret); goto release_regulators; } } #endif schedule_delayed_work(&pcie->detect_delay, msecs_to_jiffies( pcie->plat_data->boot_detect_delay)); return ret; release_regulators: if (pcie->soc_data->program_uphy) tegra_pcie_phy_exit(pcie); devm_kfree(&pdev->dev, pcie->pcie_regulators); release_platdata: devm_kfree(&pdev->dev, pcie->plat_data); release_drvdata: pci_free_host_bridge(host); platform_set_drvdata(pdev, NULL); return ret; } static int tegra_pcie_remove(struct platform_device *pdev) { struct tegra_pcie *pcie = platform_get_drvdata(pdev); PR_FUNC_LINE; if (!pcie) return 0; if (cancel_delayed_work_sync(&pcie->detect_delay)) return 0; if (IS_ENABLED(CONFIG_DEBUG_FS)) tegra_pcie_debugfs_exit(pcie); pci_stop_root_bus(pcie->host->bus); pci_bus_remove_resources(pcie->host->bus); pci_remove_root_bus(pcie->host->bus); iounmap(pcie->cfg_va_base); if (IS_ENABLED(CONFIG_PCI_MSI)) tegra_pcie_disable_msi(pcie); tegra_pcie_detach(pcie); tegra_pcie_power_off(pcie); if (pcie->soc_data->program_uphy) tegra_pcie_phy_exit(pcie); tegra_pcie_release_resources(pcie); pm_runtime_disable(pcie->dev); tegra_pcie_free_resources(pcie); pci_free_host_bridge(pcie->host); return 0; } static inline u32 get_pme_port_offset(struct tegra_pcie_port *port) { u32 ret = 0; switch (port->index) { case 0: ret = 0; break; case 1: ret = 8; break; case 2: ret = 12; break; } return ret; } static inline u32 get_pme_ack_offset(struct tegra_pcie_port *port) { u32 ret = 0; switch (port->index) { case 0: ret = 5; break; case 1: ret = 10; break; case 2: ret = 14; break; } return ret; } int tegra_pcie_pm_control(enum tegra_pcie_pm_opt pm_opt, void *user) { struct pci_dev *epdev = (struct pci_dev *)user; struct pci_dev *rpdev = epdev->bus->self; struct pci_host_bridge *host = pci_find_host_bridge(epdev->bus); struct tegra_pcie *pcie = pci_host_bridge_priv(host); struct tegra_pcie_port *port = NULL; unsigned long ctrl = 0; u32 rp; u32 val; u32 timeout = 100; /* 10 ms */ u16 val_16 = 0; rp = PCI_SLOT(rpdev->devfn); list_for_each_entry(port, &pcie->ports, list) if (rp == port->index + 1) break; switch (pm_opt) { case TEGRA_PCIE_SUSPEND: pr_debug("---> in suspend\n"); port->ep_status = 0; /* now setting it to '1' */ val = afi_readl(pcie, AFI_PCIE_PME); val |= (0x1 << get_pme_port_offset(port)); afi_writel(pcie, val, AFI_PCIE_PME); /* wait till ack is received */ do { udelay(1); val = afi_readl(pcie, AFI_PCIE_PME); val = val & (0x1 << get_pme_ack_offset(port)); } while (!(val)); usleep_range(10000, 11000); /* 10ms delay */ /* clear PME_TO */ val = afi_readl(pcie, AFI_PCIE_PME); val &= ~(0x1 << get_pme_port_offset(port)); afi_writel(pcie, val, AFI_PCIE_PME); /* by this time, link would have gone into L2/L3 ready */ /* assert reset to EP */ pr_debug("---> asserting EP reset through AFI\n"); ctrl = tegra_pcie_port_get_pex_ctrl(port); val = afi_readl(port->pcie, ctrl); val &= ~AFI_PEX_CTRL_RST; afi_writel(port->pcie, val, ctrl); val = afi_readl(port->pcie, ctrl); val &= ~AFI_PEX_CTRL_REFCLK_EN; afi_writel(port->pcie, val, ctrl); msleep(20); break; case TEGRA_PCIE_RESUME_PRE: pr_debug("---> in resume (pre)\n"); port->ep_status = 1; /* assert SBR on RP */ pr_debug("---> perform assert,de-assert of SBR\n"); pci_read_config_word(rpdev, PCI_BRIDGE_CONTROL, &val_16); val_16 |= PCI_BRIDGE_CTL_BUS_RESET; pci_write_config_word(rpdev, PCI_BRIDGE_CONTROL, val_16); msleep(20); val_16 &= ~PCI_BRIDGE_CTL_BUS_RESET; pci_write_config_word(rpdev, PCI_BRIDGE_CONTROL, val_16); msleep(100); break; case TEGRA_PCIE_RESUME_POST: pr_debug("---> in resume (post)\n"); /* de-assert reset to EP */ pr_debug("---> de-asserting EP reset through AFI\n"); ctrl = tegra_pcie_port_get_pex_ctrl(port); val = afi_readl(port->pcie, ctrl); val |= AFI_PEX_CTRL_RST; afi_writel(port->pcie, val, ctrl); val = afi_readl(port->pcie, ctrl); val |= AFI_PEX_CTRL_REFCLK_EN; afi_writel(port->pcie, val, ctrl); msleep(100); /* make sure that link is up before doing anything */ do { val = readl(port->base + RP_VEND_XP); pr_debug("---> checking for link up\n"); if (val & RP_VEND_XP_DL_UP) break; usleep_range(100, 200); } while (--timeout); if (!timeout) { dev_err(port->pcie->dev, "link %u is down\n", port->index); return -1; } /* try to read one config space register as this would * result in completion timeout, hence we wouldn't be losing * anything later on from second access onwards */ /* EP device state */ pr_debug("---> First config read START\n"); pci_read_config_word(epdev, PCI_DEVICE_ID, &val_16); pr_debug("EP device ID = 0x%04X\n", val_16); pr_debug("---> First config read END\n"); msleep(100); break; } return 0; } EXPORT_SYMBOL(tegra_pcie_pm_control); #ifdef CONFIG_PM static int tegra_pcie_enable_msi(struct tegra_pcie *, bool); static int tegra_pcie_resume(struct device *dev) { struct tegra_pcie *pcie = dev_get_drvdata(dev); PR_FUNC_LINE; if (!pcie) return 0; tegra_pcie_enable_features(pcie); return 0; } /* Since BCM4359 WiFi driver is not informing the system about its absence * when Wifi is turned off, PCIe subsystem tries to do save/restore as part * of its routine during SC7 cycle will lead to error interrupt generation * which prevents system entering into SC7 state. Hence, it is better to * disable interrupts in suspend_late as there are no interrupts after this * stage anyway and re-enable in resume_early */ static int tegra_pcie_suspend_late(struct device *dev) { struct tegra_pcie *pcie = dev_get_drvdata(dev); u32 val = 0; PR_FUNC_LINE; if (!pcie) return 0; val = afi_readl(pcie, AFI_INTR_MASK); val &= ~AFI_INTR_MASK_INT_MASK; val &= ~AFI_INTR_MASK_MSI_MASK; afi_writel(pcie, val, AFI_INTR_MASK); return 0; } static int tegra_pcie_resume_early(struct device *dev) { struct tegra_pcie *pcie = dev_get_drvdata(dev); u32 val = 0; PR_FUNC_LINE; if (!pcie) return 0; val = afi_readl(pcie, AFI_INTR_MASK); val |= AFI_INTR_MASK_INT_MASK; val |= AFI_INTR_MASK_MSI_MASK; afi_writel(pcie, val, AFI_INTR_MASK); return 0; } static const struct dev_pm_ops tegra_pcie_pm_ops = { .resume = tegra_pcie_resume, .suspend_late = tegra_pcie_suspend_late, .resume_early = tegra_pcie_resume_early, .runtime_suspend = tegra_pcie_save_device, .runtime_resume = tegra_pcie_restore_device, .suspend_noirq = tegra_pcie_save_device, .resume_noirq = tegra_pcie_restore_device, }; #endif /* CONFIG_PM */ /* driver data is accessed after init, so use __refdata instead of __initdata */ static struct platform_driver __refdata tegra_pcie_driver = { .probe = tegra_pcie_probe, .remove = tegra_pcie_remove, .driver = { .name = "tegra-pcie", .owner = THIS_MODULE, #ifdef CONFIG_PM .pm = &tegra_pcie_pm_ops, #endif .of_match_table = tegra_pcie_of_match, }, }; static int __init tegra_pcie_init_driver(void) { return platform_driver_register(&tegra_pcie_driver); } static void __exit tegra_pcie_exit_driver(void) { platform_driver_unregister(&tegra_pcie_driver); } module_init(tegra_pcie_init_driver); module_exit(tegra_pcie_exit_driver); MODULE_LICENSE("GPL v2");
27.626136
113
0.71636
[ "vector" ]
63c152a89d58d87d92ecce2377fb8b9af41bc0d6
66,057
c
C
Library/Il2cppBuildCache/Lumin/il2cppOutput/Microsoft.MixedReality.Toolkit.Services.InputAnimation_CodeGen.c
coderrick/xrrx-snake
acc1212ff0cf5aba3ad101f7cabb4adab935fb62
[ "MIT" ]
null
null
null
Library/Il2cppBuildCache/Lumin/il2cppOutput/Microsoft.MixedReality.Toolkit.Services.InputAnimation_CodeGen.c
coderrick/xrrx-snake
acc1212ff0cf5aba3ad101f7cabb4adab935fb62
[ "MIT" ]
null
null
null
Library/Il2cppBuildCache/Lumin/il2cppOutput/Microsoft.MixedReality.Toolkit.Services.InputAnimation_CodeGen.c
coderrick/xrrx-snake
acc1212ff0cf5aba3ad101f7cabb4adab935fb62
[ "MIT" ]
null
null
null
#include "pch-c.h" #ifndef _MSC_VER # include <alloca.h> #else # include <malloc.h> #endif #include "codegen/il2cpp-codegen-metadata.h" // 0x00000001 System.Boolean Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::get_IsRecording() // 0x00000002 System.Boolean Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::get_UseBufferTimeLimit() // 0x00000003 System.Void Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::set_UseBufferTimeLimit(System.Boolean) // 0x00000004 System.Single Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::get_RecordingBufferTimeLimit() // 0x00000005 System.Void Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::set_RecordingBufferTimeLimit(System.Single) // 0x00000006 System.Void Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::StartRecording() // 0x00000007 System.Void Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::StopRecording() // 0x00000008 System.Void Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::DiscardRecordedInput() // 0x00000009 System.String Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::SaveInputAnimation(System.String) // 0x0000000A System.String Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::SaveInputAnimation(System.String,System.String) // 0x0000000B System.Threading.Tasks.Task`1<System.String> Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::SaveInputAnimationAsync(System.String) // 0x0000000C System.Threading.Tasks.Task`1<System.String> Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputRecordingService::SaveInputAnimationAsync(System.String,System.String) // 0x0000000D System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker::.ctor() extern void InputAnimationMarker__ctor_m5C094A0AA3BE8B275927192C7A071A2C9A283CE0 (void); // 0x0000000E System.Single Microsoft.MixedReality.Toolkit.Input.InputAnimation::get_Duration() extern void InputAnimation_get_Duration_m324F71B6B00B2157F9089CD2216E609E86754D41 (void); // 0x0000000F System.Boolean Microsoft.MixedReality.Toolkit.Input.InputAnimation::get_HasHandData() extern void InputAnimation_get_HasHandData_mE1EC63E79BDC6DD2E080BE6398E6D1322581504E (void); // 0x00000010 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::set_HasHandData(System.Boolean) extern void InputAnimation_set_HasHandData_mDFFC64585652BC809697BFC7BB7ED7647D18BEDB (void); // 0x00000011 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputAnimation::get_HasCameraPose() extern void InputAnimation_get_HasCameraPose_m70E92BAEBAB6A367D7D12483D7B0D2E809E73C02 (void); // 0x00000012 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::set_HasCameraPose(System.Boolean) extern void InputAnimation_set_HasCameraPose_m1CC8ED88313F71BAEB15DA2546D80A1DB73A3B82 (void); // 0x00000013 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputAnimation::get_HasEyeGaze() extern void InputAnimation_get_HasEyeGaze_m6BC961015C07A77F41D039B675218CF7D5A16DC0 (void); // 0x00000014 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::set_HasEyeGaze(System.Boolean) extern void InputAnimation_set_HasEyeGaze_mD51BD84A8E028923E6B19FAF0DB46C9C1D7C5028 (void); // 0x00000015 System.Int32 Microsoft.MixedReality.Toolkit.Input.InputAnimation::get_markerCount() extern void InputAnimation_get_markerCount_m228DA21CCF2EA81EC9F0DE1959F59B809E221E02 (void); // 0x00000016 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::.ctor() extern void InputAnimation__ctor_mFFE3C34E979C4C4D4E92E7CD4957277A97A85A93 (void); // 0x00000017 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddHandStateKey(System.Single,Microsoft.MixedReality.Toolkit.Utilities.Handedness,System.Boolean,System.Boolean) extern void InputAnimation_AddHandStateKey_mDDFAFD403430BA6969ED6B46932E43A724417A32 (void); // 0x00000018 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddHandJointKey(System.Single,Microsoft.MixedReality.Toolkit.Utilities.Handedness,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose,System.Single,System.Single) extern void InputAnimation_AddHandJointKey_m3A0F66E2136C41CD45E8C36711A88E06D409B4FC (void); // 0x00000019 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddCameraPoseKey(System.Single,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose,System.Single,System.Single) extern void InputAnimation_AddCameraPoseKey_m51C0F811302D3C981AE7BC274B63375BB4C8E83B (void); // 0x0000001A System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddMarker(Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker) extern void InputAnimation_AddMarker_m9204A1EA11448605EF707B344FCFA096A3C47B0C (void); // 0x0000001B System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::RemoveMarker(System.Int32) extern void InputAnimation_RemoveMarker_m0CCD4D60F3EC08907139DA66B8E1AF233B2CD239 (void); // 0x0000001C System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::SetMarkerTime(System.Int32,System.Single) extern void InputAnimation_SetMarkerTime_m182534D2930AD14973F28FE7ECBD02A7B44CD2AA (void); // 0x0000001D System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::Clear() extern void InputAnimation_Clear_mEDD6A20649F35AE372F7949C1E5E8B01BF26BD59 (void); // 0x0000001E System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::CutoffBeforeTime(System.Single) extern void InputAnimation_CutoffBeforeTime_m203B2531044D757E39515F528FE6EFB4301925CA (void); // 0x0000001F System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::ToStream(System.IO.Stream,System.Single) extern void InputAnimation_ToStream_m5E9608AECD63E8A8AEB3113EB84E7DABA3801BBD (void); // 0x00000020 System.Threading.Tasks.Task Microsoft.MixedReality.Toolkit.Input.InputAnimation::ToStreamAsync(System.IO.Stream,System.Single,System.Action) extern void InputAnimation_ToStreamAsync_m48C744205AE242AA539375FD11AB34F2A0771B46 (void); // 0x00000021 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::EvaluateHandState(System.Single,Microsoft.MixedReality.Toolkit.Utilities.Handedness,System.Boolean&,System.Boolean&) extern void InputAnimation_EvaluateHandState_m76A721E17E56D92A5C9000C3DB7543904C43E36D (void); // 0x00000022 System.Int32 Microsoft.MixedReality.Toolkit.Input.InputAnimation::FindMarkerInterval(System.Single) extern void InputAnimation_FindMarkerInterval_m6A6F9D84E102F6F18105F391D9BD296F965C6ED5 (void); // 0x00000023 Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose Microsoft.MixedReality.Toolkit.Input.InputAnimation::EvaluateCameraPose(System.Single) extern void InputAnimation_EvaluateCameraPose_mA06BC7691D681CC6011970B06FE85F4F21CCD21E (void); // 0x00000024 Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose Microsoft.MixedReality.Toolkit.Input.InputAnimation::EvaluateHandJoint(System.Single,Microsoft.MixedReality.Toolkit.Utilities.Handedness,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint) extern void InputAnimation_EvaluateHandJoint_mB1BD9144BE8F3D891476E898375AAFD78FB1DA82 (void); // 0x00000025 UnityEngine.Ray Microsoft.MixedReality.Toolkit.Input.InputAnimation::EvaluateEyeGaze(System.Single) extern void InputAnimation_EvaluateEyeGaze_m8397D5795457BF023BA7902F2EE11F28F529048F (void); // 0x00000026 Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker Microsoft.MixedReality.Toolkit.Input.InputAnimation::GetMarker(System.Int32) extern void InputAnimation_GetMarker_mB89D4AB46775D392411E517D0BCB7B4D46607D24 (void); // 0x00000027 Microsoft.MixedReality.Toolkit.Input.InputAnimation Microsoft.MixedReality.Toolkit.Input.InputAnimation::FromRecordingBuffer(Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer,Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile) extern void InputAnimation_FromRecordingBuffer_mFC1695424E73459B9C12D60511DC7BF026FACFFB (void); // 0x00000028 Microsoft.MixedReality.Toolkit.Input.InputAnimation Microsoft.MixedReality.Toolkit.Input.InputAnimation::FromStream(System.IO.Stream) extern void InputAnimation_FromStream_m58694E2590699E9E2833A0971FFB55476FC18047 (void); // 0x00000029 System.Threading.Tasks.Task`1<Microsoft.MixedReality.Toolkit.Input.InputAnimation> Microsoft.MixedReality.Toolkit.Input.InputAnimation::FromStreamAsync(System.IO.Stream,System.Action) extern void InputAnimation_FromStreamAsync_m92C92138D59E7F5CB0E815D381BC4F72FED66E79 (void); // 0x0000002A System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddHandStateKey(System.Single,System.Boolean,System.Boolean,UnityEngine.AnimationCurve,UnityEngine.AnimationCurve) extern void InputAnimation_AddHandStateKey_m8FC218057E46653BA5F8DA3F20EDD26F0867BA7D (void); // 0x0000002B System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddHandJointKey(System.Single,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose,System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves>,System.Single,System.Single) extern void InputAnimation_AddHandJointKey_mFBEFB300645E6981C38076FE4A3570BE9DFE680C (void); // 0x0000002C System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::CutoffBeforeTime(UnityEngine.AnimationCurve,System.Single) extern void InputAnimation_CutoffBeforeTime_m40F36C19E530FD5D1310DD80D9C48A30F3C62C13 (void); // 0x0000002D Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves Microsoft.MixedReality.Toolkit.Input.InputAnimation::CreateHandJointCurves(Microsoft.MixedReality.Toolkit.Utilities.Handedness,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint) extern void InputAnimation_CreateHandJointCurves_mDF0FEA0053141B9153AA26F8BBF35A510A433910 (void); // 0x0000002E System.Boolean Microsoft.MixedReality.Toolkit.Input.InputAnimation::TryGetHandJointCurves(Microsoft.MixedReality.Toolkit.Utilities.Handedness,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves&) extern void InputAnimation_TryGetHandJointCurves_m6CBE945EF12A959ECB1EE378688BDD6D9CA9C22B (void); // 0x0000002F System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::ComputeDuration() extern void InputAnimation_ComputeDuration_m67F8213261EB8A04522E0253A305B6DF519656C0 (void); // 0x00000030 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::Optimize(Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile) extern void InputAnimation_Optimize_m85E61983DE15A609A9EA67796ABD073AE0487D27 (void); // 0x00000031 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::EvaluateHandState(System.Single,UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,System.Boolean&,System.Boolean&) extern void InputAnimation_EvaluateHandState_m9F6A2CF5B5F1956187790199ADD608B1CB7FAE36 (void); // 0x00000032 Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose Microsoft.MixedReality.Toolkit.Input.InputAnimation::EvaluateHandJoint(System.Single,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves>) extern void InputAnimation_EvaluateHandJoint_mB902B76C54C7A11773A9E1F2D78F10E299F90FC3 (void); // 0x00000033 System.Collections.Generic.IEnumerable`1<UnityEngine.AnimationCurve> Microsoft.MixedReality.Toolkit.Input.InputAnimation::GetAllAnimationCurves() extern void InputAnimation_GetAllAnimationCurves_mF2A00A8A89378A02AA213F26B7D2B0EF869AB526 (void); // 0x00000034 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddBoolKey(UnityEngine.AnimationCurve,System.Single,System.Boolean) extern void InputAnimation_AddBoolKey_mC23D7530D31F64BC0E187FCCBDD8E5F3AB61199D (void); // 0x00000035 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddFloatKey(UnityEngine.AnimationCurve,System.Single,System.Single) extern void InputAnimation_AddFloatKey_mD316869BF5B620AC0A6E57A534F3906947D7C78B (void); // 0x00000036 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddVectorKey(UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,System.Single,UnityEngine.Vector3) extern void InputAnimation_AddVectorKey_m0444BC9E945FD7596352081B54E64641AE89EA65 (void); // 0x00000037 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddPoseKeyFiltered(Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves,System.Single,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose,System.Single,System.Single) extern void InputAnimation_AddPoseKeyFiltered_mE9D95FC2C157B85DFFFDD955C8EAF0F409108705 (void); // 0x00000038 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddPositionKeyFiltered(UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,System.Single,UnityEngine.Vector3,System.Single) extern void InputAnimation_AddPositionKeyFiltered_mB6B10598350F551860641100303803CADC08019C (void); // 0x00000039 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddRotationKeyFiltered(UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,UnityEngine.AnimationCurve,System.Single,UnityEngine.Quaternion,System.Single) extern void InputAnimation_AddRotationKeyFiltered_m1B9E7C65999003864023597551742DC2947AB966 (void); // 0x0000003A System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::PoseCurvesToStream(System.IO.BinaryWriter,Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves,System.Single) extern void InputAnimation_PoseCurvesToStream_mC892445DA1552CB7D395FFA0CFFA5FC8970D18E2 (void); // 0x0000003B System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::PoseCurvesFromStream(System.IO.BinaryReader,Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves,System.Boolean) extern void InputAnimation_PoseCurvesFromStream_m67BDC1499A27777D1A196E715B799432AEED50E4 (void); // 0x0000003C System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::RayCurvesToStream(System.IO.BinaryWriter,Microsoft.MixedReality.Toolkit.Input.InputAnimation/RayCurves,System.Single) extern void InputAnimation_RayCurvesToStream_mE59C067DC66E85F627C683EA78B0F22E75DE551F (void); // 0x0000003D System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::RayCurvesFromStream(System.IO.BinaryReader,Microsoft.MixedReality.Toolkit.Input.InputAnimation/RayCurves,System.Boolean) extern void InputAnimation_RayCurvesFromStream_m2BA8BA802AF250E41613B9310C7F5CC20DC99BDD (void); // 0x0000003E System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::OptimizePositionCurve(UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,System.Single,System.Int32) extern void InputAnimation_OptimizePositionCurve_m1C7279C913A4A8B6BDBD039F3F4BCA1938A70014 (void); // 0x0000003F System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::OptimizeDirectionCurve(UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,System.Single,System.Int32) extern void InputAnimation_OptimizeDirectionCurve_mC560CC7A7D51649389102405C191CE68838CD6EA (void); // 0x00000040 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::OptimizeRotationCurve(UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,UnityEngine.AnimationCurve&,System.Single,System.Int32) extern void InputAnimation_OptimizeRotationCurve_m5FFF80C6581D8513DB63F15824956A43E1EF8EFA (void); // 0x00000041 System.Int32 Microsoft.MixedReality.Toolkit.Input.InputAnimation::AddBoolKeyFiltered(UnityEngine.AnimationCurve,System.Single,System.Boolean) extern void InputAnimation_AddBoolKeyFiltered_m39AB9D96F272BFCCEE6FFE6FDC5B67404F6C8D75 (void); // 0x00000042 System.Int32 Microsoft.MixedReality.Toolkit.Input.InputAnimation::FindKeyframeInterval(UnityEngine.AnimationCurve,System.Single) extern void InputAnimation_FindKeyframeInterval_m973AD87553EEEDFBAC0EECBB15A1BBEC5EC85463 (void); // 0x00000043 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::<FromRecordingBuffer>g__AddBoolKeyIfChanged|47_0(UnityEngine.AnimationCurve,System.Single,System.Boolean) extern void InputAnimation_U3CFromRecordingBufferU3Eg__AddBoolKeyIfChangedU7C47_0_mECF0AE0F90A09339B9B85571E7D79CF032E5FD5D (void); // 0x00000044 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::<FromRecordingBuffer>g__AddJointPoseKeys|47_1(System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves>,System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose>,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,System.Single) extern void InputAnimation_U3CFromRecordingBufferU3Eg__AddJointPoseKeysU7C47_1_m4451B5CFCFB77EFC71B2F207FCEFDE2C92AC4554 (void); // 0x00000045 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::<OptimizePositionCurve>g__Recurse|70_0(System.Int32,System.Int32,Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass70_0&) extern void InputAnimation_U3COptimizePositionCurveU3Eg__RecurseU7C70_0_m4FCE53B2AF6FF132C505DDD0B15A7D94DDE88330 (void); // 0x00000046 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::<OptimizeDirectionCurve>g__Recurse|71_0(System.Int32,System.Int32,Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass71_0&) extern void InputAnimation_U3COptimizeDirectionCurveU3Eg__RecurseU7C71_0_m3A4ECBAE6874B641DCF0EC87A2A3A909C0E61F08 (void); // 0x00000047 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation::<OptimizeRotationCurve>g__Recurse|72_0(System.Int32,System.Int32,Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass72_0&) extern void InputAnimation_U3COptimizeRotationCurveU3Eg__RecurseU7C72_0_m5C029920E1D8F76390A604EAE425EC3E7B3F30C1 (void); // 0x00000048 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves::AddKey(System.Single,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose) extern void PoseCurves_AddKey_m09FBA52357C8BD9ADE0ACB11B9A1738F75FE3038 (void); // 0x00000049 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves::Optimize(System.Single,System.Single,System.Int32) extern void PoseCurves_Optimize_mC0CF1C42C12C941ECD5913217E69A47876235A42 (void); // 0x0000004A Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves::Evaluate(System.Single) extern void PoseCurves_Evaluate_m65B8ABBF072CE1FD5A59859361DB9F3FFF70816D (void); // 0x0000004B System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/PoseCurves::.ctor() extern void PoseCurves__ctor_mF5A11EC505433BE0BE40D61E6F28FD648919471F (void); // 0x0000004C System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/RayCurves::AddKey(System.Single,UnityEngine.Ray) extern void RayCurves_AddKey_m51FCF0A127416BBB7708CD5EC608CFF5C6B24C6D (void); // 0x0000004D System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/RayCurves::Optimize(System.Single,System.Single,System.Int32) extern void RayCurves_Optimize_m5FFB2912CDBE6CF5B6451A3855E7B656190C6F16 (void); // 0x0000004E UnityEngine.Ray Microsoft.MixedReality.Toolkit.Input.InputAnimation/RayCurves::Evaluate(System.Single) extern void RayCurves_Evaluate_mC0E941F7484A969BD24DE6729769EB028C093427 (void); // 0x0000004F System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/RayCurves::.ctor() extern void RayCurves__ctor_m461CFADEE509565D400DFFACA11DA7779CBC23D9 (void); // 0x00000050 System.Int32 Microsoft.MixedReality.Toolkit.Input.InputAnimation/CompareMarkers::Compare(Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker,Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker) extern void CompareMarkers_Compare_m0FE15C6ACBD37151C55A6C49576FD6B1B4363634 (void); // 0x00000051 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/CompareMarkers::.ctor() extern void CompareMarkers__ctor_m6C6ED2992996361CF100D40ECBE0EF83A05ED469 (void); // 0x00000052 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass40_0::.ctor() extern void U3CU3Ec__DisplayClass40_0__ctor_mFF979788CF100A28885C84D53D9A940DB44B3628 (void); // 0x00000053 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass40_0::<ToStreamAsync>b__0() extern void U3CU3Ec__DisplayClass40_0_U3CToStreamAsyncU3Eb__0_m9E9FA98530439EB22B8110458663086A795215C5 (void); // 0x00000054 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<ToStreamAsync>d__40::MoveNext() extern void U3CToStreamAsyncU3Ed__40_MoveNext_mC9376548261F29A0D9E8AA0EBAD712C926BF3CC0 (void); // 0x00000055 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<ToStreamAsync>d__40::SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine) extern void U3CToStreamAsyncU3Ed__40_SetStateMachine_mCA51EC800CAE3DD1C411325421E00CA1FA5166B0 (void); // 0x00000056 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass49_0::.ctor() extern void U3CU3Ec__DisplayClass49_0__ctor_m592097E35D589AE4623C89BF6C19584E9D53191B (void); // 0x00000057 Microsoft.MixedReality.Toolkit.Input.InputAnimation Microsoft.MixedReality.Toolkit.Input.InputAnimation/<>c__DisplayClass49_0::<FromStreamAsync>b__0() extern void U3CU3Ec__DisplayClass49_0_U3CFromStreamAsyncU3Eb__0_mC707FA6AF9364676DBA368E1B7D22FE274091D79 (void); // 0x00000058 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<FromStreamAsync>d__49::MoveNext() extern void U3CFromStreamAsyncU3Ed__49_MoveNext_m7D7DA4E8D9027AF8E79F171C68B6EECBE9481D72 (void); // 0x00000059 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<FromStreamAsync>d__49::SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine) extern void U3CFromStreamAsyncU3Ed__49_SetStateMachine_mF5170AEEB1D677B504C47ACF30936D6D8F2994BB (void); // 0x0000005A System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::.ctor(System.Int32) extern void U3CGetAllAnimationCurvesU3Ed__59__ctor_mD56390198BBCFC27B1D5535EE05A5208E9C06006 (void); // 0x0000005B System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::System.IDisposable.Dispose() extern void U3CGetAllAnimationCurvesU3Ed__59_System_IDisposable_Dispose_mBA4F4E744D6C57D3703181DC93A29C4C4394ECF3 (void); // 0x0000005C System.Boolean Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::MoveNext() extern void U3CGetAllAnimationCurvesU3Ed__59_MoveNext_mD2DC953413FF5B501BAF75C850ADE71C2968D332 (void); // 0x0000005D System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::<>m__Finally1() extern void U3CGetAllAnimationCurvesU3Ed__59_U3CU3Em__Finally1_mACC6134AC770062B5F535280A4E21947A90DA644 (void); // 0x0000005E System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::<>m__Finally2() extern void U3CGetAllAnimationCurvesU3Ed__59_U3CU3Em__Finally2_m3650B7BFCBBEED6A68AE5B66E6FBE0FC0362D087 (void); // 0x0000005F UnityEngine.AnimationCurve Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::System.Collections.Generic.IEnumerator<UnityEngine.AnimationCurve>.get_Current() extern void U3CGetAllAnimationCurvesU3Ed__59_System_Collections_Generic_IEnumeratorU3CUnityEngine_AnimationCurveU3E_get_Current_mD8304B6C7B97F85A1E1DEEB8E8270ADBEFCC85AD (void); // 0x00000060 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::System.Collections.IEnumerator.Reset() extern void U3CGetAllAnimationCurvesU3Ed__59_System_Collections_IEnumerator_Reset_m4DD4534813AFB13266C389DC17E804C024D8731B (void); // 0x00000061 System.Object Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::System.Collections.IEnumerator.get_Current() extern void U3CGetAllAnimationCurvesU3Ed__59_System_Collections_IEnumerator_get_Current_mB4629844BED1ADD825FCC902D8BFDE61F35F4087 (void); // 0x00000062 System.Collections.Generic.IEnumerator`1<UnityEngine.AnimationCurve> Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::System.Collections.Generic.IEnumerable<UnityEngine.AnimationCurve>.GetEnumerator() extern void U3CGetAllAnimationCurvesU3Ed__59_System_Collections_Generic_IEnumerableU3CUnityEngine_AnimationCurveU3E_GetEnumerator_mFF3CCDF749456180BF6142C15FAFABED75A221D1 (void); // 0x00000063 System.Collections.IEnumerator Microsoft.MixedReality.Toolkit.Input.InputAnimation/<GetAllAnimationCurves>d__59::System.Collections.IEnumerable.GetEnumerator() extern void U3CGetAllAnimationCurvesU3Ed__59_System_Collections_IEnumerable_GetEnumerator_mF62033E59E615E5025239271EF8846E8A5337A13 (void); // 0x00000064 System.String Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::GetOutputFilename(System.String,System.Boolean) extern void InputAnimationSerializationUtils_GetOutputFilename_m48043CA922AD0E73716B4B372164011C16861447 (void); // 0x00000065 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteHeader(System.IO.BinaryWriter) extern void InputAnimationSerializationUtils_WriteHeader_m2414DA896B37BC54609C00103BEE490CA2D8316D (void); // 0x00000066 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadHeader(System.IO.BinaryReader,System.Int32&,System.Int32&) extern void InputAnimationSerializationUtils_ReadHeader_m80B6BD0DB5D55A9CAB5B2DE5246D393E6A42C6A4 (void); // 0x00000067 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteFloatCurve(System.IO.BinaryWriter,UnityEngine.AnimationCurve,System.Single) extern void InputAnimationSerializationUtils_WriteFloatCurve_m60A294A3D4EAFDD5D08D3DD48D9E790359BE4A09 (void); // 0x00000068 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadFloatCurve(System.IO.BinaryReader,UnityEngine.AnimationCurve) extern void InputAnimationSerializationUtils_ReadFloatCurve_m536D99B4BBD3AF6F85957E8797E7709F3C7B3336 (void); // 0x00000069 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteBoolCurve(System.IO.BinaryWriter,UnityEngine.AnimationCurve,System.Single) extern void InputAnimationSerializationUtils_WriteBoolCurve_m353A2B25C74AD3D8A7F02A0713D8C9CC6774C818 (void); // 0x0000006A System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadBoolCurve(System.IO.BinaryReader,UnityEngine.AnimationCurve) extern void InputAnimationSerializationUtils_ReadBoolCurve_m719C4C1FE043E675E12DF34876B702269A800659 (void); // 0x0000006B System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteFloatCurveSimple(System.IO.BinaryWriter,UnityEngine.AnimationCurve,System.Single) extern void InputAnimationSerializationUtils_WriteFloatCurveSimple_mFF68DD534C0F4FCEEF7E0285DF335143E9A78DE7 (void); // 0x0000006C System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadFloatCurveSimple(System.IO.BinaryReader,UnityEngine.AnimationCurve) extern void InputAnimationSerializationUtils_ReadFloatCurveSimple_mE35C73CE457EA91F2145578650E7EA2FD1D29D05 (void); // 0x0000006D System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteFloatCurveArray(System.IO.BinaryWriter,UnityEngine.AnimationCurve[],System.Single) extern void InputAnimationSerializationUtils_WriteFloatCurveArray_m81B5F3BCBFA462C1D7534A3CC9736541C0FC6B67 (void); // 0x0000006E System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadFloatCurveArray(System.IO.BinaryReader,UnityEngine.AnimationCurve[]) extern void InputAnimationSerializationUtils_ReadFloatCurveArray_m869E5D7D663B5AA9F598A605EC142AE5FDA8E6ED (void); // 0x0000006F System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteBoolCurveArray(System.IO.BinaryWriter,UnityEngine.AnimationCurve[],System.Single) extern void InputAnimationSerializationUtils_WriteBoolCurveArray_mA9D1F2ECD040D62E29CB7891CC8503859B35826A (void); // 0x00000070 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadBoolCurveArray(System.IO.BinaryReader,UnityEngine.AnimationCurve[]) extern void InputAnimationSerializationUtils_ReadBoolCurveArray_m3FAC0C7D26FB67C78FCB9E259DADCE3E63889B4B (void); // 0x00000071 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::WriteMarkerList(System.IO.BinaryWriter,System.Collections.Generic.List`1<Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker>,System.Single) extern void InputAnimationSerializationUtils_WriteMarkerList_m2F6970C7A59295395738A66B4A928698780D1649 (void); // 0x00000072 System.Void Microsoft.MixedReality.Toolkit.Input.InputAnimationSerializationUtils::ReadMarkerList(System.IO.BinaryReader,System.Collections.Generic.List`1<Microsoft.MixedReality.Toolkit.Input.InputAnimationMarker>) extern void InputAnimationSerializationUtils_ReadMarkerList_m5DDE2D3265ADF882584FB2561B21AF9736BD6D56 (void); // 0x00000073 System.Single Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::get_StartTime() extern void InputRecordingBuffer_get_StartTime_m4DA0D9853D7D89ACED044112F8A167EE3B3F1935 (void); // 0x00000074 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::.ctor() extern void InputRecordingBuffer__ctor_m43A00F4F39E27085CA2C8B91921EBB23150C9C76 (void); // 0x00000075 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::Clear() extern void InputRecordingBuffer_Clear_mCC22BFBC36EDE5E899D57C80D0F6C57BD05C57B9 (void); // 0x00000076 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::RemoveBeforeTime(System.Single) extern void InputRecordingBuffer_RemoveBeforeTime_mFF897B9D56D694C3FF7B239EBED1CBB2FF7DE1EE (void); // 0x00000077 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::SetCameraPose(Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose) extern void InputRecordingBuffer_SetCameraPose_m68DEF44DE167F57BADC4C476F231A7BB3726B4C0 (void); // 0x00000078 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::SetGazeRay(UnityEngine.Ray) extern void InputRecordingBuffer_SetGazeRay_mA00F2164D715DBAA1597B1DC61C0786DE84252E6 (void); // 0x00000079 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::SetHandState(Microsoft.MixedReality.Toolkit.Utilities.Handedness,System.Boolean,System.Boolean) extern void InputRecordingBuffer_SetHandState_m8D7F1CEF1AB0B57E3A8CA44E96CAA870B9D03600 (void); // 0x0000007A System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::SetJointPose(Microsoft.MixedReality.Toolkit.Utilities.Handedness,Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose) extern void InputRecordingBuffer_SetJointPose_m5B85A418454EAB63BF31181A75025BF4410FF502 (void); // 0x0000007B System.Int32 Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::NewKeyframe(System.Single) extern void InputRecordingBuffer_NewKeyframe_m196CC0276D1D4FF940DF8E2352C5FB7A7FD5EF11 (void); // 0x0000007C System.Collections.Generic.IEnumerator`1<Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe> Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::GetEnumerator() extern void InputRecordingBuffer_GetEnumerator_mC16F9FA32FBB1E1E1D8FE9FDFFBBB6EC47C225E7 (void); // 0x0000007D System.Collections.IEnumerator Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer::System.Collections.IEnumerable.GetEnumerator() extern void InputRecordingBuffer_System_Collections_IEnumerable_GetEnumerator_mC30CB396868C387007298A038416AFEB34A84B93 (void); // 0x0000007E System.Single Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_Time() extern void Keyframe_get_Time_m5A94321ED895DA4719F6AECB6FFCAFD4CFE81C18 (void); // 0x0000007F System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_Time(System.Single) extern void Keyframe_set_Time_m5BF4E2967A1949C46D73C5E9899E43438A7F7674 (void); // 0x00000080 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_LeftTracked() extern void Keyframe_get_LeftTracked_mC028E832EF357A6D35848E5A0D92FC203356984B (void); // 0x00000081 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_LeftTracked(System.Boolean) extern void Keyframe_set_LeftTracked_m195D1C9B70DE1C52E33F7E1452D817969018E9FC (void); // 0x00000082 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_RightTracked() extern void Keyframe_get_RightTracked_mD7CF7BC3BA431D972F6F83AE9CECA15EA8D76569 (void); // 0x00000083 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_RightTracked(System.Boolean) extern void Keyframe_set_RightTracked_mCDFA0F3628EF01C0593B0FC84509350B80FE2A16 (void); // 0x00000084 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_LeftPinch() extern void Keyframe_get_LeftPinch_m26B6CA55F56E45AF12B6C6EB92F070B7C404C3B4 (void); // 0x00000085 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_LeftPinch(System.Boolean) extern void Keyframe_set_LeftPinch_m7D15C79E632EF8AC24E5D3491383544F8B77AEEB (void); // 0x00000086 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_RightPinch() extern void Keyframe_get_RightPinch_m5D7DC4C2A2623511F1ED05AFDAEA29261DCFFD41 (void); // 0x00000087 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_RightPinch(System.Boolean) extern void Keyframe_set_RightPinch_m3D30DE7BC5A4743D627A4FA63164AAAE4EAC9C6F (void); // 0x00000088 Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_CameraPose() extern void Keyframe_get_CameraPose_m16D2BA3112660DEC614E4E7D3D1D105EFE6C7595 (void); // 0x00000089 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_CameraPose(Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose) extern void Keyframe_set_CameraPose_mB3BCF1A2A1699020C2BC399F488977652447055C (void); // 0x0000008A UnityEngine.Ray Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_GazeRay() extern void Keyframe_get_GazeRay_mB578916EE0B0905F66C7DA537AA88266B02E7847 (void); // 0x0000008B System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_GazeRay(UnityEngine.Ray) extern void Keyframe_set_GazeRay_mBB00243C934D3AF4BE3E9E3461EF1D53B48D7AAF (void); // 0x0000008C System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose> Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_LeftJoints() extern void Keyframe_get_LeftJoints_m6FA28C62D4A75A4CB545C1CCBE1CB9DEDC7DE96B (void); // 0x0000008D System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_LeftJoints(System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose>) extern void Keyframe_set_LeftJoints_mF9EF11D4505A2AFAF484C450B254A5F92627AC6B (void); // 0x0000008E System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose> Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::get_RightJoints() extern void Keyframe_get_RightJoints_m5E3998C352E7BEC081AE82800F2D0A8858E304C9 (void); // 0x0000008F System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::set_RightJoints(System.Collections.Generic.Dictionary`2<Microsoft.MixedReality.Toolkit.Utilities.TrackedHandJoint,Microsoft.MixedReality.Toolkit.Utilities.MixedRealityPose>) extern void Keyframe_set_RightJoints_mF4D49C1C8915A04A771672EC42BDBAC23D4985B8 (void); // 0x00000090 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingBuffer/Keyframe::.ctor(System.Single) extern void Keyframe__ctor_m91F47F5A8B680109F9887BA004DC4DCDA27CE6CA (void); // 0x00000091 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::add_OnRecordingStarted(System.Action) extern void InputRecordingService_add_OnRecordingStarted_m59AFC7A494D7D15837309A3E7F1D650449643C4A (void); // 0x00000092 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::remove_OnRecordingStarted(System.Action) extern void InputRecordingService_remove_OnRecordingStarted_m56FB17804146C59B2C97CC4623A45194F0D73DEB (void); // 0x00000093 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::add_OnRecordingStopped(System.Action) extern void InputRecordingService_add_OnRecordingStopped_mFF85EB8C5B7F742B736DB2AC1F273B7E85F212F1 (void); // 0x00000094 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::remove_OnRecordingStopped(System.Action) extern void InputRecordingService_remove_OnRecordingStopped_m684CAFA134D88BE02BD291AB5B5D4EB8C0DF8708 (void); // 0x00000095 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputRecordingService::get_IsRecording() extern void InputRecordingService_get_IsRecording_mABDF25EEF3633FD960D47773D6F9AA4C346E212D (void); // 0x00000096 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::set_IsRecording(System.Boolean) extern void InputRecordingService_set_IsRecording_m4F3DB5352CA6A00A3575A110A2EA55ACF2B73722 (void); // 0x00000097 System.Boolean Microsoft.MixedReality.Toolkit.Input.InputRecordingService::get_UseBufferTimeLimit() extern void InputRecordingService_get_UseBufferTimeLimit_m28B8409B14A29B84B66D3F85FF9B9FEF5E7FC2B9 (void); // 0x00000098 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::set_UseBufferTimeLimit(System.Boolean) extern void InputRecordingService_set_UseBufferTimeLimit_m9D197D9EADE7342688D045A14E07021C628CB871 (void); // 0x00000099 System.Single Microsoft.MixedReality.Toolkit.Input.InputRecordingService::get_RecordingBufferTimeLimit() extern void InputRecordingService_get_RecordingBufferTimeLimit_mB2EAF047708A84CB548579FA9E6B826F6F966F07 (void); // 0x0000009A System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::set_RecordingBufferTimeLimit(System.Single) extern void InputRecordingService_set_RecordingBufferTimeLimit_m2B5F3C1C3026E477903FCC78C0F79C67933CF073 (void); // 0x0000009B System.Single Microsoft.MixedReality.Toolkit.Input.InputRecordingService::get_StartTime() extern void InputRecordingService_get_StartTime_mCD8C83EB5DB55DBD240A30F1F00FCDA30A3A6995 (void); // 0x0000009C System.Single Microsoft.MixedReality.Toolkit.Input.InputRecordingService::get_EndTime() extern void InputRecordingService_get_EndTime_m946DC951E5887DCD4E4FB77C4C60A8C69280197B (void); // 0x0000009D System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::set_EndTime(System.Single) extern void InputRecordingService_set_EndTime_m6AF7B853301EE3481BA416768D27DB973D37D1C8 (void); // 0x0000009E Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile Microsoft.MixedReality.Toolkit.Input.InputRecordingService::get_InputRecordingProfile() extern void InputRecordingService_get_InputRecordingProfile_mF145CA8FDFF06282142B6E5F811F4609F6BFE785 (void); // 0x0000009F System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::set_InputRecordingProfile(Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile) extern void InputRecordingService_set_InputRecordingProfile_m39FFB6DB54D7AC64A3303ED8810B167E5E1E1C86 (void); // 0x000000A0 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::.ctor(Microsoft.MixedReality.Toolkit.IMixedRealityServiceRegistrar,Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputSystem,System.String,System.UInt32,Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile) extern void InputRecordingService__ctor_m0A32145DDE791E1C6CA36F9DCBC4B1211DB6E6B9 (void); // 0x000000A1 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::.ctor(Microsoft.MixedReality.Toolkit.Input.IMixedRealityInputSystem,System.String,System.UInt32,Microsoft.MixedReality.Toolkit.BaseMixedRealityProfile) extern void InputRecordingService__ctor_mF036AEEFABF6BD0CED7101E97017C66693B0D41F (void); // 0x000000A2 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::Enable() extern void InputRecordingService_Enable_m6FAB8C32295F118364CA14A7F7361265D654436F (void); // 0x000000A3 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::Disable() extern void InputRecordingService_Disable_m7F57ED51D6707D2ECDA2E698304B945709C3BCD2 (void); // 0x000000A4 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::StartRecording() extern void InputRecordingService_StartRecording_m8AC2ECF61E4B8BAAC0BFCB5A6C838786FF9C5BC8 (void); // 0x000000A5 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::StopRecording() extern void InputRecordingService_StopRecording_mB6365DA27CE3C222E30371EACA7048F72EF93E51 (void); // 0x000000A6 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::LateUpdate() extern void InputRecordingService_LateUpdate_m4B70FB672C8D6E23B407BF8EC98D5FA3702321E0 (void); // 0x000000A7 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::DiscardRecordedInput() extern void InputRecordingService_DiscardRecordedInput_m25B81E3DB1D2B2A1F8C959172F9FC9E426D7CF1E (void); // 0x000000A8 System.String Microsoft.MixedReality.Toolkit.Input.InputRecordingService::SaveInputAnimation(System.String) extern void InputRecordingService_SaveInputAnimation_mC11C0F6A14E38BF6565B584501FC5EE8F7419647 (void); // 0x000000A9 System.String Microsoft.MixedReality.Toolkit.Input.InputRecordingService::SaveInputAnimation(System.String,System.String) extern void InputRecordingService_SaveInputAnimation_mAB2F869F8DDFEB676413561C1FB5B0730B7EB0BF (void); // 0x000000AA System.Threading.Tasks.Task`1<System.String> Microsoft.MixedReality.Toolkit.Input.InputRecordingService::SaveInputAnimationAsync(System.String) extern void InputRecordingService_SaveInputAnimationAsync_m049195AE43D197BF5D947087191ECA0CBF3BA8CA (void); // 0x000000AB System.Threading.Tasks.Task`1<System.String> Microsoft.MixedReality.Toolkit.Input.InputRecordingService::SaveInputAnimationAsync(System.String,System.String) extern void InputRecordingService_SaveInputAnimationAsync_m7B31EE97B36838944CDF324D297C26B4468F280A (void); // 0x000000AC System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::ResetStartTime() extern void InputRecordingService_ResetStartTime_m3B6E3EE5518C1F18353CDC1DF3214108285BC634 (void); // 0x000000AD System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::RecordKeyframe() extern void InputRecordingService_RecordKeyframe_mC9AD4872D1DFE3D696A93DE5DC5C583240E7D60C (void); // 0x000000AE System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::RecordInputHandData(Microsoft.MixedReality.Toolkit.Utilities.Handedness) extern void InputRecordingService_RecordInputHandData_m8046EA2D6BC0D855E08A4B49852CF87B1F23F9C7 (void); // 0x000000AF System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService::PruneBuffer() extern void InputRecordingService_PruneBuffer_m7E3C4CF8CFC725648DA14B89E04C5F45A0EFB1F0 (void); // 0x000000B0 Microsoft.MixedReality.Toolkit.Input.InputAnimation Microsoft.MixedReality.Toolkit.Input.InputRecordingService::<SaveInputAnimationAsync>b__44_0() extern void InputRecordingService_U3CSaveInputAnimationAsyncU3Eb__44_0_mC10DCB1B893639E18830A3839E093A7D778BBBBF (void); // 0x000000B1 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService/<SaveInputAnimationAsync>d__44::MoveNext() extern void U3CSaveInputAnimationAsyncU3Ed__44_MoveNext_m9FCC9D4EE34F903B251DFC9267DEB1FAE4B7A645 (void); // 0x000000B2 System.Void Microsoft.MixedReality.Toolkit.Input.InputRecordingService/<SaveInputAnimationAsync>d__44::SetStateMachine(System.Runtime.CompilerServices.IAsyncStateMachine) extern void U3CSaveInputAnimationAsyncU3Ed__44_SetStateMachine_mDB2BD0422C6211FB1D2D8D184AF469F304649666 (void); // 0x000000B3 System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_FrameRate() extern void MixedRealityInputRecordingProfile_get_FrameRate_m86BDF5FC09CB89D3C1071FA6FDA5A9FFA4D36814 (void); // 0x000000B4 System.Boolean Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_RecordHandData() extern void MixedRealityInputRecordingProfile_get_RecordHandData_mD9E60E20D10052B4FA1C702D2BD40C52DEF2F9E2 (void); // 0x000000B5 System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_JointPositionThreshold() extern void MixedRealityInputRecordingProfile_get_JointPositionThreshold_m4349A57473BF6EF8DC6932C0F0D0796532FD7E6A (void); // 0x000000B6 System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_JointRotationThreshold() extern void MixedRealityInputRecordingProfile_get_JointRotationThreshold_mB05FA5B9F2F05BAD0653B4D2BD850CD77463062C (void); // 0x000000B7 System.Boolean Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_RecordCameraPose() extern void MixedRealityInputRecordingProfile_get_RecordCameraPose_m87161149954A3AAC9BB498A7F257F408F0C56439 (void); // 0x000000B8 System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_CameraPositionThreshold() extern void MixedRealityInputRecordingProfile_get_CameraPositionThreshold_m8DCEA0EAD8EF61331ACE8CD34729515A08B04492 (void); // 0x000000B9 System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_CameraRotationThreshold() extern void MixedRealityInputRecordingProfile_get_CameraRotationThreshold_m5D95FE8ECA5F39427B931880735EDC99DAC11A4A (void); // 0x000000BA System.Boolean Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_RecordEyeGaze() extern void MixedRealityInputRecordingProfile_get_RecordEyeGaze_m87FFB44F45765DBC69E92DFA72020C6C55B00215 (void); // 0x000000BB System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_EyeGazeOriginThreshold() extern void MixedRealityInputRecordingProfile_get_EyeGazeOriginThreshold_m456FB459A70D07867EBBCB771AFA8BF82E00FE49 (void); // 0x000000BC System.Single Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_EyeGazeDirectionThreshold() extern void MixedRealityInputRecordingProfile_get_EyeGazeDirectionThreshold_m73CCF70F4EA8C58E0023B4B373F938BE6757F3D5 (void); // 0x000000BD System.Int32 Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::get_PartitionSize() extern void MixedRealityInputRecordingProfile_get_PartitionSize_m0E85FBE1B9C167763298CFB08FF66B3B140D4BE4 (void); // 0x000000BE System.Void Microsoft.MixedReality.Toolkit.Input.MixedRealityInputRecordingProfile::.ctor() extern void MixedRealityInputRecordingProfile__ctor_m0C84199A4E420F20EE9BB2307DEAB3E8910D877A (void); static Il2CppMethodPointer s_methodPointers[190] = { NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, InputAnimationMarker__ctor_m5C094A0AA3BE8B275927192C7A071A2C9A283CE0, InputAnimation_get_Duration_m324F71B6B00B2157F9089CD2216E609E86754D41, InputAnimation_get_HasHandData_mE1EC63E79BDC6DD2E080BE6398E6D1322581504E, InputAnimation_set_HasHandData_mDFFC64585652BC809697BFC7BB7ED7647D18BEDB, InputAnimation_get_HasCameraPose_m70E92BAEBAB6A367D7D12483D7B0D2E809E73C02, InputAnimation_set_HasCameraPose_m1CC8ED88313F71BAEB15DA2546D80A1DB73A3B82, InputAnimation_get_HasEyeGaze_m6BC961015C07A77F41D039B675218CF7D5A16DC0, InputAnimation_set_HasEyeGaze_mD51BD84A8E028923E6B19FAF0DB46C9C1D7C5028, InputAnimation_get_markerCount_m228DA21CCF2EA81EC9F0DE1959F59B809E221E02, InputAnimation__ctor_mFFE3C34E979C4C4D4E92E7CD4957277A97A85A93, InputAnimation_AddHandStateKey_mDDFAFD403430BA6969ED6B46932E43A724417A32, InputAnimation_AddHandJointKey_m3A0F66E2136C41CD45E8C36711A88E06D409B4FC, InputAnimation_AddCameraPoseKey_m51C0F811302D3C981AE7BC274B63375BB4C8E83B, InputAnimation_AddMarker_m9204A1EA11448605EF707B344FCFA096A3C47B0C, InputAnimation_RemoveMarker_m0CCD4D60F3EC08907139DA66B8E1AF233B2CD239, InputAnimation_SetMarkerTime_m182534D2930AD14973F28FE7ECBD02A7B44CD2AA, InputAnimation_Clear_mEDD6A20649F35AE372F7949C1E5E8B01BF26BD59, InputAnimation_CutoffBeforeTime_m203B2531044D757E39515F528FE6EFB4301925CA, InputAnimation_ToStream_m5E9608AECD63E8A8AEB3113EB84E7DABA3801BBD, InputAnimation_ToStreamAsync_m48C744205AE242AA539375FD11AB34F2A0771B46, InputAnimation_EvaluateHandState_m76A721E17E56D92A5C9000C3DB7543904C43E36D, InputAnimation_FindMarkerInterval_m6A6F9D84E102F6F18105F391D9BD296F965C6ED5, InputAnimation_EvaluateCameraPose_mA06BC7691D681CC6011970B06FE85F4F21CCD21E, InputAnimation_EvaluateHandJoint_mB1BD9144BE8F3D891476E898375AAFD78FB1DA82, InputAnimation_EvaluateEyeGaze_m8397D5795457BF023BA7902F2EE11F28F529048F, InputAnimation_GetMarker_mB89D4AB46775D392411E517D0BCB7B4D46607D24, InputAnimation_FromRecordingBuffer_mFC1695424E73459B9C12D60511DC7BF026FACFFB, InputAnimation_FromStream_m58694E2590699E9E2833A0971FFB55476FC18047, InputAnimation_FromStreamAsync_m92C92138D59E7F5CB0E815D381BC4F72FED66E79, InputAnimation_AddHandStateKey_m8FC218057E46653BA5F8DA3F20EDD26F0867BA7D, InputAnimation_AddHandJointKey_mFBEFB300645E6981C38076FE4A3570BE9DFE680C, InputAnimation_CutoffBeforeTime_m40F36C19E530FD5D1310DD80D9C48A30F3C62C13, InputAnimation_CreateHandJointCurves_mDF0FEA0053141B9153AA26F8BBF35A510A433910, InputAnimation_TryGetHandJointCurves_m6CBE945EF12A959ECB1EE378688BDD6D9CA9C22B, InputAnimation_ComputeDuration_m67F8213261EB8A04522E0253A305B6DF519656C0, InputAnimation_Optimize_m85E61983DE15A609A9EA67796ABD073AE0487D27, InputAnimation_EvaluateHandState_m9F6A2CF5B5F1956187790199ADD608B1CB7FAE36, InputAnimation_EvaluateHandJoint_mB902B76C54C7A11773A9E1F2D78F10E299F90FC3, InputAnimation_GetAllAnimationCurves_mF2A00A8A89378A02AA213F26B7D2B0EF869AB526, InputAnimation_AddBoolKey_mC23D7530D31F64BC0E187FCCBDD8E5F3AB61199D, InputAnimation_AddFloatKey_mD316869BF5B620AC0A6E57A534F3906947D7C78B, InputAnimation_AddVectorKey_m0444BC9E945FD7596352081B54E64641AE89EA65, InputAnimation_AddPoseKeyFiltered_mE9D95FC2C157B85DFFFDD955C8EAF0F409108705, InputAnimation_AddPositionKeyFiltered_mB6B10598350F551860641100303803CADC08019C, InputAnimation_AddRotationKeyFiltered_m1B9E7C65999003864023597551742DC2947AB966, InputAnimation_PoseCurvesToStream_mC892445DA1552CB7D395FFA0CFFA5FC8970D18E2, InputAnimation_PoseCurvesFromStream_m67BDC1499A27777D1A196E715B799432AEED50E4, InputAnimation_RayCurvesToStream_mE59C067DC66E85F627C683EA78B0F22E75DE551F, InputAnimation_RayCurvesFromStream_m2BA8BA802AF250E41613B9310C7F5CC20DC99BDD, InputAnimation_OptimizePositionCurve_m1C7279C913A4A8B6BDBD039F3F4BCA1938A70014, InputAnimation_OptimizeDirectionCurve_mC560CC7A7D51649389102405C191CE68838CD6EA, InputAnimation_OptimizeRotationCurve_m5FFF80C6581D8513DB63F15824956A43E1EF8EFA, InputAnimation_AddBoolKeyFiltered_m39AB9D96F272BFCCEE6FFE6FDC5B67404F6C8D75, InputAnimation_FindKeyframeInterval_m973AD87553EEEDFBAC0EECBB15A1BBEC5EC85463, InputAnimation_U3CFromRecordingBufferU3Eg__AddBoolKeyIfChangedU7C47_0_mECF0AE0F90A09339B9B85571E7D79CF032E5FD5D, InputAnimation_U3CFromRecordingBufferU3Eg__AddJointPoseKeysU7C47_1_m4451B5CFCFB77EFC71B2F207FCEFDE2C92AC4554, InputAnimation_U3COptimizePositionCurveU3Eg__RecurseU7C70_0_m4FCE53B2AF6FF132C505DDD0B15A7D94DDE88330, InputAnimation_U3COptimizeDirectionCurveU3Eg__RecurseU7C71_0_m3A4ECBAE6874B641DCF0EC87A2A3A909C0E61F08, InputAnimation_U3COptimizeRotationCurveU3Eg__RecurseU7C72_0_m5C029920E1D8F76390A604EAE425EC3E7B3F30C1, PoseCurves_AddKey_m09FBA52357C8BD9ADE0ACB11B9A1738F75FE3038, PoseCurves_Optimize_mC0CF1C42C12C941ECD5913217E69A47876235A42, PoseCurves_Evaluate_m65B8ABBF072CE1FD5A59859361DB9F3FFF70816D, PoseCurves__ctor_mF5A11EC505433BE0BE40D61E6F28FD648919471F, RayCurves_AddKey_m51FCF0A127416BBB7708CD5EC608CFF5C6B24C6D, RayCurves_Optimize_m5FFB2912CDBE6CF5B6451A3855E7B656190C6F16, RayCurves_Evaluate_mC0E941F7484A969BD24DE6729769EB028C093427, RayCurves__ctor_m461CFADEE509565D400DFFACA11DA7779CBC23D9, CompareMarkers_Compare_m0FE15C6ACBD37151C55A6C49576FD6B1B4363634, CompareMarkers__ctor_m6C6ED2992996361CF100D40ECBE0EF83A05ED469, U3CU3Ec__DisplayClass40_0__ctor_mFF979788CF100A28885C84D53D9A940DB44B3628, U3CU3Ec__DisplayClass40_0_U3CToStreamAsyncU3Eb__0_m9E9FA98530439EB22B8110458663086A795215C5, U3CToStreamAsyncU3Ed__40_MoveNext_mC9376548261F29A0D9E8AA0EBAD712C926BF3CC0, U3CToStreamAsyncU3Ed__40_SetStateMachine_mCA51EC800CAE3DD1C411325421E00CA1FA5166B0, U3CU3Ec__DisplayClass49_0__ctor_m592097E35D589AE4623C89BF6C19584E9D53191B, U3CU3Ec__DisplayClass49_0_U3CFromStreamAsyncU3Eb__0_mC707FA6AF9364676DBA368E1B7D22FE274091D79, U3CFromStreamAsyncU3Ed__49_MoveNext_m7D7DA4E8D9027AF8E79F171C68B6EECBE9481D72, U3CFromStreamAsyncU3Ed__49_SetStateMachine_mF5170AEEB1D677B504C47ACF30936D6D8F2994BB, U3CGetAllAnimationCurvesU3Ed__59__ctor_mD56390198BBCFC27B1D5535EE05A5208E9C06006, U3CGetAllAnimationCurvesU3Ed__59_System_IDisposable_Dispose_mBA4F4E744D6C57D3703181DC93A29C4C4394ECF3, U3CGetAllAnimationCurvesU3Ed__59_MoveNext_mD2DC953413FF5B501BAF75C850ADE71C2968D332, U3CGetAllAnimationCurvesU3Ed__59_U3CU3Em__Finally1_mACC6134AC770062B5F535280A4E21947A90DA644, U3CGetAllAnimationCurvesU3Ed__59_U3CU3Em__Finally2_m3650B7BFCBBEED6A68AE5B66E6FBE0FC0362D087, U3CGetAllAnimationCurvesU3Ed__59_System_Collections_Generic_IEnumeratorU3CUnityEngine_AnimationCurveU3E_get_Current_mD8304B6C7B97F85A1E1DEEB8E8270ADBEFCC85AD, U3CGetAllAnimationCurvesU3Ed__59_System_Collections_IEnumerator_Reset_m4DD4534813AFB13266C389DC17E804C024D8731B, U3CGetAllAnimationCurvesU3Ed__59_System_Collections_IEnumerator_get_Current_mB4629844BED1ADD825FCC902D8BFDE61F35F4087, U3CGetAllAnimationCurvesU3Ed__59_System_Collections_Generic_IEnumerableU3CUnityEngine_AnimationCurveU3E_GetEnumerator_mFF3CCDF749456180BF6142C15FAFABED75A221D1, U3CGetAllAnimationCurvesU3Ed__59_System_Collections_IEnumerable_GetEnumerator_mF62033E59E615E5025239271EF8846E8A5337A13, InputAnimationSerializationUtils_GetOutputFilename_m48043CA922AD0E73716B4B372164011C16861447, InputAnimationSerializationUtils_WriteHeader_m2414DA896B37BC54609C00103BEE490CA2D8316D, InputAnimationSerializationUtils_ReadHeader_m80B6BD0DB5D55A9CAB5B2DE5246D393E6A42C6A4, InputAnimationSerializationUtils_WriteFloatCurve_m60A294A3D4EAFDD5D08D3DD48D9E790359BE4A09, InputAnimationSerializationUtils_ReadFloatCurve_m536D99B4BBD3AF6F85957E8797E7709F3C7B3336, InputAnimationSerializationUtils_WriteBoolCurve_m353A2B25C74AD3D8A7F02A0713D8C9CC6774C818, InputAnimationSerializationUtils_ReadBoolCurve_m719C4C1FE043E675E12DF34876B702269A800659, InputAnimationSerializationUtils_WriteFloatCurveSimple_mFF68DD534C0F4FCEEF7E0285DF335143E9A78DE7, InputAnimationSerializationUtils_ReadFloatCurveSimple_mE35C73CE457EA91F2145578650E7EA2FD1D29D05, InputAnimationSerializationUtils_WriteFloatCurveArray_m81B5F3BCBFA462C1D7534A3CC9736541C0FC6B67, InputAnimationSerializationUtils_ReadFloatCurveArray_m869E5D7D663B5AA9F598A605EC142AE5FDA8E6ED, InputAnimationSerializationUtils_WriteBoolCurveArray_mA9D1F2ECD040D62E29CB7891CC8503859B35826A, InputAnimationSerializationUtils_ReadBoolCurveArray_m3FAC0C7D26FB67C78FCB9E259DADCE3E63889B4B, InputAnimationSerializationUtils_WriteMarkerList_m2F6970C7A59295395738A66B4A928698780D1649, InputAnimationSerializationUtils_ReadMarkerList_m5DDE2D3265ADF882584FB2561B21AF9736BD6D56, InputRecordingBuffer_get_StartTime_m4DA0D9853D7D89ACED044112F8A167EE3B3F1935, InputRecordingBuffer__ctor_m43A00F4F39E27085CA2C8B91921EBB23150C9C76, InputRecordingBuffer_Clear_mCC22BFBC36EDE5E899D57C80D0F6C57BD05C57B9, InputRecordingBuffer_RemoveBeforeTime_mFF897B9D56D694C3FF7B239EBED1CBB2FF7DE1EE, InputRecordingBuffer_SetCameraPose_m68DEF44DE167F57BADC4C476F231A7BB3726B4C0, InputRecordingBuffer_SetGazeRay_mA00F2164D715DBAA1597B1DC61C0786DE84252E6, InputRecordingBuffer_SetHandState_m8D7F1CEF1AB0B57E3A8CA44E96CAA870B9D03600, InputRecordingBuffer_SetJointPose_m5B85A418454EAB63BF31181A75025BF4410FF502, InputRecordingBuffer_NewKeyframe_m196CC0276D1D4FF940DF8E2352C5FB7A7FD5EF11, InputRecordingBuffer_GetEnumerator_mC16F9FA32FBB1E1E1D8FE9FDFFBBB6EC47C225E7, InputRecordingBuffer_System_Collections_IEnumerable_GetEnumerator_mC30CB396868C387007298A038416AFEB34A84B93, Keyframe_get_Time_m5A94321ED895DA4719F6AECB6FFCAFD4CFE81C18, Keyframe_set_Time_m5BF4E2967A1949C46D73C5E9899E43438A7F7674, Keyframe_get_LeftTracked_mC028E832EF357A6D35848E5A0D92FC203356984B, Keyframe_set_LeftTracked_m195D1C9B70DE1C52E33F7E1452D817969018E9FC, Keyframe_get_RightTracked_mD7CF7BC3BA431D972F6F83AE9CECA15EA8D76569, Keyframe_set_RightTracked_mCDFA0F3628EF01C0593B0FC84509350B80FE2A16, Keyframe_get_LeftPinch_m26B6CA55F56E45AF12B6C6EB92F070B7C404C3B4, Keyframe_set_LeftPinch_m7D15C79E632EF8AC24E5D3491383544F8B77AEEB, Keyframe_get_RightPinch_m5D7DC4C2A2623511F1ED05AFDAEA29261DCFFD41, Keyframe_set_RightPinch_m3D30DE7BC5A4743D627A4FA63164AAAE4EAC9C6F, Keyframe_get_CameraPose_m16D2BA3112660DEC614E4E7D3D1D105EFE6C7595, Keyframe_set_CameraPose_mB3BCF1A2A1699020C2BC399F488977652447055C, Keyframe_get_GazeRay_mB578916EE0B0905F66C7DA537AA88266B02E7847, Keyframe_set_GazeRay_mBB00243C934D3AF4BE3E9E3461EF1D53B48D7AAF, Keyframe_get_LeftJoints_m6FA28C62D4A75A4CB545C1CCBE1CB9DEDC7DE96B, Keyframe_set_LeftJoints_mF9EF11D4505A2AFAF484C450B254A5F92627AC6B, Keyframe_get_RightJoints_m5E3998C352E7BEC081AE82800F2D0A8858E304C9, Keyframe_set_RightJoints_mF4D49C1C8915A04A771672EC42BDBAC23D4985B8, Keyframe__ctor_m91F47F5A8B680109F9887BA004DC4DCDA27CE6CA, InputRecordingService_add_OnRecordingStarted_m59AFC7A494D7D15837309A3E7F1D650449643C4A, InputRecordingService_remove_OnRecordingStarted_m56FB17804146C59B2C97CC4623A45194F0D73DEB, InputRecordingService_add_OnRecordingStopped_mFF85EB8C5B7F742B736DB2AC1F273B7E85F212F1, InputRecordingService_remove_OnRecordingStopped_m684CAFA134D88BE02BD291AB5B5D4EB8C0DF8708, InputRecordingService_get_IsRecording_mABDF25EEF3633FD960D47773D6F9AA4C346E212D, InputRecordingService_set_IsRecording_m4F3DB5352CA6A00A3575A110A2EA55ACF2B73722, InputRecordingService_get_UseBufferTimeLimit_m28B8409B14A29B84B66D3F85FF9B9FEF5E7FC2B9, InputRecordingService_set_UseBufferTimeLimit_m9D197D9EADE7342688D045A14E07021C628CB871, InputRecordingService_get_RecordingBufferTimeLimit_mB2EAF047708A84CB548579FA9E6B826F6F966F07, InputRecordingService_set_RecordingBufferTimeLimit_m2B5F3C1C3026E477903FCC78C0F79C67933CF073, InputRecordingService_get_StartTime_mCD8C83EB5DB55DBD240A30F1F00FCDA30A3A6995, InputRecordingService_get_EndTime_m946DC951E5887DCD4E4FB77C4C60A8C69280197B, InputRecordingService_set_EndTime_m6AF7B853301EE3481BA416768D27DB973D37D1C8, InputRecordingService_get_InputRecordingProfile_mF145CA8FDFF06282142B6E5F811F4609F6BFE785, InputRecordingService_set_InputRecordingProfile_m39FFB6DB54D7AC64A3303ED8810B167E5E1E1C86, InputRecordingService__ctor_m0A32145DDE791E1C6CA36F9DCBC4B1211DB6E6B9, InputRecordingService__ctor_mF036AEEFABF6BD0CED7101E97017C66693B0D41F, InputRecordingService_Enable_m6FAB8C32295F118364CA14A7F7361265D654436F, InputRecordingService_Disable_m7F57ED51D6707D2ECDA2E698304B945709C3BCD2, InputRecordingService_StartRecording_m8AC2ECF61E4B8BAAC0BFCB5A6C838786FF9C5BC8, InputRecordingService_StopRecording_mB6365DA27CE3C222E30371EACA7048F72EF93E51, InputRecordingService_LateUpdate_m4B70FB672C8D6E23B407BF8EC98D5FA3702321E0, InputRecordingService_DiscardRecordedInput_m25B81E3DB1D2B2A1F8C959172F9FC9E426D7CF1E, InputRecordingService_SaveInputAnimation_mC11C0F6A14E38BF6565B584501FC5EE8F7419647, InputRecordingService_SaveInputAnimation_mAB2F869F8DDFEB676413561C1FB5B0730B7EB0BF, InputRecordingService_SaveInputAnimationAsync_m049195AE43D197BF5D947087191ECA0CBF3BA8CA, InputRecordingService_SaveInputAnimationAsync_m7B31EE97B36838944CDF324D297C26B4468F280A, InputRecordingService_ResetStartTime_m3B6E3EE5518C1F18353CDC1DF3214108285BC634, InputRecordingService_RecordKeyframe_mC9AD4872D1DFE3D696A93DE5DC5C583240E7D60C, InputRecordingService_RecordInputHandData_m8046EA2D6BC0D855E08A4B49852CF87B1F23F9C7, InputRecordingService_PruneBuffer_m7E3C4CF8CFC725648DA14B89E04C5F45A0EFB1F0, InputRecordingService_U3CSaveInputAnimationAsyncU3Eb__44_0_mC10DCB1B893639E18830A3839E093A7D778BBBBF, U3CSaveInputAnimationAsyncU3Ed__44_MoveNext_m9FCC9D4EE34F903B251DFC9267DEB1FAE4B7A645, U3CSaveInputAnimationAsyncU3Ed__44_SetStateMachine_mDB2BD0422C6211FB1D2D8D184AF469F304649666, MixedRealityInputRecordingProfile_get_FrameRate_m86BDF5FC09CB89D3C1071FA6FDA5A9FFA4D36814, MixedRealityInputRecordingProfile_get_RecordHandData_mD9E60E20D10052B4FA1C702D2BD40C52DEF2F9E2, MixedRealityInputRecordingProfile_get_JointPositionThreshold_m4349A57473BF6EF8DC6932C0F0D0796532FD7E6A, MixedRealityInputRecordingProfile_get_JointRotationThreshold_mB05FA5B9F2F05BAD0653B4D2BD850CD77463062C, MixedRealityInputRecordingProfile_get_RecordCameraPose_m87161149954A3AAC9BB498A7F257F408F0C56439, MixedRealityInputRecordingProfile_get_CameraPositionThreshold_m8DCEA0EAD8EF61331ACE8CD34729515A08B04492, MixedRealityInputRecordingProfile_get_CameraRotationThreshold_m5D95FE8ECA5F39427B931880735EDC99DAC11A4A, MixedRealityInputRecordingProfile_get_RecordEyeGaze_m87FFB44F45765DBC69E92DFA72020C6C55B00215, MixedRealityInputRecordingProfile_get_EyeGazeOriginThreshold_m456FB459A70D07867EBBCB771AFA8BF82E00FE49, MixedRealityInputRecordingProfile_get_EyeGazeDirectionThreshold_m73CCF70F4EA8C58E0023B4B373F938BE6757F3D5, MixedRealityInputRecordingProfile_get_PartitionSize_m0E85FBE1B9C167763298CFB08FF66B3B140D4BE4, MixedRealityInputRecordingProfile__ctor_m0C84199A4E420F20EE9BB2307DEAB3E8910D877A, }; extern void U3CToStreamAsyncU3Ed__40_MoveNext_mC9376548261F29A0D9E8AA0EBAD712C926BF3CC0_AdjustorThunk (void); extern void U3CToStreamAsyncU3Ed__40_SetStateMachine_mCA51EC800CAE3DD1C411325421E00CA1FA5166B0_AdjustorThunk (void); extern void U3CFromStreamAsyncU3Ed__49_MoveNext_m7D7DA4E8D9027AF8E79F171C68B6EECBE9481D72_AdjustorThunk (void); extern void U3CFromStreamAsyncU3Ed__49_SetStateMachine_mF5170AEEB1D677B504C47ACF30936D6D8F2994BB_AdjustorThunk (void); extern void U3CSaveInputAnimationAsyncU3Ed__44_MoveNext_m9FCC9D4EE34F903B251DFC9267DEB1FAE4B7A645_AdjustorThunk (void); extern void U3CSaveInputAnimationAsyncU3Ed__44_SetStateMachine_mDB2BD0422C6211FB1D2D8D184AF469F304649666_AdjustorThunk (void); static Il2CppTokenAdjustorThunkPair s_adjustorThunks[6] = { { 0x06000054, U3CToStreamAsyncU3Ed__40_MoveNext_mC9376548261F29A0D9E8AA0EBAD712C926BF3CC0_AdjustorThunk }, { 0x06000055, U3CToStreamAsyncU3Ed__40_SetStateMachine_mCA51EC800CAE3DD1C411325421E00CA1FA5166B0_AdjustorThunk }, { 0x06000058, U3CFromStreamAsyncU3Ed__49_MoveNext_m7D7DA4E8D9027AF8E79F171C68B6EECBE9481D72_AdjustorThunk }, { 0x06000059, U3CFromStreamAsyncU3Ed__49_SetStateMachine_mF5170AEEB1D677B504C47ACF30936D6D8F2994BB_AdjustorThunk }, { 0x060000B1, U3CSaveInputAnimationAsyncU3Ed__44_MoveNext_m9FCC9D4EE34F903B251DFC9267DEB1FAE4B7A645_AdjustorThunk }, { 0x060000B2, U3CSaveInputAnimationAsyncU3Ed__44_SetStateMachine_mDB2BD0422C6211FB1D2D8D184AF469F304649666_AdjustorThunk }, }; static const int32_t s_InvokerIndices[190] = { 3747, 3747, 3069, 3865, 3186, 3895, 3895, 3895, 2817, 1405, 2817, 1405, 3895, 3865, 3747, 3069, 3747, 3069, 3747, 3069, 3793, 3895, 689, 155, 691, 3155, 3120, 1682, 3895, 3186, 1802, 868, 688, 2676, 2801, 822, 2849, 2813, 5188, 5599, 5188, 276, 156, 1802, 1386, 718, 3895, 3155, 277, 823, 3829, 4921, 4922, 4331, 4333, 4133, 4060, 4916, 4911, 4916, 4911, 4289, 4289, 4117, 4702, 5103, 4921, 4587, 4881, 4881, 4881, 1825, 1069, 2801, 3895, 1827, 1069, 2849, 3895, 1288, 3895, 3895, 3895, 3895, 3155, 3895, 3829, 3895, 3155, 3120, 3895, 3747, 3895, 3895, 3829, 3895, 3829, 3829, 3829, 5180, 5732, 4899, 4916, 5361, 4916, 5361, 4916, 5361, 4916, 5361, 4916, 5361, 4916, 5361, 3865, 3895, 3895, 3186, 3149, 3170, 949, 955, 2676, 3829, 3829, 3865, 3186, 3747, 3069, 3747, 3069, 3747, 3069, 3747, 3069, 3824, 3149, 3844, 3170, 3829, 3155, 3829, 3155, 3186, 3155, 3155, 3155, 3155, 3747, 3069, 3747, 3069, 3865, 3186, 3865, 3865, 3186, 3829, 3155, 268, 678, 3895, 3895, 3895, 3895, 3895, 3895, 2817, 1405, 2817, 1405, 3895, 3895, 3069, 3895, 3829, 3895, 3155, 3865, 3747, 3865, 3865, 3747, 3865, 3865, 3747, 3865, 3865, 3793, 3895, }; extern const CustomAttributesCacheGenerator g_Microsoft_MixedReality_Toolkit_Services_InputAnimation_AttributeGenerators[]; IL2CPP_EXTERN_C const Il2CppCodeGenModule g_Microsoft_MixedReality_Toolkit_Services_InputAnimation_CodeGenModule; const Il2CppCodeGenModule g_Microsoft_MixedReality_Toolkit_Services_InputAnimation_CodeGenModule = { "Microsoft.MixedReality.Toolkit.Services.InputAnimation.dll", 190, s_methodPointers, 6, s_adjustorThunks, s_InvokerIndices, 0, NULL, 0, NULL, 0, NULL, NULL, g_Microsoft_MixedReality_Toolkit_Services_InputAnimation_AttributeGenerators, NULL, // module initializer, NULL, NULL, NULL, };
81.855019
516
0.901691
[ "object" ]
63c50651dcea11d0d8fb72f91a3df62ba179bcc1
1,758
h
C
EVE/EveDet/AliEveMUONData.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
52
2016-12-11T13:04:01.000Z
2022-03-11T11:49:35.000Z
EVE/EveDet/AliEveMUONData.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
1,388
2016-11-01T10:27:36.000Z
2022-03-30T15:26:09.000Z
EVE/EveDet/AliEveMUONData.h
AllaMaevskaya/AliRoot
c53712645bf1c7d5f565b0d3228e3a6b9b09011a
[ "BSD-3-Clause" ]
275
2016-06-21T20:24:05.000Z
2022-03-31T13:06:19.000Z
// $Id$ // Main authors: Matevz Tadel & Alja Mrak-Tadel & Bogdan Vulpescu: 2006, 2007 /************************************************************************** * Copyright(c) 1998-2008, ALICE Experiment at CERN, all rights reserved. * * See http://aliceinfo.cern.ch/Offline/AliRoot/License.html for * * full copyright notice. * **************************************************************************/ #ifndef AliEveMUONData_H #define AliEveMUONData_H #include <TEveUtil.h> #include <TObject.h> #include <vector> class TTree; class TString; class AliRawReader; class AliEveMUONChamberData; class AliEveMUONData : public TObject, public TEveRefCnt { public: AliEveMUONData(); virtual ~AliEveMUONData(); AliEveMUONData(const AliEveMUONData&); AliEveMUONData& operator=(const AliEveMUONData&); void Reset(); void LoadDigits(TTree* tree); void LoadRecPoints(TTree* tree); void LoadRecPointsFromESD(const Char_t *fileName); void LoadHits(TTree* tree); void LoadRaw(TString fileName); void CreateChamber(Int_t chamber); void CreateAllChambers(); void DropAllChambers(); void DeleteAllChambers(); void RegisterTrack(Int_t track); Int_t GetNTrackList() const { return fNTrackList; } Int_t GetTrack(Int_t index) const; AliEveMUONChamberData* GetChamberData(Int_t chamber); protected: std::vector<AliEveMUONChamberData*> fChambers; // vector of 14 chambers static AliRawReader *fgRawReader; // raw reader Int_t fNTrackList; // number of MC tracks which have hits Int_t fTrackList[256]; // list of MC tracks which have hits ClassDef(AliEveMUONData, 0); // Manages MUON data for one event }; #endif
25.852941
77
0.641638
[ "vector" ]
63c90b8950e5a7055d2bf840fc41a55a66c8313a
19,356
c
C
Modules/cdmodule.c
AtjonTV/Python-1.4
2a80562c5a163490f444181cb75ca1b3089759ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
Modules/cdmodule.c
AtjonTV/Python-1.4
2a80562c5a163490f444181cb75ca1b3089759ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
Modules/cdmodule.c
AtjonTV/Python-1.4
2a80562c5a163490f444181cb75ca1b3089759ec
[ "Unlicense", "TCL", "DOC", "AAL", "X11" ]
null
null
null
/********************************************************** Copyright 1991-1995 by Stichting Mathematisch Centrum, Amsterdam, The Netherlands. All Rights Reserved Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the names of Stichting Mathematisch Centrum or CWI or Corporation for National Research Initiatives or CNRI not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. While CWI is the initial source for this software, a modified version is made available by the Corporation for National Research Initiatives (CNRI) at the Internet address ftp://ftp.python.org. STICHTING MATHEMATISCH CENTRUM AND CNRI DISCLAIM ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL STICHTING MATHEMATISCH CENTRUM OR CNRI BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. ******************************************************************/ /* CD module -- interface to Mark Callow's and Roger Chickering's */ /* CD Audio Library (CD). */ #include <sys/types.h> #include <cdaudio.h> /* #include <sigfpe.h> */ #include "allobjects.h" #include "import.h" #include "modsupport.h" #include "ceval.h" #define NCALLBACKS 8 typedef struct { OB_HEAD CDPLAYER *ob_cdplayer; } cdplayerobject; static object *CdError; /* exception cd.error */ static object * CD_allowremoval(self, args) cdplayerobject *self; object *args; { if (!newgetargs(args, "")) return NULL; CDallowremoval(self->ob_cdplayer); INCREF(None); return None; } static object * CD_preventremoval(self, args) cdplayerobject *self; object *args; { if (!newgetargs(args, "")) return NULL; CDpreventremoval(self->ob_cdplayer); INCREF(None); return None; } static object * CD_bestreadsize(self, args) cdplayerobject *self; object *args; { if (!newgetargs(args, "")) return NULL; return newintobject((long) CDbestreadsize(self->ob_cdplayer)); } static object * CD_close(self, args) cdplayerobject *self; object *args; { if (!newgetargs(args, "")) return NULL; if (!CDclose(self->ob_cdplayer)) { err_errno(CdError); /* XXX - ??? */ return NULL; } self->ob_cdplayer = NULL; INCREF(None); return None; } static object * CD_eject(self, args) cdplayerobject *self; object *args; { CDSTATUS status; if (!newgetargs(args, "")) return NULL; if (!CDeject(self->ob_cdplayer)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "eject failed"); return NULL; } INCREF(None); return None; } static object * CD_getstatus(self, args) cdplayerobject *self; object *args; { CDSTATUS status; if (!newgetargs(args, "")) return NULL; if (!CDgetstatus(self->ob_cdplayer, &status)) { err_errno(CdError); /* XXX - ??? */ return NULL; } return mkvalue("(ii(iii)(iii)(iii)iiii)", status.state, status.track, status.min, status.sec, status.frame, status.abs_min, status.abs_sec, status.abs_frame, status.total_min, status.total_sec, status.total_frame, status.first, status.last, status.scsi_audio, status.cur_block); } static object * CD_gettrackinfo(self, args) cdplayerobject *self; object *args; { int track; CDTRACKINFO info; CDSTATUS status; if (!newgetargs(args, "i", &track)) return NULL; if (!CDgettrackinfo(self->ob_cdplayer, track, &info)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "gettrackinfo failed"); return NULL; } return mkvalue("((iii)(iii))", info.start_min, info.start_sec, info.start_frame, info.total_min, info.total_sec, info.total_frame); } static object * CD_msftoblock(self, args) cdplayerobject *self; object *args; { int min, sec, frame; if (!newgetargs(args, "iii", &min, &sec, &frame)) return NULL; return newintobject((long) CDmsftoblock(self->ob_cdplayer, min, sec, frame)); } static object * CD_play(self, args) cdplayerobject *self; object *args; { int start, play; CDSTATUS status; if (!newgetargs(args, "ii", &start, &play)) return NULL; if (!CDplay(self->ob_cdplayer, start, play)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "play failed"); return NULL; } INCREF(None); return None; } static object * CD_playabs(self, args) cdplayerobject *self; object *args; { int min, sec, frame, play; CDSTATUS status; if (!newgetargs(args, "iiii", &min, &sec, &frame, &play)) return NULL; if (!CDplayabs(self->ob_cdplayer, min, sec, frame, play)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "playabs failed"); return NULL; } INCREF(None); return None; } static object * CD_playtrack(self, args) cdplayerobject *self; object *args; { int start, play; CDSTATUS status; if (!newgetargs(args, "ii", &start, &play)) return NULL; if (!CDplaytrack(self->ob_cdplayer, start, play)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "playtrack failed"); return NULL; } INCREF(None); return None; } static object * CD_playtrackabs(self, args) cdplayerobject *self; object *args; { int track, min, sec, frame, play; CDSTATUS status; if (!newgetargs(args, "iiiii", &track, &min, &sec, &frame, &play)) return NULL; if (!CDplaytrackabs(self->ob_cdplayer, track, min, sec, frame, play)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "playtrackabs failed"); return NULL; } INCREF(None); return None; } static object * CD_readda(self, args) cdplayerobject *self; object *args; { int numframes, n; object *result; if (!newgetargs(args, "i", &numframes)) return NULL; result = newsizedstringobject(NULL, numframes * sizeof(CDFRAME)); if (result == NULL) return NULL; n = CDreadda(self->ob_cdplayer, (CDFRAME *) getstringvalue(result), numframes); if (n == -1) { DECREF(result); err_errno(CdError); return NULL; } if (n < numframes) if (resizestring(&result, n * sizeof(CDFRAME))) return NULL; return result; } static object * CD_seek(self, args) cdplayerobject *self; object *args; { int min, sec, frame; long block; if (!newgetargs(args, "iii", &min, &sec, &frame)) return NULL; block = CDseek(self->ob_cdplayer, min, sec, frame); if (block == -1) { err_errno(CdError); return NULL; } return newintobject(block); } static object * CD_seektrack(self, args) cdplayerobject *self; object *args; { int track; long block; if (!newgetargs(args, "i", &track)) return NULL; block = CDseektrack(self->ob_cdplayer, track); if (block == -1) { err_errno(CdError); return NULL; } return newintobject(block); } static object * CD_seekblock(self, args) cdplayerobject *self; object *args; { unsigned long block; if (!newgetargs(args, "l", &block)) return NULL; block = CDseekblock(self->ob_cdplayer, block); if (block == (unsigned long) -1) { err_errno(CdError); return NULL; } return newintobject(block); } static object * CD_stop(self, args) cdplayerobject *self; object *args; { CDSTATUS status; if (!newgetargs(args, "")) return NULL; if (!CDstop(self->ob_cdplayer)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "stop failed"); return NULL; } INCREF(None); return None; } static object * CD_togglepause(self, args) cdplayerobject *self; object *args; { CDSTATUS status; if (!newgetargs(args, "")) return NULL; if (!CDtogglepause(self->ob_cdplayer)) { if (CDgetstatus(self->ob_cdplayer, &status) && status.state == CD_NODISC) err_setstr(CdError, "no disc in player"); else err_setstr(CdError, "togglepause failed"); return NULL; } INCREF(None); return None; } static struct methodlist cdplayer_methods[] = { {"allowremoval", (method)CD_allowremoval, 1}, {"bestreadsize", (method)CD_bestreadsize, 1}, {"close", (method)CD_close, 1}, {"eject", (method)CD_eject, 1}, {"getstatus", (method)CD_getstatus, 1}, {"gettrackinfo", (method)CD_gettrackinfo, 1}, {"msftoblock", (method)CD_msftoblock, 1}, {"play", (method)CD_play, 1}, {"playabs", (method)CD_playabs, 1}, {"playtrack", (method)CD_playtrack, 1}, {"playtrackabs", (method)CD_playtrackabs, 1}, {"preventremoval", (method)CD_preventremoval, 1}, {"readda", (method)CD_readda, 1}, {"seek", (method)CD_seek, 1}, {"seekblock", (method)CD_seekblock, 1}, {"seektrack", (method)CD_seektrack, 1}, {"stop", (method)CD_stop, 1}, {"togglepause", (method)CD_togglepause, 1}, {NULL, NULL} /* sentinel */ }; static void cdplayer_dealloc(self) cdplayerobject *self; { if (self->ob_cdplayer != NULL) CDclose(self->ob_cdplayer); DEL(self); } static object * cdplayer_getattr(self, name) cdplayerobject *self; char *name; { if (self->ob_cdplayer == NULL) { err_setstr(RuntimeError, "no player active"); return NULL; } return findmethod(cdplayer_methods, (object *)self, name); } typeobject CdPlayertype = { OB_HEAD_INIT(&Typetype) 0, /*ob_size*/ "cdplayer", /*tp_name*/ sizeof(cdplayerobject), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ (destructor)cdplayer_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)cdplayer_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ }; static object * newcdplayerobject(cdp) CDPLAYER *cdp; { cdplayerobject *p; p = NEWOBJ(cdplayerobject, &CdPlayertype); if (p == NULL) return NULL; p->ob_cdplayer = cdp; return (object *) p; } static object * CD_open(self, args) object *self, *args; { char *dev, *direction; CDPLAYER *cdp; /* * Variable number of args. * First defaults to "None", second defaults to "r". */ dev = NULL; direction = "r"; if (!newgetargs(args, "|zs", &dev, &direction)) return NULL; cdp = CDopen(dev, direction); if (cdp == NULL) { err_errno(CdError); return NULL; } return newcdplayerobject(cdp); } typedef struct { OB_HEAD CDPARSER *ob_cdparser; struct { object *ob_cdcallback; object *ob_cdcallbackarg; } ob_cdcallbacks[NCALLBACKS]; } cdparserobject; static void CD_callback(arg, type, data) void *arg; CDDATATYPES type; void *data; { object *result, *args, *v; char *p; int i; cdparserobject *self; self = (cdparserobject *) arg; args = newtupleobject(3); if (args == NULL) return; INCREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); settupleitem(args, 0, self->ob_cdcallbacks[type].ob_cdcallbackarg); settupleitem(args, 1, newintobject((long) type)); switch (type) { case cd_audio: v = newsizedstringobject(data, CDDA_DATASIZE); break; case cd_pnum: case cd_index: v = newintobject(((CDPROGNUM *) data)->value); break; case cd_ptime: case cd_atime: #define ptr ((struct cdtimecode *) data) v = mkvalue("(iii)", ptr->mhi * 10 + ptr->mlo, ptr->shi * 10 + ptr->slo, ptr->fhi * 10 + ptr->flo); #undef ptr break; case cd_catalog: v = newsizedstringobject(NULL, 13); p = getstringvalue(v); for (i = 0; i < 13; i++) *p++ = ((char *) data)[i] + '0'; break; case cd_ident: #define ptr ((struct cdident *) data) v = newsizedstringobject(NULL, 12); p = getstringvalue(v); CDsbtoa(p, ptr->country, 2); p += 2; CDsbtoa(p, ptr->owner, 3); p += 3; *p++ = ptr->year[0] + '0'; *p++ = ptr->year[1] + '0'; *p++ = ptr->serial[0] + '0'; *p++ = ptr->serial[1] + '0'; *p++ = ptr->serial[2] + '0'; *p++ = ptr->serial[3] + '0'; *p++ = ptr->serial[4] + '0'; #undef ptr break; case cd_control: v = newintobject((long) *((unchar *) data)); break; } settupleitem(args, 2, v); if (err_occurred()) { DECREF(args); return; } result = call_object(self->ob_cdcallbacks[type].ob_cdcallback, args); DECREF(args); XDECREF(result); } static object * CD_deleteparser(self, args) cdparserobject *self; object *args; { int i; if (!newgetargs(args, "")) return NULL; CDdeleteparser(self->ob_cdparser); self->ob_cdparser = NULL; /* no sense in keeping the callbacks, so remove them */ for (i = 0; i < NCALLBACKS; i++) { XDECREF(self->ob_cdcallbacks[i].ob_cdcallback); self->ob_cdcallbacks[i].ob_cdcallback = NULL; XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg); self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; } INCREF(None); return None; } static object * CD_parseframe(self, args) cdparserobject *self; object *args; { char *cdfp; int length; CDFRAME *p; if (!newgetargs(args, "s#", &cdfp, &length)) return NULL; if (length % sizeof(CDFRAME) != 0) { err_setstr(TypeError, "bad length"); return NULL; } p = (CDFRAME *) cdfp; while (length > 0) { CDparseframe(self->ob_cdparser, p); length -= sizeof(CDFRAME); p++; if (err_occurred()) return NULL; } INCREF(None); return None; } static object * CD_removecallback(self, args) cdparserobject *self; object *args; { int type; if (!newgetargs(args, "i", &type)) return NULL; if (type < 0 || type >= NCALLBACKS) { err_setstr(TypeError, "bad type"); return NULL; } CDremovecallback(self->ob_cdparser, (CDDATATYPES) type); XDECREF(self->ob_cdcallbacks[type].ob_cdcallback); self->ob_cdcallbacks[type].ob_cdcallback = NULL; XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); self->ob_cdcallbacks[type].ob_cdcallbackarg = NULL; INCREF(None); return None; } static object * CD_resetparser(self, args) cdparserobject *self; object *args; { if (!newgetargs(args, "")) return NULL; CDresetparser(self->ob_cdparser); INCREF(None); return None; } static object * CD_addcallback(self, args) cdparserobject *self; object *args; { int type; object *func, *funcarg; /* XXX - more work here */ if (!newgetargs(args, "iOO", &type, &func, &funcarg)) return NULL; if (type < 0 || type >= NCALLBACKS) { err_setstr(TypeError, "argument out of range"); return NULL; } #ifdef CDsetcallback CDaddcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback, (void *) self); #else CDsetcallback(self->ob_cdparser, (CDDATATYPES) type, CD_callback, (void *) self); #endif XDECREF(self->ob_cdcallbacks[type].ob_cdcallback); INCREF(func); self->ob_cdcallbacks[type].ob_cdcallback = func; XDECREF(self->ob_cdcallbacks[type].ob_cdcallbackarg); INCREF(funcarg); self->ob_cdcallbacks[type].ob_cdcallbackarg = funcarg; /* if (type == cd_audio) { sigfpe_[_UNDERFL].repls = _ZERO; handle_sigfpes(_ON, _EN_UNDERFL, NULL, _ABORT_ON_ERROR, NULL); } */ INCREF(None); return None; } static struct methodlist cdparser_methods[] = { {"addcallback", (method)CD_addcallback, 1}, {"deleteparser", (method)CD_deleteparser, 1}, {"parseframe", (method)CD_parseframe, 1}, {"removecallback", (method)CD_removecallback, 1}, {"resetparser", (method)CD_resetparser, 1}, {"setcallback", (method)CD_addcallback, 1}, /* backward compatibility */ {NULL, NULL} /* sentinel */ }; static void cdparser_dealloc(self) cdparserobject *self; { int i; for (i = 0; i < NCALLBACKS; i++) { XDECREF(self->ob_cdcallbacks[i].ob_cdcallback); self->ob_cdcallbacks[i].ob_cdcallback = NULL; XDECREF(self->ob_cdcallbacks[i].ob_cdcallbackarg); self->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; } CDdeleteparser(self->ob_cdparser); DEL(self); } static object * cdparser_getattr(self, name) cdparserobject *self; char *name; { if (self->ob_cdparser == NULL) { err_setstr(RuntimeError, "no parser active"); return NULL; } return findmethod(cdparser_methods, (object *)self, name); } typeobject CdParsertype = { OB_HEAD_INIT(&Typetype) 0, /*ob_size*/ "cdparser", /*tp_name*/ sizeof(cdparserobject), /*tp_size*/ 0, /*tp_itemsize*/ /* methods */ (destructor)cdparser_dealloc, /*tp_dealloc*/ 0, /*tp_print*/ (getattrfunc)cdparser_getattr, /*tp_getattr*/ 0, /*tp_setattr*/ 0, /*tp_compare*/ 0, /*tp_repr*/ }; static object * newcdparserobject(cdp) CDPARSER *cdp; { cdparserobject *p; int i; p = NEWOBJ(cdparserobject, &CdParsertype); if (p == NULL) return NULL; p->ob_cdparser = cdp; for (i = 0; i < NCALLBACKS; i++) { p->ob_cdcallbacks[i].ob_cdcallback = NULL; p->ob_cdcallbacks[i].ob_cdcallbackarg = NULL; } return (object *) p; } static object * CD_createparser(self, args) object *self, *args; { CDPARSER *cdp; if (!newgetargs(args, "")) return NULL; cdp = CDcreateparser(); if (cdp == NULL) { err_setstr(CdError, "createparser failed"); return NULL; } return newcdparserobject(cdp); } static object * CD_msftoframe(self, args) object *self, *args; { int min, sec, frame; if (!newgetargs(args, "iii", &min, &sec, &frame)) return NULL; return newintobject((long) CDmsftoframe(min, sec, frame)); } static struct methodlist CD_methods[] = { {"open", (method)CD_open, 1}, {"createparser", (method)CD_createparser, 1}, {"msftoframe", (method)CD_msftoframe, 1}, {NULL, NULL} /* Sentinel */ }; void initcd() { object *m, *d; m = initmodule("cd", CD_methods); d = getmoduledict(m); CdError = newstringobject("cd.error"); dictinsert(d, "error", CdError); /* Identifiers for the different types of callbacks from the parser */ dictinsert(d, "audio", newintobject((long) cd_audio)); dictinsert(d, "pnum", newintobject((long) cd_pnum)); dictinsert(d, "index", newintobject((long) cd_index)); dictinsert(d, "ptime", newintobject((long) cd_ptime)); dictinsert(d, "atime", newintobject((long) cd_atime)); dictinsert(d, "catalog", newintobject((long) cd_catalog)); dictinsert(d, "ident", newintobject((long) cd_ident)); dictinsert(d, "control", newintobject((long) cd_control)); /* Block size information for digital audio data */ dictinsert(d, "DATASIZE", newintobject((long) CDDA_DATASIZE)); dictinsert(d, "BLOCKSIZE", newintobject((long) CDDA_BLOCKSIZE)); /* Possible states for the cd player */ dictinsert(d, "ERROR", newintobject((long) CD_ERROR)); dictinsert(d, "NODISC", newintobject((long) CD_NODISC)); dictinsert(d, "READY", newintobject((long) CD_READY)); dictinsert(d, "PLAYING", newintobject((long) CD_PLAYING)); dictinsert(d, "PAUSED", newintobject((long) CD_PAUSED)); dictinsert(d, "STILL", newintobject((long) CD_STILL)); #ifdef CD_CDROM /* only newer versions of the library */ dictinsert(d, "CDROM", newintobject((long) CD_CDROM)); #endif if (err_occurred()) fatal("can't initialize module cd"); }
21.871186
82
0.678239
[ "object" ]
63ccc6ddb1df2b0d3f3e5c1b9df683db360a3465
5,607
h
C
media/capture/video/mac/video_capture_device_avfoundation_protocol_mac.h
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/capture/video/mac/video_capture_device_avfoundation_protocol_mac.h
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
media/capture/video/mac/video_capture_device_avfoundation_protocol_mac.h
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
1
2021-03-07T14:20:02.000Z
2021-03-07T14:20:02.000Z
// Copyright 2020 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_CAPTURE_VIDEO_MAC_VIDEO_CAPTURE_DEVICE_AVFOUNDATION_PROTOCOL_MAC_H_ #define MEDIA_CAPTURE_VIDEO_MAC_VIDEO_CAPTURE_DEVICE_AVFOUNDATION_PROTOCOL_MAC_H_ #import <AVFoundation/AVFoundation.h> #import <Foundation/Foundation.h> #include <vector> #import "base/mac/scoped_nsobject.h" #include "base/synchronization/lock.h" #include "base/threading/thread_checker.h" #include "media/capture/video/video_capture_device.h" #include "media/capture/video_capture_types.h" #include "ui/gfx/geometry/size.h" namespace media { class VideoCaptureDeviceMac; class CAPTURE_EXPORT VideoCaptureDeviceAVFoundationFrameReceiver { public: virtual ~VideoCaptureDeviceAVFoundationFrameReceiver() = default; // Called to deliver captured video frames. It's safe to call this method // from any thread, including those controlled by AVFoundation. virtual void ReceiveFrame(const uint8_t* video_frame, int video_frame_length, const VideoCaptureFormat& frame_format, const gfx::ColorSpace color_space, int aspect_numerator, int aspect_denominator, base::TimeDelta timestamp) = 0; // Called to deliver GpuMemoryBuffer-wrapped captured video frames. This // function may be called from any thread, including those controlled by // AVFoundation. virtual void ReceiveExternalGpuMemoryBufferFrame( CapturedExternalVideoBuffer frame, std::vector<CapturedExternalVideoBuffer> scaled_frames, base::TimeDelta timestamp) = 0; // Callbacks with the result of a still image capture, or in case of error, // respectively. It's safe to call these methods from any thread. virtual void OnPhotoTaken(const uint8_t* image_data, size_t image_length, const std::string& mime_type) = 0; // Callback when a call to takePhoto fails. virtual void OnPhotoError() = 0; // Forwarder to VideoCaptureDevice::Client::OnError(). virtual void ReceiveError(VideoCaptureError error, const base::Location& from_here, const std::string& reason) = 0; }; } // namespace media // Protocol used by VideoCaptureDeviceMac for video and image capture using // AVFoundation API. Concrete implementation objects live inside the thread // created by its owner VideoCaptureDeviceMac. @protocol VideoCaptureDeviceAVFoundationProtocol // Previous to any use, clients must call -initWithFrameReceiver: to // initialise an object of this class and register a |frameReceiver_|. This // initializes the instance and the underlying capture session and registers the // frame receiver. - (id)initWithFrameReceiver: (media::VideoCaptureDeviceAVFoundationFrameReceiver*)frameReceiver; // Frame receiver registration or removal can also happen via explicit call // to -setFrameReceiver:. Re-registrations are safe and allowed, even during // capture using this method. - (void)setFrameReceiver: (media::VideoCaptureDeviceAVFoundationFrameReceiver*)frameReceiver; // Sets which capture device to use by name, retrieved via |deviceNames|. // Method -setCaptureDevice: must be called at least once with a device // identifier from GetVideoCaptureDeviceNames(). It creates all the necessary // AVFoundation objects on the first call; it connects them ready for capture // every time. Once the deviceId is known, the library objects are created if // needed and connected for the capture, and a by default resolution is set. If // |deviceId| is nil, then the eventual capture is stopped and library objects // are disconnected. Returns YES on success, NO otherwise. If the return value // is NO, an error message is assigned to |outMessage|. This method should not // be called during capture (i.e. between -startCapture and -stopCapture). - (BOOL)setCaptureDevice:(NSString*)deviceId errorMessage:(NSString**)outMessage; // Configures the capture properties for the capture session and the video data // output; this means it MUST be called after setCaptureDevice:. Return YES on // success, else NO. - (BOOL)setCaptureHeight:(int)height width:(int)width frameRate:(float)frameRate; // If an efficient path is available, the capturer will perform scaling and // deliver scaled frames to the |frameReceiver| as specified by |resolutions|. // The scaled frames are delivered in addition to the original captured frame. // Resolutions that match the captured frame or that would result in upscaling // are ignored. - (void)setScaledResolutions:(std::vector<gfx::Size>)resolutions; // Starts video capturing and registers notification listeners. Must be // called after setCaptureDevice:, and, eventually, also after // setCaptureHeight:width:frameRate:. // The capture can be stopped and restarted multiple times, potentially // reconfiguring the device in between. // Returns YES on success, NO otherwise. - (BOOL)startCapture; // Stops video capturing and stops listening to notifications. Same as // setCaptureDevice:nil but doesn't disconnect the library objects. The capture // can be - (void)stopCapture; // Takes a photo. This method should only be called between -startCapture and // -stopCapture. - (void)takePhoto; @end #endif // MEDIA_CAPTURE_VIDEO_MAC_VIDEO_CAPTURE_DEVICE_AVFOUNDATION_PROTOCOL_MAC_H_
44.856
84
0.74407
[ "geometry", "object", "vector" ]
63cf91e720aa59f67529c83d9440b4a0726d0234
397
h
C
Sources/Internal/Math/Ray.h
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-11-14T10:18:24.000Z
2020-11-14T10:18:24.000Z
Sources/Internal/Math/Ray.h
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
null
null
null
Sources/Internal/Math/Ray.h
Serviak/dava.engine
d51a26173a3e1b36403f846ca3b2e183ac298a1a
[ "BSD-3-Clause" ]
1
2020-09-05T21:16:17.000Z
2020-09-05T21:16:17.000Z
#ifndef __DAVAENGINE_RAY_H__ #define __DAVAENGINE_RAY_H__ #include "Base/BaseTypes.h" #include "Math/Vector.h" namespace DAVA { /** \ingroup math \brief Ray in 2D space. */ class Ray2 { public: Vector2 origin; Vector2 direction; }; /** \ingroup math \brief Ray in 3D space. */ class Ray3 { public: Vector3 origin; Vector3 direction; }; }; #endif // __DAVAENGINE_RAY_H__
12.40625
30
0.687657
[ "vector", "3d" ]
63d506154cc8016c2a0bfd663afafd9a9b670427
2,947
h
C
source/msynth/msynth/model/MFxSlot.h
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
1
2022-01-30T07:40:31.000Z
2022-01-30T07:40:31.000Z
source/msynth/msynth/model/MFxSlot.h
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
source/msynth/msynth/model/MFxSlot.h
MRoc/MSynth
3eb5c6cf0ad6a3d12f555ebca5fbe84c1b255829
[ "MIT" ]
null
null
null
#ifndef __MFxSlot #define __MFxSlot #include <framework/MObject.h> #include <framework/MDefaultFactory.h> #include <framework/primitive/MObjString.h> #include <framework/list/MSelectableObjectList.h> #include <framework/treedocument/ISerializeable.h> #include "transformer/MTransformer.h" #include "transformer/MTransformerRegistry.h" /** * interface for getting informed about changes * in the fx slot */ class IFxSlotListener : public IListener { public: /** * invoked when a processor changed * ptOld - the previous slected transformer, can be null will be deleted after * ptNew - the new selected transformer, can be null */ virtual void onProcessorChanged( MTransformer* ptOld, MTransformer* ptNew ) = 0; }; /** * a slot of a effect rack. it is able * to host one effect. */ class MFxSlot : public MObject, public ISelectionListener, public ISerializeable { public: /** * runtime type info */ static MRtti gvRtti; /** * the current selected transformer, * can be null */ MTransformer* ivPtCurrentTransformer; /** * the list of available transformers */ MSelectableObjectList ivPtTransformerRttis; /** * a list of IXfSlotListener */ MListenerList ivListeners; /** * the none string */ MObjString ivNoneString; /** * hack to prevent fx change when loading and setting selection */ bool ivLoadRecursionLock; public: /** * constructor */ MFxSlot(); /** * destructor */ virtual ~MFxSlot(); /** * returns the runtime type info */ virtual IRtti* getRtti() const; /** * queries for a interface */ virtual void* getInterface( const String &className ) const; /** * invoked when selection changed in the rtti list * newSelection = the new selected object * ptSource = the object list */ virtual void selectionChanged( MObject* newSelection, MObject* ptSource ); /** * resets the slot (transformer=0) */ virtual void reset(); /** * returns the selected transformer, * can be null. */ virtual MTransformer* getTransformer(); /** * adds a IFxSlotListener */ virtual void addListener( IFxSlotListener* ptListener ); /** * removes a IFxSlotListener */ virtual void removeListener( IFxSlotListener* ptListener ); /** * loads from the given tree node */ virtual void load( MTreeNode* ptNode ); /** * stores as tree node */ virtual MTreeNode* save(); /** * returns the list of the available transformers, * selecting in this list selects a new effect */ virtual MSelectableObjectList* getTransformerRttis(); protected: /** * sets the current transformer */ virtual void setTransformer( MTransformer* ptTransformer ); /** * fires a fx changed notif */ virtual void fireFxChanged( MTransformer* ptOld, MTransformer* ptNew ); }; #endif
19.516556
82
0.664404
[ "object" ]
63dc6bbe6d6c5834f1961cf0552fc913cf291137
8,731
h
C
3rd/webrtc/include/third_party/ffmpeg/libavutil/tx_priv.h
Udalenka/StatisticsModule
bdec8c3a3628297e3d1b72616aec3b20ffa769ae
[ "MIT" ]
110
2020-10-27T02:15:35.000Z
2022-03-30T10:24:52.000Z
3rd/webrtc/include/third_party/ffmpeg/libavutil/tx_priv.h
Udalenka/StatisticsModule
bdec8c3a3628297e3d1b72616aec3b20ffa769ae
[ "MIT" ]
13
2021-02-02T05:32:42.000Z
2022-03-13T15:03:26.000Z
3rd/webrtc/include/third_party/ffmpeg/libavutil/tx_priv.h
Udalenka/StatisticsModule
bdec8c3a3628297e3d1b72616aec3b20ffa769ae
[ "MIT" ]
37
2020-11-13T15:44:23.000Z
2022-03-25T09:08:22.000Z
/* * 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 AVUTIL_TX_PRIV_H #define AVUTIL_TX_PRIV_H #include "tx.h" #include "thread.h" #include "mem_internal.h" #include "attributes.h" #ifdef TX_FLOAT #define TX_NAME(x) x ## _float #define SCALE_TYPE float typedef float FFTSample; typedef AVComplexFloat FFTComplex; #elif defined(TX_DOUBLE) #define TX_NAME(x) x ## _double #define SCALE_TYPE double typedef double FFTSample; typedef AVComplexDouble FFTComplex; #elif defined(TX_INT32) #define TX_NAME(x) x ## _int32 #define SCALE_TYPE float typedef int32_t FFTSample; typedef AVComplexInt32 FFTComplex; #else typedef void FFTComplex; #endif #if defined(TX_FLOAT) || defined(TX_DOUBLE) #define CMUL(dre, dim, are, aim, bre, bim) \ do { \ (dre) = (are) * (bre) - (aim) * (bim); \ (dim) = (are) * (bim) + (aim) * (bre); \ } while (0) #define SMUL(dre, dim, are, aim, bre, bim) \ do { \ (dre) = (are) * (bre) - (aim) * (bim); \ (dim) = (are) * (bim) - (aim) * (bre); \ } while (0) #define UNSCALE(x) (x) #define RESCALE(x) (x) #define FOLD(a, b) ((a) + (b)) #elif defined(TX_INT32) /* Properly rounds the result */ #define CMUL(dre, dim, are, aim, bre, bim) \ do { \ int64_t accu; \ (accu) = (int64_t)(bre) * (are); \ (accu) -= (int64_t)(bim) * (aim); \ (dre) = (int)(((accu) + 0x40000000) >> 31); \ (accu) = (int64_t)(bim) * (are); \ (accu) += (int64_t)(bre) * (aim); \ (dim) = (int)(((accu) + 0x40000000) >> 31); \ } while (0) #define SMUL(dre, dim, are, aim, bre, bim) \ do { \ int64_t accu; \ (accu) = (int64_t)(bre) * (are); \ (accu) -= (int64_t)(bim) * (aim); \ (dre) = (int)(((accu) + 0x40000000) >> 31); \ (accu) = (int64_t)(bim) * (are); \ (accu) -= (int64_t)(bre) * (aim); \ (dim) = (int)(((accu) + 0x40000000) >> 31); \ } while (0) #define UNSCALE(x) ((double)x/2147483648.0) #define RESCALE(x) (av_clip64(lrintf((x) * 2147483648.0), INT32_MIN, INT32_MAX)) #define FOLD(x, y) ((int)((x) + (unsigned)(y) + 32) >> 6) #endif #define BF(x, y, a, b) \ do { \ x = (a) - (b); \ y = (a) + (b); \ } while (0) #define CMUL3(c, a, b) \ CMUL((c).re, (c).im, (a).re, (a).im, (b).re, (b).im) #define COSTABLE(size) \ DECLARE_ALIGNED(32, FFTSample, TX_NAME(ff_cos_##size))[size/4 + 1] /* Used by asm, reorder with care */ struct AVTXContext { int n; /* Non-power-of-two part */ int m; /* Power-of-two part */ int inv; /* Is inverse */ int type; /* Type */ uint64_t flags; /* Flags */ double scale; /* Scale */ FFTComplex *exptab; /* MDCT exptab */ FFTComplex *tmp; /* Temporary buffer needed for all compound transforms */ int *pfatab; /* Input/Output mapping for compound transforms */ int *revtab; /* Input mapping for power of two transforms */ int *inplace_idx; /* Required indices to revtab for in-place transforms */ int *revtab_c; /* Revtab for only the C transforms, needed because * checkasm makes us reuse the same context. */ av_tx_fn top_tx; /* Used for computing transforms derived from other * transforms, like full-length iMDCTs and RDFTs. * NOTE: Do NOT use this to mix assembly with C code. */ }; /* Checks if type is an MDCT */ int ff_tx_type_is_mdct(enum AVTXType type); /* * Generates the PFA permutation table into AVTXContext->pfatab. The end table * is appended to the start table. */ int ff_tx_gen_compound_mapping(AVTXContext *s); /* * Generates a standard-ish (slightly modified) Split-Radix revtab into * AVTXContext->revtab */ int ff_tx_gen_ptwo_revtab(AVTXContext *s, int invert_lookup); /* * Generates an index into AVTXContext->inplace_idx that if followed in the * specific order, allows the revtab to be done in-place. AVTXContext->revtab * must already exist. */ int ff_tx_gen_ptwo_inplace_revtab_idx(AVTXContext *s, int *revtab); /* * This generates a parity-based revtab of length len and direction inv. * * Parity means even and odd complex numbers will be split, e.g. the even * coefficients will come first, after which the odd coefficients will be * placed. For example, a 4-point transform's coefficients after reordering: * z[0].re, z[0].im, z[2].re, z[2].im, z[1].re, z[1].im, z[3].re, z[3].im * * The basis argument is the length of the largest non-composite transform * supported, and also implies that the basis/2 transform is supported as well, * as the split-radix algorithm requires it to be. * * The dual_stride argument indicates that both the basis, as well as the * basis/2 transforms support doing two transforms at once, and the coefficients * will be interleaved between each pair in a split-radix like so (stride == 2): * tx1[0], tx1[2], tx2[0], tx2[2], tx1[1], tx1[3], tx2[1], tx2[3] * A non-zero number switches this on, with the value indicating the stride * (how many values of 1 transform to put first before switching to the other). * Must be a power of two or 0. Must be less than the basis. * Value will be clipped to the transform size, so for a basis of 16 and a * dual_stride of 8, dual 8-point transforms will be laid out as if dual_stride * was set to 4. * Usually you'll set this to half the complex numbers that fit in a single * register or 0. This allows to reuse SSE functions as dual-transform * functions in AVX mode. * * If length is smaller than basis/2 this function will not do anything. */ void ff_tx_gen_split_radix_parity_revtab(int *revtab, int len, int inv, int basis, int dual_stride); /* Templated init functions */ int ff_tx_init_mdct_fft_float(AVTXContext *s, av_tx_fn *tx, enum AVTXType type, int inv, int len, const void *scale, uint64_t flags); int ff_tx_init_mdct_fft_double(AVTXContext *s, av_tx_fn *tx, enum AVTXType type, int inv, int len, const void *scale, uint64_t flags); int ff_tx_init_mdct_fft_int32(AVTXContext *s, av_tx_fn *tx, enum AVTXType type, int inv, int len, const void *scale, uint64_t flags); typedef struct CosTabsInitOnce { void (*func)(void); AVOnce control; } CosTabsInitOnce; void ff_tx_init_float_x86(AVTXContext *s, av_tx_fn *tx); #endif /* AVUTIL_TX_PRIV_H */
42.79902
81
0.53018
[ "transform" ]
63e8b60a0216a55e05cf8c131d9fc3f3ee300541
66,663
c
C
src/x.c
acwars/emilia
a688b6a33c43c4ede72d2454901f434e414d159f
[ "MIT" ]
1
2020-12-31T03:19:21.000Z
2020-12-31T03:19:21.000Z
src/x.c
acwars/emilia
a688b6a33c43c4ede72d2454901f434e414d159f
[ "MIT" ]
null
null
null
src/x.c
acwars/emilia
a688b6a33c43c4ede72d2454901f434e414d159f
[ "MIT" ]
null
null
null
#ifndef NOX // if x11 support enabled at compile time #define _GNU_SOURCE #include "../include/x.h" #include "../include/rcptr.h" #include "../include/vector.h" #include <X11/Xlib.h> #include <limits.h> #include <uchar.h> #include <GL/glx.h> #include <X11/X.h> #include <X11/XKBlib.h> #include <X11/Xatom.h> #include <X11/cursorfont.h> #include <X11/extensions/Xrandr.h> #include <X11/extensions/Xrender.h> #include <X11/keysymdef.h> #define _NET_WM_STATE_REMOVE 0l #define _NET_WM_STATE_ADD 1l #define _NET_WM_STATE_TOGGLE 2l #define INCR_TIMEOUT_MS 500 /* Motif hints from Xm/MwmUtil.h */ typedef struct { uint32_t flags; uint32_t functions; uint32_t decorations; int32_t input_mode; uint32_t status; } mwm_hints_t; #define MWM_HINTS_FUNCTIONS (1L << 0) #define MWM_HINTS_DECORATIONS (1L << 1) #define MWM_HINTS_INPUT_MODE (1L << 2) #define MWM_HINTS_STATUS (1L << 3) #define MWM_FUNC_ALL (1L << 0) #define MWM_FUNC_RESIZE (1L << 1) #define MWM_FUNC_MOVE (1L << 2) #define MWM_FUNC_MINIMIZE (1L << 3) #define MWM_FUNC_MAXIMIZE (1L << 4) #define MWM_FUNC_CLOSE (1L << 5) #define MWM_DECOR_ALL (1L << 0) #define MWM_DECOR_BORDER (1L << 1) #define MWM_DECOR_RESIZEH (1L << 2) #define MWM_DECOR_TITLE (1L << 3) #define MWM_DECOR_MENU (1L << 4) #define MWM_DECOR_MINIMIZE (1L << 5) #define MWM_DECOR_MAXIMIZE (1L << 6) #define MWM_INPUT_MODELESS 0 #define MWM_INPUT_PRIMARY_APPLICATION_MODAL 1 #define MWM_INPUT_SYSTEM_MODAL 2 #define MWM_INPUT_FULL_APPLICATION_MODAL 3 #define MWM_INPUT_APPLICATION_MODAL MWM_INPUT_PRIMARY_APPLICATION_MODAL #define MWM_TEAROFF_WINDOW (1L << 0) #define GLX_CONTEXT_MAJOR_VERSION_ARB 0x2091 #define GLX_CONTEXT_MINOR_VERSION_ARB 0x2092 #define GLX_SWAP_INTERVAL_EXT 0x20F1 #define GLX_MAX_SWAP_INTERVAL_EXT 0x20F2 static APIENTRY PFNGLXSWAPINTERVALEXTPROC glXSwapIntervalEXT = NULL; static int32_t convert_modifier_mask(unsigned int x_mask) { int32_t mods = 0; if (x_mask & ShiftMask) { FLAG_SET(mods, MODIFIER_SHIFT); } if (x_mask & ControlMask) { FLAG_SET(mods, MODIFIER_CONTROL); } if (x_mask & Mod1Mask) { FLAG_SET(mods, MODIFIER_CONTROL); } return mods; } DEF_VECTOR(char, NULL); static WindowStatic* global; #define globalX11 ((GlobalX11*)&global->extend_data) #define windowX11(base) ((WindowX11*)&base->extend_data) static struct WindowBase* WindowX11_new(uint32_t w, uint32_t h); static void WindowX11_set_fullscreen(struct WindowBase* self, bool fullscreen); static void WindowX11_set_maximized(struct WindowBase* self, bool maximized); static void WindowX11_resize(struct WindowBase* self, uint32_t w, uint32_t h); static void WindowX11_events(struct WindowBase* self); static void WindowX11_set_wm_name(struct WindowBase* self, const char* title, const char* name); static void WindowX11_set_title(struct WindowBase* self, const char* title); static void WindowX11_set_swap_interval(struct WindowBase* self, int32_t ival); static bool WindowX11_maybe_swap(struct WindowBase* self); static void WindowX11_destroy(struct WindowBase* self); static int WindowX11_get_connection_fd(struct WindowBase* self); static void WindowX11_primary_get(struct WindowBase* self); static void WindowX11_primary_send(struct WindowBase* self, const char* text); static void WindowX11_clipboard_get(struct WindowBase* self); static void WindowX11_clipboard_send(struct WindowBase* self, const char* text); static void WindowX11_set_pointer_style(struct WindowBase* self, enum MousePointerStyle style); static void* WindowX11_get_gl_ext_proc_adress(struct WindowBase* self, const char* name); static uint32_t WindowX11_get_keycode_from_name(struct WindowBase* self, char* name); static void WindowX11_set_current_context(struct WindowBase* self, bool this); static inline void WindowX11_set_urgent(struct WindowBase* self); static int64_t WindowX11_get_window_id(struct WindowBase* self); static inline void WindowX11_set_stack_order(struct WindowBase* self, bool front_or_back); static TimePoint* WindowX11_process_timers(struct WindowBase* self) { return NULL; } static struct IWindow window_interface_x11 = { .set_fullscreen = WindowX11_set_fullscreen, .set_maximized = WindowX11_set_maximized, .resize = WindowX11_resize, .events = WindowX11_events, .process_timers = WindowX11_process_timers, .set_title = WindowX11_set_title, .maybe_swap = WindowX11_maybe_swap, .destroy = WindowX11_destroy, .get_connection_fd = WindowX11_get_connection_fd, .clipboard_send = WindowX11_clipboard_send, .clipboard_get = WindowX11_clipboard_get, .primary_get = WindowX11_primary_get, .primary_send = WindowX11_primary_send, .set_swap_interval = WindowX11_set_swap_interval, .get_gl_ext_proc_adress = WindowX11_get_gl_ext_proc_adress, .get_keycode_from_name = WindowX11_get_keycode_from_name, .set_pointer_style = WindowX11_set_pointer_style, .set_current_context = WindowX11_set_current_context, .set_urgent = WindowX11_set_urgent, .set_stack_order = WindowX11_set_stack_order, .get_window_id = WindowX11_get_window_id, }; typedef struct { char* data; size_t size; } clipboard_content_t; static void clipboard_content_destroy(clipboard_content_t* self) { free(self->data); self->data = NULL; self->size = 0; } DEF_RC_PTR(clipboard_content_t, clipboard_content_destroy); typedef struct { Display* display; struct x11_atom_values { Atom wm_delete, wm_ping, wm_state, wm_max_horz, wm_max_vert, wm_fullscreen, wm_window_type, wm_window_type_normal, wm_demands_attention; Atom clipboard, incr, uri_list_mime_type, utf8_string_mime_type, text_mime_type, text_charset_utf8_mime_type, targets; Atom dnd_enter, dnd_type_list, dnd_position, dnd_finished, dnd_leave, dnd_status, dnd_drop, dnd_selection, dnd_action_copy, dnd_proxy; } atom; struct globalX11_incr_transfer_inbound { Atom listen_property; TimePoint listen_timeout; Vector_char data; Window source; } incr_transfer_in; struct globalX11_incr_transfer_outbound { bool active; uint32_t chunk_size; Atom property, target; TimePoint listen_timeout; size_t current_offset; Window requestor; RcPtr_clipboard_content_t clipboard_content; } incr_transfer_out; Cursor cursor_hidden; Cursor cursor_beam; Cursor cursor_hand; XIM im; XIC ic; } GlobalX11; typedef struct { Window window; GLXContext glx_context; XEvent event; XSetWindowAttributes set_win_attribs; Colormap colormap; uint32_t last_button_pressed; RcPtr_clipboard_content_t clipboard_content, primary_content; struct WindowX11_dnd_offer { const char* mime_type; Atom mime_type_atom; Time timestamp; Atom action; Window source_xid; bool accepted; } dnd_offer; } WindowX11; static void WindowX11_drop_dnd_offer(WindowX11* self) { if (!self->dnd_offer.accepted) { memset(&self->dnd_offer, 0, sizeof(self->dnd_offer)); } } static void WindowX11_dnd_offer_handled(WindowX11* self) { XClientMessageEvent ev = { .display = globalX11->display, .window = self->dnd_offer.source_xid, .type = ClientMessage, .format = 32, .message_type = globalX11->atom.dnd_status, .data.l = { [0] = self->window, [1] = 1, [2] = self->dnd_offer.action, [3] = 0, [4] = 0, }, }; XSendEvent(globalX11->display, self->dnd_offer.source_xid, True, NoEventMask, (XEvent*)&ev); XSync(globalX11->display, False); XFlush(globalX11->display); WindowX11_drop_dnd_offer(self); } static void WindowX11_record_dnd_offer(WindowX11* self, Window source_xid, const char* mime, Atom mime_atom, Atom action) { self->dnd_offer.source_xid = source_xid; self->dnd_offer.mime_type = mime; self->dnd_offer.mime_type_atom = mime_atom; self->dnd_offer.action = action; self->dnd_offer.accepted = false; } static void WindowX11_primary_send(struct WindowBase* self, const char* text) { if (!text) { return; } RcPtr_new_in_place_of_clipboard_content_t(&windowX11(self)->primary_content); *RcPtr_get_clipboard_content_t(&windowX11(self)->primary_content) = (clipboard_content_t){ .data = (char*)text, .size = 0, }; XSetSelectionOwner(globalX11->display, XA_PRIMARY, windowX11(self)->window, CurrentTime); if (XGetSelectionOwner(globalX11->display, XA_PRIMARY) != windowX11(self)->window) { WRN("Failed to take ownership of PRIMARY selection\n"); } } static void WindowX11_primary_get(struct WindowBase* self) { Window owner = XGetSelectionOwner(globalX11->display, XA_PRIMARY); if (owner == windowX11(self)->window) { clipboard_content_t* cc = RcPtr_get_clipboard_content_t(&windowX11(self)->primary_content); if (cc && cc->data) { LOG("X::clipboard_get{ we own the PRIMARY selection }\n"); CALL(self->callbacks.clipboard_handler, self->callbacks.user_data, cc->data); } else { LOG("X::clipboard_get{ we own the PRIMARY selection, but have no data }\n"); } } else if (owner != None) { LOG("X::clipboard_get{ convert from owner: %ld }\n", owner); XConvertSelection(globalX11->display, XA_PRIMARY, globalX11->atom.utf8_string_mime_type, XA_PRIMARY, windowX11(self)->window, CurrentTime); } else { LOG("X::clipboard_get{ PRIMARY selection has no owner }\n"); } } static void WindowX11_clipboard_send(struct WindowBase* self, const char* text) { RcPtr_new_in_place_of_clipboard_content_t(&windowX11(self)->clipboard_content); *RcPtr_get_clipboard_content_t(&windowX11(self)->clipboard_content) = (clipboard_content_t){ .data = (char*)text, .size = 0, }; XSetSelectionOwner(globalX11->display, globalX11->atom.clipboard, windowX11(self)->window, CurrentTime); if (XGetSelectionOwner(globalX11->display, globalX11->atom.clipboard) != windowX11(self)->window) { WRN("Failed to take ownership of CLIPBOARD selection\n"); } } static void WindowX11_clipboard_get(struct WindowBase* self) { Window owner = XGetSelectionOwner(globalX11->display, globalX11->atom.clipboard); if (owner == windowX11(self)->window) { clipboard_content_t* cc = RcPtr_get_clipboard_content_t(&windowX11(self)->clipboard_content); if (cc && cc->data) { LOG("X::clipboard_get{ we own the CLIPBOARD selection }\n"); CALL(self->callbacks.clipboard_handler, self->callbacks.user_data, cc->data); } else { LOG("X::clipboard_get{ we own the CLIPBOARD selection, but have no data }\n"); } } else if (owner != None) { LOG("X::clipboard_get{ convert from owner: %ld }\n", owner); XConvertSelection(globalX11->display, globalX11->atom.clipboard, globalX11->atom.utf8_string_mime_type, globalX11->atom.clipboard, windowX11(self)->window, CurrentTime); } else { LOG("X::clipboard_get{ CLIPBOARD selection has no owner }\n"); } } static void WindowX11_setup_pointer(struct WindowBase* self) { XColor c = { .red = 0, .green = 0, .blue = 0 }; static char data[8] = { 0 }; Pixmap pmp = XCreateBitmapFromData(globalX11->display, windowX11(self)->window, data, 8, 8); globalX11->cursor_hidden = XCreatePixmapCursor(globalX11->display, pmp, pmp, &c, &c, 0, 0); globalX11->cursor_beam = XCreateFontCursor(globalX11->display, XC_xterm); globalX11->cursor_hand = XCreateFontCursor(globalX11->display, XC_hand1); } static void* WindowX11_get_gl_ext_proc_adress(struct WindowBase* self, const char* name) { return glXGetProcAddress((const GLubyte*)name); } static int x11_error_handler(Display* dpy, XErrorEvent* e) { char buf[1024]; XGetErrorText(dpy, e->error_code, buf, ARRAY_SIZE(buf)); WRN("X11 protocol error: %s (e: %d, m: %d, req: %d, XID: %lu, type: %d, s: %lu)\n", buf, e->error_code, e->minor_code, e->request_code, e->resourceid, e->type, e->serial); return 0; /* return value is ignored */ } static int x11_io_error_handler(Display* dpy) { /* if this func completes Xlib will call exit() anyway */ ERR("fatal I/O error in Xlib"); return 0; /* return value is ignored */ } static struct WindowBase* WindowX11_new(uint32_t w, uint32_t h) { bool init_globals = false; if (!global) { init_globals = true; global = calloc(1, sizeof(WindowStatic) + sizeof(GlobalX11) - sizeof(uint8_t)); XSetErrorHandler(x11_error_handler); XSetIOErrorHandler(x11_io_error_handler); } if (init_globals) { globalX11->display = XOpenDisplay(NULL); if (!globalX11->display) { free(global); return NULL; } #ifdef DEBUG XSynchronize(globalX11->display, True); #endif int glx_major, glx_minor, qry_res; if (!(qry_res = glXQueryVersion(globalX11->display, &glx_major, &glx_minor)) || (glx_major == 1 && glx_minor < 3)) { WRN("GLX version to low\n"); free(global); return NULL; } if (!XSupportsLocale()) { ERR("Xorg does not support locales\n"); } } struct WindowBase* win = calloc(1, sizeof(struct WindowBase) + sizeof(WindowX11) - sizeof(uint8_t)); XSetLocaleModifiers("@im=none"); globalX11->im = XOpenIM(globalX11->display, NULL, NULL, NULL); if (!globalX11->im) { ERR("Failed to open input method"); } globalX11->ic = XCreateIC(globalX11->im, XNInputStyle, XIMPreeditNothing | XIMStatusNothing, XNClientWindow, windowX11(win)->window, NULL); if (!globalX11->ic) { ERR("Failed to create input context"); } XSetICFocus(globalX11->ic); uint32_t timeout_ms, interval_ms; XkbGetAutoRepeatRate(globalX11->display, XkbUseCoreKbd, &timeout_ms, &interval_ms); LOG("Detected Xkb autorepeat timeout: %u, interval: %u\n", timeout_ms, interval_ms); win->key_repeat_interval_ms = interval_ms; win->w = w; win->h = h; win->interface = &window_interface_x11; static const int visual_attribs[] = { GLX_RENDER_TYPE, GLX_RGBA_BIT, GLX_DRAWABLE_TYPE, GLX_WINDOW_BIT, GLX_DOUBLEBUFFER, True, GLX_RED_SIZE, 1, GLX_GREEN_SIZE, 1, GLX_BLUE_SIZE, 1, GLX_ALPHA_SIZE, 1, GLX_DEPTH_SIZE, GLX_DONT_CARE, None }; int framebuffer_config_count; GLXFBConfig* framebuffer_configs = glXChooseFBConfig(globalX11->display, DefaultScreen(globalX11->display), visual_attribs, &framebuffer_config_count); if (!framebuffer_configs) { ERR("glXChooseFBConfig failed"); } XVisualInfo* visual_info = NULL; int framebuffer_config_selected_idx = -1, framebuffer_config_selected_no_alpha_idx = -1; for (int i = 0; i < framebuffer_config_count; ++i) { visual_info = glXGetVisualFromFBConfig(globalX11->display, framebuffer_configs[i]); if (!visual_info) { continue; } XRenderPictFormat* visual_pict_format = XRenderFindVisualFormat(globalX11->display, visual_info->visual); if (!visual_pict_format) { continue; } LOG( "X::Visual picture format{ depth: %d, r:%d(%d), g:%d(%d), b:%d(%d), a:%d(%d), type: %d, " "pf id: %lu }\n", visual_pict_format->depth, visual_pict_format->direct.red, visual_pict_format->direct.redMask, visual_pict_format->direct.green, visual_pict_format->direct.greenMask, visual_pict_format->direct.blue, visual_pict_format->direct.blueMask, visual_pict_format->direct.alpha, visual_pict_format->direct.alphaMask, visual_pict_format->type, visual_pict_format->id); if (visual_pict_format->direct.redMask > 0 && visual_pict_format->direct.greenMask > 0 && visual_pict_format->direct.blueMask > 0 && visual_pict_format->depth >= 24) { if (visual_pict_format->direct.alphaMask > 0 && visual_pict_format->depth >= 32) { framebuffer_config_selected_idx = i; break; } else { framebuffer_config_selected_no_alpha_idx = i; } } XFree(visual_info); visual_info = NULL; } bool found_alpha_config = !(framebuffer_config_selected_idx < 0); if (!found_alpha_config) { WRN("No transparent framebuffer found\n"); framebuffer_config_selected_idx = framebuffer_config_selected_no_alpha_idx; } if (framebuffer_config_selected_idx < 0) { ERR("No suitable framebuffer configuration found"); } if (!visual_info) { visual_info = glXGetVisualFromFBConfig(globalX11->display, framebuffer_configs[framebuffer_config_selected_idx]); if (!visual_info) { ERR("Failed to get visual info"); } } Colormap colormap = XCreateColormap(globalX11->display, RootWindow(globalX11->display, visual_info->screen), visual_info->visual, AllocNone); long event_mask = KeyPressMask | ButtonPressMask | ButtonReleaseMask | SubstructureRedirectMask | StructureNotifyMask | PointerMotionMask | ExposureMask | FocusChangeMask | KeymapStateMask | VisibilityChangeMask | PropertyChangeMask; windowX11(win)->set_win_attribs = (XSetWindowAttributes){ .colormap = windowX11(win)->colormap = colormap, .border_pixel = 0, .background_pixmap = None, .override_redirect = True, .event_mask = event_mask, }; windowX11(win)->glx_context = NULL; const char* exts = glXQueryExtensionsString(globalX11->display, DefaultScreen(globalX11->display)); LOG("X::GLX extensions{ %s }\n", exts); static const int context_attrs[] = { GLX_CONTEXT_MAJOR_VERSION_ARB, 2, GLX_CONTEXT_MINOR_VERSION_ARB, 1, None }; if (strstr(exts, "_swap_control")) { glXSwapIntervalEXT = (APIENTRY PFNGLXSWAPINTERVALEXTPROC)glXGetProcAddressARB( (const GLubyte*)"glXSwapIntervalEXT"); } if (!glXSwapIntervalEXT) { WRN("glXSwapIntervalEXT not found\n"); } APIENTRY PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB = NULL; if (strstr(exts, "GLX_ARB_create_context")) { glXCreateContextAttribsARB = (PFNGLXCREATECONTEXTATTRIBSARBPROC)glXGetProcAddressARB( (const GLubyte*)"glXCreateContextAttribsARB"); } if (!glXCreateContextAttribsARB || !found_alpha_config) { WRN("glXCreateContextAttribsARB not found\n"); windowX11(win)->glx_context = glXCreateNewContext(globalX11->display, framebuffer_configs[framebuffer_config_selected_idx], GLX_RGBA_TYPE, 0, True); } else { windowX11(win)->glx_context = glXCreateContextAttribsARB(globalX11->display, framebuffer_configs[framebuffer_config_selected_idx], 0, True, context_attrs); } if (!windowX11(win)->glx_context) { ERR("Failed to create GLX context"); } windowX11(win)->window = XCreateWindow(globalX11->display, RootWindow(globalX11->display, visual_info->screen), 0, 0, win->w, win->h, 0, visual_info->depth, InputOutput, visual_info->visual, CWBorderPixel | CWColormap | CWEventMask, &windowX11(win)->set_win_attribs); if (!windowX11(win)->window) { ERR("Failed to create X11 window"); } XFree(framebuffer_configs); XFree(visual_info); /* XChangeProperty(globalX11->display, */ /* windowX11(win)->window, */ /* XInternAtom(globalX11->display, "_NET_WM_ICON_NAME", False), */ /* XInternAtom(globalX11->display, "UTF8_STRING", False), */ /* 8, */ /* PropModeReplace, */ /* (unsigned char*)"emilia", */ /* strlen("emilia")); */ /* XSetIconName(globalX11->display, windowX11(win)->window, "emilia"); */ XClassHint class_hint = { APPLICATION_NAME, "CLASS" }; XWMHints wm_hints = { .flags = InputHint, .input = True }; XSetWMProperties(globalX11->display, windowX11(win)->window, NULL, NULL, NULL, 0, NULL, &wm_hints, &class_hint); if (settings.decoration_style != DECORATION_STYLE_FULL) { mwm_hints_t motif_hints; if (settings.decoration_style == DECORATION_STYLE_MINIMAL) { motif_hints = (mwm_hints_t){ .decorations = MWM_DECOR_ALL, .status = MWM_HINTS_DECORATIONS, .flags = MWM_HINTS_DECORATIONS, }; } else if (settings.decoration_style == DECORATION_STYLE_NONE) { motif_hints = (mwm_hints_t){ .flags = MWM_HINTS_DECORATIONS, }; } else { ASSERT_UNREACHABLE; } Atom atom_motif_hints = XInternAtom(globalX11->display, "_MOTIF_WM_HINTS", False); XChangeProperty(globalX11->display, windowX11(win)->window, atom_motif_hints, atom_motif_hints, 32, PropModeReplace, (unsigned char*)&motif_hints, 5); } XSync(globalX11->display, False); XMapWindow(globalX11->display, windowX11(win)->window); glXMakeCurrent(globalX11->display, windowX11(win)->window, windowX11(win)->glx_context); if (init_globals) { globalX11->atom.wm_delete = XInternAtom(globalX11->display, "WM_DELETE_WINDOW", True); globalX11->atom.wm_ping = XInternAtom(globalX11->display, "_NET_WM_PING", True); globalX11->atom.wm_state = XInternAtom(globalX11->display, "_NET_WM_STATE", True); globalX11->atom.wm_max_horz = XInternAtom(globalX11->display, "_NET_WM_STATE_MAXIMIZED_HORZ", True); globalX11->atom.wm_max_vert = XInternAtom(globalX11->display, "_NET_WM_STATE_MAXIMIZED_VERT", True); globalX11->atom.wm_fullscreen = XInternAtom(globalX11->display, "_NET_WM_STATE_FULLSCREEN", True); globalX11->atom.wm_demands_attention = XInternAtom(globalX11->display, "_NET_WM_STATE_DEMANDS_ATTENTION", True); globalX11->atom.wm_window_type_normal = XInternAtom(globalX11->display, "_NET_WM_WINDOW_TYPE_NORMAL", True); globalX11->atom.wm_window_type = XInternAtom(globalX11->display, "_NET_WM_WINDOW_TYPE", True); globalX11->atom.incr = XInternAtom(globalX11->display, "INCR", True); globalX11->atom.targets = XInternAtom(globalX11->display, "TARGETS", True); globalX11->atom.clipboard = XInternAtom(globalX11->display, "CLIPBOARD", True); globalX11->atom.uri_list_mime_type = XInternAtom(globalX11->display, "text/uri-list", True); globalX11->atom.text_mime_type = XInternAtom(globalX11->display, "text/plain", True); globalX11->atom.text_charset_utf8_mime_type = XInternAtom(globalX11->display, "text/plain;charset=utf-8", True); globalX11->atom.utf8_string_mime_type = XInternAtom(globalX11->display, "UTF8_STRING", True); globalX11->atom.dnd_enter = XInternAtom(globalX11->display, "XdndEnter", True); globalX11->atom.dnd_type_list = XInternAtom(globalX11->display, "XdndTypeList", True); globalX11->atom.dnd_position = XInternAtom(globalX11->display, "XdndPosition", True); globalX11->atom.dnd_leave = XInternAtom(globalX11->display, "XdndLeave", True); globalX11->atom.dnd_finished = XInternAtom(globalX11->display, "XdndFinished", True); globalX11->atom.dnd_status = XInternAtom(globalX11->display, "XdndStatus", True); globalX11->atom.dnd_drop = XInternAtom(globalX11->display, "XdndDrop", True); globalX11->atom.dnd_selection = XInternAtom(globalX11->display, "XdndSelection", True); globalX11->atom.dnd_action_copy = XInternAtom(globalX11->display, "XdndActionCopy", True); globalX11->atom.dnd_proxy = XInternAtom(globalX11->display, "XdndProxy", True); /* There is no actual limit on property size, ICCCM only says that INCR should be used for * data 'large relative to max request size'. It seems that (XExtendedMaxRequestSize() or * XMaxRequestSize()) / 4 is considered the max size by most clients. */ globalX11->incr_transfer_out.chunk_size = OR(XExtendedMaxRequestSize(globalX11->display), XMaxRequestSize(globalX11->display)) / 4; LOG("X::property chunk size{ bytes: %u }\n", globalX11->incr_transfer_out.chunk_size); } XChangeProperty(globalX11->display, windowX11(win)->window, globalX11->atom.wm_window_type, XA_ATOM, 32, PropModeReplace, (unsigned char*)&globalX11->atom.wm_window_type_normal, 1); XSetWMProtocols(globalX11->display, windowX11(win)->window, &globalX11->atom.wm_delete, 2); WindowX11_setup_pointer(win); XkbSelectEvents(globalX11->display, XkbUseCoreKbd, XkbAllEventsMask, XkbAllEventsMask); pid_t pid = getpid(); XChangeProperty(globalX11->display, windowX11(win)->window, XInternAtom(globalX11->display, "_NET_WM_PID", False), XA_CARDINAL, 32, PropModeReplace, (unsigned char*)&pid, 1); int xdnd_proto_version = 5; XChangeProperty(globalX11->display, windowX11(win)->window, XInternAtom(globalX11->display, "XdndAware", False), XA_ATOM, 32, PropModeReplace, (unsigned char*)&xdnd_proto_version, 1); XFlush(globalX11->display); return win; } struct WindowBase* Window_new_x11(Pair_uint32_t res) { struct WindowBase* win = WindowX11_new(res.first, res.second); if (!win) { return NULL; } win->title = NULL; WindowX11_set_wm_name(win, OR(settings.user_app_id, APPLICATION_NAME), OR(settings.user_app_id_2, NULL)); WindowX11_set_title(win, settings.title.str); return win; } static inline void WindowX11_set_urgent(struct WindowBase* self) { XClientMessageEvent e = { .type = ClientMessage, .window = windowX11(self)->window, .message_type = globalX11->atom.wm_state, .format = 32, .data.l = { [0] = _NET_WM_STATE_ADD, [1] = globalX11->atom.wm_demands_attention, [2] = 0, [3] = 0, [4] = 0, }, }; XSendEvent(globalX11->display, DefaultRootWindow(globalX11->display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*)&e); XFlush(globalX11->display); } static inline void WindowX11_fullscreen_change_state(struct WindowBase* self, const long arg) { XClientMessageEvent e = { .type = ClientMessage, .window = windowX11(self)->window, .message_type = globalX11->atom.wm_state, .format = 32, .data.l = { [0] = (long)arg, [1] = globalX11->atom.wm_fullscreen, [2] = 0, [3] = 0, } }; XSendEvent(globalX11->display, DefaultRootWindow(globalX11->display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*)&e); XFlush(globalX11->display); } static inline void WindowX11_set_stack_order(struct WindowBase* self, bool front_or_back) { if (front_or_back) { XRaiseWindow(globalX11->display, windowX11(self)->window); } else { XLowerWindow(globalX11->display, windowX11(self)->window); } } static void WindowX11_set_fullscreen(struct WindowBase* self, bool fullscreen) { if (fullscreen && !FLAG_IS_SET(self->state_flags, WINDOW_IS_FULLSCREEN)) { WindowX11_fullscreen_change_state(self, _NET_WM_STATE_ADD); FLAG_SET(self->state_flags, WINDOW_IS_FULLSCREEN); } else if (!fullscreen && FLAG_IS_SET(self->state_flags, WINDOW_IS_FULLSCREEN)) { WindowX11_fullscreen_change_state(self, _NET_WM_STATE_REMOVE); FLAG_UNSET(self->state_flags, WINDOW_IS_FULLSCREEN); } } static void WindowX11_set_maximized(struct WindowBase* self, bool maximized) { if (maximized) { WindowX11_set_fullscreen(self, false); FLAG_SET(self->state_flags, WINDOW_IS_MAXIMIZED); } else { FLAG_UNSET(self->state_flags, WINDOW_IS_MAXIMIZED); } XClientMessageEvent e = { .type = ClientMessage, .window = windowX11(self)->window, .message_type = globalX11->atom.wm_state, .format = 32, .data.l = { [0] = maximized ? _NET_WM_STATE_ADD : _NET_WM_STATE_REMOVE, [1] = globalX11->atom.wm_max_vert, [2] = 0, [3] = 0, } }; XSendEvent(globalX11->display, DefaultRootWindow(globalX11->display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*)&e); e.data.l[1] = globalX11->atom.wm_max_horz; XSendEvent(globalX11->display, DefaultRootWindow(globalX11->display), False, SubstructureRedirectMask | SubstructureNotifyMask, (XEvent*)&e); XFlush(globalX11->display); } static void WindowX11_resize(struct WindowBase* self, uint32_t w, uint32_t h) { XWindowChanges changes = { .width = self->w = w, .height = self->h = h, }; XConfigureWindow(globalX11->display, windowX11(self)->window, CWWidth, &changes); Window_notify_content_change(self); } static const char* ACCEPTED_DND_MIMES[] = { "text/uri-list", "text/plain;charset=utf-8", "UTF8_STRING", "text/plain", "STRING", "TEXT", }; static const char* mime_atom_list_select_preferred(Atom* list, size_t n, Atom* atom) { int selected_index = -1; for (uint8_t i = 0; i < n && list[i]; ++i) { char* mime = XGetAtomName(globalX11->display, list[i]); if (!mime) { continue; } LOG("[%u] offered dnd MIME type: %s\n", i, mime); for (uint_fast8_t j = 0; (j < selected_index || selected_index < 0) && j < ARRAY_SIZE(ACCEPTED_DND_MIMES); ++j) { if (!strcmp(mime, ACCEPTED_DND_MIMES[j])) { selected_index = j; if (atom) *atom = list[i]; } } XFree(mime); } return selected_index < 0 ? NULL : ACCEPTED_DND_MIMES[selected_index]; } static void WindowX11_event_map(struct WindowBase* self, XMapEvent* e) { FLAG_UNSET(self->state_flags, WINDOW_IS_MINIMIZED); Window_notify_content_change(self); } static void WindowX11_event_unmap(struct WindowBase* self, XUnmapEvent* e) { FLAG_SET(self->state_flags, WINDOW_IS_MINIMIZED); } static void WindowX11_event_focus_in(struct WindowBase* self, XFocusInEvent* e) { XSetICFocus(globalX11->ic); FLAG_SET(self->state_flags, WINDOW_IS_IN_FOCUS); CALL(self->callbacks.on_focus_changed, self->callbacks.user_data, true); Window_notify_content_change(self); if (Window_is_pointer_hidden(self)) { WindowX11_set_pointer_style(self, MOUSE_POINTER_ARROW); } if (XGetSelectionOwner(globalX11->display, XA_PRIMARY) != windowX11(self)->window) { CALL(self->callbacks.on_primary_changed, self->callbacks.user_data); } } static void WindowX11_event_focus_out(struct WindowBase* self, XFocusOutEvent* e) { XUnsetICFocus(globalX11->ic); FLAG_UNSET(self->state_flags, WINDOW_IS_IN_FOCUS); CALL(self->callbacks.on_focus_changed, self->callbacks.user_data, false); if (Window_is_pointer_hidden(self)) { WindowX11_set_pointer_style(self, MOUSE_POINTER_ARROW); } } static void WindowX11_event_expose(struct WindowBase* self, XExposeEvent* e) { Window_notify_content_change(self); } static void WindowX11_event_configure(struct WindowBase* self, XConfigureEvent* e) { self->x = e->x; self->y = e->y; if (self->w != e->width || self->h != e->height) { self->w = e->width; self->h = e->height; Window_notify_content_change(self); } } static void WindowX11_event_client_message(struct WindowBase* self, XClientMessageEvent* e) { if ((Atom)e->data.l[0] == globalX11->atom.wm_delete) { FLAG_SET(self->state_flags, WINDOW_IS_CLOSED); } else if ((Atom)e->data.l[0] == globalX11->atom.wm_ping) { e->window = DefaultRootWindow(globalX11->display); XSendEvent(globalX11->display, DefaultRootWindow(globalX11->display), True, SubstructureNotifyMask | SubstructureRedirectMask, (XEvent*)e); } else if ((Atom)e->message_type == globalX11->atom.dnd_enter) { const char* mime = NULL; Window source_xid = (Atom)e->data.l[0]; bool source_uses_xdnd_type_list = (Atom)e->data.l[1] & 1; Atom action = (Atom)e->data.l[4]; LOG("X::ClientMessage::dndEnter{ source_xid: %lu, has_type_list: %d, " "protocol_version: %ld }\n", source_xid, source_uses_xdnd_type_list, (Atom)e->data.l[1] >> (sizeof(uint32_t) / sizeof(uint8_t) - 1) * 8); Atom mime_atom = 0; if (source_uses_xdnd_type_list) { unsigned long n_items = 0, bytes_after = 0; Atom* mime_atom_list = NULL; Atom actual_type_ret; int actual_format_ret; int status = XGetWindowProperty(globalX11->display, source_xid, globalX11->atom.dnd_type_list, 0, 65536, False, AnyPropertyType, &actual_type_ret, &actual_format_ret, &n_items, &bytes_after, (unsigned char**)&mime_atom_list); if (status == Success && actual_type_ret != None && actual_format_ret != 0) { mime = mime_atom_list_select_preferred(mime_atom_list, n_items, &mime_atom); XFree(mime_atom_list); } } else { Atom* list = (Atom*)e->data.l; mime = mime_atom_list_select_preferred(list + 2, 3, &mime_atom); } if (mime) { WindowX11_record_dnd_offer(windowX11(self), source_xid, mime, mime_atom, action); } } else if ((Atom)e->message_type == globalX11->atom.dnd_position) { Window source_xid = (Atom)e->data.l[0]; Time timestamp = (Atom)e->data.l[3]; Atom action = (Atom)e->data.l[4]; #ifdef DEBUG char* an = XGetAtomName(globalX11->display, (Atom)action); LOG("X::ClientMessage::dndPosition{ source_xid: %lu, timestamp: %lu, mime: " "%s, action: %lu " "(%s) }\n", source_xid, timestamp, windowX11(self)->dnd_offer.mime_type, action, an); XFree(an); #endif XClientMessageEvent ev = { .message_type = globalX11->atom.dnd_status, .display = globalX11->display, .window = windowX11(self)->dnd_offer.source_xid, .type = ClientMessage, .format = 32, .data.l = { [0] = windowX11(self)->window, [1] = 1, [2] = (self->x << 16) | self->y, // change this when we have splits, [3] = (self->w << 16) | self->h, [4] = action, }, }; if (source_xid == windowX11(self)->dnd_offer.source_xid) { windowX11(self)->dnd_offer.timestamp = timestamp; XSendEvent(globalX11->display, source_xid, True, NoEventMask, (XEvent*)&ev); XFlush(globalX11->display); } else { ev.data.l[1] = 0; ev.data.l[4] = None; XSendEvent(globalX11->display, source_xid, True, NoEventMask, (XEvent*)&ev); XFlush(globalX11->display); WindowX11_drop_dnd_offer(windowX11(self)); } } else if ((Atom)e->message_type == globalX11->atom.dnd_drop) { Window source_xid = (Atom)e->data.l[0]; Time timestamp = (Atom)e->data.l[2]; if (source_xid == windowX11(self)->dnd_offer.source_xid) { LOG("X::ClientMessage::dndDrop { source_xid: %d, timestamp: %d, mime: %s }\n", (int)source_xid, (int)timestamp, windowX11(self)->dnd_offer.mime_type); windowX11(self)->dnd_offer.accepted = true; int ret = XConvertSelection(globalX11->display, globalX11->atom.dnd_selection, windowX11(self)->dnd_offer.mime_type_atom, globalX11->atom.dnd_selection, windowX11(self)->window, timestamp); if (ret == BadWindow || ret == BadAtom) { WRN("XConvertSelection failed: %d\n", ret); } } else { WindowX11_drop_dnd_offer(windowX11(self)); } } else if ((Atom)e->message_type == globalX11->atom.dnd_leave) { LOG("X::ClientMessage::dndLeave { accepted: %d }\n", windowX11(self)->dnd_offer.accepted); WindowX11_drop_dnd_offer(windowX11(self)); } } static void WindowX11_event_mapping(struct WindowBase* self, XMappingEvent* e) { XRefreshKeyboardMapping(e); } static void WindowX11_event_key_press(struct WindowBase* self, XKeyPressedEvent* e) { Status stat = 0; KeySym ret; char buf[5] = { 0 }; uint8_t bytes = Xutf8LookupString(globalX11->ic, e, buf, 4, &ret, &stat); mbstate_t mb = { 0 }; uint32_t code; int no_consume = (stat == 4); mbrtoc32(&code, buf, bytes, &mb); switch (ret) { case XK_Home: case XK_End: case XK_Right: case XK_Left: case XK_Up: case XK_Down: case XK_Insert: case XK_Delete: case XK_Return: case XK_KP_Enter: case XK_Page_Down: case XK_Page_Up: case XK_KP_Page_Down: case XK_KP_Page_Up: case XK_F1 ... XK_F35: case XK_KP_F1 ... XK_KP_F4: no_consume = 1; break; } LOG("X::event::KeyPress{ status:%d, ret:%lu, bytes:%d, code:%u, no_consume:%d }\n", stat, ret, bytes, code, no_consume); if (no_consume) { int32_t lower = XkbKeycodeToKeysym(globalX11->display, e->keycode, 0, 0); CALL(self->callbacks.key_handler, self->callbacks.user_data, stat == 4 ? code : ret, lower, convert_modifier_mask(e->state)); } } static void WindowX11_event_button_press(struct WindowBase* self, XButtonPressedEvent* e) { uint32_t btn; switch (e->button) { case 4: windowX11(self)->last_button_pressed = 0; btn = 65; break; case 5: windowX11(self)->last_button_pressed = 0; btn = 66; break; default: windowX11(self)->last_button_pressed = btn = e->button; } CALL(self->callbacks.button_handler, self->callbacks.user_data, btn, true, e->x, e->y, 0, convert_modifier_mask(e->state)); } static void WindowX11_event_button_release(struct WindowBase* self, XButtonReleasedEvent* e) { if (e->button != 4 && e->button != 5 && e->button) { CALL(self->callbacks.button_handler, self->callbacks.user_data, e->button, false, e->x, e->y, 0, convert_modifier_mask(e->state)); } windowX11(self)->last_button_pressed = 0; } static void WindowX11_event_motion(struct WindowBase* self, XMotionEvent* e) { if (Window_is_pointer_hidden(self)) { WindowX11_set_pointer_style(self, MOUSE_POINTER_ARROW); } CALL(self->callbacks.motion_handler, self->callbacks.user_data, windowX11(self)->last_button_pressed, e->x, e->y); } static void WindowX11_event_selection_clear(struct WindowBase* self, XSelectionClearEvent* e) { if (e->selection == XA_PRIMARY || e->selection == globalX11->atom.clipboard) { RcPtr_destroy_clipboard_content_t(e->selection == XA_PRIMARY ? &windowX11(self)->primary_content : &windowX11(self)->clipboard_content); } } static void WindowX11_event_selection_request(struct WindowBase* self, XSelectionRequestEvent* e) { RcPtr_clipboard_content_t* cc_ptr = e->selection == XA_PRIMARY ? &windowX11(self)->primary_content : e->selection == globalX11->atom.clipboard ? &windowX11(self)->clipboard_content : NULL; clipboard_content_t* cc = RcPtr_get_clipboard_content_t(cc_ptr); if (!cc || !cc->data) { /* deny */ LOG("X::event::SelectionRequestuest{ denied, no data recorded }\n"); XSelectionEvent se = { .type = SelectionNotify, .requestor = e->requestor, .selection = e->selection, .target = e->target, .property = None, .time = e->time, }; XSendEvent(globalX11->display, e->requestor, True, NoEventMask, (XEvent*)&se); } else { /* accept */ size_t data_len = cc->size = strlen(cc->data); #ifdef DEBUG char *tname, *pname, *sname; tname = XGetAtomName(globalX11->display, e->target); pname = XGetAtomName(globalX11->display, e->property); sname = XGetAtomName(globalX11->display, e->selection); LOG("X::event::SelectionRequestuest{ accepted, data: %.10s..., size: %zu/%u, selection: " "%s, target: %s, " "property: %s }\n", cc->data, data_len, globalX11->incr_transfer_out.chunk_size, sname, tname, pname); XFree(tname); XFree(pname); XFree(sname); #endif if (e->target == globalX11->atom.targets) { /* Respond with MIMEs we can provide */ Atom provided_mimes[] = { globalX11->atom.utf8_string_mime_type, globalX11->atom.text_charset_utf8_mime_type, globalX11->atom.text_mime_type, XA_STRING, }; XChangeProperty(globalX11->display, e->requestor, e->property, XA_ATOM, 32, PropModeReplace, (unsigned char*)&provided_mimes, ARRAY_SIZE(provided_mimes)); } else { if (e->target != globalX11->atom.text_charset_utf8_mime_type && e->target != globalX11->atom.utf8_string_mime_type && e->target != globalX11->atom.text_mime_type && e->target != XA_STRING) { return; } if (data_len > globalX11->incr_transfer_out.chunk_size) { LOG("X::event::SelectionRequestuest{ starting incremental transfer out }\n"); RcPtr_new_shared_in_place_of_clipboard_content_t( &globalX11->incr_transfer_out.clipboard_content, cc_ptr); if (globalX11->incr_transfer_out.active && !TimePoint_passed(globalX11->incr_transfer_out.listen_timeout)) { WRN("Previous INCR transfer in progress, refusing selection request\n"); XSelectionEvent se = { .type = SelectionNotify, .requestor = e->requestor, .selection = e->selection, .target = e->target, .property = None, .time = e->time, }; XSendEvent(globalX11->display, e->requestor, True, NoEventMask, (XEvent*)&se); return; } XChangeProperty(globalX11->display, e->requestor, e->property, globalX11->atom.incr, 32, PropModeReplace, None, 0); globalX11->incr_transfer_out.active = true; globalX11->incr_transfer_out.current_offset = 0; globalX11->incr_transfer_out.property = e->property; globalX11->incr_transfer_out.requestor = e->requestor; globalX11->incr_transfer_out.target = e->target; globalX11->incr_transfer_out.listen_timeout = TimePoint_ms_from_now(INCR_TIMEOUT_MS); /* Get prop delete events for the requesting client */ XSelectInput(globalX11->display, e->requestor, PropertyChangeMask); } else { XChangeProperty(globalX11->display, e->requestor, e->property, e->target, 8, PropModeReplace, (unsigned char*)cc->data, data_len); } } XSelectionEvent se = { .type = SelectionNotify, .requestor = e->requestor, .selection = e->selection, .target = e->target, .property = e->property, .time = e->time, }; XSendEvent(globalX11->display, e->requestor, True, NoEventMask, (XEvent*)&se); XFlush(globalX11->display); } } static void WindowX11_event_property_notify(struct WindowBase* self, XPropertyEvent* e) { if (e->state == PropertyDelete && globalX11->incr_transfer_out.active && globalX11->incr_transfer_out.requestor == e->window) { /* continue incremental transfer out */ #ifdef DEBUG char* name = XGetAtomName(globalX11->display, e->atom); LOG("X::event::PropertyNotify{ state: delete, prop: %s }\n", name); XFree(name); #endif clipboard_content_t* cc = RcPtr_get_clipboard_content_t(&globalX11->incr_transfer_out.clipboard_content); if (cc && cc->data && globalX11->incr_transfer_out.current_offset < cc->size) { size_t sz = MIN(globalX11->incr_transfer_out.chunk_size, ((int64_t)cc->size - globalX11->incr_transfer_out.current_offset)); XChangeProperty(globalX11->display, globalX11->incr_transfer_out.requestor, globalX11->incr_transfer_out.property, globalX11->incr_transfer_out.target, 8, PropModeReplace, (unsigned char*)cc->data + globalX11->incr_transfer_out.current_offset, sz); globalX11->incr_transfer_out.current_offset += sz; globalX11->incr_transfer_out.listen_timeout = TimePoint_ms_from_now(INCR_TIMEOUT_MS); LOG("X::event::PropertyNotify{ sent next chunk, %zu bytes }\n", sz); } else { XChangeProperty(globalX11->display, globalX11->incr_transfer_out.requestor, globalX11->incr_transfer_out.property, globalX11->incr_transfer_out.target, 8, PropModeReplace, 0, 0); XSelectInput(globalX11->display, globalX11->incr_transfer_out.requestor, 0); globalX11->incr_transfer_out.current_offset += globalX11->incr_transfer_out.chunk_size; globalX11->incr_transfer_out.active = false; RcPtr_destroy_clipboard_content_t(&globalX11->incr_transfer_out.clipboard_content); LOG("X::event::PropertyNotify{ transfer completed }\n"); } } else if (e->state == PropertyNewValue && e->window == globalX11->incr_transfer_in.source && e->atom == globalX11->incr_transfer_in.listen_property) { /* continue incremental transfer in */ if (TimePoint_passed(globalX11->incr_transfer_in.listen_timeout)) { WRN("Cooperating client (xid: %ld) failed to communicate\n", globalX11->incr_transfer_in.source); Vector_clear_char(&globalX11->incr_transfer_in.data); globalX11->incr_transfer_in.listen_property = 0; globalX11->incr_transfer_in.source = 0; } else { Atom actual_type_return; int actual_format_return; unsigned long n_items, bytes_after; unsigned char* prop_return = NULL; XGetWindowProperty(globalX11->display, globalX11->incr_transfer_in.source, globalX11->incr_transfer_in.listen_property, 0, LONG_MAX, True, // Deleting this tells the source to switch to the next chunk AnyPropertyType, &actual_type_return, &actual_format_return, &n_items, &bytes_after, &prop_return); if (n_items) { #ifdef DEBUG char* name = XGetAtomName(globalX11->display, e->atom); LOG("X::event::PropertyNotify{ state: new value, received %lu byte chunk, prop: %s " "}\n", n_items, name); XFree(name); #endif Vector_pushv_char(&globalX11->incr_transfer_in.data, (char*)prop_return, n_items); globalX11->incr_transfer_in.listen_timeout = TimePoint_ms_from_now(INCR_TIMEOUT_MS); } else { #ifdef DEBUG char* name = XGetAtomName(globalX11->display, e->atom); LOG("X::event::PropertyNotify{ transfer completed, prop: %s }\n", name); XFree(name); #endif Vector_push_char(&globalX11->incr_transfer_in.data, '\0'); CALL(self->callbacks.clipboard_handler, self->callbacks.user_data, globalX11->incr_transfer_in.data.buf); Vector_clear_char(&globalX11->incr_transfer_in.data); globalX11->incr_transfer_in.listen_property = 0; globalX11->incr_transfer_in.source = 0; } XFree(prop_return); } } } static void WindowX11_event_selection_notify(struct WindowBase* self, XSelectionEvent* e) { Atom clip = e->selection; Atom da, actual_type_return; int actual_format_return; unsigned long n_items, bytes_after; unsigned char* prop_return = NULL; Window target = windowX11(self)->window; XGetWindowProperty(globalX11->display, target, clip, 0, 0, False, AnyPropertyType, &actual_type_return, &actual_format_return, &n_items, &bytes_after, &prop_return); #ifdef DEBUG char *cname, *ctype; LOG("X::event::SelectionNotify { name: %s, type_ret: %lu (%s), prop_ret: %s, n: %lu, b:%lu }\n", (cname = clip == 0 ? NULL : XGetAtomName(globalX11->display, clip)), actual_type_return, ctype = (actual_format_return == 0 ? NULL : XGetAtomName(globalX11->display, actual_type_return)), prop_return, n_items, bytes_after); free(ctype); free(cname); #endif XFree(prop_return); if (actual_type_return == globalX11->atom.incr) { /* if data is larger than maximum property size (200-ish k) the selection will * be sent in chunks, 'INCR-ementally'. Initiate transfer by deleting the * property. This tell the source to change it to the first chunk of the actual * data. We will get a PropertyNotify event, set stuff up so we know what to * grab there */ LOG("X::event::SelectionNotify{ start incremental transfer in }\n"); XDeleteProperty(globalX11->display, target, clip); globalX11->incr_transfer_in.listen_property = clip; globalX11->incr_transfer_in.listen_timeout = TimePoint_s_from_now(INCR_TIMEOUT_MS); globalX11->incr_transfer_in.source = target; Vector_clear_char(&globalX11->incr_transfer_in.data); } else { XGetWindowProperty(globalX11->display, target, clip, 0, bytes_after, False, AnyPropertyType, &da, &actual_format_return, &n_items, &bytes_after, &prop_return); if (actual_type_return == globalX11->atom.uri_list_mime_type) { // If we drop files just copy their path(s) Vector_char actual_chars = Vector_new_char(); char* seq = (char*)prop_return; for (char* a; (a = strsep(&seq, "\n"));) { char* start = strstr((char*)a, "://"); if (start) { start += 3; Vector_pushv_char(&actual_chars, start, strlen(start) - 1); Vector_push_char(&actual_chars, ' '); } else { Vector_pop_char(&actual_chars); } } Vector_push_char(&actual_chars, '\0'); self->callbacks.clipboard_handler(self->callbacks.user_data, actual_chars.buf); Vector_destroy_char(&actual_chars); } else { self->callbacks.clipboard_handler(self->callbacks.user_data, (char*)prop_return); } if (clip == globalX11->atom.dnd_selection) { WindowX11_dnd_offer_handled(windowX11(self)); } XFree(prop_return); } XDeleteProperty(globalX11->display, windowX11(self)->window, clip); } static void WindowX11_events(struct WindowBase* self) { static void (*const EVENT_HANDLERS[])(Window_*, XEvent*) = { [MapNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_map, [UnmapNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_unmap, [FocusIn] = (void (*const)(Window_*, XEvent*))WindowX11_event_focus_in, [FocusOut] = (void (*const)(Window_*, XEvent*))WindowX11_event_focus_out, [Expose] = (void (*const)(Window_*, XEvent*))WindowX11_event_expose, [ConfigureNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_configure, [ClientMessage] = (void (*const)(Window_*, XEvent*))WindowX11_event_client_message, [MappingNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_mapping, [KeyPress] = (void (*const)(Window_*, XEvent*))WindowX11_event_key_press, [ButtonPress] = (void (*const)(Window_*, XEvent*))WindowX11_event_button_press, [ButtonRelease] = (void (*const)(Window_*, XEvent*))WindowX11_event_button_release, [MotionNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_motion, [SelectionClear] = (void (*const)(Window_*, XEvent*))WindowX11_event_selection_clear, [SelectionRequest] = (void (*const)(Window_*, XEvent*))WindowX11_event_selection_request, [PropertyNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_property_notify, [SelectionNotify] = (void (*const)(Window_*, XEvent*))WindowX11_event_selection_notify, }; while (XPending(globalX11->display)) { XNextEvent(globalX11->display, &windowX11(self)->event); uint32_t tp = windowX11(self)->event.type; if (tp >= ARRAY_SIZE(EVENT_HANDLERS)) { continue; } void (*const handler)(struct WindowBase*, XEvent*) = EVENT_HANDLERS[tp]; if (handler) { handler(self, &windowX11(self)->event); } } } static void WindowX11_set_current_context(struct WindowBase* self, bool is_this) { if (is_this) { glXMakeCurrent(globalX11->display, windowX11(self)->window, windowX11(self)->glx_context); } else { glXMakeCurrent(globalX11->display, None, NULL); } } static void WindowX11_set_swap_interval(struct WindowBase* self, int32_t ival) { if (glXSwapIntervalEXT) { glXSwapIntervalEXT(globalX11->display, windowX11(self)->window, ival); } } static int64_t WindowX11_get_window_id(struct WindowBase* self) { return windowX11(self)->window; } static void WindowX11_set_title(struct WindowBase* self, const char* title) { ASSERT(title, "string is NULL"); XStoreName(globalX11->display, windowX11(self)->window, title); XChangeProperty(globalX11->display, windowX11(self)->window, XInternAtom(globalX11->display, "_NET_WM_NAME", False), globalX11->atom.utf8_string_mime_type, 8, PropModeReplace, (unsigned char*)title, strlen(title)); XFlush(globalX11->display); } static void WindowX11_set_wm_name(struct WindowBase* self, const char* class_name, const char* opt_name) { ASSERT(class_name, "class name is not NULL"); XClassHint class_hint = { (char*)class_name, (char*)OR(opt_name, class_name) }; XSetClassHint(globalX11->display, windowX11(self)->window, &class_hint); } static bool WindowX11_maybe_swap(struct WindowBase* self) { if (self->paint && !FLAG_IS_SET(self->state_flags, WINDOW_IS_MINIMIZED)) { self->paint = false; CALL(self->callbacks.on_redraw_requested, self->callbacks.user_data); glXSwapBuffers(globalX11->display, windowX11(self)->window); return true; } else { return false; } } static void WindowX11_destroy(struct WindowBase* self) { RcPtr_destroy_clipboard_content_t(&windowX11(self)->clipboard_content); RcPtr_destroy_clipboard_content_t(&windowX11(self)->primary_content); XUndefineCursor(globalX11->display, windowX11(self)->window); XUnmapWindow(globalX11->display, windowX11(self)->window); glXMakeCurrent(globalX11->display, 0, 0); glXDestroyContext(globalX11->display, windowX11(self)->glx_context); XDestroyWindow(globalX11->display, windowX11(self)->window); XFreeCursor(globalX11->display, globalX11->cursor_beam); XFreeCursor(globalX11->display, globalX11->cursor_hidden); XFreeColormap(globalX11->display, windowX11(self)->colormap); XDestroyIC(globalX11->ic); XCloseIM(globalX11->im); XCloseDisplay(globalX11->display); Vector_destroy_char(&globalX11->incr_transfer_in.data); RcPtr_destroy_clipboard_content_t(&globalX11->incr_transfer_out.clipboard_content); free(self); } static int WindowX11_get_connection_fd(struct WindowBase* self) { return ConnectionNumber(globalX11->display); } static uint32_t WindowX11_get_keycode_from_name(struct WindowBase* self, char* name) { KeyCode kcode = XStringToKeysym(name); return kcode == NoSymbol ? 0 : kcode; } static void WindowX11_set_pointer_style(struct WindowBase* self, enum MousePointerStyle style) { switch (style) { case MOUSE_POINTER_HIDDEN: XDefineCursor(globalX11->display, windowX11(self)->window, globalX11->cursor_hidden); FLAG_SET(self->state_flags, WINDOW_IS_POINTER_HIDDEN); break; case MOUSE_POINTER_ARROW: /* use root window's cursor */ XUndefineCursor(globalX11->display, windowX11(self)->window); FLAG_UNSET(self->state_flags, WINDOW_IS_POINTER_HIDDEN); break; case MOUSE_POINTER_I_BEAM: XDefineCursor(globalX11->display, windowX11(self)->window, globalX11->cursor_beam); FLAG_UNSET(self->state_flags, WINDOW_IS_POINTER_HIDDEN); break; case MOUSE_POINTER_HAND: XDefineCursor(globalX11->display, windowX11(self)->window, globalX11->cursor_hand); FLAG_UNSET(self->state_flags, WINDOW_IS_POINTER_HIDDEN); break; } } #endif
38.027952
100
0.570721
[ "vector" ]
63f8d881b0c71fae4177ba8eb1e0b6035b7867a0
1,470
h
C
src/Rendering/Engine/OpenGL/GLInstanceVisualModule.h
Oncle-Ha/peridyno
7952252923d637685bf3a982856aca8095b78c50
[ "Apache-2.0" ]
22
2021-05-26T09:19:07.000Z
2022-03-28T04:06:21.000Z
src/Rendering/Engine/OpenGL/GLInstanceVisualModule.h
Oncle-Ha/peridyno
7952252923d637685bf3a982856aca8095b78c50
[ "Apache-2.0" ]
1
2021-07-27T09:43:42.000Z
2022-02-07T14:47:18.000Z
src/Rendering/Engine/OpenGL/GLInstanceVisualModule.h
Oncle-Ha/peridyno
7952252923d637685bf3a982856aca8095b78c50
[ "Apache-2.0" ]
11
2021-04-24T03:43:33.000Z
2022-03-11T14:09:21.000Z
/** * Copyright 2017-2021 Xiaowei He (xiaowei@iscas.ac.cn) * * 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 * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #pragma once #include "Topology/TriangleSet.h" #include "GLVisualModule.h" #include "GLCudaBuffer.h" #include "gl/VertexArray.h" #include "gl/Program.h" namespace dyno { class GLInstanceVisualModule : public GLVisualModule { DECLARE_CLASS(GLInstanceVisualModule) public: GLInstanceVisualModule(); public: DEF_INSTANCE_IN(TriangleSet<DataType3f>, TriangleSet, ""); DEF_ARRAY_IN(Transform3f, Transform, DeviceType::GPU, ""); protected: virtual void paintGL(RenderPass mode) override; virtual void updateGL() override; virtual bool initializeGL() override; private: gl::Program mShaderProgram; gl::VertexArray mVAO; GLCudaBuffer mVertexBuffer; GLCudaBuffer mIndexBuffer; GLCudaBuffer mInstanceBuffer; unsigned int mVertexCount = 0; unsigned int mIndexCount = 0; unsigned int mInstanceCount = 0; }; };
25.789474
75
0.748299
[ "transform" ]
63f9901b1aa41c7d03ddfa7719f7a5809cedfab9
1,761
h
C
src/cwb/cqp/builtins.h
sylvainloiseau/rcqp
fc7890ecc683633fb79a5c75a2c419bb3ac372d9
[ "BSD-3-Clause" ]
1
2019-12-01T15:37:31.000Z
2019-12-01T15:37:31.000Z
src/cwb/cqp/builtins.h
sylvainloiseau/rcqp
fc7890ecc683633fb79a5c75a2c419bb3ac372d9
[ "BSD-3-Clause" ]
null
null
null
src/cwb/cqp/builtins.h
sylvainloiseau/rcqp
fc7890ecc683633fb79a5c75a2c419bb3ac372d9
[ "BSD-3-Clause" ]
null
null
null
/* * IMS Open Corpus Workbench (CWB) * Copyright (C) 1993-2006 by IMS, University of Stuttgart * Copyright (C) 2007- by the respective contributers (see file AUTHORS) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2, 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 (in the file "COPYING", or available via * WWW at http://www.gnu.org/copyleft/gpl.html). */ #ifndef _cqp_builtins_h_ #define _cqp_builtins_h_ #include "../cl/cdaccess.h" #include "eval.h" /** * The BuiltinF object represents a built-in function. */ typedef struct _builtinf { int id; /**< The id code of this function @see call_predefined_function */ char *name; /**< The name of this function */ int nr_args; /**< How many arguments the function has */ int *argtypes; /**< Address of an ordered array of argument types ("types" are ATTAT_x constants) */ int result_type; /**< Type of the function's result ("types" are ATTAT_x constants) */ } BuiltinF; extern BuiltinF builtin_function[]; int find_predefined(char *name); int is_predefined_function(char *name); int call_predefined_function(int bf_id, DynCallResult *apl, int nr_args, Constrainttree ctptr, DynCallResult *result); #endif
35.22
111
0.657013
[ "object" ]
63ff4d732d73e64fbffb1e32493c63344770bd90
1,754
h
C
EzAcc/DemoProject/Input Combos/Motor2D/ctKenStageScene.h
Wilhelman/EzAcc-EasyAccessibilityFramework
d785c5f9c36367f6da7a89d10b1b80bd8b382173
[ "MIT" ]
null
null
null
EzAcc/DemoProject/Input Combos/Motor2D/ctKenStageScene.h
Wilhelman/EzAcc-EasyAccessibilityFramework
d785c5f9c36367f6da7a89d10b1b80bd8b382173
[ "MIT" ]
null
null
null
EzAcc/DemoProject/Input Combos/Motor2D/ctKenStageScene.h
Wilhelman/EzAcc-EasyAccessibilityFramework
d785c5f9c36367f6da7a89d10b1b80bd8b382173
[ "MIT" ]
null
null
null
#ifndef __ctKenStageScene_H__ #define __ctKenStageScene_H__ #include "ctModule.h" #include "ctAnimation.h" #include "ctGui.h" struct SDL_Surface; class ctKenStageScene : public ctModule { public: ctKenStageScene(); // Destructor virtual ~ctKenStageScene(); // Called before render is available bool Awake(pugi::xml_node& conf); // Called before the first frame bool Start(); // Called before all Updates bool PreUpdate(); // Called each loop iteration bool Update(float dt); // Called before all Updates bool PostUpdate(); // Called before quitting bool CleanUp(); bool Load(pugi::xml_node&); bool Save(pugi::xml_node&) const; void OnUITrigger(UIElement* elementTriggered, UI_State ui_state); SDL_Surface* backgroundSurface; SDL_Texture* atlas_tex = nullptr; private: void LoadAnimation(pugi::xml_node animation_node, ctAnimation* animation); void LoadRect(pugi::xml_node rect_node, SDL_Rect* rect); void SetSceneAnimationsSpeed(float dt); void SetEntitiesSpeed(float dt); private: bool quit_pressed = false; float foreground_pos = 0.0f; bool forward_foreground = false; std::string atlas_name; SDL_Rect ground = { 0,0,0,0 }; SDL_Rect foreground = { 0,0,0,0 }; SDL_Rect background = { 0,0,0,0 }; //animations ctAnimation flag = ctAnimation(); ctAnimation girl = ctAnimation(); ctAnimation two_guys = ctAnimation(); ctAnimation green_guy = ctAnimation(); ctAnimation blue_guy = ctAnimation(); ctAnimation fedora_guy = ctAnimation(); ctAnimation pink_guy = ctAnimation(); //animations velocity uint girl_vel = 0u, flag_vel = 0u, two_guys_vel = 0u, green_guy_vel = 0u, blue_guy_vel = 0u, fedora_guy_vel = 0u, pink_guy_vel = 0u; bool key_speed = false; }; #endif // __ctKenStageScene_H__
21.13253
133
0.741163
[ "render" ]
120c3e193ccc6dc10b2ca96821e632515e02f634
41,167
c
C
src/client/operate.c
sustmi/aerospike-client-php
399bdf2cf848d9ab0ff4405da2193a8fb4f90c7d
[ "Apache-2.0" ]
null
null
null
src/client/operate.c
sustmi/aerospike-client-php
399bdf2cf848d9ab0ff4405da2193a8fb4f90c7d
[ "Apache-2.0" ]
null
null
null
src/client/operate.c
sustmi/aerospike-client-php
399bdf2cf848d9ab0ff4405da2193a8fb4f90c7d
[ "Apache-2.0" ]
null
null
null
// ***************************************************************************** // Copyright 2017 Aerospike, Inc. // // Licensed under the Apache License, Version 2.0 (the "License") // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ***************************************************************************** #include "aerospike_class.h" #include "php_aerospike_types.h" #include "conversions.h" #include "policy_conversions.h" static inline bool op_requires_long_val(int op_type); static inline bool op_requires_list_val(int op_type); static inline bool op_requires_val(int op_type); static inline bool op_requires_as_val(int op_type); static inline bool op_requires_index(int op_type); static inline bool op_is_map_op(int op_type); /* Map op helpers */ static inline bool map_op_requires_key(int op_type); static inline bool map_op_requires_rank(int op_type); static inline bool map_op_requires_return_type(int op_type); static inline bool map_op_requires_map_policy(int op_type); static inline bool map_op_requires_val(int op_type); static inline bool map_op_requires_index(int op_type); static inline bool map_op_requires_count(int op_type); static inline bool map_op_requires_range_end(int op_type); static as_status add_map_op_to_operations(HashTable* op_array, int op_type, const char* bin_name, as_operations* ops, as_error* err, int serializer_type); static as_status add_op_to_operations(HashTable* op_array, as_operations* ops, as_error* err, int serializer_type); static as_status get_count_from_op_hash(as_error* err, HashTable* op_hash, uint64_t* count); static as_status get_rank_from_op_hash(as_error* err, HashTable* op_hash, int64_t* rank); static as_status get_index_from_op_hash(as_error* err, HashTable* op_hash, int64_t* index); static as_status get_key_from_op_hash(as_error* err, HashTable* op_hash, as_val** key, int serializer_type); static as_status get_value_from_op_hash(as_error* err, HashTable* op_hash, as_val** val, int serializer_type); static as_status get_range_end_from_op_hash(as_error* err, HashTable* op_hash, as_val** range_end, int serializer_type); static as_status get_map_policy_from_op_hash(as_error* err, HashTable* op_hash, as_map_policy* map_policy_p); static as_status get_return_type_from_op_hash(as_error* err, HashTable* op_hash, as_map_return_type* return_type); #define AS_MAP_POLICY_KEY "map_policy" #define AS_MAP_RANK_KEY "rank" #define AS_MAP_COUNT_KEY "count" #define AS_MAP_KEY_KEY "key" #define AS_MAP_INDEX_KEY "index" #define AS_MAP_RETURN_TYPE_KEY "return_type" #define AS_MAP_VALUE_KEY "val" #define AS_MAP_RANGE_END "range_end" /* {{{ proto int Aerospike::operate( array key, array operations [,array &returned [,array options ]] ) Performs multiple operation on a record */ PHP_METHOD(Aerospike, operate) { as_error err; as_operations ops; as_policy_operate operate_policy; as_policy_operate* operate_policy_p = NULL; zval* z_operate_policy = NULL; HashTable* z_ops = NULL; HashTable* z_key = NULL; as_key key; zval* retval = NULL; aerospike* as_client = NULL; AerospikeClient* php_client = NULL; int operations_size = 0; bool key_initialized = false; bool operations_initialized = false; as_record* rec = NULL; int serializer_type = INI_INT("aerospike.serializer"); as_error_init(&err); reset_client_error(getThis()); if(zend_parse_parameters(ZEND_NUM_ARGS(), "hh|z/z", &z_key, &z_ops, &retval, &z_operate_policy) == FAILURE) { update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid Parameters for operate", false); RETURN_LONG(AEROSPIKE_ERR_PARAM); } if (retval) { zval_dtor(retval); ZVAL_NULL(retval); } php_client = get_aerospike_from_zobj(Z_OBJ_P(getThis())); if (!php_client || !php_client->as_client || !php_client->is_valid) { update_client_error(getThis(), AEROSPIKE_ERR_CLIENT, "Invalid aerospike object", false); RETURN_LONG(AEROSPIKE_ERR_CLIENT); } as_client = php_client->as_client; if (!php_client->is_connected) { update_client_error(getThis(), AEROSPIKE_ERR_CLUSTER, "No connection to Aerospike server", false); RETURN_LONG(AEROSPIKE_ERR_CLUSTER); } if(z_hashtable_to_as_key(z_key, &key, &err) != AEROSPIKE_OK) { update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid key", err.in_doubt); RETURN_LONG(AEROSPIKE_ERR_PARAM); } key_initialized = true; if(zval_to_as_policy_operate(z_operate_policy, &operate_policy, &operate_policy_p, &as_client->config.policies.operate) != AEROSPIKE_OK) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid operate policy"); err.code = AEROSPIKE_ERR_PARAM; goto CLEANUP; } else { operate_policy_p = &operate_policy; } operations_size = zend_hash_num_elements(z_ops); if (!operations_size) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Empty operations array"); goto CLEANUP; } set_serializer_from_policy_hash(&serializer_type, z_operate_policy); as_operations_inita(&ops, operations_size); operations_initialized = true; if (set_operations_generation_from_operate_policy(&ops, z_operate_policy) != AEROSPIKE_OK) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid generation policy"); goto CLEANUP; } if (set_operations_ttl_from_operate_policy(&ops, z_operate_policy) != AEROSPIKE_OK) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid generation policy"); goto CLEANUP; } if (!hashtable_is_list(z_ops)) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Operations array must be a list"); goto CLEANUP; } zval* current_op = NULL; ZEND_HASH_FOREACH_VAL(z_ops, current_op) { if (Z_TYPE_P(current_op) != IS_ARRAY) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Operation must be an array"); goto CLEANUP; } if (add_op_to_operations(Z_ARRVAL_P(current_op), &ops, &err, serializer_type) != AEROSPIKE_OK) { as_error_update(&err, err.code, NULL); goto CLEANUP; } }ZEND_HASH_FOREACH_END(); if (aerospike_key_operate(as_client, &err, operate_policy_p, &key, &ops, &rec) != AEROSPIKE_OK) { update_client_error(getThis(), err.code, err.message, err.in_doubt); goto CLEANUP; } if (retval) { as_bins_to_zval(rec, retval, &err); } CLEANUP: if (key_initialized) { as_key_destroy(&key); } if (operations_initialized) { as_operations_destroy(&ops); } if (rec) { as_record_destroy(rec); } if (err.code != AEROSPIKE_OK) { update_client_error(getThis(), err.code, err.message, err.in_doubt); } RETURN_LONG(err.code); } /* }}} */ /* {{{ proto int Aerospike::operateOrdered( array key, array operations [,array &returned [,array options ]] ) Performs multiple operation on a record */ PHP_METHOD(Aerospike, operateOrdered) { as_error err; as_operations ops; as_policy_operate operate_policy; as_policy_operate* operate_policy_p = NULL; zval* z_operate_policy = NULL; HashTable* z_ops = NULL; HashTable* z_key = NULL; as_key key; zval* retval = NULL; aerospike* as_client = NULL; AerospikeClient* php_client = NULL; int operations_size = 0; bool key_initialized = false; bool operations_initialized = false; as_record* rec = NULL; int serializer_type = INI_INT("aerospike.serializer"); as_error_init(&err); reset_client_error(getThis()); if(zend_parse_parameters(ZEND_NUM_ARGS(), "hh|z/z", &z_key, &z_ops, &retval, &z_operate_policy) == FAILURE) { update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid Parameters for operateOrdered", false); RETURN_LONG(AEROSPIKE_ERR_PARAM); } if (retval) { zval_dtor(retval); ZVAL_NULL(retval); } php_client = get_aerospike_from_zobj(Z_OBJ_P(getThis())); if (!php_client || !php_client->as_client || !php_client->is_valid) { update_client_error(getThis(), AEROSPIKE_ERR_CLIENT, "Invalid aerospike object", false); RETURN_LONG(AEROSPIKE_ERR_CLIENT); } as_client = php_client->as_client; if (!php_client->is_connected) { update_client_error(getThis(), AEROSPIKE_ERR_CLUSTER, "No connection to Aerospike server", false); RETURN_LONG(AEROSPIKE_ERR_CLUSTER); } if(z_hashtable_to_as_key(z_key, &key, &err) != AEROSPIKE_OK) { update_client_error(getThis(), AEROSPIKE_ERR_PARAM, "Invalid key", false); RETURN_LONG(AEROSPIKE_ERR_PARAM); } key_initialized = true; if (z_operate_policy){ if(zval_to_as_policy_operate(z_operate_policy, &operate_policy, &operate_policy_p, &as_client->config.policies.operate) != AEROSPIKE_OK) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid operate policy"); goto CLEANUP; } } operations_size = zend_hash_num_elements(z_ops); if (!operations_size) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Empty operations array"); goto CLEANUP; } set_serializer_from_policy_hash(&serializer_type, z_operate_policy); as_operations_inita(&ops, operations_size); operations_initialized = true; if (set_operations_generation_from_operate_policy(&ops, z_operate_policy) != AEROSPIKE_OK) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid generation policy"); err.code = AEROSPIKE_ERR_PARAM; goto CLEANUP; } if (set_operations_ttl_from_operate_policy(&ops, z_operate_policy) != AEROSPIKE_OK) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Invalid TTL"); err.code = AEROSPIKE_ERR_PARAM; goto CLEANUP; } zval* current_op = NULL; zend_string* string_key = NULL; ZEND_HASH_FOREACH_STR_KEY_VAL(z_ops, string_key, current_op) { if (string_key) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Operations array must not have string keys"); err.code = AEROSPIKE_ERR_PARAM; goto CLEANUP; } if (Z_TYPE_P(current_op) != IS_ARRAY) { as_error_update(&err, AEROSPIKE_ERR_PARAM, "Operation must be an array"); err.code = AEROSPIKE_ERR_PARAM; goto CLEANUP; } if (add_op_to_operations(Z_ARRVAL_P(current_op), &ops, &err, serializer_type) != AEROSPIKE_OK) { update_client_error(getThis(), err.code, err.message, err.in_doubt); goto CLEANUP; } }ZEND_HASH_FOREACH_END(); if (aerospike_key_operate(as_client, &err, operate_policy_p, &key, &ops, &rec) != AEROSPIKE_OK) { update_client_error(getThis(), err.code, err.message, err.in_doubt); goto CLEANUP; } if (retval) { as_operate_record_to_zval(rec, retval, &err); } CLEANUP: if (key_initialized) { as_key_destroy(&key); } if (operations_initialized) { as_operations_destroy(&ops); } if (rec) { as_record_destroy(rec); } if (err.code != AEROSPIKE_OK) { update_client_error(getThis(), err.code, err.message, err.in_doubt); } RETURN_LONG(err.code); } /* }}} */ /* Helper function to add a php operation array to an as_operations struct * Internally checks and validates entries in the array, then adds the operation to * the operations. * returns AEROSPIKE_OK on success, other status code on failure */ static as_status add_op_to_operations(HashTable* op_array, as_operations* ops, as_error* err, int serializer_type) { int op_type; long index; zval* z_op = NULL; zval* z_op_val = NULL; zval* z_index = NULL; zval* z_bin = NULL; as_val* op_val = NULL; char* bin_name = NULL; z_op = zend_hash_str_find(op_array, "op", strlen("op")); if (!z_op) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation does not specify a type"); return AEROSPIKE_ERR_PARAM; } if (Z_TYPE_P(z_op) != IS_LONG) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation type must be an integer"); return AEROSPIKE_ERR_PARAM; } op_type = Z_LVAL_P(z_op); //handle touch differently since it is unique if (op_type == AS_OPERATOR_TOUCH) { z_op_val = zend_hash_str_find(op_array, "ttl", strlen("ttl")); if (z_op_val) { if (Z_TYPE_P(z_op_val) != IS_LONG) { as_error_update(err, AEROSPIKE_ERR_PARAM, "TTL must be an integer"); return AEROSPIKE_ERR_PARAM; } ops->ttl = (uint32_t)Z_LVAL_P(z_op_val); as_operations_add_touch(ops); } return AEROSPIKE_OK; } z_bin = zend_hash_str_find(op_array, "bin", strlen("bin")); if (!z_bin || Z_TYPE_P(z_bin) != IS_STRING) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must contain a bin name of string type"); return AEROSPIKE_ERR_PARAM; } bin_name = Z_STRVAL_P(z_bin); if (strlen(bin_name) > AS_BIN_NAME_MAX_LEN) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Bin name is too long"); return AEROSPIKE_ERR_PARAM; } /* * Verify required types and arguments for each operation */ if (op_requires_index(op_type)) { z_index = zend_hash_str_find(op_array, "index", strlen("index")); if (!z_index || Z_TYPE_P(z_index) != IS_LONG) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation requires an integer index"); return AEROSPIKE_ERR_PARAM; } index = Z_LVAL_P(z_index); } /* If it's a map operation, use the map op helper function */ if (op_is_map_op(op_type)) { return add_map_op_to_operations(op_array, op_type, bin_name, ops, err, serializer_type); } /* * Type check "val" member of the op array */ if (op_requires_val(op_type)) { z_op_val = zend_hash_str_find(op_array, "val", strlen("val")); if (!z_op_val) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation requires a val entry"); return AEROSPIKE_ERR_PARAM; } if (op_requires_list_val(op_type)) { if (Z_TYPE_P(z_op_val) != IS_ARRAY) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation requires a list val entry"); return AEROSPIKE_ERR_PARAM; } } else if (op_requires_long_val(op_type)) { if (Z_TYPE_P(z_op_val) != IS_LONG) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation requires an integer val entry"); return AEROSPIKE_ERR_PARAM; } } if (op_requires_as_val(op_type)) { zval_to_as_val(z_op_val, &op_val, err, serializer_type); if (!op_val || err->code != AEROSPIKE_OK) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Unable to convert value"); return AEROSPIKE_ERR_PARAM; } } } /* * Handle each different operation type differently */ switch(op_type) { case AS_OPERATOR_WRITE: { if (!as_operations_add_write(ops, bin_name, (as_bin_value*)op_val)) { as_val_destroy(op_val); as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case AS_OPERATOR_READ: { if (!as_operations_add_read(ops, bin_name)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case AS_OPERATOR_INCR: { if (Z_TYPE_P(z_op_val) == IS_LONG) { if (!as_operations_add_incr(ops, bin_name, Z_LVAL_P(z_op_val))) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } } else if (Z_TYPE_P(z_op_val) == IS_DOUBLE) { if (!as_operations_add_incr_double(ops, bin_name, Z_DVAL_P(z_op_val))) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } } else if (Z_TYPE_P(z_op_val) == IS_STRING) { zend_long incr_long; double incr_double; switch (is_numeric_string(Z_STRVAL_P(z_op_val), Z_STRLEN_P(z_op_val), &incr_long, &incr_double, 0)) { case IS_DOUBLE: if (!as_operations_add_incr_double(ops, bin_name, incr_double)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; case IS_LONG: if (!as_operations_add_incr(ops, bin_name, incr_long)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; default: as_error_update(err, AEROSPIKE_ERR_PARAM, "incr operation requires a long or double value"); return AEROSPIKE_ERR_PARAM; } } else { as_error_update(err, AEROSPIKE_ERR_PARAM, "incr operation requires a long or double value"); return AEROSPIKE_ERR_PARAM; } break; } case AS_OPERATOR_PREPEND: { if (Z_TYPE_P(z_op_val) != IS_STRING) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Prepend requires a string value"); return AEROSPIKE_ERR_PARAM; } if (!as_operations_add_prepend_str(ops, bin_name, Z_STRVAL_P(z_op_val))) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case AS_OPERATOR_APPEND: { if (Z_TYPE_P(z_op_val) != IS_STRING) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Append requires a string value"); return AEROSPIKE_ERR_PARAM; } if (!as_operations_add_append_str(ops, bin_name, Z_STRVAL_P(z_op_val))) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } /** Start of list operations **/ case OP_LIST_APPEND: { if (!as_operations_add_list_append(ops, bin_name, op_val)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_MERGE: { /* This op requires a zval list*/ // We know this is a list because of the check for non list earlier if (!hashtable_is_list(Z_ARRVAL_P(z_op_val))) { as_error_update(err, AEROSPIKE_ERR_PARAM, "List Merge value must not be a map"); return AEROSPIKE_ERR_CLIENT; } as_list* op_list = NULL; if (z_hashtable_to_as_list( Z_ARRVAL_P(z_op_val), &op_list, err, serializer_type) != AEROSPIKE_OK) { return err->code; } if (!as_operations_add_list_append_items(ops, bin_name, op_list)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_INSERT: { if(!as_operations_add_list_insert(ops, bin_name, index, op_val)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_INSERT_ITEMS: { if (!hashtable_is_list(Z_ARRVAL_P(z_op_val))) { as_error_update(err, AEROSPIKE_ERR_PARAM, "List Merge value must not be a map"); return AEROSPIKE_ERR_CLIENT; } as_list* op_list = NULL; if (z_hashtable_to_as_list( Z_ARRVAL_P(z_op_val), &op_list, err, serializer_type) != AEROSPIKE_OK) { return err->code; } if (!as_operations_add_list_insert_items(ops, bin_name, index, (as_list*)op_list)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_POP: { if(!as_operations_add_list_pop(ops, bin_name, index)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_POP_RANGE: { long count = Z_LVAL_P(z_op_val); if(!as_operations_add_list_pop_range(ops, bin_name, index, count)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_REMOVE: { if(!as_operations_add_list_remove(ops, bin_name, index)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_REMOVE_RANGE: { long count = Z_LVAL_P(z_op_val); if(!as_operations_add_list_remove_range(ops, bin_name, index, count)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_CLEAR: { if(!as_operations_add_list_clear(ops, bin_name)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_SET: { if(!as_operations_add_list_set(ops, bin_name, index, op_val)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_GET: { if(!as_operations_add_list_get(ops, bin_name, index)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_GET_RANGE: { long count = Z_LVAL_P(z_op_val); if(!as_operations_add_list_get_range(ops, bin_name, index, count)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_TRIM: { long count = Z_LVAL_P(z_op_val); if(!as_operations_add_list_trim(ops, bin_name, index, count)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } case OP_LIST_SIZE: { if(!as_operations_add_list_size(ops, bin_name)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Unable to add operation"); return AEROSPIKE_ERR_CLIENT; } break; } default: { if (op_val) { as_val_destroy(op_val); } as_error_update(err, AEROSPIKE_ERR_PARAM, "Unknown operation type"); return AEROSPIKE_ERR_PARAM; } } return AEROSPIKE_OK; } static as_status add_map_op_to_operations(HashTable* op_array, int op_type, const char* bin_name, as_operations* ops, as_error* err, int serializer_type) { uint64_t count; int64_t index; int64_t rank; as_val* range_end = NULL; as_val* val = NULL; as_val* key = NULL; as_map_policy map_policy; as_map_return_type return_type; if (map_op_requires_count(op_type)) { if (get_count_from_op_hash(err, op_array, &count) != AEROSPIKE_OK) { return err->code; } } if (map_op_requires_index(op_type)) { if (get_index_from_op_hash(err, op_array, &index) != AEROSPIKE_OK) { return err->code; } } if (map_op_requires_rank(op_type)) { if (get_rank_from_op_hash(err, op_array, &rank) != AEROSPIKE_OK) { return err->code; } } if (map_op_requires_return_type(op_type)) { if (get_return_type_from_op_hash(err, op_array, &return_type) != AEROSPIKE_OK) { return err->code; } } if (map_op_requires_map_policy(op_type)) { if (get_map_policy_from_op_hash(err, op_array, &map_policy) != AEROSPIKE_OK) { return err->code; } } if (map_op_requires_key(op_type)) { if (get_key_from_op_hash(err, op_array, &key, serializer_type) != AEROSPIKE_OK) { goto CLEANUP; } } if (map_op_requires_range_end(op_type)) { if (get_range_end_from_op_hash(err, op_array, &range_end, serializer_type) != AEROSPIKE_OK) { goto CLEANUP; } } if (map_op_requires_val(op_type)) { if (get_value_from_op_hash(err, op_array, &val, serializer_type) != AEROSPIKE_OK) { goto CLEANUP; } } switch(op_type) { /* 1 */ case OP_MAP_SET_POLICY: if (!as_operations_add_map_set_policy(ops, bin_name, &map_policy)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_SET_POLICY operation"); } break; /* 2 */ case OP_MAP_PUT: if (!as_operations_add_map_put(ops, bin_name, &map_policy, key, val)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_PUT operation"); } break; /* 3 */ case OP_MAP_PUT_ITEMS: { as_map* map = NULL; if (as_val_type(val) != AS_MAP) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Value must be a hashtable for OP_MAP_PUT_ITEMS"); goto CLEANUP; } map = as_map_fromval(val); if (!map) { as_error_update(err, AEROSPIKE_ERR_PARAM, "Failed to store map put items"); goto CLEANUP; } if (!as_operations_add_map_put_items(ops, bin_name, &map_policy, map)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_PUT_ITEMS operation"); } break; } /* 4 */ case OP_MAP_INCREMENT: if (!as_operations_add_map_increment(ops, bin_name, &map_policy, key, val)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_INCREMENT operation"); } break; /* 5 */ case OP_MAP_DECREMENT: if (!as_operations_add_map_decrement(ops, bin_name, &map_policy, key, val)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_INCREMENT operation"); } break; /* 6 */ case OP_MAP_SIZE: if (!as_operations_add_map_size(ops, bin_name)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_SIZE operation"); } break; /* 7 */ case OP_MAP_CLEAR: if (!as_operations_add_map_clear(ops, bin_name)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_CLEAR operation"); } break; /* 8 */ case OP_MAP_REMOVE_BY_KEY: if (!as_operations_add_map_remove_by_key(ops, bin_name, key, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_KEY operation"); } break; /* 9 */ case OP_MAP_REMOVE_BY_KEY_LIST: { as_list* key_list = NULL; if (as_val_type(key) != AS_LIST) { as_error_update(err, AEROSPIKE_ERR_PARAM, "list of keys must be an array"); goto CLEANUP; } key_list = as_list_fromval(key); if (!key_list) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to store key list for remove by key list"); goto CLEANUP; } if (!as_operations_add_map_remove_by_key_list(ops, bin_name, key_list, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_KEY_LIST operation"); } break; } /* 10 */ case OP_MAP_REMOVE_BY_KEY_RANGE: if (!as_operations_add_map_remove_by_key_range(ops, bin_name, key, range_end, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_KEY_RANGE operation"); } break; /* 11 */ case OP_MAP_REMOVE_BY_VALUE: if (!as_operations_add_map_remove_by_value(ops, bin_name, val, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_VALUE operation"); } break; /* 12 */ case OP_MAP_REMOVE_BY_VALUE_LIST: { as_list* val_list = NULL; if (as_val_type(val) != AS_LIST) { as_error_update(err, AEROSPIKE_ERR_PARAM, "list of values must be an array"); goto CLEANUP; } val_list = as_list_fromval(val); if (!val_list) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to store key list for remove by value list"); goto CLEANUP; } if (!as_operations_add_map_remove_by_value_list(ops, bin_name, val_list, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_VALUE_LIST operation"); } break; } /* 13 */ case OP_MAP_REMOVE_BY_VALUE_RANGE: if (!as_operations_add_map_remove_by_value_range(ops, bin_name, val, range_end, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_VALUE_RANGE operation"); } break; /* 14 */ case OP_MAP_REMOVE_BY_INDEX: if (!as_operations_add_map_remove_by_index(ops, bin_name, index, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_INDEX operation"); } break; /* 15 */ case OP_MAP_REMOVE_BY_INDEX_RANGE: if (!as_operations_add_map_remove_by_index_range(ops, bin_name, index, count, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_INDEX_RANGE operation"); } break; /* 16 */ case OP_MAP_REMOVE_BY_RANK: if (!as_operations_add_map_remove_by_rank(ops, bin_name, rank, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_RANK operation"); } break; /* 17 */ case OP_MAP_REMOVE_BY_RANK_RANGE: if (!as_operations_add_map_remove_by_rank_range(ops, bin_name, rank, count, return_type)) { return as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_REMOVE_BY_RANK_RANGE operation"); } break; /* 18 */ case OP_MAP_GET_BY_KEY: if (!as_operations_add_map_get_by_key(ops, bin_name, key, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_KEY operation"); } break; /* 19 */ case OP_MAP_GET_BY_KEY_RANGE: if (!as_operations_add_map_get_by_key_range(ops, bin_name, key, range_end, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_KEY_RANGE operation"); } break; /* 20 */ case OP_MAP_GET_BY_VALUE: if (!as_operations_add_map_get_by_value(ops, bin_name, val, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_VALUE operation"); } break; /* 21 */ case OP_MAP_GET_BY_VALUE_RANGE: if (!as_operations_add_map_get_by_value_range(ops, bin_name, val, range_end, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_VALUE_RANGE operation"); } break; /* 22 */ case OP_MAP_GET_BY_INDEX: if (!as_operations_add_map_get_by_index(ops, bin_name, index, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_INDEX operation"); } break; /* 23 */ case OP_MAP_GET_BY_INDEX_RANGE: if (!as_operations_add_map_get_by_index_range(ops, bin_name, index, count, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_INDEX_RANGE operation"); } break; /* 24 */ case OP_MAP_GET_BY_RANK: if (!as_operations_add_map_get_by_rank(ops, bin_name, rank, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_RANK operation"); } break; /* 25 */ case OP_MAP_GET_BY_RANK_RANGE: if (!as_operations_add_map_get_by_rank_range(ops, bin_name, rank, count, return_type)) { as_error_update(err, AEROSPIKE_ERR_CLIENT, "Failed to add OP_MAP_GET_BY_RANK_RANGE operation"); } break; default: as_error_update(err, AEROSPIKE_ERR_PARAM, "Unknown map operation"); break; } CLEANUP: /* * as_val* range_end = NULL; as_val* val = NULL; as_val* key = NULL; */ if (err->code != AEROSPIKE_OK) { if (range_end) { as_val_destroy(range_end); } if (val) { as_val_destroy(val); } if (key) { as_val_destroy(key); } } return err->code; } static inline bool op_requires_val(int op_type) { return (op_type != AS_OPERATOR_TOUCH && op_type != OP_LIST_CLEAR && op_type != AS_OPERATOR_READ && op_type != OP_LIST_SIZE && op_type != OP_LIST_POP && op_type != OP_LIST_REMOVE && op_type != OP_LIST_GET && op_type != OP_MAP_SIZE && op_type != OP_MAP_CLEAR); } static inline bool op_is_map_op(int op_type) { return ( op_type == OP_MAP_SET_POLICY || op_type == OP_MAP_PUT || op_type == OP_MAP_PUT_ITEMS || op_type == OP_MAP_INCREMENT || op_type == OP_MAP_DECREMENT || op_type == OP_MAP_SIZE || op_type == OP_MAP_CLEAR || op_type == OP_MAP_REMOVE_BY_KEY || op_type == OP_MAP_REMOVE_BY_KEY_LIST || op_type == OP_MAP_REMOVE_BY_KEY_RANGE || op_type == OP_MAP_REMOVE_BY_VALUE || op_type == OP_MAP_REMOVE_BY_VALUE_LIST || op_type == OP_MAP_REMOVE_BY_VALUE_RANGE || op_type == OP_MAP_REMOVE_BY_INDEX || op_type == OP_MAP_REMOVE_BY_INDEX_RANGE || op_type == OP_MAP_REMOVE_BY_RANK || op_type == OP_MAP_REMOVE_BY_RANK_RANGE || op_type == OP_MAP_GET_BY_KEY || op_type == OP_MAP_GET_BY_KEY_RANGE || op_type == OP_MAP_GET_BY_VALUE || op_type == OP_MAP_GET_BY_VALUE_RANGE || op_type == OP_MAP_GET_BY_INDEX || op_type == OP_MAP_GET_BY_INDEX_RANGE || op_type == OP_MAP_GET_BY_RANK || op_type == OP_MAP_GET_BY_RANK_RANGE); } static inline bool op_requires_list_val(int op_type) { return (op_type == OP_LIST_MERGE || op_type == OP_LIST_INSERT_ITEMS); } static inline bool op_requires_long_val(int op_type) { return (op_type == OP_LIST_POP_RANGE || op_type == OP_LIST_REMOVE_RANGE || op_type == OP_LIST_GET_RANGE || op_type == OP_LIST_TRIM); } static inline bool op_requires_as_val(int op_type) { return (op_type == OP_LIST_INSERT || op_type == OP_LIST_SET || op_type == OP_LIST_APPEND || op_type == AS_OPERATOR_WRITE); } static inline bool op_requires_index(int op_type) { return (op_type == OP_LIST_INSERT || op_type == OP_LIST_INSERT_ITEMS || op_type == OP_LIST_POP || op_type == OP_LIST_POP_RANGE || op_type == OP_LIST_REMOVE || op_type == OP_LIST_REMOVE_RANGE || op_type == OP_LIST_SET || op_type == OP_LIST_GET || op_type == OP_LIST_GET_RANGE || op_type == OP_LIST_TRIM); } /* Map op argument classifiers */ static inline bool map_op_requires_map_return_type(int op_type) { return ( op_type == OP_MAP_REMOVE_BY_KEY || op_type == OP_MAP_REMOVE_BY_KEY_LIST || op_type == OP_MAP_REMOVE_BY_KEY_RANGE || op_type == OP_MAP_REMOVE_BY_VALUE || op_type == OP_MAP_REMOVE_BY_VALUE_LIST || op_type == OP_MAP_REMOVE_BY_VALUE_RANGE || op_type == OP_MAP_REMOVE_BY_INDEX || op_type == OP_MAP_REMOVE_BY_INDEX_RANGE || op_type == OP_MAP_REMOVE_BY_RANK || op_type == OP_MAP_REMOVE_BY_RANK_RANGE || op_type == OP_MAP_GET_BY_KEY || op_type == OP_MAP_GET_BY_KEY_RANGE || op_type == OP_MAP_GET_BY_VALUE || op_type == OP_MAP_GET_BY_VALUE_RANGE || op_type == OP_MAP_GET_BY_INDEX || op_type == OP_MAP_GET_BY_INDEX_RANGE || op_type == OP_MAP_GET_BY_RANK || op_type == OP_MAP_GET_BY_RANK_RANGE); } static inline bool map_op_requires_key(int op_type) { return ( op_type == OP_MAP_PUT || op_type == OP_MAP_INCREMENT || op_type == OP_MAP_DECREMENT || op_type == OP_MAP_REMOVE_BY_KEY || op_type == OP_MAP_REMOVE_BY_KEY_LIST || op_type == OP_MAP_REMOVE_BY_KEY_RANGE || op_type == OP_MAP_GET_BY_KEY || op_type == OP_MAP_GET_BY_KEY_RANGE ); } static inline bool map_op_requires_val(int op_type) { return ( op_type == OP_MAP_PUT || op_type == OP_MAP_INCREMENT || op_type == OP_MAP_DECREMENT || op_type == OP_MAP_REMOVE_BY_VALUE || op_type == OP_MAP_REMOVE_BY_VALUE_LIST || op_type == OP_MAP_REMOVE_BY_VALUE_RANGE || op_type == OP_MAP_GET_BY_VALUE || op_type == OP_MAP_GET_BY_VALUE_RANGE || op_type == OP_MAP_PUT_ITEMS); } static inline bool map_op_requires_rank(int op_type) { return ( op_type == OP_MAP_REMOVE_BY_RANK || op_type == OP_MAP_REMOVE_BY_RANK_RANGE || op_type == OP_MAP_GET_BY_RANK || op_type == OP_MAP_GET_BY_RANK_RANGE); } static inline bool map_op_requires_return_type(int op_type) { return ( op_type == OP_MAP_REMOVE_BY_KEY || op_type == OP_MAP_REMOVE_BY_KEY_LIST || op_type == OP_MAP_REMOVE_BY_KEY_RANGE || op_type == OP_MAP_REMOVE_BY_VALUE || op_type == OP_MAP_REMOVE_BY_VALUE_LIST || op_type == OP_MAP_REMOVE_BY_VALUE_RANGE || op_type == OP_MAP_REMOVE_BY_INDEX || op_type == OP_MAP_REMOVE_BY_INDEX_RANGE || op_type == OP_MAP_REMOVE_BY_RANK || op_type == OP_MAP_REMOVE_BY_RANK_RANGE || op_type == OP_MAP_GET_BY_KEY || op_type == OP_MAP_GET_BY_KEY_RANGE || op_type == OP_MAP_GET_BY_VALUE || op_type == OP_MAP_GET_BY_VALUE_RANGE || op_type == OP_MAP_GET_BY_INDEX || op_type == OP_MAP_GET_BY_INDEX_RANGE || op_type == OP_MAP_GET_BY_RANK || op_type == OP_MAP_GET_BY_RANK_RANGE); } static inline bool map_op_requires_map_policy(int op_type) { return ( op_type == OP_MAP_SET_POLICY || op_type == OP_MAP_PUT || op_type == OP_MAP_PUT_ITEMS || op_type == OP_MAP_INCREMENT || op_type == OP_MAP_DECREMENT); } static inline bool map_op_requires_index(int op_type) { return ( op_type == OP_MAP_REMOVE_BY_INDEX || op_type == OP_MAP_REMOVE_BY_INDEX_RANGE || op_type == OP_MAP_GET_BY_INDEX || op_type == OP_MAP_GET_BY_INDEX_RANGE); } static inline bool map_op_requires_count(int op_type) { return ( op_type == OP_MAP_REMOVE_BY_INDEX_RANGE || op_type == OP_MAP_REMOVE_BY_RANK_RANGE || op_type == OP_MAP_GET_BY_INDEX_RANGE || op_type == OP_MAP_GET_BY_RANK_RANGE); } static inline bool map_op_requires_range_end(int op_type) { return ( op_type == OP_MAP_REMOVE_BY_KEY_RANGE || op_type == OP_MAP_REMOVE_BY_VALUE_RANGE || op_type == OP_MAP_GET_BY_KEY_RANGE || op_type == OP_MAP_GET_BY_VALUE_RANGE); } static as_status get_count_from_op_hash(as_error* err, HashTable* op_hash, uint64_t* count) { zval* z_count = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_count = zend_hash_str_find(op_hash, AS_MAP_COUNT_KEY, strlen(AS_MAP_COUNT_KEY)); if (!z_count) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required count entry"); } if (Z_TYPE_P(z_count) != IS_LONG) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Count entry must be a long type"); } if (Z_LVAL_P(z_count) < 0) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Count must not be negative"); } *count = Z_LVAL_P(z_count); return AEROSPIKE_OK; } static as_status get_index_from_op_hash(as_error* err, HashTable* op_hash, int64_t* index) { zval* z_index = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_index = zend_hash_str_find(op_hash, AS_MAP_INDEX_KEY, strlen(AS_MAP_INDEX_KEY)); if (!z_index) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required index entry"); } if (Z_TYPE_P(z_index) != IS_LONG) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Index entry must be a long type"); } *index = Z_LVAL_P(z_index); return AEROSPIKE_OK; } static as_status get_rank_from_op_hash(as_error* err, HashTable* op_hash, int64_t* rank) { zval* z_rank = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_rank = zend_hash_str_find(op_hash, AS_MAP_RANK_KEY, strlen(AS_MAP_RANK_KEY)); if (!z_rank) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required rank entry"); } if (Z_TYPE_P(z_rank) != IS_LONG) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "rank entry must be a long type"); } *rank = Z_LVAL_P(z_rank); return AEROSPIKE_OK; } /* This is limited for now, This really should allow any of the primitive as_vals, but that causes * some weird issues with PHP converting them back to arrays :(, At the very least, this should take * an int*/ static as_status get_key_from_op_hash(as_error* err, HashTable* op_hash, as_val** key, int serializer_type) { zval* z_key = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_key = zend_hash_str_find(op_hash, AS_MAP_KEY_KEY, strlen(AS_MAP_KEY_KEY)); if (!z_key) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required key entry"); } if (zval_to_as_val(z_key, key, err, serializer_type) != AEROSPIKE_OK) { return err->code; } return AEROSPIKE_OK; } static as_status get_value_from_op_hash(as_error* err, HashTable* op_hash, as_val** val, int serializer_type) { zval* z_value = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_value = zend_hash_str_find(op_hash, AS_MAP_VALUE_KEY, strlen(AS_MAP_VALUE_KEY)); if (!z_value) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required val entry"); } if (zval_to_as_val(z_value, val, err, serializer_type) != AEROSPIKE_OK) { return err->code; } return AEROSPIKE_OK; } static as_status get_range_end_from_op_hash(as_error* err, HashTable* op_hash, as_val** range_end, int serializer_type) { zval* z_range_end = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_range_end = zend_hash_str_find(op_hash, AS_MAP_RANGE_END, strlen(AS_MAP_RANGE_END)); if (!z_range_end) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required range_end entry"); } if (zval_to_as_val(z_range_end, range_end, err, serializer_type) != AEROSPIKE_OK) { return err->code; } return AEROSPIKE_OK; } static as_status get_map_policy_from_op_hash(as_error* err, HashTable* op_hash, as_map_policy* map_policy_p) { zval* z_map_policy = NULL; as_status status = AEROSPIKE_OK; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_map_policy = zend_hash_str_find(op_hash, AS_MAP_POLICY_KEY, strlen(AS_MAP_POLICY_KEY)); if (!z_map_policy) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required map_policy entry"); } status = zval_to_as_policy_map(z_map_policy, map_policy_p); if (status != AEROSPIKE_OK) { return as_error_update(err, status, "Invalid map_policy"); } return AEROSPIKE_OK; } static as_status get_return_type_from_op_hash(as_error* err, HashTable* op_hash, as_map_return_type* return_type) { zval* z_return_type = NULL; if (!op_hash) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation must not be empty"); } z_return_type = zend_hash_str_find(op_hash, AS_MAP_RETURN_TYPE_KEY, strlen(AS_MAP_RETURN_TYPE_KEY)); if (!z_return_type) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "Operation missing a required return_type entry"); } if (Z_TYPE_P(z_return_type) != IS_LONG) { return as_error_update(err, AEROSPIKE_ERR_PARAM, "return_type must be a long"); } *return_type = (as_map_return_type)Z_LVAL_P(z_return_type); return AEROSPIKE_OK; }
32.389457
121
0.7318
[ "object" ]
1219b2dfa3f8cb4f643993c9d28d539047e7b9af
705
h
C
ShadowPoint/ShadowPoint/App1.h
MLJamie/CMP301-Examples
808f17d6352dfc81649ce85990e2b4b4d8bfc7e6
[ "MIT" ]
null
null
null
ShadowPoint/ShadowPoint/App1.h
MLJamie/CMP301-Examples
808f17d6352dfc81649ce85990e2b4b4d8bfc7e6
[ "MIT" ]
null
null
null
ShadowPoint/ShadowPoint/App1.h
MLJamie/CMP301-Examples
808f17d6352dfc81649ce85990e2b4b4d8bfc7e6
[ "MIT" ]
null
null
null
// Application.h #ifndef _APP1_H #define _APP1_H // Includes #include "DXF.h" // include dxframework #include "TextureShader.h" #include "ShadowShader.h" #include "DepthShader.h" class App1 : public BaseApplication { public: App1(); ~App1(); void init(HINSTANCE hinstance, HWND hwnd, int screenWidth, int screenHeight, Input* in, bool VSYNC, bool FULL_SCREEN); bool frame(); protected: bool render(); void depthPass(); void finalPass(); void gui(); private: TextureShader* textureShader; PlaneMesh* mesh; Light* light; AModel* model; ShadowShader* shadowShader; DepthShader* depthShader; ShadowMap* shadowMap; // for testing OrthoMesh* orthoMesh; XMFLOAT3 position; }; #endif
15.666667
119
0.729078
[ "mesh", "render", "model" ]
121a4ad983b9cd22878d8b4f1842d93392db4657
466
h
C
src/PrecipReader.h
babetoduarte/EF5
5e469f288bce82259e85d26a3f30f7dc260547fb
[ "Unlicense" ]
20
2016-09-20T15:19:54.000Z
2021-09-04T21:53:30.000Z
src/PrecipReader.h
chrimerss/EF5
c97ed83ead8fd764f7c94731fd5bf74761a0bb3d
[ "Unlicense" ]
10
2016-09-20T17:13:00.000Z
2022-03-20T12:53:37.000Z
src/PrecipReader.h
chrimerss/EF5
c97ed83ead8fd764f7c94731fd5bf74761a0bb3d
[ "Unlicense" ]
20
2016-12-01T21:41:40.000Z
2021-08-07T06:11:43.000Z
#ifndef PRECIP_READER_H #define PRECIP_READER_H #include "BasicGrids.h" #include "Defines.h" #include "PrecipType.h" #include <vector> class PrecipReader { public: bool Read(char *file, SUPPORTED_PRECIP_TYPES type, std::vector<GridNode> *nodes, std::vector<float> *currentPrecip, float precipConvert, std::vector<float> *prevPrecip = NULL, bool hasQPF = false); private: char lastPrecipFile[CONFIG_MAX_LEN * 2]; }; #endif
22.190476
76
0.699571
[ "vector" ]
121b755f29f039056662846c4616aec449d5e7f1
14,014
c
C
src/third_party/wiredtiger/src/support/generation.c
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/wiredtiger/src/support/generation.c
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
src/third_party/wiredtiger/src/support/generation.c
benety/mongo
203430ac9559f82ca01e3cbb3b0e09149fec0835
[ "Apache-2.0" ]
null
null
null
/*- * Copyright (c) 2014-present MongoDB, Inc. * Copyright (c) 2008-2014 WiredTiger, Inc. * All rights reserved. * * See the file LICENSE for redistribution information. */ #include "wt_internal.h" /* * WiredTiger uses generations to manage various resources. Threads publish a current generation * before accessing a resource, and clear it when they are done. For example, a thread wanting to * replace an object in memory replaces the object and increments the object's generation. Once no * threads have the previous generation published, it is safe to discard the previous version of the * object. */ /* * __gen_name -- * Return the generation name. */ static const char * __gen_name(int which) { switch (which) { case WT_GEN_CHECKPOINT: return ("checkpoint"); case WT_GEN_COMMIT: return ("commit"); case WT_GEN_EVICT: return ("evict"); case WT_GEN_HAZARD: return ("hazard"); case WT_GEN_SPLIT: return ("split"); default: break; } return ("unknown"); } /* * __wt_gen_init -- * Initialize the connection's generations. */ void __wt_gen_init(WT_SESSION_IMPL *session) { int i; /* * All generations start at 1, a session with a generation of 0 isn't using the resource. */ for (i = 0; i < WT_GENERATIONS; ++i) S2C(session)->generations[i] = 1; /* Ensure threads see the state change. */ WT_WRITE_BARRIER(); } /* * __wt_gen -- * Return the resource's generation. */ uint64_t __wt_gen(WT_SESSION_IMPL *session, int which) { return (S2C(session)->generations[which]); } /* * __wt_gen_next -- * Switch the resource to its next generation. */ void __wt_gen_next(WT_SESSION_IMPL *session, int which, uint64_t *genp) { uint64_t gen; gen = __wt_atomic_addv64(&S2C(session)->generations[which], 1); if (genp != NULL) *genp = gen; } /* * __wt_gen_next_drain -- * Switch the resource to its next generation, then wait for it to drain. */ void __wt_gen_next_drain(WT_SESSION_IMPL *session, int which) { uint64_t v; v = __wt_atomic_addv64(&S2C(session)->generations[which], 1); __wt_gen_drain(session, which, v); } /* * __wt_gen_drain -- * Wait for the resource to drain. */ void __wt_gen_drain(WT_SESSION_IMPL *session, int which, uint64_t generation) { struct timespec start, stop; WT_CONNECTION_IMPL *conn; WT_SESSION_IMPL *s; uint64_t minutes, time_diff_ms, v; uint32_t i, session_cnt; int pause_cnt; bool verbose_timeout_flags; conn = S2C(session); verbose_timeout_flags = false; __wt_epoch(NULL, &start); /* * No lock is required because the session array is fixed size, but it may contain inactive * entries. We must review any active session, so insert a read barrier after reading the active * session count. That way, no matter what sessions come or go, we'll check the slots for all of * the sessions that could have been active when we started our check. */ WT_ORDERED_READ(session_cnt, conn->session_cnt); for (minutes = 0, pause_cnt = 0, s = conn->sessions, i = 0; i < session_cnt; ++s, ++i) { if (!s->active) continue; for (;;) { /* Ensure we only read the value once. */ WT_ORDERED_READ(v, s->generations[which]); /* * The generation argument is newer than the limit. Wait for threads in generations * older than the argument generation, threads in argument generations are OK. * * The thread's generation may be 0 (that is, not set). */ if (v == 0 || v >= generation) break; /* If we're waiting on ourselves, we're deadlocked. */ if (session == s) { WT_IGNORE_RET(__wt_panic(session, WT_PANIC, "self-deadlock")); return; } /* * The pause count is cumulative, quit spinning if it's not doing us any good, that can * happen in generations that don't move quickly. */ if (++pause_cnt < WT_THOUSAND) WT_PAUSE(); else __wt_sleep(0, 10); /* * If we wait for more than a minute, log the event. In DIAGNOSTIC mode, abort if we * ever wait more than 3 minutes, that's forever. */ if (minutes == 0) { minutes = 1; __wt_epoch(session, &start); } else { __wt_epoch(session, &stop); time_diff_ms = WT_TIMEDIFF_MS(stop, start); #define WT_GEN_DRAIN_TIMEOUT_MIN 4 if (time_diff_ms > minutes * WT_MINUTE * WT_THOUSAND) { __wt_verbose_notice(session, WT_VERB_GENERATION, "%s generation drain waited %" PRIu64 " minutes", __gen_name(which), minutes); ++minutes; WT_ASSERT(session, minutes < WT_GEN_DRAIN_TIMEOUT_MIN); } /* Enable extra logs 20ms before timing out. */ else if (!verbose_timeout_flags && time_diff_ms > (WT_GEN_DRAIN_TIMEOUT_MIN * WT_MINUTE * WT_THOUSAND - 20)) { if (which == WT_GEN_EVICT) { WT_SET_VERBOSE_LEVEL(session, WT_VERB_EVICT, WT_VERBOSE_DEBUG); WT_SET_VERBOSE_LEVEL(session, WT_VERB_EVICTSERVER, WT_VERBOSE_DEBUG); WT_SET_VERBOSE_LEVEL(session, WT_VERB_EVICT_STUCK, WT_VERBOSE_DEBUG); } else if (which == WT_GEN_CHECKPOINT) { WT_SET_VERBOSE_LEVEL(session, WT_VERB_CHECKPOINT, WT_VERBOSE_DEBUG); WT_SET_VERBOSE_LEVEL(session, WT_VERB_CHECKPOINT_CLEANUP, WT_VERBOSE_DEBUG); WT_SET_VERBOSE_LEVEL( session, WT_VERB_CHECKPOINT_PROGRESS, WT_VERBOSE_DEBUG); } verbose_timeout_flags = true; } } } } } /* * __gen_oldest -- * Return the oldest generation in use for the resource. */ static uint64_t __gen_oldest(WT_SESSION_IMPL *session, int which) { WT_CONNECTION_IMPL *conn; WT_SESSION_IMPL *s; uint64_t oldest, v; uint32_t i, session_cnt; conn = S2C(session); /* * No lock is required because the session array is fixed size, but it may contain inactive * entries. We must review any active session, so insert a read barrier after reading the active * session count. That way, no matter what sessions come or go, we'll check the slots for all of * the sessions that could have been active when we started our check. */ WT_ORDERED_READ(session_cnt, conn->session_cnt); for (oldest = conn->generations[which], s = conn->sessions, i = 0; i < session_cnt; ++s, ++i) { if (!s->active) continue; /* Ensure we only read the value once. */ WT_ORDERED_READ(v, s->generations[which]); if (v != 0 && v < oldest) oldest = v; } return (oldest); } /* * __wt_gen_active -- * Return if a specified generation is in use for the resource. */ bool __wt_gen_active(WT_SESSION_IMPL *session, int which, uint64_t generation) { WT_CONNECTION_IMPL *conn; WT_SESSION_IMPL *s; uint64_t v; uint32_t i, session_cnt; conn = S2C(session); /* * No lock is required because the session array is fixed size, but it may contain inactive * entries. We must review any active session, so insert a read barrier after reading the active * session count. That way, no matter what sessions come or go, we'll check the slots for all of * the sessions that could have been active when we started our check. */ WT_ORDERED_READ(session_cnt, conn->session_cnt); for (s = conn->sessions, i = 0; i < session_cnt; ++s, ++i) { if (!s->active) continue; /* Ensure we only read the value once. */ WT_ORDERED_READ(v, s->generations[which]); if (v != 0 && generation >= v) return (true); } #ifdef HAVE_DIAGNOSTIC { uint64_t oldest = __gen_oldest(session, which); WT_ASSERT(session, generation < oldest); } #endif return (false); } /* * __wt_session_gen -- * Return the thread's resource generation. */ uint64_t __wt_session_gen(WT_SESSION_IMPL *session, int which) { return (session->generations[which]); } /* * __wt_session_gen_enter -- * Publish a thread's resource generation. */ void __wt_session_gen_enter(WT_SESSION_IMPL *session, int which) { /* * Don't enter a generation we're already in, it will likely result in code intended to be * protected by a generation running outside one. */ WT_ASSERT(session, session->generations[which] == 0); WT_ASSERT(session, session->active); WT_ASSERT(session, session->id < S2C(session)->session_cnt); /* * Assign the thread's resource generation and publish it, ensuring threads waiting on a * resource to drain see the new value. Check we haven't raced with a generation update after * publishing, we rely on the published value not being missed when scanning for the oldest * generation. */ do { session->generations[which] = __wt_gen(session, which); WT_WRITE_BARRIER(); } while (session->generations[which] != __wt_gen(session, which)); } /* * __wt_session_gen_leave -- * Leave a thread's resource generation. */ void __wt_session_gen_leave(WT_SESSION_IMPL *session, int which) { WT_ASSERT(session, session->active); WT_ASSERT(session, session->id < S2C(session)->session_cnt); /* Ensure writes made by this thread are visible. */ WT_PUBLISH(session->generations[which], 0); /* Let threads waiting for the resource to drain proceed quickly. */ WT_FULL_BARRIER(); } /* * __stash_discard -- * Discard any memory from a session stash that we can. */ static void __stash_discard(WT_SESSION_IMPL *session, int which) { WT_CONNECTION_IMPL *conn; WT_SESSION_STASH *session_stash; WT_STASH *stash; size_t i; uint64_t oldest; conn = S2C(session); session_stash = &session->stash[which]; /* Get the resource's oldest generation. */ oldest = __gen_oldest(session, which); for (i = 0, stash = session_stash->list; i < session_stash->cnt; ++i, ++stash) { if (stash->p == NULL) continue; /* * The list is expected to be in generation-sorted order, quit as soon as we find a object * we can't discard. */ if (stash->gen >= oldest) break; (void)__wt_atomic_sub64(&conn->stashed_bytes, stash->len); (void)__wt_atomic_sub64(&conn->stashed_objects, 1); /* * It's a bad thing if another thread is in this memory after we free it, make sure nothing * good happens to that thread. */ __wt_overwrite_and_free_len(session, stash->p, stash->len); } /* * If there are enough free slots at the beginning of the list, shuffle everything down. */ if (i > 100 || i == session_stash->cnt) if ((session_stash->cnt -= i) > 0) memmove(session_stash->list, stash, session_stash->cnt * sizeof(*stash)); } /* * __wt_stash_discard -- * Discard any memory from a session stash that we can. */ void __wt_stash_discard(WT_SESSION_IMPL *session) { WT_SESSION_STASH *session_stash; int which; for (which = 0; which < WT_GENERATIONS; ++which) { session_stash = &session->stash[which]; if (session_stash->cnt >= 1) __stash_discard(session, which); } } /* * __wt_stash_add -- * Add a new entry into a session stash list. */ int __wt_stash_add(WT_SESSION_IMPL *session, int which, uint64_t generation, void *p, size_t len) { WT_CONNECTION_IMPL *conn; WT_SESSION_STASH *session_stash; WT_STASH *stash; conn = S2C(session); session_stash = &session->stash[which]; /* Grow the list as necessary. */ WT_RET(__wt_realloc_def( session, &session_stash->alloc, session_stash->cnt + 1, &session_stash->list)); /* * If no caller stashes memory with a lower generation than a previously stashed object, the * list is in generation-sorted order and discarding can be faster. (An error won't cause * problems other than we might not discard stashed objects as soon as we otherwise would have.) */ stash = session_stash->list + session_stash->cnt++; stash->p = p; stash->len = len; stash->gen = generation; (void)__wt_atomic_add64(&conn->stashed_bytes, len); (void)__wt_atomic_add64(&conn->stashed_objects, 1); /* See if we can free any previous entries. */ if (session_stash->cnt > 1) __stash_discard(session, which); return (0); } /* * __wt_stash_discard_all -- * Discard all memory from a session's stash. */ void __wt_stash_discard_all(WT_SESSION_IMPL *session_safe, WT_SESSION_IMPL *session) { WT_SESSION_STASH *session_stash; WT_STASH *stash; size_t i; int which; /* * This function is called during WT_CONNECTION.close to discard any memory that remains. For * that reason, we take two WT_SESSION_IMPL arguments: session_safe is still linked to the * WT_CONNECTION and can be safely used for calls to other WiredTiger functions, while session * is the WT_SESSION_IMPL we're cleaning up. */ for (which = 0; which < WT_GENERATIONS; ++which) { session_stash = &session->stash[which]; for (i = 0, stash = session_stash->list; i < session_stash->cnt; ++i, ++stash) __wt_free(session_safe, stash->p); __wt_free(session_safe, session_stash->list); session_stash->cnt = session_stash->alloc = 0; } }
30.8
100
0.629585
[ "object" ]
29c808092c82878571969b3c2cc6b6710b31fb33
2,542
h
C
Native ad sample/Native ad sample/native_ad_req/IMStubs.h
InMobi/iOS-Native-Samplecode-InMobi
5e3c809443ccb6a3c55da155c7e4f50059b56ad4
[ "Apache-2.0" ]
1
2017-06-08T08:27:06.000Z
2017-06-08T08:27:06.000Z
Native ad sample/Native ad sample/native_ad_req/IMStubs.h
InMobi/iOS-Native-Samplecode-InMobi
5e3c809443ccb6a3c55da155c7e4f50059b56ad4
[ "Apache-2.0" ]
null
null
null
Native ad sample/Native ad sample/native_ad_req/IMStubs.h
InMobi/iOS-Native-Samplecode-InMobi
5e3c809443ccb6a3c55da155c7e4f50059b56ad4
[ "Apache-2.0" ]
2
2017-06-08T08:27:10.000Z
2022-02-21T09:46:24.000Z
// // IMStubs.h // Native ad sample // // This class is split into various data structures, // based on the JSON request format of InMobi API 2.0 // Visit https://www.inmobi.com/support/art/26555436/22465648/api-2-0-integration-guidelines/ #import <Foundation/Foundation.h> /** * Gender type description. Use this object to send user gender info. */ typedef enum { IMGenderMale, IMGenderFemale, IMGenderNone } IMGender; /** * Internal object, used to store property Id */ @interface IMPropertyObject : NSObject /* * The Property ID, as obtained from Inmobi. */ @property(nonatomic,copy) NSString *propertyId; @end @class IMBannerObject; /* * This class stores the 'imp' object, as part of the InMobi API 2.0 */ @interface IMImpressionObject : NSObject @property(nonatomic,assign) int noOfAds; @property(nonatomic,assign) BOOL isInterstitial; @property(nonatomic,copy) NSString *displayManager; @property(nonatomic,copy) NSString *displayManagerVersion; @property(nonatomic,retain) IMBannerObject *bannerObj; @end @class IMGeoObject; /* * This class stores the 'device' object, as part of InMobi API 2.0 */ @interface IMDeviceObject : NSObject @property(nonatomic,copy) NSString *carrierIP; @property(nonatomic,copy) NSString *userAgent; @property(nonatomic,copy) NSString *IDFA,*IDV; @property(nonatomic,assign) int adt; @property(nonatomic,retain) IMGeoObject *geoObj; @end /* * This class stores the 'geo' object, within the 'device' object. */ @interface IMGeoObject : NSObject @property(nonatomic,assign) double lat,lon; @property(nonatomic,assign) int accu; @end @class IMDataObject; /* * This class stores the 'user' object, as part of InMobi API 2.0 */ @interface IMUserObject : NSObject @property(nonatomic,assign) int yob; @property(nonatomic,assign) IMGender gender; @property(nonatomic,retain) IMDataObject *dataObj; @end /* * This class store the required banner info, as part of the 'imp' object */ @interface IMBannerObject : NSObject @property(nonatomic,assign) int adSize; @property(nonatomic,copy) NSString *position; @end @class IMUserSegmentObject; /* * This class stores the 'data' object, within the 'user' object */ @interface IMDataObject : NSObject @property(nonatomic,assign) int ID; @property(nonatomic,copy) NSString *name; @property(nonatomic,retain) IMUserSegmentObject *segmentObj; @end /* * This class stores the 'segment' object, within the 'data' object */ @interface IMUserSegmentObject : NSObject @property(nonatomic,retain) NSArray *userSegmentArray; @end
24.921569
93
0.75295
[ "object" ]