blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
4
721
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
5
91
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
321 values
visit_date
timestamp[ns]date
2016-08-12 09:31:09
2023-09-06 10:45:07
revision_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
committer_date
timestamp[ns]date
2010-09-28 14:01:40
2023-09-06 06:22:19
github_id
int64
426
681M
star_events_count
int64
101
243k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[ns]date
2012-06-28 18:51:49
2023-09-14 21:59:16
gha_created_at
timestamp[ns]date
2008-02-11 22:55:26
2023-08-10 11:14:58
gha_language
stringclasses
147 values
src_encoding
stringclasses
26 values
language
stringclasses
2 values
is_vendor
bool
2 classes
is_generated
bool
2 classes
length_bytes
int64
6
10.2M
extension
stringclasses
115 values
filename
stringlengths
3
113
content
stringlengths
6
10.2M
b62c0d02dedeeade79089831fd28b20e021305aa
6436d1e6c23f9f43a8025889dc4414a3ad66acf2
/CvGameCoreDLL/AI_Defines.h
4706132164e6637799bc884cd16543a9f8360eb4
[ "MIT" ]
permissive
dguenms/Dawn-of-Civilization
b710195c4f46fe11d9229182c3b1e07b77f42637
a305e7846d085d6edf1e9c472e8dfceee1c07dd4
refs/heads/develop
2023-09-04T04:57:00.086384
2023-09-01T15:24:28
2023-09-01T15:24:28
45,362,597
116
121
MIT
2023-02-08T00:18:53
2015-11-01T23:52:28
C++
UTF-8
C
false
false
2,055
h
AI_Defines.h
#pragma once #ifndef AI_DEFINES_H #define AI_DEFINES_H #define DEFAULT_PLAYER_CLOSENESS 6 #define AI_DAGGER_THRESHOLD 100 //higher is a lower chance #define AI_DEFAULT_STRATEGY (1 << 0) #define AI_STRATEGY_DAGGER (1 << 1) #define AI_STRATEGY_SLEDGEHAMMER (1 << 2) #define AI_STRATEGY_CASTLE (1 << 3) #define AI_STRATEGY_FASTMOVERS (1 << 4) #define AI_STRATEGY_SLOWMOVERS (1 << 5) #define AI_STRATEGY_CULTURE1 (1 << 6) //religions and wonders #define AI_STRATEGY_CULTURE2 (1 << 7) //mass culture buildings #define AI_STRATEGY_CULTURE3 (1 << 8) //culture slider #define AI_STRATEGY_CULTURE4 (1 << 9) #define AI_STRATEGY_MISSIONARY (1 << 10) #define AI_STRATEGY_CRUSH (1 << 11) //convert units to City Attack #define AI_STRATEGY_PRODUCTION (1 << 12) #define AI_STRATEGY_PEACE (1 << 13) //lucky... neglect defenses. #define AI_STRATEGY_GET_BETTER_UNITS (1 << 14) #define AI_STRATEGY_LAND_BLITZ (1 << 15) #define AI_STRATEGY_AIR_BLITZ (1 << 16) #define AI_STRATEGY_LAST_STAND (1 << 17) #define AI_STRATEGY_FINAL_WAR (1 << 18) #define AI_STRATEGY_OWABWNW (1 << 19) #define AI_STRATEGY_BIG_ESPIONAGE (1 << 20) #define AI_CITY_ROLE_VALID (1 << 1) //zero is bad #define AI_CITY_ROLE_BIG_CULTURE (1 << 2) //culture victory, probably #define AI_CITY_ROLE_BIG_PRODUCTION (1 << 3) //don't build girly NW's #define AI_CITY_ROLE_BIG_MILITARY (1 << 4) //stick with military stuff #define AI_CITY_ROLE_SCIENCE (1 << 5) // #define AI_CITY_ROLE_GOLD (1 << 6) // #define AI_CITY_ROLE_PRODUCTION (1 << 7) // #define AI_CITY_ROLE_SPECIALIST (1 << 8) // #define AI_CITY_ROLE_FISHING (1 << 9) // #define AI_CITY_ROLE_STAGING (1 << 10) //send troops here #define AI_CITY_ROLE_LICHPIN (1 << 11) //this city must not fall #endif // AI_DEFINES_H
ae9a0437ae07ac00f19eefe38e33dbeaf41d15f5
4bc40d60c146300030512b11e375cb8abbf2f5b3
/FemtoRV/FIRMWARE/EXAMPLES/hello_bench.c
cbdfab56083aef26fbb93610dd61fce93ed21409
[ "BSD-3-Clause" ]
permissive
BrunoLevy/learn-fpga
fd18ea8a67cfc46d29fac9ad417ae7990b135118
fd954b06f6dc57ee042d0c82e9418e83c4b261b4
refs/heads/master
2023-08-23T06:15:43.195975
2023-08-04T06:41:22
2023-08-04T06:41:22
267,350,664
2,036
191
BSD-3-Clause
2023-06-23T13:41:44
2020-05-27T15:04:05
C++
UTF-8
C
false
false
266
c
hello_bench.c
#include <femtorv32.h> #include <femtoGL.h> // Demo program for 'make testbench' int main() { femtosoc_tty_init(); printf("Hello world !!\n Let me introduce myself, I am FemtoRV32, one of the smallest RISC-V cores\n"); putchar(4); // EOT return 0; }
e81f1278bcce7181a9dd437b99e0683f4b4286be
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/lib/libXcomposite/src/Xcomposite.c
e39a998a192058a26a929f933252be3e422b4786
[ "HPND-sell-variant", "MIT" ]
permissive
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
11,960
c
Xcomposite.c
/* * $Id: Xcomposite.c,v 1.6 2023/07/03 08:13:41 matthieu Exp $ * * Copyright © 2006 Sun Microsystems * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Sun Microsystems not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Sun Microsystems makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * SUN MICROSYSTEMS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL SUN MICROSYSTEMS 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. * * Copyright © 2003 Keith Packard * * Permission to use, copy, modify, distribute, and sell this software and its * documentation for any purpose is hereby granted without fee, provided that * the above copyright notice appear in all copies and that both that * copyright notice and this permission notice appear in supporting * documentation, and that the name of Keith Packard not be used in * advertising or publicity pertaining to distribution of the software without * specific, written prior permission. Keith Packard makes no * representations about the suitability of this software for any purpose. It * is provided "as is" without express or implied warranty. * * KEITH PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, * INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO * EVENT SHALL KEITH PACKARD 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. */ #include "xcompositeint.h" XCompositeExtInfo XCompositeExtensionInfo; const char XCompositeExtensionName[] = COMPOSITE_NAME; /* * XCompositeExtRemoveDisplay - remove the indicated display from the * extension object. (Replaces XextRemoveDisplay.) */ static int XCompositeExtRemoveDisplay (XCompositeExtInfo *extinfo, const Display *dpy) { XCompositeExtDisplayInfo *info, *prev; /* * locate this display and its back link so that it can be removed */ _XLockMutex(_Xglobal_lock); prev = NULL; for (info = extinfo->head; info; info = info->next) { if (info->display == dpy) break; prev = info; } if (!info) { _XUnlockMutex(_Xglobal_lock); return 0; /* hmm, actually an error */ } /* * remove the display from the list; handles going to zero */ if (prev) prev->next = info->next; else extinfo->head = info->next; extinfo->ndisplays--; if (info == extinfo->cur) extinfo->cur = NULL; /* flush cache */ _XUnlockMutex(_Xglobal_lock); Xfree (info); return 1; } static int XCompositeCloseDisplay (Display *dpy, _X_UNUSED XExtCodes *codes) { return XCompositeExtRemoveDisplay (&XCompositeExtensionInfo, dpy); } /* * XCompositeExtAddDisplay - add a display to this extension. (Replaces * XextAddDisplay) */ static XCompositeExtDisplayInfo * XCompositeExtAddDisplay (XCompositeExtInfo *extinfo, Display *dpy, const char *ext_name) { XCompositeExtDisplayInfo *info; info = Xmalloc (sizeof (XCompositeExtDisplayInfo)); if (!info) return NULL; info->display = dpy; info->codes = XInitExtension (dpy, ext_name); /* * if the server has the extension, then we can initialize the * appropriate function vectors */ if (info->codes) { xCompositeQueryVersionReply rep; xCompositeQueryVersionReq *req; XESetCloseDisplay (dpy, info->codes->extension, XCompositeCloseDisplay); /* * Get the version info */ LockDisplay (dpy); GetReq (CompositeQueryVersion, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeQueryVersion; req->majorVersion = COMPOSITE_MAJOR; req->minorVersion = COMPOSITE_MINOR; if (!_XReply (dpy, (xReply *) &rep, 0, xTrue)) { UnlockDisplay (dpy); SyncHandle (); Xfree(info); return NULL; } info->major_version = (int) rep.majorVersion; info->minor_version = (int) rep.minorVersion; UnlockDisplay (dpy); SyncHandle (); } else { /* The server doesn't have this extension. * Use a private Xlib-internal extension to hang the close_display * hook on so that the "cache" (extinfo->cur) is properly cleaned. * (XBUG 7955) */ XExtCodes *codes = XAddExtension(dpy); if (!codes) { Xfree(info); return NULL; } XESetCloseDisplay (dpy, codes->extension, XCompositeCloseDisplay); } /* * now, chain it onto the list */ _XLockMutex(_Xglobal_lock); info->next = extinfo->head; extinfo->head = info; extinfo->cur = info; extinfo->ndisplays++; _XUnlockMutex(_Xglobal_lock); return info; } /* * XCompositeExtFindDisplay - look for a display in this extension; keeps a * cache of the most-recently used for efficiency. (Replaces * XextFindDisplay.) */ static XCompositeExtDisplayInfo * XCompositeExtFindDisplay (XCompositeExtInfo *extinfo, const Display *dpy) { XCompositeExtDisplayInfo *info; /* * see if this was the most recently accessed display */ if ((info = extinfo->cur) && info->display == dpy) return info; /* * look for display in list */ _XLockMutex(_Xglobal_lock); for (info = extinfo->head; info; info = info->next) { if (info->display == dpy) { extinfo->cur = info; /* cache most recently used */ _XUnlockMutex(_Xglobal_lock); return info; } } _XUnlockMutex(_Xglobal_lock); return NULL; } XCompositeExtDisplayInfo * XCompositeFindDisplay (Display *dpy) { XCompositeExtDisplayInfo *info; info = XCompositeExtFindDisplay (&XCompositeExtensionInfo, dpy); if (!info) info = XCompositeExtAddDisplay (&XCompositeExtensionInfo, dpy, XCompositeExtensionName); return info; } Bool XCompositeQueryExtension (Display *dpy, int *event_base_return, int *error_base_return) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); if (XCompositeHasExtension(info)) { *event_base_return = info->codes->first_event; *error_base_return = info->codes->first_error; return True; } else return False; } Status XCompositeQueryVersion (Display *dpy, int *major_version_return, int *minor_version_return) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); XCompositeCheckExtension (dpy, info, 0); *major_version_return = info->major_version; *minor_version_return = info->minor_version; return 1; } int XCompositeVersion (void) { return XCOMPOSITE_VERSION; } void XCompositeRedirectWindow (Display *dpy, Window window, int update) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeRedirectWindowReq *req; XCompositeSimpleCheckExtension (dpy, info); LockDisplay (dpy); GetReq (CompositeRedirectWindow, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeRedirectWindow; req->window = (CARD32) window; req->update = (CARD8) update; UnlockDisplay (dpy); SyncHandle (); } void XCompositeRedirectSubwindows (Display *dpy, Window window, int update) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeRedirectSubwindowsReq *req; XCompositeSimpleCheckExtension (dpy, info); LockDisplay (dpy); GetReq (CompositeRedirectSubwindows, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeRedirectSubwindows; req->window = (CARD32) window; req->update = (CARD8) update; UnlockDisplay (dpy); SyncHandle (); } void XCompositeUnredirectWindow (Display *dpy, Window window, int update) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeUnredirectWindowReq *req; XCompositeSimpleCheckExtension (dpy, info); LockDisplay (dpy); GetReq (CompositeUnredirectWindow, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeUnredirectWindow; req->window = (CARD32) window; req->update = (CARD8) update; UnlockDisplay (dpy); SyncHandle (); } void XCompositeUnredirectSubwindows (Display *dpy, Window window, int update) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeUnredirectSubwindowsReq *req; XCompositeSimpleCheckExtension (dpy, info); LockDisplay (dpy); GetReq (CompositeUnredirectSubwindows, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeUnredirectSubwindows; req->window = (CARD32) window; req->update = (CARD8) update; UnlockDisplay (dpy); SyncHandle (); } XserverRegion XCompositeCreateRegionFromBorderClip (Display *dpy, Window window) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeCreateRegionFromBorderClipReq *req; XserverRegion region; XCompositeCheckExtension (dpy, info, 0); LockDisplay (dpy); GetReq (CompositeCreateRegionFromBorderClip, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeCreateRegionFromBorderClip; req->window = (CARD32) window; region = XAllocID (dpy); req->region = (CARD32) region; UnlockDisplay (dpy); SyncHandle (); return region; } Pixmap XCompositeNameWindowPixmap (Display *dpy, Window window) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeNameWindowPixmapReq *req; Pixmap pixmap; XCompositeCheckExtension (dpy, info, 0); LockDisplay (dpy); GetReq (CompositeNameWindowPixmap, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeNameWindowPixmap; req->window = (CARD32) window; pixmap = XAllocID (dpy); req->pixmap = (CARD32) pixmap; UnlockDisplay (dpy); SyncHandle (); return pixmap; } Window XCompositeGetOverlayWindow (Display *dpy, Window window) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeGetOverlayWindowReq *req; xCompositeGetOverlayWindowReply rep; XCompositeCheckExtension (dpy, info, 0); LockDisplay (dpy); GetReq (CompositeGetOverlayWindow, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeGetOverlayWindow; req->window = (CARD32) window; if (!_XReply (dpy, (xReply *) &rep, 0, xFalse)) { UnlockDisplay (dpy); SyncHandle (); return 0; } UnlockDisplay (dpy); SyncHandle (); return rep.overlayWin; } void XCompositeReleaseOverlayWindow (Display *dpy, Window window) { XCompositeExtDisplayInfo *info = XCompositeFindDisplay (dpy); xCompositeReleaseOverlayWindowReq *req; XCompositeSimpleCheckExtension (dpy, info); LockDisplay (dpy); GetReq (CompositeReleaseOverlayWindow, req); req->reqType = (CARD8) info->codes->major_opcode; req->compositeReqType = X_CompositeReleaseOverlayWindow; req->window = (CARD32) window; UnlockDisplay (dpy); SyncHandle (); }
00e7953f9a35258c008fed22ad1c7bc9b64bdf6f
af901bc01d668ecd411549625208b07024df3ffd
/src/internal/decl/attr-decl.h
76bc94dc909876ebbdd1b68d64f69c6396363ff3
[ "MIT", "BSD-2-Clause" ]
permissive
r-lib/rlang
2784186a4dafb2fde7357c79514b3761803d0e66
c55f6027928d3104ed449e591e8a225fcaf55e13
refs/heads/main
2023-09-06T03:23:47.522921
2023-06-07T17:01:51
2023-06-07T17:01:51
73,098,312
355
128
NOASSERTION
2023-08-31T13:11:13
2016-11-07T16:28:57
R
UTF-8
C
false
false
678
h
attr-decl.h
static r_obj* c_fn; static r_obj* as_character_call; static r_obj* names_call; static r_obj* set_names_call; static r_obj* length_call; static r_obj* node_names(r_obj* x); static r_obj* names_dispatch(r_obj* x, r_obj* env); static inline r_obj* eval_fn_dots(r_obj* fn, r_obj* x, r_obj* dots, r_obj* env); static inline r_obj* eval_as_character(r_obj* x, r_obj* env); static inline r_obj* set_names_dispatch(r_obj* x, r_obj* nm, r_obj* env); static inline r_ssize length_dispatch(r_obj* x, r_obj* env); static r_obj* fn_zap_srcref(r_obj* x); static r_obj* call_zap_srcref(r_obj* x); static r_obj* expr_vec_zap_srcref(r_obj* x); static void attrib_zap_srcref(r_obj* x);
2dfbac4a2b447aa934ec7d903111251c06fa00d0
c26d7b0ed875357278e61627da2da0650da77986
/src/libc/gen/regex.c
f84abbf44cdb536dcb61bb025f66395ce4dd2a09
[ "BSD-3-Clause" ]
permissive
RetroBSD/retrobsd
5343d9e3c424637fc3ad5b03fe720b2744490025
486f81f6abff01c7dcc207235cd2979b226a95ff
refs/heads/master
2023-09-02T23:12:05.110883
2023-07-07T18:41:40
2023-07-07T18:41:40
18,598,087
282
59
BSD-3-Clause
2023-07-18T07:35:36
2014-04-09T13:25:46
C
UTF-8
C
false
false
8,146
c
regex.c
/* * Copyright (c) 1980 Regents of the University of California. * All rights reserved. The Berkeley software License Agreement * specifies the terms and conditions for redistribution. */ /* * routines to do regular expression matching * * Entry points: * * re_comp(s) * char *s; * ... returns 0 if the string s was compiled successfully, * a pointer to an error message otherwise. * If passed 0 or a null string returns without changing * the currently compiled re (see note 11 below). * * re_exec(s) * char *s; * ... returns 1 if the string s matches the last compiled regular * expression, * 0 if the string s failed to match the last compiled * regular expression, and * -1 if the compiled regular expression was invalid * (indicating an internal error). * * The strings passed to both re_comp and re_exec may have trailing or * embedded newline characters; they are terminated by nulls. * * The identity of the author of these routines is lost in antiquity; * this is essentially the same as the re code in the original V6 ed. * * The regular expressions recognized are described below. This description * is essentially the same as that for ed. * * A regular expression specifies a set of strings of characters. * A member of this set of strings is said to be matched by * the regular expression. In the following specification for * regular expressions the word `character' means any character but NUL. * * 1. Any character except a special character matches itself. * Special characters are the regular expression delimiter plus * \ [ . and sometimes ^ * $. * 2. A . matches any character. * 3. A \ followed by any character except a digit or ( ) * matches that character. * 4. A nonempty string s bracketed [s] (or [^s]) matches any * character in (or not in) s. In s, \ has no special meaning, * and ] may only appear as the first letter. A substring * a-b, with a and b in ascending ASCII order, stands for * the inclusive range of ASCII characters. * 5. A regular expression of form 1-4 followed by * matches a * sequence of 0 or more matches of the regular expression. * 6. A regular expression, x, of form 1-8, bracketed \(x\) * matches what x matches. * 7. A \ followed by a digit n matches a copy of the string that the * bracketed regular expression beginning with the nth \( matched. * 8. A regular expression of form 1-8, x, followed by a regular * expression of form 1-7, y matches a match for x followed by * a match for y, with the x match being as long as possible * while still permitting a y match. * 9. A regular expression of form 1-8 preceded by ^ (or followed * by $), is constrained to matches that begin at the left * (or end at the right) end of a line. * 10. A regular expression of form 1-9 picks out the longest among * the leftmost matches in a line. * 11. An empty regular expression stands for a copy of the last * regular expression encountered. */ /* * constants for re's */ #define CBRA 1 #define CCHR 2 #define CDOT 4 #define CCL 6 #define NCCL 8 #define CDOL 10 #define CEOF 11 #define CKET 12 #define CBACK 18 #define CSTAR 01 #define ESIZE 512 #define NBRA 9 static char expbuf[ESIZE], *braslist[NBRA], *braelist[NBRA]; static char circf; /* * compile the regular expression argument into a dfa */ char * re_comp(sp) register char *sp; { register int c; register char *ep = expbuf; int cclcnt, numbra = 0; char *lastep = 0; char bracket[NBRA]; char *bracketp = &bracket[0]; static char *retoolong = "Regular expression too long"; #define comerr(msg) {expbuf[0] = 0; numbra = 0; return(msg); } if (sp == 0 || *sp == '\0') { if (*ep == 0) return("No previous regular expression"); return(0); } if (*sp == '^') { circf = 1; sp++; } else circf = 0; for (;;) { if (ep >= &expbuf[ESIZE]) comerr(retoolong); if ((c = *sp++) == '\0') { if (bracketp != bracket) comerr("unmatched \\("); *ep++ = CEOF; *ep++ = 0; return(0); } if (c != '*') lastep = ep; switch (c) { case '.': *ep++ = CDOT; continue; case '*': if (lastep == 0 || *lastep == CBRA || *lastep == CKET) goto defchar; *lastep |= CSTAR; continue; case '$': if (*sp != '\0') goto defchar; *ep++ = CDOL; continue; case '[': *ep++ = CCL; *ep++ = 0; cclcnt = 1; if ((c = *sp++) == '^') { c = *sp++; ep[-2] = NCCL; } do { if (c == '\0') comerr("missing ]"); if (c == '-' && ep [-1] != 0) { if ((c = *sp++) == ']') { *ep++ = '-'; cclcnt++; break; } while (ep[-1] < c) { *ep = ep[-1] + 1; ep++; cclcnt++; if (ep >= &expbuf[ESIZE]) comerr(retoolong); } } *ep++ = c; cclcnt++; if (ep >= &expbuf[ESIZE]) comerr(retoolong); } while ((c = *sp++) != ']'); lastep[1] = cclcnt; continue; case '\\': if ((c = *sp++) == '(') { if (numbra >= NBRA) comerr("too many \\(\\) pairs"); *bracketp++ = numbra; *ep++ = CBRA; *ep++ = numbra++; continue; } if (c == ')') { if (bracketp <= bracket) comerr("unmatched \\)"); *ep++ = CKET; *ep++ = *--bracketp; continue; } if (c >= '1' && c < ('1' + NBRA)) { *ep++ = CBACK; *ep++ = c - '1'; continue; } *ep++ = CCHR; *ep++ = c; continue; defchar: default: *ep++ = CCHR; *ep++ = c; } } } static int cclass(set, c, af) register char *set, c; int af; { register int n; if (c == 0) return(0); n = *set++; while (--n) if (*set++ == c) return(af); return(! af); } static int backref(i, lp) register int i; register char *lp; { register char *bp; bp = braslist[i]; while (*bp++ == *lp++) if (bp >= braelist[i]) return(1); return(0); } /* * try to match the next thing in the dfa */ static int advance(lp, ep) register char *lp, *ep; { register char *curlp; int ct, i; int rv; for (;;) switch (*ep++) { case CCHR: if (*ep++ == *lp++) continue; return(0); case CDOT: if (*lp++) continue; return(0); case CDOL: if (*lp == '\0') continue; return(0); case CEOF: return(1); case CCL: if (cclass(ep, *lp++, 1)) { ep += *ep; continue; } return(0); case NCCL: if (cclass(ep, *lp++, 0)) { ep += *ep; continue; } return(0); case CBRA: braslist[(unsigned char)*ep++] = lp; continue; case CKET: braelist[(unsigned char)*ep++] = lp; continue; case CBACK: if (braelist[i = *ep++] == 0) return(-1); if (backref(i, lp)) { lp += braelist[i] - braslist[i]; continue; } return(0); case CBACK|CSTAR: if (braelist[i = *ep++] == 0) return(-1); curlp = lp; ct = braelist[i] - braslist[i]; while (backref(i, lp)) lp += ct; while (lp >= curlp) { rv = advance(lp, ep); if (rv) return(rv); lp -= ct; } continue; case CDOT|CSTAR: curlp = lp; while (*lp++) ; goto star; case CCHR|CSTAR: curlp = lp; while (*lp++ == *ep) ; ep++; goto star; case CCL|CSTAR: case NCCL|CSTAR: curlp = lp; while (cclass(ep, *lp++, ep[-1] == (CCL|CSTAR))) ; ep += *ep; goto star; star: do { lp--; rv = advance(lp, ep); if (rv) return(rv); } while (lp > curlp); return(0); default: return(-1); } } /* * match the argument string against the compiled re */ int re_exec(p1) register char *p1; { register char *p2 = expbuf; register int c; int rv; for (c = 0; c < NBRA; c++) { braslist[c] = 0; braelist[c] = 0; } if (circf) return((advance(p1, p2))); /* * fast check for first character */ if (*p2 == CCHR) { c = p2[1]; do { if (*p1 != c) continue; rv = advance(p1, p2); if (rv) return(rv); } while (*p1++); return(0); } /* * regular algorithm */ do { rv = advance(p1, p2); if (rv) return(rv); } while (*p1++); return(0); }
7d79f3c729f8f269da56b648aada3fc19936eac2
5e4913b3d7b6dfd9f35d9e5f24486bb6b6145125
/src/plugins/backend/testmod_backend.c
352d8b3fc79ea7f76a1cb34ad73fdd664e1e6993
[ "BSD-3-Clause" ]
permissive
ElektraInitiative/libelektra
ff5d5cfc4bf91d704f58405b14ea694aad3a2edd
dbbe4ae4f669c322a8f95f59112d3f5fc370bbd9
refs/heads/master
2023-08-05T14:54:48.081359
2023-08-04T12:40:00
2023-08-04T12:40:00
21,063,580
215
170
BSD-3-Clause
2023-09-07T13:34:30
2014-06-21T08:01:04
C
UTF-8
C
false
false
18,015
c
testmod_backend.c
/** * @file * * @brief Tests for backend plugin * * @copyright BSD License (see LICENSE.md or https://www.libelektra.org) * */ #include "backendprivate.h" #include <stdlib.h> #include <string.h> #include <kdbconfig.h> #include <tests_plugin.h> // FIXME [new_backend]: tests disabled /* KeySet * set_simple (void) { return ksNew (50, keyNew ("system:/elektra/mountpoints/simple", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config/anything", KEY_VALUE, "backend", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config/more", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config/more/config", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config/more/config/below", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config/mountpoint", KEY_VALUE, "user:/tests/backend/simple", KEY_END), keyNew ("system:/elektra/mountpoints/simple/config/path", KEY_END), keyNew ("system:/elektra/mountpoints/simple/error", KEY_END), keyNew ("system:/elektra/mountpoints/simple/error/prerollback", KEY_END), keyNew ("system:/elektra/mountpoints/simple/error/prerollback/#1", KEY_END), keyNew ("system:/elektra/mountpoints/simple/error/prerollback/#1/name", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/simple/get", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/config", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/config/anything", KEY_VALUE, "plugin", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/config/more", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/config/more/config", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/config/more/config/below", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/config/path", KEY_END), keyNew ("system:/elektra/mountpoints/simple/get/pregetstorage/#0/name", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/simple/set", KEY_END), keyNew ("system:/elektra/mountpoints/simple/set/presetstorage", KEY_END), keyNew ("system:/elektra/mountpoints/simple/set/presetstorage/#0", KEY_END), keyNew ("system:/elektra/mountpoints/simple/set/presetstorage/#0/name", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), KS_END); } KeySet * set_default (void) { return ksNew (27, keyNew ("system:/elektra/mountpoints/default", KEY_END), keyNew ("system:/elektra/mountpoints/default/config", KEY_END), keyNew ("system:/elektra/mountpoints/default/config/mountpoint", KEY_VALUE, "user:/tests/backend/default", KEY_END), keyNew ("system:/elektra/mountpoints/default/config/path", KEY_VALUE, KDB_DB_FILE, KEY_END), keyNew ("system:/elektra/mountpoints/default/error", KEY_END), keyNew ("system:/elektra/mountpoints/default/error/rollback", KEY_END), keyNew ("system:/elektra/mountpoints/default/error/rollback/#0", KEY_END), keyNew ("system:/elektra/mountpoints/default/error/rollback/#0/label", KEY_VALUE, KDB_RESOLVER, KEY_END), keyNew ("system:/elektra/mountpoints/default/error/rollback/#0/name", KEY_VALUE, KDB_RESOLVER, KEY_END), keyNew ("system:/elektra/mountpoints/default/get", KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getresolver", KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getresolver/#0", KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getresolver/#0/reference", KEY_VALUE, KDB_RESOLVER, KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getstorage", KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getstorage/#0", KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getstorage/#0/label", KEY_VALUE, KDB_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/default/get/getstorage/#0/name", KEY_VALUE, KDB_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/default/set", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/commit", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/commit/#0", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/commit/#0/reference", KEY_VALUE, KDB_RESOLVER, KEY_END), keyNew ("system:/elektra/mountpoints/default/set/setresolver", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/setresolver/#0", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/setresolver/#0/reference", KEY_VALUE, KDB_RESOLVER, KEY_END), keyNew ("system:/elektra/mountpoints/default/set/setstorage", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/setstorage/#0", KEY_END), keyNew ("system:/elektra/mountpoints/default/set/setstorage/#0/reference", KEY_VALUE, KDB_STORAGE, KEY_END), KS_END); } Plugin * open_backend (KeySet * config, KeySet * modules, KeySet * global, Key * errorKey) { Plugin * backend = elektraPluginOpen ("backend", modules, ksDup (config), errorKey); output_error (errorKey); output_warnings (errorKey); if (backend != 0) { backend->global = global; } ksDel (config); return backend; } KeySet * set_simpleconf (void) { return ksNew (10, keyNew ("system:/anything", KEY_VALUE, "backend", KEY_END), keyNew ("system:/more", KEY_END), keyNew ("system:/more/config", KEY_END), keyNew ("system:/more/config/below", KEY_END), keyNew ("system:/mountpoint", KEY_VALUE, "user:/tests/backend/simple", KEY_END), keyNew ("system:/path", KEY_END), keyNew ("user:/anything", KEY_VALUE, "plugin", KEY_END), keyNew ("user:/more", KEY_END), keyNew ("user:/more/config", KEY_END), keyNew ("user:/more/config/below", KEY_END), keyNew ("user:/path", KEY_END), KS_END); } KeySet * set_backrefconf (void) { return ksNew (10, keyNew ("system:/anything", KEY_VALUE, "backend", KEY_END), keyNew ("system:/more", KEY_END), keyNew ("system:/more/config", KEY_END), keyNew ("system:/more/config/below", KEY_END), keyNew ("system:/mountpoint", KEY_VALUE, "user:/tests/backend/backref", KEY_END), keyNew ("system:/path", KEY_END), keyNew ("user:/anything", KEY_VALUE, "plugin", KEY_END), keyNew ("user:/more", KEY_END), keyNew ("user:/more/config", KEY_END), keyNew ("user:/more/config/below", KEY_END), keyNew ("user:/path", KEY_END), KS_END); } KeySet * set_defaultconf (void) { return ksNew (10, keyNew ("system:/anything", KEY_VALUE, "backend", KEY_END), keyNew ("system:/more", KEY_END), keyNew ("system:/more/config", KEY_END), keyNew ("system:/more/config/below", KEY_END), keyNew ("system:/mountpoint", KEY_VALUE, "user:/tests/backend/default", KEY_END), keyNew ("system:/path", KEY_END), keyNew ("user:/anything", KEY_VALUE, "plugin", KEY_END), keyNew ("user:/more", KEY_END), keyNew ("user:/more/config", KEY_END), keyNew ("user:/more/config/below", KEY_END), keyNew ("user:/path", KEY_END), KS_END); } int check_null_in_slot (Slot * slot, int index) { if (!slot) return 1; Slot * curSlot = slot; for (int a = 0; a <= index; a++) { if (!curSlot) { return 1; } if (a == index) { if (curSlot->value) { return 0; } return 1; } curSlot = curSlot->next; } return 1; } static void test_simple (void) { printf ("Test simple building of backend\n"); KeySet * modules = ksNew (0, KS_END); elektraModulesInit (modules, 0); KeySet * global = ksNew (0, KS_END); Key * errorKey = keyNew ("/", KEY_END); Plugin * backend = open_backend (set_simple (), modules, global, errorKey); exit_if_fail (backend != 0, "no backend found"); BackendHandle * bh = elektraPluginGetData (backend); exit_if_fail (bh != 0, "no backend handle found"); succeed_if (check_null_in_slot (bh->errorplugins[0], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[0], 2), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[1], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[2], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[2], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[2], 0), "there should be no plugin"); exit_if_fail (check_null_in_slot (bh->errorplugins[0], 1) == 0, "there should be a plugin"); succeed_if (check_null_in_slot (bh->getplugins[0], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->getplugins[1], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->getplugins[1], 2), "there should be no plugin"); succeed_if (check_null_in_slot (bh->getplugins[2], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->getplugins[3], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->getplugins[3], 1), "there should be no plugin"); exit_if_fail (check_null_in_slot (bh->getplugins[1], 0) == 0, "there should be a plugin"); succeed_if (check_null_in_slot (bh->setplugins[0], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[1], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[1], 2), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[2], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[2], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[3], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[3], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[4], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[4], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[5], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[5], 1), "there should be no plugin"); exit_if_fail (check_null_in_slot (bh->setplugins[1], 0) == 0, "there should be a plugin"); Key * mp; succeed_if ((mp = bh->mountpoint) != 0, "no mountpoint found"); succeed_if_same_string (keyName (mp), "user:/tests/backend/simple"); succeed_if_same_string (keyString (mp), "simple"); Plugin * plugin = bh->getplugins[1]->value; KeySet * test_config = set_simpleconf (); KeySet * config = elektraPluginGetConfig (plugin); succeed_if (config != 0, "there should be a config"); compare_keyset (config, test_config); ksDel (test_config); succeed_if (plugin->kdbGet != 0, "no get pointer"); succeed_if (plugin->kdbSet != 0, "no set pointer"); elektraPluginClose (backend, errorKey); elektraModulesClose (modules, 0); ksDel (modules); ksDel (global); keyDel (errorKey); } static void test_default (void) { printf ("Test default " KDB_DEFAULT_STORAGE "\n"); KeySet * modules = ksNew (0, KS_END); elektraModulesInit (modules, 0); Plugin * plugin = elektraPluginOpen (KDB_DEFAULT_STORAGE, modules, set_defaultconf (), 0); exit_if_fail (plugin, "KDB_DEFAULT_STORAGE: " KDB_DEFAULT_STORAGE " plugin could not be loaded"); KeySet * test_config = set_defaultconf (); KeySet * config = elektraPluginGetConfig (plugin); succeed_if (config != 0, "there should be a config"); compare_keyset (config, test_config); ksDel (test_config); succeed_if (plugin->kdbGet != 0, "no get pointer"); succeed_if (plugin->kdbSet != 0, "no set pointer"); elektraPluginClose (plugin, 0); KeySet * global = ksNew (0, KS_END); KeySet * defaultKeyset = set_default (); Plugin * backend = open_backend (defaultKeyset, modules, global, 0); exit_if_fail (backend != 0, "no backend found"); BackendHandle * bh = elektraPluginGetData (backend); succeed_if (bh != 0, "no backend handle found"); Key * mp; succeed_if ((mp = bh->mountpoint) != 0, "no mountpoint found"); succeed_if_same_string (keyName (mp), "user:/tests/backend/default"); succeed_if_same_string (keyString (mp), "default"); elektraPluginClose (backend, 0); elektraModulesClose (modules, 0); ksDel (modules); ksDel (global); } KeySet * set_backref (void) { return ksNew ( 50, keyNew ("system:/elektra/mountpoints/backref", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config/anything", KEY_VALUE, "backend", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config/more", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config/more/config", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config/more/config/below", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config/mountpoint", KEY_VALUE, "user:/tests/backend/backref", KEY_END), keyNew ("system:/elektra/mountpoints/backref/config/path", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/config", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/config/anything", KEY_VALUE, "plugin", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/config/more", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/config/more/config", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/config/more/config/below", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/config/path", KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/label", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/backref/error/prerollback/#0/name", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/backref/get", KEY_END), keyNew ("system:/elektra/mountpoints/backref/get/pregetstorage", KEY_END), keyNew ("system:/elektra/mountpoints/backref/get/pregetstorage/#0", KEY_END), keyNew ("system:/elektra/mountpoints/backref/get/pregetstorage/#0/reference", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), keyNew ("system:/elektra/mountpoints/backref/set", KEY_END), keyNew ("system:/elektra/mountpoints/backref/set/presetstorage", KEY_END), keyNew ("system:/elektra/mountpoints/backref/set/presetstorage/#0", KEY_END), keyNew ("system:/elektra/mountpoints/backref/set/presetstorage/#0/reference", KEY_VALUE, KDB_DEFAULT_STORAGE, KEY_END), KS_END); } static void test_backref (void) { printf ("Test back references\n"); KeySet * modules = ksNew (0, KS_END); elektraModulesInit (modules, 0); KeySet * global = ksNew (0, KS_END); Plugin * backend = open_backend (set_backref (), modules, global, 0); exit_if_fail (backend != 0, "there should be a backend"); BackendHandle * bh = elektraPluginGetData (backend); exit_if_fail (bh != 0, "no backend handle found"); succeed_if (check_null_in_slot (bh->getplugins[0], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->getplugins[0], 1), "there should be no plugin"); exit_if_fail (check_null_in_slot (bh->getplugins[1], 0) == 0, "there should be a plugin"); succeed_if (check_null_in_slot (bh->getplugins[1], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[0], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->setplugins[0], 1), "there should be no plugin"); exit_if_fail (check_null_in_slot (bh->setplugins[1], 0) == 0, "there should be a plugin"); succeed_if (check_null_in_slot (bh->setplugins[1], 1), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[0], 1), "there should be no plugin"); exit_if_fail (check_null_in_slot (bh->errorplugins[0], 0) == 0, "there should be a plugin"); succeed_if (check_null_in_slot (bh->errorplugins[1], 0), "there should be no plugin"); succeed_if (check_null_in_slot (bh->errorplugins[1], 1), "there should be no plugin"); Key * mp; succeed_if ((mp = bh->mountpoint) != 0, "no mountpoint found"); succeed_if_same_string (keyName (mp), "user:/tests/backend/backref"); succeed_if_same_string (keyString (mp), "backref"); Plugin * plugin1 = bh->getplugins[1]->value; Plugin * plugin2 = bh->setplugins[1]->value; Plugin * plugin3 = bh->errorplugins[0]->value; succeed_if (plugin1 != 0, "there should be a plugin"); succeed_if (plugin2 != 0, "there should be a plugin"); succeed_if (plugin3 != 0, "there should be a plugin"); succeed_if (plugin1 == plugin2, "it should be the same plugin"); succeed_if (plugin2 == plugin3, "it should be the same plugin"); succeed_if (plugin1 == plugin3, "it should be the same plugin"); succeed_if (plugin1->refcounter == 3, "ref counter should be 3"); KeySet * test_config = set_backrefconf (); KeySet * config = elektraPluginGetConfig (plugin1); succeed_if (config != 0, "there should be a config"); compare_keyset (config, test_config); ksDel (test_config); succeed_if (plugin1->kdbGet != 0, "no get pointer"); succeed_if (plugin1->kdbSet != 0, "no set pointer"); succeed_if (plugin2->kdbGet != 0, "no get pointer"); succeed_if (plugin2->kdbSet != 0, "no set pointer"); elektraPluginClose (backend, 0); elektraModulesClose (modules, 0); ksDel (modules); ksDel (global); } */ int main (int argc, char ** argv) { printf ("BACKEND TESTS\n"); printf ("==================\n\n"); init (argc, argv); // FIXME [new_backend]: tests disabled /* test_simple (); test_default (); test_backref (); */ print_result ("testmod_backend"); return nbError; }
fed5d648c9b5bd2f874906474b7a851ead273ef6
ace570f65d70e6ce9461bcb81aaaac31c57ec111
/firmware/common/swra124.c
faee51478ec907342411fb0fceda2ad7c2ba6ca5
[ "BSD-3-Clause" ]
permissive
greatscottgadgets/greatfet
9ed060aec2d293844c0ac59612f09ecae9c7632b
2409575d28fc7c9cae44c9085c7457ddfb54f893
refs/heads/master
2023-05-12T18:12:31.748720
2023-05-05T07:18:21
2023-05-05T07:18:21
48,184,998
273
95
BSD-3-Clause
2023-05-05T07:18:22
2015-12-17T16:17:35
C
UTF-8
C
false
false
3,105
c
swra124.c
/* * This file is part of GreatFET */ #include "swra124.h" #include <gpio.h> #include <gpio_lpc.h> #include <greatfet_core.h> #include <libopencm3/lpc43xx/scu.h> #include <pins.h> static struct gpio_t swra124_reset = GPIO(0, 10); // GF1 Pin: J1.40 static struct gpio_t swra124_clock = GPIO(0, 11); // GF1 Pin: J1.39 static struct gpio_t swra124_data = GPIO(0, 15); // GF1 Pin: J1.37 void swra124_setup() { scu_pinmux(SCU_PINMUX_GPIO0_10, SCU_GPIO_FAST | SCU_CONF_FUNCTION0); scu_pinmux(SCU_PINMUX_GPIO0_11, SCU_GPIO_FAST | SCU_CONF_FUNCTION0); scu_pinmux(SCU_PINMUX_GPIO0_15, SCU_GPIO_FAST | SCU_CONF_FUNCTION0); gpio_write(&swra124_reset, 1); gpio_write(&swra124_clock, 0); gpio_write(&swra124_data, 0); gpio_output(&swra124_reset); gpio_output(&swra124_clock); gpio_input(&swra124_data); } void swra124_debug_init() { struct { struct gpio_t *gpio; uint8_t value; } steps[] = { {.gpio = &swra124_reset, .value = 0}, {.gpio = &swra124_clock, .value = 1}, {.gpio = &swra124_clock, .value = 0}, {.gpio = &swra124_clock, .value = 1}, {.gpio = &swra124_clock, .value = 0}, {.gpio = &swra124_reset, .value = 1}, {.gpio = NULL}, }; for (int i = 0; steps[i].gpio; i++) { gpio_write(steps[i].gpio, steps[i].value); delay_us(1); } } void swra124_write_byte(const uint8_t v) { gpio_output(&swra124_data); for (int i = 0; i < 8; i++) { gpio_write(&swra124_data, (v >> (7 - i)) & 0x01); delay_us(1); gpio_write(&swra124_clock, 1); delay_us(1); gpio_write(&swra124_clock, 0); delay_us(1); } } void swra124_write(const uint8_t *data, const size_t size) { for (size_t i = 0; i < size; i++) { swra124_write_byte(data[i]); } } uint8_t swra124_read() { uint8_t result = 0; gpio_input(&swra124_data); for (int i = 0; i < 8; i++) { gpio_write(&swra124_clock, 1); delay_us(1); result = (result << 1) | gpio_read(&swra124_data); delay_us(1); gpio_write(&swra124_clock, 0); delay_us(1); } return result; } void swra124_chip_erase() { uint8_t command[] = {0x14}; swra124_write(command, 1); swra124_read(); } void swra124_write_config(const uint8_t config) { uint8_t command[] = {0x1d, config}; swra124_write(command, 2); swra124_read(); } uint8_t swra124_read_status() { uint8_t command[] = {0x34}; swra124_write(command, 1); return swra124_read(); } uint16_t swra124_get_chip_id() { uint8_t command[] = {0x68}; swra124_write(command, 1); return (swra124_read() << 8) | swra124_read(); } void swra124_halt() { uint8_t command[] = {0x44}; swra124_write(command, 1); swra124_read(); } void swra124_resume() { uint8_t command[] = {0x4c}; swra124_write(command, 1); swra124_read(); } uint8_t swra124_debug_instr(const uint8_t *instr, const size_t size) { uint8_t command[] = {0x54 | (size & 0x03)}; swra124_write(command, 1); swra124_write(instr, size); return swra124_read(); } void swra124_step_instr() { uint8_t command[] = {0x5c}; swra124_write(command, 1); swra124_read(); } uint16_t swra124_get_pc() { uint8_t command[] = {0x28}; swra124_write(command, 1); return (swra124_read() << 8) | swra124_read(); }
4a6f30719a56b6cc0c7acb344974a50bf459b1c2
d10090b0c23c789baaac67f40cccb61f39554e07
/Middleware/Third_Party/FreeRTOS/FreeRTOS_POSIX/include/FreeRTOS_POSIX/errno.h
136e04bc44f9ad7407cee66ab6e3bf0c81340a59
[ "MIT" ]
permissive
PacktPublishing/Hands-On-RTOS-with-Microcontrollers
b6b78ebf4a462a10c115338f85edb2769ac6cd58
9cb30e4846482cd2cf19aa631757bfe916cc245f
refs/heads/master
2023-08-08T16:48:34.456178
2023-01-30T10:00:49
2023-01-30T10:00:49
206,287,816
128
84
MIT
2023-07-22T15:18:15
2019-09-04T09:55:46
C
UTF-8
C
false
false
3,319
h
errno.h
/* * Amazon FreeRTOS POSIX V1.1.0 * Copyright (C) 2019 Amazon.com, Inc. or its affiliates. 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. * * http://aws.amazon.com/freertos * http://www.FreeRTOS.org */ /** * @file errno.h * @brief System error numbers. * * http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/errno.h.html * * The values defined in this file may not be compatible with the strerror * function provided by this system. */ #ifndef _FREERTOS_POSIX_ERRNO_H_ #define _FREERTOS_POSIX_ERRNO_H_ /* Undefine all errnos to avoid redefinition errors with system errnos. */ #undef EPERM #undef ENOENT #undef EBADF #undef EAGAIN #undef ENOMEM #undef EEXIST #undef EBUSY #undef EINVAL #undef ENOSPC #undef ERANGE #undef ENAMETOOLONG #undef EDEADLK #undef EOVERFLOW #undef ENOSYS #undef EMSGSIZE #undef ENOTSUP #undef ETIMEDOUT /** * @name Definition of POSIX errnos. */ /**@{ */ #define EPERM 1 /**< Operation not permitted. */ #define ENOENT 2 /**< No such file or directory. */ #define EBADF 9 /**< Bad file descriptor. */ #define EAGAIN 11 /**< Resource unavailable, try again. */ #define ENOMEM 12 /**< Not enough space. */ #define EEXIST 17 /**< File exists. */ #define EBUSY 16 /**< Device or resource busy. */ #define EINVAL 22 /**< Invalid argument. */ #define ENOSPC 28 /**< No space left on device. */ #define ERANGE 34 /**< Result too large. */ #define ENAMETOOLONG 36 /**< File name too long. */ #define EDEADLK 45 /**< Resource deadlock would occur. */ #define EOVERFLOW 75 /**< Value too large to be stored in data type. */ #define ENOSYS 88 /**< Function not supported. */ #define EMSGSIZE 90 /**< Message too long. */ #define ENOTSUP 95 /**< Operation not supported. */ #define ETIMEDOUT 116 /**< Connection timed out. */ /**@} */ /** * @name System Variable * * @brief Define FreeRTOS+POSIX errno, if enabled. * Set configUSE_POSIX_ERRNO to enable, and clear to disable. See FreeRTOS.h. * * @{ */ #if ( configUSE_POSIX_ERRNO == 1 ) extern int FreeRTOS_errno; #define errno FreeRTOS_errno #endif /**@} */ #endif /* ifndef _FREERTOS_POSIX_ERRNO_H_ */
1d4822f8eb6b52d1e22032ffe4a891ef22057c6a
e73547787354afd9b717ea57fe8dd0695d161821
/src/world/area_tik/tik_15/tik_15_5_npc.c
d1389cfcde2972529a7fbf0f2f4cabbf671a02dc
[]
no_license
pmret/papermario
8b514b19653cef8d6145e47499b3636b8c474a37
9774b26d93f1045dd2a67e502b6efc9599fb6c31
refs/heads/main
2023-08-31T07:09:48.951514
2023-08-21T18:07:08
2023-08-21T18:07:08
287,151,133
904
139
null
2023-09-14T02:44:23
2020-08-13T01:22:57
C
UTF-8
C
false
false
5,492
c
tik_15_5_npc.c
#include "tik_15.h" #define RIP_CHEATO_COST 64 enum { CHEATO_TYPE_STAR_PIECE = 0, CHEATO_TYPE_BADGE = 1, CHEATO_TYPE_CONSUMABLE = 2, }; NpcSettings N(NpcSettings_RipCheato) = { .height = 30, .radius = 24, .level = ACTOR_LEVEL_NONE, }; NpcSettings N(NpcSettings_Unused1) = { .height = 23, .radius = 19, .level = ACTOR_LEVEL_NONE, }; #include "world/common/complete/GiveReward.inc.c" s32 N(CheatoItems)[][2] = { { CHEATO_TYPE_STAR_PIECE, ITEM_NONE }, { CHEATO_TYPE_CONSUMABLE, ITEM_LIFE_SHROOM }, { CHEATO_TYPE_BADGE, ITEM_BUMP_ATTACK }, { CHEATO_TYPE_CONSUMABLE, ITEM_REPEL_GEL }, { CHEATO_TYPE_STAR_PIECE, ITEM_NONE }, { CHEATO_TYPE_CONSUMABLE, ITEM_SUPER_SHROOM }, { CHEATO_TYPE_CONSUMABLE, ITEM_MUSHROOM }, { CHEATO_TYPE_CONSUMABLE, ITEM_DRIED_SHROOM }, { CHEATO_TYPE_CONSUMABLE, ITEM_DRIED_SHROOM }, { CHEATO_TYPE_STAR_PIECE, ITEM_NONE }, { CHEATO_TYPE_CONSUMABLE, ITEM_DRIED_SHROOM }, { CHEATO_TYPE_CONSUMABLE, ITEM_DRIED_SHROOM }, { CHEATO_TYPE_CONSUMABLE, ITEM_DRIED_SHROOM }, }; API_CALLABLE(N(GetNextCheatoItem)) { s32* purchase = N(CheatoItems)[script->varTable[0]]; script->varTable[10] = purchase[0]; script->varTable[11] = purchase[1]; return ApiStatus_DONE2; } API_CALLABLE(N(CheckPlayerHasEnoughRoom)) { script->varTable[0] = get_item_empty_count(); return ApiStatus_DONE2; } API_CALLABLE(N(CheckPlayerHasEnoughCoins)) { Bytecode* args = script->ptrReadPos; evt_set_variable(script, *args++, gPlayerData.coins >= RIP_CHEATO_COST); return ApiStatus_DONE2; } EvtScript N(EVS_NpcInteract_RipCheato) = { EVT_IF_EQ(AF_TIK_02, FALSE) EVT_IF_EQ(GF_TIK15_Met_RipCheato, FALSE) EVT_SET(LVar0, MSG_MGM_0001) EVT_SET(GF_TIK15_Met_RipCheato, TRUE) EVT_ELSE EVT_SET(LVar0, MSG_MGM_0002) EVT_END_IF EVT_SET(AF_TIK_02, TRUE) EVT_ELSE EVT_SET(LVar0, MSG_MGM_0003) EVT_END_IF EVT_CALL(SpeakToPlayer, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0, LVar0) EVT_LABEL(0) EVT_CALL(ShowCoinCounter, TRUE) EVT_CALL(ShowChoice, MSG_Choice_0001) EVT_IF_NE(LVar0, 0) EVT_CALL(ShowCoinCounter, FALSE) EVT_CALL(ContinueSpeech, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0, MSG_MGM_0005) EVT_RETURN EVT_END_IF EVT_CALL(N(CheckPlayerHasEnoughCoins), LVar0) EVT_IF_EQ(LVar0, 0) EVT_CALL(ShowCoinCounter, FALSE) EVT_CALL(ContinueSpeech, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0, MSG_MGM_0006) EVT_RETURN EVT_END_IF EVT_SET(LVar0, GB_TIK15_RipCheato_PurchaseCount) EVT_CALL(N(GetNextCheatoItem)) EVT_SWITCH(LVarA) EVT_CASE_EQ(CHEATO_TYPE_STAR_PIECE) EVT_CALL(AddCoin, -RIP_CHEATO_COST) EVT_CALL(ShowCoinCounter, FALSE) EVT_CALL(EndSpeech, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0) EVT_GIVE_STAR_PIECE() EVT_CASE_EQ(CHEATO_TYPE_BADGE) EVT_CALL(AddCoin, -RIP_CHEATO_COST) EVT_CALL(ShowCoinCounter, FALSE) EVT_CALL(EndSpeech, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0) EVT_GIVE_BADGE_REWARD(ITEM_BUMP_ATTACK) EVT_CASE_EQ(CHEATO_TYPE_CONSUMABLE) EVT_CALL(N(CheckPlayerHasEnoughRoom)) EVT_IF_LE(LVar0, 0) EVT_CALL(ShowCoinCounter, FALSE) EVT_CALL(ContinueSpeech, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0, MSG_MGM_0007) EVT_RETURN EVT_END_IF EVT_CALL(AddCoin, -RIP_CHEATO_COST) EVT_CALL(ShowCoinCounter, FALSE) EVT_CALL(EndSpeech, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0) EVT_GIVE_CONSUMABLE_REWARD_ALT(LVarB) EVT_END_SWITCH EVT_IF_LT(GB_TIK15_RipCheato_PurchaseCount, 10) EVT_ADD(GB_TIK15_RipCheato_PurchaseCount, 1) EVT_END_IF EVT_CALL(SpeakToPlayer, NPC_RipCheato, ANIM_RipCheato_Talk, ANIM_RipCheato_Idle, 0, MSG_MGM_0004) EVT_GOTO(0) EVT_RETURN EVT_END }; EvtScript N(EVS_NpcInit_RipCheato) = { EVT_CALL(BindNpcInteract, NPC_SELF, EVT_PTR(N(EVS_NpcInteract_RipCheato))) EVT_SET(AF_TIK_02, FALSE) EVT_RETURN EVT_END }; NpcData N(NpcData_RipCheato) = { .id = NPC_RipCheato, .pos = { -80.0f, -10.0f, 0.0f }, .yaw = 270, .init = &N(EVS_NpcInit_RipCheato), .settings = &N(NpcSettings_RipCheato), .flags = ENEMY_FLAG_PASSIVE | ENEMY_FLAG_IGNORE_WORLD_COLLISION | ENEMY_FLAG_IGNORE_ENTITY_COLLISION | ENEMY_FLAG_FLYING, .drops = NO_DROPS, .animations = { .idle = ANIM_RipCheato_Idle, .walk = ANIM_RipCheato_Idle, .run = ANIM_RipCheato_Idle, .chase = ANIM_RipCheato_Idle, .anim_4 = ANIM_RipCheato_Idle, .anim_5 = ANIM_RipCheato_Idle, .death = ANIM_RipCheato_Idle, .hit = ANIM_RipCheato_Idle, .anim_8 = ANIM_RipCheato_Idle, .anim_9 = ANIM_RipCheato_Idle, .anim_A = ANIM_RipCheato_Idle, .anim_B = ANIM_RipCheato_Idle, .anim_C = ANIM_RipCheato_Idle, .anim_D = ANIM_RipCheato_Idle, .anim_E = ANIM_RipCheato_Idle, .anim_F = ANIM_RipCheato_Idle, }, .tattle = MSG_NpcTattle_RipCheato, }; NpcGroupList N(DefaultNPCs) = { NPC_GROUP(N(NpcData_RipCheato), BTL_KMR_1_FORMATION_06), {} };
36c316538326332b2e8acbdeb5f42f2afa70e2bf
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/zaurus/include/bswap.h
7234256fed193c12f958fe44f0ee7c830bdbf1a5
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
94
h
bswap.h
/* $NetBSD: bswap.h,v 1.1 2006/12/16 05:43:29 ober Exp $ */ #include <arm/bswap.h>
768999adfffbac9ab7cee1d0a7e3cb6242abb9ed
d8fbc197e4fb03e0f083291ec92b75542bcb4917
/inc/sysapi/error.h
f844aa3e83b7ae06dc51abac01b13f9221821c40
[]
no_license
hujianzhe/util
b7576091b9d1daa4e3b7f2e8d3be85501c7877a5
146f6c2395c6d8da7383a41d35ebc8190ba8ea02
refs/heads/master
2023-08-18T13:00:57.886249
2023-08-15T08:57:33
2023-08-15T08:57:33
112,769,785
162
55
null
2020-06-09T16:03:15
2017-12-01T17:49:43
C
UTF-8
C
false
false
369
h
error.h
// // Created by hujianzhe // #ifndef UTIL_C_SYSLIB_ERROR_H #define UTIL_C_SYSLIB_ERROR_H #include "../platform_define.h" #include <errno.h> #ifdef __cplusplus extern "C" { #endif __declspec_dll int errnoGet(void); __declspec_dll void errnoSet(int errnum); __declspec_dll char* errnoText(int errnum, char* buf, size_t bufsize); #ifdef __cplusplus } #endif #endif
431f76a58e39ff3fdceb0b0a8bba8351fe8de7e5
61da6274995cf914291af51bd02e60f408fdfedd
/src/estdims.c
aa7d8a822ae384d6045a7b6c5866a152d2d3a839
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause" ]
permissive
mrirecon/bart
360d518b4c79836d506803aa4a77e8e252ab820b
a3c9dc313f79c4c52f1ba3e617d5831ef088ddf7
refs/heads/master
2023-08-31T11:01:08.932824
2023-08-30T12:15:35
2023-08-30T13:51:18
23,212,230
264
185
BSD-3-Clause
2023-08-03T18:43:36
2014-08-22T03:57:09
C
UTF-8
C
false
false
1,144
c
estdims.c
/* Copyright 2015. The Regents of the University of California. * Copyright 2022. Martin Uecker. * All rights reserved. Use of this source code is governed by * a BSD-style license which can be found in the LICENSE file. * * Authors: * 2015 Frank Ong <frankong@berkeley.edu> */ #include <complex.h> #include "misc/mmio.h" #include "misc/io.h" #include "misc/misc.h" #include "misc/opts.h" #include "misc/mri.h" static const char help_str[] = "Estimate image dimension from non-Cartesian trajectory.\n" "Assume trajectory scaled to -DIM/2 to DIM/2 (ie dk=1/FOV=1)"; int main_estdims(int argc, char* argv[argc]) { const char* traj_file = NULL; struct arg_s args[] = { ARG_INFILE(true, &traj_file, "traj"), }; const struct opt_s opts[] = { }; cmdline(&argc, argv, ARRAY_SIZE(args), args, help_str, ARRAY_SIZE(opts), opts); int N = 16; long traj_dims[N]; complex float* traj = load_cfl(traj_file, N, traj_dims); long im_dims[N]; estimate_im_dims(N, FFT_FLAGS, im_dims, traj_dims, traj); bart_printf("%ld %ld %ld\n", im_dims[0], im_dims[1], im_dims[2]); unmap_cfl(N, traj_dims, traj); return 0; }
7aad058759107ca308431d4cda76c2a7ed8d6b97
c68f791005359cfec81af712aae0276c70b512b0
/TOKI Open 2018/mining/mining.h
38aa24382e56c59c2c3eeeb65b06461079e17eac
[]
no_license
luqmanarifin/cp
83b3435ba2fdd7e4a9db33ab47c409adb088eb90
08c2d6b6dd8c4eb80278ec34dc64fd4db5878f9f
refs/heads/master
2022-10-16T14:30:09.683632
2022-10-08T20:35:42
2022-10-08T20:35:42
51,346,488
106
46
null
2017-04-16T11:06:18
2016-02-09T04:26:58
C++
UTF-8
C
false
false
133
h
mining.h
#ifndef __MINING_H__ #define __MINING_H__ bool isIntegerDistance(int A, int B); void answer(int A, int B); void findGold(); #endif
9c8f0b5dab4435289bd096077904402d2c157d91
e22fd36933c9114a9df1694e7a6274bf059de2a6
/third_party/acados/include/hpipm/include/hpipm_s_dense_qp_ipm.h
f2d56d45299574fe394d2feac37c8d082039b71c
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
commaai/openpilot
66dfb7f31290bc8f58c9ead95d56697a52b45afb
a0b49d54222c52ff0112c402bc0e0d9262e77a66
refs/heads/master
2023-09-05T21:34:14.076796
2023-09-05T21:15:18
2023-09-05T21:15:18
74,627,617
46,071
9,878
MIT
2023-09-14T21:51:23
2016-11-24T01:33:30
Python
UTF-8
C
false
false
11,896
h
hpipm_s_dense_qp_ipm.h
/************************************************************************************************** * * * This file is part of HPIPM. * * * * HPIPM -- High-Performance Interior Point Method. * * Copyright (C) 2019 by Gianluca Frison. * * Developed at IMTEK (University of Freiburg) under the supervision of Moritz Diehl. * * All rights reserved. * * * * The 2-Clause BSD License * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions are met: * * * * 1. Redistributions of source code must retain the above copyright notice, this * * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * * this list of conditions and the following disclaimer in the documentation * * and/or other materials provided with the distribution. * * * * 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. * * * * Author: Gianluca Frison, gianluca.frison (at) imtek.uni-freiburg.de * * * **************************************************************************************************/ #ifndef HPIPM_S_DENSE_QP_IPM_H_ #define HPIPM_S_DENSE_QP_IPM_H_ #include <blasfeo_target.h> #include <blasfeo_common.h> #include <hpipm_common.h> #include <hpipm_s_dense_qp_dim.h> #include <hpipm_s_dense_qp.h> #include <hpipm_s_dense_qp_res.h> #include <hpipm_s_dense_qp_sol.h> #ifdef __cplusplus extern "C" { #endif struct s_dense_qp_ipm_arg { float mu0; // initial value for duality measure float alpha_min; // exit cond on step length float res_g_max; // exit cond on inf norm of residuals float res_b_max; // exit cond on inf norm of residuals float res_d_max; // exit cond on inf norm of residuals float res_m_max; // exit cond on inf norm of residuals float reg_prim; // reg of primal hessian float reg_dual; // reg of dual hessian float lam_min; // min value in lam vector float t_min; // min value in t vector float tau_min; // min value of barrier parameter int iter_max; // exit cond in iter number int stat_max; // iterations saved in stat int pred_corr; // Mehrotra's predictor-corrector IPM algirthm int cond_pred_corr; // conditional Mehrotra's predictor-corrector int scale; // scale hessian int itref_pred_max; // max number of iterative refinement steps for predictor step int itref_corr_max; // max number of iterative refinement steps for corrector step int warm_start; // 0 no warm start, 1 warm start primal sol, 2 warm start primal and dual sol int lq_fact; // 0 syrk+potrf, 1 mix, 2 lq int abs_form; // absolute IPM formulation int comp_res_exit; // compute residuals on exit (only for abs_form==1) int comp_res_pred; // compute residuals of prediction int kkt_fact_alg; // 0 null-space, 1 schur-complement int remove_lin_dep_eq; // 0 do not, 1 do check and remove linearly dependent equality constraints int compute_obj; // compute obj on exit int split_step; // use different steps for primal and dual variables int t_lam_min; // clip t and lam: 0 no, 1 in Gamma computation, 2 in solution int mode; hpipm_size_t memsize; }; struct s_dense_qp_ipm_ws { struct s_core_qp_ipm_workspace *core_workspace; struct s_dense_qp_res_ws *res_ws; struct s_dense_qp_sol *sol_step; struct s_dense_qp_sol *sol_itref; struct s_dense_qp *qp_step; struct s_dense_qp *qp_itref; struct s_dense_qp_res *res; struct s_dense_qp_res *res_itref; struct s_dense_qp_res *res_step; struct blasfeo_svec *Gamma; // struct blasfeo_svec *gamma; // struct blasfeo_svec *Zs_inv; // struct blasfeo_smat *Lv; // struct blasfeo_smat *AL; // struct blasfeo_smat *Le; // struct blasfeo_smat *Ctx; // struct blasfeo_svec *lv; // struct blasfeo_svec *sv; // scale for Lv struct blasfeo_svec *se; // scale for Le struct blasfeo_svec *tmp_nbg; // work space of size nb+ng struct blasfeo_svec *tmp_ns; // work space of size ns struct blasfeo_smat *lq0; struct blasfeo_smat *lq1; struct blasfeo_svec *tmp_m; struct blasfeo_smat *A_LQ; struct blasfeo_smat *A_Q; struct blasfeo_smat *Zt; struct blasfeo_smat *ZtH; struct blasfeo_smat *ZtHZ; struct blasfeo_svec *xy; struct blasfeo_svec *Yxy; struct blasfeo_svec *xz; struct blasfeo_svec *tmp_nv; struct blasfeo_svec *tmp_2ns; struct blasfeo_svec *tmp_nv2ns; struct blasfeo_smat *A_li; // A of linearly independent equality constraints struct blasfeo_svec *b_li; // b of linearly independent equality constraints struct blasfeo_smat *A_bkp; // pointer to backup A struct blasfeo_svec *b_bkp; // pointer to backup b struct blasfeo_smat *Ab_LU; float *stat; // convergence statistics int *ipiv_v; int *ipiv_e; int *ipiv_e1; void *lq_work0; void *lq_work1; void *lq_work_null; void *orglq_work_null; int iter; // iteration number int stat_max; // iterations saved in stat int stat_m; // numer of recorded stat per ipm iter int scale; int use_hess_fact; int use_A_fact; int status; int lq_fact; // cache from arg int mask_constr; // use constr mask int ne_li; // number of linearly independent equality constraints int ne_bkp; // ne backup hpipm_size_t memsize; // memory size (in bytes) of workspace }; // hpipm_size_t s_dense_qp_ipm_arg_memsize(struct s_dense_qp_dim *qp_dim); // void s_dense_qp_ipm_arg_create(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg, void *mem); // void s_dense_qp_ipm_arg_set_default(enum hpipm_mode mode, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set(char *field, void *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_iter_max(int *iter_max, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_alpha_min(float *alpha_min, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_mu0(float *mu0, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_tol_stat(float *tol_stat, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_tol_eq(float *tol_eq, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_tol_ineq(float *tol_ineq, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_tol_comp(float *tol_comp, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_reg_prim(float *reg, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_reg_dual(float *reg, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_warm_start(int *warm_start, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_pred_corr(int *pred_corr, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_cond_pred_corr(int *cond_pred_corr, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_comp_res_pred(int *comp_res_pred, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_comp_res_exit(int *comp_res_exit, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_lam_min(float *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_t_min(float *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_tau_min(float *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_kkt_fact_alg(int *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_remove_lin_dep_eq(int *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_compute_obj(int *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_split_step(int *value, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_arg_set_t_lam_min(int *value, struct s_dense_qp_ipm_arg *arg); // hpipm_size_t s_dense_qp_ipm_ws_memsize(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg); // void s_dense_qp_ipm_ws_create(struct s_dense_qp_dim *qp_dim, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws, void *mem); // void s_dense_qp_ipm_get(char *field, struct s_dense_qp_ipm_ws *ws, void *value); // void s_dense_qp_ipm_get_status(struct s_dense_qp_ipm_ws *ws, int *status); // void s_dense_qp_ipm_get_iter(struct s_dense_qp_ipm_ws *ws, int *iter); // void s_dense_qp_ipm_get_max_res_stat(struct s_dense_qp_ipm_ws *ws, float *res_stat); // void s_dense_qp_ipm_get_max_res_eq(struct s_dense_qp_ipm_ws *ws, float *res_eq); // void s_dense_qp_ipm_get_max_res_ineq(struct s_dense_qp_ipm_ws *ws, float *res_ineq); // void s_dense_qp_ipm_get_max_res_comp(struct s_dense_qp_ipm_ws *ws, float *res_comp); // void s_dense_qp_ipm_get_stat(struct s_dense_qp_ipm_ws *ws, float **stat); // void s_dense_qp_ipm_get_stat_m(struct s_dense_qp_ipm_ws *ws, int *stat_m); // void s_dense_qp_init_var(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); // void s_dense_qp_ipm_abs_step(int kk, struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); // void s_dense_qp_ipm_delta_step(int kk, struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); // void s_dense_qp_ipm_solve(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); // void s_dense_qp_ipm_predict(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); // void s_dense_qp_ipm_sens(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); // void s_dense_qp_compute_step_length(struct s_dense_qp *qp, struct s_dense_qp_sol *qp_sol, struct s_dense_qp_ipm_arg *arg, struct s_dense_qp_ipm_ws *ws); #ifdef __cplusplus } /* extern "C" */ #endif #endif // HPIPM_S_DENSE_QP_IPM_H_
3e3ba266b7ffada5f684afd1bab12cc594005f23
f21ddc1d9fcec88bf844bcc2c67b287b06156530
/zrtpcpp/zrtp/libzrtpcpp/ZrtpCrc32.h
f887d17c3422a6ef998a17523c1172a29b5ceeb5
[ "Apache-2.0", "BSD-3-Clause" ]
permissive
tomek-o/tSIP
69a6c4fa7b971fc37af97ab4a7e24c34f3bf273c
dd5d23316a819ad659e32d7bb70b8092946e73c5
refs/heads/master
2023-09-03T19:43:36.499392
2023-09-03T13:09:44
2023-09-03T13:09:44
148,903,107
110
32
null
2023-08-15T12:23:03
2018-09-15T13:11:01
C
UTF-8
C
false
false
1,730
h
ZrtpCrc32.h
/* * Copyright 2006 - 2018, Werner Dittmann * * 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 _ZRTPCRC32_H_ #define _ZRTPCRC32_H_ /** * * @file ZrtpCrc32.h * @brief Methods to compute the CRC32 checksum for ZRTP packets * * @ingroup GNU_ZRTP * @{ * * @see ZrtpCallback */ /** * Check if a buffer matches a given CRC32 checksum. * * @param buffer * Pointer to the data buffer. * @param length * Length in bytes of the data buffer. * @param crc32 * The CRC32 checksum. * * @return * @c true if the CRC32 checksum matches the computed checksum of the * buffer, @c false otherwise. */ bool zrtpCheckCksum(const uint8_t *buffer, uint16_t length, uint32_t crc32); /** * Generate a CRC32 checksum of a data buffer * * @param buffer * Pointer to the buffer. * @param length * Lenght of the buffer in bytes. * * @return * A preliminary CRC32 checksum */ uint32_t zrtpGenerateCksum(const uint8_t *buffer, uint32_t length); /** * Close CRC32 computation. * * @param crc32 * A preliminary CRC32 checksum. * * @return * The ready to use CRC32 checksum in host order. */ uint32_t zrtpEndCksum(uint32_t crc32); /** * @} */ #endif
11e66fa025a33c5dbc40f23aac5eefa67747c8b5
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/x86/mm/init_64.c
b04e502620882f154b580d8191f578a0f33d506b
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
35,208
c
init_64.c
/* * linux/arch/x86_64/mm/init.c * * Copyright (C) 1995 Linus Torvalds * Copyright (C) 2000 Pavel Machek <pavel@ucw.cz> * Copyright (C) 2002,2003 Andi Kleen <ak@suse.de> */ #include <linux/signal.h> #include <linux/sched.h> #include <linux/kernel.h> #include <linux/errno.h> #include <linux/string.h> #include <linux/types.h> #include <linux/ptrace.h> #include <linux/mman.h> #include <linux/mm.h> #include <linux/swap.h> #include <linux/smp.h> #include <linux/init.h> #include <linux/initrd.h> #include <linux/pagemap.h> #include <linux/bootmem.h> #include <linux/memblock.h> #include <linux/proc_fs.h> #include <linux/pci.h> #include <linux/pfn.h> #include <linux/poison.h> #include <linux/dma-mapping.h> #include <linux/module.h> #include <linux/memory.h> #include <linux/memory_hotplug.h> #include <linux/nmi.h> #include <linux/gfp.h> #include <linux/kcore.h> #include <asm/processor.h> #include <asm/bios_ebda.h> #include <asm/uaccess.h> #include <asm/pgtable.h> #include <asm/pgalloc.h> #include <asm/dma.h> #include <asm/fixmap.h> #include <asm/e820.h> #include <asm/apic.h> #include <asm/tlb.h> #include <asm/mmu_context.h> #include <asm/proto.h> #include <asm/smp.h> #include <asm/sections.h> #include <asm/kdebug.h> #include <asm/numa.h> #include <asm/cacheflush.h> #include <asm/init.h> #include <asm/uv/uv.h> #include <asm/setup.h> #include "mm_internal.h" static void ident_pmd_init(unsigned long pmd_flag, pmd_t *pmd_page, unsigned long addr, unsigned long end) { addr &= PMD_MASK; for (; addr < end; addr += PMD_SIZE) { pmd_t *pmd = pmd_page + pmd_index(addr); if (!pmd_present(*pmd)) set_pmd(pmd, __pmd(addr | pmd_flag)); } } static int ident_pud_init(struct x86_mapping_info *info, pud_t *pud_page, unsigned long addr, unsigned long end) { unsigned long next; for (; addr < end; addr = next) { pud_t *pud = pud_page + pud_index(addr); pmd_t *pmd; next = (addr & PUD_MASK) + PUD_SIZE; if (next > end) next = end; if (pud_present(*pud)) { pmd = pmd_offset(pud, 0); ident_pmd_init(info->pmd_flag, pmd, addr, next); continue; } pmd = (pmd_t *)info->alloc_pgt_page(info->context); if (!pmd) return -ENOMEM; ident_pmd_init(info->pmd_flag, pmd, addr, next); set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE)); } return 0; } int kernel_ident_mapping_init(struct x86_mapping_info *info, pgd_t *pgd_page, unsigned long addr, unsigned long end) { unsigned long next; int result; int off = info->kernel_mapping ? pgd_index(__PAGE_OFFSET) : 0; for (; addr < end; addr = next) { pgd_t *pgd = pgd_page + pgd_index(addr) + off; pud_t *pud; next = (addr & PGDIR_MASK) + PGDIR_SIZE; if (next > end) next = end; if (pgd_present(*pgd)) { pud = pud_offset(pgd, 0); result = ident_pud_init(info, pud, addr, next); if (result) return result; continue; } pud = (pud_t *)info->alloc_pgt_page(info->context); if (!pud) return -ENOMEM; result = ident_pud_init(info, pud, addr, next); if (result) return result; set_pgd(pgd, __pgd(__pa(pud) | _KERNPG_TABLE)); } return 0; } static int __init parse_direct_gbpages_off(char *arg) { direct_gbpages = 0; return 0; } early_param("nogbpages", parse_direct_gbpages_off); static int __init parse_direct_gbpages_on(char *arg) { direct_gbpages = 1; return 0; } early_param("gbpages", parse_direct_gbpages_on); /* * NOTE: pagetable_init alloc all the fixmap pagetables contiguous on the * physical space so we can cache the place of the first one and move * around without checking the pgd every time. */ pteval_t __supported_pte_mask __read_mostly = ~_PAGE_IOMAP; EXPORT_SYMBOL_GPL(__supported_pte_mask); int force_personality32; /* * noexec32=on|off * Control non executable heap for 32bit processes. * To control the stack too use noexec=off * * on PROT_READ does not imply PROT_EXEC for 32-bit processes (default) * off PROT_READ implies PROT_EXEC */ static int __init nonx32_setup(char *str) { if (!strcmp(str, "on")) force_personality32 &= ~READ_IMPLIES_EXEC; else if (!strcmp(str, "off")) force_personality32 |= READ_IMPLIES_EXEC; return 1; } __setup("noexec32=", nonx32_setup); /* * When memory was added/removed make sure all the processes MM have * suitable PGD entries in the local PGD level page. */ void sync_global_pgds(unsigned long start, unsigned long end) { unsigned long address; for (address = start; address <= end; address += PGDIR_SIZE) { const pgd_t *pgd_ref = pgd_offset_k(address); struct page *page; if (pgd_none(*pgd_ref)) continue; spin_lock(&pgd_lock); list_for_each_entry(page, &pgd_list, lru) { pgd_t *pgd; spinlock_t *pgt_lock; pgd = (pgd_t *)page_address(page) + pgd_index(address); /* the pgt_lock only for Xen */ pgt_lock = &pgd_page_get_mm(page)->page_table_lock; spin_lock(pgt_lock); if (pgd_none(*pgd)) set_pgd(pgd, *pgd_ref); else BUG_ON(pgd_page_vaddr(*pgd) != pgd_page_vaddr(*pgd_ref)); spin_unlock(pgt_lock); } spin_unlock(&pgd_lock); } } /* * NOTE: This function is marked __ref because it calls __init function * (alloc_bootmem_pages). It's safe to do it ONLY when after_bootmem == 0. */ static __ref void *spp_getpage(void) { void *ptr; if (after_bootmem) ptr = (void *) get_zeroed_page(GFP_ATOMIC | __GFP_NOTRACK); else ptr = alloc_bootmem_pages(PAGE_SIZE); if (!ptr || ((unsigned long)ptr & ~PAGE_MASK)) { panic("set_pte_phys: cannot allocate page data %s\n", after_bootmem ? "after bootmem" : ""); } pr_debug("spp_getpage %p\n", ptr); return ptr; } static pud_t *fill_pud(pgd_t *pgd, unsigned long vaddr) { if (pgd_none(*pgd)) { pud_t *pud = (pud_t *)spp_getpage(); pgd_populate(&init_mm, pgd, pud); if (pud != pud_offset(pgd, 0)) printk(KERN_ERR "PAGETABLE BUG #00! %p <-> %p\n", pud, pud_offset(pgd, 0)); } return pud_offset(pgd, vaddr); } static pmd_t *fill_pmd(pud_t *pud, unsigned long vaddr) { if (pud_none(*pud)) { pmd_t *pmd = (pmd_t *) spp_getpage(); pud_populate(&init_mm, pud, pmd); if (pmd != pmd_offset(pud, 0)) printk(KERN_ERR "PAGETABLE BUG #01! %p <-> %p\n", pmd, pmd_offset(pud, 0)); } return pmd_offset(pud, vaddr); } static pte_t *fill_pte(pmd_t *pmd, unsigned long vaddr) { if (pmd_none(*pmd)) { pte_t *pte = (pte_t *) spp_getpage(); pmd_populate_kernel(&init_mm, pmd, pte); if (pte != pte_offset_kernel(pmd, 0)) printk(KERN_ERR "PAGETABLE BUG #02!\n"); } return pte_offset_kernel(pmd, vaddr); } void set_pte_vaddr_pud(pud_t *pud_page, unsigned long vaddr, pte_t new_pte) { pud_t *pud; pmd_t *pmd; pte_t *pte; pud = pud_page + pud_index(vaddr); pmd = fill_pmd(pud, vaddr); pte = fill_pte(pmd, vaddr); set_pte(pte, new_pte); /* * It's enough to flush this one mapping. * (PGE mappings get flushed as well) */ __flush_tlb_one(vaddr); } void set_pte_vaddr(unsigned long vaddr, pte_t pteval) { pgd_t *pgd; pud_t *pud_page; pr_debug("set_pte_vaddr %lx to %lx\n", vaddr, native_pte_val(pteval)); pgd = pgd_offset_k(vaddr); if (pgd_none(*pgd)) { printk(KERN_ERR "PGD FIXMAP MISSING, it should be setup in head.S!\n"); return; } pud_page = (pud_t*)pgd_page_vaddr(*pgd); set_pte_vaddr_pud(pud_page, vaddr, pteval); } pmd_t * __init populate_extra_pmd(unsigned long vaddr) { pgd_t *pgd; pud_t *pud; pgd = pgd_offset_k(vaddr); pud = fill_pud(pgd, vaddr); return fill_pmd(pud, vaddr); } pte_t * __init populate_extra_pte(unsigned long vaddr) { pmd_t *pmd; pmd = populate_extra_pmd(vaddr); return fill_pte(pmd, vaddr); } /* * Create large page table mappings for a range of physical addresses. */ static void __init __init_extra_mapping(unsigned long phys, unsigned long size, pgprot_t prot) { pgd_t *pgd; pud_t *pud; pmd_t *pmd; BUG_ON((phys & ~PMD_MASK) || (size & ~PMD_MASK)); for (; size; phys += PMD_SIZE, size -= PMD_SIZE) { pgd = pgd_offset_k((unsigned long)__va(phys)); if (pgd_none(*pgd)) { pud = (pud_t *) spp_getpage(); set_pgd(pgd, __pgd(__pa(pud) | _KERNPG_TABLE | _PAGE_USER)); } pud = pud_offset(pgd, (unsigned long)__va(phys)); if (pud_none(*pud)) { pmd = (pmd_t *) spp_getpage(); set_pud(pud, __pud(__pa(pmd) | _KERNPG_TABLE | _PAGE_USER)); } pmd = pmd_offset(pud, phys); BUG_ON(!pmd_none(*pmd)); set_pmd(pmd, __pmd(phys | pgprot_val(prot))); } } void __init init_extra_mapping_wb(unsigned long phys, unsigned long size) { __init_extra_mapping(phys, size, PAGE_KERNEL_LARGE); } void __init init_extra_mapping_uc(unsigned long phys, unsigned long size) { __init_extra_mapping(phys, size, PAGE_KERNEL_LARGE_NOCACHE); } /* * The head.S code sets up the kernel high mapping: * * from __START_KERNEL_map to __START_KERNEL_map + size (== _end-_text) * * phys_addr holds the negative offset to the kernel, which is added * to the compile time generated pmds. This results in invalid pmds up * to the point where we hit the physaddr 0 mapping. * * We limit the mappings to the region from _text to _brk_end. _brk_end * is rounded up to the 2MB boundary. This catches the invalid pmds as * well, as they are located before _text: */ void __init cleanup_highmap(void) { unsigned long vaddr = __START_KERNEL_map; unsigned long vaddr_end = __START_KERNEL_map + KERNEL_IMAGE_SIZE; unsigned long end = roundup((unsigned long)_brk_end, PMD_SIZE) - 1; pmd_t *pmd = level2_kernel_pgt; /* * Native path, max_pfn_mapped is not set yet. * Xen has valid max_pfn_mapped set in * arch/x86/xen/mmu.c:xen_setup_kernel_pagetable(). */ if (max_pfn_mapped) vaddr_end = __START_KERNEL_map + (max_pfn_mapped << PAGE_SHIFT); for (; vaddr + PMD_SIZE - 1 < vaddr_end; pmd++, vaddr += PMD_SIZE) { if (pmd_none(*pmd)) continue; if (vaddr < (unsigned long) _text || vaddr > end) set_pmd(pmd, __pmd(0)); } } static unsigned long __meminit phys_pte_init(pte_t *pte_page, unsigned long addr, unsigned long end, pgprot_t prot) { unsigned long pages = 0, next; unsigned long last_map_addr = end; int i; pte_t *pte = pte_page + pte_index(addr); for (i = pte_index(addr); i < PTRS_PER_PTE; i++, addr = next, pte++) { next = (addr & PAGE_MASK) + PAGE_SIZE; if (addr >= end) { if (!after_bootmem && !e820_any_mapped(addr & PAGE_MASK, next, E820_RAM) && !e820_any_mapped(addr & PAGE_MASK, next, E820_RESERVED_KERN)) set_pte(pte, __pte(0)); continue; } /* * We will re-use the existing mapping. * Xen for example has some special requirements, like mapping * pagetable pages as RO. So assume someone who pre-setup * these mappings are more intelligent. */ if (pte_val(*pte)) { if (!after_bootmem) pages++; continue; } if (0) printk(" pte=%p addr=%lx pte=%016lx\n", pte, addr, pfn_pte(addr >> PAGE_SHIFT, PAGE_KERNEL).pte); pages++; set_pte(pte, pfn_pte(addr >> PAGE_SHIFT, prot)); last_map_addr = (addr & PAGE_MASK) + PAGE_SIZE; } update_page_count(PG_LEVEL_4K, pages); return last_map_addr; } static unsigned long __meminit phys_pmd_init(pmd_t *pmd_page, unsigned long address, unsigned long end, unsigned long page_size_mask, pgprot_t prot) { unsigned long pages = 0, next; unsigned long last_map_addr = end; int i = pmd_index(address); for (; i < PTRS_PER_PMD; i++, address = next) { pmd_t *pmd = pmd_page + pmd_index(address); pte_t *pte; pgprot_t new_prot = prot; next = (address & PMD_MASK) + PMD_SIZE; if (address >= end) { if (!after_bootmem && !e820_any_mapped(address & PMD_MASK, next, E820_RAM) && !e820_any_mapped(address & PMD_MASK, next, E820_RESERVED_KERN)) set_pmd(pmd, __pmd(0)); continue; } if (pmd_val(*pmd)) { if (!pmd_large(*pmd)) { spin_lock(&init_mm.page_table_lock); pte = (pte_t *)pmd_page_vaddr(*pmd); last_map_addr = phys_pte_init(pte, address, end, prot); spin_unlock(&init_mm.page_table_lock); continue; } /* * If we are ok with PG_LEVEL_2M mapping, then we will * use the existing mapping, * * Otherwise, we will split the large page mapping but * use the same existing protection bits except for * large page, so that we don't violate Intel's TLB * Application note (317080) which says, while changing * the page sizes, new and old translations should * not differ with respect to page frame and * attributes. */ if (page_size_mask & (1 << PG_LEVEL_2M)) { if (!after_bootmem) pages++; last_map_addr = next; continue; } new_prot = pte_pgprot(pte_clrhuge(*(pte_t *)pmd)); } if (page_size_mask & (1<<PG_LEVEL_2M)) { pages++; spin_lock(&init_mm.page_table_lock); set_pte((pte_t *)pmd, pfn_pte((address & PMD_MASK) >> PAGE_SHIFT, __pgprot(pgprot_val(prot) | _PAGE_PSE))); spin_unlock(&init_mm.page_table_lock); last_map_addr = next; continue; } pte = alloc_low_page(); last_map_addr = phys_pte_init(pte, address, end, new_prot); spin_lock(&init_mm.page_table_lock); pmd_populate_kernel(&init_mm, pmd, pte); spin_unlock(&init_mm.page_table_lock); } update_page_count(PG_LEVEL_2M, pages); return last_map_addr; } static unsigned long __meminit phys_pud_init(pud_t *pud_page, unsigned long addr, unsigned long end, unsigned long page_size_mask) { unsigned long pages = 0, next; unsigned long last_map_addr = end; int i = pud_index(addr); for (; i < PTRS_PER_PUD; i++, addr = next) { pud_t *pud = pud_page + pud_index(addr); pmd_t *pmd; pgprot_t prot = PAGE_KERNEL; next = (addr & PUD_MASK) + PUD_SIZE; if (addr >= end) { if (!after_bootmem && !e820_any_mapped(addr & PUD_MASK, next, E820_RAM) && !e820_any_mapped(addr & PUD_MASK, next, E820_RESERVED_KERN)) set_pud(pud, __pud(0)); continue; } if (pud_val(*pud)) { if (!pud_large(*pud)) { pmd = pmd_offset(pud, 0); last_map_addr = phys_pmd_init(pmd, addr, end, page_size_mask, prot); __flush_tlb_all(); continue; } /* * If we are ok with PG_LEVEL_1G mapping, then we will * use the existing mapping. * * Otherwise, we will split the gbpage mapping but use * the same existing protection bits except for large * page, so that we don't violate Intel's TLB * Application note (317080) which says, while changing * the page sizes, new and old translations should * not differ with respect to page frame and * attributes. */ if (page_size_mask & (1 << PG_LEVEL_1G)) { if (!after_bootmem) pages++; last_map_addr = next; continue; } prot = pte_pgprot(pte_clrhuge(*(pte_t *)pud)); } if (page_size_mask & (1<<PG_LEVEL_1G)) { pages++; spin_lock(&init_mm.page_table_lock); set_pte((pte_t *)pud, pfn_pte((addr & PUD_MASK) >> PAGE_SHIFT, PAGE_KERNEL_LARGE)); spin_unlock(&init_mm.page_table_lock); last_map_addr = next; continue; } pmd = alloc_low_page(); last_map_addr = phys_pmd_init(pmd, addr, end, page_size_mask, prot); spin_lock(&init_mm.page_table_lock); pud_populate(&init_mm, pud, pmd); spin_unlock(&init_mm.page_table_lock); } __flush_tlb_all(); update_page_count(PG_LEVEL_1G, pages); return last_map_addr; } unsigned long __meminit kernel_physical_mapping_init(unsigned long start, unsigned long end, unsigned long page_size_mask) { bool pgd_changed = false; unsigned long next, last_map_addr = end; unsigned long addr; start = (unsigned long)__va(start); end = (unsigned long)__va(end); addr = start; for (; start < end; start = next) { pgd_t *pgd = pgd_offset_k(start); pud_t *pud; next = (start & PGDIR_MASK) + PGDIR_SIZE; if (pgd_val(*pgd)) { pud = (pud_t *)pgd_page_vaddr(*pgd); last_map_addr = phys_pud_init(pud, __pa(start), __pa(end), page_size_mask); continue; } pud = alloc_low_page(); last_map_addr = phys_pud_init(pud, __pa(start), __pa(end), page_size_mask); spin_lock(&init_mm.page_table_lock); pgd_populate(&init_mm, pgd, pud); spin_unlock(&init_mm.page_table_lock); pgd_changed = true; } if (pgd_changed) sync_global_pgds(addr, end - 1); __flush_tlb_all(); return last_map_addr; } #ifndef CONFIG_NUMA void __init initmem_init(void) { memblock_set_node(0, (phys_addr_t)ULLONG_MAX, 0); } #endif void __init paging_init(void) { sparse_memory_present_with_active_regions(MAX_NUMNODES); sparse_init(); /* * clear the default setting with node 0 * note: don't use nodes_clear here, that is really clearing when * numa support is not compiled in, and later node_set_state * will not set it back. */ node_clear_state(0, N_MEMORY); if (N_MEMORY != N_NORMAL_MEMORY) node_clear_state(0, N_NORMAL_MEMORY); zone_sizes_init(); } /* * Memory hotplug specific functions */ #ifdef CONFIG_MEMORY_HOTPLUG /* * After memory hotplug the variables max_pfn, max_low_pfn and high_memory need * updating. */ static void update_end_of_memory_vars(u64 start, u64 size) { unsigned long end_pfn = PFN_UP(start + size); if (end_pfn > max_pfn) { max_pfn = end_pfn; max_low_pfn = end_pfn; high_memory = (void *)__va(max_pfn * PAGE_SIZE - 1) + 1; } } /* * Memory is added always to NORMAL zone. This means you will never get * additional DMA/DMA32 memory. */ int arch_add_memory(int nid, u64 start, u64 size) { struct pglist_data *pgdat = NODE_DATA(nid); struct zone *zone = pgdat->node_zones + ZONE_NORMAL; unsigned long start_pfn = start >> PAGE_SHIFT; unsigned long nr_pages = size >> PAGE_SHIFT; int ret; init_memory_mapping(start, start + size); ret = __add_pages(nid, zone, start_pfn, nr_pages); WARN_ON_ONCE(ret); /* update max_pfn, max_low_pfn and high_memory */ update_end_of_memory_vars(start, size); return ret; } EXPORT_SYMBOL_GPL(arch_add_memory); #define PAGE_INUSE 0xFD static void __meminit free_pagetable(struct page *page, int order) { struct zone *zone; bool bootmem = false; unsigned long magic; unsigned int nr_pages = 1 << order; /* bootmem page has reserved flag */ if (PageReserved(page)) { __ClearPageReserved(page); bootmem = true; magic = (unsigned long)page->lru.next; if (magic == SECTION_INFO || magic == MIX_SECTION_INFO) { while (nr_pages--) put_page_bootmem(page++); } else __free_pages_bootmem(page, order); } else free_pages((unsigned long)page_address(page), order); /* * SECTION_INFO pages and MIX_SECTION_INFO pages * are all allocated by bootmem. */ if (bootmem) { zone = page_zone(page); zone_span_writelock(zone); zone->present_pages += nr_pages; zone_span_writeunlock(zone); totalram_pages += nr_pages; } } static void __meminit free_pte_table(pte_t *pte_start, pmd_t *pmd) { pte_t *pte; int i; for (i = 0; i < PTRS_PER_PTE; i++) { pte = pte_start + i; if (pte_val(*pte)) return; } /* free a pte talbe */ free_pagetable(pmd_page(*pmd), 0); spin_lock(&init_mm.page_table_lock); pmd_clear(pmd); spin_unlock(&init_mm.page_table_lock); } static void __meminit free_pmd_table(pmd_t *pmd_start, pud_t *pud) { pmd_t *pmd; int i; for (i = 0; i < PTRS_PER_PMD; i++) { pmd = pmd_start + i; if (pmd_val(*pmd)) return; } /* free a pmd talbe */ free_pagetable(pud_page(*pud), 0); spin_lock(&init_mm.page_table_lock); pud_clear(pud); spin_unlock(&init_mm.page_table_lock); } /* Return true if pgd is changed, otherwise return false. */ static bool __meminit free_pud_table(pud_t *pud_start, pgd_t *pgd) { pud_t *pud; int i; for (i = 0; i < PTRS_PER_PUD; i++) { pud = pud_start + i; if (pud_val(*pud)) return false; } /* free a pud table */ free_pagetable(pgd_page(*pgd), 0); spin_lock(&init_mm.page_table_lock); pgd_clear(pgd); spin_unlock(&init_mm.page_table_lock); return true; } static void __meminit remove_pte_table(pte_t *pte_start, unsigned long addr, unsigned long end, bool direct) { unsigned long next, pages = 0; pte_t *pte; void *page_addr; phys_addr_t phys_addr; pte = pte_start + pte_index(addr); for (; addr < end; addr = next, pte++) { next = (addr + PAGE_SIZE) & PAGE_MASK; if (next > end) next = end; if (!pte_present(*pte)) continue; /* * We mapped [0,1G) memory as identity mapping when * initializing, in arch/x86/kernel/head_64.S. These * pagetables cannot be removed. */ phys_addr = pte_val(*pte) + (addr & PAGE_MASK); if (phys_addr < (phys_addr_t)0x40000000) return; if (IS_ALIGNED(addr, PAGE_SIZE) && IS_ALIGNED(next, PAGE_SIZE)) { /* * Do not free direct mapping pages since they were * freed when offlining, or simplely not in use. */ if (!direct) free_pagetable(pte_page(*pte), 0); spin_lock(&init_mm.page_table_lock); pte_clear(&init_mm, addr, pte); spin_unlock(&init_mm.page_table_lock); /* For non-direct mapping, pages means nothing. */ pages++; } else { /* * If we are here, we are freeing vmemmap pages since * direct mapped memory ranges to be freed are aligned. * * If we are not removing the whole page, it means * other page structs in this page are being used and * we canot remove them. So fill the unused page_structs * with 0xFD, and remove the page when it is wholly * filled with 0xFD. */ memset((void *)addr, PAGE_INUSE, next - addr); page_addr = page_address(pte_page(*pte)); if (!memchr_inv(page_addr, PAGE_INUSE, PAGE_SIZE)) { free_pagetable(pte_page(*pte), 0); spin_lock(&init_mm.page_table_lock); pte_clear(&init_mm, addr, pte); spin_unlock(&init_mm.page_table_lock); } } } /* Call free_pte_table() in remove_pmd_table(). */ flush_tlb_all(); if (direct) update_page_count(PG_LEVEL_4K, -pages); } static void __meminit remove_pmd_table(pmd_t *pmd_start, unsigned long addr, unsigned long end, bool direct) { unsigned long next, pages = 0; pte_t *pte_base; pmd_t *pmd; void *page_addr; pmd = pmd_start + pmd_index(addr); for (; addr < end; addr = next, pmd++) { next = pmd_addr_end(addr, end); if (!pmd_present(*pmd)) continue; if (pmd_large(*pmd)) { if (IS_ALIGNED(addr, PMD_SIZE) && IS_ALIGNED(next, PMD_SIZE)) { if (!direct) free_pagetable(pmd_page(*pmd), get_order(PMD_SIZE)); spin_lock(&init_mm.page_table_lock); pmd_clear(pmd); spin_unlock(&init_mm.page_table_lock); pages++; } else { /* If here, we are freeing vmemmap pages. */ memset((void *)addr, PAGE_INUSE, next - addr); page_addr = page_address(pmd_page(*pmd)); if (!memchr_inv(page_addr, PAGE_INUSE, PMD_SIZE)) { free_pagetable(pmd_page(*pmd), get_order(PMD_SIZE)); spin_lock(&init_mm.page_table_lock); pmd_clear(pmd); spin_unlock(&init_mm.page_table_lock); } } continue; } pte_base = (pte_t *)pmd_page_vaddr(*pmd); remove_pte_table(pte_base, addr, next, direct); free_pte_table(pte_base, pmd); } /* Call free_pmd_table() in remove_pud_table(). */ if (direct) update_page_count(PG_LEVEL_2M, -pages); } static void __meminit remove_pud_table(pud_t *pud_start, unsigned long addr, unsigned long end, bool direct) { unsigned long next, pages = 0; pmd_t *pmd_base; pud_t *pud; void *page_addr; pud = pud_start + pud_index(addr); for (; addr < end; addr = next, pud++) { next = pud_addr_end(addr, end); if (!pud_present(*pud)) continue; if (pud_large(*pud)) { if (IS_ALIGNED(addr, PUD_SIZE) && IS_ALIGNED(next, PUD_SIZE)) { if (!direct) free_pagetable(pud_page(*pud), get_order(PUD_SIZE)); spin_lock(&init_mm.page_table_lock); pud_clear(pud); spin_unlock(&init_mm.page_table_lock); pages++; } else { /* If here, we are freeing vmemmap pages. */ memset((void *)addr, PAGE_INUSE, next - addr); page_addr = page_address(pud_page(*pud)); if (!memchr_inv(page_addr, PAGE_INUSE, PUD_SIZE)) { free_pagetable(pud_page(*pud), get_order(PUD_SIZE)); spin_lock(&init_mm.page_table_lock); pud_clear(pud); spin_unlock(&init_mm.page_table_lock); } } continue; } pmd_base = (pmd_t *)pud_page_vaddr(*pud); remove_pmd_table(pmd_base, addr, next, direct); free_pmd_table(pmd_base, pud); } if (direct) update_page_count(PG_LEVEL_1G, -pages); } /* start and end are both virtual address. */ static void __meminit remove_pagetable(unsigned long start, unsigned long end, bool direct) { unsigned long next; pgd_t *pgd; pud_t *pud; bool pgd_changed = false; for (; start < end; start = next) { next = pgd_addr_end(start, end); pgd = pgd_offset_k(start); if (!pgd_present(*pgd)) continue; pud = (pud_t *)pgd_page_vaddr(*pgd); remove_pud_table(pud, start, next, direct); if (free_pud_table(pud, pgd)) pgd_changed = true; } if (pgd_changed) sync_global_pgds(start, end - 1); flush_tlb_all(); } void __ref vmemmap_free(unsigned long start, unsigned long end) { remove_pagetable(start, end, false); } #ifdef CONFIG_MEMORY_HOTREMOVE static void __meminit kernel_physical_mapping_remove(unsigned long start, unsigned long end) { start = (unsigned long)__va(start); end = (unsigned long)__va(end); remove_pagetable(start, end, true); } int __ref arch_remove_memory(u64 start, u64 size) { unsigned long start_pfn = start >> PAGE_SHIFT; unsigned long nr_pages = size >> PAGE_SHIFT; struct zone *zone; int ret; zone = page_zone(pfn_to_page(start_pfn)); kernel_physical_mapping_remove(start, start + size); ret = __remove_pages(zone, start_pfn, nr_pages); WARN_ON_ONCE(ret); return ret; } #endif #endif /* CONFIG_MEMORY_HOTPLUG */ static struct kcore_list kcore_vsyscall; static void __init register_page_bootmem_info(void) { #ifdef CONFIG_NUMA int i; for_each_online_node(i) register_page_bootmem_info_node(NODE_DATA(i)); #endif } void __init mem_init(void) { long codesize, reservedpages, datasize, initsize; unsigned long absent_pages; pci_iommu_alloc(); /* clear_bss() already clear the empty_zero_page */ register_page_bootmem_info(); /* this will put all memory onto the freelists */ totalram_pages = free_all_bootmem(); absent_pages = absent_pages_in_range(0, max_pfn); reservedpages = max_pfn - totalram_pages - absent_pages; after_bootmem = 1; codesize = (unsigned long) &_etext - (unsigned long) &_text; datasize = (unsigned long) &_edata - (unsigned long) &_etext; initsize = (unsigned long) &__init_end - (unsigned long) &__init_begin; /* Register memory areas for /proc/kcore */ kclist_add(&kcore_vsyscall, (void *)VSYSCALL_START, VSYSCALL_END - VSYSCALL_START, KCORE_OTHER); printk(KERN_INFO "Memory: %luk/%luk available (%ldk kernel code, " "%ldk absent, %ldk reserved, %ldk data, %ldk init)\n", nr_free_pages() << (PAGE_SHIFT-10), max_pfn << (PAGE_SHIFT-10), codesize >> 10, absent_pages << (PAGE_SHIFT-10), reservedpages << (PAGE_SHIFT-10), datasize >> 10, initsize >> 10); } #ifdef CONFIG_DEBUG_RODATA const int rodata_test_data = 0xC3; EXPORT_SYMBOL_GPL(rodata_test_data); int kernel_set_to_readonly; void set_kernel_text_rw(void) { unsigned long start = PFN_ALIGN(_text); unsigned long end = PFN_ALIGN(__stop___ex_table); if (!kernel_set_to_readonly) return; pr_debug("Set kernel text: %lx - %lx for read write\n", start, end); /* * Make the kernel identity mapping for text RW. Kernel text * mapping will always be RO. Refer to the comment in * static_protections() in pageattr.c */ set_memory_rw(start, (end - start) >> PAGE_SHIFT); } void set_kernel_text_ro(void) { unsigned long start = PFN_ALIGN(_text); unsigned long end = PFN_ALIGN(__stop___ex_table); if (!kernel_set_to_readonly) return; pr_debug("Set kernel text: %lx - %lx for read only\n", start, end); /* * Set the kernel identity mapping for text RO. */ set_memory_ro(start, (end - start) >> PAGE_SHIFT); } void mark_rodata_ro(void) { unsigned long start = PFN_ALIGN(_text); unsigned long rodata_start = PFN_ALIGN(__start_rodata); unsigned long end = (unsigned long) &__end_rodata_hpage_align; unsigned long text_end = PFN_ALIGN(&__stop___ex_table); unsigned long rodata_end = PFN_ALIGN(&__end_rodata); unsigned long all_end; printk(KERN_INFO "Write protecting the kernel read-only data: %luk\n", (end - start) >> 10); set_memory_ro(start, (end - start) >> PAGE_SHIFT); kernel_set_to_readonly = 1; /* * The rodata/data/bss/brk section (but not the kernel text!) * should also be not-executable. * * We align all_end to PMD_SIZE because the existing mapping * is a full PMD. If we would align _brk_end to PAGE_SIZE we * split the PMD and the reminder between _brk_end and the end * of the PMD will remain mapped executable. * * Any PMD which was setup after the one which covers _brk_end * has been zapped already via cleanup_highmem(). */ all_end = roundup((unsigned long)_brk_end, PMD_SIZE); set_memory_nx(text_end, (all_end - text_end) >> PAGE_SHIFT); rodata_test(); #ifdef CONFIG_CPA_DEBUG printk(KERN_INFO "Testing CPA: undo %lx-%lx\n", start, end); set_memory_rw(start, (end-start) >> PAGE_SHIFT); printk(KERN_INFO "Testing CPA: again\n"); set_memory_ro(start, (end-start) >> PAGE_SHIFT); #endif free_init_pages("unused kernel memory", (unsigned long) __va(__pa_symbol(text_end)), (unsigned long) __va(__pa_symbol(rodata_start))); free_init_pages("unused kernel memory", (unsigned long) __va(__pa_symbol(rodata_end)), (unsigned long) __va(__pa_symbol(_sdata))); } #endif int kern_addr_valid(unsigned long addr) { unsigned long above = ((long)addr) >> __VIRTUAL_MASK_SHIFT; pgd_t *pgd; pud_t *pud; pmd_t *pmd; pte_t *pte; if (above != 0 && above != -1UL) return 0; pgd = pgd_offset_k(addr); if (pgd_none(*pgd)) return 0; pud = pud_offset(pgd, addr); if (pud_none(*pud)) return 0; if (pud_large(*pud)) return pfn_valid(pud_pfn(*pud)); pmd = pmd_offset(pud, addr); if (pmd_none(*pmd)) return 0; if (pmd_large(*pmd)) return pfn_valid(pmd_pfn(*pmd)); pte = pte_offset_kernel(pmd, addr); if (pte_none(*pte)) return 0; return pfn_valid(pte_pfn(*pte)); } /* * A pseudo VMA to allow ptrace access for the vsyscall page. This only * covers the 64bit vsyscall page now. 32bit has a real VMA now and does * not need special handling anymore: */ static struct vm_area_struct gate_vma = { .vm_start = VSYSCALL_START, .vm_end = VSYSCALL_START + (VSYSCALL_MAPPED_PAGES * PAGE_SIZE), .vm_page_prot = PAGE_READONLY_EXEC, .vm_flags = VM_READ | VM_EXEC }; struct vm_area_struct *get_gate_vma(struct mm_struct *mm) { #ifdef CONFIG_IA32_EMULATION if (!mm || mm->context.ia32_compat) return NULL; #endif return &gate_vma; } int in_gate_area(struct mm_struct *mm, unsigned long addr) { struct vm_area_struct *vma = get_gate_vma(mm); if (!vma) return 0; return (addr >= vma->vm_start) && (addr < vma->vm_end); } /* * Use this when you have no reliable mm, typically from interrupt * context. It is less reliable than using a task's mm and may give * false positives. */ int in_gate_area_no_mm(unsigned long addr) { return (addr >= VSYSCALL_START) && (addr < VSYSCALL_END); } const char *arch_vma_name(struct vm_area_struct *vma) { if (vma->vm_mm && vma->vm_start == (long)vma->vm_mm->context.vdso) return "[vdso]"; if (vma == &gate_vma) return "[vsyscall]"; return NULL; } #ifdef CONFIG_X86_UV unsigned long memory_block_size_bytes(void) { if (is_uv_system()) { printk(KERN_INFO "UV: memory block size 2GB\n"); return 2UL * 1024 * 1024 * 1024; } return MIN_MEMORY_BLOCK_SIZE; } #endif #ifdef CONFIG_SPARSEMEM_VMEMMAP /* * Initialise the sparsemem vmemmap using huge-pages at the PMD level. */ static long __meminitdata addr_start, addr_end; static void __meminitdata *p_start, *p_end; static int __meminitdata node_start; static int __meminit vmemmap_populate_hugepages(unsigned long start, unsigned long end, int node) { unsigned long addr; unsigned long next; pgd_t *pgd; pud_t *pud; pmd_t *pmd; for (addr = start; addr < end; addr = next) { next = pmd_addr_end(addr, end); pgd = vmemmap_pgd_populate(addr, node); if (!pgd) return -ENOMEM; pud = vmemmap_pud_populate(pgd, addr, node); if (!pud) return -ENOMEM; pmd = pmd_offset(pud, addr); if (pmd_none(*pmd)) { void *p; p = vmemmap_alloc_block_buf(PMD_SIZE, node); if (p) { pte_t entry; entry = pfn_pte(__pa(p) >> PAGE_SHIFT, PAGE_KERNEL_LARGE); set_pmd(pmd, __pmd(pte_val(entry))); /* check to see if we have contiguous blocks */ if (p_end != p || node_start != node) { if (p_start) printk(KERN_DEBUG " [%lx-%lx] PMD -> [%p-%p] on node %d\n", addr_start, addr_end-1, p_start, p_end-1, node_start); addr_start = addr; node_start = node; p_start = p; } addr_end = addr + PMD_SIZE; p_end = p + PMD_SIZE; continue; } } else if (pmd_large(*pmd)) { vmemmap_verify((pte_t *)pmd, node, addr, next); continue; } pr_warn_once("vmemmap: falling back to regular page backing\n"); if (vmemmap_populate_basepages(addr, next, node)) return -ENOMEM; } return 0; } int __meminit vmemmap_populate(unsigned long start, unsigned long end, int node) { int err; if (cpu_has_pse) err = vmemmap_populate_hugepages(start, end, node); else err = vmemmap_populate_basepages(start, end, node); if (!err) sync_global_pgds(start, end - 1); return err; } #if defined(CONFIG_MEMORY_HOTPLUG_SPARSE) && defined(CONFIG_HAVE_BOOTMEM_INFO_NODE) void register_page_bootmem_memmap(unsigned long section_nr, struct page *start_page, unsigned long size) { unsigned long addr = (unsigned long)start_page; unsigned long end = (unsigned long)(start_page + size); unsigned long next; pgd_t *pgd; pud_t *pud; pmd_t *pmd; unsigned int nr_pages; struct page *page; for (; addr < end; addr = next) { pte_t *pte = NULL; pgd = pgd_offset_k(addr); if (pgd_none(*pgd)) { next = (addr + PAGE_SIZE) & PAGE_MASK; continue; } get_page_bootmem(section_nr, pgd_page(*pgd), MIX_SECTION_INFO); pud = pud_offset(pgd, addr); if (pud_none(*pud)) { next = (addr + PAGE_SIZE) & PAGE_MASK; continue; } get_page_bootmem(section_nr, pud_page(*pud), MIX_SECTION_INFO); if (!cpu_has_pse) { next = (addr + PAGE_SIZE) & PAGE_MASK; pmd = pmd_offset(pud, addr); if (pmd_none(*pmd)) continue; get_page_bootmem(section_nr, pmd_page(*pmd), MIX_SECTION_INFO); pte = pte_offset_kernel(pmd, addr); if (pte_none(*pte)) continue; get_page_bootmem(section_nr, pte_page(*pte), SECTION_INFO); } else { next = pmd_addr_end(addr, end); pmd = pmd_offset(pud, addr); if (pmd_none(*pmd)) continue; nr_pages = 1 << (get_order(PMD_SIZE)); page = pmd_page(*pmd); while (nr_pages--) get_page_bootmem(section_nr, page++, SECTION_INFO); } } } #endif void __meminit vmemmap_populate_print_last(void) { if (p_start) { printk(KERN_DEBUG " [%lx-%lx] PMD -> [%p-%p] on node %d\n", addr_start, addr_end-1, p_start, p_end-1, node_start); p_start = NULL; p_end = NULL; node_start = 0; } } #endif
98afece13bdb91c67cb9d776ee57454b043e1bd3
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/video/adf/adf_fbdev.c
a5b53bc08c3f6da7bda90dda1ebd724407b623bd
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
18,822
c
adf_fbdev.c
/* * Copyright (C) 2013 Google, Inc. * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ #include <linux/vmalloc.h> #include <video/adf.h> #include <video/adf_client.h> #include <video/adf_fbdev.h> #include <video/adf_format.h> #include "adf.h" struct adf_fbdev_format { u32 fourcc; u32 bpp; u32 r_length; u32 g_length; u32 b_length; u32 a_length; u32 r_offset; u32 g_offset; u32 b_offset; u32 a_offset; }; static const struct adf_fbdev_format format_table[] = { {DRM_FORMAT_RGB332, 8, 3, 3, 2, 0, 5, 2, 0, 0}, {DRM_FORMAT_BGR233, 8, 3, 3, 2, 0, 0, 3, 5, 0}, {DRM_FORMAT_XRGB4444, 16, 4, 4, 4, 0, 8, 4, 0, 0}, {DRM_FORMAT_XBGR4444, 16, 4, 4, 4, 0, 0, 4, 8, 0}, {DRM_FORMAT_RGBX4444, 16, 4, 4, 4, 0, 12, 8, 4, 0}, {DRM_FORMAT_BGRX4444, 16, 4, 4, 4, 0, 0, 4, 8, 0}, {DRM_FORMAT_ARGB4444, 16, 4, 4, 4, 4, 8, 4, 0, 12}, {DRM_FORMAT_ABGR4444, 16, 4, 4, 4, 4, 0, 4, 8, 12}, {DRM_FORMAT_RGBA4444, 16, 4, 4, 4, 4, 12, 8, 4, 0}, {DRM_FORMAT_BGRA4444, 16, 4, 4, 4, 4, 0, 4, 8, 0}, {DRM_FORMAT_XRGB1555, 16, 5, 5, 5, 0, 10, 5, 0, 0}, {DRM_FORMAT_XBGR1555, 16, 5, 5, 5, 0, 0, 5, 10, 0}, {DRM_FORMAT_RGBX5551, 16, 5, 5, 5, 0, 11, 6, 1, 0}, {DRM_FORMAT_BGRX5551, 16, 5, 5, 5, 0, 1, 6, 11, 0}, {DRM_FORMAT_ARGB1555, 16, 5, 5, 5, 1, 10, 5, 0, 15}, {DRM_FORMAT_ABGR1555, 16, 5, 5, 5, 1, 0, 5, 10, 15}, {DRM_FORMAT_RGBA5551, 16, 5, 5, 5, 1, 11, 6, 1, 0}, {DRM_FORMAT_BGRA5551, 16, 5, 5, 5, 1, 1, 6, 11, 0}, {DRM_FORMAT_RGB565, 16, 5, 6, 5, 0, 11, 5, 0, 0}, {DRM_FORMAT_BGR565, 16, 5, 6, 5, 0, 0, 5, 11, 0}, {DRM_FORMAT_RGB888, 24, 8, 8, 8, 0, 16, 8, 0, 0}, {DRM_FORMAT_BGR888, 24, 8, 8, 8, 0, 0, 8, 16, 0}, {DRM_FORMAT_XRGB8888, 32, 8, 8, 8, 0, 16, 8, 0, 0}, {DRM_FORMAT_XBGR8888, 32, 8, 8, 8, 0, 0, 8, 16, 0}, {DRM_FORMAT_RGBX8888, 32, 8, 8, 8, 0, 24, 16, 8, 0}, {DRM_FORMAT_BGRX8888, 32, 8, 8, 8, 0, 8, 16, 24, 0}, {DRM_FORMAT_ARGB8888, 32, 8, 8, 8, 8, 16, 8, 0, 24}, {DRM_FORMAT_ABGR8888, 32, 8, 8, 8, 8, 0, 8, 16, 24}, {DRM_FORMAT_RGBA8888, 32, 8, 8, 8, 8, 24, 16, 8, 0}, {DRM_FORMAT_BGRA8888, 32, 8, 8, 8, 8, 8, 16, 24, 0}, {DRM_FORMAT_XRGB2101010, 32, 10, 10, 10, 0, 20, 10, 0, 0}, {DRM_FORMAT_XBGR2101010, 32, 10, 10, 10, 0, 0, 10, 20, 0}, {DRM_FORMAT_RGBX1010102, 32, 10, 10, 10, 0, 22, 12, 2, 0}, {DRM_FORMAT_BGRX1010102, 32, 10, 10, 10, 0, 2, 12, 22, 0}, {DRM_FORMAT_ARGB2101010, 32, 10, 10, 10, 2, 20, 10, 0, 30}, {DRM_FORMAT_ABGR2101010, 32, 10, 10, 10, 2, 0, 10, 20, 30}, {DRM_FORMAT_RGBA1010102, 32, 10, 10, 10, 2, 22, 12, 2, 0}, {DRM_FORMAT_BGRA1010102, 32, 10, 10, 10, 2, 2, 12, 22, 0}, }; static u32 drm_fourcc_from_fb_var(struct fb_var_screeninfo *var) { size_t i; for (i = 0; i < ARRAY_SIZE(format_table); i++) { const struct adf_fbdev_format *f = &format_table[i]; if (var->red.length == f->r_length && var->red.offset == f->r_offset && var->green.length == f->g_length && var->green.offset == f->g_offset && var->blue.length == f->b_length && var->blue.offset == f->b_offset && var->transp.length == f->a_length && (var->transp.length == 0 || var->transp.offset == f->a_offset)) return f->fourcc; } return 0; } static const struct adf_fbdev_format *fbdev_format_info(u32 format) { size_t i; for (i = 0; i < ARRAY_SIZE(format_table); i++) { const struct adf_fbdev_format *f = &format_table[i]; if (f->fourcc == format) return f; } BUG(); } void adf_modeinfo_to_fb_videomode(const struct drm_mode_modeinfo *mode, struct fb_videomode *vmode) { memset(vmode, 0, sizeof(*vmode)); vmode->refresh = mode->vrefresh; vmode->xres = mode->hdisplay; vmode->yres = mode->vdisplay; vmode->pixclock = mode->clock ? KHZ2PICOS(mode->clock) : 0; vmode->left_margin = mode->htotal - mode->hsync_end; vmode->right_margin = mode->hsync_start - mode->hdisplay; vmode->upper_margin = mode->vtotal - mode->vsync_end; vmode->lower_margin = mode->vsync_start - mode->vdisplay; vmode->hsync_len = mode->hsync_end - mode->hsync_start; vmode->vsync_len = mode->vsync_end - mode->vsync_start; vmode->sync = 0; if (mode->flags & DRM_MODE_FLAG_PHSYNC) vmode->sync |= FB_SYNC_HOR_HIGH_ACT; if (mode->flags & DRM_MODE_FLAG_PVSYNC) vmode->sync |= FB_SYNC_VERT_HIGH_ACT; if (mode->flags & DRM_MODE_FLAG_PCSYNC) vmode->sync |= FB_SYNC_COMP_HIGH_ACT; if (mode->flags & DRM_MODE_FLAG_BCAST) vmode->sync |= FB_SYNC_BROADCAST; vmode->vmode = 0; if (mode->flags & DRM_MODE_FLAG_INTERLACE) vmode->vmode |= FB_VMODE_INTERLACED; if (mode->flags & DRM_MODE_FLAG_DBLSCAN) vmode->vmode |= FB_VMODE_DOUBLE; } EXPORT_SYMBOL(adf_modeinfo_to_fb_videomode); void adf_modeinfo_from_fb_videomode(const struct fb_videomode *vmode, struct drm_mode_modeinfo *mode) { memset(mode, 0, sizeof(*mode)); mode->hdisplay = vmode->xres; mode->hsync_start = mode->hdisplay + vmode->right_margin; mode->hsync_end = mode->hsync_start + vmode->hsync_len; mode->htotal = mode->hsync_end + vmode->left_margin; mode->vdisplay = vmode->yres; mode->vsync_start = mode->vdisplay + vmode->lower_margin; mode->vsync_end = mode->vsync_start + vmode->vsync_len; mode->vtotal = mode->vsync_end + vmode->upper_margin; mode->clock = vmode->pixclock ? PICOS2KHZ(vmode->pixclock) : 0; mode->flags = 0; if (vmode->sync & FB_SYNC_HOR_HIGH_ACT) mode->flags |= DRM_MODE_FLAG_PHSYNC; if (vmode->sync & FB_SYNC_VERT_HIGH_ACT) mode->flags |= DRM_MODE_FLAG_PVSYNC; if (vmode->sync & FB_SYNC_COMP_HIGH_ACT) mode->flags |= DRM_MODE_FLAG_PCSYNC; if (vmode->sync & FB_SYNC_BROADCAST) mode->flags |= DRM_MODE_FLAG_BCAST; if (vmode->vmode & FB_VMODE_INTERLACED) mode->flags |= DRM_MODE_FLAG_INTERLACE; if (vmode->vmode & FB_VMODE_DOUBLE) mode->flags |= DRM_MODE_FLAG_DBLSCAN; if (vmode->refresh) mode->vrefresh = vmode->refresh; else adf_modeinfo_set_vrefresh(mode); if (vmode->name) strlcpy(mode->name, vmode->name, sizeof(mode->name)); else adf_modeinfo_set_name(mode); } EXPORT_SYMBOL(adf_modeinfo_from_fb_videomode); static int adf_fbdev_post(struct adf_fbdev *fbdev) { struct adf_buffer buf; struct sync_fence *complete_fence; int ret = 0; memset(&buf, 0, sizeof(buf)); buf.overlay_engine = fbdev->eng; buf.w = fbdev->info->var.xres; buf.h = fbdev->info->var.yres; buf.format = fbdev->format; buf.dma_bufs[0] = fbdev->dma_buf; buf.offset[0] = fbdev->offset + fbdev->info->var.yoffset * fbdev->pitch + fbdev->info->var.xoffset * (fbdev->info->var.bits_per_pixel / 8); buf.pitch[0] = fbdev->pitch; buf.n_planes = 1; complete_fence = adf_interface_simple_post(fbdev->intf, &buf); if (IS_ERR(complete_fence)) { ret = PTR_ERR(complete_fence); goto done; } sync_fence_put(complete_fence); done: return ret; } static const u16 vga_palette[][3] = { {0x0000, 0x0000, 0x0000}, {0x0000, 0x0000, 0xAAAA}, {0x0000, 0xAAAA, 0x0000}, {0x0000, 0xAAAA, 0xAAAA}, {0xAAAA, 0x0000, 0x0000}, {0xAAAA, 0x0000, 0xAAAA}, {0xAAAA, 0x5555, 0x0000}, {0xAAAA, 0xAAAA, 0xAAAA}, {0x5555, 0x5555, 0x5555}, {0x5555, 0x5555, 0xFFFF}, {0x5555, 0xFFFF, 0x5555}, {0x5555, 0xFFFF, 0xFFFF}, {0xFFFF, 0x5555, 0x5555}, {0xFFFF, 0x5555, 0xFFFF}, {0xFFFF, 0xFFFF, 0x5555}, {0xFFFF, 0xFFFF, 0xFFFF}, }; static int adf_fb_alloc(struct adf_fbdev *fbdev) { int ret; ret = adf_interface_simple_buffer_alloc(fbdev->intf, fbdev->default_xres_virtual, fbdev->default_yres_virtual, fbdev->default_format, &fbdev->dma_buf, &fbdev->offset, &fbdev->pitch); if (ret < 0) { dev_err(fbdev->info->dev, "allocating fb failed: %d\n", ret); return ret; } fbdev->vaddr = dma_buf_vmap(fbdev->dma_buf); if (!fbdev->vaddr) { ret = -ENOMEM; dev_err(fbdev->info->dev, "vmapping fb failed\n"); goto err_vmap; } fbdev->info->fix.line_length = fbdev->pitch; fbdev->info->var.xres_virtual = fbdev->default_xres_virtual; fbdev->info->var.yres_virtual = fbdev->default_yres_virtual; fbdev->info->fix.smem_len = fbdev->dma_buf->size; fbdev->info->screen_base = fbdev->vaddr; return 0; err_vmap: dma_buf_put(fbdev->dma_buf); return ret; } static void adf_fb_destroy(struct adf_fbdev *fbdev) { dma_buf_vunmap(fbdev->dma_buf, fbdev->vaddr); dma_buf_put(fbdev->dma_buf); } static void adf_fbdev_set_format(struct adf_fbdev *fbdev, u32 format) { size_t i; const struct adf_fbdev_format *info = fbdev_format_info(format); for (i = 0; i < ARRAY_SIZE(vga_palette); i++) { u16 r = vga_palette[i][0]; u16 g = vga_palette[i][1]; u16 b = vga_palette[i][2]; r >>= (16 - info->r_length); g >>= (16 - info->g_length); b >>= (16 - info->b_length); fbdev->pseudo_palette[i] = (r << info->r_offset) | (g << info->g_offset) | (b << info->b_offset); if (info->a_length) { u16 a = BIT(info->a_length) - 1; fbdev->pseudo_palette[i] |= (a << info->a_offset); } } fbdev->info->var.bits_per_pixel = adf_format_bpp(format); fbdev->info->var.red.length = info->r_length; fbdev->info->var.red.offset = info->r_offset; fbdev->info->var.green.length = info->g_length; fbdev->info->var.green.offset = info->g_offset; fbdev->info->var.blue.length = info->b_length; fbdev->info->var.blue.offset = info->b_offset; fbdev->info->var.transp.length = info->a_length; fbdev->info->var.transp.offset = info->a_offset; fbdev->format = format; } static void adf_fbdev_fill_modelist(struct adf_fbdev *fbdev) { struct drm_mode_modeinfo *modelist; struct fb_videomode fbmode; size_t n_modes, i; int ret = 0; n_modes = adf_interface_modelist(fbdev->intf, NULL, 0); modelist = kzalloc(sizeof(modelist[0]) * n_modes, GFP_KERNEL); if (!modelist) { dev_warn(fbdev->info->dev, "allocating new modelist failed; keeping old modelist\n"); return; } adf_interface_modelist(fbdev->intf, modelist, n_modes); fb_destroy_modelist(&fbdev->info->modelist); for (i = 0; i < n_modes; i++) { adf_modeinfo_to_fb_videomode(&modelist[i], &fbmode); ret = fb_add_videomode(&fbmode, &fbdev->info->modelist); if (ret < 0) dev_warn(fbdev->info->dev, "adding mode %s to modelist failed: %d\n", modelist[i].name, ret); } kfree(modelist); } /** * adf_fbdev_open - default implementation of fbdev open op */ int adf_fbdev_open(struct fb_info *info, int user) { struct adf_fbdev *fbdev = info->par; int ret; mutex_lock(&fbdev->refcount_lock); if (unlikely(fbdev->refcount == UINT_MAX)) { ret = -EMFILE; goto done; } if (!fbdev->refcount) { struct drm_mode_modeinfo mode; struct fb_videomode fbmode; struct adf_device *dev = adf_interface_parent(fbdev->intf); ret = adf_device_attach(dev, fbdev->eng, fbdev->intf); if (ret < 0 && ret != -EALREADY) goto done; ret = adf_fb_alloc(fbdev); if (ret < 0) goto done; adf_interface_current_mode(fbdev->intf, &mode); adf_modeinfo_to_fb_videomode(&mode, &fbmode); fb_videomode_to_var(&fbdev->info->var, &fbmode); adf_fbdev_set_format(fbdev, fbdev->default_format); adf_fbdev_fill_modelist(fbdev); } ret = adf_fbdev_post(fbdev); if (ret < 0) { if (!fbdev->refcount) adf_fb_destroy(fbdev); goto done; } fbdev->refcount++; done: mutex_unlock(&fbdev->refcount_lock); return ret; } EXPORT_SYMBOL(adf_fbdev_open); /** * adf_fbdev_release - default implementation of fbdev release op */ int adf_fbdev_release(struct fb_info *info, int user) { struct adf_fbdev *fbdev = info->par; mutex_lock(&fbdev->refcount_lock); BUG_ON(!fbdev->refcount); fbdev->refcount--; if (!fbdev->refcount) adf_fb_destroy(fbdev); mutex_unlock(&fbdev->refcount_lock); return 0; } EXPORT_SYMBOL(adf_fbdev_release); /** * adf_fbdev_check_var - default implementation of fbdev check_var op */ int adf_fbdev_check_var(struct fb_var_screeninfo *var, struct fb_info *info) { struct adf_fbdev *fbdev = info->par; bool valid_format = true; u32 format = drm_fourcc_from_fb_var(var); u32 pitch = var->xres_virtual * var->bits_per_pixel / 8; if (!format) { dev_dbg(info->dev, "%s: unrecognized format\n", __func__); valid_format = false; } if (valid_format && var->grayscale) { dev_dbg(info->dev, "%s: grayscale modes not supported\n", __func__); valid_format = false; } if (valid_format && var->nonstd) { dev_dbg(info->dev, "%s: nonstandard formats not supported\n", __func__); valid_format = false; } if (valid_format && !adf_overlay_engine_supports_format(fbdev->eng, format)) { char format_str[ADF_FORMAT_STR_SIZE]; adf_format_str(format, format_str); dev_dbg(info->dev, "%s: format %s not supported by overlay engine %s\n", __func__, format_str, fbdev->eng->base.name); valid_format = false; } if (valid_format && pitch > fbdev->pitch) { dev_dbg(info->dev, "%s: fb pitch too small for var (pitch = %u, xres_virtual = %u, bits_per_pixel = %u)\n", __func__, fbdev->pitch, var->xres_virtual, var->bits_per_pixel); valid_format = false; } if (valid_format && var->yres_virtual > fbdev->default_yres_virtual) { dev_dbg(info->dev, "%s: fb height too small for var (h = %u, yres_virtual = %u)\n", __func__, fbdev->default_yres_virtual, var->yres_virtual); valid_format = false; } if (valid_format) { var->activate = info->var.activate; var->height = info->var.height; var->width = info->var.width; var->accel_flags = info->var.accel_flags; var->rotate = info->var.rotate; var->colorspace = info->var.colorspace; /* userspace can't change these */ } else { /* if any part of the format is invalid then fixing it up is impractical, so save just the modesetting bits and overwrite everything else */ struct fb_videomode mode; fb_var_to_videomode(&mode, var); memcpy(var, &info->var, sizeof(*var)); fb_videomode_to_var(var, &mode); } return 0; } EXPORT_SYMBOL(adf_fbdev_check_var); /** * adf_fbdev_set_par - default implementation of fbdev set_par op */ int adf_fbdev_set_par(struct fb_info *info) { struct adf_fbdev *fbdev = info->par; struct adf_interface *intf = fbdev->intf; struct fb_videomode vmode; struct drm_mode_modeinfo mode; int ret; u32 format = drm_fourcc_from_fb_var(&info->var); fb_var_to_videomode(&vmode, &info->var); adf_modeinfo_from_fb_videomode(&vmode, &mode); ret = adf_interface_set_mode(intf, &mode); if (ret < 0) return ret; ret = adf_fbdev_post(fbdev); if (ret < 0) return ret; if (format != fbdev->format) adf_fbdev_set_format(fbdev, format); return 0; } EXPORT_SYMBOL(adf_fbdev_set_par); /** * adf_fbdev_blank - default implementation of fbdev blank op */ int adf_fbdev_blank(int blank, struct fb_info *info) { struct adf_fbdev *fbdev = info->par; struct adf_interface *intf = fbdev->intf; u8 dpms_state; switch (blank) { case FB_BLANK_UNBLANK: dpms_state = DRM_MODE_DPMS_ON; break; case FB_BLANK_NORMAL: dpms_state = DRM_MODE_DPMS_STANDBY; break; case FB_BLANK_VSYNC_SUSPEND: dpms_state = DRM_MODE_DPMS_SUSPEND; break; case FB_BLANK_HSYNC_SUSPEND: dpms_state = DRM_MODE_DPMS_STANDBY; break; case FB_BLANK_POWERDOWN: dpms_state = DRM_MODE_DPMS_OFF; break; default: return -EINVAL; } return adf_interface_blank(intf, dpms_state); } EXPORT_SYMBOL(adf_fbdev_blank); /** * adf_fbdev_pan_display - default implementation of fbdev pan_display op */ int adf_fbdev_pan_display(struct fb_var_screeninfo *var, struct fb_info *info) { struct adf_fbdev *fbdev = info->par; return adf_fbdev_post(fbdev); } EXPORT_SYMBOL(adf_fbdev_pan_display); /** * adf_fbdev_mmap - default implementation of fbdev mmap op */ int adf_fbdev_mmap(struct fb_info *info, struct vm_area_struct *vma) { struct adf_fbdev *fbdev = info->par; vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); return dma_buf_mmap(fbdev->dma_buf, vma, 0); } EXPORT_SYMBOL(adf_fbdev_mmap); /** * adf_fbdev_init - initialize helper to wrap ADF device in fbdev API * * @fbdev: the fbdev helper * @interface: the ADF interface that will display the framebuffer * @eng: the ADF overlay engine that will scan out the framebuffer * @xres_virtual: the virtual width of the framebuffer * @yres_virtual: the virtual height of the framebuffer * @format: the format of the framebuffer * @fbops: the device's fbdev ops * @fmt: formatting for the framebuffer identification string * @...: variable arguments * * @format must be a standard, non-indexed RGB format, i.e., * adf_format_is_rgb(@format) && @format != @DRM_FORMAT_C8. * * Returns 0 on success or -errno on failure. */ int adf_fbdev_init(struct adf_fbdev *fbdev, struct adf_interface *interface, struct adf_overlay_engine *eng, u16 xres_virtual, u16 yres_virtual, u32 format, struct fb_ops *fbops, const char *fmt, ...) { struct adf_device *parent = adf_interface_parent(interface); struct device *dev = &parent->base.dev; u16 width_mm, height_mm; va_list args; int ret; if (!adf_format_is_rgb(format) || format == DRM_FORMAT_C8) { dev_err(dev, "fbdev helper does not support format %u\n", format); return -EINVAL; } memset(fbdev, 0, sizeof(*fbdev)); fbdev->intf = interface; fbdev->eng = eng; fbdev->info = framebuffer_alloc(0, dev); if (!fbdev->info) { dev_err(dev, "allocating framebuffer device failed\n"); return -ENOMEM; } mutex_init(&fbdev->refcount_lock); fbdev->default_xres_virtual = xres_virtual; fbdev->default_yres_virtual = yres_virtual; fbdev->default_format = format; fbdev->info->flags = FBINFO_FLAG_DEFAULT; ret = adf_interface_get_screen_size(interface, &width_mm, &height_mm); if (ret < 0) { width_mm = 0; height_mm = 0; } fbdev->info->var.width = width_mm; fbdev->info->var.height = height_mm; fbdev->info->var.activate = FB_ACTIVATE_VBL; va_start(args, fmt); vsnprintf(fbdev->info->fix.id, sizeof(fbdev->info->fix.id), fmt, args); va_end(args); fbdev->info->fix.type = FB_TYPE_PACKED_PIXELS; fbdev->info->fix.visual = FB_VISUAL_TRUECOLOR; fbdev->info->fix.xpanstep = 1; fbdev->info->fix.ypanstep = 1; INIT_LIST_HEAD(&fbdev->info->modelist); fbdev->info->fbops = fbops; fbdev->info->pseudo_palette = fbdev->pseudo_palette; fbdev->info->par = fbdev; ret = register_framebuffer(fbdev->info); if (ret < 0) { dev_err(dev, "registering framebuffer failed: %d\n", ret); return ret; } return 0; } EXPORT_SYMBOL(adf_fbdev_init); /** * adf_fbdev_destroy - destroy helper to wrap ADF device in fbdev API * * @fbdev: the fbdev helper */ void adf_fbdev_destroy(struct adf_fbdev *fbdev) { unregister_framebuffer(fbdev->info); BUG_ON(fbdev->refcount); mutex_destroy(&fbdev->refcount_lock); framebuffer_release(fbdev->info); } EXPORT_SYMBOL(adf_fbdev_destroy);
40ec05e14cfa36f4663d1beaeb8ab23054c266c7
342aebb0c15817f742a3cb357d61aebe12365bfd
/c99/test_main.c
0d5a0de02fd90e2053109a7d8036006d87bba125
[ "MIT" ]
permissive
emilybache/GildedRose-Refactoring-Kata
0eab21daf96a9e393f76b0d5d1d443755f5d6a37
6a91a10bfaff6c70c3ddb63245ee1cb447844a67
refs/heads/main
2023-09-01T03:03:54.909793
2023-08-29T09:36:23
2023-08-29T09:36:23
10,599,951
3,108
5,051
MIT
2023-09-08T07:35:13
2013-06-10T12:43:34
C++
UTF-8
C
false
false
526
c
test_main.c
#include <stdio.h> #include <stdlib.h> #include <check.h> Suite *suite_rose(void); int main(int argc, char **argv) { Suite *s; SRunner *runner; int number_fails; int forkme = 1; if (argc > 1 && strcmp(argv[1], "--nofork") == 0) { forkme = 0; } s = suite_rose(); runner = srunner_create(s); if (0 == forkme) { srunner_set_fork_status(runner, CK_NOFORK); } srunner_run_all(runner, CK_NORMAL); number_fails = srunner_ntests_failed(runner); srunner_free(runner); return number_fails; }
c0c45ba6a6d39b0deeabb9e72afd3fea1b4b53af
d9c343e0c7824b827f23c41b2c603b5eb59d3f4b
/SM3/Windows/SM3/src/sm3test.c
be5ba1d73177c7ae3234c65c10014161ec65812b
[]
no_license
NEWPLAN/SMx
d4a609687aa7338f96426470def4abf9527e6144
703ba41e52d73a0a496c0d0df06aa686299e98ea
refs/heads/master
2023-02-22T04:06:11.522348
2023-02-11T14:24:19
2023-02-11T14:24:19
91,858,424
377
188
null
2019-09-17T08:22:55
2017-05-20T01:57:38
C
UTF-8
C
false
false
1,092
c
sm3test.c
/************************************************************************* > File Name: sm3test.c > Author:NEWPLAN > E-mail:newplan001@163.com > Created Time: Thu Apr 13 23:55:50 2017 ************************************************************************/ #include <string.h> #include <stdio.h> #include "sm3.h" int main( int argc, char *argv[] ) { unsigned char *input = "abc"; int ilen = 3; unsigned char output[32]; int i; sm3_context ctx; printf("Message:\n"); printf("%s\n", input); sm3(input, ilen, output); printf("Hash:\n "); for (i = 0; i < 32; i++) { printf("%02x", output[i]); if (((i + 1) % 4 ) == 0) printf(" "); } printf("\n"); printf("Message:\n"); for (i = 0; i < 16; i++) printf("abcd"); printf("\n"); sm3_starts( &ctx ); for (i = 0; i < 16; i++) sm3_update( &ctx, "abcd", 4 ); sm3_finish( &ctx, output ); memset( &ctx, 0, sizeof( sm3_context ) ); printf("Hash:\n "); for (i = 0; i < 32; i++) { printf("%02x", output[i]); if (((i + 1) % 4 ) == 0) printf(" "); } printf("\n"); //getch(); //VS2008 }
da89af54bf0da57efa1cd701e7cb3f9510dd63ba
5c72e3dec37038e313beab6250acaa54b4b03b93
/vioinput/sys/HidTablet.c
f29313c4e28f55be208b8a6c946ef68cf06398b7
[ "BSD-3-Clause", "GPL-1.0-or-later" ]
permissive
virtio-win/kvm-guest-drivers-windows
eb29c92b6949d6bfb0ee8c70004e359180ee2398
19a79901f36aa552b85f8b4c3c9645ebe90d9ec5
refs/heads/master
2023-09-06T00:50:32.529282
2023-08-25T10:21:53
2023-08-31T07:30:16
2,524,933
1,424
294
BSD-3-Clause
2023-08-26T16:02:39
2011-10-06T09:06:41
C
UTF-8
C
false
false
35,703
c
HidTablet.c
/* * Tablet specific HID functionality * * Copyright (c) 2016-2017 Red Hat, Inc. * * Author(s): * Ladi Prosek <lprosek@redhat.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met : * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and / or other materials provided with the distribution. * 3. Neither the names of the copyright holders nor the names of their 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 HOLDERS 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 "precomp.h" #include "vioinput.h" #include "Hid.h" #if defined(EVENT_TRACING) #include "HidTablet.tmh" #endif // Defined in drivers/hid/hid-multitouch.c #define MT_DEFAULT_MAXCONTACT 10 #define MT_MAX_MAXCONTACT 250 #pragma pack(push,1) typedef struct _tagInputClassTabletSlot { UCHAR uFlags; USHORT uContactID; USHORT uAxisX; USHORT uAxisY; USHORT uTouchWidth; USHORT uTouchHeight; } INPUT_CLASS_TABLET_SLOT, * PINPUT_CLASS_TABLET_SLOT; typedef struct _tagInputClassTabletFeatureMaxContact { UCHAR uReportID; UCHAR uMaxContacts; }INPUT_CLASS_TABLET_FEATURE_MAX_CONTACT, * PINPUT_CLASS_TABLET_FEATURE_MAX_CONTACT; #pragma pack(pop) typedef struct _tagInputClassTabletTrackingID { LONG uID; BOOLEAN bPendingDel; } INPUT_CLASS_TABLET_TRACKING_ID, * PINPUT_CLASS_TABLET_TRACKING_ID; typedef struct _tagInputClassTablet { INPUT_CLASS_COMMON Common; BOOLEAN bMT; BOOLEAN bIdentifiableMT; BOOLEAN bMscTs; ULONG uMaxContacts; ULONG uLastMTSlot; PINPUT_CLASS_TABLET_SLOT pContactStat; PINPUT_CLASS_TABLET_TRACKING_ID pTrackingID; /* * HID Tablet report layout: * Total size in bytes: 1 + 11 * numContacts + 1 + 4 * +-----------------+-+-+-+-+-+---------------+----------+------------+ * | Byte Offset |7|6|5|4|3| 2 | 1 | 0 | * +-----------------+-+-+-+-+-+---------------+----------+------------+ * | 0 | Report ID | * | i*11+1 | Pad | Barrel Switch | In-range | Tip Switch | * | i*11+[2,3] | Contact ID | * | i*11+[4,5] | x-axis | * | i*11+[6,7] | y-axis | * | i*11+[8,9] | touch width | * | i*11+[10,11] | touch height | * | (i+1)*11+[1,11] | Contact i+1 | * | (i+2)*11+[1,11] | Contact i+2 | * | ... | | * | (n-1)*11+[1,11] | Contact n-1 | * | n*11+1 | Contact Count | * | n*11+[2,5] | Scan Time | * +-----------------+-+-+-+-+-+------------+----------+---------------+ */ } INPUT_CLASS_TABLET, *PINPUT_CLASS_TABLET; static NTSTATUS HIDTabletGetFeature( PINPUT_CLASS_COMMON pClass, PHID_XFER_PACKET pFeaturePkt) { PINPUT_CLASS_TABLET pTabletDesc = (PINPUT_CLASS_TABLET)pClass; UCHAR uReportID = *(PUCHAR)pFeaturePkt->reportBuffer; NTSTATUS status = STATUS_SUCCESS; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); switch (uReportID) { case REPORTID_FEATURE_TABLET_MAX_COUNT: if (pFeaturePkt->reportBufferLen >= sizeof(INPUT_CLASS_TABLET_FEATURE_MAX_CONTACT)) { PINPUT_CLASS_TABLET_FEATURE_MAX_CONTACT pFtrReport = (PINPUT_CLASS_TABLET_FEATURE_MAX_CONTACT)pFeaturePkt->reportBuffer; pFtrReport->uMaxContacts = (UCHAR)pTabletDesc->uMaxContacts; } else { status = STATUS_BUFFER_TOO_SMALL; } break; default: status = STATUS_INVALID_PARAMETER; break; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return status; } static NTSTATUS HIDTabletEventToCollect( PINPUT_CLASS_COMMON pClass, PVIRTIO_INPUT_EVENT pEvent) { PINPUT_CLASS_TABLET pTabletDesc = (PINPUT_CLASS_TABLET)pClass; PUCHAR pReport = pClass->pHidReport; PINPUT_CLASS_TABLET_SLOT pReportSlot; ULONG uNumContacts; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); switch (pEvent->type) { case EV_SYN: switch (pEvent->code) { case SYN_REPORT: /* * For identifiable MT, bDirty isn't set when handling MT events but * only states are saved. First touching contact may lift first * thus the first valid contact may not always 1st in pContactStat. * So check and find the actual contacts to report, copy to final * report buffer and set bDirty. * Anonymous MT already sets bDirty when seeing SYN_MT_REPORT. */ if (pTabletDesc->bIdentifiableMT) { UCHAR uContacts = 0; pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts] = uContacts; for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { if (pTabletDesc->pTrackingID[uNumContacts].uID != -1) { RtlCopyMemory( &((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[uContacts++], &pTabletDesc->pContactStat[uNumContacts], sizeof(INPUT_CLASS_TABLET_SLOT)); } } if (uContacts) { pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts] = uContacts; pClass->bDirty = TRUE; } } break; default: break; } break; default: break; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return STATUS_SUCCESS; } static NTSTATUS HIDTabletEventToReport( PINPUT_CLASS_COMMON pClass, PVIRTIO_INPUT_EVENT pEvent) { PINPUT_CLASS_TABLET pTabletDesc = (PINPUT_CLASS_TABLET)pClass; PUCHAR pReport = pClass->pHidReport; PUSHORT pAxisReport; PINPUT_CLASS_TABLET_SLOT pReportSlot; UCHAR uBits; ULONG uNumContacts; TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "--> %s\n", __FUNCTION__); pReport[HID_REPORT_ID_OFFSET] = pClass->uReportID; switch (pEvent->type) { case EV_ABS: // MT if (pTabletDesc->bMT) { /* * For identifiable MT, contact events are firstly saved into * pContactStat then copied to report buffer by valid tracking ID. * For anonymous MT, contact event are directly saved into report * buffer one by one on seeing SYN_MT_REPORT. */ if (pTabletDesc->bIdentifiableMT) { pReportSlot = &pTabletDesc->pContactStat[pTabletDesc->uLastMTSlot]; } else { pReportSlot = &((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[pTabletDesc->uLastMTSlot]; } switch (pEvent->code) { case ABS_MT_SLOT: /* * Subsequent identifiable MT event will re-use last set MT_SLOT * until new slot arrives so we need save it for later usage * and keep using uLastMTSlot as current slot for other operation. * Only identifiable MT will send MT_SLOT. Still add protection * in case back-end somehow goes wrong. */ if (pTabletDesc->bIdentifiableMT) { if (pEvent->value < pTabletDesc->uMaxContacts) { pTabletDesc->uLastMTSlot = (ULONG)pEvent->value; } else { pTabletDesc->uLastMTSlot = 0; } } break; case ABS_MT_TOUCH_MAJOR: pReportSlot->uTouchWidth = (USHORT)pEvent->value; break; case ABS_MT_TOUCH_MINOR: pReportSlot->uTouchHeight = (USHORT)pEvent->value; break; case ABS_MT_POSITION_X: case ABS_MT_POSITION_Y: { USHORT* pPos = (pEvent->code == ABS_MT_POSITION_X ? &pReportSlot->uAxisX : &pReportSlot->uAxisY); *pPos = (USHORT)pEvent->value; /* * For anonymous MT, contact ID for each contact is * fixed at initializing the report memory. Seeing * a position update indicates the contact down. * Slot index will be increased on SYN_MT_REPORT. * However receiving less position update can only * indicate some contact up, but don't know which. * That's why it's called anonymous MT. Thus clear * the uFlags after each report done on SYN_REPORT * so that can restart the check from new round. */ if (pTabletDesc->bMT && !pTabletDesc->bIdentifiableMT) { pReportSlot->uFlags |= 0x01; } } break; case ABS_MT_TRACKING_ID: /* * Check if negative tracking ID for actual contact up & down. * Contact ID is bind to slot until changed, save it to operate * subsequent MT event. In case of negative tracking ID, don't * mark as unused slot with -1 but mark as pending only so that * the contact can be reported lift up on EN_SYN and unset then. */ if ((LONG)pEvent->value < 0) { pTabletDesc->pTrackingID[pTabletDesc->uLastMTSlot].bPendingDel = TRUE; pReportSlot->uFlags &= ~0x01; } else { pTabletDesc->pTrackingID[pTabletDesc->uLastMTSlot].uID = (LONG)pEvent->value; pReportSlot->uContactID = (USHORT)pEvent->value; pReportSlot->uFlags |= 0x01; } break; default: break; } } else // ST { /* * ST always fills ABS_X/ABS_Y and EV_KEY in 1st slot while * uLastMTSlot remains unchanged for all events. */ pReportSlot = &((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[pTabletDesc->uLastMTSlot]; switch (pEvent->code) { case ABS_X: case ABS_Y: { USHORT* pPos = (pEvent->code == ABS_X ? &pReportSlot->uAxisX : &pReportSlot->uAxisY); *pPos = (USHORT)pEvent->value; pClass->bDirty = TRUE; } break; default: break; } } break; case EV_KEY: switch (pEvent->code) { case BTN_LEFT: case BTN_TOUCH: // tip switch + in range uBits = 0x03; break; case BTN_RIGHT: case BTN_STYLUS: // barrel switch uBits = 0x04; break; default: uBits = 0x00; break; } // MT will set bDirty before reporting at EV_SYN so drop all bits here. if (pTabletDesc->bMT) { uBits = 0x00; } if (uBits) { pReportSlot = &((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[pTabletDesc->uLastMTSlot]; if (pEvent->value) { pReportSlot->uFlags |= uBits; } else { pReportSlot->uFlags &= ~uBits; } pClass->bDirty = TRUE; } break; case EV_MSC: switch (pEvent->code) { case MSC_TIMESTAMP: if (pTabletDesc->bMscTs) { PLONG pScanTime = (PLONG)&pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts + 1]; // Convert MSC_TIMESTAMP microseconds to 100 microseconds *pScanTime = ((ULONG)pEvent->value / 100); } break; default: break; } break; case EV_SYN: switch (pEvent->code) { case SYN_REPORT: /* * Post-processing SYN_REPORT after done reporting. * For ST, the num of contacts to report is always 1 so nothing to do. * For MT, clear the number of contacts to report so that up-to-date * number can be re-count before reporting on next EV_SYN. * For identifiable MT, clear pending tracking ID. * For anonymous MT, reset uLastMTSlot and all contacts state. */ if (pTabletDesc->bIdentifiableMT) { for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { if (pTabletDesc->pTrackingID[uNumContacts].bPendingDel) { pTabletDesc->pTrackingID[uNumContacts].uID = -1; pTabletDesc->pTrackingID[uNumContacts].bPendingDel = FALSE; } } pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts] = 0; } else if (pTabletDesc->bMT) { // Reset to 1st slot so that can restart the check from new round pTabletDesc->uLastMTSlot = 0; /* * Unlike identifiable MT, there is no ABS_MT_TRACKING_ID * to denote a contact up. A contact up can be * identified if receiving less SYN_MT_REPORT before * SYN_REPORT. Mark all contacts as up here and position * update will set correct state. */ for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { ((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[uNumContacts].uFlags &= ~0x01; } } break; case SYN_MT_REPORT: /* * Anonymous MT won't use MT_SLOT/MT_TRACKING_ID for each contacts, * so move to next slot when seeing SYN_MT_REPORT. If case of * overflow, round uLastMTSlot the 1st but keep number of contacts. */ if (pTabletDesc->bMT && !pTabletDesc->bIdentifiableMT) { ++pTabletDesc->uLastMTSlot; if (pTabletDesc->uLastMTSlot <= pTabletDesc->uMaxContacts) { ++pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts]; } if (++pTabletDesc->uLastMTSlot >= pTabletDesc->uMaxContacts) { pTabletDesc->uLastMTSlot = 0; } pClass->bDirty = TRUE; } break; default: break; } break; } TraceEvents(TRACE_LEVEL_VERBOSE, DBG_READ, "<-- %s\n", __FUNCTION__); return STATUS_SUCCESS; } static VOID HIDTabletCleanup( PINPUT_CLASS_COMMON pClass) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); PINPUT_CLASS_TABLET pTabletDesc = (PINPUT_CLASS_TABLET)pClass; if (pTabletDesc->pContactStat) { VIOInputFree(&pTabletDesc->pContactStat); } if (pTabletDesc->pTrackingID) { VIOInputFree(&pTabletDesc->pTrackingID); } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "<-- %s\n", __FUNCTION__); } NTSTATUS HIDTabletProbe( PINPUT_DEVICE pContext, PDYNAMIC_ARRAY pHidDesc, PVIRTIO_INPUT_CFG_DATA pAxes, PVIRTIO_INPUT_CFG_DATA pButtons, PVIRTIO_INPUT_CFG_DATA pMisc) { PINPUT_CLASS_TABLET pTabletDesc = NULL; NTSTATUS status = STATUS_SUCCESS; UCHAR i, uValue; ULONG uAxisCode, uNumOfAbsAxes = 0, uNumOfMTAbsAxes = 0, uNumContacts = 0; BOOLEAN bContactWidth = FALSE, bContactHeight = FALSE; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "--> %s\n", __FUNCTION__); // allocate and initialize pTabletDesc pTabletDesc = VIOInputAlloc(sizeof(INPUT_CLASS_TABLET)); if (pTabletDesc == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } pTabletDesc->bMT = FALSE; pTabletDesc->bIdentifiableMT = FALSE; pTabletDesc->bMscTs = FALSE; pTabletDesc->uMaxContacts = 1; pTabletDesc->uLastMTSlot = 0; // we expect to see two absolute axes, X and Y for (i = 0; i < pAxes->size; i++) { UCHAR uNonAxes = 0; while (DecodeNextBit(&pAxes->u.bitmap[i], &uValue)) { USHORT uAxisCode = uValue + 8 * i; if (uAxisCode == ABS_X || uAxisCode == ABS_Y) { uNumOfAbsAxes++; } else if (uAxisCode == ABS_MT_SLOT) { struct virtio_input_absinfo AbsInfo; GetAbsAxisInfo(pContext, uAxisCode, &AbsInfo); pTabletDesc->uMaxContacts = AbsInfo.max + 1; if (pTabletDesc->uMaxContacts > MT_MAX_MAXCONTACT) { pTabletDesc->uMaxContacts = MT_MAX_MAXCONTACT; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Type B (identifiable contacts) MT back end report more contacts (%d) than front end can support (%d)." " Limit to (%d). Consider to increase MT_MAX_MAXCONTACT if necessary.\n", AbsInfo.max + 1, MT_MAX_MAXCONTACT, MT_MAX_MAXCONTACT); } pTabletDesc->bMT = TRUE; pTabletDesc->bIdentifiableMT = TRUE; } else if ((uAxisCode >= ABS_MT_TOUCH_MAJOR) && (uAxisCode <= ABS_MT_TOOL_Y)) { pTabletDesc->bMT = TRUE; if (uAxisCode == ABS_MT_POSITION_X || uAxisCode == ABS_MT_POSITION_Y) { uNumOfMTAbsAxes++; } if (uAxisCode == ABS_MT_TRACKING_ID) { pTabletDesc->bIdentifiableMT = TRUE; } if (uAxisCode == ABS_MT_TOUCH_MAJOR) { bContactWidth = TRUE; } if (uAxisCode == ABS_MT_TOUCH_MINOR) { bContactHeight = TRUE; } } else { uNonAxes |= (1 << uValue); } } pAxes->u.bitmap[i] = uNonAxes; } if (uNumOfAbsAxes != 2) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Tablet axes not found\n"); status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } for (i = 0; i < pMisc->size; i++) { while (DecodeNextBit(&pMisc->u.bitmap[i], &uValue)) { UCHAR msc_event = uValue + 8 * i; if (msc_event == MSC_TIMESTAMP) { pTabletDesc->bMscTs = TRUE; } } } /* * MT could be type A (anonymous contacts) or type B (identifiable contacts) * For anonymous MT, seeing another SYN_MT_REPORT indicates a new contact * in same report. * For identifiable MT, ABS_MT_SLOT and ABS_MT_TRACKING_ID are used to * identify the contact number and identity. * If we got type A, uMaxContacts can't be parsed from ABS_MT_SLOT thus * limit to MT_DEFAULT_MAXCONTACT. */ if (!pTabletDesc->bIdentifiableMT && pTabletDesc->bMT) { pTabletDesc->uMaxContacts = MT_DEFAULT_MAXCONTACT; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Type A (anonymous contacts) MT maximum contacts is limited to (%d)." " Consider to increase MT_DEFAULT_MAXCONTACT if necessary.\n", MT_DEFAULT_MAXCONTACT); } if (pTabletDesc->bMT && uNumOfMTAbsAxes != 2) { pTabletDesc->bMT = FALSE; pTabletDesc->bIdentifiableMT = FALSE; pTabletDesc->uMaxContacts = 1; TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Got MT abs info but doesn't have ABS_MT_POSITION_X and ABS_MT_POSITION_Y, fall back to ST\n"); } if (pTabletDesc->uMaxContacts > MT_MAX_MAXCONTACT) { TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Backend report more maximum contacts (%d) than frontend can support (%d), limit to (%d)." " Consider to increase MT_MAX_MAXCONTACT if necessary.\n", pTabletDesc->uMaxContacts, MT_MAX_MAXCONTACT, MT_MAX_MAXCONTACT); pTabletDesc->uMaxContacts = MT_MAX_MAXCONTACT; } // Simulate as ST for test //pTabletDesc->bMT = FALSE; //pTabletDesc->bIdentifiableMT = FALSE; //pTabletDesc->uMaxContacts = 1; // Allocate and all contact status for MT if (pTabletDesc->bMT) { pTabletDesc->pContactStat = VIOInputAlloc(sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts); if (pTabletDesc->pContactStat == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } pTabletDesc->pTrackingID = VIOInputAlloc(sizeof(INPUT_CLASS_TABLET_TRACKING_ID) * pTabletDesc->uMaxContacts); if (pTabletDesc->pTrackingID == NULL) { status = STATUS_INSUFFICIENT_RESOURCES; goto Exit; } for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { pTabletDesc->pTrackingID[uNumContacts].uID = -1; pTabletDesc->pTrackingID[uNumContacts].bPendingDel = FALSE; pTabletDesc->pContactStat[uNumContacts].uTouchWidth = 1; pTabletDesc->pContactStat[uNumContacts].uTouchHeight = 1; } } // claim our buttons from the pAxes bitmap for (i = 0; i < pButtons->size; i++) { UCHAR uNonButtons = 0; while (DecodeNextBit(&pAxes->u.bitmap[i], &uValue)) { USHORT uAxisCode = uValue + 8 * i; // a few hard-coded buttons we understand switch (uAxisCode) { case BTN_LEFT: case BTN_RIGHT: case BTN_TOUCH: case BTN_STYLUS: break; default: uNonButtons |= (1 << uValue); } } pAxes->u.bitmap[i] = uNonButtons; } pTabletDesc->Common.GetFeatureFunc = HIDTabletGetFeature; pTabletDesc->Common.EventToCollectFunc = HIDTabletEventToCollect; pTabletDesc->Common.EventToReportFunc = HIDTabletEventToReport; pTabletDesc->Common.CleanupFunc = HIDTabletCleanup; pTabletDesc->Common.uReportID = (UCHAR)(pContext->uNumOfClasses + 1); HIDAppend2(pHidDesc, HID_TAG_USAGE_PAGE, HID_USAGE_PAGE_DIGITIZER); HIDAppend2(pHidDesc, HID_TAG_USAGE, pTabletDesc->bMT ? HID_USAGE_TOUCH_SCREEN : HID_USAGE_DIGITIZER); HIDAppend2(pHidDesc, HID_TAG_COLLECTION, HID_COLLECTION_APPLICATION); HIDAppend2(pHidDesc, HID_TAG_REPORT_ID, pTabletDesc->Common.uReportID); HIDAppend2(pHidDesc, HID_TAG_USAGE, pTabletDesc->bMT ? HID_USAGE_DIGITIZER_FINGER : HID_USAGE_DIGITIZER_STYLUS); for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { struct virtio_input_absinfo AbsInfo = {0}, XAbsInfo = { 0 }, YAbsInfo = { 0 }; // Collection Logical for all contacts for reporting in hybrid mode HIDAppend2(pHidDesc, HID_TAG_COLLECTION, HID_COLLECTION_LOGICAL); // Change to digitizer page for touch HIDAppend2(pHidDesc, HID_TAG_USAGE_PAGE, HID_USAGE_PAGE_DIGITIZER); // Same logical minimum and maximum applied to below flags, 1 bit each, 1 byte total HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MINIMUM, 0x00); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, 0x01); HIDAppend2(pHidDesc, HID_TAG_REPORT_SIZE, 0x01); HIDAppend2(pHidDesc, HID_TAG_REPORT_COUNT, 0x01); // tip switch, one bit HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_TIP_SWITCH); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); // Only simluate finger down/up for MT if (!pTabletDesc->bMT) { // in range flag, one bit HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_IN_RANGE); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); // barrel switch, one bit HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_BARREL_SWITCH); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); } // padding HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, 0x00); HIDAppend2(pHidDesc, HID_TAG_REPORT_COUNT, pTabletDesc->bMT ? 0x07 : 0x05); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE | HID_DATA_FLAG_CONSTANT); // Contact Identifier, 2 bytes HIDAppend2(pHidDesc, HID_TAG_REPORT_SIZE, 0x10); HIDAppend2(pHidDesc, HID_TAG_REPORT_COUNT, 0x01); HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_CONTACT_ID); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, pTabletDesc->uMaxContacts - 1); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); // Change to generic desktop page for coordinates HIDAppend2(pHidDesc, HID_TAG_USAGE_PAGE, HID_USAGE_PAGE_GENERIC); HIDAppend2(pHidDesc, HID_TAG_UNIT_EXPONENT, 0x0E); // 10^(-2) HIDAppend2(pHidDesc, HID_TAG_UNIT, 0x11); // Linear Centimeter // 2 bytes each axis for (uAxisCode = (uNumOfMTAbsAxes ? ABS_MT_POSITION_X : ABS_X); uAxisCode <= (uNumOfMTAbsAxes ? (ULONG)ABS_MT_POSITION_Y : ABS_Y); uAxisCode++) { GetAbsAxisInfo(pContext, uAxisCode, &AbsInfo); TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Got abs axis %d, min %d, max %d\n", uAxisCode, AbsInfo.min, AbsInfo.max); if (uAxisCode == ABS_X || uAxisCode == ABS_MT_POSITION_X) { RtlCopyMemory(&XAbsInfo, &AbsInfo, sizeof(XAbsInfo)); } else { RtlCopyMemory(&YAbsInfo, &AbsInfo, sizeof(YAbsInfo)); } // Device Class Definition for HID 1.11, 6.2.2.7 // Resolution = (Logical Maximum - Logical Minimum) / // ((Physical Maximum - Physical Minimum) * (10 Unit Exponent)) // struct input_absinfo{}.res reports in units/mm, convert to cm here. HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MINIMUM, AbsInfo.min); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, AbsInfo.max); HIDAppend2(pHidDesc, HID_TAG_PHYSICAL_MINIMUM, (AbsInfo.res == 0) ? AbsInfo.min : (AbsInfo.min * 10 / AbsInfo.res)); HIDAppend2(pHidDesc, HID_TAG_PHYSICAL_MAXIMUM, (AbsInfo.res == 0) ? AbsInfo.max : (AbsInfo.max * 10 / AbsInfo.res)); HIDAppend2(pHidDesc, HID_TAG_USAGE, ((uAxisCode == ABS_X || uAxisCode == ABS_MT_POSITION_X) ? HID_USAGE_GENERIC_X : HID_USAGE_GENERIC_Y)); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); } // 2 bytes for contact width/height HIDAppend2(pHidDesc, HID_TAG_USAGE_PAGE, HID_USAGE_PAGE_DIGITIZER); /* * If the MT device report ABS_MT_TOUCH_MAJOR/ABS_MT_TOUCH_MINOR * use its min/max/res. Otherwise, re-use them as reported from X/Y. */ for (uAxisCode = ABS_MT_TOUCH_MAJOR; uAxisCode <= ABS_MT_TOUCH_MINOR; uAxisCode++) { if (uAxisCode == ABS_MT_TOUCH_MAJOR) { HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_CONTACT_WIDTH); if (bContactWidth) { GetAbsAxisInfo(pContext, HID_USAGE_DIGITIZER_CONTACT_WIDTH, &AbsInfo); } else { RtlCopyMemory(&AbsInfo, &XAbsInfo, sizeof(AbsInfo)); } } else { HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_CONTACT_HEIGHT); if (bContactHeight) { GetAbsAxisInfo(pContext, HID_USAGE_DIGITIZER_CONTACT_HEIGHT, &AbsInfo); } else { RtlCopyMemory(&AbsInfo, &YAbsInfo, sizeof(AbsInfo)); } } HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MINIMUM, AbsInfo.min); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, AbsInfo.max); HIDAppend2(pHidDesc, HID_TAG_PHYSICAL_MINIMUM, (AbsInfo.res == 0) ? AbsInfo.min : (AbsInfo.min * 10 / AbsInfo.res)); HIDAppend2(pHidDesc, HID_TAG_PHYSICAL_MAXIMUM, (AbsInfo.res == 0) ? AbsInfo.max : (AbsInfo.max * 10 / AbsInfo.res)); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); } HIDAppend1(pHidDesc, HID_TAG_END_COLLECTION); //HID_COLLECTION_LOGICAL } // Change to digitizer page for contacts information HIDAppend2(pHidDesc, HID_TAG_USAGE_PAGE, HID_USAGE_PAGE_DIGITIZER); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MINIMUM, 0x00); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, pTabletDesc->uMaxContacts); HIDAppend2(pHidDesc, HID_TAG_REPORT_SIZE, 0x08); HIDAppend2(pHidDesc, HID_TAG_REPORT_COUNT, 0x01); HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_CONTACT_COUNT); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); // Scan time, 4 bytes if (pTabletDesc->bMscTs) { HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_SCAN_TIME); HIDAppend2(pHidDesc, HID_TAG_UNIT_EXPONENT, 0x0A); // 10^(-4), 100 us HIDAppend2(pHidDesc, HID_TAG_UNIT, 0x1001); // Time system in unit of s HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, LONG_MAX); HIDAppend2(pHidDesc, HID_TAG_REPORT_SIZE, 0x20); HIDAppend2(pHidDesc, HID_TAG_REPORT_COUNT, 0x01); HIDAppend2(pHidDesc, HID_TAG_INPUT, HID_DATA_FLAG_VARIABLE); // Restore for subsequent item HIDAppend2(pHidDesc, HID_TAG_UNIT_EXPONENT, 0x00); HIDAppend2(pHidDesc, HID_TAG_UNIT, 0x00); HIDAppend2(pHidDesc, HID_TAG_LOGICAL_MAXIMUM, pTabletDesc->uMaxContacts); HIDAppend2(pHidDesc, HID_TAG_REPORT_SIZE, 0x08); HIDAppend2(pHidDesc, HID_TAG_REPORT_COUNT, 0x01); } // IOCTL_HID_GET_FEATURE will query the report for maximum count HIDAppend2(pHidDesc, HID_TAG_REPORT_ID, REPORTID_FEATURE_TABLET_MAX_COUNT); HIDAppend2(pHidDesc, HID_TAG_USAGE, HID_USAGE_DIGITIZER_CONTACT_COUNT_MAX); HIDAppend2(pHidDesc, HID_TAG_FEATURE, HID_DATA_FLAG_VARIABLE | HID_DATA_FLAG_CONSTANT); HIDAppend1(pHidDesc, HID_TAG_END_COLLECTION); //HID_COLLECTION_APPLICATION TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "Created HID tablet report descriptor\n"); // calculate the tablet HID report size pTabletDesc->Common.cbHidReportSize = 1 + // report ID sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts + // max contacts * per-contact packet. See INPUT_CLASS_TABLET_SLOT and INPUT_CLASS_TABLET for layout details. 1 + // Actual contact count (pTabletDesc->bMscTs ? sizeof(LONG) : 0) // Scan time ; // register the tablet class status = RegisterClass(pContext, &pTabletDesc->Common); if (NT_SUCCESS(status)) { PUCHAR pReport = pTabletDesc->Common.pHidReport; /* * For ST, the number of contacts to report is always 1. * For anonymous MT, the number of contats to report is always the max contacts. * For identifiable MT, the number of contacts to report is counted at SYN_REPORT. */ if (pTabletDesc->bIdentifiableMT) { pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts] = 0; } else if (pTabletDesc->bMT) { pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts] = (UCHAR)pTabletDesc->uMaxContacts; // Assign a different contact ID for anonymous MT for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { ((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[uNumContacts].uContactID = (USHORT)(uNumContacts + 1); } } else { ((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[0].uContactID = 1; pReport[HID_REPORT_DATA_OFFSET + sizeof(INPUT_CLASS_TABLET_SLOT) * pTabletDesc->uMaxContacts] = 1; } for (uNumContacts = 0; uNumContacts < pTabletDesc->uMaxContacts; uNumContacts++) { ((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[uNumContacts].uTouchWidth = 1; ((PINPUT_CLASS_TABLET_SLOT)&pReport[HID_REPORT_DATA_OFFSET])[uNumContacts].uTouchHeight = 1; } } Exit: if (!NT_SUCCESS(status) && pTabletDesc) { if (pTabletDesc->pContactStat) { VIOInputFree(&pTabletDesc->pContactStat); } if (pTabletDesc->pTrackingID) { VIOInputFree(&pTabletDesc->pTrackingID); } VIOInputFree(&pTabletDesc); } TraceEvents(TRACE_LEVEL_INFORMATION, DBG_INIT, "<-- %s (%08x)\n", __FUNCTION__, status); return status; }
f4aad752adc3e2aa22750def5b7e3ef369ed6ec2
19a9f2c19bcb81c4a14ba17831d3098de7731fb5
/ncarview/src/lib/libncarg_ras/avsread.c
0cef419bc188d0b7c7cdea6d71898f78395087c8
[ "Apache-2.0" ]
permissive
NCAR/ncl
243c30eaefce642d53373aa583b73df72eb59f22
8a96101fe14d0cf0f5ed66a5e6b1733084bc69df
refs/heads/develop
2023-03-17T07:53:18.883458
2022-05-11T16:01:03
2022-05-11T16:01:03
67,087,395
254
68
NOASSERTION
2022-10-08T07:20:06
2016-09-01T01:34:28
C
UTF-8
C
false
false
2,821
c
avsread.c
/* * $Id: avsread.c,v 1.4 2008-07-27 03:18:45 haley Exp $ */ /************************************************************************ * * * Copyright (C) 2000 * * University Corporation for Atmospheric Research * * All Rights Reserved * * * * The use of this Software is governed by a License Agreement. * * * ************************************************************************/ static read_image_compute(data, filename) AVSfield_char **data; char *filename; { AVSfield_char *input; FILE *pf; int dims[2]; float min_extent[2], max_extent[2]; unsigned int cx, cy; unsigned char header[8]; /* No data file name */ if (!filename) return(1); /* Attempt to open file */ if (!(pf = fopen(filename, "r"))) { AVSmessage(file_version, AVS_Warning, AVSmodule, "read_image_compute", "Ok", "Can't open data file %s", filename); return(0); } /* Free old memory */ if (*data) AVSfield_free(*data); /* Read dimensions */ if (fread(header, sizeof(header), 1, pf) != 1) { AVSmessage(file_version, AVS_Warning, AVSmodule, "read_image_compute", "Ok", "Error reading header from file %s", filename); fclose(pf); return(0); } cx = (header[2] << 8) + header[3]; cy = (header[6] << 8) + header[7]; /* Some old image files on little endian machines might have the */ /* bytes reversed. */ if (cx == 0 && cy == 0) { cx = (header[1] << 8) + header[0]; cy = (header[5] << 8) + header[4]; } /* Set dimensions */ dims[0] = cx; dims[1] = cy; /* Allocate space for image data */ input = (AVSfield_char *)AVSdata_alloc("field 2D 4-vector byte", dims); /* Read data, 4 bytes per pixel. */ if (fread(input->data, 4, (int)(cx*cy), pf) != (int) (cx * cy)) { AVSmessage(file_version, AVS_Warning, AVSmodule, "read_image_compute", "Ok", "Error reading file %s", filename); fclose(pf); AVSfield_free(input); return(0); } /* Close the file */ fclose(pf); /* Set the output pointer */ *data = input; /* set the labels for each component */ AVSfield_set_labels (input, "alpha;red;green;blue", ";"); /* set the extent for the image */ min_extent[0] = 0.0; min_extent[1] = 0.0; max_extent[0] = (float) cx - 1.0; max_extent[1] = (float) cy - 1.0; AVSfield_set_extent (input, min_extent, max_extent); /* Indicate success */ return(1); }
8078b616e1509da188a4d5623a6856e48a81022f
c9bc99866cfab223c777cfb741083be3e9439d81
/module/timer/src/mod_timer.c
f65f27d35d60a1447d133671e2385226220c3326
[ "BSD-3-Clause" ]
permissive
ARM-software/SCP-firmware
4738ca86ce42d82588ddafc2226a1f353ff2c797
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
refs/heads/master
2023-09-01T16:13:36.962036
2023-08-17T13:00:20
2023-08-31T07:43:37
134,399,880
211
165
NOASSERTION
2023-09-13T14:27:10
2018-05-22T10:35:56
C
UTF-8
C
false
false
19,013
c
mod_timer.c
/* * Arm SCP/MCP Software * Copyright (c) 2017-2023, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause * * Description: * Implementation of Timer module */ #include <mod_timer.h> #include <fwk_assert.h> #include <fwk_dlist.h> #include <fwk_id.h> #include <fwk_interrupt.h> #include <fwk_list.h> #include <fwk_log.h> #include <fwk_macros.h> #include <fwk_mm.h> #include <fwk_module.h> #include <fwk_module_idx.h> #include <fwk_status.h> #include <stdbool.h> #include <stdint.h> #include <string.h> /* Timer device context (element) */ struct timer_dev_ctx { /* Pointer to the device's configuration */ const struct mod_timer_dev_config *config; /* Pointer to an API provided by the driver that controls the device */ struct mod_timer_driver_api *driver; /* Identifier of the driver that controls the device */ fwk_id_t driver_dev_id; /* Storage for all alarms */ struct alarm_sub_element_ctx *alarm_pool; /* Queue of active alarms */ struct fwk_dlist alarms_active; }; /* Alarm item context (sub-element) */ struct alarm_sub_element_ctx { /* List node */ struct fwk_dlist_node node; /* Time between starting this alarm and it triggering */ uint32_t microseconds; /* Timestamp of the time this alarm will trigger */ uint64_t timestamp; /* Pointer to the callback function */ void (*callback)(uintptr_t param); /* Parameter of the callback function */ uintptr_t param; /* Flag indicating if this alarm if periodic */ bool periodic; /* Flag indicating if this alarm is in the active queue */ bool activated; /* Flag indicating if this alarm has been bound to */ bool bound; /* Flag indicating if this alarm is started */ bool started; }; /* Table of timer device context structures */ static struct timer_dev_ctx *ctx_table; /* * Forward declarations */ static void timer_isr(uintptr_t ctx_ptr); /* * Internal functions */ static int _time_to_timestamp( struct timer_dev_ctx *ctx, uint32_t microseconds, uint64_t *timestamp) { int status; uint32_t frequency; fwk_assert(ctx != NULL); fwk_assert(timestamp != NULL); status = ctx->driver->get_frequency(ctx->driver_dev_id, &frequency); if (status != FWK_SUCCESS) { return status; } *timestamp = ((uint64_t)frequency * microseconds) / 1000000; return FWK_SUCCESS; } static int _timestamp_from_now( struct timer_dev_ctx *ctx, uint32_t microseconds, uint64_t *timestamp) { int status; uint64_t counter; fwk_assert(ctx != NULL); fwk_assert(timestamp != NULL); status = _time_to_timestamp(ctx, microseconds, timestamp); if (status != FWK_SUCCESS) { return status; } status = ctx->driver->get_counter(ctx->driver_dev_id, &counter); if (status != FWK_SUCCESS) { return status; } *timestamp += counter; return FWK_SUCCESS; } static int _remaining( const struct timer_dev_ctx *ctx, uint64_t timestamp, uint64_t *remaining_ticks) { int status; uint64_t counter; fwk_assert(ctx != NULL); fwk_assert(remaining_ticks != NULL); status = ctx->driver->get_counter(ctx->driver_dev_id, &counter); if (!fwk_expect(status == FWK_SUCCESS)) { return status; } /* If timestamp is in the past, remaining_ticks is set to zero. */ if (timestamp < counter) { *remaining_ticks = 0; } else { *remaining_ticks = timestamp - counter; } return FWK_SUCCESS; } static void _configure_timer_with_next_alarm(struct timer_dev_ctx *ctx) { int status; struct alarm_sub_element_ctx *alarm_head; fwk_assert(ctx != NULL); alarm_head = (struct alarm_sub_element_ctx *)fwk_list_head(&ctx->alarms_active); if (alarm_head != NULL) { /* Configure timer device */ status = ctx->driver->set_timer(ctx->driver_dev_id, alarm_head->timestamp); if (status != FWK_SUCCESS) { FWK_LOG_DEBUG("[Timer] %s @%d", __func__, __LINE__); } status = ctx->driver->enable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { FWK_LOG_DEBUG("[Timer] %s @%d", __func__, __LINE__); } } } static void _insert_alarm_ctx_into_active_queue( struct timer_dev_ctx *ctx, struct alarm_sub_element_ctx *alarm_new) { struct fwk_dlist_node *alarm_node; struct alarm_sub_element_ctx *alarm; fwk_assert(ctx != NULL); fwk_assert(alarm_new != NULL); /* * Search though the active queue to find the correct place to insert the * new alarm item */ alarm_node = fwk_list_head(&ctx->alarms_active); alarm = FWK_LIST_GET(alarm_node, struct alarm_sub_element_ctx, node); while ((alarm_node != NULL) && (alarm_new->timestamp > alarm->timestamp)) { alarm_node = fwk_list_next(&ctx->alarms_active, alarm_node); alarm = FWK_LIST_GET(alarm_node, struct alarm_sub_element_ctx, node); } /* Insert alarm_new just BEFORE the alarm that was found */ fwk_list_insert(&ctx->alarms_active, &(alarm_new->node), alarm_node); alarm_new->activated = true; } /* * Functions fulfilling the timer API */ static int get_frequency(fwk_id_t dev_id, uint32_t *frequency) { struct timer_dev_ctx *ctx; ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; if (frequency == NULL) { return FWK_E_PARAM; } return ctx->driver->get_frequency(ctx->driver_dev_id, frequency); } static int time_to_timestamp(fwk_id_t dev_id, uint32_t microseconds, uint64_t *timestamp) { struct timer_dev_ctx *ctx; if (timestamp == NULL) { return FWK_E_PARAM; } ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; return _time_to_timestamp(ctx, microseconds, timestamp); } static int get_counter(fwk_id_t dev_id, uint64_t *counter) { struct timer_dev_ctx *ctx; ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; if (counter == NULL) { return FWK_E_PARAM; } /* Read counter */ return ctx->driver->get_counter(ctx->driver_dev_id, counter); } static int delay(fwk_id_t dev_id, uint32_t microseconds) { int status; struct timer_dev_ctx *ctx; uint64_t counter, counter_limit; ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; status = _timestamp_from_now(ctx, microseconds, &counter_limit); if (status != FWK_SUCCESS) { return status; } do { status = ctx->driver->get_counter(ctx->driver_dev_id, &counter); if (status != FWK_SUCCESS) { return status; } } while (counter < counter_limit); return FWK_SUCCESS; } static int wait(fwk_id_t dev_id, uint32_t microseconds, bool (*cond)(void*), void *data) { struct timer_dev_ctx *ctx; int status; uint64_t counter, counter_limit; ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; status = _timestamp_from_now(ctx, microseconds, &counter_limit); if (status != FWK_SUCCESS) { return status; } while (true) { if (cond(data)) { return FWK_SUCCESS; } status = ctx->driver->get_counter(ctx->driver_dev_id, &counter); if (status != FWK_SUCCESS) { return FWK_E_DEVICE; } /* * If the time to wait is over, check condition one last time. */ if (counter > counter_limit) { if (cond(data)) { return FWK_SUCCESS; } else { return FWK_E_TIMEOUT; } } } } static int remaining(fwk_id_t dev_id, uint64_t timestamp, uint64_t *remaining_ticks) { struct timer_dev_ctx *ctx; ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; if (remaining_ticks == NULL) { return FWK_E_PARAM; } return _remaining(ctx, timestamp, remaining_ticks); } static int get_next_alarm_remaining(fwk_id_t dev_id, bool *has_alarm, uint64_t *remaining_ticks) { int status, exit_status; const struct timer_dev_ctx *ctx; const struct alarm_sub_element_ctx *alarm_ctx; const struct fwk_dlist_node *alarm_ctx_node; if (has_alarm == NULL) { return FWK_E_PARAM; } if (remaining_ticks == NULL) { return FWK_E_PARAM; } ctx = &ctx_table[fwk_id_get_element_idx(dev_id)]; /* * The timer interrupt is disabled to ensure that the alarm list is not * modified while we are trying to read it below. */ status = ctx->driver->disable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { return FWK_E_DEVICE; } *has_alarm = !fwk_list_is_empty(&ctx->alarms_active); if (*has_alarm) { alarm_ctx_node = fwk_list_head(&ctx->alarms_active); alarm_ctx = FWK_LIST_GET(alarm_ctx_node, struct alarm_sub_element_ctx, node); exit_status = _remaining(ctx, alarm_ctx->timestamp, remaining_ticks); } else { exit_status = FWK_E_PARAM; } status = ctx->driver->enable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { return FWK_E_DEVICE; } return exit_status; } static const struct mod_timer_api timer_api = { .get_frequency = get_frequency, .time_to_timestamp = time_to_timestamp, .get_counter = get_counter, .delay = delay, .wait = wait, .remaining = remaining, .get_next_alarm_remaining = get_next_alarm_remaining, }; /* * Functions fulfilling the alarm API */ static int alarm_stop(fwk_id_t alarm_id) { int status; struct timer_dev_ctx *ctx; struct alarm_sub_element_ctx *alarm; unsigned int interrupt; fwk_assert(fwk_module_is_valid_sub_element_id(alarm_id)); ctx = &ctx_table[fwk_id_get_element_idx(alarm_id)]; status = fwk_interrupt_get_current(&interrupt); switch (status) { case FWK_E_STATE: /* Not within an ISR */ break; case FWK_SUCCESS: /* Within an ISR */ if (interrupt == ctx->config->timer_irq) { /* * The interrupt handler is the interrupt handler for the alarm's * timer */ break; } /* Fall-through */ default: return FWK_E_ACCESS; } alarm = &ctx->alarm_pool[fwk_id_get_sub_element_idx(alarm_id)]; /* Prevent possible data races with the timer interrupt */ status = ctx->driver->disable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { return FWK_E_DEVICE; } if (!alarm->started) { status = ctx->driver->enable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { return FWK_E_DEVICE; } else { return FWK_E_STATE; } } alarm->started = false; if (!alarm->activated) { return FWK_SUCCESS; } /* * If the alarm is stopped while the interrupts are globally disabled, an * interrupt may be pending because the alarm being stopped here has * triggered. If the interrupt is not cleared then when the interrupts are * re-enabled, the timer ISR will be executed but the alarm, cause of the * interrupt, will have disappeared. To avoid that, the timer interrupt is * cleared here. If the interrupt was triggered by another alarm, it will be * re-triggered when the timer interrupt is re-enabled. */ status = fwk_interrupt_clear_pending(ctx->config->timer_irq); if (status != FWK_SUCCESS) { return status; } fwk_list_remove(&ctx->alarms_active, (struct fwk_dlist_node *)alarm); alarm->activated = false; _configure_timer_with_next_alarm(ctx); return FWK_SUCCESS; } static int alarm_start(fwk_id_t alarm_id, unsigned int milliseconds, enum mod_timer_alarm_type type, void (*callback)(uintptr_t param), uintptr_t param) { int status; struct timer_dev_ctx *ctx; struct alarm_sub_element_ctx *alarm; unsigned int interrupt; fwk_assert(fwk_module_is_valid_sub_element_id(alarm_id)); status = fwk_interrupt_get_current(&interrupt); if (status != FWK_E_STATE) { /* * Could not attain call context OR this function is called from an * interrupt handler. */ return FWK_E_ACCESS; } ctx = ctx_table + fwk_id_get_element_idx(alarm_id); alarm = &ctx->alarm_pool[fwk_id_get_sub_element_idx(alarm_id)]; if (alarm->started) { status = alarm_stop(alarm_id); if (status != FWK_SUCCESS) { return status; } } alarm->started = true; /* Cap to ensure value will not overflow when stored as microseconds */ milliseconds = FWK_MIN(milliseconds, UINT32_MAX / 1000); /* Populate alarm item */ alarm->callback = callback; alarm->param = param; alarm->periodic = (type == MOD_TIMER_ALARM_TYPE_PERIODIC ? true : false); alarm->microseconds = milliseconds * 1000; status = _timestamp_from_now(ctx, alarm->microseconds, &alarm->timestamp); if (status != FWK_SUCCESS) { return status; } /* Disable timer interrupts to work with the active queue */ status = ctx->driver->disable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { return FWK_E_DEVICE; } _insert_alarm_ctx_into_active_queue(ctx, alarm); _configure_timer_with_next_alarm(ctx); return FWK_SUCCESS; } static const struct mod_timer_alarm_api alarm_api = { .start = alarm_start, .stop = alarm_stop, }; static void timer_isr(uintptr_t ctx_ptr) { int status; struct alarm_sub_element_ctx *alarm; struct timer_dev_ctx *ctx = (struct timer_dev_ctx *)ctx_ptr; uint64_t timestamp = 0; fwk_assert(ctx != NULL); /* Disable timer interrupts to work with the active queue */ status = ctx->driver->disable(ctx->driver_dev_id); if (status != FWK_SUCCESS) { FWK_LOG_DEBUG("[Timer] %s @%d", __func__, __LINE__); } status = fwk_interrupt_clear_pending(ctx->config->timer_irq); if (status != FWK_SUCCESS) { FWK_LOG_DEBUG("[Timer] %s @%d", __func__, __LINE__); } alarm = (struct alarm_sub_element_ctx *)fwk_list_pop_head(&ctx->alarms_active); if (alarm == NULL) { /* Timer interrupt triggered without any alarm in the active queue */ fwk_unexpected(); return; } alarm->activated = false; /* Execute the callback function */ alarm->callback(alarm->param); if (alarm->periodic && alarm->started) { /* Put this alarm back into the active queue */ status = _time_to_timestamp(ctx, alarm->microseconds, &timestamp); if (status == FWK_SUCCESS) { alarm->timestamp += timestamp; _insert_alarm_ctx_into_active_queue(ctx, alarm); } else { FWK_LOG_ERR( "[Timer] Error: Periodic alarm could not be added " "back into queue."); } } _configure_timer_with_next_alarm(ctx); } /* * Functions fulfilling the framework's module interface */ static int timer_init(fwk_id_t module_id, unsigned int element_count, const void *data) { ctx_table = fwk_mm_calloc(element_count, sizeof(struct timer_dev_ctx)); return FWK_SUCCESS; } static int timer_device_init(fwk_id_t element_id, unsigned int alarm_count, const void *data) { struct timer_dev_ctx *ctx; fwk_assert(data != NULL); ctx = ctx_table + fwk_id_get_element_idx(element_id); ctx->config = data; if (alarm_count > 0) { ctx->alarm_pool = fwk_mm_calloc(alarm_count, sizeof(struct alarm_sub_element_ctx)); } return FWK_SUCCESS; } static int timer_bind(fwk_id_t id, unsigned int round) { int status; struct timer_dev_ctx *ctx; struct mod_timer_driver_api *driver = NULL; unsigned int driver_module_idx; /* Nothing to do after the initial round. */ if (round > 0) { return FWK_SUCCESS; } if (fwk_id_is_type(id, FWK_ID_TYPE_MODULE)) { return FWK_SUCCESS; } ctx = ctx_table + fwk_id_get_element_idx(id); ctx->driver_dev_id = ctx->config->id; /* Bind to the driver API for the current device */ driver_module_idx = fwk_id_get_module_idx(ctx->driver_dev_id); status = fwk_module_bind(ctx->driver_dev_id, FWK_ID_API(driver_module_idx, 0), &driver); if (status != FWK_SUCCESS) { return status; } /* Check that the driver API is completely fulfilled */ if (driver->enable == NULL || driver->disable == NULL || driver->get_counter == NULL || driver->get_frequency == NULL) { return FWK_E_DEVICE; } ctx->driver = driver; return FWK_SUCCESS; } static int timer_process_bind_request(fwk_id_t requester_id, fwk_id_t id, fwk_id_t api_id, const void **api) { struct timer_dev_ctx *ctx; struct alarm_sub_element_ctx *alarm_ctx; if (fwk_id_is_equal(api_id, MOD_TIMER_API_ID_TIMER)) { if (!fwk_module_is_valid_element_id(id)) { fwk_unexpected(); return FWK_E_PARAM; } *api = &timer_api; return FWK_SUCCESS; } /* Alarm API requested */ if (!fwk_module_is_valid_sub_element_id(id)) { fwk_unexpected(); return FWK_E_PARAM; } ctx = ctx_table + fwk_id_get_element_idx(id); alarm_ctx = &ctx->alarm_pool[fwk_id_get_sub_element_idx(id)]; if (alarm_ctx->bound) { fwk_unexpected(); return FWK_E_STATE; } alarm_ctx->bound = true; *api = &alarm_api; return FWK_SUCCESS; } static int timer_start(fwk_id_t id) { int status; struct timer_dev_ctx *ctx; if (!fwk_module_is_valid_element_id(id)) { return FWK_SUCCESS; } ctx = ctx_table + fwk_id_get_element_idx(id); fwk_list_init(&ctx->alarms_active); status = fwk_interrupt_set_isr_param( ctx->config->timer_irq, timer_isr, (uintptr_t)ctx); if (status != FWK_SUCCESS) { return status; } return fwk_interrupt_enable(ctx->config->timer_irq); } /* Module descriptor */ const struct fwk_module module_timer = { .api_count = (unsigned int)MOD_TIMER_API_COUNT, .type = FWK_MODULE_TYPE_HAL, .init = timer_init, .element_init = timer_device_init, .bind = timer_bind, .process_bind_request = timer_process_bind_request, .start = timer_start, };
b9dfb19516cc5d490ee0d0f463eea3c26b3d8d82
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/dev/pci/if_sipreg.h
7124079b545a74d446958ab18f9839ce503d327c
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
35,578
h
if_sipreg.h
/* $NetBSD: if_sipreg.h,v 1.21 2020/03/08 02:44:12 thorpej Exp $ */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. * All rights reserved. * * This code is derived from software contributed to The NetBSD Foundation * by Jason R. Thorpe. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, 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 THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /*- * Copyright (c) 1999 Network Computer, 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. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of Network Computer, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY NETWORK COMPUTER, 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 THE FOUNDATION OR CONTRIBUTORS * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _DEV_PCI_IF_SIPREG_H_ #define _DEV_PCI_IF_SIPREG_H_ /* * Register description for the Silicon Integrated Systems SiS 900, * SiS 7016, National Semiconductor DP83815 10/100, and National * Semiconduction DP83820 10/100/1000 PCI Ethernet controller. * * Written by Jason R. Thorpe for Network Computer, Inc. */ /* * Transmit FIFO size. Used to compute the transmit drain threshold. * * On the SiS 900, the transmit FIFO is arranged as a 512 32-bit memory * array. * * On the DP83820, we have an 8KB transmit FIFO. */ #define DP83820_SIP_TXFIFO_SIZE 8192 #define OTHER_SIP_TXFIFO_SIZE (512 * 4) /* * The SiS900 uses a single descriptor format for both transmit * and receive descriptor chains. * * Note the DP83820 can use 64-bit DMA addresses for link and bufptr. * Note also that the buffer pointer and command/status words are in * the opposite order on the DP83820 to facilitate 64-bit DMA addresses. * * For transmit, buffers need not be aligned. For receive, buffers * must be aligned to 4-byte (8-byte on DP83820) boundaries. */ #define SIP_DESC_LINK 0 /* link to next descriptor */ #define SIP_DESC_CMDSTS 1 /* ccommand/status */ #define SIP_DESC_BUFPTR 2 /* pointer to DMA segment */ #define GSIP_DESC_LINK 0 #define GSIP_DESC_BUFPTR 1 #define GSIP_DESC_CMDSTS 2 #define GSIP_DESC_EXTSTS 3 /* extended status */ #define GSIP64_DESC_LINK_LO 0 #define GSIP64_DESC_LINK_HI 1 #define GSIP64_DESC_BUFPTR_LO 2 #define GSIP64_DESC_BUFPTR_HI 3 #define GSIP64_DESC_CMDSTS 4 #define GSIP64_DESC_EXTSTS 5 #define SIP_NDESC_WORDS 6 struct sip_desc { uint32_t sipd_words[SIP_NDESC_WORDS]; }; /* * CMDSTS bits common to transmit and receive. */ #define CMDSTS_OWN 0x80000000 /* owned by consumer */ #define CMDSTS_MORE 0x40000000 /* more descriptors */ #define CMDSTS_INTR 0x20000000 /* interrupt when ownership changes */ #define CMDSTS_SUPCRC 0x10000000 /* suppress CRC */ #define CMDSTS_OK 0x08000000 /* packet ok */ #define DP83820_CMDSTS_SIZE_MASK 0x0000ffff /* packet size */ #define OTHER_CMDSTS_SIZE_MASK 0x000007ff /* packet size */ #define CMDSTS_SIZE(sc, x) ((x) & sc->sc_bits.b_cmdsts_size_mask) /* * CMDSTS bits for transmit. */ #define CMDSTS_Tx_TXA 0x04000000 /* transmit abort */ #define CMDSTS_Tx_TFU 0x02000000 /* transmit FIFO underrun */ #define CMDSTS_Tx_CRS 0x01000000 /* carrier sense lost */ #define CMDSTS_Tx_TD 0x00800000 /* transmit deferred */ #define CMDSTS_Tx_ED 0x00400000 /* excessive deferral */ #define CMDSTS_Tx_OWC 0x00200000 /* out of window collision */ #define CMDSTS_Tx_EC 0x00100000 /* excessive collisions */ #define CMDSTS_Tx_CCNT 0x000f0000 /* collision count */ #define CMDSTS_COLLISIONS(x) (((x) & CMDSTS_Tx_CCNT) >> 16) /* * CMDSTS bits for receive. */ #define CMDSTS_Rx_RXA 0x04000000 /* receive abort */ #define CMDSTS_Rx_RXO 0x02000000 /* receive overrun */ #define CMDSTS_Rx_DEST 0x01800000 /* destination class */ #define CMDSTS_Rx_LONG 0x00400000 /* packet too long */ #define CMDSTS_Rx_RUNT 0x00200000 /* runt packet */ #define CMDSTS_Rx_ISE 0x00100000 /* invalid symbol error */ #define CMDSTS_Rx_CRCE 0x00080000 /* CRC error */ #define CMDSTS_Rx_FAE 0x00040000 /* frame alignment error */ #define CMDSTS_Rx_LBP 0x00020000 /* loopback packet */ /* #ifdef DP83820 */ #define CMDSTS_Rx_IRL 0x00010000 /* in-range length error */ /* #else */ #define CMDSTS_Rx_COL 0x00010000 /* collision activity */ /* #endif DP83820 */ #define CMDSTS_Rx_DEST_REJ 0x00000000 /* packet rejected */ #define CMDSTS_Rx_DEST_STA 0x00800000 /* matched station address */ #define CMDSTS_Rx_DEST_MUL 0x01000000 /* multicast address */ #define CMDSTS_Rx_DEST_BRD 0x01800000 /* broadcast address */ /* * EXTSTS bits. */ #define EXTSTS_Rx_UDPERR 0x00400000 /* UDP checksum error */ #define EXTSTS_UDPPKT 0x00200000 /* perform UDP checksum */ #define EXTSTS_Rx_TCPERR 0x00100000 /* TCP checksum error */ #define EXTSTS_TCPPKT 0x00080000 /* perform TCP checksum */ #define EXTSTS_Rx_IPERR 0x00040000 /* IP header checksum error */ #define EXTSTS_IPPKT 0x00020000 /* perform IP header checksum */ #define EXTSTS_VPKT 0x00010000 /* insert VLAN tag */ #define EXTSTS_VTCI 0x0000ffff /* VLAN tag control information */ /* * PCI Configuration space registers. */ #define SIP_PCI_CFGIOA (PCI_MAPREG_START + 0x00) #define SIP_PCI_CFGMA (PCI_MAPREG_START + 0x04) /* DP83820 only */ #define SIP_PCI_CFGMA1 (PCI_MAPREG_START + 0x08) #define SIP_PCI_CFGEROMA 0x30 /* expansion ROM address */ #define SIP_PCI_CFGPMC 0x40 /* power management cap. */ #define SIP_PCI_CFGPMCSR 0x44 /* power management ctl. */ /* * MAC Operation Registers */ #define SIP_CR 0x00 /* command register */ /* DP83820 only */ #define CR_RXPRI3 0x00010000 /* Rx priority queue select */ #define CR_RXPRI2 0x00008000 /* Rx priority queue select */ #define CR_RXPRI1 0x00004000 /* Rx priority queue select */ #define CR_RXPRI0 0x00002000 /* Rx priority queue select */ #define CR_TXPRI3 0x00001000 /* Tx priority queue select */ #define CR_TXPRI2 0x00000800 /* Tx priority queue select */ #define CR_TXPRI1 0x00000400 /* Tx priority queue select */ #define CR_TXPRI0 0x00000200 /* Tx priority queue select */ #define CR_RLD 0x00000400 /* reload from NVRAM */ #define CR_RST 0x00000100 /* software reset */ #define CR_SWI 0x00000080 /* software interrupt */ #define CR_RXR 0x00000020 /* receiver reset */ #define CR_TXR 0x00000010 /* transmit reset */ #define CR_RXD 0x00000008 /* receiver disable */ #define CR_RXE 0x00000004 /* receiver enable */ #define CR_TXD 0x00000002 /* transmit disable */ #define CR_TXE 0x00000001 /* transmit enable */ #define SIP_CFG 0x04 /* configuration register */ #define CFG_LNKSTS 0x80000000 /* link status (83815) */ /* #ifdef DP83820 */ #define CFG_SPEED1000 0x40000000 /* 1000Mb/s input pin */ #define CFG83820_SPEED100 0x20000000 /* 100Mb/s input pin */ #define CFG_DUPSTS 0x10000000 /* full-duplex status */ #define CFG_TBI_EN 0x01000000 /* ten-bit interface enable */ #define CFG_MODE_1000 0x00400000 /* 1000Mb/s mode enable */ #define CFG_PINT_DUP 0x00100000 /* interrupt on PHY DUP change */ #define CFG_PINT_LNK 0x00080000 /* interrupt on PHY LNK change */ #define CFG_PINT_SPD 0x00040000 /* interrupt on PHY SPD change */ #define CFG_TMRTEST 0x00020000 /* timer test mode */ #define CFG_MRM_DIS 0x00010000 /* MRM disable */ #define CFG_MWI_DIS 0x00008000 /* MWI disable */ #define CFG_T64ADDR 0x00004000 /* target 64-bit addressing enable */ #define CFG_PCI64_DET 0x00002000 /* 64-bit PCI bus detected */ #define CFG_DATA64_EN 0x00001000 /* 64-bit data enable */ #define CFG_M64ADDR 0x00000800 /* master 64-bit addressing enable */ /* #else */ #define CFG83815_SPEED100 0x40000000 /* 100Mb/s (83815) */ #define CFG_FDUP 0x20000000 /* full duplex (83815) */ #define CFG_POL 0x10000000 /* 10Mb/s polarity (83815) */ #define CFG_ANEG_DN 0x08000000 /* autonegotiation done (83815) */ #define CFG_PHY_CFG 0x00fc0000 /* PHY configuration (83815) */ #define CFG_PINT_ACEN 0x00020000 /* PHY interrupt auto clear (83815) */ #define CFG_PAUSE_ADV 0x00010000 /* pause advertise (83815) */ #define CFG_ANEG_SEL 0x0000e000 /* autonegotiation select (83815) */ /* #endif DP83820 */ #define CFG_PHY_RST 0x00000400 /* PHY reset (83815) */ #define CFG_PHY_DIS 0x00000200 /* PHY disable (83815) */ /* #ifdef DP83820 */ #define CFG_EXTSTS_EN 0x00000100 /* extended status enable */ /* #else */ #define CFG_EUPHCOMP 0x00000100 /* 83810 descriptor compat (83815) */ /* #endif DP83820 */ #define CFG_EDBMASTEN 0x00002000 /* 635,900B ?? from linux driver */ #define CFG_RNDCNT 0x00000400 /* 635,900B ?? from linux driver */ #define CFG_FAIRBO 0x00000200 /* 635,900B ?? from linux driver */ #define CFG_REQALG 0x00000080 /* PCI bus request alg. */ #define CFG_SB 0x00000040 /* single backoff */ #define CFG_POW 0x00000020 /* program out of window timer */ #define CFG_EXD 0x00000010 /* excessive defferal timer disable */ #define CFG_PESEL 0x00000008 /* parity error detection action */ /* #ifdef DP83820 */ #define CFG_BROM_DIS 0x00000004 /* boot ROM disable */ #define CFG_EXT_125 0x00000002 /* external 125MHz reference select */ /* #endif DP83820 */ #define CFG_BEM 0x00000001 /* big-endian mode */ #define SIP_EROMAR 0x08 /* EEPROM access register */ #define EROMAR_REQ 0x00000400 /* SiS 96x specific */ #define EROMAR_DONE 0x00000200 /* SiS 96x specific */ #define EROMAR_GNT 0x00000100 /* SiS 96x specific */ #define EROMAR_MDC 0x00000040 /* MII clock */ #define EROMAR_MDDIR 0x00000020 /* MII direction (1 == MAC->PHY) */ #define EROMAR_MDIO 0x00000010 /* MII data */ #define EROMAR_EECS 0x00000008 /* chip select */ #define EROMAR_EESK 0x00000004 /* clock */ #define EROMAR_EEDO 0x00000002 /* data out */ #define EROMAR_EEDI 0x00000001 /* data in */ #define SIP_PTSCR 0x0c /* PCI test control register */ #define PTSCR_RBIST_RST 0x00002000 /* SRAM BIST reset */ #define PTSCR_RBIST_EN 0x00000400 /* SRAM BIST enable */ #define PTSCR_RBIST_DONE 0x00000200 /* SRAM BIST done */ #define PTSCR_RBIST_RX1FAIL 0x00000100 /* Rx status FIFO BIST fail */ #define PTSCR_RBIST_RX0FAIL 0x00000080 /* Rx data FIFO BIST fail */ #define PTSCR_RBIST_TX0FAIL 0x00000020 /* Tx data FIFO BIST fail */ #define PTSCR_RBIST_HFFAIL 0x00000010 /* hash filter BIST fail */ #define PTSCR_RBIST_RXFAIL 0x00000008 /* Rx filter BIST failed */ #define PTSCR_EELOAD_EN 0x00000004 /* EEPROM load initiate */ #define PTSCR_EEBIST_EN 0x00000002 /* EEPROM BIST enable */ #define PTSCR_EEBIST_FAIL 0x00000001 /* EEPROM BIST failed */ #define PTSCR_DIS_TEST 0x40000000 /* discard timer test mode */ #define PTSCR_EROM_TACC 0x0f000000 /* boot rom access time */ #define PTSCR_TRRAMADR 0x001ff000 /* TX/RX RAM address */ #define PTSCR_BMTEN 0x00000200 /* bus master test enable */ #define PTSCR_RRTMEN 0x00000080 /* receive RAM test mode enable */ #define PTSCR_TRTMEN 0x00000040 /* transmit RAM test mode enable */ #define PTSCR_SRTMEN 0x00000020 /* status RAM test mode enable */ #define PTSCR_SRAMADR 0x0000001f /* status RAM address */ #define SIP_ISR 0x10 /* interrupt status register */ /* DP83820 only */ #define ISR_TXDESC3 0x40000000 /* Tx queue 3 */ #define ISR_TXDESC2 0x20000000 /* Tx queue 2 */ #define ISR_TXDESC1 0x10000000 /* Tx queue 1 */ #define ISR_TXDESC0 0x08000000 /* Tx queue 0 */ #define ISR_RXDESC3 0x04000000 /* Rx queue 3 */ #define ISR_RXDESC2 0x02000000 /* Rx queue 2 */ #define ISR_RXDESC1 0x01000000 /* Rx queue 1 */ #define ISR_RXDESC0 0x00800000 /* Rx queue 0 */ /* non-DP83820 only */ #define ISR_WAKEEVT 0x10000000 /* wake up event */ #if 0 #ifdef DP83820 #define ISR_TXRCMP 0x00400000 /* transmit reset complete */ #define ISR_RXRCMP 0x00200000 /* receive reset complete */ #define ISR_DPERR 0x00100000 /* detected parity error */ #define ISR_SSERR 0x00080000 /* signalled system error */ #define ISR_RMABT 0x00040000 /* received master abort */ #define ISR_RTABT 0x00020000 /* received target abort */ #else #define ISR_TXRCMP 0x02000000 /* transmit reset complete */ #define ISR_RXRCMP 0x01000000 /* receive reset complete */ #define ISR_DPERR 0x00800000 /* detected parity error */ #define ISR_SSERR 0x00400000 /* signalled system error */ #define ISR_RMABT 0x00200000 /* received master abort */ #define ISR_RTABT 0x00100000 /* received target abort */ #endif /* DP83820 */ #endif /* 0 */ /* SiS 900 only */ #define ISR_PAUSE_END 0x08000000 /* end of transmission pause */ #define ISR_PAUSE_ST 0x04000000 /* start of transmission pause */ #define ISR_RXSOVR 0x00010000 /* Rx status FIFO overrun */ #define ISR_HIBERR 0x00008000 /* high bits error set */ /* DP83820 only */ #define ISR_PHY 0x00004000 /* PHY interrupt */ #define ISR_PME 0x00002000 /* power management event */ #define ISR_SWI 0x00001000 /* software interrupt */ /* DP83820 only */ #define ISR_MIB 0x00000800 /* MIB service */ #define ISR_TXURN 0x00000400 /* Tx underrun */ #define ISR_TXIDLE 0x00000200 /* Tx idle */ #define ISR_TXERR 0x00000100 /* Tx error */ #define ISR_TXDESC 0x00000080 /* Tx descriptor interrupt */ #define ISR_TXOK 0x00000040 /* Tx okay */ #define ISR_RXORN 0x00000020 /* Rx overrun */ #define ISR_RXIDLE 0x00000010 /* Rx idle */ #define ISR_RXEARLY 0x00000008 /* Rx early */ #define ISR_RXERR 0x00000004 /* Rx error */ #define ISR_RXDESC 0x00000002 /* Rx descriptor interrupt */ #define ISR_RXOK 0x00000001 /* Rx okay */ #define SIP_IMR 0x14 /* interrupt mask register */ /* See bits in SIP_ISR */ #define SIP_IER 0x18 /* interrupt enable register */ #define IER_IE 0x00000001 /* master interrupt enable */ /* #ifdef DP83820 */ #define SIP_IHR 0x1c /* interrupt hold-off register */ #define IHR_IHCTL 0x00000100 /* interrupt hold-off control */ #define IHR_IH 0x000000ff /* interrupt hold-off timer (100us) */ /* #else */ #define SIP_ENPHY 0x1c /* enhanced PHY access register */ #define ENPHY_PHYDATA 0xffff0000 /* PHY data */ #define ENPHY_DATA_SHIFT 16 #define ENPHY_PHYADDR 0x0000f800 /* PHY number (7016 only) */ #define ENPHY_PHYADDR_SHIFT 11 #define ENPHY_REGADDR 0x000007c0 /* PHY register */ #define ENPHY_REGADDR_SHIFT 6 #define ENPHY_RWCMD 0x00000020 /* 1 == read, 0 == write */ #define ENPHY_ACCESS 0x00000010 /* PHY access enable */ /* #endif DP83820 */ #define SIP_TXDP 0x20 /* transmit descriptor pointer reg */ /* DP83820 only */ #define SIP_TXDP_HI 0x24 /* transmit descriptor pointer (high) reg */ #define DP83820_SIP_TXCFG 0x28 /* transmit configuration register */ #define OTHER_SIP_TXCFG 0x24 /* transmit configuration register */ #define TXCFG_CSI 0x80000000 /* carrier sense ignore */ #define TXCFG_HBI 0x40000000 /* heartbeat ignore */ #define TXCFG_MLB 0x20000000 /* MAC loopback */ #define TXCFG_ATP 0x10000000 /* automatic transmit padding */ #define TXCFG_MXDMA 0x00700000 /* max DMA burst size */ /* DP83820 only */ #define TXCFG_ECRETRY 0x008000000 /* excessive collision retry enable */ #define TXCFG_BRST_DIS 0x00080000 /* 1000Mb/s burst disable */ /* DP83820 only */ #define TXCFG_MXDMA_1024 0x00000000 /* 1024 bytes */ #if 0 #ifdef DP83820 #define TXCFG_MXDMA_8 0x00100000 /* 8 bytes */ #define TXCFG_MXDMA_16 0x00200000 /* 16 bytes */ #define TXCFG_MXDMA_32 0x00300000 /* 32 bytes */ #define TXCFG_MXDMA_64 0x00400000 /* 64 bytes */ #define TXCFG_MXDMA_128 0x00500000 /* 128 bytes */ #define TXCFG_MXDMA_256 0x00600000 /* 256 bytes */ #define TXCFG_MXDMA_512 0x00700000 /* 512 bytes */ #define TXCFG_FLTH_MASK 0x0000ff00 /* Fx fill threshold */ #define TXCFG_DRTH_MASK 0x000000ff /* Tx drain threshold */ #else #define TXCFG_MXDMA_512 0x00000000 /* 512 bytes */ #define TXCFG_MXDMA_8 0x00200000 /* 8 bytes */ #define TXCFG_MXDMA_16 0x00300000 /* 16 bytes */ #define TXCFG_MXDMA_32 0x00400000 /* 32 bytes */ #define TXCFG_MXDMA_64 0x00500000 /* 64 bytes */ #define TXCFG_MXDMA_128 0x00600000 /* 128 bytes */ #define TXCFG_MXDMA_256 0x00700000 /* 256 bytes */ #define TXCFG_FLTH_MASK 0x00003f00 /* Tx fill threshold */ #define TXCFG_DRTH_MASK 0x0000003f /* Tx drain threshold */ #endif /* DP83820 */ #endif /* 0 */ /* non-DP83820 only */ #define TXCFG_MXDMA_4 0x00100000 /* 4 bytes */ #define SIP_GPIOR 0x2c /* general purpose i/o register */ #define GPIOR_GP5_IN 0x00004000 /* GP 5 in */ #define GPIOR_GP4_IN 0x00002000 /* GP 4 in */ #define GPIOR_GP3_IN 0x00001000 /* GP 3 in */ #define GPIOR_GP2_IN 0x00000800 /* GP 2 in */ #define GPIOR_GP1_IN 0x00000400 /* GP 1 in */ #define GPIOR_GP5_OE 0x00000200 /* GP 5 out enable */ #define GPIOR_GP4_OE 0x00000100 /* GP 4 out enable */ #define GPIOR_GP3_OE 0x00000080 /* GP 3 out enable */ #define GPIOR_GP2_OE 0x00000040 /* GP 2 out enable */ #define GPIOR_GP1_OE 0x00000020 /* GP 1 out enable */ #define GPIOR_GP5_OUT 0x00000010 /* GP 5 out */ #define GPIOR_GP4_OUT 0x00000008 /* GP 4 out */ #define GPIOR_GP3_OUT 0x00000004 /* GP 3 out */ #define GPIOR_GP2_OUT 0x00000002 /* GP 2 out */ #define GPIOR_GP1_OUT 0x00000001 /* GP 1 out */ #define SIP_RXDP 0x30 /* receive descriptor pointer reg */ /* DP83820 only */ #define SIP_RXDP_HI 0x34 /* receive descriptor pointer (high) reg */ #define DP83820_SIP_RXCFG 0x38 /* receive configuration register */ #define OTHER_SIP_RXCFG 0x34 /* receive configuration register */ #define RXCFG_AEP 0x80000000 /* accept error packets */ #define RXCFG_ARP 0x40000000 /* accept runt packets */ /* DP83820 only */ #define RXCFG_STRIPCRC 0x20000000 /* strip CRC */ #define RXCFG_ATX 0x10000000 /* accept transmit packets */ #define RXCFG_ALP 0x08000000 /* accept long packets */ /* DP83820 only */ #define RXCFG_AIRL 0x04000000 /* accept in-range length err packets */ #define RXCFG_MXDMA 0x00700000 /* max DMA burst size */ /* DP83820 only */ #define RXCFG_MXDMA_1024 0x00000000 /* 1024 bytes */ #if 0 #ifdef DP83820 #define RXCFG_MXDMA_8 0x00100000 /* 8 bytes */ #define RXCFG_MXDMA_16 0x00200000 /* 16 bytes */ #define RXCFG_MXDMA_32 0x00300000 /* 32 bytes */ #define RXCFG_MXDMA_64 0x00400000 /* 64 bytes */ #define RXCFG_MXDMA_128 0x00500000 /* 128 bytes */ #define RXCFG_MXDMA_256 0x00600000 /* 256 bytes */ #define RXCFG_MXDMA_512 0x00700000 /* 512 bytes */ #else #define RXCFG_MXDMA_512 0x00000000 /* 512 bytes */ #define RXCFG_MXDMA_8 0x00200000 /* 8 bytes */ #define RXCFG_MXDMA_16 0x00300000 /* 16 bytes */ #define RXCFG_MXDMA_32 0x00400000 /* 32 bytes */ #define RXCFG_MXDMA_64 0x00500000 /* 64 bytes */ #define RXCFG_MXDMA_128 0x00600000 /* 128 bytes */ #define RXCFG_MXDMA_256 0x00700000 /* 256 bytes */ #endif /* DP83820 */ #endif /* 0 */ /* non-DP83820 only */ #define RXCFG_MXDMA_4 0x00100000 /* 4 bytes */ #define RXCFG_DRTH_MASK 0x0000003e /* DP83820 only */ #define SIP_PQCR 0x3c /* priority queueing control register */ #define PQCR_RXPQ_4 0x0000000c /* 4 Rx queues */ #define PQCR_RXPQ_3 0x00000008 /* 3 Rx queues */ #define PQCR_RXPQ_2 0x00000004 /* 2 Rx queues */ #define PQCR_TXFAIR 0x00000002 /* Tx fairness enable */ #define PQCR_TXPQEN 0x00000001 /* Tx priority queueing enable */ /* DP83815 only */ #define SIP83815_NS_CCSR 0x3c /* CLKRUN control/status register (83815) */ #define CCSR_PMESTS 0x00008000 /* PME status */ #define CCSR_PMEEN 0x00000100 /* PME enable */ #define CCSR_CLKRUN_EN 0x00000001 /* clkrun enable */ /* SiS 900 only */ #define SIP_FLOWCTL 0x38 /* flow control register */ #define FLOWCTL_PAUSE 0x00000002 /* PAUSE flag */ #define FLOWCTL_FLOWEN 0x00000001 /* enable flow control */ #define SIP_NS_WCSR 0x40 /* WoL control/status register (83815/83820) */ #define SIP_NS_PCR 0x44 /* pause control/status reg (83815/83820) */ #define PCR_PSEN 0x80000000 /* pause enable */ #define PCR_PS_MCAST 0x40000000 /* pause on multicast */ #define PCR_PS_DA 0x20000000 /* pause on DA */ #define PCR_PS_ACT 0x10000000 /* pause active */ #define PCR_PS_RCVD 0x08000000 /* pause packet received */ /* #ifdef DP83820 */ #define PCR_PS_STHI_8 0x03000000 /* Status FIFO Hi Threshold (8packets) */ #define PCR_PS_STHI_4 0x02000000 /* Status FIFO Hi Threshold (4packets) */ #define PCR_PS_STHI_2 0x01000000 /* Status FIFO Hi Threshold (2packets) */ #define PCR_PS_STHI_0 0x00000000 /* Status FIFO Hi Threshold (disable) */ #define PCR_PS_STLO_8 0x00c00000 /* Status FIFO Lo Threshold (8packets) */ #define PCR_PS_STLO_4 0x00800000 /* Status FIFO Lo Threshold (4packets) */ #define PCR_PS_STLO_2 0x00400000 /* Status FIFO Lo Threshold (2packets) */ #define PCR_PS_STLO_0 0x00000000 /* Status FIFO Lo Threshold (disable) */ #define PCR_PS_FFHI_8 0x00300000 /* Data FIFO Hi Threshold (8Kbyte) */ #define PCR_PS_FFHI_4 0x00200000 /* Data FIFO Hi Threshold (4Kbyte) */ #define PCR_PS_FFHI_2 0x00100000 /* Data FIFO Hi Threshold (2Kbyte) */ #define PCR_PS_FFHI_0 0x00000000 /* Data FIFO Hi Threshold (disable) */ #define PCR_PS_FFLO_8 0x000c0000 /* Data FIFO Lo Threshold (8Kbyte) */ #define PCR_PS_FFLO_4 0x00080000 /* Data FIFO Lo Threshold (4Kbyte) */ #define PCR_PS_FFLO_2 0x00040000 /* Data FIFO Lo Threshold (2Kbyte) */ #define PCR_PS_FFLO_0 0x00000000 /* Data FIFO Lo Threshold (disable) */ #define PCR_PS_TX 0x00020000 /* Transmit PAUSE frame manually */ /* #else */ #define PCR_PSNEG 0x00200000 /* Pause Negoticated (83815) */ #define PCR_MLD_EN 0x00010000 /* Manual Load Enable (83815) */ /* #endif DP83820 */ #define PCR_PAUSE_CNT_MASK 0x0000ffff /* pause count mask */ #define PCR_PAUSE_CNT 65535 /* pause count (512bit-time) */ #define SIP_RFCR 0x48 /* receive filter control register */ #define RFCR_RFEN 0x80000000 /* Rx filter enable */ #define RFCR_AAB 0x40000000 /* accept all broadcast */ #define RFCR_AAM 0x20000000 /* accept all multicast */ #define RFCR_AAP 0x10000000 /* accept all physical */ #define RFCR_APM 0x08000000 /* accept perfect match (83815) */ #define RFCR_APAT 0x07800000 /* accept pattern match (83815) */ #define RFCR_AARP 0x00400000 /* accept ARP (83815) */ #define RFCR_MHEN 0x00200000 /* multicast hash enable (83815) */ #define RFCR_UHEN 0x00100000 /* unicast hash enable (83815) */ #define RFCR_ULM 0x00080000 /* U/L bit mask (83815) */ #define RFCR_NS_RFADDR 0x000003ff /* Rx filter ext reg address (83815) */ #define RFCR_RFADDR 0x000f0000 /* Rx filter address */ #define RFCR_RFADDR_NODE0 0x00000000 /* node address 1, 0 */ #define RFCR_RFADDR_NODE2 0x00010000 /* node address 3, 2 */ #define RFCR_RFADDR_NODE4 0x00020000 /* node address 5, 4 */ #define RFCR_RFADDR_MC0 0x00040000 /* multicast hash word 0 */ #define RFCR_RFADDR_MC1 0x00050000 /* multicast hash word 1 */ #define RFCR_RFADDR_MC2 0x00060000 /* multicast hash word 2 */ #define RFCR_RFADDR_MC3 0x00070000 /* multicast hash word 3 */ #define RFCR_RFADDR_MC4 0x00080000 /* multicast hash word 4 */ #define RFCR_RFADDR_MC5 0x00090000 /* multicast hash word 5 */ #define RFCR_RFADDR_MC6 0x000a0000 /* multicast hash word 6 */ #define RFCR_RFADDR_MC7 0x000b0000 /* multicast hash word 7 */ /* For SiS900B and 635/735 only */ #define RFCR_RFADDR_MC8 0x000c0000 /* multicast hash word 8 */ #define RFCR_RFADDR_MC9 0x000d0000 /* multicast hash word 9 */ #define RFCR_RFADDR_MC10 0x000e0000 /* multicast hash word 10 */ #define RFCR_RFADDR_MC11 0x000f0000 /* multicast hash word 11 */ #define RFCR_RFADDR_MC12 0x00100000 /* multicast hash word 12 */ #define RFCR_RFADDR_MC13 0x00110000 /* multicast hash word 13 */ #define RFCR_RFADDR_MC14 0x00120000 /* multicast hash word 14 */ #define RFCR_RFADDR_MC15 0x00130000 /* multicast hash word 15 */ #define RFCR_NS_RFADDR_PMATCH0 0x0000 /* perfect match octets 1-0 */ #define RFCR_NS_RFADDR_PMATCH2 0x0002 /* perfect match octets 3-2 */ #define RFCR_NS_RFADDR_PMATCH4 0x0004 /* perfect match octets 5-4 */ #define RFCR_NS_RFADDR_PCOUNT 0x0006 /* pattern count */ /* DP83820 only */ #define RFCR_NS_RFADDR_PCOUNT2 0x0008 /* pattern count 2, 3 */ #define RFCR_NS_RFADDR_SOPAS0 0x000a /* SecureOn 0, 1 */ #define RFCR_NS_RFADDR_SOPAS2 0x000c /* SecureOn 2, 3 */ #define RFCR_NS_RFADDR_SOPAS4 0x000e /* SecureOn 4, 5 */ #define RFCR_NS_RFADDR_PATMEM 0x0200 /* pattern memory */ #define DP83820_RFCR_NS_RFADDR_FILTMEM 0x0100 /* hash memory */ #define OTHER_RFCR_NS_RFADDR_FILTMEM 0x0200 /* filter memory (hash/pattern) */ #define SIP_RFDR 0x4c /* receive filter data register */ #define RFDR_BMASK 0x00030000 /* byte mask (83815) */ #define RFDR_DATA 0x0000ffff /* data bits */ #define SIP_NS_BRAR 0x50 /* boot rom address (83815) */ #define BRAR_AUTOINC 0x80000000 /* autoincrement */ #define BRAR_ADDR 0x0000ffff /* address */ #define SIP_NS_BRDR 0x54 /* boot rom data (83815) */ #define SIP_NS_SRR 0x58 /* silicon revision register (83815) */ /* #ifdef DP83820 */ #define SRR_REV_B 0x00000103 /* #else */ #define SRR_REV_A 0x00000101 #define SRR_REV_B_1 0x00000200 #define SRR_REV_B_2 0x00000201 #define SRR_REV_B_3 0x00000203 #define SRR_REV_C_1 0x00000300 #define SRR_REV_C_2 0x00000302 /* #endif DP83820 */ #define SIP_NS_MIBC 0x5c /* mib control register (83815) */ #define MIBC_MIBS 0x00000008 /* mib counter strobe */ #define MIBC_ACLR 0x00000004 /* clear all counters */ #define MIBC_FRZ 0x00000002 /* freeze all counters */ #define MIBC_WRN 0x00000001 /* warning test indicator */ #define SIP_NS_MIB(mibreg) /* mib data registers (83815) */ \ (0x60 + (mibreg)) #define MIB_RXErroredPkts 0x00 #define MIB_RXFCSErrors 0x04 #define MIB_RXMsdPktErrors 0x08 #define MIB_RXFAErrors 0x0c #define MIB_RXSymbolErrors 0x10 #define MIB_RXFrameTooLong 0x14 /* #ifdef DP83820 */ #define MIB_RXIRLErrors 0x18 #define MIB_RXBadOpcodes 0x1c #define MIB_RXPauseFrames 0x20 #define MIB_TXPauseFrames 0x24 #define MIB_TXSQEErrors 0x28 /* #else */ #define MIB_RXTXSQEErrors 0x18 /* #endif DP83820 */ /* 83815 only */ #define SIP_NS_PHY(miireg) /* PHY registers (83815) */ \ (0x80 + ((miireg) << 2)) /* #ifdef DP83820 */ #define SIP_TXDP1 0xa0 /* transmit descriptor pointer (pri 1) */ #define SIP_TXDP2 0xa4 /* transmit descriptor pointer (pri 2) */ #define SIP_TXDP3 0xa8 /* transmit descriptor pointer (pri 3) */ #define SIP_RXDP1 0xb0 /* receive descriptor pointer (pri 1) */ #define SIP_RXDP2 0xb4 /* receive descriptor pointer (pri 2) */ #define SIP_RXDP3 0xb8 /* receive descriptor pointer (pri 3) */ #define SIP_VRCR 0xbc /* VLAN/IP receive control register */ #define VRCR_RUDPE 0x00000080 /* reject UDP checksum errors */ #define VRCR_RTCPE 0x00000040 /* reject TCP checksum errors */ #define VRCR_RIPE 0x00000020 /* reject IP checksum errors */ #define VRCR_IPEN 0x00000010 /* IP checksum enable */ #define VRCR_DUTF 0x00000008 /* discard untagged frames */ #define VRCR_DVTF 0x00000004 /* discard VLAN tagged frames */ #define VRCR_VTREN 0x00000002 /* VLAN tag removal enable */ #define VRCR_VTDEN 0x00000001 /* VLAN tag detection enable */ #define SIP_VTCR 0xc0 /* VLAN/IP transmit control register */ #define VTCR_PPCHK 0x00000008 /* per-packet checksum generation */ #define VTCR_GCHK 0x00000004 /* global checksum generation */ #define VTCR_VPPTI 0x00000002 /* VLAN per-packet tag insertion */ #define VTCR_VGTI 0x00000001 /* VLAN global tag insertion */ #define SIP_VDR 0xc4 /* VLAN data register */ #define VDR_VTCI 0xffff0000 /* VLAN tag control information */ #define VDR_VTYPE 0x0000ffff /* VLAN type field */ #define SIP83820_NS_CCSR 0xcc /* CLKRUN control/status register (83820) */ #if 0 #define CCSR_PMESTS 0x00008000 /* PME status */ #define CCSR_PMEEN 0x00000100 /* PME enable */ #define CCSR_CLKRUN_EN 0x00000001 /* clkrun enable */ #endif #define SIP_TBICR 0xe0 /* TBI control register */ #define TBICR_MR_LOOPBACK 0x00004000 /* TBI PCS loopback enable */ #define TBICR_MR_AN_ENABLE 0x00001000 /* TBI autonegotiation enable */ #define TBICR_MR_RESTART_AN 0x00000200 /* restart TBI autoneogtiation */ #define SIP_TBISR 0xe4 /* TBI status register */ #define TBISR_MR_LINK_STATUS 0x00000020 /* TBI link status */ #define TBISR_MR_AN_COMPLETE 0x00000004 /* TBI autonegotiation complete */ #define SIP_TANAR 0xe8 /* TBI autoneg adv. register */ #define TANAR_NP 0x00008000 /* next page exchange required */ #define TANAR_RF2 0x00002000 /* remote fault 2 */ #define TANAR_RF1 0x00001000 /* remote fault 1 */ #define TANAR_PS2 0x00000100 /* pause encoding 2 */ #define TANAR_PS1 0x00000080 /* pause encoding 1 */ #define TANAR_HALF_DUP 0x00000040 /* adv. half duplex */ #define TANAR_FULL_DUP 0x00000020 /* adv. full duplex */ #define SIP_TANLPAR 0xec /* TBI autoneg link partner ability register */ /* See TANAR bits */ #define SIP_TANER 0xf0 /* TBI autoneg expansion register */ #define TANER_NPA 0x00000004 /* we support next page function */ #define TANER_PR 0x00000002 /* page received from link partner */ #define SIP_TESR 0xf4 /* TBI extended status register */ #define TESR_1000FDX 0x00008000 /* we support 1000base FDX */ #define TESR_1000HDX 0x00004000 /* we support 1000base HDX */ /* #else */ #define SIP_PMCTL 0xb0 /* power management control register */ #define PMCTL_GATECLK 0x80000000 /* gate dual clock enable */ #define PMCTL_WAKEALL 0x40000000 /* wake on all Rx OK */ #define PMCTL_FRM3ACS 0x04000000 /* 3rd wake-up frame access */ #define PMCTL_FRM2ACS 0x02000000 /* 2nd wake-up frame access */ #define PMCTL_FRM1ACS 0x01000000 /* 1st wake-up frame access */ #define PMCTL_FRM3EN 0x00400000 /* 3rd wake-up frame match enable */ #define PMCTL_FRM2EN 0x00200000 /* 2nd wake-up frame match enable */ #define PMCTL_FRM1EN 0x00100000 /* 1st wake-up frame match enable */ #define PMCTL_ALGORITHM 0x00000800 /* Magic Packet match algorithm */ #define PMCTL_MAGICPKT 0x00000400 /* Magic Packet match enable */ #define PMCTL_LINKON 0x00000002 /* link on monitor enable */ #define PMCTL_LINKLOSS 0x00000001 /* link loss monitor enable */ #define SIP_PMEVT 0xb4 /* power management wake-up evnt reg */ #define PMEVT_ALLFRMMAT 0x40000000 /* receive packet ok */ #define PMEVT_FRM3MAT 0x04000000 /* match 3rd wake-up frame */ #define PMEVT_FRM2MAT 0x02000000 /* match 2nd wake-up frame */ #define PMEVT_FRM1MAT 0x01000000 /* match 1st wake-up frame */ #define PMEVT_MAGICPKT 0x00000400 /* Magic Packet */ #define PMEVT_ONEVT 0x00000002 /* link on event */ #define PMEVT_LOSSEVT 0x00000001 /* link loss event */ #define SIP_WAKECRC 0xbc /* wake-up frame CRC register */ #define SIP_WAKEMASK0 0xc0 /* wake-up frame mask registers */ #define SIP_WAKEMASK1 0xc4 #define SIP_WAKEMASK2 0xc8 #define SIP_WAKEMASK3 0xcc #define SIP_WAKEMASK4 0xe0 #define SIP_WAKEMASK5 0xe4 #define SIP_WAKEMASK6 0xe8 #define SIP_WAKEMASK7 0xec /* #endif DP83820 */ /* * Revision codes for the SiS 630 chipset built-in Ethernet. */ #define SIS_REV_900B 0x03 #define SIS_REV_630E 0x81 #define SIS_REV_630S 0x82 #define SIS_REV_630EA1 0x83 #define SIS_REV_630ET 0x84 #define SIS_REV_635 0x90 /* same for 735 (745?) */ #define SIS_REV_960 0x91 /* * MII operations for recent SiS chipsets */ #define SIS_MII_STARTDELIM 0x01 #define SIS_MII_READOP 0x02 #define SIS_MII_WRITEOP 0x01 #define SIS_MII_TURNAROUND 0x02 /* * Serial EEPROM opcodes, including the start bit. */ #define SIP_EEPROM_OPC_ERASE 0x04 #define SIP_EEPROM_OPC_WRITE 0x05 #define SIP_EEPROM_OPC_READ 0x06 /* * Serial EEPROM address map (byte address) for the SiS900. */ #define SIP_EEPROM_SIGNATURE 0x00 /* SiS 900 signature */ #define SIP_EEPROM_MASK 0x02 /* `enable' mask */ #define SIP_EEPROM_VENDOR_ID 0x04 /* PCI vendor ID */ #define SIP_EEPROM_DEVICE_ID 0x06 /* PCI device ID */ #define SIP_EEPROM_SUBVENDOR_ID 0x08 /* PCI subvendor ID */ #define SIP_EEPROM_SUBSYSTEM_ID 0x0a /* PCI subsystem ID */ #define SIP_EEPROM_PMC 0x0c /* PCI power management capabilities */ #define SIP_EEPROM_reserved 0x0e /* reserved */ #define SIP_EEPROM_ETHERNET_ID0 0x10 /* Ethernet address 0, 1 */ #define SIP_EEPROM_ETHERNET_ID1 0x12 /* Ethernet address 2, 3 */ #define SIP_EEPROM_ETHERNET_ID2 0x14 /* Ethernet address 4, 5 */ #define SIP_EEPROM_CHECKSUM 0x16 /* checksum */ /* * Serial EEPROM data (byte addresses) for the DP83815. */ #define SIP_DP83815_EEPROM_CHECKSUM 0x16 /* checksum */ #define SIP_DP83815_EEPROM_LENGTH 0x18 /* length of EEPROM data */ /* * Serial EEPROM data (byte addresses) for the DP83820. */ #define SIP_DP83820_EEPROM_SUBSYSTEM_ID 0x00 /* PCI subsystem ID */ #define SIP_DP83820_EEPROM_SUBVENDOR_ID 0x02 /* PCI subvendor ID */ #define SIP_DP83820_EEPROM_CFGINT 0x04 /* PCI INT [31:16] */ #define SIP_DP83820_EEPROM_CONFIG0 0x06 /* configuration word 0 */ #define SIP_DP83820_EEPROM_CONFIG1 0x08 /* configuration word 1 */ #define SIP_DP83820_EEPROM_CONFIG2 0x0a /* configuration word 2 */ #define SIP_DP83820_EEPROM_CONFIG3 0x0c /* configuration word 3 */ #define SIP_DP83820_EEPROM_SOPAS0 0x0e /* SecureOn [47:32] */ #define SIP_DP83820_EEPROM_SOPAS1 0x10 /* SecureOn [31:16] */ #define SIP_DP83820_EEPROM_SOPAS2 0x12 /* SecureOn [15:0] */ #define SIP_DP83820_EEPROM_PMATCH0 0x14 /* MAC [47:32] */ #define SIP_DP83820_EEPROM_PMATCH1 0x16 /* MAC [31:16] */ #define SIP_DP83820_EEPROM_PMATCH2 0x18 /* MAC [15:0] */ #define SIP_DP83820_EEPROM_CHECKSUM 0x1a /* checksum */ #define SIP_DP83820_EEPROM_LENGTH 0x1c /* length of EEPROM data */ #define DP83820_CONFIG2_CFG_EXT_125 (1U << 0) #define DP83820_CONFIG2_CFG_M64ADDR (1U << 1) #define DP83820_CONFIG2_CFG_DATA64_EN (1U << 2) #define DP83820_CONFIG2_CFG_T64ADDR (1U << 3) #define DP83820_CONFIG2_CFG_MWI_DIS (1U << 4) #define DP83820_CONFIG2_CFG_MRM_DIS (1U << 5) #define DP83820_CONFIG2_CFG_MODE_1000 (1U << 7) #define DP83820_CONFIG2_CFG_TBI_EN (1U << 9) #endif /* _DEV_PCI_IF_SIPREG_H_ */
11e0ec49f5a7a6f956292a85b63c62258a1f5975
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/app/xfontsel/xfontsel.c
540fade0fa3870ba360bf3ade70418ee08f2f548
[ "X11", "HPND" ]
permissive
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
42,384
c
xfontsel.c
/* Copyright (c) 1985-1989 X Consortium 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 X CONSORTIUM 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. Except as contained in this notice, the name of the X Consortium shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization from the X Consortium. Author: Ralph R. Swick, DEC/MIT Project Athena one weekend in November, 1989 Modified: Mark Leisher <mleisher@crl.nmsu.edu> to deal with UCS sample text. */ #include <stdio.h> #include <stdlib.h> #include <X11/Intrinsic.h> #include <X11/StringDefs.h> #include <X11/Xatom.h> #include <X11/Xaw/AsciiText.h> #include <X11/Xaw/Box.h> #include <X11/Xaw/Cardinals.h> #include <X11/Xaw/Command.h> #include <X11/Xaw/Form.h> #include <X11/Xaw/MenuButton.h> #include <X11/Xaw/Paned.h> #include <X11/Xaw/SimpleMenu.h> #include <X11/Xaw/SmeBSB.h> #include <X11/Xaw/Toggle.h> #include <X11/Xaw/Viewport.h> #include <X11/Xmu/Atoms.h> #include <X11/Xmu/StdSel.h> #include <X11/Xfuncs.h> #include <X11/Xlib.h> #include "ULabel.h" #define MIN_APP_DEFAULTS_VERSION 1 #define FIELD_COUNT 14 #define DELIM '-' /* number of font names to parse in each background iteration */ #ifndef PARSE_QUANTUM #define PARSE_QUANTUM 25 #endif #define NZ NULL,ZERO #define BACKGROUND 10 void GetFontNames(XtPointer closure); Boolean Matches(String pattern, String fontName, Boolean fields[], int *maxfields); Boolean DoWorkPiece(XtPointer closure); void Quit(Widget w, XtPointer closure, XtPointer callData) _X_NORETURN; void Reset(Widget w, XtPointer closure, XtPointer callData); void OwnSelection(Widget w, XtPointer closure, XtPointer callData); void SelectField(Widget w, XtPointer closure, XtPointer callData); void ParseFontNames(XtPointer closure); void SortFields(XtPointer closure); void FixScalables(XtPointer closure); void MakeFieldMenu(XtPointer closure); void SelectValue(Widget w, XtPointer closure, XtPointer callData); void AnyValue(Widget w, XtPointer closure, XtPointer callData); void EnableOtherValues(Widget w, XtPointer closure, XtPointer callData); void EnableMenu(XtPointer closure); void SetCurrentFont(XtPointer closure); void QuitAction(Widget w, XEvent *event, String *params, Cardinal *num_params) _X_NORETURN; static XtActionsRec xfontsel_actions[] = { {"Quit", QuitAction} }; static Atom wm_delete_window; Boolean IsXLFDFontName(String fontName); typedef void (*XtProc)(XtPointer closure); static struct _appRes { int app_defaults_version; Cursor cursor; String pattern; char *pixelSizeList; char *pointSizeList; Boolean print_on_quit; String sample_text; String sample_text16; String sample_textUCS; Boolean scaled_fonts; } AppRes; #define DEFAULTPATTERN "-*-*-*-*-*-*-*-*-*-*-*-*-*-*" static XtResource resources[] = { { "cursor", "Cursor", XtRCursor, sizeof(Cursor), XtOffsetOf( struct _appRes, cursor ), XtRImmediate, NULL }, { "pattern", "Pattern", XtRString, sizeof(String), XtOffsetOf( struct _appRes, pattern ), XtRString, (XtPointer)DEFAULTPATTERN }, { "pixelSizeList", "PixelSizeList", XtRString, sizeof(String), XtOffsetOf( struct _appRes, pixelSizeList ), XtRString, (XtPointer)"" }, { "pointSizeList", "PointSizeList", XtRString, sizeof(String), XtOffsetOf( struct _appRes, pointSizeList ), XtRString, (XtPointer)"" }, { "printOnQuit", "PrintOnQuit", XtRBoolean, sizeof(Boolean), XtOffsetOf( struct _appRes, print_on_quit ), XtRImmediate, (XtPointer)False }, { "appDefaultsVersion", "AppDefaultsVersion", XtRInt, sizeof(int), XtOffsetOf( struct _appRes, app_defaults_version ), XtRImmediate, (XtPointer)0 }, { "sampleText", "Text", XtRString, sizeof(String), XtOffsetOf( struct _appRes, sample_text ), XtRString, (XtPointer)"" }, { "sampleText16", "Text16", XtRString, sizeof(String), XtOffsetOf( struct _appRes, sample_text16 ), XtRString, (XtPointer)"" }, { "sampleTextUCS", "TextUCS", XtRString, sizeof(String), XtOffsetOf( struct _appRes, sample_textUCS ), XtRString, (XtPointer)"" }, { "scaledFonts", "ScaledFonts", XtRBoolean, sizeof(Boolean), XtOffsetOf( struct _appRes, scaled_fonts ), XtRImmediate, (XtPointer)False }, }; static XrmOptionDescRec options[] = { {"-pattern", "pattern", XrmoptionSepArg, NULL}, {"-print", "printOnQuit", XrmoptionNoArg, "True"}, {"-sample", "sampleText", XrmoptionSepArg, NULL}, {"-sample16", "sampleText16", XrmoptionSepArg, NULL}, {"-sampleUCS", "sampleTextUCS",XrmoptionSepArg, NULL}, {"-scaled", "scaledFonts", XrmoptionNoArg, "True"}, }; static void Syntax(const char *call) { fprintf (stderr, "usage: %s [-options ...] -fn font\n\n%s\n", call, "where options include:\n" " -display dpy X server to contact\n" " -geometry geom size and location of window\n" " -pattern fontspec font name pattern to match against\n" " -print print selected font name on exit\n" " -sample string sample text to use for 1-byte fonts\n" " -sample16 string sample text to use for 2-byte fonts\n" " -sampleUCS string sample text to use for ISO10646 fonts\n" " -scaled use scaled instances of fonts\n" "plus any standard toolkit options\n"); exit (1); } typedef struct FieldValue FieldValue; struct FieldValue { int field; String string; Widget menu_item; int count; /* of fonts */ int allocated; int *font; Boolean enable; }; typedef struct FieldValueList FieldValueList; struct FieldValueList { int count; /* of values */ int allocated; Boolean show_unselectable; FieldValue value[1]; /* really [allocated] */ }; typedef struct FontValues FontValues; struct FontValues { int value_index[FIELD_COUNT]; }; typedef struct FieldMenuRec FieldMenuRec; struct FieldMenuRec { int field; Widget button; }; typedef struct Choice Choice; struct Choice { Choice *prev; FieldValue *value; }; static XtResource menuResources[] = { { "showUnselectable", "ShowUnselectable", XtRBoolean, sizeof(Boolean), XtOffsetOf( FieldValueList, show_unselectable ), XtRImmediate, (XtPointer)True }, }; typedef enum {ValidateCurrentField, SkipCurrentField} ValidateAction; static void EnableAllItems(int field); static void EnableRemainingItems(ValidateAction current_field_action); static void FlushXqueue(Display *dpy); static void MarkInvalidFonts(Boolean *set, FieldValue *val); static void ScheduleWork(XtProc proc, XtPointer closure, int priority); static void SetCurrentFontCount(void); static void SetNoFonts(void); static void SetParsingFontCount(int count); static void reset_currentFontNameString(void); static XtAppContext appCtx; static int numFonts; static int numBadFonts; static FontValues *fonts; static int *scaledFonts; static int numScaledFonts; static FieldValueList *fieldValues[FIELD_COUNT]; static FontValues currentFont; static int matchingFontCount; static Boolean anyDisabled = False; static Widget resetButton; static Widget ownButton; static Widget fieldBox; static Widget countLabel; static Widget currentFontName; static char *currentFontNameString; static int currentFontNameSize; static Widget sampleText; static int textEncoding = -1; static XFontStruct *sampleFont = NULL; static Boolean *fontInSet; static Choice *choiceList = NULL; static int enabledMenuIndex; static Boolean patternFieldSpecified[FIELD_COUNT]; /* = 0 */ int main(int argc, char **argv) { Widget topLevel, pane; XtSetLanguageProc(NULL, (XtLanguageProc) NULL, NULL); topLevel = XtAppInitialize(&appCtx, "XFontSel", options, XtNumber(options), &argc, argv, NULL, NULL, 0); if (argc != 1) Syntax(argv[0]); XtAppAddActions(appCtx, xfontsel_actions, XtNumber(xfontsel_actions)); XtOverrideTranslations (topLevel, XtParseTranslationTable ("<Message>WM_PROTOCOLS: Quit()")); XtGetApplicationResources( topLevel, (XtPointer)&AppRes, resources, XtNumber(resources), NZ ); if (AppRes.app_defaults_version < MIN_APP_DEFAULTS_VERSION) { XrmDatabase rdb = XtDatabase(XtDisplay(topLevel)); XtWarning( "app-defaults file not properly installed." ); XrmPutLineResource( &rdb, "*sampleText*UCSLabel:XFontSel app-defaults file not properly installed;\\n\ see 'xfontsel' manual page." ); } ScheduleWork(GetFontNames, (XtPointer)topLevel, 0); pane = XtCreateManagedWidget("pane",panedWidgetClass,topLevel,NZ); { Widget commandBox, /* fieldBox, currentFontName,*/ viewPort; commandBox = XtCreateManagedWidget("commandBox",formWidgetClass,pane,NZ); { Widget quitButton /*, resetButton, ownButton , countLabel*/; quitButton = XtCreateManagedWidget("quitButton",commandWidgetClass,commandBox,NZ); resetButton = XtCreateManagedWidget("resetButton",commandWidgetClass,commandBox,NZ); ownButton = XtCreateManagedWidget("ownButton",toggleWidgetClass,commandBox,NZ); countLabel = XtCreateManagedWidget("countLabel",labelWidgetClass,commandBox,NZ); XtAddCallback(quitButton, XtNcallback, Quit, NULL); XtAddCallback(resetButton, XtNcallback, Reset, NULL); XtAddCallback(ownButton,XtNcallback,OwnSelection,(XtPointer)True); } fieldBox = XtCreateManagedWidget("fieldBox", boxWidgetClass, pane, NZ); { Widget /*dash,*/ field /*[FIELD_COUNT]*/; int f; for (f = 0; f < FIELD_COUNT; f++) { char name[10]; FieldMenuRec *makeRec = XtNew(FieldMenuRec); snprintf( name, sizeof(name), "field%d", f ); XtCreateManagedWidget("dash",labelWidgetClass,fieldBox,NZ); field = XtCreateManagedWidget(name, menuButtonWidgetClass, fieldBox, NZ); XtAddCallback(field, XtNcallback, SelectField, (XtPointer)(long)f); makeRec->field = f; makeRec->button = field; ScheduleWork(MakeFieldMenu, (XtPointer)makeRec, 2); ScheduleWork((XtProc)XtFree, (XtPointer)makeRec, 2); } } /* currentFontName = */ { Arg args[1]; reset_currentFontNameString(); XtSetArg(args[0], XtNlabel, currentFontNameString); currentFontName = XtCreateManagedWidget("fontName",labelWidgetClass,pane,args,ONE); } viewPort = XtCreateManagedWidget("viewPort",viewportWidgetClass,pane,NZ); sampleText = XtCreateManagedWidget("sampleText",ucsLabelWidgetClass,viewPort,NZ); } XtRealizeWidget(topLevel); XDefineCursor( XtDisplay(topLevel), XtWindow(topLevel), AppRes.cursor ); { int f; for (f = 0; f < FIELD_COUNT; f++) currentFont.value_index[f] = -1; } wm_delete_window = XInternAtom(XtDisplay(topLevel), "WM_DELETE_WINDOW", False); (void) XSetWMProtocols (XtDisplay(topLevel), XtWindow(topLevel), &wm_delete_window, 1); XtAppMainLoop(appCtx); exit(0); } typedef struct WorkPiece WorkPieceRec, *WorkPiece; struct WorkPiece { WorkPiece next; int priority; XtProc proc; XtPointer closure; }; static WorkPiece workQueue = NULL; /* * ScheduleWork( XtProc proc, XtPointer closure, int priority ) * * Adds a WorkPiece to the workQueue in FIFO order by priority. * Lower numbered priority work is completed before higher numbered * priorities. * * If the workQueue was previously empty, then makes sure that * Xt knows we have (background) work to do. */ static void ScheduleWork(XtProc proc, XtPointer closure, int priority) { WorkPiece piece = XtNew(WorkPieceRec); piece->priority = priority; piece->proc = proc; piece->closure = closure; if (workQueue == NULL) { piece->next = NULL; workQueue = piece; XtAppAddWorkProc(appCtx, DoWorkPiece, NULL); } else { if (workQueue->priority > priority) { piece->next = workQueue; workQueue = piece; } else { WorkPiece n; for (n = workQueue; n->next && n->next->priority <= priority;) n = n->next; piece->next = n->next; n->next = piece; } } } /* ARGSUSED */ Boolean DoWorkPiece(XtPointer closure) { WorkPiece piece = workQueue; if (piece) { (*piece->proc)(piece->closure); workQueue = piece->next; XtFree((XtPointer)piece); if (workQueue != NULL) return False; } return True; } /* * FinishWork() * * Drains foreground tasks from the workQueue. * Foreground == (priority < BACKGROUND) */ static void FinishWork(void) { while (workQueue && workQueue->priority < BACKGROUND) DoWorkPiece(NULL); } typedef struct ParseRec ParseRec; struct ParseRec { char **fontNames; int num_fonts; int start, end; FontValues *fonts; FieldValueList **fieldValues; }; void GetFontNames(XtPointer closure) { Widget topLevel = (Widget)closure; Display *dpy = XtDisplay(topLevel); ParseRec *parseRec; int count; char **fontNames; int work_priority = 0; fontNames = XListFonts(dpy, AppRes.pattern, 32767, &numFonts); fonts = (FontValues*)XtMalloc( numFonts*sizeof(FontValues) ); fontInSet = (Boolean*)XtMalloc( numFonts*sizeof(Boolean) ); { int f; Boolean *b; for (f = numFonts, b = fontInSet; f; f--, b++) *b = True; } for (int field = 0; field < FIELD_COUNT; field++) { fieldValues[field] = (FieldValueList*)XtMalloc(sizeof(FieldValueList)); fieldValues[field]->allocated = 1; fieldValues[field]->count = 0; } if (numFonts == 0) { SetNoFonts(); return; } count = matchingFontCount = numFonts; numBadFonts = 0; parseRec = XtNew(ParseRec); *parseRec = (ParseRec) { .fontNames = fontNames, .num_fonts = count, .start = 0, .fonts = fonts, .fieldValues = fieldValues }; /* this is bogus; the task should be responsible for quantizing...*/ while (count > PARSE_QUANTUM) { ParseRec *prevRec = parseRec; parseRec->end = parseRec->start + PARSE_QUANTUM; ScheduleWork(ParseFontNames, (XtPointer)parseRec, work_priority); ScheduleWork((XtProc)XtFree, (XtPointer)parseRec, work_priority); parseRec = XtNew(ParseRec); *parseRec = *prevRec; parseRec->start += PARSE_QUANTUM; parseRec->fonts += PARSE_QUANTUM; parseRec->fontNames += PARSE_QUANTUM; count -= PARSE_QUANTUM; work_priority = 1; } parseRec->end = numFonts; ScheduleWork(ParseFontNames,(XtPointer)parseRec,work_priority); ScheduleWork((XtProc)XFreeFontNames,(XtPointer)fontNames,work_priority); ScheduleWork((XtProc)XtFree, (XtPointer)parseRec, work_priority); if (AppRes.scaled_fonts) ScheduleWork(FixScalables,(XtPointer)topLevel, work_priority); ScheduleWork(SortFields,(XtPointer)0,work_priority); SetParsingFontCount(matchingFontCount); if (strcmp(AppRes.pattern, DEFAULTPATTERN)) { int maxField, f; for (f = 0; f < numFonts && !IsXLFDFontName(fontNames[f]); f++); if (f != numFonts) { if (Matches(AppRes.pattern, fontNames[f], patternFieldSpecified, &maxField)) { for (f = 0; f <= maxField; f++) { if (patternFieldSpecified[f]) currentFont.value_index[f] = 0; } } else XtAppWarning( appCtx, "internal error; pattern didn't match first font" ); } else { SetNoFonts(); return; } } ScheduleWork(SetCurrentFont, NULL, 1); } void ParseFontNames(XtPointer closure) { ParseRec *parseRec = (ParseRec*)closure; char **fontNames = parseRec->fontNames; int num_fonts = parseRec->end; FieldValueList **fieldValues = parseRec->fieldValues; FontValues *fontValues = parseRec->fonts - numBadFonts; int i, font; for (font = parseRec->start; font < num_fonts; font++) { char *p; int f, len; FieldValue *v; if (!IsXLFDFontName(*fontNames)) { numFonts--; numBadFonts++; continue; } for (f = 0, p = *fontNames++; f < FIELD_COUNT; f++) { const char *fieldP; if (*p) ++p; if (*p == DELIM || *p == '\0') { fieldP = ""; len = 0; } else { fieldP = p; while (*p && *++p != DELIM); len = p - fieldP; } for (i=fieldValues[f]->count,v=fieldValues[f]->value; i;i--,v++) { if (len == 0) { if (v->string == NULL) break; } else if (v->string && strncmp( v->string, fieldP, len ) == 0 && (v->string)[len] == '\0') break; } if (i == 0) { int count = fieldValues[f]->count++; if (count == fieldValues[f]->allocated) { int allocated = (fieldValues[f]->allocated += 10); fieldValues[f] = (FieldValueList*) XtRealloc( (char *) fieldValues[f], sizeof(FieldValueList) + (allocated-1) * sizeof(FieldValue) ); } v = &fieldValues[f]->value[count]; v->field = f; if (len == 0) v->string = NULL; else { char *s = XtMalloc(len + 1); strncpy( s, fieldP, len ); s[len] = '\0'; v->string = (String) s; } v->font = (int*)XtMalloc( 10*sizeof(int) ); v->allocated = 10; v->count = 0; v->enable = True; i = 1; } fontValues->value_index[f] = fieldValues[f]->count - i; if ((i = v->count++) == v->allocated) { int allocated = (v->allocated += 10); v->font = (int*)XtRealloc( (char *) v->font, allocated * sizeof(int) ); } v->font[i] = font - numBadFonts; } fontValues++; } SetParsingFontCount(numFonts - num_fonts); } /* Add the list of scalable fonts to the match-list of every value instance * for field f. Must produce sorted order. Must deal with duplicates * since we need to do this for resolution fields which can be nonzero in * the scalable fonts. */ static void AddScalables(int f) { int i; int max = fieldValues[f]->count; FieldValue *fval = fieldValues[f]->value; for (i = 0; i < max; i++, fval++) { int *oofonts, *ofonts, *nfonts, *fonts; int ocount, ncount, count; if (fval->string && !strcmp(fval->string, "0")) continue; count = numScaledFonts; fonts = scaledFonts; ocount = fval->count; ncount = ocount + count; nfonts = (int *)XtMalloc( ncount * sizeof(int) ); oofonts = ofonts = fval->font; fval->font = nfonts; fval->count = ncount; fval->allocated = ncount; while (count && ocount) { if (*fonts < *ofonts) { *nfonts++ = *fonts++; count--; } else if (*fonts == *ofonts) { *nfonts++ = *fonts++; count--; ofonts++; ocount--; fval->count--; } else { *nfonts++ = *ofonts++; ocount--; } } while (ocount) { *nfonts++ = *ofonts++; ocount--; } while (count) { *nfonts++ = *fonts++; count--; } XtFree((char *)oofonts); } } /* Merge in specific scaled sizes (specified in a comma-separated string) * for field f. Weed out duplicates. The set of matching fonts is just * the set of scalable fonts. */ static void NewScalables(int f, char *slist) { char endc = 1; char *str; int i, count; FieldValue *v; while (endc) { while (*slist == ' ' || *slist == ',') slist++; if (!*slist) break; str = slist; while ((endc = *slist) && endc != ' ' && endc != ',') slist++; *slist++ = '\0'; for (i=fieldValues[f]->count,v=fieldValues[f]->value; --i >= 0; v++) { if (v->string && !strcmp(v->string, str)) break; } if (i >= 0) continue; count = fieldValues[f]->count++; if (count == fieldValues[f]->allocated) { int allocated = (fieldValues[f]->allocated += 10); fieldValues[f] = (FieldValueList*) XtRealloc( (char *) fieldValues[f], sizeof(FieldValueList) + (allocated-1) * sizeof(FieldValue) ); } v = &fieldValues[f]->value[count]; v->field = f; v->string = str; v->count = numScaledFonts; v->font = scaledFonts; v->allocated = 0; v->enable = True; } } /* Find all scalable fonts, defined as the set matching "0" in the pixel * size field (field 6). Augment the match-lists for all other fields * that are scalable. Add in new scalable pixel and point sizes given * in resources, along with the current Screen's actual resX and resY * values. */ /*ARGSUSED*/ void FixScalables(XtPointer closure) { int i; FieldValue *fval = fieldValues[6]->value; Widget topLevel = (Widget) closure; Display *dpy = XtDisplay(topLevel); int scr = XScreenNumberOfScreen(XtScreenOfObject(topLevel)); double xres, yres; static char xreslist[21]; /* log10(UINT64_MAX) == 19 */ static char yreslist[21]; /* from xdpyinfo.c: * there are 2.54 centimeters to an inch; so there are 25.4 millimeters. * * dpi = N pixels / (M millimeters / (25.4 millimeters / 1 inch)) * = N pixels / (M inch / 25.4) * = N * 25.4 pixels / M inch */ xres = ((((double) DisplayWidth(dpy, scr)) * 25.4) / ((double) DisplayWidthMM(dpy, scr))); yres = ((((double) DisplayHeight(dpy, scr)) * 25.4) / ((double) DisplayHeightMM(dpy, scr))); /* * xxx the "0" element is always added, so we can't force these here.... * * However, what's interesting is that if the pattern contains '*' for these * fields (i.e. instead of '0') then we end up with the menu containing "0, * 100, xres", which makes for a really good demonstration of how scaling * fonts without knowing the true screen resolution leads to very wonky * results. * * xxx obviously these are static and related only to the screen of the * Widget at the time this code executes and so you can't drag the Xfontsel * winto to another screen with a different resolution and see things change * dynamically -- you have to instantiate a new Xfontsel process on each * different screen as desired. */ sprintf(xreslist, "%d", (int) (xres + 0.5)); sprintf(yreslist, "%d", (int) (yres + 0.5)); for (i = fieldValues[6]->count; --i >= 0; fval++) { if (fval->string && !strcmp(fval->string, "0")) { scaledFonts = fval->font; numScaledFonts = fval->count; AddScalables(6); NewScalables(6, AppRes.pixelSizeList); AddScalables(7); NewScalables(7, AppRes.pointSizeList); NewScalables(8, xreslist); NewScalables(9, yreslist); AddScalables(11); break; } } } /* A verbatim copy from xc/lib/font/fontfile/fontdir.c */ /* * Compare two strings just like strcmp, but preserve decimal integer * sorting order, i.e. "2" < "10" or "iso8859-2" < "iso8859-10" < * "iso10646-1". Strings are sorted as if sequences of digits were * prefixed by a length indicator (i.e., does not ignore leading zeroes). * * Markus Kuhn <Markus.Kuhn@cl.cam.ac.uk> */ #define Xisdigit(c) ('\060' <= (c) && (c) <= '\071') static int strcmpn(const char *s1, const char *s2) { int digits, predigits = 0; const char *ss1, *ss2; while (1) { if (*s1 == 0 && *s2 == 0) return 0; digits = Xisdigit(*s1) && Xisdigit(*s2); if (digits && !predigits) { ss1 = s1; ss2 = s2; while (Xisdigit(*ss1) && Xisdigit(*ss2)) ss1++, ss2++; if (!Xisdigit(*ss1) && Xisdigit(*ss2)) return -1; if (Xisdigit(*ss1) && !Xisdigit(*ss2)) return 1; } if ((unsigned char)*s1 < (unsigned char)*s2) return -1; if ((unsigned char)*s1 > (unsigned char)*s2) return 1; predigits = digits; s1++, s2++; } } /* Order is *, (nil), rest */ static int AlphabeticSort(_Xconst void *fval1, _Xconst void *fval2) { # define fval1 ((_Xconst FieldValue *)fval1) # define fval2 ((_Xconst FieldValue *)fval2) if (fval1->string && !strcmp(fval1->string, "*")) return -1; if (fval2->string && !strcmp(fval2->string, "*")) return 1; if (!fval1->string) return -1; if (!fval2->string) return 1; return strcmpn(fval1->string, fval2->string); # undef fval1 # undef fval2 } /* Order is *, (nil), rest */ static int NumericSort(_Xconst void *fval1, _Xconst void *fval2) { # define fval1 ((_Xconst FieldValue *)fval1) # define fval2 ((_Xconst FieldValue *)fval2) if (fval1->string && !strcmp(fval1->string, "*")) return -1; if (fval2->string && !strcmp(fval2->string, "*")) return 1; if (!fval1->string) return -1; if (!fval2->string) return 1; return atoi(fval1->string) - atoi(fval2->string); # undef fval1 # undef fval2 } /* Resort each field, to get reasonable menus. Sort alphabetically or * numerically, depending on the field. Since the fonts have indexes * into the fields, we need to deal with updating those indexes after the * sort. */ /*ARGSUSED*/ void SortFields(XtPointer closure) { int i, j, count; FieldValue *vals; int *indexes; int *idx; for (i = 0; i < FIELD_COUNT; i++) { count = fieldValues[i]->count; vals = fieldValues[i]->value; indexes = (int *)XtMalloc(count * sizeof(int)); /* temporarily use the field component, will restore it below */ for (j = 0; j < count; j++) vals[j].field = j; switch (i) { case 6: case 7: case 8: case 9: case 11: qsort((char *)vals, count, sizeof(FieldValue), NumericSort); break; default: qsort((char *)vals, count, sizeof(FieldValue), AlphabeticSort); break; } for (j = 0; j < count; j++) { indexes[vals[j].field] = j; vals[j].field = i; } for (j = 0; j < numFonts; j++) { idx = &fonts[j].value_index[i]; if (*idx >= 0) *idx = indexes[*idx]; } XtFree((char *)indexes); } } Boolean IsXLFDFontName(String fontName) { int f; for (f = 0; *fontName;) if (*fontName++ == DELIM) f++; return (f == FIELD_COUNT); } void MakeFieldMenu(XtPointer closure) { FieldMenuRec *makeRec = (FieldMenuRec*)closure; Widget menu; FieldValueList *values = fieldValues[makeRec->field]; FieldValue *val = values->value; int i; Arg args[1]; register Widget item; if (numFonts) menu = XtCreatePopupShell("menu",simpleMenuWidgetClass,makeRec->button,NZ); else { SetNoFonts(); return; } XtGetSubresources(menu, (XtPointer) values, "options", "Options", menuResources, XtNumber(menuResources), NZ); XtAddCallback(menu, XtNpopupCallback, EnableOtherValues, (XtPointer)(long)makeRec->field ); if (!patternFieldSpecified[val->field]) { XtSetArg( args[0], XtNlabel, "*" ); item = XtCreateManagedWidget("any",smeBSBObjectClass,menu,args,ONE); XtAddCallback(item, XtNcallback, AnyValue, (XtPointer)(long)val->field); } for (i = values->count; i; i--, val++) { XtSetArg( args[0], XtNlabel, val->string ? val->string : "(nil)" ); item = XtCreateManagedWidget(val->string ? val->string : "nil", smeBSBObjectClass, menu, args, ONE); XtAddCallback(item, XtNcallback, SelectValue, (XtPointer)val); val->menu_item = item; } } static void SetNoFonts(void) { matchingFontCount = 0; SetCurrentFontCount(); XtSetSensitive(fieldBox, False); XtSetSensitive(resetButton, False); XtSetSensitive(ownButton, False); if (AppRes.app_defaults_version >= MIN_APP_DEFAULTS_VERSION) { XtUnmapWidget(sampleText); } } Boolean Matches(register String pattern, register String fontName, Boolean fields[/*FIELD_COUNT*/], int *maxField) { register int field = (*fontName == DELIM) ? -1 : 0; register Boolean marked_this_field = False; while (*pattern) { if (*pattern == *fontName || *pattern == '?') { pattern++; if (*fontName++ == DELIM) { field++; marked_this_field = False; } else if (!marked_this_field) fields[field] = marked_this_field = True; continue; } if (*pattern == '*') { if (*++pattern == '\0') { *maxField = field; return True; } while (*fontName) { Boolean field_bits[FIELD_COUNT]; int max_field; if (*fontName == DELIM) field++; bzero( field_bits, sizeof(field_bits) ); if (Matches(pattern, fontName++, field_bits, &max_field)) { int f; *maxField = field + max_field; for (f = 0; f <= max_field; field++, f++) fields[field] = field_bits[f]; return True; } } return False; } else /* (*pattern != '*') */ return False; } if (*fontName) return False; *maxField = field; return True; } /* ARGSUSED */ void SelectValue(Widget w, XtPointer closure, XtPointer callData) { FieldValue *val = (FieldValue*)closure; #ifdef LOG_CHOICES Choice *choice = XtNew(Choice); #else static Choice pChoice; Choice *choice = &pChoice; #endif #ifdef notdef Widget button = XtParent(XtParent(w)); Arg args[1]; XtSetArg(args[0], XtNlabel, val->string); XtSetValues( button, args, ONE ); #endif currentFont.value_index[val->field] = val - fieldValues[val->field]->value; choice->prev = choiceList; choice->value = val; choiceList = choice; SetCurrentFont(NULL); EnableRemainingItems(SkipCurrentField); } /* ARGSUSED */ void AnyValue(Widget w, XtPointer closure, XtPointer callData) { int field = (long)closure; currentFont.value_index[field] = -1; SetCurrentFont(NULL); EnableAllItems(field); EnableRemainingItems(ValidateCurrentField); } static void SetCurrentFontCount(void) { char label[80]; Arg args[1]; if (matchingFontCount == 1) strcpy( label, "1 name matches" ); else if (matchingFontCount) snprintf( label, sizeof(label), "%d names match", matchingFontCount ); else strcpy( label, "no names match" ); XtSetArg( args[0], XtNlabel, label ); XtSetValues( countLabel, args, ONE ); } static void SetParsingFontCount(int count) { char label[80]; Arg args[1]; if (count == 1) strcpy( label, "1 name to parse" ); else snprintf( label, sizeof(label), "%d names to parse", count ); XtSetArg( args[0], XtNlabel, label ); XtSetValues( countLabel, args, ONE ); FlushXqueue(XtDisplay(countLabel)); } /* ARGSUSED */ static Boolean IsISO10646(Display *dpy, XFontStruct *font) { Boolean ok; int i; char *regname; Atom registry; XFontProp *xfp; ok = False; registry = XInternAtom(dpy, "CHARSET_REGISTRY", False); for (i = 0, xfp = font->properties; ok == False && i < font->n_properties; xfp++, i++) { if (xfp->name == registry) { regname = XGetAtomName(dpy, (Atom) xfp->card32); if (strcmp(regname, "ISO10646") == 0 || strcmp(regname, "iso10646") == 0) ok = True; XFree(regname); } } return ok; } /* ARGSUSED */ void SetCurrentFont(XtPointer closure) { int f; Boolean *b; if (numFonts == 0) { SetNoFonts(); return; } for (f = numFonts, b = fontInSet; f; f--, b++) *b = True; { int bytesLeft = currentFontNameSize; int pos = 0; for (f = 0; f < FIELD_COUNT; f++) { int len, i; String str; currentFontNameString[pos++] = DELIM; if ((i = currentFont.value_index[f]) != -1) { FieldValue *val = &fieldValues[f]->value[i]; if ((str = val->string)) len = strlen(str); else { str = ""; len = 0; } MarkInvalidFonts(fontInSet, val); } else { str = "*"; len = 1; } if (len+1 > --bytesLeft) { currentFontNameString = XtRealloc(currentFontNameString, currentFontNameSize+=128); bytesLeft += 128; } strcpy( &currentFontNameString[pos], str ); pos += len; bytesLeft -= len; } } { Arg args[1]; XtSetArg( args[0], XtNlabel, currentFontNameString ); XtSetValues( currentFontName, args, ONE ); } matchingFontCount = 0; for (f = numFonts, b = fontInSet; f; f--, b++) { if (*b) matchingFontCount++; } SetCurrentFontCount(); { Widget mapWidget = sampleText; Display *dpy = XtDisplay(mapWidget); XFontStruct *font = XLoadQueryFont(dpy, currentFontNameString); String sample_text; if (font == NULL) XtSetSensitive(mapWidget, False); else { int nargs = 1; Arg args[3]; int encoding; if (font->min_byte1 || font->max_byte1) { if (IsISO10646(dpy, font) == True) { encoding = XawTextEncodingUCS; sample_text = AppRes.sample_textUCS; } else { encoding = XawTextEncodingChar2b; sample_text = AppRes.sample_text16; } } else { encoding = XawTextEncoding8bit; sample_text = AppRes.sample_text; } XtSetArg( args[0], XtNfont, font ); if (encoding != textEncoding) { XtSetArg(args[1], XtNencoding, encoding); XtSetArg(args[2], XtNlabel, sample_text); textEncoding = encoding; nargs = 3; } XtSetValues( sampleText, args, nargs ); XtSetSensitive(mapWidget, True); XtMapWidget(mapWidget); if (sampleFont) XFreeFont( dpy, sampleFont ); sampleFont = font; OwnSelection( sampleText, (XtPointer)False, (XtPointer)True ); } FlushXqueue(dpy); } } static void MarkInvalidFonts(Boolean *set, FieldValue *val) { int fi = 0, vi; int *fp = val->font; for (vi = val->count; vi; vi--, fp++) { while (fi < *fp) { set[fi] = False; fi++; } fi++; } while (fi < numFonts) { set[fi] = False; fi++; } } static void EnableRemainingItems(ValidateAction current_field_action) { if (matchingFontCount == 0 || matchingFontCount == numFonts) { if (anyDisabled) { int field; for (field = 0; field < FIELD_COUNT; field++) { EnableAllItems(field); } anyDisabled = False; } } else { int field; for (field = 0; field < FIELD_COUNT; field++) { FieldValue *value = fieldValues[field]->value; int count; if (current_field_action == SkipCurrentField && field == choiceList->value->field) continue; for (count = fieldValues[field]->count; count; count--, value++) { int *fp = value->font; int fontCount; for (fontCount = value->count; fontCount; fontCount--, fp++) { if (fontInSet[*fp]) { value->enable = True; goto NextValue; } } value->enable = False; NextValue:; } } anyDisabled = True; } enabledMenuIndex = -1; { int f; for (f = 0; f < FIELD_COUNT; f++) ScheduleWork(EnableMenu, (XtPointer)(long)f, BACKGROUND); } } static void EnableAllItems(int field) { FieldValue *value = fieldValues[field]->value; int count; for (count = fieldValues[field]->count; count; count--, value++) { value->enable = True; } } /* ARGSUSED */ void SelectField(Widget w, XtPointer closure, XtPointer callData) { int field = (long)closure; FieldValue *values = fieldValues[field]->value; int count = fieldValues[field]->count; printf( "field %d:\n", field ); while (count--) { printf( " %s: %d fonts\n", values->string, values->count ); values++; } printf( "\n" ); } /* When 2 out of 3 y-related scalable fields are set, we need to restrict * the third set to only match on exact matches, that is, ignore the * matching to scalable fonts. Because choosing a random third value * will almost always produce an illegal font name, and it isn't worth * trying to compute which choices might be legal to the font scaler. */ static void DisableScaled(int f, int f1, int f2) { int i, j; FieldValue *v; int *font; for (i = fieldValues[f]->count, v = fieldValues[f]->value; --i >= 0; v++) { if (!v->enable || !v->string || !strcmp(v->string, "0")) continue; for (j = v->count, font = v->font; --j >= 0; font++) { if (fontInSet[*font] && fonts[*font].value_index[f1] == currentFont.value_index[f1] && fonts[*font].value_index[f2] == currentFont.value_index[f2]) break; } if (j < 0) { v->enable = False; XtSetSensitive(v->menu_item, False); } } } /* ARGSUSED */ void EnableOtherValues(Widget w, XtPointer closure, XtPointer callData) { int field = (long)closure; Boolean *font_in_set = (Boolean*)XtMalloc(numFonts*sizeof(Boolean)); Boolean *b; int f, count; FinishWork(); for (f = numFonts, b = font_in_set; f; f--, b++) *b = True; for (f = 0; f < FIELD_COUNT; f++) { int i; if (f != field && (i = currentFont.value_index[f]) != -1) { MarkInvalidFonts( font_in_set, &fieldValues[f]->value[i] ); } } if (scaledFonts) { /* Check for 2 out of 3 scalable y fields being set */ const char *str; Bool specificPxl, specificPt, specificY; f = currentFont.value_index[6]; specificPxl = (f >= 0 && (str = fieldValues[6]->value[f].string) && strcmp(str, "0")); f = currentFont.value_index[7]; specificPt = (f >= 0 && (str = fieldValues[7]->value[f].string) && strcmp(str, "0")); f = currentFont.value_index[9]; specificY = (f >= 0 && (str = fieldValues[9]->value[f].string) && strcmp(str, "0")); if (specificPt && specificY) DisableScaled(6, 7, 9); if (specificPxl && specificY) DisableScaled(7, 6, 9); if (specificPxl && specificPt) DisableScaled(9, 6, 7); } count = 0; for (f = numFonts, b = font_in_set; f; f--, b++) { if (*b) count++; } if (count != matchingFontCount) { Boolean *sp = fontInSet; FieldValueList *fieldValue = fieldValues[field]; for (b = font_in_set, f = 0; f < numFonts; f++, b++, sp++) { if (*b != *sp) { int i = fonts[f].value_index[field]; FieldValue *val = &fieldValue->value[i]; val->enable = True; XtSetSensitive(val->menu_item, True); if (++count == matchingFontCount) break; } } } XtFree((char *)font_in_set); if (enabledMenuIndex < field) EnableMenu((XtPointer)(long)field); } void EnableMenu(XtPointer closure) { int field = (long)closure; FieldValue *val = fieldValues[field]->value; int f; Widget *managed = NULL, *pManaged = NULL; Widget *unmanaged = NULL, *pUnmanaged = NULL; Boolean showUnselectable = fieldValues[field]->show_unselectable; for (f = fieldValues[field]->count; f; f--, val++) { if (showUnselectable) { if (val->enable != XtIsSensitive(val->menu_item)) XtSetSensitive(val->menu_item, val->enable); } else { if (val->enable != XtIsManaged(val->menu_item)) { if (val->enable) { if (managed == NULL) { managed = (Widget*) XtMalloc(fieldValues[field]->count*sizeof(Widget)); pManaged = managed; } *pManaged++ = val->menu_item; } else { if (unmanaged == NULL) { unmanaged = (Widget*) XtMalloc(fieldValues[field]->count*sizeof(Widget)); pUnmanaged = unmanaged; } *pUnmanaged++ = val->menu_item; } } } } if (pManaged != managed) { XtManageChildren(managed, pManaged - managed); XtFree((char *) managed); } if (pUnmanaged != unmanaged) { XtUnmanageChildren(unmanaged, pUnmanaged - unmanaged); XtFree((char *) unmanaged); } enabledMenuIndex = field; } static void FlushXqueue(Display *dpy) { XSync(dpy, False); while (XtAppPending(appCtx)) XtAppProcessEvent(appCtx, XtIMAll); } /* ARGSUSED */ void Quit(Widget w, XtPointer closure, XtPointer callData) { XtCloseDisplay(XtDisplay(w)); if (AppRes.print_on_quit) printf( "%s", currentFontNameString ); exit(0); } void Reset(Widget w, XtPointer closure, XtPointer callData) { Arg args[1]; reset_currentFontNameString(); XtSetArg(args[0], XtNlabel, currentFontNameString); XtSetValues(currentFontName, args, ONE); for (int f = 0; f < FIELD_COUNT; f++) currentFont.value_index[f] = patternFieldSpecified[f] ? 0 : -1; SetCurrentFont(NULL); EnableRemainingItems(SkipCurrentField); /* menu */ } static void reset_currentFontNameString(void) { currentFontNameSize = strlen(AppRes.pattern); if (currentFontNameSize < 128) currentFontNameSize = 128; XtFree(currentFontNameString); currentFontNameString = XtMalloc(currentFontNameSize); strcpy(currentFontNameString, AppRes.pattern); } static Boolean ConvertSelection(Widget w, Atom *selection, Atom *target, Atom *type, XtPointer *value, unsigned long *length, int *format) { /* XmuConvertStandardSelection will use the second parameter only when * converting to the target TIMESTAMP. However, it will never be * called upon to perform this conversion, because Xt will handle it * internally. CurrentTime will never be used. */ if (XmuConvertStandardSelection(w, CurrentTime, selection, target, type, (XPointer *) value, length, format)) return True; if (*target == XA_STRING) { *type = XA_STRING; *value = currentFontNameString; *length = strlen(*value); *format = 8; return True; } else { return False; } } static AtomPtr _XA_PRIMARY_FONT = NULL; #define XA_PRIMARY_FONT XmuInternAtom(XtDisplay(w),_XA_PRIMARY_FONT) /* ARGSUSED */ static void LoseSelection(Widget w, Atom *selection) { Arg args[1]; XtSetArg( args[0], XtNstate, False ); XtSetValues( w, args, ONE ); if (*selection == XA_PRIMARY_FONT) { XtSetSensitive(currentFontName, False); } } /* ARGSUSED */ static void DoneSelection(Widget w, Atom *selection, Atom *target) { /* do nothing */ } /* ARGSUSED */ void OwnSelection(Widget w, XtPointer closure, XtPointer callData) { Time time = XtLastTimestampProcessed(XtDisplay(w)); Boolean primary = (Boolean) (long) closure; Boolean own = (Boolean) (long) callData; if (_XA_PRIMARY_FONT == NULL) _XA_PRIMARY_FONT = XmuMakeAtom("PRIMARY_FONT"); if (own) { XtOwnSelection( w, XA_PRIMARY_FONT, time, ConvertSelection, LoseSelection, DoneSelection ); if (primary) XtOwnSelection( w, XA_PRIMARY, time, ConvertSelection, LoseSelection, DoneSelection ); if (!XtIsSensitive(currentFontName)) { XtSetSensitive(currentFontName, True); } } else { XtDisownSelection(w, XA_PRIMARY_FONT, time); if (primary) XtDisownSelection(w, XA_PRIMARY, time); XtSetSensitive(currentFontName, False); } } /*ARGSUSED*/ void QuitAction(Widget w, XEvent *event, String *params, Cardinal *num_params) { exit (0); }
5ad64493ae20b9690477febc3fbeda0b52d6814a
3f017c2c3a55a2ac783045a23977765862ef4b20
/modules/zip/module.c
f2b26cfb7a9252e08161a24eed49f7b6867b9830
[]
no_license
DC-SWAT/DreamShell
8e4310087eb7f8e9bed285b8c66992e4df9c9143
f2551e18c06345fed0f5144245d6380203c20fa6
refs/heads/master
2023-07-09T16:50:05.291266
2023-06-23T05:32:37
2023-06-23T05:32:37
13,268,848
308
94
null
2023-06-23T05:04:53
2013-10-02T10:58:30
C
UTF-8
C
false
false
625
c
module.c
/* DreamShell ##version## module.c - zip module Copyright (C)2009-2014 SWAT */ #include "ds.h" DEFAULT_MODULE_HEADER(zip); int builtin_zip_cmd(int argc, char *argv[]); int builtin_unzip_cmd(int argc, char *argv[]); int lib_open(klibrary_t *lib) { AddCmd(lib_get_name(), "zip archiver", (CmdHandler *) builtin_zip_cmd); AddCmd("unzip", "unzip archives", (CmdHandler *) builtin_unzip_cmd); return nmmgr_handler_add(&ds_zip_hnd.nmmgr); } int lib_close(klibrary_t *lib) { RemoveCmd(GetCmdByName(lib_get_name())); RemoveCmd(GetCmdByName("unzip")); return nmmgr_handler_remove(&ds_zip_hnd.nmmgr); }
351f2b7318a324dc947b4202bbfd9017c0669b99
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/net/intel-iavf-kmod/files/patch-if__iavf__iflib.c
2fcb40507f2224b4796132a2888651f31ba5c138
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
423
c
patch-if__iavf__iflib.c
--- if_iavf_iflib.c.orig 2023-07-06 09:26:54 UTC +++ if_iavf_iflib.c @@ -130,8 +130,12 @@ static driver_t iavf_driver = { "iavf", iavf_methods, sizeof(struct iavf_sc), }; +#if __FreeBSD_version >= 1400058 +DRIVER_MODULE(iavf, pci, iavf_driver, 0, 0); +#else devclass_t iavf_devclass; DRIVER_MODULE(iavf, pci, iavf_driver, iavf_devclass, 0, 0); +#endif MODULE_VERSION(iavf, 1); MODULE_DEPEND(iavf, pci, 1, 1, 1);
af3c35f4c76e4330dbd5a7b43dd0dd228e393d2a
2c5414ed169892c538cd802c06d67001d9e4b960
/plugins/python/regress/iohelpers.h
42b32e102f238ef39e2c4ad635da1055f0d19717
[ "LicenseRef-scancode-unknown-license-reference", "BSD-3-Clause", "Zlib", "BSD-Source-Code", "ISC", "BSD-2-Clause" ]
permissive
sudo-project/sudo
bdfeebb02cb39151fc4cfe69366b887f092e0c16
956de5cbbc650d6aec19804cd376a39164e76e5b
refs/heads/main
2023-09-04T11:12:09.797952
2023-09-02T21:25:58
2023-09-02T21:25:58
57,972,154
922
216
NOASSERTION
2023-08-18T00:43:55
2016-05-03T13:41:24
C
UTF-8
C
false
false
2,164
h
iohelpers.h
/* * SPDX-License-Identifier: ISC * * Copyright (c) 2020 Robert Manner <robert.manner@oneidentity.com> * * Permission to use, copy, modify, and 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. */ #ifndef PYTHON_IO_HELPERS #define PYTHON_IO_HELPERS #include <config.h> #include <stdio.h> #include <stdlib.h> #ifdef HAVE_STDBOOL_H # include <stdbool.h> #else # include "compat/stdbool.h" #endif /* HAVE_STDBOOL_H */ #include <string.h> #include <stdarg.h> #include <signal.h> #include <pwd.h> #include "sudo_compat.h" #define MAX_OUTPUT (2 << 16) int rmdir_recursive(const char *path); int fwriteall(const char *file_path, const char *string); int freadall(const char *file_path, char *output, size_t max_len); // allocates new string with the content of 'string' but 'old' replaced to 'new' // The allocated array will be dest_length size and null terminated correctly. char *str_replaced(const char *string, size_t dest_length, const char *old, const char *new); // same, but "string" must be able to store 'max_length' number of characters including the null terminator void str_replace_in_place(char *string, size_t max_length, const char *old, const char *new); int vsnprintf_append(char * restrict output, size_t max_output_len, const char * restrict fmt, va_list args); int snprintf_append(char * restrict output, size_t max_output_len, const char * restrict fmt, ...); int str_array_count(char **str_array); void str_array_snprint(char *out_str, size_t max_len, char **str_array, int array_len); #endif
a9e070f30070ae726d84b7a7d47336f2563081c2
fcc9b5cb92607deaac4b097776ed0490789d8c3e
/src/runtime/x86-linux-os.h
58309ca694debe1d01b35ffba1a307ed3dd7f7c5
[ "LicenseRef-scancode-other-permissive", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "LicenseRef-scancode-warranty-disclaimer", "BSD-3-Clause", "LicenseRef-scancode-mit-specification-disclaimer", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "UPL-1.0" ]
permissive
sbcl/sbcl
ef248b5e8614ba7f0a1132c4f2cfcb000a074400
85003adf60ef659082c244972e816ea62240b9cb
refs/heads/master
2023-09-01T05:14:15.225083
2023-08-31T20:09:49
2023-08-31T20:09:49
1,890,957
1,737
408
NOASSERTION
2023-08-28T13:05:04
2011-06-13T20:33:25
Common Lisp
UTF-8
C
false
false
412
h
x86-linux-os.h
#ifndef _X86_LINUX_OS_H #define _X86_LINUX_OS_H typedef ucontext_t os_context_t; typedef greg_t os_context_register_t; #include "arch-os-generic.inc" unsigned long os_context_fp_control(os_context_t *context); #define RESTORE_FP_CONTROL_FROM_CONTEXT void os_restore_fp_control(os_context_t *context); #define OS_CONTEXT_PC(context) context->uc_mcontext.gregs[14] /* REG_EIP */ #endif /* _X86_LINUX_OS_H */
86d2c7106a7009e9f1422724a034d3812ebb8abe
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/external/bsd/drm2/dist/drm/nouveau/include/nvkm/core/firmware.h
e25c51908a2a6defdeb752421fa0d0ccaf55c44f
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
3,232
h
firmware.h
/* $NetBSD: firmware.h,v 1.2 2021/12/18 23:45:33 riastradh Exp $ */ /* SPDX-License-Identifier: MIT */ #ifndef __NVKM_FIRMWARE_H__ #define __NVKM_FIRMWARE_H__ #include <core/option.h> #include <core/subdev.h> int nvkm_firmware_get(const struct nvkm_subdev *, const char *fwname, int ver, const struct firmware **); void nvkm_firmware_put(const struct firmware *); int nvkm_firmware_load_blob(const struct nvkm_subdev *subdev, const char *path, const char *name, int ver, struct nvkm_blob *); int nvkm_firmware_load_name(const struct nvkm_subdev *subdev, const char *path, const char *name, int ver, const struct firmware **); #define nvkm_firmware_load(s,l,o,p...) ({ \ struct nvkm_subdev *_s = (s); \ const char *_opts = (o); \ char _option[32]; \ typeof(l[0]) *_list = (l), *_next, *_fwif = NULL; \ int _ver, _fwv, _ret = 0; \ \ snprintf(_option, sizeof(_option), "Nv%sFw", _opts); \ _ver = nvkm_longopt(_s->device->cfgopt, _option, -2); \ if (_ver >= -1) { \ for (_next = _list; !_fwif && _next->load; _next++) { \ if (_next->version == _ver) \ _fwif = _next; \ } \ _ret = _fwif ? 0 : -EINVAL; \ } \ \ if (_ret == 0) { \ snprintf(_option, sizeof(_option), "Nv%sFwVer", _opts); \ _fwv = _fwif ? _fwif->version : -1; \ _ver = nvkm_longopt(_s->device->cfgopt, _option, _fwv); \ for (_next = _fwif ? _fwif : _list; _next->load; _next++) { \ _fwv = (_ver >= 0) ? _ver : _next->version; \ _ret = _next->load(p, _fwv, _next); \ if (_ret == 0 || _ver >= 0) { \ _fwif = _next; \ break; \ } \ } \ } \ \ if (_ret) { \ nvkm_error(_s, "failed to load firmware\n"); \ _fwif = ERR_PTR(_ret); \ } \ \ _fwif; \ }) #endif
807ec175da82abad4be0e0424b8d4e8d95a580ff
64f63e6468d7d1a8239ca8a60cb3a57671d7026e
/include/sysmem_user.h
25631f03c7fc6d96060dbf8a148275b267ac8179
[ "BSD-3-Clause", "MIT" ]
permissive
uofw/uofw
511c6877af464a4c18cd62405805ed92b15b39c3
c517e4cee6679cf2c0ecb24afaa50a86c6460cf1
refs/heads/master
2023-02-09T17:10:03.719610
2023-02-03T13:11:50
2023-02-03T13:11:50
6,622,246
312
93
NOASSERTION
2023-09-05T19:54:15
2012-11-09T23:39:19
C
UTF-8
C
false
false
1,132
h
sysmem_user.h
/* Copyright (C) 2011, 2012, 2013 The uOFW team See the file COPYING for copying permission. */ #ifndef SYSMEM_USER_H #define SYSMEM_USER_H #include "common_header.h" #include "sysmem_common.h" enum SceSysMemPartitionId { SCE_KERNEL_UNKNOWN_PARTITION = 0, SCE_KERNEL_PRIMARY_KERNEL_PARTITION = 1, SCE_KERNEL_PRIMARY_USER_PARTITION = 2, SCE_KERNEL_OTHER_KERNEL_PARTITION_1 = 3, //PRIMARY_ME_KERNEL_PARTITION according to TyRaNiD SCE_KERNEL_OTHER_KERNEL_PARTITION_2 = 4, SCE_KERNEL_VSHELL_PARTITION = 5, SCE_KERNEL_SC_USER_PARTITION = 6, SCE_KERNEL_ME_USER_PARTITION = 7, SCE_KERNEL_EXTENDED_SC_KERNEL_PARTITION = 8, SCE_KERNEL_EXTENDED_SC_2_KERNEL_PARTITION = 9, SCE_KERNEL_EXTENDED_ME_KERNEL_PARTITION = 10, SCE_KERNEL_VSHELL_KERNEL_PARTITION = 11, SCE_KERNEL_EXTENDED_KERNEL_PARTITION = 12, }; enum SceSysMemBlockType { SCE_KERNEL_SMEM_Low = 0, SCE_KERNEL_SMEM_High = 1, SCE_KERNEL_SMEM_Addr = 2, SCE_KERNEL_SMEM_LOWALIGNED = 3, SCE_KERNEL_SMEM_HIGHALIGNED = 4 }; #endif /* SYSMEM_USER_H */
7e2cdfd9af4f9ce0a5f36dd231dc68908aa3a97b
aa3befea459382dc5c01c925653d54f435b3fb0f
/boards/arm/stm32/stm3210e-eval/src/stm32_extcontext.c
04eebf0acbc5649120a61e598efbcf4113eb8f12
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
3,722
c
stm32_extcontext.c
/**************************************************************************** * boards/arm/stm32/stm3210e-eval/src/stm32_extcontext.c * * 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. * ****************************************************************************/ /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #include <sys/types.h> #include <assert.h> #include <debug.h> #include "arm_internal.h" #include "stm32.h" #include "stm3210e-eval.h" #ifdef CONFIG_STM32_FSMC /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ #if STM32_NGPIO_PORTS < 6 # error "Required GPIO ports not enabled" #endif /**************************************************************************** * Private Data ****************************************************************************/ /**************************************************************************** * Private Functions ****************************************************************************/ /**************************************************************************** * Public Functions ****************************************************************************/ /**************************************************************************** * Name: stm32_extcontextsave * * Description: * Save current GPIOs that will used by external memory configurations * ****************************************************************************/ void stm32_extcontextsave(struct extmem_save_s *save) { DEBUGASSERT(save != NULL); save->gpiod_crl = getreg32(STM32_GPIOE_CRL); save->gpiod_crh = getreg32(STM32_GPIOE_CRH); save->gpioe_crl = getreg32(STM32_GPIOD_CRL); save->gpioe_crh = getreg32(STM32_GPIOD_CRH); save->gpiof_crl = getreg32(STM32_GPIOF_CRL); save->gpiof_crh = getreg32(STM32_GPIOF_CRH); save->gpiog_crl = getreg32(STM32_GPIOG_CRL); save->gpiog_crh = getreg32(STM32_GPIOG_CRH); } /**************************************************************************** * Name: stm32_extcontextrestore * * Description: * Restore GPIOs that were used by external memory configurations * ****************************************************************************/ void stm32_extcontextrestore(struct extmem_save_s *restore) { DEBUGASSERT(restore != NULL); putreg32(restore->gpiod_crl, STM32_GPIOE_CRL); putreg32(restore->gpiod_crh, STM32_GPIOE_CRH); putreg32(restore->gpioe_crl, STM32_GPIOD_CRL); putreg32(restore->gpioe_crh, STM32_GPIOD_CRH); putreg32(restore->gpiof_crl, STM32_GPIOF_CRL); putreg32(restore->gpiof_crh, STM32_GPIOF_CRH); putreg32(restore->gpiog_crl, STM32_GPIOG_CRL); putreg32(restore->gpiog_crh, STM32_GPIOG_CRH); } #endif /* CONFIG_STM32_FSMC */
c96ea472cfce99c75d68c3f13d342075b4823c5c
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/dlmalloc/dlmalloc.c
fb940138fe79631fa73b61588ea3468f28a95235
[ "CC0-1.0", "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
42,799
c
dlmalloc.c
#include "third_party/dlmalloc/dlmalloc.h" #include "libc/assert.h" #include "libc/calls/calls.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/intrin/bsr.h" #include "libc/intrin/likely.h" #include "libc/intrin/weaken.h" #include "libc/macros.internal.h" #include "libc/mem/mem.h" #include "libc/nexgen32e/rdtsc.h" #include "libc/runtime/internal.h" #include "libc/runtime/runtime.h" #include "libc/runtime/sysconf.h" #include "libc/stdckdint.h" #include "libc/stdio/rand.h" #include "libc/stdio/stdio.h" #include "libc/str/str.h" #include "libc/sysv/consts/map.h" #include "libc/sysv/consts/prot.h" #include "libc/thread/thread.h" #include "third_party/dlmalloc/vespene.internal.h" // clang-format off #define FOOTERS 0 #define MSPACES 0 #define HAVE_MMAP 1 #define HAVE_MREMAP 0 #define HAVE_MORECORE 0 #define USE_LOCKS 2 #define MORECORE_CONTIGUOUS 0 #define MALLOC_INSPECT_ALL 1 #define ABORT_ON_ASSERT_FAILURE 0 #define LOCK_AT_FORK 1 #define NO_MALLOC_STATS 1 #if IsTiny() #define INSECURE 1 #define PROCEED_ON_ERROR 1 #endif #if IsModeDbg() #define DEBUG 1 #endif #undef assert #define assert(x) npassert(x) #include "third_party/dlmalloc/platform.inc" #include "third_party/dlmalloc/locks.inc" #include "third_party/dlmalloc/chunks.inc" #include "third_party/dlmalloc/headfoot.inc" #include "third_party/dlmalloc/global.inc" #include "third_party/dlmalloc/system.inc" #include "third_party/dlmalloc/hooks.inc" #include "third_party/dlmalloc/debugging.inc" #include "third_party/dlmalloc/indexing.inc" #include "third_party/dlmalloc/binmaps.inc" #include "third_party/dlmalloc/runtimechecks.inc" #include "third_party/dlmalloc/init.inc" #include "third_party/dlmalloc/debuglib.inc" #include "third_party/dlmalloc/statistics.inc" #include "third_party/dlmalloc/smallbins.inc" #include "third_party/dlmalloc/directmap.inc" #include "third_party/dlmalloc/trees.inc" #include "third_party/dlmalloc/management.inc" /* -------------------------- System allocation -------------------------- */ /* Get memory from system using MORECORE or MMAP */ static void* sys_alloc(mstate m, size_t nb) { char* tbase = CMFAIL; size_t tsize = 0; flag_t mmap_flag = 0; size_t asize; /* allocation size */ ensure_initialization(); /* Directly map large chunks, but only if already initialized */ if (use_mmap(m) && nb >= mparams.mmap_threshold && m->topsize != 0) { void* mem = mmap_alloc(m, nb); if (mem != 0) return mem; } asize = granularity_align(nb + SYS_ALLOC_PADDING); if (asize <= nb) return 0; /* wraparound */ if (m->footprint_limit != 0) { size_t fp = m->footprint + asize; if (fp <= m->footprint || fp > m->footprint_limit) return 0; } /* Try getting memory in any of three ways (in most-preferred to least-preferred order): 1. A call to MORECORE that can normally contiguously extend memory. (disabled if not MORECORE_CONTIGUOUS or not HAVE_MORECORE or or main space is mmapped or a previous contiguous call failed) 2. A call to MMAP new space (disabled if not HAVE_MMAP). Note that under the default settings, if MORECORE is unable to fulfill a request, and HAVE_MMAP is true, then mmap is used as a noncontiguous system allocator. This is a useful backup strategy for systems with holes in address spaces -- in this case sbrk cannot contiguously expand the heap, but mmap may be able to find space. 3. A call to MORECORE that cannot usually contiguously extend memory. (disabled if not HAVE_MORECORE) In all cases, we need to request enough bytes from system to ensure we can malloc nb bytes upon success, so pad with enough space for top_foot, plus alignment-pad to make sure we don't lose bytes if not on boundary, and round this up to a granularity unit. */ if (MORECORE_CONTIGUOUS && !use_noncontiguous(m)) { char* br = CMFAIL; size_t ssize = asize; /* sbrk call size */ msegmentptr ss = (m->top == 0)? 0 : segment_holding(m, (char*)m->top); ACQUIRE_MALLOC_GLOBAL_LOCK(); if (ss == 0) { /* First time through or recovery */ char* base = (char*)CALL_MORECORE(0); if (base != CMFAIL) { size_t fp; /* Adjust to end on a page boundary */ if (!is_page_aligned(base)) ssize += (page_align((size_t)base) - (size_t)base); fp = m->footprint + ssize; /* recheck limits */ if (ssize > nb && ssize < HALF_MAX_SIZE_T && (m->footprint_limit == 0 || (fp > m->footprint && fp <= m->footprint_limit)) && (br = (char*)(CALL_MORECORE(ssize))) == base) { tbase = base; tsize = ssize; } } } else { /* Subtract out existing available top space from MORECORE request. */ ssize = granularity_align(nb - m->topsize + SYS_ALLOC_PADDING); /* Use mem here only if it did continuously extend old space */ if (ssize < HALF_MAX_SIZE_T && (br = (char*)(CALL_MORECORE(ssize))) == ss->base+ss->size) { tbase = br; tsize = ssize; } } if (tbase == CMFAIL) { /* Cope with partial failure */ if (br != CMFAIL) { /* Try to use/extend the space we did get */ if (ssize < HALF_MAX_SIZE_T && ssize < nb + SYS_ALLOC_PADDING) { size_t esize = granularity_align(nb + SYS_ALLOC_PADDING - ssize); if (esize < HALF_MAX_SIZE_T) { char* end = (char*)CALL_MORECORE(esize); if (end != CMFAIL) ssize += esize; else { /* Can't use; try to release */ (void) CALL_MORECORE(-ssize); br = CMFAIL; } } } } if (br != CMFAIL) { /* Use the space we did get */ tbase = br; tsize = ssize; } else disable_contiguous(m); /* Don't try contiguous path in the future */ } RELEASE_MALLOC_GLOBAL_LOCK(); } if (HAVE_MMAP && tbase == CMFAIL) { /* Try MMAP */ char* mp = (char*)(dlmalloc_requires_more_vespene_gas(asize)); if (mp != CMFAIL) { tbase = mp; tsize = asize; mmap_flag = USE_MMAP_BIT; } } if (HAVE_MORECORE && tbase == CMFAIL) { /* Try noncontiguous MORECORE */ if (asize < HALF_MAX_SIZE_T) { char* br = CMFAIL; char* end = CMFAIL; ACQUIRE_MALLOC_GLOBAL_LOCK(); br = (char*)(CALL_MORECORE(asize)); end = (char*)(CALL_MORECORE(0)); RELEASE_MALLOC_GLOBAL_LOCK(); if (br != CMFAIL && end != CMFAIL && br < end) { size_t ssize = end - br; if (ssize > nb + TOP_FOOT_SIZE) { tbase = br; tsize = ssize; } } } } if (tbase != CMFAIL) { if ((m->footprint += tsize) > m->max_footprint) m->max_footprint = m->footprint; if (!is_initialized(m)) { /* first-time initialization */ if (m->least_addr == 0 || tbase < m->least_addr) m->least_addr = tbase; m->seg.base = tbase; m->seg.size = tsize; m->seg.sflags = mmap_flag; m->magic = mparams.magic; m->release_checks = MAX_RELEASE_CHECK_RATE; init_bins(m); #if !ONLY_MSPACES if (is_global(m)) init_top(m, (mchunkptr)tbase, tsize - TOP_FOOT_SIZE); else #endif { /* Offset top by embedded malloc_state */ mchunkptr mn = next_chunk(mem2chunk(m)); init_top(m, mn, (size_t)((tbase + tsize) - (char*)mn) -TOP_FOOT_SIZE); } } else { /* Try to merge with an existing segment */ msegmentptr sp = &m->seg; /* Only consider most recent segment if traversal suppressed */ while (sp != 0 && tbase != sp->base + sp->size) sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; if (sp != 0 && !is_extern_segment(sp) && (sp->sflags & USE_MMAP_BIT) == mmap_flag && segment_holds(sp, m->top)) { /* append */ sp->size += tsize; init_top(m, m->top, m->topsize + tsize); } else { if (tbase < m->least_addr) m->least_addr = tbase; sp = &m->seg; while (sp != 0 && sp->base != tbase + tsize) sp = (NO_SEGMENT_TRAVERSAL) ? 0 : sp->next; if (sp != 0 && !is_extern_segment(sp) && (sp->sflags & USE_MMAP_BIT) == mmap_flag) { char* oldbase = sp->base; sp->base = tbase; sp->size += tsize; return prepend_alloc(m, tbase, oldbase, nb); } else add_segment(m, tbase, tsize, mmap_flag); } } if (nb < m->topsize) { /* Allocate from new or extended top space */ size_t rsize = m->topsize -= nb; mchunkptr p = m->top; mchunkptr r = m->top = chunk_plus_offset(p, nb); r->head = rsize | PINUSE_BIT; set_size_and_pinuse_of_inuse_chunk(m, p, nb); check_top_chunk(m, m->top); check_malloced_chunk(m, chunk2mem(p), nb); return chunk2mem(p); } } MALLOC_FAILURE_ACTION; return 0; } /* ----------------------- system deallocation -------------------------- */ /* Unmap and unlink any mmapped segments that don't contain used chunks */ static size_t release_unused_segments(mstate m) { size_t released = 0; int nsegs = 0; msegmentptr pred = &m->seg; msegmentptr sp = pred->next; while (sp != 0) { char* base = sp->base; size_t size = sp->size; msegmentptr next = sp->next; ++nsegs; if (is_mmapped_segment(sp) && !is_extern_segment(sp)) { mchunkptr p = align_as_chunk(base); size_t psize = chunksize(p); /* Can unmap if first chunk holds entire segment and not pinned */ if (!is_inuse(p) && (char*)p + psize >= base + size - TOP_FOOT_SIZE) { tchunkptr tp = (tchunkptr)p; assert(segment_holds(sp, (char*)sp)); if (p == m->dv) { m->dv = 0; m->dvsize = 0; } else { unlink_large_chunk(m, tp); } if (CALL_MUNMAP(base, size) == 0) { released += size; m->footprint -= size; /* unlink obsoleted record */ sp = pred; sp->next = next; } else { /* back out if cannot unmap */ insert_large_chunk(m, tp, psize); } } } if (NO_SEGMENT_TRAVERSAL) /* scan only first segment */ break; pred = sp; sp = next; } /* Reset check counter */ m->release_checks = (((size_t) nsegs > (size_t) MAX_RELEASE_CHECK_RATE)? (size_t) nsegs : (size_t) MAX_RELEASE_CHECK_RATE); return released; } static int sys_trim(mstate m, size_t pad) { size_t released = 0; ensure_initialization(); if (pad < MAX_REQUEST && is_initialized(m)) { pad += TOP_FOOT_SIZE; /* ensure enough room for segment overhead */ if (m->topsize > pad) { /* Shrink top space in granularity-size units, keeping at least one */ size_t unit = mparams.granularity; size_t extra = ((m->topsize - pad + (unit - SIZE_T_ONE)) / unit - SIZE_T_ONE) * unit; msegmentptr sp = segment_holding(m, (char*)m->top); if (!is_extern_segment(sp)) { if (is_mmapped_segment(sp)) { if (HAVE_MMAP && sp->size >= extra && !has_segment_link(m, sp)) { /* can't shrink if pinned */ size_t newsize = sp->size - extra; (void)newsize; /* placate people compiling -Wunused-variable */ /* Prefer mremap, fall back to munmap */ if (CALL_MREMAP(sp->base, sp->size, newsize, 0) != MFAIL || (!extra || !CALL_MUNMAP(sp->base + newsize, extra))) { released = extra; } } } else if (HAVE_MORECORE) { if (extra >= HALF_MAX_SIZE_T) /* Avoid wrapping negative */ extra = (HALF_MAX_SIZE_T) + SIZE_T_ONE - unit; ACQUIRE_MALLOC_GLOBAL_LOCK(); { /* Make sure end of memory is where we last set it. */ char* old_br = (char*)(CALL_MORECORE(0)); if (old_br == sp->base + sp->size) { char* rel_br = (char*)(CALL_MORECORE(-extra)); char* new_br = (char*)(CALL_MORECORE(0)); if (rel_br != CMFAIL && new_br < old_br) released = old_br - new_br; } } RELEASE_MALLOC_GLOBAL_LOCK(); } } if (released != 0) { sp->size -= released; m->footprint -= released; init_top(m, m->top, m->topsize - released); check_top_chunk(m, m->top); } } /* Unmap any unused mmapped segments */ if (HAVE_MMAP) released += release_unused_segments(m); /* On failure, disable autotrim to avoid repeated failed future calls */ if (released == 0 && m->topsize > m->trim_check) m->trim_check = MAX_SIZE_T; } return (released != 0)? 1 : 0; } /* Consolidate and bin a chunk. Differs from exported versions of free mainly in that the chunk need not be marked as inuse. */ static void dispose_chunk(mstate m, mchunkptr p, size_t psize) { mchunkptr next = chunk_plus_offset(p, psize); if (!pinuse(p)) { mchunkptr prev; size_t prevsize = p->prev_foot; if (is_mmapped(p)) { psize += prevsize + MMAP_FOOT_PAD; if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) m->footprint -= psize; return; } prev = chunk_minus_offset(p, prevsize); psize += prevsize; p = prev; if (RTCHECK(ok_address(m, prev))) { /* consolidate backward */ if (p != m->dv) { unlink_chunk(m, p, prevsize); } else if ((next->head & INUSE_BITS) == INUSE_BITS) { m->dvsize = psize; set_free_with_pinuse(p, psize, next); return; } } else { CORRUPTION_ERROR_ACTION(m); return; } } if (RTCHECK(ok_address(m, next))) { if (!cinuse(next)) { /* consolidate forward */ if (next == m->top) { size_t tsize = m->topsize += psize; m->top = p; p->head = tsize | PINUSE_BIT; if (p == m->dv) { m->dv = 0; m->dvsize = 0; } return; } else if (next == m->dv) { size_t dsize = m->dvsize += psize; m->dv = p; set_size_and_pinuse_of_free_chunk(p, dsize); return; } else { size_t nsize = chunksize(next); psize += nsize; unlink_chunk(m, next, nsize); set_size_and_pinuse_of_free_chunk(p, psize); if (p == m->dv) { m->dvsize = psize; return; } } } else { set_free_with_pinuse(p, psize, next); } insert_chunk(m, p, psize); } else { CORRUPTION_ERROR_ACTION(m); } } /* ---------------------------- malloc --------------------------- */ /* allocate a large request from the best fitting chunk in a treebin */ static void* tmalloc_large(mstate m, size_t nb) { tchunkptr v = 0; size_t rsize = -nb; /* Unsigned negation */ tchunkptr t; bindex_t idx; compute_tree_index(nb, idx); if ((t = *treebin_at(m, idx)) != 0) { /* Traverse tree for this bin looking for node with size == nb */ size_t sizebits = nb << leftshift_for_tree_index(idx); tchunkptr rst = 0; /* The deepest untaken right subtree */ for (;;) { tchunkptr rt; size_t trem = chunksize(t) - nb; if (trem < rsize) { v = t; if ((rsize = trem) == 0) break; } rt = t->child[1]; t = t->child[(sizebits >> (SIZE_T_BITSIZE-SIZE_T_ONE)) & 1]; if (rt != 0 && rt != t) rst = rt; if (t == 0) { t = rst; /* set t to least subtree holding sizes > nb */ break; } sizebits <<= 1; } } if (t == 0 && v == 0) { /* set t to root of next non-empty treebin */ binmap_t leftbits = left_bits(idx2bit(idx)) & m->treemap; if (leftbits != 0) { bindex_t i; binmap_t leastbit = least_bit(leftbits); compute_bit2idx(leastbit, i); t = *treebin_at(m, i); } } while (t != 0) { /* find smallest of tree or subtree */ size_t trem = chunksize(t) - nb; if (trem < rsize) { rsize = trem; v = t; } t = leftmost_child(t); } /* If dv is a better fit, return 0 so malloc will use it */ if (v != 0 && rsize < (size_t)(m->dvsize - nb)) { if (RTCHECK(ok_address(m, v))) { /* split */ mchunkptr r = chunk_plus_offset(v, nb); assert(chunksize(v) == rsize + nb); if (RTCHECK(ok_next(v, r))) { unlink_large_chunk(m, v); if (rsize < MIN_CHUNK_SIZE) set_inuse_and_pinuse(m, v, (rsize + nb)); else { set_size_and_pinuse_of_inuse_chunk(m, v, nb); set_size_and_pinuse_of_free_chunk(r, rsize); insert_chunk(m, r, rsize); } return chunk2mem(v); } } CORRUPTION_ERROR_ACTION(m); } return 0; } /* allocate a small request from the best fitting chunk in a treebin */ static void* tmalloc_small(mstate m, size_t nb) { tchunkptr t, v; size_t rsize; bindex_t i; binmap_t leastbit = least_bit(m->treemap); compute_bit2idx(leastbit, i); v = t = *treebin_at(m, i); rsize = chunksize(t) - nb; while ((t = leftmost_child(t)) != 0) { size_t trem = chunksize(t) - nb; if (trem < rsize) { rsize = trem; v = t; } } if (RTCHECK(ok_address(m, v))) { mchunkptr r = chunk_plus_offset(v, nb); assert(chunksize(v) == rsize + nb); if (RTCHECK(ok_next(v, r))) { unlink_large_chunk(m, v); if (rsize < MIN_CHUNK_SIZE) set_inuse_and_pinuse(m, v, (rsize + nb)); else { set_size_and_pinuse_of_inuse_chunk(m, v, nb); set_size_and_pinuse_of_free_chunk(r, rsize); replace_dv(m, r, rsize); } return chunk2mem(v); } } CORRUPTION_ERROR_ACTION(m); return 0; } #if !ONLY_MSPACES void* dlmalloc(size_t bytes) { /* Basic algorithm: If a small request (< 256 bytes minus per-chunk overhead): 1. If one exists, use a remainderless chunk in associated smallbin. (Remainderless means that there are too few excess bytes to represent as a chunk.) 2. If it is big enough, use the dv chunk, which is normally the chunk adjacent to the one used for the most recent small request. 3. If one exists, split the smallest available chunk in a bin, saving remainder in dv. 4. If it is big enough, use the top chunk. 5. If available, get memory from system and use it Otherwise, for a large request: 1. Find the smallest available binned chunk that fits, and use it if it is better fitting than dv chunk, splitting if necessary. 2. If better fitting than any binned chunk, use the dv chunk. 3. If it is big enough, use the top chunk. 4. If request size >= mmap threshold, try to directly mmap this chunk. 5. If available, get memory from system and use it The ugly goto's here ensure that postaction occurs along all paths. */ #if USE_LOCKS ensure_initialization(); /* initialize in sys_alloc if not using locks */ #endif if (!PREACTION(gm)) { void* mem; size_t nb; if (bytes <= MAX_SMALL_REQUEST) { bindex_t idx; binmap_t smallbits; nb = (bytes < MIN_REQUEST)? MIN_CHUNK_SIZE : pad_request(bytes); idx = small_index(nb); smallbits = gm->smallmap >> idx; if ((smallbits & 0x3U) != 0) { /* Remainderless fit to a smallbin. */ mchunkptr b, p; idx += ~smallbits & 1; /* Uses next bin if idx empty */ b = smallbin_at(gm, idx); p = b->fd; assert(chunksize(p) == small_index2size(idx)); unlink_first_small_chunk(gm, b, p, idx); set_inuse_and_pinuse(gm, p, small_index2size(idx)); mem = chunk2mem(p); check_malloced_chunk(gm, mem, nb); goto postaction; } else if (nb > gm->dvsize) { if (smallbits != 0) { /* Use chunk in next nonempty smallbin */ mchunkptr b, p, r; size_t rsize; bindex_t i; binmap_t leftbits = (smallbits << idx) & left_bits(idx2bit(idx)); binmap_t leastbit = least_bit(leftbits); compute_bit2idx(leastbit, i); b = smallbin_at(gm, i); p = b->fd; assert(chunksize(p) == small_index2size(i)); unlink_first_small_chunk(gm, b, p, i); rsize = small_index2size(i) - nb; /* Fit here cannot be remainderless if 4byte sizes */ if (SIZE_T_SIZE != 4 && rsize < MIN_CHUNK_SIZE) set_inuse_and_pinuse(gm, p, small_index2size(i)); else { set_size_and_pinuse_of_inuse_chunk(gm, p, nb); r = chunk_plus_offset(p, nb); set_size_and_pinuse_of_free_chunk(r, rsize); replace_dv(gm, r, rsize); } mem = chunk2mem(p); check_malloced_chunk(gm, mem, nb); goto postaction; } else if (gm->treemap != 0 && (mem = tmalloc_small(gm, nb)) != 0) { check_malloced_chunk(gm, mem, nb); goto postaction; } } } else if (bytes >= MAX_REQUEST) nb = MAX_SIZE_T; /* Too big to allocate. Force failure (in sys alloc) */ else { nb = pad_request(bytes); if (gm->treemap != 0 && (mem = tmalloc_large(gm, nb)) != 0) { check_malloced_chunk(gm, mem, nb); goto postaction; } } if (nb <= gm->dvsize) { size_t rsize = gm->dvsize - nb; mchunkptr p = gm->dv; if (rsize >= MIN_CHUNK_SIZE) { /* split dv */ mchunkptr r = gm->dv = chunk_plus_offset(p, nb); gm->dvsize = rsize; set_size_and_pinuse_of_free_chunk(r, rsize); set_size_and_pinuse_of_inuse_chunk(gm, p, nb); } else { /* exhaust dv */ size_t dvs = gm->dvsize; gm->dvsize = 0; gm->dv = 0; set_inuse_and_pinuse(gm, p, dvs); } mem = chunk2mem(p); check_malloced_chunk(gm, mem, nb); goto postaction; } else if (nb < gm->topsize) { /* Split top */ size_t rsize = gm->topsize -= nb; mchunkptr p = gm->top; mchunkptr r = gm->top = chunk_plus_offset(p, nb); r->head = rsize | PINUSE_BIT; set_size_and_pinuse_of_inuse_chunk(gm, p, nb); mem = chunk2mem(p); check_top_chunk(gm, gm->top); check_malloced_chunk(gm, mem, nb); goto postaction; } mem = sys_alloc(gm, nb); POSTACTION(gm); if (mem == MAP_FAILED && _weaken(__oom_hook)) { _weaken(__oom_hook)(bytes); } return mem; postaction: POSTACTION(gm); return mem; } return 0; } /* ---------------------------- free --------------------------- */ void dlfree(void* mem) { /* Consolidate freed chunks with preceeding or succeeding bordering free chunks, if they exist, and then place in a bin. Intermixed with special cases for top, dv, mmapped chunks, and usage errors. */ if (mem != 0) { mchunkptr p = mem2chunk(mem); #if FOOTERS mstate fm = get_mstate_for(p); if (!ok_magic(fm)) { USAGE_ERROR_ACTION(fm, p); return; } #else /* FOOTERS */ #define fm gm #endif /* FOOTERS */ if (!PREACTION(fm)) { check_inuse_chunk(fm, p); if (RTCHECK(ok_address(fm, p) && ok_inuse(p))) { size_t psize = chunksize(p); mchunkptr next = chunk_plus_offset(p, psize); if (!pinuse(p)) { size_t prevsize = p->prev_foot; if (is_mmapped(p)) { psize += prevsize + MMAP_FOOT_PAD; if (CALL_MUNMAP((char*)p - prevsize, psize) == 0) fm->footprint -= psize; goto postaction; } else { mchunkptr prev = chunk_minus_offset(p, prevsize); psize += prevsize; p = prev; if (RTCHECK(ok_address(fm, prev))) { /* consolidate backward */ if (p != fm->dv) { unlink_chunk(fm, p, prevsize); } else if ((next->head & INUSE_BITS) == INUSE_BITS) { fm->dvsize = psize; set_free_with_pinuse(p, psize, next); goto postaction; } } else goto erroraction; } } if (RTCHECK(ok_next(p, next) && ok_pinuse(next))) { if (!cinuse(next)) { /* consolidate forward */ if (next == fm->top) { size_t tsize = fm->topsize += psize; fm->top = p; p->head = tsize | PINUSE_BIT; if (p == fm->dv) { fm->dv = 0; fm->dvsize = 0; } if (should_trim(fm, tsize)) sys_trim(fm, 0); goto postaction; } else if (next == fm->dv) { size_t dsize = fm->dvsize += psize; fm->dv = p; set_size_and_pinuse_of_free_chunk(p, dsize); goto postaction; } else { size_t nsize = chunksize(next); psize += nsize; unlink_chunk(fm, next, nsize); set_size_and_pinuse_of_free_chunk(p, psize); if (p == fm->dv) { fm->dvsize = psize; goto postaction; } } } else set_free_with_pinuse(p, psize, next); if (is_small(psize)) { insert_small_chunk(fm, p, psize); check_free_chunk(fm, p); } else { tchunkptr tp = (tchunkptr)p; insert_large_chunk(fm, tp, psize); check_free_chunk(fm, p); if (--fm->release_checks == 0) release_unused_segments(fm); } goto postaction; } } erroraction: USAGE_ERROR_ACTION(fm, p); postaction: POSTACTION(fm); } } #if !FOOTERS #undef fm #endif /* FOOTERS */ } void* dlcalloc(size_t n_elements, size_t elem_size) { void* mem; size_t req = 0; if (ckd_mul(&req, n_elements, elem_size)) req = -1; mem = dlmalloc(req); if (mem != 0 && calloc_must_clear(mem2chunk(mem))) bzero(mem, req); return mem; } #endif /* !ONLY_MSPACES */ /* ------------ Internal support for realloc, memalign, etc -------------- */ /* Try to realloc; only in-place unless can_move true */ static mchunkptr try_realloc_chunk(mstate m, mchunkptr p, size_t nb, int can_move) { mchunkptr newp = 0; size_t oldsize = chunksize(p); mchunkptr next = chunk_plus_offset(p, oldsize); if (RTCHECK(ok_address(m, p) && ok_inuse(p) && ok_next(p, next) && ok_pinuse(next))) { if (is_mmapped(p)) { newp = mmap_resize(m, p, nb, can_move); } else if (oldsize >= nb) { /* already big enough */ size_t rsize = oldsize - nb; if (rsize >= MIN_CHUNK_SIZE) { /* split off remainder */ mchunkptr r = chunk_plus_offset(p, nb); set_inuse(m, p, nb); set_inuse(m, r, rsize); dispose_chunk(m, r, rsize); } newp = p; } else if (next == m->top) { /* extend into top */ if (oldsize + m->topsize > nb) { size_t newsize = oldsize + m->topsize; size_t newtopsize = newsize - nb; mchunkptr newtop = chunk_plus_offset(p, nb); set_inuse(m, p, nb); newtop->head = newtopsize |PINUSE_BIT; m->top = newtop; m->topsize = newtopsize; newp = p; } } else if (next == m->dv) { /* extend into dv */ size_t dvs = m->dvsize; if (oldsize + dvs >= nb) { size_t dsize = oldsize + dvs - nb; if (dsize >= MIN_CHUNK_SIZE) { mchunkptr r = chunk_plus_offset(p, nb); mchunkptr n = chunk_plus_offset(r, dsize); set_inuse(m, p, nb); set_size_and_pinuse_of_free_chunk(r, dsize); clear_pinuse(n); m->dvsize = dsize; m->dv = r; } else { /* exhaust dv */ size_t newsize = oldsize + dvs; set_inuse(m, p, newsize); m->dvsize = 0; m->dv = 0; } newp = p; } } else if (!cinuse(next)) { /* extend into next free chunk */ size_t nextsize = chunksize(next); if (oldsize + nextsize >= nb) { size_t rsize = oldsize + nextsize - nb; unlink_chunk(m, next, nextsize); if (rsize < MIN_CHUNK_SIZE) { size_t newsize = oldsize + nextsize; set_inuse(m, p, newsize); } else { mchunkptr r = chunk_plus_offset(p, nb); set_inuse(m, p, nb); set_inuse(m, r, rsize); dispose_chunk(m, r, rsize); } newp = p; } } } else { USAGE_ERROR_ACTION(m, chunk2mem(p)); } return newp; } static void* internal_memalign(mstate m, size_t alignment, size_t bytes) { void* mem = 0; if (alignment < MIN_CHUNK_SIZE) /* must be at least a minimum chunk size */ alignment = MIN_CHUNK_SIZE; /* alignment is 32+ bytes rounded up to nearest two power */ alignment = 2ul << _bsrl(MAX(MIN_CHUNK_SIZE, alignment) - 1); if (bytes >= MAX_REQUEST - alignment) { if (m != 0) { /* Test isn't needed but avoids compiler warning */ MALLOC_FAILURE_ACTION; } } else { size_t nb = request2size(bytes); size_t req = nb + alignment + MIN_CHUNK_SIZE - CHUNK_OVERHEAD; mem = internal_malloc(m, req); if (mem != 0) { mchunkptr p = mem2chunk(mem); if (PREACTION(m)) return 0; if ((((size_t)(mem)) & (alignment - 1)) != 0) { /* misaligned */ /* Find an aligned spot inside chunk. Since we need to give back leading space in a chunk of at least MIN_CHUNK_SIZE, if the first calculation places us at a spot with less than MIN_CHUNK_SIZE leader, we can move to the next aligned spot. We've allocated enough total room so that this is always possible. */ char* br = (char*)mem2chunk((size_t)(((size_t)((char*)mem + alignment - SIZE_T_ONE)) & -alignment)); char* pos = ((size_t)(br - (char*)(p)) >= MIN_CHUNK_SIZE)? br : br+alignment; mchunkptr newp = (mchunkptr)pos; size_t leadsize = pos - (char*)(p); size_t newsize = chunksize(p) - leadsize; if (is_mmapped(p)) { /* For mmapped chunks, just adjust offset */ newp->prev_foot = p->prev_foot + leadsize; newp->head = newsize; } else { /* Otherwise, give back leader, use the rest */ set_inuse(m, newp, newsize); set_inuse(m, p, leadsize); dispose_chunk(m, p, leadsize); } p = newp; } /* Give back spare room at the end */ if (!is_mmapped(p)) { size_t size = chunksize(p); if (size > nb + MIN_CHUNK_SIZE) { size_t remainder_size = size - nb; mchunkptr remainder = chunk_plus_offset(p, nb); set_inuse(m, p, nb); set_inuse(m, remainder, remainder_size); dispose_chunk(m, remainder, remainder_size); } } mem = chunk2mem(p); assert (chunksize(p) >= nb); assert(((size_t)mem & (alignment - 1)) == 0); check_inuse_chunk(m, p); POSTACTION(m); } } return mem; } /* Common support for independent_X routines, handling all of the combinations that can result. The opts arg has: bit 0 set if all elements are same size (using sizes[0]) bit 1 set if elements should be zeroed */ static void** ialloc(mstate m, size_t n_elements, size_t* sizes, int opts, void* chunks[]) { size_t element_size; /* chunksize of each element, if all same */ size_t contents_size; /* total size of elements */ size_t array_size; /* request size of pointer array */ void* mem; /* malloced aggregate space */ mchunkptr p; /* corresponding chunk */ size_t remainder_size; /* remaining bytes while splitting */ void** marray; /* either "chunks" or malloced ptr array */ mchunkptr array_chunk; /* chunk for malloced ptr array */ flag_t was_enabled; /* to disable mmap */ size_t size; size_t i; ensure_initialization(); /* compute array length, if needed */ if (chunks != 0) { if (n_elements == 0) return chunks; /* nothing to do */ marray = chunks; array_size = 0; } else { /* if empty req, must still return chunk representing empty array */ if (n_elements == 0) return (void**)internal_malloc(m, 0); marray = 0; array_size = request2size(n_elements * (sizeof(void*))); } /* compute total element size */ if (opts & 0x1) { /* all-same-size */ element_size = request2size(*sizes); contents_size = n_elements * element_size; } else { /* add up all the sizes */ element_size = 0; contents_size = 0; for (i = 0; i != n_elements; ++i) contents_size += request2size(sizes[i]); } size = contents_size + array_size; /* Allocate the aggregate chunk. First disable direct-mmapping so malloc won't use it, since we would not be able to later free/realloc space internal to a segregated mmap region. */ was_enabled = use_mmap(m); disable_mmap(m); mem = internal_malloc(m, size - CHUNK_OVERHEAD); if (was_enabled) enable_mmap(m); if (mem == 0) return 0; if (PREACTION(m)) return 0; p = mem2chunk(mem); remainder_size = chunksize(p); assert(!is_mmapped(p)); if (opts & 0x2) { /* optionally clear the elements */ bzero((size_t*)mem, remainder_size - SIZE_T_SIZE - array_size); } /* If not provided, allocate the pointer array as final part of chunk */ if (marray == 0) { size_t array_chunk_size; array_chunk = chunk_plus_offset(p, contents_size); array_chunk_size = remainder_size - contents_size; marray = (void**) (chunk2mem(array_chunk)); set_size_and_pinuse_of_inuse_chunk(m, array_chunk, array_chunk_size); remainder_size = contents_size; } /* split out elements */ for (i = 0; ; ++i) { marray[i] = chunk2mem(p); if (i != n_elements-1) { if (element_size != 0) size = element_size; else size = request2size(sizes[i]); remainder_size -= size; set_size_and_pinuse_of_inuse_chunk(m, p, size); p = chunk_plus_offset(p, size); } else { /* the final element absorbs any overallocation slop */ set_size_and_pinuse_of_inuse_chunk(m, p, remainder_size); break; } } #if DEBUG if (marray != chunks) { /* final element must have exactly exhausted chunk */ if (element_size != 0) { assert(remainder_size == element_size); } else { assert(remainder_size == request2size(sizes[i])); } check_inuse_chunk(m, mem2chunk(marray)); } for (i = 0; i != n_elements; ++i) check_inuse_chunk(m, mem2chunk(marray[i])); #endif /* DEBUG */ POSTACTION(m); return marray; } /* Try to free all pointers in the given array. Note: this could be made faster, by delaying consolidation, at the price of disabling some user integrity checks, We still optimize some consolidations by combining adjacent chunks before freeing, which will occur often if allocated with ialloc or the array is sorted. */ static size_t internal_bulk_free(mstate m, void* array[], size_t nelem) { size_t unfreed = 0; if (!PREACTION(m)) { void** a; void** fence = &(array[nelem]); for (a = array; a != fence; ++a) { void* mem = *a; if (mem != 0) { mchunkptr p = mem2chunk(mem); size_t psize = chunksize(p); #if FOOTERS if (get_mstate_for(p) != m) { ++unfreed; continue; } #endif check_inuse_chunk(m, p); *a = 0; if (RTCHECK(ok_address(m, p) && ok_inuse(p))) { void ** b = a + 1; /* try to merge with next chunk */ mchunkptr next = next_chunk(p); if (b != fence && *b == chunk2mem(next)) { size_t newsize = chunksize(next) + psize; set_inuse(m, p, newsize); *b = chunk2mem(p); } else dispose_chunk(m, p, psize); } else { CORRUPTION_ERROR_ACTION(m); break; } } } if (should_trim(m, m->topsize)) sys_trim(m, 0); POSTACTION(m); } return unfreed; } /* Traversal */ #if MALLOC_INSPECT_ALL static void internal_inspect_all(mstate m, void(*handler)(void *start, void *end, size_t used_bytes, void* callback_arg), void* arg) { if (is_initialized(m)) { mchunkptr top = m->top; msegmentptr s; for (s = &m->seg; s != 0; s = s->next) { mchunkptr q = align_as_chunk(s->base); while (segment_holds(s, q) && q->head != FENCEPOST_HEAD) { mchunkptr next = next_chunk(q); size_t sz = chunksize(q); size_t used; void* start; if (is_inuse(q)) { used = sz - CHUNK_OVERHEAD; /* must not be mmapped */ start = chunk2mem(q); } else { used = 0; if (is_small(sz)) { /* offset by possible bookkeeping */ start = (void*)((char*)q + sizeof(struct malloc_chunk)); } else { start = (void*)((char*)q + sizeof(struct malloc_tree_chunk)); } } if (start < (void*)next) /* skip if all space is bookkeeping */ handler(start, next, used, arg); if (q == top) break; q = next; } } } } #endif /* MALLOC_INSPECT_ALL */ /* ------------------ Exported realloc, memalign, etc -------------------- */ #if !ONLY_MSPACES void* dlrealloc(void* oldmem, size_t bytes) { void* mem = 0; if (oldmem == 0) { mem = dlmalloc(bytes); } else if (UNLIKELY(bytes >= MAX_REQUEST)) { MALLOC_FAILURE_ACTION; } #ifdef REALLOC_ZERO_BYTES_FREES else if (bytes == 0) { dlfree(oldmem); } #endif /* REALLOC_ZERO_BYTES_FREES */ else { size_t nb = request2size(bytes); mchunkptr oldp = mem2chunk(oldmem); #if ! FOOTERS mstate m = gm; #else /* FOOTERS */ mstate m = get_mstate_for(oldp); if (!ok_magic(m)) { USAGE_ERROR_ACTION(m, oldmem); return 0; } #endif /* FOOTERS */ if (!PREACTION(m)) { mchunkptr newp = try_realloc_chunk(m, oldp, nb, 1); POSTACTION(m); if (newp != 0) { check_inuse_chunk(m, newp); mem = chunk2mem(newp); } else { mem = internal_malloc(m, bytes); if (mem != 0) { size_t oc = chunksize(oldp) - overhead_for(oldp); memcpy(mem, oldmem, (oc < bytes)? oc : bytes); internal_free(m, oldmem); } } } } return mem; } void* dlrealloc_in_place(void* oldmem, size_t bytes) { void* mem = 0; if (oldmem != 0) { if (bytes >= MAX_REQUEST) { MALLOC_FAILURE_ACTION; } else { size_t nb = request2size(bytes); mchunkptr oldp = mem2chunk(oldmem); #if ! FOOTERS mstate m = gm; #else /* FOOTERS */ mstate m = get_mstate_for(oldp); if (!ok_magic(m)) { USAGE_ERROR_ACTION(m, oldmem); return 0; } #endif /* FOOTERS */ if (!PREACTION(m)) { mchunkptr newp = try_realloc_chunk(m, oldp, nb, 0); POSTACTION(m); if (newp == oldp) { check_inuse_chunk(m, newp); mem = oldmem; } } } } return mem; } void* dlmemalign(size_t alignment, size_t bytes) { if (alignment <= MALLOC_ALIGNMENT) { return dlmalloc(bytes); } return internal_memalign(gm, alignment, bytes); } #if USE_LOCKS void dlmalloc_atfork(void) { bzero(&gm->mutex, sizeof(gm->mutex)); bzero(&malloc_global_mutex, sizeof(malloc_global_mutex)); } #endif void** dlindependent_calloc(size_t n_elements, size_t elem_size, void* chunks[]) { size_t sz = elem_size; /* serves as 1-element array */ return ialloc(gm, n_elements, &sz, 3, chunks); } void** dlindependent_comalloc(size_t n_elements, size_t sizes[], void* chunks[]) { return ialloc(gm, n_elements, sizes, 0, chunks); } size_t dlbulk_free(void* array[], size_t nelem) { return internal_bulk_free(gm, array, nelem); } #if MALLOC_INSPECT_ALL void dlmalloc_inspect_all(void(*handler)(void *start, void *end, size_t used_bytes, void* callback_arg), void* arg) { ensure_initialization(); if (!PREACTION(gm)) { internal_inspect_all(gm, handler, arg); POSTACTION(gm); } } #endif /* MALLOC_INSPECT_ALL */ int dlmalloc_trim(size_t pad) { int result = 0; ensure_initialization(); if (!PREACTION(gm)) { result = sys_trim(gm, pad); POSTACTION(gm); } return result; } size_t dlmalloc_footprint(void) { return gm->footprint; } size_t dlmalloc_max_footprint(void) { return gm->max_footprint; } size_t dlmalloc_footprint_limit(void) { size_t maf = gm->footprint_limit; return maf == 0 ? MAX_SIZE_T : maf; } size_t dlmalloc_set_footprint_limit(size_t bytes) { size_t result; /* invert sense of 0 */ if (bytes == 0) result = granularity_align(1); /* Use minimal size */ if (bytes == MAX_SIZE_T) result = 0; /* disable */ else result = granularity_align(bytes); return gm->footprint_limit = result; } #if !NO_MALLINFO struct mallinfo dlmallinfo(void) { return internal_mallinfo(gm); } #endif /* NO_MALLINFO */ #if !NO_MALLOC_STATS void dlmalloc_stats() { internal_malloc_stats(gm); } #endif /* NO_MALLOC_STATS */ int dlmallopt(int param_number, int value) { return change_mparam(param_number, value); } size_t dlmalloc_usable_size(void* mem) { mchunkptr p; size_t bytes; if (mem) { p = mem2chunk(mem); if (is_inuse(p)) { bytes = chunksize(p) - overhead_for(p); } else { bytes = 0; } } else { bytes = 0; } return bytes; } #endif /* !ONLY_MSPACES */ /* ----------------------------- user mspaces ---------------------------- */ #if MSPACES #include "third_party/dlmalloc/mspaces.inc" #endif /* MSPACES */
028bf24fe7784afc884295171866bfd2f1af4f1e
3225f903ab65e9e242f250a02b3b74fc7e34b098
/third_party/libuip/net/rime/collect-neighbor.c
dae9289ea9570896f89e9589e10281d31d96526c
[ "MIT", "BSD-2-Clause" ]
permissive
timvideos/litex-buildenv
6f7657a0d2836f66bbc8ad29f89f1f975eda7832
fafb0f1c645a0d36ff4947686b4d2d8e3433f686
refs/heads/master
2022-06-04T18:02:22.567089
2022-05-21T15:21:25
2022-05-21T15:21:25
115,785,208
217
88
BSD-2-Clause
2022-05-21T15:21:26
2017-12-30T08:50:22
Python
UTF-8
C
false
false
12,924
c
collect-neighbor.c
/* * Copyright (c) 2006, Swedish Institute of Computer Science. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the Institute 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 INSTITUTE 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 INSTITUTE OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * This file is part of the Contiki operating system. * */ /** * \file * Radio neighborhood management * \author * Adam Dunkels <adam@sics.se> */ /** * \addtogroup rimeneighbor * @{ */ #include <limits.h> #include <stdio.h> #include "contiki.h" #include "lib/memb.h" #include "lib/list.h" #include "net/rime/collect-neighbor.h" #include "net/rime/collect.h" #ifdef COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS #define MAX_COLLECT_NEIGHBORS COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS #else /* COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS */ #define MAX_COLLECT_NEIGHBORS 8 #endif /* COLLECT_NEIGHBOR_CONF_MAX_COLLECT_NEIGHBORS */ #define RTMETRIC_MAX COLLECT_MAX_DEPTH MEMB(collect_neighbors_mem, struct collect_neighbor, MAX_COLLECT_NEIGHBORS); #define MAX_AGE 180 #define MAX_LE_AGE 10 #define PERIODIC_INTERVAL CLOCK_SECOND * 60 #define EXPECTED_CONGESTION_DURATION CLOCK_SECOND * 240 #define CONGESTION_PENALTY 8 * COLLECT_LINK_ESTIMATE_UNIT #define DEBUG 0 #if DEBUG #include <stdio.h> #define PRINTF(...) printf(__VA_ARGS__) #else #define PRINTF(...) #endif /*---------------------------------------------------------------------------*/ static void periodic(void *ptr) { struct collect_neighbor_list *neighbor_list; struct collect_neighbor *n; neighbor_list = ptr; /* Go through all collect_neighbors and increase their age. */ for(n = list_head(neighbor_list->list); n != NULL; n = list_item_next(n)) { n->age++; n->le_age++; } for(n = list_head(neighbor_list->list); n != NULL; n = list_item_next(n)) { if(n->le_age == MAX_LE_AGE) { collect_link_estimate_new(&n->le); n->le_age = 0; } if(n->age == MAX_AGE) { memb_free(&collect_neighbors_mem, n); list_remove(neighbor_list->list, n); n = list_head(neighbor_list->list); } } ctimer_set(&neighbor_list->periodic, PERIODIC_INTERVAL, periodic, neighbor_list); } /*---------------------------------------------------------------------------*/ void collect_neighbor_init(void) { static uint8_t initialized = 0; if(initialized == 0) { initialized = 1; memb_init(&collect_neighbors_mem); } } /*---------------------------------------------------------------------------*/ void collect_neighbor_list_new(struct collect_neighbor_list *neighbors_list) { LIST_STRUCT_INIT(neighbors_list, list); list_init(neighbors_list->list); ctimer_set(&neighbors_list->periodic, CLOCK_SECOND, periodic, neighbors_list); } /*---------------------------------------------------------------------------*/ struct collect_neighbor * collect_neighbor_list_find(struct collect_neighbor_list *neighbors_list, const linkaddr_t *addr) { struct collect_neighbor *n; if(neighbors_list == NULL) { return NULL; } for(n = list_head(neighbors_list->list); n != NULL; n = list_item_next(n)) { if(linkaddr_cmp(&n->addr, addr)) { return n; } } return NULL; } /*---------------------------------------------------------------------------*/ int collect_neighbor_list_add(struct collect_neighbor_list *neighbors_list, const linkaddr_t *addr, uint16_t nrtmetric) { struct collect_neighbor *n; if(addr == NULL) { PRINTF("collect_neighbor_list_add: attempt to add NULL addr\n"); return 0; } if(neighbors_list == NULL) { return 0; } PRINTF("collect_neighbor_add: adding %d.%d\n", addr->u8[0], addr->u8[1]); /* Check if the collect_neighbor is already on the list. */ for(n = list_head(neighbors_list->list); n != NULL; n = list_item_next(n)) { if(linkaddr_cmp(&n->addr, addr)) { PRINTF("collect_neighbor_add: already on list %d.%d\n", addr->u8[0], addr->u8[1]); break; } } /* If the collect_neighbor was not on the list, we try to allocate memory for it. */ if(n == NULL) { PRINTF("collect_neighbor_add: not on list, allocating %d.%d\n", addr->u8[0], addr->u8[1]); n = memb_alloc(&collect_neighbors_mem); if(n != NULL) { list_add(neighbors_list->list, n); } } /* If we could not allocate memory, we try to recycle an old neighbor. XXX Should also look for the one with the worst rtmetric (not link esimate). XXX Also make sure that we don't replace a neighbor with a neighbor that has a worse metric. */ if(n == NULL) { uint16_t worst_rtmetric; struct collect_neighbor *worst_neighbor; /* Find the neighbor that has the highest rtmetric. This is the neighbor that we are least likely to be using in the future. But we also need to make sure that the neighbor we are currently adding is not worst than the one we would be replacing. If so, we don't put the new neighbor on the list. */ worst_rtmetric = 0; worst_neighbor = NULL; for(n = list_head(neighbors_list->list); n != NULL; n = list_item_next(n)) { if(n->rtmetric > worst_rtmetric) { worst_neighbor = n; worst_rtmetric = n->rtmetric; } } /* Only add this new neighbor if its rtmetric is lower than the one it would replace. */ if(nrtmetric < worst_rtmetric) { n = worst_neighbor; } if(n != NULL) { PRINTF("collect_neighbor_add: not on list, not allocated, recycling %d.%d\n", n->addr.u8[0], n->addr.u8[1]); } } if(n != NULL) { n->age = 0; linkaddr_copy(&n->addr, addr); n->rtmetric = nrtmetric; collect_link_estimate_new(&n->le); n->le_age = 0; return 1; } return 0; } /*---------------------------------------------------------------------------*/ list_t collect_neighbor_list(struct collect_neighbor_list *neighbors_list) { if(neighbors_list == NULL) { return NULL; } return neighbors_list->list; } /*---------------------------------------------------------------------------*/ void collect_neighbor_list_remove(struct collect_neighbor_list *neighbors_list, const linkaddr_t *addr) { struct collect_neighbor *n; if(neighbors_list == NULL) { return; } n = collect_neighbor_list_find(neighbors_list, addr); if(n != NULL) { list_remove(neighbors_list->list, n); memb_free(&collect_neighbors_mem, n); } } /*---------------------------------------------------------------------------*/ struct collect_neighbor * collect_neighbor_list_best(struct collect_neighbor_list *neighbors_list) { int found; struct collect_neighbor *n, *best; uint16_t rtmetric; rtmetric = RTMETRIC_MAX; best = NULL; found = 0; if(neighbors_list == NULL) { return NULL; } /* PRINTF("%d: ", node_id);*/ PRINTF("collect_neighbor_best: "); /* Find the neighbor with the lowest rtmetric + linkt estimate. */ for(n = list_head(neighbors_list->list); n != NULL; n = list_item_next(n)) { PRINTF("%d.%d %d+%d=%d, ", n->addr.u8[0], n->addr.u8[1], n->rtmetric, collect_neighbor_link_estimate(n), collect_neighbor_rtmetric(n)); if(collect_neighbor_rtmetric_link_estimate(n) < rtmetric) { rtmetric = collect_neighbor_rtmetric_link_estimate(n); best = n; } } PRINTF("\n"); return best; } /*---------------------------------------------------------------------------*/ int collect_neighbor_list_num(struct collect_neighbor_list *neighbors_list) { if(neighbors_list == NULL) { return 0; } PRINTF("collect_neighbor_num %d\n", list_length(neighbors_list->list)); return list_length(neighbors_list->list); } /*---------------------------------------------------------------------------*/ struct collect_neighbor * collect_neighbor_list_get(struct collect_neighbor_list *neighbors_list, int num) { int i; struct collect_neighbor *n; if(neighbors_list == NULL) { return NULL; } PRINTF("collect_neighbor_get %d\n", num); i = 0; for(n = list_head(neighbors_list->list); n != NULL; n = list_item_next(n)) { if(i == num) { PRINTF("collect_neighbor_get found %d.%d\n", n->addr.u8[0], n->addr.u8[1]); return n; } i++; } return NULL; } /*---------------------------------------------------------------------------*/ void collect_neighbor_list_purge(struct collect_neighbor_list *neighbors_list) { if(neighbors_list == NULL) { return; } while(list_head(neighbors_list->list) != NULL) { memb_free(&collect_neighbors_mem, list_pop(neighbors_list->list)); } } /*---------------------------------------------------------------------------*/ void collect_neighbor_update_rtmetric(struct collect_neighbor *n, uint16_t rtmetric) { if(n != NULL) { PRINTF("%d.%d: collect_neighbor_update %d.%d rtmetric %d\n", linkaddr_node_addr.u8[0], linkaddr_node_addr.u8[1], n->addr.u8[0], n->addr.u8[1], rtmetric); n->rtmetric = rtmetric; n->age = 0; } } /*---------------------------------------------------------------------------*/ void collect_neighbor_tx_fail(struct collect_neighbor *n, uint16_t num_tx) { if(n == NULL) { return; } collect_link_estimate_update_tx_fail(&n->le, num_tx); n->le_age = 0; n->age = 0; } /*---------------------------------------------------------------------------*/ void collect_neighbor_tx(struct collect_neighbor *n, uint16_t num_tx) { if(n == NULL) { return; } collect_link_estimate_update_tx(&n->le, num_tx); n->le_age = 0; n->age = 0; } /*---------------------------------------------------------------------------*/ void collect_neighbor_rx(struct collect_neighbor *n) { if(n == NULL) { return; } collect_link_estimate_update_rx(&n->le); n->age = 0; } /*---------------------------------------------------------------------------*/ uint16_t collect_neighbor_link_estimate(struct collect_neighbor *n) { if(n == NULL) { return 0; } if(collect_neighbor_is_congested(n)) { /* printf("Congested %d.%d, sould return %d, returning %d\n", n->addr.u8[0], n->addr.u8[1], collect_link_estimate(&n->le), collect_link_estimate(&n->le) + CONGESTION_PENALTY);*/ return collect_link_estimate(&n->le) + CONGESTION_PENALTY; } else { return collect_link_estimate(&n->le); } } /*---------------------------------------------------------------------------*/ uint16_t collect_neighbor_rtmetric_link_estimate(struct collect_neighbor *n) { if(n == NULL) { return 0; } return n->rtmetric + collect_link_estimate(&n->le); } /*---------------------------------------------------------------------------*/ uint16_t collect_neighbor_rtmetric(struct collect_neighbor *n) { if(n == NULL) { return 0; } return n->rtmetric; } /*---------------------------------------------------------------------------*/ void collect_neighbor_set_congested(struct collect_neighbor *n) { if(n == NULL) { return; } timer_set(&n->congested_timer, EXPECTED_CONGESTION_DURATION); } /*---------------------------------------------------------------------------*/ int collect_neighbor_is_congested(struct collect_neighbor *n) { if(n == NULL) { return 0; } if(timer_expired(&n->congested_timer)) { return 0; } else { return 1; } } /*---------------------------------------------------------------------------*/ /** @} */
01c5c8009567facfec09e94c03756ae73109bb2e
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/mips/include/asm/sibyte/sb1250_smbus.h
3cb73e89bbbcf05d48ab2cd7e3ed461514f5d7dd
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
7,085
h
sb1250_smbus.h
/* ********************************************************************* * SB1250 Board Support Package * * SMBUS Constants File: sb1250_smbus.h * * This module contains constants and macros useful for * manipulating the SB1250's SMbus devices. * * SB1250 specification level: 10/21/02 * BCM1280 specification level: 11/24/03 * ********************************************************************* * * Copyright 2000,2001,2002,2003 * Broadcom Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of * the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA ********************************************************************* */ #ifndef _SB1250_SMBUS_H #define _SB1250_SMBUS_H #include <asm/sibyte/sb1250_defs.h> /* * SMBus Clock Frequency Register (Table 14-2) */ #define S_SMB_FREQ_DIV 0 #define M_SMB_FREQ_DIV _SB_MAKEMASK(13, S_SMB_FREQ_DIV) #define V_SMB_FREQ_DIV(x) _SB_MAKEVALUE(x, S_SMB_FREQ_DIV) #define K_SMB_FREQ_400KHZ 0x1F #define K_SMB_FREQ_100KHZ 0x7D #define K_SMB_FREQ_10KHZ 1250 #define S_SMB_CMD 0 #define M_SMB_CMD _SB_MAKEMASK(8, S_SMB_CMD) #define V_SMB_CMD(x) _SB_MAKEVALUE(x, S_SMB_CMD) /* * SMBus control register (Table 14-4) */ #define M_SMB_ERR_INTR _SB_MAKEMASK1(0) #define M_SMB_FINISH_INTR _SB_MAKEMASK1(1) #define S_SMB_DATA_OUT 4 #define M_SMB_DATA_OUT _SB_MAKEMASK1(S_SMB_DATA_OUT) #define V_SMB_DATA_OUT(x) _SB_MAKEVALUE(x, S_SMB_DATA_OUT) #define M_SMB_DATA_DIR _SB_MAKEMASK1(5) #define M_SMB_DATA_DIR_OUTPUT M_SMB_DATA_DIR #define M_SMB_CLK_OUT _SB_MAKEMASK1(6) #define M_SMB_DIRECT_ENABLE _SB_MAKEMASK1(7) /* * SMBus status registers (Table 14-5) */ #define M_SMB_BUSY _SB_MAKEMASK1(0) #define M_SMB_ERROR _SB_MAKEMASK1(1) #define M_SMB_ERROR_TYPE _SB_MAKEMASK1(2) #if SIBYTE_HDR_FEATURE(1250, PASS3) || SIBYTE_HDR_FEATURE(112x, PASS1) || SIBYTE_HDR_FEATURE_CHIP(1480) #define S_SMB_SCL_IN 5 #define M_SMB_SCL_IN _SB_MAKEMASK1(S_SMB_SCL_IN) #define V_SMB_SCL_IN(x) _SB_MAKEVALUE(x, S_SMB_SCL_IN) #define G_SMB_SCL_IN(x) _SB_GETVALUE(x, S_SMB_SCL_IN, M_SMB_SCL_IN) #endif /* 1250 PASS3 || 112x PASS1 || 1480 */ #define S_SMB_REF 6 #define M_SMB_REF _SB_MAKEMASK1(S_SMB_REF) #define V_SMB_REF(x) _SB_MAKEVALUE(x, S_SMB_REF) #define G_SMB_REF(x) _SB_GETVALUE(x, S_SMB_REF, M_SMB_REF) #define S_SMB_DATA_IN 7 #define M_SMB_DATA_IN _SB_MAKEMASK1(S_SMB_DATA_IN) #define V_SMB_DATA_IN(x) _SB_MAKEVALUE(x, S_SMB_DATA_IN) #define G_SMB_DATA_IN(x) _SB_GETVALUE(x, S_SMB_DATA_IN, M_SMB_DATA_IN) /* * SMBus Start/Command registers (Table 14-9) */ #define S_SMB_ADDR 0 #define M_SMB_ADDR _SB_MAKEMASK(7, S_SMB_ADDR) #define V_SMB_ADDR(x) _SB_MAKEVALUE(x, S_SMB_ADDR) #define G_SMB_ADDR(x) _SB_GETVALUE(x, S_SMB_ADDR, M_SMB_ADDR) #define M_SMB_QDATA _SB_MAKEMASK1(7) #define S_SMB_TT 8 #define M_SMB_TT _SB_MAKEMASK(3, S_SMB_TT) #define V_SMB_TT(x) _SB_MAKEVALUE(x, S_SMB_TT) #define G_SMB_TT(x) _SB_GETVALUE(x, S_SMB_TT, M_SMB_TT) #define K_SMB_TT_WR1BYTE 0 #define K_SMB_TT_WR2BYTE 1 #define K_SMB_TT_WR3BYTE 2 #define K_SMB_TT_CMD_RD1BYTE 3 #define K_SMB_TT_CMD_RD2BYTE 4 #define K_SMB_TT_RD1BYTE 5 #define K_SMB_TT_QUICKCMD 6 #define K_SMB_TT_EEPROMREAD 7 #define V_SMB_TT_WR1BYTE V_SMB_TT(K_SMB_TT_WR1BYTE) #define V_SMB_TT_WR2BYTE V_SMB_TT(K_SMB_TT_WR2BYTE) #define V_SMB_TT_WR3BYTE V_SMB_TT(K_SMB_TT_WR3BYTE) #define V_SMB_TT_CMD_RD1BYTE V_SMB_TT(K_SMB_TT_CMD_RD1BYTE) #define V_SMB_TT_CMD_RD2BYTE V_SMB_TT(K_SMB_TT_CMD_RD2BYTE) #define V_SMB_TT_RD1BYTE V_SMB_TT(K_SMB_TT_RD1BYTE) #define V_SMB_TT_QUICKCMD V_SMB_TT(K_SMB_TT_QUICKCMD) #define V_SMB_TT_EEPROMREAD V_SMB_TT(K_SMB_TT_EEPROMREAD) #define M_SMB_PEC _SB_MAKEMASK1(15) /* * SMBus Data Register (Table 14-6) and SMBus Extra Register (Table 14-7) */ #define S_SMB_LB 0 #define M_SMB_LB _SB_MAKEMASK(8, S_SMB_LB) #define V_SMB_LB(x) _SB_MAKEVALUE(x, S_SMB_LB) #define S_SMB_MB 8 #define M_SMB_MB _SB_MAKEMASK(8, S_SMB_MB) #define V_SMB_MB(x) _SB_MAKEVALUE(x, S_SMB_MB) /* * SMBus Packet Error Check register (Table 14-8) */ #define S_SPEC_PEC 0 #define M_SPEC_PEC _SB_MAKEMASK(8, S_SPEC_PEC) #define V_SPEC_MB(x) _SB_MAKEVALUE(x, S_SPEC_PEC) #if SIBYTE_HDR_FEATURE(1250, PASS2) || SIBYTE_HDR_FEATURE(112x, PASS1) || SIBYTE_HDR_FEATURE_CHIP(1480) #define S_SMB_CMDH 8 #define M_SMB_CMDH _SB_MAKEMASK(8, S_SMB_CMDH) #define V_SMB_CMDH(x) _SB_MAKEVALUE(x, S_SMB_CMDH) #define M_SMB_EXTEND _SB_MAKEMASK1(14) #define S_SMB_DFMT 8 #define M_SMB_DFMT _SB_MAKEMASK(3, S_SMB_DFMT) #define V_SMB_DFMT(x) _SB_MAKEVALUE(x, S_SMB_DFMT) #define G_SMB_DFMT(x) _SB_GETVALUE(x, S_SMB_DFMT, M_SMB_DFMT) #define K_SMB_DFMT_1BYTE 0 #define K_SMB_DFMT_2BYTE 1 #define K_SMB_DFMT_3BYTE 2 #define K_SMB_DFMT_4BYTE 3 #define K_SMB_DFMT_NODATA 4 #define K_SMB_DFMT_CMD4BYTE 5 #define K_SMB_DFMT_CMD5BYTE 6 #define K_SMB_DFMT_RESERVED 7 #define V_SMB_DFMT_1BYTE V_SMB_DFMT(K_SMB_DFMT_1BYTE) #define V_SMB_DFMT_2BYTE V_SMB_DFMT(K_SMB_DFMT_2BYTE) #define V_SMB_DFMT_3BYTE V_SMB_DFMT(K_SMB_DFMT_3BYTE) #define V_SMB_DFMT_4BYTE V_SMB_DFMT(K_SMB_DFMT_4BYTE) #define V_SMB_DFMT_NODATA V_SMB_DFMT(K_SMB_DFMT_NODATA) #define V_SMB_DFMT_CMD4BYTE V_SMB_DFMT(K_SMB_DFMT_CMD4BYTE) #define V_SMB_DFMT_CMD5BYTE V_SMB_DFMT(K_SMB_DFMT_CMD5BYTE) #define V_SMB_DFMT_RESERVED V_SMB_DFMT(K_SMB_DFMT_RESERVED) #define S_SMB_AFMT 11 #define M_SMB_AFMT _SB_MAKEMASK(2, S_SMB_AFMT) #define V_SMB_AFMT(x) _SB_MAKEVALUE(x, S_SMB_AFMT) #define G_SMB_AFMT(x) _SB_GETVALUE(x, S_SMB_AFMT, M_SMB_AFMT) #define K_SMB_AFMT_NONE 0 #define K_SMB_AFMT_ADDR 1 #define K_SMB_AFMT_ADDR_CMD1BYTE 2 #define K_SMB_AFMT_ADDR_CMD2BYTE 3 #define V_SMB_AFMT_NONE V_SMB_AFMT(K_SMB_AFMT_NONE) #define V_SMB_AFMT_ADDR V_SMB_AFMT(K_SMB_AFMT_ADDR) #define V_SMB_AFMT_ADDR_CMD1BYTE V_SMB_AFMT(K_SMB_AFMT_ADDR_CMD1BYTE) #define V_SMB_AFMT_ADDR_CMD2BYTE V_SMB_AFMT(K_SMB_AFMT_ADDR_CMD2BYTE) #define M_SMB_DIR _SB_MAKEMASK1(13) #endif /* 1250 PASS2 || 112x PASS1 || 1480 */ #endif
49e4cd99b8ee0c0471b57082fba8c6cd7c8103d5
e48198ffea7b0b80669253fb970fdcc1d2f4c518
/src/ops.c
d46a049fe4e790715fb79f1164f8f650bd368e25
[ "GPL-1.0-or-later", "Vim", "GPL-2.0-only" ]
permissive
vim/vim
f9ea5913ff884c87bc11f7826b1fc277fba8a2b5
816fbcc262687b81fc46f82f7bbeb1453addfe0c
refs/heads/master
2023-09-01T16:01:56.964678
2023-08-31T21:52:30
2023-08-31T21:52:30
40,997,482
37,589
7,920
Vim
2023-09-14T20:57:43
2015-08-18T21:03:56
Vim Script
UTF-8
C
false
false
114,203
c
ops.c
/* vi:set ts=8 sts=4 sw=4 noet: * * VIM - Vi IMproved by Bram Moolenaar * * Do ":help uganda" in Vim to read copying and usage conditions. * Do ":help credits" in Vim to see a list of people who contributed. * See README.txt for an overview of the Vim source code. */ /* * ops.c: implementation of various operators: op_shift, op_delete, op_tilde, * op_change, op_yank, do_join */ #include "vim.h" static void shift_block(oparg_T *oap, int amount); static void mb_adjust_opend(oparg_T *oap); static int do_addsub(int op_type, pos_T *pos, int length, linenr_T Prenum1); // Flags for third item in "opchars". #define OPF_LINES 1 // operator always works on lines #define OPF_CHANGE 2 // operator changes text /* * The names of operators. * IMPORTANT: Index must correspond with defines in vim.h!!! * The third field holds OPF_ flags. */ static char opchars[][3] = { {NUL, NUL, 0}, // OP_NOP {'d', NUL, OPF_CHANGE}, // OP_DELETE {'y', NUL, 0}, // OP_YANK {'c', NUL, OPF_CHANGE}, // OP_CHANGE {'<', NUL, OPF_LINES | OPF_CHANGE}, // OP_LSHIFT {'>', NUL, OPF_LINES | OPF_CHANGE}, // OP_RSHIFT {'!', NUL, OPF_LINES | OPF_CHANGE}, // OP_FILTER {'g', '~', OPF_CHANGE}, // OP_TILDE {'=', NUL, OPF_LINES | OPF_CHANGE}, // OP_INDENT {'g', 'q', OPF_LINES | OPF_CHANGE}, // OP_FORMAT {':', NUL, OPF_LINES}, // OP_COLON {'g', 'U', OPF_CHANGE}, // OP_UPPER {'g', 'u', OPF_CHANGE}, // OP_LOWER {'J', NUL, OPF_LINES | OPF_CHANGE}, // DO_JOIN {'g', 'J', OPF_LINES | OPF_CHANGE}, // DO_JOIN_NS {'g', '?', OPF_CHANGE}, // OP_ROT13 {'r', NUL, OPF_CHANGE}, // OP_REPLACE {'I', NUL, OPF_CHANGE}, // OP_INSERT {'A', NUL, OPF_CHANGE}, // OP_APPEND {'z', 'f', OPF_LINES}, // OP_FOLD {'z', 'o', OPF_LINES}, // OP_FOLDOPEN {'z', 'O', OPF_LINES}, // OP_FOLDOPENREC {'z', 'c', OPF_LINES}, // OP_FOLDCLOSE {'z', 'C', OPF_LINES}, // OP_FOLDCLOSEREC {'z', 'd', OPF_LINES}, // OP_FOLDDEL {'z', 'D', OPF_LINES}, // OP_FOLDDELREC {'g', 'w', OPF_LINES | OPF_CHANGE}, // OP_FORMAT2 {'g', '@', OPF_CHANGE}, // OP_FUNCTION {Ctrl_A, NUL, OPF_CHANGE}, // OP_NR_ADD {Ctrl_X, NUL, OPF_CHANGE}, // OP_NR_SUB }; /* * Translate a command name into an operator type. * Must only be called with a valid operator name! */ int get_op_type(int char1, int char2) { int i; if (char1 == 'r') // ignore second character return OP_REPLACE; if (char1 == '~') // when tilde is an operator return OP_TILDE; if (char1 == 'g' && char2 == Ctrl_A) // add return OP_NR_ADD; if (char1 == 'g' && char2 == Ctrl_X) // subtract return OP_NR_SUB; if (char1 == 'z' && char2 == 'y') // OP_YANK return OP_YANK; for (i = 0; ; ++i) { if (opchars[i][0] == char1 && opchars[i][1] == char2) break; if (i == (int)ARRAY_LENGTH(opchars) - 1) { internal_error("get_op_type()"); break; } } return i; } /* * Return TRUE if operator "op" always works on whole lines. */ static int op_on_lines(int op) { return opchars[op][2] & OPF_LINES; } #if defined(FEAT_JOB_CHANNEL) || defined(PROTO) /* * Return TRUE if operator "op" changes text. */ int op_is_change(int op) { return opchars[op][2] & OPF_CHANGE; } #endif /* * Get first operator command character. * Returns 'g' or 'z' if there is another command character. */ int get_op_char(int optype) { return opchars[optype][0]; } /* * Get second operator command character. */ int get_extra_op_char(int optype) { return opchars[optype][1]; } /* * op_shift - handle a shift operation */ void op_shift(oparg_T *oap, int curs_top, int amount) { long i; int first_char; int block_col = 0; if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) return; if (oap->block_mode) block_col = curwin->w_cursor.col; for (i = oap->line_count; --i >= 0; ) { first_char = *ml_get_curline(); if (first_char == NUL) // empty line curwin->w_cursor.col = 0; else if (oap->block_mode) shift_block(oap, amount); else // Move the line right if it doesn't start with '#', 'smartindent' // isn't set or 'cindent' isn't set or '#' isn't in 'cino'. if (first_char != '#' || !preprocs_left()) shift_line(oap->op_type == OP_LSHIFT, p_sr, amount, FALSE); ++curwin->w_cursor.lnum; } changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L); if (oap->block_mode) { curwin->w_cursor.lnum = oap->start.lnum; curwin->w_cursor.col = block_col; } else if (curs_top) // put cursor on first line, for ">>" { curwin->w_cursor.lnum = oap->start.lnum; beginline(BL_SOL | BL_FIX); // shift_line() may have set cursor.col } else --curwin->w_cursor.lnum; // put cursor on last line, for ":>" #ifdef FEAT_FOLDING // The cursor line is not in a closed fold foldOpenCursor(); #endif if (oap->line_count > p_report) { char *op; char *msg_line_single; char *msg_line_plural; if (oap->op_type == OP_RSHIFT) op = ">"; else op = "<"; msg_line_single = NGETTEXT("%ld line %sed %d time", "%ld line %sed %d times", amount); msg_line_plural = NGETTEXT("%ld lines %sed %d time", "%ld lines %sed %d times", amount); vim_snprintf((char *)IObuff, IOSIZE, NGETTEXT(msg_line_single, msg_line_plural, oap->line_count), oap->line_count, op, amount); msg_attr_keep((char *)IObuff, 0, TRUE); } if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set "'[" and "']" marks. curbuf->b_op_start = oap->start; curbuf->b_op_end.lnum = oap->end.lnum; curbuf->b_op_end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); if (curbuf->b_op_end.col > 0) --curbuf->b_op_end.col; } } /* * Shift the current line one shiftwidth left (if left != 0) or right * leaves cursor on first blank in the line. */ void shift_line( int left, int round, int amount, int call_changed_bytes) // call changed_bytes() { int count; int i, j; int sw_val = (int)get_sw_value_indent(curbuf); count = get_indent(); // get current indent if (round) // round off indent { i = count / sw_val; // number of 'shiftwidth' rounded down j = count % sw_val; // extra spaces if (j && left) // first remove extra spaces --amount; if (left) { i -= amount; if (i < 0) i = 0; } else i += amount; count = i * sw_val; } else // original vi indent { if (left) { count -= sw_val * amount; if (count < 0) count = 0; } else count += sw_val * amount; } // Set new indent if (State & VREPLACE_FLAG) change_indent(INDENT_SET, count, FALSE, NUL, call_changed_bytes); else (void)set_indent(count, call_changed_bytes ? SIN_CHANGED : 0); } /* * Shift one line of the current block one shiftwidth right or left. * Leaves cursor on first character in block. */ static void shift_block(oparg_T *oap, int amount) { int left = (oap->op_type == OP_LSHIFT); int oldstate = State; int total; char_u *newp, *oldp; int oldcol = curwin->w_cursor.col; int sw_val = (int)get_sw_value_indent(curbuf); int ts_val = (int)curbuf->b_p_ts; struct block_def bd; int incr; colnr_T ws_vcol; int added; unsigned new_line_len; // the length of the line after the // block shift #ifdef FEAT_RIGHTLEFT int old_p_ri = p_ri; p_ri = 0; // don't want revins in indent #endif State = MODE_INSERT; // don't want MODE_REPLACE for State block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE); if (bd.is_short) return; // total is number of screen columns to be inserted/removed total = (int)((unsigned)amount * (unsigned)sw_val); if ((total / sw_val) != amount) return; // multiplication overflow oldp = ml_get_curline(); if (!left) { int tabs = 0, spaces = 0; chartabsize_T cts; /* * 1. Get start vcol * 2. Total ws vcols * 3. Divvy into TABs & spp * 4. Construct new string */ total += bd.pre_whitesp; // all virtual WS up to & incl a split TAB ws_vcol = bd.start_vcol - bd.pre_whitesp; if (bd.startspaces) { if (has_mbyte) { if ((*mb_ptr2len)(bd.textstart) == 1) ++bd.textstart; else { ws_vcol = 0; bd.startspaces = 0; } } else ++bd.textstart; } // TODO: is passing bd.textstart for start of the line OK? init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, bd.start_vcol, bd.textstart, bd.textstart); for ( ; VIM_ISWHITE(*cts.cts_ptr); ) { incr = lbr_chartabsize_adv(&cts); total += incr; cts.cts_vcol += incr; } bd.textstart = cts.cts_ptr; bd.start_vcol = cts.cts_vcol; clear_chartabsize_arg(&cts); // OK, now total=all the VWS reqd, and textstart points at the 1st // non-ws char in the block. #ifdef FEAT_VARTABS if (!curbuf->b_p_et) tabstop_fromto(ws_vcol, ws_vcol + total, ts_val, curbuf->b_p_vts_array, &tabs, &spaces); else spaces = total; #else if (!curbuf->b_p_et) tabs = ((ws_vcol % ts_val) + total) / ts_val; // number of tabs if (tabs > 0) spaces = ((ws_vcol % ts_val) + total) % ts_val; // number of spp else spaces = total; #endif // if we're splitting a TAB, allow for it bd.textcol -= bd.pre_whitesp_c - (bd.startspaces != 0); new_line_len = bd.textcol + tabs + spaces + (int)STRLEN(bd.textstart); newp = alloc(new_line_len + 1); if (newp == NULL) return; mch_memmove(newp, oldp, (size_t)bd.textcol); vim_memset(newp + bd.textcol, TAB, (size_t)tabs); vim_memset(newp + bd.textcol + tabs, ' ', (size_t)spaces); // Note that STRMOVE() copies the trailing NUL. STRMOVE(newp + bd.textcol + tabs + spaces, bd.textstart); } else // left { colnr_T destination_col; // column to which text in block will // be shifted char_u *verbatim_copy_end; // end of the part of the line which is // copied verbatim colnr_T verbatim_copy_width;// the (displayed) width of this part // of line unsigned fill; // nr of spaces that replace a TAB size_t block_space_width; size_t shift_amount; char_u *non_white = bd.textstart; colnr_T non_white_col; chartabsize_T cts; /* * Firstly, let's find the first non-whitespace character that is * displayed after the block's start column and the character's column * number. Also, let's calculate the width of all the whitespace * characters that are displayed in the block and precede the searched * non-whitespace character. */ // If "bd.startspaces" is set, "bd.textstart" points to the character, // the part of which is displayed at the block's beginning. Let's start // searching from the next character. if (bd.startspaces) MB_PTR_ADV(non_white); // The character's column is in "bd.start_vcol". non_white_col = bd.start_vcol; init_chartabsize_arg(&cts, curwin, curwin->w_cursor.lnum, non_white_col, bd.textstart, non_white); while (VIM_ISWHITE(*cts.cts_ptr)) { incr = lbr_chartabsize_adv(&cts); cts.cts_vcol += incr; } non_white_col = cts.cts_vcol; non_white = cts.cts_ptr; clear_chartabsize_arg(&cts); block_space_width = non_white_col - oap->start_vcol; // We will shift by "total" or "block_space_width", whichever is less. shift_amount = (block_space_width < (size_t)total ? block_space_width : (size_t)total); // The column to which we will shift the text. destination_col = (colnr_T)(non_white_col - shift_amount); // Now let's find out how much of the beginning of the line we can // reuse without modification. verbatim_copy_end = bd.textstart; verbatim_copy_width = bd.start_vcol; // If "bd.startspaces" is set, "bd.textstart" points to the character // preceding the block. We have to subtract its width to obtain its // column number. if (bd.startspaces) verbatim_copy_width -= bd.start_char_vcols; init_chartabsize_arg(&cts, curwin, 0, verbatim_copy_width, bd.textstart, verbatim_copy_end); while (cts.cts_vcol < destination_col) { incr = lbr_chartabsize(&cts); if (cts.cts_vcol + incr > destination_col) break; cts.cts_vcol += incr; MB_PTR_ADV(cts.cts_ptr); } verbatim_copy_width = cts.cts_vcol; verbatim_copy_end = cts.cts_ptr; clear_chartabsize_arg(&cts); // If "destination_col" is different from the width of the initial // part of the line that will be copied, it means we encountered a tab // character, which we will have to partly replace with spaces. fill = destination_col - verbatim_copy_width; // The replacement line will consist of: // - the beginning of the original line up to "verbatim_copy_end", // - "fill" number of spaces, // - the rest of the line, pointed to by non_white. new_line_len = (unsigned)(verbatim_copy_end - oldp) + fill + (unsigned)STRLEN(non_white); newp = alloc(new_line_len + 1); if (newp == NULL) return; mch_memmove(newp, oldp, (size_t)(verbatim_copy_end - oldp)); vim_memset(newp + (verbatim_copy_end - oldp), ' ', (size_t)fill); // Note that STRMOVE() copies the trailing NUL. STRMOVE(newp + (verbatim_copy_end - oldp) + fill, non_white); } // replace the line added = new_line_len - (int)STRLEN(oldp); ml_replace(curwin->w_cursor.lnum, newp, FALSE); inserted_bytes(curwin->w_cursor.lnum, bd.textcol, added); State = oldstate; curwin->w_cursor.col = oldcol; #ifdef FEAT_RIGHTLEFT p_ri = old_p_ri; #endif } /* * Insert string "s" (b_insert ? before : after) block :AKelly * Caller must prepare for undo. */ static void block_insert( oparg_T *oap, char_u *s, int b_insert, struct block_def *bdp) { int ts_val; int count = 0; // extra spaces to replace a cut TAB int spaces = 0; // non-zero if cutting a TAB colnr_T offset; // pointer along new line colnr_T startcol; // column where insert starts unsigned s_len; // STRLEN(s) char_u *newp, *oldp; // new, old lines linenr_T lnum; // loop var int oldstate = State; State = MODE_INSERT; // don't want MODE_REPLACE for State s_len = (unsigned)STRLEN(s); for (lnum = oap->start.lnum + 1; lnum <= oap->end.lnum; lnum++) { block_prep(oap, bdp, lnum, TRUE); if (bdp->is_short && b_insert) continue; // OP_INSERT, line ends before block start oldp = ml_get(lnum); if (b_insert) { ts_val = bdp->start_char_vcols; spaces = bdp->startspaces; if (spaces != 0) count = ts_val - 1; // we're cutting a TAB offset = bdp->textcol; } else // append { ts_val = bdp->end_char_vcols; if (!bdp->is_short) // spaces = padding after block { spaces = (bdp->endspaces ? ts_val - bdp->endspaces : 0); if (spaces != 0) count = ts_val - 1; // we're cutting a TAB offset = bdp->textcol + bdp->textlen - (spaces != 0); } else // spaces = padding to block edge { // if $ used, just append to EOL (ie spaces==0) if (!bdp->is_MAX) spaces = (oap->end_vcol - bdp->end_vcol) + 1; count = spaces; offset = bdp->textcol + bdp->textlen; } } if (has_mbyte && spaces > 0) // avoid copying part of a multi-byte character offset -= (*mb_head_off)(oldp, oldp + offset); if (spaces < 0) // can happen when the cursor was moved spaces = 0; // Make sure the allocated size matches what is actually copied below. newp = alloc(STRLEN(oldp) + spaces + s_len + (spaces > 0 && !bdp->is_short ? ts_val - spaces : 0) + count + 1); if (newp == NULL) continue; // copy up to shifted part mch_memmove(newp, oldp, (size_t)offset); oldp += offset; // insert pre-padding vim_memset(newp + offset, ' ', (size_t)spaces); startcol = offset + spaces; // copy the new text mch_memmove(newp + startcol, s, (size_t)s_len); offset += s_len; if (spaces > 0 && !bdp->is_short) { if (*oldp == TAB) { // insert post-padding vim_memset(newp + offset + spaces, ' ', (size_t)(ts_val - spaces)); // we're splitting a TAB, don't copy it oldp++; // We allowed for that TAB, remember this now count++; } else // Not a TAB, no extra spaces count = spaces; } if (spaces > 0) offset += count; STRMOVE(newp + offset, oldp); ml_replace(lnum, newp, FALSE); if (b_insert) // correct any text properties inserted_bytes(lnum, startcol, s_len); if (lnum == oap->end.lnum) { // Set "']" mark to the end of the block instead of the end of // the insert in the first line. curbuf->b_op_end.lnum = oap->end.lnum; curbuf->b_op_end.col = offset; } } // for all lnum changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L); State = oldstate; } /* * Handle a delete operation. * * Return FAIL if undo failed, OK otherwise. */ int op_delete(oparg_T *oap) { int n; linenr_T lnum; char_u *ptr; char_u *newp, *oldp; struct block_def bd; linenr_T old_lcount = curbuf->b_ml.ml_line_count; int did_yank = FALSE; if (curbuf->b_ml.ml_flags & ML_EMPTY) // nothing to do return OK; // Nothing to delete, return here. Do prepare undo, for op_change(). if (oap->empty) return u_save_cursor(); if (!curbuf->b_p_ma) { emsg(_(e_cannot_make_changes_modifiable_is_off)); return FAIL; } if (VIsual_select && oap->is_VIsual) // use register given with CTRL_R, defaults to zero oap->regname = VIsual_select_reg; #ifdef FEAT_CLIPBOARD adjust_clip_reg(&oap->regname); #endif if (has_mbyte) mb_adjust_opend(oap); /* * Imitate the strange Vi behaviour: If the delete spans more than one * line and motion_type == MCHAR and the result is a blank line, make the * delete linewise. Don't do this for the change command or Visual mode. */ if ( oap->motion_type == MCHAR && !oap->is_VIsual && !oap->block_mode && oap->line_count > 1 && oap->motion_force == NUL && oap->op_type == OP_DELETE) { ptr = ml_get(oap->end.lnum) + oap->end.col; if (*ptr != NUL) ptr += oap->inclusive; ptr = skipwhite(ptr); if (*ptr == NUL && inindent(0)) oap->motion_type = MLINE; } /* * Check for trying to delete (e.g. "D") in an empty line. * Note: For the change operator it is ok. */ if ( oap->motion_type == MCHAR && oap->line_count == 1 && oap->op_type == OP_DELETE && *ml_get(oap->start.lnum) == NUL) { /* * It's an error to operate on an empty region, when 'E' included in * 'cpoptions' (Vi compatible). */ if (virtual_op) // Virtual editing: Nothing gets deleted, but we set the '[ and '] // marks as if it happened. goto setmarks; if (vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL) beep_flush(); return OK; } /* * Do a yank of whatever we're about to delete. * If a yank register was specified, put the deleted text into that * register. For the black hole register '_' don't yank anything. */ if (oap->regname != '_') { if (oap->regname != 0) { // check for read-only register if (!valid_yank_reg(oap->regname, TRUE)) { beep_flush(); return OK; } get_yank_register(oap->regname, TRUE); // yank into specif'd reg. if (op_yank(oap, TRUE, FALSE) == OK) // yank without message did_yank = TRUE; } else reset_y_append(); // not appending to unnamed register /* * Put deleted text into register 1 and shift number registers if the * delete contains a line break, or when using a specific operator (Vi * compatible) */ if (oap->motion_type == MLINE || oap->line_count > 1 || oap->use_reg_one) { shift_delete_registers(); if (op_yank(oap, TRUE, FALSE) == OK) did_yank = TRUE; } // Yank into small delete register when no named register specified // and the delete is within one line. if (( #ifdef FEAT_CLIPBOARD ((clip_unnamed & CLIP_UNNAMED) && oap->regname == '*') || ((clip_unnamed & CLIP_UNNAMED_PLUS) && oap->regname == '+') || #endif oap->regname == 0) && oap->motion_type != MLINE && oap->line_count == 1) { oap->regname = '-'; get_yank_register(oap->regname, TRUE); if (op_yank(oap, TRUE, FALSE) == OK) did_yank = TRUE; oap->regname = 0; } /* * If there's too much stuff to fit in the yank register, then get a * confirmation before doing the delete. This is crude, but simple. * And it avoids doing a delete of something we can't put back if we * want. */ if (!did_yank) { int msg_silent_save = msg_silent; msg_silent = 0; // must display the prompt n = ask_yesno((char_u *)_("cannot yank; delete anyway"), TRUE); msg_silent = msg_silent_save; if (n != 'y') { emsg(_(e_command_aborted)); return FAIL; } } #if defined(FEAT_EVAL) if (did_yank && has_textyankpost()) yank_do_autocmd(oap, get_y_current()); #endif } /* * block mode delete */ if (oap->block_mode) { if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) return FAIL; for (lnum = curwin->w_cursor.lnum; lnum <= oap->end.lnum; ++lnum) { block_prep(oap, &bd, lnum, TRUE); if (bd.textlen == 0) // nothing to delete continue; // Adjust cursor position for tab replaced by spaces and 'lbr'. if (lnum == curwin->w_cursor.lnum) { curwin->w_cursor.col = bd.textcol + bd.startspaces; curwin->w_cursor.coladd = 0; } // "n" == number of chars deleted // If we delete a TAB, it may be replaced by several characters. // Thus the number of characters may increase! n = bd.textlen - bd.startspaces - bd.endspaces; oldp = ml_get(lnum); newp = alloc(STRLEN(oldp) + 1 - n); if (newp == NULL) continue; // copy up to deleted part mch_memmove(newp, oldp, (size_t)bd.textcol); // insert spaces vim_memset(newp + bd.textcol, ' ', (size_t)(bd.startspaces + bd.endspaces)); // copy the part after the deleted part oldp += bd.textcol + bd.textlen; STRMOVE(newp + bd.textcol + bd.startspaces + bd.endspaces, oldp); // replace the line ml_replace(lnum, newp, FALSE); #ifdef FEAT_PROP_POPUP if (curbuf->b_has_textprop && n != 0) adjust_prop_columns(lnum, bd.textcol, -n, 0); #endif } check_cursor_col(); changed_lines(curwin->w_cursor.lnum, curwin->w_cursor.col, oap->end.lnum + 1, 0L); oap->line_count = 0; // no lines deleted } else if (oap->motion_type == MLINE) { if (oap->op_type == OP_CHANGE) { // Delete the lines except the first one. Temporarily move the // cursor to the next line. Save the current line number, if the // last line is deleted it may be changed. if (oap->line_count > 1) { lnum = curwin->w_cursor.lnum; ++curwin->w_cursor.lnum; del_lines((long)(oap->line_count - 1), TRUE); curwin->w_cursor.lnum = lnum; } if (u_save_cursor() == FAIL) return FAIL; if (curbuf->b_p_ai) // don't delete indent { beginline(BL_WHITE); // cursor on first non-white did_ai = TRUE; // delete the indent when ESC hit ai_col = curwin->w_cursor.col; } else beginline(0); // cursor in column 0 truncate_line(FALSE); // delete the rest of the line // leave cursor past last char in line if (oap->line_count > 1) u_clearline(); // "U" command not possible after "2cc" } else { del_lines(oap->line_count, TRUE); beginline(BL_WHITE | BL_FIX); u_clearline(); // "U" command not possible after "dd" } } else { if (virtual_op) { int endcol = 0; // For virtualedit: break the tabs that are partly included. if (gchar_pos(&oap->start) == '\t') { if (u_save_cursor() == FAIL) // save first line for undo return FAIL; if (oap->line_count == 1) endcol = getviscol2(oap->end.col, oap->end.coladd); coladvance_force(getviscol2(oap->start.col, oap->start.coladd)); oap->start = curwin->w_cursor; if (oap->line_count == 1) { coladvance(endcol); oap->end.col = curwin->w_cursor.col; oap->end.coladd = curwin->w_cursor.coladd; curwin->w_cursor = oap->start; } } // Break a tab only when it's included in the area. if (gchar_pos(&oap->end) == '\t' && (int)oap->end.coladd < oap->inclusive) { // save last line for undo if (u_save((linenr_T)(oap->end.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) return FAIL; curwin->w_cursor = oap->end; coladvance_force(getviscol2(oap->end.col, oap->end.coladd)); oap->end = curwin->w_cursor; curwin->w_cursor = oap->start; } if (has_mbyte) mb_adjust_opend(oap); } if (oap->line_count == 1) // delete characters within one line { if (u_save_cursor() == FAIL) // save line for undo return FAIL; // if 'cpoptions' contains '$', display '$' at end of change if ( vim_strchr(p_cpo, CPO_DOLLAR) != NULL && oap->op_type == OP_CHANGE && oap->end.lnum == curwin->w_cursor.lnum && !oap->is_VIsual) display_dollar(oap->end.col - !oap->inclusive); n = oap->end.col - oap->start.col + 1 - !oap->inclusive; if (virtual_op) { // fix up things for virtualedit-delete: // break the tabs which are going to get in our way char_u *curline = ml_get_curline(); int len = (int)STRLEN(curline); if (oap->end.coladd != 0 && (int)oap->end.col >= len - 1 && !(oap->start.coladd && (int)oap->end.col >= len - 1)) n++; // Delete at least one char (e.g, when on a control char). if (n == 0 && oap->start.coladd != oap->end.coladd) n = 1; // When deleted a char in the line, reset coladd. if (gchar_cursor() != NUL) curwin->w_cursor.coladd = 0; } (void)del_bytes((long)n, !virtual_op, oap->op_type == OP_DELETE && !oap->is_VIsual); } else // delete characters between lines { pos_T curpos; // save deleted and changed lines for undo if (u_save((linenr_T)(curwin->w_cursor.lnum - 1), (linenr_T)(curwin->w_cursor.lnum + oap->line_count)) == FAIL) return FAIL; truncate_line(TRUE); // delete from cursor to end of line curpos = curwin->w_cursor; // remember curwin->w_cursor ++curwin->w_cursor.lnum; del_lines((long)(oap->line_count - 2), FALSE); // delete from start of line until op_end n = (oap->end.col + 1 - !oap->inclusive); curwin->w_cursor.col = 0; (void)del_bytes((long)n, !virtual_op, oap->op_type == OP_DELETE && !oap->is_VIsual); curwin->w_cursor = curpos; // restore curwin->w_cursor (void)do_join(2, FALSE, FALSE, FALSE, FALSE); } if (oap->op_type == OP_DELETE) auto_format(FALSE, TRUE); } msgmore(curbuf->b_ml.ml_line_count - old_lcount); setmarks: if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { if (oap->block_mode) { curbuf->b_op_end.lnum = oap->end.lnum; curbuf->b_op_end.col = oap->start.col; } else curbuf->b_op_end = oap->start; curbuf->b_op_start = oap->start; } return OK; } /* * Adjust end of operating area for ending on a multi-byte character. * Used for deletion. */ static void mb_adjust_opend(oparg_T *oap) { char_u *p; if (!oap->inclusive) return; p = ml_get(oap->end.lnum); oap->end.col += mb_tail_off(p, p + oap->end.col); } /* * Replace the character under the cursor with "c". * This takes care of multi-byte characters. */ static void replace_character(int c) { int n = State; State = MODE_REPLACE; ins_char(c); State = n; // Backup to the replaced character. dec_cursor(); } /* * Replace a whole area with one character. */ int op_replace(oparg_T *oap, int c) { int n, numc; int num_chars; char_u *newp, *oldp; size_t oldlen; struct block_def bd; char_u *after_p = NULL; int had_ctrl_v_cr = FALSE; if ((curbuf->b_ml.ml_flags & ML_EMPTY ) || oap->empty) return OK; // nothing to do if (c == REPLACE_CR_NCHAR) { had_ctrl_v_cr = TRUE; c = CAR; } else if (c == REPLACE_NL_NCHAR) { had_ctrl_v_cr = TRUE; c = NL; } if (has_mbyte) mb_adjust_opend(oap); if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) return FAIL; /* * block mode replace */ if (oap->block_mode) { bd.is_MAX = (curwin->w_curswant == MAXCOL); for ( ; curwin->w_cursor.lnum <= oap->end.lnum; ++curwin->w_cursor.lnum) { curwin->w_cursor.col = 0; // make sure cursor position is valid block_prep(oap, &bd, curwin->w_cursor.lnum, TRUE); if (bd.textlen == 0 && (!virtual_op || bd.is_MAX)) continue; // nothing to replace // n == number of extra chars required // If we split a TAB, it may be replaced by several characters. // Thus the number of characters may increase! // If the range starts in virtual space, count the initial // coladd offset as part of "startspaces" if (virtual_op && bd.is_short && *bd.textstart == NUL) { pos_T vpos; vpos.lnum = curwin->w_cursor.lnum; getvpos(&vpos, oap->start_vcol); bd.startspaces += vpos.coladd; n = bd.startspaces; } else // allow for pre spaces n = (bd.startspaces ? bd.start_char_vcols - 1 : 0); // allow for post spp n += (bd.endspaces && !bd.is_oneChar && bd.end_char_vcols > 0) ? bd.end_char_vcols - 1 : 0; // Figure out how many characters to replace. numc = oap->end_vcol - oap->start_vcol + 1; if (bd.is_short && (!virtual_op || bd.is_MAX)) numc -= (oap->end_vcol - bd.end_vcol) + 1; // A double-wide character can be replaced only up to half the // times. if ((*mb_char2cells)(c) > 1) { if ((numc & 1) && !bd.is_short) { ++bd.endspaces; ++n; } numc = numc / 2; } // Compute bytes needed, move character count to num_chars. num_chars = numc; numc *= (*mb_char2len)(c); // oldlen includes textlen, so don't double count n += numc - bd.textlen; oldp = ml_get_curline(); oldlen = STRLEN(oldp); newp = alloc(oldlen + 1 + n); if (newp == NULL) continue; vim_memset(newp, NUL, (size_t)(oldlen + 1 + n)); // copy up to deleted part mch_memmove(newp, oldp, (size_t)bd.textcol); oldp += bd.textcol + bd.textlen; // insert pre-spaces vim_memset(newp + bd.textcol, ' ', (size_t)bd.startspaces); // insert replacement chars CHECK FOR ALLOCATED SPACE // REPLACE_CR_NCHAR/REPLACE_NL_NCHAR is used for entering CR // literally. if (had_ctrl_v_cr || (c != '\r' && c != '\n')) { if (has_mbyte) { n = (int)STRLEN(newp); while (--num_chars >= 0) n += (*mb_char2bytes)(c, newp + n); } else vim_memset(newp + STRLEN(newp), c, (size_t)numc); if (!bd.is_short) { // insert post-spaces vim_memset(newp + STRLEN(newp), ' ', (size_t)bd.endspaces); // copy the part after the changed part STRMOVE(newp + STRLEN(newp), oldp); } } else { // Replacing with \r or \n means splitting the line. after_p = alloc(oldlen + 1 + n - STRLEN(newp)); if (after_p != NULL) STRMOVE(after_p, oldp); } // replace the line ml_replace(curwin->w_cursor.lnum, newp, FALSE); if (after_p != NULL) { ml_append(curwin->w_cursor.lnum++, after_p, 0, FALSE); appended_lines_mark(curwin->w_cursor.lnum, 1L); oap->end.lnum++; vim_free(after_p); } } } else { /* * MCHAR and MLINE motion replace. */ if (oap->motion_type == MLINE) { oap->start.col = 0; curwin->w_cursor.col = 0; oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); if (oap->end.col) --oap->end.col; } else if (!oap->inclusive) dec(&(oap->end)); while (LTOREQ_POS(curwin->w_cursor, oap->end)) { int done = FALSE; n = gchar_cursor(); if (n != NUL) { int new_byte_len = (*mb_char2len)(c); int old_byte_len = mb_ptr2len(ml_get_cursor()); if (new_byte_len > 1 || old_byte_len > 1) { // This is slow, but it handles replacing a single-byte // with a multi-byte and the other way around. if (curwin->w_cursor.lnum == oap->end.lnum) oap->end.col += new_byte_len - old_byte_len; replace_character(c); done = TRUE; } else { if (n == TAB) { int end_vcol = 0; if (curwin->w_cursor.lnum == oap->end.lnum) { // oap->end has to be recalculated when // the tab breaks end_vcol = getviscol2(oap->end.col, oap->end.coladd); } coladvance_force(getviscol()); if (curwin->w_cursor.lnum == oap->end.lnum) getvpos(&oap->end, end_vcol); } // with "coladd" set may move to just after a TAB if (gchar_cursor() != NUL) { PBYTE(curwin->w_cursor, c); done = TRUE; } } } if (!done && virtual_op && curwin->w_cursor.lnum == oap->end.lnum) { int virtcols = oap->end.coladd; if (curwin->w_cursor.lnum == oap->start.lnum && oap->start.col == oap->end.col && oap->start.coladd) virtcols -= oap->start.coladd; // oap->end has been trimmed so it's effectively inclusive; // as a result an extra +1 must be counted so we don't // trample the NUL byte. coladvance_force(getviscol2(oap->end.col, oap->end.coladd) + 1); curwin->w_cursor.col -= (virtcols + 1); for (; virtcols >= 0; virtcols--) { if ((*mb_char2len)(c) > 1) replace_character(c); else PBYTE(curwin->w_cursor, c); if (inc(&curwin->w_cursor) == -1) break; } } // Advance to next character, stop at the end of the file. if (inc_cursor() == -1) break; } } curwin->w_cursor = oap->start; check_cursor(); changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L); if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set "'[" and "']" marks. curbuf->b_op_start = oap->start; curbuf->b_op_end = oap->end; } return OK; } static int swapchars(int op_type, pos_T *pos, int length); /* * Handle the (non-standard vi) tilde operator. Also for "gu", "gU" and "g?". */ static void op_tilde(oparg_T *oap) { pos_T pos; struct block_def bd; int did_change = FALSE; if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) return; pos = oap->start; if (oap->block_mode) // Visual block mode { for (; pos.lnum <= oap->end.lnum; ++pos.lnum) { int one_change; block_prep(oap, &bd, pos.lnum, FALSE); pos.col = bd.textcol; one_change = swapchars(oap->op_type, &pos, bd.textlen); did_change |= one_change; #ifdef FEAT_NETBEANS_INTG if (netbeans_active() && one_change) { char_u *ptr; netbeans_removed(curbuf, pos.lnum, bd.textcol, (long)bd.textlen); // get the line now, it may have been flushed ptr = ml_get_buf(curbuf, pos.lnum, FALSE); netbeans_inserted(curbuf, pos.lnum, bd.textcol, &ptr[bd.textcol], bd.textlen); } #endif } if (did_change) changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L); } else // not block mode { if (oap->motion_type == MLINE) { oap->start.col = 0; pos.col = 0; oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); if (oap->end.col) --oap->end.col; } else if (!oap->inclusive) dec(&(oap->end)); if (pos.lnum == oap->end.lnum) did_change = swapchars(oap->op_type, &pos, oap->end.col - pos.col + 1); else for (;;) { did_change |= swapchars(oap->op_type, &pos, pos.lnum == oap->end.lnum ? oap->end.col + 1: (int)STRLEN(ml_get_pos(&pos))); if (LTOREQ_POS(oap->end, pos) || inc(&pos) == -1) break; } if (did_change) { changed_lines(oap->start.lnum, oap->start.col, oap->end.lnum + 1, 0L); #ifdef FEAT_NETBEANS_INTG if (netbeans_active()) { char_u *ptr; int count; pos = oap->start; while (pos.lnum < oap->end.lnum) { ptr = ml_get_buf(curbuf, pos.lnum, FALSE); count = (int)STRLEN(ptr) - pos.col; netbeans_removed(curbuf, pos.lnum, pos.col, (long)count); // get the line again, it may have been flushed ptr = ml_get_buf(curbuf, pos.lnum, FALSE); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count); pos.col = 0; pos.lnum++; } count = oap->end.col - pos.col + 1; netbeans_removed(curbuf, pos.lnum, pos.col, (long)count); // get the line again, it may have been flushed ptr = ml_get_buf(curbuf, pos.lnum, FALSE); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], count); } #endif } } if (!did_change && oap->is_VIsual) // No change: need to remove the Visual selection redraw_curbuf_later(UPD_INVERTED); if ((cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set '[ and '] marks. curbuf->b_op_start = oap->start; curbuf->b_op_end = oap->end; } if (oap->line_count > p_report) smsg(NGETTEXT("%ld line changed", "%ld lines changed", oap->line_count), oap->line_count); } /* * Invoke swapchar() on "length" bytes at position "pos". * "pos" is advanced to just after the changed characters. * "length" is rounded up to include the whole last multi-byte character. * Also works correctly when the number of bytes changes. * Returns TRUE if some character was changed. */ static int swapchars(int op_type, pos_T *pos, int length) { int todo; int did_change = 0; for (todo = length; todo > 0; --todo) { if (has_mbyte) { int len = (*mb_ptr2len)(ml_get_pos(pos)); // we're counting bytes, not characters if (len > 0) todo -= len - 1; } did_change |= swapchar(op_type, pos); if (inc(pos) == -1) // at end of file break; } return did_change; } /* * If op_type == OP_UPPER: make uppercase, * if op_type == OP_LOWER: make lowercase, * if op_type == OP_ROT13: do rot13 encoding, * else swap case of character at 'pos' * returns TRUE when something actually changed. */ int swapchar(int op_type, pos_T *pos) { int c; int nc; c = gchar_pos(pos); // Only do rot13 encoding for ASCII characters. if (c >= 0x80 && op_type == OP_ROT13) return FALSE; if (op_type == OP_UPPER && c == 0xdf && (enc_latin1like || STRCMP(p_enc, "iso-8859-2") == 0)) { pos_T sp = curwin->w_cursor; // Special handling of German sharp s: change to "SS". curwin->w_cursor = *pos; del_char(FALSE); ins_char('S'); ins_char('S'); curwin->w_cursor = sp; inc(pos); } if (enc_dbcs != 0 && c >= 0x100) // No lower/uppercase letter return FALSE; nc = c; if (MB_ISLOWER(c)) { if (op_type == OP_ROT13) nc = ROT13(c, 'a'); else if (op_type != OP_LOWER) nc = MB_TOUPPER(c); } else if (MB_ISUPPER(c)) { if (op_type == OP_ROT13) nc = ROT13(c, 'A'); else if (op_type != OP_UPPER) nc = MB_TOLOWER(c); } if (nc != c) { if (enc_utf8 && (c >= 0x80 || nc >= 0x80)) { pos_T sp = curwin->w_cursor; curwin->w_cursor = *pos; // don't use del_char(), it also removes composing chars del_bytes(utf_ptr2len(ml_get_cursor()), FALSE, FALSE); ins_char(nc); curwin->w_cursor = sp; } else PBYTE(*pos, nc); return TRUE; } return FALSE; } /* * op_insert - Insert and append operators for Visual mode. */ void op_insert(oparg_T *oap, long count1) { long ins_len, pre_textlen = 0; char_u *firstline, *ins_text; colnr_T ind_pre_col = 0, ind_post_col; int ind_pre_vcol = 0, ind_post_vcol = 0; struct block_def bd; int i; pos_T t1; pos_T start_insert; // offset when cursor was moved in insert mode int offset = 0; // edit() changes this - record it for OP_APPEND bd.is_MAX = (curwin->w_curswant == MAXCOL); // vis block is still marked. Get rid of it now. curwin->w_cursor.lnum = oap->start.lnum; update_screen(UPD_INVERTED); if (oap->block_mode) { // When 'virtualedit' is used, need to insert the extra spaces before // doing block_prep(). When only "block" is used, virtual edit is // already disabled, but still need it when calling // coladvance_force(). // coladvance_force() uses get_ve_flags() to get the 'virtualedit' // state for the current window. To override that state, we need to // set the window-local value of ve_flags rather than the global value. if (curwin->w_cursor.coladd > 0) { int old_ve_flags = curwin->w_ve_flags; if (u_save_cursor() == FAIL) return; curwin->w_ve_flags = VE_ALL; coladvance_force(oap->op_type == OP_APPEND ? oap->end_vcol + 1 : getviscol()); if (oap->op_type == OP_APPEND) --curwin->w_cursor.col; curwin->w_ve_flags = old_ve_flags; } // Get the info about the block before entering the text block_prep(oap, &bd, oap->start.lnum, TRUE); // Get indent information ind_pre_col = (colnr_T)getwhitecols_curline(); ind_pre_vcol = get_indent(); firstline = ml_get(oap->start.lnum) + bd.textcol; if (oap->op_type == OP_APPEND) firstline += bd.textlen; pre_textlen = (long)STRLEN(firstline); } if (oap->op_type == OP_APPEND) { if (oap->block_mode && curwin->w_cursor.coladd == 0) { // Move the cursor to the character right of the block. curwin->w_set_curswant = TRUE; while (*ml_get_cursor() != NUL && (curwin->w_cursor.col < bd.textcol + bd.textlen)) ++curwin->w_cursor.col; if (bd.is_short && !bd.is_MAX) { // First line was too short, make it longer and adjust the // values in "bd". if (u_save_cursor() == FAIL) return; for (i = 0; i < bd.endspaces; ++i) ins_char(' '); bd.textlen += bd.endspaces; } } else { curwin->w_cursor = oap->end; check_cursor_col(); // Works just like an 'i'nsert on the next character. if (!LINEEMPTY(curwin->w_cursor.lnum) && oap->start_vcol != oap->end_vcol) inc_cursor(); } } t1 = oap->start; start_insert = curwin->w_cursor; (void)edit(NUL, FALSE, (linenr_T)count1); // When a tab was inserted, and the characters in front of the tab // have been converted to a tab as well, the column of the cursor // might have actually been reduced, so need to adjust here. if (t1.lnum == curbuf->b_op_start_orig.lnum && LT_POS(curbuf->b_op_start_orig, t1)) oap->start = curbuf->b_op_start_orig; // If user has moved off this line, we don't know what to do, so do // nothing. // Also don't repeat the insert when Insert mode ended with CTRL-C. if (curwin->w_cursor.lnum != oap->start.lnum || got_int) return; if (oap->block_mode) { struct block_def bd2; int did_indent = FALSE; size_t len; int add; // If indent kicked in, the firstline might have changed // but only do that, if the indent actually increased. ind_post_col = (colnr_T)getwhitecols_curline(); if (curbuf->b_op_start.col > ind_pre_col && ind_post_col > ind_pre_col) { bd.textcol += ind_post_col - ind_pre_col; ind_post_vcol = get_indent(); bd.start_vcol += ind_post_vcol - ind_pre_vcol; did_indent = TRUE; } // The user may have moved the cursor before inserting something, try // to adjust the block for that. But only do it, if the difference // does not come from indent kicking in. if (oap->start.lnum == curbuf->b_op_start_orig.lnum && !bd.is_MAX && !did_indent) { int t = getviscol2(curbuf->b_op_start_orig.col, curbuf->b_op_start_orig.coladd); if (oap->op_type == OP_INSERT && oap->start.col + oap->start.coladd != curbuf->b_op_start_orig.col + curbuf->b_op_start_orig.coladd) { oap->start.col = curbuf->b_op_start_orig.col; pre_textlen -= t - oap->start_vcol; oap->start_vcol = t; } else if (oap->op_type == OP_APPEND && oap->start.col + oap->start.coladd >= curbuf->b_op_start_orig.col + curbuf->b_op_start_orig.coladd) { oap->start.col = curbuf->b_op_start_orig.col; // reset pre_textlen to the value of OP_INSERT pre_textlen += bd.textlen; pre_textlen -= t - oap->start_vcol; oap->start_vcol = t; oap->op_type = OP_INSERT; } } // Spaces and tabs in the indent may have changed to other spaces and // tabs. Get the starting column again and correct the length. // Don't do this when "$" used, end-of-line will have changed. // // if indent was added and the inserted text was after the indent, // correct the selection for the new indent. if (did_indent && bd.textcol - ind_post_col > 0) { oap->start.col += ind_post_col - ind_pre_col; oap->start_vcol += ind_post_vcol - ind_pre_vcol; oap->end.col += ind_post_col - ind_pre_col; oap->end_vcol += ind_post_vcol - ind_pre_vcol; } block_prep(oap, &bd2, oap->start.lnum, TRUE); if (did_indent && bd.textcol - ind_post_col > 0) { // undo for where "oap" is used below oap->start.col -= ind_post_col - ind_pre_col; oap->start_vcol -= ind_post_vcol - ind_pre_vcol; oap->end.col -= ind_post_col - ind_pre_col; oap->end_vcol -= ind_post_vcol - ind_pre_vcol; } if (!bd.is_MAX || bd2.textlen < bd.textlen) { if (oap->op_type == OP_APPEND) { pre_textlen += bd2.textlen - bd.textlen; if (bd2.endspaces) --bd2.textlen; } bd.textcol = bd2.textcol; bd.textlen = bd2.textlen; } /* * Subsequent calls to ml_get() flush the firstline data - take a * copy of the required string. */ firstline = ml_get(oap->start.lnum); len = STRLEN(firstline); add = bd.textcol; if (oap->op_type == OP_APPEND) { add += bd.textlen; // account for pressing cursor in insert mode when '$' was used if (bd.is_MAX && (start_insert.lnum == Insstart.lnum && start_insert.col > Insstart.col)) { offset = (start_insert.col - Insstart.col); add -= offset; if (oap->end_vcol > offset) oap->end_vcol -= (offset + 1); else // moved outside of the visual block, what to do? return; } } if ((size_t)add > len) firstline += len; // short line, point to the NUL else firstline += add; if (pre_textlen >= 0 && (ins_len = (long)STRLEN(firstline) - pre_textlen - offset) > 0) { ins_text = vim_strnsave(firstline, ins_len); if (ins_text != NULL) { // block handled here if (u_save(oap->start.lnum, (linenr_T)(oap->end.lnum + 1)) == OK) block_insert(oap, ins_text, (oap->op_type == OP_INSERT), &bd); curwin->w_cursor.col = oap->start.col; check_cursor(); vim_free(ins_text); } } } } /* * op_change - handle a change operation * * return TRUE if edit() returns because of a CTRL-O command */ int op_change(oparg_T *oap) { colnr_T l; int retval; long offset; linenr_T linenr; long ins_len; long pre_textlen = 0; long pre_indent = 0; char_u *firstline; char_u *ins_text, *newp, *oldp; struct block_def bd; l = oap->start.col; if (oap->motion_type == MLINE) { l = 0; can_si = may_do_si(); // Like opening a new line, do smart indent } // First delete the text in the region. In an empty buffer only need to // save for undo if (curbuf->b_ml.ml_flags & ML_EMPTY) { if (u_save_cursor() == FAIL) return FALSE; } else if (op_delete(oap) == FAIL) return FALSE; if ((l > curwin->w_cursor.col) && !LINEEMPTY(curwin->w_cursor.lnum) && !virtual_op) inc_cursor(); // check for still on same line (<CR> in inserted text meaningless) // skip blank lines too if (oap->block_mode) { // Add spaces before getting the current line length. if (virtual_op && (curwin->w_cursor.coladd > 0 || gchar_cursor() == NUL)) coladvance_force(getviscol()); firstline = ml_get(oap->start.lnum); pre_textlen = (long)STRLEN(firstline); pre_indent = (long)getwhitecols(firstline); bd.textcol = curwin->w_cursor.col; } if (oap->motion_type == MLINE) fix_indent(); // Reset finish_op now, don't want it set inside edit(). int save_finish_op = finish_op; finish_op = FALSE; retval = edit(NUL, FALSE, (linenr_T)1); finish_op = save_finish_op; /* * In Visual block mode, handle copying the new text to all lines of the * block. * Don't repeat the insert when Insert mode ended with CTRL-C. */ if (oap->block_mode && oap->start.lnum != oap->end.lnum && !got_int) { // Auto-indenting may have changed the indent. If the cursor was past // the indent, exclude that indent change from the inserted text. firstline = ml_get(oap->start.lnum); if (bd.textcol > (colnr_T)pre_indent) { long new_indent = (long)getwhitecols(firstline); pre_textlen += new_indent - pre_indent; bd.textcol += new_indent - pre_indent; } ins_len = (long)STRLEN(firstline) - pre_textlen; if (ins_len > 0) { // Subsequent calls to ml_get() flush the firstline data - take a // copy of the inserted text. if ((ins_text = alloc(ins_len + 1)) != NULL) { vim_strncpy(ins_text, firstline + bd.textcol, (size_t)ins_len); for (linenr = oap->start.lnum + 1; linenr <= oap->end.lnum; linenr++) { block_prep(oap, &bd, linenr, TRUE); if (!bd.is_short || virtual_op) { pos_T vpos; // If the block starts in virtual space, count the // initial coladd offset as part of "startspaces" if (bd.is_short) { vpos.lnum = linenr; (void)getvpos(&vpos, oap->start_vcol); } else vpos.coladd = 0; oldp = ml_get(linenr); newp = alloc(STRLEN(oldp) + vpos.coladd + ins_len + 1); if (newp == NULL) continue; // copy up to block start mch_memmove(newp, oldp, (size_t)bd.textcol); offset = bd.textcol; vim_memset(newp + offset, ' ', (size_t)vpos.coladd); offset += vpos.coladd; mch_memmove(newp + offset, ins_text, (size_t)ins_len); offset += ins_len; oldp += bd.textcol; STRMOVE(newp + offset, oldp); ml_replace(linenr, newp, FALSE); #ifdef FEAT_PROP_POPUP // Shift the properties for linenr as edit() would do. if (curbuf->b_has_textprop) adjust_prop_columns(linenr, bd.textcol, vpos.coladd + ins_len, 0); #endif } } check_cursor(); changed_lines(oap->start.lnum + 1, 0, oap->end.lnum + 1, 0L); } vim_free(ins_text); } } auto_format(FALSE, TRUE); return retval; } /* * When the cursor is on the NUL past the end of the line and it should not be * there move it left. */ void adjust_cursor_eol(void) { unsigned int cur_ve_flags = get_ve_flags(); int adj_cursor = (curwin->w_cursor.col > 0 && gchar_cursor() == NUL && (cur_ve_flags & VE_ONEMORE) == 0 && !(restart_edit || (State & MODE_INSERT))); if (!adj_cursor) return; // Put the cursor on the last character in the line. dec_cursor(); if (cur_ve_flags == VE_ALL) { colnr_T scol, ecol; // Coladd is set to the width of the last character. getvcol(curwin, &curwin->w_cursor, &scol, NULL, &ecol); curwin->w_cursor.coladd = ecol - scol + 1; } } /* * If "process" is TRUE and the line begins with a comment leader (possibly * after some white space), return a pointer to the text after it. Put a boolean * value indicating whether the line ends with an unclosed comment in * "is_comment". * line - line to be processed, * process - if FALSE, will only check whether the line ends with an unclosed * comment, * include_space - whether to also skip space following the comment leader, * is_comment - will indicate whether the current line ends with an unclosed * comment. */ char_u * skip_comment( char_u *line, int process, int include_space, int *is_comment) { char_u *comment_flags = NULL; int lead_len; int leader_offset = get_last_leader_offset(line, &comment_flags); *is_comment = FALSE; if (leader_offset != -1) { // Let's check whether the line ends with an unclosed comment. // If the last comment leader has COM_END in flags, there's no comment. while (*comment_flags) { if (*comment_flags == COM_END || *comment_flags == ':') break; ++comment_flags; } if (*comment_flags != COM_END) *is_comment = TRUE; } if (process == FALSE) return line; lead_len = get_leader_len(line, &comment_flags, FALSE, include_space); if (lead_len == 0) return line; // Find: // - COM_END, // - colon, // whichever comes first. while (*comment_flags) { if (*comment_flags == COM_END || *comment_flags == ':') break; ++comment_flags; } // If we found a colon, it means that we are not processing a line // starting with a closing part of a three-part comment. That's good, // because we don't want to remove those as this would be annoying. if (*comment_flags == ':' || *comment_flags == NUL) line += lead_len; return line; } /* * Join 'count' lines (minimal 2) at the cursor position. * When "save_undo" is TRUE save lines for undo first. * Set "use_formatoptions" to FALSE when e.g. processing backspace and comment * leaders should not be removed. * When setmark is TRUE, sets the '[ and '] mark, else, the caller is expected * to set those marks. * * return FAIL for failure, OK otherwise */ int do_join( long count, int insert_space, int save_undo, int use_formatoptions UNUSED, int setmark) { char_u *curr = NULL; char_u *curr_start = NULL; char_u *cend; char_u *newp; size_t newp_len; char_u *spaces; // number of spaces inserted before a line int endcurr1 = NUL; int endcurr2 = NUL; int currsize = 0; // size of the current line int sumsize = 0; // size of the long new line linenr_T t; colnr_T col = 0; int ret = OK; int *comments = NULL; int remove_comments = (use_formatoptions == TRUE) && has_format_option(FO_REMOVE_COMS); int prev_was_comment; #ifdef FEAT_PROP_POPUP int propcount = 0; // number of props over all joined lines int props_remaining; #endif if (save_undo && u_save((linenr_T)(curwin->w_cursor.lnum - 1), (linenr_T)(curwin->w_cursor.lnum + count)) == FAIL) return FAIL; // Allocate an array to store the number of spaces inserted before each // line. We will use it to pre-compute the length of the new line and the // proper placement of each original line in the new one. spaces = lalloc_clear(count, TRUE); if (spaces == NULL) return FAIL; if (remove_comments) { comments = lalloc_clear(count * sizeof(int), TRUE); if (comments == NULL) { vim_free(spaces); return FAIL; } } /* * Don't move anything yet, just compute the final line length * and setup the array of space strings lengths * This loops forward over the joined lines. */ for (t = 0; t < count; ++t) { curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t)); #ifdef FEAT_PROP_POPUP propcount += count_props((linenr_T) (curwin->w_cursor.lnum + t), t > 0, t + 1 == count); #endif if (t == 0 && setmark && (cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '[ mark. curwin->w_buffer->b_op_start.lnum = curwin->w_cursor.lnum; curwin->w_buffer->b_op_start.col = (colnr_T)STRLEN(curr); } if (remove_comments) { // We don't want to remove the comment leader if the // previous line is not a comment. if (t > 0 && prev_was_comment) { char_u *new_curr = skip_comment(curr, TRUE, insert_space, &prev_was_comment); comments[t] = (int)(new_curr - curr); curr = new_curr; } else curr = skip_comment(curr, FALSE, insert_space, &prev_was_comment); } if (insert_space && t > 0) { curr = skipwhite(curr); if (*curr != NUL && *curr != ')' && sumsize != 0 && endcurr1 != TAB && (!has_format_option(FO_MBYTE_JOIN) || (mb_ptr2char(curr) < 0x100 && endcurr1 < 0x100)) && (!has_format_option(FO_MBYTE_JOIN2) || (mb_ptr2char(curr) < 0x100 && !(enc_utf8 && utf_eat_space(endcurr1))) || (endcurr1 < 0x100 && !(enc_utf8 && utf_eat_space(mb_ptr2char(curr))))) ) { // don't add a space if the line is ending in a space if (endcurr1 == ' ') endcurr1 = endcurr2; else ++spaces[t]; // extra space when 'joinspaces' set and line ends in '.' if ( p_js && (endcurr1 == '.' || (vim_strchr(p_cpo, CPO_JOINSP) == NULL && (endcurr1 == '?' || endcurr1 == '!')))) ++spaces[t]; } } currsize = (int)STRLEN(curr); sumsize += currsize + spaces[t]; endcurr1 = endcurr2 = NUL; if (insert_space && currsize > 0) { if (has_mbyte) { cend = curr + currsize; MB_PTR_BACK(curr, cend); endcurr1 = (*mb_ptr2char)(cend); if (cend > curr) { MB_PTR_BACK(curr, cend); endcurr2 = (*mb_ptr2char)(cend); } } else { endcurr1 = *(curr + currsize - 1); if (currsize > 1) endcurr2 = *(curr + currsize - 2); } } line_breakcheck(); if (got_int) { ret = FAIL; goto theend; } } // store the column position before last line col = sumsize - currsize - spaces[count - 1]; // allocate the space for the new line newp_len = sumsize + 1; #ifdef FEAT_PROP_POPUP newp_len += propcount * sizeof(textprop_T); #endif newp = alloc(newp_len); if (newp == NULL) { ret = FAIL; goto theend; } cend = newp + sumsize; *cend = 0; /* * Move affected lines to the new long one. * This loops backwards over the joined lines, including the original line. * * Move marks from each deleted line to the joined line, adjusting the * column. This is not Vi compatible, but Vi deletes the marks, thus that * should not really be a problem. */ #ifdef FEAT_PROP_POPUP props_remaining = propcount; #endif for (t = count - 1; ; --t) { int spaces_removed; cend -= currsize; mch_memmove(cend, curr, (size_t)currsize); if (spaces[t] > 0) { cend -= spaces[t]; vim_memset(cend, ' ', (size_t)(spaces[t])); } // If deleting more spaces than adding, the cursor moves no more than // what is added if it is inside these spaces. spaces_removed = (curr - curr_start) - spaces[t]; mark_col_adjust(curwin->w_cursor.lnum + t, (colnr_T)0, -t, (long)(cend - newp - spaces_removed), spaces_removed); #ifdef FEAT_PROP_POPUP prepend_joined_props(newp + sumsize + 1, propcount, &props_remaining, curwin->w_cursor.lnum + t, t == count - 1, (long)(cend - newp), spaces_removed); #endif if (t == 0) break; curr = curr_start = ml_get((linenr_T)(curwin->w_cursor.lnum + t - 1)); if (remove_comments) curr += comments[t - 1]; if (insert_space && t > 1) curr = skipwhite(curr); currsize = (int)STRLEN(curr); } ml_replace_len(curwin->w_cursor.lnum, newp, (colnr_T)newp_len, TRUE, FALSE); if (setmark && (cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // Set the '] mark. curwin->w_buffer->b_op_end.lnum = curwin->w_cursor.lnum; curwin->w_buffer->b_op_end.col = (colnr_T)sumsize; } // Only report the change in the first line here, del_lines() will report // the deleted line. changed_lines(curwin->w_cursor.lnum, currsize, curwin->w_cursor.lnum + 1, 0L); /* * Delete following lines. To do this we move the cursor there * briefly, and then move it back. After del_lines() the cursor may * have moved up (last line deleted), so the current lnum is kept in t. */ t = curwin->w_cursor.lnum; ++curwin->w_cursor.lnum; del_lines(count - 1, FALSE); curwin->w_cursor.lnum = t; /* * Set the cursor column: * Vi compatible: use the column of the first join * vim: use the column of the last join */ curwin->w_cursor.col = (vim_strchr(p_cpo, CPO_JOINCOL) != NULL ? currsize : col); check_cursor_col(); curwin->w_cursor.coladd = 0; curwin->w_set_curswant = TRUE; theend: vim_free(spaces); if (remove_comments) vim_free(comments); return ret; } #ifdef FEAT_LINEBREAK /* * Reset 'linebreak' and take care of side effects. * Returns the previous value, to be passed to restore_lbr(). */ static int reset_lbr(void) { if (!curwin->w_p_lbr) return FALSE; // changing 'linebreak' may require w_virtcol to be updated curwin->w_p_lbr = FALSE; curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL); return TRUE; } /* * Restore 'linebreak' and take care of side effects. */ static void restore_lbr(int lbr_saved) { if (curwin->w_p_lbr || !lbr_saved) return; // changing 'linebreak' may require w_virtcol to be updated curwin->w_p_lbr = TRUE; curwin->w_valid &= ~(VALID_WROW|VALID_WCOL|VALID_VIRTCOL); } #endif /* * prepare a few things for block mode yank/delete/tilde * * for delete: * - textlen includes the first/last char to be (partly) deleted * - start/endspaces is the number of columns that are taken by the * first/last deleted char minus the number of columns that have to be * deleted. * for yank and tilde: * - textlen includes the first/last char to be wholly yanked * - start/endspaces is the number of columns of the first/last yanked char * that are to be yanked. */ void block_prep( oparg_T *oap, struct block_def *bdp, linenr_T lnum, int is_del) { int incr = 0; char_u *pend; char_u *pstart; char_u *line; char_u *prev_pstart; char_u *prev_pend; chartabsize_T cts; #ifdef FEAT_LINEBREAK // Avoid a problem with unwanted linebreaks in block mode. int lbr_saved = reset_lbr(); #endif bdp->startspaces = 0; bdp->endspaces = 0; bdp->textlen = 0; bdp->start_vcol = 0; bdp->end_vcol = 0; bdp->is_short = FALSE; bdp->is_oneChar = FALSE; bdp->pre_whitesp = 0; bdp->pre_whitesp_c = 0; bdp->end_char_vcols = 0; bdp->start_char_vcols = 0; line = ml_get(lnum); prev_pstart = line; init_chartabsize_arg(&cts, curwin, lnum, bdp->start_vcol, line, line); while (cts.cts_vcol < oap->start_vcol && *cts.cts_ptr != NUL) { // Count a tab for what it's worth (if list mode not on) incr = lbr_chartabsize(&cts); cts.cts_vcol += incr; if (VIM_ISWHITE(*cts.cts_ptr)) { bdp->pre_whitesp += incr; bdp->pre_whitesp_c++; } else { bdp->pre_whitesp = 0; bdp->pre_whitesp_c = 0; } prev_pstart = cts.cts_ptr; MB_PTR_ADV(cts.cts_ptr); } bdp->start_vcol = cts.cts_vcol; pstart = cts.cts_ptr; clear_chartabsize_arg(&cts); bdp->start_char_vcols = incr; if (bdp->start_vcol < oap->start_vcol) // line too short { bdp->end_vcol = bdp->start_vcol; bdp->is_short = TRUE; if (!is_del || oap->op_type == OP_APPEND) bdp->endspaces = oap->end_vcol - oap->start_vcol + 1; } else { // notice: this converts partly selected Multibyte characters to // spaces, too. bdp->startspaces = bdp->start_vcol - oap->start_vcol; if (is_del && bdp->startspaces) bdp->startspaces = bdp->start_char_vcols - bdp->startspaces; pend = pstart; bdp->end_vcol = bdp->start_vcol; if (bdp->end_vcol > oap->end_vcol) // it's all in one character { bdp->is_oneChar = TRUE; if (oap->op_type == OP_INSERT) bdp->endspaces = bdp->start_char_vcols - bdp->startspaces; else if (oap->op_type == OP_APPEND) { bdp->startspaces += oap->end_vcol - oap->start_vcol + 1; bdp->endspaces = bdp->start_char_vcols - bdp->startspaces; } else { bdp->startspaces = oap->end_vcol - oap->start_vcol + 1; if (is_del && oap->op_type != OP_LSHIFT) { // just putting the sum of those two into // bdp->startspaces doesn't work for Visual replace, // so we have to split the tab in two bdp->startspaces = bdp->start_char_vcols - (bdp->start_vcol - oap->start_vcol); bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1; } } } else { init_chartabsize_arg(&cts, curwin, lnum, bdp->end_vcol, line, pend); prev_pend = pend; while (cts.cts_vcol <= oap->end_vcol && *cts.cts_ptr != NUL) { // count a tab for what it's worth (if list mode not on) prev_pend = cts.cts_ptr; incr = lbr_chartabsize_adv(&cts); cts.cts_vcol += incr; } bdp->end_vcol = cts.cts_vcol; pend = cts.cts_ptr; clear_chartabsize_arg(&cts); if (bdp->end_vcol <= oap->end_vcol && (!is_del || oap->op_type == OP_APPEND || oap->op_type == OP_REPLACE)) // line too short { bdp->is_short = TRUE; // Alternative: include spaces to fill up the block. // Disadvantage: can lead to trailing spaces when the line is // short where the text is put // if (!is_del || oap->op_type == OP_APPEND) if (oap->op_type == OP_APPEND || virtual_op) bdp->endspaces = oap->end_vcol - bdp->end_vcol + oap->inclusive; else bdp->endspaces = 0; // replace doesn't add characters } else if (bdp->end_vcol > oap->end_vcol) { bdp->endspaces = bdp->end_vcol - oap->end_vcol - 1; if (!is_del && bdp->endspaces) { bdp->endspaces = incr - bdp->endspaces; if (pend != pstart) pend = prev_pend; } } } bdp->end_char_vcols = incr; if (is_del && bdp->startspaces) pstart = prev_pstart; bdp->textlen = (int)(pend - pstart); } bdp->textcol = (colnr_T) (pstart - line); bdp->textstart = pstart; #ifdef FEAT_LINEBREAK restore_lbr(lbr_saved); #endif } /* * Handle the add/subtract operator. */ void op_addsub( oparg_T *oap, linenr_T Prenum1, // Amount of add/subtract int g_cmd) // was g<c-a>/g<c-x> { pos_T pos; struct block_def bd; int change_cnt = 0; linenr_T amount = Prenum1; // do_addsub() might trigger re-evaluation of 'foldexpr' halfway, when the // buffer is not completely updated yet. Postpone updating folds until before // the call to changed_lines(). #ifdef FEAT_FOLDING disable_fold_update++; #endif if (!VIsual_active) { pos = curwin->w_cursor; if (u_save_cursor() == FAIL) { #ifdef FEAT_FOLDING disable_fold_update--; #endif return; } change_cnt = do_addsub(oap->op_type, &pos, 0, amount); #ifdef FEAT_FOLDING disable_fold_update--; #endif if (change_cnt) changed_lines(pos.lnum, 0, pos.lnum + 1, 0L); } else { int one_change; int length; pos_T startpos; if (u_save((linenr_T)(oap->start.lnum - 1), (linenr_T)(oap->end.lnum + 1)) == FAIL) { #ifdef FEAT_FOLDING disable_fold_update--; #endif return; } pos = oap->start; for (; pos.lnum <= oap->end.lnum; ++pos.lnum) { if (oap->block_mode) // Visual block mode { block_prep(oap, &bd, pos.lnum, FALSE); pos.col = bd.textcol; length = bd.textlen; } else if (oap->motion_type == MLINE) { curwin->w_cursor.col = 0; pos.col = 0; length = (colnr_T)STRLEN(ml_get(pos.lnum)); } else // oap->motion_type == MCHAR { if (pos.lnum == oap->start.lnum && !oap->inclusive) dec(&(oap->end)); length = (colnr_T)STRLEN(ml_get(pos.lnum)); pos.col = 0; if (pos.lnum == oap->start.lnum) { pos.col += oap->start.col; length -= oap->start.col; } if (pos.lnum == oap->end.lnum) { length = (int)STRLEN(ml_get(oap->end.lnum)); if (oap->end.col >= length) oap->end.col = length - 1; length = oap->end.col - pos.col + 1; } } one_change = do_addsub(oap->op_type, &pos, length, amount); if (one_change) { // Remember the start position of the first change. if (change_cnt == 0) startpos = curbuf->b_op_start; ++change_cnt; } #ifdef FEAT_NETBEANS_INTG if (netbeans_active() && one_change) { char_u *ptr; netbeans_removed(curbuf, pos.lnum, pos.col, (long)length); ptr = ml_get_buf(curbuf, pos.lnum, FALSE); netbeans_inserted(curbuf, pos.lnum, pos.col, &ptr[pos.col], length); } #endif if (g_cmd && one_change) amount += Prenum1; } #ifdef FEAT_FOLDING disable_fold_update--; #endif if (change_cnt) changed_lines(oap->start.lnum, 0, oap->end.lnum + 1, 0L); if (!change_cnt && oap->is_VIsual) // No change: need to remove the Visual selection redraw_curbuf_later(UPD_INVERTED); // Set '[ mark if something changed. Keep the last end // position from do_addsub(). if (change_cnt > 0 && (cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) curbuf->b_op_start = startpos; if (change_cnt > p_report) smsg(NGETTEXT("%d line changed", "%d lines changed", change_cnt), change_cnt); } } /* * Add or subtract 'Prenum1' from a number in a line * op_type is OP_NR_ADD or OP_NR_SUB * * Returns TRUE if some character was changed. */ static int do_addsub( int op_type, pos_T *pos, int length, linenr_T Prenum1) { int col; char_u *buf1; char_u buf2[NUMBUFLEN]; int pre; // 'X'/'x': hex; '0': octal; 'B'/'b': bin static int hexupper = FALSE; // 0xABC uvarnumber_T n; uvarnumber_T oldn; char_u *ptr; int c; int todel; int do_hex; int do_oct; int do_bin; int do_alpha; int do_unsigned; int firstdigit; int subtract; int negative = FALSE; int was_positive = TRUE; int visual = VIsual_active; int did_change = FALSE; pos_T save_cursor = curwin->w_cursor; int maxlen = 0; pos_T startpos; pos_T endpos; colnr_T save_coladd = 0; do_hex = (vim_strchr(curbuf->b_p_nf, 'x') != NULL); // "heX" do_oct = (vim_strchr(curbuf->b_p_nf, 'o') != NULL); // "Octal" do_bin = (vim_strchr(curbuf->b_p_nf, 'b') != NULL); // "Bin" do_alpha = (vim_strchr(curbuf->b_p_nf, 'p') != NULL); // "alPha" do_unsigned = (vim_strchr(curbuf->b_p_nf, 'u') != NULL); // "Unsigned" if (virtual_active()) { save_coladd = pos->coladd; pos->coladd = 0; } curwin->w_cursor = *pos; ptr = ml_get(pos->lnum); col = pos->col; if (*ptr == NUL || col + !!save_coladd >= (int)STRLEN(ptr)) goto theend; /* * First check if we are on a hexadecimal number, after the "0x". */ if (!VIsual_active) { if (do_bin) while (col > 0 && vim_isbdigit(ptr[col])) { --col; if (has_mbyte) col -= (*mb_head_off)(ptr, ptr + col); } if (do_hex) while (col > 0 && vim_isxdigit(ptr[col])) { --col; if (has_mbyte) col -= (*mb_head_off)(ptr, ptr + col); } if ( do_bin && do_hex && ! ((col > 0 && (ptr[col] == 'X' || ptr[col] == 'x') && ptr[col - 1] == '0' && (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1)) && vim_isxdigit(ptr[col + 1])))) { // In case of binary/hexadecimal pattern overlap match, rescan col = pos->col; while (col > 0 && vim_isdigit(ptr[col])) { col--; if (has_mbyte) col -= (*mb_head_off)(ptr, ptr + col); } } if (( do_hex && col > 0 && (ptr[col] == 'X' || ptr[col] == 'x') && ptr[col - 1] == '0' && (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1)) && vim_isxdigit(ptr[col + 1])) || ( do_bin && col > 0 && (ptr[col] == 'B' || ptr[col] == 'b') && ptr[col - 1] == '0' && (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1)) && vim_isbdigit(ptr[col + 1]))) { // Found hexadecimal or binary number, move to its start. --col; if (has_mbyte) col -= (*mb_head_off)(ptr, ptr + col); } else { /* * Search forward and then backward to find the start of number. */ col = pos->col; while (ptr[col] != NUL && !vim_isdigit(ptr[col]) && !(do_alpha && ASCII_ISALPHA(ptr[col]))) col += mb_ptr2len(ptr + col); while (col > 0 && vim_isdigit(ptr[col - 1]) && !(do_alpha && ASCII_ISALPHA(ptr[col]))) { --col; if (has_mbyte) col -= (*mb_head_off)(ptr, ptr + col); } } } if (visual) { while (ptr[col] != NUL && length > 0 && !vim_isdigit(ptr[col]) && !(do_alpha && ASCII_ISALPHA(ptr[col]))) { int mb_len = mb_ptr2len(ptr + col); col += mb_len; length -= mb_len; } if (length == 0) goto theend; if (col > pos->col && ptr[col - 1] == '-' && (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1)) && !do_unsigned) { negative = TRUE; was_positive = FALSE; } } /* * If a number was found, and saving for undo works, replace the number. */ firstdigit = ptr[col]; if (!VIM_ISDIGIT(firstdigit) && !(do_alpha && ASCII_ISALPHA(firstdigit))) { beep_flush(); goto theend; } if (do_alpha && ASCII_ISALPHA(firstdigit)) { // decrement or increment alphabetic character if (op_type == OP_NR_SUB) { if (CharOrd(firstdigit) < Prenum1) { if (isupper(firstdigit)) firstdigit = 'A'; else firstdigit = 'a'; } else firstdigit -= Prenum1; } else { if (26 - CharOrd(firstdigit) - 1 < Prenum1) { if (isupper(firstdigit)) firstdigit = 'Z'; else firstdigit = 'z'; } else firstdigit += Prenum1; } curwin->w_cursor.col = col; if (!did_change) startpos = curwin->w_cursor; did_change = TRUE; (void)del_char(FALSE); ins_char(firstdigit); endpos = curwin->w_cursor; curwin->w_cursor.col = col; } else { pos_T save_pos; int i; if (col > 0 && ptr[col - 1] == '-' && (!has_mbyte || !(*mb_head_off)(ptr, ptr + col - 1)) && !visual && !do_unsigned) { // negative number --col; negative = TRUE; } // get the number value (unsigned) if (visual && VIsual_mode != 'V') maxlen = (curbuf->b_visual.vi_curswant == MAXCOL ? (int)STRLEN(ptr) - col : length); int overflow = FALSE; vim_str2nr(ptr + col, &pre, &length, 0 + (do_bin ? STR2NR_BIN : 0) + (do_oct ? STR2NR_OCT : 0) + (do_hex ? STR2NR_HEX : 0), NULL, &n, maxlen, FALSE, &overflow); // ignore leading '-' for hex and octal and bin numbers if (pre && negative) { ++col; --length; negative = FALSE; } // add or subtract subtract = FALSE; if (op_type == OP_NR_SUB) subtract ^= TRUE; if (negative) subtract ^= TRUE; oldn = n; if (!overflow) // if number is too big don't add/subtract { if (subtract) n -= (uvarnumber_T)Prenum1; else n += (uvarnumber_T)Prenum1; } // handle wraparound for decimal numbers if (!pre) { if (subtract) { if (n > oldn) { n = 1 + (n ^ (uvarnumber_T)-1); negative ^= TRUE; } } else { // add if (n < oldn) { n = (n ^ (uvarnumber_T)-1); negative ^= TRUE; } } if (n == 0) negative = FALSE; } if (do_unsigned && negative) { if (subtract) // sticking at zero. n = (uvarnumber_T)0; else // sticking at 2^64 - 1. n = (uvarnumber_T)(-1); negative = FALSE; } if (visual && !was_positive && !negative && col > 0) { // need to remove the '-' col--; length++; } /* * Delete the old number. */ curwin->w_cursor.col = col; if (!did_change) startpos = curwin->w_cursor; did_change = TRUE; todel = length; c = gchar_cursor(); /* * Don't include the '-' in the length, only the length of the * part after it is kept the same. */ if (c == '-') --length; save_pos = curwin->w_cursor; for (i = 0; i < todel; ++i) { if (c < 0x100 && isalpha(c)) { if (isupper(c)) hexupper = TRUE; else hexupper = FALSE; } inc_cursor(); c = gchar_cursor(); } curwin->w_cursor = save_pos; /* * Prepare the leading characters in buf1[]. * When there are many leading zeros it could be very long. * Allocate a bit too much. */ buf1 = alloc(length + NUMBUFLEN); if (buf1 == NULL) goto theend; ptr = buf1; if (negative && (!visual || was_positive)) *ptr++ = '-'; if (pre) { *ptr++ = '0'; --length; } if (pre == 'b' || pre == 'B' || pre == 'x' || pre == 'X') { *ptr++ = pre; --length; } /* * Put the number characters in buf2[]. */ if (pre == 'b' || pre == 'B') { int bit = 0; int bits = sizeof(uvarnumber_T) * 8; // leading zeros for (bit = bits; bit > 0; bit--) if ((n >> (bit - 1)) & 0x1) break; for (i = 0; bit > 0; bit--) buf2[i++] = ((n >> (bit - 1)) & 0x1) ? '1' : '0'; buf2[i] = '\0'; } else if (pre == 0) vim_snprintf((char *)buf2, NUMBUFLEN, "%llu", n); else if (pre == '0') vim_snprintf((char *)buf2, NUMBUFLEN, "%llo", n); else if (pre && hexupper) vim_snprintf((char *)buf2, NUMBUFLEN, "%llX", n); else vim_snprintf((char *)buf2, NUMBUFLEN, "%llx", n); length -= (int)STRLEN(buf2); /* * Adjust number of zeros to the new number of digits, so the * total length of the number remains the same. * Don't do this when * the result may look like an octal number. */ if (firstdigit == '0' && !(do_oct && pre == 0)) while (length-- > 0) *ptr++ = '0'; *ptr = NUL; STRCAT(buf1, buf2); // Insert just after the first character to be removed, so that any // text properties will be adjusted. Then delete the old number // afterwards. save_pos = curwin->w_cursor; if (todel > 0) inc_cursor(); ins_str(buf1); // insert the new number vim_free(buf1); // del_char() will also mark line needing displaying if (todel > 0) { int bytes_after = (int)STRLEN(ml_get_curline()) - curwin->w_cursor.col; // Delete the one character before the insert. curwin->w_cursor = save_pos; (void)del_char(FALSE); curwin->w_cursor.col = (colnr_T)(STRLEN(ml_get_curline()) - bytes_after); --todel; } while (todel-- > 0) (void)del_char(FALSE); endpos = curwin->w_cursor; if (did_change && curwin->w_cursor.col) --curwin->w_cursor.col; } if (did_change && (cmdmod.cmod_flags & CMOD_LOCKMARKS) == 0) { // set the '[ and '] marks curbuf->b_op_start = startpos; curbuf->b_op_end = endpos; if (curbuf->b_op_end.col > 0) --curbuf->b_op_end.col; } theend: if (visual) curwin->w_cursor = save_cursor; else if (did_change) curwin->w_set_curswant = TRUE; else if (virtual_active()) curwin->w_cursor.coladd = save_coladd; return did_change; } void clear_oparg(oparg_T *oap) { CLEAR_POINTER(oap); } /* * Count the number of bytes, characters and "words" in a line. * * "Words" are counted by looking for boundaries between non-space and * space characters. (it seems to produce results that match 'wc'.) * * Return value is byte count; word count for the line is added to "*wc". * Char count is added to "*cc". * * The function will only examine the first "limit" characters in the * line, stopping if it encounters an end-of-line (NUL byte). In that * case, eol_size will be added to the character count to account for * the size of the EOL character. */ static varnumber_T line_count_info( char_u *line, varnumber_T *wc, varnumber_T *cc, varnumber_T limit, int eol_size) { varnumber_T i; varnumber_T words = 0; varnumber_T chars = 0; int is_word = 0; for (i = 0; i < limit && line[i] != NUL; ) { if (is_word) { if (vim_isspace(line[i])) { words++; is_word = 0; } } else if (!vim_isspace(line[i])) is_word = 1; ++chars; i += (*mb_ptr2len)(line + i); } if (is_word) words++; *wc += words; // Add eol_size if the end of line was reached before hitting limit. if (i < limit && line[i] == NUL) { i += eol_size; chars += eol_size; } *cc += chars; return i; } /* * Give some info about the position of the cursor (for "g CTRL-G"). * In Visual mode, give some info about the selected region. (In this case, * the *_count_cursor variables store running totals for the selection.) * When "dict" is not NULL store the info there instead of showing it. */ void cursor_pos_info(dict_T *dict) { char_u *p; char_u buf1[50]; char_u buf2[40]; linenr_T lnum; varnumber_T byte_count = 0; varnumber_T bom_count = 0; varnumber_T byte_count_cursor = 0; varnumber_T char_count = 0; varnumber_T char_count_cursor = 0; varnumber_T word_count = 0; varnumber_T word_count_cursor = 0; int eol_size; varnumber_T last_check = 100000L; long line_count_selected = 0; pos_T min_pos, max_pos; oparg_T oparg; struct block_def bd; /* * Compute the length of the file in characters. */ if (curbuf->b_ml.ml_flags & ML_EMPTY) { if (dict == NULL) { msg(_(no_lines_msg)); return; } } else { if (get_fileformat(curbuf) == EOL_DOS) eol_size = 2; else eol_size = 1; if (VIsual_active) { if (LT_POS(VIsual, curwin->w_cursor)) { min_pos = VIsual; max_pos = curwin->w_cursor; } else { min_pos = curwin->w_cursor; max_pos = VIsual; } if (*p_sel == 'e' && max_pos.col > 0) --max_pos.col; if (VIsual_mode == Ctrl_V) { #ifdef FEAT_LINEBREAK char_u * saved_sbr = p_sbr; char_u * saved_w_sbr = curwin->w_p_sbr; // Make 'sbr' empty for a moment to get the correct size. p_sbr = empty_option; curwin->w_p_sbr = empty_option; #endif oparg.is_VIsual = 1; oparg.block_mode = TRUE; oparg.op_type = OP_NOP; getvcols(curwin, &min_pos, &max_pos, &oparg.start_vcol, &oparg.end_vcol); #ifdef FEAT_LINEBREAK p_sbr = saved_sbr; curwin->w_p_sbr = saved_w_sbr; #endif if (curwin->w_curswant == MAXCOL) oparg.end_vcol = MAXCOL; // Swap the start, end vcol if needed if (oparg.end_vcol < oparg.start_vcol) { oparg.end_vcol += oparg.start_vcol; oparg.start_vcol = oparg.end_vcol - oparg.start_vcol; oparg.end_vcol -= oparg.start_vcol; } } line_count_selected = max_pos.lnum - min_pos.lnum + 1; } for (lnum = 1; lnum <= curbuf->b_ml.ml_line_count; ++lnum) { // Check for a CTRL-C every 100000 characters. if (byte_count > last_check) { ui_breakcheck(); if (got_int) return; last_check = byte_count + 100000L; } // Do extra processing for VIsual mode. if (VIsual_active && lnum >= min_pos.lnum && lnum <= max_pos.lnum) { char_u *s = NULL; long len = 0L; switch (VIsual_mode) { case Ctrl_V: virtual_op = virtual_active(); block_prep(&oparg, &bd, lnum, 0); virtual_op = MAYBE; s = bd.textstart; len = (long)bd.textlen; break; case 'V': s = ml_get(lnum); len = MAXCOL; break; case 'v': { colnr_T start_col = (lnum == min_pos.lnum) ? min_pos.col : 0; colnr_T end_col = (lnum == max_pos.lnum) ? max_pos.col - start_col + 1 : MAXCOL; s = ml_get(lnum) + start_col; len = end_col; } break; } if (s != NULL) { byte_count_cursor += line_count_info(s, &word_count_cursor, &char_count_cursor, len, eol_size); if (lnum == curbuf->b_ml.ml_line_count && !curbuf->b_p_eol && (curbuf->b_p_bin || !curbuf->b_p_fixeol) && (long)STRLEN(s) < len) byte_count_cursor -= eol_size; } } else { // In non-visual mode, check for the line the cursor is on if (lnum == curwin->w_cursor.lnum) { word_count_cursor += word_count; char_count_cursor += char_count; byte_count_cursor = byte_count + line_count_info(ml_get(lnum), &word_count_cursor, &char_count_cursor, (varnumber_T)(curwin->w_cursor.col + 1), eol_size); } } // Add to the running totals byte_count += line_count_info(ml_get(lnum), &word_count, &char_count, (varnumber_T)MAXCOL, eol_size); } // Correction for when last line doesn't have an EOL. if (!curbuf->b_p_eol && (curbuf->b_p_bin || !curbuf->b_p_fixeol)) byte_count -= eol_size; if (dict == NULL) { if (VIsual_active) { if (VIsual_mode == Ctrl_V && curwin->w_curswant < MAXCOL) { getvcols(curwin, &min_pos, &max_pos, &min_pos.col, &max_pos.col); vim_snprintf((char *)buf1, sizeof(buf1), _("%ld Cols; "), (long)(oparg.end_vcol - oparg.start_vcol + 1)); } else buf1[0] = NUL; if (char_count_cursor == byte_count_cursor && char_count == byte_count) vim_snprintf((char *)IObuff, IOSIZE, _("Selected %s%ld of %ld Lines; %lld of %lld Words; %lld of %lld Bytes"), buf1, line_count_selected, (long)curbuf->b_ml.ml_line_count, word_count_cursor, word_count, byte_count_cursor, byte_count); else vim_snprintf((char *)IObuff, IOSIZE, _("Selected %s%ld of %ld Lines; %lld of %lld Words; %lld of %lld Chars; %lld of %lld Bytes"), buf1, line_count_selected, (long)curbuf->b_ml.ml_line_count, word_count_cursor, word_count, char_count_cursor, char_count, byte_count_cursor, byte_count); } else { p = ml_get_curline(); validate_virtcol(); col_print(buf1, sizeof(buf1), (int)curwin->w_cursor.col + 1, (int)curwin->w_virtcol + 1); col_print(buf2, sizeof(buf2), (int)STRLEN(p), linetabsize_str(p)); if (char_count_cursor == byte_count_cursor && char_count == byte_count) vim_snprintf((char *)IObuff, IOSIZE, _("Col %s of %s; Line %ld of %ld; Word %lld of %lld; Byte %lld of %lld"), (char *)buf1, (char *)buf2, (long)curwin->w_cursor.lnum, (long)curbuf->b_ml.ml_line_count, word_count_cursor, word_count, byte_count_cursor, byte_count); else vim_snprintf((char *)IObuff, IOSIZE, _("Col %s of %s; Line %ld of %ld; Word %lld of %lld; Char %lld of %lld; Byte %lld of %lld"), (char *)buf1, (char *)buf2, (long)curwin->w_cursor.lnum, (long)curbuf->b_ml.ml_line_count, word_count_cursor, word_count, char_count_cursor, char_count, byte_count_cursor, byte_count); } } bom_count = bomb_size(); if (dict == NULL && bom_count > 0) { size_t len = STRLEN(IObuff); vim_snprintf((char *)IObuff + len, IOSIZE - len, _("(+%lld for BOM)"), bom_count); } if (dict == NULL) { // Don't shorten this message, the user asked for it. p = p_shm; p_shm = (char_u *)""; msg((char *)IObuff); p_shm = p; } } #if defined(FEAT_EVAL) if (dict != NULL) { dict_add_number(dict, "words", word_count); dict_add_number(dict, "chars", char_count); dict_add_number(dict, "bytes", byte_count + bom_count); dict_add_number(dict, VIsual_active ? "visual_bytes" : "cursor_bytes", byte_count_cursor); dict_add_number(dict, VIsual_active ? "visual_chars" : "cursor_chars", char_count_cursor); dict_add_number(dict, VIsual_active ? "visual_words" : "cursor_words", word_count_cursor); } #endif } /* * Handle indent and format operators and visual mode ":". */ static void op_colon(oparg_T *oap) { stuffcharReadbuff(':'); if (oap->is_VIsual) stuffReadbuff((char_u *)"'<,'>"); else { // Make the range look nice, so it can be repeated. if (oap->start.lnum == curwin->w_cursor.lnum) stuffcharReadbuff('.'); else stuffnumReadbuff((long)oap->start.lnum); #ifdef FEAT_FOLDING // When using !! on a closed fold the range ".!" works best to operate // on, it will be made the whole closed fold later. linenr_T endOfStartFold = oap->start.lnum; (void)hasFolding(oap->start.lnum, NULL, &endOfStartFold); #endif if (oap->end.lnum != oap->start.lnum #ifdef FEAT_FOLDING && oap->end.lnum != endOfStartFold #endif ) { // Make it a range with the end line. stuffcharReadbuff(','); if (oap->end.lnum == curwin->w_cursor.lnum) stuffcharReadbuff('.'); else if (oap->end.lnum == curbuf->b_ml.ml_line_count) stuffcharReadbuff('$'); else if (oap->start.lnum == curwin->w_cursor.lnum #ifdef FEAT_FOLDING // do not use ".+number" for a closed fold, it would count // folded lines twice && !hasFolding(oap->end.lnum, NULL, NULL) #endif ) { stuffReadbuff((char_u *)".+"); stuffnumReadbuff((long)oap->line_count - 1); } else stuffnumReadbuff((long)oap->end.lnum); } } if (oap->op_type != OP_COLON) stuffReadbuff((char_u *)"!"); if (oap->op_type == OP_INDENT) { if (*get_equalprg() == NUL) stuffReadbuff((char_u *)"indent"); else stuffReadbuff(get_equalprg()); stuffReadbuff((char_u *)"\n"); } else if (oap->op_type == OP_FORMAT) { if (*curbuf->b_p_fp != NUL) stuffReadbuff(curbuf->b_p_fp); else if (*p_fp != NUL) stuffReadbuff(p_fp); else stuffReadbuff((char_u *)"fmt"); stuffReadbuff((char_u *)"\n']"); } // do_cmdline() does the rest } // callback function for 'operatorfunc' static callback_T opfunc_cb; /* * Process the 'operatorfunc' option value. * Returns OK or FAIL. */ char * did_set_operatorfunc(optset_T *args UNUSED) { if (option_set_callback_func(p_opfunc, &opfunc_cb) == FAIL) return e_invalid_argument; return NULL; } #if defined(EXITFREE) || defined(PROTO) void free_operatorfunc_option(void) { # ifdef FEAT_EVAL free_callback(&opfunc_cb); # endif } #endif #if defined(FEAT_EVAL) || defined(PROTO) /* * Mark the global 'operatorfunc' callback with "copyID" so that it is not * garbage collected. */ int set_ref_in_opfunc(int copyID UNUSED) { int abort = FALSE; abort = set_ref_in_callback(&opfunc_cb, copyID); return abort; } #endif /* * Handle the "g@" operator: call 'operatorfunc'. */ static void op_function(oparg_T *oap UNUSED) { #ifdef FEAT_EVAL typval_T argv[2]; pos_T orig_start = curbuf->b_op_start; pos_T orig_end = curbuf->b_op_end; typval_T rettv; if (*p_opfunc == NUL) emsg(_(e_operatorfunc_is_empty)); else { // Set '[ and '] marks to text to be operated on. curbuf->b_op_start = oap->start; curbuf->b_op_end = oap->end; if (oap->motion_type != MLINE && !oap->inclusive) // Exclude the end position. decl(&curbuf->b_op_end); argv[0].v_type = VAR_STRING; if (oap->block_mode) argv[0].vval.v_string = (char_u *)"block"; else if (oap->motion_type == MLINE) argv[0].vval.v_string = (char_u *)"line"; else argv[0].vval.v_string = (char_u *)"char"; argv[1].v_type = VAR_UNKNOWN; // Reset virtual_op so that 'virtualedit' can be changed in the // function. int save_virtual_op = virtual_op; virtual_op = MAYBE; // Reset finish_op so that mode() returns the right value. int save_finish_op = finish_op; finish_op = FALSE; if (call_callback(&opfunc_cb, 0, &rettv, 1, argv) != FAIL) clear_tv(&rettv); virtual_op = save_virtual_op; finish_op = save_finish_op; if (cmdmod.cmod_flags & CMOD_LOCKMARKS) { curbuf->b_op_start = orig_start; curbuf->b_op_end = orig_end; } } #else emsg(_(e_eval_feature_not_available)); #endif } /* * Calculate start/end virtual columns for operating in block mode. */ static void get_op_vcol( oparg_T *oap, colnr_T redo_VIsual_vcol, int initial) // when TRUE adjust position for 'selectmode' { colnr_T start, end; if (VIsual_mode != Ctrl_V || (!initial && oap->end.col < curwin->w_width)) return; oap->block_mode = TRUE; // prevent from moving onto a trail byte if (has_mbyte) mb_adjustpos(curwin->w_buffer, &oap->end); getvvcol(curwin, &(oap->start), &oap->start_vcol, NULL, &oap->end_vcol); if (!redo_VIsual_busy) { getvvcol(curwin, &(oap->end), &start, NULL, &end); if (start < oap->start_vcol) oap->start_vcol = start; if (end > oap->end_vcol) { if (initial && *p_sel == 'e' && start >= 1 && start - 1 >= oap->end_vcol) oap->end_vcol = start - 1; else oap->end_vcol = end; } } // if '$' was used, get oap->end_vcol from longest line if (curwin->w_curswant == MAXCOL) { curwin->w_cursor.col = MAXCOL; oap->end_vcol = 0; for (curwin->w_cursor.lnum = oap->start.lnum; curwin->w_cursor.lnum <= oap->end.lnum; ++curwin->w_cursor.lnum) { getvvcol(curwin, &curwin->w_cursor, NULL, NULL, &end); if (end > oap->end_vcol) oap->end_vcol = end; } } else if (redo_VIsual_busy) oap->end_vcol = oap->start_vcol + redo_VIsual_vcol - 1; // Correct oap->end.col and oap->start.col to be the // upper-left and lower-right corner of the block area. // // (Actually, this does convert column positions into character // positions) curwin->w_cursor.lnum = oap->end.lnum; coladvance(oap->end_vcol); oap->end = curwin->w_cursor; curwin->w_cursor = oap->start; coladvance(oap->start_vcol); oap->start = curwin->w_cursor; } // Information for redoing the previous Visual selection. typedef struct { int rv_mode; // 'v', 'V', or Ctrl-V linenr_T rv_line_count; // number of lines colnr_T rv_vcol; // number of cols or end column long rv_count; // count for Visual operator int rv_arg; // extra argument } redo_VIsual_T; static int is_ex_cmdchar(cmdarg_T *cap) { return cap->cmdchar == ':' || cap->cmdchar == K_COMMAND || cap->cmdchar == K_SCRIPT_COMMAND; } /* * Handle an operator after Visual mode or when the movement is finished. * "gui_yank" is true when yanking text for the clipboard. */ void do_pending_operator(cmdarg_T *cap, int old_col, int gui_yank) { oparg_T *oap = cap->oap; pos_T old_cursor; int empty_region_error; int restart_edit_save; #ifdef FEAT_LINEBREAK int lbr_saved = curwin->w_p_lbr; #endif // The visual area is remembered for redo static redo_VIsual_T redo_VIsual = {NUL, 0, 0, 0,0}; int include_line_break = FALSE; #if defined(FEAT_CLIPBOARD) // Yank the visual area into the GUI selection register before we operate // on it and lose it forever. // Don't do it if a specific register was specified, so that ""x"*P works. // This could call do_pending_operator() recursively, but that's OK // because gui_yank will be TRUE for the nested call. if ((clip_star.available || clip_plus.available) && oap->op_type != OP_NOP && !gui_yank && VIsual_active && !redo_VIsual_busy && oap->regname == 0) clip_auto_select(); #endif old_cursor = curwin->w_cursor; // If an operation is pending, handle it... if ((finish_op || VIsual_active) && oap->op_type != OP_NOP) { // Yank can be redone when 'y' is in 'cpoptions', but not when yanking // for the clipboard. int redo_yank = vim_strchr(p_cpo, CPO_YANK) != NULL && !gui_yank; #ifdef FEAT_LINEBREAK // Avoid a problem with unwanted linebreaks in block mode. (void)reset_lbr(); #endif oap->is_VIsual = VIsual_active; if (oap->motion_force == 'V') oap->motion_type = MLINE; else if (oap->motion_force == 'v') { // If the motion was linewise, "inclusive" will not have been set. // Use "exclusive" to be consistent. Makes "dvj" work nice. if (oap->motion_type == MLINE) oap->inclusive = FALSE; // If the motion already was characterwise, toggle "inclusive" else if (oap->motion_type == MCHAR) oap->inclusive = !oap->inclusive; oap->motion_type = MCHAR; } else if (oap->motion_force == Ctrl_V) { // Change line- or characterwise motion into Visual block mode. if (!VIsual_active) { VIsual_active = TRUE; VIsual = oap->start; } VIsual_mode = Ctrl_V; VIsual_select = FALSE; VIsual_reselect = FALSE; } // Only redo yank when 'y' flag is in 'cpoptions'. // Never redo "zf" (define fold). if ((redo_yank || oap->op_type != OP_YANK) && ((!VIsual_active || oap->motion_force) // Also redo Operator-pending Visual mode mappings || (VIsual_active && is_ex_cmdchar(cap) && oap->op_type != OP_COLON)) && cap->cmdchar != 'D' #ifdef FEAT_FOLDING && oap->op_type != OP_FOLD && oap->op_type != OP_FOLDOPEN && oap->op_type != OP_FOLDOPENREC && oap->op_type != OP_FOLDCLOSE && oap->op_type != OP_FOLDCLOSEREC && oap->op_type != OP_FOLDDEL && oap->op_type != OP_FOLDDELREC #endif ) { prep_redo(oap->regname, cap->count0, get_op_char(oap->op_type), get_extra_op_char(oap->op_type), oap->motion_force, cap->cmdchar, cap->nchar); if (cap->cmdchar == '/' || cap->cmdchar == '?') // was a search { // If 'cpoptions' does not contain 'r', insert the search // pattern to really repeat the same command. if (vim_strchr(p_cpo, CPO_REDO) == NULL) AppendToRedobuffLit(cap->searchbuf, -1); AppendToRedobuff(NL_STR); } else if (is_ex_cmdchar(cap)) { // do_cmdline() has stored the first typed line in // "repeat_cmdline". When several lines are typed repeating // won't be possible. if (repeat_cmdline == NULL) ResetRedobuff(); else { if (cap->cmdchar == ':') AppendToRedobuffLit(repeat_cmdline, -1); else AppendToRedobuffSpec(repeat_cmdline); AppendToRedobuff(NL_STR); VIM_CLEAR(repeat_cmdline); } } } if (redo_VIsual_busy) { // Redo of an operation on a Visual area. Use the same size from // redo_VIsual.rv_line_count and redo_VIsual.rv_vcol. oap->start = curwin->w_cursor; curwin->w_cursor.lnum += redo_VIsual.rv_line_count - 1; if (curwin->w_cursor.lnum > curbuf->b_ml.ml_line_count) curwin->w_cursor.lnum = curbuf->b_ml.ml_line_count; VIsual_mode = redo_VIsual.rv_mode; if (redo_VIsual.rv_vcol == MAXCOL || VIsual_mode == 'v') { if (VIsual_mode == 'v') { if (redo_VIsual.rv_line_count <= 1) { validate_virtcol(); curwin->w_curswant = curwin->w_virtcol + redo_VIsual.rv_vcol - 1; } else curwin->w_curswant = redo_VIsual.rv_vcol; } else { curwin->w_curswant = MAXCOL; } coladvance(curwin->w_curswant); } cap->count0 = redo_VIsual.rv_count; if (redo_VIsual.rv_count != 0) cap->count1 = redo_VIsual.rv_count; else cap->count1 = 1; } else if (VIsual_active) { if (!gui_yank) { // Save the current VIsual area for '< and '> marks, and "gv" curbuf->b_visual.vi_start = VIsual; curbuf->b_visual.vi_end = curwin->w_cursor; curbuf->b_visual.vi_mode = VIsual_mode; restore_visual_mode(); curbuf->b_visual.vi_curswant = curwin->w_curswant; #ifdef FEAT_EVAL curbuf->b_visual_mode_eval = VIsual_mode; #endif } // In Select mode, a linewise selection is operated upon like a // characterwise selection. // Special case: gH<Del> deletes the last line. if (VIsual_select && VIsual_mode == 'V' && cap->oap->op_type != OP_DELETE) { if (LT_POS(VIsual, curwin->w_cursor)) { VIsual.col = 0; curwin->w_cursor.col = (colnr_T)STRLEN(ml_get(curwin->w_cursor.lnum)); } else { curwin->w_cursor.col = 0; VIsual.col = (colnr_T)STRLEN(ml_get(VIsual.lnum)); } VIsual_mode = 'v'; } // If 'selection' is "exclusive", backup one character for // charwise selections. else if (VIsual_mode == 'v') include_line_break = unadjust_for_sel(); oap->start = VIsual; if (VIsual_mode == 'V') { oap->start.col = 0; oap->start.coladd = 0; } } // Set oap->start to the first position of the operated text, oap->end // to the end of the operated text. w_cursor is equal to oap->start. if (LT_POS(oap->start, curwin->w_cursor)) { #ifdef FEAT_FOLDING // Include folded lines completely. if (!VIsual_active) { if (hasFolding(oap->start.lnum, &oap->start.lnum, NULL)) oap->start.col = 0; if ((curwin->w_cursor.col > 0 || oap->inclusive || oap->motion_type == MLINE) && hasFolding(curwin->w_cursor.lnum, NULL, &curwin->w_cursor.lnum)) curwin->w_cursor.col = (colnr_T)STRLEN(ml_get_curline()); } #endif oap->end = curwin->w_cursor; curwin->w_cursor = oap->start; // w_virtcol may have been updated; if the cursor goes back to its // previous position w_virtcol becomes invalid and isn't updated // automatically. curwin->w_valid &= ~VALID_VIRTCOL; } else { #ifdef FEAT_FOLDING // Include folded lines completely. if (!VIsual_active && oap->motion_type == MLINE) { if (hasFolding(curwin->w_cursor.lnum, &curwin->w_cursor.lnum, NULL)) curwin->w_cursor.col = 0; if (hasFolding(oap->start.lnum, NULL, &oap->start.lnum)) oap->start.col = (colnr_T)STRLEN(ml_get(oap->start.lnum)); } #endif oap->end = oap->start; oap->start = curwin->w_cursor; } // Just in case lines were deleted that make the position invalid. check_pos(curwin->w_buffer, &oap->end); oap->line_count = oap->end.lnum - oap->start.lnum + 1; // Set "virtual_op" before resetting VIsual_active. virtual_op = virtual_active(); if (VIsual_active || redo_VIsual_busy) { get_op_vcol(oap, redo_VIsual.rv_vcol, TRUE); if (!redo_VIsual_busy && !gui_yank) { // Prepare to reselect and redo Visual: this is based on the // size of the Visual text resel_VIsual_mode = VIsual_mode; if (curwin->w_curswant == MAXCOL) resel_VIsual_vcol = MAXCOL; else { if (VIsual_mode != Ctrl_V) getvvcol(curwin, &(oap->end), NULL, NULL, &oap->end_vcol); if (VIsual_mode == Ctrl_V || oap->line_count <= 1) { if (VIsual_mode != Ctrl_V) getvvcol(curwin, &(oap->start), &oap->start_vcol, NULL, NULL); resel_VIsual_vcol = oap->end_vcol - oap->start_vcol + 1; } else resel_VIsual_vcol = oap->end_vcol; } resel_VIsual_line_count = oap->line_count; } // can't redo yank (unless 'y' is in 'cpoptions') and ":" if ((redo_yank || oap->op_type != OP_YANK) && oap->op_type != OP_COLON #ifdef FEAT_FOLDING && oap->op_type != OP_FOLD && oap->op_type != OP_FOLDOPEN && oap->op_type != OP_FOLDOPENREC && oap->op_type != OP_FOLDCLOSE && oap->op_type != OP_FOLDCLOSEREC && oap->op_type != OP_FOLDDEL && oap->op_type != OP_FOLDDELREC #endif && oap->motion_force == NUL ) { // Prepare for redoing. Only use the nchar field for "r", // otherwise it might be the second char of the operator. if (cap->cmdchar == 'g' && (cap->nchar == 'n' || cap->nchar == 'N')) prep_redo(oap->regname, cap->count0, get_op_char(oap->op_type), get_extra_op_char(oap->op_type), oap->motion_force, cap->cmdchar, cap->nchar); else if (!is_ex_cmdchar(cap)) { int opchar = get_op_char(oap->op_type); int extra_opchar = get_extra_op_char(oap->op_type); int nchar = oap->op_type == OP_REPLACE ? cap->nchar : NUL; // reverse what nv_replace() did if (nchar == REPLACE_CR_NCHAR) nchar = CAR; else if (nchar == REPLACE_NL_NCHAR) nchar = NL; if (opchar == 'g' && extra_opchar == '@') // also repeat the count for 'operatorfunc' prep_redo_num2(oap->regname, 0L, NUL, 'v', cap->count0, opchar, extra_opchar, nchar); else prep_redo(oap->regname, 0L, NUL, 'v', opchar, extra_opchar, nchar); } if (!redo_VIsual_busy) { redo_VIsual.rv_mode = resel_VIsual_mode; redo_VIsual.rv_vcol = resel_VIsual_vcol; redo_VIsual.rv_line_count = resel_VIsual_line_count; redo_VIsual.rv_count = cap->count0; redo_VIsual.rv_arg = cap->arg; } } // oap->inclusive defaults to TRUE. // If oap->end is on a NUL (empty line) oap->inclusive becomes // FALSE. This makes "d}P" and "v}dP" work the same. if (oap->motion_force == NUL || oap->motion_type == MLINE) oap->inclusive = TRUE; if (VIsual_mode == 'V') oap->motion_type = MLINE; else { oap->motion_type = MCHAR; if (VIsual_mode != Ctrl_V && *ml_get_pos(&(oap->end)) == NUL && (include_line_break || !virtual_op)) { oap->inclusive = FALSE; // Try to include the newline, unless it's an operator // that works on lines only. if (*p_sel != 'o' && !op_on_lines(oap->op_type) && oap->end.lnum < curbuf->b_ml.ml_line_count) { ++oap->end.lnum; oap->end.col = 0; oap->end.coladd = 0; ++oap->line_count; } } } redo_VIsual_busy = FALSE; // Switch Visual off now, so screen updating does // not show inverted text when the screen is redrawn. // With OP_YANK and sometimes with OP_COLON and OP_FILTER there is // no screen redraw, so it is done here to remove the inverted // part. if (!gui_yank) { VIsual_active = FALSE; setmouse(); mouse_dragging = 0; may_clear_cmdline(); if ((oap->op_type == OP_YANK || oap->op_type == OP_COLON || oap->op_type == OP_FUNCTION || oap->op_type == OP_FILTER) && oap->motion_force == NUL) { #ifdef FEAT_LINEBREAK // make sure redrawing is correct restore_lbr(lbr_saved); #endif redraw_curbuf_later(UPD_INVERTED); } } } // Include the trailing byte of a multi-byte char. if (has_mbyte && oap->inclusive) { int l; l = (*mb_ptr2len)(ml_get_pos(&oap->end)); if (l > 1) oap->end.col += l - 1; } curwin->w_set_curswant = TRUE; // oap->empty is set when start and end are the same. The inclusive // flag affects this too, unless yanking and the end is on a NUL. oap->empty = (oap->motion_type == MCHAR && (!oap->inclusive || (oap->op_type == OP_YANK && gchar_pos(&oap->end) == NUL)) && EQUAL_POS(oap->start, oap->end) && !(virtual_op && oap->start.coladd != oap->end.coladd)); // For delete, change and yank, it's an error to operate on an // empty region, when 'E' included in 'cpoptions' (Vi compatible). empty_region_error = (oap->empty && vim_strchr(p_cpo, CPO_EMPTYREGION) != NULL); // Force a redraw when operating on an empty Visual region, when // 'modifiable is off or creating a fold. if (oap->is_VIsual && (oap->empty || !curbuf->b_p_ma #ifdef FEAT_FOLDING || oap->op_type == OP_FOLD #endif )) { #ifdef FEAT_LINEBREAK restore_lbr(lbr_saved); #endif redraw_curbuf_later(UPD_INVERTED); } // If the end of an operator is in column one while oap->motion_type // is MCHAR and oap->inclusive is FALSE, we put op_end after the last // character in the previous line. If op_start is on or before the // first non-blank in the line, the operator becomes linewise // (strange, but that's the way vi does it). if ( oap->motion_type == MCHAR && oap->inclusive == FALSE && !(cap->retval & CA_NO_ADJ_OP_END) && oap->end.col == 0 && (!oap->is_VIsual || *p_sel == 'o') && !oap->block_mode && oap->line_count > 1) { oap->end_adjusted = TRUE; // remember that we did this --oap->line_count; --oap->end.lnum; if (inindent(0)) oap->motion_type = MLINE; else { oap->end.col = (colnr_T)STRLEN(ml_get(oap->end.lnum)); if (oap->end.col) { --oap->end.col; oap->inclusive = TRUE; } } } else oap->end_adjusted = FALSE; switch (oap->op_type) { case OP_LSHIFT: case OP_RSHIFT: op_shift(oap, TRUE, oap->is_VIsual ? (int)cap->count1 : 1); auto_format(FALSE, TRUE); break; case OP_JOIN_NS: case OP_JOIN: if (oap->line_count < 2) oap->line_count = 2; if (curwin->w_cursor.lnum + oap->line_count - 1 > curbuf->b_ml.ml_line_count) beep_flush(); else { (void)do_join(oap->line_count, oap->op_type == OP_JOIN, TRUE, TRUE, TRUE); auto_format(FALSE, TRUE); } break; case OP_DELETE: VIsual_reselect = FALSE; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); } else { (void)op_delete(oap); // save cursor line for undo if it wasn't saved yet if (oap->motion_type == MLINE && has_format_option(FO_AUTO) && u_save_cursor() == OK) auto_format(FALSE, TRUE); } break; case OP_YANK: if (empty_region_error) { if (!gui_yank) { vim_beep(BO_OPER); CancelRedo(); } } else { #ifdef FEAT_LINEBREAK restore_lbr(lbr_saved); #endif oap->excl_tr_ws = cap->cmdchar == 'z'; (void)op_yank(oap, FALSE, !gui_yank); } check_cursor_col(); break; case OP_CHANGE: VIsual_reselect = FALSE; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); } else { // This is a new edit command, not a restart. Need to // remember it to make 'insertmode' work with mappings for // Visual mode. But do this only once and not when typed and // 'insertmode' isn't set. if (p_im || !KeyTyped) restart_edit_save = restart_edit; else restart_edit_save = 0; restart_edit = 0; #ifdef FEAT_LINEBREAK // Restore linebreak, so that when the user edits it looks as // before. restore_lbr(lbr_saved); #endif if (op_change(oap)) // will call edit() cap->retval |= CA_COMMAND_BUSY; if (restart_edit == 0) restart_edit = restart_edit_save; } break; case OP_FILTER: if (vim_strchr(p_cpo, CPO_FILTER) != NULL) AppendToRedobuff((char_u *)"!\r"); // use any last used !cmd else bangredo = TRUE; // do_bang() will put cmd in redo buffer // FALLTHROUGH case OP_INDENT: case OP_COLON: // If 'equalprg' is empty, do the indenting internally. if (oap->op_type == OP_INDENT && *get_equalprg() == NUL) { if (curbuf->b_p_lisp) { #ifdef FEAT_EVAL if (use_indentexpr_for_lisp()) op_reindent(oap, get_expr_indent); else #endif op_reindent(oap, get_lisp_indent); break; } op_reindent(oap, #ifdef FEAT_EVAL *curbuf->b_p_inde != NUL ? get_expr_indent : #endif get_c_indent); break; } op_colon(oap); break; case OP_TILDE: case OP_UPPER: case OP_LOWER: case OP_ROT13: if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); } else op_tilde(oap); check_cursor_col(); break; case OP_FORMAT: #if defined(FEAT_EVAL) if (*curbuf->b_p_fex != NUL) op_formatexpr(oap); // use expression else #endif { if (*p_fp != NUL || *curbuf->b_p_fp != NUL) op_colon(oap); // use external command else op_format(oap, FALSE); // use internal function } break; case OP_FORMAT2: op_format(oap, TRUE); // use internal function break; case OP_FUNCTION: { redo_VIsual_T save_redo_VIsual = redo_VIsual; #ifdef FEAT_LINEBREAK // Restore linebreak, so that when the user edits it looks as // before. restore_lbr(lbr_saved); #endif // call 'operatorfunc' op_function(oap); // Restore the info for redoing Visual mode, the function may // invoke another operator and unintentionally change it. redo_VIsual = save_redo_VIsual; break; } case OP_INSERT: case OP_APPEND: VIsual_reselect = FALSE; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); } else { // This is a new edit command, not a restart. Need to // remember it to make 'insertmode' work with mappings for // Visual mode. But do this only once. restart_edit_save = restart_edit; restart_edit = 0; #ifdef FEAT_LINEBREAK // Restore linebreak, so that when the user edits it looks as // before. restore_lbr(lbr_saved); #endif op_insert(oap, cap->count1); #ifdef FEAT_LINEBREAK // Reset linebreak, so that formatting works correctly. (void)reset_lbr(); #endif // TODO: when inserting in several lines, should format all // the lines. auto_format(FALSE, TRUE); if (restart_edit == 0) restart_edit = restart_edit_save; else cap->retval |= CA_COMMAND_BUSY; } break; case OP_REPLACE: VIsual_reselect = FALSE; // don't reselect now if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); } else { #ifdef FEAT_LINEBREAK // Restore linebreak, so that when the user edits it looks as // before. restore_lbr(lbr_saved); #endif op_replace(oap, cap->nchar); } break; #ifdef FEAT_FOLDING case OP_FOLD: VIsual_reselect = FALSE; // don't reselect now foldCreate(oap->start.lnum, oap->end.lnum); break; case OP_FOLDOPEN: case OP_FOLDOPENREC: case OP_FOLDCLOSE: case OP_FOLDCLOSEREC: VIsual_reselect = FALSE; // don't reselect now opFoldRange(oap->start.lnum, oap->end.lnum, oap->op_type == OP_FOLDOPEN || oap->op_type == OP_FOLDOPENREC, oap->op_type == OP_FOLDOPENREC || oap->op_type == OP_FOLDCLOSEREC, oap->is_VIsual); break; case OP_FOLDDEL: case OP_FOLDDELREC: VIsual_reselect = FALSE; // don't reselect now deleteFold(oap->start.lnum, oap->end.lnum, oap->op_type == OP_FOLDDELREC, oap->is_VIsual); break; #endif case OP_NR_ADD: case OP_NR_SUB: if (empty_region_error) { vim_beep(BO_OPER); CancelRedo(); } else { VIsual_active = TRUE; #ifdef FEAT_LINEBREAK restore_lbr(lbr_saved); #endif op_addsub(oap, cap->count1, redo_VIsual.rv_arg); VIsual_active = FALSE; } check_cursor_col(); break; default: clearopbeep(oap); } virtual_op = MAYBE; if (!gui_yank) { // if 'sol' not set, go back to old column for some commands if (!p_sol && oap->motion_type == MLINE && !oap->end_adjusted && (oap->op_type == OP_LSHIFT || oap->op_type == OP_RSHIFT || oap->op_type == OP_DELETE)) { #ifdef FEAT_LINEBREAK (void)reset_lbr(); #endif coladvance(curwin->w_curswant = old_col); } } else { curwin->w_cursor = old_cursor; } oap->block_mode = FALSE; clearop(oap); motion_force = NUL; } #ifdef FEAT_LINEBREAK restore_lbr(lbr_saved); #endif }
ee61e265e003ba35821819c6874b06f3cbee7ced
af8fe84a9a43f5d7309cca301a791e9a1da6edf2
/src/ui/components/waiting.c
60cc9422acd8585f3108876ca0087a8f53e764d8
[ "Apache-2.0" ]
permissive
digitalbitbox/bitbox02-firmware
c2581b02088009385d7c40066ad940a469eca761
12cfa59f05c200a72fa204961e3a5f8b3d3c0ba0
refs/heads/master
2023-08-31T22:14:19.307352
2023-08-31T09:29:16
2023-08-31T09:29:16
190,549,724
219
87
Apache-2.0
2023-09-14T07:10:09
2019-06-06T09:00:23
C
UTF-8
C
false
false
1,984
c
waiting.c
// Copyright 2019 Shift Cryptosecurity AG // // 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 "waiting.h" #include "image.h" #include "ui_images.h" #include <hardfault.h> #include <screen.h> #include <ui/ui_util.h> #include <string.h> static void _render(component_t* component) { // TODO - add an interesting animation? ui_util_component_render_subcomponents(component); } /********************************** Component Functions **********************************/ /** * Collects all component functions. */ static component_functions_t _component_functions = { .cleanup = ui_util_component_cleanup, .render = _render, .on_event = ui_util_on_event_noop, }; /********************************** Create Instance **********************************/ /** * Creates a waiting screen. */ component_t* waiting_create(void) { component_t* waiting = malloc(sizeof(component_t)); if (!waiting) { Abort("Error: malloc waiting"); } memset(waiting, 0, sizeof(component_t)); waiting->f = &_component_functions; waiting->dimension.width = SCREEN_WIDTH; waiting->dimension.height = SCREEN_HEIGHT; waiting->position.top = 0; waiting->position.left = 0; component_t* bb2_logo = image_create( IMAGE_BB2_LOGO, sizeof(IMAGE_BB2_LOGO), IMAGE_BB2_LOGO_W, IMAGE_BB2_LOGO_H, CENTER, waiting); ui_util_add_sub_component(waiting, bb2_logo); return waiting; }
78b05fbe332103f9dce1dd5c571141b5840e33c5
f367e4b66a1ee42e85830b31df88f63723c36a47
/plugins/filter_nightfall/nightfall.c
3e37d2a0bc49c43a54b56fa921e4bbfe8a2c09cc
[ "Apache-2.0" ]
permissive
fluent/fluent-bit
06873e441162b92941024e9a7e9e8fc934150bf7
1a41f49dc2f3ae31a780caa9ffd6137b1d703065
refs/heads/master
2023-09-05T13:44:55.347372
2023-09-05T10:14:33
2023-09-05T10:14:33
29,933,948
4,907
1,565
Apache-2.0
2023-09-14T10:17:02
2015-01-27T20:41:52
C
UTF-8
C
false
false
23,287
c
nightfall.c
/* -*- Mode: C; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Fluent Bit * ========== * Copyright (C) 2019-2021 The Fluent Bit Authors * Copyright (C) 2015-2018 Treasure Data 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 <fluent-bit/flb_filter.h> #include <fluent-bit/flb_info.h> #include <fluent-bit/flb_filter.h> #include <fluent-bit/flb_filter_plugin.h> #include <fluent-bit/flb_http_client.h> #include <fluent-bit/flb_upstream.h> #include <fluent-bit/flb_sds.h> #include <fluent-bit/flb_time.h> #include <fluent-bit/flb_pack.h> #include <fluent-bit/tls/flb_tls.h> #include <fluent-bit/flb_log_event_decoder.h> #include <fluent-bit/flb_log_event_encoder.h> #include "nightfall.h" #include "nightfall_api.h" static int redact_array_fields(msgpack_packer *new_rec_pk, int *to_redact_index, msgpack_object_array *to_redact, struct nested_obj *cur, struct mk_list *stack, char *should_pop); static int redact_map_fields(msgpack_packer *new_rec_pk, int *to_redact_index, msgpack_object_array *to_redact, struct nested_obj *cur, struct mk_list *stack, char *should_pop); static void maybe_redact_field(msgpack_packer *new_rec_pk, msgpack_object *field, msgpack_object_array *to_redact, int *to_redact_i, int byte_offset); static int cb_nightfall_init(struct flb_filter_instance *f_ins, struct flb_config *config, void *data) { struct flb_filter_nightfall *ctx = NULL; int ret; /* Create context */ ctx = flb_calloc(1, sizeof(struct flb_filter_nightfall)); if (!ctx) { flb_errno(); return -1; } ctx->ins = f_ins; /* Populate context with config map defaults and incoming properties */ ret = flb_filter_config_map_set(f_ins, (void *) ctx); if (ret == -1) { flb_plg_error(f_ins, "configuration error"); flb_free(ctx); return -1; } if (ctx->sampling_rate <= 0 || ctx->sampling_rate > 1) { flb_plg_error(f_ins, "invalid sampling rate, must be (0,1]"); flb_free(ctx); return -1; } if (ctx->nightfall_api_key == NULL) { flb_plg_error(f_ins, "invalid Nightfall API key"); flb_free(ctx); return -1; } if (ctx->policy_id == NULL) { flb_plg_error(f_ins, "invalid Nightfall policy ID"); flb_free(ctx); return -1; } ctx->auth_header = flb_sds_create_size(42); flb_sds_printf(&ctx->auth_header, "Bearer %s", ctx->nightfall_api_key); ctx->tls = flb_tls_create(FLB_TLS_CLIENT_MODE, ctx->tls_verify, ctx->tls_debug, ctx->tls_vhost, ctx->tls_ca_path, NULL, NULL, NULL, NULL); if (!ctx->tls) { flb_plg_error(f_ins, "tls initialization error"); flb_free(ctx); return -1; } ctx->upstream = flb_upstream_create_url(config, FLB_FILTER_NIGHTFALL_API_URL, FLB_IO_TLS, ctx->tls); if (!ctx->upstream) { flb_plg_error(ctx->ins, "connection initialization error"); flb_free(ctx); return -1; } flb_stream_disable_async_mode(&ctx->upstream->base); flb_filter_set_context(f_ins, ctx); srand((unsigned int)time(NULL)); return 0; } static int redact_record(msgpack_object *data, char **to_redact_data, size_t *to_redact_size, struct flb_time t, msgpack_sbuffer *new_rec) { int ret; struct mk_list stack; struct nested_obj *cur; struct nested_obj *new_obj; struct mk_list *head; struct mk_list *tmp; msgpack_sbuffer new_rec_sbuf; msgpack_packer new_rec_pk; char should_pop = FLB_TRUE; int to_redact_index = 0; msgpack_unpacked finding_list_unpacked; size_t finding_list_off = 0; msgpack_object_array to_redact; /* Convert to_redact_data to a msgpack_object_array */ msgpack_unpacked_init(&finding_list_unpacked); ret = msgpack_unpack_next(&finding_list_unpacked, *to_redact_data, *to_redact_size, &finding_list_off); if (ret == MSGPACK_UNPACK_SUCCESS) { to_redact = finding_list_unpacked.data.via.array; } mk_list_init(&stack); msgpack_sbuffer_init(&new_rec_sbuf); msgpack_packer_init(&new_rec_pk, &new_rec_sbuf, msgpack_sbuffer_write); new_obj = flb_calloc(1, sizeof(struct nested_obj)); new_obj->obj = data; new_obj->cur_index = 0; new_obj->start_at_val = FLB_FALSE; mk_list_add(&new_obj->_head, &stack); if (data->type == MSGPACK_OBJECT_ARRAY) { msgpack_pack_array(&new_rec_pk, data->via.array.size); } else if (data->type == MSGPACK_OBJECT_MAP) { msgpack_pack_map(&new_rec_pk, data->via.map.size); } /* * Since logs can contain many levels of nested objects, use stack-based DFS here * to build back and redact log. */ while (mk_list_is_empty(&stack) == -1) { cur = mk_list_entry_last(&stack, struct nested_obj, _head); should_pop = FLB_TRUE; switch(cur->obj->type) { case MSGPACK_OBJECT_ARRAY: ret = redact_array_fields(&new_rec_pk, &to_redact_index, &to_redact, cur, &stack, &should_pop); if (ret != 0) { msgpack_unpacked_destroy(&finding_list_unpacked); mk_list_foreach_safe(head, tmp, &stack) { cur = mk_list_entry(head, struct nested_obj, _head); mk_list_del(&cur->_head); flb_free(cur); } return -1; } break; case MSGPACK_OBJECT_MAP: ret = redact_map_fields(&new_rec_pk, &to_redact_index, &to_redact, cur, &stack, &should_pop); if (ret != 0) { msgpack_unpacked_destroy(&finding_list_unpacked); mk_list_foreach_safe(head, tmp, &stack) { cur = mk_list_entry(head, struct nested_obj, _head); mk_list_del(&cur->_head); flb_free(cur); } return -1; } break; case MSGPACK_OBJECT_STR: maybe_redact_field(&new_rec_pk, cur->obj, &to_redact, &to_redact_index, 0); break; case MSGPACK_OBJECT_POSITIVE_INTEGER: maybe_redact_field(&new_rec_pk, cur->obj, &to_redact, &to_redact_index, 0); break; case MSGPACK_OBJECT_NEGATIVE_INTEGER: maybe_redact_field(&new_rec_pk, cur->obj, &to_redact, &to_redact_index, 0); break; default: msgpack_pack_object(&new_rec_pk, *cur->obj); } if (should_pop) { mk_list_del(&cur->_head); flb_free(cur); } } msgpack_unpacked_destroy(&finding_list_unpacked); *new_rec = new_rec_sbuf; return 0; } static int redact_array_fields(msgpack_packer *new_rec_pk, int *to_redact_index, msgpack_object_array *to_redact, struct nested_obj *cur, struct mk_list *stack, char *should_pop) { msgpack_object *item; struct nested_obj *new_obj; int i; for (i = cur->cur_index; i < cur->obj->via.array.size; i++) { item = &cur->obj->via.array.ptr[i]; if (item->type == MSGPACK_OBJECT_MAP || item->type == MSGPACK_OBJECT_ARRAY) { /* A nested object, so add to stack and return to DFS to process immediately */ new_obj = flb_malloc(sizeof(struct nested_obj)); if (!new_obj) { flb_errno(); return -1; } new_obj->obj = item; new_obj->cur_index = 0; new_obj->start_at_val = FLB_FALSE; mk_list_add(&new_obj->_head, stack); if (item->type == MSGPACK_OBJECT_ARRAY) { msgpack_pack_array(new_rec_pk, item->via.array.size); } else { msgpack_pack_map(new_rec_pk, item->via.map.size); } /* * Since we are not done yet with the current array, increment the index that * keeps track of progress and don't pop the current array so we can come * back later. */ cur->cur_index = i + 1; *should_pop = FLB_FALSE; break; } else if (item->type == MSGPACK_OBJECT_STR || item->type == MSGPACK_OBJECT_POSITIVE_INTEGER || item->type == MSGPACK_OBJECT_NEGATIVE_INTEGER) { /* * A field that could potentially contain sensitive content, so we check * if there were any findings associated with it */ maybe_redact_field(new_rec_pk, item, to_redact, to_redact_index, 0); } else { /* Non scannable type, so just append as is. */ msgpack_pack_object(new_rec_pk, *item); } } return 0; } static int redact_map_fields(msgpack_packer *new_rec_pk, int *to_redact_index, msgpack_object_array *to_redact, struct nested_obj *cur, struct mk_list *stack, char *should_pop) { msgpack_object *k; msgpack_object *v; struct nested_obj *new_obj; int i; for (i = cur->cur_index; i < cur->obj->via.map.size; i++) { k = &cur->obj->via.map.ptr[i].key; if (!cur->start_at_val) { /* Handle the key of this kv pair */ if (k->type == MSGPACK_OBJECT_MAP || k->type == MSGPACK_OBJECT_ARRAY) { /* A nested object, so add to stack and return to DFS to process immediately */ new_obj = flb_malloc(sizeof(struct nested_obj)); if (!new_obj) { flb_errno(); return -1; } new_obj->obj = k; new_obj->cur_index = 0; new_obj->start_at_val = FLB_FALSE; mk_list_add(&new_obj->_head, stack); if (k->type == MSGPACK_OBJECT_ARRAY) { msgpack_pack_array(new_rec_pk, k->via.array.size); } else { msgpack_pack_map(new_rec_pk, k->via.map.size); } /* * Since we are not done yet with the current kv pair, don't increment * the progress index and set flag so we know to start at the value later */ cur->cur_index = i; cur->start_at_val = FLB_TRUE; /* Set should_pop to false because we are not done with the current map */ *should_pop = FLB_FALSE; break; } else if (k->type == MSGPACK_OBJECT_STR || k->type == MSGPACK_OBJECT_POSITIVE_INTEGER || k->type == MSGPACK_OBJECT_NEGATIVE_INTEGER) { /* * A field that could potentially contain sensitive content, so we check * if there were any findings associated with it */ maybe_redact_field(new_rec_pk, k, to_redact, to_redact_index, 0); } else { /* Non scannable type, so just append as is. */ msgpack_pack_object(new_rec_pk, *k); } } /* Handle the value of this kv pair */ v = &cur->obj->via.map.ptr[i].val; if (v->type == MSGPACK_OBJECT_MAP || v->type == MSGPACK_OBJECT_ARRAY) { /* A nested object, so add to stack and return to DFS to process immediately */ new_obj = flb_malloc(sizeof(struct nested_obj)); if (!new_obj) { flb_errno(); return -1; } new_obj->obj = v; new_obj->cur_index = 0; new_obj->start_at_val = FLB_FALSE; mk_list_add(&new_obj->_head, stack); if (v->type == MSGPACK_OBJECT_ARRAY) { msgpack_pack_array(new_rec_pk, v->via.array.size); } else { msgpack_pack_map(new_rec_pk, v->via.map.size); } /* Increment here because we are done with this kv pair */ cur->cur_index = i + 1; cur->start_at_val = FLB_FALSE; /* Set should_pop to false because we are not done with the current map */ *should_pop = FLB_FALSE; break; } else if (v->type == MSGPACK_OBJECT_STR || v->type == MSGPACK_OBJECT_POSITIVE_INTEGER || v->type == MSGPACK_OBJECT_NEGATIVE_INTEGER) { if (k->type == MSGPACK_OBJECT_STR) { /* * When building the request to scan the log, keys that are strings are * appended to the beginning of the value to provide more context when * scanning in the format of "<key> <val>", which is why we need to * offset the length of the key plus a space when we do redaction on the * value on its own. */ maybe_redact_field(new_rec_pk, v, to_redact, to_redact_index, k->via.str.size + 1); } else { maybe_redact_field(new_rec_pk, v, to_redact, to_redact_index, 0); } } else { msgpack_pack_object(new_rec_pk, *v); } } return 0; } static void maybe_redact_field(msgpack_packer *new_rec_pk, msgpack_object *field, msgpack_object_array *to_redact, int *to_redact_i, int byte_offset) { flb_sds_t cur_str; msgpack_object_array content_range; int64_t content_start; int64_t content_end; int i; int64_t replace_i; /* * Should not happen under normal circumstances as len of to_redact should be the * same as the number of scannable fields (positive/negative ints, strings) in the * event, but if that is the case just append the rest of the fields. */ if (*to_redact_i >= to_redact->size) { msgpack_pack_object(new_rec_pk, *field); return; } /* * Check if there was anything sensitive found for this field, if there wasn't we * can leave it as is */ if (to_redact->ptr[*to_redact_i].via.array.size == 0) { msgpack_pack_object(new_rec_pk, *field); *to_redact_i = *to_redact_i + 1; return; } /* If field is an integer redact entire field */ if (field->type == MSGPACK_OBJECT_POSITIVE_INTEGER || field->type == MSGPACK_OBJECT_NEGATIVE_INTEGER) { msgpack_pack_str_with_body(new_rec_pk, "******", 7); *to_redact_i = *to_redact_i + 1; return; } /* If field is a string redact only the sensitive parts */ cur_str = flb_sds_create_len(field->via.str.ptr, field->via.str.size); for (i = 0; i < to_redact->ptr[*to_redact_i].via.array.size; i++) { content_range = to_redact->ptr[*to_redact_i].via.array.ptr[i].via.array; content_start = content_range.ptr[0].via.i64 - byte_offset; if (content_start < 0) { content_start = 0; } content_end = content_range.ptr[1].via.i64 - byte_offset; for (replace_i = content_start; replace_i < content_end && replace_i < flb_sds_len(cur_str); replace_i++) { cur_str[replace_i] = '*'; } } msgpack_pack_str_with_body(new_rec_pk, cur_str, flb_sds_len(cur_str)); *to_redact_i = *to_redact_i + 1; flb_sds_destroy(cur_str); } static int cb_nightfall_filter(const void *data, size_t bytes, const char *tag, int tag_len, void **out_buf, size_t *out_size, struct flb_filter_instance *f_ins, struct flb_input_instance *i_ins, void *context, struct flb_config *config) { struct flb_filter_nightfall *ctx = context; int ret; char is_modified = FLB_FALSE; struct flb_time tmp = {0}; char *to_redact; size_t to_redact_size; char is_sensitive = FLB_FALSE; msgpack_sbuffer new_rec_sbuf; struct flb_log_event_encoder log_encoder; struct flb_log_event_decoder log_decoder; struct flb_log_event log_event; (void) f_ins; (void) i_ins; (void) config; /* * Generate a random double between 0 and 1, if it is over the sampling rate * configured don't scan this log. */ if ((double)rand()/(double)RAND_MAX > ctx->sampling_rate) { return FLB_FILTER_NOTOUCH; } ret = flb_log_event_decoder_init(&log_decoder, (char *) data, bytes); if (ret != FLB_EVENT_DECODER_SUCCESS) { flb_plg_error(ctx->ins, "Log event decoder initialization error : %d", ret); return FLB_FILTER_NOTOUCH; } ret = flb_log_event_encoder_init(&log_encoder, FLB_LOG_EVENT_FORMAT_DEFAULT); if (ret != FLB_EVENT_ENCODER_SUCCESS) { flb_plg_error(ctx->ins, "Log event encoder initialization error : %d", ret); flb_log_event_decoder_destroy(&log_decoder); return FLB_FILTER_NOTOUCH; } while ((ret = flb_log_event_decoder_next( &log_decoder, &log_event)) == FLB_EVENT_DECODER_SUCCESS) { ret = scan_log(ctx, log_event.body, &to_redact, &to_redact_size, &is_sensitive); if (ret != 0) { flb_plg_error(ctx->ins, "scanning error"); flb_log_event_decoder_destroy(&log_decoder); flb_log_event_encoder_destroy(&log_encoder); return FLB_FILTER_NOTOUCH; } if (is_sensitive == FLB_TRUE) { ret = redact_record(log_event.body, &to_redact, &to_redact_size, tmp, &new_rec_sbuf); if (ret != 0) { flb_plg_error(ctx->ins, "redaction error"); flb_free(to_redact); msgpack_sbuffer_destroy(&new_rec_sbuf); flb_log_event_decoder_destroy(&log_decoder); flb_log_event_encoder_destroy(&log_encoder); return FLB_FILTER_NOTOUCH; } is_modified = FLB_TRUE; } if (is_modified) { ret = flb_log_event_encoder_begin_record(&log_encoder); if (ret == FLB_EVENT_ENCODER_SUCCESS) { ret = flb_log_event_encoder_set_timestamp( &log_encoder, &log_event.timestamp); } if (ret == FLB_EVENT_ENCODER_SUCCESS) { ret = flb_log_event_encoder_set_metadata_from_msgpack_object( &log_encoder, log_event.metadata); } if (ret == FLB_EVENT_ENCODER_SUCCESS) { ret = flb_log_event_encoder_set_body_from_raw_msgpack( &log_encoder, new_rec_sbuf.data, new_rec_sbuf.size); } if (ret == FLB_EVENT_ENCODER_SUCCESS) { ret = flb_log_event_encoder_commit_record( &log_encoder); } } } flb_free(to_redact); if (log_encoder.output_length > 0) { *out_buf = log_encoder.output_buffer; *out_size = log_encoder.output_length; ret = FLB_FILTER_MODIFIED; flb_log_event_encoder_claim_internal_buffer_ownership(&log_encoder); } else { flb_plg_error(ctx->ins, "Log event encoder error : %d", ret); ret = FLB_FILTER_NOTOUCH; } flb_log_event_decoder_destroy(&log_decoder); flb_log_event_encoder_destroy(&log_encoder); return ret; } static int cb_nightfall_exit(void *data, struct flb_config *config) { struct flb_filter_nightfall *ctx = data; if (ctx == NULL) { return 0; } if (ctx->upstream) { flb_upstream_destroy(ctx->upstream); } if (ctx->tls) { flb_tls_destroy(ctx->tls); } if (ctx->auth_header) { flb_sds_destroy(ctx->auth_header); } flb_free(ctx); return 0; } /* Configuration properties map */ static struct flb_config_map config_map[] = { { FLB_CONFIG_MAP_STR, "nightfall_api_key", NULL, 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, nightfall_api_key), "The Nightfall API key to scan your logs with." }, { FLB_CONFIG_MAP_STR, "policy_id", NULL, 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, policy_id), "The Nightfall policy ID to scan your logs with." }, { FLB_CONFIG_MAP_DOUBLE, "sampling_rate", "1", 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, sampling_rate), "The sampling rate for scanning, must be (0,1]. 1 means all logs will be scanned." }, { FLB_CONFIG_MAP_INT, "tls.debug", "0", 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, tls_debug), "Set TLS debug level: 0 (no debug), 1 (error), " "2 (state change), 3 (info) and 4 (verbose)" }, { FLB_CONFIG_MAP_BOOL, "tls.verify", "true", 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, tls_verify), "Enable or disable verification of TLS peer certificate" }, { FLB_CONFIG_MAP_STR, "tls.vhost", NULL, 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, tls_vhost), "Set optional TLS virtual host" }, { FLB_CONFIG_MAP_STR, "tls.ca_path", NULL, 0, FLB_TRUE, offsetof(struct flb_filter_nightfall, tls_ca_path), "Path to root certificates on the system" }, {0} }; struct flb_filter_plugin filter_nightfall_plugin = { .name = "nightfall", .description = "scans records for sensitive content", .cb_init = cb_nightfall_init, .cb_filter = cb_nightfall_filter, .cb_exit = cb_nightfall_exit, .config_map = config_map, .flags = 0 };
c77d054b8016b3eca71d03734839a55ea91cec4e
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/include/net/udplite.h
71375459a8843da6cbbf7062a0e71bf90a6ee716
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
3,838
h
udplite.h
/* * Definitions for the UDP-Lite (RFC 3828) code. */ #ifndef _UDPLITE_H #define _UDPLITE_H #include <net/ip6_checksum.h> /* UDP-Lite socket options */ #define UDPLITE_SEND_CSCOV 10 /* sender partial coverage (as sent) */ #define UDPLITE_RECV_CSCOV 11 /* receiver partial coverage (threshold ) */ extern struct proto udplite_prot; extern struct udp_table udplite_table; /* * Checksum computation is all in software, hence simpler getfrag. */ static __inline__ int udplite_getfrag(void *from, char *to, int offset, int len, int odd, struct sk_buff *skb) { return memcpy_fromiovecend(to, (struct iovec *) from, offset, len); } /* Designate sk as UDP-Lite socket */ static inline int udplite_sk_init(struct sock *sk) { udp_sk(sk)->pcflag = UDPLITE_BIT; return 0; } /* * Checksumming routines */ static inline int udplite_checksum_init(struct sk_buff *skb, struct udphdr *uh) { u16 cscov; /* In UDPv4 a zero checksum means that the transmitter generated no * checksum. UDP-Lite (like IPv6) mandates checksums, hence packets * with a zero checksum field are illegal. */ if (uh->check == 0) { LIMIT_NETDEBUG(KERN_DEBUG "UDPLite: zeroed checksum field\n"); return 1; } cscov = ntohs(uh->len); if (cscov == 0) /* Indicates that full coverage is required. */ ; else if (cscov < 8 || cscov > skb->len) { /* * Coverage length violates RFC 3828: log and discard silently. */ LIMIT_NETDEBUG(KERN_DEBUG "UDPLite: bad csum coverage %d/%d\n", cscov, skb->len); return 1; } else if (cscov < skb->len) { UDP_SKB_CB(skb)->partial_cov = 1; UDP_SKB_CB(skb)->cscov = cscov; if (skb->ip_summed == CHECKSUM_COMPLETE) skb->ip_summed = CHECKSUM_NONE; } return 0; } /* Slow-path computation of checksum. Socket is locked. */ static inline __wsum udplite_csum_outgoing(struct sock *sk, struct sk_buff *skb) { const struct udp_sock *up = udp_sk(skb->sk); int cscov = up->len; __wsum csum = 0; if (up->pcflag & UDPLITE_SEND_CC) { /* * Sender has set `partial coverage' option on UDP-Lite socket. * The special case "up->pcslen == 0" signifies full coverage. */ if (up->pcslen < up->len) { if (0 < up->pcslen) cscov = up->pcslen; udp_hdr(skb)->len = htons(up->pcslen); } /* * NOTE: Causes for the error case `up->pcslen > up->len': * (i) Application error (will not be penalized). * (ii) Payload too big for send buffer: data is split * into several packets, each with its own header. * In this case (e.g. last segment), coverage may * exceed packet length. * Since packets with coverage length > packet length are * illegal, we fall back to the defaults here. */ } skb->ip_summed = CHECKSUM_NONE; /* no HW support for checksumming */ skb_queue_walk(&sk->sk_write_queue, skb) { const int off = skb_transport_offset(skb); const int len = skb->len - off; csum = skb_checksum(skb, off, (cscov > len)? len : cscov, csum); if ((cscov -= len) <= 0) break; } return csum; } /* Fast-path computation of checksum. Socket may not be locked. */ static inline __wsum udplite_csum(struct sk_buff *skb) { const struct udp_sock *up = udp_sk(skb->sk); const int off = skb_transport_offset(skb); int len = skb->len - off; if ((up->pcflag & UDPLITE_SEND_CC) && up->pcslen < len) { if (0 < up->pcslen) len = up->pcslen; udp_hdr(skb)->len = htons(up->pcslen); } skb->ip_summed = CHECKSUM_NONE; /* no HW support for checksumming */ return skb_checksum(skb, off, len, 0); } extern void udplite4_register(void); extern int udplite_get_port(struct sock *sk, unsigned short snum, int (*scmp)(const struct sock *, const struct sock *)); #endif /* _UDPLITE_H */
518575f944ee1a0876187792d1214bc4a0ed0e64
f3e2559f9f03135ef71a9573932d6e09360a6a38
/miniupnpd/upnpstun.h
6bb349e679029a25583640e4055275b1a2292b87
[ "BSD-3-Clause" ]
permissive
miniupnp/miniupnp
75751b7513dbf7dbf9aef2be7c3f49b459fdaee2
fb5c328a5e8fd57a3ec0f5d33915377a5d3581f3
refs/heads/master
2023-08-22T19:12:55.862346
2023-08-06T22:50:37
2023-08-06T22:50:37
2,435,778
1,246
475
BSD-3-Clause
2023-08-06T22:50:38
2011-09-22T08:25:20
C
UTF-8
C
false
false
443
h
upnpstun.h
/* MiniUPnP project * http://miniupnp.free.fr/ or http://miniupnp.tuxfamily.org/ * (c) 2018 Pali Rohár * This software is subject to the conditions detailed * in the LICENCE file provided within the distribution */ #ifndef UPNPSTUN_H_INCLUDED #define UPNPSTUN_H_INCLUDED int perform_stun(const char *if_name, const char *if_addr, const char *stun_host, unsigned short stun_port, struct in_addr *ext_addr, int *restrictive_nat); #endif
5bdd66eda93a8cfa302d8f0f6da568688b6d52aa
2b6a4eddac65e3712d0d06f3a0262dae6253263e
/Source/src/WixSharp.Samples/Wix_bin/SDK/inc/butil.h
a42cac112a0bd3dbe16d0151a12848b37cdb516a
[ "MIT" ]
permissive
oleg-shilo/wixsharp
6005721bb7607b7060b99d6e4f5569b3404ca63d
7601893a5e9e14408ce9ef63415290d5c56254a6
refs/heads/master
2023-08-24T07:45:11.137770
2023-07-22T10:50:56
2023-07-22T10:50:56
49,761,249
976
245
MIT
2023-07-22T10:50:57
2016-01-16T05:51:01
C#
UTF-8
C
false
false
964
h
butil.h
#pragma once // Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information. #ifdef __cplusplus extern "C" { #endif enum BUNDLE_INSTALL_CONTEXT { BUNDLE_INSTALL_CONTEXT_MACHINE, BUNDLE_INSTALL_CONTEXT_USER, }; HRESULT DAPI BundleGetBundleInfo( __in LPCWSTR szBundleId, // Bundle code __in LPCWSTR szAttribute, // attribute name __out_ecount_opt(*pcchValueBuf) LPWSTR lpValueBuf, // returned value, NULL if not desired __inout_opt LPDWORD pcchValueBuf // in/out buffer character count ); HRESULT DAPI BundleEnumRelatedBundle( __in LPCWSTR lpUpgradeCode, __in BUNDLE_INSTALL_CONTEXT context, __inout PDWORD pdwStartIndex, __out_ecount(MAX_GUID_CHARS+1) LPWSTR lpBundleIdBuf ); #ifdef __cplusplus } #endif
d4dc6271960e04be607fc9aaaa8c8be724c61aa6
749e6814d6488aea461676385780d847e07fd380
/Core/GDCore/DocMainPage.h
8ba296e8e01674fc8eb1ae933d67f6a7492f3525
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
4ian/GDevelop
258a007a2aa74bfd97c75a6c1753bc3fd48e634f
134886eedcfaeaa04139463aaf826b71c11819c5
refs/heads/master
2023-08-18T23:14:56.149709
2023-08-18T20:39:40
2023-08-18T20:39:40
21,331,090
4,722
748
NOASSERTION
2023-09-14T21:40:54
2014-06-29T19:58:38
JavaScript
UTF-8
C
false
false
4,501
h
DocMainPage.h
/** * \mainpage GDevelop Core * \image html gdlogo.png * \section welcome GDevelop Core documentation * * The **GDevelop Core** library contains the structure of a GDevelop game, classes and tools that are used by the *platforms* and the *GDevelop IDE*. * * \section gettingstarted Getting started * * In most cases, you should start by <a href="https://github.com/4ian/GDevelop/blob/master/newIDE/README.md">installing and launching the development version of GDevelop</a>. * * - If you're interested in writing extensions for GDevelop, read <a href="https://github.com/4ian/GDevelop/blob/master/newIDE/README-extensions.md">the documentation about extensions</a>. * - If you want to dig more into how GDevelop is architectured and work on the core, read <a href="https://github.com/4ian/GDevelop/blob/master/Core/GDevelop-Architecture-Overview.md">GDevelop Architecture Overview</a>. Then, you can browse this reference to get more information about a class or function. * * \section other Other documentations * * GDevelop is architectured around a `Core` (this library), a game engine (`GDJS`) and extensions (`Extensions` folder). The editor (`newIDE` folder) is using all of these libraries. * * - [Open GDevelop JS Platform documentation](../GDJS Documentation/index.html) * - <a href="https://github.com/4ian/GDevelop/blob/master/newIDE/README.md">Getting started with the editor</a> * - <a href="https://github.com/4ian/GDevelop/blob/master/newIDE/README-extensions.md">Getting started with the extensions</a> */ /** * \defgroup PlatformDefinition Platform Definition (Common classes used by all platforms) * * Classes defining the common concepts used by all platforms: gd::Project, gd::Layout... */ /** * \defgroup IDE IDE Classes (Classes to be used to implement a development environment) * * Classes to be used to implement a development environment. */ /** * \defgroup IDEDialogs IDE Dialogs (Pre-made dialogs to be used to implement a development environment) * * Pre-made dialogs to be used to implement a development environment */ /** * \defgroup IDEDialogsEventsEditor Events Editor related classes * * Classes and tools used to implement an events editor. * \ingroup IDEDialogs */ /** * \defgroup Events Events (Classes defining the event system and some tools associated with events) * * Classes defining the event system and some tools associated with events */ /** * \defgroup CommonProgrammingTools Common programming tools * * Common functions and tools for programming. */ /** * \defgroup TinyXml Integrated TinyXml library * * See the full documentation of TinyXml [here](http://www.grinninglizard.com/tinyxmldocs/index.html). */ /** * \defgroup SpriteObjectExtension Standard Sprite Object extension * \ingroup BuiltinExtensions */ /** * \class TiXmlAttribute * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlAttributeSet * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlBase * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlComment * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlCursor * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlDeclaration * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlDocument * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlElement * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlHandle * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlNode * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlOutStream * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlParsingData * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlPrinter * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlString * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlText * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlUnknown * \brief Part of the tinyxml library * \ingroup TinyXml */ /** * \class TiXmlVisitor * \brief Part of the tinyxml library * \ingroup TinyXml */
030dd72c49774987f4096c577dd102ff31231147
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/arm/mach-ixp4xx/wg302v2-pci.c
c92e5b82af3686c47fab014cb13d9c6b01da7f0a
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
1,431
c
wg302v2-pci.c
/* * arch/arch/mach-ixp4xx/wg302v2-pci.c * * PCI setup routines for the Netgear WG302 v2 and WAG302 v2 * * Copyright (C) 2007 Imre Kaloz <kaloz@openwrt.org> * * based on coyote-pci.c: * Copyright (C) 2002 Jungo Software Technologies. * Copyright (C) 2003 MontaVista Software, Inc. * * Maintainer: Imre Kaloz <kaloz@openwrt.org> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * */ #include <linux/kernel.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/irq.h> #include <asm/mach-types.h> #include <mach/hardware.h> #include <asm/mach/pci.h> void __init wg302v2_pci_preinit(void) { irq_set_irq_type(IRQ_IXP4XX_GPIO8, IRQ_TYPE_LEVEL_LOW); irq_set_irq_type(IRQ_IXP4XX_GPIO9, IRQ_TYPE_LEVEL_LOW); ixp4xx_pci_preinit(); } static int __init wg302v2_map_irq(const struct pci_dev *dev, u8 slot, u8 pin) { if (slot == 1) return IRQ_IXP4XX_GPIO8; else if (slot == 2) return IRQ_IXP4XX_GPIO9; else return -1; } struct hw_pci wg302v2_pci __initdata = { .nr_controllers = 1, .ops = &ixp4xx_ops, .preinit = wg302v2_pci_preinit, .setup = ixp4xx_setup, .map_irq = wg302v2_map_irq, }; int __init wg302v2_pci_init(void) { if (machine_is_wg302v2()) pci_common_init(&wg302v2_pci); return 0; } subsys_initcall(wg302v2_pci_init);
05e6c224f02666f7ecb89e7da13e88a5d918bfb3
748626778e870ce6cdfd0c1f3b46d7f8a096b5a8
/src/condor_includes/condor_fix_sys_stat.h
febb7f417b512c22e955bf7a6c199ad3d0679679
[ "Apache-2.0" ]
permissive
htcondor/htcondor
1c8bab33379299f64e5274a7d525f3c64c64c47f
3b67625b2f4d97bcc28f534340a6fd7ac518dc75
refs/heads/main
2023-08-31T03:17:53.070364
2023-08-31T00:18:04
2023-08-31T00:18:04
5,808,515
249
165
Apache-2.0
2023-09-14T18:44:26
2012-09-14T11:35:15
C++
UTF-8
C
false
false
2,679
h
condor_fix_sys_stat.h
/*************************************************************** * * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department, * University of Wisconsin-Madison, WI. * * 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 _CONDOR_FIX_SYS_STAT_H #define _CONDOR_FIX_SYS_STAT_H /* On many platforms, stat defines several static functions which redirect stat to xstat, fstat to fxstat, and so on. We want to kill all of these definitions right here and then provide prototypes for the libc versions of stat and friends. The whole point of this is to enable us to redefine the libc versions of stat and friends as we please. We only perform this action when CONDOR_KILL_STAT_DEFINITIONS is in effect. This should probably only be set by the syscall library. Notice that a #define stat is not what we want -- this will clobber all sorts of arguments and structures that use the symbol stat. By defining a macros with arguments, stat(), we will only kill the static function definition. */ #include "condor_header_features.h" #if defined(CONDOR_KILLS_STAT_DEFINITIONS) #define mknod(a,b,c) __condor_hack_mknod(a,b,c) #define stat(a,b) __condor_hack_stat(a,b) #define lstat(a,b) __condor_hack_lstat(a,b) #define fstat(a,b) __condor_hack_fstat(a,b) #define __mknod(a,b,c) __condor_hack___mknod(a,b,c) #define __stat(a,b) __condor_hack___stat(a,b) #define __lstat(a,b) __condor_hack___lstat(a,b) #define __fstat(a,b) __condor_hack___fstat(a,b) #define __fxstatat64(a,b,c,d,e) __condor_hack___fxstatat64(a,b,c,d,e) #endif #include <sys/stat.h> #if defined(CONDOR_KILLS_STAT_DEFINITIONS) #undef fstat #undef lstat #undef stat #undef mknod #undef __fstat #undef __lstat #undef __stat #undef __mknod #undef __fxstatat64 /* Now, we must provide the protoypes that we lost. */ BEGIN_C_DECLS extern int stat(const char *path, struct stat *buf); extern int lstat(const char *path, struct stat *buf); extern int fstat(int fd, struct stat *buf); extern int mknod(const char *path, mode_t mode, dev_t device); END_C_DECLS #endif #endif /* _CONDOR_FIX_SYS_STAT_H */
cce31b203efc57e9130af1cb941bd474f187d9eb
78dc9f153549b281be709227bc9897931b06260d
/generation/WinSDK/RecompiledIdlHeaders/um/bluetoothleapis.h
8d432133dcf212f5429a3c668e62868148fcc089
[ "MIT" ]
permissive
microsoft/win32metadata
dff35b4fe904d556162cee5133294c4498f1a79a
5bf233f04d45f7a697e112e9639722551103eb07
refs/heads/main
2023-09-01T19:51:22.972899
2023-08-30T21:39:44
2023-08-30T21:39:44
270,838,404
1,240
107
NOASSERTION
2023-09-14T18:49:44
2020-06-08T21:52:10
C++
UTF-8
C
false
false
25,551
h
bluetoothleapis.h
/*++ Copyright (c) 2010 Microsoft Corporation Module Name: BluetoothLEApis.h Abstract: Public Bluetooth Low Energy Application Development Interfaces Environment: User mode --*/ #ifdef _MSC_VER #pragma once #endif //_MSC_VER #include <winapifamily.h> #include <BthLEDef.h> #pragma region Desktop Family #if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) #ifdef __cplusplus extern "C"{ #endif #if NTDDI_VERSION >= NTDDI_WIN8 // // Description: // The BluetoothGATTGetServices function gets all the primary services available for a server. // // Parameters: // hDevice [in] // Handle to the Bluetooth device from which to obtain the list of primary services. // // ServicesBufferCount [in] // The number of elements allocated for the ServicesBuffer parameter. // // ServicesBuffer [out, optional] // Pointer to buffer into which to return services. // // ServicesBufferActual [out] // Pointer to buffer into which the actual number of services were returned in the ServicesBuffer parameter. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // // Return Value: // S_OK // The operation completed successfully. // // ERROR_MORE_DATA // The buffer parameter is NULL and the number of items available is being returned. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_INVALID_USER_BUFFER // A buffer is specified, but the buffer count size is smaller than what is required, in bytes. // // ERROR_INVALID_FUNCTION // No services are present in the cache. // // ERROR_BAD_COMMAND // The current data in the cache appears to be inconsistent, and is leading to internal errors. // // ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTGetServices( _In_ HANDLE hDevice, _In_ USHORT ServicesBufferCount, _Out_writes_to_opt_(ServicesBufferCount, *ServicesBufferActual) PBTH_LE_GATT_SERVICE ServicesBuffer, _Out_ USHORT* ServicesBufferActual, _In_ ULONG Flags ); // // Description: // The BluetoothGATTGetIncludedServices function gets all the included services available for a given service. // // Parameters: // hDevice [in] // Handle to the Bluetooth device or parent service. // // ParentService [in] // The parent service of the included services to be retrieved. This parameter // is required if a device handle is passed to hDevice. This parameter is optional // if a service handle was passed to hDevice, in which case the service specified // by the service handle will be treated as the parent unless the parent service // is provided. If both a parent service and a service handle is provided and the // parent service hierarchy do not roll up to the service handle that is provided, // the function will fail with ERROR_ACCESS_DENIED. // // IncludedServicesBufferCount [in] // The number of elements allocated for the IncludedServicesBuffer parameter. // // IncludedServicesBuffer [out, optional] // Pointer to buffer into which to return included services. // // IncludedServicesBufferActual [out] // Pointer to buffer into which the actual number of included services were returned in // the IncludedServicesBuffer parameter. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // // Return Value: // S_OK // The operation completed successfully. // // ERROR_MORE_DATA // The buffer parameter is NULL and the number of items available is being returned. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_INVALID_USER_BUFFER // A buffer is specified, but the buffer count size is smaller than what is required, in bytes. // // ERROR_INVALID_FUNCTION // No services are present in the cache. // // ERROR_BAD_COMMAND // The current data in the cache appears to be inconsistent, and is leading to internal errors. // // ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // ERROR_ACCESS_DENIED // If both a parent service and a service handle is provided and the // parent service hierarchy do not roll up to the service handle that is provided. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTGetIncludedServices( _In_ HANDLE hDevice, _In_opt_ PBTH_LE_GATT_SERVICE ParentService, _In_ USHORT IncludedServicesBufferCount, _Out_writes_to_opt_(IncludedServicesBufferCount, *IncludedServicesBufferActual) PBTH_LE_GATT_SERVICE IncludedServicesBuffer, _Out_ USHORT* IncludedServicesBufferActual, _In_ ULONG Flags ); // // Description: // The BluetoothGATTGetCharacteristics function gets all the characteristics available for the specified service. // // Parameters: // hDevice [in] // Handle to the Bluetooth device or service. // // Service [in] // The parent service of the characteristics to be retrieved. This parameter // is required if a device handle is passed to hDevice. This parameter is optional // if a service handle was passed to hDevice, in which case the service specified // by the service handle will be treated as the parent. // // CharacteristicsBufferCount [in] // The number of elements allocated for the CharacteristicsBuffer parameter. // // CharacteristicsBuffer [out, optional] // Pointer to buffer into which to return characteristics. // // IncludedServicesBufferActual [out] // Pointer to buffer into which the actual number of characteristics were returned in // the CharacteristicsBuffer parameter. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // // Return Value: // S_OK // The operation completed successfully. // // ERROR_MORE_DATA // The buffer parameter is NULL and the number of items available is being returned. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_INVALID_USER_BUFFER // A buffer is specified, but the buffer count size is smaller than what is required, in bytes. // // ERROR_BAD_COMMAND // The current data in the cache appears to be inconsistent, and is leading to internal errors. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTGetCharacteristics( _In_ HANDLE hDevice, _In_opt_ PBTH_LE_GATT_SERVICE Service, _In_ USHORT CharacteristicsBufferCount, _Out_writes_to_opt_(CharacteristicsBufferCount, *CharacteristicsBufferActual) PBTH_LE_GATT_CHARACTERISTIC CharacteristicsBuffer, _Out_ USHORT* CharacteristicsBufferActual, _In_ ULONG Flags ); // // Description: // The BluetoothGATTGetDescriptors function gets all the descriptors available for the specified characteristic. // // Parameters: // hDevice [in] // Handle to the Bluetooth device or service. If a service handle is passed, then the service must be // the grandparent of the descriptor. // // Characteristic [in] // The parent characteristic of the descriptors to be retrieved. // // DescriptorsBufferCount [in] // The number of elements allocated for the DescriptorsBuffer parameter. // // DescriptorsBuffer [out, optional] // Pointer to buffer into which to return descriptors. // // DescriptorsBufferActual [out] // Pointer to buffer into which the actual number of descriptors were returned in // the DescriptorsBuffer parameter. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // // Return Value: // S_OK // The operation completed successfully. // // ERROR_MORE_DATA // The buffer parameter is NULL and the number of items available is being returned. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_INVALID_USER_BUFFER // A buffer is specified, but the buffer count size is smaller than what is required, in bytes. // // ERROR_BAD_COMMAND // The current data in the cache appears to be inconsistent, and is leading to internal errors. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTGetDescriptors( _In_ HANDLE hDevice, _In_ PBTH_LE_GATT_CHARACTERISTIC Characteristic, _In_ USHORT DescriptorsBufferCount, _Out_writes_to_opt_(DescriptorsBufferCount, *DescriptorsBufferActual) PBTH_LE_GATT_DESCRIPTOR DescriptorsBuffer, _Out_ USHORT* DescriptorsBufferActual, _In_ ULONG Flags ); // // Description: // The BluetoothGATTGetCharacteristicValue function gets the value of the specified characteristic. // // Parameters: // hDevice [in] // Handle to the service. // // Characteristic [in] // The parent characteristic of the characteristic value to be retrieved. // // CharacteristicValueDataSize [in] // The number of elements allocated for the CharacteristicValue parameter. // // CharacteristicValue [out, optional] // Pointer to buffer into which to return characteristic value. // // CharacteristicValueSizeRequired [out] // Pointer to buffer into which to store the number of bytes // needed to return data in the buffer pointed to by CharacteristicValue. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // BLUETOOTH_GATT_FLAG_CONNECTION_ENCRYPTED: The client requests the data to be transmitted over an encrypted channel. // BLUETOOTH_GATT_FLAG_CONNECTION_AUTHENTICATED: The client requests the data to be transmitted over an authenticated channel. // BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_CACHE: The characteristic value is to be read from the cache // (regardless of whether it is present in the cache or not). // BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE: The characteristic value is to be read directly from the device. // This overwrites the one in the cache if one is already present. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_MORE_DATA // The buffer parameter is NULL and the number of bytes needed is being returned. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_INVALID_USER_BUFFER // A buffer is specified, but the buffer count size is smaller than what is required, in bytes. // // ERROR_BAD_COMMAND // The current data in the cache appears to be inconsistent, and is leading to internal errors. // // ERROR_BAD_NET_RESP // The target server did not provide an appropriate network response. // // ERROR_SEM_TIMEOUT // The request timed-out. // // ERROR_PRIVILEGE_NOT_HELD // The characteristic value is not readable as dictated by the characteristic properties. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // E_BLUETOOTH_ATT_<ERROR_CODE> // An error code returned by the device indicating a specific error has occured. // Consult the Bluetooth specification for more information. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTGetCharacteristicValue( _In_ HANDLE hDevice, _In_ PBTH_LE_GATT_CHARACTERISTIC Characteristic, _In_ ULONG CharacteristicValueDataSize, _Out_opt_ PBTH_LE_GATT_CHARACTERISTIC_VALUE CharacteristicValue, _Out_opt_ USHORT* CharacteristicValueSizeRequired, _In_ ULONG Flags ); // // Description: // The BluetoothGATTGetDescriptorValue function gets the value of the specified descriptor. // // Parameters: // hDevice [in] // Handle to the service. // // Descriptor [in] // The parent descriptor of the descriptor value to be retrieved. // // DescriptorValueDataSize [in] // The number of elements allocated for the DescriptorValue parameter. // // DescriptorValue [out, optional] // Pointer to buffer into which to return descriptor value. // // DescriptorValueSizeRequired [out] // Pointer to buffer into which to store the number of bytes // needed to return data in the buffer pointed to by DescriptorValue. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // BLUETOOTH_GATT_FLAG_CONNECTION_ENCRYPTED: The client requests the data to be transmitted over an encrypted channel. // BLUETOOTH_GATT_FLAG_CONNECTION_AUTHENTICATED: The client requests the data to be transmitted over an authenticated channel. // BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_CACHE: The descriptor value is to be read from the cache // (regardless of whether it is present in the cache or not). // BLUETOOTH_GATT_FLAG_FORCE_READ_FROM_DEVICE: The descriptor value is to be read directly from the device. // This overwrites the one in the cache if one is already present. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_MORE_DATA // The buffer parameter is NULL and the number of bytes needed is being returned. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_INVALID_USER_BUFFER // A buffer is specified, but the buffer count size is smaller than what is required, in bytes. // // ERROR_BAD_COMMAND // The current data in the cache appears to be inconsistent, and is leading to internal errors. // // ERROR_BAD_NET_RESP // The target server did not provide an appropriate network response. // // ERROR_SEM_TIMEOUT // The request timed-out. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // E_BLUETOOTH_ATT_<ERROR_CODE> // An error code returned by the device indicating a specific error has occured. // Consult the Bluetooth specification for more information. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTGetDescriptorValue( _In_ HANDLE hDevice, _In_ PBTH_LE_GATT_DESCRIPTOR Descriptor, _In_ ULONG DescriptorValueDataSize, _Out_opt_ PBTH_LE_GATT_DESCRIPTOR_VALUE DescriptorValue, _Out_opt_ USHORT* DescriptorValueSizeRequired, _In_ ULONG Flags ); // // Description: // The BluetoothGATTBeginReliableWrite function specifies that reliable writes are about to begin. // // Parameters: // hDevice [in] // Handle to the service. // // ReliableWriteContext [out] // Pointer to the context describing the reliable write operation. // // Flags [in] // Reserved. Must be set to BLUETOOTH_GATT_FLAG_NONE. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_FUNCTION // A reliable write operation is already presently underway. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTBeginReliableWrite( _In_ HANDLE hDevice, _Out_ PBTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext, _In_ ULONG Flags ); // // Description: // The BluetoothGATTSetCharacteristicValue function writes the specified characteristic value to the Bluetooth device. // // Parameters: // hDevice [in] // Handle to the service. // // Characteristic [in] // The parent characteristic. // // CharacteristicValue [in] // Pointer to the characteristic value. // // ReliableWriteContext [in] // The context describing the reliable write operation returned from a // previous call to BluetoothGATTBeginReliableWrite. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // BLUETOOTH_GATT_FLAG_CONNECTION_ENCRYPTED: The client requests the data to be transmitted over an encrypted channel. // BLUETOOTH_GATT_FLAG_CONNECTION_AUTHENTICATED: The client requests the data to be transmitted over an authenticated channel. // BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE : Write without response. // BLUETOOTH_GATT_FLAG_SIGNED_WRITE: Signed write. Profile drivers must use with // BLUETOOTH_GATT_FLAG_WRITE_WITHOUT_RESPONSE in order to produce // signed write without a response. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_BAD_NET_RESP // The target server did not provide an appropriate network response. // // ERROR_SEM_TIMEOUT // The request timed-out. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // ERROR_INVALID_FUNCTION // A reliable write operation is already presently underway. // // E_BLUETOOTH_ATT_<ERROR_CODE> // An error code returned by the device indicating a specific error has occured. // Consult the Bluetooth specification for more information. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTSetCharacteristicValue( _In_ HANDLE hDevice, _In_ PBTH_LE_GATT_CHARACTERISTIC Characteristic, _In_ PBTH_LE_GATT_CHARACTERISTIC_VALUE CharacteristicValue, _In_opt_ BTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext, _In_ ULONG Flags ); // // Description: // The BluetoothGATTEndReliableWrite function specifies the end of reliable writes, // and the writes should be committed. // // Parameters: // hDevice [in] // Handle to the service. // // ReliableWriteContext [in] // The context describing the reliable write operation returned from a previous // call to BluetoothGATTBeginReliableWrite. // // Flags [in] // Reserved. Must be set to BLUETOOTH_GATT_FLAG_NONE. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_FUNCTION // A reliable write operation is no presently underway. // // ERROR_BAD_NET_RESP // The target server did not provide an appropriate network response. // // ERROR_SEM_TIMEOUT // The request timed-out. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // E_BLUETOOTH_ATT_<ERROR_CODE> // An error code returned by the device indicating a specific error has occured. // Consult the Bluetooth specification for more information. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTEndReliableWrite( _In_ HANDLE hDevice, _In_ BTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext, _In_ ULONG Flags ); // // Description: // The BluetoothGATTAbortReliableWrite function specifies the end of reliable // write procedures, and the writes should be aborted. // // Parameters: // hDevice [in] // Handle to the service. // // ReliableWriteContext [in] // The context describing the reliable write operation returned from a previous // call to BluetoothGATTBeginReliableWrite. // // Flags [in] // Reserved. Must be set to BLUETOOTH_GATT_FLAG_NONE. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_FUNCTION // A reliable write operation is no presently underway. // // ERROR_BAD_NET_RESP // The target server did not provide an appropriate network response. // // ERROR_SEM_TIMEOUT // The request timed-out. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // E_BLUETOOTH_ATT_<ERROR_CODE> // An error code returned by the device indicating a specific error has occured. // Consult the Bluetooth specification for more information. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTAbortReliableWrite( _In_ HANDLE hDevice, _In_ BTH_LE_GATT_RELIABLE_WRITE_CONTEXT ReliableWriteContext, _In_ ULONG Flags ); // // Description: // The BluetoothGATTSetDescriptorValue function writes the specified descriptor value to the Bluetooth device. // // Parameters: // hDevice [in] // Handle to the service. // // Descriptor [in] // The parent descriptor. // // DescriptorValue [in] // Pointer to the descriptor value. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // BLUETOOTH_GATT_FLAG_CONNECTION_ENCRYPTED: The client requests the data to be transmitted over an encrypted channel. // BLUETOOTH_GATT_FLAG_CONNECTION_AUTHENTICATED: The client requests the data to be transmitted over an authenticated channel. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // // ERROR_BAD_NET_RESP // The target server did not provide an appropriate network response. // // ERROR_SEM_TIMEOUT // The request timed-out. // /// ERROR_NO_SYSTEM_RESOURCES // The operation ran out of memory. // // ERROR_INVALID_FUNCTION // A reliable write operation is already presently underway. // // E_BLUETOOTH_ATT_<ERROR_CODE> // An error code returned by the device indicating a specific error has occured. // Consult the Bluetooth specification for more information. // _Success_(S_OK == return) HRESULT WINAPI BluetoothGATTSetDescriptorValue( _In_ HANDLE hDevice, _In_ PBTH_LE_GATT_DESCRIPTOR Descriptor, _In_ PBTH_LE_GATT_DESCRIPTOR_VALUE DescriptorValue, _In_ ULONG Flags ); // // Description: // Registers for a characteristic value change event on the given characteristic // identified by its characteristic handle. // // Parameters: // hDevice [in] // Handle to the Bluetooth device or a service in the Bluetooth device. // For CharacteristicValueChangedEvent, this must be a service handle. // // EventType [in] // CharacteristicValueChangedEvent: event callback to receive Handle Value Notifications or Handle Value Indications. // // EventParameters [in] // CharacteristicValueChangedEvent: A pointer to BLUETOOTH_GATT_NOTIFICATION_REGISTRATION // that specifies the characteristics to be registered for the changed event notifications. // // Callback [in] // The callback method to call when the Characteristic value changes. // // CallbackContext [in] // A client context provided in the client provided callback function. // // EventHandle [out] // Upon successful registration, this parameter receives a handle to this registration. // The client shall use this handle when calling BluetoothGATTUnregisterEvent. // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // BLUETOOTH_GATT_FLAG_CONNECTION_ENCRYPTED: The client requests the data to be transmitted over an encrypted channel. // BLUETOOTH_GATT_FLAG_CONNECTION_AUTHENTICATED: The client requests the data to be transmitted over an authenticated channel. // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // HRESULT WINAPI BluetoothGATTRegisterEvent( _In_ HANDLE hService, _In_ BTH_LE_GATT_EVENT_TYPE EventType, _In_ PVOID EventParameterIn, _In_ PFNBLUETOOTH_GATT_EVENT_CALLBACK Callback, _In_opt_ PVOID CallbackContext, _Out_ BLUETOOTH_GATT_EVENT_HANDLE * pEventHandle, _In_ ULONG Flags ); // // Description: // Unregisters the given characteristic value change event. // // Parameters: // EventHandle [in] // Obtained via BluetoothGATTRegisterEvent // // Flags [in] // BLUETOOTH_GATT_FLAG_NONE: The client does not have specific GATT requirements (default). // // Return Value: // S_OK // The operation completed successfully. // // ERROR_INVALID_PARAMETER // One of the parameters were invalid. // HRESULT WINAPI BluetoothGATTUnregisterEvent( _In_ BLUETOOTH_GATT_EVENT_HANDLE EventHandle, _In_ ULONG Flags ); #endif //NTDDI_WIN8 #ifdef __cplusplus } #endif #endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */ #pragma endregion
8cbb39276611b8bbcc67736d43f67f391d4d815d
4cf3ee2c90e6ad1cea9cdba1b1e76224eee2ac4d
/utils/atj2137/atjboottool/fw.h
95f80871164dec18238a7b723cd0a0d1fb600bf1
[]
no_license
Rockbox/rockbox
36f73fc2660f3edb32dc07db26c5f9b88851975f
67c4231e34cd8147963a054c44a715f3413fb2e3
refs/heads/master
2021-09-15T22:10:00.710240
2021-08-29T12:19:02
2021-09-12T17:35:35
3,184,247
394
157
null
2021-09-05T11:00:28
2012-01-15T15:37:35
C
UTF-8
C
false
false
1,516
h
fw.h
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2017 Amaury Pouly * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #ifndef __FW_H__ #define __FW_H__ #include <stdint.h> /* Unpack an AFI file: the callback function will be called once for each file in the archive with * its name and content. If the callback returns a nonzero value, the function will stop and return * that value. Returns 0 on success */ typedef int (*fw_extract_callback_t)(const char *name, uint8_t *buf, size_t size); int fw_unpack(uint8_t *buf, size_t size, fw_extract_callback_t cb); /* Check if a file looks like an AFI file */ bool fw_check(uint8_t *buf, size_t size); #endif /* __FW_H__ */
7f00da96fca59823f461c94e831056024b8013c3
00613931db0dc1113d628b673b8a242fee684fac
/Core/Atom/AtomEcho/Arduino/StreamHttpClient_ECHO/src/libhelix-aac/sbrhfadj.c
f16cb07ba6c805fc1023f285a0c276ec1b3829b4
[ "LicenseRef-scancode-unknown-license-reference", "GPL-3.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-proprietary-license", "MIT" ]
permissive
m5stack/M5-ProductExampleCodes
437b9413d92adb43c873149dd768da3d0b979869
1bc38736e61a362080d1dffc4020b3a2a1dff6ae
refs/heads/master
2022-09-16T07:38:54.184583
2022-07-21T01:05:46
2022-07-21T01:05:46
156,688,327
316
524
MIT
2022-07-21T01:05:47
2018-11-08T10:17:23
C
UTF-8
C
false
false
32,600
c
sbrhfadj.c
/* ***** BEGIN LICENSE BLOCK ***** * Source last modified: $Id: sbrhfadj.c,v 1.3 2005/05/24 16:01:55 albertofloyd Exp $ * * Portions Copyright (c) 1995-2005 RealNetworks, Inc. All Rights Reserved. * * The contents of this file, and the files included with this file, * are subject to the current version of the RealNetworks Public * Source License (the "RPSL") available at * http://www.helixcommunity.org/content/rpsl unless you have licensed * the file under the current version of the RealNetworks Community * Source License (the "RCSL") available at * http://www.helixcommunity.org/content/rcsl, in which case the RCSL * will apply. You may also obtain the license terms directly from * RealNetworks. You may not use this file except in compliance with * the RPSL or, if you have a valid RCSL with RealNetworks applicable * to this file, the RCSL. Please see the applicable RPSL or RCSL for * the rights, obligations and limitations governing use of the * contents of the file. * * This file is part of the Helix DNA Technology. RealNetworks is the * developer of the Original Code and owns the copyrights in the * portions it created. * * This file, and the files included with this file, is distributed * and made available on an 'AS IS' basis, WITHOUT WARRANTY OF ANY * KIND, EITHER EXPRESS OR IMPLIED, AND REALNETWORKS HEREBY DISCLAIMS * ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, QUIET * ENJOYMENT OR NON-INFRINGEMENT. * * Technology Compatibility Kit Test Suite(s) Location: * http://www.helixcommunity.org/content/tck * * Contributor(s): * * ***** END LICENSE BLOCK ***** */ /************************************************************************************** * Fixed-point HE-AAC decoder * Jon Recker (jrecker@real.com) * February 2005 * * sbrhfadj.c - high frequency adjustment for SBR **************************************************************************************/ #include "sbr.h" #include "assembly.h" /* invBandTab[i] = 1.0 / (i + 1), Q31 */ static const int invBandTab[64] PROGMEM = { 0x7fffffff, 0x40000000, 0x2aaaaaab, 0x20000000, 0x1999999a, 0x15555555, 0x12492492, 0x10000000, 0x0e38e38e, 0x0ccccccd, 0x0ba2e8ba, 0x0aaaaaab, 0x09d89d8a, 0x09249249, 0x08888889, 0x08000000, 0x07878788, 0x071c71c7, 0x06bca1af, 0x06666666, 0x06186186, 0x05d1745d, 0x0590b216, 0x05555555, 0x051eb852, 0x04ec4ec5, 0x04bda12f, 0x04924925, 0x0469ee58, 0x04444444, 0x04210842, 0x04000000, 0x03e0f83e, 0x03c3c3c4, 0x03a83a84, 0x038e38e4, 0x03759f23, 0x035e50d8, 0x03483483, 0x03333333, 0x031f3832, 0x030c30c3, 0x02fa0be8, 0x02e8ba2f, 0x02d82d83, 0x02c8590b, 0x02b93105, 0x02aaaaab, 0x029cbc15, 0x028f5c29, 0x02828283, 0x02762762, 0x026a439f, 0x025ed098, 0x0253c825, 0x02492492, 0x023ee090, 0x0234f72c, 0x022b63cc, 0x02222222, 0x02192e2a, 0x02108421, 0x02082082, 0x02000000, }; /************************************************************************************** * Function: EstimateEnvelope * * Description: estimate power of generated HF QMF bands in one time-domain envelope * (4.6.18.7.3) * * Inputs: initialized PSInfoSBR struct * initialized SBRHeader struct for this SCE/CPE block * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * index of current envelope * * Outputs: power of each QMF subband, stored as integer (Q0) * 2^N, N >= 0 * * Return: none **************************************************************************************/ static void EstimateEnvelope(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, int env) { int i, m, iStart, iEnd, xre, xim, nScale, expMax; int p, n, mStart, mEnd, invFact, t; int *XBuf; U64 eCurr; unsigned char *freqBandTab; /* estimate current envelope */ iStart = sbrGrid->envTimeBorder[env] + HF_ADJ; iEnd = sbrGrid->envTimeBorder[env+1] + HF_ADJ; if (sbrGrid->freqRes[env]) { n = sbrFreq->nHigh; freqBandTab = sbrFreq->freqHigh; } else { n = sbrFreq->nLow; freqBandTab = sbrFreq->freqLow; } /* ADS should inline MADD64 (smlal) properly, but check to make sure */ expMax = 0; if (sbrHdr->interpFreq) { for (m = 0; m < sbrFreq->numQMFBands; m++) { eCurr.w64 = 0; XBuf = psi->XBuf[iStart][sbrFreq->kStart + m]; for (i = iStart; i < iEnd; i++) { /* scale to int before calculating power (precision not critical, and avoids overflow) */ xre = (*XBuf) >> FBITS_OUT_QMFA; XBuf += 1; xim = (*XBuf) >> FBITS_OUT_QMFA; XBuf += (2*64 - 1); eCurr.w64 = MADD64(eCurr.w64, xre, xre); eCurr.w64 = MADD64(eCurr.w64, xim, xim); } /* eCurr.w64 is now Q(64 - 2*FBITS_OUT_QMFA) (64-bit word) * if energy is too big to fit in 32-bit word (> 2^31) scale down by power of 2 */ nScale = 0; if (eCurr.r.hi32) { nScale = (32 - CLZ(eCurr.r.hi32)) + 1; t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */ t |= eCurr.r.hi32 << (32 - nScale); } else if (eCurr.r.lo32 >> 31) { nScale = 1; t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */ } else { t = (int)eCurr.r.lo32; } invFact = invBandTab[(iEnd - iStart)-1]; psi->eCurr[m] = MULSHIFT32(t, invFact); psi->eCurrExp[m] = nScale + 1; /* +1 for invFact = Q31 */ if (psi->eCurrExp[m] > expMax) expMax = psi->eCurrExp[m]; } } else { for (p = 0; p < n; p++) { mStart = freqBandTab[p]; mEnd = freqBandTab[p+1]; eCurr.w64 = 0; for (i = iStart; i < iEnd; i++) { XBuf = psi->XBuf[i][mStart]; for (m = mStart; m < mEnd; m++) { xre = (*XBuf++) >> FBITS_OUT_QMFA; xim = (*XBuf++) >> FBITS_OUT_QMFA; eCurr.w64 = MADD64(eCurr.w64, xre, xre); eCurr.w64 = MADD64(eCurr.w64, xim, xim); } } nScale = 0; if (eCurr.r.hi32) { nScale = (32 - CLZ(eCurr.r.hi32)) + 1; t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */ t |= eCurr.r.hi32 << (32 - nScale); } else if (eCurr.r.lo32 >> 31) { nScale = 1; t = (int)(eCurr.r.lo32 >> nScale); /* logical (unsigned) >> */ } else { t = (int)eCurr.r.lo32; } invFact = invBandTab[(iEnd - iStart)-1]; invFact = MULSHIFT32(invBandTab[(mEnd - mStart)-1], invFact) << 1; t = MULSHIFT32(t, invFact); for (m = mStart; m < mEnd; m++) { psi->eCurr[m - sbrFreq->kStart] = t; psi->eCurrExp[m - sbrFreq->kStart] = nScale + 1; /* +1 for invFact = Q31 */ } if (psi->eCurrExp[mStart - sbrFreq->kStart] > expMax) expMax = psi->eCurrExp[mStart - sbrFreq->kStart]; } } psi->eCurrExpMax = expMax; } /************************************************************************************** * Function: GetSMapped * * Description: calculate SMapped (4.6.18.7.2) * * Inputs: initialized PSInfoSBR struct * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * initialized SBRChan struct for this channel * index of current envelope * index of current QMF band * la flag for this envelope * * Outputs: none * * Return: 1 if a sinusoid is present in this band, 0 if not **************************************************************************************/ static int GetSMapped(SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int env, int band, int la) { int bandStart, bandEnd, oddFlag, r; if (sbrGrid->freqRes[env]) { /* high resolution */ bandStart = band; bandEnd = band+1; } else { /* low resolution (see CalcFreqLow() for mapping) */ oddFlag = sbrFreq->nHigh & 0x01; bandStart = (band > 0 ? 2*band - oddFlag : 0); /* starting index for freqLow[band] */ bandEnd = 2*(band+1) - oddFlag; /* ending index for freqLow[band+1] */ } /* sMapped = 1 if sIndexMapped == 1 for any frequency in this band */ for (band = bandStart; band < bandEnd; band++) { if (sbrChan->addHarmonic[1][band]) { r = ((sbrFreq->freqHigh[band+1] + sbrFreq->freqHigh[band]) >> 1); if (env >= la || sbrChan->addHarmonic[0][r] == 1) return 1; } } return 0; } #define GBOOST_MAX 0x2830afd3 /* Q28, 1.584893192 squared */ #define ACC_SCALE 6 /* squared version of table in 4.6.18.7.5 */ static const int limGainTab[4] PROGMEM = {0x20138ca7, 0x40000000, 0x7fb27dce, 0x80000000}; /* Q30 (0x80000000 = sentinel for GMAX) */ /************************************************************************************** * Function: CalcMaxGain * * Description: calculate max gain in one limiter band (4.6.18.7.5) * * Inputs: initialized PSInfoSBR struct * initialized SBRHeader struct for this SCE/CPE block * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * index of current channel (0 for SCE, 0 or 1 for CPE) * index of current envelope * index of current limiter band * number of fraction bits in dequantized envelope * (max = Q(FBITS_OUT_DQ_ENV - 6) = Q23, can go negative) * * Outputs: updated gainMax, gainMaxFBits, and sumEOrigMapped in PSInfoSBR struct * * Return: none **************************************************************************************/ static void CalcMaxGain(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, int ch, int env, int lim, int fbitsDQ) { int m, mStart, mEnd, q, z, r; int sumEOrigMapped, sumECurr, gainMax, eOMGainMax, envBand; unsigned char eCurrExpMax; unsigned char *freqBandTab; mStart = sbrFreq->freqLimiter[lim]; /* these are offsets from kStart */ mEnd = sbrFreq->freqLimiter[lim + 1]; freqBandTab = (sbrGrid->freqRes[env] ? sbrFreq->freqHigh : sbrFreq->freqLow); /* calculate max gain to apply to signal in this limiter band */ sumECurr = 0; sumEOrigMapped = 0; eCurrExpMax = psi->eCurrExpMax; eOMGainMax = psi->eOMGainMax; envBand = psi->envBand; for (m = mStart; m < mEnd; m++) { /* map current QMF band to appropriate envelope band */ if (m == freqBandTab[envBand + 1] - sbrFreq->kStart) { envBand++; eOMGainMax = psi->envDataDequant[ch][env][envBand] >> ACC_SCALE; /* summing max 48 bands */ } sumEOrigMapped += eOMGainMax; /* easy test for overflow on ARM */ sumECurr += (psi->eCurr[m] >> (eCurrExpMax - psi->eCurrExp[m])); if (sumECurr >> 30) { sumECurr >>= 1; eCurrExpMax++; } } psi->eOMGainMax = eOMGainMax; psi->envBand = envBand; psi->gainMaxFBits = 30; /* Q30 tables */ if (sumECurr == 0) { /* any non-zero numerator * 1/EPS_0 is > G_MAX */ gainMax = (sumEOrigMapped == 0 ? (int)limGainTab[sbrHdr->limiterGains] : (int)0x80000000); } else if (sumEOrigMapped == 0) { /* 1/(any non-zero denominator) * EPS_0 * limGainTab[x] is appx. 0 */ gainMax = 0; } else { /* sumEOrigMapped = Q(fbitsDQ - ACC_SCALE), sumECurr = Q(-eCurrExpMax) */ gainMax = limGainTab[sbrHdr->limiterGains]; if (sbrHdr->limiterGains != 3) { q = MULSHIFT32(sumEOrigMapped, gainMax); /* Q(fbitsDQ - ACC_SCALE - 2), gainMax = Q30 */ z = CLZ(sumECurr) - 1; r = InvRNormalized(sumECurr << z); /* in = Q(z - eCurrExpMax), out = Q(29 + 31 - z + eCurrExpMax) */ gainMax = MULSHIFT32(q, r); /* Q(29 + 31 - z + eCurrExpMax + fbitsDQ - ACC_SCALE - 2 - 32) */ psi->gainMaxFBits = 26 - z + eCurrExpMax + fbitsDQ - ACC_SCALE; } } psi->sumEOrigMapped = sumEOrigMapped; psi->gainMax = gainMax; } /************************************************************************************** * Function: CalcNoiseDivFactors * * Description: calculate 1/(1+Q) and Q/(1+Q) (4.6.18.7.4; 4.6.18.7.5) * * Inputs: dequantized noise floor scalefactor * * Outputs: 1/(1+Q) and Q/(1+Q), format = Q31 * * Return: none **************************************************************************************/ static void CalcNoiseDivFactors(int q, int *qp1Inv, int *qqp1Inv) { int z, qp1, t, s; /* 1 + Q_orig */ qp1 = (q >> 1); qp1 += (1 << (FBITS_OUT_DQ_NOISE - 1)); /* >> 1 to avoid overflow when adding 1.0 */ z = CLZ(qp1) - 1; /* z <= 31 - FBITS_OUT_DQ_NOISE */ qp1 <<= z; /* Q(FBITS_OUT_DQ_NOISE + z) = Q31 * 2^-(31 - (FBITS_OUT_DQ_NOISE + z)) */ t = InvRNormalized(qp1) << 1; /* Q30 * 2^(31 - (FBITS_OUT_DQ_NOISE + z)), guaranteed not to overflow */ /* normalize to Q31 */ s = (31 - (FBITS_OUT_DQ_NOISE - 1) - z - 1); /* clearly z >= 0, z <= (30 - (FBITS_OUT_DQ_NOISE - 1)) */ *qp1Inv = (t >> s); /* s = [0, 31 - FBITS_OUT_DQ_NOISE] */ *qqp1Inv = MULSHIFT32(t, q) << (32 - FBITS_OUT_DQ_NOISE - s); } /************************************************************************************** * Function: CalcComponentGains * * Description: calculate gain of envelope, sinusoids, and noise in one limiter band * (4.6.18.7.5) * * Inputs: initialized PSInfoSBR struct * initialized SBRHeader struct for this SCE/CPE block * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * initialized SBRChan struct for this channel * index of current channel (0 for SCE, 0 or 1 for CPE) * index of current envelope * index of current limiter band * number of fraction bits in dequantized envelope * * Outputs: gains for envelope, sinusoids and noise * number of fraction bits for envelope gain * sum of the total gain for each component in this band * other updated state variables * * Return: none **************************************************************************************/ static void CalcComponentGains(PSInfoSBR *psi, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch, int env, int lim, int fbitsDQ) { int d, m, mStart, mEnd, q, qm, noiseFloor, sIndexMapped; int shift, eCurr, maxFlag, gainMax, gainMaxFBits; int gain, sm, z, r, fbitsGain, gainScale; unsigned char *freqBandTab; mStart = sbrFreq->freqLimiter[lim]; /* these are offsets from kStart */ mEnd = sbrFreq->freqLimiter[lim + 1]; gainMax = psi->gainMax; gainMaxFBits = psi->gainMaxFBits; d = (env == psi->la || env == sbrChan->laPrev ? 0 : 1); freqBandTab = (sbrGrid->freqRes[env] ? sbrFreq->freqHigh : sbrFreq->freqLow); /* figure out which noise floor this envelope is in (only 1 or 2 noise floors allowed) */ noiseFloor = 0; if (sbrGrid->numNoiseFloors == 2 && sbrGrid->noiseTimeBorder[1] <= sbrGrid->envTimeBorder[env]) noiseFloor++; psi->sumECurrGLim = 0; psi->sumSM = 0; psi->sumQM = 0; /* calculate energy of noise to add in this limiter band */ for (m = mStart; m < mEnd; m++) { if (m == sbrFreq->freqNoise[psi->noiseFloorBand + 1] - sbrFreq->kStart) { /* map current QMF band to appropriate noise floor band (NOTE: freqLimiter[0] == freqLow[0] = freqHigh[0]) */ psi->noiseFloorBand++; CalcNoiseDivFactors(psi->noiseDataDequant[ch][noiseFloor][psi->noiseFloorBand], &(psi->qp1Inv), &(psi->qqp1Inv)); } if (m == sbrFreq->freqHigh[psi->highBand + 1] - sbrFreq->kStart) psi->highBand++; if (m == freqBandTab[psi->sBand + 1] - sbrFreq->kStart) { psi->sBand++; psi->sMapped = GetSMapped(sbrGrid, sbrFreq, sbrChan, env, psi->sBand, psi->la); } /* get sIndexMapped for this QMF subband */ sIndexMapped = 0; r = ((sbrFreq->freqHigh[psi->highBand+1] + sbrFreq->freqHigh[psi->highBand]) >> 1); if (m + sbrFreq->kStart == r) { /* r = center frequency, deltaStep = (env >= la || sIndexMapped'(r, numEnv'-1) == 1) */ if (env >= psi->la || sbrChan->addHarmonic[0][r] == 1) sIndexMapped = sbrChan->addHarmonic[1][psi->highBand]; } /* save sine flags from last envelope in this frame: * addHarmonic[0][0...63] = saved sine present flag from previous frame, for each QMF subband * addHarmonic[1][0...nHigh-1] = addHarmonic bit from current frame, for each high-res frequency band * from MPEG reference code - slightly different from spec * (sIndexMapped'(m,LE'-1) can still be 0 when numEnv == psi->la) */ if (env == sbrGrid->numEnv - 1) { if (m + sbrFreq->kStart == r) sbrChan->addHarmonic[0][m + sbrFreq->kStart] = sbrChan->addHarmonic[1][psi->highBand]; else sbrChan->addHarmonic[0][m + sbrFreq->kStart] = 0; } gain = psi->envDataDequant[ch][env][psi->sBand]; qm = MULSHIFT32(gain, psi->qqp1Inv) << 1; sm = (sIndexMapped ? MULSHIFT32(gain, psi->qp1Inv) << 1 : 0); /* three cases: (sMapped == 0 && delta == 1), (sMapped == 0 && delta == 0), (sMapped == 1) */ if (d == 1 && psi->sMapped == 0) gain = MULSHIFT32(psi->qp1Inv, gain) << 1; else if (psi->sMapped != 0) gain = MULSHIFT32(psi->qqp1Inv, gain) << 1; /* gain, qm, sm = Q(fbitsDQ), gainMax = Q(fbitsGainMax) */ eCurr = psi->eCurr[m]; if (eCurr) { z = CLZ(eCurr) - 1; r = InvRNormalized(eCurr << z); /* in = Q(z - eCurrExp), out = Q(29 + 31 - z + eCurrExp) */ gainScale = MULSHIFT32(gain, r); /* out = Q(29 + 31 - z + eCurrExp + fbitsDQ - 32) */ fbitsGain = 29 + 31 - z + psi->eCurrExp[m] + fbitsDQ - 32; } else { /* if eCurr == 0, then gain is unchanged (divide by EPS = 1) */ gainScale = gain; fbitsGain = fbitsDQ; } /* see if gain for this band exceeds max gain */ maxFlag = 0; if (gainMax != (int)0x80000000) { if (fbitsGain >= gainMaxFBits) { shift = MIN(fbitsGain - gainMaxFBits, 31); maxFlag = ((gainScale >> shift) > gainMax ? 1 : 0); } else { shift = MIN(gainMaxFBits - fbitsGain, 31); maxFlag = (gainScale > (gainMax >> shift) ? 1 : 0); } } if (maxFlag) { /* gainScale > gainMax, calculate ratio with 32/16 division */ q = 0; r = gainScale; /* guaranteed > 0, else maxFlag could not have been set */ z = CLZ(r); if (z < 16) { q = 16 - z; r >>= q; /* out = Q(fbitsGain - q) */ } z = CLZ(gainMax) - 1; r = (gainMax << z) / r; /* out = Q((fbitsGainMax + z) - (fbitsGain - q)) */ q = (gainMaxFBits + z) - (fbitsGain - q); /* r = Q(q) */ if (q > 30) { r >>= MIN(q - 30, 31); } else { z = MIN(30 - q, 30); CLIP_2N_SHIFT30(r, z); /* let r = Q30 since range = [0.0, 1.0) (clip to 0x3fffffff = 0.99999) */ } qm = MULSHIFT32(qm, r) << 2; gain = MULSHIFT32(gain, r) << 2; psi->gLimBuf[m] = gainMax; psi->gLimFbits[m] = gainMaxFBits; } else { psi->gLimBuf[m] = gainScale; psi->gLimFbits[m] = fbitsGain; } /* sumSM, sumQM, sumECurrGLim = Q(fbitsDQ - ACC_SCALE) */ psi->smBuf[m] = sm; psi->sumSM += (sm >> ACC_SCALE); psi->qmLimBuf[m] = qm; if (env != psi->la && env != sbrChan->laPrev && sm == 0) psi->sumQM += (qm >> ACC_SCALE); /* eCurr * gain^2 same as gain^2, before division by eCurr * (but note that gain != 0 even if eCurr == 0, since it's divided by eps) */ if (eCurr) psi->sumECurrGLim += (gain >> ACC_SCALE); } } /************************************************************************************** * Function: ApplyBoost * * Description: calculate and apply boost factor for envelope, sinusoids, and noise * in this limiter band (4.6.18.7.5) * * Inputs: initialized PSInfoSBR struct * initialized SBRFreq struct for this SCE/CPE block * index of current limiter band * number of fraction bits in dequantized envelope * * Outputs: envelope gain, sinusoids and noise after scaling by gBoost * format = Q(FBITS_GLIM_BOOST) for envelope gain, * = Q(FBITS_QLIM_BOOST) for noise * = Q(FBITS_OUT_QMFA) for sinusoids * * Return: none * * Notes: after scaling, each component has at least 1 GB **************************************************************************************/ static void ApplyBoost(PSInfoSBR *psi, SBRFreq *sbrFreq, int lim, int fbitsDQ) { int m, mStart, mEnd, q, z, r; int sumEOrigMapped, gBoost; mStart = sbrFreq->freqLimiter[lim]; /* these are offsets from kStart */ mEnd = sbrFreq->freqLimiter[lim + 1]; sumEOrigMapped = psi->sumEOrigMapped >> 1; r = (psi->sumECurrGLim >> 1) + (psi->sumSM >> 1) + (psi->sumQM >> 1); /* 1 GB fine (sm and qm are mutually exclusive in acc) */ if (r < (1 << (31-28))) { /* any non-zero numerator * 1/EPS_0 is > GBOOST_MAX * round very small r to zero to avoid scaling problems */ gBoost = (sumEOrigMapped == 0 ? (1 << 28) : GBOOST_MAX); z = 0; } else if (sumEOrigMapped == 0) { /* 1/(any non-zero denominator) * EPS_0 is appx. 0 */ gBoost = 0; z = 0; } else { /* numerator (sumEOrigMapped) and denominator (r) have same Q format (before << z) */ z = CLZ(r) - 1; /* z = [0, 27] */ r = InvRNormalized(r << z); gBoost = MULSHIFT32(sumEOrigMapped, r); } /* gBoost = Q(28 - z) */ if (gBoost > (GBOOST_MAX >> z)) { gBoost = GBOOST_MAX; z = 0; } gBoost <<= z; /* gBoost = Q28, minimum 1 GB */ /* convert gain, noise, sinusoids to fixed Q format, clipping if necessary * (rare, usually only happens at very low bitrates, introduces slight * distortion into final HF mapping, but should be inaudible) */ for (m = mStart; m < mEnd; m++) { /* let gLimBoost = Q24, since in practice the max values are usually 16 to 20 * unless limiterGains == 3 (limiter off) and eCurr ~= 0 (i.e. huge gain, but only * because the envelope has 0 power anyway) */ q = MULSHIFT32(psi->gLimBuf[m], gBoost) << 2; /* Q(gLimFbits) * Q(28) --> Q(gLimFbits[m]-2) */ r = SqrtFix(q, psi->gLimFbits[m] - 2, &z); z -= FBITS_GLIM_BOOST; if (z >= 0) { psi->gLimBoost[m] = r >> MIN(z, 31); } else { z = MIN(30, -z); CLIP_2N_SHIFT30(r, z); psi->gLimBoost[m] = r; } q = MULSHIFT32(psi->qmLimBuf[m], gBoost) << 2; /* Q(fbitsDQ) * Q(28) --> Q(fbitsDQ-2) */ r = SqrtFix(q, fbitsDQ - 2, &z); z -= FBITS_QLIM_BOOST; /* << by 14, since integer sqrt of x < 2^16, and we want to leave 1 GB */ if (z >= 0) { psi->qmLimBoost[m] = r >> MIN(31, z); } else { z = MIN(30, -z); CLIP_2N_SHIFT30(r, z); psi->qmLimBoost[m] = r; } q = MULSHIFT32(psi->smBuf[m], gBoost) << 2; /* Q(fbitsDQ) * Q(28) --> Q(fbitsDQ-2) */ r = SqrtFix(q, fbitsDQ - 2, &z); z -= FBITS_OUT_QMFA; /* justify for adding to signal (xBuf) later */ if (z >= 0) { psi->smBoost[m] = r >> MIN(31, z); } else { z = MIN(30, -z); CLIP_2N_SHIFT30(r, z); psi->smBoost[m] = r; } } } /************************************************************************************** * Function: CalcGain * * Description: calculate and apply proper gain to HF components in one envelope * (4.6.18.7.5) * * Inputs: initialized PSInfoSBR struct * initialized SBRHeader struct for this SCE/CPE block * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * initialized SBRChan struct for this channel * index of current channel (0 for SCE, 0 or 1 for CPE) * index of current envelope * * Outputs: envelope gain, sinusoids and noise after scaling * * Return: none **************************************************************************************/ static void CalcGain(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch, int env) { int lim, fbitsDQ; /* initialize to -1 so that mapping limiter bands to env/noise bands works right on first pass */ psi->envBand = -1; psi->noiseFloorBand = -1; psi->sBand = -1; psi->highBand = -1; fbitsDQ = (FBITS_OUT_DQ_ENV - psi->envDataDequantScale[ch][env]); /* Q(29 - optional scalefactor) */ for (lim = 0; lim < sbrFreq->nLimiter; lim++) { /* the QMF bands are divided into lim regions (consecutive, non-overlapping) */ CalcMaxGain(psi, sbrHdr, sbrGrid, sbrFreq, ch, env, lim, fbitsDQ); CalcComponentGains(psi, sbrGrid, sbrFreq, sbrChan, ch, env, lim, fbitsDQ); ApplyBoost(psi, sbrFreq, lim, fbitsDQ); } } /* hSmooth table from 4.7.18.7.6, format = Q31 */ static const int hSmoothCoef[MAX_NUM_SMOOTH_COEFS] PROGMEM = { 0x2aaaaaab, 0x2697a512, 0x1becfa68, 0x0ebdb043, 0x04130598, }; /************************************************************************************** * Function: MapHF * * Description: map HF components to proper QMF bands, with optional gain smoothing * filter (4.6.18.7.6) * * Inputs: initialized PSInfoSBR struct * initialized SBRHeader struct for this SCE/CPE block * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * initialized SBRChan struct for this channel * index of current envelope * reset flag (can be non-zero for first envelope only) * * Outputs: complete reconstructed subband QMF samples for this envelope * * Return: none * * Notes: ensures that output has >= MIN_GBITS_IN_QMFS guard bits, * so it's not necessary to check anything in the synth QMF **************************************************************************************/ static void MapHF(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int env, int hfReset) { int noiseTabIndex, sinIndex, gainNoiseIndex, hSL; int i, iStart, iEnd, m, idx, j, s, n, smre, smim; int gFilt, qFilt, xre, xim, gbMask, gbIdx; int *XBuf; noiseTabIndex = sbrChan->noiseTabIndex; sinIndex = sbrChan->sinIndex; gainNoiseIndex = sbrChan->gainNoiseIndex; /* oldest entries in filter delay buffer */ if (hfReset) noiseTabIndex = 2; /* starts at 1, double since complex */ hSL = (sbrHdr->smoothMode ? 0 : 4); if (hfReset) { for (i = 0; i < hSL; i++) { for (m = 0; m < sbrFreq->numQMFBands; m++) { sbrChan->gTemp[gainNoiseIndex][m] = psi->gLimBoost[m]; sbrChan->qTemp[gainNoiseIndex][m] = psi->qmLimBoost[m]; } gainNoiseIndex++; if (gainNoiseIndex == MAX_NUM_SMOOTH_COEFS) gainNoiseIndex = 0; } ASSERT(env == 0); /* should only be reset when env == 0 */ } iStart = sbrGrid->envTimeBorder[env]; iEnd = sbrGrid->envTimeBorder[env+1]; for (i = iStart; i < iEnd; i++) { /* save new values in temp buffers (delay) * we only store MAX_NUM_SMOOTH_COEFS most recent values, * so don't keep storing the same value over and over */ if (i - iStart < MAX_NUM_SMOOTH_COEFS) { for (m = 0; m < sbrFreq->numQMFBands; m++) { sbrChan->gTemp[gainNoiseIndex][m] = psi->gLimBoost[m]; sbrChan->qTemp[gainNoiseIndex][m] = psi->qmLimBoost[m]; } } /* see 4.6.18.7.6 */ XBuf = psi->XBuf[i + HF_ADJ][sbrFreq->kStart]; gbMask = 0; for (m = 0; m < sbrFreq->numQMFBands; m++) { if (env == psi->la || env == sbrChan->laPrev) { /* no smoothing filter for gain, and qFilt = 0 (only need to do once) */ if (i == iStart) { psi->gFiltLast[m] = sbrChan->gTemp[gainNoiseIndex][m]; psi->qFiltLast[m] = 0; } } else if (hSL == 0) { /* no smoothing filter for gain, (only need to do once) */ if (i == iStart) { psi->gFiltLast[m] = sbrChan->gTemp[gainNoiseIndex][m]; psi->qFiltLast[m] = sbrChan->qTemp[gainNoiseIndex][m]; } } else { /* apply smoothing filter to gain and noise (after MAX_NUM_SMOOTH_COEFS, it's always the same) */ if (i - iStart < MAX_NUM_SMOOTH_COEFS) { gFilt = 0; qFilt = 0; idx = gainNoiseIndex; for (j = 0; j < MAX_NUM_SMOOTH_COEFS; j++) { /* sum(abs(hSmoothCoef[j])) for all j < 1.0 */ gFilt += MULSHIFT32(sbrChan->gTemp[idx][m], hSmoothCoef[j]); qFilt += MULSHIFT32(sbrChan->qTemp[idx][m], hSmoothCoef[j]); idx--; if (idx < 0) idx += MAX_NUM_SMOOTH_COEFS; } psi->gFiltLast[m] = gFilt << 1; /* restore to Q(FBITS_GLIM_BOOST) (gain of filter < 1.0, so no overflow) */ psi->qFiltLast[m] = qFilt << 1; /* restore to Q(FBITS_QLIM_BOOST) */ } } if (psi->smBoost[m] != 0) { /* add scaled signal and sinusoid, don't add noise (qFilt = 0) */ smre = psi->smBoost[m]; smim = smre; /* sinIndex: [0] xre += sm [1] xim += sm*s [2] xre -= sm [3] xim -= sm*s */ s = (sinIndex >> 1); /* if 2 or 3, flip sign to subtract sm */ s <<= 31; smre ^= (s >> 31); smre -= (s >> 31); s ^= ((m + sbrFreq->kStart) << 31); smim ^= (s >> 31); smim -= (s >> 31); /* if sinIndex == 0 or 2, smim = 0; if sinIndex == 1 or 3, smre = 0 */ s = sinIndex << 31; smim &= (s >> 31); s ^= 0x80000000; smre &= (s >> 31); noiseTabIndex += 2; /* noise filtered by 0, but still need to bump index */ } else { /* add scaled signal and scaled noise */ qFilt = psi->qFiltLast[m]; n = noiseTab[noiseTabIndex++]; smre = MULSHIFT32(n, qFilt) >> (FBITS_QLIM_BOOST - 1 - FBITS_OUT_QMFA); n = noiseTab[noiseTabIndex++]; smim = MULSHIFT32(n, qFilt) >> (FBITS_QLIM_BOOST - 1 - FBITS_OUT_QMFA); } noiseTabIndex &= 1023; /* 512 complex numbers */ gFilt = psi->gFiltLast[m]; xre = MULSHIFT32(gFilt, XBuf[0]); xim = MULSHIFT32(gFilt, XBuf[1]); CLIP_2N_SHIFT30(xre, 32 - FBITS_GLIM_BOOST); CLIP_2N_SHIFT30(xim, 32 - FBITS_GLIM_BOOST); xre += smre; *XBuf++ = xre; xim += smim; *XBuf++ = xim; gbMask |= FASTABS(xre); gbMask |= FASTABS(xim); } /* update circular buffer index */ gainNoiseIndex++; if (gainNoiseIndex == MAX_NUM_SMOOTH_COEFS) gainNoiseIndex = 0; sinIndex++; sinIndex &= 3; /* ensure MIN_GBITS_IN_QMFS guard bits in output * almost never occurs in practice, but checking here makes synth QMF logic very simple */ if (gbMask >> (31 - MIN_GBITS_IN_QMFS)) { XBuf = psi->XBuf[i + HF_ADJ][sbrFreq->kStart]; for (m = 0; m < sbrFreq->numQMFBands; m++) { xre = XBuf[0]; xim = XBuf[1]; CLIP_2N(xre, (31 - MIN_GBITS_IN_QMFS)); CLIP_2N(xim, (31 - MIN_GBITS_IN_QMFS)); *XBuf++ = xre; *XBuf++ = xim; } CLIP_2N(gbMask, (31 - MIN_GBITS_IN_QMFS)); } gbIdx = ((i + HF_ADJ) >> 5) & 0x01; sbrChan->gbMask[gbIdx] |= gbMask; } sbrChan->noiseTabIndex = noiseTabIndex; sbrChan->sinIndex = sinIndex; sbrChan->gainNoiseIndex = gainNoiseIndex; } /************************************************************************************** * Function: AdjustHighFreq * * Description: adjust high frequencies and add noise and sinusoids (4.6.18.7) * * Inputs: initialized PSInfoSBR struct * initialized SBRHeader struct for this SCE/CPE block * initialized SBRGrid struct for this channel * initialized SBRFreq struct for this SCE/CPE block * initialized SBRChan struct for this channel * index of current channel (0 for SCE, 0 or 1 for CPE) * * Outputs: complete reconstructed subband QMF samples for this channel * * Return: none **************************************************************************************/ void AdjustHighFreq(PSInfoSBR *psi, SBRHeader *sbrHdr, SBRGrid *sbrGrid, SBRFreq *sbrFreq, SBRChan *sbrChan, int ch) { int i, env, hfReset; unsigned char frameClass, pointer; frameClass = sbrGrid->frameClass; pointer = sbrGrid->pointer; /* derive la from table 4.159 */ if ((frameClass == SBR_GRID_FIXVAR || frameClass == SBR_GRID_VARVAR) && pointer > 0) psi->la = sbrGrid->numEnv + 1 - pointer; else if (frameClass == SBR_GRID_VARFIX && pointer > 1) psi->la = pointer - 1; else psi->la = -1; /* for each envelope, estimate gain and adjust SBR QMF bands */ hfReset = sbrChan->reset; for (env = 0; env < sbrGrid->numEnv; env++) { EstimateEnvelope(psi, sbrHdr, sbrGrid, sbrFreq, env); CalcGain(psi, sbrHdr, sbrGrid, sbrFreq, sbrChan, ch, env); MapHF(psi, sbrHdr, sbrGrid, sbrFreq, sbrChan, env, hfReset); hfReset = 0; /* only set for first envelope after header reset */ } /* set saved sine flags to 0 for QMF bands outside of current frequency range */ for (i = 0; i < sbrFreq->freqLimiter[0] + sbrFreq->kStart; i++) sbrChan->addHarmonic[0][i] = 0; for (i = sbrFreq->freqLimiter[sbrFreq->nLimiter] + sbrFreq->kStart; i < 64; i++) sbrChan->addHarmonic[0][i] = 0; sbrChan->addHarmonicFlag[0] = sbrChan->addHarmonicFlag[1]; /* save la for next frame */ if (psi->la == sbrGrid->numEnv) sbrChan->laPrev = 0; else sbrChan->laPrev = -1; }
c282bbf512bcd1dccccf75f334feaa430a895e7e
7c857119fe1505b1d80d6e62969661c06dc1a2f4
/IntelFrameworkPkg/Include/Protocol/AcpiSupport.h
278ef8e42b35764720e4c250af52a8378bcde61e
[ "BSD-2-Clause" ]
permissive
CloverHackyColor/CloverBootloader
7042ca7dd6b513d22be591a295e49071ae1482ee
2711170df4f60b2ae5aa20add3e00f35cf57b7e5
refs/heads/master
2023-08-30T22:14:34.590134
2023-08-27T19:14:02
2023-08-27T19:14:02
205,810,121
4,734
770
BSD-2-Clause
2023-09-03T12:41:33
2019-09-02T08:22:14
C
UTF-8
C
false
false
5,227
h
AcpiSupport.h
/** @file This protocol provides some basic services to support publishing ACPI system tables. The services handle many of the more mundane tasks that are required to publish a set of tables. The services will: - Generate common tables. - Update the table links. - Ensure that tables are properly aligned and use correct types of memory. - Update checksum values and IDs. - Complete the final installation of the tables. Copyright (c) 2007 - 2010, Intel Corporation. All rights reserved.<BR> This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License that accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php. THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. @par Revision Reference: This Protocol is defined in Framework ACPI Specification. Version 0.9. **/ #ifndef _ACPI_SUPPORT_PROTOCOL_H_ #define _ACPI_SUPPORT_PROTOCOL_H_ #include <Protocol/AcpiSystemDescriptionTable.h> typedef struct _EFI_ACPI_SUPPORT_PROTOCOL EFI_ACPI_SUPPORT_PROTOCOL; // // ACPI Support Protocol GUID // #define EFI_ACPI_SUPPORT_GUID \ { \ 0xdbff9d55, 0x89b7, 0x46da, {0xbd, 0xdf, 0x67, 0x7d, 0x3d, 0xc0, 0x24, 0x1d } \ } // // Protocol Member Functions // /** Returns a requested ACPI table. @param This A pointer to the EFI_ACPI_SUPPORT_PROTOCOL instance. @param Index The zero-based index of the table to retrieve. @param Table The pointer for returning the table buffer. @param Version Updated with the ACPI versions to which this table belongs. @param Handle The pointer for identifying the table. @retval EFI_SUCCESS The function completed successfully. @retval EFI_NOT_FOUND The requested index is too large and a table was not found. **/ typedef EFI_STATUS (EFIAPI *EFI_ACPI_GET_ACPI_TABLE)( IN EFI_ACPI_SUPPORT_PROTOCOL *This, IN INTN Index, OUT VOID **Table, OUT EFI_ACPI_TABLE_VERSION *Version, OUT UINTN *Handle ); /** Used to add, remove, or update ACPI tables. @param This A pointer to the EFI_ACPI_SUPPORT_PROTOCOL instance. @param Table The pointer to the new table to add or update. @param Checksum If TRUE, indicates that the checksum should be calculated for this table. @param Version Indicates to which version(s) of ACPI the table should be added. @param Handle The pointer to the handle of the table to remove or update. @retval EFI_SUCCESS The function completed successfully. @retval EFI_INVALID_PARAMETER *Handle was zero and Table was NULL. @retval EFI_ABORTED Could not complete the desired action. **/ typedef EFI_STATUS (EFIAPI *EFI_ACPI_SET_ACPI_TABLE)( IN EFI_ACPI_SUPPORT_PROTOCOL *This, IN VOID *Table OPTIONAL, IN BOOLEAN Checksum, IN EFI_ACPI_TABLE_VERSION Version, IN OUT UINTN *Handle ); /** Causes one or more versions of the ACPI tables to be published in the EFI system configuration tables. The PublishTables() function installs the ACPI tables for the versions that are specified in Version. No tables are published for Version equal to EFI_ACPI_VERSION_NONE. Once published, tables will continue to be updated as tables are modified with EFI_ACPI_SUPPORT_PROTOCOL.SetAcpiTable(). @param This A pointer to the EFI_ACPI_SUPPORT_PROTOCOL instance. @param Version Indicates to which version(s) of ACPI the table should be published. @retval EFI_SUCCESS The function completed successfully. @retval EFI_ABORTED An error occurred and the function could not complete successfully. **/ typedef EFI_STATUS (EFIAPI *EFI_ACPI_PUBLISH_TABLES)( IN EFI_ACPI_SUPPORT_PROTOCOL *This, IN EFI_ACPI_TABLE_VERSION Version ); // // ACPI Support Protocol // /** This protocol provides some basic services to support publishing ACPI system tables. The services handle many of the more mundane tasks that are required to publish a set of tables. **/ struct _EFI_ACPI_SUPPORT_PROTOCOL { /// /// Returns a table specified by an index if it exists. /// EFI_ACPI_GET_ACPI_TABLE GetAcpiTable; /// /// Adds, removes, or updates ACPI tables. /// EFI_ACPI_SET_ACPI_TABLE SetAcpiTable; /// /// Publishes the ACPI tables. /// EFI_ACPI_PUBLISH_TABLES PublishTables; }; // // Extern the GUID for protocol users. // extern EFI_GUID gEfiAcpiSupportProtocolGuid; #endif
2b8ae003f61bceba988c5ce90bde9dbc2c160105
321d11eaee885ceb3a74db0a062f9bbdf282148c
/crypto/uid.c
e26c27c6749b2e716c2750606df2a66adbb742fc
[ "Apache-2.0", "OpenSSL", "LicenseRef-scancode-proprietary-license" ]
permissive
openssl/openssl
75691ebaae957793f2ff0673f77545277dfb3988
5318c012885a5382eadbf95aa9c1d35664bca819
refs/heads/master
2023-09-03T15:22:52.727123
2023-09-01T07:10:49
2023-09-02T14:30:01
7,634,677
24,148
11,569
Apache-2.0
2023-09-14T19:48:11
2013-01-15T22:34:48
C
UTF-8
C
false
false
1,388
c
uid.c
/* * Copyright 2001-2021 The OpenSSL Project Authors. All Rights Reserved. * * Licensed under the Apache License 2.0 (the "License"). You may not use * this file except in compliance with the License. You can obtain a copy * in the file LICENSE in the source distribution or at * https://www.openssl.org/source/license.html */ #include <openssl/crypto.h> #include <openssl/opensslconf.h> #if defined(OPENSSL_SYS_WIN32) || defined(OPENSSL_SYS_VXWORKS) || defined(OPENSSL_SYS_UEFI) || defined(__wasi__) int OPENSSL_issetugid(void) { return 0; } #elif defined(__OpenBSD__) || (defined(__FreeBSD__) && __FreeBSD__ > 2) || defined(__DragonFly__) || (defined(__GLIBC__) && defined(__FreeBSD_kernel__)) # include <unistd.h> int OPENSSL_issetugid(void) { return issetugid(); } #else # include <unistd.h> # include <sys/types.h> # if defined(__GLIBC__) && defined(__GLIBC_PREREQ) # if __GLIBC_PREREQ(2, 16) # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # elif defined(__ANDROID_API__) /* see https://developer.android.google.cn/ndk/guides/cpu-features */ # if __ANDROID_API__ >= 18 # include <sys/auxv.h> # define OSSL_IMPLEMENT_GETAUXVAL # endif # endif int OPENSSL_issetugid(void) { # ifdef OSSL_IMPLEMENT_GETAUXVAL return getauxval(AT_SECURE) != 0; # else return getuid() != geteuid() || getgid() != getegid(); # endif } #endif
3a376c8a1677b4138aa297cd444a11ab1cfeaac7
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/drivers/message/fusion/lsi/mpi_type.h
888b26dbc41345dd08fd461c13b80b96f8dd7a52
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
2,234
h
mpi_type.h
/* * Copyright (c) 2000-2008 LSI Corporation. * * * Name: mpi_type.h * Title: MPI Basic type definitions * Creation Date: June 6, 2000 * * mpi_type.h Version: 01.05.02 * * Version History * --------------- * * Date Version Description * -------- -------- ------------------------------------------------------ * 05-08-00 00.10.01 Original release for 0.10 spec dated 4/26/2000. * 06-06-00 01.00.01 Update version number for 1.0 release. * 11-02-00 01.01.01 Original release for post 1.0 work * 02-20-01 01.01.02 Added define and ifdef for MPI_POINTER. * 08-08-01 01.02.01 Original release for v1.2 work. * 05-11-04 01.03.01 Original release for MPI v1.3. * 08-19-04 01.05.01 Original release for MPI v1.5. * -------------------------------------------------------------------------- */ #ifndef MPI_TYPE_H #define MPI_TYPE_H /******************************************************************************* * Define MPI_POINTER if it hasn't already been defined. By default MPI_POINTER * is defined to be a near pointer. MPI_POINTER can be defined as a far pointer * by defining MPI_POINTER as "far *" before this header file is included. */ #ifndef MPI_POINTER #define MPI_POINTER * #endif /***************************************************************************** * * B a s i c T y p e s * *****************************************************************************/ typedef signed char S8; typedef unsigned char U8; typedef signed short S16; typedef unsigned short U16; typedef int32_t S32; typedef u_int32_t U32; typedef struct _S64 { U32 Low; S32 High; } S64; typedef struct _U64 { U32 Low; U32 High; } U64; /****************************************************************************/ /* Pointers */ /****************************************************************************/ typedef S8 *PS8; typedef U8 *PU8; typedef S16 *PS16; typedef U16 *PU16; typedef S32 *PS32; typedef U32 *PU32; typedef S64 *PS64; typedef U64 *PU64; #endif
5f483ec929061159fbdb89a678c3de139d7ee973
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/lib/mesa/src/freedreno/decode/crashdec-mempool.c
98404ffb8b4ff744e0a9b047b2c5d73541171985
[]
no_license
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
11,554
c
crashdec-mempool.c
/* * Copyright © 2020 Valve Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include "crashdec.h" static void dump_mem_pool_reg_write(unsigned reg, uint32_t data, unsigned context, bool pipe) { if (pipe) { struct rnndecaddrinfo *info = rnn_reginfo(rnn_pipe, reg); printf("\t\twrite %s (%02x) pipe\n", info->name, reg); if (!strcmp(info->typeinfo->name, "void")) { /* registers that ignore their payload */ } else { printf("\t\t\t"); dump_register(rnn_pipe, reg, data); } } else { printf("\t\twrite %s (%05x) context %d\n", regname(reg, 1), reg, context); dump_register_val(reg, data, 2); } } static void dump_mem_pool_chunk(const uint32_t *chunk) { struct __attribute__((packed)) { bool reg0_enabled : 1; bool reg1_enabled : 1; uint32_t data0 : 32; uint32_t data1 : 32; uint32_t reg0 : 18; uint32_t reg1 : 18; bool reg0_pipe : 1; bool reg1_pipe : 1; uint32_t reg0_context : 1; uint32_t reg1_context : 1; uint32_t padding : 22; } fields; memcpy(&fields, chunk, 4 * sizeof(uint32_t)); if (fields.reg0_enabled) { dump_mem_pool_reg_write(fields.reg0, fields.data0, fields.reg0_context, fields.reg0_pipe); } if (fields.reg1_enabled) { dump_mem_pool_reg_write(fields.reg1, fields.data1, fields.reg1_context, fields.reg1_pipe); } } void dump_cp_mem_pool(uint32_t *mempool) { /* The mem pool is a shared pool of memory used for storing in-flight * register writes. There are 6 different queues, one for each * cluster. Writing to $data (or for some special registers, $addr) * pushes data onto the appropriate queue, and each queue is pulled * from by the appropriate cluster. The queues are thus written to * in-order, but may be read out-of-order. * * The queues are conceptually divided into 128-bit "chunks", and the * read and write pointers are in units of chunks. These chunks are * organized internally into 8-chunk "blocks", and memory is allocated * dynamically in terms of blocks. Each queue is represented as a * singly-linked list of blocks, as well as 3-bit start/end chunk * pointers that point within the first/last block. The next pointers * are located in a separate array, rather than inline. */ /* TODO: The firmware CP_MEM_POOL save/restore routines do something * like: * * cread $02, [ $00 + 0 ] * and $02, $02, 0x118 * ... * brne $02, 0, #label * mov $03, 0x2000 * mov $03, 0x1000 * label: * ... * * I think that control register 0 is the GPU version, and some * versions have a smaller mem pool. It seems some models have a mem * pool that's half the size, and a bunch of offsets are shifted * accordingly. Unfortunately the kernel driver's dumping code doesn't * seem to take this into account, even the downstream android driver, * and we don't know which versions 0x8, 0x10, or 0x100 correspond * to. Or maybe we can use CP_DBG_MEM_POOL_SIZE to figure this out? */ bool small_mem_pool = false; /* The array of next pointers for each block. */ const uint32_t *next_pointers = small_mem_pool ? &mempool[0x800] : &mempool[0x1000]; /* Maximum number of blocks in the pool, also the size of the pointers * array. */ const int num_blocks = small_mem_pool ? 0x30 : 0x80; /* Number of queues */ const unsigned num_queues = 6; /* Unfortunately the per-queue state is a little more complicated than * a simple pair of begin/end pointers. Instead of a single beginning * block, there are *two*, with the property that either the two are * equal or the second is the "next" of the first. Similarly there are * two end blocks. Thus the queue either looks like this: * * A -> B -> ... -> C -> D * * Or like this, or some combination: * * A/B -> ... -> C/D * * However, there's only one beginning/end chunk offset. Now the * question is, which of A or B is the actual start? I.e. is the chunk * offset an offset inside A or B? It depends. I'll show a typical read * cycle, starting here (read pointer marked with a *) with a chunk * offset of 0: * * A B * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * |_|_|_|_|_|_|_|_| -> |*|_|_|_|_|_|_|_| -> |_|_|_|_|_|_|_|_| * * Once the pointer advances far enough, the hardware decides to free * A, after which the read-side state looks like: * * (free) A/B * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * |_|_|_|_|_|_|_|_| |_|_|_|*|_|_|_|_| -> |_|_|_|_|_|_|_|_| * * Then after advancing the pointer a bit more, the hardware fetches * the "next" pointer for A and stores it in B: * * (free) A B * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|*| -> |_|_|_|_|_|_|_|_| * * Then the read pointer advances into B, at which point we've come * back to the first state having advanced a whole block: * * (free) A B * _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ * |_|_|_|_|_|_|_|_| |_|_|_|_|_|_|_|_| -> |*|_|_|_|_|_|_|_| * * * There is a similar cycle for the write pointer. Now, the question * is, how do we know which state we're in? We need to know this to * know whether the pointer (*) is in A or B if they're different. It * seems like there should be some bit somewhere describing this, but * after lots of experimentation I've come up empty-handed. For now we * assume that if the pointer is in the first half, then we're in * either the first or second state and use B, and otherwise we're in * the second or third state and use A. So far I haven't seen anything * that violates this assumption. */ struct { uint32_t unk0; uint32_t padding0[7]; /* Mirrors of unk0 */ struct { uint32_t chunk : 3; uint32_t first_block : 32 - 3; } writer[6]; uint32_t padding1[2]; /* Mirrors of writer[4], writer[5] */ uint32_t unk1; uint32_t padding2[7]; /* Mirrors of unk1 */ uint32_t writer_second_block[6]; uint32_t padding3[2]; uint32_t unk2[6]; uint32_t padding4[2]; struct { uint32_t chunk : 3; uint32_t first_block : 32 - 3; } reader[6]; uint32_t padding5[2]; /* Mirrors of reader[4], reader[5] */ uint32_t unk3; uint32_t padding6[7]; /* Mirrors of unk3 */ uint32_t reader_second_block[6]; uint32_t padding7[2]; uint32_t block_count[6]; uint32_t padding[2]; uint32_t unk4; uint32_t padding9[7]; /* Mirrors of unk4 */ } data1; const uint32_t *data1_ptr = small_mem_pool ? &mempool[0xc00] : &mempool[0x1800]; memcpy(&data1, data1_ptr, sizeof(data1)); /* Based on the kernel, the first dword is the mem pool size (in * blocks?) and mirrors CP_MEM_POOL_DBG_SIZE. */ const uint32_t *data2_ptr = small_mem_pool ? &mempool[0x1000] : &mempool[0x2000]; const int data2_size = 0x60; /* This seems to be the size of each queue in chunks. */ const uint32_t *queue_sizes = &data2_ptr[0x18]; printf("\tdata2:\n"); dump_hex_ascii(data2_ptr, 4 * data2_size, 1); /* These seem to be some kind of counter of allocated/deallocated blocks */ if (verbose) { printf("\tunk0: %x\n", data1.unk0); printf("\tunk1: %x\n", data1.unk1); printf("\tunk3: %x\n", data1.unk3); printf("\tunk4: %x\n\n", data1.unk4); } for (int queue = 0; queue < num_queues; queue++) { const char *cluster_names[6] = {"FE", "SP_VS", "PC_VS", "GRAS", "SP_PS", "PS"}; printf("\tCLUSTER_%s:\n\n", cluster_names[queue]); if (verbose) { printf("\t\twriter_first_block: 0x%x\n", data1.writer[queue].first_block); printf("\t\twriter_second_block: 0x%x\n", data1.writer_second_block[queue]); printf("\t\twriter_chunk: %d\n", data1.writer[queue].chunk); printf("\t\treader_first_block: 0x%x\n", data1.reader[queue].first_block); printf("\t\treader_second_block: 0x%x\n", data1.reader_second_block[queue]); printf("\t\treader_chunk: %d\n", data1.reader[queue].chunk); printf("\t\tblock_count: %d\n", data1.block_count[queue]); printf("\t\tunk2: 0x%x\n", data1.unk2[queue]); printf("\t\tqueue_size: %d\n\n", queue_sizes[queue]); } uint32_t cur_chunk = data1.reader[queue].chunk; uint32_t cur_block = cur_chunk > 3 ? data1.reader[queue].first_block : data1.reader_second_block[queue]; uint32_t last_chunk = data1.writer[queue].chunk; uint32_t last_block = last_chunk > 3 ? data1.writer[queue].first_block : data1.writer_second_block[queue]; if (verbose) printf("\tblock %x\n", cur_block); if (cur_block >= num_blocks) { fprintf(stderr, "block %x too large\n", cur_block); exit(1); } unsigned calculated_queue_size = 0; while (cur_block != last_block || cur_chunk != last_chunk) { calculated_queue_size++; uint32_t *chunk_ptr = &mempool[cur_block * 0x20 + cur_chunk * 4]; dump_mem_pool_chunk(chunk_ptr); printf("\t%05x: %08x %08x %08x %08x\n", 4 * (cur_block * 0x20 + cur_chunk + 4), chunk_ptr[0], chunk_ptr[1], chunk_ptr[2], chunk_ptr[3]); cur_chunk++; if (cur_chunk == 8) { cur_block = next_pointers[cur_block]; if (verbose) printf("\tblock %x\n", cur_block); if (cur_block >= num_blocks) { fprintf(stderr, "block %x too large\n", cur_block); exit(1); } cur_chunk = 0; } } if (calculated_queue_size != queue_sizes[queue]) { printf("\t\tCALCULATED SIZE %d DOES NOT MATCH!\n", calculated_queue_size); } printf("\n"); } }
6871131800ab9b26d4451d1980fa83e8e7592c47
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/third_party/ctags/vstring.c
d4ffbf2559772fa99b6e381553da5d143080e85b
[ "GPL-2.0-only", "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
4,958
c
vstring.c
// clang-format off /* * $Id: vstring.c 558 2007-06-15 19:17:02Z elliotth $ * * Copyright (c) 1998-2002, Darren Hiebert * * This source code is released for free distribution under the terms of the * GNU General Public License. * * This module contains functions supporting resizeable strings. */ /* * INCLUDE FILES */ #include "third_party/ctags/general.h" /* must always come first */ #include "libc/limits.h" #include "libc/sysv/consts/_posix.h" #include "libc/sysv/consts/iov.h" #include "libc/sysv/consts/limits.h" #include "libc/sysv/consts/xopen.h" #include "libc/thread/thread.h" /* to define INT_MAX */ #include "libc/mem/alg.h" #include "libc/str/str.h" #include "libc/str/str.h" #include "third_party/ctags/debug.h" #include "third_party/ctags/routines.h" #include "third_party/ctags/vstring.h" /* * DATA DEFINITIONS */ static const size_t vStringInitialSize = 32; /* * FUNCTION DEFINITIONS */ static void vStringResize (vString *const string, const size_t newSize) { char *const newBuffer = xRealloc (string->buffer, newSize, char); string->size = newSize; string->buffer = newBuffer; } /* * External interface */ extern boolean vStringAutoResize (vString *const string) { boolean ok = TRUE; if (string->size <= INT_MAX / 2) { const size_t newSize = string->size * 2; vStringResize (string, newSize); } return ok; } extern void vStringClear (vString *const string) { string->length = 0; string->buffer [0] = '\0'; DebugStatement ( memset (string->buffer, 0, string->size); ) } extern void vStringDelete (vString *const string) { if (string != NULL) { if (string->buffer != NULL) eFree (string->buffer); eFree (string); } } extern vString *vStringNew (void) { vString *const string = xMalloc (1, vString); string->length = 0; string->size = vStringInitialSize; string->buffer = xMalloc (string->size, char); vStringClear (string); return string; } #ifndef VSTRING_PUTC_MACRO extern void vStringPut (vString *const string, const int c) { if (string->length + 1 == string->size) /* check for buffer overflow */ vStringAutoResize (string); string->buffer [string->length] = c; if (c != '\0') string->buffer [++string->length] = '\0'; } #endif extern void vStringCatS (vString *const string, const char *const s) { #if 1 const size_t len = strlen (s); while (string->length + len + 1 >= string->size)/* check for buffer overflow */ vStringAutoResize (string); strcpy (string->buffer + string->length, s); string->length += len; #else const char *p = s; do vStringPut (string, *p); while (*p++ != '\0'); #endif } extern vString *vStringNewCopy (const vString *const string) { vString *vs = vStringNew (); vStringCatS (vs, string->buffer); return vs; } extern vString *vStringNewInit (const char *const s) { vString *vs = vStringNew (); vStringCatS (vs, s); return vs; } extern void vStringNCatS ( vString *const string, const char *const s, const size_t length) { const char *p = s; size_t remain = length; while (*p != '\0' && remain > 0) { vStringPut (string, *p); --remain; ++p; } vStringTerminate (string); } /* Strip trailing newline from string. */ extern void vStringStripNewline (vString *const string) { const size_t final = string->length - 1; if (string->buffer [final] == '\n') { string->buffer [final] = '\0'; string->length--; } } /* Strip leading white space from string. */ extern void vStringStripLeading (vString *const string) { while (isspace ((int) string->buffer [0]) && string->length > 0) { size_t i; for (i = 1 ; i < string->length ; ++i) string->buffer [i - 1] = string->buffer [i]; --string->length; string->buffer [string->length] = '\0'; } } /* Strip trailing white space from string. */ extern void vStringStripTrailing (vString *const string) { while (isspace ((int) string->buffer [string->length - 1]) && string->length > 0) { string->length--; string->buffer [string->length] = '\0'; } } /* Chop last character from string. */ extern void vStringChop (vString *const string) { if (string->length > 0) { --string->length; string->buffer [string->length] = '\0'; } } extern void vStringCopyS (vString *const string, const char *const s) { vStringClear (string); vStringCatS (string, s); } extern void vStringNCopyS ( vString *const string, const char *const s, const size_t length) { vStringClear (string); vStringNCatS (string, s, length); } extern void vStringCopyToLower (vString *const dest, const vString *const src) { const size_t length = src->length; const char *s = src->buffer; char *d; size_t i; if (dest->size < src->size) vStringResize (dest, src->size); d = dest->buffer; for (i = 0 ; i < length ; ++i) { int c = s [i]; d [i] = tolower (c); } d [i] = '\0'; } extern void vStringSetLength (vString *const string) { string->length = strlen (string->buffer); } /* vi:set tabstop=4 shiftwidth=4: */
0a27f97f3a01ba7bee79e410a09cf30648e69f12
5eff7a36d9a9917dce9111f0c3074375fe6f7656
/lib/mesa/src/intel/vulkan/anv_bo_sync.c
149ae2c2ba2d399b3b0e8ff7fbb163c548739e97
[]
no_license
openbsd/xenocara
cb392d02ebba06f6ff7d826fd8a89aa3b8401779
a012b5de33ea0b977095d77316a521195b26cc6b
refs/heads/master
2023-08-25T12:16:58.862008
2023-08-12T16:16:25
2023-08-12T16:16:25
66,967,384
177
66
null
2023-07-22T18:12:37
2016-08-30T18:36:01
C
UTF-8
C
false
false
8,331
c
anv_bo_sync.c
/* * Copyright © 2021 Intel Corporation * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice (including the next * paragraph) shall be included in all copies or substantial portions of the * Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS * IN THE SOFTWARE. */ #include "anv_private.h" #include "util/os_time.h" static struct anv_bo_sync * to_anv_bo_sync(struct vk_sync *sync) { assert(sync->type == &anv_bo_sync_type); return container_of(sync, struct anv_bo_sync, sync); } static VkResult anv_bo_sync_init(struct vk_device *vk_device, struct vk_sync *vk_sync, uint64_t initial_value) { struct anv_device *device = container_of(vk_device, struct anv_device, vk); struct anv_bo_sync *sync = to_anv_bo_sync(vk_sync); sync->state = initial_value ? ANV_BO_SYNC_STATE_SIGNALED : ANV_BO_SYNC_STATE_RESET; return anv_device_alloc_bo(device, "bo-sync", 4096, ANV_BO_ALLOC_EXTERNAL | ANV_BO_ALLOC_IMPLICIT_SYNC, 0 /* explicit_address */, &sync->bo); } static void anv_bo_sync_finish(struct vk_device *vk_device, struct vk_sync *vk_sync) { struct anv_device *device = container_of(vk_device, struct anv_device, vk); struct anv_bo_sync *sync = to_anv_bo_sync(vk_sync); anv_device_release_bo(device, sync->bo); } static VkResult anv_bo_sync_reset(struct vk_device *vk_device, struct vk_sync *vk_sync) { struct anv_bo_sync *sync = to_anv_bo_sync(vk_sync); sync->state = ANV_BO_SYNC_STATE_RESET; return VK_SUCCESS; } static int64_t anv_get_relative_timeout(uint64_t abs_timeout) { uint64_t now = os_time_get_nano(); /* We don't want negative timeouts. * * DRM_IOCTL_I915_GEM_WAIT uses a signed 64 bit timeout and is * supposed to block indefinitely timeouts < 0. Unfortunately, * this was broken for a couple of kernel releases. Since there's * no way to know whether or not the kernel we're using is one of * the broken ones, the best we can do is to clamp the timeout to * INT64_MAX. This limits the maximum timeout from 584 years to * 292 years - likely not a big deal. */ if (abs_timeout < now) return 0; uint64_t rel_timeout = abs_timeout - now; if (rel_timeout > (uint64_t) INT64_MAX) rel_timeout = INT64_MAX; return rel_timeout; } static VkResult anv_bo_sync_wait(struct vk_device *vk_device, uint32_t wait_count, const struct vk_sync_wait *waits, enum vk_sync_wait_flags wait_flags, uint64_t abs_timeout_ns) { struct anv_device *device = container_of(vk_device, struct anv_device, vk); VkResult result; uint32_t pending = wait_count; while (pending) { pending = 0; bool signaled = false; for (uint32_t i = 0; i < wait_count; i++) { struct anv_bo_sync *sync = to_anv_bo_sync(waits[i].sync); switch (sync->state) { case ANV_BO_SYNC_STATE_RESET: /* This fence hasn't been submitted yet, we'll catch it the next * time around. Yes, this may mean we dead-loop but, short of * lots of locking and a condition variable, there's not much that * we can do about that. */ assert(!(wait_flags & VK_SYNC_WAIT_PENDING)); pending++; continue; case ANV_BO_SYNC_STATE_SIGNALED: /* This fence is not pending. If waitAll isn't set, we can return * early. Otherwise, we have to keep going. */ if (wait_flags & VK_SYNC_WAIT_ANY) return VK_SUCCESS; continue; case ANV_BO_SYNC_STATE_SUBMITTED: /* These are the fences we really care about. Go ahead and wait * on it until we hit a timeout. */ if (!(wait_flags & VK_SYNC_WAIT_PENDING)) { uint64_t rel_timeout = anv_get_relative_timeout(abs_timeout_ns); result = anv_device_wait(device, sync->bo, rel_timeout); /* This also covers VK_TIMEOUT */ if (result != VK_SUCCESS) return result; sync->state = ANV_BO_SYNC_STATE_SIGNALED; signaled = true; } if (wait_flags & VK_SYNC_WAIT_ANY) return VK_SUCCESS; break; default: unreachable("Invalid BO sync state"); } } if (pending && !signaled) { /* If we've hit this then someone decided to vkWaitForFences before * they've actually submitted any of them to a queue. This is a * fairly pessimal case, so it's ok to lock here and use a standard * pthreads condition variable. */ pthread_mutex_lock(&device->mutex); /* It's possible that some of the fences have changed state since the * last time we checked. Now that we have the lock, check for * pending fences again and don't wait if it's changed. */ uint32_t now_pending = 0; for (uint32_t i = 0; i < wait_count; i++) { struct anv_bo_sync *sync = to_anv_bo_sync(waits[i].sync); if (sync->state == ANV_BO_SYNC_STATE_RESET) now_pending++; } assert(now_pending <= pending); if (now_pending == pending) { struct timespec abstime = { .tv_sec = abs_timeout_ns / NSEC_PER_SEC, .tv_nsec = abs_timeout_ns % NSEC_PER_SEC, }; ASSERTED int ret; ret = pthread_cond_timedwait(&device->queue_submit, &device->mutex, &abstime); assert(ret != EINVAL); if (os_time_get_nano() >= abs_timeout_ns) { pthread_mutex_unlock(&device->mutex); return VK_TIMEOUT; } } pthread_mutex_unlock(&device->mutex); } } return VK_SUCCESS; } const struct vk_sync_type anv_bo_sync_type = { .size = sizeof(struct anv_bo_sync), .features = VK_SYNC_FEATURE_BINARY | VK_SYNC_FEATURE_GPU_WAIT | VK_SYNC_FEATURE_GPU_MULTI_WAIT | VK_SYNC_FEATURE_CPU_WAIT | VK_SYNC_FEATURE_CPU_RESET | VK_SYNC_FEATURE_WAIT_ANY | VK_SYNC_FEATURE_WAIT_PENDING, .init = anv_bo_sync_init, .finish = anv_bo_sync_finish, .reset = anv_bo_sync_reset, .wait_many = anv_bo_sync_wait, }; VkResult anv_create_sync_for_memory(struct vk_device *device, VkDeviceMemory memory, bool signal_memory, struct vk_sync **sync_out) { ANV_FROM_HANDLE(anv_device_memory, mem, memory); struct anv_bo_sync *bo_sync; bo_sync = vk_zalloc(&device->alloc, sizeof(*bo_sync), 8, VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); if (bo_sync == NULL) return vk_error(device, VK_ERROR_OUT_OF_HOST_MEMORY); bo_sync->sync.type = &anv_bo_sync_type; bo_sync->state = signal_memory ? ANV_BO_SYNC_STATE_RESET : ANV_BO_SYNC_STATE_SUBMITTED; bo_sync->bo = anv_bo_ref(mem->bo); *sync_out = &bo_sync->sync; return VK_SUCCESS; }
52f07f03d5aed29379491df3dab7a7201a7d9656
120324bbbf63c54de0b7f1ca48d5dcbbc5cfb193
/lib/libterminal/libtsm/src/tsm_screen.c
1813ed1192cc380f96fb48a726ce221d29c3985f
[ "MIT", "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "HPND-Markus-Kuhn", "LGPL-2.1-or-later", "LGPL-2.1-only" ]
permissive
evilbinary/scheme-lib
a6d42c7c4f37e684c123bff574816544132cb957
690352c118748413f9730838b001a03be9a6f18e
refs/heads/master
2022-06-22T06:16:56.203827
2022-06-16T05:54:54
2022-06-16T05:54:54
76,329,726
609
71
MIT
2022-06-16T05:54:55
2016-12-13T06:27:36
Scheme
UTF-8
C
false
false
33,839
c
tsm_screen.c
/* * libtsm - Screen Management * * Copyright (c) 2011-2013 David Herrmann <dh.herrmann@gmail.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. */ /* * Screen Management * This provides the abstracted screen management. It does not do any * terminal-emulation, instead it provides a resizable table of cells. You can * insert, remove and modify the cells freely. * A screen has always a fixed, but changeable, width and height. This defines * the number of columns and rows. The screen doesn't care for pixels, glyphs or * framebuffers. The screen only contains information about each cell. * * Screens are the logical model behind a real screen of a terminal emulator. * Users usually allocate a screen for each terminal-emulator they run. All they * have to do is render the screen onto their widget on each change and forward * any widget-events to the screen. * * The screen object already includes scrollback-buffers, selection support and * more. This simplifies terminal emulators a lot, but also prevents them from * accessing the real screen data. However, terminal emulators should have no * reason to access the data directly. The screen API should provide everything * they need. * * AGEING: * Each cell, line and screen has an "age" field. This field describes when it * was changed the last time. After drawing a screen, the current screen age is * returned. This allows users to skip drawing specific cells, if their * framebuffer was already drawn with a newer age than a given cell. * However, the screen-age might overflow. This is properly detected and causes * drawing functions to return "0" as age. Users must reset all their * framebuffer ages then. Otherwise, further drawing operations might * incorrectly skip cells. * Furthermore, if a cell has age "0", it means it _has_ to be drawn. No ageing * information is available. */ #include <errno.h> #include <inttypes.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include "libtsm.h" #include "libtsm_int.h" #include "shl_llog.h" #define LLOG_SUBSYSTEM "tsm_screen" static struct cell *get_cursor_cell(struct tsm_screen *con) { unsigned int cur_x, cur_y; cur_x = con->cursor_x; if (cur_x >= con->size_x) cur_x = con->size_x - 1; cur_y = con->cursor_y; if (cur_y >= con->size_y) cur_y = con->size_y - 1; return &con->lines[cur_y]->cells[cur_x]; } static void move_cursor(struct tsm_screen *con, unsigned int x, unsigned int y) { struct cell *c; /* if cursor is hidden, just move it */ if (con->flags & TSM_SCREEN_HIDE_CURSOR) { con->cursor_x = x; con->cursor_y = y; return; } /* If cursor is visible, we have to mark the current and the new cell * as changed by resetting their age. We skip it if the cursor-position * didn't actually change. */ if (con->cursor_x == x && con->cursor_y == y) return; c = get_cursor_cell(con); c->age = con->age_cnt; con->cursor_x = x; con->cursor_y = y; c = get_cursor_cell(con); c->age = con->age_cnt; } void screen_cell_init(struct tsm_screen *con, struct cell *cell) { cell->ch = 0; cell->width = 1; cell->age = con->age_cnt; memcpy(&cell->attr, &con->def_attr, sizeof(cell->attr)); } static int line_new(struct tsm_screen *con, struct line **out, unsigned int width) { struct line *line; unsigned int i; if (!width) return -EINVAL; line = malloc(sizeof(*line)); if (!line) return -ENOMEM; line->next = NULL; line->prev = NULL; line->size = width; line->age = con->age_cnt; line->cells = malloc(sizeof(struct cell) * width); if (!line->cells) { free(line); return -ENOMEM; } for (i = 0; i < width; ++i) screen_cell_init(con, &line->cells[i]); *out = line; return 0; } static void line_free(struct line *line) { free(line->cells); free(line); } static int line_resize(struct tsm_screen *con, struct line *line, unsigned int width) { struct cell *tmp; if (!line || !width) return -EINVAL; if (line->size < width) { tmp = realloc(line->cells, width * sizeof(struct cell)); if (!tmp) return -ENOMEM; line->cells = tmp; while (line->size < width) { screen_cell_init(con, &line->cells[line->size]); ++line->size; } } return 0; } /* This links the given line into the scrollback-buffer */ static void link_to_scrollback(struct tsm_screen *con, struct line *line) { struct line *tmp; /* TODO: more sophisticated ageing */ con->age = con->age_cnt; if (con->sb_max == 0) { if (con->sel_active) { if (con->sel_start.line == line) { con->sel_start.line = NULL; con->sel_start.y = SELECTION_TOP; } if (con->sel_end.line == line) { con->sel_end.line = NULL; con->sel_end.y = SELECTION_TOP; } } line_free(line); return; } /* Remove a line from the scrollback buffer if it reaches its maximum. * We must take care to correctly keep the current position as the new * line is linked in after we remove the top-most line here. * sb_max == 0 is tested earlier so we can assume sb_max > 0 here. In * other words, buf->sb_first is a valid line if sb_count >= sb_max. */ if (con->sb_count >= con->sb_max) { tmp = con->sb_first; con->sb_first = tmp->next; if (tmp->next) tmp->next->prev = NULL; else con->sb_last = NULL; --con->sb_count; /* (position == tmp && !next) means we have sb_max=1 so set * position to the new line. Otherwise, set to new first line. * If position!=tmp and we have a fixed-position then nothing * needs to be done because we can stay at the same line. If we * have no fixed-position, we need to set the position to the * next inserted line, which can be "line", too. */ if (con->sb_pos) { if (con->sb_pos == tmp || !(con->flags & TSM_SCREEN_FIXED_POS)) { if (con->sb_pos->next) con->sb_pos = con->sb_pos->next; else con->sb_pos = line; } } if (con->sel_active) { if (con->sel_start.line == tmp) { con->sel_start.line = NULL; con->sel_start.y = SELECTION_TOP; } if (con->sel_end.line == tmp) { con->sel_end.line = NULL; con->sel_end.y = SELECTION_TOP; } } line_free(tmp); } line->sb_id = ++con->sb_last_id; line->next = NULL; line->prev = con->sb_last; if (con->sb_last) con->sb_last->next = line; else con->sb_first = line; con->sb_last = line; ++con->sb_count; } static void screen_scroll_up(struct tsm_screen *con, unsigned int num) { unsigned int i, j, max, pos; int ret; if (!num) return; /* TODO: more sophisticated ageing */ con->age = con->age_cnt; max = con->margin_bottom + 1 - con->margin_top; if (num > max) num = max; /* We cache lines on the stack to speed up the scrolling. However, if * num is too big we might get overflows here so use recursion if num * exceeds a hard-coded limit. * 128 seems to be a sane limit that should never be reached but should * also be small enough so we do not get stack overflows. */ if (num > 128) { screen_scroll_up(con, 128); return screen_scroll_up(con, num - 128); } struct line *cache[num]; for (i = 0; i < num; ++i) { pos = con->margin_top + i; if (!(con->flags & TSM_SCREEN_ALTERNATE)) ret = line_new(con, &cache[i], con->size_x); else ret = -EAGAIN; if (!ret) { link_to_scrollback(con, con->lines[pos]); } else { cache[i] = con->lines[pos]; for (j = 0; j < con->size_x; ++j) screen_cell_init(con, &cache[i]->cells[j]); } } if (num < max) { memmove(&con->lines[con->margin_top], &con->lines[con->margin_top + num], (max - num) * sizeof(struct line*)); } memcpy(&con->lines[con->margin_top + (max - num)], cache, num * sizeof(struct line*)); if (con->sel_active) { if (!con->sel_start.line && con->sel_start.y >= 0) { con->sel_start.y -= num; if (con->sel_start.y < 0) { con->sel_start.line = con->sb_last; while (con->sel_start.line && ++con->sel_start.y < 0) con->sel_start.line = con->sel_start.line->prev; con->sel_start.y = SELECTION_TOP; } } if (!con->sel_end.line && con->sel_end.y >= 0) { con->sel_end.y -= num; if (con->sel_end.y < 0) { con->sel_end.line = con->sb_last; while (con->sel_end.line && ++con->sel_end.y < 0) con->sel_end.line = con->sel_end.line->prev; con->sel_end.y = SELECTION_TOP; } } } } static void screen_scroll_down(struct tsm_screen *con, unsigned int num) { unsigned int i, j, max; if (!num) return; /* TODO: more sophisticated ageing */ con->age = con->age_cnt; max = con->margin_bottom + 1 - con->margin_top; if (num > max) num = max; /* see screen_scroll_up() for an explanation */ if (num > 128) { screen_scroll_down(con, 128); return screen_scroll_down(con, num - 128); } struct line *cache[num]; for (i = 0; i < num; ++i) { cache[i] = con->lines[con->margin_bottom - i]; for (j = 0; j < con->size_x; ++j) screen_cell_init(con, &cache[i]->cells[j]); } if (num < max) { memmove(&con->lines[con->margin_top + num], &con->lines[con->margin_top], (max - num) * sizeof(struct line*)); } memcpy(&con->lines[con->margin_top], cache, num * sizeof(struct line*)); if (con->sel_active) { if (!con->sel_start.line && con->sel_start.y >= 0) con->sel_start.y += num; if (!con->sel_end.line && con->sel_end.y >= 0) con->sel_end.y += num; } } static void screen_write(struct tsm_screen *con, unsigned int x, unsigned int y, tsm_symbol_t ch, unsigned int len, const struct tsm_screen_attr *attr) { struct line *line; unsigned int i; if (!len) return; if (x >= con->size_x || y >= con->size_y) { llog_warning(con, "writing beyond buffer boundary"); return; } line = con->lines[y]; if ((con->flags & TSM_SCREEN_INSERT_MODE) && (int)x < ((int)con->size_x - len)) { line->age = con->age_cnt; memmove(&line->cells[x + len], &line->cells[x], sizeof(struct cell) * (con->size_x - len - x)); } line->cells[x].age = con->age_cnt; line->cells[x].ch = ch; line->cells[x].width = len; memcpy(&line->cells[x].attr, attr, sizeof(*attr)); for (i = 1; i < len && i + x < con->size_x; ++i) { line->cells[x + i].age = con->age_cnt; line->cells[x + i].width = 0; } } static void screen_erase_region(struct tsm_screen *con, unsigned int x_from, unsigned int y_from, unsigned int x_to, unsigned int y_to, bool protect) { unsigned int to; struct line *line; /* TODO: more sophisticated ageing */ con->age = con->age_cnt; if (y_to >= con->size_y) y_to = con->size_y - 1; if (x_to >= con->size_x) x_to = con->size_x - 1; for ( ; y_from <= y_to; ++y_from) { line = con->lines[y_from]; if (!line) { x_from = 0; continue; } if (y_from == y_to) to = x_to; else to = con->size_x - 1; for ( ; x_from <= to; ++x_from) { if (protect && line->cells[x_from].attr.protect) continue; screen_cell_init(con, &line->cells[x_from]); } x_from = 0; } } static inline unsigned int to_abs_x(struct tsm_screen *con, unsigned int x) { return x; } static inline unsigned int to_abs_y(struct tsm_screen *con, unsigned int y) { if (!(con->flags & TSM_SCREEN_REL_ORIGIN)) return y; return con->margin_top + y; } SHL_EXPORT int tsm_screen_new(struct tsm_screen **out, tsm_log_t log, void *log_data) { struct tsm_screen *con; int ret; unsigned int i; if (!out) return -EINVAL; con = malloc(sizeof(*con)); if (!con) return -ENOMEM; memset(con, 0, sizeof(*con)); con->ref = 1; con->llog = log; con->llog_data = log_data; con->age_cnt = 1; con->age = con->age_cnt; con->def_attr.fr = 255; con->def_attr.fg = 255; con->def_attr.fb = 255; ret = tsm_symbol_table_new(&con->sym_table); if (ret) goto err_free; ret = tsm_screen_resize(con, 80, 24); if (ret) goto err_free; llog_debug(con, "new screen"); *out = con; return 0; err_free: for (i = 0; i < con->line_num; ++i) { line_free(con->main_lines[i]); line_free(con->alt_lines[i]); } free(con->main_lines); free(con->alt_lines); free(con->tab_ruler); tsm_symbol_table_unref(con->sym_table); free(con); return ret; } SHL_EXPORT void tsm_screen_ref(struct tsm_screen *con) { if (!con) return; ++con->ref; } SHL_EXPORT void tsm_screen_unref(struct tsm_screen *con) { unsigned int i; if (!con || !con->ref || --con->ref) return; llog_debug(con, "destroying screen"); for (i = 0; i < con->line_num; ++i) { line_free(con->main_lines[i]); line_free(con->alt_lines[i]); } free(con->main_lines); free(con->alt_lines); free(con->tab_ruler); tsm_symbol_table_unref(con->sym_table); free(con); } void tsm_screen_set_opts(struct tsm_screen *scr, unsigned int opts) { if (!scr || !opts) return; scr->opts |= opts; } void tsm_screen_reset_opts(struct tsm_screen *scr, unsigned int opts) { if (!scr || !opts) return; scr->opts &= ~opts; } unsigned int tsm_screen_get_opts(struct tsm_screen *scr) { if (!scr) return 0; return scr->opts; } SHL_EXPORT unsigned int tsm_screen_get_width(struct tsm_screen *con) { if (!con) return 0; return con->size_x; } SHL_EXPORT unsigned int tsm_screen_get_height(struct tsm_screen *con) { if (!con) return 0; return con->size_y; } SHL_EXPORT int tsm_screen_resize(struct tsm_screen *con, unsigned int x, unsigned int y) { struct line **cache; unsigned int i, j, width, diff, start; int ret; bool *tab_ruler; if (!con || !x || !y) return -EINVAL; if (con->size_x == x && con->size_y == y) return 0; /* First make sure the line buffer is big enough for our new screen. * That is, allocate all new lines and make sure each line has enough * cells to hold the new screen or the current screen. If we fail, we * can safely return -ENOMEM and the buffer is still valid. We must * allocate the new lines to at least the same size as the current * lines. Otherwise, if this function fails in later turns, we will have * invalid lines in the buffer. */ if (y > con->line_num) { /* resize main buffer */ cache = realloc(con->main_lines, sizeof(struct line*) * y); if (!cache) return -ENOMEM; if (con->lines == con->main_lines) con->lines = cache; con->main_lines = cache; /* resize alt buffer */ cache = realloc(con->alt_lines, sizeof(struct line*) * y); if (!cache) return -ENOMEM; if (con->lines == con->alt_lines) con->lines = cache; con->alt_lines = cache; /* allocate new lines */ if (x > con->size_x) width = x; else width = con->size_x; while (con->line_num < y) { ret = line_new(con, &con->main_lines[con->line_num], width); if (ret) return ret; ret = line_new(con, &con->alt_lines[con->line_num], width); if (ret) { line_free(con->main_lines[con->line_num]); return ret; } ++con->line_num; } } /* Resize all lines in the buffer if we increase screen width. This * will guarantee that all lines are big enough so we can resize the * buffer without reallocating them later. */ if (x > con->size_x) { tab_ruler = realloc(con->tab_ruler, sizeof(bool) * x); if (!tab_ruler) return -ENOMEM; con->tab_ruler = tab_ruler; for (i = 0; i < con->line_num; ++i) { ret = line_resize(con, con->main_lines[i], x); if (ret) return ret; ret = line_resize(con, con->alt_lines[i], x); if (ret) return ret; } } screen_inc_age(con); /* clear expansion/padding area */ start = x; if (x > con->size_x) start = con->size_x; for (j = 0; j < con->line_num; ++j) { /* main-lines may go into SB, so clear all cells */ i = 0; if (j < con->size_y) i = start; for ( ; i < con->main_lines[j]->size; ++i) screen_cell_init(con, &con->main_lines[j]->cells[i]); /* alt-lines never go into SB, only clear visible cells */ i = 0; if (j < con->size_y) i = con->size_x; for ( ; i < x; ++i) screen_cell_init(con, &con->alt_lines[j]->cells[i]); } /* xterm destroys margins on resize, so do we */ con->margin_top = 0; con->margin_bottom = con->size_y - 1; /* reset tabs */ for (i = 0; i < x; ++i) { if (i % 8 == 0) con->tab_ruler[i] = true; else con->tab_ruler[i] = false; } /* We need to adjust x-size first as screen_scroll_up() and friends may * have to reallocate lines. The y-size is adjusted after them to avoid * missing lines when shrinking y-size. * We need to carefully look for the functions that we call here as they * have stronger invariants as when called normally. */ con->size_x = x; if (con->cursor_x >= con->size_x) move_cursor(con, con->size_x - 1, con->cursor_y); /* scroll buffer if screen height shrinks */ if (y < con->size_y) { diff = con->size_y - y; screen_scroll_up(con, diff); if (con->cursor_y > diff) move_cursor(con, con->cursor_x, con->cursor_y - diff); else move_cursor(con, con->cursor_x, 0); } con->size_y = y; con->margin_bottom = con->size_y - 1; if (con->cursor_y >= con->size_y) move_cursor(con, con->cursor_x, con->size_y - 1); return 0; } SHL_EXPORT int tsm_screen_set_margins(struct tsm_screen *con, unsigned int top, unsigned int bottom) { unsigned int upper, lower; if (!con) return -EINVAL; if (!top) top = 1; if (bottom <= top) { upper = 0; lower = con->size_y - 1; } else if (bottom > con->size_y) { upper = 0; lower = con->size_y - 1; } else { upper = top - 1; lower = bottom - 1; } con->margin_top = upper; con->margin_bottom = lower; return 0; } /* set maximum scrollback buffer size */ SHL_EXPORT void tsm_screen_set_max_sb(struct tsm_screen *con, unsigned int max) { struct line *line; if (!con) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; while (con->sb_count > max) { line = con->sb_first; con->sb_first = line->next; if (line->next) line->next->prev = NULL; else con->sb_last = NULL; con->sb_count--; /* We treat fixed/unfixed position the same here because we * remove lines from the TOP of the scrollback buffer. */ if (con->sb_pos == line) con->sb_pos = con->sb_first; if (con->sel_active) { if (con->sel_start.line == line) { con->sel_start.line = NULL; con->sel_start.y = SELECTION_TOP; } if (con->sel_end.line == line) { con->sel_end.line = NULL; con->sel_end.y = SELECTION_TOP; } } line_free(line); } con->sb_max = max; } /* clear scrollback buffer */ SHL_EXPORT void tsm_screen_clear_sb(struct tsm_screen *con) { struct line *iter, *tmp; if (!con) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; for (iter = con->sb_first; iter; ) { tmp = iter; iter = iter->next; line_free(tmp); } con->sb_first = NULL; con->sb_last = NULL; con->sb_count = 0; con->sb_pos = NULL; if (con->sel_active) { if (con->sel_start.line) { con->sel_start.line = NULL; con->sel_start.y = SELECTION_TOP; } if (con->sel_end.line) { con->sel_end.line = NULL; con->sel_end.y = SELECTION_TOP; } } } SHL_EXPORT void tsm_screen_sb_up(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; while (num--) { if (con->sb_pos) { if (!con->sb_pos->prev) return; con->sb_pos = con->sb_pos->prev; } else if (!con->sb_last) { return; } else { con->sb_pos = con->sb_last; } } } SHL_EXPORT void tsm_screen_sb_down(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; while (num--) { if (con->sb_pos) con->sb_pos = con->sb_pos->next; else return; } } SHL_EXPORT void tsm_screen_sb_page_up(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); tsm_screen_sb_up(con, num * con->size_y); } SHL_EXPORT void tsm_screen_sb_page_down(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); tsm_screen_sb_down(con, num * con->size_y); } SHL_EXPORT void tsm_screen_sb_reset(struct tsm_screen *con) { if (!con) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; con->sb_pos = NULL; } SHL_EXPORT void tsm_screen_set_def_attr(struct tsm_screen *con, const struct tsm_screen_attr *attr) { if (!con || !attr) return; memcpy(&con->def_attr, attr, sizeof(*attr)); } SHL_EXPORT void tsm_screen_reset(struct tsm_screen *con) { unsigned int i; if (!con) return; screen_inc_age(con); con->age = con->age_cnt; con->flags = 0; con->margin_top = 0; con->margin_bottom = con->size_y - 1; con->lines = con->main_lines; for (i = 0; i < con->size_x; ++i) { if (i % 8 == 0) con->tab_ruler[i] = true; else con->tab_ruler[i] = false; } } SHL_EXPORT void tsm_screen_set_flags(struct tsm_screen *con, unsigned int flags) { unsigned int old; struct cell *c; if (!con || !flags) return; screen_inc_age(con); old = con->flags; con->flags |= flags; if (!(old & TSM_SCREEN_ALTERNATE) && (flags & TSM_SCREEN_ALTERNATE)) { con->age = con->age_cnt; con->lines = con->alt_lines; } if (!(old & TSM_SCREEN_HIDE_CURSOR) && (flags & TSM_SCREEN_HIDE_CURSOR)) { c = get_cursor_cell(con); c->age = con->age_cnt; } if (!(old & TSM_SCREEN_INVERSE) && (flags & TSM_SCREEN_INVERSE)) con->age = con->age_cnt; } SHL_EXPORT void tsm_screen_reset_flags(struct tsm_screen *con, unsigned int flags) { unsigned int old; struct cell *c; if (!con || !flags) return; screen_inc_age(con); old = con->flags; con->flags &= ~flags; if ((old & TSM_SCREEN_ALTERNATE) && (flags & TSM_SCREEN_ALTERNATE)) { con->age = con->age_cnt; con->lines = con->main_lines; } if ((old & TSM_SCREEN_HIDE_CURSOR) && (flags & TSM_SCREEN_HIDE_CURSOR)) { c = get_cursor_cell(con); c->age = con->age_cnt; } if ((old & TSM_SCREEN_INVERSE) && (flags & TSM_SCREEN_INVERSE)) con->age = con->age_cnt; } SHL_EXPORT unsigned int tsm_screen_get_flags(struct tsm_screen *con) { if (!con) return 0; return con->flags; } SHL_EXPORT unsigned int tsm_screen_get_cursor_x(struct tsm_screen *con) { if (!con) return 0; return con->cursor_x; } SHL_EXPORT unsigned int tsm_screen_get_cursor_y(struct tsm_screen *con) { if (!con) return 0; return con->cursor_y; } SHL_EXPORT void tsm_screen_set_tabstop(struct tsm_screen *con) { if (!con || con->cursor_x >= con->size_x) return; con->tab_ruler[con->cursor_x] = true; } SHL_EXPORT void tsm_screen_reset_tabstop(struct tsm_screen *con) { if (!con || con->cursor_x >= con->size_x) return; con->tab_ruler[con->cursor_x] = false; } SHL_EXPORT void tsm_screen_reset_all_tabstops(struct tsm_screen *con) { unsigned int i; if (!con) return; for (i = 0; i < con->size_x; ++i) con->tab_ruler[i] = false; } SHL_EXPORT void tsm_screen_write(struct tsm_screen *con, tsm_symbol_t ch, const struct tsm_screen_attr *attr) { unsigned int last, len; if (!con) return; len = tsm_symbol_get_width(con->sym_table, ch); if (!len) return; screen_inc_age(con); if (con->cursor_y <= con->margin_bottom || con->cursor_y >= con->size_y) last = con->margin_bottom; else last = con->size_y - 1; if (con->cursor_x >= con->size_x) { if (con->flags & TSM_SCREEN_AUTO_WRAP) move_cursor(con, 0, con->cursor_y + 1); else move_cursor(con, con->size_x - 1, con->cursor_y); } if (con->cursor_y > last) { move_cursor(con, con->cursor_x, last); screen_scroll_up(con, 1); } screen_write(con, con->cursor_x, con->cursor_y, ch, len, attr); move_cursor(con, con->cursor_x + len, con->cursor_y); } SHL_EXPORT void tsm_screen_newline(struct tsm_screen *con) { if (!con) return; screen_inc_age(con); tsm_screen_move_down(con, 1, true); tsm_screen_move_line_home(con); } SHL_EXPORT void tsm_screen_scroll_up(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); screen_scroll_up(con, num); } SHL_EXPORT void tsm_screen_scroll_down(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); screen_scroll_down(con, num); } SHL_EXPORT void tsm_screen_move_to(struct tsm_screen *con, unsigned int x, unsigned int y) { unsigned int last; if (!con) return; screen_inc_age(con); if (con->flags & TSM_SCREEN_REL_ORIGIN) last = con->margin_bottom; else last = con->size_y - 1; x = to_abs_x(con, x); if (x >= con->size_x) x = con->size_x - 1; y = to_abs_y(con, y); if (y > last) y = last; move_cursor(con, x, y); } SHL_EXPORT void tsm_screen_move_up(struct tsm_screen *con, unsigned int num, bool scroll) { unsigned int diff, size; if (!con || !num) return; screen_inc_age(con); if (con->cursor_y >= con->margin_top) size = con->margin_top; else size = 0; diff = con->cursor_y - size; if (num > diff) { num -= diff; if (scroll) screen_scroll_down(con, num); move_cursor(con, con->cursor_x, size); } else { move_cursor(con, con->cursor_x, con->cursor_y - num); } } SHL_EXPORT void tsm_screen_move_down(struct tsm_screen *con, unsigned int num, bool scroll) { unsigned int diff, size; if (!con || !num) return; screen_inc_age(con); if (con->cursor_y <= con->margin_bottom) size = con->margin_bottom + 1; else size = con->size_y; diff = size - con->cursor_y - 1; if (num > diff) { num -= diff; if (scroll) screen_scroll_up(con, num); move_cursor(con, con->cursor_x, size - 1); } else { move_cursor(con, con->cursor_x, con->cursor_y + num); } } SHL_EXPORT void tsm_screen_move_left(struct tsm_screen *con, unsigned int num) { unsigned int x; if (!con || !num) return; screen_inc_age(con); if (num > con->size_x) num = con->size_x; x = con->cursor_x; if (x >= con->size_x) x = con->size_x - 1; if (num > x) move_cursor(con, 0, con->cursor_y); else move_cursor(con, x - num, con->cursor_y); } SHL_EXPORT void tsm_screen_move_right(struct tsm_screen *con, unsigned int num) { if (!con || !num) return; screen_inc_age(con); if (num > con->size_x) num = con->size_x; if (num + con->cursor_x >= con->size_x) move_cursor(con, con->size_x - 1, con->cursor_y); else move_cursor(con, con->cursor_x + num, con->cursor_y); } SHL_EXPORT void tsm_screen_move_line_end(struct tsm_screen *con) { if (!con) return; screen_inc_age(con); move_cursor(con, con->size_x - 1, con->cursor_y); } SHL_EXPORT void tsm_screen_move_line_home(struct tsm_screen *con) { if (!con) return; screen_inc_age(con); move_cursor(con, 0, con->cursor_y); } SHL_EXPORT void tsm_screen_tab_right(struct tsm_screen *con, unsigned int num) { unsigned int i, j, x; if (!con || !num) return; screen_inc_age(con); x = con->cursor_x; for (i = 0; i < num; ++i) { for (j = x + 1; j < con->size_x; ++j) { if (con->tab_ruler[j]) break; } x = j; if (x + 1 >= con->size_x) break; } /* tabs never cause pending new-lines */ if (x >= con->size_x) x = con->size_x - 1; move_cursor(con, x, con->cursor_y); } SHL_EXPORT void tsm_screen_tab_left(struct tsm_screen *con, unsigned int num) { unsigned int i, x; int j; if (!con || !num) return; screen_inc_age(con); x = con->cursor_x; for (i = 0; i < num; ++i) { for (j = x - 1; j > 0; --j) { if (con->tab_ruler[j]) break; } if (j <= 0) { x = 0; break; } x = j; } move_cursor(con, x, con->cursor_y); } SHL_EXPORT void tsm_screen_insert_lines(struct tsm_screen *con, unsigned int num) { unsigned int i, j, max; if (!con || !num) return; if (con->cursor_y < con->margin_top || con->cursor_y > con->margin_bottom) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; max = con->margin_bottom - con->cursor_y + 1; if (num > max) num = max; struct line *cache[num]; for (i = 0; i < num; ++i) { cache[i] = con->lines[con->margin_bottom - i]; for (j = 0; j < con->size_x; ++j) screen_cell_init(con, &cache[i]->cells[j]); } if (num < max) { memmove(&con->lines[con->cursor_y + num], &con->lines[con->cursor_y], (max - num) * sizeof(struct line*)); memcpy(&con->lines[con->cursor_y], cache, num * sizeof(struct line*)); } con->cursor_x = 0; } SHL_EXPORT void tsm_screen_delete_lines(struct tsm_screen *con, unsigned int num) { unsigned int i, j, max; if (!con || !num) return; if (con->cursor_y < con->margin_top || con->cursor_y > con->margin_bottom) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; max = con->margin_bottom - con->cursor_y + 1; if (num > max) num = max; struct line *cache[num]; for (i = 0; i < num; ++i) { cache[i] = con->lines[con->cursor_y + i]; for (j = 0; j < con->size_x; ++j) screen_cell_init(con, &cache[i]->cells[j]); } if (num < max) { memmove(&con->lines[con->cursor_y], &con->lines[con->cursor_y + num], (max - num) * sizeof(struct line*)); memcpy(&con->lines[con->cursor_y + (max - num)], cache, num * sizeof(struct line*)); } con->cursor_x = 0; } SHL_EXPORT void tsm_screen_insert_chars(struct tsm_screen *con, unsigned int num) { struct cell *cells; unsigned int max, mv, i; if (!con || !num || !con->size_y || !con->size_x) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; if (con->cursor_x >= con->size_x) con->cursor_x = con->size_x - 1; if (con->cursor_y >= con->size_y) con->cursor_y = con->size_y - 1; max = con->size_x - con->cursor_x; if (num > max) num = max; mv = max - num; cells = con->lines[con->cursor_y]->cells; if (mv) memmove(&cells[con->cursor_x + num], &cells[con->cursor_x], mv * sizeof(*cells)); for (i = 0; i < num; ++i) screen_cell_init(con, &cells[con->cursor_x + i]); } SHL_EXPORT void tsm_screen_delete_chars(struct tsm_screen *con, unsigned int num) { struct cell *cells; unsigned int max, mv, i; if (!con || !num || !con->size_y || !con->size_x) return; screen_inc_age(con); /* TODO: more sophisticated ageing */ con->age = con->age_cnt; if (con->cursor_x >= con->size_x) con->cursor_x = con->size_x - 1; if (con->cursor_y >= con->size_y) con->cursor_y = con->size_y - 1; max = con->size_x - con->cursor_x; if (num > max) num = max; mv = max - num; cells = con->lines[con->cursor_y]->cells; if (mv) memmove(&cells[con->cursor_x], &cells[con->cursor_x + num], mv * sizeof(*cells)); for (i = 0; i < num; ++i) screen_cell_init(con, &cells[con->cursor_x + mv + i]); } SHL_EXPORT void tsm_screen_erase_cursor(struct tsm_screen *con) { unsigned int x; if (!con) return; screen_inc_age(con); if (con->cursor_x >= con->size_x) x = con->size_x - 1; else x = con->cursor_x; screen_erase_region(con, x, con->cursor_y, x, con->cursor_y, false); } SHL_EXPORT void tsm_screen_erase_chars(struct tsm_screen *con, unsigned int num) { unsigned int x; if (!con || !num) return; screen_inc_age(con); if (con->cursor_x >= con->size_x) x = con->size_x - 1; else x = con->cursor_x; screen_erase_region(con, x, con->cursor_y, x + num - 1, con->cursor_y, false); } SHL_EXPORT void tsm_screen_erase_cursor_to_end(struct tsm_screen *con, bool protect) { unsigned int x; if (!con) return; screen_inc_age(con); if (con->cursor_x >= con->size_x) x = con->size_x - 1; else x = con->cursor_x; screen_erase_region(con, x, con->cursor_y, con->size_x - 1, con->cursor_y, protect); } SHL_EXPORT void tsm_screen_erase_home_to_cursor(struct tsm_screen *con, bool protect) { if (!con) return; screen_inc_age(con); screen_erase_region(con, 0, con->cursor_y, con->cursor_x, con->cursor_y, protect); } SHL_EXPORT void tsm_screen_erase_current_line(struct tsm_screen *con, bool protect) { if (!con) return; screen_inc_age(con); screen_erase_region(con, 0, con->cursor_y, con->size_x - 1, con->cursor_y, protect); } SHL_EXPORT void tsm_screen_erase_screen_to_cursor(struct tsm_screen *con, bool protect) { if (!con) return; screen_inc_age(con); screen_erase_region(con, 0, 0, con->cursor_x, con->cursor_y, protect); } SHL_EXPORT void tsm_screen_erase_cursor_to_screen(struct tsm_screen *con, bool protect) { unsigned int x; if (!con) return; screen_inc_age(con); if (con->cursor_x >= con->size_x) x = con->size_x - 1; else x = con->cursor_x; screen_erase_region(con, x, con->cursor_y, con->size_x - 1, con->size_y - 1, protect); } SHL_EXPORT void tsm_screen_erase_screen(struct tsm_screen *con, bool protect) { if (!con) return; screen_inc_age(con); screen_erase_region(con, 0, 0, con->size_x - 1, con->size_y - 1, protect); }
02d2086104ab3e063792c8465ab15b5776871a67
69db0de8c61c7cba691193edd3f087fdb54351c2
/include/region_map.h
fec528e1bb7219b7ccc235ee2251a57ff5d1c343
[]
no_license
pret/pokefirered
5363c332321c7650d4c85be6aa2e8baf3acda162
f8741615bfa0123e38680f30103f217c269ec96a
refs/heads/master
2023-08-31T15:22:19.498797
2023-08-31T15:15:29
2023-08-31T15:15:29
115,841,713
847
709
null
2023-09-12T22:48:38
2017-12-31T04:07:51
C
UTF-8
C
false
false
463
h
region_map.h
#ifndef GUARD_REGION_MAP_H #define GUARD_REGION_MAP_H #include "global.h" #include "bg.h" enum { REGIONMAP_TYPE_NORMAL, REGIONMAP_TYPE_WALL, REGIONMAP_TYPE_FLY, REGIONMAP_TYPE_COUNT }; u8 *GetMapName(u8 *dest, u16 mapsec, u16 fill); u8 *GetMapNameGeneric(u8 *dest, u16 mapsec); u8 *GetMapNameGeneric_(u8 *dest, u16 mapsec); void InitRegionMapWithExitCB(u8 type, void (*callback)(void)); void CB2_OpenFlyMap(void); #endif // GUARD_REGION_MAP_H
4ca9af3e84e1733485eed3e722b85751ff947ca5
9907672fcd81ab73ac63b2a83422a82bf31eadde
/atcoder/tyama_atcoderkupc2012I_easy.c
03bbb87d27a3ad8969cfe3c59d5f63afe7c10db9
[ "0BSD" ]
permissive
cielavenir/procon
bbe1974b9bddb51b76d58722a0686a5b477c4456
746e1a91f574f20647e8aaaac0d9e6173f741176
refs/heads/master
2023-06-21T23:11:24.562546
2023-06-11T13:15:15
2023-06-11T13:15:15
7,557,464
137
136
null
2020-10-20T09:35:52
2013-01-11T09:40:26
C++
UTF-8
C
false
false
904
c
tyama_atcoderkupc2012I_easy.c
#include <stdio.h> #include <math.h> main(){ double w,h,theta1,theta2,theta3,z; int e; scanf("%lf%lf%d",&w,&h,&e); if(e>0)exit(1); printf("? %.12f %.12f\n",-w,-h);fflush(stdout); scanf("%lf",&theta1); if(theta1<1e-9){ printf("? %.12f %.12f\n",-w,h);fflush(stdout); scanf("%lf",&theta1);theta1=-theta1; theta1*=M_PI/180; printf("? %.12f %.12f\n",w,h);fflush(stdout); scanf("%lf",&theta2);theta2=-theta2;theta2=180-theta2; theta2*=M_PI/180; theta3=M_PI-theta1-theta2; z=sin(theta2)*2*w/sin(theta3); printf("! %.12f %.12f\n",z*cos(theta1)-w,-z*sin(theta1)+h); }else{ theta1*=M_PI/180; printf("? %.12f %.12f\n",w,-h);fflush(stdout); scanf("%lf",&theta2);theta2=180-theta2; theta2*=M_PI/180; theta3=M_PI-theta1-theta2; z=sin(theta2)*2*w/sin(theta3); //(-w,-h)からtheta1(rad)、斜辺の長さz printf("! %.12f %.12f\n",z*cos(theta1)-w,z*sin(theta1)-h); } exit(0); }
c0903762a4e4a7cc379ef486e08f090c43d5c972
e1cddfd754d952134e72dfd03522c5ea4fb6008e
/src/vnet/udp/udp_input.c
33ee2cddefd5a6c3face028f9074b7cb363b25cc
[ "Apache-2.0" ]
permissive
FDio/vpp
0ad30fa1bec2975ffa6b66b45c9f4f32163123b6
f234b0d4626d7e686422cc9dfd25958584f4931e
refs/heads/master
2023-08-31T16:09:04.068646
2022-03-14T09:49:15
2023-08-31T09:50:00
96,556,718
1,048
630
Apache-2.0
2023-06-21T05:39:17
2017-07-07T16:29:40
C
UTF-8
C
false
false
10,769
c
udp_input.c
/* * Copyright (c) 2016-2019 Cisco and/or its affiliates. * 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 <vlibmemory/api.h> #include <vlib/vlib.h> #include <vppinfra/hash.h> #include <vppinfra/error.h> #include <vppinfra/elog.h> #include <vnet/vnet.h> #include <vnet/ip/ip.h> #include <vnet/udp/udp.h> #include <vnet/udp/udp_packet.h> #include <vnet/session/session.h> static vlib_error_desc_t udp_error_counters[] = { #define udp_error(f, n, s, d) { #n, d, VL_COUNTER_SEVERITY_##s }, #include "udp_error.def" #undef udp_error }; typedef struct { u32 connection; u32 disposition; u32 thread_index; } udp_input_trace_t; /* packet trace format function */ static u8 * format_udp_input_trace (u8 * s, va_list * args) { CLIB_UNUSED (vlib_main_t * vm) = va_arg (*args, vlib_main_t *); CLIB_UNUSED (vlib_node_t * node) = va_arg (*args, vlib_node_t *); udp_input_trace_t *t = va_arg (*args, udp_input_trace_t *); s = format (s, "UDP_INPUT: connection %d, disposition %d, thread %d", t->connection, t->disposition, t->thread_index); return s; } #define foreach_udp_input_next \ _ (DROP, "error-drop") typedef enum { #define _(s, n) UDP_INPUT_NEXT_##s, foreach_udp_input_next #undef _ UDP_INPUT_N_NEXT, } udp_input_next_t; always_inline void udp_input_inc_counter (vlib_main_t * vm, u8 is_ip4, u8 evt, u8 val) { if (is_ip4) vlib_node_increment_counter (vm, udp4_input_node.index, evt, val); else vlib_node_increment_counter (vm, udp6_input_node.index, evt, val); } #define udp_store_err_counters(vm, is_ip4, cnts) \ { \ int i; \ for (i = 0; i < UDP_N_ERROR; i++) \ if (cnts[i]) \ udp_input_inc_counter(vm, is_ip4, i, cnts[i]); \ } #define udp_inc_err_counter(cnts, err, val) \ { \ cnts[err] += val; \ } static void udp_trace_buffer (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_buffer_t * b, session_t * s, u16 error0) { udp_input_trace_t *t; if (PREDICT_TRUE (!(b->flags & VLIB_BUFFER_IS_TRACED))) return; t = vlib_add_trace (vm, node, b, sizeof (*t)); t->connection = s ? s->connection_index : ~0; t->disposition = error0; t->thread_index = s ? s->thread_index : vm->thread_index; } static udp_connection_t * udp_connection_accept (udp_connection_t * listener, session_dgram_hdr_t * hdr, u32 thread_index) { udp_connection_t *uc; uc = udp_connection_alloc (thread_index); ip_copy (&uc->c_lcl_ip, &hdr->lcl_ip, hdr->is_ip4); ip_copy (&uc->c_rmt_ip, &hdr->rmt_ip, hdr->is_ip4); uc->c_lcl_port = hdr->lcl_port; uc->c_rmt_port = hdr->rmt_port; uc->c_is_ip4 = hdr->is_ip4; uc->c_fib_index = listener->c_fib_index; uc->mss = listener->mss; uc->flags |= UDP_CONN_F_CONNECTED; uc->cfg_flags = listener->cfg_flags; if (session_dgram_accept (&uc->connection, listener->c_s_index, listener->c_thread_index)) { udp_connection_free (uc); return 0; } transport_share_local_endpoint (TRANSPORT_PROTO_UDP, &uc->c_lcl_ip, uc->c_lcl_port); return uc; } static void udp_connection_enqueue (udp_connection_t * uc0, session_t * s0, session_dgram_hdr_t * hdr0, u32 thread_index, vlib_buffer_t * b, u8 queue_event, u32 * error0) { int wrote0; if (!(uc0->flags & UDP_CONN_F_CONNECTED)) clib_spinlock_lock (&uc0->rx_lock); if (svm_fifo_max_enqueue_prod (s0->rx_fifo) < hdr0->data_length + sizeof (session_dgram_hdr_t)) { *error0 = UDP_ERROR_FIFO_FULL; goto unlock_rx_lock; } /* If session is owned by another thread and rx event needed, * enqueue event now while we still have the peeker lock */ if (s0->thread_index != thread_index) { wrote0 = session_enqueue_dgram_connection_cl ( s0, hdr0, b, TRANSPORT_PROTO_UDP, /* queue event */ queue_event && !svm_fifo_has_event (s0->rx_fifo)); } else { wrote0 = session_enqueue_dgram_connection (s0, hdr0, b, TRANSPORT_PROTO_UDP, queue_event); } /* In some rare cases, session_enqueue_dgram_connection can fail because a * chunk cannot be allocated in the RX FIFO */ if (PREDICT_FALSE (wrote0 == 0)) *error0 = UDP_ERROR_FIFO_NOMEM; unlock_rx_lock: if (!(uc0->flags & UDP_CONN_F_CONNECTED)) clib_spinlock_unlock (&uc0->rx_lock); } always_inline session_t * udp_parse_and_lookup_buffer (vlib_buffer_t * b, session_dgram_hdr_t * hdr, u8 is_ip4) { udp_header_t *udp; u32 fib_index; session_t *s; /* udp_local hands us a pointer to the udp data */ udp = (udp_header_t *) (vlib_buffer_get_current (b) - sizeof (*udp)); fib_index = vnet_buffer (b)->ip.fib_index; hdr->data_offset = 0; hdr->lcl_port = udp->dst_port; hdr->rmt_port = udp->src_port; hdr->is_ip4 = is_ip4; hdr->gso_size = 0; if (is_ip4) { ip4_header_t *ip4; /* TODO: must fix once udp_local does ip options correctly */ ip4 = (ip4_header_t *) (((u8 *) udp) - sizeof (*ip4)); ip_set (&hdr->lcl_ip, &ip4->dst_address, 1); ip_set (&hdr->rmt_ip, &ip4->src_address, 1); hdr->data_length = clib_net_to_host_u16 (ip4->length); hdr->data_length -= sizeof (ip4_header_t) + sizeof (udp_header_t); s = session_lookup_safe4 (fib_index, &ip4->dst_address, &ip4->src_address, udp->dst_port, udp->src_port, TRANSPORT_PROTO_UDP); } else { ip6_header_t *ip60; ip60 = (ip6_header_t *) (((u8 *) udp) - sizeof (*ip60)); ip_set (&hdr->lcl_ip, &ip60->dst_address, 0); ip_set (&hdr->rmt_ip, &ip60->src_address, 0); hdr->data_length = clib_net_to_host_u16 (ip60->payload_length); hdr->data_length -= sizeof (udp_header_t); s = session_lookup_safe6 (fib_index, &ip60->dst_address, &ip60->src_address, udp->dst_port, udp->src_port, TRANSPORT_PROTO_UDP); } if (PREDICT_TRUE (!(b->flags & VLIB_BUFFER_NEXT_PRESENT))) b->current_length = hdr->data_length; else b->total_length_not_including_first_buffer = hdr->data_length - b->current_length; return s; } always_inline uword udp46_input_inline (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame, u8 is_ip4) { u32 thread_index = vm->thread_index, n_left_from, *from, *first_buffer; vlib_buffer_t *bufs[VLIB_FRAME_SIZE], **b; u16 err_counters[UDP_N_ERROR] = { 0 }; from = first_buffer = vlib_frame_vector_args (frame); n_left_from = frame->n_vectors; vlib_get_buffers (vm, from, bufs, n_left_from); b = bufs; while (n_left_from > 0) { u32 error0 = UDP_ERROR_ENQUEUED; session_dgram_hdr_t hdr0; udp_connection_t *uc0; session_t *s0; s0 = udp_parse_and_lookup_buffer (b[0], &hdr0, is_ip4); if (PREDICT_FALSE (!s0)) { error0 = UDP_ERROR_NO_LISTENER; goto done; } if (s0->session_state == SESSION_STATE_OPENED) { u8 queue_event = 1; uc0 = udp_connection_from_transport (session_get_transport (s0)); uc0->sw_if_index = vnet_buffer (b[0])->sw_if_index[VLIB_RX]; if (uc0->flags & UDP_CONN_F_CONNECTED) { if (s0->thread_index != thread_index) { /* * Clone the transport. It will be cleaned up with the * session once we notify the session layer. */ uc0 = udp_connection_clone_safe (s0->connection_index, s0->thread_index); ASSERT (s0->session_index == uc0->c_s_index); /* * Ask session layer for a new session. */ session_dgram_connect_notify (&uc0->connection, s0->thread_index, &s0); queue_event = 0; } else s0->session_state = SESSION_STATE_READY; } udp_connection_enqueue (uc0, s0, &hdr0, thread_index, b[0], queue_event, &error0); } else if (s0->session_state == SESSION_STATE_READY) { uc0 = udp_connection_from_transport (session_get_transport (s0)); udp_connection_enqueue (uc0, s0, &hdr0, thread_index, b[0], 1, &error0); } else if (s0->session_state == SESSION_STATE_LISTENING) { uc0 = udp_connection_from_transport (session_get_transport (s0)); if (uc0->flags & UDP_CONN_F_CONNECTED) { uc0 = udp_connection_accept (uc0, &hdr0, thread_index); if (!uc0) { error0 = UDP_ERROR_CREATE_SESSION; goto done; } s0 = session_get (uc0->c_s_index, uc0->c_thread_index); uc0->sw_if_index = vnet_buffer (b[0])->sw_if_index[VLIB_RX]; error0 = UDP_ERROR_ACCEPT; } udp_connection_enqueue (uc0, s0, &hdr0, thread_index, b[0], 1, &error0); } else { error0 = UDP_ERROR_NOT_READY; } done: if (PREDICT_FALSE (node->flags & VLIB_NODE_FLAG_TRACE)) udp_trace_buffer (vm, node, b[0], s0, error0); b += 1; n_left_from -= 1; udp_inc_err_counter (err_counters, error0, 1); } vlib_buffer_free (vm, first_buffer, frame->n_vectors); session_main_flush_enqueue_events (TRANSPORT_PROTO_UDP, thread_index); udp_store_err_counters (vm, is_ip4, err_counters); return frame->n_vectors; } static uword udp4_input (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { return udp46_input_inline (vm, node, frame, 1); } /* *INDENT-OFF* */ VLIB_REGISTER_NODE (udp4_input_node) = { .function = udp4_input, .name = "udp4-input", .vector_size = sizeof (u32), .format_trace = format_udp_input_trace, .type = VLIB_NODE_TYPE_INTERNAL, .n_errors = UDP_N_ERROR, .error_counters = udp_error_counters, .n_next_nodes = UDP_INPUT_N_NEXT, .next_nodes = { #define _(s, n) [UDP_INPUT_NEXT_##s] = n, foreach_udp_input_next #undef _ }, }; /* *INDENT-ON* */ static uword udp6_input (vlib_main_t * vm, vlib_node_runtime_t * node, vlib_frame_t * frame) { return udp46_input_inline (vm, node, frame, 0); } /* *INDENT-OFF* */ VLIB_REGISTER_NODE (udp6_input_node) = { .function = udp6_input, .name = "udp6-input", .vector_size = sizeof (u32), .format_trace = format_udp_input_trace, .type = VLIB_NODE_TYPE_INTERNAL, .n_errors = UDP_N_ERROR, .error_counters = udp_error_counters, .n_next_nodes = UDP_INPUT_N_NEXT, .next_nodes = { #define _(s, n) [UDP_INPUT_NEXT_##s] = n, foreach_udp_input_next #undef _ }, }; /* *INDENT-ON* */ /* * fd.io coding-style-patch-verification: ON * * Local Variables: * eval: (c-set-style "gnu") * End: */
7422ecc5dc766c3b75728f1e34e2e2d2e6c435a9
581bdcc078d282e388f1b655d4cfc4e08152d117
/plugins/HardwareDevices/prpsh.h
b295ec175eb005470df7176f34552f967dff255f
[ "MIT", "BSD-3-Clause", "LGPL-2.0-or-later", "Zlib", "LGPL-2.1-or-later", "GPL-2.0-only", "LicenseRef-scancode-public-domain" ]
permissive
winsiderss/systeminformer
774928be871f0055263ac5e62ae0a598b098486b
5a6b442acd45d681f699a133d476a3211d072871
refs/heads/master
2023-08-28T15:43:41.074679
2023-08-27T20:59:20
2023-08-27T20:59:20
50,824,485
2,137
292
MIT
2023-09-10T22:35:12
2016-02-01T08:10:21
C
UTF-8
C
false
false
2,882
h
prpsh.h
/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex 2017 * */ // NOTE: Copied from processhacker2\ProcessHacker\procprp.h #ifndef PV_PRP_H #define PV_PRP_H #define PV_PROPCONTEXT_MAXPAGES 20 typedef struct _PV_PROPSHEETCONTEXT { BOOLEAN LayoutInitialized; WNDPROC DefaultWindowProc; PH_LAYOUT_MANAGER LayoutManager; PPH_LAYOUT_ITEM TabPageItem; WNDPROC OldOptionsButtonWndProc; HWND OptionsButtonWindowHandle; PWSTR PositionSettingName; PWSTR SizeSettingName; } PV_PROPSHEETCONTEXT, *PPV_PROPSHEETCONTEXT; typedef struct _PV_PROPCONTEXT { PROPSHEETHEADER PropSheetHeader; HPROPSHEETPAGE *PropSheetPages; BOOLEAN EnableControlButtons; PWSTR PositionSettingName; PWSTR SizeSettingName; } PV_PROPCONTEXT, *PPV_PROPCONTEXT; typedef struct _PV_PROPPAGECONTEXT { PPV_PROPCONTEXT PropContext; PVOID Context; PROPSHEETPAGE PropSheetPage; BOOLEAN LayoutInitialized; } PV_PROPPAGECONTEXT, *PPV_PROPPAGECONTEXT; PPV_PROPCONTEXT HdCreatePropContext( _In_ PWSTR Caption ); BOOLEAN PvAddPropPage( _Inout_ PPV_PROPCONTEXT PropContext, _In_ _Assume_refs_(1) PPV_PROPPAGECONTEXT PropPageContext ); BOOLEAN PvAddPropPage2( _Inout_ PPV_PROPCONTEXT PropContext, _In_ HPROPSHEETPAGE PropSheetPageHandle ); PPV_PROPPAGECONTEXT PvCreatePropPageContext( _In_ LPCWSTR Template, _In_ DLGPROC DlgProc, _In_opt_ PVOID Context ); PPV_PROPPAGECONTEXT PvCreatePropPageContextEx( _In_opt_ PVOID InstanceHandle, _In_ LPCWSTR Template, _In_ DLGPROC DlgProc, _In_opt_ PVOID Context ); #define PH_PROP_PAGE_TAB_CONTROL_PARENT ((PPH_LAYOUT_ITEM)0x1) PPH_LAYOUT_ITEM PvAddPropPageLayoutItem( _In_ HWND hwnd, _In_ HWND Handle, _In_ PPH_LAYOUT_ITEM ParentItem, _In_ ULONG Anchor ); PPH_LAYOUT_ITEM PvAddPropPageLayoutItemEx( _In_ HWND hwnd, _In_ HWND Handle, _In_ PPH_LAYOUT_ITEM ParentItem, _In_ ULONG Anchor, _In_ BOOLEAN EnableControlButtons, _In_opt_ PWSTR PositionSettingName, _In_opt_ PWSTR SizeSettingName ); VOID PvDoPropPageLayout( _In_ HWND hwnd ); _Success_(return) FORCEINLINE BOOLEAN PvPropPageDlgProcHeader( _In_ HWND hwndDlg, _In_ UINT uMsg, _In_ LPARAM lParam, _Out_ LPPROPSHEETPAGE *PropSheetPage, _Out_ PPV_PROPPAGECONTEXT *PropPageContext ) { LPPROPSHEETPAGE propSheetPage; if (uMsg == WM_INITDIALOG) { // Save the context. PhSetWindowContext(hwndDlg, ULONG_MAX, (HANDLE)lParam); } propSheetPage = PhGetWindowContext(hwndDlg, ULONG_MAX); if (!propSheetPage) return FALSE; *PropSheetPage = propSheetPage; *PropPageContext = (PPV_PROPPAGECONTEXT)propSheetPage->lParam; return TRUE; } #endif
3568b744164124e1e70ad5b80ca7f4db5f99648a
25e99a0af5751865bce1702ee85cc5c080b0715c
/ds_algo/src/零基礎學數據結構/例题代码/12/例12_2/例12_2.c
229c325c4a40dd17bd7baafbd0bc1bf9853449d9
[]
no_license
jasonblog/note
215837f6a08d07abe3e3d2be2e1f183e14aa4a30
4471f95736c60969a718d854cab929f06726280a
refs/heads/master
2023-05-31T13:02:27.451743
2022-04-04T11:28:06
2022-04-04T11:28:06
35,311,001
130
67
null
2023-02-10T21:26:36
2015-05-09T02:04:40
C
UTF-8
C
false
false
3,362
c
例12_2.c
/*包含头文件*/ #include<stdio.h> #include<stdlib.h> #define MaxSize 50 typedef int KeyType; typedef struct { /*数据元素类型定义*/ KeyType key;/*关键字*/ } DataType; typedef struct { /*顺序表类型定义*/ DataType data[MaxSize]; int length; } SqList; void InitSeqList(SqList* L, DataType a[], int n); void DispList(SqList L, int n); void AdjustHeap(SqList* H, int s, int m); void CreateHeap(SqList* H, int n); void HeapSort(SqList* H); void SelectSort(SqList* L, int n); void SelectSort(SqList* L, int n) /*简单选择排序*/ { int i, j, k; DataType t; /*将第i个元素的关键字与后面[i+1...n]个元素的关键字比较,将关键字最小的的元素放在第i个位置*/ for (i = 1; i <= n - 1; i++) { j = i; for (k = i + 1; k <= n; k++) /*关键字最小的元素的序号为j*/ if (L->data[k].key < L->data[j].key) { j = k; } if (j != i) { /*如果序号i不等于j,则需要将序号i和序号j的元素交换*/ t = L->data[i]; L->data[i] = L->data[j]; L->data[j] = t; } } } void CreateHeap(SqList* H, int n) /*建立大顶堆*/ { int i; for (i = n / 2; i >= 1; i--) { /*从序号n/2开始建立大顶堆*/ AdjustHeap(H, i, n); } } void AdjustHeap(SqList* H, int s, int m) /*调整H.data[s...m]的关键字,使其成为一个大顶堆*/ { DataType t; int j; t = (*H).data[s]; /*将根结点暂时保存在t中*/ for (j = 2 * s; j <= m; j *= 2) { if (j < m && (*H).data[j].key < (*H).data[j + 1].key) { /*沿关键字较大的孩子结点向下筛选*/ j++; /*j为关键字较大的结点的下标*/ } if (t.key > (*H).data[j].key) { /*如果孩子结点的值小于根结点的值,则不进行交换*/ break; } (*H).data[s] = (*H).data[j]; s = j; } (*H).data[s] = t; /*将根结点插入到正确位置*/ } void HeapSort(SqList* H) /*对顺序表H进行堆排序*/ { DataType t; int i; CreateHeap(H, H->length); /*创建堆*/ for (i = (*H).length; i > 1; i--) { /*将堆顶元素与最后一个元素交换,重新调整堆*/ t = (*H).data[1]; (*H).data[1] = (*H).data[i]; (*H).data[i] = t; AdjustHeap(H, 1, i - 1); /*将(*H).data[1..i-1]调整为大顶堆*/ } } void main() { DataType a[] = {56, 22, 67, 32, 59, 12, 89, 26, 48, 37}; int delta[] = {5, 3, 1}; int i, n = 10, m = 3; SqList L; /*简单选择排序*/ InitSeqList(&L, a, n); printf("排序前:"); DispList(L, n); SelectSort(&L, n); printf("简单选择排序结果:"); DispList(L, n); /*堆排序*/ InitSeqList(&L, a, n); printf("排序前:"); DispList(L, n); HeapSort(&L, n); printf("堆排序结果:"); DispList(L, n); } void InitSeqList(SqList* L, DataType a[], int n) /*顺序表的初始化*/ { int i; for (i = 1; i <= n; i++) { L->data[i] = a[i - 1]; } L->length = n; } void DispList(SqList L, int n) /*输出表中的元素*/ { int i; for (i = 1; i <= n; i++) { printf("%4d", L.data[i].key); } printf("\n"); }
3a368a131c5ca5d5eaf5e9e398ff3965a76f731c
7bf23792fa14360c8f28ae90b99d8245ddfdf25e
/common/sys/pic.h
6810c2211447453b829d34d2537d5c08f3850ae4
[ "BSD-2-Clause" ]
permissive
limine-bootloader/limine
8d75c386d6967ebc65d6712e005866cf0594c28d
541dbd265ca62a33eadbabc0934122affacbbd77
refs/heads/v5.x-branch
2023-09-02T16:57:46.624937
2023-08-30T03:33:29
2023-08-30T03:34:47
186,746,473
1,236
224
BSD-2-Clause
2023-09-13T15:23:03
2019-05-15T04:02:11
C
UTF-8
C
false
false
189
h
pic.h
#ifndef __SYS__PIC_H__ #define __SYS__PIC_H__ #include <stdbool.h> void pic_eoi(int irq); void pic_flush(void); void pic_set_mask(int line, bool status); void pic_mask_all(void); #endif
f58ccbab5fbb2dc86b1c958c29adb55b37cb3818
e814383d36a10839104efaa4df277996ab220fa3
/ompi/mca/hook/demo/hook_demo_component.c
919b57cf90270908766a6fa1236df1ac50770673
[ "mpich2", "BSD-3-Clause-Open-MPI" ]
permissive
open-mpi/ompi
a1d7483ae1d83dd8fd8ae3ee95e832e0a0ee04e3
1edfdb025c4450f694600083ad871cf06c8d45cd
refs/heads/main
2023-09-01T01:30:02.040705
2023-08-29T17:32:18
2023-08-29T17:32:18
24,107,001
2,008
973
NOASSERTION
2023-09-14T20:59:26
2014-09-16T16:08:30
C
UTF-8
C
false
false
3,513
c
hook_demo_component.c
/* * Copyright (c) 2017 IBM Corporation. All rights reserved. * $COPYRIGHT$ * * Additional copyrights may follow * * $HEADER$ */ #include "ompi_config.h" #include "hook_demo.h" static int ompi_hook_demo_component_open(void); static int ompi_hook_demo_component_close(void); static int ompi_hook_demo_component_register(void); /* * Public string showing the component version number */ const char *mca_hook_demo_component_version_string = "Open MPI 'demo' hook MCA component version " OMPI_VERSION; /* * Instantiate the public struct with all of our public information * and pointers to our public functions in it */ const ompi_hook_base_component_1_0_0_t mca_hook_demo_component = { /* First, the mca_component_t struct containing meta information * about the component itself */ .hookm_version = { OMPI_HOOK_BASE_VERSION_1_0_0, /* Component name and version */ .mca_component_name = "demo", MCA_BASE_MAKE_VERSION(component, OMPI_MAJOR_VERSION, OMPI_MINOR_VERSION, OMPI_RELEASE_VERSION), /* Component open and close functions */ .mca_open_component = ompi_hook_demo_component_open, .mca_close_component = ompi_hook_demo_component_close, .mca_register_component_params = ompi_hook_demo_component_register, // Force this component to always be considered - component must be static .mca_component_flags = MCA_BASE_COMPONENT_FLAG_REQUIRED, }, .hookm_data = { /* The component is checkpoint ready */ MCA_BASE_METADATA_PARAM_CHECKPOINT }, /* Component functions */ .hookm_mpi_initialized_top = ompi_hook_demo_mpi_initialized_top, .hookm_mpi_initialized_bottom = ompi_hook_demo_mpi_initialized_bottom, .hookm_mpi_finalized_top = ompi_hook_demo_mpi_finalized_top, .hookm_mpi_finalized_bottom = ompi_hook_demo_mpi_finalized_bottom, .hookm_mpi_init_top = ompi_hook_demo_mpi_init_top, .hookm_mpi_init_top_post_opal = ompi_hook_demo_mpi_init_top_post_opal, .hookm_mpi_init_bottom = ompi_hook_demo_mpi_init_bottom, .hookm_mpi_init_error = ompi_hook_demo_mpi_init_error, .hookm_mpi_finalize_top = ompi_hook_demo_mpi_finalize_top, .hookm_mpi_finalize_bottom = ompi_hook_demo_mpi_finalize_bottom, }; /* * Example 'extra' component with an additional callback that is dynamically * registered at runtime in addition to the callbacks that are a part of the * component structure. */ ompi_hook_base_component_1_0_0_t hook_demo_extra_component = { /* Component functions */ .hookm_mpi_init_bottom = ompi_hook_demo_extra_mpi_init_bottom, }; static int ompi_hook_demo_component_open(void) { opal_output(0, "hook/demo: component_open()"); // Register the 'extra' callback(s) to be called the next time those // functions are encountered. ompi_hook_base_register_callbacks( &hook_demo_extra_component ); return OMPI_SUCCESS; } static int ompi_hook_demo_component_close(void) { opal_output(0, "hook/demo: component_close()"); // Deregister the 'extra' callback(s) so that they are no longer called. // Must pass in the same 'component' structure that was passed to the // ompi_hook_base_register_callbacks() earlier. ompi_hook_base_deregister_callbacks( &hook_demo_extra_component ); return OMPI_SUCCESS; } static int ompi_hook_demo_component_register(void) { opal_output(0, "hook/demo: component_register()"); return OMPI_SUCCESS; }
cea9a80902741d6a19ddb273ad8e3cd2a023d3dc
229a28fc18c13bfe1ba7fc81c38b03651ed8e93b
/sw/vendor/riscv-isa-sim/riscv/insns/c_jal.h
4f156f61fbe3dc22b9565225ee7dcf5bfc57fdea
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference", "LicenseRef-scancode-bsd-3-clause-jtag", "GPL-3.0-or-later" ]
permissive
pulp-platform/snitch
d3967742434fa21e8af71afa6be35ea5420166ca
d026f47843f0ea6c269244c4e6851e0e09141ec3
refs/heads/master
2023-08-24T08:42:36.230951
2023-06-19T09:34:05
2023-06-19T09:34:05
289,236,605
194
44
Apache-2.0
2023-07-11T12:46:26
2020-08-21T09:57:34
SystemVerilog
UTF-8
C
false
false
217
h
c_jal.h
require_extension('C'); if (xlen == 32) { reg_t tmp = npc; set_pc(pc + insn.rvc_j_imm()); WRITE_REG(X_RA, tmp); } else { // c.addiw require(insn.rvc_rd() != 0); WRITE_RD(sext32(RVC_RS1 + insn.rvc_imm())); }
73a11f5a0af4a4854bf49b5dcc6ee654917b20e1
aa3befea459382dc5c01c925653d54f435b3fb0f
/libs/libc/libc.h
2073233b6344407cf4ccd30aa90194de9ba8ec54
[ "MIT-open-group", "BSD-3-Clause", "HPND-sell-variant", "BSD-4-Clause-UC", "LicenseRef-scancode-warranty-disclaimer", "MIT-0", "LicenseRef-scancode-bsd-atmel", "LicenseRef-scancode-gary-s-brown", "LicenseRef-scancode-proprietary-license", "SunPro", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "LicenseRef-scancode-other-permissive", "HPND", "ISC", "Apache-2.0", "LicenseRef-scancode-public-domain", "BSD-2-Clause", "GPL-1.0-or-later", "CC-BY-2.0", "CC-BY-4.0" ]
permissive
apache/nuttx
14519a7bff4a87935d94fb8fb2b19edb501c7cec
606b6d9310fb25c7d92c6f95bf61737e3c79fa0f
refs/heads/master
2023-08-25T06:55:45.822534
2023-08-23T16:03:31
2023-08-24T21:25:47
228,103,273
407
241
Apache-2.0
2023-09-14T18:26:05
2019-12-14T23:27:55
C
UTF-8
C
false
false
4,836
h
libc.h
/**************************************************************************** * libs/libc/libc.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. * ****************************************************************************/ #ifndef __LIBS_LIBC_LIBC_H #define __LIBS_LIBC_LIBC_H /**************************************************************************** * Included Files ****************************************************************************/ #include <nuttx/config.h> #ifndef __ASSEMBLY__ # include <sys/types.h> # include <stdbool.h> # include <stdio.h> # include <stdlib.h> # include <limits.h> # include <semaphore.h> # include <nuttx/lib/lib.h> # include <nuttx/streams.h> #endif /**************************************************************************** * Pre-processor Definitions ****************************************************************************/ /* This configuration directory is used in environment variable processing * when we need to reference the user's home directory. There are no user * directories in NuttX so, by default, this always refers to the root * directory. */ #ifndef CONFIG_LIBC_HOMEDIR # define CONFIG_LIBC_HOMEDIR "/" #endif #define LIB_BUFLEN_UNKNOWN INT_MAX #if defined(CONFIG_BUILD_FLAT) || \ ((!defined(CONFIG_LIBC_PREVENT_STRING_USER) && !defined(__KERNEL__)) || \ (!defined(CONFIG_LIBC_PREVENT_STRING_KERNEL) && defined(__KERNEL__))) # define LIBC_BUILD_STRING #endif /**************************************************************************** * Public Types ****************************************************************************/ /**************************************************************************** * Public Data ****************************************************************************/ #ifndef __ASSEMBLY__ #undef EXTERN #if defined(__cplusplus) #define EXTERN extern "C" extern "C" { #else #define EXTERN extern #endif /**************************************************************************** * Public Function Prototypes ****************************************************************************/ /* Defined in lib_dtoa.c */ #ifdef CONFIG_LIBC_FLOATINGPOINT FAR char *__dtoa(double d, int mode, int ndigits, FAR int *decpt, FAR int *sign, FAR char **rve); #endif /* Defined in lib_getfullpath.c */ int lib_getfullpath(int dirfd, FAR const char *path, FAR char *fullpath, size_t fulllen); /* Defined in lib_fopen.c */ int lib_mode2oflags(FAR const char *mode); /* Defined in lib_libfwrite.c */ ssize_t lib_fwrite(FAR const void *ptr, size_t count, FAR FILE *stream); /* Defined in lib_libfread.c */ ssize_t lib_fread(FAR void *ptr, size_t count, FAR FILE *stream); /* Defined in lib_libgets.c */ FAR char *lib_dgets(FAR char *buf, size_t buflen, int fd, bool keepnl, bool consume); /* Defined in lib_libfgets.c */ FAR char *lib_fgets(FAR char *buf, size_t buflen, FILE *stream, bool keepnl, bool consume); /* Defined in lib_libfflush.c */ ssize_t lib_fflush(FAR FILE *stream, bool bforce); /* Defined in lib_rdflush.c */ int lib_rdflush(FAR FILE *stream); /* Defined in lib_wrflush.c */ int lib_wrflush(FAR FILE *stream); /* Defined in lib_libgetbase.c */ int lib_getbase(FAR const char *nptr, FAR const char **endptr); /* Defined in lib_skipspace.c */ void lib_skipspace(FAR const char **pptr); /* Defined in lib_isbasedigit.c */ bool lib_isbasedigit(int ch, int base, FAR int *value); /* Defined in lib_checkbase.c */ int lib_checkbase(int base, FAR const char **pptr); /* Defined in lib_parsehostfile.c */ #ifdef CONFIG_NETDB_HOSTFILE struct hostent; ssize_t lib_parse_hostfile(FAR FILE *stream, FAR struct hostent *host, FAR char *buf, size_t buflen); #endif #ifndef CONFIG_DISABLE_ENVIRON int lib_restoredir(void); #endif /* Defined in lib_cxx_initialize.c */ void lib_cxx_initialize(void); #undef EXTERN #if defined(__cplusplus) } #endif #endif /* __ASSEMBLY__ */ #endif /* __LIBS_LIBC_LIBC_H */
1aa2e5c747c926bbce5d6ae52681925cd571ea29
0744dcc5394cebf57ebcba343747af6871b67017
/os/board/rtl8730e/src/component/soc/amebad2/fwlib/ram_hp/ameba_vad.c
ce7cf4050214781635c880895986dbc34ad40c4b
[ "Apache-2.0", "GPL-1.0-or-later", "BSD-3-Clause", "ISC", "MIT", "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-other-permissive" ]
permissive
Samsung/TizenRT
96abf62f1853f61fcf91ff14671a5e0c6ca48fdb
1a5c2e00a4b1bbf4c505bbf5cc6a8259e926f686
refs/heads/master
2023-08-31T08:59:33.327998
2023-08-08T06:09:20
2023-08-31T04:38:20
82,517,252
590
719
Apache-2.0
2023-09-14T06:54:49
2017-02-20T04:38:30
C
UTF-8
C
false
false
37,816
c
ameba_vad.c
/** ****************************************************************************** * @file ameba_vad.c * @author Hank_Li * @version V1.0.0 * @date 2021-02-02 * @brief This file contains all the functions prototypes for VAD. ****************************************************************************** * @attention * * This module is a confidential and proprietary property of RealTek and * possession or use of this module requires written permission of RealTek. * * Copyright(c) 2015, Realtek Semiconductor Corporation. All rights reserved. ****************************************************************************** */ #include "ameba_soc.h" #include "ameba_vad_pc.h" #include "sysreg_lsys.h" #include "sysreg_pll.h" #include "sysreg_pmc.h" #include "hal_platform.h" #include "ameba_vad.h" /** * @brief Power up the VAD module. Must be called before other configurations. * @param clock_source * This parameter can be one of the following values: * @arg VAD_OSC * @arg VAD_XTAL */ void VAD_Power_Init(u32 clock_source) { u32 reg_val = 0; if (clock_source == VAD_OSC) { reg_val = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LSYS_CKSL_GRP0); reg_val &= (~LSYS_BIT_CKSL_VAD); HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LSYS_CKSL_GRP0, reg_val); reg_val = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_AON_CLK); reg_val |= APBPeriph_OSC4M_FORCE4_CLOCK; HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_AON_CLK, reg_val); } else { reg_val = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LSYS_CKSL_GRP0); reg_val |= (LSYS_BIT_CKSL_VAD); HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LSYS_CKSL_GRP0, reg_val); } reg_val = HAL_READ32(SYSTEM_CTRL_BASE_LP, REG_LSYS_CKSL_GRP0); reg_val &= (~LSYS_BIT_CKSL_VADM); reg_val |= LSYS_CKSL_VADM(0); HAL_WRITE32(SYSTEM_CTRL_BASE_LP, REG_LSYS_CKSL_GRP0, reg_val); } /** * @brief Set VAD 24bit */ void VAD_Set_Bit(void) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)(VAD_REG_BASE_S)); } else { VAD = ((VAD_TypeDef *)(VAD_REG_BASE)); } VAD->VAD_BUF_CTRL0 &= ~VAD_BIT_BIT_SEL; } /** * @brief Initialize the ADC path of the codec to be used * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 */ void VAD_ADC_Codec_Init(u32 codec_index) { assert_param(codec_index <= VAD_CODEC_THREE); u32 reg_value = 0; VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } reg_value = (VAD -> VAD_CODEC_CTRLx[codec_index]); reg_value &= (~(VAD_BIT_PC_ADC_x_AD_MIX_MUTE)); reg_value |= VAD_BIT_PC_ADC_x_DMIC_MIX_MUTE; reg_value &= (~VAD_BIT_PC_ADC_x_AD_MUTE); VAD -> VAD_CODEC_CTRLx[codec_index] = reg_value; VAD -> VAD_CLK_CTRL |= VAD_BIT_PC_TCON_AD_ANA_CLK_SEL;//bit0->1 2M VAD -> VAD_CLK_CTRL |= VAD_BIT_PC_TCON_AD_ANA_EN; switch (codec_index) { case VAD_CODEC_ZERO: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_ADC_0_EN); break; case VAD_CODEC_ONE: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_ADC_1_EN); break; case VAD_CODEC_TWO: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_ADC_2_EN); break; case VAD_CODEC_THREE: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_ADC_3_EN); break; default: break; } } /** * @brief Set VAD ADC Clock to PC_VAD */ void VAD_ADC_Clock_Enable(void) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_BUF_CTRL0 |= VAD_BIT_ADC_ANALOG_CLK_SEL; } /** * @brief Initialize the ADC * @param ADC_index * This parameter can be one of the following values: * @arg VAD_ADC_ZERO: use adc0 * @arg VAD_ADC_ONE: use adc1 * @arg VAD_ADC_TWO: use adc2 * @arg VAD_ADC_THREE: use adc3 * @arg VAD_ADC_FOUR: use adc4 */ void VAD_ADC_Init(u32 ADC_index) { assert_param(ADC_index <= VAD_ADC_FOUR); AUDIO_CODEC_SetMicBstChnMute(ADC_index + 1, MICIN, UNMUTE); AUDIO_CODEC_SetMicBstPowerMode(ADC_index + 1, LOWPOWER); AUDIO_CODEC_SetMicBstInputMode(ADC_index + 1, DIFF); } /** * @brief Initialize the DMIC path of the codec to be used * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 */ void VAD_DMIC_Codec_Init(u32 codec_index) { assert_param(codec_index <= VAD_CODEC_THREE); u32 reg_value = 0; VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } reg_value = (VAD -> VAD_CODEC_CTRLx[codec_index]); reg_value |= (VAD_BIT_PC_ADC_x_AD_MIX_MUTE); reg_value &= (~VAD_BIT_PC_ADC_x_DMIC_MIX_MUTE); reg_value &= (~VAD_BIT_PC_ADC_x_AD_MUTE); VAD -> VAD_CODEC_CTRLx[codec_index] = reg_value; VAD -> VAD_CLK_CTRL |= VAD_BIT_PC_TCON_DMIC_EN; } /** * @brief delay for a period * @param time_ms * You can call this function when you need a delay, e.g, the dmic need a period of time * to output stable signal, and you need to wait for a period in this situation */ void VAD_Delay(u32 time_ms) { DelayMs(time_ms); } /** * @brief start the codec * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 */ void VAD_DMIC_Codec_Enable(u32 codec_index) { assert_param(codec_index <= VAD_CODEC_THREE); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } switch (codec_index) { case VAD_CODEC_ZERO: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_DMIC_SRC_0_EN | VAD_BIT_PC_TCON_ADC_0_EN); break; case VAD_CODEC_ONE: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_DMIC_SRC_1_EN | VAD_BIT_PC_TCON_ADC_1_EN); break; case VAD_CODEC_TWO: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_DMIC_SRC_2_EN | VAD_BIT_PC_TCON_ADC_2_EN); break; case VAD_CODEC_THREE: VAD -> VAD_CLK_CTRL |= (VAD_BIT_PC_TCON_DMIC_SRC_3_EN | VAD_BIT_PC_TCON_ADC_3_EN); break; default: break; } } /** * @brief set the codec index and its related ADC data source * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param adc_index * This parameter can be one of the following values: * @arg VAD_ADC_ZERO: use ADC0 * @arg VAD_ADC_ONE: use ADC1 * @arg VAD_ADC_TWO: use ADC2 * @arg VAD_ADC_THREE: use ADC3 * @arg VAD_ADC_FOUR: use ADC4 */ void VAD_ADC_Select(u32 codec_index, u32 adc_index) { assert_param(codec_index <= VAD_CODEC_THREE); assert_param(adc_index <= VAD_ADC_FOUR); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } switch (codec_index) { case VAD_CODEC_ZERO: VAD -> VAD_FILTER_CTRL |= (VAD_PC_ADC_SDM_DATA_ADC_0_SEL(adc_index)); break; case VAD_CODEC_ONE: VAD -> VAD_FILTER_CTRL |= (VAD_PC_ADC_SDM_DATA_ADC_1_SEL(adc_index)); break; case VAD_CODEC_TWO: VAD -> VAD_FILTER_CTRL |= (VAD_PC_ADC_SDM_DATA_ADC_2_SEL(adc_index)); break; case VAD_CODEC_THREE: VAD -> VAD_FILTER_CTRL |= (VAD_PC_ADC_SDM_DATA_ADC_3_SEL(adc_index)); break; default: break; } } /** * @brief set the codec index and its related DMIC data source * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param dmic_index * This parameter can be one of the following values: * @arg VAD_DMIC_ZERO: use DMIC0 * @arg VAD_DMIC_ZERO: use DMIC1 * @arg VAD_DMIC_TWO: use DMIC2 * @arg VAD_DMIC_THREE: use DMIC3 * @arg VAD_DMIC_FOUR: use DMIC4 * @arg VAD_DMIC_FIVE: use DMIC5 * @arg VAD_DMIC_SIX: use DMIC6 * @arg VAD_DMIC_SEVEN: use DMIC7 */ void VAD_DMIC_Select(u32 codec_index, u32 dmic_index) { assert_param(codec_index <= VAD_CODEC_THREE); assert_param(dmic_index <= VAD_DMIC_SEVEN); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } switch (codec_index) { case VAD_CODEC_ZERO: VAD -> VAD_FILTER_CTRL |= (VAD_PC_DMIC_DATA_ADC_0_SEL(dmic_index)); break; case VAD_CODEC_ONE: VAD -> VAD_FILTER_CTRL |= (VAD_PC_DMIC_DATA_ADC_1_SEL(dmic_index)); break; case VAD_CODEC_TWO: VAD -> VAD_FILTER_CTRL |= (VAD_PC_DMIC_DATA_ADC_2_SEL(dmic_index)); break; case VAD_CODEC_THREE: VAD -> VAD_FILTER_CTRL |= (VAD_PC_DMIC_DATA_ADC_3_SEL(dmic_index)); break; default: break; } } /** * @brief set the source for voice activity detection * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 */ void VAD_Source_Select(u32 codec_index) { assert_param(codec_index <= VAD_CODEC_THREE); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_VAD_IN_SEL); VAD -> VAD_SEL_CTRL |= VAD_PC_VAD_IN_SEL(codec_index); } /** * @brief set the codec index and its related DMIC data source * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param cut_fre_select * This parameter can be one of the following values: * @arg VAD_HPF_ZERO: cut frequency 0.3Hz * @arg VAD_HPF_ONE: cut frequency 0.6Hz * @arg VAD_HPF_TWO: cut frequency 1.2Hz * @arg VAD_HPF_THREE: cut frequency 2.5Hz * @arg VAD_HPF_FOUR: cut frequency 5Hz * @arg VAD_HPF_FIVE: cut frequency 10Hz * @arg VAD_HPF_SIX: cut frequency 20Hz * @arg VAD_HPF_SEVEN: cut frequency 40Hz */ void VAD_HPF_Init(u32 codec_index, u32 cut_fre_select) { assert_param(codec_index <= VAD_CODEC_THREE); assert_param(cut_fre_select <= VAD_HPF_SEVEN); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } u32 reg_val = VAD -> VAD_CODEC_CTRLx[codec_index]; reg_val &= (~VAD_MASK_PC_ADC_x_AD_HPF_COEF); reg_val |= VAD_PC_ADC_x_AD_HPF_COEF(cut_fre_select); reg_val |= VAD_BIT_PC_ADC_x_AD_DCHPF_EN; VAD -> VAD_CODEC_CTRLx[codec_index] = reg_val; } /** * @brief enable interrupt, set interrupt routine and priority * @param vad_interrupt_source * This parameter can be one of the following values: * @arg VAD_INTERRUPT_KM0: enable interrupt for KM0 * @arg VAD_INTERRUPT_KM4: enable interrupt for KM4 * @arg VAD_INTERRUPT_CA7: enable interrupt for CA7 * @param CallbackFunc * This parameter should be a function written by the user * @param IrqPriority * This parameter is the priority of this interrupt */ void VAD_Interrupt_set(u32 vad_interrupt_source, IRQ_FUN CallbackFunc, u32 IrqPriority) { assert_param(vad_interrupt_source <= VAD_INTERRUPT_KM0); switch (vad_interrupt_source) { case VAD_INTERRUPT_KM0: printf("CPU: KM0\n"); break; case VAD_INTERRUPT_KM4: printf("CPU: KM4\n"); break; case VAD_INTERRUPT_CA7: printf("CPU: CA7\n"); break; default: break; } InterruptRegister(CallbackFunc, VADBT_OR_VADPC_IRQ, NULL, IrqPriority); InterruptEn(VADBT_OR_VADPC_IRQ, IrqPriority); } /** * @brief Configure VAD buf operation(one block) * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param block_index * This parameter can be one of the following values: * @arg VAD_BLOCK_A: use ram block A * @arg VAD_BLOCK_B: use ram block B * @arg VAD_BLOCK_C: use ram block C * @arg VAD_BLOCK_D: use ram block D * @param transfer_mode * This parameter can be one of the follow values: * @arg VAD_BLOCK_MODE: use block mode * @arg VAD_INTERLEAVE_MODE: use interleave mode */ void VAD_Buf_move_one(u32 codec_index, u32 block_index, u32 transfer_mode) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_SHARE_SRAM_ENABLE; /*enable sram blocks as needed. e.g., if block_num = 0(A), only 32k ram is needed. if block_num = 1(B), 64k ram is needed, and so on.*/ VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(block_index); /*sram lock*/ VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_LOCK; if (transfer_mode == VAD_INTERLEAVE_MODE) { VAD -> VAD_BUF_CTRL0 |= VAD_BIT_W_MODE_SEL; } else { VAD -> VAD_BUF_CTRL0 &= (~VAD_BIT_W_MODE_SEL); } /*disable all channels*/ VAD -> VAD_BUF_CTRL0 &= (~(VAD_BIT_CH0_IN_VADBUF_EN | VAD_BIT_CH1_IN_VADBUF_EN | VAD_BIT_CH2_IN_VADBUF_EN | VAD_BIT_CH3_IN_VADBUF_EN)); switch (codec_index) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index); VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index); VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index); VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index); VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } } /** * @brief Configure VAD buf operation(two block) * @param codec_index_x * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param block_index * This parameter can be one of the following values: * @arg VAD_BLOCK_AB: use ram block A and block B * @arg VAD_BLOCK_BC: use ram block B and block C * @arg VAD_BLOCK_CD: use ram block C and block D * @param transfer_mode * This parameter can be one of the follow values: * @arg VAD_BLOCK_MODE: use block mode * @arg VAD_INTERLEAVE_MODE: use interleave mode */ void VAD_Buf_move_two(u32 codec_index_0, u32 codec_index_1, u32 block_index, u32 transfer_mode) { assert_param(codec_index_0 != codec_index_1); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_SHARE_SRAM_ENABLE; switch (block_index) { case VAD_BLOCK_AB: VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(1); break; case VAD_BLOCK_BC: VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(2); break; case VAD_BLOCK_CD: VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(3); break; default: break; } /*sram lock*/ VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_LOCK; if (transfer_mode == VAD_INTERLEAVE_MODE) { VAD -> VAD_BUF_CTRL0 |= VAD_BIT_W_MODE_SEL; } else { VAD -> VAD_BUF_CTRL0 &= (~VAD_BIT_W_MODE_SEL); } /*disable all channels*/ VAD -> VAD_BUF_CTRL0 &= (~(VAD_BIT_CH0_IN_VADBUF_EN | VAD_BIT_CH1_IN_VADBUF_EN | VAD_BIT_CH2_IN_VADBUF_EN | VAD_BIT_CH3_IN_VADBUF_EN)); switch (codec_index_0) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index); break; default: break; } switch (codec_index_1) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index + 1); break; default: break; } switch (codec_index_0) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } switch (codec_index_1) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } } /** * @brief Configure VAD buf operation(three block) * @param codec_index_x * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param block_index * This parameter can be one of the following values: * @arg VAD_BLOCK_ABC: use ram block A, block B and block C * @arg VAD_BLOCK_BCD: use ram block B, block C and block D * @param transfer_mode * This parameter can be one of the follow values: * @arg VAD_BLOCK_MODE: use block mode * @arg VAD_INTERLEAVE_MODE: use interleave mode */ void VAD_Buf_move_three(u32 codec_index_0, u32 codec_index_1, u32 codec_index_2, u32 block_index, u32 transfer_mode) { assert_param(codec_index_0 != codec_index_1); assert_param(codec_index_0 != codec_index_2); assert_param(codec_index_1 != codec_index_2); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_SHARE_SRAM_ENABLE; switch (block_index) { case VAD_BLOCK_ABC: VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(2); break; case VAD_BLOCK_BCD: VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(3); break; default: break; } /*sram lock*/ VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_LOCK; if (transfer_mode == VAD_INTERLEAVE_MODE) { VAD -> VAD_BUF_CTRL0 |= VAD_BIT_W_MODE_SEL; } else { VAD -> VAD_BUF_CTRL0 &= (~VAD_BIT_W_MODE_SEL); } /*disable all channels*/ VAD -> VAD_BUF_CTRL0 &= (~(VAD_BIT_CH0_IN_VADBUF_EN | VAD_BIT_CH1_IN_VADBUF_EN | VAD_BIT_CH2_IN_VADBUF_EN | VAD_BIT_CH3_IN_VADBUF_EN)); switch (codec_index_0) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index); break; default: break; } switch (codec_index_1) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index + 1); break; default: break; } switch (codec_index_2) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index + 2); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index + 2); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index + 2); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index + 2); break; default: break; } switch (codec_index_0) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } switch (codec_index_1) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } switch (codec_index_2) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } } /** * @brief Configure VAD buf operation(four block) * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 * @param block_index * This parameter can be one of the following values: * @arg VAD_BLOCK_ABCD: use ram block A, block B, block C and block D * @param transfer_mode * This parameter can be one of the follow values: * @arg VAD_BLOCK_MODE: use block mode * @arg VAD_INTERLEAVE_MODE: use interleave mode */ void VAD_Buf_move_four(u32 codec_index_0, u32 codec_index_1, u32 codec_index_2, u32 codec_index_3, u32 block_index, u32 transfer_mode) { assert_param(codec_index_0 != codec_index_1); assert_param(codec_index_0 != codec_index_2); assert_param(codec_index_1 != codec_index_2); assert_param(codec_index_1 != codec_index_2); assert_param(codec_index_2 != codec_index_3); VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_SHARE_SRAM_ENABLE; VAD -> VAD_BUF_CTRL0 |= VAD_W_SRAM_ADDRESS_SEL(3); /*sram lock*/ VAD -> VAD_BUF_CTRL0 |= VAD_BIT_BUF_LOCK; if (transfer_mode == VAD_INTERLEAVE_MODE) { VAD -> VAD_BUF_CTRL0 |= VAD_BIT_W_MODE_SEL; } else { VAD -> VAD_BUF_CTRL0 &= (~VAD_BIT_W_MODE_SEL); } /*disable all channels*/ VAD -> VAD_BUF_CTRL0 &= (~(VAD_BIT_CH0_IN_VADBUF_EN | VAD_BIT_CH1_IN_VADBUF_EN | VAD_BIT_CH2_IN_VADBUF_EN | VAD_BIT_CH3_IN_VADBUF_EN)); switch (codec_index_0) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index); break; default: break; } switch (codec_index_1) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index + 1); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index + 1); break; default: break; } switch (codec_index_2) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index + 2); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index + 2); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index + 2); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index + 2); break; default: break; } switch (codec_index_3) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC0_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC0_IN_BUF_ADD_BLOCK(block_index + 3); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC1_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC1_IN_BUF_ADD_BLOCK(block_index + 3); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC2_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC2_IN_BUF_ADD_BLOCK(block_index + 3); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 &= (~(VAD_MASK_CODEC3_IN_BUF_ADD_BLOCK)); VAD -> VAD_BUF_CTRL0 |= VAD_CODEC3_IN_BUF_ADD_BLOCK(block_index + 3); break; default: break; } switch (codec_index_0) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } switch (codec_index_1) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } switch (codec_index_2) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } switch (codec_index_3) { case VAD_CODEC_ZERO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH0_IN_VADBUF_EN); break; case VAD_CODEC_ONE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH1_IN_VADBUF_EN); break; case VAD_CODEC_TWO: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH2_IN_VADBUF_EN); break; case VAD_CODEC_THREE: VAD -> VAD_BUF_CTRL0 |= (VAD_BIT_CH3_IN_VADBUF_EN); break; default: break; } } /** * @brief Choose the codec to do voice activity detection * @param codec_index * This parameter can be one of the following values: * @arg VAD_CODEC_ZERO: use codec0 * @arg VAD_CODEC_TWO: use codec1 * @arg VAD_CODEC_THREE: use codec2 * @arg VAD_CODEC_FOUR: use codec3 */ void VAD_Codec_Select(u8 codec_index) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_VAD_IN_SEL); VAD -> VAD_SEL_CTRL |= VAD_PC_VAD_IN_SEL(codec_index); } /** * @brief Enable VAD */ void VAD_Start(void) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } /*enable VAD*/ VAD -> VAD_CLK_CTRL |= VAD_BIT_PC_TCON_VAD_EN; } /** * @brief use "pitch" as the criterion to detect voice activity * @param type * This parameter can be one of the following values: * @arg VAD_HOLD: the flag will keep 1 once voice activity is detected * @arg VAD_INSTANT: the flag will keeps changing with the voice activity */ void VAD_Pitch_Set(u32 type) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } if (type == VAD_INSTANT) { VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_SEL_VAD_FLAG); VAD -> VAD_SEL_CTRL |= VAD_PC_SEL_VAD_FLAG(1); } else { VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_SEL_VAD_FLAG); VAD -> VAD_SEL_CTRL |= VAD_PC_SEL_VAD_FLAG(0); } } /** * @brief use "energy" as the criterion to detect voice activity * @param type * This parameter can be one of the following values: * @arg VAD_HOLD: the flag will keep 1 once voice activity is detected * @arg VAD_INSTANT: the flag will keeps changing with the voice activity */ void VAD_Energy_Set(u32 type) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } if (type == VAD_INSTANT) { VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_SEL_VAD_FLAG); VAD -> VAD_SEL_CTRL |= VAD_PC_SEL_VAD_FLAG(1); } else { VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_SEL_VAD_FLAG); VAD -> VAD_SEL_CTRL |= VAD_PC_SEL_VAD_FLAG(0); } VAD -> VAD_PITCH_DET_CTRL2 |= VAD_BIT_PITCH_DET_ENERGY_MODE_MANUAL_EN; } /** * @brief use "abs value" as the criterion to detect voice activity * @param type * This parameter can be one of the following values: * @arg VAD_HOLD: the flag will keep 1 once voice activity is detected * @arg VAD_INSTANT: the flag will keeps changing with the voice activity */ void VAD_Abs_Set(u32 type) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } if (type == VAD_INSTANT) { VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_SEL_VAD_FLAG); VAD -> VAD_SEL_CTRL |= VAD_PC_SEL_VAD_FLAG(4); } else { VAD -> VAD_SEL_CTRL &= (~VAD_MASK_PC_SEL_VAD_FLAG); VAD -> VAD_SEL_CTRL |= VAD_PC_SEL_VAD_FLAG(5); } } /** * @brief set the threshold of absolute energy * @param type * This parameter should be set between 0 and 8191 */ void VAD_Abs_Thre(u16 thre) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL6 &= (~VAD_MASK_PITCH_DET_ST_ABS_THR); VAD -> VAD_PITCH_DET_CTRL6 |= (thre); } /** * @brief set the threshold value in energy mode * @param thr: the accumulated time when thr keeps checking check time= REG * 4ms * This parameter should be set between 0 and 2047 */ void VAD_Energy_keep_Thre(u16 thr) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL2 &= (~VAD_MASK_PITCH_DET_ENERGY_KEEP_THR); VAD -> VAD_PITCH_DET_CTRL2 |= (VAD_PITCH_DET_ENERGY_KEEP_THR(thr)); } /** * @brief set the threshold and higher threshole for peak search * @param thr1 * This parameter should be set between 0 and 1023 * @param thr2 * This parameter should be set between 0 and 1023, and it should be larger than thr1 */ void VAD_Energy_Search_Thre(u16 thr1, u16 thr2) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL4 &= (~VAD_MASK_PITCH_DET_PEAK_SEARCH_THR); VAD -> VAD_PITCH_DET_CTRL4 |= (VAD_PITCH_DET_PEAK_SEARCH_THR(thr1)); VAD -> VAD_PITCH_DET_CTRL4 &= (~VAD_MASK_PITCH_DET_PEAK_SEARCH_THR2); VAD -> VAD_PITCH_DET_CTRL4 |= (VAD_PITCH_DET_PEAK_SEARCH_THR2(thr2)); } /** * @brief set the default threshold of onset detection * @param thr * This parameter should be set between 0 and 31 */ void VAD_Det_OD_Default_Thre(u16 thr) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL3 &= (~VAD_MASK_PITCH_DET_OD_THR_DEFAULT); VAD -> VAD_PITCH_DET_CTRL3 |= (VAD_PITCH_DET_OD_THR_DEFAULT(thr)); } /** * @brief set the threshold of majority vote to determine whether the speech features appear range * @param thr * This parameter should be set between 0 and 31 */ void VAD_Det_MV_Thre(u16 thr) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL2 &= (~VAD_MASK_PITCH_DET_MV_THR); VAD -> VAD_PITCH_DET_CTRL2 |= (VAD_PITCH_DET_MV_THR(thr)); } /** * @brief set the threshold for checking the potential energy variation in voice * @param thr * This parameter should be set between 0 and 7 */ void VAD_Det_Energy_CHK_Thre(u16 thr) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL2 &= (~VAD_MASK_PITCH_DET_ENERGY_CHK_THR); VAD -> VAD_PITCH_DET_CTRL2 |= (VAD_PITCH_DET_ENERGY_CHK_THR(thr)); } /** * @brief set the energy mode threshold of onset detection * @param thr * This parameter should be set between 0 and 31 */ void VAD_Det_OD_Energy_Thre(u16 thr) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL3 &= (~VAD_MASK_PITCH_DET_OD_THR_ENERGY); VAD -> VAD_PITCH_DET_CTRL3 |= (VAD_PITCH_DET_OD_THR_ENERGY(thr)); } /** * @brief set the threshold to determine the validation of short_term energy range * @param thr * This parameter should be set between 0 and 8191 */ void VAD_Pitch_Det_Thr_ST_Valid(u16 thr) { VAD_TypeDef *VAD; if (TrustZone_IsSecure()) { VAD = ((VAD_TypeDef *)VAD_REG_BASE_S); } else { VAD = ((VAD_TypeDef *)VAD_REG_BASE); } VAD -> VAD_PITCH_DET_CTRL6 &= (~VAD_MASK_PITCH_DET_THR_ST_VALID); VAD -> VAD_PITCH_DET_CTRL6 |= (VAD_PITCH_DET_THR_ST_VALID(thr)); }
4e03deb5b1103a6d14bb8965705d1715a60d8cfa
a11d8701fa9e4a21dd722d4a14956a5d42bf91b6
/Other/0.10/C/gst-sdk-tutorials/playback-tutorial-5.c
a09f6ab089b6a45cc1d27672734ad49f549b9549
[]
no_license
rubenrua/GstreamerCodeSnippets
d63eddf575f44c7d1f8002de5f58b2e8102f24f3
f164eac29a6117bf647c9f888d95aa7910d305f6
refs/heads/master
2023-03-15T22:33:23.194678
2023-03-01T20:22:00
2023-03-01T20:22:12
6,569,439
115
47
null
2017-01-10T05:12:22
2012-11-06T21:04:31
Objective-C
UTF-8
C
false
false
4,475
c
playback-tutorial-5.c
#include <string.h> #include <gst/gst.h> #include <gst/interfaces/colorbalance.h> typedef struct _CustomData { GstElement *pipeline; GMainLoop *loop; } CustomData; /* Process a color balance command */ static void update_color_channel (const gchar *channel_name, gboolean increase, GstColorBalance *cb) { gdouble step; gint value; GstColorBalanceChannel *channel = NULL; const GList *channels, *l; /* Retrieve the list of channels and locate the requested one */ channels = gst_color_balance_list_channels (cb); for (l = channels; l != NULL; l = l->next) { GstColorBalanceChannel *tmp = (GstColorBalanceChannel *)l->data; if (g_strrstr (tmp->label, channel_name)) { channel = tmp; break; } } if (!channel) return; /* Change the channel's value */ step = 0.1 * (channel->max_value - channel->min_value); value = gst_color_balance_get_value (cb, channel); if (increase) { value = (gint)(value + step); if (value > channel->max_value) value = channel->max_value; } else { value = (gint)(value - step); if (value < channel->min_value) value = channel->min_value; } gst_color_balance_set_value (cb, channel, value); } /* Output the current values of all Color Balance channels */ static void print_current_values (GstElement *pipeline) { const GList *channels, *l; /* Output Color Balance values */ channels = gst_color_balance_list_channels (GST_COLOR_BALANCE (pipeline)); for (l = channels; l != NULL; l = l->next) { GstColorBalanceChannel *channel = (GstColorBalanceChannel *)l->data; gint value = gst_color_balance_get_value (GST_COLOR_BALANCE (pipeline), channel); g_print ("%s: %3d%% ", channel->label, 100 * (value - channel->min_value) / (channel->max_value - channel->min_value)); } g_print ("\n"); } /* Process keyboard input */ static gboolean handle_keyboard (GIOChannel *source, GIOCondition cond, CustomData *data) { gchar *str = NULL; if (g_io_channel_read_line (source, &str, NULL, NULL, NULL) != G_IO_STATUS_NORMAL) { return TRUE; } switch (g_ascii_tolower (str[0])) { case 'c': update_color_channel ("CONTRAST", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); break; case 'b': update_color_channel ("BRIGHTNESS", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); break; case 'h': update_color_channel ("HUE", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); break; case 's': update_color_channel ("SATURATION", g_ascii_isupper (str[0]), GST_COLOR_BALANCE (data->pipeline)); break; case 'q': g_main_loop_quit (data->loop); break; default: break; } g_free (str); print_current_values (data->pipeline); return TRUE; } int main(int argc, char *argv[]) { CustomData data; GstStateChangeReturn ret; GIOChannel *io_stdin; /* Initialize GStreamer */ gst_init (&argc, &argv); /* Initialize our data structure */ memset (&data, 0, sizeof (data)); /* Print usage map */ g_print ( "USAGE: Choose one of the following options, then press enter:\n" " 'C' to increase contrast, 'c' to decrease contrast\n" " 'B' to increase brightness, 'b' to decrease brightness\n" " 'H' to increase hue, 'h' to decrease hue\n" " 'S' to increase saturation, 's' to decrease saturation\n" " 'Q' to quit\n"); /* Build the pipeline */ data.pipeline = gst_parse_launch ("playbin2 uri=http://docs.gstreamer.com/media/sintel_trailer-480p.webm", NULL); /* Add a keyboard watch so we get notified of keystrokes */ #ifdef _WIN32 io_stdin = g_io_channel_win32_new_fd (fileno (stdin)); #else io_stdin = g_io_channel_unix_new (fileno (stdin)); #endif g_io_add_watch (io_stdin, G_IO_IN, (GIOFunc)handle_keyboard, &data); /* Start playing */ ret = gst_element_set_state (data.pipeline, GST_STATE_PLAYING); if (ret == GST_STATE_CHANGE_FAILURE) { g_printerr ("Unable to set the pipeline to the playing state.\n"); gst_object_unref (data.pipeline); return -1; } print_current_values (data.pipeline); /* Create a GLib Main Loop and set it to run */ data.loop = g_main_loop_new (NULL, FALSE); g_main_loop_run (data.loop); /* Free resources */ g_main_loop_unref (data.loop); g_io_channel_unref (io_stdin); gst_element_set_state (data.pipeline, GST_STATE_NULL); gst_object_unref (data.pipeline); return 0; }
530b74f5c1b92d637ae04174672715eb4aa09b5b
9c774a31ff1e98a6366e71e54e84ea97e6f050a2
/hdf5-blosc2/src/blosc2_plugin.h
c19185bdda2697c3ee00ca13d2fc68e5d270e8ed
[ "BSD-3-Clause" ]
permissive
PyTables/PyTables
65c355d47d68b5e8f4240fc7cc32906c3b6f2eea
f3817d7637b465de1a2ab5da9dffd3aba185c331
refs/heads/master
2023-08-30T02:46:42.212028
2023-08-18T05:32:06
2023-08-18T05:32:06
1,844,194
1,076
267
BSD-3-Clause
2023-09-09T06:56:39
2011-06-03T19:44:46
Python
UTF-8
C
false
false
663
h
blosc2_plugin.h
/* * Dynamically loaded filter plugin for HDF5 blosc2 filter. * * Header file * ----------- * * This provides dynamically loaded HDF5 filter functionality (introduced * in HDF5-1.8.11, May 2013) to the blosc2 HDF5 filter. * * Usage: compile as a shared library and install either to the default * search location for HDF5 filter plugins (on Linux * /usr/local/hdf5/lib/plugin) or to a location pointed to by the * HDF5_PLUGIN_PATH environment variable. * */ #ifndef PLUGIN_BLOSC2_H #define PLUGIN_BLOSC2_H #include "H5PLextern.h" H5PL_type_t H5PLget_plugin_type(void); const void* H5PLget_plugin_info(void); #endif // PLUGIN_BLOSC2_H
99f912c9fa77ae807729574d4e3144fb066d8aa9
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/dev/pci/drm/i915/display/g4x_dp.h
eead3efa0f1e1ddd8f17d4abd277c02559381f7a
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
764
h
g4x_dp.h
/* SPDX-License-Identifier: MIT */ /* * Copyright © 2020 Intel Corporation */ #ifndef _G4X_DP_H_ #define _G4X_DP_H_ #include <linux/types.h> #include "i915_reg.h" enum pipe; enum port; #define drm_i915_private inteldrm_softc struct drm_i915_private; struct intel_crtc_state; struct intel_dp; struct intel_encoder; const struct dpll *vlv_get_dpll(struct drm_i915_private *i915); enum pipe vlv_active_pipe(struct intel_dp *intel_dp); void g4x_dp_set_clock(struct intel_encoder *encoder, struct intel_crtc_state *pipe_config); bool g4x_dp_port_enabled(struct drm_i915_private *dev_priv, i915_reg_t dp_reg, enum port port, enum pipe *pipe); bool g4x_dp_init(struct drm_i915_private *dev_priv, i915_reg_t output_reg, enum port port); #endif
6c5fe53db9c29f6d2b0e859784ec51ba92fa194e
7df190df28da7e4ff166e55dc8ce780f11236a9f
/src/router/lsof/dialects/du/dfile.c
696d11dac7dc4c7ba297c7ab2e6376fdb81583dc
[]
no_license
mirror/dd-wrt
25416946e6132aa54b35809de61834a1825a9a36
8f2934a5a2adfbb59b471375aa3a38de5d036531
refs/heads/master
2023-08-31T14:54:47.496685
2023-08-30T17:40:54
2023-08-30T17:40:54
7,470,282
520
281
null
2023-05-29T20:56:24
2013-01-06T17:21:29
null
UTF-8
C
false
false
3,097
c
dfile.c
/* * dfile.c - DEC OSF/1, Digital UNIX, Tru64 UNIX file processing functions for * lsof */ /* * Copyright 1994 Purdue Research Foundation, West Lafayette, Indiana * 47907. All rights reserved. * * Written by Victor A. Abell * * This software is not subject to any license of the American Telephone * and Telegraph Company or the Regents of the University of California. * * Permission is granted to anyone to use this software for any purpose on * any computer system, and to alter it and redistribute it freely, subject * to the following restrictions: * * 1. Neither the authors nor Purdue University are responsible for any * consequences of the use of this software. * * 2. The origin of this software must not be misrepresented, either by * explicit claim or by omission. Credit to the authors and Purdue * University must appear in documentation and sources. * * 3. Altered versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 4. This notice may not be removed or altered. */ #ifndef lint static char copyright[] = "@(#) Copyright 1994 Purdue Research Foundation.\nAll rights reserved.\n"; #endif #include "lsof.h" #if defined(HASIPv6) /* * gethostbyname2() -- an RFC2133-compatible get-host-by-name-two function * to get AF_INET and AF_INET6 addresses from host names, * using the RFC2553-compatible getipnodebyname() function */ extern struct hostent * gethostbyname2(nm, prot) char *nm; /* host name */ int prot; /* protocol -- AF_INET or AF_INET6 */ { int err; static struct hostent *hep = (struct hostent *)NULL; if (hep) (void) freehostent(hep); hep = getipnodebyname(nm, prot, 0, &err); return(hep); } #endif /* defined(HASIPv6) */ #if defined(HASPRIVNMCACHE) /* * print_advfs_path() - print an ADVFS file path * * return: 1 if path printed * * This code was provided by Dean Brock <brock@cs.unca.edu>. * * This function is called by the name HASPRIVNMCACHE from printname(). */ int print_advfs_path(lf) struct lfile *lf; /* file whose name is to be printed */ { char buf[MAXPATHLEN+1]; mlBfTagT t2pb; /* * Print any non-NULL path returned by tag_to_path() for ADVFS files that * have sequence and inode numbers. */ if (!lf->advfs_seq_stat || lf->inp_ty != 1 || !lf->fsdir || !*lf->fsdir) return(0); t2pb.ml_ino = (int)lf->inode; t2pb.ml_seq = lf->advfs_seq; if (tag_to_path(lf->fsdir, t2pb, MAXPATHLEN, buf) || !*buf) return(0); buf[MAXPATHLEN] = '\0'; safestrprt((buf[0] == '/' && buf[1] == '/') ? &buf[1] : buf, stdout, 0); return(1); } #endif /* defined(HASPRIVNMCACHE) */ /* * print_dev() - print device */ char * print_dev(lf, dev) struct lfile *lf; /* file whose device is to be printed */ dev_t *dev; /* device to be printed */ { static char buf[128]; if (GET_MIN_DEV(*dev) > 9999999) (void) snpf(buf, sizeof(buf), "%d,%#x", GET_MAJ_DEV(*dev), GET_MIN_DEV(*dev)); else (void) snpf(buf, sizeof(buf), "%d,%d", GET_MAJ_DEV(*dev), GET_MIN_DEV(*dev)); return(buf); }
68d64125c77d8d213a93e7533eca7050f669dfbe
376e1818d427b5e4d32fa6dd6c7b71e9fd88afdb
/games/eternal-lands/patches/patch-platform.h
485d1ef0945bf0e833e5d8db6fbc76639076d1a8
[]
no_license
NetBSD/pkgsrc
a0732c023519650ef821ab89c23ab6ab59e25bdb
d042034ec4896cc5b47ed6f2e5b8802d9bc5c556
refs/heads/trunk
2023-09-01T07:40:12.138283
2023-09-01T05:25:19
2023-09-01T05:25:19
88,439,572
321
138
null
2023-07-12T22:34:14
2017-04-16T20:04:15
null
UTF-8
C
false
false
645
h
patch-platform.h
$NetBSD: patch-platform.h,v 1.1 2021/04/04 09:09:30 nia Exp $ For unknown reasons, the BSD section causes confusing compiler errors. We use the same GL lib as Linux anyway, so just reuse that section. --- platform.h.orig 2020-04-29 19:47:42.000000000 +0000 +++ platform.h @@ -85,16 +85,13 @@ #include "elglext.h" #define APIENTRY #define APIENTRYP * -#elif !defined(BSD) +#else #define GL_GLEXT_LEGACY #include <GL/gl.h> #include <GL/glu.h> #undef GL_VERSION_1_2 #undef GL_VERSION_1_3 #include "glext.h" -#else // BSD - #include <GL/gl.h> - #include <GL/glu.h> #endif // Inlucde the plaform specific location sound libs
1c2ef26e76a0ef40f7b3de441aa1e2019d030ec2
1efb2283837c9b70bc6449cec877799e4efa3268
/src/pm/hydra/mpiexec/pmiserv_kvs.c
05273953125161cc91c8eff3753103302a460c40
[ "mpich2" ]
permissive
pmodels/mpich
d2392e8e30536cad3e500c16aa1e71211101d83f
2d265f9f5f93ebdd07ad547423bc6212868262a4
refs/heads/main
2023-09-04T05:50:15.041823
2023-09-01T23:07:33
2023-09-01T23:07:33
70,918,679
506
313
NOASSERTION
2023-09-14T14:38:36
2016-10-14T14:39:42
C
UTF-8
C
false
false
11,141
c
pmiserv_kvs.c
/* * Copyright (C) by Argonne National Laboratory * See COPYRIGHT in top-level directory */ #include "hydra_server.h" #include "pmiserv_pmi.h" #include "pmiserv_utils.h" struct HYD_pmcd_pmi_v2_reqs { struct HYD_proxy *proxy; int process_fd; int pgid; struct PMIU_cmd *pmi; const char *key; struct HYD_pmcd_pmi_v2_reqs *prev; struct HYD_pmcd_pmi_v2_reqs *next; }; static struct HYD_pmcd_pmi_v2_reqs *pending_reqs = NULL; static bool check_epoch_reached(struct HYD_pg *pg, int process_fd); static HYD_status HYD_pmcd_pmi_v2_queue_req(struct HYD_proxy *proxy, int process_fd, int pgid, struct PMIU_cmd *pmi, const char *key); static HYD_status check_pending_reqs(const char *key); static const bool is_static = true; HYD_status HYD_pmiserv_kvs_get(struct HYD_proxy *proxy, int process_fd, int pgid, struct PMIU_cmd *pmi, bool sync) { HYD_status status = HYD_SUCCESS; int pmi_errno; HYDU_FUNC_ENTER(); struct HYD_pg *pg; struct HYD_pmcd_pmi_pg_scratch *pg_scratch; pg = PMISERV_pg_by_id(proxy->pgid); pg_scratch = (struct HYD_pmcd_pmi_pg_scratch *) pg->pg_scratch; const char *kvsname; const char *key; pmi_errno = PMIU_msg_get_query_get(pmi, &kvsname, &key); if (kvsname && strcmp(pg_scratch->kvsname, kvsname) != 0) { HYDU_ERR_SETANDJUMP(status, HYD_INTERNAL_ERROR, "kvsname (%s) does not match this group's kvs space (%s)\n", kvsname, pg_scratch->kvsname); } int found; const char *val; found = 0; val = NULL; if (strcmp(key, "PMI_dead_processes") == 0) { found = 1; val = pg_scratch->dead_processes; } else { HYD_kvs_find(pg_scratch->kvs, key, &val, &found); } if (!found && sync) { /* check whether all proxies have arrived at the same epoch or enqueue * the "get". A "put" (from another proxy) will poke the progress. */ if (!check_epoch_reached(pg, process_fd)) { status = HYD_pmcd_pmi_v2_queue_req(proxy, process_fd, pgid, pmi, key); HYDU_ERR_POP(status, "unable to queue request\n"); goto fn_exit; } } struct PMIU_cmd pmi_response; if (val) { if (sync) { pmi_errno = PMIU_msg_set_response_kvsget(pmi, &pmi_response, is_static, val, true); } else { pmi_errno = PMIU_msg_set_response_get(pmi, &pmi_response, is_static, val, true); } } else { pmi_errno = PMIU_msg_set_response_fail(pmi, &pmi_response, is_static, 1, "key_not_found"); } HYDU_ASSERT(!pmi_errno, status); status = HYD_pmiserv_pmi_reply(proxy, process_fd, &pmi_response); HYDU_ERR_POP(status, "error writing PMI line\n"); fn_exit: HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; } HYD_status HYD_pmiserv_kvs_put(struct HYD_proxy *proxy, int process_fd, int pgid, struct PMIU_cmd *pmi) { HYD_status status = HYD_SUCCESS; int pmi_errno; HYDU_FUNC_ENTER(); const char *kvsname, *key, *val; pmi_errno = PMIU_msg_get_query_put(pmi, &kvsname, &key, &val); HYDU_ASSERT(!pmi_errno, status); struct HYD_pg *pg; struct HYD_pmcd_pmi_pg_scratch *pg_scratch; pg = PMISERV_pg_by_id(proxy->pgid); pg_scratch = (struct HYD_pmcd_pmi_pg_scratch *) pg->pg_scratch; status = HYD_pmcd_pmi_add_kvs(key, val, pg_scratch->kvs, HYD_server_info.user_global.debug); HYDU_ERR_POP(status, "unable to put data into kvs\n"); struct PMIU_cmd pmi_response; pmi_errno = PMIU_msg_set_response(pmi, &pmi_response, is_static); HYDU_ASSERT(!pmi_errno, status); status = HYD_pmiserv_pmi_reply(proxy, process_fd, &pmi_response); HYDU_ERR_POP(status, "send command failed\n"); status = check_pending_reqs(key); HYDU_ERR_POP(status, "check_pending_reqs failed\n"); fn_exit: HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; } /* NOTE: this is an aggregate put from proxy with multiple key=val pairs */ HYD_status HYD_pmiserv_kvs_mput(struct HYD_proxy *proxy, int process_fd, int pgid, struct PMIU_cmd *pmi) { HYD_status status = HYD_SUCCESS; HYDU_FUNC_ENTER(); struct HYD_pg *pg; struct HYD_pmcd_pmi_pg_scratch *pg_scratch; pg = PMISERV_pg_by_id(proxy->pgid); pg_scratch = (struct HYD_pmcd_pmi_pg_scratch *) pg->pg_scratch; /* FIXME: leak of pmi's abstraction */ for (int i = 0; i < pmi->num_tokens; i++) { status = HYD_pmcd_pmi_add_kvs(pmi->tokens[i].key, pmi->tokens[i].val, pg_scratch->kvs, HYD_server_info.user_global.debug); HYDU_ERR_POP(status, "unable to add key pair to kvs\n"); } fn_exit: HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; } HYD_status HYD_pmiserv_kvs_fence(struct HYD_proxy *proxy, int process_fd, int pgid, struct PMIU_cmd *pmi) { struct HYD_pg *pg; struct HYD_pmcd_pmi_pg_scratch *pg_scratch; int pmi_errno; int i; HYD_status status = HYD_SUCCESS; HYDU_FUNC_ENTER(); pg = PMISERV_pg_by_id(proxy->pgid); pg_scratch = (struct HYD_pmcd_pmi_pg_scratch *) pg->pg_scratch; int cur_epoch = -1; /* Try to find the epoch point of this process */ for (i = 0; i < pg->pg_process_count; i++) { if (pg_scratch->ecount[i].process_fd == process_fd) { pg_scratch->ecount[i].epoch++; cur_epoch = pg_scratch->ecount[i].epoch; break; } } if (i == pg->pg_process_count) { /* couldn't find the current process; find a NULL entry */ for (i = 0; i < pg->pg_process_count; i++) if (pg_scratch->ecount[i].epoch == -1) break; pg_scratch->ecount[i].process_fd = process_fd; pg_scratch->ecount[i].epoch = 0; cur_epoch = pg_scratch->ecount[i].epoch; } struct PMIU_cmd pmi_response; pmi_errno = PMIU_msg_set_response(pmi, &pmi_response, is_static); HYDU_ASSERT(!pmi_errno, status); status = HYD_pmiserv_pmi_reply(proxy, process_fd, &pmi_response); HYDU_ERR_POP(status, "send command failed\n"); if (cur_epoch == pg_scratch->epoch) { pg_scratch->fence_count++; if (pg_scratch->fence_count % pg->pg_process_count == 0) { /* Poke the progress engine before exiting */ status = check_pending_reqs(NULL); HYDU_ERR_POP(status, "check pending requests error\n"); /* reset fence_count */ pg_scratch->epoch++; pg_scratch->fence_count = 0; for (i = 0; i < pg->pg_process_count; i++) { if (pg_scratch->ecount[i].epoch >= pg_scratch->epoch) { pg_scratch->fence_count++; } } } } fn_exit: HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; } /* routines for epoch checking (PMI-v2 kvs-fence) */ HYD_status HYD_pmiserv_epoch_init(struct HYD_pg *pg) { HYD_status status = HYD_SUCCESS; HYDU_FUNC_ENTER(); struct HYD_pmcd_pmi_pg_scratch *pg_scratch; pg_scratch = pg->pg_scratch; HYDU_MALLOC_OR_JUMP(pg_scratch->ecount, struct HYD_pmcd_pmi_ecount *, pg->pg_process_count * sizeof(struct HYD_pmcd_pmi_ecount), status); /* initialize as sentinels. The first kvs-fence will fill the entry. * Subsequent kvs-fence will increment the epoch. */ for (int i = 0; i < pg->pg_process_count; i++) { pg_scratch->ecount[i].process_fd = -1; pg_scratch->ecount[i].epoch = -1; } fn_exit: HYDU_FUNC_EXIT(); return status; fn_fail: goto fn_exit; } HYD_status HYD_pmiserv_epoch_free(struct HYD_pg *pg) { struct HYD_pmcd_pmi_pg_scratch *pg_scratch; pg_scratch = pg->pg_scratch; MPL_free(pg_scratch->ecount); return HYD_SUCCESS; } static bool check_epoch_reached(struct HYD_pg *pg, int process_fd) { struct HYD_pmcd_pmi_pg_scratch *pg_scratch; pg_scratch = (struct HYD_pmcd_pmi_pg_scratch *) pg->pg_scratch; int idx = -1; for (int i = 0; i < pg->pg_process_count; i++) { if (pg_scratch->ecount[i].process_fd == process_fd) { idx = i; break; } } assert(idx != -1); for (int i = 0; i < pg->pg_process_count; i++) { if (pg_scratch->ecount[i].epoch < pg_scratch->ecount[idx].epoch) { return false; } } return true; } static HYD_status HYD_pmcd_pmi_v2_queue_req(struct HYD_proxy *proxy, int process_fd, int pgid, struct PMIU_cmd *pmi, const char *key) { struct HYD_pmcd_pmi_v2_reqs *req, *tmp; HYD_status status = HYD_SUCCESS; HYDU_MALLOC_OR_JUMP(req, struct HYD_pmcd_pmi_v2_reqs *, sizeof(struct HYD_pmcd_pmi_v2_reqs), status); req->proxy = proxy; req->process_fd = process_fd; req->pgid = pgid; req->prev = NULL; req->next = NULL; req->pmi = PMIU_cmd_dup(pmi); req->key = MPL_strdup(key); if (pending_reqs == NULL) pending_reqs = req; else { for (tmp = pending_reqs; tmp->next; tmp = tmp->next); tmp->next = req; req->prev = tmp; } fn_exit: return status; fn_fail: goto fn_exit; } /* Process the pending get with matching key. If the key is NULL, * we are in a kvs-fence, clear all the pending reqs. */ static HYD_status check_pending_reqs(const char *key) { struct HYD_pmcd_pmi_v2_reqs *req, *list_head = NULL, *list_tail = NULL; HYD_status status = HYD_SUCCESS; int count = 0; int has_pending = 0; for (req = pending_reqs; req; req = req->next) { count++; if (key && strcmp(key, req->key) == 0) { has_pending++; } } if (key && !has_pending) { goto fn_exit; } /* FIXME: this dequeue then enqueue is a bit silly. */ for (int i = 0; i < count; i++) { /* Dequeue a request */ req = pending_reqs; if (pending_reqs) { pending_reqs = pending_reqs->next; req->next = NULL; } if (key && req && strcmp(key, req->key)) { /* If the key doesn't match the request, just queue it back */ if (list_head == NULL) { list_head = req; list_tail = req; } else { list_tail->next = req; req->prev = list_tail; list_tail = req; } } else { status = HYD_pmiserv_kvs_get(req->proxy, req->process_fd, req->pgid, req->pmi, true); HYDU_ERR_POP(status, "kvs_get returned error\n"); /* Free the dequeued request */ PMIU_cmd_free(req->pmi); MPL_free(req); } } if (list_head) { list_tail->next = pending_reqs; pending_reqs = list_head; } fn_exit: return status; fn_fail: goto fn_exit; }
203735d00625b019f123c34641ab1d7fa0114969
975fdf27ce73834e30c5af34e85a418c46d514c5
/source/decoder.h
6bb6d52f37bc73a6ea03f1dd66f6ac35c7e225b3
[ "MIT" ]
permissive
agronholm/cbor2
627a3a50d507b05513e403cf61685db868eb5fe9
760b820a84c657f413e9087114486c483e6ca67b
refs/heads/master
2023-09-01T01:27:45.530877
2023-06-02T10:51:56
2023-06-02T14:57:40
60,716,223
174
55
MIT
2023-09-11T22:35:06
2016-06-08T17:19:54
C
UTF-8
C
false
false
609
h
decoder.h
#define PY_SSIZE_T_CLEAN #include <Python.h> #include <stdbool.h> #include <stdint.h> typedef struct { PyObject_HEAD PyObject *read; // cached read() method of fp PyObject *tag_hook; PyObject *object_hook; PyObject *shareables; PyObject *stringref_namespace; PyObject *str_errors; bool immutable; Py_ssize_t shared_index; } CBORDecoderObject; extern PyTypeObject CBORDecoderType; PyObject * CBORDecoder_new(PyTypeObject *, PyObject *, PyObject *); int CBORDecoder_init(CBORDecoderObject *, PyObject *, PyObject *); PyObject * CBORDecoder_decode(CBORDecoderObject *);
d04e8b2557b633837d27ecdb674b7214171fe07e
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/playstation2/include/vmparam.h
91f2df1d3c94a03da3825cb8285af8a6f02a901b
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
281
h
vmparam.h
/* $NetBSD: vmparam.h,v 1.5 2014/03/31 11:41:01 martin Exp $ */ /* * PlayStation 2 has one physical memory segment. * 0 ... kernel itself * 1 ... heap (continuous) */ #define VM_PHYSSEG_MAX 2 #define VM_NFREELIST 1 #define VM_FREELIST_DEFAULT 0 #include <mips/vmparam.h>
db731ac071e1970f4e08b94e06548e86a055ef78
9ceacf33fd96913cac7ef15492c126d96cae6911
/sys/arch/loongson/dev/glxclk.c
652462d534fb9b30cf7a9867bf0517d75d4ac13a
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
6,877
c
glxclk.c
/* $OpenBSD: glxclk.c,v 1.9 2023/08/26 09:37:43 visa Exp $ */ /* * Copyright (c) 2013 Paul Irofti. * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <sys/param.h> #include <sys/systm.h> #include <sys/clockintr.h> #include <sys/device.h> #include <sys/kernel.h> #include <sys/stdint.h> #include <machine/bus.h> #include <machine/autoconf.h> #include <dev/isa/isavar.h> #include <dev/pci/pcireg.h> #include <dev/pci/pcivar.h> #include <dev/pci/pcidevs.h> #include <dev/pci/glxreg.h> #include <dev/pci/glxvar.h> struct glxclk_softc { struct device sc_dev; bus_space_tag_t sc_iot; bus_space_handle_t sc_ioh; struct intrclock sc_intrclock; }; struct cfdriver glxclk_cd = { NULL, "glxclk", DV_DULL }; int glxclk_match(struct device *, void *, void *); void glxclk_attach(struct device *, struct device *, void *); int glxclk_intr(void *); void glxclk_initclock(void); void glxclk_startclock(struct cpu_info *); void glxclk_rearm(void *, uint64_t); void glxclk_trigger(void *); const struct cfattach glxclk_ca = { sizeof(struct glxclk_softc), glxclk_match, glxclk_attach, }; #define MSR_LBAR_ENABLE 0x100000000ULL #define MSR_LBAR_MFGPT DIVIL_LBAR_MFGPT #define MSR_MFGPT_SIZE 0x40 #define MSR_MFGPT_ADDR_MASK 0xffc0 /* * Experience shows that the clock source goes crazy on scale factors * lower than 8, so keep it at 8. */ #define AMD5536_MFGPT1_CMP2 0x0000000a /* Compare value for CMP2 */ #define AMD5536_MFGPT1_CNT 0x0000000c /* Up counter */ #define AMD5536_MFGPT1_SETUP 0x0000000e /* Setup register */ #define AMD5536_MFGPT1_SCALE 0x3 /* Set divider to 8 */ #define AMD5536_MFGPT1_CLOCK (1 << 15) /* Clock frequency */ #define AMD5536_MFGPT1_C2_IRQM 0x00000200 #define AMD5536_MFGPT_CNT_EN (1 << 15) /* Enable counting */ #define AMD5536_MFGPT_CMP2 (1 << 14) /* Compare 2 output */ #define AMD5536_MFGPT_CMP1 (1 << 13) /* Compare 1 output */ #define AMD5536_MFGPT_SETUP (1 << 12) /* Set to 1 after 1st write */ #define AMD5536_MFGPT_STOP_EN (1 << 11) /* Stop enable */ #define AMD5536_MFGPT_CMP2MODE (1 << 9)|(1 << 8)/* Set to GE + activate IRQ */ #define AMD5536_MFGPT_CLKSEL (1 << 4) /* Clock select 14MHz */ struct glxclk_softc *glxclk_sc; int glxclk_match(struct device *parent, void *match, void *aux) { struct glxpcib_attach_args *gaa = aux; struct cfdata *cf = match; if (strcmp(gaa->gaa_name, cf->cf_driver->cd_name) != 0) return 0; return 1; } void glxclk_attach(struct device *parent, struct device *self, void *aux) { glxclk_sc = (struct glxclk_softc *)self; struct glxpcib_attach_args *gaa = aux; u_int64_t wa; glxclk_sc->sc_iot = gaa->gaa_iot; glxclk_sc->sc_ioh = gaa->gaa_ioh; wa = rdmsr(MSR_LBAR_MFGPT); if ((wa & MSR_LBAR_ENABLE) == 0) { printf(" not configured\n"); return; } if (bus_space_map(glxclk_sc->sc_iot, wa & MSR_MFGPT_ADDR_MASK, MSR_MFGPT_SIZE, 0, &glxclk_sc->sc_ioh)) { printf(" not configured\n"); return; } /* Set comparator 2 */ bus_space_write_2(glxclk_sc->sc_iot, glxclk_sc->sc_ioh, AMD5536_MFGPT1_CMP2, 1); /* Reset counter to 0 */ bus_space_write_2(glxclk_sc->sc_iot, glxclk_sc->sc_ioh, AMD5536_MFGPT1_CNT, 0); /* * All the bits in the range 11:0 have to be written at once. * After they're set the first time all further writes are * ignored. */ uint16_t setup = (AMD5536_MFGPT1_SCALE | AMD5536_MFGPT_CMP2MODE); bus_space_write_2(glxclk_sc->sc_iot, glxclk_sc->sc_ioh, AMD5536_MFGPT1_SETUP, setup); /* Check to see if the MFGPT_SETUP bit was set */ setup = bus_space_read_2(glxclk_sc->sc_iot, glxclk_sc->sc_ioh, AMD5536_MFGPT1_SETUP); if ((setup & AMD5536_MFGPT_SETUP) == 0) { printf(" not configured\n"); return; } /* Enable MFGPT1 Comparator 2 Output to the Interrupt Mapper */ wa = rdmsr(MFGPT_IRQ); wa |= AMD5536_MFGPT1_C2_IRQM; wrmsr(MFGPT_IRQ, wa); /* * Tie PIC input 5 to IG7 for glxclk(4). */ wa = rdmsr(PIC_ZSEL_LOW); wa &= ~(0xfUL << 20); wa |= 7 << 20; wrmsr(PIC_ZSEL_LOW, wa); /* * The interrupt argument is NULL in order to notify the dispatcher * to pass the clock frame as argument. This trick also forces keeping * the soft state global because during the interrupt we need to * disable the counter in the MFGPT setup register. */ isa_intr_establish(sys_platform->isa_chipset, 7, IST_LEVEL, IPL_CLOCK, glxclk_intr, NULL, "clock"); glxclk_sc->sc_intrclock.ic_cookie = glxclk_sc; glxclk_sc->sc_intrclock.ic_rearm = glxclk_rearm; glxclk_sc->sc_intrclock.ic_trigger = glxclk_trigger; md_initclock = glxclk_initclock; md_startclock = glxclk_startclock; printf("\n"); } void glxclk_initclock(void) { /* * MFGPT runs on powers of two, adjust the hz value accordingly. */ stathz = hz = 128; profhz = hz * 10; tick = 1000000 / hz; tick_nsec = 1000000000 / hz; clockintr_init(CL_RNDSTAT); } void glxclk_startclock(struct cpu_info *ci) { clockintr_cpu_init(&glxclk_sc->sc_intrclock); /* Start the clock. */ int s = splclock(); ci->ci_clock_started++; clockintr_trigger(); splx(s); } int glxclk_intr(void *arg) { struct clockframe *frame = arg; struct cpu_info *ci = curcpu(); struct glxclk_softc *sc = glxclk_sc; /* Clear the current event and disable the counter. */ bus_space_write_2(sc->sc_iot, sc->sc_ioh, AMD5536_MFGPT1_SETUP, AMD5536_MFGPT_CMP1 | AMD5536_MFGPT_CMP2); if (ci->ci_clock_started == 0) return 1; clockintr_dispatch(frame); return 1; } void glxclk_rearm(void *cookie, uint64_t nsecs) { const uint64_t freq = AMD5536_MFGPT1_CLOCK >> AMD5536_MFGPT1_SCALE; const uint64_t nsec_ratio = (freq << 32) / 1000000000; /* Subtract 1 to leave room for rounding. */ const uint64_t nsec_max = UINT64_MAX / nsec_ratio - 1; struct glxclk_softc *sc = cookie; uint64_t count; register_t sr; nsecs = MIN(nsecs, nsec_max); count = MAX((nsecs * nsec_ratio + (1U << 31)) >> 32, 1); sr = disableintr(); bus_space_write_2(sc->sc_iot, sc->sc_ioh, AMD5536_MFGPT1_CMP2, count); bus_space_write_2(sc->sc_iot, sc->sc_ioh, AMD5536_MFGPT1_CNT, 0); bus_space_write_2(sc->sc_iot, sc->sc_ioh, AMD5536_MFGPT1_SETUP, AMD5536_MFGPT_CNT_EN | AMD5536_MFGPT_CMP2); setsr(sr); } void glxclk_trigger(void *cookie) { glxclk_rearm(cookie, 0); }
a66a775114f2093b62df812bd76ee302510d7328
ec6a71b57ebe88538269197fd16bede6bc2062ae
/erts/emulator/beam/code_ix.h
1c0472152306f0d81884e879d910f7250f52bff8
[ "Apache-2.0" ]
permissive
erlang/otp
7c6e88ca955bd6a3ede1530154c80e8ce449a370
334589af62a8db25a81afba2ecc50f33ff69ddb8
refs/heads/master
2023-08-30T23:37:28.061328
2023-08-30T04:20:48
2023-08-30T04:20:48
374,927
9,920
3,018
Apache-2.0
2023-09-14T10:37:26
2009-11-16T17:17:57
Erlang
UTF-8
C
false
false
11,194
h
code_ix.h
/* * %CopyrightBegin% * * Copyright Ericsson AB 2012-2023. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * %CopyrightEnd% */ /* Description: * This is the interface that facilitates changing the beam code * (load,upgrade,delete) while allowing executing Erlang processes to * access the code without any locks or other expensive memory barriers. * * The basic idea is to maintain several "logical copies" of the code. These * copies are identified by a global 'code index', an integer of 0, 1 or 2. * The code index is used as argument to code access structures like * export, module, beam_catches, beam_ranges. * * The current 'active' code index is used to access the current running * code. The 'staging' code index is used by the process that performs * a code change operation. When a code change operation completes * successfully, the staging code index becomes the new active code index. * * The third code index is not explicitly used. It can be thought of as * the "previous active" or the "next staging" index. It is needed to make * sure that we do not reuse a code index for staging until we are sure * that no executing BIFs are still referencing it. * We could get by with only two (0 and 1), but that would require that we * must wait for all schedulers to re-schedule before each code change * operation can start staging. * * Note that the 'code index' is very loosely coupled to the concept of * 'current' and 'old' module versions. You can almost say that they are * orthogonal to each other. Code index is an emulator global concept while * 'current' and 'old' is specific for each module. */ #ifndef __CODE_IX_H__ #define __CODE_IX_H__ #ifndef __SYS_H__ # ifdef HAVE_CONFIG_H # include "config.h" # endif # include "sys.h" #endif #include "beam_opcodes.h" #undef ERL_THR_PROGRESS_TSD_TYPE_ONLY #define ERL_THR_PROGRESS_TSD_TYPE_ONLY #include "erl_thr_progress.h" #undef ERL_THR_PROGRESS_TSD_TYPE_ONLY struct process; #define ERTS_NUM_CODE_IX 3 #ifdef BEAMASM #define ERTS_ADDRESSV_SIZE (ERTS_NUM_CODE_IX + 1) #define ERTS_SAVE_CALLS_CODE_IX (ERTS_ADDRESSV_SIZE - 1) #else #define ERTS_ADDRESSV_SIZE ERTS_NUM_CODE_IX #endif /* This structure lets `Export` entries and `ErlFunEntry` share dispatch code, * which greatly improves the performance of fun calls. */ typedef struct ErtsDispatchable_ { ErtsCodePtr addresses[ERTS_ADDRESSV_SIZE]; } ErtsDispatchable; typedef unsigned ErtsCodeIndex; typedef struct ErtsCodeMFA_ { Eterm module; Eterm function; byte arity; } ErtsCodeMFA; /* * The ErtsCodeInfo structure is used both in the Export entry * and in the code as the function header. */ /* If you change the size of this, you also have to update the code in ops.tab to reflect the new func_info size */ typedef struct ErtsCodeInfo_ { /* In both the JIT and interpreter, we may jump here to raise a * function_clause error. * * In addition, the JIT also stores the current breakpoint flags here. */ struct { #ifndef BEAMASM BeamInstr op; #else struct { char raise_function_clause[sizeof(BeamInstr) - 1]; char breakpoint_flag; } metadata; #endif } u; /* Trace breakpoint */ struct generic_bp *gen_bp; ErtsCodeMFA mfa; } ErtsCodeInfo; typedef struct { erts_refc_t pending_schedulers; ErtsThrPrgrLaterOp later_op; UWord size; void (*later_function)(void *); void *later_data; } ErtsCodeBarrier; /* Get the code associated with a ErtsCodeInfo ptr. */ ERTS_GLB_INLINE ErtsCodePtr erts_codeinfo_to_code(const ErtsCodeInfo *ci); /* Get the ErtsCodeInfo for from a code ptr. */ ERTS_GLB_INLINE const ErtsCodeInfo *erts_code_to_codeinfo(ErtsCodePtr I); /* Get the code associated with a ErtsCodeMFA ptr. */ ERTS_GLB_INLINE ErtsCodePtr erts_codemfa_to_code(const ErtsCodeMFA *mfa); /* Get the ErtsCodeMFA from a code ptr. */ ERTS_GLB_INLINE const ErtsCodeMFA *erts_code_to_codemfa(ErtsCodePtr I); /* Called once at emulator initialization. */ void erts_code_ix_init(void); /* Return active code index. * Is guaranteed to be valid until the calling BIF returns. * To get a consistent view of the code, only one call to erts_active_code_ix() * should be made and the returned ix reused within the same BIF call. */ ERTS_GLB_INLINE ErtsCodeIndex erts_active_code_ix(void); /* Return staging code ix. * Only used by a process performing code loading/upgrading/deleting/purging. * Code staging permission must be seized. */ ERTS_GLB_INLINE ErtsCodeIndex erts_staging_code_ix(void); /** @brief Try to seize exclusive code loading permission. That is, both * staging and modification permission. * * Main process lock (only) must be held. * System thread progress must not be blocked. * Caller must not already have the code modification or staging permissions. * Caller is suspended and *must* yield if 0 is returned. */ int erts_try_seize_code_load_permission(struct process* c_p); /** @brief Release code loading permission. Resumes any suspended waiters. */ void erts_release_code_load_permission(void); /** @brief Try to seize exclusive code staging permission. Needed for code * loading and purging. * * This is kept separate from code modification permission to allow tracing and * similar during long-running purge operations. * * * Main process lock (only) must be held. * * System thread progress must not be blocked. * * Caller is suspended and *must* yield if 0 is returned. * * Caller must not already have the code modification or staging permissions. * * That is, it is _NOT_ possible to add code modification permission when you * already have staging permission. The other way around is fine however. */ int erts_try_seize_code_stage_permission(struct process* c_p); /** @brief Release code stage permission. Resumes any suspended waiters. */ void erts_release_code_stage_permission(void); /** @brief Try to seize exclusive code modification permission. Needed for * tracing, breakpoints, and so on. * * This used to be called code_write_permission, but was renamed to break * merges of code that uses the old locking paradigm. * * * Main process lock (only) must be held. * * System thread progress must not be blocked. * * Caller is suspended and *must* yield if 0 is returned. * * Caller must not already have the code modification permission, but may * have staging permission. */ int erts_try_seize_code_mod_permission(struct process* c_p); /** @brief As \c erts_try_seize_code_mod_permission but for aux work. * * System thread progress must not be blocked. * On success return true. * On failure return false and aux work func(arg) will be scheduled when * permission is released. */ int erts_try_seize_code_mod_permission_aux(void (*func)(void *), void *arg); /** @brief Release code modification permission. Resumes any suspended * waiters. */ void erts_release_code_mod_permission(void); /* Prepare the "staging area" to be a complete copy of the active code. * * Code staging permission must have been seized. * * Must be followed by calls to either "end" and "commit" or "abort" before * code staging permission can be released. */ void erts_start_staging_code_ix(int num_new); /* End the staging. * Preceded by "start" and must be followed by "commit". */ void erts_end_staging_code_ix(void); /* Set staging code index as new active code index. * Preceded by "end". */ void erts_commit_staging_code_ix(void); /* Abort the staging. * Preceded by "start". */ void erts_abort_staging_code_ix(void); #ifdef DEBUG void erts_debug_require_code_barrier(void); void erts_debug_check_code_barrier(void); #endif /* Schedules an operation to run after thread progress _and_ all schedulers * have issued an instruction barrier. */ void erts_schedule_code_barrier(ErtsCodeBarrier *barrier, void (*later_function)(void *), void *later_data); void erts_schedule_code_barrier_cleanup(ErtsCodeBarrier *barrier, void (*later_function)(void *), void *later_data, UWord size); /* Issues a code barrier on the current thread, as well as all managed threads * when they wake up after thread progress is unblocked. * * Requires that thread progress is blocked. */ void erts_blocking_code_barrier(void); /* Helper function for the above: all managed threads should call this as soon * as thread progress is unblocked, _BEFORE_ updating thread progress. */ void erts_code_ix_finalize_wait(void); #ifdef ERTS_ENABLE_LOCK_CHECK int erts_has_code_load_permission(void); int erts_has_code_stage_permission(void); int erts_has_code_mod_permission(void); #endif /* module/function/arity can be NIL/NIL/-1 when the MFA is pointing to some invalid code, for instance unloaded_fun. */ #define ASSERT_MFA(MFA) \ ASSERT((is_atom((MFA)->module) || is_nil((MFA)->module)) && \ (is_atom((MFA)->function) || is_nil((MFA)->function)) && \ (((MFA)->arity >= 0 && (MFA)->arity < 1024) || (MFA)->arity == -1)) extern erts_atomic32_t the_active_code_index; extern erts_atomic32_t the_staging_code_index; #if ERTS_GLB_INLINE_INCL_FUNC_DEF ERTS_GLB_INLINE ErtsCodePtr erts_codeinfo_to_code(const ErtsCodeInfo *ci) { #ifndef BEAMASM ASSERT(BeamIsOpCode(ci->u.op, op_i_func_info_IaaI) || !ci->u.op); #endif ASSERT_MFA(&ci->mfa); return (ErtsCodePtr)&ci[1]; } ERTS_GLB_INLINE const ErtsCodeInfo *erts_code_to_codeinfo(ErtsCodePtr I) { const ErtsCodeInfo *ci = &((const ErtsCodeInfo *)I)[-1]; #ifndef BEAMASM ASSERT(BeamIsOpCode(ci->u.op, op_i_func_info_IaaI) || !ci->u.op); #endif ASSERT_MFA(&ci->mfa); return ci; } ERTS_GLB_INLINE ErtsCodePtr erts_codemfa_to_code(const ErtsCodeMFA *mfa) { ASSERT_MFA(mfa); return (ErtsCodePtr)&mfa[1]; } ERTS_GLB_INLINE const ErtsCodeMFA *erts_code_to_codemfa(ErtsCodePtr I) { const ErtsCodeMFA *mfa = &((const ErtsCodeMFA *)I)[-1]; ASSERT_MFA(mfa); return mfa; } ERTS_GLB_INLINE ErtsCodeIndex erts_active_code_ix(void) { return erts_atomic32_read_nob(&the_active_code_index); } ERTS_GLB_INLINE ErtsCodeIndex erts_staging_code_ix(void) { return erts_atomic32_read_nob(&the_staging_code_index); } #endif /* ERTS_GLB_INLINE_INCL_FUNC_DEF */ #endif /* !__CODE_IX_H__ */
69a4c9ade6444aede4cdd5aa2813f7332adf7c72
9ca6d7ee24abbf3e2de2ec9499635a31ec863bb1
/QiniuSDK/include/QNPartsUploadPerformerV2.h
70bc0855a977c00906620a5499a5548ad3f93147
[ "MIT" ]
permissive
qiniu/objc-sdk
be895a012f654f704b0781e2c600e78d5d81e2c9
c1bdb198c5aa00ff4a4e7e8d580ed587977f455d
refs/heads/master
2023-08-18T10:55:39.592753
2023-08-07T10:44:46
2023-08-07T10:44:46
24,551,801
476
249
MIT
2023-09-12T09:35:07
2014-09-28T06:14:51
Objective-C
UTF-8
C
false
false
37
h
QNPartsUploadPerformerV2.h
../Storage/QNPartsUploadPerformerV2.h
531b70493e33f3967ba3f847174fafd23e9784bd
4d0300263d28fb461f285cc2c3dfd7c51621cb4d
/platform/iphone/Corona/CoronaLuaIOS.h
44be8aaaafb0a23788a999cd9eb5d37ef3d3f65c
[ "MIT", "LicenseRef-scancode-generic-cla", "LicenseRef-scancode-free-unknown" ]
permissive
coronalabs/corona
6a108e8bfc8026e8c85e6768cdd8590b5a83bdc2
5e853b590f6857f43f4d1eb98ee2b842f67eef0d
refs/heads/master
2023-08-30T14:29:19.542726
2023-08-22T15:18:29
2023-08-22T15:18:29
163,527,358
2,487
326
MIT
2023-09-02T16:46:40
2018-12-29T17:05:15
C++
UTF-8
C
false
false
766
h
CoronaLuaIOS.h
////////////////////////////////////////////////////////////////////////////// // // This file is part of the Corona game engine. // For overview and more information on licensing please refer to README.md // Home page: https://github.com/coronalabs/corona // Contact: support@coronalabs.com // ////////////////////////////////////////////////////////////////////////////// #ifndef _CoronaLuaIOS_H__ #define _CoronaLuaIOS_H__ #include "CoronaMacros.h" #include "CoronaLuaObjCHelper.h" struct lua_State; // ---------------------------------------------------------------------------- CORONA_API int CoronaLuaPushImage( lua_State *L, UIImage *image ); // ---------------------------------------------------------------------------- #endif // _CoronaLuaIOS_H__
c215578da8aa6aea52f237203150a513b32a73ff
4cf3ee2c90e6ad1cea9cdba1b1e76224eee2ac4d
/apps/menus/audiohw_eq_menu.c
06ab32c151f650806447dfe9cd74ac8615576295
[]
no_license
Rockbox/rockbox
36f73fc2660f3edb32dc07db26c5f9b88851975f
67c4231e34cd8147963a054c44a715f3413fb2e3
refs/heads/master
2021-09-15T22:10:00.710240
2021-08-29T12:19:02
2021-09-12T17:35:35
3,184,247
394
157
null
2021-09-05T11:00:28
2012-01-15T15:37:35
C
UTF-8
C
false
false
9,829
c
audiohw_eq_menu.c
/*************************************************************************** * __________ __ ___. * Open \______ \ ____ ____ | | _\_ |__ _______ ___ * Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ / * Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < < * Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \ * \/ \/ \/ \/ \/ * $Id$ * * Copyright (C) 2010 Michael Sevakis * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or (at your option) any later version. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * ****************************************************************************/ #include <stdio.h> #include "config.h" #include "sound.h" #include "settings.h" #include "lang.h" #include "menu.h" #include "talk.h" #define HW_EQ_IDX(band, setting) ((void *)(((setting) << 8) | (band))) #define HW_EQ_IDX_BAND(data) ((uint8_t)(uintptr_t)(data)) #define HW_EQ_IDX_SETTING(data) ((uint8_t)((uintptr_t)(data) >> 8)) static unsigned short hw_eq_setting_lang_ids[AUDIOHW_EQ_SETTING_NUM] = { LANG_HW_EQ_GAIN, #ifdef AUDIOHW_HAVE_EQ_FREQUENCY LANG_HW_EQ_FREQUENCY, #endif #ifdef AUDIOHW_HAVE_EQ_WIDTH LANG_HW_EQ_WIDTH, #endif }; static char * hw_eq_get_name(int selected_item, void * data, char *buffer, size_t buffer_len) { snprintf(buffer, buffer_len, str(hw_eq_setting_lang_ids[HW_EQ_IDX_SETTING(data)]), HW_EQ_IDX_BAND(data) + 1); return buffer; (void)selected_item; } static int hw_eq_speak_item(int selected_item, void * data) { talk_id(hw_eq_setting_lang_ids[HW_EQ_IDX_SETTING(data)], false); talk_number(HW_EQ_IDX_BAND(data) + 1, true); return 0; (void)selected_item; } static int hw_eq_do_band_setting(void *param) { int band = HW_EQ_IDX_BAND(param); int setting = HW_EQ_IDX_SETTING(param); char desc[MAX_PATH]; struct menu_callback_with_desc cbwdesc = { .menu_callback = NULL, .desc = hw_eq_get_name(0, param, desc, sizeof(desc)), .icon_id = Icon_NOICON }; struct menu_item_ex item = { .flags = MT_SETTING_W_TEXT | MENU_HAS_DESC, { .variable = (void*)(&global_settings.hw_eq_bands[band].gain + setting) }, { .callback_and_desc = &cbwdesc } }; do_setting_from_menu(&item, NULL); return 0; } MENUITEM_FUNCTION_DYNTEXT(hw_eq_band1_gain, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND1, AUDIOHW_EQ_GAIN), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND1, AUDIOHW_EQ_GAIN), NULL, Icon_Menu_setting); #ifdef AUDIOHW_HAVE_EQ_BAND1_FREQUENCY MENUITEM_FUNCTION_DYNTEXT(hw_eq_band1_frequency, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND1, AUDIOHW_EQ_FREQUENCY), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND1, AUDIOHW_EQ_FREQUENCY), NULL, Icon_NOICON); #endif #ifdef AUDIOHW_HAVE_EQ_BAND2 MENUITEM_FUNCTION_DYNTEXT(hw_eq_band2_gain, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND2, AUDIOHW_EQ_GAIN), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND2, AUDIOHW_EQ_GAIN), NULL, Icon_Menu_setting); #ifdef AUDIOHW_HAVE_EQ_BAND2_FREQUENCY MENUITEM_FUNCTION_DYNTEXT(hw_eq_band2_frequency, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND2, AUDIOHW_EQ_FREQUENCY), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND2, AUDIOHW_EQ_FREQUENCY), NULL, Icon_NOICON); #endif #ifdef AUDIOHW_HAVE_EQ_BAND2_WIDTH MENUITEM_FUNCTION_DYNTEXT(hw_eq_band2_width, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND2, AUDIOHW_EQ_WIDTH), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND2, AUDIOHW_EQ_WIDTH), NULL, Icon_NOICON); #endif #endif /* AUDIOHW_HAVE_EQ_BAND2 */ #ifdef AUDIOHW_HAVE_EQ_BAND3 MENUITEM_FUNCTION_DYNTEXT(hw_eq_band3_gain, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND3, AUDIOHW_EQ_GAIN), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND3, AUDIOHW_EQ_GAIN), NULL, Icon_Menu_setting); #ifdef AUDIOHW_HAVE_EQ_BAND3_FREQUENCY MENUITEM_FUNCTION_DYNTEXT(hw_eq_band3_frequency, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND3, AUDIOHW_EQ_FREQUENCY), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND3, AUDIOHW_EQ_FREQUENCY), NULL, Icon_NOICON); #endif #ifdef AUDIOHW_HAVE_EQ_BAND3_WIDTH MENUITEM_FUNCTION_DYNTEXT(hw_eq_band3_width, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND3, AUDIOHW_EQ_WIDTH), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND3, AUDIOHW_EQ_WIDTH), NULL, Icon_NOICON); #endif #endif /* AUDIOHW_HAVE_EQ_BAND3 */ #ifdef AUDIOHW_HAVE_EQ_BAND4 MENUITEM_FUNCTION_DYNTEXT(hw_eq_band4_gain, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND4, AUDIOHW_EQ_GAIN), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND4, AUDIOHW_EQ_GAIN), NULL, Icon_Menu_setting); #ifdef AUDIOHW_HAVE_EQ_BAND4_FREQUENCY MENUITEM_FUNCTION_DYNTEXT(hw_eq_band4_frequency, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND4, AUDIOHW_EQ_FREQUENCY), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND4, AUDIOHW_EQ_FREQUENCY), NULL, Icon_NOICON); #endif #ifdef AUDIOHW_HAVE_EQ_BAND4_WIDTH MENUITEM_FUNCTION_DYNTEXT(hw_eq_band4_width, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND4, AUDIOHW_EQ_WIDTH), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND4, AUDIOHW_EQ_WIDTH), NULL, Icon_NOICON); #endif #endif /* AUDIOHW_HAVE_EQ_BAND4 */ #ifdef AUDIOHW_HAVE_EQ_BAND5 MENUITEM_FUNCTION_DYNTEXT(hw_eq_band5_gain, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND5, AUDIOHW_EQ_GAIN), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND5, AUDIOHW_EQ_GAIN), NULL, Icon_Menu_setting); #ifdef AUDIOHW_HAVE_EQ_BAND5_FREQUENCY MENUITEM_FUNCTION_DYNTEXT(hw_eq_band5_frequency, MENU_FUNC_USEPARAM, hw_eq_do_band_setting, HW_EQ_IDX(AUDIOHW_EQ_BAND5, AUDIOHW_EQ_FREQUENCY), hw_eq_get_name, hw_eq_speak_item, HW_EQ_IDX(AUDIOHW_EQ_BAND5, AUDIOHW_EQ_FREQUENCY), NULL, Icon_NOICON); #endif #endif /* AUDIOHW_HAVE_EQ_BAND5 */ /* Submenu for multiple "tone controls". Gain + all advanced settings. */ MAKE_MENU(hardware_eq_tone_controls_advanced, ID2P(LANG_HW_EQ_TONE_CONTROLS_ADVANCED), NULL, Icon_NOICON ,&hw_eq_band1_gain #ifdef AUDIOHW_HAVE_EQ_BAND1_FREQUENCY ,&hw_eq_band1_frequency #endif #ifdef AUDIOHW_HAVE_EQ_BAND2 ,&hw_eq_band2_gain #ifdef AUDIOHW_HAVE_EQ_BAND2_FREQUENCY ,&hw_eq_band2_frequency #endif #ifdef AUDIOHW_HAVE_EQ_BAND2_WIDTH ,&hw_eq_band2_width #endif #endif /* AUDIOHW_HAVE_EQ_BAND2 */ #ifdef AUDIOHW_HAVE_EQ_BAND3 ,&hw_eq_band3_gain #ifdef AUDIOHW_HAVE_EQ_BAND3_FREQUENCY ,&hw_eq_band3_frequency #endif #ifdef AUDIOHW_HAVE_EQ_BAND3_WIDTH ,&hw_eq_band3_width #endif #endif /* AUDIOHW_HAVE_EQ_BAND3 */ #ifdef AUDIOHW_HAVE_EQ_BAND4 ,&hw_eq_band4_gain #ifdef AUDIOHW_HAVE_EQ_BAND4_FREQUENCY ,&hw_eq_band4_frequency #endif #ifdef AUDIOHW_HAVE_EQ_BAND4_WIDTH ,&hw_eq_band4_width #endif #endif /* AUDIOHW_HAVE_EQ_BAND4 */ #ifdef AUDIOHW_HAVE_EQ_BAND5 ,&hw_eq_band5_gain #ifdef AUDIOHW_HAVE_EQ_BAND5_FREQUENCY ,&hw_eq_band5_frequency #endif #endif /* AUDIOHW_HAVE_EQ_BAND5 */ ); /* Shows only the gains + advanced settings submenu */ MAKE_MENU(audiohw_eq_tone_controls, ID2P(LANG_HW_EQ_TONE_CONTROLS), NULL, Icon_NOICON ,&hw_eq_band1_gain #ifdef AUDIOHW_HAVE_EQ_BAND2 ,&hw_eq_band2_gain #endif #ifdef AUDIOHW_HAVE_EQ_BAND3 ,&hw_eq_band3_gain #endif #ifdef AUDIOHW_HAVE_EQ_BAND4 ,&hw_eq_band4_gain #endif #ifdef AUDIOHW_HAVE_EQ_BAND5 ,&hw_eq_band5_gain #endif ,&hardware_eq_tone_controls_advanced );
d113d6b3a8b7869a6994aab8bae4244b30f5dec0
0ab34cafb4fce823bdb64588375a5e0320c4d5da
/src/profiler/telemeh.h
4be4a335db51f5da77a8c0934eb38d13228ec3d9
[ "Artistic-2.0", "MIT", "BSD-3-Clause", "LicenseRef-scancode-public-domain" ]
permissive
MoarVM/MoarVM
00eb8de04ef3eb43d8dd108a016a5fbd644f7cb7
2f8234c222dea886da28a9e369e34f3cff18ad8a
refs/heads/main
2023-08-24T03:30:58.906341
2023-08-23T03:28:20
2023-08-23T03:28:20
10,411,154
616
228
NOASSERTION
2023-08-23T03:28:33
2013-05-31T19:02:30
C
UTF-8
C
false
false
653
h
telemeh.h
#include "stdint.h" MVM_PUBLIC void MVM_telemetry_timestamp(MVMThreadContext *threadID, const char *description); MVM_PUBLIC unsigned int MVM_telemetry_interval_start(MVMThreadContext *threadID, const char *description); MVM_PUBLIC void MVM_telemetry_interval_stop(MVMThreadContext *threadID, int intervalID, const char *description); MVM_PUBLIC void MVM_telemetry_interval_annotate(uintptr_t subject, int intervalID, const char *description); MVM_PUBLIC void MVM_telemetry_interval_annotate_dynamic(uintptr_t subject, int intervalID, char *description); MVM_PUBLIC void MVM_telemetry_init(FILE *outfile); MVM_PUBLIC void MVM_telemetry_finish(void);
cfbe5d8295c0806a923a7b3201b53adf2c65258a
fdbb74a95924e2677466614f6ab6e2bb13b2a95a
/libc/thread/pthread_setname_np.c
b7b30bb073aa5c2204f3d1bfaa8c0b4826b430c0
[ "ISC" ]
permissive
jart/cosmopolitan
fb11b5658939023977060a7c6c71a74093d9cb44
0d748ad58e1063dd1f8560f18a0c75293b9415b7
refs/heads/master
2023-09-06T09:17:29.303607
2023-09-02T03:49:13
2023-09-02T03:50:18
272,457,606
11,887
435
ISC
2023-09-14T17:47:58
2020-06-15T14:16:13
C
UTF-8
C
false
false
4,691
c
pthread_setname_np.c
/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│ │vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi│ ╞══════════════════════════════════════════════════════════════════════════════╡ │ Copyright 2022 Justine Alexandra Roberts Tunney │ │ │ │ Permission to use, copy, modify, and/or distribute this software for │ │ any purpose with or without fee is hereby granted, provided that the │ │ above copyright notice and this permission notice appear in all copies. │ │ │ │ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL │ │ WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED │ │ WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE │ │ AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL │ │ DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR │ │ PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER │ │ TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR │ │ PERFORMANCE OF THIS SOFTWARE. │ ╚─────────────────────────────────────────────────────────────────────────────*/ #include "libc/calls/blockcancel.internal.h" #include "libc/calls/calls.h" #include "libc/calls/syscall-sysv.internal.h" #include "libc/dce.h" #include "libc/errno.h" #include "libc/fmt/itoa.h" #include "libc/intrin/asan.internal.h" #include "libc/intrin/atomic.h" #include "libc/str/str.h" #include "libc/sysv/consts/at.h" #include "libc/sysv/consts/o.h" #include "libc/sysv/consts/pr.h" #include "libc/thread/posixthread.internal.h" static errno_t pthread_setname_impl(pthread_t thread, const char *name) { char path[128], *p; int e, fd, rc, tid, len; if ((rc = pthread_getunique_np(thread, &tid))) return rc; len = strlen(name); if (IsLinux()) { e = errno; if (tid == gettid()) { if (prctl(PR_SET_NAME, name) == -1) { rc = errno; errno = e; return rc; } } else { p = path; p = stpcpy(p, "/proc/self/task/"); p = FormatUint32(p, tid); p = stpcpy(p, "/comm"); if ((fd = sys_openat(AT_FDCWD, path, O_WRONLY | O_CLOEXEC, 0)) == -1) { rc = errno; errno = e; return rc; } rc = sys_write(fd, name, len); rc |= sys_close(fd); if (rc == -1) { rc = errno; errno = e; return rc; } } if (len > 15) { // linux is documented as truncating here. we still set the name // since the limit might be raised in the future checking return // value of this function is a bummer. Grep it for TASK_COMM_LEN return ERANGE; } return 0; } else if (IsFreebsd() || IsNetbsd() || IsOpenbsd()) { int ax; if (IsFreebsd()) { ax = 464; // thr_set_name } else if (IsNetbsd()) { ax = 323; // _lwp_setname } else { ax = 143; // sys_setthrname } asm volatile("syscall" : "+a"(ax), "+D"(tid), "+S"(name) : /* no inputs */ : "rcx", "rdx", "r8", "r9", "r10", "r11", "memory"); return ax; } else { return ENOSYS; } } /** * Registers custom name of thread with system, e.g. * * void *worker(void *arg) { * pthread_setname_np(pthread_self(), "justine"); * pause(); * return 0; * } * * int main(int argc, char *argv[]) { * pthread_t id; * pthread_create(&id, 0, worker, 0); * pthread_join(id, 0); * } * * ProTip: The `htop` software is good at displaying thread names. * * @return 0 on success, or errno on error * @raise ERANGE if length of `name` exceeded system limit, in which * case the name may have still been set with os using truncation * @raise ENOSYS on MacOS, and Windows * @see pthread_getname_np() */ errno_t pthread_setname_np(pthread_t thread, const char *name) { errno_t rc; BLOCK_CANCELLATIONS; rc = pthread_setname_impl(thread, name); ALLOW_CANCELLATIONS; return rc; }
dec12fb7c4fd17dc6d08203f62cbceea23aeda53
e65a4dbfbfb0e54e59787ba7741efee12f7687f3
/graphics/igt-gpu-tools/files/patch-lib_i915_perf.c
91b6cf3bde11d277d5ed182b94967e3c613f5c4d
[ "BSD-2-Clause" ]
permissive
freebsd/freebsd-ports
86f2e89d43913412c4f6b2be3e255bc0945eac12
605a2983f245ac63f5420e023e7dce56898ad801
refs/heads/main
2023-08-30T21:46:28.720924
2023-08-30T19:33:44
2023-08-30T19:33:44
1,803,961
916
918
NOASSERTION
2023-09-08T04:06:26
2011-05-26T11:15:35
null
UTF-8
C
false
false
255
c
patch-lib_i915_perf.c
--- lib/i915/perf.c.orig 2022-08-31 20:00:01 UTC +++ lib/i915/perf.c @@ -29,7 +29,9 @@ #include <fcntl.h> #include <sys/ioctl.h> #include <sys/stat.h> +#ifdef __linux__ #include <sys/sysmacros.h> +#endif #include <sys/types.h> #include <unistd.h>
ebeb3d00fce078e9fe237e1bf8d0b7056af7bcd2
aad6ac6c6040370665cec6043130442b08d645ef
/openvkl/include/openvkl/VKLFormat.h
0babe0f0783f20919503805a2e238813af5acc81
[ "Apache-2.0" ]
permissive
openvkl/openvkl
c6847771221427116acf689151e2f6332b926233
fac6c96b24ae73941716b7368ffc289eb9c47532
refs/heads/master
2023-07-08T06:43:36.202995
2023-02-28T18:14:51
2023-02-28T18:14:51
211,395,280
177
19
Apache-2.0
2023-03-09T10:00:35
2019-09-27T20:17:19
C++
UTF-8
C
false
false
745
h
VKLFormat.h
// Copyright 2020 Intel Corporation // SPDX-License-Identifier: Apache-2.0 #pragma once #include "ispc_cpp_interop.h" // ========================================================================== // // An enum for data format constants. // This value determines how voxel data buffers are interpreted by VKL. // ========================================================================== // #if __cplusplus > 201103L enum VKLFormat : vkl_uint32 #else enum VKLFormat #endif { // The node has no spatial variation. VKL_FORMAT_TILE = 0, // The buffer contains a dense grid of voxels. // The suffix _ZYX indicates z-major ordering, i.e., the z-coordinate // advances most quickly. VKL_FORMAT_DENSE_ZYX, VKL_FORMAT_INVALID = 100 };
d545522c0b46f84f311a113089575fec88ef7347
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/linux-a64/arch/sh/include/asm/clock.h
0390a07e7e3bd0e6374df1fd2efa79bb79d1d24d
[ "Linux-syscall-note", "GPL-2.0-only", "GPL-1.0-or-later", "LicenseRef-scancode-free-unknown", "Apache-2.0" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
397
h
clock.h
#ifndef __ASM_SH_CLOCK_H #define __ASM_SH_CLOCK_H #include <linux/sh_clk.h> /* Should be defined by processor-specific code */ void __deprecated arch_init_clk_ops(struct sh_clk_ops **, int type); int __init arch_clk_init(void); /* arch/sh/kernel/cpu/clock-cpg.c */ int __init __deprecated cpg_clk_init(void); /* arch/sh/kernel/cpu/clock.c */ int clk_init(void); #endif /* __ASM_SH_CLOCK_H */
9290eb1b31673f6cf5a8c1e598b5560667d31e89
88ae8695987ada722184307301e221e1ba3cc2fa
/third_party/ffmpeg/libavcodec/dvbsubdec.c
bcc607d1d7c0f0dcfebb2298e9da4c872dfe73bb
[ "BSD-3-Clause", "Apache-2.0", "LGPL-2.0-or-later", "MIT", "GPL-1.0-or-later", "LGPL-2.1-only", "LGPL-3.0-only", "GPL-2.0-only", "LGPL-2.1-or-later", "GPL-3.0-or-later", "LGPL-3.0-or-later", "IJG", "LicenseRef-scancode-other-permissive", "GPL-2.0-or-later", "GPL-3.0-only" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C
false
false
46,706
c
dvbsubdec.c
/* * DVB subtitle decoding * Copyright (c) 2005 Ian Caulfield * * 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 */ #include "avcodec.h" #include "get_bits.h" #include "bytestream.h" #include "codec_internal.h" #include "decode.h" #include "libavutil/colorspace.h" #include "libavutil/imgutils.h" #include "libavutil/opt.h" #include "libavutil/thread.h" #define DVBSUB_PAGE_SEGMENT 0x10 #define DVBSUB_REGION_SEGMENT 0x11 #define DVBSUB_CLUT_SEGMENT 0x12 #define DVBSUB_OBJECT_SEGMENT 0x13 #define DVBSUB_DISPLAYDEFINITION_SEGMENT 0x14 #define DVBSUB_DISPLAY_SEGMENT 0x80 #define cm (ff_crop_tab + MAX_NEG_CROP) #define RGBA(r,g,b,a) (((unsigned)(a) << 24) | ((r) << 16) | ((g) << 8) | (b)) typedef struct DVBSubCLUT { int id; int version; uint32_t clut4[4]; uint32_t clut16[16]; uint32_t clut256[256]; struct DVBSubCLUT *next; } DVBSubCLUT; static DVBSubCLUT default_clut; typedef struct DVBSubObjectDisplay { int object_id; int region_id; int x_pos; int y_pos; int fgcolor; int bgcolor; struct DVBSubObjectDisplay *region_list_next; struct DVBSubObjectDisplay *object_list_next; } DVBSubObjectDisplay; typedef struct DVBSubObject { int id; int version; int type; DVBSubObjectDisplay *display_list; struct DVBSubObject *next; } DVBSubObject; typedef struct DVBSubRegionDisplay { int region_id; int x_pos; int y_pos; struct DVBSubRegionDisplay *next; } DVBSubRegionDisplay; typedef struct DVBSubRegion { int id; int version; int width; int height; int depth; int clut; int bgcolor; uint8_t computed_clut[4*256]; int has_computed_clut; uint8_t *pbuf; int buf_size; int dirty; DVBSubObjectDisplay *display_list; struct DVBSubRegion *next; } DVBSubRegion; typedef struct DVBSubDisplayDefinition { int version; int x; int y; int width; int height; } DVBSubDisplayDefinition; typedef struct DVBSubContext { AVClass *class; int composition_id; int ancillary_id; int version; int time_out; int compute_edt; /**< if 1 end display time calculated using pts if 0 (Default) calculated using time out */ int compute_clut; int clut_count2[257][256]; int substream; int64_t prev_start; DVBSubRegion *region_list; DVBSubCLUT *clut_list; DVBSubObject *object_list; DVBSubRegionDisplay *display_list; DVBSubDisplayDefinition *display_definition; } DVBSubContext; static DVBSubObject* get_object(DVBSubContext *ctx, int object_id) { DVBSubObject *ptr = ctx->object_list; while (ptr && ptr->id != object_id) { ptr = ptr->next; } return ptr; } static DVBSubCLUT* get_clut(DVBSubContext *ctx, int clut_id) { DVBSubCLUT *ptr = ctx->clut_list; while (ptr && ptr->id != clut_id) { ptr = ptr->next; } return ptr; } static DVBSubRegion* get_region(DVBSubContext *ctx, int region_id) { DVBSubRegion *ptr = ctx->region_list; while (ptr && ptr->id != region_id) { ptr = ptr->next; } return ptr; } static void delete_region_display_list(DVBSubContext *ctx, DVBSubRegion *region) { DVBSubObject *object, *obj2, **obj2_ptr; DVBSubObjectDisplay *display, *obj_disp, **obj_disp_ptr; while (region->display_list) { display = region->display_list; object = get_object(ctx, display->object_id); if (object) { obj_disp_ptr = &object->display_list; obj_disp = *obj_disp_ptr; while (obj_disp && obj_disp != display) { obj_disp_ptr = &obj_disp->object_list_next; obj_disp = *obj_disp_ptr; } if (obj_disp) { *obj_disp_ptr = obj_disp->object_list_next; if (!object->display_list) { obj2_ptr = &ctx->object_list; obj2 = *obj2_ptr; while (obj2 != object) { av_assert0(obj2); obj2_ptr = &obj2->next; obj2 = *obj2_ptr; } *obj2_ptr = obj2->next; av_freep(&obj2); } } } region->display_list = display->region_list_next; av_freep(&display); } } static void delete_cluts(DVBSubContext *ctx) { while (ctx->clut_list) { DVBSubCLUT *clut = ctx->clut_list; ctx->clut_list = clut->next; av_freep(&clut); } } static void delete_objects(DVBSubContext *ctx) { while (ctx->object_list) { DVBSubObject *object = ctx->object_list; ctx->object_list = object->next; av_freep(&object); } } static void delete_regions(DVBSubContext *ctx) { while (ctx->region_list) { DVBSubRegion *region = ctx->region_list; ctx->region_list = region->next; delete_region_display_list(ctx, region); av_freep(&region->pbuf); av_freep(&region); } } static av_cold void init_default_clut(void) { int i, r, g, b, a = 0; default_clut.id = -1; default_clut.next = NULL; default_clut.clut4[0] = RGBA( 0, 0, 0, 0); default_clut.clut4[1] = RGBA(255, 255, 255, 255); default_clut.clut4[2] = RGBA( 0, 0, 0, 255); default_clut.clut4[3] = RGBA(127, 127, 127, 255); default_clut.clut16[0] = RGBA( 0, 0, 0, 0); for (i = 1; i < 16; i++) { if (i < 8) { r = (i & 1) ? 255 : 0; g = (i & 2) ? 255 : 0; b = (i & 4) ? 255 : 0; } else { r = (i & 1) ? 127 : 0; g = (i & 2) ? 127 : 0; b = (i & 4) ? 127 : 0; } default_clut.clut16[i] = RGBA(r, g, b, 255); } default_clut.clut256[0] = RGBA( 0, 0, 0, 0); for (i = 1; i < 256; i++) { if (i < 8) { r = (i & 1) ? 255 : 0; g = (i & 2) ? 255 : 0; b = (i & 4) ? 255 : 0; a = 63; } else { switch (i & 0x88) { case 0x00: r = ((i & 1) ? 85 : 0) + ((i & 0x10) ? 170 : 0); g = ((i & 2) ? 85 : 0) + ((i & 0x20) ? 170 : 0); b = ((i & 4) ? 85 : 0) + ((i & 0x40) ? 170 : 0); a = 255; break; case 0x08: r = ((i & 1) ? 85 : 0) + ((i & 0x10) ? 170 : 0); g = ((i & 2) ? 85 : 0) + ((i & 0x20) ? 170 : 0); b = ((i & 4) ? 85 : 0) + ((i & 0x40) ? 170 : 0); a = 127; break; case 0x80: r = 127 + ((i & 1) ? 43 : 0) + ((i & 0x10) ? 85 : 0); g = 127 + ((i & 2) ? 43 : 0) + ((i & 0x20) ? 85 : 0); b = 127 + ((i & 4) ? 43 : 0) + ((i & 0x40) ? 85 : 0); a = 255; break; case 0x88: r = ((i & 1) ? 43 : 0) + ((i & 0x10) ? 85 : 0); g = ((i & 2) ? 43 : 0) + ((i & 0x20) ? 85 : 0); b = ((i & 4) ? 43 : 0) + ((i & 0x40) ? 85 : 0); a = 255; break; } } default_clut.clut256[i] = RGBA(r, g, b, a); } } static av_cold int dvbsub_init_decoder(AVCodecContext *avctx) { static AVOnce init_static_once = AV_ONCE_INIT; DVBSubContext *ctx = avctx->priv_data; if (ctx->substream < 0) { ctx->composition_id = -1; ctx->ancillary_id = -1; } else if (!avctx->extradata || (avctx->extradata_size < 4) || ((avctx->extradata_size % 5 != 0) && (avctx->extradata_size != 4))) { av_log(avctx, AV_LOG_WARNING, "Invalid DVB subtitles stream extradata!\n"); ctx->composition_id = -1; ctx->ancillary_id = -1; } else { if (avctx->extradata_size > 5*ctx->substream + 2) { ctx->composition_id = AV_RB16(avctx->extradata + 5*ctx->substream); ctx->ancillary_id = AV_RB16(avctx->extradata + 5*ctx->substream + 2); } else { av_log(avctx, AV_LOG_WARNING, "Selected DVB subtitles sub-stream %d is not available\n", ctx->substream); ctx->composition_id = AV_RB16(avctx->extradata); ctx->ancillary_id = AV_RB16(avctx->extradata + 2); } } ctx->version = -1; ctx->prev_start = AV_NOPTS_VALUE; ff_thread_once(&init_static_once, init_default_clut); return 0; } static av_cold int dvbsub_close_decoder(AVCodecContext *avctx) { DVBSubContext *ctx = avctx->priv_data; DVBSubRegionDisplay *display; delete_regions(ctx); delete_objects(ctx); delete_cluts(ctx); av_freep(&ctx->display_definition); while (ctx->display_list) { display = ctx->display_list; ctx->display_list = display->next; av_freep(&display); } return 0; } static int dvbsub_read_2bit_string(AVCodecContext *avctx, uint8_t *destbuf, int dbuf_len, const uint8_t **srcbuf, int buf_size, int non_mod, uint8_t *map_table, int x_pos) { GetBitContext gb; int bits; int run_length; int pixels_read = x_pos; init_get_bits(&gb, *srcbuf, buf_size << 3); destbuf += x_pos; while (get_bits_count(&gb) < buf_size << 3 && pixels_read < dbuf_len) { bits = get_bits(&gb, 2); if (bits) { if (non_mod != 1 || bits != 1) { if (map_table) *destbuf++ = map_table[bits]; else *destbuf++ = bits; } pixels_read++; } else { bits = get_bits1(&gb); if (bits == 1) { run_length = get_bits(&gb, 3) + 3; bits = get_bits(&gb, 2); if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } else { bits = get_bits1(&gb); if (bits == 0) { bits = get_bits(&gb, 2); if (bits == 2) { run_length = get_bits(&gb, 4) + 12; bits = get_bits(&gb, 2); if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } else if (bits == 3) { run_length = get_bits(&gb, 8) + 29; bits = get_bits(&gb, 2); if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } else if (bits == 1) { if (map_table) bits = map_table[0]; else bits = 0; run_length = 2; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } else { (*srcbuf) += (get_bits_count(&gb) + 7) >> 3; return pixels_read; } } else { if (map_table) bits = map_table[0]; else bits = 0; *destbuf++ = bits; pixels_read++; } } } } if (get_bits(&gb, 6)) av_log(avctx, AV_LOG_ERROR, "line overflow\n"); (*srcbuf) += (get_bits_count(&gb) + 7) >> 3; return pixels_read; } static int dvbsub_read_4bit_string(AVCodecContext *avctx, uint8_t *destbuf, int dbuf_len, const uint8_t **srcbuf, int buf_size, int non_mod, uint8_t *map_table, int x_pos) { GetBitContext gb; int bits; int run_length; int pixels_read = x_pos; init_get_bits(&gb, *srcbuf, buf_size << 3); destbuf += x_pos; while (get_bits_count(&gb) < buf_size << 3 && pixels_read < dbuf_len) { bits = get_bits(&gb, 4); if (bits) { if (non_mod != 1 || bits != 1) { if (map_table) *destbuf++ = map_table[bits]; else *destbuf++ = bits; } pixels_read++; } else { bits = get_bits1(&gb); if (bits == 0) { run_length = get_bits(&gb, 3); if (run_length == 0) { (*srcbuf) += (get_bits_count(&gb) + 7) >> 3; return pixels_read; } run_length += 2; if (map_table) bits = map_table[0]; else bits = 0; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } else { bits = get_bits1(&gb); if (bits == 0) { run_length = get_bits(&gb, 2) + 4; bits = get_bits(&gb, 4); if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } else { bits = get_bits(&gb, 2); if (bits == 2) { run_length = get_bits(&gb, 4) + 9; bits = get_bits(&gb, 4); if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } else if (bits == 3) { run_length = get_bits(&gb, 8) + 25; bits = get_bits(&gb, 4); if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } else if (bits == 1) { if (map_table) bits = map_table[0]; else bits = 0; run_length = 2; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } else { if (map_table) bits = map_table[0]; else bits = 0; *destbuf++ = bits; pixels_read ++; } } } } } if (get_bits(&gb, 8)) av_log(avctx, AV_LOG_ERROR, "line overflow\n"); (*srcbuf) += (get_bits_count(&gb) + 7) >> 3; return pixels_read; } static int dvbsub_read_8bit_string(AVCodecContext *avctx, uint8_t *destbuf, int dbuf_len, const uint8_t **srcbuf, int buf_size, int non_mod, uint8_t *map_table, int x_pos) { const uint8_t *sbuf_end = (*srcbuf) + buf_size; int bits; int run_length; int pixels_read = x_pos; destbuf += x_pos; while (*srcbuf < sbuf_end && pixels_read < dbuf_len) { bits = *(*srcbuf)++; if (bits) { if (non_mod != 1 || bits != 1) { if (map_table) *destbuf++ = map_table[bits]; else *destbuf++ = bits; } pixels_read++; } else { bits = *(*srcbuf)++; run_length = bits & 0x7f; if ((bits & 0x80) == 0) { if (run_length == 0) { return pixels_read; } bits = 0; } else { bits = *(*srcbuf)++; } if (non_mod == 1 && bits == 1) pixels_read += run_length; else { if (map_table) bits = map_table[bits]; while (run_length-- > 0 && pixels_read < dbuf_len) { *destbuf++ = bits; pixels_read++; } } } } if (*(*srcbuf)++) av_log(avctx, AV_LOG_ERROR, "line overflow\n"); return pixels_read; } static void compute_default_clut(DVBSubContext *ctx, uint8_t *clut, AVSubtitleRect *rect, int w, int h) { uint8_t list[256] = {0}; uint8_t list_inv[256]; int counttab[256] = {0}; int (*counttab2)[256] = ctx->clut_count2; int count, i, x, y; ptrdiff_t stride = rect->linesize[0]; memset(ctx->clut_count2, 0 , sizeof(ctx->clut_count2)); #define V(x,y) rect->data[0][(x) + (y)*stride] for (y = 0; y<h; y++) { for (x = 0; x<w; x++) { int v = V(x,y) + 1; int vl = x ? V(x-1,y) + 1 : 0; int vr = x+1<w ? V(x+1,y) + 1 : 0; int vt = y ? V(x,y-1) + 1 : 0; int vb = y+1<h ? V(x,y+1) + 1 : 0; counttab[v-1] += !!((v!=vl) + (v!=vr) + (v!=vt) + (v!=vb)); counttab2[vl][v-1] ++; counttab2[vr][v-1] ++; counttab2[vt][v-1] ++; counttab2[vb][v-1] ++; } } #define L(x,y) list[d[(x) + (y)*stride]] for (i = 0; i<256; i++) { counttab2[i+1][i] = 0; } for (i = 0; i<256; i++) { int bestscore = 0; int bestv = 0; for (x = 0; x < 256; x++) { int scorev = 0; if (list[x]) continue; scorev += counttab2[0][x]; for (y = 0; y < 256; y++) { scorev += list[y] * counttab2[y+1][x]; } if (scorev) { int score = 1024LL*scorev / counttab[x]; if (score > bestscore) { bestscore = score; bestv = x; } } } if (!bestscore) break; list [ bestv ] = 1; list_inv[ i ] = bestv; } count = FFMAX(i - 1, 1); for (i--; i >= 0; i--) { int v = i * 255 / count; AV_WN32(clut + 4*list_inv[i], RGBA(v/2,v,v/2,v)); } } static int save_subtitle_set(AVCodecContext *avctx, AVSubtitle *sub, int *got_output) { DVBSubContext *ctx = avctx->priv_data; DVBSubRegionDisplay *display; DVBSubDisplayDefinition *display_def = ctx->display_definition; DVBSubRegion *region; AVSubtitleRect *rect; const DVBSubCLUT *clut; const uint32_t *clut_table; int i; int offset_x=0, offset_y=0; int ret = 0; if (display_def) { offset_x = display_def->x; offset_y = display_def->y; } /* Not touching AVSubtitles again*/ if (sub->num_rects) { avpriv_request_sample(ctx, "Different Version of Segment asked Twice"); return AVERROR_PATCHWELCOME; } for (display = ctx->display_list; display; display = display->next) { region = get_region(ctx, display->region_id); if (region && region->dirty) sub->num_rects++; } if (ctx->compute_edt == 0) { sub->end_display_time = ctx->time_out * 1000; *got_output = 1; } else if (ctx->prev_start != AV_NOPTS_VALUE) { sub->end_display_time = av_rescale_q((sub->pts - ctx->prev_start ), AV_TIME_BASE_Q, (AVRational){ 1, 1000 }) - 1; *got_output = 1; } if (sub->num_rects > 0) { sub->rects = av_calloc(sub->num_rects, sizeof(*sub->rects)); if (!sub->rects) { ret = AVERROR(ENOMEM); goto fail; } for (i = 0; i < sub->num_rects; i++) { sub->rects[i] = av_mallocz(sizeof(*sub->rects[i])); if (!sub->rects[i]) { ret = AVERROR(ENOMEM); goto fail; } } i = 0; for (display = ctx->display_list; display; display = display->next) { region = get_region(ctx, display->region_id); if (!region) continue; if (!region->dirty) continue; rect = sub->rects[i]; rect->x = display->x_pos + offset_x; rect->y = display->y_pos + offset_y; rect->w = region->width; rect->h = region->height; rect->nb_colors = (1 << region->depth); rect->type = SUBTITLE_BITMAP; rect->linesize[0] = region->width; clut = get_clut(ctx, region->clut); if (!clut) clut = &default_clut; switch (region->depth) { case 2: clut_table = clut->clut4; break; case 8: clut_table = clut->clut256; break; case 4: default: clut_table = clut->clut16; break; } rect->data[1] = av_mallocz(AVPALETTE_SIZE); if (!rect->data[1]) { ret = AVERROR(ENOMEM); goto fail; } memcpy(rect->data[1], clut_table, (1 << region->depth) * sizeof(*clut_table)); rect->data[0] = av_memdup(region->pbuf, region->buf_size); if (!rect->data[0]) { ret = AVERROR(ENOMEM); goto fail; } if ((clut == &default_clut && ctx->compute_clut < 0) || ctx->compute_clut == 1) { if (!region->has_computed_clut) { compute_default_clut(ctx, region->computed_clut, rect, rect->w, rect->h); region->has_computed_clut = 1; } memcpy(rect->data[1], region->computed_clut, sizeof(region->computed_clut)); } i++; } } return 0; fail: if (sub->rects) { for (i=0; i < sub->num_rects; i++) { rect = sub->rects[i]; if (rect) { av_freep(&rect->data[0]); av_freep(&rect->data[1]); } av_freep(&sub->rects[i]); } av_freep(&sub->rects); } sub->num_rects = 0; return ret; } static void dvbsub_parse_pixel_data_block(AVCodecContext *avctx, DVBSubObjectDisplay *display, const uint8_t *buf, int buf_size, int top_bottom, int non_mod) { DVBSubContext *ctx = avctx->priv_data; DVBSubRegion *region = get_region(ctx, display->region_id); const uint8_t *buf_end = buf + buf_size; uint8_t *pbuf; int x_pos, y_pos; int i; uint8_t map2to4[] = { 0x0, 0x7, 0x8, 0xf}; uint8_t map2to8[] = {0x00, 0x77, 0x88, 0xff}; uint8_t map4to8[] = {0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99, 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff}; uint8_t *map_table; #if 0 ff_dlog(avctx, "DVB pixel block size %d, %s field:\n", buf_size, top_bottom ? "bottom" : "top"); for (i = 0; i < buf_size; i++) { if (i % 16 == 0) ff_dlog(avctx, "0x%8p: ", buf+i); ff_dlog(avctx, "%02x ", buf[i]); if (i % 16 == 15) ff_dlog(avctx, "\n"); } if (i % 16) ff_dlog(avctx, "\n"); #endif if (!region) return; pbuf = region->pbuf; region->dirty = 1; x_pos = display->x_pos; y_pos = display->y_pos; y_pos += top_bottom; while (buf < buf_end) { if ((*buf!=0xf0 && x_pos >= region->width) || y_pos >= region->height) { av_log(avctx, AV_LOG_ERROR, "Invalid object location! %d-%d %d-%d %02x\n", x_pos, region->width, y_pos, region->height, *buf); return; } switch (*buf++) { case 0x10: if (region->depth == 8) map_table = map2to8; else if (region->depth == 4) map_table = map2to4; else map_table = NULL; x_pos = dvbsub_read_2bit_string(avctx, pbuf + (y_pos * region->width), region->width, &buf, buf_end - buf, non_mod, map_table, x_pos); break; case 0x11: if (region->depth < 4) { av_log(avctx, AV_LOG_ERROR, "4-bit pixel string in %d-bit region!\n", region->depth); return; } if (region->depth == 8) map_table = map4to8; else map_table = NULL; x_pos = dvbsub_read_4bit_string(avctx, pbuf + (y_pos * region->width), region->width, &buf, buf_end - buf, non_mod, map_table, x_pos); break; case 0x12: if (region->depth < 8) { av_log(avctx, AV_LOG_ERROR, "8-bit pixel string in %d-bit region!\n", region->depth); return; } x_pos = dvbsub_read_8bit_string(avctx, pbuf + (y_pos * region->width), region->width, &buf, buf_end - buf, non_mod, NULL, x_pos); break; case 0x20: map2to4[0] = (*buf) >> 4; map2to4[1] = (*buf++) & 0xf; map2to4[2] = (*buf) >> 4; map2to4[3] = (*buf++) & 0xf; break; case 0x21: for (i = 0; i < 4; i++) map2to8[i] = *buf++; break; case 0x22: for (i = 0; i < 16; i++) map4to8[i] = *buf++; break; case 0xf0: x_pos = display->x_pos; y_pos += 2; break; default: av_log(avctx, AV_LOG_INFO, "Unknown/unsupported pixel block 0x%x\n", *(buf-1)); } } if (ctx->compute_clut != -2) region->has_computed_clut = 0; } static int dvbsub_parse_object_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { DVBSubContext *ctx = avctx->priv_data; const uint8_t *buf_end = buf + buf_size; int object_id; DVBSubObject *object; DVBSubObjectDisplay *display; int top_field_len, bottom_field_len; int coding_method, non_modifying_color; object_id = AV_RB16(buf); buf += 2; object = get_object(ctx, object_id); if (!object) return AVERROR_INVALIDDATA; coding_method = ((*buf) >> 2) & 3; non_modifying_color = ((*buf++) >> 1) & 1; if (coding_method == 0) { top_field_len = AV_RB16(buf); buf += 2; bottom_field_len = AV_RB16(buf); buf += 2; if (buf + top_field_len + bottom_field_len > buf_end) { av_log(avctx, AV_LOG_ERROR, "Field data size %d+%d too large\n", top_field_len, bottom_field_len); return AVERROR_INVALIDDATA; } for (display = object->display_list; display; display = display->object_list_next) { const uint8_t *block = buf; int bfl = bottom_field_len; dvbsub_parse_pixel_data_block(avctx, display, block, top_field_len, 0, non_modifying_color); if (bottom_field_len > 0) block = buf + top_field_len; else bfl = top_field_len; dvbsub_parse_pixel_data_block(avctx, display, block, bfl, 1, non_modifying_color); } } else if (coding_method == 1) { avpriv_report_missing_feature(avctx, "coded as a string of characters"); return AVERROR_PATCHWELCOME; } else if (coding_method == 2) { avpriv_report_missing_feature(avctx, "progressive coding of pixels"); return AVERROR_PATCHWELCOME; } else { av_log(avctx, AV_LOG_ERROR, "Unknown object coding %d\n", coding_method); return AVERROR_INVALIDDATA; } return 0; } static int dvbsub_parse_clut_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { DVBSubContext *ctx = avctx->priv_data; const uint8_t *buf_end = buf + buf_size; int i, clut_id; int version; DVBSubCLUT *clut; int entry_id, depth , full_range; int y, cr, cb, alpha; int r, g, b, r_add, g_add, b_add; ff_dlog(avctx, "DVB clut packet:\n"); for (i=0; i < buf_size; i++) { ff_dlog(avctx, "%02x ", buf[i]); if (i % 16 == 15) ff_dlog(avctx, "\n"); } if (i % 16) ff_dlog(avctx, "\n"); clut_id = *buf++; version = ((*buf)>>4)&15; buf += 1; clut = get_clut(ctx, clut_id); if (!clut) { clut = av_memdup(&default_clut, sizeof(*clut)); if (!clut) return AVERROR(ENOMEM); clut->id = clut_id; clut->version = -1; clut->next = ctx->clut_list; ctx->clut_list = clut; } if (clut->version != version) { clut->version = version; while (buf + 4 < buf_end) { entry_id = *buf++; depth = (*buf) & 0xe0; if (depth == 0) { av_log(avctx, AV_LOG_ERROR, "Invalid clut depth 0x%x!\n", *buf); } full_range = (*buf++) & 1; if (full_range) { y = *buf++; cr = *buf++; cb = *buf++; alpha = *buf++; } else { y = buf[0] & 0xfc; cr = (((buf[0] & 3) << 2) | ((buf[1] >> 6) & 3)) << 4; cb = (buf[1] << 2) & 0xf0; alpha = (buf[1] << 6) & 0xc0; buf += 2; } if (y == 0) alpha = 0xff; YUV_TO_RGB1_CCIR(cb, cr); YUV_TO_RGB2_CCIR(r, g, b, y); ff_dlog(avctx, "clut %d := (%d,%d,%d,%d)\n", entry_id, r, g, b, alpha); if (!!(depth & 0x80) + !!(depth & 0x40) + !!(depth & 0x20) > 1) { ff_dlog(avctx, "More than one bit level marked: %x\n", depth); if (avctx->strict_std_compliance > FF_COMPLIANCE_NORMAL) return AVERROR_INVALIDDATA; } if (depth & 0x80 && entry_id < 4) clut->clut4[entry_id] = RGBA(r,g,b,255 - alpha); else if (depth & 0x40 && entry_id < 16) clut->clut16[entry_id] = RGBA(r,g,b,255 - alpha); else if (depth & 0x20) clut->clut256[entry_id] = RGBA(r,g,b,255 - alpha); } } return 0; } static int dvbsub_parse_region_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { DVBSubContext *ctx = avctx->priv_data; const uint8_t *buf_end = buf + buf_size; int region_id, object_id; int av_unused version; DVBSubRegion *region; DVBSubObject *object; DVBSubObjectDisplay *display; int fill; int ret; if (buf_size < 10) return AVERROR_INVALIDDATA; region_id = *buf++; region = get_region(ctx, region_id); if (!region) { region = av_mallocz(sizeof(*region)); if (!region) return AVERROR(ENOMEM); region->id = region_id; region->version = -1; region->next = ctx->region_list; ctx->region_list = region; } version = ((*buf)>>4) & 15; fill = ((*buf++) >> 3) & 1; region->width = AV_RB16(buf); buf += 2; region->height = AV_RB16(buf); buf += 2; ret = av_image_check_size2(region->width, region->height, avctx->max_pixels, AV_PIX_FMT_PAL8, 0, avctx); if (ret >= 0 && region->width * region->height * 2 > 320 * 1024 * 8) { ret = AVERROR_INVALIDDATA; av_log(avctx, AV_LOG_ERROR, "Pixel buffer memory constraint violated\n"); } if (ret < 0) { region->width= region->height= 0; return ret; } if (region->width * region->height != region->buf_size) { av_free(region->pbuf); region->buf_size = region->width * region->height; region->pbuf = av_malloc(region->buf_size); if (!region->pbuf) { region->buf_size = region->width = region->height = 0; return AVERROR(ENOMEM); } fill = 1; region->dirty = 0; } region->depth = 1 << (((*buf++) >> 2) & 7); if (region->depth < 2 || region->depth > 8) { av_log(avctx, AV_LOG_ERROR, "region depth %d is invalid\n", region->depth); region->depth= 4; } region->clut = *buf++; if (region->depth == 8) { region->bgcolor = *buf++; buf += 1; } else { buf += 1; if (region->depth == 4) region->bgcolor = (((*buf++) >> 4) & 15); else region->bgcolor = (((*buf++) >> 2) & 3); } ff_dlog(avctx, "Region %d, (%dx%d)\n", region_id, region->width, region->height); if (fill) { memset(region->pbuf, region->bgcolor, region->buf_size); ff_dlog(avctx, "Fill region (%d)\n", region->bgcolor); } delete_region_display_list(ctx, region); while (buf + 5 < buf_end) { object_id = AV_RB16(buf); buf += 2; object = get_object(ctx, object_id); if (!object) { object = av_mallocz(sizeof(*object)); if (!object) return AVERROR(ENOMEM); object->id = object_id; object->next = ctx->object_list; ctx->object_list = object; } object->type = (*buf) >> 6; display = av_mallocz(sizeof(*display)); if (!display) return AVERROR(ENOMEM); display->object_id = object_id; display->region_id = region_id; display->x_pos = AV_RB16(buf) & 0xfff; buf += 2; display->y_pos = AV_RB16(buf) & 0xfff; buf += 2; if (display->x_pos >= region->width || display->y_pos >= region->height) { av_log(avctx, AV_LOG_ERROR, "Object outside region\n"); av_free(display); return AVERROR_INVALIDDATA; } if ((object->type == 1 || object->type == 2) && buf+1 < buf_end) { display->fgcolor = *buf++; display->bgcolor = *buf++; } display->region_list_next = region->display_list; region->display_list = display; display->object_list_next = object->display_list; object->display_list = display; } return 0; } static int dvbsub_parse_page_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size, AVSubtitle *sub, int *got_output) { DVBSubContext *ctx = avctx->priv_data; DVBSubRegionDisplay *display; DVBSubRegionDisplay *tmp_display_list, **tmp_ptr; const uint8_t *buf_end = buf + buf_size; int region_id; int page_state; int timeout; int version; if (buf_size < 1) return AVERROR_INVALIDDATA; timeout = *buf++; version = ((*buf)>>4) & 15; page_state = ((*buf++) >> 2) & 3; if (ctx->version == version) { return 0; } ctx->time_out = timeout; ctx->version = version; ff_dlog(avctx, "Page time out %ds, state %d\n", ctx->time_out, page_state); if (ctx->compute_edt == 1) save_subtitle_set(avctx, sub, got_output); if (page_state == 1 || page_state == 2) { delete_regions(ctx); delete_objects(ctx); delete_cluts(ctx); } tmp_display_list = ctx->display_list; ctx->display_list = NULL; while (buf + 5 < buf_end) { region_id = *buf++; buf += 1; display = ctx->display_list; while (display && display->region_id != region_id) { display = display->next; } if (display) { av_log(avctx, AV_LOG_ERROR, "duplicate region\n"); break; } display = tmp_display_list; tmp_ptr = &tmp_display_list; while (display && display->region_id != region_id) { tmp_ptr = &display->next; display = display->next; } if (!display) { display = av_mallocz(sizeof(*display)); if (!display) return AVERROR(ENOMEM); } display->region_id = region_id; display->x_pos = AV_RB16(buf); buf += 2; display->y_pos = AV_RB16(buf); buf += 2; *tmp_ptr = display->next; display->next = ctx->display_list; ctx->display_list = display; ff_dlog(avctx, "Region %d, (%d,%d)\n", region_id, display->x_pos, display->y_pos); } while (tmp_display_list) { display = tmp_display_list; tmp_display_list = display->next; av_freep(&display); } return 0; } static int dvbsub_parse_display_definition_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size) { DVBSubContext *ctx = avctx->priv_data; DVBSubDisplayDefinition *display_def = ctx->display_definition; int dds_version, info_byte; if (buf_size < 5) return AVERROR_INVALIDDATA; info_byte = bytestream_get_byte(&buf); dds_version = info_byte >> 4; if (display_def && display_def->version == dds_version) return 0; // already have this display definition version if (!display_def) { display_def = av_mallocz(sizeof(*display_def)); if (!display_def) return AVERROR(ENOMEM); ctx->display_definition = display_def; } display_def->version = dds_version; display_def->x = 0; display_def->y = 0; display_def->width = bytestream_get_be16(&buf) + 1; display_def->height = bytestream_get_be16(&buf) + 1; if (!avctx->width || !avctx->height) { int ret = ff_set_dimensions(avctx, display_def->width, display_def->height); if (ret < 0) return ret; } if (info_byte & 1<<3) { // display_window_flag if (buf_size < 13) return AVERROR_INVALIDDATA; display_def->x = bytestream_get_be16(&buf); display_def->width = bytestream_get_be16(&buf) - display_def->x + 1; display_def->y = bytestream_get_be16(&buf); display_def->height = bytestream_get_be16(&buf) - display_def->y + 1; } return 0; } static int dvbsub_display_end_segment(AVCodecContext *avctx, const uint8_t *buf, int buf_size, AVSubtitle *sub,int *got_output) { DVBSubContext *ctx = avctx->priv_data; if (ctx->compute_edt == 0) save_subtitle_set(avctx, sub, got_output); return 0; } static int dvbsub_decode(AVCodecContext *avctx, AVSubtitle *sub, int *got_sub_ptr, const AVPacket *avpkt) { const uint8_t *buf = avpkt->data; int buf_size = avpkt->size; DVBSubContext *ctx = avctx->priv_data; const uint8_t *p, *p_end; int segment_type; int page_id; int segment_length; int i; int ret = 0; int got_segment = 0; int got_dds = 0; ff_dlog(avctx, "DVB sub packet:\n"); for (i=0; i < buf_size; i++) { ff_dlog(avctx, "%02x ", buf[i]); if (i % 16 == 15) ff_dlog(avctx, "\n"); } if (i % 16) ff_dlog(avctx, "\n"); if (buf_size <= 6 || *buf != 0x0f) { ff_dlog(avctx, "incomplete or broken packet"); return AVERROR_INVALIDDATA; } p = buf; p_end = buf + buf_size; while (p_end - p >= 6 && *p == 0x0f) { p += 1; segment_type = *p++; page_id = AV_RB16(p); p += 2; segment_length = AV_RB16(p); p += 2; if (avctx->debug & FF_DEBUG_STARTCODE) { av_log(avctx, AV_LOG_DEBUG, "segment_type:%d page_id:%d segment_length:%d\n", segment_type, page_id, segment_length); } if (p_end - p < segment_length) { ff_dlog(avctx, "incomplete or broken packet"); ret = -1; goto end; } if (page_id == ctx->composition_id || page_id == ctx->ancillary_id || ctx->composition_id == -1 || ctx->ancillary_id == -1) { int ret = 0; switch (segment_type) { case DVBSUB_PAGE_SEGMENT: ret = dvbsub_parse_page_segment(avctx, p, segment_length, sub, got_sub_ptr); got_segment |= 1; break; case DVBSUB_REGION_SEGMENT: ret = dvbsub_parse_region_segment(avctx, p, segment_length); got_segment |= 2; break; case DVBSUB_CLUT_SEGMENT: ret = dvbsub_parse_clut_segment(avctx, p, segment_length); if (ret < 0) goto end; got_segment |= 4; break; case DVBSUB_OBJECT_SEGMENT: ret = dvbsub_parse_object_segment(avctx, p, segment_length); got_segment |= 8; break; case DVBSUB_DISPLAYDEFINITION_SEGMENT: ret = dvbsub_parse_display_definition_segment(avctx, p, segment_length); got_dds = 1; break; case DVBSUB_DISPLAY_SEGMENT: ret = dvbsub_display_end_segment(avctx, p, segment_length, sub, got_sub_ptr); if (got_segment == 15 && !got_dds && !avctx->width && !avctx->height) { // Default from ETSI EN 300 743 V1.3.1 (7.2.1) avctx->width = 720; avctx->height = 576; } got_segment |= 16; break; default: ff_dlog(avctx, "Subtitling segment type 0x%x, page id %d, length %d\n", segment_type, page_id, segment_length); break; } if (ret < 0) goto end; } p += segment_length; } // Some streams do not send a display segment but if we have all the other // segments then we need no further data. if (got_segment == 15) { av_log(avctx, AV_LOG_DEBUG, "Missing display_end_segment, emulating\n"); dvbsub_display_end_segment(avctx, p, 0, sub, got_sub_ptr); } end: if (ret < 0) { return ret; } else { if (ctx->compute_edt == 1) FFSWAP(int64_t, ctx->prev_start, sub->pts); } return p - buf; } #define DS AV_OPT_FLAG_DECODING_PARAM | AV_OPT_FLAG_SUBTITLE_PARAM #define OFFSET(x) offsetof(DVBSubContext, x) static const AVOption options[] = { {"compute_edt", "compute end of time using pts or timeout", OFFSET(compute_edt), AV_OPT_TYPE_BOOL, {.i64 = 0}, 0, 1, DS}, {"compute_clut", "compute clut when not available(-1) or only once (-2) or always(1) or never(0)", OFFSET(compute_clut), AV_OPT_TYPE_BOOL, {.i64 = -1}, -2, 1, DS}, {"dvb_substream", "", OFFSET(substream), AV_OPT_TYPE_INT, {.i64 = -1}, -1, 63, DS}, {NULL} }; static const AVClass dvbsubdec_class = { .class_name = "DVB Sub Decoder", .item_name = av_default_item_name, .option = options, .version = LIBAVUTIL_VERSION_INT, }; const FFCodec ff_dvbsub_decoder = { .p.name = "dvbsub", CODEC_LONG_NAME("DVB subtitles"), .p.type = AVMEDIA_TYPE_SUBTITLE, .p.id = AV_CODEC_ID_DVB_SUBTITLE, .priv_data_size = sizeof(DVBSubContext), .init = dvbsub_init_decoder, .close = dvbsub_close_decoder, FF_CODEC_DECODE_SUB_CB(dvbsub_decode), .p.priv_class = &dvbsubdec_class, };
defd49351551b77fed5ad7285343d3ee7caf7c5f
95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5
/Engine/lib/curl/lib/curl_ctype.h
c70945a8d2009b89b745b40bd36035e7efcb8f0c
[ "MIT", "LicenseRef-scancode-unknown", "curl" ]
permissive
TorqueGameEngines/Torque3D
4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8
a445a4364664e299196bd551d213844486080145
refs/heads/development
2023-09-03T12:40:40.658487
2023-08-24T14:44:43
2023-08-24T14:44:43
267,440,108
1,192
178
MIT
2023-09-13T14:28:16
2020-05-27T22:35:54
C++
UTF-8
C
false
false
2,218
h
curl_ctype.h
#ifndef HEADER_CURL_CTYPE_H #define HEADER_CURL_CTYPE_H /*************************************************************************** * _ _ ____ _ * Project ___| | | | _ \| | * / __| | | | |_) | | * | (__| |_| | _ <| |___ * \___|\___/|_| \_\_____| * * Copyright (C) 1998 - 2022, Daniel Stenberg, <daniel@haxx.se>, et al. * * This software is licensed as described in the file COPYING, which * you should have received as part of this distribution. The terms * are also available at https://curl.se/docs/copyright.html. * * You may opt to use, copy, modify, merge, publish, distribute and/or sell * copies of the Software, and permit persons to whom the Software is * furnished to do so, under the terms of the COPYING file. * * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY * KIND, either express or implied. * * SPDX-License-Identifier: curl * ***************************************************************************/ #include "curl_setup.h" int Curl_isspace(int c); int Curl_isdigit(int c); int Curl_isalnum(int c); int Curl_isxdigit(int c); int Curl_isgraph(int c); int Curl_isprint(int c); int Curl_isalpha(int c); int Curl_isupper(int c); int Curl_islower(int c); int Curl_iscntrl(int c); #define ISSPACE(x) (Curl_isspace((int) ((unsigned char)x))) #define ISDIGIT(x) (Curl_isdigit((int) ((unsigned char)x))) #define ISALNUM(x) (Curl_isalnum((int) ((unsigned char)x))) #define ISXDIGIT(x) (Curl_isxdigit((int) ((unsigned char)x))) #define ISGRAPH(x) (Curl_isgraph((int) ((unsigned char)x))) #define ISALPHA(x) (Curl_isalpha((int) ((unsigned char)x))) #define ISPRINT(x) (Curl_isprint((int) ((unsigned char)x))) #define ISUPPER(x) (Curl_isupper((int) ((unsigned char)x))) #define ISLOWER(x) (Curl_islower((int) ((unsigned char)x))) #define ISCNTRL(x) (Curl_iscntrl((int) ((unsigned char)x))) #define ISASCII(x) (((x) >= 0) && ((x) <= 0x80)) #define ISBLANK(x) (int)((((unsigned char)x) == ' ') || \ (((unsigned char)x) == '\t')) #endif /* HEADER_CURL_CTYPE_H */
d8fada9c2cd00c04728095fb87a68248fe34a0fe
c9bc99866cfab223c777cfb741083be3e9439d81
/product/sgm776/scp_romfw/config_ppu_v1.c
3bdf07e2f81c7b16a66d14a3f10b0eb77d8d4cf8
[ "BSD-3-Clause" ]
permissive
ARM-software/SCP-firmware
4738ca86ce42d82588ddafc2226a1f353ff2c797
f6bcca436768359ffeadd84d65e8ea0c3efc7ef1
refs/heads/master
2023-09-01T16:13:36.962036
2023-08-17T13:00:20
2023-08-31T07:43:37
134,399,880
211
165
NOASSERTION
2023-09-13T14:27:10
2018-05-22T10:35:56
C
UTF-8
C
false
false
2,334
c
config_ppu_v1.c
/* * Arm SCP/MCP Software * Copyright (c) 2017-2021, Arm Limited and Contributors. All rights reserved. * * SPDX-License-Identifier: BSD-3-Clause */ #include "sgm776_mmap.h" #include <mod_msys_rom.h> #include <mod_power_domain.h> #include <mod_ppu_v1.h> #include <fwk_element.h> #include <fwk_id.h> #include <fwk_module.h> #include <fwk_module_idx.h> #include <fmw_cmsis.h> #include <stdbool.h> static struct fwk_element sgm776_ppu_v1_element_table[] = { { .name = "SYS0", .data = &((struct mod_ppu_v1_pd_config) { .pd_type = MOD_PD_TYPE_SYSTEM, .ppu.reg_base = PPU_SYS0_BASE, .ppu.irq = PPU_SYS0_IRQ, .default_power_on = true, .observer_id = FWK_ID_NONE_INIT, }), }, { .name = "SYS1", .data = &((struct mod_ppu_v1_pd_config) { .pd_type = MOD_PD_TYPE_SYSTEM, .ppu.reg_base = PPU_SYS1_BASE, .ppu.irq = PPU_SYS1_IRQ, .default_power_on = true, .observer_id = FWK_ID_NONE_INIT, }), }, { .name = "CLUS0", .data = &((struct mod_ppu_v1_pd_config) { .pd_type = MOD_PD_TYPE_CLUSTER, .ppu.reg_base = PPU_CLUS0_BASE, .ppu.irq = PPU_CLUS0_IRQ, .observer_id = FWK_ID_NONE_INIT, }), }, { .name = "CORE0", .data = &((struct mod_ppu_v1_pd_config) { .pd_type = MOD_PD_TYPE_CORE, .ppu.reg_base = PPU_CLUS0CORE0_BASE, .ppu.irq = PPU_CLUS0CORE0_IRQ, .cluster_id = FWK_ID_ELEMENT_INIT(FWK_MODULE_IDX_PPU_V1, 2), .observer_id = FWK_ID_NONE_INIT, }), }, { 0 }, /* Termination entry */ }; static const struct fwk_element *sgm776_ppu_v1_get_element_table( fwk_id_t module_id) { return sgm776_ppu_v1_element_table; } /* * Power module configuration data */ struct fwk_module_config config_ppu_v1 = { .data = &(struct mod_ppu_v1_config){ .pd_notification_id = FWK_ID_NOTIFICATION_INIT( FWK_MODULE_IDX_MSYS_ROM, MOD_MSYS_ROM_NOTIFICATION_IDX_POWER_SYSTOP), .pd_source_id = FWK_ID_MODULE_INIT(FWK_MODULE_IDX_MSYS_ROM), }, .elements = FWK_MODULE_DYNAMIC_ELEMENTS(sgm776_ppu_v1_get_element_table), };
349643c600a801ab883d9227164fee854d72d75e
f42190636add23ead6a5022d706a124032d66f92
/src/Microsoft.DotNet.Wpf/src/WpfGfx/shared/util/UtilLib/Pch.h
b567e07cb2a4ba0dfee68baf4fb19b8afbb79488
[ "MIT" ]
permissive
dotnet/wpf
b8f73a99e03f87b4dee5db643e38e2c0704f707a
2ff355a607d79eef5fea7796de1f29cf9ea4fbed
refs/heads/main
2023-09-04T09:35:19.355384
2023-09-03T02:30:37
2023-09-03T02:30:37
153,711,945
6,927
1,397
MIT
2023-09-14T17:22:06
2018-10-19T01:55:23
C#
UTF-8
C
false
false
630
h
Pch.h
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //----------------------------------------------------------------------------- // // // File: Precomp.h //----------------------------------------------------------------------------- #define AVALON_INCLUDE_NT_HEADERS #include "Always.h" #include <strsafe.h> #pragma push_macro("UnsignedMultiply128") #undef UnsignedMultiply128 #include <intsafe.h> #pragma pop_macro("UnsignedMultiply128") #include "Public.h"
626b14513a9892d9dd8e574c71a03b7a868d8f59
6923f79f1eaaba0ab28b25337ba6cb56be97d32d
/NumericalRecipes3/calendar.h
ca7033f5c3ccef31d56b03dee511e7fbcae02929
[]
no_license
burakbayramli/books
9fe7ba0cabf06e113eb125d62fe16d4946f4a4f0
5e9a0e03aa7ddf5e5ddf89943ccc68d94b539e95
refs/heads/master
2023-08-17T05:31:08.885134
2023-08-14T10:05:37
2023-08-14T10:05:37
72,460,321
223
174
null
2022-10-24T12:15:06
2016-10-31T17:24:00
Jupyter Notebook
UTF-8
C
false
false
1,692
h
calendar.h
Int julday(const Int mm, const Int id, const Int iyyy) { const Int IGREG=15+31*(10+12*1582); Int ja,jul,jy=iyyy,jm; if (jy == 0) throw("julday: there is no year zero."); if (jy < 0) ++jy; if (mm > 2) { jm=mm+1; } else { --jy; jm=mm+13; } jul = Int(floor(365.25*jy)+floor(30.6001*jm)+id+1720995); if (id+31*(mm+12*iyyy) >= IGREG) { ja=Int(0.01*jy); jul += 2-ja+Int(0.25*ja); } return jul; } void caldat(const Int julian, Int &mm, Int &id, Int &iyyy) { const Int IGREG=2299161; Int ja,jalpha,jb,jc,jd,je; if (julian >= IGREG) { jalpha=Int((Doub(julian-1867216)-0.25)/36524.25); ja=julian+1+jalpha-Int(0.25*jalpha); } else if (julian < 0) { ja=julian+36525*(1-julian/36525); } else ja=julian; jb=ja+1524; jc=Int(6680.0+(Doub(jb-2439870)-122.1)/365.25); jd=Int(365*jc+(0.25*jc)); je=Int((jb-jd)/30.6001); id=jb-jd-Int(30.6001*je); mm=je-1; if (mm > 12) mm -= 12; iyyy=jc-4715; if (mm > 2) --iyyy; if (iyyy <= 0) --iyyy; if (julian < 0) iyyy -= 100*(1-julian/36525); } void flmoon(const Int n, const Int nph, Int &jd, Doub &frac) { const Doub RAD=3.141592653589793238/180.0; Int i; Doub am,as,c,t,t2,xtra; c=n+nph/4.0; t=c/1236.85; t2=t*t; as=359.2242+29.105356*c; am=306.0253+385.816918*c+0.010730*t2; jd=2415020+28*n+7*nph; xtra=0.75933+1.53058868*c+((1.178e-4)-(1.55e-7)*t)*t2; if (nph == 0 || nph == 2) xtra += (0.1734-3.93e-4*t)*sin(RAD*as)-0.4068*sin(RAD*am); else if (nph == 1 || nph == 3) xtra += (0.1721-4.0e-4*t)*sin(RAD*as)-0.6280*sin(RAD*am); else throw("nph is unknown in flmoon"); i=Int(xtra >= 0.0 ? floor(xtra) : ceil(xtra-1.0)); jd += i; frac=xtra-i; }
45ed99729617b36f080f371d42b1fad56d3ea6a4
91aee99745750204ddba60d07f323316c7cde91b
/src/libsodium/crypto_stream/salsa20/xmm6/salsa20_xmm6.h
29d88038841cf3de3a6501a2917e0459021f1b96
[ "ISC" ]
permissive
jedisct1/libsodium
7dfb8c418b1bd8f7d0539be3386e07e3599fc48f
0ea62015f2c397168566c7f8c6df65e59a0d1049
refs/heads/master
2023-09-01T10:53:16.647374
2023-08-31T21:23:30
2023-08-31T21:23:30
7,710,647
10,795
1,968
NOASSERTION
2023-09-14T16:00:28
2013-01-20T00:03:40
C
UTF-8
C
false
false
227
h
salsa20_xmm6.h
#include <stdint.h> #include "../stream_salsa20.h" #include "crypto_stream_salsa20.h" #include "salsa20_xmm6-asm_namespace.h" extern struct crypto_stream_salsa20_implementation crypto_stream_salsa20_xmm6_implementation;
95fdce2dce124f1a12f596619e3cc85528bf44cf
b01b4365ab6c9afeb6664563dd314df4f269014f
/tail/tail.c
4691b67fe7303e44cc90f42963d786cfd7d2b95a
[ "MIT" ]
permissive
malxau/yori
6208011ca60485cfbf141c7639e9f941a160e002
027f9b42c08cc5fcc682ecb7fb67e6de5363b8de
refs/heads/master
2023-09-01T13:11:19.083028
2023-08-28T00:00:02
2023-08-28T00:00:02
127,679,677
1,234
31
MIT
2023-04-23T04:54:56
2018-04-01T23:29:17
C
UTF-8
C
false
false
19,070
c
tail.c
/** * @file tail/tail.c * * Yori shell display the final lines in a file * * Copyright (c) 2017-2019 Malcolm J. Smith * * 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 <yoripch.h> #include <yorilib.h> #pragma warning(disable: 4220) // Varargs matches remaining parameters /** Help text to display to the user. */ const CHAR strTailHelpText[] = "\n" "Output the final lines of one or more files.\n" "\n" "TAIL [-license] [-b] [-f] [-s] [-n count] [-c line] [<file>...]\n" "\n" " -b Use basic search criteria for files only\n" " -c Specify a line to display context around instead of EOF\n" " -f Wait for new output and continue outputting\n" " -n Specify the number of lines to display\n" " -s Process files from all subdirectories\n"; /** Display usage text to the user. */ BOOL TailHelp(VOID) { YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("Tail %i.%02i\n"), YORI_VER_MAJOR, YORI_VER_MINOR); #if YORI_BUILD_ID YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T(" Build %i\n"), YORI_BUILD_ID); #endif YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%hs"), strTailHelpText); return TRUE; } /** Context passed to the callback which is invoked for each file found. */ typedef struct _TAIL_CONTEXT { /** Records the total number of files processed. */ DWORDLONG FilesFound; /** Records the total number of files processed within a single command line argument. */ DWORDLONG FilesFoundThisArg; /** Specifies the number of lines to display in each matching file. */ DWORD LinesToDisplay; /** The first error encountered when enumerating objects from a single arg. This is used to preserve file not found/path not found errors so that when the program falls back to interpreting the argument as a literal, if that still doesn't work, this is the error code that is displayed. */ DWORD SavedErrorThisArg; /** If nonzero, specifies the final line to display from each file. This implies that tail is running in context mode, looking for a region in the middle of the file. */ DWORDLONG FinalLine; /** Specifies the number of lines that have been found from the current stream. */ DWORDLONG LinesFound; /** An array of LinesToDisplay YORI_STRING structures. */ PYORI_STRING LinesArray; /** If TRUE, continue outputting results as more arrive. If FALSE, terminate as soon as the requested lines have been output. */ BOOLEAN WaitForMore; /** TRUE to indicate that files are being enumerated recursively. */ BOOLEAN Recursive; } TAIL_CONTEXT, *PTAIL_CONTEXT; /** Process a single opened stream, enumerating through all lines and displaying the set requested by the user. @param hSource The opened source stream. @param TailContext Pointer to context information specifying which lines to display. @return TRUE to indicate success, FALSE to indicate failure. */ BOOL TailProcessStream( __in HANDLE hSource, __in PTAIL_CONTEXT TailContext ) { PVOID LineContext = NULL; DWORDLONG StartLine = 0; DWORDLONG CurrentLine; PYORI_STRING LineString; YORI_LIB_LINE_ENDING LineEnding; BOOL TimeoutReached; DWORD SeekToEndOffset = 0; DWORD Err; DWORD BytesWritten; DWORD FileType = GetFileType(hSource); FileType = FileType & ~(FILE_TYPE_REMOTE); // // If it's a file and we want the final few lines, start searching // from the end, assuming an average line size of 256 bytes. // if (FileType == FILE_TYPE_DISK && TailContext->FinalLine == 0) { SeekToEndOffset = 256 * TailContext->LinesToDisplay; } TailContext->FilesFound++; TailContext->FilesFoundThisArg++; while (TRUE) { if (SeekToEndOffset != 0) { if (!SetFilePointer(hSource, -1 * SeekToEndOffset, NULL, FILE_END)) { SeekToEndOffset = 0; SetFilePointer(hSource, 0, NULL, FILE_BEGIN); } } TailContext->LinesFound = 0; while (TRUE) { if (!YoriLibReadLineToStringEx(&TailContext->LinesArray[TailContext->LinesFound % TailContext->LinesToDisplay], &LineContext, !TailContext->WaitForMore, INFINITE, hSource, &LineEnding, &TimeoutReached)) { break; } TailContext->LinesFound++; if (TailContext->FinalLine != 0 && TailContext->LinesFound >= TailContext->FinalLine) { break; } } if (TailContext->LinesFound > TailContext->LinesToDisplay) { StartLine = TailContext->LinesFound - TailContext->LinesToDisplay; break; } else if (SeekToEndOffset != 0) { // // If we didn't get enough lines and we have a file that // supports arbitrary seeks, try to grab more data. If // we've already hit our arbitrary maximum (a 4Kb average // line size) start scanning from the top. // if (SeekToEndOffset < 4096 * TailContext->LinesToDisplay) { SeekToEndOffset = 4096 * TailContext->LinesToDisplay; } else { SeekToEndOffset = 0; SetFilePointer(hSource, 0, NULL, FILE_BEGIN); } YoriLibLineReadCloseOrCache(LineContext); LineContext = NULL; continue; } else { StartLine = 0; break; } } for (CurrentLine = StartLine; CurrentLine < TailContext->LinesFound; CurrentLine++) { LineString = &TailContext->LinesArray[CurrentLine % TailContext->LinesToDisplay]; YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%y\n"), LineString); } if (TailContext->WaitForMore) { while (TRUE) { if (!YoriLibReadLineToStringEx(&TailContext->LinesArray[0], &LineContext, FALSE, INFINITE, hSource, &LineEnding, &TimeoutReached)) { // // Check if the target handle is still around // if (!WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), NULL, 0, &BytesWritten, NULL)) { Err = GetLastError(); if (Err == ERROR_NO_DATA || Err == ERROR_PIPE_NOT_CONNECTED) { break; } } if (YoriLibIsOperationCancelled()) { break; } Sleep(200); continue; } YoriLibOutput(YORI_LIB_OUTPUT_STDOUT, _T("%y\n"), &TailContext->LinesArray[0]); } } YoriLibLineReadCloseOrCache(LineContext); return TRUE; } /** A callback that is invoked when a file is found that matches a search criteria specified in the set of strings to enumerate. @param FilePath Pointer to the file path that was found. @param FileInfo Information about the file. This can be NULL if the file was not found by enumeration. @param Depth Specifies recursion depth. Ignored in this application. @param Context Pointer to the tail context structure indicating the action to perform and populated with the file and line count found. @return TRUE to continute enumerating, FALSE to abort. */ BOOL TailFileFoundCallback( __in PYORI_STRING FilePath, __in_opt PWIN32_FIND_DATA FileInfo, __in DWORD Depth, __in PVOID Context ) { HANDLE FileHandle; PTAIL_CONTEXT TailContext = (PTAIL_CONTEXT)Context; UNREFERENCED_PARAMETER(Depth); ASSERT(YoriLibIsStringNullTerminated(FilePath)); if (FileInfo == NULL || (FileInfo->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) == 0) { FileHandle = CreateFile(FilePath->StartOfString, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_BACKUP_SEMANTICS, NULL); if (FileHandle == NULL || FileHandle == INVALID_HANDLE_VALUE) { if (TailContext->SavedErrorThisArg == ERROR_SUCCESS) { DWORD LastError = GetLastError(); LPTSTR ErrText = YoriLibGetWinErrorText(LastError); YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("tail: open of %y failed: %s"), FilePath, ErrText); YoriLibFreeWinErrorText(ErrText); } return TRUE; } TailContext->SavedErrorThisArg = ERROR_SUCCESS; TailProcessStream(FileHandle, TailContext); CloseHandle(FileHandle); } return TRUE; } /** A callback that is invoked when a directory cannot be successfully enumerated. @param FilePath Pointer to the file path that could not be enumerated. @param ErrorCode The Win32 error code describing the failure. @param Depth Recursion depth, ignored in this application. @param Context Pointer to the context block indicating whether the enumeration was recursive. Recursive enumerates do not complain if a matching file is not in every single directory, because common usage expects files to be in a subset of directories only. @return TRUE to continute enumerating, FALSE to abort. */ BOOL TailFileEnumerateErrorCallback( __in PYORI_STRING FilePath, __in DWORD ErrorCode, __in DWORD Depth, __in PVOID Context ) { YORI_STRING UnescapedFilePath; BOOL Result = FALSE; PTAIL_CONTEXT TailContext = (PTAIL_CONTEXT)Context; UNREFERENCED_PARAMETER(Depth); YoriLibInitEmptyString(&UnescapedFilePath); if (!YoriLibUnescapePath(FilePath, &UnescapedFilePath)) { UnescapedFilePath.StartOfString = FilePath->StartOfString; UnescapedFilePath.LengthInChars = FilePath->LengthInChars; } if (ErrorCode == ERROR_FILE_NOT_FOUND || ErrorCode == ERROR_PATH_NOT_FOUND) { if (!TailContext->Recursive) { TailContext->SavedErrorThisArg = ErrorCode; } Result = TRUE; } else { LPTSTR ErrText = YoriLibGetWinErrorText(ErrorCode); YORI_STRING DirName; LPTSTR FilePart; YoriLibInitEmptyString(&DirName); DirName.StartOfString = UnescapedFilePath.StartOfString; FilePart = YoriLibFindRightMostCharacter(&UnescapedFilePath, '\\'); if (FilePart != NULL) { DirName.LengthInChars = (DWORD)(FilePart - DirName.StartOfString); } else { DirName.LengthInChars = UnescapedFilePath.LengthInChars; } YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Enumerate of %y failed: %s"), &DirName, ErrText); YoriLibFreeWinErrorText(ErrText); } YoriLibFreeStringContents(&UnescapedFilePath); return Result; } #ifdef YORI_BUILTIN /** The main entrypoint for the tail builtin command. */ #define ENTRYPOINT YoriCmd_TAIL #else /** The main entrypoint for the tail standalone application. */ #define ENTRYPOINT ymain #endif /** The main entrypoint for the tail cmdlet. @param ArgC The number of arguments. @param ArgV An array of arguments. @return Exit code of the process, zero indicating success or nonzero on failure. */ DWORD ENTRYPOINT( __in DWORD ArgC, __in YORI_STRING ArgV[] ) { BOOL ArgumentUnderstood; DWORD i; DWORD StartArg = 0; DWORD MatchFlags; DWORD Count; BOOL BasicEnumeration = FALSE; TAIL_CONTEXT TailContext; LONGLONG ContextLine; YORI_STRING Arg; ZeroMemory(&TailContext, sizeof(TailContext)); TailContext.LinesToDisplay = 10; ContextLine = -1; for (i = 1; i < ArgC; i++) { ArgumentUnderstood = FALSE; ASSERT(YoriLibIsStringNullTerminated(&ArgV[i])); if (YoriLibIsCommandLineOption(&ArgV[i], &Arg)) { if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("?")) == 0) { TailHelp(); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("license")) == 0) { YoriLibDisplayMitLicense(_T("2017-2019")); return EXIT_SUCCESS; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("b")) == 0) { BasicEnumeration = TRUE; ArgumentUnderstood = TRUE; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("c")) == 0) { if (ArgC > i + 1) { DWORD CharsConsumed; if (YoriLibStringToNumber(&ArgV[i + 1], TRUE, &ContextLine, &CharsConsumed) && CharsConsumed > 0) { ArgumentUnderstood = TRUE; i++; } else { ContextLine = -1; } } } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("f")) == 0) { TailContext.WaitForMore = TRUE; ArgumentUnderstood = TRUE; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("n")) == 0) { if (ArgC > i + 1) { LONGLONG LineCount; DWORD CharsConsumed; if (YoriLibStringToNumber(&ArgV[i + 1], TRUE, &LineCount, &CharsConsumed) && LineCount != 0 && LineCount < 1 * 1024 * 1024) { TailContext.LinesToDisplay = (DWORD)LineCount; ArgumentUnderstood = TRUE; i++; } } } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("s")) == 0) { TailContext.Recursive = TRUE; ArgumentUnderstood = TRUE; } else if (YoriLibCompareStringWithLiteralInsensitive(&Arg, _T("-")) == 0) { StartArg = i + 1; ArgumentUnderstood = TRUE; break; } } else { ArgumentUnderstood = TRUE; StartArg = i; break; } if (!ArgumentUnderstood) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("Argument not understood, ignored: %y\n"), &ArgV[i]); } } if (ContextLine != -1) { TailContext.FinalLine = ContextLine + TailContext.LinesToDisplay / 2; } TailContext.LinesArray = YoriLibMalloc(TailContext.LinesToDisplay * sizeof(YORI_STRING)); if (TailContext.LinesArray == NULL) { return EXIT_FAILURE; } #if YORI_BUILTIN YoriLibCancelEnable(FALSE); #endif // // Attempt to enable backup privilege so an administrator can access more // objects successfully. // YoriLibEnableBackupPrivilege(); for (Count = 0; Count < TailContext.LinesToDisplay; Count++) { YoriLibInitEmptyString(&TailContext.LinesArray[Count]); } // // If no file name is specified, use stdin; otherwise open // the file and use that // if (StartArg == 0 || StartArg == ArgC) { if (YoriLibIsStdInConsole()) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("No file or pipe for input\n")); YoriLibFree(TailContext.LinesArray); return EXIT_FAILURE; } TailProcessStream(GetStdHandle(STD_INPUT_HANDLE), &TailContext); } else { MatchFlags = YORILIB_FILEENUM_RETURN_FILES | YORILIB_FILEENUM_DIRECTORY_CONTENTS; if (TailContext.Recursive) { MatchFlags |= YORILIB_FILEENUM_RECURSE_BEFORE_RETURN | YORILIB_FILEENUM_RECURSE_PRESERVE_WILD; } if (BasicEnumeration) { MatchFlags |= YORILIB_FILEENUM_BASIC_EXPANSION; } for (i = StartArg; i < ArgC; i++) { TailContext.FilesFoundThisArg = 0; TailContext.SavedErrorThisArg = ERROR_SUCCESS; YoriLibForEachStream(&ArgV[i], MatchFlags, 0, TailFileFoundCallback, TailFileEnumerateErrorCallback, &TailContext); if (TailContext.FilesFoundThisArg == 0) { YORI_STRING FullPath; YoriLibInitEmptyString(&FullPath); if (YoriLibUserStringToSingleFilePath(&ArgV[i], TRUE, &FullPath)) { TailFileFoundCallback(&FullPath, NULL, 0, &TailContext); YoriLibFreeStringContents(&FullPath); } if (TailContext.SavedErrorThisArg != ERROR_SUCCESS) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("File or directory not found: %y\n"), &ArgV[i]); } } } } for (Count = 0; Count < TailContext.LinesToDisplay; Count++) { YoriLibFreeStringContents(&TailContext.LinesArray[Count]); } YoriLibFree(TailContext.LinesArray); #if !YORI_BUILTIN YoriLibLineReadCleanupCache(); #endif if (TailContext.FilesFound == 0) { YoriLibOutput(YORI_LIB_OUTPUT_STDERR, _T("tail: no matching files found\n")); return EXIT_FAILURE; } return EXIT_SUCCESS; } // vim:sw=4:ts=4:et:
e7fa93b12c604f6860415f98ac1b9702a544a83f
317410b28757af216145d23259d63fc96d07f613
/cpu/bd19/audio_encode/audio_encode.h
80028056e5efe2db5ce6e20366b58dda0f32f539
[ "Apache-2.0" ]
permissive
Jieli-Tech/fw-AC63_BT_SDK
48c757dca7e8000ec763bf5466583a4cd8c4a11c
393d63758081d56f0bf0a39ac596bee32c33d493
refs/heads/master
2023-07-18T02:14:56.187266
2023-06-21T03:14:20
2023-06-21T03:14:20
272,586,610
113
76
Apache-2.0
2022-10-20T23:07:31
2020-06-16T02:02:15
C
UTF-8
C
false
false
178
h
audio_encode.h
#ifndef _AUDIO_ENC_H_ #define _AUDIO_ENC_H_ #include "asm/includes.h" #include "media/includes.h" #include "system/includes.h" int audio_enc_init(); #endif/*_AUDIO_ENC_H_*/
9064be4186355cff9d7c9ed7167e9d6b18b1e246
0480082b1a9f42e251ffb3403e9a1f8728e6995c
/src/api/haskell/external/network-3.1.2.7/cbits/initWinSock.c
e720b85201a2dc6e3e88b6c1b0d11eb456388f8f
[ "MIT", "LGPL-2.0-or-later", "FSFAP", "ISC", "LicenseRef-scancode-warranty-disclaimer", "GPL-3.0-or-later", "BSL-1.0", "Apache-2.0", "LGPL-2.0-only", "Autoconf-exception-2.0", "GPL-2.0-or-later", "OCaml-LGPL-linking-exception", "MPL-1.0", "GPL-3.0-only", "Autoconf-exception-macro", "BSD-2-Clause", "GPL-1.0-or-later", "BSD-3-Clause", "LicenseRef-scancode-other-permissive", "MPL-2.0", "Python-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
CloudI/CloudI
5cc5cd2e97cbc737d3b412fe2fe267bd748b357d
0dd802a50b397cbd41ae04fb2e77a3615d3f2dd0
refs/heads/develop
2023-08-31T13:04:24.814582
2023-08-26T21:56:46
2023-08-26T21:56:46
293,999
289
35
MIT
2018-10-04T16:17:36
2009-09-01T06:11:16
Erlang
UTF-8
C
false
false
990
c
initWinSock.c
#include "HsNet.h" #include "HsFFI.h" #if defined(_WIN32) static int winsock_inited = 0; static void shutdownHandler(void) { WSACleanup(); } /* Initialising WinSock... */ int initWinSock () { WORD wVersionRequested; WSADATA wsaData; int err; if (!winsock_inited) { wVersionRequested = MAKEWORD( 2, 2 ); err = WSAStartup ( wVersionRequested, &wsaData ); if ( err != 0 ) { return err; } if ( LOBYTE( wsaData.wVersion ) != 2 || HIBYTE( wsaData.wVersion ) != 2 ) { WSACleanup(); return (-1); } atexit(shutdownHandler); winsock_inited = 1; } return 0; } SOCKET wsaDuplicate (SOCKET s) { WSAPROTOCOL_INFOW protocolInfo; if (WSADuplicateSocketW (s, GetCurrentProcessId (), &protocolInfo) != 0) return -1; SOCKET res = WSASocketW(FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, FROM_PROTOCOL_INFO, &protocolInfo, 0, 0); if (res == SOCKET_ERROR) return -1; return res; } #endif
5e852b7bbef026a9ea326c93de1cf359b78ded11
0fde82bf8a529c1045595b0f451dc7005a9d90cf
/generate/novas/nutation.h
8ebc3326e1c46a58ca704b9ca41373ca0fa6024f
[ "MIT" ]
permissive
cosinekitty/astronomy
18ccec1d62bbae24a8424b3eb807f4b3b97c04a1
056076b85aa591ba756ef8a24fc017ddb3b3029b
refs/heads/master
2023-09-04T18:00:34.676849
2023-08-28T19:20:08
2023-08-28T19:20:08
180,022,816
305
56
MIT
2023-08-28T19:20:10
2019-04-07T20:55:20
C
UTF-8
C
false
false
652
h
nutation.h
/* Naval Observatory Vector Astrometry Software (NOVAS) C Edition, Version 3.1 nutation.h: Header file for nutation models U. S. Naval Observatory Astronomical Applications Dept. Washington, DC http://www.usno.navy.mil/USNO/astronomical-applications */ #ifndef _NUTATION_ #define _NUTATION_ /* Function prototypes */ void iau2000a (double jd_high, double jd_low, double *dpsi, double *deps); void iau2000b (double jd_high, double jd_low, double *dpsi, double *deps); void nu2000k (double jd_high, double jd_low, double *dpsi, double *deps); #endif
4255c6714a9c75c6fcefaf7af21307d5865167a6
4de159aea4b1eb5a527a3011275be57c4bb8d28f
/src/deps/kazmath/mat3.c
fc54a4300f24f29ff8c445991e0aeab66288096c
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
tanis2000/binocle-c
27691ec089a4b75acc451ef6abc4767cb06a6fdd
cd3dbacdd5cb94bfce489b9ee2f07e218c645e29
refs/heads/master
2023-09-04T20:39:34.331172
2023-08-29T13:22:12
2023-08-29T13:22:12
192,515,187
132
8
MIT
2023-05-09T14:39:31
2019-06-18T10:07:33
C
UTF-8
C
false
false
11,107
c
mat3.c
/* Copyright (c) 2008, Luke Benstead. 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. 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 <stdlib.h> #include <memory.h> #include <assert.h> #include "utility.h" #include "vec3.h" #include "mat3.h" #include "mat4.h" #include "quaternion.h" kmMat3* kmMat3Fill(kmMat3* pOut, const kmScalar* pMat) { memcpy(pOut->mat, pMat, sizeof(kmScalar) * 9); return pOut; } kmMat3* kmMat3Identity(kmMat3* pOut) { memset(pOut->mat, 0, sizeof(kmScalar) * 9); pOut->mat[0] = pOut->mat[4] = pOut->mat[8] = 1.0f; return pOut; } kmScalar kmMat3Determinant(const kmMat3* pIn) { kmScalar output; /* calculating the determinant following the rule of sarus, | 0 3 6 | 0 3 | m = | 1 4 7 | 1 4 | | 2 5 8 | 2 5 | now sum up the products of the diagonals going to the right (i.e. 0,4,8) and substract the products of the other diagonals (i.e. 2,4,6) */ output = pIn->mat[0] * pIn->mat[4] * pIn->mat[8] + pIn->mat[1] * pIn->mat[5] * pIn->mat[6] + pIn->mat[2] * pIn->mat[3] * pIn->mat[7]; output -= pIn->mat[2] * pIn->mat[4] * pIn->mat[6] + pIn->mat[0] * pIn->mat[5] * pIn->mat[7] + pIn->mat[1] * pIn->mat[3] * pIn->mat[8]; return output; } kmMat3* kmMat3Adjugate(kmMat3* pOut, const kmMat3* pIn) { pOut->mat[0] = pIn->mat[4] * pIn->mat[8] - pIn->mat[5] * pIn->mat[7]; pOut->mat[1] = pIn->mat[2] * pIn->mat[7] - pIn->mat[1] * pIn->mat[8]; pOut->mat[2] = pIn->mat[1] * pIn->mat[5] - pIn->mat[2] * pIn->mat[4]; pOut->mat[3] = pIn->mat[5] * pIn->mat[6] - pIn->mat[3] * pIn->mat[8]; pOut->mat[4] = pIn->mat[0] * pIn->mat[8] - pIn->mat[2] * pIn->mat[6]; pOut->mat[5] = pIn->mat[2] * pIn->mat[3] - pIn->mat[0] * pIn->mat[5]; pOut->mat[6] = pIn->mat[3] * pIn->mat[7] - pIn->mat[4] * pIn->mat[6]; pOut->mat[7] = pIn->mat[1] * pIn->mat[6] - pIn->mat[0] * pIn->mat[7]; pOut->mat[8] = pIn->mat[0] * pIn->mat[4] - pIn->mat[1] * pIn->mat[3]; return pOut; } kmMat3* kmMat3Inverse(kmMat3* pOut, const kmMat3* pM) { kmScalar determinate = kmMat3Determinant(pM); kmScalar detInv; kmMat3 adjugate; if(determinate == 0.0) { return NULL; } detInv = 1.0 / determinate; kmMat3Adjugate(&adjugate, pM); kmMat3MultiplyScalar(pOut, &adjugate, detInv); return pOut; } kmBool kmMat3IsIdentity(const kmMat3* pIn) { static kmScalar identity [] = { 1.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f, 1.0f}; return (memcmp(identity, pIn->mat, sizeof(kmScalar) * 9) == 0); } kmMat3* kmMat3Transpose(kmMat3* pOut, const kmMat3* pIn) { kmScalar temp[9]; temp[0] = pIn->mat[0]; temp[1] = pIn->mat[3]; temp[2] = pIn->mat[6]; temp[3] = pIn->mat[1]; temp[4] = pIn->mat[4]; temp[5] = pIn->mat[7]; temp[6] = pIn->mat[2]; temp[7] = pIn->mat[5]; temp[8] = pIn->mat[8]; memcpy(&pOut->mat, temp, sizeof(kmScalar)*9); return pOut; } kmMat3* kmMat3MultiplyMat3(kmMat3* pOut, const kmMat3* pM1, const kmMat3* pM2) { kmScalar mat[9]; const kmScalar *m1 = pM1->mat, *m2 = pM2->mat; mat[0] = m1[0] * m2[0] + m1[3] * m2[1] + m1[6] * m2[2]; mat[1] = m1[1] * m2[0] + m1[4] * m2[1] + m1[7] * m2[2]; mat[2] = m1[2] * m2[0] + m1[5] * m2[1] + m1[8] * m2[2]; mat[3] = m1[0] * m2[3] + m1[3] * m2[4] + m1[6] * m2[5]; mat[4] = m1[1] * m2[3] + m1[4] * m2[4] + m1[7] * m2[5]; mat[5] = m1[2] * m2[3] + m1[5] * m2[4] + m1[8] * m2[5]; mat[6] = m1[0] * m2[6] + m1[3] * m2[7] + m1[6] * m2[8]; mat[7] = m1[1] * m2[6] + m1[4] * m2[7] + m1[7] * m2[8]; mat[8] = m1[2] * m2[6] + m1[5] * m2[7] + m1[8] * m2[8]; memcpy(pOut->mat, mat, sizeof(kmScalar)*9); return pOut; } kmMat3* kmMat3MultiplyScalar(kmMat3* pOut, const kmMat3* pM, const kmScalar pFactor) { kmScalar mat[9]; int i; for(i = 0; i < 9; i++) { mat[i] = pM->mat[i] * pFactor; } memcpy(pOut->mat, mat, sizeof(kmScalar)*9); return pOut; } kmMat3* kmMat3AssignMat3(kmMat3* pOut, const kmMat3* pIn) { assert(pOut != pIn); /*You have tried to self-assign!!*/ memcpy(pOut->mat, pIn->mat, sizeof(kmScalar)*9); return pOut; } kmBool kmMat3AreEqual(const kmMat3* pMat1, const kmMat3* pMat2) { int i; if (pMat1 == pMat2) { return KM_TRUE; } for (i = 0; i < 9; ++i) { if(!kmAlmostEqual(pMat1->mat[i], pMat2->mat[i])) { return KM_FALSE; } } return KM_TRUE; } kmMat3* kmMat3FromScaling(kmMat3* pOut, const kmScalar x, const kmScalar y) { /* memset(pOut->mat, 0, sizeof(kmScalar) * 9);*/ kmMat3Identity(pOut); pOut->mat[0] = x; pOut->mat[4] = y; return pOut; } kmMat3* kmMat3FromTranslation(kmMat3* pOut, const kmScalar x, const kmScalar y) { /* memset(pOut->mat, 0, sizeof(kmScalar) * 9);*/ kmMat3Identity(pOut); pOut->mat[6] = x; pOut->mat[7] = y; /* pOut->mat[8] = 1.0;*/ return pOut; } kmMat3* kmMat3FromRotationQuaternion(kmMat3* pOut, const kmQuaternion* pIn) { if (!pIn || !pOut) { return NULL; } /* First row */ pOut->mat[0] = 1.0f - 2.0f * (pIn->y * pIn->y + pIn->z * pIn->z); pOut->mat[1] = 2.0f * (pIn->x * pIn->y - pIn->w * pIn->z); pOut->mat[2] = 2.0f * (pIn->x * pIn->z + pIn->w * pIn->y); /* Second row */ pOut->mat[3] = 2.0f * (pIn->x * pIn->y + pIn->w * pIn->z); pOut->mat[4] = 1.0f - 2.0f * (pIn->x * pIn->x + pIn->z * pIn->z); pOut->mat[5] = 2.0f * (pIn->y * pIn->z - pIn->w * pIn->x); /* Third row */ pOut->mat[6] = 2.0f * (pIn->x * pIn->z - pIn->w * pIn->y); pOut->mat[7] = 2.0f * (pIn->y * pIn->z + pIn->w * pIn->x); pOut->mat[8] = 1.0f - 2.0f * (pIn->x * pIn->x + pIn->y * pIn->y); return pOut; } kmMat3* kmMat3FromRotationAxisAngle(kmMat3* pOut, const struct kmVec3* axis, kmScalar radians) { kmScalar rcos = cosf(radians); kmScalar rsin = sinf(radians); pOut->mat[0] = rcos + axis->x * axis->x * (1 - rcos); pOut->mat[1] = axis->z * rsin + axis->y * axis->x * (1 - rcos); pOut->mat[2] = -axis->y * rsin + axis->z * axis->x * (1 - rcos); pOut->mat[3] = -axis->z * rsin + axis->x * axis->y * (1 - rcos); pOut->mat[4] = rcos + axis->y * axis->y * (1 - rcos); pOut->mat[5] = axis->x * rsin + axis->z * axis->y * (1 - rcos); pOut->mat[6] = axis->y * rsin + axis->x * axis->z * (1 - rcos); pOut->mat[7] = -axis->x * rsin + axis->y * axis->z * (1 - rcos); pOut->mat[8] = rcos + axis->z * axis->z * (1 - rcos); return pOut; } kmMat3* kmMat3FromRotationAxisAngleInDegrees(kmMat3* pOut, const struct kmVec3* axis, const kmScalar degrees) { return kmMat3FromRotationAxisAngle(pOut, axis, kmDegreesToRadians(degrees)); } void kmMat3ExtractRotationAxisAngle(const kmMat3* pIn, kmVec3* pAxis, kmScalar* radians) { /*Surely not this easy?*/ kmQuaternion temp; kmQuaternionRotationMatrix(&temp, pIn); kmQuaternionToAxisAngle(&temp, pAxis, radians); } kmMat3* kmMat3FromRotationX(kmMat3* pOut, const kmScalar radians) { /* | 1 0 0 | M = | 0 cos(A) -sin(A) | | 0 sin(A) cos(A) | */ pOut->mat[0] = 1.0f; pOut->mat[1] = 0.0f; pOut->mat[2] = 0.0f; pOut->mat[3] = 0.0f; pOut->mat[4] = cosf(radians); pOut->mat[5] = sinf(radians); pOut->mat[6] = 0.0f; pOut->mat[7] = -sinf(radians); pOut->mat[8] = cosf(radians); return pOut; } kmMat3* kmMat3FromRotationY(kmMat3* pOut, const kmScalar radians) { /* | cos(A) 0 sin(A) | M = | 0 1 0 | | -sin(A) 0 cos(A) | */ pOut->mat[0] = cosf(radians); pOut->mat[1] = 0.0f; pOut->mat[2] = -sinf(radians); pOut->mat[3] = 0.0f; pOut->mat[4] = 1.0f; pOut->mat[5] = 0.0f; pOut->mat[6] = sinf(radians); pOut->mat[7] = 0.0f; pOut->mat[8] = cosf(radians); return pOut; } kmMat3* kmMat3FromRotationZ(kmMat3* pOut, const kmScalar radians) { /* | cos(A) -sin(A) 0 | M = | sin(A) cos(A) 0 | | 0 0 1 | */ pOut->mat[0] = cosf(radians); pOut->mat[1] =-sinf(radians); pOut->mat[2] = 0.0f; pOut->mat[3] = sinf(radians); pOut->mat[4] = cosf(radians); pOut->mat[5] = 0.0f; pOut->mat[6] = 0.0f; pOut->mat[7] = 0.0f; pOut->mat[8] = 1.0f; return pOut; } kmMat3* kmMat3FromRotationXInDegrees(kmMat3* pOut, const kmScalar degrees) { return kmMat3FromRotationX(pOut, kmDegreesToRadians(degrees)); } kmMat3* kmMat3FromRotationYInDegrees(kmMat3* pOut, const kmScalar degrees) { return kmMat3FromRotationY(pOut, kmDegreesToRadians(degrees)); } kmMat3* kmMat3FromRotationZInDegrees(kmMat3* pOut, const kmScalar degrees) { return kmMat3FromRotationZ(pOut, kmDegreesToRadians(degrees)); } kmVec3* kmMat3ExtractUpVec3(const kmMat3* pIn, kmVec3* pOut) { pOut->x = pIn->mat[3]; pOut->y = pIn->mat[4]; pOut->z = pIn->mat[5]; kmVec3Normalize(pOut, pOut); return pOut; } kmVec3* kmMat3ExtractRightVec3(const kmMat3* pIn, kmVec3* pOut) { pOut->x = pIn->mat[0]; pOut->y = pIn->mat[1]; pOut->z = pIn->mat[2]; kmVec3Normalize(pOut, pOut); return pOut; } kmVec3* kmMat3ExtractForwardVec3(const kmMat3* pIn, kmVec3* pOut) { pOut->x = pIn->mat[6]; pOut->y = pIn->mat[7]; pOut->z = pIn->mat[8]; kmVec3Normalize(pOut, pOut); return pOut; } kmMat3* kmMat3FromRotationLookAt(kmMat3* pOut, const kmVec3* pEye, const kmVec3* pCenter, const kmVec3* pUp) { kmVec3 f, up, s, u; kmVec3Subtract(&f, pCenter, pEye); kmVec3Normalize(&f, &f); kmVec3Assign(&up, pUp); kmVec3Normalize(&up, &up); kmVec3Cross(&s, &f, &up); kmVec3Normalize(&s, &s); kmVec3Cross(&u, &s, &f); kmVec3Normalize(&s, &s); pOut->mat[0] = s.x; pOut->mat[3] = s.y; pOut->mat[6] = s.z; pOut->mat[1] = u.x; pOut->mat[4] = u.y; pOut->mat[7] = u.z; pOut->mat[2] = -f.x; pOut->mat[5] = -f.y; pOut->mat[8] = -f.z; return pOut; }
fa2b37b899388fd08c85993ee7e645fb99086006
72f2515c4cef9e02c27452b32269ca403f76c69a
/src/modules/fancyzones/FancyZonesLib/FancyZonesWinHookEventIDs.h
5558caaf297e1f6404578456b4a70a497207a971
[ "LicenseRef-scancode-generic-cla", "MIT", "BSL-1.0", "Unlicense" ]
permissive
microsoft/PowerToys
4625ffc4c513265094bf9e0f490753a54aabeaa0
3244ba989921dd26dd32be75021ed68c9cfcdda9
refs/heads/main
2023-08-17T00:10:06.645243
2023-08-16T16:31:10
2023-08-16T16:31:10
184,456,251
103,306
7,187
MIT
2023-09-14T16:52:26
2019-05-01T17:44:02
C#
UTF-8
C
false
false
1,306
h
FancyZonesWinHookEventIDs.h
#pragma once extern UINT WM_PRIV_MOVESIZESTART; extern UINT WM_PRIV_MOVESIZEEND; extern UINT WM_PRIV_LOCATIONCHANGE; extern UINT WM_PRIV_NAMECHANGE; extern UINT WM_PRIV_WINDOWCREATED; extern UINT WM_PRIV_INIT; // Scheduled when FancyZones is initialized extern UINT WM_PRIV_VD_SWITCH; // Scheduled when virtual desktop switch occurs extern UINT WM_PRIV_EDITOR; // Scheduled when the editor exits extern UINT WM_PRIV_LAYOUT_HOTKEYS_FILE_UPDATE; // Scheduled when the watched layout-hotkeys.json file is updated extern UINT WM_PRIV_LAYOUT_TEMPLATES_FILE_UPDATE; // Scheduled when the watched layout-templates.json file is updated extern UINT WM_PRIV_CUSTOM_LAYOUTS_FILE_UPDATE; // Scheduled when the watched custom-layouts.json file is updated extern UINT WM_PRIV_APPLIED_LAYOUTS_FILE_UPDATE; // Scheduled when the watched applied-layouts.json file is updated extern UINT WM_PRIV_DEFAULT_LAYOUTS_FILE_UPDATE; // Scheduled when the watched default-layouts.json file is updated extern UINT WM_PRIV_SNAP_HOTKEY; // Scheduled when we receive a snap hotkey key down press extern UINT WM_PRIV_QUICK_LAYOUT_KEY; // Scheduled when we receive a key down press to quickly apply a layout extern UINT WM_PRIV_SETTINGS_CHANGED; // Scheduled when the a watched settings file is updated void InitializeWinhookEventIds();
265f7dbd8fd0a50d583ba773030dcc4fc80a77bc
28d0f8c01599f8f6c711bdde0b59f9c2cd221203
/sys/arch/macppc/dev/platinumfb.c
e080c0bc5bed918d6055713ac718ecf816a4720e
[]
no_license
NetBSD/src
1a9cbc22ed778be638b37869ed4fb5c8dd616166
23ee83f7c0aea0777bd89d8ebd7f0cde9880d13c
refs/heads/trunk
2023-08-31T13:24:58.105962
2023-08-27T15:50:47
2023-08-27T15:50:47
88,439,547
656
348
null
2023-07-20T20:07:24
2017-04-16T20:03:43
null
UTF-8
C
false
false
28,120
c
platinumfb.c
/* * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /* A console driver for Apple's Platinum onboard video controller, * found in (all?) Catalyst logic boards including the Powermac 7200. * * Used valkyriefb.c from NetBSD, and platinumfb.c/platinumfb.h from * Linux sources as templates. * * Platinum is broken regarding openfirmware video variables. In OF, * for a powermac 7200, doing "dev /platinum .properties" results in: * * name platinum * device_type display * model AAPL,343S1184 * AAPL,connector monitor * reg F8000000 00000800 * F1000000 01000000 * AAPL,interrupts 0000001E * * The first reg is the register set, and the second is for the * framebuffer. There is also a set of colormap registers hardcoded * in platinumfbreg.h that (I think) aren't in openfirmware. * * powermac 7200 VRAM min and max limits are 1 and 4 Mb respectively. * OF claims 16M so we don't use that value. If other machines can * can have more or less VRAM this code will need to be modified */ #include <sys/cdefs.h> __KERNEL_RCSID(0, "$NetBSD: platinumfb.c,v 1.6 2021/08/07 16:18:57 thorpej Exp $"); #include <sys/param.h> #include <sys/systm.h> #include <sys/kernel.h> #include <sys/device.h> #include <uvm/uvm_param.h> #include <dev/ofw/openfirm.h> #include <machine/autoconf.h> #include <machine/pio.h> #include <dev/wscons/wsdisplayvar.h> #include <dev/wscons/wsconsio.h> #include <dev/wsfont/wsfont.h> #include <dev/rasops/rasops.h> #include <dev/wscons/wsdisplay_vconsvar.h> #include <dev/videomode/videomode.h> #include <arch/macppc/dev/platinumfbreg.h> #include <sys/sysctl.h> #include "opt_wsemul.h" /* * here is a link of supported modes and resolutions: * https://support.apple.com/kb/SP343?locale=en_US * * default console and X bpp/depth for built-in X config file, * select 8 or 16 or 32. * */ #define PLATINUM_CONSOLE_DEPTH 8 #define PLATINUM_FB_DEPTH 16 /* * XXX 16 bit console not working without this patch to rasops15.c, * http://mail-index.netbsd.org/current-users/2016/09/14/msg030132.html * see thread, but rasops may need separate flags for host byte order * and video hw byte order */ /* * resolution, from one of platinumfb_setting vmode_name's. */ #define PLATINUM_FB_VMODE "1024x768x60" struct platinumfb_setting { char vmode_name[24]; int32_t width; int32_t height; uint8_t freq; uint8_t macmode; int32_t pitch[3]; uint32_t regs[26]; uint8_t offset[3]; uint8_t mode[3]; uint8_t dacula_ctrl[3]; uint8_t clock_params[2][2]; }; struct platinumfb_softc { device_t sc_dev; int sc_node; uint8_t *sc_reg; uint32_t sc_reg_size; uint8_t *sc_cmap; uint32_t sc_cmap_size; uint8_t *sc_fb; uint32_t sc_fb_size; int sc_depth; int sc_width, sc_height, sc_linebytes; const struct videomode *sc_videomode; uint8_t sc_modereg; int sc_mode; u_char sc_cmap_red[256]; u_char sc_cmap_green[256]; u_char sc_cmap_blue[256]; struct vcons_data vd; uint8_t sc_cmode; uint8_t sc_dac_type; uint32_t sc_vram; int sc_on; struct platinumfb_setting *sc_pfs; }; #define DIV2 0x20 #define DIV4 0x40 #define DIV8 0x60 #define DIV16 0x80 static struct platinumfb_setting platinum_5 = { "640x480x60", 640, 480, 60, 5, { 672, 1312, 2592 }, { 0xff0, 4, 0, 0, 0, 0, 0x320, 0, 0, 0x15e, 0xc8, 0x18, 0x18f, 0x2f, 0x35, 0x3e, 0x42, 0x182, 0x18e, 0x41a, 0x418, 2, 7, 0x44, 0x404, 0x408 }, { 0x34, 0x3c, 0x41 }, { 2, 0, 0xff }, { 0x11, 0x15, 0x19 }, {{ 26, 0 + DIV8 }, { 14, 2 + DIV4 }} }; static struct platinumfb_setting platinum_12 = { "800x600x75", 800, 600, 75, 12, { 832, 1632, 3232 }, { 0xff0, 4, 0, 0, 0, 0, 0x320, 0, 0, 0x1ce, 0x108, 0x14, 0x20f, 0x27, 0x30, 0x39, 0x72, 0x202, 0x20e, 0x4e2, 0x4e0, 4, 9, 0x2e, 0x4de, 0x4df }, { 0x64, 0x6c, 0x71 }, { 2, 0, 0xff }, { 0x11, 0x15, 0x19 }, {{ 122, 7 + DIV4 }, { 62, 9 + DIV2 }} }; static struct platinumfb_setting platinum_14 = { "1024x768x60", 1024, 768, 60, 14, { 1056, 2080, 4128 }, { 0xff0, 4, 0, 0, 0, 0, 0x320, 0, 0, 0x25a, 0x14f, 0x22, 0x29f, 0x43, 0x49, 0x5b, 0x8e, 0x28e, 0x29e, 0x64c, 0x64a, 0xa, 0xf, 0x44, 0x644, 0x646 }, { 0x80, 0x88, 0x8d }, { 2, 0, 0xff }, { 0x11, 0x15, 0x19 }, {{ 71, 6 + DIV2 }, { 118, 13 + DIV2 }} }; static struct platinumfb_setting platinum_20 = { "1280x1024x75", 1280, 1024, 75, 20, { 1312, 2592, 2592 }, { 0xffc, 4, 0, 0, 0, 0, 0x428, 0, 0, 0xb3, 0xd3, 0x12, 0x1a5, 0x23, 0x28, 0x2d, 0x5e, 0x19e, 0x1a4, 0x854, 0x852, 4, 9, 0x50, 0x850, 0x851 }, { 0x58, 0x5d, 0x5d }, { 0, 0xff, 0xff }, { 0x51, 0x55, 0x55 }, {{ 45, 3 }, { 66, 7 }} }; static struct platinumfb_setting *pfb_setting[] = { &platinum_5, &platinum_12, &platinum_14, &platinum_20 }; static struct vcons_screen platinumfb_console_screen; static int platinumfb_match(device_t, cfdata_t, void *); static void platinumfb_attach(device_t, device_t, void *); CFATTACH_DECL_NEW(platinumfb, sizeof(struct platinumfb_softc), platinumfb_match, platinumfb_attach, NULL, NULL); static int platinumfb_init(device_t); static int platinumfb_set_mode(struct platinumfb_softc *, const struct videomode *, int); static void platinumfb_set_rasops(struct platinumfb_softc *, struct rasops_info *, int); static int platinumfb_ioctl(void *, void *, u_long, void *, int, struct lwp *); static paddr_t platinumfb_mmap(void *, void *, off_t, int); static void platinumfb_init_screen(void *, struct vcons_screen *, int, long *); static int platinumfb_putcmap(struct platinumfb_softc *, struct wsdisplay_cmap *); static int platinumfb_getcmap(struct platinumfb_softc *, struct wsdisplay_cmap *); static void platinumfb_init_cmap(struct platinumfb_softc *); static void platinumfb_restore_palette(struct platinumfb_softc *); static void platinumfb_putpalreg(struct platinumfb_softc *, uint8_t, uint8_t, uint8_t, uint8_t); static uint32_t platinumfb_line_tweak(struct platinumfb_softc *); static paddr_t platinumfb_page_align_up(struct platinumfb_softc *); static void platinumfb_set_clock(struct platinumfb_softc *); static void platinumfb_dac_type(struct platinumfb_softc *); static void platinumfb_memory_size(struct platinumfb_softc *); static void platinumfb_set_hardware(struct platinumfb_softc *); static inline void platinumfb_write_reg(struct platinumfb_softc *, int, uint32_t); #ifdef notyet static inline uint32_t platinumfb_read_reg(struct platinumfb_softc *, int); #endif static inline void platinumfb_write_cmap_reg(struct platinumfb_softc *, int, uint8_t); static inline uint8_t platinumfb_read_cmap_reg(struct platinumfb_softc *, int); static inline void platinumfb_store_d2(struct platinumfb_softc *, uint8_t, uint8_t); struct wsscreen_descr platinumfb_defaultscreen = { "default", 0, 0, NULL, 8, 16, WSSCREEN_WSCOLORS | WSSCREEN_HILIT, NULL, }; const struct wsscreen_descr *_platinumfb_scrlist[] = { &platinumfb_defaultscreen, /* XXX other formats, graphics screen? */ }; struct wsscreen_list platinumfb_screenlist = { sizeof(_platinumfb_scrlist) / sizeof(struct wsscreen_descr *), _platinumfb_scrlist }; struct wsdisplay_accessops platinumfb_accessops = { platinumfb_ioctl, platinumfb_mmap, NULL, NULL, NULL, NULL, /* load_font */ NULL, /* polls */ NULL, /* scroll */ }; static inline void platinumfb_write_reg(struct platinumfb_softc *sc, int reg, uint32_t val) { out32(sc->sc_reg + PLATINUM_REG_OFFSET_ADDR(reg), val); } #ifdef notyet static inline uint32_t platinumfb_read_reg(struct platinumfb_softc *sc, int reg) { return in32(sc->sc_reg + PLATINUM_REG_OFFSET_ADDR(reg)); } #endif static inline void platinumfb_write_cmap_reg(struct platinumfb_softc *sc, int reg_offset, uint8_t val) { out8(sc->sc_cmap + reg_offset, val); } static inline uint8_t platinumfb_read_cmap_reg(struct platinumfb_softc *sc, int reg_offset) { return in8(sc->sc_cmap + reg_offset); } static inline void platinumfb_store_d2(struct platinumfb_softc *sc, uint8_t a, uint8_t d) { platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_ADDR_OFFSET, a + 32); platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_D2_OFFSET, d); } static void platinumfb_putpalreg(struct platinumfb_softc *sc, uint8_t reg, uint8_t r, uint8_t g, uint8_t b) { platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_ADDR_OFFSET, reg); platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_LUT_OFFSET, r); platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_LUT_OFFSET, g); platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_LUT_OFFSET, b); } static uint32_t platinumfb_line_tweak(struct platinumfb_softc *sc) { /* bytes per line adjustment depending on resolution and depth */ if (sc->sc_cmode > PLATINUM_CMODE_8 && strcmp(sc->sc_pfs->vmode_name, "832x624x75") == 0) return 0x10; else return 0x20; } static paddr_t platinumfb_page_align_up(struct platinumfb_softc *sc) { /* round up framebuffer address to the next highest page */ paddr_t addr = (paddr_t)sc->sc_fb; paddr_t ret = round_page(addr); if (ret == addr) ret = round_page(addr + 1); return ret; } /* 2 versions of platinum clock, older one uses clock[1] and * freq = 14.3Mhz * c0 / (c1 & 0x1f) / (1 << (c1 >> 5)) * newer one uses clock[0] and * freq = 15Mhz * c0 / ((c1 & 0x1f) + 2) / (1 << (c1 >> 5)) */ static void platinumfb_set_clock(struct platinumfb_softc *sc) { uint8_t clk_idx = sc->sc_dac_type == PLATINUM_DAC_1 ? 1 : 0; uint8_t d2; platinumfb_store_d2(sc, 6, 0xc6); platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_ADDR_OFFSET, 3+32); d2 = platinumfb_read_cmap_reg(sc, PLATINUM_CMAP_D2_OFFSET); if (d2 == 2) { platinumfb_store_d2(sc, 7, sc->sc_pfs->clock_params[clk_idx][0]); platinumfb_store_d2(sc, 8, sc->sc_pfs->clock_params[clk_idx][1]); platinumfb_store_d2(sc, 3, 3); } else { platinumfb_store_d2(sc, 4, sc->sc_pfs->clock_params[clk_idx][0]); platinumfb_store_d2(sc, 5, sc->sc_pfs->clock_params[clk_idx][1]); platinumfb_store_d2(sc, 3, 2); } delay(5000); platinumfb_store_d2(sc, 9, 0xa6); } static void platinumfb_dac_type(struct platinumfb_softc *sc) { uint8_t dtype = 0; platinumfb_write_cmap_reg(sc, PLATINUM_CMAP_ADDR_OFFSET, 0x40); dtype = platinumfb_read_cmap_reg(sc, PLATINUM_CMAP_D2_OFFSET); switch (dtype) { case PLATINUM_DAC_0: case PLATINUM_DAC_1: /* do nothing */ break; default: aprint_error_dev(sc->sc_dev, "unknown dac 0x%x, using 0x%x\n", dtype, PLATINUM_DAC_0); dtype = PLATINUM_DAC_0; break; } /* save type */ sc->sc_dac_type = dtype; } static void platinumfb_memory_size(struct platinumfb_softc *sc) { int i; off_t offset = PLATINUM_FB_BANK_SIZE; paddr_t total_vram = PLATINUM_FB_MIN_SIZE; uint8_t test_val[] = {0x34, 0x56, 0x78}; uint8_t bank[] = {0, 0, 0}; uint8_t num_elems = sizeof(test_val)/sizeof(test_val[0]); volatile uint8_t *fbuffer = mapiodev((paddr_t)sc->sc_fb, sc->sc_fb_size, false); if (fbuffer == NULL) panic("platinumfb could not mapiodev"); /* turn on all banks of RAM */ platinumfb_write_reg(sc, 16, (paddr_t)sc->sc_fb); platinumfb_write_reg(sc, 20, 0x1011); platinumfb_write_reg(sc, 24, 0); /* * write "unique" value to each bank of memory and read value * back. if match assumes VRAM bank exists. On the powermac 7200, * bank0 is always there and soldered to motherboard, don't know * if that is the case for others */ for (i = 0 ; i < num_elems; i++) { out8(fbuffer + offset, test_val[i]); out8(fbuffer + offset + 0x8, 0x0); __asm volatile ("eieio; dcbf 0,%0"::"r"(&fbuffer[offset]):"memory"); bank[i] = fbuffer[offset] == test_val[i]; total_vram += bank[i] * PLATINUM_FB_BANK_SIZE; offset += PLATINUM_FB_BANK_SIZE; } /* save total vram or minimum */ if (total_vram >= PLATINUM_FB_MIN_SIZE && total_vram <= PLATINUM_FB_MAX_SIZE) { sc->sc_vram = total_vram; } else { aprint_error_dev(sc->sc_dev, "invalid VRAM size 0x%lx, using min 0x%x\n", total_vram, PLATINUM_FB_MIN_SIZE); sc->sc_vram = PLATINUM_FB_MIN_SIZE; } unmapiodev((paddr_t)fbuffer, sc->sc_fb_size); } static int platinumfb_match(device_t parent, cfdata_t cf, void *aux) { struct confargs *ca = aux; return (strcmp(ca->ca_name, "platinum") == 0); } static void platinumfb_attach(device_t parent, device_t self, void *aux) { struct platinumfb_softc *sc = device_private(self); struct confargs *ca = aux; u_int *reg = ca->ca_reg; sc->sc_dev = self; sc->sc_node = ca->ca_node; sc->sc_reg = (uint8_t *)reg[0]; sc->sc_reg_size = reg[1]; sc->sc_fb = (uint8_t *)reg[2]; sc->sc_fb_size = PLATINUM_FB_MAX_SIZE; sc->sc_cmap = (uint8_t *)PLATINUM_CMAP_BASE_ADDR; sc->sc_cmap_size = PLATINUM_CMAP_SIZE; aprint_normal(" reg-addr 0x%08lx fb-addr 0x%08lx cmap-addr 0x%08lx\n", (paddr_t)sc->sc_reg, (paddr_t)sc->sc_fb, (paddr_t)sc->sc_cmap); config_finalize_register(sc->sc_dev, platinumfb_init); } static void platinumfb_init_cmap(struct platinumfb_softc *sc) { int i; uint8_t tmp; switch (sc->sc_cmode) { case PLATINUM_CMODE_8: default: /* R3G3B2 colormap */ for (i = 0; i < 256; i++) { tmp = i & 0xe0; /* * replicate bits so 0xe0 maps to a red value of 0xff * in order to make white look actually white */ tmp |= (tmp >> 3) | (tmp >> 6); sc->sc_cmap_red[i] = tmp; tmp = (i & 0x1c) << 3; tmp |= (tmp >> 3) | (tmp >> 6); sc->sc_cmap_green[i] = tmp; tmp = (i & 0x03) << 6; tmp |= tmp >> 2; tmp |= tmp >> 4; sc->sc_cmap_blue[i] = tmp; } break; case PLATINUM_CMODE_16: for (i = 0; i < 32; i++) { tmp = 255 * i / 32; sc->sc_cmap_red[i] = tmp; sc->sc_cmap_green[i] = tmp; sc->sc_cmap_blue[i] = tmp; } for (i = 32; i < 256; i++) { sc->sc_cmap_red[i] = 0; sc->sc_cmap_blue[i] = 0; sc->sc_cmap_green[i] = 0; } break; case PLATINUM_CMODE_32: for (i = 0; i < 256; i++) { sc->sc_cmap_red[i] = i; sc->sc_cmap_green[i] = i; sc->sc_cmap_blue[i] = i; } break; } } static void platinumfb_restore_palette(struct platinumfb_softc *sc) { int i; for (i = 0; i < 256; i++) { platinumfb_putpalreg(sc, i, sc->sc_cmap_red[i], sc->sc_cmap_green[i], sc->sc_cmap_blue[i]); } } static int platinumfb_init(device_t self) { struct platinumfb_softc *sc = device_private(self); const struct videomode *mode = NULL; struct rasops_info *ri; struct wsemuldisplaydev_attach_args aa; bool is_console = FALSE; long defattr; int i; /* * become console if OF variable "output-device" contains "platinum", * since normal OF video variables are unavailable */ int options; char output_device[128]; options = OF_finddevice("/options"); if (options == 0 || options == -1 || OF_getprop(options, "output-device", output_device, sizeof(output_device)) == 0 ) { aprint_error_dev(sc->sc_dev, "could not get output-device prop, assuming not console\n"); } else { if (strstr(output_device,"platinum")) { is_console = TRUE; } } sc->sc_pfs = NULL; sc->sc_mode = WSDISPLAYIO_MODE_EMUL; sc->sc_on = WSDISPLAYIO_VIDEO_ON; /* determine vram memory and dac clock type */ platinumfb_memory_size(sc); platinumfb_dac_type(sc); aprint_normal_dev(sc->sc_dev,"is_console %d dac 0x%x vram 0x%x\n", is_console, sc->sc_dac_type, sc->sc_vram); for (i=0; i < sizeof(pfb_setting)/sizeof(pfb_setting[0]); i++) { if (strcmp(PLATINUM_FB_VMODE, pfb_setting[i]->vmode_name)==0) { mode = pick_mode_by_ref(pfb_setting[i]->width, pfb_setting[i]->height, pfb_setting[i]->freq); break; } } if (!mode) { aprint_error_dev(sc->sc_dev, "pick_mode_by_ref failed, using default\n"); mode = pick_mode_by_ref(800, 600, 75); } if (platinumfb_set_mode(sc, mode, PLATINUM_CONSOLE_DEPTH) != 0) { aprint_error_dev(sc->sc_dev, "platinumfb_set_mode failed\n"); return 0; } vcons_init(&sc->vd, sc, &platinumfb_defaultscreen, &platinumfb_accessops); sc->vd.init_screen = platinumfb_init_screen; ri = &platinumfb_console_screen.scr_ri; vcons_init_screen(&sc->vd, &platinumfb_console_screen, 1, &defattr); platinumfb_console_screen.scr_flags |= VCONS_SCREEN_IS_STATIC; platinumfb_defaultscreen.textops = &ri->ri_ops; platinumfb_defaultscreen.capabilities = ri->ri_caps; platinumfb_defaultscreen.nrows = ri->ri_rows; platinumfb_defaultscreen.ncols = ri->ri_cols; if (is_console) { wsdisplay_cnattach(&platinumfb_defaultscreen, ri, 0, 0, defattr); vcons_replay_msgbuf(&platinumfb_console_screen); } aa.console = is_console; aa.scrdata = &platinumfb_screenlist; aa.accessops = &platinumfb_accessops; aa.accesscookie = &sc->vd; config_found(self, &aa, wsemuldisplaydevprint, CFARGS_NONE); return 0; } static void platinumfb_set_hardware(struct platinumfb_softc *sc) { int i; bool one_bank = sc->sc_vram == PLATINUM_FB_BANK_SIZE; /* now start programming the chip */ platinumfb_write_reg(sc, 24, 7); /* turn off display */ for (i = 0; i < 26; ++i) platinumfb_write_reg(sc, i+32, sc->sc_pfs->regs[i]); platinumfb_write_reg(sc, 26+32, one_bank ? sc->sc_pfs->offset[sc->sc_cmode] + 4 - sc->sc_cmode : sc->sc_pfs->offset[sc->sc_cmode]); /* * reg 16 apparently needs an address 0x10 less the where frame * buffer/ri_bits start for console text to be aligned. In * addition, X memory maps (mmap) the frame buffer starting on * page boundaries. So to get both X and console text aligned we * start at the first page up from sc_fb[0]. Starting at sc_fb[0] * did work on my machine but not sure if this negative offset * would be problematic elsewhere. * * Not sure why linux used different fb offsets for each mode, as * any addresses seemed to work as long as relative difference was * 0x10. */ platinumfb_write_reg(sc, 16, platinumfb_page_align_up(sc) - 0x10); platinumfb_write_reg(sc, 18, sc->sc_pfs->pitch[sc->sc_cmode]); /* * XXX register 19 setting looks wrong for 1 bank & 32 bpp. * 512x384 is only resolution that would use such a setting, but * that is not currently in videomodes.c */ if (sc->sc_cmode == PLATINUM_CMODE_32 && (sc->sc_pfs->macmode == 1 || sc->sc_pfs->macmode == 2)) aprint_error_dev(sc->sc_dev, "platinumfb reg19 array out-of-bounds"); platinumfb_write_reg(sc, 19, one_bank ? sc->sc_pfs->mode[sc->sc_cmode+1] : /* XXX fix this for 32 bpp */ sc->sc_pfs->mode[sc->sc_cmode]); platinumfb_write_reg(sc, 20, one_bank ? 0x11 : 0x1011); platinumfb_write_reg(sc, 21, 0x100); platinumfb_write_reg(sc, 22, 1); platinumfb_write_reg(sc, 23, 1); platinumfb_write_reg(sc, 26, 0xc00); platinumfb_write_reg(sc, 27, 0x235); /* platinumfb_write_reg(sc, 27, 0x2aa); */ platinumfb_store_d2(sc, 0, one_bank ? sc->sc_pfs->dacula_ctrl[sc->sc_cmode] & 0xf : sc->sc_pfs->dacula_ctrl[sc->sc_cmode]); platinumfb_store_d2(sc, 1, 4); platinumfb_store_d2(sc, 2, 0); platinumfb_set_clock(sc); platinumfb_write_reg(sc, 24, 0); /* turn display on */ } static int platinumfb_set_mode(struct platinumfb_softc *sc, const struct videomode *mode, int depth) { int i; /* first find the parameter for the mode register */ i = 0; while((i < __arraycount(pfb_setting)) && (strcmp(mode->name, pfb_setting[i]->vmode_name) != 0)) i++; if (i >= __arraycount(pfb_setting)) { aprint_error_dev(sc->sc_dev, "Can't find a mode register value for %s\n", mode->name); return EINVAL; } /* found a mode */ sc->sc_pfs = pfb_setting[i]; /* determine depth settings */ switch (depth) { case 8: default: sc->sc_depth = 8; sc->sc_cmode = PLATINUM_CMODE_8; break; case 15: case 16: /* 15 bpp but use 16 so X/wsfb works */ sc->sc_depth = 16; sc->sc_cmode = PLATINUM_CMODE_16; break; case 24: case 32: /* 24 bpp but use 32 so X/wsfb works */ sc->sc_depth = 32; sc->sc_cmode = PLATINUM_CMODE_32; break; } sc->sc_modereg = sc->sc_pfs->macmode; sc->sc_videomode = mode; sc->sc_height = mode->vdisplay; sc->sc_width = mode->hdisplay; sc->sc_linebytes = sc->sc_width * (1 << sc->sc_cmode) + platinumfb_line_tweak(sc); /* check if we have enough video memory */ if (sc->sc_height * sc->sc_linebytes > sc->sc_vram - PAGE_SIZE) { aprint_error_dev(sc->sc_dev, "Not enough video RAM for %s\n", mode->name); return EINVAL; } /* set up and write colormap */ platinumfb_init_cmap(sc); platinumfb_restore_palette(sc); /* set hardware registers */ platinumfb_set_hardware(sc); aprint_normal_dev(sc->sc_dev, "switched to %s in %d bit color\n", sc->sc_pfs->vmode_name, sc->sc_depth); return 0; } static int platinumfb_ioctl(void *v, void *vs, u_long cmd, void *data, int flag, struct lwp *l) { struct vcons_data *vd = v; struct platinumfb_softc *sc = vd->cookie; struct wsdisplay_fbinfo *wdf; struct vcons_screen *ms = vd->active; int i; switch (cmd) { case WSDISPLAYIO_GTYPE: *(u_int *)data = WSDISPLAY_TYPE_PLATINUM; return 0; case WSDISPLAYIO_GINFO: wdf = (void *)data; wdf->height = ms->scr_ri.ri_height; wdf->width = ms->scr_ri.ri_width; wdf->depth = ms->scr_ri.ri_depth; wdf->cmsize = 256; return 0; case WSDISPLAYIO_GVIDEO: *(int *)data = sc->sc_on; return 0; case WSDISPLAYIO_SVIDEO: /* * poor man's screen blanking, just write zeros to colormap * registers but don't save in softc. */ if (*(int *)data != sc->sc_on) { sc->sc_on = (sc->sc_on == WSDISPLAYIO_VIDEO_ON ? WSDISPLAYIO_VIDEO_OFF : WSDISPLAYIO_VIDEO_ON); /* XXX need to lock colormap? */ if (sc->sc_on == WSDISPLAYIO_VIDEO_OFF) { for (i=0; i < 256; i++) platinumfb_putpalreg(sc, i, 0, 0, 0); } else { platinumfb_restore_palette(sc); } } return 0; case WSDISPLAYIO_GETCMAP: if (sc->sc_cmode == PLATINUM_CMODE_8) { return platinumfb_getcmap(sc, (struct wsdisplay_cmap *)data); } else return 0; case WSDISPLAYIO_PUTCMAP: if (sc->sc_cmode == PLATINUM_CMODE_8) { return platinumfb_putcmap(sc, (struct wsdisplay_cmap *)data); } else return 0; case WSDISPLAYIO_SMODE: { int new_mode = *(int*)data; if (new_mode != sc->sc_mode) { int new_depth = new_mode == WSDISPLAYIO_MODE_EMUL ? PLATINUM_CONSOLE_DEPTH : PLATINUM_FB_DEPTH; switch(new_mode) { /* * XXX - not sure how this is supposed to work for * switching bpp between console and X, but cases with * (EMUL MAPPED) or (EMUL MAPPED DUMBFB) work, but * (EMUL DUMBFB) garbles screen for some reason. */ case WSDISPLAYIO_MODE_EMUL: case WSDISPLAYIO_MODE_MAPPED: /* case WSDISPLAYIO_MODE_DUMBFB: XXX */ /* in case screen is "blanked" */ platinumfb_restore_palette(sc); sc->sc_mode = new_mode; platinumfb_set_mode(sc, sc->sc_videomode, new_depth); platinumfb_set_rasops(sc, &ms->scr_ri, true); if (new_mode == WSDISPLAYIO_MODE_EMUL) vcons_redraw_screen(ms); } } return 0; } case WSDISPLAYIO_LINEBYTES: *(u_int *)data = sc->sc_linebytes; return 0; case WSDISPLAYIO_GET_FBINFO: { struct wsdisplayio_fbinfo *fbi = data; return wsdisplayio_get_fbinfo(&ms->scr_ri, fbi); } } return EPASSTHROUGH; } static paddr_t platinumfb_mmap(void *v, void *vs, off_t offset, int prot) { struct vcons_data *vd = v; struct platinumfb_softc *sc = vd->cookie; paddr_t pa = -1; paddr_t fb_aligned = platinumfb_page_align_up(sc); paddr_t fb_vram = sc->sc_vram - (fb_aligned - (paddr_t)sc->sc_fb); /* XXX need to worry about superuser or mapping other registers? */ if (offset >= 0 && offset < fb_vram) pa = fb_aligned + offset; return pa; } static void platinumfb_set_rasops(struct platinumfb_softc *sc, struct rasops_info *ri, int existing) { memset(ri, 0, sizeof(struct rasops_info)); ri->ri_depth = sc->sc_depth; ri->ri_width = sc->sc_width; ri->ri_height = sc->sc_height; ri->ri_stride = sc->sc_linebytes; ri->ri_bits = (u_char*)platinumfb_page_align_up(sc); ri->ri_flg = RI_FULLCLEAR; if (existing) ri->ri_flg |= RI_CLEAR; switch (sc->sc_cmode) { case PLATINUM_CMODE_8: default: ri->ri_flg |= RI_ENABLE_ALPHA | RI_8BIT_IS_RGB; break; case PLATINUM_CMODE_16: if (strcmp(sc->sc_pfs->vmode_name, "640x480x60") == 0 || strcmp(sc->sc_pfs->vmode_name, "800x600x75") == 0 ) ri->ri_flg |= RI_ENABLE_ALPHA; ri->ri_rnum = 5; ri->ri_rpos = 10; ri->ri_gnum = 5; ri->ri_gpos = 5; ri->ri_bnum = 5; ri->ri_bpos = 0; break; case PLATINUM_CMODE_32: if (strcmp(sc->sc_pfs->vmode_name, "640x480x60") == 0 || strcmp(sc->sc_pfs->vmode_name, "800x600x75") == 0 ) ri->ri_flg |= RI_ENABLE_ALPHA; ri->ri_rnum = 8; ri->ri_rpos = 16; ri->ri_gnum = 8; ri->ri_gpos = 8; ri->ri_bnum = 8; ri->ri_bpos = 0; break; } rasops_init(ri, 0, 0); ri->ri_caps = WSSCREEN_WSCOLORS; rasops_reconfig(ri, sc->sc_height / ri->ri_font->fontheight, sc->sc_width / ri->ri_font->fontwidth); } static void platinumfb_init_screen(void *cookie, struct vcons_screen *scr, int existing, long *defattr) { struct platinumfb_softc *sc = cookie; struct rasops_info *ri = &scr->scr_ri; scr->scr_flags |= VCONS_DONT_READ; platinumfb_set_rasops(sc, ri, existing); ri->ri_hw = scr; } static int platinumfb_putcmap(struct platinumfb_softc *sc, struct wsdisplay_cmap *cm) { u_char *r, *g, *b; u_int index = cm->index; u_int count = cm->count; int i, error; u_char rbuf[256], gbuf[256], bbuf[256]; if (cm->index >= 256 || cm->count > 256 || (cm->index + cm->count) > 256) return EINVAL; error = copyin(cm->red, &rbuf[index], count); if (error) return error; error = copyin(cm->green, &gbuf[index], count); if (error) return error; error = copyin(cm->blue, &bbuf[index], count); if (error) return error; memcpy(&sc->sc_cmap_red[index], &rbuf[index], count); memcpy(&sc->sc_cmap_green[index], &gbuf[index], count); memcpy(&sc->sc_cmap_blue[index], &bbuf[index], count); /* write colormap registers if not currently blanked */ if (sc->sc_on == WSDISPLAYIO_VIDEO_ON) { r = &sc->sc_cmap_red[index]; g = &sc->sc_cmap_green[index]; b = &sc->sc_cmap_blue[index]; for (i = 0; i < count; i++) { platinumfb_putpalreg(sc, index, *r, *g, *b); index++; r++, g++, b++; } } return 0; } static int platinumfb_getcmap(struct platinumfb_softc *sc, struct wsdisplay_cmap *cm) { u_int index = cm->index; u_int count = cm->count; int error; if (index >= 255 || count > 256 || index + count > 256) return EINVAL; error = copyout(&sc->sc_cmap_red[index], cm->red, count); if (error) return error; error = copyout(&sc->sc_cmap_green[index], cm->green, count); if (error) return error; error = copyout(&sc->sc_cmap_blue[index], cm->blue, count); if (error) return error; return 0; }
4208dbc8d0c991802e3153f383c74a67c729c6be
a411a55762de11dc2c9d913ff33d2f1477ac02cf
/lte/gateway/c/core/oai/common/common_types.h
1a841cf8c122f191d30a0bc31d5a7b85bb3c8deb
[ "BSD-3-Clause" ]
permissive
magma/magma
0dc48c1513d9968bd05fb7589f302c192b7c0f94
0e1d895dfe625681229e181fbc2dbad83e13c5cb
refs/heads/master
2023-09-04T09:31:56.140395
2023-08-29T13:54:49
2023-08-29T13:54:49
170,803,235
1,219
525
NOASSERTION
2023-09-07T17:45:42
2019-02-15T04:46:24
C++
UTF-8
C
false
false
13,703
h
common_types.h
/* * Copyright (c) 2015, EURECOM (www.eurecom.fr) * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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. * * The views and conclusions contained in the software and documentation are * those of the authors and should not be interpreted as representing official * policies, either expressed or implied, of the FreeBSD Project. */ /*! \file common_types.c \brief \author Sebastien ROUX, Lionel Gauthier \company Eurecom \email: lionel.gauthier@eurecom.fr */ #ifndef FILE_COMMON_TYPES_SEEN #define FILE_COMMON_TYPES_SEEN #include <inttypes.h> #include <stdint.h> #include <stdbool.h> #include "lte/gateway/c/core/common/common_defs.h" #include "lte/gateway/c/core/oai/common/security_types.h" #include "lte/gateway/c/core/oai/include/TrackingAreaIdentity.h" #include "lte/gateway/c/core/oai/lib/3gpp/3gpp_33.401.h" //------------------------------------------------------------------------------ typedef uint16_t sctp_stream_id_t; typedef uint32_t sctp_assoc_id_t; typedef uint32_t sctp_ppid_t; typedef uint64_t enb_s1ap_id_key_t; #define MME_APP_ENB_S1AP_ID_KEY(kEy, eNb_Id, eNb_Ue_S1Ap_Id) \ do { \ kEy = (((enb_s1ap_id_key_t)eNb_Id) << 24) | eNb_Ue_S1Ap_Id; \ } while (0); #define MME_APP_ENB_S1AP_ID_KEY2ENB_S1AP_ID(kEy) \ (enb_ue_s1ap_id_t)(((enb_s1ap_id_key_t)kEy) & ENB_UE_S1AP_ID_MASK) #define MME_APP_ENB_S1AP_ID_KEY_FORMAT "0x%16" PRIX64 #define M_TMSI_BIT_MASK UINT32_MAX //------------------------------------------------------------------------------ // UE S1AP IDs #define INVALID_ENB_UE_S1AP_ID_KEY 0xFFFFFFFFFFFFFFFF #define ENB_UE_S1AP_ID_MASK 0x00FFFFFF #define ENB_UE_S1AP_ID_FMT "%u" #define MME_UE_S1AP_ID_FMT "%u" #define COMP_S1AP_ID_FMT "0x%016" PRIX64 /* INVALID_MME_UE_S1AP_ID * Any value between 0..2^32-1, is allowed/valid as per 3GPP spec 36.413. * Here we are conisdering 0 as invalid. Don't allocate 0 and consider this as * invalid */ #define INVALID_MME_UE_S1AP_ID 0x0 #define INVALID_ENB_UE_S1AP_ID 0x0 // UE NGAP IDs #define INVALID_AMF_UE_NGAP_ID 0x0 #define INVALID_GNB_UE_NGAP_ID_KEY 0xFFFFFFFFFFFFFFFF #define GNB_UE_NGAP_ID_FMT "%u" #define AMF_UE_NGAP_ID_FMT "%lu" /* INVALID_AMF_UE_NGAP_ID * Any value between 0..2^32-1, is allowed/valid as per 3GPP spec 36.413. * Here we are conisdering 0 as invalid. Don't allocate 0 and consider this as * invalid */ #define INVALID_AMF_UE_NGAP_ID 0x0 #define INVALID_GNB_UE_NGAP_ID 0x0 #define AMF_APP_GNB_NGAP_ID_KEY(kEy, gNb_Id, gNb_Ue_NgAp_Id) \ do { \ kEy = (((gnb_ngap_id_key_t)gNb_Id) << 32) | gNb_Ue_NgAp_Id; \ } while (0); //------------------------------------------------------------------------------ // TEIDs typedef uint32_t teid_t; #define TEID_FMT "%u" #define TEID_SCAN_FMT SCNx32 typedef teid_t s11_teid_t; typedef teid_t s1u_teid_t; #define INVALID_TEID 0x00000000 //------------------------------------------------------------------------------ // IMSI typedef uint64_t imsi64_t; typedef uint64_t imei64_t; #define IMSI_64_FMT "%" SCNu64 #define IMEI_64_FMT "%" SCNu64 #define IMSI_64_FMT_DYN_LEN "%.*lu" #define INVALID_IMSI64 (imsi64_t)0 //------------------------------------------------------------------------------ // PLMN #define ASCII_ZERO 0x30 #define PLMN_BYTES 7 //------------------------------------------------------------------------------ #define LAC_FMT "0x%04X" /* Checks LAC validity */ #define LAC_IS_VALID(lac) \ (((lac) != INVALID_LAC_0000) && ((lac) != INVALID_LAC_FFFE)) //------------------------------------------------------------------------------ // GUTI #define GUTI_FMT PLMN_FMT "|%04x|%02x|%08x" #define GUTI_ARG(GuTi_PtR) \ PLMN_ARG(&(GuTi_PtR)->gummei.plmn), (GuTi_PtR)->gummei.mme_gid, \ (GuTi_PtR)->gummei.mme_code, (GuTi_PtR)->m_tmsi #define GUTI_ARG_M5G(GuTi_PtR) \ PLMN_ARG(&(GuTi_PtR)->guamfi.plmn), (GuTi_PtR)->guamfi.amf_gid, \ (GuTi_PtR)->guamfi.amf_code, (GuTi_PtR)->guamfi.amf_Pointer, \ (GuTi_PtR)->m_tmsi #define MSISDN_LENGTH (15) #define IMEI_DIGITS_MAX (15) #define IMEISV_DIGITS_MAX (16) #define CHARGING_CHARACTERISTICS_LENGTH (4) // 3GPP TS 29.061 #define APN_MAX_LENGTH (100) #define PRIORITY_LEVEL_MAX (15) #define PRIORITY_LEVEL_MIN (1) #define BEARERS_PER_UE (11) #define MAX_APN_PER_UE (10) //------------------------------------------------------------------------------ // IPv6 Interface Identifier length in bytes #define IPV6_INTERFACE_ID_LEN 8 // IPv6 Prefix length in bits #define IPV6_PREFIX_LEN 64 //------------------------------------------------------------------------------ typedef uint8_t ksi_t; #define KSI_NO_KEY_AVAILABLE 0x07 typedef uint8_t AcT_t; /* Access Technology */ typedef enum { RAT_WLAN = 0, RAT_VIRTUAL = 1, RAT_UTRAN = 1000, RAT_GERAN = 1001, RAT_GAN = 1002, RAT_HSPA_EVOLUTION = 1003, RAT_EUTRAN = 1004, RAT_NG_RAN = 1006, RAT_CDMA2000_1X = 2000, RAT_HRPD = 2001, RAT_UMB = 2002, RAT_EHRPD = 2003, } rat_type_t; #define NUMBER_OF_RAT_TYPE 12 typedef enum { SS_SERVICE_GRANTED = 0, SS_OPERATOR_DETERMINED_BARRING = 1, SS_MAX, } subscriber_status_t; typedef enum { NAM_PACKET_AND_CIRCUIT = 0, NAM_RESERVED = 1, NAM_ONLY_PACKET = 2, NAM_MAX, } network_access_mode_t; typedef struct supported_features_s { #define FEATURE_LIST_ID_2_EXTERNAL_IDENTIFIER bool external_identifier : 1; #define FEATURE_LIST_ID_2_NR_AS_SECONDARY_RAT (1U) bool nr_as_secondary_rat : 1; bool regional_subscription : 1; } supported_features_t; typedef uint64_t bitrate_t; typedef char* APN_t; typedef uint8_t APNRestriction_t; typedef uint8_t DelayValue_t; typedef uint8_t priority_level_t; #define PRIORITY_LEVEL_FMT "0x%" PRIu8 #define PRIORITY_LEVEL_SCAN_FMT SCNu8 typedef uint32_t SequenceNumber_t; typedef uint32_t access_restriction_t; typedef uint32_t context_identifier_t; typedef uint32_t rau_tau_timer_t; typedef uint32_t ard_t; typedef int pdn_cid_t; // pdn connexion identity, related to esm protocol, // sometimes type is mixed with int return code!!... typedef uint8_t proc_tid_t; // procedure transaction identity, related to esm protocol #define ARD_UTRAN_NOT_ALLOWED (1U) #define ARD_GERAN_NOT_ALLOWED (1U << 1) #define ARD_GAN_NOT_ALLOWED (1U << 2) #define ARD_I_HSDPA_EVO_NOT_ALLOWED (1U << 3) #define ARD_E_UTRAN_NOT_ALLOWED (1U << 4) #define ARD_HO_TO_NON_3GPP_NOT_ALLOWED (1U << 5) #define ARD_MAX (1U << 6) typedef union { uint8_t imei[IMEI_DIGITS_MAX - 1]; // -1 = remove CD/SD digit uint8_t imeisv[IMEISV_DIGITS_MAX]; } me_identity_t; typedef enum { BPS = 0, KBPS = 1, } apn_ambr_bitrate_unit_t; #define AMBR_UNIT_CONVERT_THRESHOLD 65535 typedef struct { apn_ambr_bitrate_unit_t br_unit; bitrate_t br_ul; bitrate_t br_dl; } ambr_t; typedef uint8_t pdn_type_t; typedef enum { IPv4 = 0, IPv6 = 1, IPv4_AND_v6 = 2, IPv4_OR_v6 = 3, IP_MAX, } pdn_type_value_t; typedef struct paa_s { pdn_type_value_t pdn_type; struct in_addr ipv4_address; struct in6_addr ipv6_address; /* Note in rel.8 the ipv6 prefix length has a fixed value of /64 */ uint8_t ipv6_prefix_length; int vlan; } paa_t; //----------------- typedef struct { pdn_type_value_t pdn_type; struct { struct in_addr ipv4_address; struct in6_addr ipv6_address; } address; } ip_address_t; struct fteid_s; typedef struct { #define ZONE_CODE_LEN 2 uint8_t zone_code[ZONE_CODE_LEN]; } regional_subscription_t; //----------------- typedef enum { QCI_1 = 1, QCI_2 = 2, QCI_3 = 3, QCI_4 = 4, QCI_5 = 5, QCI_6 = 6, QCI_7 = 7, QCI_8 = 8, QCI_9 = 9, /* Values from 128 to 254 are operator specific. * Other are reserved. */ QCI_MAX, } qci_e; typedef uint8_t qci_t; #define QCI_FMT "0x%" PRIu8 #define QCI_SCAN_FMT SCNu8 typedef enum { PRE_EMPTION_CAPABILITY_ENABLED = 0, PRE_EMPTION_CAPABILITY_DISABLED = 1, PRE_EMPTION_CAPABILITY_MAX, } pre_emption_capability_t; #define PRE_EMPTION_CAPABILITY_FMT "0x%" PRIu8 #define PRE_EMPTION_CAPABILITY_SCAN_FMT SCNu8 typedef enum { PRE_EMPTION_VULNERABILITY_ENABLED = 0, PRE_EMPTION_VULNERABILITY_DISABLED = 1, PRE_EMPTION_VULNERABILITY_MAX, } pre_emption_vulnerability_t; #define PRE_EMPTION_VULNERABILITY_FMT "0x%" PRIu8 #define PRE_EMPTION_VULNERABILITY_SCAN_FMT SCNu8 typedef struct { priority_level_t priority_level; pre_emption_vulnerability_t pre_emp_vulnerability; pre_emption_capability_t pre_emp_capability; } allocation_retention_priority_t; typedef struct eps_subscribed_qos_profile_s { qci_t qci; allocation_retention_priority_t allocation_retention_priority; } eps_subscribed_qos_profile_t; typedef struct { char value[CHARGING_CHARACTERISTICS_LENGTH + 1]; size_t length; } charging_characteristics_t; typedef struct apn_configuration_s { context_identifier_t context_identifier; /* Each APN configuration can have 0, 1, or 2 ip address: * - 0 means subscribed is dynamically allocated by P-GW depending on the * pdn_type * - 1 Only one type of IP address is returned by HSS * - 2 IPv4 and IPv6 address are returned by HSS and are statically * allocated */ uint8_t nb_ip_address; ip_address_t ip_address[2]; #ifdef ACCESS_POINT_NAME_MAX_LENGTH #define SERVICE_SELECTION_MAX_LENGTH ACCESS_POINT_NAME_MAX_LENGTH #else #define SERVICE_SELECTION_MAX_LENGTH 100 #endif pdn_type_t pdn_type; char service_selection[SERVICE_SELECTION_MAX_LENGTH]; int service_selection_length; eps_subscribed_qos_profile_t subscribed_qos; ambr_t ambr; charging_characteristics_t charging_characteristics; } apn_configuration_t; typedef enum { ALL_APN_CONFIGURATIONS_INCLUDED = 0, MODIFIED_ADDED_APN_CONFIGURATIONS_INCLUDED = 1, ALL_APN_MAX, } all_apn_conf_ind_t; typedef struct { context_identifier_t context_identifier; all_apn_conf_ind_t all_apn_conf_ind; /* Number of APNs provided */ uint8_t nb_apns; /* List of APNs configuration 1 to n elements */ struct apn_configuration_s apn_configuration[MAX_APN_PER_UE]; } apn_config_profile_t; typedef struct { subscriber_status_t subscriber_status; char msisdn[MSISDN_LENGTH + 1]; uint8_t msisdn_length; network_access_mode_t access_mode; access_restriction_t access_restriction; ambr_t subscribed_ambr; apn_config_profile_t apn_config_profile; rau_tau_timer_t rau_tau_timer; charging_characteristics_t default_charging_characteristics; #define MAX_REGIONAL_SUB 10 uint8_t num_zcs; regional_subscription_t reg_sub[MAX_REGIONAL_SUB]; } subscription_data_t; typedef struct authentication_info_s { uint8_t nb_of_vectors; eutran_vector_t eutran_vector[MAX_EPS_AUTH_VECTORS]; } authentication_info_t; typedef struct m5g_authentication_info_s { uint8_t nb_of_vectors; m5gauth_vector_t m5gauth_vector[MAX_EPS_AUTH_VECTORS]; } m5g_authentication_info_t; typedef struct served_tai_s { uint8_t nb_tai; uint16_t* plmn_mcc; uint16_t* plmn_mnc; uint16_t* plmn_mnc_len; uint16_t* tac; } served_tai_t; typedef struct partial_list_s { uint8_t list_type; uint8_t nb_elem; plmn_t* plmn; uint16_t* tac; } partial_list_t; typedef enum { DIAMETER_AUTHENTICATION_DATA_UNAVAILABLE = 4181, DIAMETER_ERROR_USER_UNKNOWN = 5001, DIAMETER_ERROR_ROAMING_NOT_ALLOWED = 5004, DIAMETER_ERROR_UNKNOWN_EPS_SUBSCRIPTION = 5420, DIAMETER_ERROR_RAT_NOT_ALLOWED = 5421, DIAMETER_ERROR_EQUIPMENT_UNKNOWN = 5422, DIAMETER_ERROR_UNKNOWN_SERVING_NODE = 5423, } s6a_experimental_result_t; typedef enum { DIAMETER_SUCCESS = 2001, DIAMETER_UNABLE_TO_COMPLY = 5012, } s6a_base_result_t; typedef struct { #define S6A_RESULT_BASE 0x0 #define S6A_RESULT_EXPERIMENTAL 0x1 unsigned present : 1; union { /* Experimental result as defined in 3GPP TS 29.272 */ s6a_experimental_result_t experimental; /* Diameter basics results as defined in RFC 3588 */ s6a_base_result_t base; } choice; } s6a_result_t; typedef enum { MME_UPDATE_PROCEDURE = 0, SGSN_UPDATE_PROCEDURE, SUBSCRIPTION_WITHDRAWL, UPDATE_PROCEDURE_IWF, INITIAL_ATTACH_PROCEDURE } s6a_cancellation_type_t; #include "lte/gateway/c/core/oai/include/nas/commonDef.h" struct fteid_s; typedef struct tac_list_per_sac_s { uint8_t num_tac_entries; #define MAX_TACS_PER_SAC 10 tac_t tacs[MAX_TACS_PER_SAC]; } tac_list_per_sac_t; #endif /* FILE_COMMON_TYPES_SEEN */
056d189d6e59e6b1de5f0f3140e4bb34daafff5d
7eaf54a78c9e2117247cb2ab6d3a0c20719ba700
/SOFTWARE/A64-TERES/u-boot_new/include/configs/am335x_igep0033.h
c17327fef481a36023876bd40290130282b92f36
[ "LicenseRef-scancode-free-unknown", "Apache-2.0", "GPL-2.0-or-later" ]
permissive
OLIMEX/DIY-LAPTOP
ae82f4ee79c641d9aee444db9a75f3f6709afa92
a3fafd1309135650bab27f5eafc0c32bc3ca74ee
refs/heads/rel3
2023-08-04T01:54:19.483792
2023-04-03T07:18:12
2023-04-03T07:18:12
80,094,055
507
92
Apache-2.0
2023-04-03T07:05:59
2017-01-26T07:25:50
C
UTF-8
C
false
false
9,024
h
am335x_igep0033.h
/* * Copyright (C) 2013, ISEE 2007 SL - http://www.isee.biz/ * * 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. * * This program is distributed "as is" WITHOUT ANY WARRANTY of any * kind, whether express or implied; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef __CONFIG_IGEP0033_H #define __CONFIG_IGEP0033_H #define CONFIG_AM33XX #define CONFIG_OMAP #define CONFIG_OMAP_COMMON #include <asm/arch/omap.h> /* Mach type */ #define MACH_TYPE_IGEP0033 4521 /* Until the next sync */ #define CONFIG_MACH_TYPE MACH_TYPE_IGEP0033 /* Clock defines */ #define V_OSCK 24000000 /* Clock output from T2 */ #define V_SCLK (V_OSCK) #define CONFIG_ENV_SIZE (128 << 10) /* 128 KiB */ #define CONFIG_SYS_MALLOC_LEN (1024 << 10) #define CONFIG_SYS_LONGHELP /* undef to save memory */ #define CONFIG_SYS_HUSH_PARSER /* use "hush" command parser */ #define CONFIG_SYS_PROMPT "U-Boot# " #define CONFIG_SYS_NO_FLASH /* Display cpuinfo */ #define CONFIG_DISPLAY_CPUINFO /* Flattened Device Tree */ #define CONFIG_OF_LIBFDT /* Commands to include */ #include <config_cmd_default.h> #define CONFIG_CMD_ASKENV #define CONFIG_CMD_BOOTZ #define CONFIG_CMD_DHCP #define CONFIG_CMD_ECHO #define CONFIG_CMD_EXT4 #define CONFIG_CMD_FAT #define CONFIG_CMD_FS_GENERIC #define CONFIG_CMD_MMC #define CONFIG_CMD_MTDPARTS #define CONFIG_CMD_NAND #define CONFIG_CMD_NET #define CONFIG_CMD_PING #define CONFIG_CMD_UBI #define CONFIG_CMD_UBIFS /* Make the verbose messages from UBI stop printing */ #define CONFIG_UBI_SILENCE_MSG #define CONFIG_UBIFS_SILENCE_MSG #define CONFIG_BOOTDELAY 1 /* negative for no autoboot */ #define CONFIG_ENV_VARS_UBOOT_CONFIG #define CONFIG_ENV_VARS_UBOOT_RUNTIME_CONFIG #define CONFIG_EXTRA_ENV_SETTINGS \ "loadaddr=0x80F80000\0" \ "dtbaddr=0x80200000\0" \ "bootdir=/boot\0" \ "bootfile=zImage\0" \ "dtbfile=am335x-base0033.dtb\0" \ "console=ttyO0,115200n8\0" \ "mtdids=" MTDIDS_DEFAULT "\0" \ "mtdparts=" MTDPARTS_DEFAULT "\0" \ "mmcdev=0\0" \ "mmcroot=/dev/mmcblk0p2 rw\0" \ "ubiroot=ubi0:filesystem rw ubi.mtd=3,2048\0" \ "mmcrootfstype=ext4 rootwait\0" \ "ubirootfstype=ubifs rootwait\0" \ "mmcargs=setenv bootargs console=${console} " \ "root=${mmcroot} " \ "rootfstype=${mmcrootfstype}\0" \ "ubiargs=setenv bootargs console=${console} " \ "root=${ubiroot} " \ "rootfstype=${ubirootfstype}\0" \ "bootenv=uEnv.txt\0" \ "loadbootenv=load mmc ${mmcdev} ${loadaddr} ${bootenv}\0" \ "importbootenv=echo Importing environment from mmc ...; " \ "env import -t ${loadaddr} ${filesize}\0" \ "mmcload=load mmc ${mmcdev}:2 ${loadaddr} ${bootdir}/${bootfile}; " \ "load mmc ${mmcdev}:2 ${dtbaddr} ${bootdir}/${dtbfile}\0" \ "ubiload=ubi part filesystem 2048; ubifsmount ubi0; " \ "ubifsload ${loadaddr} ${bootdir}/${bootfile}; " \ "ubifsload ${dtbaddr} ${bootdir}/${dtbfile} \0" \ "mmcboot=echo Booting from mmc ...; " \ "run mmcargs; " \ "bootz ${loadaddr} - ${dtbaddr}\0" \ "ubiboot=echo Booting from nand (ubifs) ...; " \ "run ubiargs; run ubiload; " \ "bootz ${loadaddr} - ${dtbaddr}\0" \ #define CONFIG_BOOTCOMMAND \ "mmc dev ${mmcdev}; if mmc rescan; then " \ "echo SD/MMC found on device ${mmcdev};" \ "if run loadbootenv; then " \ "echo Loaded environment from ${bootenv};" \ "run importbootenv;" \ "fi;" \ "if test -n $uenvcmd; then " \ "echo Running uenvcmd ...;" \ "run uenvcmd;" \ "fi;" \ "if run mmcload; then " \ "run mmcboot;" \ "fi;" \ "else " \ "run ubiboot;" \ "fi;" \ /* Max number of command args */ #define CONFIG_SYS_MAXARGS 16 /* Console I/O Buffer Size */ #define CONFIG_SYS_CBSIZE 512 /* Print Buffer Size */ #define CONFIG_SYS_PBSIZE (CONFIG_SYS_CBSIZE \ + sizeof(CONFIG_SYS_PROMPT) + 16) /* Boot Argument Buffer Size */ #define CONFIG_SYS_BARGSIZE CONFIG_SYS_CBSIZE #define CONFIG_SYS_LOAD_ADDR 0x81000000 /* Default load address */ /* Physical Memory Map */ #define CONFIG_NR_DRAM_BANKS 1 /* 1 bank of DRAM */ #define CONFIG_MAX_RAM_BANK_SIZE (1024 << 20) /* 1GB */ #define CONFIG_SYS_SDRAM_BASE 0x80000000 #define CONFIG_SYS_INIT_SP_ADDR (NON_SECURE_SRAM_END - \ GENERATED_GBL_DATA_SIZE) /* Platform/Board specific defs */ #define CONFIG_SYS_TIMERBASE 0x48040000 /* Use Timer2 */ #define CONFIG_SYS_PTV 2 /* Divisor: 2^(PTV+1) => 8 */ /* NS16550 Configuration */ #define CONFIG_SYS_NS16550 #define CONFIG_SYS_NS16550_SERIAL #define CONFIG_SYS_NS16550_REG_SIZE (-4) #define CONFIG_SYS_NS16550_CLK (48000000) #define CONFIG_SYS_NS16550_COM1 0x44e09000 /* UART0 */ #define CONFIG_CONS_INDEX 1 #define CONFIG_BAUDRATE 115200 /* CPU */ #define CONFIG_ARCH_CPU_INIT #define CONFIG_ENV_OVERWRITE 1 #define CONFIG_SYS_CONSOLE_INFO_QUIET /* MMC support */ #define CONFIG_MMC #define CONFIG_GENERIC_MMC #define CONFIG_OMAP_HSMMC #define CONFIG_DOS_PARTITION /* GPIO support */ #define CONFIG_OMAP_GPIO /* Ethernet support */ #define CONFIG_DRIVER_TI_CPSW #define CONFIG_MII #define CONFIG_BOOTP_DNS #define CONFIG_BOOTP_DNS2 #define CONFIG_BOOTP_SEND_HOSTNAME #define CONFIG_BOOTP_GATEWAY #define CONFIG_BOOTP_SUBNETMASK #define CONFIG_NET_RETRY_COUNT 10 #define CONFIG_NET_MULTI #define CONFIG_PHYLIB #define CONFIG_PHY_SMSC /* NAND support */ #define CONFIG_NAND #define CONFIG_NAND_OMAP_GPMC #define CONFIG_NAND_OMAP_ELM #define CONFIG_SYS_NAND_BASE (0x08000000) /* phys address CS0 */ #define CONFIG_SYS_MAX_NAND_DEVICE 1 #define CONFIG_SYS_NAND_ONFI_DETECTION 1 #define CONFIG_SYS_ENV_SECT_SIZE (128 << 10) /* 128 KiB */ #define CONFIG_SYS_REDUNDAND_ENVIRONMENT #define CONFIG_ENV_IS_IN_NAND #define CONFIG_ENV_OFFSET 0x180000 /* environment starts here */ #define CONFIG_ENV_ADDR_REDUND (CONFIG_ENV_OFFSET + CONFIG_SYS_ENV_SECT_SIZE) #define CONFIG_ENV_SIZE_REDUND (CONFIG_ENV_SIZE) #define CONFIG_MTD_PARTITIONS #define CONFIG_MTD_DEVICE #define CONFIG_RBTREE #define CONFIG_LZO #define MTDIDS_DEFAULT "nand0=omap2-nand.0" #define MTDPARTS_DEFAULT "mtdparts=omap2-nand.0:512k(spl),"\ "1m(uboot),256k(environment),"\ "-(filesystem)" /* Unsupported features */ #undef CONFIG_USE_IRQ /* Defines for SPL */ #define CONFIG_SPL #define CONFIG_SPL_FRAMEWORK /* * Place the image at the start of the ROM defined image space. * We limit our size to the ROM-defined downloaded image area, and use the * rest of the space for stack. */ #define CONFIG_SPL_TEXT_BASE 0x402F0400 #define CONFIG_SPL_MAX_SIZE (0x4030C000 - CONFIG_SPL_TEXT_BASE) #define CONFIG_SPL_STACK CONFIG_SYS_INIT_SP_ADDR #define CONFIG_SPL_BSS_START_ADDR 0x80000000 #define CONFIG_SPL_BSS_MAX_SIZE 0x80000 /* 512 KB */ #define CONFIG_SYS_MMCSD_RAW_MODE_U_BOOT_SECTOR 0x300 /* address 0x60000 */ #define CONFIG_SYS_U_BOOT_MAX_SIZE_SECTORS 0x200 /* 256 KB */ #define CONFIG_SYS_MMC_SD_FAT_BOOT_PARTITION 1 #define CONFIG_SPL_FAT_LOAD_PAYLOAD_NAME "u-boot.img" #define CONFIG_SPL_MMC_SUPPORT #define CONFIG_SPL_FAT_SUPPORT #define CONFIG_SPL_LIBCOMMON_SUPPORT #define CONFIG_SPL_LIBDISK_SUPPORT #define CONFIG_SPL_LIBGENERIC_SUPPORT #define CONFIG_SPL_SERIAL_SUPPORT #define CONFIG_SPL_GPIO_SUPPORT #define CONFIG_SPL_YMODEM_SUPPORT #define CONFIG_SPL_LDSCRIPT "$(CPUDIR)/am33xx/u-boot-spl.lds" #define CONFIG_SPL_BOARD_INIT #define CONFIG_SPL_NAND_AM33XX_BCH #define CONFIG_SPL_NAND_SUPPORT #define CONFIG_SPL_NAND_BASE #define CONFIG_SPL_NAND_DRIVERS #define CONFIG_SPL_NAND_ECC #define CONFIG_SYS_NAND_5_ADDR_CYCLE #define CONFIG_SYS_NAND_PAGE_COUNT (CONFIG_SYS_NAND_BLOCK_SIZE / \ CONFIG_SYS_NAND_PAGE_SIZE) #define CONFIG_SYS_NAND_PAGE_SIZE 2048 #define CONFIG_SYS_NAND_OOBSIZE 64 #define CONFIG_SYS_NAND_BLOCK_SIZE (128*1024) #define CONFIG_SYS_NAND_BAD_BLOCK_POS NAND_LARGE_BADBLOCK_POS #define CONFIG_SYS_NAND_ECCPOS { 2, 3, 4, 5, 6, 7, 8, 9, \ 10, 11, 12, 13, 14, 15, 16, 17, \ 18, 19, 20, 21, 22, 23, 24, 25, \ 26, 27, 28, 29, 30, 31, 32, 33, \ 34, 35, 36, 37, 38, 39, 40, 41, \ 42, 43, 44, 45, 46, 47, 48, 49, \ 50, 51, 52, 53, 54, 55, 56, 57, } #define CONFIG_SYS_NAND_ECCSIZE 512 #define CONFIG_SYS_NAND_ECCBYTES 14 #define CONFIG_NAND_OMAP_ECCSCHEME OMAP_ECC_BCH8_CODE_HW #define CONFIG_SYS_NAND_U_BOOT_START CONFIG_SYS_TEXT_BASE #define CONFIG_SYS_NAND_U_BOOT_OFFS 0x80000 /* * 1MB into the SDRAM to allow for SPL's bss at the beginning of SDRAM * 64 bytes before this address should be set aside for u-boot.img's * header. That is 0x800FFFC0--0x80100000 should not be used for any * other needs. */ #define CONFIG_SYS_TEXT_BASE 0x80800000 #define CONFIG_SYS_SPL_MALLOC_START 0x80208000 #define CONFIG_SYS_SPL_MALLOC_SIZE 0x100000 /* * Since SPL did pll and ddr initialization for us, * we don't need to do it twice. */ #ifndef CONFIG_SPL_BUILD #define CONFIG_SKIP_LOWLEVEL_INIT #endif #endif /* ! __CONFIG_IGEP0033_H */
cb3fad24fcfcb29bedab3537c0bb74380e5206bc
af3c84d99e1dec9fc131eb1f91f1f66135f7cb1a
/leaf/Inc/leaf-filters.h
0ec9cc6a082636e86ef7525f34a0134e37b49215
[ "MIT" ]
permissive
spiricom/LEAF
9429f08826cfa2cf4650b12cd1dabdc83628f55c
24536188a26343aa3f52f3303b445e4f1509ae33
refs/heads/master
2023-08-29T09:26:29.005874
2023-04-26T13:15:08
2023-04-26T13:15:08
158,136,606
153
24
null
2019-05-15T17:08:50
2018-11-18T23:20:42
C
UTF-8
C
false
false
46,596
h
leaf-filters.h
/*============================================================================== leaf-filters.h Created: 20 Jan 2017 12:01:10pm Author: Michael R Mulshine ==============================================================================*/ #ifndef LEAF_FILTERS_H_INCLUDED #define LEAF_FILTERS_H_INCLUDED #ifdef __cplusplus extern "C" { #endif //============================================================================== #include "leaf-math.h" #include "leaf-mempool.h" #include "leaf-delay.h" #include "leaf-tables.h" /*! * @internal * Header. * @include basic-oscillators.h * @example basic-oscillators.c * An example. */ //============================================================================== /*! @defgroup tallpass tAllpass @ingroup filters @brief Schroeder allpass. Comb-filter with feedforward and feedback. @{ @fn void tAllpass_init (tAllpass* const, float initDelay, uint32_t maxDelay, LEAF* const leaf) @brief Initialize a tAllpass to the default mempool of a LEAF instance. @param filter A pointer to the tAllpass to initialize. @param leaf A pointer to the leaf instance. @fn void tAllpass_initToPool (tAllpass* const, float initDelay, uint32_t maxDelay, tMempool* const) @brief Initialize a tAllpass to a specified mempool. @param filter A pointer to the tAllpass to initialize. @param mempool A pointer to the tMempool to use. @fn void tAllpass_free (tAllpass* const) @brief Free a tAllpass from its mempool. @param filter A pointer to the tAllpass to free. @fn float tAllpass_tick (tAllpass* const, float input) @brief @param filter A pointer to the relevant tAllpass. @fn void tAllpass_setGain (tAllpass* const, float gain) @brief @param filter A pointer to the relevant tAllpass. @fn void tAllpass_setDelay (tAllpass* const, float delay) @brief @param filter A pointer to the relevant tAllpass.  @} */ typedef struct _tAllpass { tMempool mempool; float gain; tLinearDelay delay; float lastOut; } _tAllpass; typedef _tAllpass* tAllpass; void tAllpass_init (tAllpass* const, float initDelay, uint32_t maxDelay, LEAF* const leaf); void tAllpass_initToPool (tAllpass* const, float initDelay, uint32_t maxDelay, tMempool* const); void tAllpass_free (tAllpass* const); float tAllpass_tick (tAllpass* const, float input); void tAllpass_setGain (tAllpass* const, float gain); void tAllpass_setDelay (tAllpass* const, float delay); //============================================================================== /*! @defgroup tonepole tOnePole @ingroup filters @brief OnePole filter, reimplemented from STK (Cook and Scavone). @{ @fn void tOnePole_init (tOnePole* const, float thePole, LEAF* const leaf) @brief Initialize a tOnePole to the default mempool of a LEAF instance. @param filter A pointer to the tOnePole to initialize. @param leaf A pointer to the leaf instance. @fn void tOnePole_initToPool (tOnePole* const, float thePole, tMempool* const) @brief Initialize a tOnePole to a specified mempool. @param filter A pointer to the tOnePole to initialize. @param mempool A pointer to the tMempool to use. @fn void tOnePole_free (tOnePole* const) @brief Free a tOnePole from its mempool. @param filter A pointer to the tOnePole to free. @fn float tOnePole_tick (tOnePole* const, float input) @brief @param filter A pointer to the relevant tOnePole. @fn void tOnePole_setB0 (tOnePole* const, float b0) @brief @param filter A pointer to the relevant tOnePole. @fn void tOnePole_setA1 (tOnePole* const, float a1) @brief @param filter A pointer to the relevant tOnePole. @fn void tOnePole_setPole (tOnePole* const, float thePole) @brief @param filter A pointer to the relevant tOnePole. @fn void tOnePole_setFreq (tOnePole* const, float freq) @brief @param filter A pointer to the relevant tOnePole. @fn void tOnePole_setCoefficients(tOnePole* const, float b0, float a1) @brief @param filter A pointer to the relevant tOnePole. @fn void tOnePole_setGain (tOnePole* const, float gain) @brief @param filter A pointer to the relevant tOnePole.  @} */ typedef struct _tOnePole { tMempool mempool; float freq; float gain; float a0,a1; float b0,b1; float lastIn, lastOut; float twoPiTimesInvSampleRate; } _tOnePole; typedef _tOnePole* tOnePole; void tOnePole_init (tOnePole* const, float thePole, LEAF* const leaf); void tOnePole_initToPool (tOnePole* const, float thePole, tMempool* const); void tOnePole_free (tOnePole* const); float tOnePole_tick (tOnePole* const, float input); void tOnePole_setB0 (tOnePole* const, float b0); void tOnePole_setA1 (tOnePole* const, float a1); void tOnePole_setPole (tOnePole* const, float thePole); void tOnePole_setFreq (tOnePole* const, float freq); void tOnePole_setCoefficients(tOnePole* const, float b0, float a1); void tOnePole_setGain (tOnePole* const, float gain); void tOnePole_setSampleRate (tOnePole* const, float sr); //============================================================================== /*! @defgroup ttwopole tTwoPole @ingroup filters @brief TwoPole filter, reimplemented from STK (Cook and Scavone). @{ @fn void tTwoPole_init (tTwoPole* const, LEAF* const leaf) @brief Initialize a tTwoPole to the default mempool of a LEAF instance. @param filter A pointer to the tTwoPole to initialize. @param leaf A pointer to the leaf instance. @fn void tTwoPole_initToPool (tTwoPole* const, tMempool* const) @brief Initialize a tTwoPole to a specified mempool. @param filter A pointer to the tTwoPole to initialize. @param mempool A pointer to the tMempool to use. @fn void tTwoPole_free (tTwoPole* const) @brief Free a tTwoPole from its mempool. @param filter A pointer to the tTwoPole to free. @fn float tTwoPole_tick (tTwoPole* const, float input) @brief @param filter A pointer to the relevant tTwoPole. @fn void tTwoPole_setB0 (tTwoPole* const, float b0) @brief @param filter A pointer to the relevant tTwoPole. @fn void tTwoPole_setA1 (tTwoPole* const, float a1) @brief @param filter A pointer to the relevant tTwoPole. @fn void tTwoPole_setA2 (tTwoPole* const, float a2) @brief @param filter A pointer to the relevant tTwoPole. @fn void tTwoPole_setResonance (tTwoPole* const, float freq, float radius, int normalize) @brief @param filter A pointer to the relevant tTwoPole. @fn void tTwoPole_setCoefficients(tTwoPole* const, float b0, float a1, float a2) @brief @param filter A pointer to the relevant tTwoPole. @fn void tTwoPole_setGain (tTwoPole* const, float gain) @brief @param filter A pointer to the relevant tTwoPole.  @} */ typedef struct _tTwoPole { tMempool mempool; float gain; float a0, a1, a2; float b0; float radius, frequency; int normalize; float lastOut[2]; float sampleRate; float twoPiTimesInvSampleRate; } _tTwoPole; typedef _tTwoPole* tTwoPole; void tTwoPole_init (tTwoPole* const, LEAF* const leaf); void tTwoPole_initToPool (tTwoPole* const, tMempool* const); void tTwoPole_free (tTwoPole* const); float tTwoPole_tick (tTwoPole* const, float input); void tTwoPole_setB0 (tTwoPole* const, float b0); void tTwoPole_setA1 (tTwoPole* const, float a1); void tTwoPole_setA2 (tTwoPole* const, float a2); void tTwoPole_setResonance (tTwoPole* const, float freq, float radius, int normalize); void tTwoPole_setCoefficients(tTwoPole* const, float b0, float a1, float a2); void tTwoPole_setGain (tTwoPole* const, float gain); void tTwoPole_setSampleRate (tTwoPole* const, float sr); //============================================================================== /*! @defgroup tonezero tOneZero @ingroup filters @brief OneZero filter, reimplemented from STK (Cook and Scavone). @{ @fn void tOneZero_init (tOneZero* const, float theZero, LEAF* const leaf) @brief Initialize a tOneZero to the default mempool of a LEAF instance. @param filter A pointer to the tSlide to initialize. @param leaf A pointer to the leaf instance. @fn void tOneZero_initToPool (tOneZero* const, float theZero, tMempool* const) @brief Initialize a tOneZero to a specified mempool. @param filter A pointer to the tOneZero to initialize. @param mempool A pointer to the tMempool to use. @fn void tOneZero_free (tOneZero* const) @brief Free a tOneZero from its mempool. @param filter A pointer to the tOneZero to free. @fn float tOneZero_tick (tOneZero* const, float input) @brief @param filter A pointer to the relevant tOneZero. @fn void tOneZero_setB0 (tOneZero* const, float b0) @brief @param filter A pointer to the relevant tOneZero. @fn void tOneZero_setB1 (tOneZero* const, float b1) @brief @param filter A pointer to the relevant tOneZero. @fn void tOneZero_setZero (tOneZero* const, float theZero) @brief @param filter A pointer to the relevant tOneZero. @fn void tOneZero_setCoefficients(tOneZero* const, float b0, float b1) @brief @param filter A pointer to the relevant tOneZero. @fn void tOneZero_setGain (tOneZero* const, float gain) @brief @param filter A pointer to the relevant tOneZero. @fn float tOneZero_getPhaseDelay (tOneZero *f, float frequency) @brief @param filter A pointer to the relevant tOneZero.  @} */ typedef struct _tOneZero { tMempool mempool; float gain; float b0,b1; float lastIn, lastOut, frequency; float invSampleRate; } _tOneZero; typedef _tOneZero* tOneZero; void tOneZero_init (tOneZero* const, float theZero, LEAF* const leaf); void tOneZero_initToPool (tOneZero* const, float theZero, tMempool* const); void tOneZero_free (tOneZero* const); float tOneZero_tick (tOneZero* const, float input); void tOneZero_setB0 (tOneZero* const, float b0); void tOneZero_setB1 (tOneZero* const, float b1); void tOneZero_setZero (tOneZero* const, float theZero); void tOneZero_setCoefficients(tOneZero* const, float b0, float b1); void tOneZero_setGain (tOneZero* const, float gain); float tOneZero_getPhaseDelay (tOneZero* const, float frequency); void tOneZero_setSampleRate (tOneZero* const, float sr); //============================================================================== /*! @defgroup ttwozero tTwoZero @ingroup filters @brief TwoZero filter, reimplemented from STK (Cook and Scavone). @{ @fn void tTwoZero_init (tTwoZero* const, LEAF* const leaf) @brief Initialize a tTwoZero to the default mempool of a LEAF instance. @param filter A pointer to the tTwoZero to initialize. @param leaf A pointer to the leaf instance. @fn void tTwoZero_initToPool (tTwoZero* const, tMempool* const) @brief Initialize a tTwoZero to a specified mempool. @param filter A pointer to the tTwoZero to initialize. @param mempool A pointer to the tMempool to use. @fn void tTwoZero_free (tTwoZero* const) @brief Free a tTwoZero from its mempool. @param filter A pointer to the tTwoZero to free. @fn float tTwoZero_tick (tTwoZero* const, float input) @brief @param filter A pointer to the relevant tTwoZero. @fn void tTwoZero_setB0 (tTwoZero* const, float b0) @brief @param filter A pointer to the relevant tTwoZero. @fn void tTwoZero_setB1 (tTwoZero* const, float b1) @brief @param filter A pointer to the relevant tTwoZero. @fn void tTwoZero_setB2 (tTwoZero* const, float b2) @brief @param filter A pointer to the relevant tTwoZero. @fn void tTwoZero_setNotch (tTwoZero* const, float frequency, float radius) @brief @param filter A pointer to the relevant tTwoZero. @fn void tTwoZero_setCoefficients(tTwoZero* const, float b0, float b1, float b2) @brief @param filter A pointer to the relevant tTwoZero. @fn void tTwoZero_setGain (tTwoZero* const, float gain) @brief @param filter A pointer to the relevant tTwoZero.  @} */ typedef struct _tTwoZero { tMempool mempool; float gain; float b0, b1, b2; float frequency, radius; float lastIn[2]; float twoPiTimesInvSampleRate; } _tTwoZero; typedef _tTwoZero* tTwoZero; void tTwoZero_init (tTwoZero* const, LEAF* const leaf); void tTwoZero_initToPool (tTwoZero* const, tMempool* const); void tTwoZero_free (tTwoZero* const); float tTwoZero_tick (tTwoZero* const, float input); void tTwoZero_setB0 (tTwoZero* const, float b0); void tTwoZero_setB1 (tTwoZero* const, float b1); void tTwoZero_setB2 (tTwoZero* const, float b2); void tTwoZero_setNotch (tTwoZero* const, float frequency, float radius); void tTwoZero_setCoefficients(tTwoZero* const, float b0, float b1, float b2); void tTwoZero_setGain (tTwoZero* const, float gain); void tTwoZero_setSampleRate (tTwoZero* const, float sr); //============================================================================== /*! @defgroup tpolezero tPoleZero @ingroup filters @brief PoleZero filter, reimplemented from STK (Cook and Scavone). @{ @fn void tPoleZero_init (tPoleZero* const, LEAF* const leaf) @brief Initialize a tPoleZero to the default mempool of a LEAF instance. @param filter A pointer to the tPoleZero to initialize. @param leaf A pointer to the leaf instance. @fn void tPoleZero_initToPool (tPoleZero* const, tMempool* const) @brief Initialize a tPoleZero to a specified mempool. @param filter A pointer to the tPoleZero to initialize. @param mempool A pointer to the tMempool to use. @fn void tPoleZero_free (tPoleZero* const) @brief Free a tPoleZero from its mempool. @param filter A pointer to the tPoleZero to free. @fn float tPoleZero_tick (tPoleZero* const, float input) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setB0 (tPoleZero* const, float b0) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setB1 (tPoleZero* const, float b1) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setA1 (tPoleZero* const, float a1) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setCoefficients (tPoleZero* const, float b0, float b1, float a1) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setAllpass (tPoleZero* const, float coeff) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setBlockZero (tPoleZero* const, float thePole) @brief @param filter A pointer to the relevant tPoleZero. @fn void tPoleZero_setGain (tPoleZero* const, float gain) @brief @param filter A pointer to the relevant tPoleZero.  @} */ typedef struct _tPoleZero { tMempool mempool; float gain; float a0,a1; float b0,b1; float lastIn, lastOut; } _tPoleZero; typedef _tPoleZero* tPoleZero; void tPoleZero_init (tPoleZero* const, LEAF* const leaf); void tPoleZero_initToPool (tPoleZero* const, tMempool* const); void tPoleZero_free (tPoleZero* const); float tPoleZero_tick (tPoleZero* const, float input); void tPoleZero_setB0 (tPoleZero* const, float b0); void tPoleZero_setB1 (tPoleZero* const, float b1); void tPoleZero_setA1 (tPoleZero* const, float a1); void tPoleZero_setCoefficients (tPoleZero* const, float b0, float b1, float a1); void tPoleZero_setAllpass (tPoleZero* const, float coeff); void tPoleZero_setBlockZero (tPoleZero* const, float thePole); void tPoleZero_setGain (tPoleZero* const, float gain); //============================================================================== /*! @defgroup tbiquad tBiQuad @ingroup filters @brief BiQuad filter, reimplemented from STK (Cook and Scavone). @{ @fn void tBiQuad_init (tBiQuad* const, LEAF* const leaf) @brief Initialize a tBiQuad to the default mempool of a LEAF instance. @param filter A pointer to the tBiQuad to initialize. @param leaf A pointer to the leaf instance. @fn void tBiQuad_initToPool (tBiQuad* const, tMempool* const) @brief Initialize a tBiQuad to a specified mempool. @param filter A pointer to the tBiQuad to initialize. @param mempool A pointer to the tMempool to use. @fn void tBiQuad_free (tBiQuad* const) @brief Free a tBiQuad from its mempool. @param filter A pointer to the tBiQuad to free. @fn float tBiQuad_tick (tBiQuad* const, float input) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setB0 (tBiQuad* const, float b0) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setB1 (tBiQuad* const, float b1) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setB2 (tBiQuad* const, float b2) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setA1 (tBiQuad* const, float a1) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setA2 (tBiQuad* const, float a2) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setNotch (tBiQuad* const, float freq, float radius) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setResonance (tBiQuad* const, float freq, float radius, int normalize) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setCoefficients(tBiQuad* const, float b0, float b1, float b2, float a1, float a2) @brief @param filter A pointer to the relevant tBiQuad. @fn void tBiQuad_setGain (tBiQuad* const, float gain) @brief @param filter A pointer to the relevant tBiQuad.  @} */ typedef struct _tBiQuad { tMempool mempool; float gain; float a0, a1, a2; float b0, b1, b2; float lastIn[2]; float lastOut[2]; float frequency, radius; int normalize; float sampleRate; float twoPiTimesInvSampleRate; } _tBiQuad; typedef _tBiQuad* tBiQuad; void tBiQuad_init (tBiQuad* const, LEAF* const leaf); void tBiQuad_initToPool (tBiQuad* const, tMempool* const); void tBiQuad_free (tBiQuad* const); float tBiQuad_tick (tBiQuad* const, float input); void tBiQuad_setB0 (tBiQuad* const, float b0); void tBiQuad_setB1 (tBiQuad* const, float b1); void tBiQuad_setB2 (tBiQuad* const, float b2); void tBiQuad_setA1 (tBiQuad* const, float a1); void tBiQuad_setA2 (tBiQuad* const, float a2); void tBiQuad_setNotch (tBiQuad* const, float freq, float radius); void tBiQuad_setResonance (tBiQuad* const, float freq, float radius, int normalize); void tBiQuad_setCoefficients(tBiQuad* const, float b0, float b1, float b2, float a1, float a2); void tBiQuad_setGain (tBiQuad* const, float gain); void tBiQuad_setSampleRate (tBiQuad* const, float sr); //============================================================================== /*! @defgroup tsvf tSVF @ingroup filters @brief State Variable Filter, algorithm from Andy Simper. @{ @fn void tSVF_init (tSVF* const, SVFType type, float freq, float Q, LEAF* const leaf) @brief Initialize a tSVF to the default mempool of a LEAF instance. @param filter A pointer to the tSVF to initialize. @param leaf A pointer to the leaf instance. @fn void tSVF_initToPool (tSVF* const, SVFType type, float freq, float Q, tMempool* const) @brief Initialize a tSVF to a specified mempool. @param filter A pointer to the tSVF to initialize. @param mempool A pointer to the tMempool to use. @fn void tSVF_free (tSVF* const) @brief Free a tSVF from its mempool. @param filter A pointer to the tSVF to free. @fn float tSVF_tick (tSVF* const, float v0) @brief @param filter A pointer to the relevant tSVF. @fn void tSVF_setFreq (tSVF* const, float freq) @brief @param filter A pointer to the relevant tSVF. @fn void tSVF_setQ (tSVF* const, float Q) @brief @param filter A pointer to the relevant tSVF. @fn void tSVF_setFreqAndQ (tSVF* const svff, float freq, float Q) @brief @param filter A pointer to the relevant tSVF.  @} */ typedef enum SVFType { SVFTypeHighpass = 0, SVFTypeLowpass, SVFTypeBandpass, SVFTypeNotch, SVFTypePeak, SVFTypeLowShelf, SVFTypeHighShelf } SVFType; typedef struct _tSVF { tMempool mempool; SVFType type; float cutoff, Q; float ic1eq,ic2eq; float g,k,a1,a2,a3,cH,cB,cL,cBK; float sampleRate; float invSampleRate; } _tSVF; typedef _tSVF* tSVF; void tSVF_init (tSVF* const, SVFType type, float freq, float Q, LEAF* const leaf); void tSVF_initToPool (tSVF* const, SVFType type, float freq, float Q, tMempool* const); void tSVF_free (tSVF* const); float tSVF_tick (tSVF* const, float v0); void tSVF_setFreq (tSVF* const, float freq); void tSVF_setFreqFast (tSVF* const vf, float cutoff); void tSVF_setQ (tSVF* const, float Q); void tSVF_setFreqAndQ (tSVF* const svff, float freq, float Q); void tSVF_setSampleRate (tSVF* const svff, float sr); //============================================================================== /*! @defgroup tefficientsvf tEfficientSVF @ingroup filters @brief Efficient State Variable Filter for 14-bit control input, [0, 4096). @{ @fn void tEfficientSVF_init (tEfficientSVF* const, SVFType type, uint16_t input, float Q, LEAF* const leaf) @brief Initialize a tEfficientSVF to the default mempool of a LEAF instance. @param filter A pointer to the tEfficientSVF to initialize. @param leaf A pointer to the leaf instance. @fn void tEfficientSVF_initToPool (tEfficientSVF* const, SVFType type, uint16_t input, float Q, tMempool* const) @brief Initialize a tEfficientSVF to a specified mempool. @param filter A pointer to the tEfficientSVF to initialize. @param mempool A pointer to the tMempool to use. @fn void tEfficientSVF_free (tEfficientSVF* const) @brief Free a tEfficientSVF from its mempool. @param filter A pointer to the tEfficientSVF to free. @fn float tEfficientSVF_tick (tEfficientSVF* const, float v0) @brief @param filter A pointer to the relevant tEfficientSVF. @fn void tEfficientSVF_setFreq (tEfficientSVF* const, uint16_t controlFreq) @brief @param filter A pointer to the relevant tEfficientSVF. @fn void tEfficientSVF_setQ (tEfficientSVF* const, float Q) @brief @param filter A pointer to the relevant tEfficientSVF.  @} */ typedef struct _tEfficientSVF { tMempool mempool; SVFType type; float cutoff, Q; float ic1eq,ic2eq; float g,k,a1,a2,a3; } _tEfficientSVF; typedef _tEfficientSVF* tEfficientSVF; void tEfficientSVF_init (tEfficientSVF* const, SVFType type, uint16_t input, float Q, LEAF* const leaf); void tEfficientSVF_initToPool (tEfficientSVF* const, SVFType type, uint16_t input, float Q, tMempool* const); void tEfficientSVF_free (tEfficientSVF* const); float tEfficientSVF_tick (tEfficientSVF* const, float v0); void tEfficientSVF_setFreq (tEfficientSVF* const, uint16_t controlFreq); void tEfficientSVF_setQ (tEfficientSVF* const, float Q); void tEfficientSVF_setFreqAndQ (tEfficientSVF* const, uint16_t controlFreq, float Q); //============================================================================== /*! @defgroup thighpass tHighpass @ingroup filters @brief Simple Highpass filter. @{ @fn void tHighpass_init (tHighpass* const, float freq, LEAF* const leaf) @brief Initialize a tHighpass to the default mempool of a LEAF instance. @param filter A pointer to the tHighpass to initialize. @param leaf A pointer to the leaf instance. @fn void tHighpass_initToPool (tHighpass* const, float freq, tMempool* const) @brief Initialize a tHighpass to a specified mempool. @param filter A pointer to the tHighpass to initialize. @param mempool A pointer to the tMempool to use. @fn void tHighpass_free (tHighpass* const) @brief Free a tHighpass from its mempool. @param filter A pointer to the tHighpass to free. @fn float tHighpass_tick (tHighpass* const, float x) @brief @param filter A pointer to the relevant tHighpass. @fn void tHighpass_setFreq (tHighpass* const, float freq) @brief @param filter A pointer to the relevant tHighpass. @fn float tHighpass_getFreq (tHighpass* const) @brief @param filter A pointer to the relevant tHighpass.  @} */ typedef struct _tHighpass { tMempool mempool; float xs, ys, R; float frequency; float twoPiTimesInvSampleRate; } _tHighpass; typedef _tHighpass* tHighpass; void tHighpass_init (tHighpass* const, float freq, LEAF* const leaf); void tHighpass_initToPool (tHighpass* const, float freq, tMempool* const); void tHighpass_free (tHighpass* const); float tHighpass_tick (tHighpass* const, float x); void tHighpass_setFreq (tHighpass* const, float freq); float tHighpass_getFreq (tHighpass* const); void tHighpass_setSampleRate (tHighpass* const, float sr); //============================================================================== /*! @defgroup tbutterworth tButterworth @ingroup filters @brief Butterworth filter. @{ @fn void tButterworth_init (tButterworth* const, int N, float f1, float f2, LEAF* const leaf, LEAF* const leaf) @brief Initialize a tButterworth to the default mempool of a LEAF instance. @param filter A pointer to the tButterworth to initialize. @param leaf A pointer to the leaf instance. @param order Order of the filter. @param lowCutoff Lower cutoff frequency. @param upperCutoff Upper cutoff frequency. @fn void tButterworth_initToPool (tButterworth* const, int N, float f1, float f2, tMempool* const) @brief Initialize a tButterworth to a specified mempool. @param filter A pointer to the tButterworth to initialize. @param mempool A pointer to the tMempool to use. @param order Order of the filter. @param lowCutoff Lower cutoff frequency. @param upperCutoff Upper cutoff frequency. @fn void tButterworth_free (tButterworth* const) @brief Free a tButterworth from its mempool. @param filter A pointer to the tButterworth to free. @fn float tButterworth_tick (tButterworth* const, float input) @brief @param filter A pointer to the relevant tButterworth. @fn void tButterworth_setF1 (tButterworth* const, float in) @brief @param filter A pointer to the relevant tButterworth. @fn void tButterworth_setF2 (tButterworth* const, float in) @brief @param filter A pointer to the relevant tButterworth. @fn void tButterworth_setFreqs (tButterworth* const, float f1, float f2) @brief @param filter A pointer to the relevant tButterworth.  @} */ #define NUM_SVF_BW 16 typedef struct _tButterworth { tMempool mempool; float gain; int order; int numSVF; tSVF* svf; float f1,f2; } _tButterworth; typedef _tButterworth* tButterworth; void tButterworth_init (tButterworth* const, int N, float f1, float f2, LEAF* const leaf); void tButterworth_initToPool (tButterworth* const, int N, float f1, float f2, tMempool* const); void tButterworth_free (tButterworth* const); float tButterworth_tick (tButterworth* const, float input); void tButterworth_setF1 (tButterworth* const, float in); void tButterworth_setF2 (tButterworth* const, float in); void tButterworth_setFreqs (tButterworth* const, float f1, float f2); void tButterworth_setSampleRate (tButterworth* const, float sr); //============================================================================== /*! @defgroup tfir tFIR @ingroup filters @brief Finite impulse response filter. @{ @fn void tFIR_init (tFIR* const, float* coeffs, int numTaps, LEAF* const leaf) @brief Initialize a tFIR to the default mempool of a LEAF instance. @param filter A pointer to the tFIR to initialize. @param leaf A pointer to the leaf instance. @fn void tFIR_initToPool (tFIR* const, float* coeffs, int numTaps, tMempool* const) @brief Initialize a tFIR to a specified mempool. @param filter A pointer to the tFIR to initialize. @param mempool A pointer to the tMempool to use. @fn void tFIR_free (tFIR* const) @brief Free a tFIR from its mempool. @param filter A pointer to the tFIR to free. @fn float tFIR_tick (tFIR* const, float input) @brief @param filter A pointer to the relevant tFIR.  @} */ typedef struct _tFIR { tMempool mempool; float* past; float* coeff; int numTaps; } _tFIR; typedef _tFIR* tFIR; void tFIR_init (tFIR* const, float* coeffs, int numTaps, LEAF* const leaf); void tFIR_initToPool (tFIR* const, float* coeffs, int numTaps, tMempool* const); void tFIR_free (tFIR* const); float tFIR_tick (tFIR* const, float input); //============================================================================== /*! @defgroup tmedianfilter tMedianFilter @ingroup filters @brief Median filter. @{ @fn void tMedianFilter_init (tMedianFilter* const, int size, LEAF* const leaf) @brief Initialize a tMedianFilter to the default mempool of a LEAF instance. @param filter A pointer to the tMedianFilter to initialize. @param leaf A pointer to the leaf instance.f @fn void tMedianFilter_initToPool (tMedianFilter* const, int size, tMempool* const) @brief Initialize a tMedianFilter to a specified mempool. @param filter A pointer to the tMedianFilter to initialize. @param mempool A pointer to the tMempool to use. @fn void tMedianFilter_free (tMedianFilter* const) @brief Free a tMedianFilter from its mempool. @param filter A pointer to the tMedianFilter to free. @fn float tMedianFilter_tick (tMedianFilter* const, float input) @brief @param filter A pointer to the relevant tMedianFilter.  @} */ typedef struct _tMedianFilter { tMempool mempool; float* val; int* age; int m; int size; int middlePosition; int last; int pos; } _tMedianFilter; typedef _tMedianFilter* tMedianFilter; void tMedianFilter_init (tMedianFilter* const, int size, LEAF* const leaf); void tMedianFilter_initToPool (tMedianFilter* const, int size, tMempool* const); void tMedianFilter_free (tMedianFilter* const); float tMedianFilter_tick (tMedianFilter* const, float input); /*! @defgroup tvzfilter tVZFilter @ingroup filters @brief Vadim Zavalishin style from VA book (from implementation in RSlib posted to kvr forum) @{ @fn void tVZFilter_init (tVZFilter* const, VZFilterType type, float freq, float Q, LEAF* const leaf) @brief Initialize a tVZFilter to the default mempool of a LEAF instance. @param filter A pointer to the tVZFilter to initialize. @param leaf A pointer to the leaf instance. @fn void tVZFilter_initToPool (tVZFilter* const, VZFilterType type, float freq, float Q, tMempool* const) @brief Initialize a tVZFilter to a specified mempool. @param filter A pointer to the tVZFilter to initialize. @param mempool A pointer to the tMempool to use. @fn void tVZFilter_free (tVZFilter* const) @brief Free a tVZFilter from its mempool. @param filter A pointer to the tVZFilter to free. @fn float tVZFilter_tick (tVZFilter* const, float input) @brief @param filter A pointer to the relevant tVZFilter. @fn float tVZFilter_tickEfficient (tVZFilter* const vf, float in) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_calcCoeffs (tVZFilter* const) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_setBandwidth (tVZFilter* const, float bandWidth) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_setFreq (tVZFilter* const, float freq) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_setFreqAndBandwidth (tVZFilter* const vf, float freq, float bw) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_setGain (tVZFilter* const, float gain) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_setType (tVZFilter* const, VZFilterType type) @brief @param filter A pointer to the relevant tVZFilter. @fn float tVZFilter_BandwidthToR (tVZFilter* const vf, float B) @brief @param filter A pointer to the relevant tVZFilter. @fn void tVZFilter_setSampleRate (tVZFilter* const, float sampleRate) @brief @param filter A pointer to the relevant tVZFilter.  @} */ typedef enum VZFilterType { Highpass = 0, Lowpass, BandpassSkirt, BandpassPeak, BandReject, Bell, Lowshelf, Highshelf, Morph, Bypass, Allpass } VZFilterType; typedef struct _tVZFilter { tMempool mempool; VZFilterType type; // state: float s1, s2; // filter coefficients: float g; // embedded integrator gain float R2; // twice the damping coefficient (R2 == 2*R == 1/Q) float h; // factor for feedback (== 1/(1+2*R*g+g*g)) float cL, cB, cH; // coefficients for low-, band-, and highpass signals // parameters: float fc; // characteristic frequency float G; // gain float invG; //1/gain float Q; //q of filter float B; // bandwidth (in octaves) float m; // morph parameter (0...1) float R2Plusg; //precomputed for the tick float sampleRate; //local sampling rate of filter (may be different from leaf sr if oversampled) float invSampleRate; } _tVZFilter; typedef _tVZFilter* tVZFilter; void tVZFilter_init (tVZFilter* const, VZFilterType type, float freq, float Q, LEAF* const leaf); void tVZFilter_initToPool (tVZFilter* const, VZFilterType type, float freq, float Q, tMempool* const); void tVZFilter_free (tVZFilter* const); void tVZFilter_setSampleRate (tVZFilter* const, float sampleRate); float tVZFilter_tick (tVZFilter* const, float input); float tVZFilter_tickEfficient (tVZFilter* const vf, float in); void tVZFilter_calcCoeffs (tVZFilter* const); void tVZFilter_calcCoeffsEfficientBP (tVZFilter* const); void tVZFilter_setBandwidth (tVZFilter* const, float bandWidth); void tVZFilter_setFreq (tVZFilter* const, float freq); void tVZFilter_setFreqFast (tVZFilter* const vf, float cutoff); void tVZFilter_setFreqAndBandwidth (tVZFilter* const vf, float freq, float bw); void tVZFilter_setFreqAndBandwidthEfficientBP (tVZFilter* const vf, float freq, float bw); void tVZFilter_setGain (tVZFilter* const, float gain); void tVZFilter_setResonance (tVZFilter* const vf, float res); void tVZFilter_setFrequencyAndResonance (tVZFilter* const vf, float freq, float res); void tVZFilter_setFrequencyAndResonanceAndGain (tVZFilter* const vf, float freq, float res, float gains); void tVZFilter_setFastFrequencyAndResonanceAndGain (tVZFilter* const vf, float freq, float res, float gain); void tVZFilter_setFrequencyAndBandwidthAndGain (tVZFilter* const vf, float freq, float BW, float gain); void tVZFilter_setFrequencyAndResonanceAndMorph (tVZFilter* const vf, float freq, float res, float morph); void tVZFilter_setMorphOnly (tVZFilter* const vf, float morph); void tVZFilter_setMorph (tVZFilter* const vf, float morph); void tVZFilter_setType (tVZFilter* const, VZFilterType type); float tVZFilter_BandwidthToR (tVZFilter* const vf, float B); float tVZFilter_BandwidthToREfficientBP(tVZFilter* const vf, float B); /*! @defgroup tdiodefilter tDiodeFilter @ingroup filters @brief Diode filter. @{ @fn void tDiodeFilter_init (tDiodeFilter* const, float freq, float Q, LEAF* const leaf) @brief Initialize a tDiodeFilter to the default mempool of a LEAF instance. @param filter A pointer to the tDiodeFilter to initialize. @param leaf A pointer to the leaf instance. @fn void tDiodeFilter_initToPool (tDiodeFilter* const, float freq, float Q, tMempool* const) @brief Initialize a tDiodeFilter to a specified mempool. @param filter A pointer to the tDiodeFilter to initialize. @param mempool A pointer to the tMempool to use. @fn void tDiodeFilter_free (tDiodeFilter* const) @brief Free a tDiodeFilter from its mempool. @param filter A pointer to the tDiodeFilter to free. @fn float tDiodeFilter_tick (tDiodeFilter* const, float input) @brief @param filter A pointer to the relevant tDiodeFilter. @fn void tDiodeFilter_setFreq (tDiodeFilter* const vf, float cutoff) @brief @param filter A pointer to the relevant tDiodeFilter. @fn void tDiodeFilter_setQ (tDiodeFilter* const vf, float resonance) @brief @param filter A pointer to the relevant tDiodeFilter.  @} */ //diode ladder filter by Ivan C, based on mystran's method typedef struct _tDiodeFilter { tMempool mempool; float cutoff; float f; float r; float Vt; float n; float gamma; float zi; float g0inv; float g1inv; float g2inv; float s0, s1, s2, s3; float invSampleRate; } _tDiodeFilter; typedef _tDiodeFilter* tDiodeFilter; void tDiodeFilter_init (tDiodeFilter* const, float freq, float Q, LEAF* const leaf); void tDiodeFilter_initToPool (tDiodeFilter* const, float freq, float Q, tMempool* const); void tDiodeFilter_free (tDiodeFilter* const); float tDiodeFilter_tick (tDiodeFilter* const, float input); void tDiodeFilter_setFreq (tDiodeFilter* const vf, float cutoff); void tDiodeFilter_setFreqFast (tDiodeFilter* const vf, float cutoff); void tDiodeFilter_setQ (tDiodeFilter* const vf, float resonance); void tDiodeFilter_setSampleRate(tDiodeFilter* const vf, float sr); //transistor ladder filter by aciddose, based on mystran's method, KVR forums typedef struct _tLadderFilter { tMempool mempool; float cutoff; float invSampleRate; int oversampling; float c; float fb; float c2; float a; float s; float d; float b[4]; // stored states } _tLadderFilter; typedef _tLadderFilter* tLadderFilter; void tLadderFilter_init (tLadderFilter* const, float freq, float Q, LEAF* const leaf); void tLadderFilter_initToPool (tLadderFilter* const, float freq, float Q, tMempool* const); void tLadderFilter_free (tLadderFilter* const); float tLadderFilter_tick (tLadderFilter* const, float input); void tLadderFilter_setFreq (tLadderFilter* const vf, float cutoff); void tLadderFilter_setFreqFast (tLadderFilter* const vf, float cutoff); void tLadderFilter_setQ (tLadderFilter* const vf, float resonance); void tLadderFilter_setSampleRate(tLadderFilter* const vf, float sr); #ifdef __cplusplus } #endif #endif // LEAF_FILTERS_H_INCLUDED //==============================================================================
fc292668564e66aaa51b8267b7b869062395e586
3464a8faf38798940a24245a8919a8403ac15a60
/SOFTWARE/ESP32-PoE_NES-Emu/components/nofrendo/nes/nes_mmc.h
a8f6a1041d8c656f7e44efc22a5adf77fc97a798
[ "GPL-2.0-only", "Apache-2.0", "GPL-3.0-only", "CC-BY-SA-3.0" ]
permissive
OLIMEX/ESP32-POE
32594089c4945c286564c9ef757c1568b29d0bef
768a5bc54bd9ce3de1569dcf79c29a69143ef8e9
refs/heads/master
2023-08-18T13:20:35.350515
2023-08-03T06:53:47
2023-08-03T06:53:47
147,683,474
241
107
Apache-2.0
2019-04-24T05:41:47
2018-09-06T14:08:27
C
UTF-8
C
false
false
3,681
h
nes_mmc.h
/* ** Nofrendo (c) 1998-2000 Matthew Conte (matt@conte.com) ** ** ** This program is free software; you can redistribute it and/or ** modify it under the terms of version 2 of the GNU Library General ** Public License as published by the Free Software Foundation. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU ** Library General Public License for more details. To obtain a ** copy of the GNU Library General Public License, write to the Free ** Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. ** ** Any permitted reproduction of these routines, in whole or in part, ** must bear this legend. ** ** ** nes_mmc.h ** ** NES Memory Management Controller (mapper) defines / prototypes ** $Id: nes_mmc.h,v 1.2 2001/04/27 14:37:11 neil Exp $ */ #ifndef _NES_MMC_H_ #define _NES_MMC_H_ #include <libsnss.h> #include <nes_apu.h> #define MMC_LASTBANK -1 typedef struct { uint32 min_range, max_range; uint8 (*read_func)(uint32 address); } map_memread; typedef struct { uint32 min_range, max_range; void (*write_func)(uint32 address, uint8 value); } map_memwrite; typedef struct mapintf_s { int number; char *name; void (*init)(void); void (*vblank)(void); void (*hblank)(int vblank); void (*get_state)(SnssMapperBlock *state); void (*set_state)(SnssMapperBlock *state); map_memread *mem_read; map_memwrite *mem_write; apuext_t *sound_ext; } mapintf_t; #include <nes_rom.h> typedef struct mmc_s { mapintf_t *intf; rominfo_t *cart; /* link it back to the cart */ } mmc_t; extern rominfo_t *mmc_getinfo(void); extern void mmc_bankvrom(int size, uint32 address, int bank); extern void mmc_bankrom(int size, uint32 address, int bank); /* Prototypes */ extern mmc_t *mmc_create(rominfo_t *rominfo); extern void mmc_destroy(mmc_t **nes_mmc); extern void mmc_getcontext(mmc_t *dest_mmc); extern void mmc_setcontext(mmc_t *src_mmc); extern bool mmc_peek(int map_num); extern void mmc_reset(void); #endif /* _NES_MMC_H_ */ /* ** $Log: nes_mmc.h,v $ ** Revision 1.2 2001/04/27 14:37:11 neil ** wheeee ** ** Revision 1.1.1.1 2001/04/27 07:03:54 neil ** initial ** ** Revision 1.2 2000/10/25 00:23:16 matt ** makefiles updated for new directory structure ** ** Revision 1.1 2000/10/24 12:20:28 matt ** changed directory structure ** ** Revision 1.18 2000/10/22 19:17:24 matt ** mapper cleanups galore ** ** Revision 1.17 2000/10/21 19:26:59 matt ** many more cleanups ** ** Revision 1.16 2000/10/17 03:22:58 matt ** cleaning up rom module ** ** Revision 1.15 2000/10/10 13:58:15 matt ** stroustrup squeezing his way in the door ** ** Revision 1.14 2000/07/31 04:27:59 matt ** one million cleanups ** ** Revision 1.13 2000/07/25 02:25:53 matt ** safer xxx_destroy calls ** ** Revision 1.12 2000/07/17 01:52:28 matt ** made sure last line of all source files is a newline ** ** Revision 1.11 2000/07/15 23:50:03 matt ** migrated state get/set from nes_mmc.c to state.c ** ** Revision 1.10 2000/07/11 02:38:01 matt ** added setcontext() routine ** ** Revision 1.9 2000/07/10 05:27:41 matt ** cleaned up mapper-specific callbacks ** ** Revision 1.8 2000/07/04 23:12:58 matt ** brand spankin' new mapper interface implemented ** ** Revision 1.7 2000/07/04 04:56:36 matt ** modifications for new SNSS ** ** Revision 1.6 2000/06/29 14:17:18 matt ** uses snsslib now ** ** Revision 1.5 2000/06/29 03:09:24 matt ** modified to support new snss code ** ** Revision 1.4 2000/06/09 15:12:26 matt ** initial revision ** */
bf42f6d5140b2595577074c5bd560a2360bbb4e8
9ceacf33fd96913cac7ef15492c126d96cae6911
/lib/libcsi/csi_util.c
6aadf5fa0eaa3f2e0dc857eff81c2cdf0704e2bd
[]
no_license
openbsd/src
ab97ef834fd2d5a7f6729814665e9782b586c130
9e79f3a0ebd11a25b4bff61e900cb6de9e7795e9
refs/heads/master
2023-09-02T18:54:56.624627
2023-09-02T15:16:12
2023-09-02T15:16:12
66,966,208
3,394
1,235
null
2023-08-08T02:42:25
2016-08-30T18:18:25
C
UTF-8
C
false
false
2,134
c
csi_util.c
/* $OpenBSD: csi_util.c,v 1.2 2022/01/10 23:03:07 tb Exp $ */ /* * Copyright (c) 2018 Joel Sing <jsing@openbsd.org> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include <stdlib.h> #include <openssl/bn.h> #include "csi.h" #include "csi_internal.h" int csi_integer_to_bn(struct csi_err *err, const char *field, struct csi_integer *integer, BIGNUM **bn) { BN_clear_free(*bn); *bn = NULL; if (integer->len > CSI_MAX_BIGNUM_BYTES) { csi_err_setx(err, CSI_ERR_INVAL, "%s too large", field); goto err; } if ((*bn = BN_bin2bn(integer->data, integer->len, NULL)) == NULL) { csi_err_setx(err, CSI_ERR_MEM, "out of memory"); goto err; } return 0; err: return -1; } int csi_bn_to_integer(struct csi_err *err, const BIGNUM *bn, struct csi_integer *integer) { uint8_t *b = NULL; int len = 0; freezero((uint8_t *)integer->data, integer->len); integer->data = NULL; integer->len = 0; len = BN_num_bytes(bn); if (len < 0 || len > CSI_MAX_BIGNUM_BYTES) { csi_err_setx(err, CSI_ERR_INVAL, "invalid bignum length %i", len); goto err; } /* XXX - prepend zero to avoid interpretation as negative? */ if ((b = calloc(1, len)) == NULL) goto errmem; if (BN_bn2bin(bn, b) != len) goto errmem; integer->data = b; integer->len = (size_t)len; return 0; errmem: csi_err_setx(err, CSI_ERR_MEM, "out of memory"); err: freezero(b, len); return -1; }
9cafb638e0ff3aa624e1e33a8dab3d39ac25c3d9
f9e7d65cb784c01a0200145ba8d289afe41d4a56
/chip/ish/ish_persistent_data.h
0fd973e1bb07b6ebd9b6c148fd041fd6cc50076f
[ "BSD-3-Clause" ]
permissive
FrameworkComputer/EmbeddedController
ad7086769e87d0a4179eae96a7c9ff5e383ff54e
f6d6b927eed71550d3475411cfc3e59abe5cef2a
refs/heads/hx20-hx30
2023-08-08T20:45:10.621169
2023-05-26T07:03:59
2023-05-26T07:03:59
447,021,040
846
48
BSD-3-Clause
2023-05-26T07:04:59
2022-01-12T00:11:14
C
UTF-8
C
false
false
1,502
h
ish_persistent_data.h
/* Copyright 2019 The Chromium OS 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 __CROS_EC_ISH_PERSISTENT_DATA_H #define __CROS_EC_ISH_PERSISTENT_DATA_H #include "panic.h" /* * If you make backwards-incompatible changes to this struct, (that * is, reading a previous version of the data would be incorrect), * simply change the magic number in ish_persistent_data.c. This will * cause the struct to be re-initialized when the firmware loads. */ struct ish_persistent_data { uint32_t magic; uint32_t reset_flags; uint32_t watchdog_counter; struct panic_data panic_data; }; /* * Local copy of persistent data, which is copied from AON memory only * if the data in AON memory is valid. */ extern struct ish_persistent_data ish_persistent_data; /* * Copy the AON persistent data into the local copy and initialize * system reset flags, only if magic number is correct. */ void ish_persistent_data_init(void); /* * Commit the local copy to the AON memory (to be called at reset). */ void ish_persistent_data_commit(void); /** * SNOWBALL - registers about UMA/IMR DDR information and FW location * in it. ISH Bringup will set these register values at boot */ struct snowball_struct { uint32_t reserved[28]; uint32_t volatile uma_base_hi; uint32_t volatile uma_base_lo; uint32_t volatile uma_limit; uint32_t volatile fw_offset; }; #endif /* __CROS_EC_ISH_PERSISTENT_DATA_H */