code
stringlengths 3
1.05M
| repo_name
stringlengths 4
116
| path
stringlengths 3
942
| language
stringclasses 30
values | license
stringclasses 15
values | size
int32 3
1.05M
|
---|---|---|---|---|---|
@import url("//fonts.googleapis.com/css?family=Open+Sans:400italic,700italic,400,700");
/*!
* Bootswatch v3.1.1
* Homepage: http://bootswatch.com
* Copyright 2012-2014 Thomas Park
* Licensed under MIT
* Based on Bootstrap
*/
/*! normalize.css v3.0.0 | MIT License | git.io/normalize */
html {
font-family: sans-serif;
-ms-text-size-adjust: 100%;
-webkit-text-size-adjust: 100%;
}
body {
margin: 15;
}
article,
aside,
details,
figcaption,
figure,
footer,
header,
hgroup,
main,
nav,
section,
summary {
display: block;
}
audio,
canvas,
progress,
video {
display: inline-block;
vertical-align: baseline;
}
audio:not([controls]) {
display: none;
height: 0;
}
[hidden],
template {
display: none;
}
a {
background: transparent;
}
a:active,
a:hover {
outline: 0;
}
abbr[title] {
border-bottom: 1px dotted;
}
b,
strong {
font-weight: bold;
}
dfn {
font-style: italic;
}
h1 {
font-size: 2em;
margin: 0.67em 0;
}
mark {
background: #ff0;
color: #000;
}
small {
font-size: 80%;
}
sub,
sup {
font-size: 75%;
line-height: 0;
position: relative;
vertical-align: baseline;
}
sup {
top: -0.5em;
}
sub {
bottom: -0.25em;
}
img {
border: 0;
}
svg:not(:root) {
overflow: hidden;
}
figure {
margin: 1em 40px;
}
hr {
-moz-box-sizing: content-box;
box-sizing: content-box;
height: 0;
}
pre {
overflow: auto;
}
code,
kbd,
pre,
samp {
font-family: monospace, monospace;
font-size: 1em;
}
button,
input,
optgroup,
select,
textarea {
color: inherit;
font: inherit;
margin: 0;
}
button {
overflow: visible;
}
button,
select {
text-transform: none;
}
button,
html input[type="button"],
input[type="reset"],
input[type="submit"] {
-webkit-appearance: button;
cursor: pointer;
}
button[disabled],
html input[disabled] {
cursor: default;
}
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}
input {
line-height: normal;
}
input[type="checkbox"],
input[type="radio"] {
box-sizing: border-box;
padding: 0;
}
input[type="number"]::-webkit-inner-spin-button,
input[type="number"]::-webkit-outer-spin-button {
height: auto;
}
input[type="search"] {
-webkit-appearance: textfield;
-moz-box-sizing: content-box;
-webkit-box-sizing: content-box;
box-sizing: content-box;
}
input[type="search"]::-webkit-search-cancel-button,
input[type="search"]::-webkit-search-decoration {
-webkit-appearance: none;
}
fieldset {
border: 1px solid #c0c0c0;
margin: 0 2px;
padding: 0.35em 0.625em 0.75em;
}
legend {
border: 0;
padding: 0;
}
textarea {
overflow: auto;
}
optgroup {
font-weight: bold;
}
table {
border-collapse: collapse;
border-spacing: 0;
}
td,
th {
padding: 0;
}
@media print {
* {
text-shadow: none !important;
color: #000 !important;
background: transparent !important;
box-shadow: none !important;
}
a,
a:visited {
text-decoration: underline;
}
a[href]:after {
content: " (" attr(href) ")";
}
abbr[title]:after {
content: " (" attr(title) ")";
}
a[href^="javascript:"]:after,
a[href^="#"]:after {
content: "";
}
pre,
blockquote {
border: 1px solid #999;
page-break-inside: avoid;
}
thead {
display: table-header-group;
}
tr,
img {
page-break-inside: avoid;
}
img {
max-width: 100% !important;
}
p,
h2,
h3 {
orphans: 3;
widows: 3;
}
h2,
h3 {
page-break-after: avoid;
}
select {
background: #fff !important;
}
.navbar {
display: none;
}
.table td,
.table th {
background-color: #fff !important;
}
.btn > .caret,
.dropup > .btn > .caret {
border-top-color: #000 !important;
}
.label {
border: 1px solid #000;
}
.table {
border-collapse: collapse !important;
}
.table-bordered th,
.table-bordered td {
border: 1px solid #ddd !important;
}
}
* {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
*:before,
*:after {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
html {
font-size: 62.5%;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0);
}
body {
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-size: 14px;
line-height: 1.42857143;
color: #666666;
background-color: #ffffff;
}
input,
button,
select,
textarea {
font-family: inherit;
font-size: inherit;
line-height: inherit;
}
a {
color: #3399f3;
text-decoration: none;
}
a:hover,
a:focus {
color: #3399f3;
text-decoration: underline;
}
a:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
figure {
margin: 0;
}
img {
vertical-align: middle;
}
.img-responsive,
.thumbnail > img,
.thumbnail a > img,
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
display: block;
max-width: 100%;
height: auto;
}
.img-rounded {
border-radius: 6px;
}
.img-thumbnail {
padding: 4px;
line-height: 1.42857143;
background-color: #ffffff;
border: 1px solid #dddddd;
border-radius: 4px;
-webkit-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
display: inline-block;
max-width: 100%;
height: auto;
}
.img-circle {
border-radius: 50%;
}
hr {
margin-top: 20px;
margin-bottom: 20px;
border: 0;
border-top: 1px solid #eeeeee;
}
.sr-only {
position: absolute;
width: 1px;
height: 1px;
margin: -1px;
padding: 0;
overflow: hidden;
clip: rect(0, 0, 0, 0);
border: 0;
}
h1,
h2,
h3,
h4,
h5,
h6,
.h1,
.h2,
.h3,
.h4,
.h5,
.h6 {
font-family: "Open Sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
font-weight: 500;
line-height: 1.1;
color: #2d2d2d;
}
h1 small,
h2 small,
h3 small,
h4 small,
h5 small,
h6 small,
.h1 small,
.h2 small,
.h3 small,
.h4 small,
.h5 small,
.h6 small,
h1 .small,
h2 .small,
h3 .small,
h4 .small,
h5 .small,
h6 .small,
.h1 .small,
.h2 .small,
.h3 .small,
.h4 .small,
.h5 .small,
.h6 .small {
font-weight: normal;
line-height: 1;
color: #999999;
}
h1,
.h1,
h2,
.h2,
h3,
.h3 {
margin-top: 20px;
margin-bottom: 10px;
}
h1 small,
.h1 small,
h2 small,
.h2 small,
h3 small,
.h3 small,
h1 .small,
.h1 .small,
h2 .small,
.h2 .small,
h3 .small,
.h3 .small {
font-size: 65%;
}
h4,
.h4,
h5,
.h5,
h6,
.h6 {
margin-top: 10px;
margin-bottom: 10px;
}
h4 small,
.h4 small,
h5 small,
.h5 small,
h6 small,
.h6 small,
h4 .small,
.h4 .small,
h5 .small,
.h5 .small,
h6 .small,
.h6 .small {
font-size: 75%;
}
h1,
.h1 {
font-size: 36px;
}
h2,
.h2 {
font-size: 30px;
}
h3,
.h3 {
font-size: 24px;
}
h4,
.h4 {
font-size: 18px;
}
h5,
.h5 {
font-size: 14px;
}
h6,
.h6 {
font-size: 12px;
}
p {
margin: 0 0 10px;
}
.lead {
margin-bottom: 20px;
font-size: 16px;
font-weight: 200;
line-height: 1.4;
}
@media (min-width: 768px) {
.lead {
font-size: 21px;
}
}
small,
.small {
font-size: 85%;
}
cite {
font-style: normal;
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.text-justify {
text-align: justify;
}
.text-muted {
color: #999999;
}
.text-primary {
color: #446e9b;
}
a.text-primary:hover {
color: #345578;
}
.text-success {
color: #468847;
}
a.text-success:hover {
color: #356635;
}
.text-info {
color: #3a87ad;
}
a.text-info:hover {
color: #2d6987;
}
.text-warning {
color: #c09853;
}
a.text-warning:hover {
color: #a47e3c;
}
.text-danger {
color: #b94a48;
}
a.text-danger:hover {
color: #953b39;
}
.bg-primary {
color: #fff;
background-color: #446e9b;
}
a.bg-primary:hover {
background-color: #345578;
}
.bg-success {
background-color: #dff0d8;
}
a.bg-success:hover {
background-color: #c1e2b3;
}
.bg-info {
background-color: #d9edf7;
}
a.bg-info:hover {
background-color: #afd9ee;
}
.bg-warning {
background-color: #fcf8e3;
}
a.bg-warning:hover {
background-color: #f7ecb5;
}
.bg-danger {
background-color: #f2dede;
}
a.bg-danger:hover {
background-color: #e4b9b9;
}
.page-header {
padding-bottom: 9px;
margin: 40px 0 20px;
border-bottom: 1px solid #eeeeee;
}
ul,
ol {
margin-top: 0;
margin-bottom: 10px;
}
ul ul,
ol ul,
ul ol,
ol ol {
margin-bottom: 0;
}
.list-unstyled {
padding-left: 0;
list-style: none;
}
.list-inline {
padding-left: 0;
list-style: none;
margin-left: -5px;
}
.list-inline > li {
display: inline-block;
padding-left: 5px;
padding-right: 5px;
}
dl {
margin-top: 0;
margin-bottom: 20px;
}
dt,
dd {
line-height: 1.42857143;
}
dt {
font-weight: bold;
}
dd {
margin-left: 0;
}
@media (min-width: 768px) {
.dl-horizontal dt {
float: left;
width: 160px;
clear: left;
text-align: right;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.dl-horizontal dd {
margin-left: 180px;
}
}
abbr[title],
abbr[data-original-title] {
cursor: help;
border-bottom: 1px dotted #999999;
}
.initialism {
font-size: 90%;
text-transform: uppercase;
}
blockquote {
padding: 10px 20px;
margin: 0 0 20px;
font-size: 17.5px;
border-left: 5px solid #eeeeee;
}
blockquote p:last-child,
blockquote ul:last-child,
blockquote ol:last-child {
margin-bottom: 0;
}
blockquote footer,
blockquote small,
blockquote .small {
display: block;
font-size: 80%;
line-height: 1.42857143;
color: #999999;
}
blockquote footer:before,
blockquote small:before,
blockquote .small:before {
content: '\2014 \00A0';
}
.blockquote-reverse,
blockquote.pull-right {
padding-right: 15px;
padding-left: 0;
border-right: 5px solid #eeeeee;
border-left: 0;
text-align: right;
}
.blockquote-reverse footer:before,
blockquote.pull-right footer:before,
.blockquote-reverse small:before,
blockquote.pull-right small:before,
.blockquote-reverse .small:before,
blockquote.pull-right .small:before {
content: '';
}
.blockquote-reverse footer:after,
blockquote.pull-right footer:after,
.blockquote-reverse small:after,
blockquote.pull-right small:after,
.blockquote-reverse .small:after,
blockquote.pull-right .small:after {
content: '\00A0 \2014';
}
blockquote:before,
blockquote:after {
content: "";
}
address {
margin-bottom: 20px;
font-style: normal;
line-height: 1.42857143;
}
code,
kbd,
pre,
samp {
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
code {
padding: 2px 4px;
font-size: 90%;
color: #c7254e;
background-color: #f9f2f4;
white-space: nowrap;
border-radius: 4px;
}
kbd {
padding: 2px 4px;
font-size: 90%;
color: #ffffff;
background-color: #333333;
border-radius: 3px;
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.25);
}
pre {
display: block;
padding: 9.5px;
margin: 0 0 10px;
font-size: 13px;
line-height: 1.42857143;
word-break: break-all;
word-wrap: break-word;
color: #333333;
background-color: #f5f5f5;
border: 1px solid #cccccc;
border-radius: 4px;
}
pre code {
padding: 0;
font-size: inherit;
color: inherit;
white-space: pre-wrap;
background-color: transparent;
border-radius: 0;
}
.pre-scrollable {
max-height: 340px;
overflow-y: scroll;
}
.container {
margin-right: auto;
margin-left: auto;
padding-left: 15px;
padding-right: 15px;
}
@media (min-width: 768px) {
.container {
width: 750px;
}
}
@media (min-width: 992px) {
.container {
width: 970px;
}
}
@media (min-width: 1200px) {
.container {
width: 1170px;
}
}
.container-fluid {
margin-right: auto;
margin-left: auto;
padding-left: 15px;
padding-right: 15px;
}
.row {
margin-left: -15px;
margin-right: -15px;
}
.col-xs-1, .col-sm-1, .col-md-1, .col-lg-1, .col-xs-2, .col-sm-2, .col-md-2, .col-lg-2, .col-xs-3, .col-sm-3, .col-md-3, .col-lg-3, .col-xs-4, .col-sm-4, .col-md-4, .col-lg-4, .col-xs-5, .col-sm-5, .col-md-5, .col-lg-5, .col-xs-6, .col-sm-6, .col-md-6, .col-lg-6, .col-xs-7, .col-sm-7, .col-md-7, .col-lg-7, .col-xs-8, .col-sm-8, .col-md-8, .col-lg-8, .col-xs-9, .col-sm-9, .col-md-9, .col-lg-9, .col-xs-10, .col-sm-10, .col-md-10, .col-lg-10, .col-xs-11, .col-sm-11, .col-md-11, .col-lg-11, .col-xs-12, .col-sm-12, .col-md-12, .col-lg-12 {
position: relative;
min-height: 1px;
padding-left: 15px;
padding-right: 15px;
}
.col-xs-1, .col-xs-2, .col-xs-3, .col-xs-4, .col-xs-5, .col-xs-6, .col-xs-7, .col-xs-8, .col-xs-9, .col-xs-10, .col-xs-11, .col-xs-12 {
float: left;
}
.col-xs-12 {
width: 100%;
}
.col-xs-11 {
width: 91.66666667%;
}
.col-xs-10 {
width: 83.33333333%;
}
.col-xs-9 {
width: 75%;
}
.col-xs-8 {
width: 66.66666667%;
}
.col-xs-7 {
width: 58.33333333%;
}
.col-xs-6 {
width: 50%;
}
.col-xs-5 {
width: 41.66666667%;
}
.col-xs-4 {
width: 33.33333333%;
}
.col-xs-3 {
width: 25%;
}
.col-xs-2 {
width: 16.66666667%;
}
.col-xs-1 {
width: 8.33333333%;
}
.col-xs-pull-12 {
right: 100%;
}
.col-xs-pull-11 {
right: 91.66666667%;
}
.col-xs-pull-10 {
right: 83.33333333%;
}
.col-xs-pull-9 {
right: 75%;
}
.col-xs-pull-8 {
right: 66.66666667%;
}
.col-xs-pull-7 {
right: 58.33333333%;
}
.col-xs-pull-6 {
right: 50%;
}
.col-xs-pull-5 {
right: 41.66666667%;
}
.col-xs-pull-4 {
right: 33.33333333%;
}
.col-xs-pull-3 {
right: 25%;
}
.col-xs-pull-2 {
right: 16.66666667%;
}
.col-xs-pull-1 {
right: 8.33333333%;
}
.col-xs-pull-0 {
right: 0%;
}
.col-xs-push-12 {
left: 100%;
}
.col-xs-push-11 {
left: 91.66666667%;
}
.col-xs-push-10 {
left: 83.33333333%;
}
.col-xs-push-9 {
left: 75%;
}
.col-xs-push-8 {
left: 66.66666667%;
}
.col-xs-push-7 {
left: 58.33333333%;
}
.col-xs-push-6 {
left: 50%;
}
.col-xs-push-5 {
left: 41.66666667%;
}
.col-xs-push-4 {
left: 33.33333333%;
}
.col-xs-push-3 {
left: 25%;
}
.col-xs-push-2 {
left: 16.66666667%;
}
.col-xs-push-1 {
left: 8.33333333%;
}
.col-xs-push-0 {
left: 0%;
}
.col-xs-offset-12 {
margin-left: 100%;
}
.col-xs-offset-11 {
margin-left: 91.66666667%;
}
.col-xs-offset-10 {
margin-left: 83.33333333%;
}
.col-xs-offset-9 {
margin-left: 75%;
}
.col-xs-offset-8 {
margin-left: 66.66666667%;
}
.col-xs-offset-7 {
margin-left: 58.33333333%;
}
.col-xs-offset-6 {
margin-left: 50%;
}
.col-xs-offset-5 {
margin-left: 41.66666667%;
}
.col-xs-offset-4 {
margin-left: 33.33333333%;
}
.col-xs-offset-3 {
margin-left: 25%;
}
.col-xs-offset-2 {
margin-left: 16.66666667%;
}
.col-xs-offset-1 {
margin-left: 8.33333333%;
}
.col-xs-offset-0 {
margin-left: 0%;
}
@media (min-width: 768px) {
.col-sm-1, .col-sm-2, .col-sm-3, .col-sm-4, .col-sm-5, .col-sm-6, .col-sm-7, .col-sm-8, .col-sm-9, .col-sm-10, .col-sm-11, .col-sm-12 {
float: left;
}
.col-sm-12 {
width: 100%;
}
.col-sm-11 {
width: 91.66666667%;
}
.col-sm-10 {
width: 83.33333333%;
}
.col-sm-9 {
width: 75%;
}
.col-sm-8 {
width: 66.66666667%;
}
.col-sm-7 {
width: 58.33333333%;
}
.col-sm-6 {
width: 50%;
}
.col-sm-5 {
width: 41.66666667%;
}
.col-sm-4 {
width: 33.33333333%;
}
.col-sm-3 {
width: 25%;
}
.col-sm-2 {
width: 16.66666667%;
}
.col-sm-1 {
width: 8.33333333%;
}
.col-sm-pull-12 {
right: 100%;
}
.col-sm-pull-11 {
right: 91.66666667%;
}
.col-sm-pull-10 {
right: 83.33333333%;
}
.col-sm-pull-9 {
right: 75%;
}
.col-sm-pull-8 {
right: 66.66666667%;
}
.col-sm-pull-7 {
right: 58.33333333%;
}
.col-sm-pull-6 {
right: 50%;
}
.col-sm-pull-5 {
right: 41.66666667%;
}
.col-sm-pull-4 {
right: 33.33333333%;
}
.col-sm-pull-3 {
right: 25%;
}
.col-sm-pull-2 {
right: 16.66666667%;
}
.col-sm-pull-1 {
right: 8.33333333%;
}
.col-sm-pull-0 {
right: 0%;
}
.col-sm-push-12 {
left: 100%;
}
.col-sm-push-11 {
left: 91.66666667%;
}
.col-sm-push-10 {
left: 83.33333333%;
}
.col-sm-push-9 {
left: 75%;
}
.col-sm-push-8 {
left: 66.66666667%;
}
.col-sm-push-7 {
left: 58.33333333%;
}
.col-sm-push-6 {
left: 50%;
}
.col-sm-push-5 {
left: 41.66666667%;
}
.col-sm-push-4 {
left: 33.33333333%;
}
.col-sm-push-3 {
left: 25%;
}
.col-sm-push-2 {
left: 16.66666667%;
}
.col-sm-push-1 {
left: 8.33333333%;
}
.col-sm-push-0 {
left: 0%;
}
.col-sm-offset-12 {
margin-left: 100%;
}
.col-sm-offset-11 {
margin-left: 91.66666667%;
}
.col-sm-offset-10 {
margin-left: 83.33333333%;
}
.col-sm-offset-9 {
margin-left: 75%;
}
.col-sm-offset-8 {
margin-left: 66.66666667%;
}
.col-sm-offset-7 {
margin-left: 58.33333333%;
}
.col-sm-offset-6 {
margin-left: 50%;
}
.col-sm-offset-5 {
margin-left: 41.66666667%;
}
.col-sm-offset-4 {
margin-left: 33.33333333%;
}
.col-sm-offset-3 {
margin-left: 25%;
}
.col-sm-offset-2 {
margin-left: 16.66666667%;
}
.col-sm-offset-1 {
margin-left: 8.33333333%;
}
.col-sm-offset-0 {
margin-left: 0%;
}
}
@media (min-width: 992px) {
.col-md-1, .col-md-2, .col-md-3, .col-md-4, .col-md-5, .col-md-6, .col-md-7, .col-md-8, .col-md-9, .col-md-10, .col-md-11, .col-md-12 {
float: left;
}
.col-md-12 {
width: 100%;
}
.col-md-11 {
width: 91.66666667%;
}
.col-md-10 {
width: 83.33333333%;
}
.col-md-9 {
width: 75%;
}
.col-md-8 {
width: 66.66666667%;
}
.col-md-7 {
width: 58.33333333%;
}
.col-md-6 {
width: 50%;
}
.col-md-5 {
width: 41.66666667%;
}
.col-md-4 {
width: 33.33333333%;
}
.col-md-3 {
width: 25%;
}
.col-md-2 {
width: 16.66666667%;
}
.col-md-1 {
width: 8.33333333%;
}
.col-md-pull-12 {
right: 100%;
}
.col-md-pull-11 {
right: 91.66666667%;
}
.col-md-pull-10 {
right: 83.33333333%;
}
.col-md-pull-9 {
right: 75%;
}
.col-md-pull-8 {
right: 66.66666667%;
}
.col-md-pull-7 {
right: 58.33333333%;
}
.col-md-pull-6 {
right: 50%;
}
.col-md-pull-5 {
right: 41.66666667%;
}
.col-md-pull-4 {
right: 33.33333333%;
}
.col-md-pull-3 {
right: 25%;
}
.col-md-pull-2 {
right: 16.66666667%;
}
.col-md-pull-1 {
right: 8.33333333%;
}
.col-md-pull-0 {
right: 0%;
}
.col-md-push-12 {
left: 100%;
}
.col-md-push-11 {
left: 91.66666667%;
}
.col-md-push-10 {
left: 83.33333333%;
}
.col-md-push-9 {
left: 75%;
}
.col-md-push-8 {
left: 66.66666667%;
}
.col-md-push-7 {
left: 58.33333333%;
}
.col-md-push-6 {
left: 50%;
}
.col-md-push-5 {
left: 41.66666667%;
}
.col-md-push-4 {
left: 33.33333333%;
}
.col-md-push-3 {
left: 25%;
}
.col-md-push-2 {
left: 16.66666667%;
}
.col-md-push-1 {
left: 8.33333333%;
}
.col-md-push-0 {
left: 0%;
}
.col-md-offset-12 {
margin-left: 100%;
}
.col-md-offset-11 {
margin-left: 91.66666667%;
}
.col-md-offset-10 {
margin-left: 83.33333333%;
}
.col-md-offset-9 {
margin-left: 75%;
}
.col-md-offset-8 {
margin-left: 66.66666667%;
}
.col-md-offset-7 {
margin-left: 58.33333333%;
}
.col-md-offset-6 {
margin-left: 50%;
}
.col-md-offset-5 {
margin-left: 41.66666667%;
}
.col-md-offset-4 {
margin-left: 33.33333333%;
}
.col-md-offset-3 {
margin-left: 25%;
}
.col-md-offset-2 {
margin-left: 16.66666667%;
}
.col-md-offset-1 {
margin-left: 8.33333333%;
}
.col-md-offset-0 {
margin-left: 0%;
}
}
@media (min-width: 1200px) {
.col-lg-1, .col-lg-2, .col-lg-3, .col-lg-4, .col-lg-5, .col-lg-6, .col-lg-7, .col-lg-8, .col-lg-9, .col-lg-10, .col-lg-11, .col-lg-12 {
float: left;
}
.col-lg-12 {
width: 100%;
}
.col-lg-11 {
width: 91.66666667%;
}
.col-lg-10 {
width: 83.33333333%;
}
.col-lg-9 {
width: 75%;
}
.col-lg-8 {
width: 66.66666667%;
}
.col-lg-7 {
width: 58.33333333%;
}
.col-lg-6 {
width: 50%;
}
.col-lg-5 {
width: 41.66666667%;
}
.col-lg-4 {
width: 33.33333333%;
}
.col-lg-3 {
width: 25%;
}
.col-lg-2 {
width: 16.66666667%;
}
.col-lg-1 {
width: 8.33333333%;
}
.col-lg-pull-12 {
right: 100%;
}
.col-lg-pull-11 {
right: 91.66666667%;
}
.col-lg-pull-10 {
right: 83.33333333%;
}
.col-lg-pull-9 {
right: 75%;
}
.col-lg-pull-8 {
right: 66.66666667%;
}
.col-lg-pull-7 {
right: 58.33333333%;
}
.col-lg-pull-6 {
right: 50%;
}
.col-lg-pull-5 {
right: 41.66666667%;
}
.col-lg-pull-4 {
right: 33.33333333%;
}
.col-lg-pull-3 {
right: 25%;
}
.col-lg-pull-2 {
right: 16.66666667%;
}
.col-lg-pull-1 {
right: 8.33333333%;
}
.col-lg-pull-0 {
right: 0%;
}
.col-lg-push-12 {
left: 100%;
}
.col-lg-push-11 {
left: 91.66666667%;
}
.col-lg-push-10 {
left: 83.33333333%;
}
.col-lg-push-9 {
left: 75%;
}
.col-lg-push-8 {
left: 66.66666667%;
}
.col-lg-push-7 {
left: 58.33333333%;
}
.col-lg-push-6 {
left: 50%;
}
.col-lg-push-5 {
left: 41.66666667%;
}
.col-lg-push-4 {
left: 33.33333333%;
}
.col-lg-push-3 {
left: 25%;
}
.col-lg-push-2 {
left: 16.66666667%;
}
.col-lg-push-1 {
left: 8.33333333%;
}
.col-lg-push-0 {
left: 0%;
}
.col-lg-offset-12 {
margin-left: 100%;
}
.col-lg-offset-11 {
margin-left: 91.66666667%;
}
.col-lg-offset-10 {
margin-left: 83.33333333%;
}
.col-lg-offset-9 {
margin-left: 75%;
}
.col-lg-offset-8 {
margin-left: 66.66666667%;
}
.col-lg-offset-7 {
margin-left: 58.33333333%;
}
.col-lg-offset-6 {
margin-left: 50%;
}
.col-lg-offset-5 {
margin-left: 41.66666667%;
}
.col-lg-offset-4 {
margin-left: 33.33333333%;
}
.col-lg-offset-3 {
margin-left: 25%;
}
.col-lg-offset-2 {
margin-left: 16.66666667%;
}
.col-lg-offset-1 {
margin-left: 8.33333333%;
}
.col-lg-offset-0 {
margin-left: 0%;
}
}
table {
max-width: 100%;
background-color: transparent;
}
th {
text-align: left;
}
.table {
width: 100%;
margin-bottom: 20px;
}
.table > thead > tr > th,
.table > tbody > tr > th,
.table > tfoot > tr > th,
.table > thead > tr > td,
.table > tbody > tr > td,
.table > tfoot > tr > td {
padding: 8px;
line-height: 1.42857143;
vertical-align: top;
border-top: 1px solid #dddddd;
}
.table > thead > tr > th {
vertical-align: bottom;
border-bottom: 2px solid #dddddd;
}
.table > caption + thead > tr:first-child > th,
.table > colgroup + thead > tr:first-child > th,
.table > thead:first-child > tr:first-child > th,
.table > caption + thead > tr:first-child > td,
.table > colgroup + thead > tr:first-child > td,
.table > thead:first-child > tr:first-child > td {
border-top: 0;
}
.table > tbody + tbody {
border-top: 2px solid #dddddd;
}
.table .table {
background-color: #ffffff;
}
.table-condensed > thead > tr > th,
.table-condensed > tbody > tr > th,
.table-condensed > tfoot > tr > th,
.table-condensed > thead > tr > td,
.table-condensed > tbody > tr > td,
.table-condensed > tfoot > tr > td {
padding: 5px;
}
.table-bordered {
border: 1px solid #dddddd;
}
.table-bordered > thead > tr > th,
.table-bordered > tbody > tr > th,
.table-bordered > tfoot > tr > th,
.table-bordered > thead > tr > td,
.table-bordered > tbody > tr > td,
.table-bordered > tfoot > tr > td {
border: 1px solid #dddddd;
}
.table-bordered > thead > tr > th,
.table-bordered > thead > tr > td {
border-bottom-width: 2px;
}
.table-striped > tbody > tr:nth-child(odd) > td,
.table-striped > tbody > tr:nth-child(odd) > th {
background-color: #f9f9f9;
}
.table-hover > tbody > tr:hover > td,
.table-hover > tbody > tr:hover > th {
background-color: #f5f5f5;
}
table col[class*="col-"] {
position: static;
float: none;
display: table-column;
}
table td[class*="col-"],
table th[class*="col-"] {
position: static;
float: none;
display: table-cell;
}
.table > thead > tr > td.active,
.table > tbody > tr > td.active,
.table > tfoot > tr > td.active,
.table > thead > tr > th.active,
.table > tbody > tr > th.active,
.table > tfoot > tr > th.active,
.table > thead > tr.active > td,
.table > tbody > tr.active > td,
.table > tfoot > tr.active > td,
.table > thead > tr.active > th,
.table > tbody > tr.active > th,
.table > tfoot > tr.active > th {
background-color: #f5f5f5;
}
.table-hover > tbody > tr > td.active:hover,
.table-hover > tbody > tr > th.active:hover,
.table-hover > tbody > tr.active:hover > td,
.table-hover > tbody > tr.active:hover > th {
background-color: #e8e8e8;
}
.table > thead > tr > td.success,
.table > tbody > tr > td.success,
.table > tfoot > tr > td.success,
.table > thead > tr > th.success,
.table > tbody > tr > th.success,
.table > tfoot > tr > th.success,
.table > thead > tr.success > td,
.table > tbody > tr.success > td,
.table > tfoot > tr.success > td,
.table > thead > tr.success > th,
.table > tbody > tr.success > th,
.table > tfoot > tr.success > th {
background-color: #dff0d8;
}
.table-hover > tbody > tr > td.success:hover,
.table-hover > tbody > tr > th.success:hover,
.table-hover > tbody > tr.success:hover > td,
.table-hover > tbody > tr.success:hover > th {
background-color: #d0e9c6;
}
.table > thead > tr > td.info,
.table > tbody > tr > td.info,
.table > tfoot > tr > td.info,
.table > thead > tr > th.info,
.table > tbody > tr > th.info,
.table > tfoot > tr > th.info,
.table > thead > tr.info > td,
.table > tbody > tr.info > td,
.table > tfoot > tr.info > td,
.table > thead > tr.info > th,
.table > tbody > tr.info > th,
.table > tfoot > tr.info > th {
background-color: #d9edf7;
}
.table-hover > tbody > tr > td.info:hover,
.table-hover > tbody > tr > th.info:hover,
.table-hover > tbody > tr.info:hover > td,
.table-hover > tbody > tr.info:hover > th {
background-color: #c4e3f3;
}
.table > thead > tr > td.warning,
.table > tbody > tr > td.warning,
.table > tfoot > tr > td.warning,
.table > thead > tr > th.warning,
.table > tbody > tr > th.warning,
.table > tfoot > tr > th.warning,
.table > thead > tr.warning > td,
.table > tbody > tr.warning > td,
.table > tfoot > tr.warning > td,
.table > thead > tr.warning > th,
.table > tbody > tr.warning > th,
.table > tfoot > tr.warning > th {
background-color: #fcf8e3;
}
.table-hover > tbody > tr > td.warning:hover,
.table-hover > tbody > tr > th.warning:hover,
.table-hover > tbody > tr.warning:hover > td,
.table-hover > tbody > tr.warning:hover > th {
background-color: #faf2cc;
}
.table > thead > tr > td.danger,
.table > tbody > tr > td.danger,
.table > tfoot > tr > td.danger,
.table > thead > tr > th.danger,
.table > tbody > tr > th.danger,
.table > tfoot > tr > th.danger,
.table > thead > tr.danger > td,
.table > tbody > tr.danger > td,
.table > tfoot > tr.danger > td,
.table > thead > tr.danger > th,
.table > tbody > tr.danger > th,
.table > tfoot > tr.danger > th {
background-color: #f2dede;
}
.table-hover > tbody > tr > td.danger:hover,
.table-hover > tbody > tr > th.danger:hover,
.table-hover > tbody > tr.danger:hover > td,
.table-hover > tbody > tr.danger:hover > th {
background-color: #ebcccc;
}
@media (max-width: 767px) {
.table-responsive {
width: 100%;
margin-bottom: 15px;
overflow-y: hidden;
overflow-x: scroll;
-ms-overflow-style: -ms-autohiding-scrollbar;
border: 1px solid #dddddd;
-webkit-overflow-scrolling: touch;
}
.table-responsive > .table {
margin-bottom: 0;
}
.table-responsive > .table > thead > tr > th,
.table-responsive > .table > tbody > tr > th,
.table-responsive > .table > tfoot > tr > th,
.table-responsive > .table > thead > tr > td,
.table-responsive > .table > tbody > tr > td,
.table-responsive > .table > tfoot > tr > td {
white-space: nowrap;
}
.table-responsive > .table-bordered {
border: 0;
}
.table-responsive > .table-bordered > thead > tr > th:first-child,
.table-responsive > .table-bordered > tbody > tr > th:first-child,
.table-responsive > .table-bordered > tfoot > tr > th:first-child,
.table-responsive > .table-bordered > thead > tr > td:first-child,
.table-responsive > .table-bordered > tbody > tr > td:first-child,
.table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.table-responsive > .table-bordered > thead > tr > th:last-child,
.table-responsive > .table-bordered > tbody > tr > th:last-child,
.table-responsive > .table-bordered > tfoot > tr > th:last-child,
.table-responsive > .table-bordered > thead > tr > td:last-child,
.table-responsive > .table-bordered > tbody > tr > td:last-child,
.table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.table-responsive > .table-bordered > tbody > tr:last-child > th,
.table-responsive > .table-bordered > tfoot > tr:last-child > th,
.table-responsive > .table-bordered > tbody > tr:last-child > td,
.table-responsive > .table-bordered > tfoot > tr:last-child > td {
border-bottom: 0;
}
}
fieldset {
padding: 0;
margin: 0;
border: 0;
min-width: 0;
}
legend {
display: block;
width: 100%;
padding: 0;
margin-bottom: 20px;
font-size: 21px;
line-height: inherit;
color: #666666;
border: 0;
border-bottom: 1px solid #e5e5e5;
}
label {
display: inline-block;
margin-bottom: 5px;
font-weight: bold;
}
input[type="search"] {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
input[type="radio"],
input[type="checkbox"] {
margin: 4px 0 0;
margin-top: 1px \9;
/* IE8-9 */
line-height: normal;
}
input[type="file"] {
display: block;
}
input[type="range"] {
display: block;
width: 100%;
}
select[multiple],
select[size] {
height: auto;
}
input[type="file"]:focus,
input[type="radio"]:focus,
input[type="checkbox"]:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
output {
display: block;
padding-top: 9px;
font-size: 14px;
line-height: 1.42857143;
color: #666666;
}
.form-control {
display: block;
width: 100%;
height: 38px;
padding: 8px 12px;
font-size: 14px;
line-height: 1.42857143;
color: #666666;
background-color: #ffffff;
background-image: none;
border: 1px solid #cccccc;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
-webkit-transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
transition: border-color ease-in-out .15s, box-shadow ease-in-out .15s;
}
.form-control:focus {
border-color: #66afe9;
outline: 0;
-webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
box-shadow: inset 0 1px 1px rgba(0,0,0,.075), 0 0 8px rgba(102, 175, 233, 0.6);
}
.form-control::-moz-placeholder {
color: #999999;
opacity: 1;
}
.form-control:-ms-input-placeholder {
color: #999999;
}
.form-control::-webkit-input-placeholder {
color: #999999;
}
.form-control[disabled],
.form-control[readonly],
fieldset[disabled] .form-control {
cursor: not-allowed;
background-color: #eeeeee;
opacity: 1;
}
textarea.form-control {
height: auto;
}
input[type="search"] {
-webkit-appearance: none;
}
input[type="date"] {
line-height: 38px;
}
.form-group {
margin-bottom: 15px;
}
.radio,
.checkbox {
display: block;
min-height: 20px;
margin-top: 10px;
margin-bottom: 10px;
padding-left: 20px;
}
.radio label,
.checkbox label {
display: inline;
font-weight: normal;
cursor: pointer;
}
.radio input[type="radio"],
.radio-inline input[type="radio"],
.checkbox input[type="checkbox"],
.checkbox-inline input[type="checkbox"] {
float: left;
margin-left: -20px;
}
.radio + .radio,
.checkbox + .checkbox {
margin-top: -5px;
}
.radio-inline,
.checkbox-inline {
display: inline-block;
padding-left: 20px;
margin-bottom: 0;
vertical-align: middle;
font-weight: normal;
cursor: pointer;
}
.radio-inline + .radio-inline,
.checkbox-inline + .checkbox-inline {
margin-top: 0;
margin-left: 10px;
}
input[type="radio"][disabled],
input[type="checkbox"][disabled],
.radio[disabled],
.radio-inline[disabled],
.checkbox[disabled],
.checkbox-inline[disabled],
fieldset[disabled] input[type="radio"],
fieldset[disabled] input[type="checkbox"],
fieldset[disabled] .radio,
fieldset[disabled] .radio-inline,
fieldset[disabled] .checkbox,
fieldset[disabled] .checkbox-inline {
cursor: not-allowed;
}
.input-sm {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-sm {
height: 30px;
line-height: 30px;
}
textarea.input-sm,
select[multiple].input-sm {
height: auto;
}
.input-lg {
height: 54px;
padding: 14px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-lg {
height: 54px;
line-height: 54px;
}
textarea.input-lg,
select[multiple].input-lg {
height: auto;
}
.has-feedback {
position: relative;
}
.has-feedback .form-control {
padding-right: 47.5px;
}
.has-feedback .form-control-feedback {
position: absolute;
top: 25px;
right: 0;
display: block;
width: 38px;
height: 38px;
line-height: 38px;
text-align: center;
}
.has-success .help-block,
.has-success .control-label,
.has-success .radio,
.has-success .checkbox,
.has-success .radio-inline,
.has-success .checkbox-inline {
color: #468847;
}
.has-success .form-control {
border-color: #468847;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-success .form-control:focus {
border-color: #356635;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #7aba7b;
}
.has-success .input-group-addon {
color: #468847;
border-color: #468847;
background-color: #dff0d8;
}
.has-success .form-control-feedback {
color: #468847;
}
.has-warning .help-block,
.has-warning .control-label,
.has-warning .radio,
.has-warning .checkbox,
.has-warning .radio-inline,
.has-warning .checkbox-inline {
color: #c09853;
}
.has-warning .form-control {
border-color: #c09853;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-warning .form-control:focus {
border-color: #a47e3c;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #dbc59e;
}
.has-warning .input-group-addon {
color: #c09853;
border-color: #c09853;
background-color: #fcf8e3;
}
.has-warning .form-control-feedback {
color: #c09853;
}
.has-error .help-block,
.has-error .control-label,
.has-error .radio,
.has-error .checkbox,
.has-error .radio-inline,
.has-error .checkbox-inline {
color: #b94a48;
}
.has-error .form-control {
border-color: #b94a48;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075);
}
.has-error .form-control:focus {
border-color: #953b39;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.075), 0 0 6px #d59392;
}
.has-error .input-group-addon {
color: #b94a48;
border-color: #b94a48;
background-color: #f2dede;
}
.has-error .form-control-feedback {
color: #b94a48;
}
.form-control-static {
margin-bottom: 0;
}
.help-block {
display: block;
margin-top: 5px;
margin-bottom: 10px;
color: #a6a6a6;
}
@media (min-width: 768px) {
.form-inline .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.form-inline .input-group > .form-control {
width: 100%;
}
.form-inline .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.form-inline .radio,
.form-inline .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
padding-left: 0;
vertical-align: middle;
}
.form-inline .radio input[type="radio"],
.form-inline .checkbox input[type="checkbox"] {
float: none;
margin-left: 0;
}
.form-inline .has-feedback .form-control-feedback {
top: 0;
}
}
.form-horizontal .control-label,
.form-horizontal .radio,
.form-horizontal .checkbox,
.form-horizontal .radio-inline,
.form-horizontal .checkbox-inline {
margin-top: 0;
margin-bottom: 0;
padding-top: 9px;
}
.form-horizontal .radio,
.form-horizontal .checkbox {
min-height: 29px;
}
.form-horizontal .form-group {
margin-left: -15px;
margin-right: -15px;
}
.form-horizontal .form-control-static {
padding-top: 9px;
}
@media (min-width: 768px) {
.form-horizontal .control-label {
text-align: right;
}
}
.form-horizontal .has-feedback .form-control-feedback {
top: 0;
right: 15px;
}
.btn {
display: inline-block;
margin-bottom: 0;
font-weight: normal;
text-align: center;
vertical-align: middle;
cursor: pointer;
background-image: none;
border: 1px solid transparent;
white-space: nowrap;
padding: 8px 12px;
font-size: 14px;
line-height: 1.42857143;
border-radius: 4px;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
.btn:focus,
.btn:active:focus,
.btn.active:focus {
outline: thin dotted;
outline: 5px auto -webkit-focus-ring-color;
outline-offset: -2px;
}
.btn:hover,
.btn:focus {
color: #ffffff;
text-decoration: none;
}
.btn:active,
.btn.active {
outline: 0;
background-image: none;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn.disabled,
.btn[disabled],
fieldset[disabled] .btn {
cursor: not-allowed;
pointer-events: none;
opacity: 0.65;
filter: alpha(opacity=65);
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-default {
color: #ffffff;
background-color: #474949;
border-color: #474949;
}
.btn-default:hover,
.btn-default:focus,
.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
color: #ffffff;
background-color: #333434;
border-color: #292a2a;
}
.btn-default:active,
.btn-default.active,
.open .dropdown-toggle.btn-default {
background-image: none;
}
.btn-default.disabled,
.btn-default[disabled],
fieldset[disabled] .btn-default,
.btn-default.disabled:hover,
.btn-default[disabled]:hover,
fieldset[disabled] .btn-default:hover,
.btn-default.disabled:focus,
.btn-default[disabled]:focus,
fieldset[disabled] .btn-default:focus,
.btn-default.disabled:active,
.btn-default[disabled]:active,
fieldset[disabled] .btn-default:active,
.btn-default.disabled.active,
.btn-default[disabled].active,
fieldset[disabled] .btn-default.active {
background-color: #474949;
border-color: #474949;
}
.btn-default .badge {
color: #474949;
background-color: #ffffff;
}
.btn-primary {
color: #ffffff;
background-color: #446e9b;
border-color: #446e9b;
}
.btn-primary:hover,
.btn-primary:focus,
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
color: #ffffff;
background-color: #385a7f;
border-color: #315070;
}
.btn-primary:active,
.btn-primary.active,
.open .dropdown-toggle.btn-primary {
background-image: none;
}
.btn-primary.disabled,
.btn-primary[disabled],
fieldset[disabled] .btn-primary,
.btn-primary.disabled:hover,
.btn-primary[disabled]:hover,
fieldset[disabled] .btn-primary:hover,
.btn-primary.disabled:focus,
.btn-primary[disabled]:focus,
fieldset[disabled] .btn-primary:focus,
.btn-primary.disabled:active,
.btn-primary[disabled]:active,
fieldset[disabled] .btn-primary:active,
.btn-primary.disabled.active,
.btn-primary[disabled].active,
fieldset[disabled] .btn-primary.active {
background-color: #446e9b;
border-color: #446e9b;
}
.btn-primary .badge {
color: #446e9b;
background-color: #ffffff;
}
.btn-success {
color: #ffffff;
background-color: #3cb521;
border-color: #3cb521;
}
.btn-success:hover,
.btn-success:focus,
.btn-success:active,
.btn-success.active,
.open .dropdown-toggle.btn-success {
color: #ffffff;
background-color: #31921b;
border-color: #2b8118;
}
.btn-success:active,
.btn-success.active,
.open .dropdown-toggle.btn-success {
background-image: none;
}
.btn-success.disabled,
.btn-success[disabled],
fieldset[disabled] .btn-success,
.btn-success.disabled:hover,
.btn-success[disabled]:hover,
fieldset[disabled] .btn-success:hover,
.btn-success.disabled:focus,
.btn-success[disabled]:focus,
fieldset[disabled] .btn-success:focus,
.btn-success.disabled:active,
.btn-success[disabled]:active,
fieldset[disabled] .btn-success:active,
.btn-success.disabled.active,
.btn-success[disabled].active,
fieldset[disabled] .btn-success.active {
background-color: #3cb521;
border-color: #3cb521;
}
.btn-success .badge {
color: #3cb521;
background-color: #ffffff;
}
.btn-info {
color: #ffffff;
background-color: #3399f3;
border-color: #3399f3;
}
.btn-info:hover,
.btn-info:focus,
.btn-info:active,
.btn-info.active,
.open .dropdown-toggle.btn-info {
color: #ffffff;
background-color: #0e86ef;
border-color: #0d7bdc;
}
.btn-info:active,
.btn-info.active,
.open .dropdown-toggle.btn-info {
background-image: none;
}
.btn-info.disabled,
.btn-info[disabled],
fieldset[disabled] .btn-info,
.btn-info.disabled:hover,
.btn-info[disabled]:hover,
fieldset[disabled] .btn-info:hover,
.btn-info.disabled:focus,
.btn-info[disabled]:focus,
fieldset[disabled] .btn-info:focus,
.btn-info.disabled:active,
.btn-info[disabled]:active,
fieldset[disabled] .btn-info:active,
.btn-info.disabled.active,
.btn-info[disabled].active,
fieldset[disabled] .btn-info.active {
background-color: #3399f3;
border-color: #3399f3;
}
.btn-info .badge {
color: #3399f3;
background-color: #ffffff;
}
.btn-warning {
color: #ffffff;
background-color: #d47500;
border-color: #d47500;
}
.btn-warning:hover,
.btn-warning:focus,
.btn-warning:active,
.btn-warning.active,
.open .dropdown-toggle.btn-warning {
color: #ffffff;
background-color: #ab5e00;
border-color: #975300;
}
.btn-warning:active,
.btn-warning.active,
.open .dropdown-toggle.btn-warning {
background-image: none;
}
.btn-warning.disabled,
.btn-warning[disabled],
fieldset[disabled] .btn-warning,
.btn-warning.disabled:hover,
.btn-warning[disabled]:hover,
fieldset[disabled] .btn-warning:hover,
.btn-warning.disabled:focus,
.btn-warning[disabled]:focus,
fieldset[disabled] .btn-warning:focus,
.btn-warning.disabled:active,
.btn-warning[disabled]:active,
fieldset[disabled] .btn-warning:active,
.btn-warning.disabled.active,
.btn-warning[disabled].active,
fieldset[disabled] .btn-warning.active {
background-color: #d47500;
border-color: #d47500;
}
.btn-warning .badge {
color: #d47500;
background-color: #ffffff;
}
.btn-danger {
color: #ffffff;
background-color: #cd0200;
border-color: #cd0200;
}
.btn-danger:hover,
.btn-danger:focus,
.btn-danger:active,
.btn-danger.active,
.open .dropdown-toggle.btn-danger {
color: #ffffff;
background-color: #a40200;
border-color: #900100;
}
.btn-danger:active,
.btn-danger.active,
.open .dropdown-toggle.btn-danger {
background-image: none;
}
.btn-danger.disabled,
.btn-danger[disabled],
fieldset[disabled] .btn-danger,
.btn-danger.disabled:hover,
.btn-danger[disabled]:hover,
fieldset[disabled] .btn-danger:hover,
.btn-danger.disabled:focus,
.btn-danger[disabled]:focus,
fieldset[disabled] .btn-danger:focus,
.btn-danger.disabled:active,
.btn-danger[disabled]:active,
fieldset[disabled] .btn-danger:active,
.btn-danger.disabled.active,
.btn-danger[disabled].active,
fieldset[disabled] .btn-danger.active {
background-color: #cd0200;
border-color: #cd0200;
}
.btn-danger .badge {
color: #cd0200;
background-color: #ffffff;
}
.btn-link {
color: #3399f3;
font-weight: normal;
cursor: pointer;
border-radius: 0;
}
.btn-link,
.btn-link:active,
.btn-link[disabled],
fieldset[disabled] .btn-link {
background-color: transparent;
-webkit-box-shadow: none;
box-shadow: none;
}
.btn-link,
.btn-link:hover,
.btn-link:focus,
.btn-link:active {
border-color: transparent;
}
.btn-link:hover,
.btn-link:focus {
color: #3399f3;
text-decoration: underline;
background-color: transparent;
}
.btn-link[disabled]:hover,
fieldset[disabled] .btn-link:hover,
.btn-link[disabled]:focus,
fieldset[disabled] .btn-link:focus {
color: #999999;
text-decoration: none;
}
.btn-lg,
.btn-group-lg > .btn {
padding: 14px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
.btn-sm,
.btn-group-sm > .btn {
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-xs,
.btn-group-xs > .btn {
padding: 1px 5px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
.btn-block {
display: block;
width: 100%;
padding-left: 0;
padding-right: 0;
}
.btn-block + .btn-block {
margin-top: 5px;
}
input[type="submit"].btn-block,
input[type="reset"].btn-block,
input[type="button"].btn-block {
width: 100%;
}
.fade {
opacity: 0;
-webkit-transition: opacity 0.15s linear;
transition: opacity 0.15s linear;
}
.fade.in {
opacity: 1;
}
.collapse {
display: none;
}
.collapse.in {
display: block;
}
.collapsing {
position: relative;
height: 0;
overflow: hidden;
-webkit-transition: height 0.35s ease;
transition: height 0.35s ease;
}
@font-face {
font-family: 'Glyphicons Halflings';
src: url('../fonts/glyphicons-halflings-regular.eot');
src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'), url('../fonts/glyphicons-halflings-regular.woff') format('woff'), url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'), url('../fonts/glyphicons-halflings-regular.svg#glyphicons_halflingsregular') format('svg');
}
.glyphicon {
position: relative;
top: 1px;
display: inline-block;
font-family: 'Glyphicons Halflings';
font-style: normal;
font-weight: normal;
line-height: 1;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.glyphicon-asterisk:before {
content: "\2a";
}
.glyphicon-plus:before {
content: "\2b";
}
.glyphicon-euro:before {
content: "\20ac";
}
.glyphicon-minus:before {
content: "\2212";
}
.glyphicon-cloud:before {
content: "\2601";
}
.glyphicon-envelope:before {
content: "\2709";
}
.glyphicon-pencil:before {
content: "\270f";
}
.glyphicon-glass:before {
content: "\e001";
}
.glyphicon-music:before {
content: "\e002";
}
.glyphicon-search:before {
content: "\e003";
}
.glyphicon-heart:before {
content: "\e005";
}
.glyphicon-star:before {
content: "\e006";
}
.glyphicon-star-empty:before {
content: "\e007";
}
.glyphicon-user:before {
content: "\e008";
}
.glyphicon-film:before {
content: "\e009";
}
.glyphicon-th-large:before {
content: "\e010";
}
.glyphicon-th:before {
content: "\e011";
}
.glyphicon-th-list:before {
content: "\e012";
}
.glyphicon-ok:before {
content: "\e013";
}
.glyphicon-remove:before {
content: "\e014";
}
.glyphicon-zoom-in:before {
content: "\e015";
}
.glyphicon-zoom-out:before {
content: "\e016";
}
.glyphicon-off:before {
content: "\e017";
}
.glyphicon-signal:before {
content: "\e018";
}
.glyphicon-cog:before {
content: "\e019";
}
.glyphicon-trash:before {
content: "\e020";
}
.glyphicon-home:before {
content: "\e021";
}
.glyphicon-file:before {
content: "\e022";
}
.glyphicon-time:before {
content: "\e023";
}
.glyphicon-road:before {
content: "\e024";
}
.glyphicon-download-alt:before {
content: "\e025";
}
.glyphicon-download:before {
content: "\e026";
}
.glyphicon-upload:before {
content: "\e027";
}
.glyphicon-inbox:before {
content: "\e028";
}
.glyphicon-play-circle:before {
content: "\e029";
}
.glyphicon-repeat:before {
content: "\e030";
}
.glyphicon-refresh:before {
content: "\e031";
}
.glyphicon-list-alt:before {
content: "\e032";
}
.glyphicon-lock:before {
content: "\e033";
}
.glyphicon-flag:before {
content: "\e034";
}
.glyphicon-headphones:before {
content: "\e035";
}
.glyphicon-volume-off:before {
content: "\e036";
}
.glyphicon-volume-down:before {
content: "\e037";
}
.glyphicon-volume-up:before {
content: "\e038";
}
.glyphicon-qrcode:before {
content: "\e039";
}
.glyphicon-barcode:before {
content: "\e040";
}
.glyphicon-tag:before {
content: "\e041";
}
.glyphicon-tags:before {
content: "\e042";
}
.glyphicon-book:before {
content: "\e043";
}
.glyphicon-bookmark:before {
content: "\e044";
}
.glyphicon-print:before {
content: "\e045";
}
.glyphicon-camera:before {
content: "\e046";
}
.glyphicon-font:before {
content: "\e047";
}
.glyphicon-bold:before {
content: "\e048";
}
.glyphicon-italic:before {
content: "\e049";
}
.glyphicon-text-height:before {
content: "\e050";
}
.glyphicon-text-width:before {
content: "\e051";
}
.glyphicon-align-left:before {
content: "\e052";
}
.glyphicon-align-center:before {
content: "\e053";
}
.glyphicon-align-right:before {
content: "\e054";
}
.glyphicon-align-justify:before {
content: "\e055";
}
.glyphicon-list:before {
content: "\e056";
}
.glyphicon-indent-left:before {
content: "\e057";
}
.glyphicon-indent-right:before {
content: "\e058";
}
.glyphicon-facetime-video:before {
content: "\e059";
}
.glyphicon-picture:before {
content: "\e060";
}
.glyphicon-map-marker:before {
content: "\e062";
}
.glyphicon-adjust:before {
content: "\e063";
}
.glyphicon-tint:before {
content: "\e064";
}
.glyphicon-edit:before {
content: "\e065";
}
.glyphicon-share:before {
content: "\e066";
}
.glyphicon-check:before {
content: "\e067";
}
.glyphicon-move:before {
content: "\e068";
}
.glyphicon-step-backward:before {
content: "\e069";
}
.glyphicon-fast-backward:before {
content: "\e070";
}
.glyphicon-backward:before {
content: "\e071";
}
.glyphicon-play:before {
content: "\e072";
}
.glyphicon-pause:before {
content: "\e073";
}
.glyphicon-stop:before {
content: "\e074";
}
.glyphicon-forward:before {
content: "\e075";
}
.glyphicon-fast-forward:before {
content: "\e076";
}
.glyphicon-step-forward:before {
content: "\e077";
}
.glyphicon-eject:before {
content: "\e078";
}
.glyphicon-chevron-left:before {
content: "\e079";
}
.glyphicon-chevron-right:before {
content: "\e080";
}
.glyphicon-plus-sign:before {
content: "\e081";
}
.glyphicon-minus-sign:before {
content: "\e082";
}
.glyphicon-remove-sign:before {
content: "\e083";
}
.glyphicon-ok-sign:before {
content: "\e084";
}
.glyphicon-question-sign:before {
content: "\e085";
}
.glyphicon-info-sign:before {
content: "\e086";
}
.glyphicon-screenshot:before {
content: "\e087";
}
.glyphicon-remove-circle:before {
content: "\e088";
}
.glyphicon-ok-circle:before {
content: "\e089";
}
.glyphicon-ban-circle:before {
content: "\e090";
}
.glyphicon-arrow-left:before {
content: "\e091";
}
.glyphicon-arrow-right:before {
content: "\e092";
}
.glyphicon-arrow-up:before {
content: "\e093";
}
.glyphicon-arrow-down:before {
content: "\e094";
}
.glyphicon-share-alt:before {
content: "\e095";
}
.glyphicon-resize-full:before {
content: "\e096";
}
.glyphicon-resize-small:before {
content: "\e097";
}
.glyphicon-exclamation-sign:before {
content: "\e101";
}
.glyphicon-gift:before {
content: "\e102";
}
.glyphicon-leaf:before {
content: "\e103";
}
.glyphicon-fire:before {
content: "\e104";
}
.glyphicon-eye-open:before {
content: "\e105";
}
.glyphicon-eye-close:before {
content: "\e106";
}
.glyphicon-warning-sign:before {
content: "\e107";
}
.glyphicon-plane:before {
content: "\e108";
}
.glyphicon-calendar:before {
content: "\e109";
}
.glyphicon-random:before {
content: "\e110";
}
.glyphicon-comment:before {
content: "\e111";
}
.glyphicon-magnet:before {
content: "\e112";
}
.glyphicon-chevron-up:before {
content: "\e113";
}
.glyphicon-chevron-down:before {
content: "\e114";
}
.glyphicon-retweet:before {
content: "\e115";
}
.glyphicon-shopping-cart:before {
content: "\e116";
}
.glyphicon-folder-close:before {
content: "\e117";
}
.glyphicon-folder-open:before {
content: "\e118";
}
.glyphicon-resize-vertical:before {
content: "\e119";
}
.glyphicon-resize-horizontal:before {
content: "\e120";
}
.glyphicon-hdd:before {
content: "\e121";
}
.glyphicon-bullhorn:before {
content: "\e122";
}
.glyphicon-bell:before {
content: "\e123";
}
.glyphicon-certificate:before {
content: "\e124";
}
.glyphicon-thumbs-up:before {
content: "\e125";
}
.glyphicon-thumbs-down:before {
content: "\e126";
}
.glyphicon-hand-right:before {
content: "\e127";
}
.glyphicon-hand-left:before {
content: "\e128";
}
.glyphicon-hand-up:before {
content: "\e129";
}
.glyphicon-hand-down:before {
content: "\e130";
}
.glyphicon-circle-arrow-right:before {
content: "\e131";
}
.glyphicon-circle-arrow-left:before {
content: "\e132";
}
.glyphicon-circle-arrow-up:before {
content: "\e133";
}
.glyphicon-circle-arrow-down:before {
content: "\e134";
}
.glyphicon-globe:before {
content: "\e135";
}
.glyphicon-wrench:before {
content: "\e136";
}
.glyphicon-tasks:before {
content: "\e137";
}
.glyphicon-filter:before {
content: "\e138";
}
.glyphicon-briefcase:before {
content: "\e139";
}
.glyphicon-fullscreen:before {
content: "\e140";
}
.glyphicon-dashboard:before {
content: "\e141";
}
.glyphicon-paperclip:before {
content: "\e142";
}
.glyphicon-heart-empty:before {
content: "\e143";
}
.glyphicon-link:before {
content: "\e144";
}
.glyphicon-phone:before {
content: "\e145";
}
.glyphicon-pushpin:before {
content: "\e146";
}
.glyphicon-usd:before {
content: "\e148";
}
.glyphicon-gbp:before {
content: "\e149";
}
.glyphicon-sort:before {
content: "\e150";
}
.glyphicon-sort-by-alphabet:before {
content: "\e151";
}
.glyphicon-sort-by-alphabet-alt:before {
content: "\e152";
}
.glyphicon-sort-by-order:before {
content: "\e153";
}
.glyphicon-sort-by-order-alt:before {
content: "\e154";
}
.glyphicon-sort-by-attributes:before {
content: "\e155";
}
.glyphicon-sort-by-attributes-alt:before {
content: "\e156";
}
.glyphicon-unchecked:before {
content: "\e157";
}
.glyphicon-expand:before {
content: "\e158";
}
.glyphicon-collapse-down:before {
content: "\e159";
}
.glyphicon-collapse-up:before {
content: "\e160";
}
.glyphicon-log-in:before {
content: "\e161";
}
.glyphicon-flash:before {
content: "\e162";
}
.glyphicon-log-out:before {
content: "\e163";
}
.glyphicon-new-window:before {
content: "\e164";
}
.glyphicon-record:before {
content: "\e165";
}
.glyphicon-save:before {
content: "\e166";
}
.glyphicon-open:before {
content: "\e167";
}
.glyphicon-saved:before {
content: "\e168";
}
.glyphicon-import:before {
content: "\e169";
}
.glyphicon-export:before {
content: "\e170";
}
.glyphicon-send:before {
content: "\e171";
}
.glyphicon-floppy-disk:before {
content: "\e172";
}
.glyphicon-floppy-saved:before {
content: "\e173";
}
.glyphicon-floppy-remove:before {
content: "\e174";
}
.glyphicon-floppy-save:before {
content: "\e175";
}
.glyphicon-floppy-open:before {
content: "\e176";
}
.glyphicon-credit-card:before {
content: "\e177";
}
.glyphicon-transfer:before {
content: "\e178";
}
.glyphicon-cutlery:before {
content: "\e179";
}
.glyphicon-header:before {
content: "\e180";
}
.glyphicon-compressed:before {
content: "\e181";
}
.glyphicon-earphone:before {
content: "\e182";
}
.glyphicon-phone-alt:before {
content: "\e183";
}
.glyphicon-tower:before {
content: "\e184";
}
.glyphicon-stats:before {
content: "\e185";
}
.glyphicon-sd-video:before {
content: "\e186";
}
.glyphicon-hd-video:before {
content: "\e187";
}
.glyphicon-subtitles:before {
content: "\e188";
}
.glyphicon-sound-stereo:before {
content: "\e189";
}
.glyphicon-sound-dolby:before {
content: "\e190";
}
.glyphicon-sound-5-1:before {
content: "\e191";
}
.glyphicon-sound-6-1:before {
content: "\e192";
}
.glyphicon-sound-7-1:before {
content: "\e193";
}
.glyphicon-copyright-mark:before {
content: "\e194";
}
.glyphicon-registration-mark:before {
content: "\e195";
}
.glyphicon-cloud-download:before {
content: "\e197";
}
.glyphicon-cloud-upload:before {
content: "\e198";
}
.glyphicon-tree-conifer:before {
content: "\e199";
}
.glyphicon-tree-deciduous:before {
content: "\e200";
}
.caret {
display: inline-block;
width: 0;
height: 0;
margin-left: 2px;
vertical-align: middle;
border-top: 4px solid;
border-right: 4px solid transparent;
border-left: 4px solid transparent;
}
.dropdown {
position: relative;
}
.dropdown-toggle:focus {
outline: 0;
}
.dropdown-menu {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
display: none;
float: left;
min-width: 160px;
padding: 5px 0;
margin: 2px 0 0;
list-style: none;
font-size: 14px;
background-color: #ffffff;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.15);
border-radius: 4px;
-webkit-box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
box-shadow: 0 6px 12px rgba(0, 0, 0, 0.175);
background-clip: padding-box;
}
.dropdown-menu.pull-right {
right: 0;
left: auto;
}
.dropdown-menu .divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.dropdown-menu > li > a {
display: block;
padding: 3px 20px;
clear: both;
font-weight: normal;
line-height: 1.42857143;
color: #333333;
white-space: nowrap;
}
.dropdown-menu > li > a:hover,
.dropdown-menu > li > a:focus {
text-decoration: none;
color: #ffffff;
background-color: #446e9b;
}
.dropdown-menu > .active > a,
.dropdown-menu > .active > a:hover,
.dropdown-menu > .active > a:focus {
color: #ffffff;
text-decoration: none;
outline: 0;
background-color: #446e9b;
}
.dropdown-menu > .disabled > a,
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
color: #999999;
}
.dropdown-menu > .disabled > a:hover,
.dropdown-menu > .disabled > a:focus {
text-decoration: none;
background-color: transparent;
background-image: none;
filter: progid:DXImageTransform.Microsoft.gradient(enabled = false);
cursor: not-allowed;
}
.open > .dropdown-menu {
display: block;
}
.open > a {
outline: 0;
}
.dropdown-menu-right {
left: auto;
right: 0;
}
.dropdown-menu-left {
left: 0;
right: auto;
}
.dropdown-header {
display: block;
padding: 3px 20px;
font-size: 12px;
line-height: 1.42857143;
color: #999999;
}
.dropdown-backdrop {
position: fixed;
left: 0;
right: 0;
bottom: 0;
top: 0;
z-index: 990;
}
.pull-right > .dropdown-menu {
right: 0;
left: auto;
}
.dropup .caret,
.navbar-fixed-bottom .dropdown .caret {
border-top: 0;
border-bottom: 4px solid;
content: "";
}
.dropup .dropdown-menu,
.navbar-fixed-bottom .dropdown .dropdown-menu {
top: auto;
bottom: 100%;
margin-bottom: 1px;
}
@media (min-width: 768px) {
.navbar-right .dropdown-menu {
left: auto;
right: 0;
}
.navbar-right .dropdown-menu-left {
left: 0;
right: auto;
}
}
.btn-group,
.btn-group-vertical {
position: relative;
display: inline-block;
vertical-align: middle;
}
.btn-group > .btn,
.btn-group-vertical > .btn {
position: relative;
float: left;
}
.btn-group > .btn:hover,
.btn-group-vertical > .btn:hover,
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus,
.btn-group > .btn:active,
.btn-group-vertical > .btn:active,
.btn-group > .btn.active,
.btn-group-vertical > .btn.active {
z-index: 2;
}
.btn-group > .btn:focus,
.btn-group-vertical > .btn:focus {
outline: none;
}
.btn-group .btn + .btn,
.btn-group .btn + .btn-group,
.btn-group .btn-group + .btn,
.btn-group .btn-group + .btn-group {
margin-left: -1px;
}
.btn-toolbar {
margin-left: -5px;
}
.btn-toolbar .btn-group,
.btn-toolbar .input-group {
float: left;
}
.btn-toolbar > .btn,
.btn-toolbar > .btn-group,
.btn-toolbar > .input-group {
margin-left: 5px;
}
.btn-group > .btn:not(:first-child):not(:last-child):not(.dropdown-toggle) {
border-radius: 0;
}
.btn-group > .btn:first-child {
margin-left: 0;
}
.btn-group > .btn:first-child:not(:last-child):not(.dropdown-toggle) {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group > .btn:last-child:not(:first-child),
.btn-group > .dropdown-toggle:not(:first-child) {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.btn-group > .btn-group {
float: left;
}
.btn-group > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group > .btn-group:first-child > .btn:last-child,
.btn-group > .btn-group:first-child > .dropdown-toggle {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.btn-group > .btn-group:last-child > .btn:first-child {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.btn-group .dropdown-toggle:active,
.btn-group.open .dropdown-toggle {
outline: 0;
}
.btn-group > .btn + .dropdown-toggle {
padding-left: 8px;
padding-right: 8px;
}
.btn-group > .btn-lg + .dropdown-toggle {
padding-left: 12px;
padding-right: 12px;
}
.btn-group.open .dropdown-toggle {
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.btn-group.open .dropdown-toggle.btn-link {
-webkit-box-shadow: none;
box-shadow: none;
}
.btn .caret {
margin-left: 0;
}
.btn-lg .caret {
border-width: 5px 5px 0;
border-bottom-width: 0;
}
.dropup .btn-lg .caret {
border-width: 0 5px 5px;
}
.btn-group-vertical > .btn,
.btn-group-vertical > .btn-group,
.btn-group-vertical > .btn-group > .btn {
display: block;
float: none;
width: 100%;
max-width: 100%;
}
.btn-group-vertical > .btn-group > .btn {
float: none;
}
.btn-group-vertical > .btn + .btn,
.btn-group-vertical > .btn + .btn-group,
.btn-group-vertical > .btn-group + .btn,
.btn-group-vertical > .btn-group + .btn-group {
margin-top: -1px;
margin-left: 0;
}
.btn-group-vertical > .btn:not(:first-child):not(:last-child) {
border-radius: 0;
}
.btn-group-vertical > .btn:first-child:not(:last-child) {
border-top-right-radius: 4px;
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn:last-child:not(:first-child) {
border-bottom-left-radius: 4px;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.btn-group-vertical > .btn-group:not(:first-child):not(:last-child) > .btn {
border-radius: 0;
}
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .btn:last-child,
.btn-group-vertical > .btn-group:first-child:not(:last-child) > .dropdown-toggle {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.btn-group-vertical > .btn-group:last-child:not(:first-child) > .btn:first-child {
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.btn-group-justified {
display: table;
width: 100%;
table-layout: fixed;
border-collapse: separate;
}
.btn-group-justified > .btn,
.btn-group-justified > .btn-group {
float: none;
display: table-cell;
width: 1%;
}
.btn-group-justified > .btn-group .btn {
width: 100%;
}
[data-toggle="buttons"] > .btn > input[type="radio"],
[data-toggle="buttons"] > .btn > input[type="checkbox"] {
display: none;
}
.input-group {
position: relative;
display: table;
border-collapse: separate;
}
.input-group[class*="col-"] {
float: none;
padding-left: 0;
padding-right: 0;
}
.input-group .form-control {
position: relative;
z-index: 2;
float: left;
width: 100%;
margin-bottom: 0;
}
.input-group-lg > .form-control,
.input-group-lg > .input-group-addon,
.input-group-lg > .input-group-btn > .btn {
height: 54px;
padding: 14px 16px;
font-size: 18px;
line-height: 1.33;
border-radius: 6px;
}
select.input-group-lg > .form-control,
select.input-group-lg > .input-group-addon,
select.input-group-lg > .input-group-btn > .btn {
height: 54px;
line-height: 54px;
}
textarea.input-group-lg > .form-control,
textarea.input-group-lg > .input-group-addon,
textarea.input-group-lg > .input-group-btn > .btn,
select[multiple].input-group-lg > .form-control,
select[multiple].input-group-lg > .input-group-addon,
select[multiple].input-group-lg > .input-group-btn > .btn {
height: auto;
}
.input-group-sm > .form-control,
.input-group-sm > .input-group-addon,
.input-group-sm > .input-group-btn > .btn {
height: 30px;
padding: 5px 10px;
font-size: 12px;
line-height: 1.5;
border-radius: 3px;
}
select.input-group-sm > .form-control,
select.input-group-sm > .input-group-addon,
select.input-group-sm > .input-group-btn > .btn {
height: 30px;
line-height: 30px;
}
textarea.input-group-sm > .form-control,
textarea.input-group-sm > .input-group-addon,
textarea.input-group-sm > .input-group-btn > .btn,
select[multiple].input-group-sm > .form-control,
select[multiple].input-group-sm > .input-group-addon,
select[multiple].input-group-sm > .input-group-btn > .btn {
height: auto;
}
.input-group-addon,
.input-group-btn,
.input-group .form-control {
display: table-cell;
}
.input-group-addon:not(:first-child):not(:last-child),
.input-group-btn:not(:first-child):not(:last-child),
.input-group .form-control:not(:first-child):not(:last-child) {
border-radius: 0;
}
.input-group-addon,
.input-group-btn {
width: 1%;
white-space: nowrap;
vertical-align: middle;
}
.input-group-addon {
padding: 8px 12px;
font-size: 14px;
font-weight: normal;
line-height: 1;
color: #666666;
text-align: center;
background-color: #eeeeee;
border: 1px solid #cccccc;
border-radius: 4px;
}
.input-group-addon.input-sm {
padding: 5px 10px;
font-size: 12px;
border-radius: 3px;
}
.input-group-addon.input-lg {
padding: 14px 16px;
font-size: 18px;
border-radius: 6px;
}
.input-group-addon input[type="radio"],
.input-group-addon input[type="checkbox"] {
margin-top: 0;
}
.input-group .form-control:first-child,
.input-group-addon:first-child,
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group > .btn,
.input-group-btn:first-child > .dropdown-toggle,
.input-group-btn:last-child > .btn:not(:last-child):not(.dropdown-toggle),
.input-group-btn:last-child > .btn-group:not(:last-child) > .btn {
border-bottom-right-radius: 0;
border-top-right-radius: 0;
}
.input-group-addon:first-child {
border-right: 0;
}
.input-group .form-control:last-child,
.input-group-addon:last-child,
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group > .btn,
.input-group-btn:last-child > .dropdown-toggle,
.input-group-btn:first-child > .btn:not(:first-child),
.input-group-btn:first-child > .btn-group:not(:first-child) > .btn {
border-bottom-left-radius: 0;
border-top-left-radius: 0;
}
.input-group-addon:last-child {
border-left: 0;
}
.input-group-btn {
position: relative;
font-size: 0;
white-space: nowrap;
}
.input-group-btn > .btn {
position: relative;
}
.input-group-btn > .btn + .btn {
margin-left: -1px;
}
.input-group-btn > .btn:hover,
.input-group-btn > .btn:focus,
.input-group-btn > .btn:active {
z-index: 2;
}
.input-group-btn:first-child > .btn,
.input-group-btn:first-child > .btn-group {
margin-right: -1px;
}
.input-group-btn:last-child > .btn,
.input-group-btn:last-child > .btn-group {
margin-left: -1px;
}
.nav {
margin-bottom: 0;
padding-left: 0;
list-style: none;
}
.nav > li {
position: relative;
display: block;
}
.nav > li > a {
position: relative;
display: block;
padding: 10px 15px;
}
.nav > li > a:hover,
.nav > li > a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.nav > li.disabled > a {
color: #999999;
}
.nav > li.disabled > a:hover,
.nav > li.disabled > a:focus {
color: #999999;
text-decoration: none;
background-color: transparent;
cursor: not-allowed;
}
.nav .open > a,
.nav .open > a:hover,
.nav .open > a:focus {
background-color: #eeeeee;
border-color: #3399f3;
}
.nav .nav-divider {
height: 1px;
margin: 9px 0;
overflow: hidden;
background-color: #e5e5e5;
}
.nav > li > a > img {
max-width: none;
}
.nav-tabs {
border-bottom: 1px solid #dddddd;
}
.nav-tabs > li {
float: left;
margin-bottom: -1px;
}
.nav-tabs > li > a {
margin-right: 2px;
line-height: 1.42857143;
border: 1px solid transparent;
border-radius: 4px 4px 0 0;
}
.nav-tabs > li > a:hover {
border-color: #eeeeee #eeeeee #dddddd;
}
.nav-tabs > li.active > a,
.nav-tabs > li.active > a:hover,
.nav-tabs > li.active > a:focus {
color: #666666;
background-color: #ffffff;
border: 1px solid #dddddd;
border-bottom-color: transparent;
cursor: default;
}
.nav-tabs.nav-justified {
width: 100%;
border-bottom: 0;
}
.nav-tabs.nav-justified > li {
float: none;
}
.nav-tabs.nav-justified > li > a {
text-align: center;
margin-bottom: 5px;
}
.nav-tabs.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-tabs.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs.nav-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border: 1px solid #dddddd;
}
@media (min-width: 768px) {
.nav-tabs.nav-justified > li > a {
border-bottom: 1px solid #dddddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs.nav-justified > .active > a,
.nav-tabs.nav-justified > .active > a:hover,
.nav-tabs.nav-justified > .active > a:focus {
border-bottom-color: #ffffff;
}
}
.nav-pills > li {
float: left;
}
.nav-pills > li > a {
border-radius: 4px;
}
.nav-pills > li + li {
margin-left: 2px;
}
.nav-pills > li.active > a,
.nav-pills > li.active > a:hover,
.nav-pills > li.active > a:focus {
color: #ffffff;
background-color: #446e9b;
}
.nav-stacked > li {
float: none;
}
.nav-stacked > li + li {
margin-top: 2px;
margin-left: 0;
}
.nav-justified {
width: 100%;
}
.nav-justified > li {
float: none;
}
.nav-justified > li > a {
text-align: center;
margin-bottom: 5px;
}
.nav-justified > .dropdown .dropdown-menu {
top: auto;
left: auto;
}
@media (min-width: 768px) {
.nav-justified > li {
display: table-cell;
width: 1%;
}
.nav-justified > li > a {
margin-bottom: 0;
}
}
.nav-tabs-justified {
border-bottom: 0;
}
.nav-tabs-justified > li > a {
margin-right: 0;
border-radius: 4px;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border: 1px solid #dddddd;
}
@media (min-width: 768px) {
.nav-tabs-justified > li > a {
border-bottom: 1px solid #dddddd;
border-radius: 4px 4px 0 0;
}
.nav-tabs-justified > .active > a,
.nav-tabs-justified > .active > a:hover,
.nav-tabs-justified > .active > a:focus {
border-bottom-color: #ffffff;
}
}
.tab-content > .tab-pane {
display: none;
}
.tab-content > .active {
display: block;
}
.nav-tabs .dropdown-menu {
margin-top: -1px;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar {
position: relative;
min-height: 50px;
margin-bottom: 20px;
border: 1px solid transparent;
}
@media (min-width: 768px) {
.navbar {
border-radius: 4px;
}
}
@media (min-width: 768px) {
.navbar-header {
float: left;
}
}
.navbar-collapse {
max-height: 340px;
overflow-x: visible;
padding-right: 15px;
padding-left: 15px;
border-top: 1px solid transparent;
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
-webkit-overflow-scrolling: touch;
}
.navbar-collapse.in {
overflow-y: auto;
}
@media (min-width: 768px) {
.navbar-collapse {
width: auto;
border-top: 0;
box-shadow: none;
}
.navbar-collapse.collapse {
display: block !important;
height: auto !important;
padding-bottom: 0;
overflow: visible !important;
}
.navbar-collapse.in {
overflow-y: visible;
}
.navbar-fixed-top .navbar-collapse,
.navbar-static-top .navbar-collapse,
.navbar-fixed-bottom .navbar-collapse {
padding-left: 0;
padding-right: 0;
}
}
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: -15px;
margin-left: -15px;
}
@media (min-width: 768px) {
.container > .navbar-header,
.container-fluid > .navbar-header,
.container > .navbar-collapse,
.container-fluid > .navbar-collapse {
margin-right: 0;
margin-left: 0;
}
}
.navbar-static-top {
z-index: 1000;
border-width: 0 0 1px;
}
@media (min-width: 768px) {
.navbar-static-top {
border-radius: 0;
}
}
.navbar-fixed-top,
.navbar-fixed-bottom {
position: fixed;
right: 0;
left: 0;
z-index: 1030;
}
@media (min-width: 768px) {
.navbar-fixed-top,
.navbar-fixed-bottom {
border-radius: 0;
}
}
.navbar-fixed-top {
top: 0;
border-width: 0 0 1px;
}
.navbar-fixed-bottom {
bottom: 0;
margin-bottom: 0;
border-width: 1px 0 0;
}
.navbar-brand {
float: left;
padding: 15px 15px;
font-size: 18px;
line-height: 20px;
height: 50px;
}
.navbar-brand:hover,
.navbar-brand:focus {
text-decoration: none;
}
@media (min-width: 768px) {
.navbar > .container .navbar-brand,
.navbar > .container-fluid .navbar-brand {
margin-left: -15px;
}
}
.navbar-toggle {
position: relative;
float: right;
margin-right: 15px;
padding: 9px 10px;
margin-top: 8px;
margin-bottom: 8px;
background-color: transparent;
background-image: none;
border: 1px solid transparent;
border-radius: 4px;
}
.navbar-toggle:focus {
outline: none;
}
.navbar-toggle .icon-bar {
display: block;
width: 22px;
height: 2px;
border-radius: 1px;
}
.navbar-toggle .icon-bar + .icon-bar {
margin-top: 4px;
}
@media (min-width: 768px) {
.navbar-toggle {
display: none;
}
}
.navbar-nav {
margin: 7.5px -15px;
}
.navbar-nav > li > a {
padding-top: 10px;
padding-bottom: 10px;
line-height: 20px;
}
@media (max-width: 767px) {
.navbar-nav .open .dropdown-menu {
position: static;
float: none;
width: auto;
margin-top: 0;
background-color: transparent;
border: 0;
box-shadow: none;
}
.navbar-nav .open .dropdown-menu > li > a,
.navbar-nav .open .dropdown-menu .dropdown-header {
padding: 5px 15px 5px 25px;
}
.navbar-nav .open .dropdown-menu > li > a {
line-height: 20px;
}
.navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-nav .open .dropdown-menu > li > a:focus {
background-image: none;
}
}
@media (min-width: 768px) {
.navbar-nav {
float: left;
margin: 0;
}
.navbar-nav > li {
float: left;
}
.navbar-nav > li > a {
padding-top: 15px;
padding-bottom: 15px;
}
.navbar-nav.navbar-right:last-child {
margin-right: -15px;
}
}
@media (min-width: 768px) {
.navbar-left {
float: left !important;
}
.navbar-right {
float: right !important;
}
}
.navbar-form {
margin-left: -15px;
margin-right: -15px;
padding: 10px 15px;
border-top: 1px solid transparent;
border-bottom: 1px solid transparent;
-webkit-box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1), 0 1px 0 rgba(255, 255, 255, 0.1);
margin-top: 6px;
margin-bottom: 6px;
}
@media (min-width: 768px) {
.navbar-form .form-group {
display: inline-block;
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .form-control {
display: inline-block;
width: auto;
vertical-align: middle;
}
.navbar-form .input-group > .form-control {
width: 100%;
}
.navbar-form .control-label {
margin-bottom: 0;
vertical-align: middle;
}
.navbar-form .radio,
.navbar-form .checkbox {
display: inline-block;
margin-top: 0;
margin-bottom: 0;
padding-left: 0;
vertical-align: middle;
}
.navbar-form .radio input[type="radio"],
.navbar-form .checkbox input[type="checkbox"] {
float: none;
margin-left: 0;
}
.navbar-form .has-feedback .form-control-feedback {
top: 0;
}
}
@media (max-width: 767px) {
.navbar-form .form-group {
margin-bottom: 5px;
}
}
@media (min-width: 768px) {
.navbar-form {
width: auto;
border: 0;
margin-left: 0;
margin-right: 0;
padding-top: 0;
padding-bottom: 0;
-webkit-box-shadow: none;
box-shadow: none;
}
.navbar-form.navbar-right:last-child {
margin-right: -15px;
}
}
.navbar-nav > li > .dropdown-menu {
margin-top: 0;
border-top-right-radius: 0;
border-top-left-radius: 0;
}
.navbar-fixed-bottom .navbar-nav > li > .dropdown-menu {
border-bottom-right-radius: 0;
border-bottom-left-radius: 0;
}
.navbar-btn {
margin-top: 6px;
margin-bottom: 6px;
}
.navbar-btn.btn-sm {
margin-top: 10px;
margin-bottom: 10px;
}
.navbar-btn.btn-xs {
margin-top: 14px;
margin-bottom: 14px;
}
.navbar-text {
margin-top: 15px;
margin-bottom: 15px;
}
@media (min-width: 768px) {
.navbar-text {
float: left;
margin-left: 15px;
margin-right: 15px;
}
.navbar-text.navbar-right:last-child {
margin-right: 0;
}
}
.navbar-default {
background-color: #eeeeee;
border-color: #dddddd;
}
.navbar-default .navbar-brand {
color: #777777;
}
.navbar-default .navbar-brand:hover,
.navbar-default .navbar-brand:focus {
color: #3399f3;
background-color: transparent;
}
.navbar-default .navbar-text {
color: #777777;
}
.navbar-default .navbar-nav > li > a {
color: #777777;
}
.navbar-default .navbar-nav > li > a:hover,
.navbar-default .navbar-nav > li > a:focus {
color: #3399f3;
background-color: transparent;
}
.navbar-default .navbar-nav > .active > a,
.navbar-default .navbar-nav > .active > a:hover,
.navbar-default .navbar-nav > .active > a:focus {
color: #3399f3;
background-color: transparent;
}
.navbar-default .navbar-nav > .disabled > a,
.navbar-default .navbar-nav > .disabled > a:hover,
.navbar-default .navbar-nav > .disabled > a:focus {
color: #444444;
background-color: transparent;
}
.navbar-default .navbar-toggle {
border-color: #dddddd;
}
.navbar-default .navbar-toggle:hover,
.navbar-default .navbar-toggle:focus {
background-color: #dddddd;
}
.navbar-default .navbar-toggle .icon-bar {
background-color: #cccccc;
}
.navbar-default .navbar-collapse,
.navbar-default .navbar-form {
border-color: #dddddd;
}
.navbar-default .navbar-nav > .open > a,
.navbar-default .navbar-nav > .open > a:hover,
.navbar-default .navbar-nav > .open > a:focus {
background-color: transparent;
color: #3399f3;
}
@media (max-width: 767px) {
.navbar-default .navbar-nav .open .dropdown-menu > li > a {
color: #777777;
}
.navbar-default .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > li > a:focus {
color: #3399f3;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .active > a,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #3399f3;
background-color: transparent;
}
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-default .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #444444;
background-color: transparent;
}
}
.navbar-default .navbar-link {
color: #777777;
}
.navbar-default .navbar-link:hover {
color: #3399f3;
}
.navbar-inverse {
background-color: #446e9b;
border-color: #345578;
}
.navbar-inverse .navbar-brand {
color: #dddddd;
}
.navbar-inverse .navbar-brand:hover,
.navbar-inverse .navbar-brand:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-text {
color: #dddddd;
}
.navbar-inverse .navbar-nav > li > a {
color: #dddddd;
}
.navbar-inverse .navbar-nav > li > a:hover,
.navbar-inverse .navbar-nav > li > a:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .active > a,
.navbar-inverse .navbar-nav > .active > a:hover,
.navbar-inverse .navbar-nav > .active > a:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav > .disabled > a,
.navbar-inverse .navbar-nav > .disabled > a:hover,
.navbar-inverse .navbar-nav > .disabled > a:focus {
color: #cccccc;
background-color: transparent;
}
.navbar-inverse .navbar-toggle {
border-color: #345578;
}
.navbar-inverse .navbar-toggle:hover,
.navbar-inverse .navbar-toggle:focus {
background-color: #345578;
}
.navbar-inverse .navbar-toggle .icon-bar {
background-color: #ffffff;
}
.navbar-inverse .navbar-collapse,
.navbar-inverse .navbar-form {
border-color: #395c82;
}
.navbar-inverse .navbar-nav > .open > a,
.navbar-inverse .navbar-nav > .open > a:hover,
.navbar-inverse .navbar-nav > .open > a:focus {
background-color: transparent;
color: #ffffff;
}
@media (max-width: 767px) {
.navbar-inverse .navbar-nav .open .dropdown-menu > .dropdown-header {
border-color: #345578;
}
.navbar-inverse .navbar-nav .open .dropdown-menu .divider {
background-color: #345578;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a {
color: #dddddd;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > li > a:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .active > a:focus {
color: #ffffff;
background-color: transparent;
}
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:hover,
.navbar-inverse .navbar-nav .open .dropdown-menu > .disabled > a:focus {
color: #cccccc;
background-color: transparent;
}
}
.navbar-inverse .navbar-link {
color: #dddddd;
}
.navbar-inverse .navbar-link:hover {
color: #ffffff;
}
.breadcrumb {
padding: 8px 15px;
margin-bottom: 20px;
list-style: none;
background-color: #f5f5f5;
border-radius: 4px;
}
.breadcrumb > li {
display: inline-block;
}
.breadcrumb > li + li:before {
content: "/\00a0";
padding: 0 5px;
color: #cccccc;
}
.breadcrumb > .active {
color: #999999;
}
.pagination {
display: inline-block;
padding-left: 0;
margin: 20px 0;
border-radius: 4px;
}
.pagination > li {
display: inline;
}
.pagination > li > a,
.pagination > li > span {
position: relative;
float: left;
padding: 8px 12px;
line-height: 1.42857143;
text-decoration: none;
color: #3399f3;
background-color: #ffffff;
border: 1px solid #dddddd;
margin-left: -1px;
}
.pagination > li:first-child > a,
.pagination > li:first-child > span {
margin-left: 0;
border-bottom-left-radius: 4px;
border-top-left-radius: 4px;
}
.pagination > li:last-child > a,
.pagination > li:last-child > span {
border-bottom-right-radius: 4px;
border-top-right-radius: 4px;
}
.pagination > li > a:hover,
.pagination > li > span:hover,
.pagination > li > a:focus,
.pagination > li > span:focus {
color: #3399f3;
background-color: #eeeeee;
border-color: #dddddd;
}
.pagination > .active > a,
.pagination > .active > span,
.pagination > .active > a:hover,
.pagination > .active > span:hover,
.pagination > .active > a:focus,
.pagination > .active > span:focus {
z-index: 2;
color: #999999;
background-color: #f5f5f5;
border-color: #dddddd;
cursor: default;
}
.pagination > .disabled > span,
.pagination > .disabled > span:hover,
.pagination > .disabled > span:focus,
.pagination > .disabled > a,
.pagination > .disabled > a:hover,
.pagination > .disabled > a:focus {
color: #999999;
background-color: #ffffff;
border-color: #dddddd;
cursor: not-allowed;
}
.pagination-lg > li > a,
.pagination-lg > li > span {
padding: 14px 16px;
font-size: 18px;
}
.pagination-lg > li:first-child > a,
.pagination-lg > li:first-child > span {
border-bottom-left-radius: 6px;
border-top-left-radius: 6px;
}
.pagination-lg > li:last-child > a,
.pagination-lg > li:last-child > span {
border-bottom-right-radius: 6px;
border-top-right-radius: 6px;
}
.pagination-sm > li > a,
.pagination-sm > li > span {
padding: 5px 10px;
font-size: 12px;
}
.pagination-sm > li:first-child > a,
.pagination-sm > li:first-child > span {
border-bottom-left-radius: 3px;
border-top-left-radius: 3px;
}
.pagination-sm > li:last-child > a,
.pagination-sm > li:last-child > span {
border-bottom-right-radius: 3px;
border-top-right-radius: 3px;
}
.pager {
padding-left: 0;
margin: 20px 0;
list-style: none;
text-align: center;
}
.pager li {
display: inline;
}
.pager li > a,
.pager li > span {
display: inline-block;
padding: 5px 14px;
background-color: #ffffff;
border: 1px solid #dddddd;
border-radius: 15px;
}
.pager li > a:hover,
.pager li > a:focus {
text-decoration: none;
background-color: #eeeeee;
}
.pager .next > a,
.pager .next > span {
float: right;
}
.pager .previous > a,
.pager .previous > span {
float: left;
}
.pager .disabled > a,
.pager .disabled > a:hover,
.pager .disabled > a:focus,
.pager .disabled > span {
color: #999999;
background-color: #ffffff;
cursor: not-allowed;
}
.label {
display: inline;
padding: .2em .6em .3em;
font-size: 75%;
font-weight: bold;
line-height: 1;
color: #ffffff;
text-align: center;
white-space: nowrap;
vertical-align: baseline;
border-radius: .25em;
}
.label[href]:hover,
.label[href]:focus {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
.label:empty {
display: none;
}
.btn .label {
position: relative;
top: -1px;
}
.label-default {
background-color: #474949;
}
.label-default[href]:hover,
.label-default[href]:focus {
background-color: #2e2f2f;
}
.label-primary {
background-color: #446e9b;
}
.label-primary[href]:hover,
.label-primary[href]:focus {
background-color: #345578;
}
.label-success {
background-color: #3cb521;
}
.label-success[href]:hover,
.label-success[href]:focus {
background-color: #2e8a19;
}
.label-info {
background-color: #3399f3;
}
.label-info[href]:hover,
.label-info[href]:focus {
background-color: #0e80e5;
}
.label-warning {
background-color: #d47500;
}
.label-warning[href]:hover,
.label-warning[href]:focus {
background-color: #a15900;
}
.label-danger {
background-color: #cd0200;
}
.label-danger[href]:hover,
.label-danger[href]:focus {
background-color: #9a0200;
}
.badge {
display: inline-block;
min-width: 10px;
padding: 3px 7px;
font-size: 12px;
font-weight: bold;
color: #ffffff;
line-height: 1;
vertical-align: baseline;
white-space: nowrap;
text-align: center;
background-color: #999999;
border-radius: 10px;
}
.badge:empty {
display: none;
}
.btn .badge {
position: relative;
top: -1px;
}
.btn-xs .badge {
top: 0;
padding: 1px 5px;
}
a.badge:hover,
a.badge:focus {
color: #ffffff;
text-decoration: none;
cursor: pointer;
}
a.list-group-item.active > .badge,
.nav-pills > .active > a > .badge {
color: #3399f3;
background-color: #ffffff;
}
.nav-pills > li > a > .badge {
margin-left: 3px;
}
.jumbotron {
padding: 30px;
margin-bottom: 30px;
color: inherit;
background-color: #eeeeee;
}
.jumbotron h1,
.jumbotron .h1 {
color: inherit;
}
.jumbotron p {
margin-bottom: 15px;
font-size: 21px;
font-weight: 200;
}
.container .jumbotron {
border-radius: 6px;
}
.jumbotron .container {
max-width: 100%;
}
@media screen and (min-width: 768px) {
.jumbotron {
padding-top: 48px;
padding-bottom: 48px;
}
.container .jumbotron {
padding-left: 60px;
padding-right: 60px;
}
.jumbotron h1,
.jumbotron .h1 {
font-size: 63px;
}
}
.thumbnail {
display: block;
padding: 4px;
margin-bottom: 20px;
line-height: 1.42857143;
background-color: #ffffff;
border: 1px solid #dddddd;
border-radius: 4px;
-webkit-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.thumbnail > img,
.thumbnail a > img {
margin-left: auto;
margin-right: auto;
}
a.thumbnail:hover,
a.thumbnail:focus,
a.thumbnail.active {
border-color: #3399f3;
}
.thumbnail .caption {
padding: 9px;
color: #666666;
}
.alert {
padding: 15px;
margin-bottom: 20px;
border: 1px solid transparent;
border-radius: 4px;
}
.alert h4 {
margin-top: 0;
color: inherit;
}
.alert .alert-link {
font-weight: bold;
}
.alert > p,
.alert > ul {
margin-bottom: 0;
}
.alert > p + p {
margin-top: 5px;
}
.alert-dismissable {
padding-right: 35px;
}
.alert-dismissable .close {
position: relative;
top: -2px;
right: -21px;
color: inherit;
}
.alert-success {
background-color: #dff0d8;
border-color: #d6e9c6;
color: #468847;
}
.alert-success hr {
border-top-color: #c9e2b3;
}
.alert-success .alert-link {
color: #356635;
}
.alert-info {
background-color: #d9edf7;
border-color: #bce8f1;
color: #3a87ad;
}
.alert-info hr {
border-top-color: #a6e1ec;
}
.alert-info .alert-link {
color: #2d6987;
}
.alert-warning {
background-color: #fcf8e3;
border-color: #fbeed5;
color: #c09853;
}
.alert-warning hr {
border-top-color: #f8e5be;
}
.alert-warning .alert-link {
color: #a47e3c;
}
.alert-danger {
background-color: #f2dede;
border-color: #eed3d7;
color: #b94a48;
}
.alert-danger hr {
border-top-color: #e6c1c7;
}
.alert-danger .alert-link {
color: #953b39;
}
@-webkit-keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
@keyframes progress-bar-stripes {
from {
background-position: 40px 0;
}
to {
background-position: 0 0;
}
}
.progress {
overflow: hidden;
height: 20px;
margin-bottom: 20px;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
box-shadow: inset 0 1px 2px rgba(0, 0, 0, 0.1);
}
.progress-bar {
float: left;
width: 0%;
height: 100%;
font-size: 12px;
line-height: 20px;
color: #ffffff;
text-align: center;
background-color: #446e9b;
-webkit-box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
box-shadow: inset 0 -1px 0 rgba(0, 0, 0, 0.15);
-webkit-transition: width 0.6s ease;
transition: width 0.6s ease;
}
.progress-striped .progress-bar {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-size: 40px 40px;
}
.progress.active .progress-bar {
-webkit-animation: progress-bar-stripes 2s linear infinite;
animation: progress-bar-stripes 2s linear infinite;
}
.progress-bar-success {
background-color: #3cb521;
}
.progress-striped .progress-bar-success {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-info {
background-color: #3399f3;
}
.progress-striped .progress-bar-info {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-warning {
background-color: #d47500;
}
.progress-striped .progress-bar-warning {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.progress-bar-danger {
background-color: #cd0200;
}
.progress-striped .progress-bar-danger {
background-image: -webkit-linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
background-image: linear-gradient(45deg, rgba(255, 255, 255, 0.15) 25%, transparent 25%, transparent 50%, rgba(255, 255, 255, 0.15) 50%, rgba(255, 255, 255, 0.15) 75%, transparent 75%, transparent);
}
.media,
.media-body {
overflow: hidden;
zoom: 1;
}
.media,
.media .media {
margin-top: 15px;
}
.media:first-child {
margin-top: 0;
}
.media-object {
display: block;
}
.media-heading {
margin: 0 0 5px;
}
.media > .pull-left {
margin-right: 10px;
}
.media > .pull-right {
margin-left: 10px;
}
.media-list {
padding-left: 0;
list-style: none;
}
.list-group {
margin-bottom: 20px;
padding-left: 0;
}
.list-group-item {
position: relative;
display: block;
padding: 10px 15px;
margin-bottom: -1px;
background-color: #ffffff;
border: 1px solid #dddddd;
}
.list-group-item:first-child {
border-top-right-radius: 4px;
border-top-left-radius: 4px;
}
.list-group-item:last-child {
margin-bottom: 0;
border-bottom-right-radius: 4px;
border-bottom-left-radius: 4px;
}
.list-group-item > .badge {
float: right;
}
.list-group-item > .badge + .badge {
margin-right: 5px;
}
a.list-group-item {
color: #555555;
}
a.list-group-item .list-group-item-heading {
color: #333333;
}
a.list-group-item:hover,
a.list-group-item:focus {
text-decoration: none;
background-color: #f5f5f5;
}
a.list-group-item.active,
a.list-group-item.active:hover,
a.list-group-item.active:focus {
z-index: 2;
color: #ffffff;
background-color: #446e9b;
border-color: #446e9b;
}
a.list-group-item.active .list-group-item-heading,
a.list-group-item.active:hover .list-group-item-heading,
a.list-group-item.active:focus .list-group-item-heading {
color: inherit;
}
a.list-group-item.active .list-group-item-text,
a.list-group-item.active:hover .list-group-item-text,
a.list-group-item.active:focus .list-group-item-text {
color: #c5d5e6;
}
.list-group-item-success {
color: #468847;
background-color: #dff0d8;
}
a.list-group-item-success {
color: #468847;
}
a.list-group-item-success .list-group-item-heading {
color: inherit;
}
a.list-group-item-success:hover,
a.list-group-item-success:focus {
color: #468847;
background-color: #d0e9c6;
}
a.list-group-item-success.active,
a.list-group-item-success.active:hover,
a.list-group-item-success.active:focus {
color: #fff;
background-color: #468847;
border-color: #468847;
}
.list-group-item-info {
color: #3a87ad;
background-color: #d9edf7;
}
a.list-group-item-info {
color: #3a87ad;
}
a.list-group-item-info .list-group-item-heading {
color: inherit;
}
a.list-group-item-info:hover,
a.list-group-item-info:focus {
color: #3a87ad;
background-color: #c4e3f3;
}
a.list-group-item-info.active,
a.list-group-item-info.active:hover,
a.list-group-item-info.active:focus {
color: #fff;
background-color: #3a87ad;
border-color: #3a87ad;
}
.list-group-item-warning {
color: #c09853;
background-color: #fcf8e3;
}
a.list-group-item-warning {
color: #c09853;
}
a.list-group-item-warning .list-group-item-heading {
color: inherit;
}
a.list-group-item-warning:hover,
a.list-group-item-warning:focus {
color: #c09853;
background-color: #faf2cc;
}
a.list-group-item-warning.active,
a.list-group-item-warning.active:hover,
a.list-group-item-warning.active:focus {
color: #fff;
background-color: #c09853;
border-color: #c09853;
}
.list-group-item-danger {
color: #b94a48;
background-color: #f2dede;
}
a.list-group-item-danger {
color: #b94a48;
}
a.list-group-item-danger .list-group-item-heading {
color: inherit;
}
a.list-group-item-danger:hover,
a.list-group-item-danger:focus {
color: #b94a48;
background-color: #ebcccc;
}
a.list-group-item-danger.active,
a.list-group-item-danger.active:hover,
a.list-group-item-danger.active:focus {
color: #fff;
background-color: #b94a48;
border-color: #b94a48;
}
.list-group-item-heading {
margin-top: 0;
margin-bottom: 5px;
}
.list-group-item-text {
margin-bottom: 0;
line-height: 1.3;
}
.panel {
margin-bottom: 20px;
background-color: #ffffff;
border: 1px solid transparent;
border-radius: 4px;
-webkit-box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: 0 1px 1px rgba(0, 0, 0, 0.05);
}
.panel-body {
padding: 15px;
}
.panel-heading {
padding: 10px 15px;
border-bottom: 1px solid transparent;
border-top-right-radius: 3px;
border-top-left-radius: 3px;
}
.panel-heading > .dropdown .dropdown-toggle {
color: inherit;
}
.panel-title {
margin-top: 0;
margin-bottom: 0;
font-size: 16px;
color: inherit;
}
.panel-title > a {
color: inherit;
}
.panel-footer {
padding: 10px 15px;
background-color: #f5f5f5;
border-top: 1px solid #dddddd;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .list-group {
margin-bottom: 0;
}
.panel > .list-group .list-group-item {
border-width: 1px 0;
border-radius: 0;
}
.panel > .list-group:first-child .list-group-item:first-child {
border-top: 0;
border-top-right-radius: 3px;
border-top-left-radius: 3px;
}
.panel > .list-group:last-child .list-group-item:last-child {
border-bottom: 0;
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel-heading + .list-group .list-group-item:first-child {
border-top-width: 0;
}
.panel > .table,
.panel > .table-responsive > .table {
margin-bottom: 0;
}
.panel > .table:first-child,
.panel > .table-responsive:first-child > .table:first-child {
border-top-right-radius: 3px;
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:first-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:first-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:first-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:first-child {
border-top-left-radius: 3px;
}
.panel > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child td:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child td:last-child,
.panel > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > thead:first-child > tr:first-child th:last-child,
.panel > .table:first-child > tbody:first-child > tr:first-child th:last-child,
.panel > .table-responsive:first-child > .table:first-child > tbody:first-child > tr:first-child th:last-child {
border-top-right-radius: 3px;
}
.panel > .table:last-child,
.panel > .table-responsive:last-child > .table:last-child {
border-bottom-right-radius: 3px;
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:first-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:first-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:first-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:first-child {
border-bottom-left-radius: 3px;
}
.panel > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child td:last-child,
.panel > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tbody:last-child > tr:last-child th:last-child,
.panel > .table:last-child > tfoot:last-child > tr:last-child th:last-child,
.panel > .table-responsive:last-child > .table:last-child > tfoot:last-child > tr:last-child th:last-child {
border-bottom-right-radius: 3px;
}
.panel > .panel-body + .table,
.panel > .panel-body + .table-responsive {
border-top: 1px solid #dddddd;
}
.panel > .table > tbody:first-child > tr:first-child th,
.panel > .table > tbody:first-child > tr:first-child td {
border-top: 0;
}
.panel > .table-bordered,
.panel > .table-responsive > .table-bordered {
border: 0;
}
.panel > .table-bordered > thead > tr > th:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:first-child,
.panel > .table-bordered > tbody > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:first-child,
.panel > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:first-child,
.panel > .table-bordered > thead > tr > td:first-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:first-child,
.panel > .table-bordered > tbody > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:first-child,
.panel > .table-bordered > tfoot > tr > td:first-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:first-child {
border-left: 0;
}
.panel > .table-bordered > thead > tr > th:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > th:last-child,
.panel > .table-bordered > tbody > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > th:last-child,
.panel > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > th:last-child,
.panel > .table-bordered > thead > tr > td:last-child,
.panel > .table-responsive > .table-bordered > thead > tr > td:last-child,
.panel > .table-bordered > tbody > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tbody > tr > td:last-child,
.panel > .table-bordered > tfoot > tr > td:last-child,
.panel > .table-responsive > .table-bordered > tfoot > tr > td:last-child {
border-right: 0;
}
.panel > .table-bordered > thead > tr:first-child > td,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > td,
.panel > .table-bordered > tbody > tr:first-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > td,
.panel > .table-bordered > thead > tr:first-child > th,
.panel > .table-responsive > .table-bordered > thead > tr:first-child > th,
.panel > .table-bordered > tbody > tr:first-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:first-child > th {
border-bottom: 0;
}
.panel > .table-bordered > tbody > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > td,
.panel > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > td,
.panel > .table-bordered > tbody > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tbody > tr:last-child > th,
.panel > .table-bordered > tfoot > tr:last-child > th,
.panel > .table-responsive > .table-bordered > tfoot > tr:last-child > th {
border-bottom: 0;
}
.panel > .table-responsive {
border: 0;
margin-bottom: 0;
}
.panel-group {
margin-bottom: 20px;
}
.panel-group .panel {
margin-bottom: 0;
border-radius: 4px;
overflow: hidden;
}
.panel-group .panel + .panel {
margin-top: 5px;
}
.panel-group .panel-heading {
border-bottom: 0;
}
.panel-group .panel-heading + .panel-collapse .panel-body {
border-top: 1px solid #dddddd;
}
.panel-group .panel-footer {
border-top: 0;
}
.panel-group .panel-footer + .panel-collapse .panel-body {
border-bottom: 1px solid #dddddd;
}
.panel-default {
border-color: #dddddd;
}
.panel-default > .panel-heading {
color: #333333;
background-color: #f5f5f5;
border-color: #dddddd;
}
.panel-default > .panel-heading + .panel-collapse .panel-body {
border-top-color: #dddddd;
}
.panel-default > .panel-footer + .panel-collapse .panel-body {
border-bottom-color: #dddddd;
}
.panel-primary {
border-color: #446e9b;
}
.panel-primary > .panel-heading {
color: #ffffff;
background-color: #446e9b;
border-color: #446e9b;
}
.panel-primary > .panel-heading + .panel-collapse .panel-body {
border-top-color: #446e9b;
}
.panel-primary > .panel-footer + .panel-collapse .panel-body {
border-bottom-color: #446e9b;
}
.panel-success {
border-color: #d6e9c6;
}
.panel-success > .panel-heading {
color: #468847;
background-color: #dff0d8;
border-color: #d6e9c6;
}
.panel-success > .panel-heading + .panel-collapse .panel-body {
border-top-color: #d6e9c6;
}
.panel-success > .panel-footer + .panel-collapse .panel-body {
border-bottom-color: #d6e9c6;
}
.panel-info {
border-color: #bce8f1;
}
.panel-info > .panel-heading {
color: #3a87ad;
background-color: #d9edf7;
border-color: #bce8f1;
}
.panel-info > .panel-heading + .panel-collapse .panel-body {
border-top-color: #bce8f1;
}
.panel-info > .panel-footer + .panel-collapse .panel-body {
border-bottom-color: #bce8f1;
}
.panel-warning {
border-color: #fbeed5;
}
.panel-warning > .panel-heading {
color: #c09853;
background-color: #fcf8e3;
border-color: #fbeed5;
}
.panel-warning > .panel-heading + .panel-collapse .panel-body {
border-top-color: #fbeed5;
}
.panel-warning > .panel-footer + .panel-collapse .panel-body {
border-bottom-color: #fbeed5;
}
.panel-danger {
border-color: #eed3d7;
}
.panel-danger > .panel-heading {
color: #b94a48;
background-color: #f2dede;
border-color: #eed3d7;
}
.panel-danger > .panel-heading + .panel-collapse .panel-body {
border-top-color: #eed3d7;
}
.panel-danger > .panel-footer + .panel-collapse .panel-body {
border-bottom-color: #eed3d7;
}
.well {
min-height: 20px;
padding: 19px;
margin-bottom: 20px;
background-color: #f5f5f5;
border: 1px solid #e3e3e3;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.05);
}
.well blockquote {
border-color: #ddd;
border-color: rgba(0, 0, 0, 0.15);
}
.well-lg {
padding: 24px;
border-radius: 6px;
}
.well-sm {
padding: 9px;
border-radius: 3px;
}
.close {
float: right;
font-size: 21px;
font-weight: bold;
line-height: 1;
color: #000000;
text-shadow: 0 1px 0 #ffffff;
opacity: 0.2;
filter: alpha(opacity=20);
}
.close:hover,
.close:focus {
color: #000000;
text-decoration: none;
cursor: pointer;
opacity: 0.5;
filter: alpha(opacity=50);
}
button.close {
padding: 0;
cursor: pointer;
background: transparent;
border: 0;
-webkit-appearance: none;
}
.modal-open {
overflow: hidden;
}
.modal {
display: none;
overflow: auto;
overflow-y: scroll;
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1050;
-webkit-overflow-scrolling: touch;
outline: 0;
}
.modal.fade .modal-dialog {
-webkit-transform: translate(0, -25%);
-ms-transform: translate(0, -25%);
transform: translate(0, -25%);
-webkit-transition: -webkit-transform 0.3s ease-out;
-moz-transition: -moz-transform 0.3s ease-out;
-o-transition: -o-transform 0.3s ease-out;
transition: transform 0.3s ease-out;
}
.modal.in .modal-dialog {
-webkit-transform: translate(0, 0);
-ms-transform: translate(0, 0);
transform: translate(0, 0);
}
.modal-dialog {
position: relative;
width: auto;
margin: 10px;
}
.modal-content {
position: relative;
background-color: #ffffff;
border: 1px solid #999999;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
-webkit-box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
box-shadow: 0 3px 9px rgba(0, 0, 0, 0.5);
background-clip: padding-box;
outline: none;
}
.modal-backdrop {
position: fixed;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 1040;
background-color: #000000;
}
.modal-backdrop.fade {
opacity: 0;
filter: alpha(opacity=0);
}
.modal-backdrop.in {
opacity: 0.5;
filter: alpha(opacity=50);
}
.modal-header {
padding: 15px;
border-bottom: 1px solid #e5e5e5;
min-height: 16.42857143px;
}
.modal-header .close {
margin-top: -2px;
}
.modal-title {
margin: 0;
line-height: 1.42857143;
}
.modal-body {
position: relative;
padding: 20px;
}
.modal-footer {
margin-top: 15px;
padding: 19px 20px 20px;
text-align: right;
border-top: 1px solid #e5e5e5;
}
.modal-footer .btn + .btn {
margin-left: 5px;
margin-bottom: 0;
}
.modal-footer .btn-group .btn + .btn {
margin-left: -1px;
}
.modal-footer .btn-block + .btn-block {
margin-left: 0;
}
@media (min-width: 768px) {
.modal-dialog {
width: 600px;
margin: 30px auto;
}
.modal-content {
-webkit-box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
box-shadow: 0 5px 15px rgba(0, 0, 0, 0.5);
}
.modal-sm {
width: 300px;
}
}
@media (min-width: 992px) {
.modal-lg {
width: 900px;
}
}
.tooltip {
position: absolute;
z-index: 1030;
display: block;
visibility: visible;
font-size: 12px;
line-height: 1.4;
opacity: 0;
filter: alpha(opacity=0);
}
.tooltip.in {
opacity: 0.9;
filter: alpha(opacity=90);
}
.tooltip.top {
margin-top: -3px;
padding: 5px 0;
}
.tooltip.right {
margin-left: 3px;
padding: 0 5px;
}
.tooltip.bottom {
margin-top: 3px;
padding: 5px 0;
}
.tooltip.left {
margin-left: -3px;
padding: 0 5px;
}
.tooltip-inner {
max-width: 200px;
padding: 3px 8px;
color: #ffffff;
text-align: center;
text-decoration: none;
background-color: rgba(0, 0, 0, 0.9);
border-radius: 4px;
}
.tooltip-arrow {
position: absolute;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.tooltip.top .tooltip-arrow {
bottom: 0;
left: 50%;
margin-left: -5px;
border-width: 5px 5px 0;
border-top-color: rgba(0, 0, 0, 0.9);
}
.tooltip.top-left .tooltip-arrow {
bottom: 0;
left: 5px;
border-width: 5px 5px 0;
border-top-color: rgba(0, 0, 0, 0.9);
}
.tooltip.top-right .tooltip-arrow {
bottom: 0;
right: 5px;
border-width: 5px 5px 0;
border-top-color: rgba(0, 0, 0, 0.9);
}
.tooltip.right .tooltip-arrow {
top: 50%;
left: 0;
margin-top: -5px;
border-width: 5px 5px 5px 0;
border-right-color: rgba(0, 0, 0, 0.9);
}
.tooltip.left .tooltip-arrow {
top: 50%;
right: 0;
margin-top: -5px;
border-width: 5px 0 5px 5px;
border-left-color: rgba(0, 0, 0, 0.9);
}
.tooltip.bottom .tooltip-arrow {
top: 0;
left: 50%;
margin-left: -5px;
border-width: 0 5px 5px;
border-bottom-color: rgba(0, 0, 0, 0.9);
}
.tooltip.bottom-left .tooltip-arrow {
top: 0;
left: 5px;
border-width: 0 5px 5px;
border-bottom-color: rgba(0, 0, 0, 0.9);
}
.tooltip.bottom-right .tooltip-arrow {
top: 0;
right: 5px;
border-width: 0 5px 5px;
border-bottom-color: rgba(0, 0, 0, 0.9);
}
.popover {
position: absolute;
top: 0;
left: 0;
z-index: 1010;
display: none;
max-width: 276px;
padding: 1px;
text-align: left;
background-color: #ffffff;
background-clip: padding-box;
border: 1px solid #cccccc;
border: 1px solid rgba(0, 0, 0, 0.2);
border-radius: 6px;
-webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
white-space: normal;
}
.popover.top {
margin-top: -10px;
}
.popover.right {
margin-left: 10px;
}
.popover.bottom {
margin-top: 10px;
}
.popover.left {
margin-left: -10px;
}
.popover-title {
margin: 0;
padding: 8px 14px;
font-size: 14px;
font-weight: normal;
line-height: 18px;
background-color: #f7f7f7;
border-bottom: 1px solid #ebebeb;
border-radius: 5px 5px 0 0;
}
.popover-content {
padding: 9px 14px;
}
.popover > .arrow,
.popover > .arrow:after {
position: absolute;
display: block;
width: 0;
height: 0;
border-color: transparent;
border-style: solid;
}
.popover > .arrow {
border-width: 11px;
}
.popover > .arrow:after {
border-width: 10px;
content: "";
}
.popover.top > .arrow {
left: 50%;
margin-left: -11px;
border-bottom-width: 0;
border-top-color: #999999;
border-top-color: rgba(0, 0, 0, 0.25);
bottom: -11px;
}
.popover.top > .arrow:after {
content: " ";
bottom: 1px;
margin-left: -10px;
border-bottom-width: 0;
border-top-color: #ffffff;
}
.popover.right > .arrow {
top: 50%;
left: -11px;
margin-top: -11px;
border-left-width: 0;
border-right-color: #999999;
border-right-color: rgba(0, 0, 0, 0.25);
}
.popover.right > .arrow:after {
content: " ";
left: 1px;
bottom: -10px;
border-left-width: 0;
border-right-color: #ffffff;
}
.popover.bottom > .arrow {
left: 50%;
margin-left: -11px;
border-top-width: 0;
border-bottom-color: #999999;
border-bottom-color: rgba(0, 0, 0, 0.25);
top: -11px;
}
.popover.bottom > .arrow:after {
content: " ";
top: 1px;
margin-left: -10px;
border-top-width: 0;
border-bottom-color: #ffffff;
}
.popover.left > .arrow {
top: 50%;
right: -11px;
margin-top: -11px;
border-right-width: 0;
border-left-color: #999999;
border-left-color: rgba(0, 0, 0, 0.25);
}
.popover.left > .arrow:after {
content: " ";
right: 1px;
border-right-width: 0;
border-left-color: #ffffff;
bottom: -10px;
}
.carousel {
position: relative;
}
.carousel-inner {
position: relative;
overflow: hidden;
width: 100%;
}
.carousel-inner > .item {
display: none;
position: relative;
-webkit-transition: 0.6s ease-in-out left;
transition: 0.6s ease-in-out left;
}
.carousel-inner > .item > img,
.carousel-inner > .item > a > img {
line-height: 1;
}
.carousel-inner > .active,
.carousel-inner > .next,
.carousel-inner > .prev {
display: block;
}
.carousel-inner > .active {
left: 0;
}
.carousel-inner > .next,
.carousel-inner > .prev {
position: absolute;
top: 0;
width: 100%;
}
.carousel-inner > .next {
left: 100%;
}
.carousel-inner > .prev {
left: -100%;
}
.carousel-inner > .next.left,
.carousel-inner > .prev.right {
left: 0;
}
.carousel-inner > .active.left {
left: -100%;
}
.carousel-inner > .active.right {
left: 100%;
}
.carousel-control {
position: absolute;
top: 0;
left: 0;
bottom: 0;
width: 15%;
opacity: 0.5;
filter: alpha(opacity=50);
font-size: 20px;
color: #ffffff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}
.carousel-control.left {
background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.5) 0%), color-stop(rgba(0, 0, 0, 0.0001) 100%));
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.0001) 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#80000000', endColorstr='#00000000', GradientType=1);
}
.carousel-control.right {
left: auto;
right: 0;
background-image: -webkit-linear-gradient(left, color-stop(rgba(0, 0, 0, 0.0001) 0%), color-stop(rgba(0, 0, 0, 0.5) 100%));
background-image: linear-gradient(to right, rgba(0, 0, 0, 0.0001) 0%, rgba(0, 0, 0, 0.5) 100%);
background-repeat: repeat-x;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#00000000', endColorstr='#80000000', GradientType=1);
}
.carousel-control:hover,
.carousel-control:focus {
outline: none;
color: #ffffff;
text-decoration: none;
opacity: 0.9;
filter: alpha(opacity=90);
}
.carousel-control .icon-prev,
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right {
position: absolute;
top: 50%;
z-index: 5;
display: inline-block;
}
.carousel-control .icon-prev,
.carousel-control .glyphicon-chevron-left {
left: 50%;
}
.carousel-control .icon-next,
.carousel-control .glyphicon-chevron-right {
right: 50%;
}
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 20px;
height: 20px;
margin-top: -10px;
margin-left: -10px;
font-family: serif;
}
.carousel-control .icon-prev:before {
content: '\2039';
}
.carousel-control .icon-next:before {
content: '\203a';
}
.carousel-indicators {
position: absolute;
bottom: 10px;
left: 50%;
z-index: 15;
width: 60%;
margin-left: -30%;
padding-left: 0;
list-style: none;
text-align: center;
}
.carousel-indicators li {
display: inline-block;
width: 10px;
height: 10px;
margin: 1px;
text-indent: -999px;
border: 1px solid #ffffff;
border-radius: 10px;
cursor: pointer;
background-color: #000 \9;
background-color: rgba(0, 0, 0, 0);
}
.carousel-indicators .active {
margin: 0;
width: 12px;
height: 12px;
background-color: #ffffff;
}
.carousel-caption {
position: absolute;
left: 15%;
right: 15%;
bottom: 20px;
z-index: 10;
padding-top: 20px;
padding-bottom: 20px;
color: #ffffff;
text-align: center;
text-shadow: 0 1px 2px rgba(0, 0, 0, 0.6);
}
.carousel-caption .btn {
text-shadow: none;
}
@media screen and (min-width: 768px) {
.carousel-control .glyphicon-chevron-left,
.carousel-control .glyphicon-chevron-right,
.carousel-control .icon-prev,
.carousel-control .icon-next {
width: 30px;
height: 30px;
margin-top: -15px;
margin-left: -15px;
font-size: 30px;
}
.carousel-caption {
left: 20%;
right: 20%;
padding-bottom: 30px;
}
.carousel-indicators {
bottom: 20px;
}
}
@-ms-viewport {
width: device-width;
}
.visible-xs,
.visible-sm,
.visible-md,
.visible-lg {
display: none !important;
}
@media (max-width: 767px) {
.visible-xs {
display: block !important;
}
table.visible-xs {
display: table;
}
tr.visible-xs {
display: table-row !important;
}
th.visible-xs,
td.visible-xs {
display: table-cell !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.visible-sm {
display: block !important;
}
table.visible-sm {
display: table;
}
tr.visible-sm {
display: table-row !important;
}
th.visible-sm,
td.visible-sm {
display: table-cell !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.visible-md {
display: block !important;
}
table.visible-md {
display: table;
}
tr.visible-md {
display: table-row !important;
}
th.visible-md,
td.visible-md {
display: table-cell !important;
}
}
@media (min-width: 1200px) {
.visible-lg {
display: block !important;
}
table.visible-lg {
display: table;
}
tr.visible-lg {
display: table-row !important;
}
th.visible-lg,
td.visible-lg {
display: table-cell !important;
}
}
@media (max-width: 767px) {
.hidden-xs {
display: none !important;
}
}
@media (min-width: 768px) and (max-width: 991px) {
.hidden-sm {
display: none !important;
}
}
@media (min-width: 992px) and (max-width: 1199px) {
.hidden-md {
display: none !important;
}
}
@media (min-width: 1200px) {
.hidden-lg {
display: none !important;
}
}
.visible-print {
display: none !important;
}
@media print {
.visible-print {
display: block !important;
}
table.visible-print {
display: table;
}
tr.visible-print {
display: table-row !important;
}
th.visible-print,
td.visible-print {
display: table-cell !important;
}
}
@media print {
.hidden-print {
display: none !important;
}
}
.navbar {
background-image: -webkit-linear-gradient(#ffffff, #eeeeee 50%, #e4e4e4);
background-image: linear-gradient(#ffffff, #eeeeee 50%, #e4e4e4);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffffffff', endColorstr='#ffe4e4e4', GradientType=0);
filter: none;
border: 1px solid #d5d5d5;
text-shadow: 0 1px 0 rgba(255, 255, 255, 0.3);
}
.navbar-inverse {
background-image: -webkit-linear-gradient(#6d94bf, #446e9b 50%, #3e648d);
background-image: linear-gradient(#6d94bf, #446e9b 50%, #3e648d);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff6d94bf', endColorstr='#ff3e648d', GradientType=0);
filter: none;
border: 1px solid #345578;
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
}
.navbar-nav > li > a,
.navbar-nav > li > a:hover {
padding-top: 17px;
padding-bottom: 13px;
-webkit-transition: color ease-in-out 0.2s;
transition: color ease-in-out 0.2s;
}
.navbar-brand,
.navbar-brand:hover {
-webkit-transition: color ease-in-out 0.2s;
transition: color ease-in-out 0.2s;
}
.navbar .caret,
.navbar .caret:hover {
-webkit-transition: border-color ease-in-out 0.2s;
transition: border-color ease-in-out 0.2s;
}
.navbar .dropdown-menu {
text-shadow: none;
}
.btn {
text-shadow: 0 -1px 0 rgba(0, 0, 0, 0.3);
}
.btn-default {
background-image: -webkit-linear-gradient(#6d7070, #474949 50%, #3d3f3f);
background-image: linear-gradient(#6d7070, #474949 50%, #3d3f3f);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff6d7070', endColorstr='#ff3d3f3f', GradientType=0);
filter: none;
border: 1px solid #2e2f2f;
}
.btn-default:hover {
background-image: -webkit-linear-gradient(#636565, #3d3f3f 50%, #333434);
background-image: linear-gradient(#636565, #3d3f3f 50%, #333434);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff636565', endColorstr='#ff333434', GradientType=0);
filter: none;
border: 1px solid #242525;
}
.btn-primary {
background-image: -webkit-linear-gradient(#6d94bf, #446e9b 50%, #3e648d);
background-image: linear-gradient(#6d94bf, #446e9b 50%, #3e648d);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff6d94bf', endColorstr='#ff3e648d', GradientType=0);
filter: none;
border: 1px solid #345578;
}
.btn-primary:hover {
background-image: -webkit-linear-gradient(#5f8ab9, #3e648d 50%, #385a7f);
background-image: linear-gradient(#5f8ab9, #3e648d 50%, #385a7f);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff5f8ab9', endColorstr='#ff385a7f', GradientType=0);
filter: none;
border: 1px solid #2e4b69;
}
.btn-success {
background-image: -webkit-linear-gradient(#61dd45, #3cb521 50%, #36a41e);
background-image: linear-gradient(#61dd45, #3cb521 50%, #36a41e);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff61dd45', endColorstr='#ff36a41e', GradientType=0);
filter: none;
border: 1px solid #2e8a19;
}
.btn-success:hover {
background-image: -webkit-linear-gradient(#52da34, #36a41e 50%, #31921b);
background-image: linear-gradient(#52da34, #36a41e 50%, #31921b);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff52da34', endColorstr='#ff31921b', GradientType=0);
filter: none;
border: 1px solid #287916;
}
.btn-info {
background-image: -webkit-linear-gradient(#7bbdf7, #3399f3 50%, #208ff2);
background-image: linear-gradient(#7bbdf7, #3399f3 50%, #208ff2);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff7bbdf7', endColorstr='#ff208ff2', GradientType=0);
filter: none;
border: 1px solid #0e80e5;
}
.btn-info:hover {
background-image: -webkit-linear-gradient(#68b3f6, #208ff2 50%, #0e86ef);
background-image: linear-gradient(#68b3f6, #208ff2 50%, #0e86ef);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ff68b3f6', endColorstr='#ff0e86ef', GradientType=0);
filter: none;
border: 1px solid #0c75d2;
}
.btn-warning {
background-image: -webkit-linear-gradient(#ff9c21, #d47500 50%, #c06a00);
background-image: linear-gradient(#ff9c21, #d47500 50%, #c06a00);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff9c21', endColorstr='#ffc06a00', GradientType=0);
filter: none;
border: 1px solid #a15900;
}
.btn-warning:hover {
background-image: -webkit-linear-gradient(#ff930d, #c06a00 50%, #ab5e00);
background-image: linear-gradient(#ff930d, #c06a00 50%, #ab5e00);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff930d', endColorstr='#ffab5e00', GradientType=0);
filter: none;
border: 1px solid #8d4e00;
}
.btn-danger {
background-image: -webkit-linear-gradient(#ff1d1b, #cd0200 50%, #b90200);
background-image: linear-gradient(#ff1d1b, #cd0200 50%, #b90200);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff1d1b', endColorstr='#ffb90200', GradientType=0);
filter: none;
border: 1px solid #9a0200;
}
.btn-danger:hover {
background-image: -webkit-linear-gradient(#ff0906, #b90200 50%, #a40200);
background-image: linear-gradient(#ff0906, #b90200 50%, #a40200);
background-repeat: no-repeat;
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='#ffff0906', endColorstr='#ffa40200', GradientType=0);
filter: none;
border: 1px solid #860100;
}
.btn:active,
.btn.active {
background-image: none;
-webkit-box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
box-shadow: inset 0 3px 5px rgba(0, 0, 0, 0.125);
}
.panel-primary .panel-title {
color: #fff;
}
.clearfix:before,
.clearfix:after,
.container:before,
.container:after,
.container-fluid:before,
.container-fluid:after,
.row:before,
.row:after,
.form-horizontal .form-group:before,
.form-horizontal .form-group:after,
.btn-toolbar:before,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:before,
.btn-group-vertical > .btn-group:after,
.nav:before,
.nav:after,
.navbar:before,
.navbar:after,
.navbar-header:before,
.navbar-header:after,
.navbar-collapse:before,
.navbar-collapse:after,
.pager:before,
.pager:after,
.panel-body:before,
.panel-body:after,
.modal-footer:before,
.modal-footer:after {
content: " ";
display: table;
}
.clearfix:after,
.container:after,
.container-fluid:after,
.row:after,
.form-horizontal .form-group:after,
.btn-toolbar:after,
.btn-group-vertical > .btn-group:after,
.nav:after,
.navbar:after,
.navbar-header:after,
.navbar-collapse:after,
.pager:after,
.panel-body:after,
.modal-footer:after {
clear: both;
}
.center-block {
display: block;
margin-left: auto;
margin-right: auto;
}
.pull-right {
float: right !important;
}
.pull-left {
float: left !important;
}
.hide {
display: none !important;
}
.show {
display: block !important;
}
.invisible {
visibility: hidden;
}
.text-hide {
font: 0/0 a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
.hidden {
display: none !important;
visibility: hidden !important;
}
.affix {
position: fixed;
}
|
ecrit/ecrit
|
at.ecrit.eclipse.plugin.outputter.html/rsc/templates/css/bright_theme.css
|
CSS
|
epl-1.0
| 127,621 |
/**
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
/*
* Created on Mar 29, 2004
*
*/
package org.python.pydev.editor.codecompletion;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.text.BadLocationException;
import org.eclipse.jface.text.IDocument;
import org.eclipse.jface.text.ITextViewer;
import org.eclipse.jface.text.contentassist.ContentAssistEvent;
import org.eclipse.jface.text.contentassist.ICompletionListener;
import org.eclipse.jface.text.contentassist.ICompletionProposal;
import org.eclipse.jface.text.contentassist.IContextInformation;
import org.eclipse.jface.text.contentassist.IContextInformationValidator;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.python.pydev.core.IInterpreterManager;
import org.python.pydev.core.IPythonNature;
import org.python.pydev.core.MisconfigurationException;
import org.python.pydev.core.PythonNatureWithoutProjectException;
import org.python.pydev.core.docutils.PySelection;
import org.python.pydev.core.log.Log;
import org.python.pydev.editor.IPySyntaxHighlightingAndCodeCompletionEditor;
import org.python.pydev.editor.codecompletion.templates.PyTemplateCompletionProcessor;
import org.python.pydev.plugin.PydevPlugin;
import org.python.pydev.plugin.nature.SystemPythonNature;
import org.python.pydev.shared_core.string.StringUtils;
import org.python.pydev.shared_ui.content_assist.AbstractCompletionProcessorWithCycling;
import org.python.pydev.ui.interpreters.ChooseInterpreterManager;
/**
* @author Dmoore
* @author Fabio Zadrozny
*
* This class is responsible for code completion / template completion.
*/
public class PythonCompletionProcessor extends AbstractCompletionProcessorWithCycling {
/**
* This makes the templates completion
*/
private PyTemplateCompletionProcessor templatesCompletion = new PyTemplateCompletionProcessor();
/**
* This makes python code completion
*/
private IPyCodeCompletion codeCompletion;
/**
* Edit.
*/
private IPySyntaxHighlightingAndCodeCompletionEditor edit;
/**
* Some error...
*/
private String error;
/**
* These are the activation chars (cache)
*/
private volatile static char[] activationChars = null;
/**
* This is the class that manages the context information (validates it and
* changes its presentation).
*/
private PyContextInformationValidator contextInformationValidator;
/**
* @param edit the editor that works with this processor
* @param pyContentAssistant the content assistant that will invoke this completion
*/
public PythonCompletionProcessor(IPySyntaxHighlightingAndCodeCompletionEditor edit,
PyContentAssistant pyContentAssistant) {
super(pyContentAssistant);
this.edit = edit;
this.contentAssistant = pyContentAssistant;
this.codeCompletion = getCodeCompletionEngine();
contextInformationValidator = new PyContextInformationValidator();
pyContentAssistant.addCompletionListener(new ICompletionListener() {
public void assistSessionEnded(ContentAssistEvent event) {
}
public void assistSessionStarted(ContentAssistEvent event) {
startCycle();
}
public void selectionChanged(ICompletionProposal proposal, boolean smartToggle) {
//ignore
}
});
}
protected IPyCodeCompletion getCodeCompletionEngine() {
return new PyCodeCompletion();
}
/**
* This is the interface implemented to get the completions.
*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeCompletionProposals(org.eclipse.jface.text.ITextViewer, int)
*/
@SuppressWarnings("unchecked")
public ICompletionProposal[] computeCompletionProposals(ITextViewer viewer, int documentOffset) {
updateStatus();
ICompletionProposal[] proposals;
try {
//FIRST: discover activation token and qualifier.
IDocument doc = viewer.getDocument();
//list for storing the proposals
ArrayList<ICompletionProposal> pythonAndTemplateProposals = new ArrayList<ICompletionProposal>();
IPythonNature nature = edit.getPythonNature();
if (nature == null) {
IInterpreterManager manager = ChooseInterpreterManager.chooseInterpreterManager();
if (manager != null) {
nature = new SystemPythonNature(manager);
} else {
CompletionError completionError = new CompletionError(new RuntimeException(
"No interpreter configured."));
this.error = completionError.getErrorMessage();
return new ICompletionProposal[] { completionError };
}
}
if (nature == null || !nature.startRequests()) {
return new ICompletionProposal[0];
}
try {
CompletionRequest request = new CompletionRequest(edit.getEditorFile(), nature, doc, documentOffset,
codeCompletion);
//SECOND: getting code completions and deciding if templates should be shown too.
//Get code completion proposals
if (PyCodeCompletionPreferencesPage.useCodeCompletion()) {
if (whatToShow == SHOW_ALL) {
try {
pythonAndTemplateProposals.addAll(getPythonProposals(viewer, documentOffset, doc, request));
} catch (Throwable e) {
Log.log(e);
CompletionError completionError = new CompletionError(e);
this.error = completionError.getErrorMessage();
//Make the error visible to the user!
return new ICompletionProposal[] { completionError };
}
}
}
String[] strs = PySelection.getActivationTokenAndQual(doc, documentOffset, false);
String activationToken = strs[0];
String qualifier = strs[1];
//THIRD: Get template proposals (if asked for)
if (request.showTemplates && (activationToken == null || activationToken.trim().length() == 0)) {
List<ICompletionProposal> templateProposals = getTemplateProposals(viewer, documentOffset,
activationToken, qualifier);
pythonAndTemplateProposals.addAll(templateProposals);
}
//to show the valid ones, we'll get the qualifier from the initial request
proposals = PyCodeCompletionUtils.onlyValidSorted(pythonAndTemplateProposals, request.qualifier,
request.isInCalltip);
} finally {
nature.endRequests();
}
} catch (Exception e) {
Log.log(e);
CompletionError completionError = new CompletionError(e);
this.error = completionError.getErrorMessage();
//Make the error visible to the user!
return new ICompletionProposal[] { completionError };
}
doCycle();
// Return the proposals
return proposals;
}
/**
* Returns the python proposals as a list.
* First parameter of tuple is a list and second is a Boolean object indicating whether the templates
* should be also shown or not.
* @param viewer
* @throws CoreException
* @throws BadLocationException
* @throws MisconfigurationException
* @throws IOException
* @throws PythonNatureWithoutProjectException
*/
private List getPythonProposals(ITextViewer viewer, int documentOffset, IDocument doc, CompletionRequest request)
throws CoreException, BadLocationException, IOException, MisconfigurationException,
PythonNatureWithoutProjectException {
//if non empty string, we're in imports section.
String importsTipperStr = request.codeCompletion.getImportsTipperStr(request).importsTipperStr;
if (importsTipperStr.length() != 0 || request.isInCalltip) {
request.showTemplates = false; //don't show templates if we are in the imports section or inside a calltip.
}
List allProposals = request.codeCompletion.getCodeCompletionProposals(viewer, request);
return allProposals;
}
/**
* Returns the template proposals as a list.
*/
private List<ICompletionProposal> getTemplateProposals(ITextViewer viewer, int documentOffset,
String activationToken,
java.lang.String qualifier) {
List<ICompletionProposal> propList = new ArrayList<ICompletionProposal>();
this.templatesCompletion.addTemplateProposals(viewer, documentOffset, propList);
return propList;
}
/**
* Ok, if we have
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#computeContextInformation(org.eclipse.jface.text.ITextViewer, int)
*/
public IContextInformation[] computeContextInformation(ITextViewer viewer, int documentOffset) {
//System.out.println("computeContextInformation");
if (viewer.getDocument() != this.contextInformationValidator.doc) {
return null;
}
//System.out.println("this.contextInformationValidator.returnedFalseOnce:"+this.contextInformationValidator.returnedFalseOnce);
//if we didn't return false at least once, it is already installed.
if (this.contextInformationValidator.returnedFalseOnce
&& this.contextInformationValidator.isContextInformationValid(documentOffset)) {
return new IContextInformation[] { this.contextInformationValidator.fInformation };
}
return null;
}
/**
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getCompletionProposalAutoActivationCharacters()
*/
public char[] getCompletionProposalAutoActivationCharacters() {
return getStaticCompletionProposalAutoActivationCharacters();
}
/**
* Attribute that determines if the listener that'll clear the auto activation chars is already in place.
*/
private volatile static boolean listenerToClearAutoActivationAlreadySetup = false;
/**
* @return the auto-activation chars that should be used.
*/
public static char[] getStaticCompletionProposalAutoActivationCharacters() {
if (!listenerToClearAutoActivationAlreadySetup) {
//clears the cache when the preferences are changed.
IPreferenceStore preferenceStore = PydevPlugin.getDefault().getPreferenceStore();
preferenceStore.addPropertyChangeListener(new IPropertyChangeListener() {
public void propertyChange(PropertyChangeEvent event) {
activationChars = null; //clear the cache when it changes
}
});
listenerToClearAutoActivationAlreadySetup = true;
}
if (activationChars == null) { //let's cache this
if (!PyCodeCompletionPreferencesPage.useAutocomplete()) {
activationChars = new char[0];
} else {
char[] c = new char[0];
if (PyCodeCompletionPreferencesPage.isToAutocompleteOnDot()) {
c = StringUtils.addChar(c, '.');
}
if (PyCodeCompletionPreferencesPage.isToAutocompleteOnPar()) {
c = StringUtils.addChar(c, '(');
}
activationChars = c;
}
}
return activationChars;
}
/**
*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationAutoActivationCharacters()
*/
public char[] getContextInformationAutoActivationCharacters() {
return null;
}
/**
* If completion fails for some reason, we could give it here...
*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getErrorMessage()
*/
public java.lang.String getErrorMessage() {
String ret = this.error;
this.error = null;
return ret;
}
/**
*
* @see org.eclipse.jface.text.contentassist.IContentAssistProcessor#getContextInformationValidator()
*/
public IContextInformationValidator getContextInformationValidator() {
return this.contextInformationValidator;
}
}
|
rgom/Pydev
|
plugins/org.python.pydev/src_completions/org/python/pydev/editor/codecompletion/PythonCompletionProcessor.java
|
Java
|
epl-1.0
| 13,137 |
/**
*/
package de.cooperateproject.modeling.textual.component.component;
import de.cooperateproject.modeling.textual.common.metamodel.textualCommons.UMLReferencingElement;
/**
* <!-- begin-user-doc -->
* A representation of the model object '<em><b>Connector End</b></em>'.
* <!-- end-user-doc -->
*
* <p>
* The following features are supported:
* </p>
* <ul>
* <li>{@link de.cooperateproject.modeling.textual.component.component.ConnectorEnd#getPart <em>Part</em>}</li>
* <li>{@link de.cooperateproject.modeling.textual.component.component.ConnectorEnd#getRole <em>Role</em>}</li>
* </ul>
*
* @see de.cooperateproject.modeling.textual.component.component.ComponentPackage#getConnectorEnd()
* @model
* @generated
*/
public interface ConnectorEnd extends UMLReferencingElement<org.eclipse.uml2.uml.ConnectorEnd> {
/**
* Returns the value of the '<em><b>Part</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Part</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Part</em>' reference.
* @see #setPart(Attribute)
* @see de.cooperateproject.modeling.textual.component.component.ComponentPackage#getConnectorEnd_Part()
* @model transient="true"
* @generated
*/
Attribute getPart();
/**
* Sets the value of the '{@link de.cooperateproject.modeling.textual.component.component.ConnectorEnd#getPart <em>Part</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Part</em>' reference.
* @see #getPart()
* @generated
*/
void setPart(Attribute value);
/**
* Returns the value of the '<em><b>Role</b></em>' reference.
* <!-- begin-user-doc -->
* <p>
* If the meaning of the '<em>Role</em>' reference isn't clear,
* there really should be more of a description here...
* </p>
* <!-- end-user-doc -->
* @return the value of the '<em>Role</em>' reference.
* @see #setRole(Port)
* @see de.cooperateproject.modeling.textual.component.component.ComponentPackage#getConnectorEnd_Role()
* @model transient="true"
* @generated
*/
Port getRole();
/**
* Sets the value of the '{@link de.cooperateproject.modeling.textual.component.component.ConnectorEnd#getRole <em>Role</em>}' reference.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @param value the new value of the '<em>Role</em>' reference.
* @see #getRole()
* @generated
*/
void setRole(Port value);
} // ConnectorEnd
|
Cooperate-Project/Cooperate
|
bundles/de.cooperateproject.modeling.textual.component.metamodel/src-gen/de/cooperateproject/modeling/textual/component/component/ConnectorEnd.java
|
Java
|
epl-1.0
| 2,701 |
/*******************************************************************************
* Copyright (c) 2015 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package com.ibm.ws.jdbc.management.j2ee.internal;
import java.util.Hashtable;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.StandardMBean;
import org.osgi.framework.BundleContext;
import org.osgi.framework.ServiceRegistration;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.management.j2ee.JDBCDriverMBean;
import com.ibm.ws.ffdc.FFDCFilter;
//TWAS Source: /SERV1/ws/code/j2c.impl/src/com/ibm/ejs/j2c/mbeans/JDBCDriverMbeanImpl.java
/**
* JDBCDriverMBeanImpl is an MBean for a JDBCDriver. It implements the JDBCDriverMBean interface.
* This Mbean provide getters of information only. No information setter is provided.
*/
public class JDBCDriverMBeanImpl extends StandardMBean implements JDBCDriverMBean {
/////////////////////////////////// Variables used in tracing ///////////////////////////////////
private static final TraceComponent tc = Tr.register(JDBCDriverMBeanImpl.class, "RRA");
private static final boolean IS_DEBUGGING = false; //Change to true if testing needed only.
private static final String className = "JDBCResourceMBeanImpl";
///////////////////////////////// Variables used by the getters /////////////////////////////////
private String name;
///////////////////////// Variables used in the registration of the MBean /////////////////////////
private ServiceRegistration<?> reg = null;
private ObjectName obn = null;
private StringBuilder objectName = null;
//////////////////////////////////////The constructor method //////////////////////////////////////
/**
* JDBCDriverMbeanImpl is the construct responsible for populating the variables used by the getters
* with information from the JDBCDriver which is given by {@code JDBCDriverService}.
*
* @param id String representing the value of the id of the DataSource assigned by the user.
* @param name String representing the value of the XPath which as the same as config.displayId.
* @param J2EEServer String representing the parent MBean J2EEServer's value of its "name" key.
*/
protected JDBCDriverMBeanImpl(String id, String name, String J2EEServer) {
super(JDBCDriverMBean.class, false);
final String methodName = "JDBCDriverMBeanImpl()";
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(tc, methodName, this);
if (trace && tc.isDebugEnabled())
Tr.debug(tc, "\n *** Values provided to " + className + ": " + methodName + " ***"
+ "\n String id: " + id
+ "\n String name: " + name
+ "\n String J2EEServer: " + J2EEServer);
//Start building String which will be used in the {@code ObjectName}.
objectName = new StringBuilder("WebSphere:type=JDBCDriverMBean,j2eeType=JDBCDriver");
if (id != null && !id.isEmpty()) {
objectName.append(",id=" + MBeanHelper.toObnString(id));
}
if (name != null && !name.isEmpty()) {
objectName.append(",name=" + MBeanHelper.toObnString(name));
this.name = name;
}
if (J2EEServer != null && !J2EEServer.isEmpty()) {
objectName.append(",J2EEServer=" + MBeanHelper.toObnString(J2EEServer));
}
//Example output of this ObjectName:
//WebSphere:type=JDBCDriverMBean,j2eeType=JDBCDriver,
// id=xxx,
// name=XPath,
// J2EEServer=xxx
//Building {@code ObjectName} with the String we concatenated.
try {
if (trace && tc.isDebugEnabled())
Tr.debug(tc, objectName.toString(), this);
obn = new ObjectName(objectName.toString());
} catch (MalformedObjectNameException e) {
FFDCFilter.processException(e, getClass().getName(), "[Exp: 4567]", this);
if (trace && tc.isDebugEnabled())
Tr.debug(tc, "Unable to create ObjectName with the string: " + objectName.toString(), e);
} catch (NullPointerException e) {
FFDCFilter.processException(e, getClass().getName(), "[Exp: 4568]", this);
if (trace && tc.isDebugEnabled())
Tr.debug(tc, "Unable to create ObjectName with a null string: " + objectName.toString(), e);
}
if (trace && tc.isEntryEnabled())
Tr.exit(tc, methodName, this);
}
/////////////////////////////////// Registration Methods ///////////////////////////////////
public void register(BundleContext bndCtx) {
final String methodName = "register()";
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(tc, methodName, this);
Hashtable<String, String> props = new Hashtable<String, String>();
props.put("jmx.objectname", this.obn.toString());
if (IS_DEBUGGING)
// Extra Check: Does this MBean exist already?
MBeanHelper.isMbeanExist(objectName.toString() + "*", className, methodName);
// Register the MBean
if (trace && tc.isDebugEnabled())
Tr.debug(tc, "activateMBean started for " + this.obn.toString());
this.reg = bndCtx.registerService(JDBCDriverMBean.class.getName(), this, props);
if (trace && tc.isEntryEnabled())
Tr.exit(tc, methodName, this);
}
public void unregister() {
final String methodName = "unregister()";
final boolean trace = TraceComponent.isAnyTracingEnabled();
if (trace && tc.isEntryEnabled())
Tr.entry(tc, methodName, this);
if (reg != null)
reg.unregister();
reg = null;
if (trace && tc.isEntryEnabled())
Tr.exit(tc, methodName, this);
}
/////////////////////////////////// Getters Methods ///////////////////////////////////
/*
* (non-Javadoc)
*
* @see com.ibm.websphere.management.j2ee.J2EEManagedObjectMBean#getobjectName()
*/
@Override
public String getobjectName() {
return this.objectName.toString();
}
/*
* (non-Javadoc)
*
* @see com.ibm.websphere.management.j2ee.J2EEManagedObjectMBean#isstateManageable()
*/
@Override
public boolean isstateManageable() {
return false;
}
/*
* (non-Javadoc)
*
* @see com.ibm.websphere.management.j2ee.J2EEManagedObjectMBean#isstatisticsProvider()
*/
@Override
public boolean isstatisticsProvider() {
return false;
}
/*
* (non-Javadoc)
*
* @see com.ibm.websphere.management.j2ee.J2EEManagedObjectMBean#iseventProvider()
*/
@Override
public boolean iseventProvider() {
return false;
}
/**
* getName() obtain the value of the name key in the {@code ObjectName}
*/
protected String getName() {
return this.name;
}
}
|
OpenLiberty/open-liberty
|
dev/com.ibm.ws.jdbc.management.j2ee/src/com/ibm/ws/jdbc/management/j2ee/internal/JDBCDriverMBeanImpl.java
|
Java
|
epl-1.0
| 7,629 |
/**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.millheat.internal.config;
/**
* The {@link MillheatAccountConfiguration} class contains account thing configuration parameters.
*
* @author Arne Seime - Initial contribution
*/
public class MillheatAccountConfiguration {
/**
* Username/email address used in app
*/
public String username;
public String password;
public int refreshInterval = 120;
}
|
MikeJMajor/openhab2-addons-dlinksmarthome
|
bundles/org.openhab.binding.millheat/src/main/java/org/openhab/binding/millheat/internal/config/MillheatAccountConfiguration.java
|
Java
|
epl-1.0
| 789 |
/**
* Copyright (c) 2005-2012 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.debug.ui.launching;
import org.eclipse.core.resources.IProject;
import org.python.pydev.ast.interpreter_managers.InterpreterManagersAPI;
import org.python.pydev.core.IInterpreterManager;
import org.python.pydev.debug.core.Constants;
public class IronpythonUnitTestLaunchShortcut extends AbstractLaunchShortcut {
@Override
protected String getLaunchConfigurationType() {
return Constants.ID_IRONPYTHON_UNITTEST_LAUNCH_CONFIGURATION_TYPE;
}
@Override
protected IInterpreterManager getInterpreterManager(IProject project) {
return InterpreterManagersAPI.getIronpythonInterpreterManager();
}
}
|
akurtakov/Pydev
|
plugins/org.python.pydev.debug/src/org/python/pydev/debug/ui/launching/IronpythonUnitTestLaunchShortcut.java
|
Java
|
epl-1.0
| 949 |
/**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.sonyprojector.internal.communication;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import org.eclipse.jdt.annotation.NonNullByDefault;
import org.openhab.binding.sonyprojector.internal.SonyProjectorException;
import org.openhab.core.types.StateOption;
import org.openhab.core.util.HexUtils;
/**
* Represents the different block noise reduction modes available for the projector
*
* @author Laurent Garnier - Initial contribution
*/
@NonNullByDefault
public enum SonyProjectorBlockNr {
HIGH("High", new byte[] { 0x00, 0x03 }),
MIDDLE("Middle", new byte[] { 0x00, 0x02 }),
LOW("Low", new byte[] { 0x00, 0x01 }),
OFF("Off", new byte[] { 0x00, 0x00 });
private String name;
private byte[] dataCode;
/**
* Constructor
*
* @param name the name of the block noise reduction mode
* @param dataCode the data code identifying the block noise reduction mode
*/
private SonyProjectorBlockNr(String name, byte[] dataCode) {
this.name = name;
this.dataCode = dataCode;
}
/**
* Get the data code identifying the current block noise reduction mode
*
* @return the data code
*/
public byte[] getDataCode() {
return dataCode;
}
/**
* Get the name of the current block noise reduction mode
*
* @return the name
*/
public String getName() {
return name;
}
/**
* Get the list of {@link StateOption} associated to the available block noise reduction modes
*
* @return the list of {@link StateOption} associated to the available block noise reduction modes
*/
public static List<StateOption> getStateOptions() {
List<StateOption> options = new ArrayList<>();
for (SonyProjectorBlockNr value : SonyProjectorBlockNr.values()) {
options.add(new StateOption(value.getName(), value.getName()));
}
return options;
}
/**
* Get the block noise reduction mode associated to a name
*
* @param name the name used to identify the block noise reduction mode
*
* @return the block noise reduction mode associated to the searched name
*
* @throws SonyProjectorException - If no block noise reduction mode is associated to the searched name
*/
public static SonyProjectorBlockNr getFromName(String name) throws SonyProjectorException {
for (SonyProjectorBlockNr value : SonyProjectorBlockNr.values()) {
if (value.getName().equals(name)) {
return value;
}
}
throw new SonyProjectorException("Invalid name for a block noise reduction mode: " + name);
}
/**
* Get the block noise reduction mode associated to a data code
*
* @param dataCode the data code used to identify the block noise reduction mode
*
* @return the block noise reduction mode associated to the searched data code
*
* @throws SonyProjectorException - If no block noise reduction mode is associated to the searched data code
*/
public static SonyProjectorBlockNr getFromDataCode(byte[] dataCode) throws SonyProjectorException {
for (SonyProjectorBlockNr value : SonyProjectorBlockNr.values()) {
if (Arrays.equals(dataCode, value.getDataCode())) {
return value;
}
}
throw new SonyProjectorException(
"Invalid data code for a block noise reduction mode: " + HexUtils.bytesToHex(dataCode));
}
}
|
paulianttila/openhab2
|
bundles/org.openhab.binding.sonyprojector/src/main/java/org/openhab/binding/sonyprojector/internal/communication/SonyProjectorBlockNr.java
|
Java
|
epl-1.0
| 3,954 |
/*******************************************************************************
* Copyright (c) 2004-2010 Sunil Kamath (IcemanK). All rights reserved. This
* program is made available under the terms of the Common Public License v1.0
* which is available at http://www.eclipse.org/legal/cpl-v10.html
*
* Contributors: Sunil Kamath (IcemanK) - initial API and implementation
*******************************************************************************/
package net.sf.eclipsensis.util.winapi.x86;
import net.sf.eclipsensis.util.winapi.IHandle;
public class Handle32 implements IHandle
{
int value;
public Handle32(int value)
{
this.value = value;
}
public Number getValue()
{
return value;
}
public String toHexString()
{
return Integer.toHexString(value);
}
@Override
public String toString()
{
return Integer.toString(value);
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + value;
return result;
}
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
Handle32 other = (Handle32) obj;
if (value != other.value)
{
return false;
}
return true;
}
}
|
chrismathis/eclipsensis
|
plugins/net.sf.eclipsensis/src/net/sf/eclipsensis/util/winapi/x86/Handle32.java
|
Java
|
epl-1.0
| 1,616 |
/*
* Copyright (c) 2012-2017 Red Hat, Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*/
package org.eclipse.che.multiuser.organization.api;
import static org.mockito.Mockito.when;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotNull;
import javax.ws.rs.core.UriBuilder;
import org.eclipse.che.api.core.rest.ServiceContext;
import org.eclipse.che.dto.server.DtoFactory;
import org.eclipse.che.multiuser.organization.shared.Constants;
import org.eclipse.che.multiuser.organization.shared.dto.OrganizationDto;
import org.everrest.core.impl.uri.UriBuilderImpl;
import org.mockito.Mock;
import org.mockito.testng.MockitoTestNGListener;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Listeners;
import org.testng.annotations.Test;
/**
* Tests for {@link org.eclipse.che.multiuser.organization.api.OrganizationLinksInjector}
*
* @author Sergii Leschenko
*/
@Listeners(MockitoTestNGListener.class)
public class OrganizationLinksInjectorTest {
private static final String URI_BASE = "http://localhost:8080";
@Mock ServiceContext context;
OrganizationLinksInjector organizationLinksInjector = new OrganizationLinksInjector();
@BeforeMethod
public void setUp() {
final UriBuilder uriBuilder = new UriBuilderImpl();
uriBuilder.uri(URI_BASE);
when(context.getBaseUriBuilder()).thenReturn(uriBuilder);
}
@Test
public void shouldInjectLinks() {
final OrganizationDto organization = DtoFactory.newDto(OrganizationDto.class).withId("org123");
final OrganizationDto withLinks = organizationLinksInjector.injectLinks(organization, context);
assertEquals(withLinks.getLinks().size(), 2);
assertNotNull(withLinks.getLink(Constants.LINK_REL_SELF));
assertNotNull(withLinks.getLink(Constants.LINK_REL_SUBORGANIZATIONS));
}
}
|
TypeFox/che
|
multiuser/api/che-multiuser-api-organization/src/test/java/org/eclipse/che/multiuser/organization/api/OrganizationLinksInjectorTest.java
|
Java
|
epl-1.0
| 2,110 |
// Compiled by ClojureScript 1.10.238 {}
goog.provide('clojure.browser.event');
goog.require('cljs.core');
goog.require('goog.events');
goog.require('goog.events.EventTarget');
goog.require('goog.events.EventType');
/**
* @interface
*/
clojure.browser.event.IEventType = function(){};
clojure.browser.event.event_types = (function clojure$browser$event$event_types(this$){
if(((!((this$ == null))) && (!((this$.clojure$browser$event$IEventType$event_types$arity$1 == null))))){
return this$.clojure$browser$event$IEventType$event_types$arity$1(this$);
} else {
var x__4211__auto__ = (((this$ == null))?null:this$);
var m__4212__auto__ = (clojure.browser.event.event_types[goog.typeOf(x__4211__auto__)]);
if(!((m__4212__auto__ == null))){
return m__4212__auto__.call(null,this$);
} else {
var m__4212__auto____$1 = (clojure.browser.event.event_types["_"]);
if(!((m__4212__auto____$1 == null))){
return m__4212__auto____$1.call(null,this$);
} else {
throw cljs.core.missing_protocol.call(null,"IEventType.event-types",this$);
}
}
}
});
goog.events.EventTarget.prototype.clojure$browser$event$IEventType$ = cljs.core.PROTOCOL_SENTINEL;
goog.events.EventTarget.prototype.clojure$browser$event$IEventType$event_types$arity$1 = (function (this$){
var this$__$1 = this;
return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,((function (this$__$1){
return (function (p__9160){
var vec__9161 = p__9160;
var k = cljs.core.nth.call(null,vec__9161,(0),null);
var v = cljs.core.nth.call(null,vec__9161,(1),null);
return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
});})(this$__$1))
,cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.events.EventType))));
});
if(typeof Element !== 'undefined'){
Element.prototype.clojure$browser$event$IEventType$ = cljs.core.PROTOCOL_SENTINEL;
Element.prototype.clojure$browser$event$IEventType$event_types$arity$1 = (function (this$){
var this$__$1 = this;
return cljs.core.into.call(null,cljs.core.PersistentArrayMap.EMPTY,cljs.core.map.call(null,((function (this$__$1){
return (function (p__9164){
var vec__9165 = p__9164;
var k = cljs.core.nth.call(null,vec__9165,(0),null);
var v = cljs.core.nth.call(null,vec__9165,(1),null);
return new cljs.core.PersistentVector(null, 2, 5, cljs.core.PersistentVector.EMPTY_NODE, [cljs.core.keyword.call(null,k.toLowerCase()),v], null);
});})(this$__$1))
,cljs.core.merge.call(null,cljs.core.js__GT_clj.call(null,goog.events.EventType))));
});
} else {
}
clojure.browser.event.listen = (function clojure$browser$event$listen(var_args){
var G__9169 = arguments.length;
switch (G__9169) {
case 3:
return clojure.browser.event.listen.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)]));
break;
case 4:
return clojure.browser.event.listen.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]));
break;
default:
throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join('')));
}
});
clojure.browser.event.listen.cljs$core$IFn$_invoke$arity$3 = (function (src,type,fn){
return clojure.browser.event.listen.call(null,src,type,fn,false);
});
clojure.browser.event.listen.cljs$core$IFn$_invoke$arity$4 = (function (src,type,fn,capture_QMARK_){
return goog.events.listen(src,cljs.core.get.call(null,clojure.browser.event.event_types.call(null,src),type,type),fn,capture_QMARK_);
});
clojure.browser.event.listen.cljs$lang$maxFixedArity = 4;
clojure.browser.event.listen_once = (function clojure$browser$event$listen_once(var_args){
var G__9172 = arguments.length;
switch (G__9172) {
case 3:
return clojure.browser.event.listen_once.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)]));
break;
case 4:
return clojure.browser.event.listen_once.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]));
break;
default:
throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join('')));
}
});
clojure.browser.event.listen_once.cljs$core$IFn$_invoke$arity$3 = (function (src,type,fn){
return clojure.browser.event.listen_once.call(null,src,type,fn,false);
});
clojure.browser.event.listen_once.cljs$core$IFn$_invoke$arity$4 = (function (src,type,fn,capture_QMARK_){
return goog.events.listenOnce(src,cljs.core.get.call(null,clojure.browser.event.event_types.call(null,src),type,type),fn,capture_QMARK_);
});
clojure.browser.event.listen_once.cljs$lang$maxFixedArity = 4;
clojure.browser.event.unlisten = (function clojure$browser$event$unlisten(var_args){
var G__9175 = arguments.length;
switch (G__9175) {
case 3:
return clojure.browser.event.unlisten.cljs$core$IFn$_invoke$arity$3((arguments[(0)]),(arguments[(1)]),(arguments[(2)]));
break;
case 4:
return clojure.browser.event.unlisten.cljs$core$IFn$_invoke$arity$4((arguments[(0)]),(arguments[(1)]),(arguments[(2)]),(arguments[(3)]));
break;
default:
throw (new Error(["Invalid arity: ",cljs.core.str.cljs$core$IFn$_invoke$arity$1(arguments.length)].join('')));
}
});
clojure.browser.event.unlisten.cljs$core$IFn$_invoke$arity$3 = (function (src,type,fn){
return clojure.browser.event.unlisten.call(null,src,type,fn,false);
});
clojure.browser.event.unlisten.cljs$core$IFn$_invoke$arity$4 = (function (src,type,fn,capture_QMARK_){
return goog.events.unlisten(src,cljs.core.get.call(null,clojure.browser.event.event_types.call(null,src),type,type),fn,capture_QMARK_);
});
clojure.browser.event.unlisten.cljs$lang$maxFixedArity = 4;
clojure.browser.event.unlisten_by_key = (function clojure$browser$event$unlisten_by_key(key){
return goog.events.unlistenByKey(key);
});
clojure.browser.event.dispatch_event = (function clojure$browser$event$dispatch_event(src,event){
return goog.events.dispatchEvent(src,event);
});
clojure.browser.event.expose = (function clojure$browser$event$expose(e){
return goog.events.expose(e);
});
clojure.browser.event.fire_listeners = (function clojure$browser$event$fire_listeners(obj,type,capture,event){
return null;
});
clojure.browser.event.total_listener_count = (function clojure$browser$event$total_listener_count(){
return goog.events.getTotalListenerCount();
});
clojure.browser.event.get_listener = (function clojure$browser$event$get_listener(src,type,listener,opt_capt,opt_handler){
return null;
});
clojure.browser.event.all_listeners = (function clojure$browser$event$all_listeners(obj,type,capture){
return null;
});
clojure.browser.event.unique_event_id = (function clojure$browser$event$unique_event_id(event_type){
return null;
});
clojure.browser.event.has_listener = (function clojure$browser$event$has_listener(obj,opt_type,opt_capture){
return null;
});
clojure.browser.event.remove_all = (function clojure$browser$event$remove_all(opt_obj,opt_type,opt_capt){
return null;
});
//# sourceMappingURL=event.js.map
|
markbastian/clojure-club
|
src/main/cljs/spiral_challenge/jolley_spiral/.out/clojure/browser/event.js
|
JavaScript
|
epl-1.0
| 6,970 |
package es.optsicom.lib.web.dto;
import java.util.ArrayList;
import java.util.List;
public class ReportTableResponseDTO {
private String title;
private List<List<ReportCellResponseDTO>> cellValues;
private List<ReportTitleResponseDTO> rowTitles;
private List<ReportTitleResponseDTO> columnTitles;
public ReportTableResponseDTO() {
this.title = "";
this.cellValues = new ArrayList<>();
this.rowTitles = new ArrayList<>();
this.columnTitles = new ArrayList<>();
}
public ReportTableResponseDTO(String title, List<List<ReportCellResponseDTO>> cellValues, List<ReportTitleResponseDTO> rowTitles,
List<ReportTitleResponseDTO> columnTitles) {
super();
this.title = title;
this.cellValues = cellValues;
this.rowTitles = rowTitles;
this.columnTitles = columnTitles;
}
public String getTitle() {
return title;
}
public List<List<ReportCellResponseDTO>> getCellValues() {
return cellValues;
}
public List<ReportTitleResponseDTO> getRowTitles() {
return rowTitles;
}
public List<ReportTitleResponseDTO> getColumnTitles() {
return columnTitles;
}
}
|
codeurjc/optsicom-framework
|
es.optsicom.lib.web/src/main/java/es/optsicom/lib/web/dto/ReportTableResponseDTO.java
|
Java
|
epl-1.0
| 1,092 |
/*
Common Public License Version 0.5
THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF
THIS COMMON PUBLIC LICENSE ("AGREEMENT"). ANY USE,
REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES
RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT.
1. DEFINITIONS
"Contribution" means:
a) in the case of the initial Contributor, the
initial code and documentation distributed under
this Agreement, and
b) in the case of each subsequent Contributor:
i) changes to the Program, and
ii) additions to the Program;
where such changes and/or additions to the Program
originate from and are distributed by that
particular Contributor. A Contribution 'originates'
from a Contributor if it was added to the Program
by such Contributor itself or anyone acting on such
Contributor's behalf. Contributions do not include
additions to the Program which: (i) are separate
modules of software distributed in conjunction with
the Program under their own license agreement, and
(ii) are not derivative works of the Program.
"Contributor" means any person or entity that distributes
the Program.
"Licensed Patents " mean patent claims licensable by a
Contributor which are necessarily infringed by the use or
sale of its Contribution alone or when combined with the
Program.
"Program" means the Contributions distributed in
accordance with this Agreement.
"Recipient" means anyone who receives the Program under
this Agreement, including all Contributors.
2. GRANT OF RIGHTS
a) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a
non-exclusive, worldwide, royalty-free copyright
license to reproduce, prepare derivative works of,
publicly display, publicly perform, distribute and
sublicense the Contribution of such Contributor, if
any, and such derivative works, in source code and
object code form.
b) Subject to the terms of this Agreement, each
Contributor hereby grants Recipient a
non-exclusive, worldwide, royalty-free patent
license under Licensed Patents to make, use, sell,
offer to sell, import and otherwise transfer the
Contribution of such Contributor, if any, in source
code and object code form. This patent license
shall apply to the combination of the Contribution
and the Program if, at the time the Contribution is
added by the Contributor, such addition of the
Contribution causes such combination to be covered
by the Licensed Patents. The patent license shall
not apply to any other combinations which include
the Contribution. No hardware per se is licensed
hereunder.
c) Recipient understands that although each
Contributor grants the licenses to its
Contributions set forth herein, no assurances are
provided by any Contributor that the Program does
not infringe the patent or other intellectual
property rights of any other entity. Each
Contributor disclaims any liability to Recipient
for claims brought by any other entity based on
infringement of intellectual property rights or
otherwise. As a condition to exercising the rights
and licenses granted hereunder, each Recipient
hereby assumes sole responsibility to secure any
other intellectual property rights needed, if any.
For example, if a third party patent license is
required to allow Recipient to distribute the
Program, it is Recipient's responsibility to
acquire that license before distributing the
Program.
d) Each Contributor represents that to its
knowledge it has sufficient copyright rights in its
Contribution, if any, to grant the copyright
license set forth in this Agreement.
3. REQUIREMENTS
A Contributor may choose to distribute the Program in
object code form under its own license agreement, provided
that:
a) it complies with the terms and conditions of
this Agreement; and
b) its license agreement:
i) effectively disclaims on behalf of all
Contributors all warranties and conditions, express
and implied, including warranties or conditions of
title and non-infringement, and implied warranties
or conditions of merchantability and fitness for a
particular purpose;
ii) effectively excludes on behalf of all
Contributors all liability for damages, including
direct, indirect, special, incidental and
consequential damages, such as lost profits;
iii) states that any provisions which differ from
this Agreement are offered by that Contributor
alone and not by any other party; and
iv) states that source code for the Program is
available from such Contributor, and informs
licensees how to obtain it in a reasonable manner
on or through a medium customarily used for
software exchange.
When the Program is made available in source code form:
a) it must be made available under this Agreement;
and
b) a copy of this Agreement must be included with
each copy of the Program.
Contributors may not remove or alter any copyright notices
contained within the Program.
Each Contributor must identify itself as the originator of
its Contribution, if any, in a manner that reasonably
allows subsequent Recipients to identify the originator of
the Contribution.
4. COMMERCIAL DISTRIBUTION
Commercial distributors of software may accept certain
responsibilities with respect to end users, business
partners and the like. While this license is intended to
facilitate the commercial use of the Program, the
Contributor who includes the Program in a commercial
product offering should do so in a manner which does not
create potential liability for other Contributors.
Therefore, if a Contributor includes the Program in a
commercial product offering, such Contributor ("Commercial
Contributor") hereby agrees to defend and indemnify every
other Contributor ("Indemnified Contributor") against any
losses, damages and costs (collectively "Losses") arising
from claims, lawsuits and other legal actions brought by a
third party against the Indemnified Contributor to the
extent caused by the acts or omissions of such Commercial
Contributor in connection with its distribution of the
Program in a commercial product offering. The obligations
in this section do not apply to any claims or Losses
relating to any actual or alleged intellectual property
infringement. In order to qualify, an Indemnified
Contributor must: a) promptly notify the Commercial
Contributor in writing of such claim, and b) allow the
Commercial Contributor to control, and cooperate with the
Commercial Contributor in, the defense and any related
settlement negotiations. The Indemnified Contributor may
participate in any such claim at its own expense.
For example, a Contributor might include the Program in a
commercial product offering, Product X. That Contributor
is then a Commercial Contributor. If that Commercial
Contributor then makes performance claims, or offers
warranties related to Product X, those performance claims
and warranties are such Commercial Contributor's
responsibility alone. Under this section, the Commercial
Contributor would have to defend claims against the other
Contributors related to those performance claims and
warranties, and if a court requires any other Contributor
to pay any damages as a result, the Commercial Contributor
must pay those damages.
5. NO WARRANTY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE
PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT
WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR
IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR
CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR
FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely
responsible for determining the appropriateness of using
and distributing the Program and assumes all risks
associated with its exercise of rights under this
Agreement, including but not limited to the risks and
costs of program errors, compliance with applicable laws,
damage to or loss of data, programs or equipment, and
unavailability or interruption of operations.
6. DISCLAIMER OF LIABILITY
EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER
RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION
LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE
OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
7. GENERAL
If any provision of this Agreement is invalid or
unenforceable under applicable law, it shall not affect
the validity or enforceability of the remainder of the
terms of this Agreement, and without further action by the
parties hereto, such provision shall be reformed to the
minimum extent necessary to make such provision valid and
enforceable.
If Recipient institutes patent litigation against a
Contributor with respect to a patent applicable to
software (including a cross-claim or counterclaim in a
lawsuit), then any patent licenses granted by that
Contributor to such Recipient under this Agreement shall
terminate as of the date such litigation is filed. In
addition, If Recipient institutes patent litigation
against any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that the Program
itself (excluding combinations of the Program with other
software or hardware) infringes such Recipient's
patent(s), then such Recipient's rights granted under
Section 2(b) shall terminate as of the date such
litigation is filed.
All Recipient's rights under this Agreement shall
terminate if it fails to comply with any of the material
terms or conditions of this Agreement and does not cure
such failure in a reasonable period of time after becoming
aware of such noncompliance. If all Recipient's rights
under this Agreement terminate, Recipient agrees to cease
use and distribution of the Program as soon as reasonably
practicable. However, Recipient's obligations under this
Agreement and any licenses granted by Recipient relating
to the Program shall continue and survive.
Everyone is permitted to copy and distribute copies of
this Agreement, but in order to avoid inconsistency the
Agreement is copyrighted and may only be modified in the
following manner. The Agreement Steward reserves the right
to publish new versions (including revisions) of this
Agreement from time to time. No one other than the
Agreement Steward has the right to modify this Agreement.
IBM is the initial Agreement Steward. IBM may assign the
responsibility to serve as the Agreement Steward to a
suitable separate entity. Each new version of the
Agreement will be given a distinguishing version number.
The Program (including Contributions) may always be
distributed subject to the version of the Agreement under
which it was received. In addition, after a new version of
the Agreement is published, Contributor may elect to
distribute the Program (including its Contributions) under
the new version. Except as expressly stated in Sections
2(a) and 2(b) above, Recipient receives no rights or
licenses to the intellectual property of any Contributor
under this Agreement, whether expressly, by implication,
estoppel or otherwise. All rights in the Program not
expressly granted under this Agreement are reserved.
This Agreement is governed by the laws of the State of New
York and the intellectual property laws of the United
States of America. No party to this Agreement will bring a
legal action under this Agreement more than one year after
the cause of action arose. Each party waives its rights to
a jury trial in any resulting litigation.
*/
/* (C) COPYRIGHT Corrent Corp. 2002, 2003 */
/***************************************************************************
Change Log
==========
5/19/03 Kapil Sood ([email protected])
Added support for CKA_VALUE_BITS for DH
4/25/03 Kapil Sood ([email protected])
Added DH key pair generation and DH shared key derivation
functions.
8/27/02 Kapil Sood ([email protected])
Added token interface for the Corrent S2000/S2010/S3500
PCI-X based crypto accelerator cards.
****************************************************************************/
#include <pthread.h>
#include <string.h> // for memcmp() et al
#include <stdlib.h>
#include "pkcs11types.h"
#include "defs.h"
#include "host_defs.h"
#include "h_extern.h"
#include "args.h"
#include "errno.h"
#include "tok_specific.h"
#include <openssl/des.h>
#include <openssl/rand.h>
#include <openssl/rsa.h>
#include <openssl/aes.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include "typhoon.h"
#include "tok_struct.h"
typedef unsigned int uint32_t;
int crfd ;
pthread_mutex_t rngmtx = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t nextmutex = PTHREAD_MUTEX_INITIALIZER;
unsigned int rnginitialized=0;
int CR_MAX_MODULUS_SIZE_BITS = 2048 ;
int CR_MAX_MODULUS_SIZE_BYTES = 256 ;
CK_CHAR manuf[] = "Corrent Corp.";
CK_CHAR model[] = "S3500/S2000" ;
CK_CHAR descr[] = "PKCS#11 Corrent token";
CK_CHAR label[] = "Linux PKCS#11 ";
CK_RV
token_specific_session(CK_SLOT_ID slotid)
{
return CKR_OK;
}
CK_RV
token_rng(CK_BYTE *output, CK_ULONG bytes)
{
token rand_num ;
RC rc ;
rand_num.p_data = (BYTE *) output ;
rand_num.data_size = bytes ;
rc = CR_get_random(&rand_num, (INT32) bytes) ;
if (rc != SUCCESS)
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
#if 0
int ranfd;
int rlen,totallen=0;
ranfd = open("/dev/urandom",O_RDONLY);
if (ranfd >= 0 ){
do {
rlen = read(ranfd,output+totallen,bytes-totallen);
totallen += rlen;
} while( totallen < bytes);
return CKR_OK;
} else {
return CKR_FUNCTION_FAILED;
}
#endif /* if 0 */
}
// convert pkcs slot number to local representation
int
tok_slot2local(CK_SLOT_ID snum)
{
return 1;
}
CK_RV
token_specific_init(char * Correlator,CK_SLOT_ID SlotNumber)
{
crfd = CR_init_lib(NULL, NULL);
return CKR_OK;
}
CK_RV
token_specific_final()
{
CR_close_lib();
return CKR_OK;
}
CK_RV
token_specific_des_key_gen(CK_BYTE *des_key,CK_ULONG len)
{
// Nothing different to do for DES or TDES here as this is just
// random data... Validation handles the rest
rng_generate(des_key,len);
// we really need to validate the key for parity etc...
// we should do that here... The caller validates the single des keys
// against the known and suspected poor keys..
return CKR_OK;
}
// convert from the local PKCS11 template representation to
// the underlying requirement
// returns the pointer to the local key representation
//
void * rsa_convert_public_key( OBJECT *key_obj )
{
CK_BBOOL rc;
CK_ATTRIBUTE *modulus = NULL;
CK_ATTRIBUTE *pub_exp = NULL;
rsa_key *rsa_pub_key;
token *t_modulus, *t_exponent ;
rc = template_attribute_find( key_obj->template, CKA_MODULUS, &modulus );
rc &= template_attribute_find( key_obj->template, CKA_PUBLIC_EXPONENT, &pub_exp );
if (rc == FALSE)
return NULL;
rsa_pub_key = (rsa_key *) create_rsa_key(modulus->ulValueLen, pub_exp->ulValueLen);
if (rsa_pub_key == NULL)
return NULL;
memcpy(rsa_pub_key->modulus->p_data, modulus->pValue, modulus->ulValueLen) ;
memcpy(rsa_pub_key->exponent->p_data, pub_exp->pValue, pub_exp->ulValueLen) ;
rsa_pub_key->modulus->data_size = modulus->ulValueLen;
rsa_pub_key->exponent->data_size = pub_exp->ulValueLen;
return (void *)rsa_pub_key;
}
void * rsa_convert_private_key(OBJECT *key_obj)
{
CK_ATTRIBUTE * modulus = NULL;
CK_ATTRIBUTE * priv_exp = NULL;
CK_ATTRIBUTE * prime1 = NULL;
CK_ATTRIBUTE * prime2 = NULL;
CK_ATTRIBUTE * exp1 = NULL;
CK_ATTRIBUTE * exp2 = NULL;
CK_ATTRIBUTE * coeff = NULL;
CK_BBOOL rc;
rsa_crt_key *privKey;
rsa_key *privKey2 ;
rc = template_attribute_find( key_obj->template, CKA_MODULUS, &modulus );
rc &= template_attribute_find( key_obj->template, CKA_PRIVATE_EXPONENT, &priv_exp );
rc &= template_attribute_find( key_obj->template, CKA_PRIME_1, &prime1 );
rc &= template_attribute_find( key_obj->template, CKA_PRIME_2, &prime2 );
rc &= template_attribute_find( key_obj->template, CKA_EXPONENT_1, &exp1 );
rc &= template_attribute_find( key_obj->template, CKA_EXPONENT_2, &exp2 );
rc &= template_attribute_find( key_obj->template, CKA_COEFFICIENT, &coeff );
if ( rc == FALSE)
return NULL;
/* CRT operations are faster for N>1024 operations. For all other operations,
perform non-CRT operations */
if (modulus->ulValueLen > 1024)
{
privKey = (rsa_crt_key *) create_rsa_crt_key(prime1->ulValueLen, prime2->ulValueLen,
exp1->ulValueLen, exp2->ulValueLen,
coeff->ulValueLen) ;
if (privKey != NULL)
{
memcpy(privKey->prime_p->p_data, prime1->pValue, prime1->ulValueLen) ;
privKey->prime_p->data_size = prime1->ulValueLen;
memcpy(privKey->prime_q->p_data, prime2->pValue, prime2->ulValueLen) ;
privKey->prime_q->data_size = prime2->ulValueLen;
memcpy(privKey->dmp1->p_data, exp1->pValue, exp1->ulValueLen) ;
privKey->dmp1->data_size = exp1->ulValueLen;
memcpy(privKey->dmq1->p_data, exp2->pValue, exp2->ulValueLen) ;
privKey->dmq1->data_size = exp2->ulValueLen;
memcpy(privKey->iqmp->p_data, coeff->pValue, coeff->ulValueLen) ;
privKey->iqmp->data_size = coeff->ulValueLen;
return (void *) privKey ;
}
else
return NULL;
}
else
{
privKey2 = (rsa_key *) create_rsa_key(modulus->ulValueLen, priv_exp->ulValueLen) ;
if (privKey2 != NULL)
{
memcpy(privKey2->modulus->p_data, modulus->pValue, modulus->ulValueLen) ;
privKey2->modulus->data_size = modulus->ulValueLen;
memcpy(privKey2->exponent->p_data, priv_exp->pValue, priv_exp->ulValueLen) ;
privKey2->exponent->data_size = priv_exp->ulValueLen;
return (void *) privKey2 ;
}
else
return NULL ;
}
return NULL;
} /* end rsa_convert_private_key() */
#define RNG_BUF_SIZE 100
// This function is only required if public key cryptography
// has been selected in your variant set up.
// Set a mutex in this function and get a cache;
// using the ICA device to get random numbers a byte at a
// time is VERY slow.. Keygen is gated by this function.
unsigned char nextRandom (void)
{
static unsigned char buffer[RNG_BUF_SIZE];
unsigned char byte;
static int used = (RNG_BUF_SIZE); // protected access by the mutex
pthread_mutex_lock(&nextmutex);
if (used >= RNG_BUF_SIZE)
{
rng_generate(buffer,sizeof(buffer));
used = 0;
}
byte = buffer[used++];
pthread_mutex_unlock(&nextmutex);
return((unsigned char)byte);
}
void swapper(char *s, char *d, int size)
{
int i=0;
int j=size;
for(i=0;i<size;i++)
d[i]=s[--j];
}
CK_RV
os_specific_rsa_keygen(TEMPLATE *publ_tmpl, TEMPLATE *priv_tmpl)
{
CK_ATTRIBUTE *publ_exp = NULL;
CK_ATTRIBUTE *attr = NULL;
CK_ULONG mod_bits;
CK_BBOOL flag;
CK_RV rc;
CK_ULONG BNLength;
RSA *rsa;
BIGNUM *bignum;
CK_BYTE *ssl_ptr;
unsigned long three = 3;
unsigned char *exp_str;
unsigned long exponent;
flag = template_attribute_find( publ_tmpl, CKA_MODULUS_BITS, &attr );
if (!flag){
OCK_LOG_ERR(ERR_TEMPLATE_INCOMPLETE);
return CKR_TEMPLATE_INCOMPLETE; // should never happen
}
mod_bits = *(CK_ULONG *)attr->pValue;
flag = template_attribute_find( publ_tmpl, CKA_PUBLIC_EXPONENT, &publ_exp );
if (!flag){
OCK_LOG_ERR(ERR_TEMPLATE_INCOMPLETE);
return CKR_TEMPLATE_INCOMPLETE;
}
// we don't support less than 1024 bit keys in the sw
if (mod_bits < 512 || mod_bits > 2048) {
OCK_LOG_ERR(ERR_KEY_SIZE_RANGE);
return CKR_KEY_SIZE_RANGE;
}
// Because of a limition of OpenSSL, this token only supports
// 3 as an exponent in RSA key generation
rsa = RSA_new();
if (rsa == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
return CKR_HOST_MEMORY;
}
RSA_blinding_off(rsa);
rsa = RSA_generate_key(mod_bits, three, NULL, NULL);
if (rsa == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
return CKR_HOST_MEMORY;
}
// Now fill in the objects..
//
// modulus: n
//
bignum = rsa->n;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_MODULUS, ssl_ptr, BNLength, &attr ); // in bytes
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( publ_tmpl, attr );
free(ssl_ptr);
// Public Exponent
bignum = rsa->e;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_PUBLIC_EXPONENT, ssl_ptr, BNLength, &attr ); // in bytes
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( publ_tmpl, attr );
free(ssl_ptr);
// local = TRUE
//
flag = TRUE;
rc = build_attribute( CKA_LOCAL, &flag, sizeof(CK_BBOOL), &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( publ_tmpl, attr );
//
// now, do the private key
//
// Cheat here and put the whole original key into the CKA_VALUE... remember
// to force the system to not return this for RSA keys..
// Add the modulus to the private key information
bignum = rsa->n;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_MODULUS, ssl_ptr, BNLength ,&attr ); // in bytes
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
// Private Exponent
bignum = rsa->d;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc( BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_PRIVATE_EXPONENT, ssl_ptr, BNLength, &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
// prime #1: p
//
bignum = rsa->p;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_PRIME_1, ssl_ptr, BNLength, &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
// prime #2: q
//
bignum = rsa->q;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_PRIME_2, ssl_ptr, BNLength, &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
// exponent 1: d mod(p-1)
//
bignum = rsa->dmp1;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_EXPONENT_1, ssl_ptr, BNLength, &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
// exponent 2: d mod(q-1)
//
bignum = rsa->dmq1;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_EXPONENT_2, ssl_ptr, BNLength, &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
// CRT coefficient: q_inverse mod(p)
//
bignum = rsa->iqmp;
BNLength = BN_num_bytes(bignum);
ssl_ptr = malloc(BNLength);
if (ssl_ptr == NULL) {
OCK_LOG_ERR(ERR_HOST_MEMORY);
rc = CKR_HOST_MEMORY;
goto done;
}
BNLength = BN_bn2bin(bignum, ssl_ptr);
rc = build_attribute( CKA_COEFFICIENT, ssl_ptr, BNLength, &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
free(ssl_ptr);
flag = TRUE;
rc = build_attribute( CKA_LOCAL, &flag, sizeof(CK_BBOOL), &attr );
if (rc != CKR_OK){
OCK_LOG_ERR(ERR_BLD_ATTR);
goto done;
}
template_update_attribute( priv_tmpl, attr );
done:
RSA_free(rsa);
return rc;
}
CK_RV
token_specific_rsa_generate_keypair( TEMPLATE * publ_tmpl,
TEMPLATE * priv_tmpl )
{
CK_RV rc;
rc = os_specific_rsa_keygen(publ_tmpl,priv_tmpl);
if (rc != CKR_OK)
OCK_LOG_ERR(ERR_KEYGEN);
return rc;
}
CK_RV token_specific_rsa_encrypt( CK_BYTE *in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
OBJECT *key_obj )
{
RC rc;
CK_RV ret_val ;
rsa_key *mexp;
token ciphertext, plaintext ;
CK_ULONG count ;
mexp = (rsa_key *)rsa_convert_public_key(key_obj);
if (mexp == NULL)
return CKR_FUNCTION_FAILED;
/* Setup the input and output Corrent tokens */
plaintext.p_data = in_data ;
plaintext.data_size = in_data_len ;
ciphertext.p_data = out_data ;
ciphertext.data_size = in_data_len ; /* will be updated by the CR lib */
rc = CR_mod_exp_mont(&ciphertext, &plaintext, mexp->modulus, mexp->exponent) ;
if ( rc == SUCCESS )
ret_val = CKR_OK;
else
ret_val = CKR_FUNCTION_FAILED;
/* Corrent library may return results after triming leading zeros. Insert the leading
zeros back and adjust length below, if necessary */
if (ciphertext.data_size < in_data_len)
{
memmove(&out_data[in_data_len-ciphertext.data_size], &out_data[0], ciphertext.data_size) ;
memset(&out_data[0], 0, in_data_len-ciphertext.data_size) ;
ciphertext.data_size = in_data_len ;
}
/* Free the key storage for CR format */
destroy_rsa_key((rsa_key *) mexp) ;
return ret_val ;
} /* end token_specific_rsa_encrypt() */
CK_RV token_specific_rsa_decrypt( CK_BYTE *in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
OBJECT *key_obj )
{
CK_ATTRIBUTE *modulus ;
RC rc ;
CK_RV ret_val;
rsa_crt_key *privKey = NULL;
rsa_key *privKey2 = NULL;
token ciphertext, plaintext ;
INT32 count ;
rc = template_attribute_find( key_obj->template, CKA_MODULUS, &modulus );
if ( rc == FALSE)
return CKR_FUNCTION_FAILED;
/* CRT operations are faster for N>1024 operations. For all other operations,
perform non-CRT operations */
if (modulus->ulValueLen > 1024)
privKey = (rsa_crt_key *)rsa_convert_private_key(key_obj);
else
privKey2 = (rsa_key *)rsa_convert_private_key(key_obj);
if ((privKey == NULL) && (privKey2 == NULL))
return CKR_FUNCTION_FAILED;
memset(out_data, 0, in_data_len) ;
/* Setup the input and output Corrent tokens */
ciphertext.p_data = in_data ;
ciphertext.data_size = in_data_len ;
plaintext.p_data = out_data ;
plaintext.data_size = in_data_len ; /* will be updated by the CR lib */
/* Based on modulus size, invoke CRT or non-CRT */
if (modulus->ulValueLen > 1024)
rc = CR_mod_exp_crt(&plaintext, &ciphertext, privKey->prime_p, privKey->prime_q,
privKey->dmp1, privKey->dmq1, privKey->iqmp) ;
else
rc = CR_mod_exp_mont(&plaintext, &ciphertext, privKey2->modulus, privKey2->exponent) ;
/* Corrent library returns results after triming leading zeros. Insert the leading
zeros back and adjust length below, if necessary */
if (plaintext.data_size < in_data_len)
{
memmove(&out_data[in_data_len-plaintext.data_size], &out_data[0], plaintext.data_size) ;
memset(&out_data[0], 0, in_data_len-plaintext.data_size) ;
plaintext.data_size = in_data_len ;
}
if ( rc == SUCCESS )
ret_val = CKR_OK;
else
ret_val = CKR_FUNCTION_FAILED;
/* Free the key storage for CR format */
if (modulus->ulValueLen > 1024)
destroy_rsa_crt_key((rsa_crt_key *) privKey) ;
else
destroy_rsa_key((rsa_key *) privKey2) ;
return ret_val ;
} /* end token_specific_rsa_decrypt() */
CK_RV
token_specific_des_ecb(CK_BYTE * in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
CK_ULONG *out_data_len,
CK_BYTE *key_value,
CK_BYTE encrypt)
{
CK_ULONG rc;
des_key_schedule des_key2;
const_des_cblock key_val_SSL, in_key_data;
des_cblock out_key_data;
int i,j;
int ret;
// Create the key schedule
memcpy(&key_val_SSL, key_value, 8);
des_set_key_unchecked(&key_val_SSL, des_key2);
// the des decrypt will only fail if the data length is not evenly divisible
// by 8
if (in_data_len % 8 ){
OCK_LOG_ERR(ERR_DATA_LEN_RANGE);
return CKR_DATA_LEN_RANGE;
}
// Both the encrypt and the decrypt are done 8 bytes at a time
if (encrypt) {
for (i=0; i<in_data_len; i=i+8) {
memcpy(in_key_data, in_data+i, 8);
des_ecb_encrypt(&in_key_data, &out_key_data, des_key2, DES_ENCRYPT);
memcpy(out_data+i, out_key_data, 8);
}
*out_data_len = in_data_len;
rc = CKR_OK;
} else {
for(j=0; j < in_data_len; j=j+8) {
memcpy(in_key_data, in_data+j, 8);
des_ecb_encrypt(&in_key_data, &out_key_data, des_key2, DES_DECRYPT);
memcpy(out_data+j, out_key_data, 8);
}
*out_data_len = in_data_len;
rc = CKR_OK;
}
return rc;
}
CK_RV
token_specific_des_cbc(CK_BYTE * in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
CK_ULONG *out_data_len,
CK_BYTE *key_value,
CK_BYTE *init_v,
CK_BYTE encrypt)
{
CK_ULONG rc;
des_cblock ivec;
int ret;
des_key_schedule des_key2;
const_des_cblock key_val_SSL, in_key_data;
des_cblock out_key_data;
// Create the key schedule
memcpy(&key_val_SSL, key_value, 8);
des_set_key_unchecked(&key_val_SSL, des_key2);
memcpy(&ivec, init_v, 8);
// the des decrypt will only fail if the data length is not evenly divisible
// by 8
if (in_data_len % 8 ){
OCK_LOG_ERR(ERR_DATA_LEN_RANGE);
return CKR_DATA_LEN_RANGE;
}
if ( encrypt){
des_ncbc_encrypt(in_data, out_data, in_data_len, des_key2, &ivec, DES_ENCRYPT);
*out_data_len = in_data_len;
rc = CKR_OK;
} else {
des_ncbc_encrypt(in_data, out_data, in_data_len, des_key2, &ivec, DES_DECRYPT);
*out_data_len = in_data_len;
rc = CKR_OK;
}
return rc;
}
CK_RV
token_specific_tdes_ecb(CK_BYTE * in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
CK_ULONG *out_data_len,
CK_BYTE *key_value,
CK_BYTE encrypt)
{
CK_RV rc;
int k,j, ret;
des_cblock out_temp;
des_key_schedule des_key1;
des_key_schedule des_key2;
des_key_schedule des_key3;
const_des_cblock key_SSL1, key_SSL2, key_SSL3, in_key_data;
des_cblock out_key_data;
// The key as passed is a 24 byte long string containing three des keys
// pick them apart and create the 3 corresponding key schedules
memcpy(&key_SSL1, key_value, 8);
memcpy(&key_SSL2, key_value+8, 8);
memcpy(&key_SSL3, key_value+16, 8);
des_set_key_unchecked(&key_SSL1, des_key1);
des_set_key_unchecked(&key_SSL2, des_key2);
des_set_key_unchecked(&key_SSL3, des_key3);
// the des decrypt will only fail if the data length is not evenly divisible
// by 8
if (in_data_len % 8 ){
OCK_LOG_ERR(ERR_DATA_LEN_RANGE);
return CKR_DATA_LEN_RANGE;
}
// the encrypt and decrypt are done 8 bytes at a time
if (encrypt) {
for(k=0;k<in_data_len;k=k+8){
memcpy(in_key_data, in_data+k, 8);
des_ecb3_encrypt(&in_key_data,
&out_key_data,
des_key1,
des_key2,
des_key3,
DES_ENCRYPT);
memcpy(out_data+k, out_key_data, 8);
}
*out_data_len = in_data_len;
rc = CKR_OK;
} else {
for (j=0;j<in_data_len;j=j+8){
memcpy(in_key_data, in_data+j, 8);
des_ecb3_encrypt(&in_key_data,
&out_key_data,
des_key1,
des_key2,
des_key3,
DES_DECRYPT);
memcpy(out_data+j, out_key_data, 8);
}
*out_data_len = in_data_len;
rc = CKR_OK;
}
return rc;
}
CK_RV
token_specific_tdes_cbc(CK_BYTE * in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
CK_ULONG *out_data_len,
CK_BYTE *key_value,
CK_BYTE *init_v,
CK_BYTE encrypt)
{
CK_RV rc = CKR_OK;
des_key_schedule des_key1;
des_key_schedule des_key2;
des_key_schedule des_key3;
const_des_cblock key_SSL1, key_SSL2, key_SSL3, in_key_data;
des_cblock ivec;
// The key as passed in is a 24 byte string containing 3 keys
// pick it apart and create the key schedules
memcpy(&key_SSL1, key_value, 8);
memcpy(&key_SSL2, key_value+8, 8);
memcpy(&key_SSL3, key_value+16, 8);
des_set_key_unchecked(&key_SSL1, des_key1);
des_set_key_unchecked(&key_SSL2, des_key2);
des_set_key_unchecked(&key_SSL3, des_key3);
memcpy(ivec, init_v, sizeof(ivec));
// the des decrypt will only fail if the data length is not evenly divisible
// by 8
if (in_data_len % 8 ){
OCK_LOG_ERR(ERR_DATA_LEN_RANGE);
return CKR_DATA_LEN_RANGE;
}
// Encrypt or decrypt the data
if (encrypt){
des_ede3_cbc_encrypt(in_data,
out_data,
in_data_len,
des_key1,
des_key2,
des_key3,
&ivec,
DES_ENCRYPT);
*out_data_len = in_data_len;
rc = CKR_OK;
}else {
des_ede3_cbc_encrypt(in_data,
out_data,
in_data_len,
des_key1,
des_key2,
des_key3,
&ivec,
DES_DECRYPT);
*out_data_len = in_data_len;
rc = CKR_OK;
}
return rc;
}
#ifndef NOAES
CK_RV
token_specific_aes_key_gen( CK_BYTE *key, CK_ULONG len )
{
return rng_generate(key, len);
}
CK_RV
token_specific_aes_ecb( CK_BYTE *in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
CK_ULONG *out_data_len,
CK_BYTE *key_value,
CK_ULONG key_len,
CK_BYTE encrypt)
{
AES_KEY ssl_aes_key;
int i;
/* There's a previous check that in_data_len % AES_BLOCK_SIZE == 0,
* so this is fine */
CK_ULONG loops = (CK_ULONG)(in_data_len/AES_BLOCK_SIZE);
memset( &ssl_aes_key, 0, sizeof(AES_KEY));
// AES_ecb_encrypt encrypts only a single block, so we have to break up the
// input data here
if (encrypt) {
AES_set_encrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
for( i=0; i<loops; i++ ) {
AES_ecb_encrypt((unsigned char *)in_data + (i*AES_BLOCK_SIZE),
(unsigned char *)out_data + (i*AES_BLOCK_SIZE),
&ssl_aes_key,
AES_ENCRYPT);
}
} else {
AES_set_decrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
for( i=0; i<loops; i++ ) {
AES_ecb_encrypt((unsigned char *)in_data + (i*AES_BLOCK_SIZE),
(unsigned char *)out_data + (i*AES_BLOCK_SIZE),
&ssl_aes_key,
AES_DECRYPT);
}
}
*out_data_len = in_data_len;
return CKR_OK;
}
CK_RV
token_specific_aes_cbc( CK_BYTE *in_data,
CK_ULONG in_data_len,
CK_BYTE *out_data,
CK_ULONG *out_data_len,
CK_BYTE *key_value,
CK_ULONG key_len,
CK_BYTE *init_v,
CK_BYTE encrypt)
{
AES_KEY ssl_aes_key;
int i;
memset( &ssl_aes_key, 0, sizeof(AES_KEY));
// AES_cbc_encrypt chunks the data into AES_BLOCK_SIZE blocks, unlike
// AES_ecb_encrypt, so no looping required.
if (encrypt) {
AES_set_encrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
AES_cbc_encrypt((unsigned char *)in_data, (unsigned char *)out_data,
in_data_len, &ssl_aes_key,
init_v, AES_ENCRYPT);
} else {
AES_set_decrypt_key((unsigned char *)key_value, (key_len*8), &ssl_aes_key);
AES_cbc_encrypt((unsigned char *)in_data, (unsigned char *)out_data,
in_data_len, &ssl_aes_key,
init_v, AES_DECRYPT);
}
*out_data_len = in_data_len;
return CKR_OK;
}
#endif
// This computes DH shared secret, where:
// Output: z is computed shared secret
// Input: y is other party's public key
// x is private key
// p is prime
// All length's are in number of bytes. All data comes in as Big Endian.
CK_RV
token_specific_dh_pkcs_derive( CK_BYTE *z,
CK_ULONG *z_len,
CK_BYTE *y,
CK_ULONG y_len,
CK_BYTE *x,
CK_ULONG x_len,
CK_BYTE *p,
CK_ULONG p_len)
{
CK_RV ret_val ;
RC rc ;
token z_tok, y_tok, x_tok, p_tok ;
// Setup the tokens with values from the input params
z_tok.p_data = z ;
z_tok.data_size = p_len ;
y_tok.p_data = y ;
y_tok.data_size = y_len ;
x_tok.p_data = x ;
x_tok.data_size = x_len ;
p_tok.p_data = p ;
p_tok.data_size = p_len ;
// Perform: z = y^x mod p
rc = CR_mod_exp_mont(&z_tok, &y_tok, &p_tok, &x_tok) ;
if ( rc == SUCCESS )
ret_val = CKR_OK;
else
{
ret_val = CKR_FUNCTION_FAILED;
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
}
/* Corrent library may return results after triming leading zeros. Insert the leading
zeros back and adjust length below, if necessary */
if (z_tok.data_size < p_len)
{
memmove(z+(p_len-z_tok.data_size), z, z_tok.data_size) ;
memset(z, 0, p_len-z_tok.data_size) ;
z_tok.data_size = p_len ;
}
*z_len = z_tok.data_size ;
return ret_val;
} /* end token_specific_dh_pkcs_derive() */
// This computes DH key pair, where:
// Output: priv_tmpl is generated private key
// pub_tmpl is computed public key
// Input: pub_tmpl is public key (prime and generator)
// All length's are in number of bytes. All data comes in as Big Endian.
CK_RV
token_specific_dh_pkcs_key_pair_gen( TEMPLATE * publ_tmpl,
TEMPLATE * priv_tmpl )
{
RC rc;
CK_ATTRIBUTE *prime_attr = NULL;
CK_ATTRIBUTE *base_attr = NULL;
CK_ATTRIBUTE *temp_attr = NULL ;
CK_ATTRIBUTE *value_bits_attr = NULL;
CK_ATTRIBUTE *temp_value_bits_attr ;
CK_BYTE *temp_byte;
CK_ULONG temp_bn_len, count ;
CK_BYTE *priv_key_value ;
CK_ULONG priv_key_value_len ;
CK_BYTE *pub_key_value ;
CK_ULONG pub_key_value_len ;
CK_BYTE *p_temp ;
token pub_key_t, priv_key_t, prime_t, base_t ;
char *base_p ;
rc = template_attribute_find( publ_tmpl, CKA_PRIME, &prime_attr );
rc &= template_attribute_find( publ_tmpl, CKA_BASE, &base_attr );
if (rc == FALSE) {
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
if ((prime_attr->ulValueLen > CR_MAX_MODULUS_SIZE_BYTES) ||
(prime_attr->ulValueLen < 64))
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
// Check if the CKA_VALUE_BITS attribute of the private key has been set.
// If set, then check value to be less than size of prime, and use that value.
// If not set, then use the value dependent on size of prime.
rc = template_attribute_find( priv_tmpl, CKA_VALUE_BITS, &temp_value_bits_attr );
if (rc == FALSE)
{
// Randomly generate private key value
priv_key_value_len = prime_attr->ulValueLen ;
priv_key_value = malloc(priv_key_value_len) ;
token_rng(priv_key_value, priv_key_value_len) ;
// Right shift MSB of private to make it smaller than the prime
p_temp = (CK_BYTE *)prime_attr->pValue ;
while (p_temp[0] < priv_key_value[0])
priv_key_value[0] = priv_key_value[0] >> 1 ;
}
else
{
// Randomly generate private key value. Round off the value of CKA_VALUE_BITS
// to next higher byte size for added security (and convenience/speed).
priv_key_value_len = *(CK_ULONG *)temp_value_bits_attr->pValue ;
if (priv_key_value_len > CR_MAX_MODULUS_SIZE_BITS)
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
// Convert to next higher Byte size
priv_key_value_len = (priv_key_value_len/8) + 1 ;
// If the value set is less than 22 (180 bits), then bump the private-key
// value to at least 180 bits (23 bytes)...for additional security
if (priv_key_value_len < 22)
priv_key_value_len = 23 ;
priv_key_value = malloc(priv_key_value_len) ;
token_rng(priv_key_value, priv_key_value_len) ;
// If private size is same as prime size, make sure that the private
// value is less than prime value.
if (priv_key_value_len == prime_attr->ulValueLen)
{
// Right shift MSB of private to make it smaller than the prime
p_temp = (CK_BYTE *)prime_attr->pValue ;
while (p_temp[0] < priv_key_value[0])
priv_key_value[0] = priv_key_value[0] >> 1 ;
}
}
// Calculate public key using: pub_key = base^priv_key mod prime
// Setup the tokens with values from the input params
pub_key_t.data_size = CR_MAX_MODULUS_SIZE_BYTES ;
pub_key_value = malloc(pub_key_t.data_size) ;
pub_key_t.p_data = pub_key_value ;
priv_key_t.p_data = priv_key_value ;
priv_key_t.data_size = priv_key_value_len ;
prime_t.p_data = (char *)prime_attr->pValue ;
prime_t.data_size = prime_attr->ulValueLen ;
base_t.p_data = (char *)base_attr->pValue ;
base_t.data_size = base_attr->ulValueLen ;
// Perform mod exp operation
rc = CR_mod_exp_mont(&pub_key_t, &base_t, &prime_t, &priv_key_t) ;
if ( rc != SUCCESS )
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED ;
}
/* Corrent library may return results after triming leading zeros. Insert the leading
zeros back and adjust length below, if necessary */
if (pub_key_t.data_size < prime_t.data_size)
{
memmove(pub_key_value+(prime_t.data_size-pub_key_t.data_size), pub_key_value,
pub_key_t.data_size) ;
memset(pub_key_value, 0, prime_t.data_size-pub_key_t.data_size) ;
pub_key_t.data_size = prime_t.data_size ;
}
pub_key_value_len = pub_key_t.data_size ;
// Insert the public key component in the publ_tmpl
rc = build_attribute( CKA_VALUE, pub_key_value, pub_key_value_len, &temp_attr ); // in bytes
if (rc != CKR_OK)
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
template_update_attribute( publ_tmpl, temp_attr );
free(pub_key_value);
// Insert the private key component in the priv_tmpl
rc = build_attribute( CKA_VALUE, priv_key_value, priv_key_value_len, &temp_attr ); // in bytes
if (rc != CKR_OK)
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
template_update_attribute( priv_tmpl, temp_attr );
free(priv_key_value);
// Update CKA_VALUE_BITS attribute in the private key
value_bits_attr = (CK_ATTRIBUTE *)malloc( sizeof(CK_ATTRIBUTE) + sizeof(CK_ULONG) );
value_bits_attr->type = CKA_VALUE_BITS;
value_bits_attr->ulValueLen = sizeof(CK_ULONG);
value_bits_attr->pValue = (CK_BYTE *)value_bits_attr + sizeof(CK_ATTRIBUTE);
*(CK_ULONG *)value_bits_attr->pValue = 8*priv_key_value_len;
template_update_attribute( priv_tmpl, value_bits_attr );
// Add prime and base to the private key template
rc = build_attribute( CKA_PRIME,(char *)prime_attr->pValue,
prime_attr->ulValueLen, &temp_attr ); // in bytes
if (rc != CKR_OK)
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
template_update_attribute( priv_tmpl, temp_attr );
rc = build_attribute( CKA_BASE,(char *)base_attr->pValue,
base_attr->ulValueLen, &temp_attr ); // in bytes
if (rc != CKR_OK)
{
OCK_LOG_ERR(ERR_FUNCTION_FAILED);
return CKR_FUNCTION_FAILED;
}
template_update_attribute( priv_tmpl, temp_attr );
return CKR_OK ;
} /* end token_specific_dh_key_pair_gen() */
MECH_LIST_ELEMENT mech_list[] = {
{ CKM_RSA_PKCS_KEY_PAIR_GEN, 512, 2048, CKF_HW | CKF_GENERATE_KEY_PAIR },
#if !(NODSA)
{ CKM_DSA_KEY_PAIR_GEN, 512, 1024, CKF_HW | CKF_GENERATE_KEY_PAIR },
#endif
{ CKM_DES_KEY_GEN, 8, 8, CKF_HW | CKF_GENERATE },
{ CKM_DES3_KEY_GEN, 24, 24, CKF_HW | CKF_GENERATE },
#if !(NOCDMF)
{ CKM_CDMF_KEY_GEN, 0, 0, CKF_HW | CKF_GENERATE },
#endif
{ CKM_RSA_PKCS, 512, 2048, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP |
CKF_SIGN | CKF_VERIFY |
CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER },
#if !(NOX509)
{ CKM_RSA_X_509, 512, 2048, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP |
CKF_SIGN | CKF_VERIFY |
CKF_SIGN_RECOVER | CKF_VERIFY_RECOVER },
#endif
#if !(NOMD2)
{ CKM_MD2_RSA_PKCS, 512, 2048, CKF_HW |
CKF_SIGN | CKF_VERIFY },
#endif
#if !(NOMD5)
{ CKM_MD5_RSA_PKCS, 512, 2048, CKF_HW |
CKF_SIGN | CKF_VERIFY },
#endif
#if !(NOSHA1)
{ CKM_SHA1_RSA_PKCS, 512, 2048, CKF_HW |
CKF_SIGN | CKF_VERIFY },
#endif
#if !(NODSA)
{ CKM_DSA, 512, 1024, CKF_HW |
CKF_SIGN | CKF_VERIFY },
#endif
/* Begin code contributed by Corrent corp. */
#if !(NODH)
{ CKM_DH_PKCS_DERIVE, 512, 2048, CKF_HW | CKF_DERIVE },
{ CKM_DH_PKCS_KEY_PAIR_GEN, 512, 2048, CKF_HW | CKF_GENERATE_KEY_PAIR },
#endif
/* End code contributed by Corrent corp. */
{ CKM_DES_ECB, 8, 8, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_DES_CBC, 8, 8, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_DES_CBC_PAD, 8, 8, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
#if !(NOCDMF)
{ CKM_CDMF_ECB, 0, 0, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_CDMF_CBC, 0, 0, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
#endif
{ CKM_DES3_ECB, 24, 24, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_DES3_CBC, 24, 24, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_DES3_CBC_PAD, 24, 24, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
#if !(NOSHA1)
{ CKM_SHA_1, 0, 0, CKF_HW | CKF_DIGEST },
{ CKM_SHA_1_HMAC, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
{ CKM_SHA_1_HMAC_GENERAL, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
{ CKM_SHA256, 0, 0, CKF_HW | CKF_DIGEST },
{ CKM_SHA256_HMAC, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
{ CKM_SHA256_HMAC_GENERAL, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif
#if !(NOMD2)
{ CKM_MD2, 0, 0, CKF_HW | CKF_DIGEST },
{ CKM_MD2_HMAC, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
{ CKM_MD2_HMAC_GENERAL, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif
#if !(NOMD5)
{ CKM_MD5, 0, 0, CKF_HW | CKF_DIGEST },
{ CKM_MD5_HMAC, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
{ CKM_MD5_HMAC_GENERAL, 0, 0, CKF_HW | CKF_SIGN | CKF_VERIFY },
#endif
{ CKM_SSL3_PRE_MASTER_KEY_GEN, 48, 48, CKF_HW | CKF_GENERATE },
{ CKM_SSL3_MASTER_KEY_DERIVE, 48, 48, CKF_HW | CKF_DERIVE },
{ CKM_SSL3_KEY_AND_MAC_DERIVE, 48, 48, CKF_HW | CKF_DERIVE },
{ CKM_SSL3_MD5_MAC, 384, 384, CKF_HW | CKF_SIGN | CKF_VERIFY },
{ CKM_SSL3_SHA1_MAC, 384, 384, CKF_HW | CKF_SIGN | CKF_VERIFY },
#if !(NOAES)
{ CKM_AES_KEY_GEN, 16, 32, CKF_HW },
{ CKM_AES_ECB, 16, 32, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_AES_CBC, 16, 32, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
{ CKM_AES_CBC_PAD, 16, 32, CKF_HW |
CKF_ENCRYPT | CKF_DECRYPT |
CKF_WRAP | CKF_UNWRAP },
#endif
};
CK_ULONG mech_list_len = (sizeof(mech_list) / sizeof(MECH_LIST_ELEMENT));
CK_RV
token_specific_get_mechanism_list(CK_MECHANISM_TYPE_PTR pMechanismList,
CK_ULONG_PTR pulCount)
{
int rc;
/* common/mech_list.c */
rc = ock_generic_get_mechanism_list(pMechanismList, pulCount);
return rc;
}
CK_RV
token_specific_get_mechanism_info(CK_MECHANISM_TYPE type,
CK_MECHANISM_INFO_PTR pInfo)
{
int rc;
/* common/mech_list.c */
rc = ock_generic_get_mechanism_info(type, pInfo);
return rc;
}
|
shpedoikal/opencryptoki
|
usr/lib/pkcs11/cr_stdll/cr_specific.c
|
C
|
epl-1.0
| 57,369 |
/**
* Copyright (c) 2005-2013 by Appcelerator, Inc. All Rights Reserved.
* Licensed under the terms of the Eclipse Public License (EPL).
* Please see the license.txt included with this distribution for details.
* Any modifications to this file must keep this entire header intact.
*/
package org.python.pydev.ui;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.jface.util.IPropertyChangeListener;
import org.eclipse.jface.util.PropertyChangeEvent;
import org.eclipse.swt.events.ControlEvent;
import org.eclipse.swt.events.ControlListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.ViewPart;
import org.python.pydev.plugin.PyDevUiPrefs;
import org.python.pydev.shared_core.SharedCorePlugin;
import org.python.pydev.shared_core.callbacks.CallbackWithListeners;
import org.python.pydev.shared_core.callbacks.ICallbackWithListeners;
public abstract class ViewPartWithOrientation extends ViewPart implements IPropertyChangeListener {
protected Composite fParent;
protected int fCurrentOrientation;
private int orientationPreference;
protected ViewPartWithOrientation() {
String orientationPreferencesKey = getOrientationPreferencesKey();
if (!SharedCorePlugin.inTestMode()) {
IPreferenceStore preferenceStore = PyDevUiPrefs.getPreferenceStore();
orientationPreference = preferenceStore.getInt(orientationPreferencesKey);
PyDevUiPrefs.getPreferenceStore().addPropertyChangeListener(this);
}
}
/*default*/static final int PREFERENCES_VIEW_ORIENTATION_AUTOMATIC = 0;
/*default*/static final int PREFERENCES_VIEW_ORIENTATION_HORIZONTAL = 1;
/*default*/static final int PREFERENCES_VIEW_ORIENTATION_VERTICAL = 2;
//Subclasses will be passed these constants!
public static final int VIEW_ORIENTATION_HORIZONTAL = 1;
public static final int VIEW_ORIENTATION_VERTICAL = 2;
@SuppressWarnings("rawtypes")
public final ICallbackWithListeners onControlCreated = new CallbackWithListeners();
@SuppressWarnings("rawtypes")
public final ICallbackWithListeners onControlDisposed = new CallbackWithListeners();
@Override
public void createPartControl(Composite parent) {
fParent = parent;
addResizeListener(parent);
}
public abstract String getOrientationPreferencesKey();
/*default*/int getOrientationPreferenceValue() {
return orientationPreference;
}
protected void addOrientationPreferences(IMenuManager menuManager) {
menuManager.add(new SetOrientationAction(this));
}
protected void updateOrientation() {
switch (orientationPreference) {
case PREFERENCES_VIEW_ORIENTATION_HORIZONTAL:
setNewOrientation(VIEW_ORIENTATION_HORIZONTAL);
break;
case PREFERENCES_VIEW_ORIENTATION_VERTICAL:
setNewOrientation(VIEW_ORIENTATION_VERTICAL);
break;
default:
//automatic
Point size = fParent.getSize();
if (size.x != 0 && size.y != 0) {
if (size.x > size.y) {
setNewOrientation(VIEW_ORIENTATION_HORIZONTAL);
} else {
setNewOrientation(VIEW_ORIENTATION_VERTICAL);
}
}
}
}
private void addResizeListener(Composite parent) {
parent.addControlListener(new ControlListener() {
@Override
public void controlMoved(ControlEvent e) {
}
@Override
public void controlResized(ControlEvent e) {
updateOrientation();
}
});
}
protected abstract void setNewOrientation(int orientation);
@Override
public void dispose() {
PyDevUiPrefs.getPreferenceStore().removePropertyChangeListener(this);
super.dispose();
}
/* (non-Javadoc)
* @see org.eclipse.jface.util.IPropertyChangeListener#propertyChange(org.eclipse.jface.util.PropertyChangeEvent)
*/
@Override
public void propertyChange(PropertyChangeEvent event) {
if (event.getProperty().equals(this.getOrientationPreferencesKey())) {
orientationPreference = (Integer) event.getNewValue();
updateOrientation();
}
}
}
|
fabioz/Pydev
|
plugins/org.python.pydev/src/org/python/pydev/ui/ViewPartWithOrientation.java
|
Java
|
epl-1.0
| 4,468 |
/*
* Hibernate, Relational Persistence for Idiomatic Java
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser 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 Lesser General Public License
* for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
* Boston, MA 02110-1301 USA
*
*/
package org.hibernate.event.def;
import java.io.Serializable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.AssertionFailure;
import org.hibernate.EntityMode;
import org.hibernate.HibernateException;
import org.hibernate.LockMode;
import org.hibernate.PersistentObjectException;
import org.hibernate.TransientObjectException;
import org.hibernate.classic.Lifecycle;
import org.hibernate.engine.Cascade;
import org.hibernate.engine.CascadingAction;
import org.hibernate.engine.EntityEntry;
import org.hibernate.engine.EntityKey;
import org.hibernate.engine.SessionFactoryImplementor;
import org.hibernate.engine.SessionImplementor;
import org.hibernate.engine.Status;
import org.hibernate.event.EventSource;
import org.hibernate.event.SaveOrUpdateEvent;
import org.hibernate.event.SaveOrUpdateEventListener;
import org.hibernate.persister.entity.EntityPersister;
import org.hibernate.pretty.MessageHelper;
import org.hibernate.proxy.HibernateProxy;
/**
* Defines the default listener used by Hibernate for handling save-update
* events.
*
* @author Steve Ebersole
* @author Gavin King
*/
public class DefaultSaveOrUpdateEventListener extends AbstractSaveEventListener implements SaveOrUpdateEventListener {
private static final Logger log = LoggerFactory.getLogger( DefaultSaveOrUpdateEventListener.class );
/**
* Handle the given update event.
*
* @param event The update event to be handled.
*/
public void onSaveOrUpdate(SaveOrUpdateEvent event) {
final SessionImplementor source = event.getSession();
final Object object = event.getObject();
final Serializable requestedId = event.getRequestedId();
if ( requestedId != null ) {
//assign the requested id to the proxy, *before*
//reassociating the proxy
if ( object instanceof HibernateProxy ) {
( ( HibernateProxy ) object ).getHibernateLazyInitializer().setIdentifier( requestedId );
}
}
if ( reassociateIfUninitializedProxy( object, source ) ) {
log.trace( "reassociated uninitialized proxy" );
// an uninitialized proxy, noop, don't even need to
// return an id, since it is never a save()
}
else {
//initialize properties of the event:
final Object entity = source.getPersistenceContext().unproxyAndReassociate( object );
event.setEntity( entity );
event.setEntry( source.getPersistenceContext().getEntry( entity ) );
//return the id in the event object
event.setResultId( performSaveOrUpdate( event ) );
}
}
protected boolean reassociateIfUninitializedProxy(Object object, SessionImplementor source) {
return source.getPersistenceContext().reassociateIfUninitializedProxy( object );
}
protected Serializable performSaveOrUpdate(SaveOrUpdateEvent event) {
int entityState = getEntityState(
event.getEntity(),
event.getEntityName(),
event.getEntry(),
event.getSession()
);
switch ( entityState ) {
case DETACHED:
entityIsDetached( event );
return null;
case PERSISTENT:
return entityIsPersistent( event );
default: //TRANSIENT or DELETED
return entityIsTransient( event );
}
}
protected Serializable entityIsPersistent(SaveOrUpdateEvent event) throws HibernateException {
log.trace( "ignoring persistent instance" );
EntityEntry entityEntry = event.getEntry();
if ( entityEntry == null ) {
throw new AssertionFailure( "entity was transient or detached" );
}
else {
if ( entityEntry.getStatus() == Status.DELETED ) {
throw new AssertionFailure( "entity was deleted" );
}
final SessionFactoryImplementor factory = event.getSession().getFactory();
Serializable requestedId = event.getRequestedId();
Serializable savedId;
if ( requestedId == null ) {
savedId = entityEntry.getId();
}
else {
final boolean isEqual = !entityEntry.getPersister().getIdentifierType()
.isEqual( requestedId, entityEntry.getId(), event.getSession().getEntityMode(), factory );
if ( isEqual ) {
throw new PersistentObjectException(
"object passed to save() was already persistent: " +
MessageHelper.infoString( entityEntry.getPersister(), requestedId, factory )
);
}
savedId = requestedId;
}
if ( log.isTraceEnabled() ) {
log.trace(
"object already associated with session: " +
MessageHelper.infoString( entityEntry.getPersister(), savedId, factory )
);
}
return savedId;
}
}
/**
* The given save-update event named a transient entity.
* <p/>
* Here, we will perform the save processing.
*
* @param event The save event to be handled.
*
* @return The entity's identifier after saving.
*/
protected Serializable entityIsTransient(SaveOrUpdateEvent event) {
log.trace( "saving transient instance" );
final EventSource source = event.getSession();
EntityEntry entityEntry = event.getEntry();
if ( entityEntry != null ) {
if ( entityEntry.getStatus() == Status.DELETED ) {
source.forceFlush( entityEntry );
}
else {
throw new AssertionFailure( "entity was persistent" );
}
}
Serializable id = saveWithGeneratedOrRequestedId( event );
source.getPersistenceContext().reassociateProxy( event.getObject(), id );
return id;
}
/**
* Save the transient instance, assigning the right identifier
*
* @param event The initiating event.
*
* @return The entity's identifier value after saving.
*/
protected Serializable saveWithGeneratedOrRequestedId(SaveOrUpdateEvent event) {
return saveWithGeneratedId(
event.getEntity(),
event.getEntityName(),
null,
event.getSession(),
true
);
}
/**
* The given save-update event named a detached entity.
* <p/>
* Here, we will perform the update processing.
*
* @param event The update event to be handled.
*/
protected void entityIsDetached(SaveOrUpdateEvent event) {
log.trace( "updating detached instance" );
if ( event.getSession().getPersistenceContext().isEntryFor( event.getEntity() ) ) {
//TODO: assertion only, could be optimized away
throw new AssertionFailure( "entity was persistent" );
}
Object entity = event.getEntity();
EntityPersister persister = event.getSession().getEntityPersister( event.getEntityName(), entity );
event.setRequestedId(
getUpdateId(
entity, persister, event.getRequestedId(), event.getSession()
)
);
performUpdate( event, entity, persister );
}
/**
* Determine the id to use for updating.
*
* @param entity The entity.
* @param persister The entity persister
* @param requestedId The requested identifier
* @param session The session
*
* @return The id.
*
* @throws TransientObjectException If the entity is considered transient.
*/
protected Serializable getUpdateId(
Object entity,
EntityPersister persister,
Serializable requestedId,
SessionImplementor session) {
// use the id assigned to the instance
Serializable id = persister.getIdentifier( entity, session );
if ( id == null ) {
// assume this is a newly instantiated transient object
// which should be saved rather than updated
throw new TransientObjectException(
"The given object has a null identifier: " +
persister.getEntityName()
);
}
else {
return id;
}
}
protected void performUpdate(
SaveOrUpdateEvent event,
Object entity,
EntityPersister persister) throws HibernateException {
if ( !persister.isMutable() ) {
log.trace( "immutable instance passed to performUpdate()" );
}
if ( log.isTraceEnabled() ) {
log.trace(
"updating " +
MessageHelper.infoString(
persister, event.getRequestedId(), event.getSession().getFactory()
)
);
}
final EventSource source = event.getSession();
EntityKey key = new EntityKey( event.getRequestedId(), persister, source.getEntityMode() );
source.getPersistenceContext().checkUniqueness( key, entity );
if ( invokeUpdateLifecycle( entity, persister, source ) ) {
reassociate( event, event.getObject(), event.getRequestedId(), persister );
return;
}
// this is a transient object with existing persistent state not loaded by the session
new OnUpdateVisitor( source, event.getRequestedId(), entity ).process( entity, persister );
//TODO: put this stuff back in to read snapshot from
// the second-level cache (needs some extra work)
/*Object[] cachedState = null;
if ( persister.hasCache() ) {
CacheEntry entry = (CacheEntry) persister.getCache()
.get( event.getRequestedId(), source.getTimestamp() );
cachedState = entry==null ?
null :
entry.getState(); //TODO: half-assemble this stuff
}*/
source.getPersistenceContext().addEntity(
entity,
( persister.isMutable() ? Status.MANAGED : Status.READ_ONLY ),
null, //cachedState,
key,
persister.getVersion( entity, source.getEntityMode() ),
LockMode.NONE,
true,
persister,
false,
true //assume true, since we don't really know, and it doesn't matter
);
persister.afterReassociate( entity, source );
if ( log.isTraceEnabled() ) {
log.trace(
"updating " +
MessageHelper.infoString( persister, event.getRequestedId(), source.getFactory() )
);
}
cascadeOnUpdate( event, persister, entity );
}
protected boolean invokeUpdateLifecycle(Object entity, EntityPersister persister, EventSource source) {
if ( persister.implementsLifecycle( source.getEntityMode() ) ) {
log.debug( "calling onUpdate()" );
if ( ( ( Lifecycle ) entity ).onUpdate( source ) ) {
log.debug( "update vetoed by onUpdate()" );
return true;
}
}
return false;
}
/**
* Handles the calls needed to perform cascades as part of an update request
* for the given entity.
*
* @param event The event currently being processed.
* @param persister The defined persister for the entity being updated.
* @param entity The entity being updated.
*/
private void cascadeOnUpdate(SaveOrUpdateEvent event, EntityPersister persister, Object entity) {
EventSource source = event.getSession();
source.getPersistenceContext().incrementCascadeLevel();
try {
new Cascade( CascadingAction.SAVE_UPDATE, Cascade.AFTER_UPDATE, source )
.cascade( persister, entity );
}
finally {
source.getPersistenceContext().decrementCascadeLevel();
}
}
protected CascadingAction getCascadeAction() {
return CascadingAction.SAVE_UPDATE;
}
}
|
ControlSystemStudio/cs-studio
|
thirdparty/plugins/org.csstudio.platform.libs.hibernate/project/core/src/main/java/org/hibernate/event/def/DefaultSaveOrUpdateEventListener.java
|
Java
|
epl-1.0
| 11,547 |
/*******************************************************************************
* Copyright (c) 2000, 2013 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
* IBM Corporation - added constant AccDefault
* IBM Corporation - added constants AccBridge and AccVarargs for J2SE 1.5
*******************************************************************************/
package org.eclipse.jdt.core;
import org.eclipse.jdt.internal.compiler.classfmt.ClassFileConstants;
import org.eclipse.jdt.internal.compiler.lookup.ExtraCompilerModifiers;
/**
* Utility class for decoding modifier flags in Java elements.
* <p>
* This class provides static methods only.
* </p>
* <p>
* Note that the numeric values of these flags match the ones for class files
* as described in the Java Virtual Machine Specification (except for
* {@link #AccDeprecated}, {@link #AccAnnotationDefault}, and {@link #AccDefaultMethod}).
* </p>
* <p>
* The AST class <code>Modifier</code> provides
* similar functionality as this class, only in the
* <code>org.eclipse.jdt.core.dom</code> package.
* </p>
*
* @see IMember#getFlags()
* @noinstantiate This class is not intended to be instantiated by clients.
*/
public final class Flags {
/**
* Constant representing the absence of any flag.
* @since 3.0
*/
public static final int AccDefault = ClassFileConstants.AccDefault;
/**
* Public access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccPublic = ClassFileConstants.AccPublic;
/**
* Private access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccPrivate = ClassFileConstants.AccPrivate;
/**
* Protected access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccProtected = ClassFileConstants.AccProtected;
/**
* Static access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccStatic = ClassFileConstants.AccStatic;
/**
* Final access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccFinal = ClassFileConstants.AccFinal;
/**
* Synchronized access flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccSynchronized = ClassFileConstants.AccSynchronized;
/**
* Volatile property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccVolatile = ClassFileConstants.AccVolatile;
/**
* Transient property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccTransient = ClassFileConstants.AccTransient;
/**
* Native property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccNative = ClassFileConstants.AccNative;
/**
* Interface property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccInterface = ClassFileConstants.AccInterface;
/**
* Abstract property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccAbstract = ClassFileConstants.AccAbstract;
/**
* Strictfp property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccStrictfp = ClassFileConstants.AccStrictfp;
/**
* Super property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccSuper = ClassFileConstants.AccSuper;
/**
* Synthetic property flag. See The Java Virtual Machine Specification for more details.
* @since 2.0
*/
public static final int AccSynthetic = ClassFileConstants.AccSynthetic;
/**
* Deprecated property flag.
* <p>
* Note that this flag's value is internal and is not defined in the
* Virtual Machine specification.
* </p>
* @since 2.0
*/
public static final int AccDeprecated = ClassFileConstants.AccDeprecated;
/**
* Bridge method property flag (added in J2SE 1.5). Used to flag a compiler-generated
* bridge methods.
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccBridge = ClassFileConstants.AccBridge;
/**
* Varargs method property flag (added in J2SE 1.5).
* Used to flag variable arity method declarations.
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccVarargs = ClassFileConstants.AccVarargs;
/**
* Enum property flag (added in J2SE 1.5).
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccEnum = ClassFileConstants.AccEnum;
/**
* Annotation property flag (added in J2SE 1.5).
* See The Java Virtual Machine Specification for more details.
* @since 3.0
*/
public static final int AccAnnotation = ClassFileConstants.AccAnnotation;
/**
* Default method property flag.
* <p>
* Note that this flag's value is internal and is not defined in the
* Virtual Machine specification.
* </p>
* @since 3.10
*/
public static final int AccDefaultMethod = ExtraCompilerModifiers.AccDefaultMethod;
/**
* Annotation method default property flag.
* Used to flag annotation type methods that declare a default value.
* <p>
* Note that this flag's value is internal and is not defined in the
* Virtual Machine specification.
* </p>
* @since 3.10
*/
public static final int AccAnnotationDefault = ClassFileConstants.AccAnnotationDefault;
/**
* Not instantiable.
*/
private Flags() {
// Not instantiable
}
/**
* Returns whether the given integer includes the <code>abstract</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>abstract</code> modifier is included
*/
public static boolean isAbstract(int flags) {
return (flags & AccAbstract) != 0;
}
/**
* Returns whether the given integer includes the indication that the
* element is deprecated (<code>@deprecated</code> tag in Javadoc comment).
*
* @param flags the flags
* @return <code>true</code> if the element is marked as deprecated
*/
public static boolean isDeprecated(int flags) {
return (flags & AccDeprecated) != 0;
}
/**
* Returns whether the given integer includes the <code>final</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>final</code> modifier is included
*/
public static boolean isFinal(int flags) {
return (flags & AccFinal) != 0;
}
/**
* Returns whether the given integer includes the <code>interface</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>interface</code> modifier is included
* @since 2.0
*/
public static boolean isInterface(int flags) {
return (flags & AccInterface) != 0;
}
/**
* Returns whether the given integer includes the <code>native</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>native</code> modifier is included
*/
public static boolean isNative(int flags) {
return (flags & AccNative) != 0;
}
/**
* Returns whether the given integer does not include one of the
* <code>public</code>, <code>private</code>, or <code>protected</code> flags.
*
* @param flags the flags
* @return <code>true</code> if no visibility flag is set
* @since 3.2
*/
public static boolean isPackageDefault(int flags) {
return (flags & (AccPublic | AccPrivate | AccProtected)) == 0;
}
/**
* Returns whether the given integer includes the <code>private</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>private</code> modifier is included
*/
public static boolean isPrivate(int flags) {
return (flags & AccPrivate) != 0;
}
/**
* Returns whether the given integer includes the <code>protected</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>protected</code> modifier is included
*/
public static boolean isProtected(int flags) {
return (flags & AccProtected) != 0;
}
/**
* Returns whether the given integer includes the <code>public</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>public</code> modifier is included
*/
public static boolean isPublic(int flags) {
return (flags & AccPublic) != 0;
}
/**
* Returns whether the given integer includes the <code>static</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>static</code> modifier is included
*/
public static boolean isStatic(int flags) {
return (flags & AccStatic) != 0;
}
/**
* Returns whether the given integer includes the <code>super</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>super</code> modifier is included
* @since 3.2
*/
public static boolean isSuper(int flags) {
return (flags & AccSuper) != 0;
}
/**
* Returns whether the given integer includes the <code>strictfp</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>strictfp</code> modifier is included
*/
public static boolean isStrictfp(int flags) {
return (flags & AccStrictfp) != 0;
}
/**
* Returns whether the given integer includes the <code>synchronized</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>synchronized</code> modifier is included
*/
public static boolean isSynchronized(int flags) {
return (flags & AccSynchronized) != 0;
}
/**
* Returns whether the given integer includes the indication that the
* element is synthetic.
*
* @param flags the flags
* @return <code>true</code> if the element is marked synthetic
*/
public static boolean isSynthetic(int flags) {
return (flags & AccSynthetic) != 0;
}
/**
* Returns whether the given integer includes the <code>transient</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>transient</code> modifier is included
*/
public static boolean isTransient(int flags) {
return (flags & AccTransient) != 0;
}
/**
* Returns whether the given integer includes the <code>volatile</code> modifier.
*
* @param flags the flags
* @return <code>true</code> if the <code>volatile</code> modifier is included
*/
public static boolean isVolatile(int flags) {
return (flags & AccVolatile) != 0;
}
/**
* Returns whether the given integer has the <code>AccBridge</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccBridge</code> flag is included
* @see #AccBridge
* @since 3.0
*/
public static boolean isBridge(int flags) {
return (flags & AccBridge) != 0;
}
/**
* Returns whether the given integer has the <code>AccVarargs</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccVarargs</code> flag is included
* @see #AccVarargs
* @since 3.0
*/
public static boolean isVarargs(int flags) {
return (flags & AccVarargs) != 0;
}
/**
* Returns whether the given integer has the <code>AccEnum</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccEnum</code> flag is included
* @see #AccEnum
* @since 3.0
*/
public static boolean isEnum(int flags) {
return (flags & AccEnum) != 0;
}
/**
* Returns whether the given integer has the <code>AccAnnotation</code>
* bit set.
*
* @param flags the flags
* @return <code>true</code> if the <code>AccAnnotation</code> flag is included
* @see #AccAnnotation
* @since 3.0
*/
public static boolean isAnnotation(int flags) {
return (flags & AccAnnotation) != 0;
}
/**
* Returns whether the given integer has the <code>AccDefaultMethod</code>
* bit set. Note that this flag represents the usage of the 'default' keyword
* on a method and should not be confused with the 'package' access visibility (which used to be called 'default access').
*
* @return <code>true</code> if the <code>AccDefaultMethod</code> flag is included
* @see #AccDefaultMethod
* @since 3.10
*/
public static boolean isDefaultMethod(int flags) {
return (flags & AccDefaultMethod) != 0;
}
/**
* Returns whether the given integer has the <code>AccAnnnotationDefault</code>
* bit set.
*
* @return <code>true</code> if the <code>AccAnnotationDefault</code> flag is included
* @see #AccAnnotationDefault
* @since 3.10
*/
public static boolean isAnnnotationDefault(int flags) {
return (flags & AccAnnotationDefault) != 0;
}
/**
* Returns a standard string describing the given modifier flags.
* Only modifier flags are included in the output; deprecated,
* synthetic, bridge, etc. flags are ignored.
* <p>
* The flags are output in the following order:
* <pre> public protected private
* abstract default static final synchronized native strictfp transient volatile</pre>
* <p>
* This order is consistent with the recommendations in JLS8 ("*Modifier:" rules in chapters 8 and 9).
* </p>
* <p>
* Note that the flags of a method can include the AccVarargs flag that has no standard description. Since the AccVarargs flag has the same value as
* the AccTransient flag (valid for fields only), attempting to get the description of method modifiers with the AccVarargs flag set would result in an
* unexpected description. Clients should ensure that the AccVarargs is not included in the flags of a method as follows:
* <pre>
* IMethod method = ...
* int flags = method.getFlags() & ~Flags.AccVarargs;
* return Flags.toString(flags);
* </pre>
* </p>
* <p>
* Examples results:
* <pre>
* <code>"public static final"</code>
* <code>"private native"</code>
* </pre>
* </p>
*
* @param flags the flags
* @return the standard string representation of the given flags
*/
public static String toString(int flags) {
StringBuffer sb = new StringBuffer();
if (isPublic(flags))
sb.append("public "); //$NON-NLS-1$
if (isProtected(flags))
sb.append("protected "); //$NON-NLS-1$
if (isPrivate(flags))
sb.append("private "); //$NON-NLS-1$
if (isAbstract(flags))
sb.append("abstract "); //$NON-NLS-1$
if (isDefaultMethod(flags))
sb.append("default "); //$NON-NLS-1$
if (isStatic(flags))
sb.append("static "); //$NON-NLS-1$
if (isFinal(flags))
sb.append("final "); //$NON-NLS-1$
if (isSynchronized(flags))
sb.append("synchronized "); //$NON-NLS-1$
if (isNative(flags))
sb.append("native "); //$NON-NLS-1$
if (isStrictfp(flags))
sb.append("strictfp "); //$NON-NLS-1$
if (isTransient(flags))
sb.append("transient "); //$NON-NLS-1$
if (isVolatile(flags))
sb.append("volatile "); //$NON-NLS-1$
int len = sb.length();
if (len == 0)
return ""; //$NON-NLS-1$
sb.setLength(len - 1);
return sb.toString();
}
}
|
trylimits/Eclipse-Postfix-Code-Completion
|
luna/org.eclipse.jdt.core/model/org/eclipse/jdt/core/Flags.java
|
Java
|
epl-1.0
| 15,403 |
# INTRODUCTION
## A PROBLEM STATEMENT
This library demonstrates a technique of generating random numbers for cryptographic purposes without hardware generators.
Encryption and signing requires a random numbers with good quality.
Generating a random numbers (or sequences of random bytes) without hardware generators is not
trivial task. Especially this problem is actual for a small devices where sources of random data are absent or limited.
The solution is to have true random seed saved in a secured file (vault) and cipher which can produce encrypted pseudo random generated
(PRNG) sequences based on random seed with good random characteristics.
Many cryptographic libraries (e.g. BouncyCastle) use SecureRandom class for encryption and signing to
get random numbers. SecureRandom depends on OS implementation. Another words, realization of random engine is outside your
application which you cannot control. To avoid of using poor random numbers you MUST seed SecureRandom generator with good random
data every time you call cryptographic functions which requires the random data. Or you can extend SecureRandom class with your realization
that produces a random numbers which quality you can control.
RULE: The strength of any cryptographic system is highly depends on random numbers!
## HOW TO USE:
Some steps how to msprandom inside your application:
1. Generate on your computer or notebook a true random seed and put it to a vault using this library (function new-vault).
2. Put a vault (file) with random seed on your device, computer or server where you need to encrypt and sign data.
3. Load the vault once at the start of the program when you need encrypt or sign data (function load-vault).
4. Call gen-rand function from msprandom library to get random bytes as many times as you need.
The vault with random seed is encrypted and secured with HMAC.
Random seed in a vault is updated every time you load vault with unpredictable way, so HMAC is changing too.
Changing a vault is made intentionally against situation if attacker can rich some copy of your vault in the past.
## HOW IT WORKS:
To generate a true random seed a human input is used. Here are the algorithm of collecting a random data:
1. Run separate thread where atomic counter increments every tic from 0..255 with a very high speed.
2. Wait for unbuffered key press by human and get a scan code of pressed button.
3. Take current nanoseconds value from start of Epoch and take mod 256 to convert its value to a random byte.
4. Xor values between each other: scan-code-byte ^ current-counter-value ^ nanoseconds to produce random byte.
5. Add random byte to output vector. We suppose that only 3 bits has true randomness in this random byte. So, to get
true random 32 bytes we need ~ 32*3 button press from user input.
6 Repeat steps 2-5 until we get required amount of random bytes.
7. If we collected required amount of random data then do final step -> hash output vector with cryptographically strong
hash function GOST 3411-94 to guarantee that probability 1 and 0 bits in output vector will be 0.5.
Note, that hash function used here only to mix random bits and do not influence to the quality of random data.
So hash(random data) = random data.
Using this algorithm the msprandom collects a true 512 random bits as a seed which will be saved an a vault.
Why 512 random bits is enough?
Well, every PRNG needs a true random seed. If an attacker knows a seed then it can predict key generation and so on.
256 bits of initial random seed is far enough to keep millitary grade secrets.
I did 512 to be sure that nobody can brute force or guess the initial random seed.
So, you can freely use msprandom to seed you PRNG or SecureRandom generators.
## USAGE
1. Create new project `lein new app rand-tester`
2. Add to your project.clj the following lines:
```
:dependencies [[com.middlesphere/msprandom "0.5.2"]]
:profiles {
:dev {:dependencies [[org.bouncycastle/bcprov-jdk15on "1.52"]]}
:provided {:dependencies [[org.bouncycastle/bcprov-jdk15on "1.52"]]}}
:manifest {"Class-Path" "bcprov-jdk15on-1.52.jar"}
```
Bouncycastle library should be as a separate jar file, not inside jar.
### Create random data vault
Before you can get random numbers with good quality you should create a true random numbers and put them in a vault.
Here is the code snippet how to create true random numbers and put them to a secured vault.
```
(msprandom.core/new-vault "vault.edn" "StrongPassword12")
```
This code should be run in console mode due to unbuffered console input is used to collect random data.
Generated random data 512 bit length is encrypted with given password and HMAC is added to detect any changes.
### Get random data
To get good random data you should:
1. Load true random seed from vault.
```
(let [ seed (msprandom.core/load-vault "vault.edn" "StrongPassword12")]
(println (msprandom.crypto/bytes-to-hex seed)))
```
** Warning, call this function only 1 time at the start of the program. **
2. To produce random data call msprandom.core/gen-rand function to get random data based on seed 512 bits length.
This function generates strong random sequence of bytes using PRNG based on GOST28147-89 in CFB mode.
Here is the code snippet how to get 1000 bytes of random data.
```
(let [ seed (msprandom.core/load-vault "vault.edn" "StrongPassword12")
rand-data (msprandom.core/gen-rand seed 1000)]
(println (msprandom.crypto/bytes-to-hex rand-data)))
```
You can call msprandom.core/secure-rand as many times as you need.
** After successful reading of random data a random vault is updated to to avoid usage the same random data twice.
Strong cryptography hash function is used to derive new random data.
So, next time you load random data from a vault you will get different value of true random seed. **
## License
Copyright © 2015 by Middlepshere.
Distributed under the Eclipse Public License either version 1.0 or any later version.
|
middlesphere/msprandom
|
doc/intro.md
|
Markdown
|
epl-1.0
| 6,085 |
/*
// This software is subject to the terms of the Eclipse Public License v1.0
// Agreement, available at the following URL:
// http://www.eclipse.org/legal/epl-v10.html.
// You must accept the terms of that agreement to use this software.
//
// Copyright (C) 2002-2005 Julian Hyde
// Copyright (C) 2005-2011 Pentaho and others
// Copyright (C) 2006-2007 Cincom Systems, Inc.
// All Rights Reserved.
*/
package mondrian.gui;
import mondrian.gui.validate.ValidationUtils;
import mondrian.olap.*;
import mondrian.olap.Util.PropertyList;
import org.apache.log4j.Logger;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.util.*;
import java.util.List;
import javax.swing.*;
import javax.swing.text.DefaultEditorKit;
/**
* @author sean
*/
public class QueryPanel extends javax.swing.JPanel {
private static final Logger LOGGER = Logger.getLogger(QueryPanel.class);
Connection connection;
JMenuItem queryMenuItem;
int windowMenuIndex;
// map of schema frames and schema menu items
Map<JInternalFrame, JMenuItem> schemaWindowMap;
final Workbench workbench;
/**
* Creates new form QueryPanel
*/
public QueryPanel(Workbench workbench) {
this.workbench = workbench;
initComponents();
}
public void setConnection(Connection c) {
connection = c;
}
public Connection getConnection() {
return connection;
}
//====================================================
public void setMenuItem(JMenuItem mi) {
this.queryMenuItem = mi;
}
public void setSchemaWindowMap(
Map<JInternalFrame, JMenuItem> schemaWindowMap)
{
this.schemaWindowMap = schemaWindowMap;
setCatalogs();
}
private void setCatalogs() {
List<String> v = new ArrayList<String>();
Iterator<JMenuItem> it = schemaWindowMap.values().iterator();
while (it.hasNext()) {
JMenuItem elem = it.next();
v.add(elem.getText());
}
ComboBoxModel cCatalogs =
new DefaultComboBoxModel(new Vector<String>(v));
schemaList.setModel(cCatalogs);
}
public void setWindowMenuIndex(int i) {
this.windowMenuIndex = i;
}
/**
* @return the workbench i18n converter
*/
public I18n getResourceConverter() {
return workbench.getResourceConverter();
}
public void initConnection(String smenutext) {
schemaList.setSelectedItem(smenutext);
connectButtonActionPerformed(null);
}
//=====================================================
/**
* This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
private void initComponents() {
jScrollPane3 = new javax.swing.JScrollPane();
executeButton = new javax.swing.JButton();
jSplitPane1 = new javax.swing.JSplitPane();
jScrollPane1 = new javax.swing.JScrollPane();
queryTextPane = new javax.swing.JTextPane();
jScrollPane2 = new javax.swing.JScrollPane();
resultTextPane = new javax.swing.JTextPane();
connectButton = new javax.swing.JButton();
jPopupMenu = new JPopupMenu();
jPopupMenu.add(new DefaultEditorKit.CutAction());
jPopupMenu.add(new DefaultEditorKit.CopyAction());
jPopupMenu.add(new DefaultEditorKit.PasteAction());
schemaScrollPane1 = new javax.swing.JScrollPane();
schemaLabel = new javax.swing.JLabel();
schemaList = new JComboBox(
new String[]{
getResourceConverter().getString(
"common.join.title", "Join"),
getResourceConverter().getString(
"common.table.title", "Table")
});
//schemaScrollPane1.setViewportView(schemaList);
schemaPanel = new JPanel();
//schemaPanel.setLayout(new BorderLayout(25,0));
schemaPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 10, 0));
setLayout(new java.awt.BorderLayout());
schemaLabel.setFont(new Font("Dialog", 1, 12));
schemaLabel.setForeground(
(Color) UIManager.getDefaults().get(
"CheckBoxMenuItem.acceleratorForeground"));
schemaLabel.setHorizontalAlignment(SwingConstants.CENTER);
schemaLabel.setText(
getResourceConverter().getString(
"common.schema.title", "Schema"));
//schemaLabel.setBorder(new EtchedBorder());
schemaList.setBackground(Color.white);
final JPanel qpanel = this;
schemaList.addItemListener(
new ItemListener() {
public void itemStateChanged(ItemEvent e) {
}
});
connectButton.setText(
getResourceConverter().getString(
"queryPanel.connect.title", "Connect"));
connectButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
connectButtonActionPerformed(evt);
}
});
schemaPanel.add(schemaLabel); //java.awt.BorderLayout.WEST
schemaPanel.add(schemaList);
schemaPanel.add(connectButton);
add(schemaPanel, java.awt.BorderLayout.NORTH);
executeButton.setText(
getResourceConverter().getString(
"queryPanel.execute.title", "Execute"));
executeButton.addActionListener(
new ActionListener() {
public void actionPerformed(ActionEvent evt) {
executeButtonActionPerformed(evt);
}
});
add(executeButton, java.awt.BorderLayout.SOUTH);
jSplitPane1.setDividerLocation(100);
jSplitPane1.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);
queryTextPane.setFont(new java.awt.Font("Courier New", 0, 12));
queryTextPane.setText("");
queryTextPane.addMouseListener(
new MouseAdapter() {
// From MouseAdapter javadoc:
//
// Popup menus are triggered differently
// on different systems. Therefore, isPopupTrigger
// should be checked in both mousePressed
// and mouseReleased
// for proper cross-platform functionality.
public void mousePressed(MouseEvent e) {
checkPopupTrigger(e);
}
public void mouseReleased(MouseEvent e) {
checkPopupTrigger(e);
}
public void checkPopupTrigger(MouseEvent e) {
if (e.isPopupTrigger()) {
int x = e.getX();
int y = e.getY();
jPopupMenu.show(queryTextPane, x, y);
}
}
});
jScrollPane1.setViewportView(queryTextPane);
jSplitPane1.setTopComponent(jScrollPane1);
resultTextPane.setEditable(false);
resultTextPane.setFont(new java.awt.Font("Courier New", 0, 12));
jScrollPane2.setViewportView(resultTextPane);
jSplitPane1.setBottomComponent(jScrollPane2);
add(jSplitPane1, java.awt.BorderLayout.CENTER);
}
private void executeButtonActionPerformed(ActionEvent evt) {
//run the query, and show the results.
try {
if (connection == null) {
JOptionPane.showMessageDialog(
this, getResourceConverter().getString(
"queryPanel.noConnection.alert",
"No Mondrian connection. Select a Schema to connect."),
getResourceConverter().getString(
"common.alertDialog.title", "Alert"),
JOptionPane.WARNING_MESSAGE);
return;
} //common.alertDialog.title
Query q = connection.parseQuery(queryTextPane.getText());
Result r = connection.execute(q);
//document = DomBuilder.build(getResult());
java.io.StringWriter sw = new java.io.StringWriter();
java.io.PrintWriter pw = new java.io.PrintWriter(sw);
r.print(pw);
resultTextPane.setText(sw.getBuffer().toString());
} catch (Exception ex) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
PrintStream p = new PrintStream(os);
Throwable e = ex;
while (e != null) {
p.println(e.getLocalizedMessage());
LOGGER.error("", e);
Throwable prev = e;
e = e.getCause();
if (e == prev) {
break;
}
p.println();
}
resultTextPane.setText(os.toString());
}
}
private void connectButtonActionPerformed(ActionEvent evt) {
File sfile = null;
try {
String sfname = (String) schemaList.getSelectedItem();
JInternalFrame sf = lookupFrame(sfname);
if (sf == null) {
// this case may arise when a schema file is opened, mdx query
// is opened and the schema frame is closed
JOptionPane.showMessageDialog(
this, getResourceConverter().getString(
"queryPanel.schemaNotOpen.alert",
"Schema file is not open"),
getResourceConverter().getString(
"common.errorDialog.title", "Error"),
JOptionPane.ERROR_MESSAGE);
return;
}
SchemaExplorer se =
(SchemaExplorer) sf.getContentPane().getComponent(0);
if (se.isNewFile()) {
JOptionPane.showMessageDialog(
this,
getResourceConverter().getString(
"queryPanel.saveSchemaFirst.alert",
"You must first save the Schema to open a Mondrian connection"),
getResourceConverter().getString(
"common.alertDialog.title", "Alert"),
JOptionPane.WARNING_MESSAGE);
sf.setSelected(true);
return;
}
sfile = se.getSchemaFile();
PropertyList list = new PropertyList();
list.put("Provider", "mondrian");
list.put("Jdbc", se.getJdbcConnectionUrl());
list.put("Catalog", se.getSchemaFile().toURL().toString());
final String jdbcUsername = se.getJdbcUsername();
if (!ValidationUtils.isEmpty(jdbcUsername)) {
list.put("JdbcUser", jdbcUsername);
}
final String jdbcPassword = se.getJdbcPassword();
if (!ValidationUtils.isEmpty(jdbcPassword)) {
list.put("JdbcPassword", jdbcPassword);
}
Connection con = DriverManager.getConnection(list, null);
// clear cache before connecting
con.getCacheControl(null).flushSchemaCache();
if (con != null) {
connection = con;
queryMenuItem.setText(
getResourceConverter().getFormattedString(
"queryPanel.successfulConnection.menuItem",
"{0} MDX - {1}",
Integer.toString(windowMenuIndex),
se.getSchemaFile().getName()));
Component o = this;
while (o != null) {
if (o.getClass() == JInternalFrame.class) {
((JInternalFrame) o).setTitle(
getResourceConverter().getFormattedString(
"queryPanel.successfulConnection.internalFrame.title",
"MDX Query - connected to {0}",
se.getSchemaFile().getName()));
break;
}
o = o.getParent();
}
JOptionPane.showMessageDialog(
this,
"Mondrian connection Successful.",
getResourceConverter().getString(
"common.informationDialog.title", "Information"),
JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(
this,
getResourceConverter().getFormattedString(
"queryPanel.unsuccessfulConnection.alert",
"Mondrian connection could not be done for - {0}",
se.getSchemaFile().getName()),
getResourceConverter().getString(
"common.errorDialog.title", "Error"),
JOptionPane.ERROR_MESSAGE);
}
} catch (Exception ex) {
LOGGER.error("Exception: " + ex.getMessage(), ex);
JOptionPane.showMessageDialog(
this,
getResourceConverter().getFormattedString(
"queryPanel.unsuccessfulConnection.exception",
"Mondrian connection could not be done for - {0}",
sfile == null
? getResourceConverter().getString(
"queryPanel.selectedSchema.alert",
"selected Schema")
: sfile.getName()),
getResourceConverter().getString(
"common.errorDialog.title", "Error"),
JOptionPane.ERROR_MESSAGE);
resultTextPane.setText(getResourceConverter().getFormattedString(
"queryPanel.exceptionMessage",
"Exception: {0}\n\nSee workbench log for full stacktrace.",
ex.getMessage()));
}
}
private JInternalFrame lookupFrame(String sfname) {
JInternalFrame sf = null;
for (Map.Entry<JInternalFrame, JMenuItem> entry
: schemaWindowMap.entrySet())
{
if ((entry.getValue()).getText().equals(sfname)) {
sf = entry.getKey();
break;
}
}
return sf;
}
// Variables declaration - do not modify
private javax.swing.JScrollPane jScrollPane3;
private javax.swing.JScrollPane jScrollPane2;
private javax.swing.JTextPane resultTextPane;
private javax.swing.JScrollPane jScrollPane1;
private javax.swing.JTextPane queryTextPane;
private javax.swing.JSplitPane jSplitPane1;
private javax.swing.JButton executeButton;
private javax.swing.JComboBox schemaList;
private JLabel schemaLabel;
private JPanel schemaPanel;
private javax.swing.JScrollPane schemaScrollPane1;
private javax.swing.JButton connectButton;
private JPopupMenu jPopupMenu;
// End of variables declaration
}
// End QueryPanel.java
|
rfellows/mondrian
|
src/main/mondrian/gui/QueryPanel.java
|
Java
|
epl-1.0
| 15,220 |
/**
* Copyright (c) 2010-2021 Contributors to the openHAB project
*
* See the NOTICE file(s) distributed with this work for additional
* information.
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0
*
* SPDX-License-Identifier: EPL-2.0
*/
package org.openhab.binding.opengarage.internal;
import java.io.IOException;
import org.openhab.binding.opengarage.internal.api.ControllerVariables;
import org.openhab.binding.opengarage.internal.api.Enums.OpenGarageCommand;
import org.openhab.core.io.net.http.HttpUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Handles performing the actual HTTP requests for communicating with Opengarage units.
*
* @author Paul Smedley - Initial Contribution
*
*/
public class OpenGarageWebTargets {
private static final int TIMEOUT_MS = 30000;
private String getControllerVariablesUri;
private String changeControllerVariablesUri;
private final Logger logger = LoggerFactory.getLogger(OpenGarageWebTargets.class);
public OpenGarageWebTargets(String ipAddress, long port, String password) {
String baseUri = "http://" + ipAddress + ":" + port + "/";
getControllerVariablesUri = baseUri + "jc";
changeControllerVariablesUri = baseUri + "cc?dkey=" + password;
}
public ControllerVariables getControllerVariables() throws OpenGarageCommunicationException {
String response = invoke(getControllerVariablesUri);
return ControllerVariables.parse(response);
}
public void setControllerVariables(OpenGarageCommand request) throws OpenGarageCommunicationException {
logger.debug("Received request: {}", request);
String queryParams = null;
switch (request) {
case OPEN:
queryParams = "&open=1";
break;
case CLOSE:
queryParams = "&close=1";
break;
case CLICK:
queryParams = "&click=1";
break;
}
if (queryParams != null) {
invoke(changeControllerVariablesUri, queryParams);
}
}
private String invoke(String uri) throws OpenGarageCommunicationException {
return invoke(uri, "");
}
private String invoke(String uri, String params) throws OpenGarageCommunicationException {
String uriWithParams = uri + params;
logger.debug("Calling url: {}", uriWithParams);
String response;
synchronized (this) {
try {
response = HttpUtil.executeUrl("GET", uriWithParams, TIMEOUT_MS);
} catch (IOException ex) {
logger.debug("{}", ex.getLocalizedMessage(), ex);
// Response will also be set to null if parsing in executeUrl fails so we use null here to make the
// error check below consistent.
response = null;
}
}
if (response == null) {
throw new OpenGarageCommunicationException(
String.format("OpenGaragecontroller returned error while invoking %s", uriWithParams));
}
return response;
}
}
|
paulianttila/openhab2
|
bundles/org.openhab.binding.opengarage/src/main/java/org/openhab/binding/opengarage/internal/OpenGarageWebTargets.java
|
Java
|
epl-1.0
| 3,278 |
/*******************************************************************************
* Copyright (c) 2015 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
/*
* Some of the code was derived from code supplied by the Apache Software Foundation licensed under the Apache License, Version 2.0.
*/
package com.ibm.ws.transport.iiop.security.config.css;
import javax.security.auth.Subject;
import org.omg.CSIIOP.EstablishTrustInClient;
import org.omg.IOP.Codec;
import org.omg.PortableInterceptor.ClientRequestInfo;
import com.ibm.websphere.crypto.PasswordUtil;
import com.ibm.websphere.ras.Tr;
import com.ibm.websphere.ras.TraceComponent;
import com.ibm.websphere.ras.annotation.Sensitive;
import com.ibm.websphere.ras.annotation.Trivial;
import com.ibm.websphere.security.cred.WSCredential;
import com.ibm.ws.security.authentication.utility.SubjectHelper;
import com.ibm.ws.security.context.SubjectManager;
import com.ibm.ws.transport.iiop.security.config.tss.TSSASMechConfig;
import com.ibm.ws.transport.iiop.security.config.tss.TSSGSSUPMechConfig;
import com.ibm.ws.transport.iiop.security.util.Util;
import com.ibm.wsspi.kernel.service.utils.SerializableProtectedString;
/**
* This GSSUP mechanism obtains its username and password from a named username
* password credential that is stored in the subject associated w/ the call
* stack.
*
* @version $Revision: 503493 $ $Date: 2007-02-04 13:47:55 -0800 (Sun, 04 Feb 2007) $
*/
public class CSSGSSUPMechConfigDynamic implements CSSASMechConfig {
private static TraceComponent tc = Tr.register(CSSGSSUPMechConfigDynamic.class);
private final String mechanism = "GSSUP";
private final String domain;
private final boolean required;
private final String username;
private final SerializableProtectedString password;
/* ctor for the client */
public CSSGSSUPMechConfigDynamic(String username, SerializableProtectedString password, String domain, boolean required) {
this.username = username;
this.password = password;
this.domain = domain;
this.required = required;
}
/* ctor for the server */
public CSSGSSUPMechConfigDynamic(String domain, boolean required) {
this.username = null;
this.password = null;
this.domain = domain;
this.required = required;
}
public CSSGSSUPMechConfigDynamic(String domain) {
this.username = null;
this.password = null;
this.domain = domain;
required = false;
}
@Override
public short getSupports() {
return EstablishTrustInClient.value;
}
@Override
public short getRequires() {
return (required ? EstablishTrustInClient.value : 0);
}
@Override
public boolean canHandle(TSSASMechConfig asMech) {
// We can handle if the server mechanism is also GSSUP or if the server authentication layer is not required and we do not require authentication.
if (asMech instanceof TSSGSSUPMechConfig || (asMech.getRequires() == 0 && (required == false))) {
return true;
}
return false;
}
@Override
public String getMechanism() {
return mechanism;
}
@Sensitive
@Override
public byte[] encode(TSSASMechConfig tssasMechConfig, CSSSASMechConfig sas_mech, ClientRequestInfo ri, Codec codec) {
byte[] encoding = null;
if (tssasMechConfig instanceof TSSGSSUPMechConfig) {
String targetName = ((TSSGSSUPMechConfig) tssasMechConfig).getTargetName();
if (sas_mech.isAsserting()) {
encoding = encodeGSSUPFromTrustedIdAndPassword(sas_mech, codec, targetName);
} else {
encoding = encodeGSSUPFromBasicAuthSubject(codec, targetName);
}
}
if (encoding == null) {
encoding = new byte[0];
}
return encoding;
}
@Sensitive
private byte[] encodeGSSUPFromTrustedIdAndPassword(CSSSASMechConfig sas_mech, Codec codec, String targetName) {
byte[] encoding = new byte[0];
String trustedIdentity = sas_mech.getTrustedIdentity();
SerializableProtectedString trustedPassword = sas_mech.getTrustedPassword();
if (trustedIdentity != null && (trustedPassword != null && trustedPassword.isEmpty() == false)) {
String password = PasswordUtil.passwordDecode(new String(trustedPassword.getChars()));
encoding = commonEncode(codec, trustedIdentity, password, targetName);
}
return encoding;
}
@Sensitive
private byte[] encodeGSSUPFromBasicAuthSubject(Codec codec, String targetName) {
byte[] encoding = new byte[0];
Subject subject = getSubject();
SubjectHelper subjectHelper = new SubjectHelper();
WSCredential wsCredential = null;
if (subject != null) {
wsCredential = subjectHelper.getWSCredential(subject);
}
// There must be a WSCredential in the subject, but check for null to satisfy findbugs
if (wsCredential != null && wsCredential.isBasicAuth()) {
try {
encoding = commonEncode(codec, wsCredential.getSecurityName(), new String(wsCredential.getCredentialToken(), "UTF-8"), targetName);
} catch (Exception e) {
// This should never happen since a basic auth credential never expires and it is never in a destroyed state, but this exception needs to be caught.
if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
Tr.debug(tc, "The GSSUP token could not be encoded because of exception with message: " + e.getMessage());
}
}
} else if (password != null && !password.isEmpty() && username != null && !username.isEmpty()) {
// fallback to the default.
String scopedUserName = Util.buildScopedUserName(username, targetName);
String pwd = PasswordUtil.passwordDecode(new String(password.getChars()));
encoding = Util.encodeGSSUPToken(codec, scopedUserName, pwd.toCharArray(), targetName);
}
return encoding;
}
private Subject getSubject() {
SubjectManager subjectManager = new SubjectManager();
Subject subject = subjectManager.getInvocationSubject();
if (subject == null) {
subject = subjectManager.getCallerSubject();
}
return subject;
}
@Sensitive
private byte[] commonEncode(Codec codec, String username, @Sensitive String password, String targetName) {
String extendedUserName = Util.buildScopedUserName(username, targetName);
return Util.encodeGSSUPToken(codec, extendedUserName, password.toCharArray(), targetName);
}
@Override
@Trivial
public String toString() {
StringBuilder buf = new StringBuilder();
toString("", buf);
return buf.toString();
}
@Override
@Trivial
public void toString(String spaces, StringBuilder buf) {
String moreSpaces = spaces + " ";
buf.append(spaces).append("CSSGSSUPMechConfigDynamic: [\n");
buf.append(moreSpaces).append("domain: ").append(domain).append("\n");
if (username != null) {
buf.append(moreSpaces).append("user: ").append(username).append("\n");
}
buf.append(spaces).append("]\n");
}
}
|
kgibm/open-liberty
|
dev/com.ibm.ws.security.csiv2.common/src/com/ibm/ws/transport/iiop/security/config/css/CSSGSSUPMechConfigDynamic.java
|
Java
|
epl-1.0
| 7,786 |
/**
* Copyright 2016 Red Hat, Inc. and/or its affiliates.
*
* Licensed under the Eclipse Public License version 1.0, available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.jboss.forge.addon.javaee.faces.ui.setup;
import javax.inject.Inject;
import org.jboss.arquillian.container.test.api.Deployment;
import org.jboss.arquillian.junit.Arquillian;
import org.jboss.forge.addon.facets.FacetFactory;
import org.jboss.forge.addon.javaee.faces.FacesFacet;
import org.jboss.forge.addon.javaee.faces.ui.FacesSetupWizard;
import org.jboss.forge.addon.javaee.servlet.ServletFacet;
import org.jboss.forge.addon.javaee.servlet.ServletFacet_3_1;
import org.jboss.forge.addon.projects.Project;
import org.jboss.forge.addon.projects.ProjectFactory;
import org.jboss.forge.addon.projects.Projects;
import org.jboss.forge.addon.ui.controller.CommandController;
import org.jboss.forge.addon.ui.result.Failed;
import org.jboss.forge.addon.ui.result.Result;
import org.jboss.forge.addon.ui.test.UITestHarness;
import org.jboss.forge.addon.ui.util.Selections;
import org.jboss.forge.arquillian.AddonDependencies;
import org.jboss.forge.arquillian.AddonDependency;
import org.jboss.forge.arquillian.archive.AddonArchive;
import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
@RunWith(Arquillian.class)
public class FacesSetupWizardTest
{
@Deployment
@AddonDependencies({
@AddonDependency(name = "org.jboss.forge.addon:ui-test-harness"),
@AddonDependency(name = "org.jboss.forge.addon:javaee"),
@AddonDependency(name = "org.jboss.forge.addon:maven"),
@AddonDependency(name = "org.jboss.forge.furnace.container:cdi")
})
public static AddonArchive getDeployment()
{
return ShrinkWrap.create(AddonArchive.class).addBeansXML();
}
@Inject
private FacetFactory facetFactory;
@Inject
private ProjectFactory projectFactory;
@Inject
private UITestHarness uiTestHarness;
@SuppressWarnings("unchecked")
@Test
public void testSetupCreatesFacesConfigXML() throws Exception
{
Project project = projectFactory.createTempProject();
facetFactory.install(project, ServletFacet_3_1.class);
try (CommandController tester = uiTestHarness.createCommandController(FacesSetupWizard.class,
project.getRoot()))
{
tester.initialize();
Assert.assertTrue(tester.isValid());
Result result = tester.execute();
project = Projects.getSelectedProject(projectFactory, Selections.from(project.getRoot()));
Assert.assertFalse(result instanceof Failed);
Assert.assertTrue(project.hasFacet(FacesFacet.class));
Assert.assertTrue(project.getFacet(FacesFacet.class).getConfigFile().exists());
Assert.assertTrue(project.getFacet(ServletFacet.class).getWebInfDirectory().exists());
Assert.assertTrue(project.getFacet(ServletFacet.class).getWebInfDirectory().getChild("faces-config.xml")
.exists());
}
}
}
|
jerr/jbossforge-core
|
javaee/tests/src/test/java/org/jboss/forge/addon/javaee/faces/ui/setup/FacesSetupWizardTest.java
|
Java
|
epl-1.0
| 3,088 |
###########################################################
#
# Copyright (c) 2005, Southpaw Technology
# All Rights Reserved
#
# PROPRIETARY INFORMATION. This software is proprietary to
# Southpaw Technology, and is not to be reproduced, transmitted,
# or disclosed in any way without written permission.
#
#
#
import tacticenv
from pyasm.security import *
from pyasm.command import *
from sql import *
from search import *
import unittest
class TestCmd(Command):
def __init__(self, sobject):
self.sobject = sobject
def execute(self):
self.sobject.set_value("description", "whatever2")
self.sobject.commit()
self.description = "changed description to 'whatever'"
class SearchTest(unittest.TestCase):
def setUp(self):
Batch()
def test_all(self):
self._test_search_type()
def _test_search_type(self):
'''tests search type as an object'''
# set the template and instantiate
SearchType.set_global_template("prod", "prod2")
search_type = SearchType.get("prod/template")
# now switch the template
SObjectFactory.set_template("prod", "prod")
search_type2 = SearchType.get("prod/template")
print(search_type.get_base_key())
print(search_type.get_full_key())
self.assertEquals("prod/template", search_type.get_base_key())
self.assertEquals("prod/template?prod=prod2",search_type.get_full_key())
search = Search(search_type)
sobjects = search.do_search()
sobject = sobjects[0]
cmd = TestCmd(sobject)
Command.execute_cmd(cmd)
if __name__ == "__main__":
unittest.main()
|
diegocortassa/TACTIC
|
src/pyasm/search/search_template_test.py
|
Python
|
epl-1.0
| 1,722 |
package com.kale.floatbar.util;
import com.kale.floatbar.service.DrawService;
import android.accessibilityservice.AccessibilityService;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;
/**
* @author:Jack Tony
* @tips :这里是得到设置好的数据的工具类,之所以只有get方法,没有set方法。是因为set方法在preference控件中进行了设置
* @date :2014-10-8
*/
public class Prefs {
private Context mContext;
private static SharedPreferences sharedPreferences;
private String preferencesName = "com.kale.floatbar_preferences";
public Prefs(Context mContext) {
this.mContext = mContext;
sharedPreferences = mContext.getSharedPreferences(preferencesName, Context.MODE_PRIVATE);
}
/**
* 设置是否是第一次打开,如果是第一次那么就展示没有开启辅助功能
*
* @param isFirstTime
*/
public void setIsFirstTime(boolean isFirstTime) {
sharedPreferences.edit().putBoolean("isFristTime", isFirstTime);
}
public boolean isFirstTime() {
return sharedPreferences.getBoolean("isFristTime", false);
}
/**
* 悬浮窗是否打开了,如果打开了就可用
*
* @return
*/
public boolean isEnabled() {
return sharedPreferences.getBoolean("enabled", true);
}
/**
* 清除所有设置数据
*/
public void clearPrefs() {
sharedPreferences.edit().clear().commit();
Toast.makeText(mContext, "已恢复到默认设置", 0).show();
}
// //////////////////////////////////////////////////////////////////////
/**
* 得到悬浮窗的color颜色
*
* @return
*/
public int getColor() {
String color = sharedPreferences.getString("color", "green");
int colorInt = 0xff000000;
if (color.equals("black")) {
colorInt = 0xff000000;
} else if (color.equals("white")) {
colorInt = 0xffffffff;
} else if (color.equals("blue")) {
colorInt = 0xff6dcaec;
} else if (color.equals("green")) {
colorInt = 0xffb9e3d9;
} else if (color.equals("red")) {
colorInt = 0xffff7979;
} else if (color.equals("orange")) {
colorInt = 0xffffd060;
}
return colorInt;
}
/**
* 得到透明度
*
* @return
*/
public int getAlpha() {
return sharedPreferences.getInt("alpha", 200);
}
/**
* 设置有无点击反馈
*
* @return
*/
public boolean isFeedback() {
return sharedPreferences.getBoolean("feedback", true);
}
// /////////////////////////////下面是后台任务抽屉的设置//////////////////////////////////////
/**
* @return 是不是右手模式
*/
public boolean isRightMode() {
return sharedPreferences.getBoolean("rightMode", true);
}
/**
* @return 得到悬浮条宽度
*/
public int getWidth() {
return sharedPreferences.getInt("width", 30);
}
/**
* @return 得到悬浮条高度
*/
public int getHeight() {
return sharedPreferences.getInt("height", 200);
}
/**
* @return 得到悬浮条位置
*/
public int getDistance() {
return sharedPreferences.getInt("distance", 200);
}
// /////////////////////////////////////////////////////////////////////////
public void doSwipUp(AccessibilityService service) {
String swip = sharedPreferences.getString("swipUp", "closeBar");
doOperation(service, swip);
/*
* String activity = Util.getRunningActivityName(service);
* System.out.println(activity); Toast.makeText(mContext, activity,
* 1).show();
*/
}
public void doSwipDown(AccessibilityService service) {
String swip = sharedPreferences.getString("swipDown", "openBar");
doOperation(service, swip);
}
public void doSwipLeft(AccessibilityService service) {
String swip = sharedPreferences.getString("swipLeft", "openDraw");
doOperation(service, swip);
}
public void doSwipRight(AccessibilityService service) {
String swip = sharedPreferences.getString("swipRight", "openDraw");
doOperation(service, swip);
}
public void doTouch(AccessibilityService service) {
String event = sharedPreferences.getString("onTouch", "nothing");
doOperation(service, event);
}
public void doDoubleClick(AccessibilityService service) {
String event = sharedPreferences.getString("doubleClick", "back");
doOperation(service, event);
}
public void doLongClick(AccessibilityService service) {
String event = sharedPreferences.getString("longClick", "home");
doOperation(service, event);
}
/**
* 执行操作的方法,根据传来的不同值执行不同的操作
*
* @param service
* @param event
*/
private void doOperation(AccessibilityService service, String event) {
if (event.equals("openBar")) {
Util.openStatusBar(mContext);
} else if (event.equals("closeBar")) {
Util.closeStatusBar(mContext);
} else if (event.equals("openDraw")) {
mContext.startService(new Intent(mContext, DrawService.class));
} else if (event.equals("recents")) {
Util.recentApps(service);
} else if (event.equals("back")) {
Util.virtualBack(service);
} else if (event.equals("home")) {
Util.virtualHome(mContext);
} else if (event.equals("camera")) {
Util.openCamera(mContext);
}
}
// /////////////////////////////////////////////////////////////////////
public boolean getDrawMode() {
return sharedPreferences.getBoolean("drawMode", false);
}
public int getDrawColor() {
String color = sharedPreferences.getString("drawColor", "black");
int colorInt = 0xff000000;
if (color.equals("black")) {
colorInt = 0xff000000;
} else if (color.equals("white")) {
colorInt = 0xffffffff;
} else if (color.equals("blue")) {
colorInt = 0xff6dcaec;
} else if (color.equals("green")) {
colorInt = 0xffb6db49;
} else if (color.equals("red")) {
colorInt = 0xffff7979;
} else if (color.equals("orange")) {
colorInt = 0xffffd060;
}
return colorInt;
}
public int getDrawAlpha() {
int alpha = sharedPreferences.getInt("drawAlpha", 120);
return alpha;
}
public int getDrawTextColor() {
String color = sharedPreferences.getString("drawTextColor", "white");
return color.equals("white") ? 0xFFFFFFFF : 0xFF000000;
}
}
|
vivian8725118/Float-Bar
|
FloatBar/src/com/kale/floatbar/util/Prefs.java
|
Java
|
epl-1.0
| 6,112 |
body {
font-family: monospace;
}
|
doctorwidget/volta
|
resources/public/css/volta_home.css
|
CSS
|
epl-1.0
| 34 |
/**
* Copyright (c) 2015 Bosch Software Innovations GmbH and others.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package org.eclipse.hawkbit.repository.jpa;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.validation.ConstraintViolationException;
import org.assertj.core.api.Assertions;
import org.eclipse.hawkbit.repository.ActionStatusFields;
import org.eclipse.hawkbit.repository.DeploymentManagement;
import org.eclipse.hawkbit.repository.event.remote.MultiActionAssignEvent;
import org.eclipse.hawkbit.repository.event.remote.MultiActionCancelEvent;
import org.eclipse.hawkbit.repository.event.remote.TargetAssignDistributionSetEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.ActionCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.ActionUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.CancelTargetAssignmentEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.DistributionSetUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.SoftwareModuleCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TargetUpdatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TenantConfigurationCreatedEvent;
import org.eclipse.hawkbit.repository.event.remote.entity.TenantConfigurationUpdatedEvent;
import org.eclipse.hawkbit.repository.exception.AssignmentQuotaExceededException;
import org.eclipse.hawkbit.repository.exception.EntityNotFoundException;
import org.eclipse.hawkbit.repository.exception.ForceQuitActionNotAllowedException;
import org.eclipse.hawkbit.repository.exception.IncompatibleTargetTypeException;
import org.eclipse.hawkbit.repository.exception.IncompleteDistributionSetException;
import org.eclipse.hawkbit.repository.exception.InvalidDistributionSetException;
import org.eclipse.hawkbit.repository.exception.MultiAssignmentIsNotEnabledException;
import org.eclipse.hawkbit.repository.jpa.configuration.Constants;
import org.eclipse.hawkbit.repository.jpa.model.JpaAction;
import org.eclipse.hawkbit.repository.jpa.model.JpaActionStatus;
import org.eclipse.hawkbit.repository.jpa.model.JpaDistributionSet;
import org.eclipse.hawkbit.repository.jpa.model.JpaTarget;
import org.eclipse.hawkbit.repository.jpa.specifications.DistributionSetSpecification;
import org.eclipse.hawkbit.repository.jpa.specifications.SpecificationsBuilder;
import org.eclipse.hawkbit.repository.model.Action;
import org.eclipse.hawkbit.repository.model.Action.ActionType;
import org.eclipse.hawkbit.repository.model.Action.Status;
import org.eclipse.hawkbit.repository.model.ActionStatus;
import org.eclipse.hawkbit.repository.model.DeploymentRequest;
import org.eclipse.hawkbit.repository.model.DistributionSet;
import org.eclipse.hawkbit.repository.model.DistributionSetAssignmentResult;
import org.eclipse.hawkbit.repository.model.DistributionSetTag;
import org.eclipse.hawkbit.repository.model.DistributionSetType;
import org.eclipse.hawkbit.repository.model.SoftwareModule;
import org.eclipse.hawkbit.repository.model.Target;
import org.eclipse.hawkbit.repository.model.TargetType;
import org.eclipse.hawkbit.repository.model.TargetUpdateStatus;
import org.eclipse.hawkbit.repository.test.matcher.Expect;
import org.eclipse.hawkbit.repository.test.matcher.ExpectEvents;
import org.eclipse.hawkbit.tenancy.configuration.TenantConfigurationProperties.TenantConfigurationKey;
import org.junit.jupiter.api.Test;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Slice;
import org.springframework.data.domain.Sort.Direction;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import io.qameta.allure.Description;
import io.qameta.allure.Feature;
import io.qameta.allure.Story;
/**
* Test class testing the functionality of triggering a deployment of
* {@link DistributionSet}s to {@link Target}s.
*
*/
@Feature("Component Tests - Repository")
@Story("Deployment Management")
class DeploymentManagementTest extends AbstractJpaIntegrationTest {
private static final boolean STATE_ACTIVE = true;
private static final boolean STATE_INACTIVE = false;
@Test
@Description("Verifies that management get access react as specified on calls for non existing entities by means "
+ "of Optional not present.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 0) })
void nonExistingEntityAccessReturnsNotPresent() {
assertThat(deploymentManagement.findAction(1234L)).isNotPresent();
assertThat(deploymentManagement.findActionWithDetails(NOT_EXIST_IDL)).isNotPresent();
}
@Test
@Description("Verifies that management queries react as specified on calls for non existing entities "
+ " by means of throwing EntityNotFoundException.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1) })
void entityQueriesReferringToNotExistingEntitiesThrowsException() {
final Target target = testdataFactory.createTarget();
final String dsName = "DistributionSet";
verifyThrownExceptionBy(() -> assignDistributionSet(NOT_EXIST_IDL, target.getControllerId()), dsName);
verifyThrownExceptionBy(() -> deploymentManagement.cancelAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget(NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.countActionsByTarget("xxx", NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByDistributionSet(PAGE, NOT_EXIST_IDL),
"DistributionSet");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget(NOT_EXIST_ID, PAGE), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActionsByTarget("id==*", NOT_EXIST_ID, PAGE), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findActiveActionsByTarget(PAGE, NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.findInActiveActionsByTarget(PAGE, NOT_EXIST_ID), "Target");
verifyThrownExceptionBy(() -> deploymentManagement.forceQuitAction(NOT_EXIST_IDL), "Action");
verifyThrownExceptionBy(() -> deploymentManagement.forceTargetAction(NOT_EXIST_IDL), "Action");
}
@Test
@Description("Test verifies that the repistory retrieves the action including all defined (lazy) details.")
void findActionWithLazyDetails() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0",
new ArrayList<DistributionSetTag>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
final Action action = deploymentManagement.findActionWithDetails(actionId).get();
assertThat(action.getDistributionSet()).as("DistributionSet in action").isNotNull();
assertThat(action.getTarget()).as("Target in action").isNotNull();
assertThat(deploymentManagement.getAssignedDistributionSet(action.getTarget().getControllerId()).get())
.as("AssignedDistributionSet of target in action").isNotNull();
}
@Test
@Description("Test verifies that actions of a target are found by using id-based search.")
void findActionByTargetId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0",
new ArrayList<DistributionSetTag>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
// act
final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
PAGE);
final Long count = deploymentManagement.countActionsByTarget(testTarget.get(0).getControllerId());
assertThat(count).as("One Action for target").isEqualTo(1L).isEqualTo(actions.getContent().size());
assertThat(actions.getContent().get(0).getId()).as("Action of target").isEqualTo(actionId);
}
@Test
@Description("Test verifies that the 'max actions per target' quota is enforced.")
void assertMaxActionsPerTargetQuotaIsEnforced() {
final int maxActions = quotaManagement.getMaxActionsPerTarget();
final Target testTarget = testdataFactory.createTarget();
final DistributionSet ds1 = testdataFactory.createDistributionSet("ds1");
enableMultiAssignments();
for (int i = 0; i < maxActions; i++) {
deploymentManagement.offlineAssignedDistributionSets(Collections
.singletonList(new SimpleEntry<String, Long>(testTarget.getControllerId(), ds1.getId())));
}
assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> assignDistributionSet(ds1.getId(), testTarget.getControllerId(), 77));
}
@Test
@Description("An assignment request with more assignments than allowed by 'maxTargetDistributionSetAssignmentsPerManualAssignment' quota throws an exception.")
void assignmentRequestThatIsTooLarge() {
final int maxActions = quotaManagement.getMaxTargetDistributionSetAssignmentsPerManualAssignment();
final DistributionSet ds1 = testdataFactory.createDistributionSet("1");
final DistributionSet ds2 = testdataFactory.createDistributionSet("2");
final List<Target> targets = testdataFactory.createTargets(maxActions, "assignmentTest1");
assignDistributionSet(ds1, targets);
targets.add(testdataFactory.createTarget("assignmentTest2"));
assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> assignDistributionSet(ds2, targets));
}
@Test
@Description("Test verifies that action-states of an action are found by using id-based search.")
void findActionStatusByActionId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0", Collections.emptyList());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
final Slice<Action> actions = deploymentManagement.findActionsByTarget(testTarget.get(0).getControllerId(),
PAGE);
final ActionStatus expectedActionStatus = ((JpaAction) actions.getContent().get(0)).getActionStatus().get(0);
// act
final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);
assertThat(actionStates.getContent()).hasSize(1);
assertThat(actionStates.getContent().get(0)).as("Action-status of action").isEqualTo(expectedActionStatus);
}
@Test
@Description("Test verifies that messages of an action-status are found by using id-based search.")
void findMessagesByActionStatusId() {
final DistributionSet testDs = testdataFactory.createDistributionSet("TestDs", "1.0",
new ArrayList<DistributionSetTag>());
final List<Target> testTarget = testdataFactory.createTargets(1);
// one action with one action status is generated
final Long actionId = getFirstAssignedActionId(assignDistributionSet(testDs, testTarget));
// create action-status entry with one message
controllerManagement.addUpdateActionStatus(entityFactory.actionStatus().create(actionId)
.status(Action.Status.FINISHED).messages(Collections.singletonList("finished message")));
final Page<ActionStatus> actionStates = deploymentManagement.findActionStatusByAction(PAGE, actionId);
// find newly created action-status entry with message
final JpaActionStatus actionStatusWithMessage = actionStates.getContent().stream().map(c -> (JpaActionStatus) c)
.filter(entry -> entry.getMessages() != null && entry.getMessages().size() > 0).findFirst().get();
final String expectedMsg = actionStatusWithMessage.getMessages().get(0);
// act
final Page<String> messages = deploymentManagement.findMessagesByActionStatusId(PAGE,
actionStatusWithMessage.getId());
assertThat(actionStates.getTotalElements()).as("Two action-states in total").isEqualTo(2L);
assertThat(messages.getContent().get(0)).as("Message of action-status").isEqualTo(expectedMsg);
}
@Test
@Description("Ensures that tag to distribution set assignment that does not exist will cause EntityNotFoundException.")
void assignDistributionSetToTagThatDoesNotExistThrowsException() {
final List<Long> assignDS = Lists.newArrayListWithExpectedSize(5);
for (int i = 0; i < 4; i++) {
assignDS.add(testdataFactory.createDistributionSet("DS" + i, "1.0", Collections.emptyList()).getId());
}
// not exists
assignDS.add(100L);
final DistributionSetTag tag = distributionSetTagManagement.create(entityFactory.tag().create().name("Tag1"));
assertThatExceptionOfType(EntityNotFoundException.class)
.isThrownBy(() -> distributionSetManagement.assignTag(assignDS, tag.getId()))
.withMessageContaining("DistributionSet").withMessageContaining(String.valueOf(100L));
}
@Test
@Description("Test verifies that an assignment with automatic cancelation works correctly even if the update is split into multiple partitions on the database.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 20),
@Expect(type = TargetUpdatedEvent.class, count = 40),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 2),
@Expect(type = ActionCreatedEvent.class, count = 40),
@Expect(type = CancelTargetAssignmentEvent.class, count = 20),
@Expect(type = ActionUpdatedEvent.class, count = 20),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6) })
void multiAssigmentHistoryOverMultiplePagesResultsInTwoActiveAction() {
final DistributionSet cancelDs = testdataFactory.createDistributionSet("Canceled DS", "1.0",
Collections.emptyList());
final DistributionSet cancelDs2 = testdataFactory.createDistributionSet("Canceled DS", "1.2",
Collections.emptyList());
final List<Target> targets = testdataFactory.createTargets(quotaManagement.getMaxTargetsPerAutoAssignment());
assertThat(deploymentManagement.countActionsAll()).isZero();
assignDistributionSet(cancelDs, targets).getAssignedEntity();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(quotaManagement.getMaxTargetsPerAutoAssignment());
assignDistributionSet(cancelDs2, targets).getAssignedEntity();
assertThat(deploymentManagement.countActionsAll()).isEqualTo(2L * quotaManagement.getMaxTargetsPerAutoAssignment());
}
@Test
@Description("Cancels multiple active actions on a target. Expected behaviour is that with two active "
+ "actions after canceling the second active action the first one is still running as it is not touched by the cancelation. After canceling the first one "
+ "also the target goes back to IN_SYNC as no open action is left.")
void manualCancelWithMultipleAssignmentsCancelLastOneFirst() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
final DistributionSet dsFirst = testdataFactory.createDistributionSet("", true);
final DistributionSet dsSecond = testdataFactory.createDistributionSet("2", true);
final DistributionSet dsInstalled = action.getDistributionSet();
// check initial status
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("target has update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
// assign the two sets in a row
JpaAction firstAction = assignSet(target, dsFirst);
JpaAction secondAction = assignSet(target, dsSecond);
assertThat(actionRepository.findAll()).as("wrong size of actions").hasSize(3);
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(5);
// we cancel second -> back to first
deploymentManagement.cancelAction(secondAction.getId());
secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()).get();
// confirm cancellation
controllerManagement.addCancelActionStatus(
entityFactory.actionStatus().create(secondAction.getId()).status(Status.CANCELED));
assertThat(actionStatusRepository.findAll()).as("wrong size of actions status").hasSize(7);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong ds").contains(dsFirst);
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong update status")
.isEqualTo(TargetUpdateStatus.PENDING);
// we cancel first -> back to installed
deploymentManagement.cancelAction(firstAction.getId());
firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()).get();
// confirm cancellation
controllerManagement.addCancelActionStatus(
entityFactory.actionStatus().create(firstAction.getId()).status(Status.CANCELED));
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(9);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds")
.contains(dsInstalled);
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@Test
@Description("Cancels multiple active actions on a target. Expected behaviour is that with two active "
+ "actions after canceling the first active action the system switched to second one. After canceling this one "
+ "also the target goes back to IN_SYNC as no open action is left.")
void manualCancelWithMultipleAssignmentsCancelMiddleOneFirst() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
final DistributionSet dsFirst = testdataFactory.createDistributionSet("", true);
final DistributionSet dsSecond = testdataFactory.createDistributionSet("2", true);
final DistributionSet dsInstalled = action.getDistributionSet();
// check initial status
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
// assign the two sets in a row
JpaAction firstAction = assignSet(target, dsFirst);
JpaAction secondAction = assignSet(target, dsSecond);
assertThat(actionRepository.findAll()).as("wrong size of actions").hasSize(3);
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(5);
// we cancel first -> second is left
deploymentManagement.cancelAction(firstAction.getId());
// confirm cancellation
firstAction = (JpaAction) deploymentManagement.findActionWithDetails(firstAction.getId()).get();
controllerManagement.addCancelActionStatus(
entityFactory.actionStatus().create(firstAction.getId()).status(Status.CANCELED));
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(7);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds").contains(dsSecond);
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong target update status")
.isEqualTo(TargetUpdateStatus.PENDING);
// we cancel second -> remain assigned until finished cancellation
deploymentManagement.cancelAction(secondAction.getId());
secondAction = (JpaAction) deploymentManagement.findActionWithDetails(secondAction.getId()).get();
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(8);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds").contains(dsSecond);
// confirm cancellation
controllerManagement.addCancelActionStatus(
entityFactory.actionStatus().create(secondAction.getId()).status(Status.CANCELED));
// cancelled success -> back to dsInstalled
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong installed ds")
.contains(dsInstalled);
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@Test
@Description("Force Quit an Assignment. Expected behaviour is that the action is canceled and is marked as deleted. The assigned Software module")
void forceQuitSetActionToInactive() throws InterruptedException {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
final DistributionSet dsInstalled = action.getDistributionSet();
final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true);
// verify initial status
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC);
Action assigningAction = assignSet(target, ds);
// verify assignment
assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2);
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4);
// force quit assignment
deploymentManagement.cancelAction(assigningAction.getId());
assigningAction = deploymentManagement.findActionWithDetails(assigningAction.getId()).get();
deploymentManagement.forceQuitAction(assigningAction.getId());
assigningAction = deploymentManagement.findActionWithDetails(assigningAction.getId()).get();
// verify
assertThat(assigningAction.getStatus()).as("wrong size of status").isEqualTo(Status.CANCELED);
assertThat(deploymentManagement.getAssignedDistributionSet("4712")).as("wrong assigned ds")
.contains(dsInstalled);
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong target update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
}
@Test
@Description("Force Quit an not canceled Assignment. Expected behaviour is that the action can not be force quit and there is thrown an exception.")
void forceQuitNotAllowedThrowsException() {
final Action action = prepareFinishedUpdate("4712", "installed", true);
final Target target = action.getTarget();
final DistributionSet ds = testdataFactory.createDistributionSet("newDS", true);
// verify initial status
assertThat(targetManagement.getByControllerID("4712").get().getUpdateStatus()).as("wrong update status")
.isEqualTo(TargetUpdateStatus.IN_SYNC);
final Action assigningAction = assignSet(target, ds);
// verify assignment
assertThat(actionRepository.findAll()).as("wrong size of action").hasSize(2);
assertThat(actionStatusRepository.findAll()).as("wrong size of action status").hasSize(4);
// force quit assignment
assertThatExceptionOfType(ForceQuitActionNotAllowedException.class)
.as("expected ForceQuitActionNotAllowedException")
.isThrownBy(() -> deploymentManagement.forceQuitAction(assigningAction.getId()));
}
private JpaAction assignSet(final Target target, final DistributionSet ds) {
assignDistributionSet(ds.getId(), target.getControllerId());
assertThat(targetManagement.getByControllerID(target.getControllerId()).get().getUpdateStatus())
.as("wrong update status").isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.getAssignedDistributionSet(target.getControllerId())).as("wrong assigned ds")
.contains(ds);
final JpaAction action = actionRepository
.findByTargetAndDistributionSet(PAGE, (JpaTarget) target, (JpaDistributionSet) ds).getContent().get(0);
assertThat(action).as("action should not be null").isNotNull();
return action;
}
@Test
@Description("Simple offline deployment of a distribution set to a list of targets. Verifies that offline assigment "
+ "is correctly executed for targets that do not have a running update already. Those are ignored.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 20),
@Expect(type = TargetUpdatedEvent.class, count = 20), @Expect(type = ActionCreatedEvent.class, count = 20),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1) })
void assignedDistributionSet() {
final List<String> controllerIds = testdataFactory.createTargets(10).stream().map(Target::getControllerId)
.collect(Collectors.toList());
final List<Target> onlineAssignedTargets = testdataFactory.createTargets(10, "2");
controllerIds.addAll(onlineAssignedTargets.stream().map(Target::getControllerId).collect(Collectors.toList()));
final DistributionSet ds = testdataFactory.createDistributionSet();
assignDistributionSet(testdataFactory.createDistributionSet("2"), onlineAssignedTargets);
final long current = System.currentTimeMillis();
final List<Entry<String, Long>> offlineAssignments = controllerIds.stream()
.map(targetId -> new SimpleEntry<String, Long>(targetId, ds.getId())).collect(Collectors.toList());
final List<DistributionSetAssignmentResult> assignmentResults = deploymentManagement
.offlineAssignedDistributionSets(offlineAssignments);
assertThat(assignmentResults).hasSize(1);
final List<Target> targets = assignmentResults.get(0).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
assertThat(actionRepository.count()).isEqualTo(20);
assertThat(actionRepository.findByDistributionSetId(PAGE, ds.getId())).as("Offline actions are not active")
.allMatch(action -> !action.isActive()).as("Actions should be initiated by current user")
.allMatch(a -> a.getInitiatedBy().equals(tenantAware.getCurrentUsername()));
assertThat(targetManagement.findByInstalledDistributionSet(PAGE, ds.getId()).getContent())
.usingElementComparator(controllerIdComparator()).containsAll(targets).hasSize(10)
.containsAll(targetManagement.findByAssignedDistributionSet(PAGE, ds.getId()))
.as("InstallationDate set").allMatch(target -> target.getInstallationDate() >= current)
.as("TargetUpdateStatus IN_SYNC")
.allMatch(target -> TargetUpdateStatus.IN_SYNC.equals(target.getUpdateStatus()))
.as("InstallationDate equal to LastModifiedAt")
.allMatch(target -> target.getLastModifiedAt() == target.getInstallationDate());
}
@Test
@Description("Offline assign multiple DSs to a single Target in multiassignment mode.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4), @Expect(type = ActionCreatedEvent.class, count = 4),
@Expect(type = DistributionSetCreatedEvent.class, count = 4),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 12),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void multiOfflineAssignment() {
final List<String> targetIds = testdataFactory.createTargets(1).stream().map(Target::getControllerId)
.collect(Collectors.toList());
final List<Long> dsIds = testdataFactory.createDistributionSets(4).stream().map(DistributionSet::getId)
.collect(Collectors.toList());
enableMultiAssignments();
final List<Entry<String, Long>> offlineAssignments = new ArrayList<>();
targetIds.forEach(targetId -> dsIds
.forEach(dsId -> offlineAssignments.add(new SimpleEntry<String, Long>(targetId, dsId))));
final List<DistributionSetAssignmentResult> assignmentResults = deploymentManagement
.offlineAssignedDistributionSets(offlineAssignments);
assertThat(getResultingActionCount(assignmentResults)).isEqualTo(4);
targetIds.forEach(controllerId -> {
final List<Long> assignedDsIds = actionRepository.findByTargetControllerId(PAGE, controllerId).stream()
.peek(a -> assertThat(a.getInitiatedBy()).as("Actions should be initiated by current user")
.isEqualTo(tenantAware.getCurrentUsername()))
.map(action -> action.getDistributionSet().getId()).collect(Collectors.toList());
assertThat(assignedDsIds).containsExactlyInAnyOrderElementsOf(dsIds);
});
}
@Test
@Description("Verifies that if an account is set to action autoclose running actions in case of a new assigned set get closed and set to CANCELED.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 10),
@Expect(type = TargetUpdatedEvent.class, count = 20), @Expect(type = ActionCreatedEvent.class, count = 20),
@Expect(type = ActionUpdatedEvent.class, count = 10),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 2),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1),
@Expect(type = TenantConfigurationUpdatedEvent.class, count = 1) })
void assignDistributionSetAndAutoCloseActiveActions() {
tenantConfigurationManagement
.addOrUpdateConfiguration(TenantConfigurationKey.REPOSITORY_ACTIONS_AUTOCLOSE_ENABLED, true);
try {
final List<Target> targets = testdataFactory.createTargets(10);
// First assignment
final DistributionSet ds1 = testdataFactory.createDistributionSet("1");
assignDistributionSet(ds1, targets);
assertDsExclusivelyAssignedToTargets(targets, ds1.getId(), STATE_ACTIVE, Status.RUNNING);
// Second assignment
final DistributionSet ds2 = testdataFactory.createDistributionSet("2");
assignDistributionSet(ds2, targets);
assertDsExclusivelyAssignedToTargets(targets, ds2.getId(), STATE_ACTIVE, Status.RUNNING);
assertDsExclusivelyAssignedToTargets(targets, ds1.getId(), STATE_INACTIVE, Status.CANCELED);
assertThat(targetManagement.findByAssignedDistributionSet(PAGE, ds2.getId()).getContent()).hasSize(10)
.as("InstallationDate not set").allMatch(target -> (target.getInstallationDate() == null));
} finally {
tenantConfigurationManagement
.addOrUpdateConfiguration(TenantConfigurationKey.REPOSITORY_ACTIONS_AUTOCLOSE_ENABLED, false);
}
}
@Test
@Description("If multi-assignment is enabled, verify that the previous Distribution Set assignment is not canceled when a new one is assigned.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 10),
@Expect(type = TargetUpdatedEvent.class, count = 20), @Expect(type = ActionCreatedEvent.class, count = 20),
@Expect(type = DistributionSetCreatedEvent.class, count = 2),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 6),
@Expect(type = MultiActionAssignEvent.class, count = 2),
@Expect(type = MultiActionCancelEvent.class, count = 0),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 0),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void previousAssignmentsAreNotCanceledInMultiAssignMode() {
enableMultiAssignments();
final List<Target> targets = testdataFactory.createTargets(10);
final List<String> targetIds = targets.stream().map(Target::getControllerId).collect(Collectors.toList());
// First assignment
final DistributionSet ds1 = testdataFactory.createDistributionSet("Multi-assign-1");
assignDistributionSet(ds1.getId(), targetIds, 77);
assertDsExclusivelyAssignedToTargets(targets, ds1.getId(), STATE_ACTIVE, Status.RUNNING);
// Second assignment
final DistributionSet ds2 = testdataFactory.createDistributionSet("Multi-assign-2");
assignDistributionSet(ds2.getId(), targetIds, 45);
assertDsExclusivelyAssignedToTargets(targets, ds2.getId(), STATE_ACTIVE, Status.RUNNING);
assertDsExclusivelyAssignedToTargets(targets, ds1.getId(), STATE_ACTIVE, Status.RUNNING);
}
private void assertDsExclusivelyAssignedToTargets(final List<Target> targets, final long dsId, final boolean active,
final Status status) {
final List<Action> assignment = actionRepository.findByDistributionSetId(PAGE, dsId).getContent();
final String currentUsername = tenantAware.getCurrentUsername();
assertThat(assignment).hasSize(10).allMatch(action -> action.isActive() == active)
.as("Is assigned to DS " + dsId).allMatch(action -> action.getDistributionSet().getId().equals(dsId))
.as("State is " + status).allMatch(action -> action.getStatus() == status)
.as("Initiated by " + currentUsername).allMatch(a -> a.getInitiatedBy().equals(currentUsername));
final long[] targetIds = targets.stream().mapToLong(Target::getId).toArray();
assertThat(targetIds).as("All targets represented in assignment").containsExactlyInAnyOrder(
assignment.stream().mapToLong(action -> action.getTarget().getId()).toArray());
}
@Test
@Description("Assign multiple DSs to a single Target in one request in multiassignment mode.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4), @Expect(type = ActionCreatedEvent.class, count = 4),
@Expect(type = DistributionSetCreatedEvent.class, count = 4),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 12),
@Expect(type = MultiActionAssignEvent.class, count = 1),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 0),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void multiAssignmentInOneRequest() {
final List<Target> targets = testdataFactory.createTargets(1);
final List<DistributionSet> distributionSets = testdataFactory.createDistributionSets(4);
final List<DeploymentRequest> deploymentRequests = createAssignmentRequests(distributionSets, targets, 34);
enableMultiAssignments();
final List<DistributionSetAssignmentResult> results = deploymentManagement
.assignDistributionSets(deploymentRequests);
assertThat(getResultingActionCount(results)).isEqualTo(deploymentRequests.size());
final List<Long> dsIds = distributionSets.stream().map(DistributionSet::getId).collect(Collectors.toList());
targets.forEach(target -> {
final List<Long> assignedDsIds = actionRepository.findByTargetControllerId(PAGE, target.getControllerId())
.stream()
.peek(a -> assertThat(a.getInitiatedBy()).as("Initiated by current user")
.isEqualTo(tenantAware.getCurrentUsername()))
.map(action -> action.getDistributionSet().getId()).collect(Collectors.toList());
assertThat(assignedDsIds).containsExactlyInAnyOrderElementsOf(dsIds);
});
}
@Test
@Description("Assign multiple DSs to single Target in one request in multiAssignment mode and cancel each created action afterwards.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = TargetUpdatedEvent.class, count = 4), @Expect(type = ActionCreatedEvent.class, count = 4),
@Expect(type = DistributionSetCreatedEvent.class, count = 4),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 12),
@Expect(type = MultiActionAssignEvent.class, count = 1),
@Expect(type = MultiActionCancelEvent.class, count = 4),
@Expect(type = ActionUpdatedEvent.class, count = 4),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 0),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void cancelMultiAssignmentActions() {
final List<Target> targets = testdataFactory.createTargets(1);
final List<DistributionSet> distributionSets = testdataFactory.createDistributionSets(4);
final List<DeploymentRequest> deploymentRequests = createAssignmentRequests(distributionSets, targets, 34);
enableMultiAssignments();
final List<DistributionSetAssignmentResult> results = deploymentManagement
.assignDistributionSets(deploymentRequests);
assertThat(getResultingActionCount(results)).isEqualTo(deploymentRequests.size());
final List<Long> dsIds = distributionSets.stream().map(DistributionSet::getId).collect(Collectors.toList());
targets.forEach(target -> {
actionRepository.findByTargetControllerId(PAGE, target.getControllerId()).forEach(action -> {
assertThat(action.getDistributionSet().getId()).isIn(dsIds);
assertThat(action.getInitiatedBy()).as("Should be Initiated by current user")
.isEqualTo(tenantAware.getCurrentUsername());
deploymentManagement.cancelAction(action.getId());
});
});
}
protected List<DeploymentRequest> createAssignmentRequests(final Collection<DistributionSet> distributionSets,
final Collection<Target> targets, final int weight) {
final List<DeploymentRequest> deploymentRequests = new ArrayList<>();
distributionSets.forEach(ds -> targets.forEach(target -> deploymentRequests.add(DeploymentManagement
.deploymentRequest(target.getControllerId(), ds.getId()).setWeight(weight).build())));
return deploymentRequests;
}
@Test
@Description("A Request resulting in multiple assignments to a single target is only allowed when multiassignment is enabled.")
void multipleAssignmentsToTargetOnlyAllowedInMultiAssignMode() {
final Target target = testdataFactory.createTarget();
final List<DistributionSet> distributionSets = testdataFactory.createDistributionSets(2);
final DeploymentRequest targetToDS0 = DeploymentManagement
.deploymentRequest(target.getControllerId(), distributionSets.get(0).getId()).setWeight(78).build();
final DeploymentRequest targetToDS1 = DeploymentManagement
.deploymentRequest(target.getControllerId(), distributionSets.get(1).getId()).setWeight(565).build();
Assertions.assertThatExceptionOfType(MultiAssignmentIsNotEnabledException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(Arrays.asList(targetToDS0, targetToDS1)));
enableMultiAssignments();
assertThat(getResultingActionCount(
deploymentManagement.assignDistributionSets(Arrays.asList(targetToDS0, targetToDS1)))).isEqualTo(2);
}
@Test
@Description("Assigning distribution set to the list of targets with a non-existing one leads to successful assignment of valid targets, while not found targets are silently ignored.")
void assignDistributionSetToNotExistingTarget() {
final String notExistingId = "notExistingTarget";
final DistributionSet createdDs = testdataFactory.createDistributionSet();
final String[] knownTargetIdsArray = { "1", "2" };
final List<String> knownTargetIds = Lists.newArrayList(knownTargetIdsArray);
testdataFactory.createTargets(knownTargetIdsArray);
// add not existing target to targets
knownTargetIds.add(notExistingId);
final List<DistributionSetAssignmentResult> assignDistributionSetsResults = assignDistributionSetToTargets(
createdDs, knownTargetIds);
for (final DistributionSetAssignmentResult assignDistributionSetsResult : assignDistributionSetsResults) {
assertThat(assignDistributionSetsResult.getAlreadyAssigned()).isZero();
assertThat(assignDistributionSetsResult.getAssigned()).isEqualTo(2);
assertThat(assignDistributionSetsResult.getTotal()).isEqualTo(2);
}
}
private List<DistributionSetAssignmentResult> assignDistributionSetToTargets(final DistributionSet distributionSet,
final Iterable<String> targetIds) {
final List<DeploymentRequest> deploymentRequests = new ArrayList<>();
for (final String controllerId : targetIds) {
deploymentRequests.add(new DeploymentRequest(controllerId, distributionSet.getId(), ActionType.FORCED, 0,
null, null, null, null));
}
return deploymentManagement.assignDistributionSets(deploymentRequests);
}
@Test
@Description("Duplicate Assignments are removed from a request when multiassignment is disabled, otherwise not")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = ActionCreatedEvent.class, count = 3), @Expect(type = TargetUpdatedEvent.class, count = 2),
@Expect(type = MultiActionAssignEvent.class, count = 1),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void duplicateAssignmentsInRequestAreOnlyRemovedIfMultiassignmentDisabled() {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
final List<DeploymentRequest> twoEqualAssignments = Collections.nCopies(2,
DeploymentManagement.deploymentRequest(targetId, dsId).build());
assertThat(getResultingActionCount(deploymentManagement.assignDistributionSets(twoEqualAssignments)))
.isEqualTo(1);
enableMultiAssignments();
final List<DeploymentRequest> twoEqualAssignmentsWithWeight = Collections.nCopies(2,
DeploymentManagement.deploymentRequest(targetId, dsId).setWeight(555).build());
assertThat(getResultingActionCount(deploymentManagement.assignDistributionSets(twoEqualAssignmentsWithWeight)))
.isEqualTo(2);
}
private int getResultingActionCount(final List<DistributionSetAssignmentResult> results) {
return results.stream().map(DistributionSetAssignmentResult::getTotal).reduce(0, Integer::sum);
}
@Test
@Description("An assignment request is not accepted if it would lead to a target exceeding the max actions per target quota.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 0),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void maxActionsPerTargetIsCheckedBeforeAssignmentExecution() {
final int maxActions = quotaManagement.getMaxActionsPerTarget();
final String controllerId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
final List<DeploymentRequest> deploymentRequests = Collections.nCopies(maxActions + 1,
DeploymentManagement.deploymentRequest(controllerId, dsId).setWeight(24).build());
enableMultiAssignments();
Assertions.assertThatExceptionOfType(AssignmentQuotaExceededException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequests));
assertThat(actionRepository.countByTargetControllerId(controllerId)).isZero();
}
@Test
@Description("An assignment request without a weight is ok when multi assignment in enabled.")
void weightNotRequiredInMultiAssignmentMode() {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
final DeploymentRequest assignWithoutWeight = DeploymentManagement.deploymentRequest(targetId, dsId).build();
final DeploymentRequest assignWithWeight = DeploymentManagement.deploymentRequest(targetId, dsId).setWeight(567)
.build();
enableMultiAssignments();
deploymentManagement.assignDistributionSets(Arrays.asList(assignWithoutWeight, assignWithWeight));
}
@Test
@Description("An assignment request containing a weight causes an error when multi assignment in disabled.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
void weightNotAllowedWhenMultiAssignmentModeNotEnabled() {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
final DeploymentRequest assignWithoutWeight = DeploymentManagement.deploymentRequest(targetId, dsId)
.setWeight(456).build();
Assertions.assertThatExceptionOfType(MultiAssignmentIsNotEnabledException.class).isThrownBy(
() -> deploymentManagement.assignDistributionSets(Collections.singletonList(assignWithoutWeight)));
}
@Test
@Description("Weights are validated and contained in the resulting Action.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3),
@Expect(type = ActionCreatedEvent.class, count = 2), @Expect(type = TargetUpdatedEvent.class, count = 2),
@Expect(type = MultiActionAssignEvent.class, count = 2),
@Expect(type = TenantConfigurationCreatedEvent.class, count = 1) })
void weightValidatedAndSaved() {
final String targetId = testdataFactory.createTarget().getControllerId();
final Long dsId = testdataFactory.createDistributionSet().getId();
final DeploymentRequest valideRequest1 = DeploymentManagement.deploymentRequest(targetId, dsId)
.setWeight(Action.WEIGHT_MAX).build();
final DeploymentRequest valideRequest2 = DeploymentManagement.deploymentRequest(targetId, dsId)
.setWeight(Action.WEIGHT_MIN).build();
final DeploymentRequest weightTooLow = DeploymentManagement.deploymentRequest(targetId, dsId)
.setWeight(Action.WEIGHT_MIN - 1).build();
final DeploymentRequest weightTooHigh = DeploymentManagement.deploymentRequest(targetId, dsId)
.setWeight(Action.WEIGHT_MAX + 1).build();
enableMultiAssignments();
Assertions.assertThatExceptionOfType(ConstraintViolationException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(Collections.singletonList(weightTooLow)));
Assertions.assertThatExceptionOfType(ConstraintViolationException.class).isThrownBy(
() -> deploymentManagement.assignDistributionSets(Collections.singletonList(weightTooHigh)));
final Long valideActionId1 = getFirstAssignedAction(
deploymentManagement.assignDistributionSets(Collections.singletonList(valideRequest1)).get(0)).getId();
final Long valideActionId2 = getFirstAssignedAction(
deploymentManagement.assignDistributionSets(Collections.singletonList(valideRequest2)).get(0)).getId();
assertThat(actionRepository.getById(valideActionId1).get().getWeight()).get().isEqualTo(Action.WEIGHT_MAX);
assertThat(actionRepository.getById(valideActionId2).get().getWeight()).get().isEqualTo(Action.WEIGHT_MIN);
}
/**
* test a simple deployment by calling the
* {@link TargetRepository#assignDistributionSet(DistributionSet, Iterable)} and
* checking the active action and the action history of the targets.
*
*/
@Test
@Description("Simple deployment or distribution set to target assignment test.")
@ExpectEvents({ @Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 30), @Expect(type = ActionCreatedEvent.class, count = 20),
@Expect(type = TargetUpdatedEvent.class, count = 20),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 3) })
void assignDistributionSet2Targets() {
final String myCtrlIDPref = "myCtrlID";
final Iterable<Target> savedNakedTargets = testdataFactory.createTargets(10, myCtrlIDPref, "first description");
final String myDeployedCtrlIDPref = "myDeployedCtrlID";
List<Target> savedDeployedTargets = testdataFactory.createTargets(20, myDeployedCtrlIDPref,
"first description");
final DistributionSet ds = testdataFactory.createDistributionSet("");
assignDistributionSet(ds, savedDeployedTargets);
// verify that one Action for each assignDistributionSet
final Page<JpaAction> actions = actionRepository.findAll(PAGE);
assertThat(actions.getNumberOfElements()).as("wrong size of actions").isEqualTo(20);
assertThat(actions).as("Actions should be initiated by current user")
.allMatch(a -> a.getInitiatedBy().equals(tenantAware.getCurrentUsername()));
final Iterable<Target> allFoundTargets = targetManagement.findAll(PAGE).getContent();
// get final updated version of targets
savedDeployedTargets = targetManagement.getByControllerID(
savedDeployedTargets.stream().map(target -> target.getControllerId()).collect(Collectors.toList()));
assertThat(allFoundTargets).as("founded targets are wrong").containsAll(savedDeployedTargets)
.containsAll(savedNakedTargets);
assertThat(savedDeployedTargets).as("saved target are wrong")
.doesNotContain(Iterables.toArray(savedNakedTargets, Target.class));
assertThat(savedNakedTargets).as("saved target are wrong")
.doesNotContain(Iterables.toArray(savedDeployedTargets, Target.class));
for (final Target myt : savedNakedTargets) {
final Target t = targetManagement.getByControllerID(myt.getControllerId()).get();
assertThat(deploymentManagement.countActionsByTarget(t.getControllerId())).as("action should be empty")
.isZero();
}
for (final Target myt : savedDeployedTargets) {
final Target t = targetManagement.getByControllerID(myt.getControllerId()).get();
final List<Action> activeActionsByTarget = deploymentManagement
.findActiveActionsByTarget(PAGE, t.getControllerId()).getContent();
assertThat(activeActionsByTarget).as("action should not be empty").isNotEmpty();
assertThat(t.getUpdateStatus()).as("wrong target update status").isEqualTo(TargetUpdateStatus.PENDING);
for (final Action ua : activeActionsByTarget) {
assertThat(ua.getDistributionSet()).as("action has wrong ds").isEqualTo(ds);
}
}
}
@Test
@Description("Test that it is not possible to assign a distribution set that is not complete.")
@ExpectEvents({ @Expect(type = TargetAssignDistributionSetEvent.class, count = 1),
@Expect(type = DistributionSetCreatedEvent.class, count = 1),
@Expect(type = TargetCreatedEvent.class, count = 10), @Expect(type = ActionCreatedEvent.class, count = 10),
@Expect(type = TargetUpdatedEvent.class, count = 10),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 2),
@Expect(type = DistributionSetUpdatedEvent.class, count = 1)
})
void failDistributionSetAssigmentThatIsNotComplete() throws InterruptedException {
final List<Target> targets = testdataFactory.createTargets(10);
final SoftwareModule ah = testdataFactory.createSoftwareModuleApp();
final SoftwareModule os = testdataFactory.createSoftwareModuleOs();
final DistributionSet incomplete = distributionSetManagement.create(entityFactory.distributionSet().create()
.name("incomplete").version("v1").type(standardDsType).modules(Collections.singletonList(ah.getId())));
assertThatExceptionOfType(IncompleteDistributionSetException.class)
.as("expected IncompleteDistributionSetException")
.isThrownBy(() -> assignDistributionSet(incomplete, targets));
final DistributionSet nowComplete = distributionSetManagement.assignSoftwareModules(incomplete.getId(),
Sets.newHashSet(os.getId()));
assertThat(assignDistributionSet(nowComplete, targets).getAssigned()).as("assign ds doesn't work")
.isEqualTo(10);
}
@Test
@Description("Multiple deployments or distribution set to target assignment test. Expected behaviour is that a new deployment "
+ "overides unfinished old one which are canceled as part of the operation.")
@ExpectEvents({ @Expect(type = TargetCreatedEvent.class, count = 5 + 4),
@Expect(type = TargetUpdatedEvent.class, count = 3 * 4),
@Expect(type = ActionCreatedEvent.class, count = 3 * 4),
@Expect(type = ActionUpdatedEvent.class, count = 4 * 2),
@Expect(type = CancelTargetAssignmentEvent.class, count = 4 * 2),
@Expect(type = DistributionSetCreatedEvent.class, count = 3),
@Expect(type = SoftwareModuleCreatedEvent.class, count = 9),
@Expect(type = TargetAssignDistributionSetEvent.class, count = 3) })
void multipleDeployments() throws InterruptedException {
final String undeployedTargetPrefix = "undep-T";
final int noOfUndeployedTargets = 5;
final String deployedTargetPrefix = "dep-T";
final int noOfDeployedTargets = 4;
final int noOfDistributionSets = 3;
final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets,
deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS");
final List<Long> deployedTargetIDs = deploymentResult.getDeployedTargetIDs();
final List<Long> undeployedTargetIDs = deploymentResult.getUndeployedTargetIDs();
final Collection<JpaTarget> savedNakedTargets = (Collection) deploymentResult.getUndeployedTargets();
final Collection<JpaTarget> savedDeployedTargets = (Collection) deploymentResult.getDeployedTargets();
// retrieving all Actions created by the assignDistributionSet call
final Page<JpaAction> page = actionRepository.findAll(PAGE);
assertThat(page).as("Actions should be initiated by current user")
.allMatch(a -> a.getInitiatedBy().equals(tenantAware.getCurrentUsername()));
// and verify the number
assertThat(page.getTotalElements()).as("wrong size of actions")
.isEqualTo(noOfDeployedTargets * noOfDistributionSets);
// only records retrieved from the DB can be evaluated to be sure that
// all fields are
// populated;
final List<JpaTarget> allFoundTargets = targetRepository.findAll();
final List<JpaTarget> deployedTargetsFromDB = targetRepository.findAllById(deployedTargetIDs);
final List<JpaTarget> undeployedTargetsFromDB = targetRepository.findAllById(undeployedTargetIDs);
// test that number of Targets
assertThat(allFoundTargets.spliterator().getExactSizeIfKnown()).as("number of target is wrong")
.isEqualTo(deployedTargetsFromDB.spliterator().getExactSizeIfKnown()
+ undeployedTargetsFromDB.spliterator().getExactSizeIfKnown());
assertThat(deployedTargetsFromDB.spliterator().getExactSizeIfKnown()).as("number of target is wrong")
.isEqualTo(noOfDeployedTargets);
assertThat(undeployedTargetsFromDB.spliterator().getExactSizeIfKnown()).as("number of target is wrong")
.isEqualTo(noOfUndeployedTargets);
// test the content of different lists
assertThat(allFoundTargets).as("content of founded target is wrong").containsAll(deployedTargetsFromDB)
.containsAll(undeployedTargetsFromDB);
assertThat(deployedTargetsFromDB).as("content of deployed target is wrong")
.usingElementComparator(controllerIdComparator()).containsAll(savedDeployedTargets)
.doesNotContain(Iterables.toArray(undeployedTargetsFromDB, JpaTarget.class));
assertThat(undeployedTargetsFromDB).as("content of undeployed target is wrong").containsAll(savedNakedTargets)
.doesNotContain(Iterables.toArray(deployedTargetsFromDB, JpaTarget.class));
}
@Test
@Description("Multiple deployments or distribution set to target assignment test including finished response "
+ "from target/controller. Expected behaviour is that in case of OK finished update the target will go to "
+ "IN_SYNC status and installed DS is set to the assigned DS entry.")
void assignDistributionSetAndAddFinishedActionStatus() {
final PageRequest pageRequest = PageRequest.of(0, 100, Direction.ASC, ActionStatusFields.ID.getFieldName());
final DeploymentResult deployResWithDsA = prepareComplexRepo("undep-A-T", 2, "dep-A-T", 4, 1, "dsA");
final DeploymentResult deployResWithDsB = prepareComplexRepo("undep-B-T", 3, "dep-B-T", 5, 1, "dsB");
final DeploymentResult deployResWithDsC = prepareComplexRepo("undep-C-T", 4, "dep-C-T", 6, 1, "dsC");
// keep a reference to the created DistributionSets
final JpaDistributionSet dsA = (JpaDistributionSet) deployResWithDsA.getDistributionSets().get(0);
final JpaDistributionSet dsB = (JpaDistributionSet) deployResWithDsB.getDistributionSets().get(0);
final JpaDistributionSet dsC = (JpaDistributionSet) deployResWithDsC.getDistributionSets().get(0);
// retrieving the UpdateActions created by the assignments
actionRepository.findByDistributionSetId(pageRequest, dsA.getId()).getContent().get(0);
actionRepository.findByDistributionSetId(pageRequest, dsB.getId()).getContent().get(0);
actionRepository.findByDistributionSetId(pageRequest, dsC.getId()).getContent().get(0);
// verifying the correctness of the assignments
for (final Target t : deployResWithDsA.getDeployedTargets()) {
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()).get().getId())
.as("assignment is not correct").isEqualTo(dsA.getId());
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
.as("installed ds should be null").isNotPresent();
}
for (final Target t : deployResWithDsB.getDeployedTargets()) {
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()).get().getId())
.as("assigned ds is wrong").isEqualTo(dsB.getId());
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
.as("installed ds should be null").isNotPresent();
}
for (final Target t : deployResWithDsC.getDeployedTargets()) {
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId()).get().getId())
.isEqualTo(dsC.getId());
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
.as("installed ds should not be null").isNotPresent();
assertThat(targetManagement.getByControllerID(t.getControllerId()).get().getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING);
}
final List<Target> updatedTsDsA = testdataFactory
.sendUpdateActionStatusToTargets(deployResWithDsA.getDeployedTargets(), Status.FINISHED,
Collections.singletonList("alles gut"))
.stream().map(Action::getTarget).collect(Collectors.toList());
// verify, that dsA is deployed correctly
for (final Target t_ : updatedTsDsA) {
final Target t = targetManagement.getByControllerID(t_.getControllerId()).get();
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId())).as("assigned ds is wrong")
.contains(dsA);
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
.as("installed ds is wrong").contains(dsA);
assertThat(targetManagement.getByControllerID(t.getControllerId()).get().getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.IN_SYNC);
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, t.getControllerId()))
.as("no actions should be active").isEmpty();
}
// deploy dsA to the target which already have dsB deployed -> must
// remove updActB from
// activeActions, add a corresponding cancelAction and another
// UpdateAction for dsA
final List<Target> deployed2DS = assignDistributionSet(dsA, deployResWithDsB.getDeployedTargets())
.getAssignedEntity().stream().map(Action::getTarget).collect(Collectors.toList());
actionRepository.findByDistributionSetId(pageRequest, dsA.getId()).getContent().get(1);
// get final updated version of targets
final List<Target> deployResWithDsBTargets = targetManagement.getByControllerID(deployResWithDsB
.getDeployedTargets().stream().map(Target::getControllerId).collect(Collectors.toList()));
assertThat(deployed2DS).as("deployed ds is wrong").usingElementComparator(controllerIdComparator())
.containsAll(deployResWithDsBTargets);
assertThat(deployed2DS).as("deployed ds is wrong").hasSameSizeAs(deployResWithDsBTargets);
for (final Target t_ : deployed2DS) {
final Target t = targetManagement.getByControllerID(t_.getControllerId()).get();
assertThat(deploymentManagement.getAssignedDistributionSet(t.getControllerId())).as("assigned ds is wrong")
.contains(dsA);
assertThat(deploymentManagement.getInstalledDistributionSet(t.getControllerId()))
.as("installed ds should be null").isNotPresent();
assertThat(targetManagement.getByControllerID(t.getControllerId()).get().getUpdateStatus())
.as("wrong target info update status").isEqualTo(TargetUpdateStatus.PENDING);
}
}
/**
* test the deletion of {@link DistributionSet}s including exception in case of
* {@link Target}s are assigned by {@link Target#getAssignedDistributionSet()}
* or {@link Target#getInstalledDistributionSet()}
*/
@Test
@Description("Deletes distribution set. Expected behaviour is that a soft delete is performed "
+ "if the DS is assigned to a target and a hard delete if the DS is not in use at all.")
void deleteDistributionSet() {
final PageRequest pageRequest = PageRequest.of(0, 100, Direction.ASC, "id");
final String undeployedTargetPrefix = "undep-T";
final int noOfUndeployedTargets = 2;
final String deployedTargetPrefix = "dep-T";
final int noOfDeployedTargets = 4;
final int noOfDistributionSets = 3;
final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets,
deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS");
final DistributionSet dsA = testdataFactory.createDistributionSet("");
distributionSetManagement.delete(dsA.getId());
assertThat(distributionSetManagement.get(dsA.getId())).isNotPresent();
// // verify that the ds is not physically deleted
for (final DistributionSet ds : deploymentResult.getDistributionSets()) {
distributionSetManagement.delete(ds.getId());
final DistributionSet foundDS = distributionSetManagement.get(ds.getId()).get();
assertThat(foundDS).as("founded should not be null").isNotNull();
assertThat(foundDS.isDeleted()).as("found ds should be deleted").isTrue();
}
// verify that deleted attribute is used correctly
List<DistributionSet> allFoundDS = distributionSetManagement.findByCompleted(PAGE, true).getContent();
assertThat(allFoundDS.size()).as("no ds should be founded").isZero();
assertThat(distributionSetRepository.findAll(SpecificationsBuilder.combineWithAnd(Arrays
.asList(DistributionSetSpecification.isDeleted(true), DistributionSetSpecification.isCompleted(true))),
PAGE).getContent()).as("wrong size of founded ds").hasSize(noOfDistributionSets);
for (final DistributionSet ds : deploymentResult.getDistributionSets()) {
testdataFactory.sendUpdateActionStatusToTargets(deploymentResult.getDeployedTargets(), Status.FINISHED,
Collections.singletonList("blabla alles gut"));
}
// try to delete again
distributionSetManagement.delete(deploymentResult.getDistributionSetIDs());
// verify that the result is the same, even though distributionSet dsA
// has been installed
// successfully and no activeAction is referring to created distribution
// sets
allFoundDS = distributionSetManagement.findByCompleted(pageRequest, true).getContent();
assertThat(allFoundDS.size()).as("no ds should be founded").isZero();
assertThat(distributionSetRepository.findAll(SpecificationsBuilder.combineWithAnd(Arrays
.asList(DistributionSetSpecification.isDeleted(true), DistributionSetSpecification.isCompleted(true))),
PAGE).getContent()).as("wrong size of founded ds").hasSize(noOfDistributionSets);
}
@Test
@Description("Deletes multiple targets and verifies that all related metadata is also deleted.")
void deletesTargetsAndVerifyCascadeDeletes() {
final String undeployedTargetPrefix = "undep-T";
final int noOfUndeployedTargets = 2;
final String deployedTargetPrefix = "dep-T";
final int noOfDeployedTargets = 4;
final int noOfDistributionSets = 3;
final DeploymentResult deploymentResult = prepareComplexRepo(undeployedTargetPrefix, noOfUndeployedTargets,
deployedTargetPrefix, noOfDeployedTargets, noOfDistributionSets, "myTestDS");
for (final DistributionSet ds : deploymentResult.getDistributionSets()) {
testdataFactory.sendUpdateActionStatusToTargets(deploymentResult.getDeployedTargets(), Status.FINISHED,
Collections.singletonList("blabla alles gut"));
}
assertThat(targetManagement.count()).as("size of targets is wrong").isNotZero();
assertThat(actionStatusRepository.count()).as("size of action status is wrong").isNotZero();
targetManagement.delete(deploymentResult.getUndeployedTargetIDs());
targetManagement.delete(deploymentResult.getDeployedTargetIDs());
assertThat(targetManagement.count()).as("size of targets should be zero").isZero();
assertThat(actionStatusRepository.count()).as("size of action status is wrong").isZero();
}
@Test
@Description("Testing if changing target and the status without refreshing the entities from the DB (e.g. concurrent changes from UI and from controller) works")
void alternatingAssignmentAndAddUpdateActionStatus() {
final DistributionSet dsA = testdataFactory.createDistributionSet("a");
final DistributionSet dsB = testdataFactory.createDistributionSet("b");
List<Target> targs = Collections.singletonList(testdataFactory.createTarget("target-id-A"));
// doing the assignment
targs = assignDistributionSet(dsA, targs).getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
Target targ = targetManagement.getByControllerID(targs.iterator().next().getControllerId()).get();
// checking the revisions of the created entities
// verifying that the revision of the object and the revision within the
// DB has not changed
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
// verifying that the assignment is correct
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements())
.as("Active target actions are wrong").isEqualTo(1);
assertThat(deploymentManagement.countActionsByTarget(targ.getControllerId())).as("Target actions are wrong")
.isEqualTo(1);
assertThat(targ.getUpdateStatus()).as("UpdateStatus of target is wrong").isEqualTo(TargetUpdateStatus.PENDING);
assertThat(deploymentManagement.getAssignedDistributionSet(targ.getControllerId()))
.as("Assigned distribution set of target is wrong").contains(dsA);
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getContent().get(0)
.getDistributionSet()).as("Distribution set of actionn is wrong").isEqualTo(dsA);
assertThat(deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getContent().get(0)
.getDistributionSet()).as("Installed distribution set of action should be null").isNotNull();
final Page<Action> updAct = actionRepository.findByDistributionSetId(PAGE, dsA.getId());
controllerManagement.addUpdateActionStatus(
entityFactory.actionStatus().create(updAct.getContent().get(0).getId()).status(Status.FINISHED));
targ = targetManagement.getByControllerID(targ.getControllerId()).get();
assertEquals(0, deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements(),
"active target actions are wrong");
assertEquals(1,
deploymentManagement.findInActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements(),
"active actions are wrong");
assertEquals(TargetUpdateStatus.IN_SYNC, targ.getUpdateStatus(), "tagret update status is not correct");
assertEquals(dsA, deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get(),
"wrong assigned ds");
assertEquals(dsA, deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get(),
"wrong installed ds");
targs = assignDistributionSet(dsB.getId(), "target-id-A").getAssignedEntity().stream().map(Action::getTarget)
.collect(Collectors.toList());
targ = targs.iterator().next();
assertEquals(1, deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getTotalElements(),
"active actions are wrong");
assertEquals(TargetUpdateStatus.PENDING,
targetManagement.getByControllerID(targ.getControllerId()).get().getUpdateStatus(),
"target status is wrong");
assertEquals(dsB, deploymentManagement.getAssignedDistributionSet(targ.getControllerId()).get(),
"wrong assigned ds");
assertEquals(dsA.getId(),
deploymentManagement.getInstalledDistributionSet(targ.getControllerId()).get().getId(),
"Installed ds is wrong");
assertEquals(dsB, deploymentManagement.findActiveActionsByTarget(PAGE, targ.getControllerId()).getContent()
.get(0).getDistributionSet(), "Active ds is wrong");
}
@Test
@Description("The test verifies that the DS itself is not changed because of an target assignment"
+ " which is a relationship but not a changed on the entity itself..")
void checkThatDsRevisionsIsNotChangedWithTargetAssignment() {
final DistributionSet dsA = testdataFactory.createDistributionSet("a");
testdataFactory.createDistributionSet("b");
final Target targ = testdataFactory.createTarget("target-id-A");
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
assignDistributionSet(dsA, Collections.singletonList(targ));
assertThat(dsA.getOptLockRevision()).as("lock revision is wrong")
.isEqualTo(distributionSetManagement.getWithDetails(dsA.getId()).get().getOptLockRevision());
}
@Test
@Description("Tests the switch from a soft to hard update by API")
void forceSoftAction() {
// prepare
final Target target = testdataFactory.createTarget("knownControllerId");
final DistributionSet ds = testdataFactory.createDistributionSet("a");
// assign ds to create an action
final DistributionSetAssignmentResult assignDistributionSet = assignDistributionSet(ds.getId(),
target.getControllerId(), ActionType.SOFT);
final Long actionId = getFirstAssignedActionId(assignDistributionSet);
// verify preparation
Action findAction = deploymentManagement.findAction(actionId).get();
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.SOFT);
// test
deploymentManagement.forceTargetAction(actionId);
// verify test
findAction = deploymentManagement.findAction(actionId).get();
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
}
@Test
@Description("Tests the switch from a hard to hard update by API, e.g. which in fact should not change anything.")
void forceAlreadyForcedActionNothingChanges() {
// prepare
final Target target = testdataFactory.createTarget("knownControllerId");
final DistributionSet ds = testdataFactory.createDistributionSet("a");
// assign ds to create an action
final DistributionSetAssignmentResult assignDistributionSet = assignDistributionSet(ds.getId(),
target.getControllerId(), ActionType.FORCED);
final Long actionId = getFirstAssignedActionId(assignDistributionSet);
// verify preparation
Action findAction = deploymentManagement.findAction(actionId).get();
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
// test
final Action forceTargetAction = deploymentManagement.forceTargetAction(actionId);
// verify test
assertThat(forceTargetAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
findAction = deploymentManagement.findAction(actionId).get();
assertThat(findAction.getActionType()).as("action type is wrong").isEqualTo(ActionType.FORCED);
}
@Test
@Description("Tests the computation of already assigned entities returned as a result of an assignment")
void testAlreadyAssignedAndAssignedActionsInAssignmentResult() {
// create target1, distributionSet, assign ds to target1 and finish
// update (close all actions)
final Action action = prepareFinishedUpdate("target1", "ds", false);
final Target target2 = testdataFactory.createTarget("target2");
final Target target3 = testdataFactory.createTarget("target3");
// assign ds to target2, but don't finish update (actions should be
// still open)
assignDistributionSet(action.getDistributionSet().getId(), target2.getControllerId());
final DistributionSetAssignmentResult assignmentResult = assignDistributionSet(
action.getDistributionSet().getId(),
Arrays.asList(action.getTarget().getControllerId(), target3.getControllerId()), ActionType.FORCED);
assertThat(assignmentResult).isNotNull();
assertThat(assignmentResult.getTotal()).as("Total count of assigned and already assigned targets").isEqualTo(2);
assertThat(assignmentResult.getAssigned()).as("Total count of assigned targets").isEqualTo(1);
assertThat(assignmentResult.getAlreadyAssigned()).as("Total count of already assigned targets").isEqualTo(1);
assertThat(assignmentResult.getAssignedEntity()).isNotEmpty();
assertThat(assignmentResult.getAssignedEntity()).allMatch(
a -> a.getTarget().equals(target3) && a.getDistributionSet().equals(action.getDistributionSet()));
assertThat(assignmentResult.getAssignedEntity())
.noneMatch(a -> a.getTarget().getControllerId().equals("target1"));
}
@Test
@Description("Verify that the DistributionSetAssignmentResult not contains already assigned targets.")
void verifyDistributionSetAssignmentResultNotContainsAlreadyAssignedTargets() {
final DistributionSet dsToTargetAssigned = testdataFactory.createDistributionSet("ds-3");
// create assigned DS
final Target savedTarget = testdataFactory.createTarget();
DistributionSetAssignmentResult assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(),
savedTarget.getControllerId());
assertThat(assignmentResult.getAssignedEntity()).hasSize(1);
assignmentResult = assignDistributionSet(dsToTargetAssigned.getId(), savedTarget.getControllerId());
assertThat(assignmentResult.getAssignedEntity()).isEmpty();
assertThat(distributionSetRepository.findAll()).hasSize(1);
}
@Test
@Description("Tests that an exception is thrown when a target is assigned to an incomplete distribution set")
public void verifyAssignTargetsToIncompleteDistribution() {
final DistributionSet distributionSet = testdataFactory.createIncompleteDistributionSet();
final Target target = testdataFactory.createTarget();
assertThatExceptionOfType(IncompleteDistributionSetException.class)
.as("Incomplete distributionSet should throw an exception")
.isThrownBy(() -> assignDistributionSet(distributionSet, target));
}
@Test
@Description("Tests that an exception is thrown when a target is assigned to an invalidated distribution set")
public void verifyAssignTargetsToInvalidDistribution() {
final DistributionSet distributionSet = testdataFactory.createAndInvalidateDistributionSet();
final Target target = testdataFactory.createTarget();
assertThatExceptionOfType(InvalidDistributionSetException.class)
.as("Invalid distributionSet should throw an exception")
.isThrownBy(() -> assignDistributionSet(distributionSet, target));
}
@Test
@Description("Verify that the DistributionSet assignments work for multiple targets of the same target type within the same request.")
void verifyDSAssignmentForMultipleTargetsWithSameTargetType() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final TargetType targetType = testdataFactory.createTargetType("test-type",
Collections.singletonList(ds.getType()));
final List<DeploymentRequest> deploymentRequests = new ArrayList<>();
for (int i = 0; i < quotaManagement.getMaxTargetDistributionSetAssignmentsPerManualAssignment(); i++) {
final Target target = testdataFactory.createTarget("test-target-" + i, "test-target-" + i,
targetType.getId());
final DeploymentRequest deployment = DeploymentManagement
.deploymentRequest(target.getControllerId(), ds.getId()).build();
deploymentRequests.add(deployment);
}
deploymentManagement.assignDistributionSets(deploymentRequests);
final List<Target> content = targetManagement.findAll(Pageable.unpaged()).getContent();
content.stream().map(JpaTarget.class::cast)
.forEach(jpaTarget -> assertThat(jpaTarget.getAssignedDistributionSet()).isEqualTo(ds));
}
@Test
@Description("Verify that the DistributionSet assignments work for multiple targets of different target types.")
void verifyDSAssignmentForMultipleTargetsWithDifferentTargetTypes() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final TargetType targetType1 = testdataFactory.createTargetType("test-type1",
Collections.singletonList(ds.getType()));
final TargetType targetType2 = testdataFactory.createTargetType("test-type2",
Collections.singletonList(ds.getType()));
final Target target1 = testdataFactory.createTarget("test-target1", "test-target1", targetType1.getId());
final Target target2 = testdataFactory.createTarget("test-target2", "test-target2", targetType2.getId());
final DeploymentRequest deployment1 = DeploymentManagement
.deploymentRequest(target1.getControllerId(), ds.getId()).build();
final DeploymentRequest deployment2 = DeploymentManagement
.deploymentRequest(target2.getControllerId(), ds.getId()).build();
final List<DeploymentRequest> deploymentRequests = Arrays.asList(deployment1, deployment2);
deploymentManagement.assignDistributionSets(deploymentRequests);
final Optional<DistributionSet> assignedDsTarget1 = targetManagement
.getByControllerID(target1.getControllerId()).map(JpaTarget.class::cast)
.map(JpaTarget::getAssignedDistributionSet);
final Optional<DistributionSet> assignedDsTarget2 = targetManagement
.getByControllerID(target2.getControllerId()).map(JpaTarget.class::cast)
.map(JpaTarget::getAssignedDistributionSet);
assertThat(assignedDsTarget1).contains(ds);
assertThat(assignedDsTarget2).contains(ds);
}
@Test
@Description("Verify that the DistributionSet assignment fails for target with incompatible target type.")
void verifyDSAssignmentFailsForTargetsWithIncompatibleTargetTypes() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final DistributionSetType dsType = testdataFactory.findOrCreateDistributionSetType("test-ds-type", "dsType");
final TargetType targetType = testdataFactory.createTargetType("target-type",
Collections.singletonList(dsType));
final Target target = testdataFactory.createTarget("test-target", "test-target", targetType.getId());
final DeploymentRequest deploymentRequest = DeploymentManagement
.deploymentRequest(target.getControllerId(), ds.getId()).build();
final List<DeploymentRequest> deploymentRequests = Collections.singletonList(deploymentRequest);
assertThatExceptionOfType(IncompatibleTargetTypeException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequests));
}
@Test
@Description("Verify that the DistributionSet assignment fails for target with target type that is not compatible with any dsType.")
void verifyDSAssignmentFailsForTargetsWithTargetTypesThatAreNotCompatibleWithAnyDs() {
final DistributionSet ds = testdataFactory.createDistributionSet("test-ds");
final TargetType emptyTargetType = testdataFactory.createTargetType("target-type", Collections.emptyList());
final Target targetWithEmptyType = testdataFactory.createTarget("test-target", "test-target",
emptyTargetType.getId());
final DeploymentRequest deploymentRequestWithEmptyType = DeploymentManagement
.deploymentRequest(targetWithEmptyType.getControllerId(), ds.getId()).build();
final List<DeploymentRequest> deploymentRequests = Collections.singletonList(deploymentRequestWithEmptyType);
assertThatExceptionOfType(IncompatibleTargetTypeException.class)
.isThrownBy(() -> deploymentManagement.assignDistributionSets(deploymentRequests));
}
/**
* Helper methods that creates 2 lists of targets and a list of distribution
* sets.
* <p>
* <b>All created distribution sets are assigned to all targets of the target
* list deployedTargets.</b>
*
* @param undeployedTargetPrefix
* prefix to be used as target controller prefix
* @param noOfUndeployedTargets
* number of targets which remain undeployed
* @param deployedTargetPrefix
* prefix to be used as target controller prefix
* @param noOfDeployedTargets
* number of targets to which the created distribution sets assigned
* @param noOfDistributionSets
* number of distribution sets
* @param distributionSetPrefix
* prefix for the created distribution sets
* @return the {@link DeploymentResult} containing all created targets, the
* distribution sets, the corresponding IDs for later evaluation in
* tests
*/
private DeploymentResult prepareComplexRepo(final String undeployedTargetPrefix, final int noOfUndeployedTargets,
final String deployedTargetPrefix, final int noOfDeployedTargets, final int noOfDistributionSets,
final String distributionSetPrefix) {
final Iterable<Target> nakedTargets = testdataFactory.createTargets(noOfUndeployedTargets,
undeployedTargetPrefix, "first description");
List<Target> deployedTargets = testdataFactory.createTargets(noOfDeployedTargets, deployedTargetPrefix,
"first description");
// creating 10 DistributionSets
final Collection<DistributionSet> dsList = testdataFactory.createDistributionSets(distributionSetPrefix,
noOfDistributionSets);
String time = String.valueOf(System.currentTimeMillis());
time = time.substring(time.length() - 5);
// assigning all DistributionSet to the Target in the list
// deployedTargets
for (final DistributionSet ds : dsList) {
deployedTargets = assignDistributionSet(ds, deployedTargets).getAssignedEntity().stream()
.map(Action::getTarget).collect(Collectors.toList());
}
return new DeploymentResult(deployedTargets, nakedTargets, dsList, deployedTargetPrefix, undeployedTargetPrefix,
distributionSetPrefix);
}
private static class DeploymentResult {
final List<Long> deployedTargetIDs = new ArrayList<>();
final List<Long> undeployedTargetIDs = new ArrayList<>();
final List<Long> distributionSetIDs = new ArrayList<>();
private final List<Target> undeployedTargets = new ArrayList<>();
private final List<Target> deployedTargets = new ArrayList<>();
private final List<DistributionSet> distributionSets = new ArrayList<>();
public DeploymentResult(final Iterable<Target> deployedTs, final Iterable<Target> undeployedTs,
final Iterable<DistributionSet> dss, final String deployedTargetPrefix,
final String undeployedTargetPrefix, final String distributionSetPrefix) {
Iterables.addAll(deployedTargets, deployedTs);
Iterables.addAll(undeployedTargets, undeployedTs);
Iterables.addAll(distributionSets, dss);
deployedTargets.forEach(t -> deployedTargetIDs.add(t.getId()));
undeployedTargets.forEach(t -> undeployedTargetIDs.add(t.getId()));
distributionSets.forEach(ds -> distributionSetIDs.add(ds.getId()));
}
public List<Long> getDistributionSetIDs() {
return distributionSetIDs;
}
public List<Long> getDeployedTargetIDs() {
return deployedTargetIDs;
}
public List<Target> getUndeployedTargets() {
return undeployedTargets;
}
public List<DistributionSet> getDistributionSets() {
return distributionSets;
}
public List<Target> getDeployedTargets() {
return deployedTargets;
}
public List<Long> getUndeployedTargetIDs() {
return undeployedTargetIDs;
}
}
}
|
eclipse/hawkbit
|
hawkbit-repository/hawkbit-repository-jpa/src/test/java/org/eclipse/hawkbit/repository/jpa/DeploymentManagementTest.java
|
Java
|
epl-1.0
| 91,834 |
/*******************************************************************************
* Copyright (c) 2011 Red Hat, Inc.
* All rights reserved.
* This program is made available under the terms of the
* Eclipse Public License v1.0 which accompanies this distribution,
* and is available at http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Red Hat, Inc. - initial API and implementation
*
* @author Innar Made
******************************************************************************/
package org.camunda.bpm.modeler.ui.features.event.definitions;
import org.camunda.bpm.modeler.core.features.event.definitions.AbstractEventDefinitionFeatureContainer;
import org.camunda.bpm.modeler.core.features.event.definitions.CreateEventDefinition;
import org.camunda.bpm.modeler.core.features.event.definitions.DecorationAlgorithm;
import org.camunda.bpm.modeler.core.utils.BusinessObjectUtil;
import org.camunda.bpm.modeler.core.utils.GraphicsUtil;
import org.camunda.bpm.modeler.core.utils.StyleUtil;
import org.camunda.bpm.modeler.core.utils.StyleUtil.FillStyle;
import org.camunda.bpm.modeler.ui.Images;
import org.eclipse.bpmn2.BaseElement;
import org.eclipse.bpmn2.BoundaryEvent;
import org.eclipse.bpmn2.Bpmn2Package;
import org.eclipse.bpmn2.CancelEventDefinition;
import org.eclipse.bpmn2.CatchEvent;
import org.eclipse.bpmn2.Event;
import org.eclipse.bpmn2.IntermediateThrowEvent;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.graphiti.features.ICreateFeature;
import org.eclipse.graphiti.features.IFeatureProvider;
import org.eclipse.graphiti.features.context.ICreateContext;
import org.eclipse.graphiti.mm.algorithms.Polygon;
import org.eclipse.graphiti.mm.pictograms.ContainerShape;
import org.eclipse.graphiti.mm.pictograms.Shape;
import org.eclipse.graphiti.services.Graphiti;
public class CancelEventDefinitionContainer extends AbstractEventDefinitionFeatureContainer {
@Override
public boolean canApplyTo(Object o) {
return super.canApplyTo(o) && o instanceof CancelEventDefinition;
}
@Override
public ICreateFeature getCreateFeature(IFeatureProvider fp) {
return new CreateCancelEventDefinition(fp);
}
@Override
protected Shape drawForStart(DecorationAlgorithm algorithm, ContainerShape shape) {
return null; // NOT ALLOWED ACCORDING TO SPEC
}
@Override
protected Shape drawForEnd(DecorationAlgorithm algorithm, ContainerShape shape) {
return drawFilled(algorithm, shape);
}
@Override
protected Shape drawForThrow(DecorationAlgorithm algorithm, ContainerShape shape) {
return null; // NOT ALLOWED ACCORDING TO SPEC
}
@Override
protected Shape drawForCatch(DecorationAlgorithm algorithm, ContainerShape shape) {
return null; // NOT ALLOWED ACCORDING TO SPEC
}
@Override
protected Shape drawForBoundary(DecorationAlgorithm algorithm, ContainerShape shape) {
return draw(algorithm, shape);
}
private Shape draw(DecorationAlgorithm algorithm, ContainerShape shape) {
BaseElement be = BusinessObjectUtil.getFirstElementOfType(shape, BaseElement.class, true);
Shape cancelShape = Graphiti.getPeService().createShape(shape, false);
Polygon link = GraphicsUtil.createEventCancel(cancelShape);
StyleUtil.setFillStyle(link, FillStyle.FILL_STYLE_BACKGROUND);
StyleUtil.applyStyle(link, be);
return cancelShape;
}
private Shape drawFilled(DecorationAlgorithm algorithm, ContainerShape shape) {
BaseElement be = BusinessObjectUtil.getFirstElementOfType(shape, BaseElement.class, true);
Shape cancelShape = Graphiti.getPeService().createShape(shape, false);
Polygon link = GraphicsUtil.createEventCancel(cancelShape);
StyleUtil.setFillStyle(link, FillStyle.FILL_STYLE_FOREGROUND);
StyleUtil.applyStyle(link, be);
return cancelShape;
}
public static class CreateCancelEventDefinition extends CreateEventDefinition<CancelEventDefinition> {
public CreateCancelEventDefinition(IFeatureProvider fp) {
super(fp, "Cancel Definition", "Adds cancel trigger to event");
}
@Override
public boolean canCreate(ICreateContext context) {
if (!super.canCreate(context)) {
return false;
}
Event e = (Event) getBusinessObjectForPictogramElement(context.getTargetContainer());
if (e instanceof BoundaryEvent) {
BoundaryEvent be = (BoundaryEvent) e;
return be.isCancelActivity();
}
if (e instanceof CatchEvent || e instanceof IntermediateThrowEvent) {
return false;
}
return true;
}
@Override
protected String getStencilImageId() {
return Images.IMG_16_CANCEL;
}
/* (non-Javadoc)
* @see org.camunda.bpm.modeler.features.AbstractBpmn2CreateFeature#getBusinessObjectClass()
*/
@Override
public EClass getBusinessObjectClass() {
return Bpmn2Package.eINSTANCE.getCancelEventDefinition();
}
}
}
|
camunda/camunda-eclipse-plugin
|
org.camunda.bpm.modeler/src/org/camunda/bpm/modeler/ui/features/event/definitions/CancelEventDefinitionContainer.java
|
Java
|
epl-1.0
| 4,770 |
/*******************************************************************************
* Copyright (c) 2010, SAP AG.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Mathias Kinzler (SAP AG) - initial implementation
*******************************************************************************/
package org.eclipse.egit.ui.internal.preferences;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.eclipse.egit.core.RepositoryCache;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIText;
import org.eclipse.egit.ui.internal.SWTUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.layout.GridDataFactory;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.jgit.lib.Repository;
import org.eclipse.jgit.lib.StoredConfig;
import org.eclipse.jgit.storage.file.FileBasedConfig;
import org.eclipse.jgit.util.FS;
import org.eclipse.jgit.util.SystemReader;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StackLayout;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.TabFolder;
import org.eclipse.swt.widgets.TabItem;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* Displays the global Git configuration and allows to edit it.
* <p>
* In EGit, this maps to the user configuration.
*/
public class GlobalConfigurationPreferencePage extends PreferencePage implements
IWorkbenchPreferencePage {
/** The ID of this page */
public static final String ID = "org.eclipse.egit.ui.internal.preferences.GlobalConfigurationPreferencePage"; //$NON-NLS-1$
private FileBasedConfig userConfig;
private FileBasedConfig sysConfig;
private StackLayout repoConfigStackLayout;
private List<Repository> repositories;
private Map<Repository, ConfigurationEditorComponent> repoConfigEditors = new HashMap<Repository, ConfigurationEditorComponent>();
private Set<Repository> dirtyRepositories = new HashSet<Repository>();
private boolean userIsDirty;
private boolean sysIsDirty;
private ConfigurationEditorComponent userConfigEditor;
private ConfigurationEditorComponent sysConfigEditor;
private Composite repoConfigComposite;
@Override
protected Control createContents(Composite parent) {
Composite composite = SWTUtils.createHVFillComposite(parent,
SWTUtils.MARGINS_NONE);
TabFolder tabFolder = new TabFolder(composite, SWT.NONE);
tabFolder.setLayoutData(SWTUtils.createHVFillGridData());
userConfigEditor = new ConfigurationEditorComponent(tabFolder, userConfig, true, false) {
@Override
protected void setErrorMessage(String message) {
GlobalConfigurationPreferencePage.this.setErrorMessage(message);
}
@Override
protected void setDirty(boolean dirty) {
userIsDirty = dirty;
updateApplyButton();
}
};
sysConfigEditor = new ConfigurationEditorComponent(tabFolder, sysConfig, true, true) {
@Override
protected void setErrorMessage(String message) {
GlobalConfigurationPreferencePage.this.setErrorMessage(message);
}
@Override
protected void setDirty(boolean dirty) {
sysIsDirty = dirty;
updateApplyButton();
}
@Override
protected void setChangeSystemPrefix(String prefix) throws IOException {
FS.DETECTED.setGitPrefix(new File(prefix));
sysConfig = SystemReader.getInstance().openSystemConfig(null,
FS.DETECTED);
setConfig(sysConfig);
}
};
Control result = userConfigEditor.createContents();
Dialog.applyDialogFont(result);
TabItem userTabItem = new TabItem(tabFolder, SWT.FILL);
userTabItem.setControl(result);
userTabItem.setText(UIText.GlobalConfigurationPreferencePage_userSettingTabTitle);
result = sysConfigEditor.createContents();
Dialog.applyDialogFont(result);
TabItem sysTabItem = new TabItem(tabFolder, SWT.FILL);
sysTabItem.setControl(result);
sysTabItem.setText(UIText.GlobalConfigurationPreferencePage_systemSettingTabTitle);
Composite repoTab = new Composite(tabFolder, SWT.NONE);
GridLayoutFactory.swtDefaults().margins(0, 0).applyTo(repoTab);
GridDataFactory.fillDefaults().grab(true, true).applyTo(repoTab);
Composite repositoryComposite = new Composite(repoTab, SWT.NONE);
repositoryComposite.setLayout(new GridLayout(2, false));
GridDataFactory.fillDefaults().grab(true, false).applyTo(
repositoryComposite);
Label repoLabel = new Label(repositoryComposite, SWT.NONE);
repoLabel
.setText(UIText.GlobalConfigurationPreferencePage_repositorySettingRepositoryLabel);
Combo repoCombo = new Combo(repositoryComposite, SWT.READ_ONLY);
repoCombo.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
Combo combo = (Combo) e.widget;
showRepositoryConfiguration(combo.getSelectionIndex());
}
});
repoCombo.setItems(getRepositoryComboItems());
repoConfigComposite = new Composite(repoTab, SWT.NONE);
GridDataFactory.fillDefaults().grab(true, true).applyTo(repoConfigComposite);
repoConfigStackLayout = new StackLayout();
repoConfigComposite.setLayout(repoConfigStackLayout);
TabItem repoTabItem = new TabItem(tabFolder, SWT.FILL);
repoTabItem.setControl(repoTab);
repoTabItem.setText(UIText.GlobalConfigurationPreferencePage_repositorySettingTabTitle);
if (repoCombo.getItemCount() > 0) {
repoCombo.select(0);
showRepositoryConfiguration(0);
} else {
repoCombo.setItems(new String[] {UIText.GlobalConfigurationPreferencePage_repositorySettingNoRepositories});
repoCombo.select(0);
repoCombo.setEnabled(false);
}
return composite;
}
@Override
public void setVisible(boolean visible) {
if (visible)
updateApplyButton();
super.setVisible(visible);
}
@Override
protected void updateApplyButton() {
if (getApplyButton() != null)
getApplyButton().setEnabled(userIsDirty || sysIsDirty || !dirtyRepositories.isEmpty());
}
@Override
public boolean performOk() {
boolean ok = true;
if (userIsDirty) {
try {
userConfigEditor.save();
} catch (IOException e) {
Activator.handleError(e.getMessage(), e, true);
ok = false;
}
}
if (sysIsDirty) {
try {
sysConfigEditor.save();
} catch (IOException e) {
Activator.handleError(e.getMessage(), e, true);
ok = false;
}
}
// Use array since calling save updates the dirty state which updates
// the set of dirty repositories that is being iterated over
final Repository[] repos = dirtyRepositories
.toArray(new Repository[dirtyRepositories.size()]);
for (Repository repository : repos) {
ConfigurationEditorComponent editor = repoConfigEditors.get(repository);
try {
editor.save();
} catch (IOException e) {
Activator.handleError(e.getMessage(), e, true);
ok = false;
}
}
return ok;
}
@Override
protected void performDefaults() {
try {
userConfigEditor.restore();
sysConfigEditor.restore();
for (ConfigurationEditorComponent editor : repoConfigEditors.values()) {
editor.restore();
}
} catch (IOException e) {
Activator.handleError(e.getMessage(), e, true);
}
super.performDefaults();
}
public void init(IWorkbench workbench) {
if (sysConfig == null)
sysConfig = SystemReader.getInstance().openSystemConfig(null, FS.DETECTED);
if (userConfig == null)
userConfig = SystemReader.getInstance().openUserConfig(null, FS.DETECTED); // no inherit here!
if (repositories == null) {
repositories = new ArrayList<Repository>();
List<String> repoPaths = Activator.getDefault().getRepositoryUtil().getConfiguredRepositories();
RepositoryCache repositoryCache = org.eclipse.egit.core.Activator.getDefault().getRepositoryCache();
for (String repoPath : repoPaths) {
File gitDir = new File(repoPath);
if (!gitDir.exists())
continue;
try {
repositories.add(repositoryCache.lookupRepository(gitDir));
} catch (IOException e) {
continue;
}
}
sortRepositoriesByName();
}
}
private String getName(final Repository repo) {
return Activator.getDefault().getRepositoryUtil()
.getRepositoryName(repo);
}
private void sortRepositoriesByName() {
Collections.sort(repositories, new Comparator<Repository>() {
public int compare(Repository repo1, Repository repo2) {
return getName(repo1).compareTo(getName(repo2));
}
});
}
private String[] getRepositoryComboItems() {
List<String> items = new ArrayList<String>();
for (Repository repository : repositories) {
String repoName = getName(repository);
if (repoName.length() > 0)
items.add(repoName);
}
return items.toArray(new String[items.size()]);
}
private void showRepositoryConfiguration(int index) {
Repository repository = repositories.get(index);
ConfigurationEditorComponent editor = repoConfigEditors.get(repository);
if (editor == null) {
editor = createConfigurationEditor(repository);
repoConfigEditors.put(repository, editor);
}
repoConfigStackLayout.topControl = editor.getContents();
repoConfigComposite.layout();
}
private ConfigurationEditorComponent createConfigurationEditor(final Repository repository) {
StoredConfig repositoryConfig;
if (repository.getConfig() instanceof FileBasedConfig) {
File configFile = ((FileBasedConfig) repository.getConfig()).getFile();
repositoryConfig = new FileBasedConfig(configFile, repository
.getFS());
} else {
repositoryConfig = repository.getConfig();
}
ConfigurationEditorComponent editorComponent = new ConfigurationEditorComponent(repoConfigComposite, repositoryConfig, true, false) {
@Override
protected void setErrorMessage(String message) {
GlobalConfigurationPreferencePage.this.setErrorMessage(message);
}
@Override
protected void setDirty(boolean dirty) {
if (dirty)
dirtyRepositories.add(repository);
else
dirtyRepositories.remove(repository);
updateApplyButton();
}
};
editorComponent.createContents();
return editorComponent;
}
}
|
mdoninger/egit
|
org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/preferences/GlobalConfigurationPreferencePage.java
|
Java
|
epl-1.0
| 10,656 |
/*******************************************************************************
* Copyright (c) 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.app.api.core.exception.model;
import org.eclipse.kapua.qa.markers.junit.JUnitTests;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import javax.ws.rs.core.Response;
@Category(JUnitTests.class)
public class ThrowableInfoTest extends Assert {
Response.Status[] statusList;
int[] expectedStatusCodes;
Throwable[] throwables;
String[] expectedMessage;
@Before
public void initialize() {
statusList = new Response.Status[]{Response.Status.OK, Response.Status.CREATED, Response.Status.ACCEPTED, Response.Status.NO_CONTENT,
Response.Status.RESET_CONTENT, Response.Status.PARTIAL_CONTENT, Response.Status.MOVED_PERMANENTLY, Response.Status.FOUND,
Response.Status.SEE_OTHER, Response.Status.NOT_MODIFIED, Response.Status.USE_PROXY, Response.Status.TEMPORARY_REDIRECT,
Response.Status.BAD_REQUEST, Response.Status.UNAUTHORIZED, Response.Status.PAYMENT_REQUIRED, Response.Status.FORBIDDEN,
Response.Status.NOT_FOUND, Response.Status.METHOD_NOT_ALLOWED, Response.Status.NOT_ACCEPTABLE, Response.Status.PROXY_AUTHENTICATION_REQUIRED,
Response.Status.REQUEST_TIMEOUT, Response.Status.CONFLICT, Response.Status.GONE, Response.Status.LENGTH_REQUIRED,
Response.Status.PRECONDITION_FAILED, Response.Status.REQUEST_ENTITY_TOO_LARGE, Response.Status.REQUEST_URI_TOO_LONG, Response.Status.UNSUPPORTED_MEDIA_TYPE,
Response.Status.REQUESTED_RANGE_NOT_SATISFIABLE, Response.Status.EXPECTATION_FAILED, Response.Status.INTERNAL_SERVER_ERROR, Response.Status.NOT_IMPLEMENTED,
Response.Status.BAD_GATEWAY, Response.Status.SERVICE_UNAVAILABLE, Response.Status.GATEWAY_TIMEOUT, Response.Status.HTTP_VERSION_NOT_SUPPORTED};
expectedStatusCodes = new int[]{200, 201, 202, 204, 205, 206, 301, 302, 303, 304, 305, 307, 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 500, 501, 502, 503, 504, 505};
throwables = new Throwable[]{new Throwable(), new Throwable("message")};
expectedMessage = new String[]{null, "message"};
}
@Test
public void throwableInfoWithoutParametersTest() {
ThrowableInfo throwableInfo = new ThrowableInfo();
assertEquals("Expected and actual values should be the same.", 0, throwableInfo.getHttpErrorCode());
assertNull("Null expected.", throwableInfo.getMessage());
assertNull("Null expected.", throwableInfo.getStackTrace());
}
@Test
public void throwableInfoWithParametersFalseStackTraceTest() {
for (int i = 0; i < statusList.length; i++) {
for (int j = 0; j < throwables.length; j++) {
ThrowableInfo throwableInfo = new ThrowableInfo(statusList[i], throwables[j]);
assertEquals("Expected and actual values should be the same.", expectedStatusCodes[i], throwableInfo.getHttpErrorCode());
assertEquals("Expected and actual values should be the same.", expectedMessage[j], throwableInfo.getMessage());
assertNull("Null expected.", throwableInfo.getStackTrace());
}
}
}
@Test(expected = NullPointerException.class)
public void throwableInfoNullStatusTest() {
new ThrowableInfo(null, new Throwable());
}
@Test
public void throwableInfoNullThrowableTest() {
for (int i = 0; i < statusList.length; i++) {
ThrowableInfo throwableInfo = new ThrowableInfo(statusList[i], null);
assertEquals("Expected and actual values should be the same.", expectedStatusCodes[i], throwableInfo.getHttpErrorCode());
assertNull("Null expected.", throwableInfo.getMessage());
assertNull("Null expected.", throwableInfo.getStackTrace());
}
}
@Test
public void setAndGetHttpErrorCodeTest() {
ThrowableInfo throwableInfo1 = new ThrowableInfo();
ThrowableInfo throwableInfo2 = new ThrowableInfo(Response.Status.OK, new Throwable());
for (int i = 0; i < statusList.length; i++) {
throwableInfo1.setHttpErrorCode(statusList[i]);
assertEquals("Expected and actual values should be the same.", expectedStatusCodes[i], throwableInfo1.getHttpErrorCode());
}
try {
throwableInfo1.setHttpErrorCode(null);
fail("Exception expected.");
} catch (Exception e) {
assertEquals("NullPointerException expected.", new NullPointerException().toString(), e.toString());
}
for (int i = 0; i < statusList.length; i++) {
throwableInfo2.setHttpErrorCode(statusList[i]);
assertEquals("Expected and actual values should be the same.", expectedStatusCodes[i], throwableInfo2.getHttpErrorCode());
}
try {
throwableInfo2.setHttpErrorCode(null);
fail("Exception expected.");
} catch (Exception e) {
assertEquals("NullPointerException expected.", new NullPointerException().toString(), e.toString());
}
}
@Test
public void setAndGetMessageTest() {
ThrowableInfo throwableInfo1 = new ThrowableInfo();
ThrowableInfo throwableInfo2 = new ThrowableInfo(Response.Status.OK, new Throwable());
String[] messages = {null, "", "mess_age", "message#123", "@message-333", "message<9>,", "(1*2)m,."};
for (int i = 0; i < messages.length; i++) {
throwableInfo1.setMessage(messages[i]);
assertEquals("Expected and actual values should be the same.", messages[i], throwableInfo1.getMessage());
}
for (int i = 0; i < messages.length; i++) {
throwableInfo2.setMessage(messages[i]);
assertEquals("Expected and actual values should be the same.", messages[i], throwableInfo2.getMessage());
}
}
}
|
stzilli/kapua
|
rest-api/core/src/test/java/org/eclipse/kapua/app/api/core/exception/model/ThrowableInfoTest.java
|
Java
|
epl-1.0
| 6,481 |
.signup-widget {
margin-top: 30px;
background-color: #eee;
padding-top: 8%;
padding-left: 10%;
padding-right: 10%;
padding-bottom: 10%;
}
.signup-title {
text-align: center;
color: #333;
font-size: 50px;
}
.signup-pane {
background-color: white;
margin-top: 10px;
height: 350px;
padding: 20px;
}
.signup-fields > input {
font-size: 20px;
height: 36px;
width: 85%;
border: 2px solid #666;
border-radius: 4px;
margin: 20px;
margin-left: 0px;
padding-left: 4px;
padding-right: 4px;
}
button.next-button {
position: absolute;
bottom: 120px;
left: 50%;
margin-left: -65px;
color: #333;
font-size: 20px;
width: 130px;
height: 40px;
background-color: #eee;
border: none;
border-radius: 4px;
}
button.next-button:hover {
background-color: #ccc;
}
.signup-arrow {
margin-left: -20px;
left: 50%;
color: #70767c;
font-size: 40px;
}
.signup-indicators {
position: relative;
margin-left: -90px;
left: 50%;
margin-top: 10px;
}
.signup-indicators li {
display: inline-block;
width: 20px;
height: 20px;
margin: 6px;
cursor: pointer;
background-color: #ccc;
border-radius: 20px;
}
.signup-indicators li.active {
background-color: #666;
}
|
continuata/stayhere-org-uk
|
resources/public/css/signup.css
|
CSS
|
epl-1.0
| 1,245 |
/*******************************************************************************
* Copyright (c) 2018, 2021 Eurotech and/or its affiliates and others
*
* This program and the accompanying materials are made
* available under the terms of the Eclipse Public License 2.0
* which is available at https://www.eclipse.org/legal/epl-2.0/
*
* SPDX-License-Identifier: EPL-2.0
*
* Contributors:
* Eurotech - initial API and implementation
*******************************************************************************/
package org.eclipse.kapua.app.console.module.endpoint.client;
import org.eclipse.kapua.app.console.module.api.client.messages.ConsoleMessages;
import org.eclipse.kapua.app.console.module.api.client.messages.ValidationMessages;
import org.eclipse.kapua.app.console.module.api.client.ui.dialog.entity.EntityAddEditDialog;
import org.eclipse.kapua.app.console.module.api.client.ui.panel.FormPanel;
import org.eclipse.kapua.app.console.module.api.client.ui.validator.RegexFieldValidator;
import org.eclipse.kapua.app.console.module.api.client.ui.widget.KapuaNumberField;
import org.eclipse.kapua.app.console.module.api.client.ui.widget.KapuaTextField;
import org.eclipse.kapua.app.console.module.api.client.util.ConsoleInfo;
import org.eclipse.kapua.app.console.module.api.client.util.DialogUtils;
import org.eclipse.kapua.app.console.module.api.client.util.FailureHandler;
import org.eclipse.kapua.app.console.module.api.shared.model.session.GwtSession;
import org.eclipse.kapua.app.console.module.endpoint.client.messages.ConsoleEndpointMessages;
import org.eclipse.kapua.app.console.module.endpoint.shared.model.GwtEndpoint;
import org.eclipse.kapua.app.console.module.endpoint.shared.model.GwtEndpointCreator;
import org.eclipse.kapua.app.console.module.endpoint.shared.model.validation.GwtEndpointValidationRegex;
import org.eclipse.kapua.app.console.module.endpoint.shared.service.GwtEndpointService;
import org.eclipse.kapua.app.console.module.endpoint.shared.service.GwtEndpointServiceAsync;
import org.eclipse.kapua.service.endpoint.EndpointInfo;
import com.extjs.gxt.ui.client.widget.form.CheckBox;
import com.extjs.gxt.ui.client.widget.form.CheckBoxGroup;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
public class EndpointAddDialog extends EntityAddEditDialog {
private static final GwtEndpointServiceAsync GWT_ENDPOINT_SERVICE = GWT.create(GwtEndpointService.class);
private static final ConsoleEndpointMessages MSGS = GWT.create(ConsoleEndpointMessages.class);
private static final ConsoleMessages CMSGS = GWT.create(ConsoleMessages.class);
private static final ValidationMessages VAL_MSGS = GWT.create(ValidationMessages.class);
protected KapuaTextField<String> endpointSchemaField;
protected KapuaTextField<String> endpointDnsField;
protected KapuaNumberField endpointPortField;
protected CheckBoxGroup endpointSecureCheckboxGroup;
protected CheckBox endpointSercureCheckbox;
public EndpointAddDialog(GwtSession currentSession) {
super(currentSession);
DialogUtils.resizeDialog(this, 400, 220);
}
@Override
public void createBody() {
submitButton.disable();
FormPanel endpointFormPanel = new FormPanel(FORM_LABEL_WIDTH);
endpointSchemaField = new KapuaTextField<String>();
endpointSchemaField.setAllowBlank(false);
endpointSchemaField.setFieldLabel("* " + MSGS.dialogAddFieldSchema());
endpointSchemaField.setToolTip(MSGS.dialogAddFieldSchemaTooltip());
endpointSchemaField.setValidator(new RegexFieldValidator(GwtEndpointValidationRegex.URI_SCHEME, MSGS.dialogAddFieldSchemaValidation()));
endpointSchemaField.setMaxLength(64);
endpointFormPanel.add(endpointSchemaField);
endpointDnsField = new KapuaTextField<String>();
endpointDnsField.setAllowBlank(false);
endpointDnsField.setFieldLabel("* " + MSGS.dialogAddFieldDns());
endpointDnsField.setToolTip(MSGS.dialogAddFieldDnsTooltip());
endpointDnsField.setValidator(new RegexFieldValidator(GwtEndpointValidationRegex.URI_DNS, MSGS.dialogAddFieldDnsValidation()));
endpointDnsField.setMaxLength(1024);
endpointFormPanel.add(endpointDnsField);
endpointPortField = new KapuaNumberField();
endpointPortField.setAllowBlank(false);
endpointPortField.setFieldLabel("* " + MSGS.dialogAddFieldPort());
endpointPortField.setToolTip(MSGS.dialogAddFieldPortTooltip());
endpointPortField.setValidator(new RegexFieldValidator(GwtEndpointValidationRegex.URI_PORT, MSGS.dialogAddFieldPortValidation()));
endpointPortField.setAllowNegative(false);
endpointPortField.setAllowDecimals(false);
endpointPortField.setMaxLength(5);
endpointPortField.setMinValue(1);
endpointPortField.setMaxValue(65535);
endpointPortField.setPropertyEditorType(Integer.class);
endpointFormPanel.add(endpointPortField);
endpointSercureCheckbox = new CheckBox();
endpointSercureCheckbox.setBoxLabel("");
endpointSercureCheckbox.setToolTip(MSGS.dialogAddFieldSecureTooltip());
endpointSecureCheckboxGroup = new CheckBoxGroup();
endpointSecureCheckboxGroup.setFieldLabel(MSGS.dialogAddFieldSecure());
endpointSecureCheckboxGroup.add(endpointSercureCheckbox);
endpointFormPanel.add(endpointSecureCheckboxGroup);
bodyPanel.add(endpointFormPanel);
}
public void validateEndPoint() {
if (endpointSchemaField.getValue() == null || endpointDnsField.getValue() == null) {
ConsoleInfo.display(CMSGS.error(), CMSGS.allFieldsRequired());
} else if (endpointPortField.getValue() == null) {
ConsoleInfo.display(CMSGS.error(), MSGS.portFieldEmptyOrInvalid());
} else if (!endpointSchemaField.isValid()) {
ConsoleInfo.display(CMSGS.error(), endpointSchemaField.getErrorMessage());
} else if (!endpointDnsField.isValid()) {
ConsoleInfo.display(CMSGS.error(), endpointDnsField.getErrorMessage());
} else if (!endpointPortField.isValid()) {
ConsoleInfo.display(CMSGS.error(), endpointPortField.getErrorMessage());
}
}
@Override
protected void preSubmit() {
validateEndPoint();
super.preSubmit();
}
@Override
public void submit() {
GwtEndpointCreator gwtEndpointCreator = new GwtEndpointCreator();
gwtEndpointCreator.setScopeId(currentSession.getSelectedAccountId());
gwtEndpointCreator.setSchema(endpointSchemaField.getValue());
gwtEndpointCreator.setDns(endpointDnsField.getValue());
gwtEndpointCreator.setPort(endpointPortField.getValue());
gwtEndpointCreator.setSecure(endpointSecureCheckboxGroup.getValue() != null);
gwtEndpointCreator.setEndpointType(EndpointInfo.ENDPOINT_TYPE_RESOURCE);
GWT_ENDPOINT_SERVICE.create(gwtEndpointCreator, new AsyncCallback<GwtEndpoint>() {
@Override
public void onSuccess(GwtEndpoint gwtEndpoint) {
exitStatus = true;
exitMessage = MSGS.dialogAddConfirmation();
hide();
}
@Override
public void onFailure(Throwable cause) {
exitStatus = false;
status.hide();
formPanel.getButtonBar().enable();
unmask();
submitButton.enable();
cancelButton.enable();
if (!isPermissionErrorMessage(cause)) {
FailureHandler.handleFormException(formPanel, cause);
endpointDnsField.markInvalid(VAL_MSGS.DUPLICATE_NAME());
endpointSchemaField.markInvalid(VAL_MSGS.DUPLICATE_NAME());
endpointPortField.markInvalid(VAL_MSGS.DUPLICATE_NAME());
}
}
});
}
@Override
public String getHeaderMessage() {
return MSGS.dialogAddHeader();
}
@Override
public String getInfoMessage() {
return MSGS.dialogAddInfo();
}
}
|
stzilli/kapua
|
console/module/endpoint/src/main/java/org/eclipse/kapua/app/console/module/endpoint/client/EndpointAddDialog.java
|
Java
|
epl-1.0
| 8,175 |
var util = require("./util.js");
var types = util.types;
var countParens = util.countParens;
var matchParen = util.matchParen;
var inArray = util.inArray;
var operators_before_exp = ["=","<",">","."];
function Call(token)
{
this.token = token;
}
//test for a function call starting at the given token index
function testFuncDecl(statement, start, parenLevel)
{
var t = statement.length;
if(statement[start].type === types.IDENTIFIER) //function name
{
if(((start+1) < t) && (statement[start+1].type === types.OPEN_PAREN)) //open paren
{
//find matching paren
var close = matchParen(statement, start+1);
if(close !== -1) //close paren
{
if(start === 0) //if its got nothing before it, it gauranteed to be a call (not a prototyp)
{
return true;
}
else if(parenLevel > 0) //if it's inside parens, it can't be a prototype, it must be a call
{
return true;
}
else
{
//look at previous tokens to see if there were tokens that indicate expression or function call
//as opposed to a prototype
for(var p = 0; p < start; p++)
{
var prev = statement[p];
if((prev.type === types.UNKNOWN) && inArray(prev.name, operators_before_exp))
return true;
else if((prev.type === types.KEYWORD_OTHER) && (prev.name === "return"))
return true;
}
}
}
}
}
return false;
}
module.exports = function(statements) {
var calls = [];
//find function definitions
for(var i = 0; i < statements.length; i++)
{
var statement = statements[i];
var parenLevel = 0;
//minimum number of tokens needed to form function DECLARATION
// main ( ) ;
if(statement.length >= 3)
{
for(var t = 0; t < statement.length - 3; t++)
{
var token = statement[t];
parenLevel += countParens(token);
//test using this position as a starting point
if(testFuncDecl(statement, t, parenLevel))
{
//oh boy oh boy oh boy!!
var c = new Call(token);
calls.push(c);
}
}
}
}
return calls;
};
|
brendan-w/cgraph
|
server/parser/detect_calls.js
|
JavaScript
|
gpl-2.0
| 2,053 |
<?php /* Smarty version Smarty-3.1.6, created on 2011-12-19 07:57:24
compiled from "/Users/ericdum/Sites/work/sixue365/1/templates/header.php" */ ?>
<?php /*%%SmartyHeaderCode:19498921484eee7de4d6fe15-00538420%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_valid = $_smarty_tpl->decodeProperties(array (
'file_dependency' =>
array (
'27475b257fa0af3c3fed0fae895d4860fedbc1ba' =>
array (
0 => '/Users/ericdum/Sites/work/sixue365/1/templates/header.php',
1 => 1323961277,
2 => 'file',
),
),
'nocache_hash' => '19498921484eee7de4d6fe15-00538420',
'function' =>
array (
),
'has_nocache_code' => false,
'version' => 'Smarty-3.1.6',
'unifunc' => 'content_4eee7de4d8435',
),false); /*/%%SmartyHeaderCode%%*/?>
<?php if ($_valid && !is_callable('content_4eee7de4d8435')) {function content_4eee7de4d8435($_smarty_tpl) {?><div id="header" class="clearfix">
<div class="floatLeft">
<div id="logo" class="floatLeft">
<a href="http://localhost/work/sixue365/1/"><img src="./images/logo.png"/></a>
</div>
<div id="slogan" class="floatLeft">
<img src="./images/slogan.png">
</div>
</div>
<div class="contact400 floatRight">
<img src="./images/phone.png" class="marginRight5 marginTopm7">: 4008100100-256
</div>
</div>
<?php }} ?>
|
ericdum/niuble.com
|
other_sites/showcases/sixue/templates_c/27475b257fa0af3c3fed0fae895d4860fedbc1ba.file.header.php.cache.php
|
PHP
|
gpl-2.0
| 1,375 |
<?php
//initializarea sesiunii
function session_set(){
ini_set('session.use_only_cookies', 1);// se vor folosi numai cookie-uri pt transmiterea id-ului de sesiune
session_start();
setcookie(session_name(), session_id(), time() + 2*60, "/"); // prelungeste viata cookie-ului de la ultimul click
}
function logged_in() {
return isset($_SESSION['user_id']);
}
function confirm_logged_in() {
if (!logged_in()) {
redirect_to("login.php");
}
}
function logged_out(){
// 1. Gasesc sesiunea
session_set();
// 2. Sterg toate variabilele sesiunii
$_SESSION = array();//sau unset($_SESSION)
// 3. Sterg cookie-ul de sesiune
if(isset($_COOKIE[session_name()])) {
setcookie(session_name(), '', time()-42000, '/');
}
// 4. Sterg fisierul de pe server asociat sesiunii
session_destroy();
}
?>
|
completit/PHP-MySql
|
curs09/00_rec_proiect_cms/cms_07/includes/session.php
|
PHP
|
gpl-2.0
| 844 |
/*
* Copyright (c) 2010, 2013, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package jdk.nashorn.internal.ir;
import jdk.nashorn.internal.codegen.types.Type;
import jdk.nashorn.internal.ir.annotations.Immutable;
import jdk.nashorn.internal.ir.visitor.NodeVisitor;
/**
* IR representation of a property access (period operator.)
*/
@Immutable
public final class AccessNode extends BaseNode {
/** Property name. */
private final String property;
/**
* Constructor
*
* @param token token
* @param finish finish
* @param base base node
* @param property property
*/
public AccessNode(final long token, final int finish, final Expression base, final String property) {
super(token, finish, base, false);
this.property = property;
}
private AccessNode(final AccessNode accessNode, final Expression base, final String property, final boolean isFunction, final Type type, final int id) {
super(accessNode, base, isFunction, type, id);
this.property = property;
}
/**
* Assist in IR navigation.
* @param visitor IR navigating visitor.
*/
@Override
public Node accept(final NodeVisitor<? extends LexicalContext> visitor) {
if (visitor.enterAccessNode(this)) {
return visitor.leaveAccessNode(
setBase((Expression)base.accept(visitor)));
}
return this;
}
@Override
public void toString(final StringBuilder sb, final boolean printType) {
final boolean needsParen = tokenType().needsParens(getBase().tokenType(), true);
if (printType) {
optimisticTypeToString(sb);
}
if (needsParen) {
sb.append('(');
}
base.toString(sb, printType);
if (needsParen) {
sb.append(')');
}
sb.append('.');
sb.append(property);
}
/**
* Get the property name
*
* @return the property name
*/
public String getProperty() {
return property;
}
private AccessNode setBase(final Expression base) {
if (this.base == base) {
return this;
}
return new AccessNode(this, base, property, isFunction(), type, programPoint);
}
@Override
public AccessNode setType(final Type type) {
if (this.type == type) {
return this;
}
return new AccessNode(this, base, property, isFunction(), type, programPoint);
}
@Override
public AccessNode setProgramPoint(final int programPoint) {
if (this.programPoint == programPoint) {
return this;
}
return new AccessNode(this, base, property, isFunction(), type, programPoint);
}
@Override
public AccessNode setIsFunction() {
if (isFunction()) {
return this;
}
return new AccessNode(this, base, property, true, type, programPoint);
}
}
|
hazzik/nashorn
|
src/jdk/nashorn/internal/ir/AccessNode.java
|
Java
|
gpl-2.0
| 4,118 |
#include <utils/Log.h>
#include <fcntl.h>
#include <math.h>
#include "camera_custom_nvram.h"
#include "camera_custom_sensor.h"
#include "image_sensor.h"
#include "kd_imgsensor_define.h"
#include "camera_AE_PLineTable_ov8850raw.h"
#include "camera_info_ov8850raw.h"
#include "camera_custom_AEPlinetable.h"
const NVRAM_CAMERA_ISP_PARAM_STRUCT CAMERA_ISP_DEFAULT_VALUE =
{{
//Version
Version: NVRAM_CAMERA_PARA_FILE_VERSION,
//SensorId
SensorId: SENSOR_ID,
ISPComm:{
{
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
}
},
ISPPca:{
#include INCLUDE_FILENAME_ISP_PCA_PARAM
},
ISPRegs:{
#include INCLUDE_FILENAME_ISP_REGS_PARAM
},
ISPMfbMixer:{{
{//00: MFB mixer for ISO 100
0x00000000, 0x00000000
},
{//01: MFB mixer for ISO 200
0x00000000, 0x00000000
},
{//02: MFB mixer for ISO 400
0x00000000, 0x00000000
},
{//03: MFB mixer for ISO 800
0x00000000, 0x00000000
},
{//04: MFB mixer for ISO 1600
0x00000000, 0x00000000
},
{//05: MFB mixer for ISO 2400
0x00000000, 0x00000000
},
{//06: MFB mixer for ISO 3200
0x00000000, 0x00000000
}
}},
ISPCcmPoly22:{
80650, // i4R_AVG
16601, // i4R_STD
88575, // i4B_AVG
18234, // i4B_STD
{ // i4P00[9]
5070000, -2380000, -127500, -837500, 4082500, -687500, -67500, -2477500, 5105000
},
{ // i4P10[9]
2839740, -2934101, 84573, -431329, -469658, 910297, 106513, 1535044, -1673300
},
{ // i4P01[9]
2522353, -2479441, -52433, -600990, -417886, 1024162, -40114, 684322, -679998
},
{ // i4P20[9]
0, 0, 0, 0, 0, 0, 0, 0, 0
},
{ // i4P11[9]
0, 0, 0, 0, 0, 0, 0, 0, 0
},
{ // i4P02[9]
0, 0, 0, 0, 0, 0, 0, 0, 0
}
}
}};
const NVRAM_CAMERA_3A_STRUCT CAMERA_3A_NVRAM_DEFAULT_VALUE =
{
NVRAM_CAMERA_3A_FILE_VERSION, // u4Version
SENSOR_ID, // SensorId
// AE NVRAM
{
// rDevicesInfo
/*
{
1152, // u4MinGain, 1024 base = 1x
8000, // u4MaxGain, 16x
75, // u4MiniISOGain, ISOxx
64, // u4GainStepUnit, 1x/8
17, // u4PreExpUnit
30, // u4PreMaxFrameRate
17, // u4VideoExpUnit
30, // u4VideoMaxFrameRate
1024, // u4Video2PreRatio, 1024 base = 1x
16, // u4CapExpUnit
25, // u4CapMaxFrameRate
1024, // u4Cap2PreRatio, 1024 base = 1x
22, // u4LensFno, Fno = 2.8
350 // u4FocusLength_100x
},
*/
{
1152, // u4MinGain, 1024 base = 1x
8000, // u4MaxGain, 16x
75, // u4MiniISOGain, ISOxx
64, // u4GainStepUnit, 1x/8
27, // u4PreExpUnit
30, // u4PreMaxFrameRate
27, // u4VideoExpUnit
30, // u4VideoMaxFrameRate
1024, // u4Video2PreRatio, 1024 base = 1x
27, // u4CapExpUnit
14, // u4CapMaxFrameRate
1024, // u4Cap2PreRatio, 1024 base = 1x
22, // u4LensFno, Fno = 2.8
350 // u4FocusLength_100x
},
// rHistConfig
{
3, //4, // u4HistHighThres
40, // u4HistLowThres
1, //2, // u4MostBrightRatio
1, // u4MostDarkRatio
160, // u4CentralHighBound
20, // u4CentralLowBound
{240, 230, 220, 210, 200}, // u4OverExpThres[AE_CCT_STRENGTH_NUM]
{75, 108, 138, 148, 170}, // u4HistStretchThres[AE_CCT_STRENGTH_NUM]
{18, 22, 26, 30, 34} // u4BlackLightThres[AE_CCT_STRENGTH_NUM]
},
// rCCTConfig
{
TRUE, // bEnableBlackLight
TRUE, // bEnableHistStretch
FALSE, // bEnableAntiOverExposure
TRUE, // bEnableTimeLPF
FALSE, // bEnableCaptureThres
FALSE, // bEnableVideoThres
FALSE, // bEnableStrobeThres
47, // u4AETarget
47, // u4StrobeAETarget
20, //50, // u4InitIndex
4, // u4BackLightWeight
32, // u4HistStretchWeight
4, // u4AntiOverExpWeight
2, // u4BlackLightStrengthIndex
2, // u4HistStretchStrengthIndex
2, // u4AntiOverExpStrengthIndex
2, // u4TimeLPFStrengthIndex
{1, 3, 5, 7, 8}, // u4LPFConvergeTable[AE_CCT_STRENGTH_NUM]
90, // u4InDoorEV = 9.0, 10 base
-8, //-10, // i4BVOffset delta BV = value/10
70, //64, // u4PreviewFlareOffset
70,//64, // u4CaptureFlareOffset
3, // u4CaptureFlareThres
70, //64, // u4VideoFlareOffset
3, // u4VideoFlareThres
70,//64, // u4StrobeFlareOffset
3, // u4StrobeFlareThres
160, // u4PrvMaxFlareThres
0, // u4PrvMinFlareThres
160, // u4VideoMaxFlareThres
0, // u4VideoMinFlareThres
18, // u4FlatnessThres // 10 base for flatness condition.
64 //75 // u4FlatnessStrength
}
},
// AWB NVRAM
{
// AWB calibration data
{
// rUnitGain (unit gain: 1.0 = 512)
{
0, // i4R
0, // i4G
0 // i4B
},
// rGoldenGain (golden sample gain: 1.0 = 512)
{
0, // i4R
0, // i4G
0 // i4B
},
// rTuningUnitGain (Tuning sample unit gain: 1.0 = 512)
{
0, // i4R
0, // i4G
0 // i4B
},
// rD65Gain (D65 WB gain: 1.0 = 512)
{
1016, // i4R //1016---906
512, // i4G
655 // i4B //655--->685
}
},
// Original XY coordinate of AWB light source
{
// Strobe
{
145, // i4X
-298 // i4Y
},
// Horizon
{
-338, // i4X
-327 // i4Y
},
// A
{
-217, // i4X
-339 // i4Y
},
// TL84
{
-59, // i4X
-379 // i4Y
},
// CWF
{
-26, // i4X
-411 // i4Y
},
// DNP
{
34, // i4X
-371 // i4Y
},
// D65
{
162, // i4X
-344 // i4Y
},
// DF
{
123, // i4X
-399 // i4Y
}
},
// Rotated XY coordinate of AWB light source
{
// Strobe
{
145, // i4X
-298 // i4Y
},
// Horizon
{
-338, // i4X
-327 // i4Y
},
// A
{
-217, // i4X
-339 // i4Y
},
// TL84
{
-59, // i4X
-379 // i4Y
},
// CWF
{
-26, // i4X
-411 // i4Y
},
// DNP
{
34, // i4X
-371 // i4Y
},
// D65
{
162, // i4X
-344 // i4Y
},
// DF
{
123, // i4X
-399 // i4Y
}
},
// AWB gain of AWB light source
{
// Strobe
{
932, // i4R
512, // i4G
630 // i4B
},
// Horizon
{
512, // i4R
520, // i4G
1280 // i4B
},
// A
{
603, // i4R
512, // i4G
1087 // i4B
},
// TL84
{
790, // i4R
512, // i4G
927 // i4B
},
// CWF
{
862, // i4R
512, // i4G
926 // i4B
},
// DNP
{
886, // i4R
512, // i4G
807 // i4B
},
// D65
{
1016, // i4R
512, // i4G
655 // i4B
},
// DF
{
1038, // i4R
512, // i4G
744 // i4B
}
},
// Rotation matrix parameter
{
0, // i4RotationAngle
256, // i4Cos
0 // i4Sin
},
// Daylight locus parameter
{
-126, // i4SlopeNumerator
128 // i4SlopeDenominator
},
// AWB light area
{
// Strobe:FIXME
{
0, // i4RightBound
0, // i4LeftBound
0, // i4UpperBound
0 // i4LowerBound
},
// Tungsten
{
-109, // i4RightBound
-759, // i4LeftBound
-253, // i4UpperBound
-393 // i4LowerBound
},
// Warm fluorescent
{
-109, // i4RightBound
-759, // i4LeftBound
-393, // i4UpperBound
-503 // i4LowerBound
},
// Fluorescent
{
-16, // i4RightBound
-109, // i4LeftBound
-273, // i4UpperBound
-395 // i4LowerBound
},
// CWF
{
-16, // i4RightBound
-109, // i4LeftBound
-395, // i4UpperBound
-461 // i4LowerBound
},
// Daylight
{
187, // i4RightBound
-16, // i4LeftBound
-254, // i4UpperBound
-434 // i4LowerBound
},
// Shade
{
547, // i4RightBound
187, // i4LeftBound
-254, // i4UpperBound
-434 // i4LowerBound
},
// Daylight Fluorescent
{
130, // i4RightBound
-16, // i4LeftBound
-434, // i4UpperBound
-504 // i4LowerBound
}
},
// PWB light area
{
// Reference area
{
547, // i4RightBound
-759, // i4LeftBound
0, // i4UpperBound
-504 // i4LowerBound
},
// Daylight
{
212, // i4RightBound
-16, // i4LeftBound
-254, // i4UpperBound
-434 // i4LowerBound
},
// Cloudy daylight
{
312, // i4RightBound
137, // i4LeftBound
-254, // i4UpperBound
-434 // i4LowerBound
},
// Shade
{
412, // i4RightBound
137, // i4LeftBound
-254, // i4UpperBound
-434 // i4LowerBound
},
// Twilight
{
-16, // i4RightBound
-176, // i4LeftBound
-254, // i4UpperBound
-434 // i4LowerBound
},
// Fluorescent
{
212, // i4RightBound
-159, // i4LeftBound
-294, // i4UpperBound
-461 // i4LowerBound
},
// Warm fluorescent
{
-107, // i4RightBound
-317, // i4LeftBound
-244, // i4UpperBound
-411 // i4LowerBound
},
// Incandescent
{
-107, // i4RightBound
-317, // i4LeftBound
-224, // i4UpperBound
-404 // i4LowerBound
},
// Gray World
{
5000, // i4RightBound
-5000, // i4LeftBound
5000, // i4UpperBound
-5000 // i4LowerBound
}
},
// PWB default gain
{
// Daylight
{
931, // i4R
512, // i4G
714 // i4B
},
// Cloudy daylight
{
1105, // i4R
512, // i4G
602 // i4B
},
// Shade
{
1183, // i4R
512, // i4G
563 // i4B
},
// Twilight
{
716, // i4R
512, // i4G
929 // i4B
},
// Fluorescent
{
885, // i4R
512, // i4G
823 // i4B
},
// Warm fluorescent
{
599, // i4R
512, // i4G
1063 // i4B
},
// Incandescent
{
588, // i4R
512, // i4G
1044 // i4B
},
// Gray World
{
512, // i4R
512, // i4G
512 // i4B
}
},
// AWB preference color
{
// Tungsten
{
0, // i4SliderValue
6144 // i4OffsetThr
},
// Warm fluorescent
{
0, // i4SliderValue
4692 // i4OffsetThr
},
// Shade
{
0, // i4SliderValue
1341 // i4OffsetThr
},
// Daylight WB gain
{
854, // i4R
536, // i4G
512 // i4B
},
// Preference gain: strobe
{
512, // i4R
512, // i4G
512 // i4B
},
// Preference gain: tungsten
{
512, // i4R
512, // i4G
520 // i4B
},
// Preference gain: warm fluorescent
{
512, // i4R
512, // i4G
516 // i4B
},
// Preference gain: fluorescent
{
498, // i4R
512, // i4G
525 // i4B
},
// Preference gain: CWF
{
512, // i4R
512, // i4G
525 // i4B
},
// Preference gain: daylight
{
502, //506 , // i4R
512, // i4G
526 //518 // i4B
},
// Preference gain: shade
{
504, //506, // i4R
512, // i4G
524 //518 // i4B
},
// Preference gain: daylight fluorescent
{
512, // i4R
512, // i4G
514 // i4B
}
},
{// CCT estimation
{// CCT
2300, // i4CCT[0]
2850, // i4CCT[1]
4100, // i4CCT[2]
5100, // i4CCT[3]
6500 // i4CCT[4]
},
{// Rotated X coordinate
-500, // i4RotatedXCoordinate[0]
-379, // i4RotatedXCoordinate[1]
-221, // i4RotatedXCoordinate[2]
-128, // i4RotatedXCoordinate[3]
0 // i4RotatedXCoordinate[4]
}
}
},
{0}
};
#include INCLUDE_FILENAME_ISP_LSC_PARAM
//}; // namespace
typedef NSFeature::RAWSensorInfo<SENSOR_ID> SensorInfoSingleton_T;
namespace NSFeature {
template <>
UINT32
SensorInfoSingleton_T::
impGetDefaultData(CAMERA_DATA_TYPE_ENUM const CameraDataType, VOID*const pDataBuf, UINT32 const size) const
{
UINT32 dataSize[CAMERA_DATA_TYPE_NUM] = {sizeof(NVRAM_CAMERA_ISP_PARAM_STRUCT),
sizeof(NVRAM_CAMERA_3A_STRUCT),
sizeof(NVRAM_CAMERA_SHADING_STRUCT),
sizeof(NVRAM_LENS_PARA_STRUCT),
sizeof(AE_PLINETABLE_T)};
if (CameraDataType > CAMERA_DATA_AE_PLINETABLE || NULL == pDataBuf || (size < dataSize[CameraDataType]))
{
return 1;
}
switch(CameraDataType)
{
case CAMERA_NVRAM_DATA_ISP:
memcpy(pDataBuf,&CAMERA_ISP_DEFAULT_VALUE,sizeof(NVRAM_CAMERA_ISP_PARAM_STRUCT));
break;
case CAMERA_NVRAM_DATA_3A:
memcpy(pDataBuf,&CAMERA_3A_NVRAM_DEFAULT_VALUE,sizeof(NVRAM_CAMERA_3A_STRUCT));
break;
case CAMERA_NVRAM_DATA_SHADING:
memcpy(pDataBuf,&CAMERA_SHADING_DEFAULT_VALUE,sizeof(NVRAM_CAMERA_SHADING_STRUCT));
break;
case CAMERA_DATA_AE_PLINETABLE:
memcpy(pDataBuf,&g_PlineTableMapping,sizeof(AE_PLINETABLE_T));
break;
default:
break;
}
return 0;
}}; // NSFeature
|
PaoloW8/kernel_ZOPO
|
mediatek/custom/mt6589/hal/imgsensor/ov8850_mipi_raw/camera_tuning_para_ov8850raw.cpp
|
C++
|
gpl-2.0
| 18,551 |
/*
* This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef TRINITY_MOVEMENTGENERATOR_IMPL_H
#define TRINITY_MOVEMENTGENERATOR_IMPL_H
#include "MovementGenerator.h"
template<class MOVEMENT_GEN>
inline MovementGenerator*
MovementGeneratorFactory<MOVEMENT_GEN>::Create(void * /*data*/) const
{
return (new MOVEMENT_GEN());
}
#endif
|
Traesh/TrinityCore
|
src/server/game/Movement/MovementGeneratorImpl.h
|
C
|
gpl-2.0
| 1,031 |
/*
* ext4.h
*
* Copyright (C) 1992, 1993, 1994, 1995
* Remy Card ([email protected])
* Laboratoire MASI - Institut Blaise Pascal
* Universite Pierre et Marie Curie (Paris VI)
*
* from
*
* linux/include/linux/minix_fs.h
*
* Copyright (C) 1991, 1992 Linus Torvalds
*/
#ifndef _EXT4_H
#define _EXT4_H
#include <linux/types.h>
#include <linux/blkdev.h>
#include <linux/magic.h>
#include <linux/jbd2.h>
#include <linux/quota.h>
#include <linux/rwsem.h>
#include <linux/rbtree.h>
#include <linux/seqlock.h>
#include <linux/mutex.h>
#include <linux/timer.h>
#include <linux/wait.h>
#include <linux/blockgroup_lock.h>
#include <linux/percpu_counter.h>
#include <linux/ratelimit.h>
#ifdef __KERNEL__
#include <linux/compat.h>
#endif
/*
* The fourth extended filesystem constants/structures
*/
/*
* Define EXT4FS_DEBUG to produce debug messages
*/
#undef EXT4FS_DEBUG
/*
* Debug code
*/
#ifdef EXT4FS_DEBUG
#define ext4_debug(f, a...) \
do { \
printk(KERN_DEBUG "EXT4-fs DEBUG (%s, %d): %s:", \
__FILE__, __LINE__, __func__); \
printk(KERN_DEBUG f, ## a); \
} while (0)
#else
#define ext4_debug(fmt, ...) no_printk(fmt, ##__VA_ARGS__)
#endif
#define EXT4_ERROR_INODE(inode, fmt, a...) \
ext4_error_inode((inode), __func__, __LINE__, 0, (fmt), ## a)
#define EXT4_ERROR_INODE_BLOCK(inode, block, fmt, a...) \
ext4_error_inode((inode), __func__, __LINE__, (block), (fmt), ## a)
#define EXT4_ERROR_FILE(file, block, fmt, a...) \
ext4_error_file((file), __func__, __LINE__, (block), (fmt), ## a)
/* data type for block offset of block group */
typedef int ext4_grpblk_t;
/* data type for filesystem-wide blocks number */
typedef unsigned long long ext4_fsblk_t;
/* data type for file logical block number */
typedef __u32 ext4_lblk_t;
/* data type for block group number */
typedef unsigned int ext4_group_t;
/*
* Flags used in mballoc's allocation_context flags field.
*
* Also used to show what's going on for debugging purposes when the
* flag field is exported via the traceport interface
*/
/* prefer goal again. length */
#define EXT4_MB_HINT_MERGE 0x0001
/* blocks already reserved */
#define EXT4_MB_HINT_RESERVED 0x0002
/* metadata is being allocated */
#define EXT4_MB_HINT_METADATA 0x0004
/* first blocks in the file */
#define EXT4_MB_HINT_FIRST 0x0008
/* search for the best chunk */
#define EXT4_MB_HINT_BEST 0x0010
/* data is being allocated */
#define EXT4_MB_HINT_DATA 0x0020
/* don't preallocate (for tails) */
#define EXT4_MB_HINT_NOPREALLOC 0x0040
/* allocate for locality group */
#define EXT4_MB_HINT_GROUP_ALLOC 0x0080
/* allocate goal blocks or none */
#define EXT4_MB_HINT_GOAL_ONLY 0x0100
/* goal is meaningful */
#define EXT4_MB_HINT_TRY_GOAL 0x0200
/* blocks already pre-reserved by delayed allocation */
#define EXT4_MB_DELALLOC_RESERVED 0x0400
/* We are doing stream allocation */
#define EXT4_MB_STREAM_ALLOC 0x0800
/* Use reserved root blocks if needed */
#define EXT4_MB_USE_ROOT_BLOCKS 0x1000
struct ext4_allocation_request {
/* target inode for block we're allocating */
struct inode *inode;
/* how many blocks we want to allocate */
unsigned int len;
/* logical block in target inode */
ext4_lblk_t logical;
/* the closest logical allocated block to the left */
ext4_lblk_t lleft;
/* the closest logical allocated block to the right */
ext4_lblk_t lright;
/* phys. target (a hint) */
ext4_fsblk_t goal;
/* phys. block for the closest logical allocated block to the left */
ext4_fsblk_t pleft;
/* phys. block for the closest logical allocated block to the right */
ext4_fsblk_t pright;
/* flags. see above EXT4_MB_HINT_* */
unsigned int flags;
};
/*
* Logical to physical block mapping, used by ext4_map_blocks()
*
* This structure is used to pass requests into ext4_map_blocks() as
* well as to store the information returned by ext4_map_blocks(). It
* takes less room on the stack than a struct buffer_head.
*/
#define EXT4_MAP_NEW (1 << BH_New)
#define EXT4_MAP_MAPPED (1 << BH_Mapped)
#define EXT4_MAP_UNWRITTEN (1 << BH_Unwritten)
#define EXT4_MAP_BOUNDARY (1 << BH_Boundary)
#define EXT4_MAP_UNINIT (1 << BH_Uninit)
/* Sometimes (in the bigalloc case, from ext4_da_get_block_prep) the caller of
* ext4_map_blocks wants to know whether or not the underlying cluster has
* already been accounted for. EXT4_MAP_FROM_CLUSTER conveys to the caller that
* the requested mapping was from previously mapped (or delayed allocated)
* cluster. We use BH_AllocFromCluster only for this flag. BH_AllocFromCluster
* should never appear on buffer_head's state flags.
*/
#define EXT4_MAP_FROM_CLUSTER (1 << BH_AllocFromCluster)
#define EXT4_MAP_FLAGS (EXT4_MAP_NEW | EXT4_MAP_MAPPED |\
EXT4_MAP_UNWRITTEN | EXT4_MAP_BOUNDARY |\
EXT4_MAP_UNINIT | EXT4_MAP_FROM_CLUSTER)
struct ext4_map_blocks {
ext4_fsblk_t m_pblk;
ext4_lblk_t m_lblk;
unsigned int m_len;
unsigned int m_flags;
};
/*
* For delayed allocation tracking
*/
struct mpage_da_data {
struct inode *inode;
sector_t b_blocknr; /* start block number of extent */
size_t b_size; /* size of extent */
unsigned long b_state; /* state of the extent */
unsigned long first_page, next_page; /* extent of pages */
struct writeback_control *wbc;
int io_done;
int pages_written;
int retval;
};
/*
* Flags for ext4_io_end->flags
*/
#define EXT4_IO_END_UNWRITTEN 0x0001
#define EXT4_IO_END_ERROR 0x0002
#define EXT4_IO_END_QUEUED 0x0004
#define EXT4_IO_END_DIRECT 0x0008
#define EXT4_IO_END_IN_FSYNC 0x0010
struct ext4_io_page {
struct page *p_page;
atomic_t p_count;
};
#define MAX_IO_PAGES 128
/*
* For converting uninitialized extents on a work queue.
*
* 'page' is only used from the writepage() path; 'pages' is only used for
* buffered writes; they are used to keep page references until conversion
* takes place. For AIO/DIO, neither field is filled in.
*/
typedef struct ext4_io_end {
struct list_head list; /* per-file finished IO list */
struct inode *inode; /* file being written to */
unsigned int flag; /* unwritten or not */
struct page *page; /* for writepage() path */
loff_t offset; /* offset in the file */
ssize_t size; /* size of the extent */
struct work_struct work; /* data work queue */
struct kiocb *iocb; /* iocb struct for AIO */
int result; /* error value for AIO */
int num_io_pages; /* for writepages() */
struct ext4_io_page *pages[MAX_IO_PAGES]; /* for writepages() */
} ext4_io_end_t;
struct ext4_io_submit {
int io_op;
struct bio *io_bio;
ext4_io_end_t *io_end;
struct ext4_io_page *io_page;
sector_t io_next_block;
};
/*
* Special inodes numbers
*/
#define EXT4_BAD_INO 1 /* Bad blocks inode */
#define EXT4_ROOT_INO 2 /* Root inode */
#define EXT4_USR_QUOTA_INO 3 /* User quota inode */
#define EXT4_GRP_QUOTA_INO 4 /* Group quota inode */
#define EXT4_BOOT_LOADER_INO 5 /* Boot loader inode */
#define EXT4_UNDEL_DIR_INO 6 /* Undelete directory inode */
#define EXT4_RESIZE_INO 7 /* Reserved group descriptors inode */
#define EXT4_JOURNAL_INO 8 /* Journal inode */
/* First non-reserved inode for old ext4 filesystems */
#define EXT4_GOOD_OLD_FIRST_INO 11
/*
* Maximal count of links to a file
*/
#define EXT4_LINK_MAX 65000
/*
* Macro-instructions used to manage several block sizes
*/
#define EXT4_MIN_BLOCK_SIZE 1024
#define EXT4_MAX_BLOCK_SIZE 65536
#define EXT4_MIN_BLOCK_LOG_SIZE 10
#define EXT4_MAX_BLOCK_LOG_SIZE 16
#ifdef __KERNEL__
# define EXT4_BLOCK_SIZE(s) ((s)->s_blocksize)
#else
# define EXT4_BLOCK_SIZE(s) (EXT4_MIN_BLOCK_SIZE << (s)->s_log_block_size)
#endif
#define EXT4_ADDR_PER_BLOCK(s) (EXT4_BLOCK_SIZE(s) / sizeof(__u32))
#define EXT4_CLUSTER_SIZE(s) (EXT4_BLOCK_SIZE(s) << \
EXT4_SB(s)->s_cluster_bits)
#ifdef __KERNEL__
# define EXT4_BLOCK_SIZE_BITS(s) ((s)->s_blocksize_bits)
# define EXT4_CLUSTER_BITS(s) (EXT4_SB(s)->s_cluster_bits)
#else
# define EXT4_BLOCK_SIZE_BITS(s) ((s)->s_log_block_size + 10)
#endif
#ifdef __KERNEL__
#define EXT4_ADDR_PER_BLOCK_BITS(s) (EXT4_SB(s)->s_addr_per_block_bits)
#define EXT4_INODE_SIZE(s) (EXT4_SB(s)->s_inode_size)
#define EXT4_FIRST_INO(s) (EXT4_SB(s)->s_first_ino)
#else
#define EXT4_INODE_SIZE(s) (((s)->s_rev_level == EXT4_GOOD_OLD_REV) ? \
EXT4_GOOD_OLD_INODE_SIZE : \
(s)->s_inode_size)
#define EXT4_FIRST_INO(s) (((s)->s_rev_level == EXT4_GOOD_OLD_REV) ? \
EXT4_GOOD_OLD_FIRST_INO : \
(s)->s_first_ino)
#endif
#define EXT4_BLOCK_ALIGN(size, blkbits) ALIGN((size), (1 << (blkbits)))
/* Translate a block number to a cluster number */
#define EXT4_B2C(sbi, blk) ((blk) >> (sbi)->s_cluster_bits)
/* Translate a cluster number to a block number */
#define EXT4_C2B(sbi, cluster) ((cluster) << (sbi)->s_cluster_bits)
/* Translate # of blks to # of clusters */
#define EXT4_NUM_B2C(sbi, blks) (((blks) + (sbi)->s_cluster_ratio - 1) >> \
(sbi)->s_cluster_bits)
/*
* Structure of a blocks group descriptor
*/
struct ext4_group_desc
{
__le32 bg_block_bitmap_lo; /* Blocks bitmap block */
__le32 bg_inode_bitmap_lo; /* Inodes bitmap block */
__le32 bg_inode_table_lo; /* Inodes table block */
__le16 bg_free_blocks_count_lo;/* Free blocks count */
__le16 bg_free_inodes_count_lo;/* Free inodes count */
__le16 bg_used_dirs_count_lo; /* Directories count */
__le16 bg_flags; /* EXT4_BG_flags (INODE_UNINIT, etc) */
__u32 bg_reserved[2]; /* Likely block/inode bitmap checksum */
__le16 bg_itable_unused_lo; /* Unused inodes count */
__le16 bg_checksum; /* crc16(sb_uuid+group+desc) */
__le32 bg_block_bitmap_hi; /* Blocks bitmap block MSB */
__le32 bg_inode_bitmap_hi; /* Inodes bitmap block MSB */
__le32 bg_inode_table_hi; /* Inodes table block MSB */
__le16 bg_free_blocks_count_hi;/* Free blocks count MSB */
__le16 bg_free_inodes_count_hi;/* Free inodes count MSB */
__le16 bg_used_dirs_count_hi; /* Directories count MSB */
__le16 bg_itable_unused_hi; /* Unused inodes count MSB */
__u32 bg_reserved2[3];
};
/*
* Structure of a flex block group info
*/
struct flex_groups {
atomic64_t free_clusters;
atomic_t free_inodes;
atomic_t used_dirs;
};
#define EXT4_BG_INODE_UNINIT 0x0001 /* Inode table/bitmap not in use */
#define EXT4_BG_BLOCK_UNINIT 0x0002 /* Block bitmap not in use */
#define EXT4_BG_INODE_ZEROED 0x0004 /* On-disk itable initialized to zero */
/*
* Macro-instructions used to manage group descriptors
*/
#define EXT4_MIN_DESC_SIZE 32
#define EXT4_MIN_DESC_SIZE_64BIT 64
#define EXT4_MAX_DESC_SIZE EXT4_MIN_BLOCK_SIZE
#define EXT4_DESC_SIZE(s) (EXT4_SB(s)->s_desc_size)
#ifdef __KERNEL__
# define EXT4_BLOCKS_PER_GROUP(s) (EXT4_SB(s)->s_blocks_per_group)
# define EXT4_CLUSTERS_PER_GROUP(s) (EXT4_SB(s)->s_clusters_per_group)
# define EXT4_DESC_PER_BLOCK(s) (EXT4_SB(s)->s_desc_per_block)
# define EXT4_INODES_PER_GROUP(s) (EXT4_SB(s)->s_inodes_per_group)
# define EXT4_DESC_PER_BLOCK_BITS(s) (EXT4_SB(s)->s_desc_per_block_bits)
#else
# define EXT4_BLOCKS_PER_GROUP(s) ((s)->s_blocks_per_group)
# define EXT4_DESC_PER_BLOCK(s) (EXT4_BLOCK_SIZE(s) / EXT4_DESC_SIZE(s))
# define EXT4_INODES_PER_GROUP(s) ((s)->s_inodes_per_group)
#endif
/*
* Constants relative to the data blocks
*/
#define EXT4_NDIR_BLOCKS 12
#define EXT4_IND_BLOCK EXT4_NDIR_BLOCKS
#define EXT4_DIND_BLOCK (EXT4_IND_BLOCK + 1)
#define EXT4_TIND_BLOCK (EXT4_DIND_BLOCK + 1)
#define EXT4_N_BLOCKS (EXT4_TIND_BLOCK + 1)
/*
* Inode flags
*/
#define EXT4_SECRM_FL 0x00000001 /* Secure deletion */
#define EXT4_UNRM_FL 0x00000002 /* Undelete */
#define EXT4_COMPR_FL 0x00000004 /* Compress file */
#define EXT4_SYNC_FL 0x00000008 /* Synchronous updates */
#define EXT4_IMMUTABLE_FL 0x00000010 /* Immutable file */
#define EXT4_APPEND_FL 0x00000020 /* writes to file may only append */
#define EXT4_NODUMP_FL 0x00000040 /* do not dump file */
#define EXT4_NOATIME_FL 0x00000080 /* do not update atime */
/* Reserved for compression usage... */
#define EXT4_DIRTY_FL 0x00000100
#define EXT4_COMPRBLK_FL 0x00000200 /* One or more compressed clusters */
#define EXT4_NOCOMPR_FL 0x00000400 /* Don't compress */
#define EXT4_ECOMPR_FL 0x00000800 /* Compression error */
/* End compression flags --- maybe not all used */
#define EXT4_INDEX_FL 0x00001000 /* hash-indexed directory */
#define EXT4_IMAGIC_FL 0x00002000 /* AFS directory */
#define EXT4_JOURNAL_DATA_FL 0x00004000 /* file data should be journaled */
#define EXT4_NOTAIL_FL 0x00008000 /* file tail should not be merged */
#define EXT4_DIRSYNC_FL 0x00010000 /* dirsync behaviour (directories only) */
#define EXT4_TOPDIR_FL 0x00020000 /* Top of directory hierarchies*/
#define EXT4_HUGE_FILE_FL 0x00040000 /* Set to each huge file */
#define EXT4_EXTENTS_FL 0x00080000 /* Inode uses extents */
#define EXT4_EA_INODE_FL 0x00200000 /* Inode used for large EA */
#define EXT4_EOFBLOCKS_FL 0x00400000 /* Blocks allocated beyond EOF */
#define EXT4_RESERVED_FL 0x80000000 /* reserved for ext4 lib */
#define EXT4_FL_USER_VISIBLE 0x004BDFFF /* User visible flags */
#define EXT4_FL_USER_MODIFIABLE 0x004B80FF /* User modifiable flags */
/* Flags that should be inherited by new inodes from their parent. */
#define EXT4_FL_INHERITED (EXT4_SECRM_FL | EXT4_UNRM_FL | EXT4_COMPR_FL |\
EXT4_SYNC_FL | EXT4_NODUMP_FL | EXT4_NOATIME_FL |\
EXT4_NOCOMPR_FL | EXT4_JOURNAL_DATA_FL |\
EXT4_NOTAIL_FL | EXT4_DIRSYNC_FL)
/* Flags that are appropriate for regular files (all but dir-specific ones). */
#define EXT4_REG_FLMASK (~(EXT4_DIRSYNC_FL | EXT4_TOPDIR_FL))
/* Flags that are appropriate for non-directories/regular files. */
#define EXT4_OTHER_FLMASK (EXT4_NODUMP_FL | EXT4_NOATIME_FL)
/* Mask out flags that are inappropriate for the given type of inode. */
static inline __u32 ext4_mask_flags(umode_t mode, __u32 flags)
{
if (S_ISDIR(mode))
return flags;
else if (S_ISREG(mode))
return flags & EXT4_REG_FLMASK;
else
return flags & EXT4_OTHER_FLMASK;
}
/*
* Inode flags used for atomic set/get
*/
enum {
EXT4_INODE_SECRM = 0, /* Secure deletion */
EXT4_INODE_UNRM = 1, /* Undelete */
EXT4_INODE_COMPR = 2, /* Compress file */
EXT4_INODE_SYNC = 3, /* Synchronous updates */
EXT4_INODE_IMMUTABLE = 4, /* Immutable file */
EXT4_INODE_APPEND = 5, /* writes to file may only append */
EXT4_INODE_NODUMP = 6, /* do not dump file */
EXT4_INODE_NOATIME = 7, /* do not update atime */
/* Reserved for compression usage... */
EXT4_INODE_DIRTY = 8,
EXT4_INODE_COMPRBLK = 9, /* One or more compressed clusters */
EXT4_INODE_NOCOMPR = 10, /* Don't compress */
EXT4_INODE_ECOMPR = 11, /* Compression error */
/* End compression flags --- maybe not all used */
EXT4_INODE_INDEX = 12, /* hash-indexed directory */
EXT4_INODE_IMAGIC = 13, /* AFS directory */
EXT4_INODE_JOURNAL_DATA = 14, /* file data should be journaled */
EXT4_INODE_NOTAIL = 15, /* file tail should not be merged */
EXT4_INODE_DIRSYNC = 16, /* dirsync behaviour (directories only) */
EXT4_INODE_TOPDIR = 17, /* Top of directory hierarchies*/
EXT4_INODE_HUGE_FILE = 18, /* Set to each huge file */
EXT4_INODE_EXTENTS = 19, /* Inode uses extents */
EXT4_INODE_EA_INODE = 21, /* Inode used for large EA */
EXT4_INODE_EOFBLOCKS = 22, /* Blocks allocated beyond EOF */
EXT4_INODE_RESERVED = 31, /* reserved for ext4 lib */
};
#define TEST_FLAG_VALUE(FLAG) (EXT4_##FLAG##_FL == (1 << EXT4_INODE_##FLAG))
#define CHECK_FLAG_VALUE(FLAG) if (!TEST_FLAG_VALUE(FLAG)) { \
printk(KERN_EMERG "EXT4 flag fail: " #FLAG ": %d %d\n", \
EXT4_##FLAG##_FL, EXT4_INODE_##FLAG); BUG_ON(1); }
/*
* Since it's pretty easy to mix up bit numbers and hex values, and we
* can't do a compile-time test for ENUM values, we use a run-time
* test to make sure that EXT4_XXX_FL is consistent with respect to
* EXT4_INODE_XXX. If all is well the printk and BUG_ON will all drop
* out so it won't cost any extra space in the compiled kernel image.
* But it's important that these values are the same, since we are
* using EXT4_INODE_XXX to test for the flag values, but EXT4_XX_FL
* must be consistent with the values of FS_XXX_FL defined in
* include/linux/fs.h and the on-disk values found in ext2, ext3, and
* ext4 filesystems, and of course the values defined in e2fsprogs.
*
* It's not paranoia if the Murphy's Law really *is* out to get you. :-)
*/
static inline void ext4_check_flag_values(void)
{
CHECK_FLAG_VALUE(SECRM);
CHECK_FLAG_VALUE(UNRM);
CHECK_FLAG_VALUE(COMPR);
CHECK_FLAG_VALUE(SYNC);
CHECK_FLAG_VALUE(IMMUTABLE);
CHECK_FLAG_VALUE(APPEND);
CHECK_FLAG_VALUE(NODUMP);
CHECK_FLAG_VALUE(NOATIME);
CHECK_FLAG_VALUE(DIRTY);
CHECK_FLAG_VALUE(COMPRBLK);
CHECK_FLAG_VALUE(NOCOMPR);
CHECK_FLAG_VALUE(ECOMPR);
CHECK_FLAG_VALUE(INDEX);
CHECK_FLAG_VALUE(IMAGIC);
CHECK_FLAG_VALUE(JOURNAL_DATA);
CHECK_FLAG_VALUE(NOTAIL);
CHECK_FLAG_VALUE(DIRSYNC);
CHECK_FLAG_VALUE(TOPDIR);
CHECK_FLAG_VALUE(HUGE_FILE);
CHECK_FLAG_VALUE(EXTENTS);
CHECK_FLAG_VALUE(EA_INODE);
CHECK_FLAG_VALUE(EOFBLOCKS);
CHECK_FLAG_VALUE(RESERVED);
}
/* Used to pass group descriptor data when online resize is done */
struct ext4_new_group_input {
__u32 group; /* Group number for this data */
__u64 block_bitmap; /* Absolute block number of block bitmap */
__u64 inode_bitmap; /* Absolute block number of inode bitmap */
__u64 inode_table; /* Absolute block number of inode table start */
__u32 blocks_count; /* Total number of blocks in this group */
__u16 reserved_blocks; /* Number of reserved blocks in this group */
__u16 unused;
};
#if defined(__KERNEL__) && defined(CONFIG_COMPAT)
struct compat_ext4_new_group_input {
u32 group;
compat_u64 block_bitmap;
compat_u64 inode_bitmap;
compat_u64 inode_table;
u32 blocks_count;
u16 reserved_blocks;
u16 unused;
};
#endif
/* The struct ext4_new_group_input in kernel space, with free_blocks_count */
struct ext4_new_group_data {
__u32 group;
__u64 block_bitmap;
__u64 inode_bitmap;
__u64 inode_table;
__u32 blocks_count;
__u16 reserved_blocks;
__u16 unused;
__u32 free_blocks_count;
};
/* Indexes used to index group tables in ext4_new_group_data */
enum {
BLOCK_BITMAP = 0, /* block bitmap */
INODE_BITMAP, /* inode bitmap */
INODE_TABLE, /* inode tables */
GROUP_TABLE_COUNT,
};
/*
* Flags used by ext4_map_blocks()
*/
/* Allocate any needed blocks and/or convert an unitialized
extent to be an initialized ext4 */
#define EXT4_GET_BLOCKS_CREATE 0x0001
/* Request the creation of an unitialized extent */
#define EXT4_GET_BLOCKS_UNINIT_EXT 0x0002
#define EXT4_GET_BLOCKS_CREATE_UNINIT_EXT (EXT4_GET_BLOCKS_UNINIT_EXT|\
EXT4_GET_BLOCKS_CREATE)
/* Caller is from the delayed allocation writeout path,
so set the magic i_delalloc_reserve_flag after taking the
inode allocation semaphore for */
#define EXT4_GET_BLOCKS_DELALLOC_RESERVE 0x0004
/* caller is from the direct IO path, request to creation of an
unitialized extents if not allocated, split the uninitialized
extent if blocks has been preallocated already*/
#define EXT4_GET_BLOCKS_PRE_IO 0x0008
#define EXT4_GET_BLOCKS_CONVERT 0x0010
#define EXT4_GET_BLOCKS_IO_CREATE_EXT (EXT4_GET_BLOCKS_PRE_IO|\
EXT4_GET_BLOCKS_CREATE_UNINIT_EXT)
/* Convert extent to initialized after IO complete */
#define EXT4_GET_BLOCKS_IO_CONVERT_EXT (EXT4_GET_BLOCKS_CONVERT|\
EXT4_GET_BLOCKS_CREATE_UNINIT_EXT)
/* Punch out blocks of an extent */
#define EXT4_GET_BLOCKS_PUNCH_OUT_EXT 0x0020
/* Don't normalize allocation size (used for fallocate) */
#define EXT4_GET_BLOCKS_NO_NORMALIZE 0x0040
/* Request will not result in inode size update (user for fallocate) */
#define EXT4_GET_BLOCKS_KEEP_SIZE 0x0080
/*
* Flags used by ext4_free_blocks
*/
#define EXT4_FREE_BLOCKS_METADATA 0x0001
#define EXT4_FREE_BLOCKS_FORGET 0x0002
#define EXT4_FREE_BLOCKS_VALIDATED 0x0004
#define EXT4_FREE_BLOCKS_NO_QUOT_UPDATE 0x0008
#define EXT4_FREE_BLOCKS_NOFREE_FIRST_CLUSTER 0x0010
#define EXT4_FREE_BLOCKS_NOFREE_LAST_CLUSTER 0x0020
/*
* Flags used by ext4_discard_partial_page_buffers
*/
#define EXT4_DISCARD_PARTIAL_PG_ZERO_UNMAPPED 0x0001
/*
* ioctl commands
*/
#define EXT4_IOC_GETFLAGS FS_IOC_GETFLAGS
#define EXT4_IOC_SETFLAGS FS_IOC_SETFLAGS
#define EXT4_IOC_GETVERSION _IOR('f', 3, long)
#define EXT4_IOC_SETVERSION _IOW('f', 4, long)
#define EXT4_IOC_GETVERSION_OLD FS_IOC_GETVERSION
#define EXT4_IOC_SETVERSION_OLD FS_IOC_SETVERSION
#define EXT4_IOC_GETRSVSZ _IOR('f', 5, long)
#define EXT4_IOC_SETRSVSZ _IOW('f', 6, long)
#define EXT4_IOC_GROUP_EXTEND _IOW('f', 7, unsigned long)
#define EXT4_IOC_GROUP_ADD _IOW('f', 8, struct ext4_new_group_input)
#define EXT4_IOC_MIGRATE _IO('f', 9)
/* note ioctl 10 reserved for an early version of the FIEMAP ioctl */
/* note ioctl 11 reserved for filesystem-independent FIEMAP ioctl */
#define EXT4_IOC_ALLOC_DA_BLKS _IO('f', 12)
#define EXT4_IOC_MOVE_EXT _IOWR('f', 15, struct move_extent)
#define EXT4_IOC_RESIZE_FS _IOW('f', 16, __u64)
#if defined(__KERNEL__) && defined(CONFIG_COMPAT)
/*
* ioctl commands in 32 bit emulation
*/
#define EXT4_IOC32_GETFLAGS FS_IOC32_GETFLAGS
#define EXT4_IOC32_SETFLAGS FS_IOC32_SETFLAGS
#define EXT4_IOC32_GETVERSION _IOR('f', 3, int)
#define EXT4_IOC32_SETVERSION _IOW('f', 4, int)
#define EXT4_IOC32_GETRSVSZ _IOR('f', 5, int)
#define EXT4_IOC32_SETRSVSZ _IOW('f', 6, int)
#define EXT4_IOC32_GROUP_EXTEND _IOW('f', 7, unsigned int)
#define EXT4_IOC32_GROUP_ADD _IOW('f', 8, struct compat_ext4_new_group_input)
#define EXT4_IOC32_GETVERSION_OLD FS_IOC32_GETVERSION
#define EXT4_IOC32_SETVERSION_OLD FS_IOC32_SETVERSION
#endif
/* Max physical block we can address w/o extents */
#define EXT4_MAX_BLOCK_FILE_PHYS 0xFFFFFFFF
/*
* Structure of an inode on the disk
*/
struct ext4_inode {
__le16 i_mode; /* File mode */
__le16 i_uid; /* Low 16 bits of Owner Uid */
__le32 i_size_lo; /* Size in bytes */
__le32 i_atime; /* Access time */
__le32 i_ctime; /* Inode Change time */
__le32 i_mtime; /* Modification time */
__le32 i_dtime; /* Deletion Time */
__le16 i_gid; /* Low 16 bits of Group Id */
__le16 i_links_count; /* Links count */
__le32 i_blocks_lo; /* Blocks count */
__le32 i_flags; /* File flags */
union {
struct {
__le32 l_i_version;
} linux1;
struct {
__u32 h_i_translator;
} hurd1;
struct {
__u32 m_i_reserved1;
} masix1;
} osd1; /* OS dependent 1 */
__le32 i_block[EXT4_N_BLOCKS];/* Pointers to blocks */
__le32 i_generation; /* File version (for NFS) */
__le32 i_file_acl_lo; /* File ACL */
__le32 i_size_high;
__le32 i_obso_faddr; /* Obsoleted fragment address */
union {
struct {
__le16 l_i_blocks_high; /* were l_i_reserved1 */
__le16 l_i_file_acl_high;
__le16 l_i_uid_high; /* these 2 fields */
__le16 l_i_gid_high; /* were reserved2[0] */
__u32 l_i_reserved2;
} linux2;
struct {
__le16 h_i_reserved1; /* Obsoleted fragment number/size which are removed in ext4 */
__u16 h_i_mode_high;
__u16 h_i_uid_high;
__u16 h_i_gid_high;
__u32 h_i_author;
} hurd2;
struct {
__le16 h_i_reserved1; /* Obsoleted fragment number/size which are removed in ext4 */
__le16 m_i_file_acl_high;
__u32 m_i_reserved2[2];
} masix2;
} osd2; /* OS dependent 2 */
__le16 i_extra_isize;
__le16 i_pad1;
__le32 i_ctime_extra; /* extra Change time (nsec << 2 | epoch) */
__le32 i_mtime_extra; /* extra Modification time(nsec << 2 | epoch) */
__le32 i_atime_extra; /* extra Access time (nsec << 2 | epoch) */
__le32 i_crtime; /* File Creation time */
__le32 i_crtime_extra; /* extra FileCreationtime (nsec << 2 | epoch) */
__le32 i_version_hi; /* high 32 bits for 64-bit version */
};
struct move_extent {
__u32 reserved; /* should be zero */
__u32 donor_fd; /* donor file descriptor */
__u64 orig_start; /* logical start offset in block for orig */
__u64 donor_start; /* logical start offset in block for donor */
__u64 len; /* block length to be moved */
__u64 moved_len; /* moved block length */
};
#define EXT4_EPOCH_BITS 2
#define EXT4_EPOCH_MASK ((1 << EXT4_EPOCH_BITS) - 1)
#define EXT4_NSEC_MASK (~0UL << EXT4_EPOCH_BITS)
/*
* Extended fields will fit into an inode if the filesystem was formatted
* with large inodes (-I 256 or larger) and there are not currently any EAs
* consuming all of the available space. For new inodes we always reserve
* enough space for the kernel's known extended fields, but for inodes
* created with an old kernel this might not have been the case. None of
* the extended inode fields is critical for correct filesystem operation.
* This macro checks if a certain field fits in the inode. Note that
* inode-size = GOOD_OLD_INODE_SIZE + i_extra_isize
*/
#define EXT4_FITS_IN_INODE(ext4_inode, einode, field) \
((offsetof(typeof(*ext4_inode), field) + \
sizeof((ext4_inode)->field)) \
<= (EXT4_GOOD_OLD_INODE_SIZE + \
(einode)->i_extra_isize)) \
static inline __le32 ext4_encode_extra_time(struct timespec *time)
{
return cpu_to_le32((sizeof(time->tv_sec) > 4 ?
(time->tv_sec >> 32) & EXT4_EPOCH_MASK : 0) |
((time->tv_nsec << EXT4_EPOCH_BITS) & EXT4_NSEC_MASK));
}
static inline void ext4_decode_extra_time(struct timespec *time, __le32 extra)
{
if (sizeof(time->tv_sec) > 4)
time->tv_sec |= (__u64)(le32_to_cpu(extra) & EXT4_EPOCH_MASK)
<< 32;
time->tv_nsec = (le32_to_cpu(extra) & EXT4_NSEC_MASK) >> EXT4_EPOCH_BITS;
}
#define EXT4_INODE_SET_XTIME(xtime, inode, raw_inode) \
do { \
(raw_inode)->xtime = cpu_to_le32((inode)->xtime.tv_sec); \
if (EXT4_FITS_IN_INODE(raw_inode, EXT4_I(inode), xtime ## _extra)) \
(raw_inode)->xtime ## _extra = \
ext4_encode_extra_time(&(inode)->xtime); \
} while (0)
#define EXT4_EINODE_SET_XTIME(xtime, einode, raw_inode) \
do { \
if (EXT4_FITS_IN_INODE(raw_inode, einode, xtime)) \
(raw_inode)->xtime = cpu_to_le32((einode)->xtime.tv_sec); \
if (EXT4_FITS_IN_INODE(raw_inode, einode, xtime ## _extra)) \
(raw_inode)->xtime ## _extra = \
ext4_encode_extra_time(&(einode)->xtime); \
} while (0)
#define EXT4_INODE_GET_XTIME(xtime, inode, raw_inode) \
do { \
(inode)->xtime.tv_sec = (signed)le32_to_cpu((raw_inode)->xtime); \
if (EXT4_FITS_IN_INODE(raw_inode, EXT4_I(inode), xtime ## _extra)) \
ext4_decode_extra_time(&(inode)->xtime, \
raw_inode->xtime ## _extra); \
else \
(inode)->xtime.tv_nsec = 0; \
} while (0)
#define EXT4_EINODE_GET_XTIME(xtime, einode, raw_inode) \
do { \
if (EXT4_FITS_IN_INODE(raw_inode, einode, xtime)) \
(einode)->xtime.tv_sec = \
(signed)le32_to_cpu((raw_inode)->xtime); \
else \
(einode)->xtime.tv_sec = 0; \
if (EXT4_FITS_IN_INODE(raw_inode, einode, xtime ## _extra)) \
ext4_decode_extra_time(&(einode)->xtime, \
raw_inode->xtime ## _extra); \
else \
(einode)->xtime.tv_nsec = 0; \
} while (0)
#define i_disk_version osd1.linux1.l_i_version
#if defined(__KERNEL__) || defined(__linux__)
#define i_reserved1 osd1.linux1.l_i_reserved1
#define i_file_acl_high osd2.linux2.l_i_file_acl_high
#define i_blocks_high osd2.linux2.l_i_blocks_high
#define i_uid_low i_uid
#define i_gid_low i_gid
#define i_uid_high osd2.linux2.l_i_uid_high
#define i_gid_high osd2.linux2.l_i_gid_high
#define i_reserved2 osd2.linux2.l_i_reserved2
#elif defined(__GNU__)
#define i_translator osd1.hurd1.h_i_translator
#define i_uid_high osd2.hurd2.h_i_uid_high
#define i_gid_high osd2.hurd2.h_i_gid_high
#define i_author osd2.hurd2.h_i_author
#elif defined(__masix__)
#define i_reserved1 osd1.masix1.m_i_reserved1
#define i_file_acl_high osd2.masix2.m_i_file_acl_high
#define i_reserved2 osd2.masix2.m_i_reserved2
#endif /* defined(__KERNEL__) || defined(__linux__) */
/*
* storage for cached extent
* If ec_len == 0, then the cache is invalid.
* If ec_start == 0, then the cache represents a gap (null mapping)
*/
struct ext4_ext_cache {
ext4_fsblk_t ec_start;
ext4_lblk_t ec_block;
__u32 ec_len; /* must be 32bit to return holes */
};
/*
* fourth extended file system inode data in memory
*/
struct ext4_inode_info {
__le32 i_data[15]; /* unconverted */
__u32 i_dtime;
ext4_fsblk_t i_file_acl;
/*
* i_block_group is the number of the block group which contains
* this file's inode. Constant across the lifetime of the inode,
* it is ued for making block allocation decisions - we try to
* place a file's data blocks near its inode block, and new inodes
* near to their parent directory's inode.
*/
ext4_group_t i_block_group;
ext4_lblk_t i_dir_start_lookup;
#if (BITS_PER_LONG < 64)
unsigned long i_state_flags; /* Dynamic state flags */
#endif
unsigned long i_flags;
#ifdef CONFIG_EXT4_FS_XATTR
/*
* Extended attributes can be read independently of the main file
* data. Taking i_mutex even when reading would cause contention
* between readers of EAs and writers of regular file data, so
* instead we synchronize on xattr_sem when reading or changing
* EAs.
*/
struct rw_semaphore xattr_sem;
#endif
struct list_head i_orphan; /* unlinked but open inodes */
/*
* i_disksize keeps track of what the inode size is ON DISK, not
* in memory. During truncate, i_size is set to the new size by
* the VFS prior to calling ext4_truncate(), but the filesystem won't
* set i_disksize to 0 until the truncate is actually under way.
*
* The intent is that i_disksize always represents the blocks which
* are used by this file. This allows recovery to restart truncate
* on orphans if we crash during truncate. We actually write i_disksize
* into the on-disk inode when writing inodes out, instead of i_size.
*
* The only time when i_disksize and i_size may be different is when
* a truncate is in progress. The only things which change i_disksize
* are ext4_get_block (growth) and ext4_truncate (shrinkth).
*/
loff_t i_disksize;
/*
* i_data_sem is for serialising ext4_truncate() against
* ext4_getblock(). In the 2.4 ext2 design, great chunks of inode's
* data tree are chopped off during truncate. We can't do that in
* ext4 because whenever we perform intermediate commits during
* truncate, the inode and all the metadata blocks *must* be in a
* consistent state which allows truncation of the orphans to restart
* during recovery. Hence we must fix the get_block-vs-truncate race
* by other means, so we have i_data_sem.
*/
struct rw_semaphore i_data_sem;
struct inode vfs_inode;
struct jbd2_inode *jinode;
struct ext4_ext_cache i_cached_extent;
/*
* File creation time. Its function is same as that of
* struct timespec i_{a,c,m}time in the generic inode.
*/
struct timespec i_crtime;
/* mballoc */
struct list_head i_prealloc_list;
spinlock_t i_prealloc_lock;
/* ialloc */
ext4_group_t i_last_alloc_group;
/* allocation reservation info for delalloc */
/* In case of bigalloc, these refer to clusters rather than blocks */
unsigned int i_reserved_data_blocks;
unsigned int i_reserved_meta_blocks;
unsigned int i_allocated_meta_blocks;
ext4_lblk_t i_da_metadata_calc_last_lblock;
int i_da_metadata_calc_len;
/* on-disk additional length */
__u16 i_extra_isize;
#ifdef CONFIG_QUOTA
/* quota space reservation, managed internally by quota code */
qsize_t i_reserved_quota;
#endif
/* completed IOs that might need unwritten extents handling */
struct list_head i_completed_io_list;
spinlock_t i_completed_io_lock;
atomic_t i_ioend_count; /* Number of outstanding io_end structs */
/* current io_end structure for async DIO write*/
ext4_io_end_t *cur_aio_dio;
atomic_t i_aiodio_unwritten; /* Nr. of inflight conversions pending */
spinlock_t i_block_reservation_lock;
/*
* Transactions that contain inode's metadata needed to complete
* fsync and fdatasync, respectively.
*/
tid_t i_sync_tid;
tid_t i_datasync_tid;
};
/*
* File system states
*/
#define EXT4_VALID_FS 0x0001 /* Unmounted cleanly */
#define EXT4_ERROR_FS 0x0002 /* Errors detected */
#define EXT4_ORPHAN_FS 0x0004 /* Orphans being recovered */
/*
* Misc. filesystem flags
*/
#define EXT2_FLAGS_SIGNED_HASH 0x0001 /* Signed dirhash in use */
#define EXT2_FLAGS_UNSIGNED_HASH 0x0002 /* Unsigned dirhash in use */
#define EXT2_FLAGS_TEST_FILESYS 0x0004 /* to test development code */
/*
* Mount flags
*/
#define EXT4_MOUNT_GRPID 0x00004 /* Create files with directory's group */
#define EXT4_MOUNT_DEBUG 0x00008 /* Some debugging messages */
#define EXT4_MOUNT_ERRORS_CONT 0x00010 /* Continue on errors */
#define EXT4_MOUNT_ERRORS_RO 0x00020 /* Remount fs ro on errors */
#define EXT4_MOUNT_ERRORS_PANIC 0x00040 /* Panic on errors */
#define EXT4_MOUNT_ERRORS_MASK 0x00070
#define EXT4_MOUNT_MINIX_DF 0x00080 /* Mimics the Minix statfs */
#define EXT4_MOUNT_NOLOAD 0x00100 /* Don't use existing journal*/
#define EXT4_MOUNT_DATA_FLAGS 0x00C00 /* Mode for data writes: */
#define EXT4_MOUNT_JOURNAL_DATA 0x00400 /* Write data to journal */
#define EXT4_MOUNT_ORDERED_DATA 0x00800 /* Flush data before commit */
#define EXT4_MOUNT_WRITEBACK_DATA 0x00C00 /* No data ordering */
#define EXT4_MOUNT_UPDATE_JOURNAL 0x01000 /* Update the journal format */
#define EXT4_MOUNT_NO_UID32 0x02000 /* Disable 32-bit UIDs */
#define EXT4_MOUNT_XATTR_USER 0x04000 /* Extended user attributes */
#define EXT4_MOUNT_POSIX_ACL 0x08000 /* POSIX Access Control Lists */
#define EXT4_MOUNT_NO_AUTO_DA_ALLOC 0x10000 /* No auto delalloc mapping */
#define EXT4_MOUNT_BARRIER 0x20000 /* Use block barriers */
#define EXT4_MOUNT_QUOTA 0x80000 /* Some quota option set */
#define EXT4_MOUNT_USRQUOTA 0x100000 /* "old" user quota */
#define EXT4_MOUNT_GRPQUOTA 0x200000 /* "old" group quota */
#define EXT4_MOUNT_DIOREAD_NOLOCK 0x400000 /* Enable support for dio read nolocking */
#define EXT4_MOUNT_JOURNAL_CHECKSUM 0x800000 /* Journal checksums */
#define EXT4_MOUNT_JOURNAL_ASYNC_COMMIT 0x1000000 /* Journal Async Commit */
#define EXT4_MOUNT_MBLK_IO_SUBMIT 0x4000000 /* multi-block io submits */
#define EXT4_MOUNT_DELALLOC 0x8000000 /* Delalloc support */
#define EXT4_MOUNT_DATA_ERR_ABORT 0x10000000 /* Abort on file data write */
#define EXT4_MOUNT_BLOCK_VALIDITY 0x20000000 /* Block validity checking */
#define EXT4_MOUNT_DISCARD 0x40000000 /* Issue DISCARD requests */
#define EXT4_MOUNT_INIT_INODE_TABLE 0x80000000 /* Initialize uninitialized itables */
#define EXT4_MOUNT2_EXPLICIT_DELALLOC 0x00000001 /* User explicitly
specified delalloc */
#define clear_opt(sb, opt) EXT4_SB(sb)->s_mount_opt &= \
~EXT4_MOUNT_##opt
#define set_opt(sb, opt) EXT4_SB(sb)->s_mount_opt |= \
EXT4_MOUNT_##opt
#define test_opt(sb, opt) (EXT4_SB(sb)->s_mount_opt & \
EXT4_MOUNT_##opt)
#define clear_opt2(sb, opt) EXT4_SB(sb)->s_mount_opt2 &= \
~EXT4_MOUNT2_##opt
#define set_opt2(sb, opt) EXT4_SB(sb)->s_mount_opt2 |= \
EXT4_MOUNT2_##opt
#define test_opt2(sb, opt) (EXT4_SB(sb)->s_mount_opt2 & \
EXT4_MOUNT2_##opt)
#define ext4_test_and_set_bit __test_and_set_bit_le
#define ext4_set_bit __set_bit_le
#define ext4_set_bit_atomic ext2_set_bit_atomic
#define ext4_test_and_clear_bit __test_and_clear_bit_le
#define ext4_clear_bit __clear_bit_le
#define ext4_clear_bit_atomic ext2_clear_bit_atomic
#define ext4_test_bit test_bit_le
#define ext4_find_next_zero_bit find_next_zero_bit_le
#define ext4_find_next_bit find_next_bit_le
extern void ext4_set_bits(void *bm, int cur, int len);
/*
* Maximal mount counts between two filesystem checks
*/
#define EXT4_DFL_MAX_MNT_COUNT 20 /* Allow 20 mounts */
#define EXT4_DFL_CHECKINTERVAL 0 /* Don't use interval check */
/*
* Behaviour when detecting errors
*/
#define EXT4_ERRORS_CONTINUE 1 /* Continue execution */
#define EXT4_ERRORS_RO 2 /* Remount fs read-only */
#define EXT4_ERRORS_PANIC 3 /* Panic */
#define EXT4_ERRORS_DEFAULT EXT4_ERRORS_CONTINUE
/*
* Structure of the super block
*/
struct ext4_super_block {
/*00*/ __le32 s_inodes_count; /* Inodes count */
__le32 s_blocks_count_lo; /* Blocks count */
__le32 s_r_blocks_count_lo; /* Reserved blocks count */
__le32 s_free_blocks_count_lo; /* Free blocks count */
/*10*/ __le32 s_free_inodes_count; /* Free inodes count */
__le32 s_first_data_block; /* First Data Block */
__le32 s_log_block_size; /* Block size */
__le32 s_log_cluster_size; /* Allocation cluster size */
/*20*/ __le32 s_blocks_per_group; /* # Blocks per group */
__le32 s_clusters_per_group; /* # Clusters per group */
__le32 s_inodes_per_group; /* # Inodes per group */
__le32 s_mtime; /* Mount time */
/*30*/ __le32 s_wtime; /* Write time */
__le16 s_mnt_count; /* Mount count */
__le16 s_max_mnt_count; /* Maximal mount count */
__le16 s_magic; /* Magic signature */
__le16 s_state; /* File system state */
__le16 s_errors; /* Behaviour when detecting errors */
__le16 s_minor_rev_level; /* minor revision level */
/*40*/ __le32 s_lastcheck; /* time of last check */
__le32 s_checkinterval; /* max. time between checks */
__le32 s_creator_os; /* OS */
__le32 s_rev_level; /* Revision level */
/*50*/ __le16 s_def_resuid; /* Default uid for reserved blocks */
__le16 s_def_resgid; /* Default gid for reserved blocks */
/*
* These fields are for EXT4_DYNAMIC_REV superblocks only.
*
* Note: the difference between the compatible feature set and
* the incompatible feature set is that if there is a bit set
* in the incompatible feature set that the kernel doesn't
* know about, it should refuse to mount the filesystem.
*
* e2fsck's requirements are more strict; if it doesn't know
* about a feature in either the compatible or incompatible
* feature set, it must abort and not try to meddle with
* things it doesn't understand...
*/
__le32 s_first_ino; /* First non-reserved inode */
__le16 s_inode_size; /* size of inode structure */
__le16 s_block_group_nr; /* block group # of this superblock */
__le32 s_feature_compat; /* compatible feature set */
/*60*/ __le32 s_feature_incompat; /* incompatible feature set */
__le32 s_feature_ro_compat; /* readonly-compatible feature set */
/*68*/ __u8 s_uuid[16]; /* 128-bit uuid for volume */
/*78*/ char s_volume_name[16]; /* volume name */
/*88*/ char s_last_mounted[64]; /* directory where last mounted */
/*C8*/ __le32 s_algorithm_usage_bitmap; /* For compression */
/*
* Performance hints. Directory preallocation should only
* happen if the EXT4_FEATURE_COMPAT_DIR_PREALLOC flag is on.
*/
__u8 s_prealloc_blocks; /* Nr of blocks to try to preallocate*/
__u8 s_prealloc_dir_blocks; /* Nr to preallocate for dirs */
__le16 s_reserved_gdt_blocks; /* Per group desc for online growth */
/*
* Journaling support valid if EXT4_FEATURE_COMPAT_HAS_JOURNAL set.
*/
/*D0*/ __u8 s_journal_uuid[16]; /* uuid of journal superblock */
/*E0*/ __le32 s_journal_inum; /* inode number of journal file */
__le32 s_journal_dev; /* device number of journal file */
__le32 s_last_orphan; /* start of list of inodes to delete */
__le32 s_hash_seed[4]; /* HTREE hash seed */
__u8 s_def_hash_version; /* Default hash version to use */
__u8 s_jnl_backup_type;
__le16 s_desc_size; /* size of group descriptor */
/*100*/ __le32 s_default_mount_opts;
__le32 s_first_meta_bg; /* First metablock block group */
__le32 s_mkfs_time; /* When the filesystem was created */
__le32 s_jnl_blocks[17]; /* Backup of the journal inode */
/* 64bit support valid if EXT4_FEATURE_COMPAT_64BIT */
/*150*/ __le32 s_blocks_count_hi; /* Blocks count */
__le32 s_r_blocks_count_hi; /* Reserved blocks count */
__le32 s_free_blocks_count_hi; /* Free blocks count */
__le16 s_min_extra_isize; /* All inodes have at least # bytes */
__le16 s_want_extra_isize; /* New inodes should reserve # bytes */
__le32 s_flags; /* Miscellaneous flags */
__le16 s_raid_stride; /* RAID stride */
__le16 s_mmp_update_interval; /* # seconds to wait in MMP checking */
__le64 s_mmp_block; /* Block for multi-mount protection */
__le32 s_raid_stripe_width; /* blocks on all data disks (N*stride)*/
__u8 s_log_groups_per_flex; /* FLEX_BG group size */
__u8 s_reserved_char_pad;
__le16 s_reserved_pad;
__le64 s_kbytes_written; /* nr of lifetime kilobytes written */
__le32 s_snapshot_inum; /* Inode number of active snapshot */
__le32 s_snapshot_id; /* sequential ID of active snapshot */
__le64 s_snapshot_r_blocks_count; /* reserved blocks for active
snapshot's future use */
__le32 s_snapshot_list; /* inode number of the head of the
on-disk snapshot list */
#define EXT4_S_ERR_START offsetof(struct ext4_super_block, s_error_count)
__le32 s_error_count; /* number of fs errors */
__le32 s_first_error_time; /* first time an error happened */
__le32 s_first_error_ino; /* inode involved in first error */
__le64 s_first_error_block; /* block involved of first error */
__u8 s_first_error_func[32]; /* function where the error happened */
__le32 s_first_error_line; /* line number where error happened */
__le32 s_last_error_time; /* most recent time of an error */
__le32 s_last_error_ino; /* inode involved in last error */
__le32 s_last_error_line; /* line number where error happened */
__le64 s_last_error_block; /* block involved of last error */
__u8 s_last_error_func[32]; /* function where the error happened */
#define EXT4_S_ERR_END offsetof(struct ext4_super_block, s_mount_opts)
__u8 s_mount_opts[64];
__le32 s_usr_quota_inum; /* inode for tracking user quota */
__le32 s_grp_quota_inum; /* inode for tracking group quota */
__le32 s_overhead_clusters; /* overhead blocks/clusters in fs */
__le32 s_reserved[109]; /* Padding to the end of the block */
};
#define EXT4_S_ERR_LEN (EXT4_S_ERR_END - EXT4_S_ERR_START)
#ifdef __KERNEL__
/*
* run-time mount flags
*/
#define EXT4_MF_MNTDIR_SAMPLED 0x0001
#define EXT4_MF_FS_ABORTED 0x0002 /* Fatal error detected */
/*
* fourth extended-fs super-block data in memory
*/
struct ext4_sb_info {
unsigned long s_desc_size; /* Size of a group descriptor in bytes */
unsigned long s_inodes_per_block;/* Number of inodes per block */
unsigned long s_blocks_per_group;/* Number of blocks in a group */
unsigned long s_clusters_per_group; /* Number of clusters in a group */
unsigned long s_inodes_per_group;/* Number of inodes in a group */
unsigned long s_itb_per_group; /* Number of inode table blocks per group */
unsigned long s_gdb_count; /* Number of group descriptor blocks */
unsigned long s_desc_per_block; /* Number of group descriptors per block */
ext4_group_t s_groups_count; /* Number of groups in the fs */
ext4_group_t s_blockfile_groups;/* Groups acceptable for non-extent files */
unsigned long s_overhead; /* # of fs overhead clusters */
unsigned int s_cluster_ratio; /* Number of blocks per cluster */
unsigned int s_cluster_bits; /* log2 of s_cluster_ratio */
loff_t s_bitmap_maxbytes; /* max bytes for bitmap files */
struct buffer_head * s_sbh; /* Buffer containing the super block */
struct ext4_super_block *s_es; /* Pointer to the super block in the buffer */
struct buffer_head **s_group_desc;
unsigned int s_mount_opt;
unsigned int s_mount_opt2;
unsigned int s_mount_flags;
unsigned int s_def_mount_opt;
ext4_fsblk_t s_sb_block;
uid_t s_resuid;
gid_t s_resgid;
unsigned short s_mount_state;
unsigned short s_pad;
int s_addr_per_block_bits;
int s_desc_per_block_bits;
int s_inode_size;
int s_first_ino;
unsigned int s_inode_readahead_blks;
unsigned int s_inode_goal;
spinlock_t s_next_gen_lock;
u32 s_next_generation;
u32 s_hash_seed[4];
int s_def_hash_version;
int s_hash_unsigned; /* 3 if hash should be signed, 0 if not */
struct percpu_counter s_freeclusters_counter;
struct percpu_counter s_freeinodes_counter;
struct percpu_counter s_dirs_counter;
struct percpu_counter s_dirtyclusters_counter;
struct blockgroup_lock *s_blockgroup_lock;
struct proc_dir_entry *s_proc;
struct kobject s_kobj;
struct completion s_kobj_unregister;
/* Journaling */
struct journal_s *s_journal;
struct list_head s_orphan;
struct mutex s_orphan_lock;
unsigned long s_resize_flags; /* Flags indicating if there
is a resizer */
unsigned long s_commit_interval;
u32 s_max_batch_time;
u32 s_min_batch_time;
struct block_device *journal_bdev;
#ifdef CONFIG_QUOTA
char *s_qf_names[MAXQUOTAS]; /* Names of quota files with journalled quota */
int s_jquota_fmt; /* Format of quota to use */
#endif
unsigned int s_want_extra_isize; /* New inodes should reserve # bytes */
struct rb_root system_blks;
#ifdef EXTENTS_STATS
/* ext4 extents stats */
unsigned long s_ext_min;
unsigned long s_ext_max;
unsigned long s_depth_max;
spinlock_t s_ext_stats_lock;
unsigned long s_ext_blocks;
unsigned long s_ext_extents;
#endif
/* for buddy allocator */
struct ext4_group_info ***s_group_info;
struct inode *s_buddy_cache;
spinlock_t s_md_lock;
unsigned short *s_mb_offsets;
unsigned int *s_mb_maxs;
/* tunables */
unsigned long s_stripe;
unsigned int s_mb_stream_request;
unsigned int s_mb_max_to_scan;
unsigned int s_mb_min_to_scan;
unsigned int s_mb_stats;
unsigned int s_mb_order2_reqs;
unsigned int s_mb_group_prealloc;
unsigned int s_max_writeback_mb_bump;
/* where last allocation was done - for stream allocation */
unsigned long s_mb_last_group;
unsigned long s_mb_last_start;
/* stats for buddy allocator */
atomic_t s_bal_reqs; /* number of reqs with len > 1 */
atomic_t s_bal_success; /* we found long enough chunks */
atomic_t s_bal_allocated; /* in blocks */
atomic_t s_bal_ex_scanned; /* total extents scanned */
atomic_t s_bal_goals; /* goal hits */
atomic_t s_bal_breaks; /* too long searches */
atomic_t s_bal_2orders; /* 2^order hits */
spinlock_t s_bal_lock;
unsigned long s_mb_buddies_generated;
unsigned long long s_mb_generation_time;
atomic_t s_mb_lost_chunks;
atomic_t s_mb_preallocated;
atomic_t s_mb_discarded;
atomic_t s_lock_busy;
/* locality groups */
struct ext4_locality_group __percpu *s_locality_groups;
/* for write statistics */
unsigned long s_sectors_written_start;
u64 s_kbytes_written;
unsigned int s_log_groups_per_flex;
struct flex_groups *s_flex_groups;
/* workqueue for dio unwritten */
struct workqueue_struct *dio_unwritten_wq;
/* timer for periodic error stats printing */
struct timer_list s_err_report;
/* Lazy inode table initialization info */
struct ext4_li_request *s_li_request;
/* Wait multiplier for lazy initialization thread */
unsigned int s_li_wait_mult;
/* Kernel thread for multiple mount protection */
struct task_struct *s_mmp_tsk;
/* record the last minlen when FITRIM is called. */
atomic_t s_last_trim_minblks;
/* Ratelimit ext4 messages. */
struct ratelimit_state s_err_ratelimit_state;
struct ratelimit_state s_warning_ratelimit_state;
struct ratelimit_state s_msg_ratelimit_state;
};
static inline struct ext4_sb_info *EXT4_SB(struct super_block *sb)
{
return sb->s_fs_info;
}
static inline struct ext4_inode_info *EXT4_I(struct inode *inode)
{
return container_of(inode, struct ext4_inode_info, vfs_inode);
}
static inline struct timespec ext4_current_time(struct inode *inode)
{
return (inode->i_sb->s_time_gran < NSEC_PER_SEC) ?
current_fs_time(inode->i_sb) : CURRENT_TIME_SEC;
}
static inline int ext4_valid_inum(struct super_block *sb, unsigned long ino)
{
return ino == EXT4_ROOT_INO ||
ino == EXT4_JOURNAL_INO ||
ino == EXT4_RESIZE_INO ||
(ino >= EXT4_FIRST_INO(sb) &&
ino <= le32_to_cpu(EXT4_SB(sb)->s_es->s_inodes_count));
}
static inline void ext4_set_io_unwritten_flag(struct inode *inode,
struct ext4_io_end *io_end)
{
if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
io_end->flag |= EXT4_IO_END_UNWRITTEN;
atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
}
}
/*
* Inode dynamic state flags
*/
enum {
EXT4_STATE_JDATA, /* journaled data exists */
EXT4_STATE_NEW, /* inode is newly created */
EXT4_STATE_XATTR, /* has in-inode xattrs */
EXT4_STATE_NO_EXPAND, /* No space for expansion */
EXT4_STATE_DA_ALLOC_CLOSE, /* Alloc DA blks on close */
EXT4_STATE_EXT_MIGRATE, /* Inode is migrating */
EXT4_STATE_DIO_UNWRITTEN, /* need convert on dio done*/
EXT4_STATE_NEWENTRY, /* File just added to dir */
EXT4_STATE_DELALLOC_RESERVED, /* blks already reserved for delalloc */
};
#define EXT4_INODE_BIT_FNS(name, field, offset) \
static inline int ext4_test_inode_##name(struct inode *inode, int bit) \
{ \
return test_bit(bit + (offset), &EXT4_I(inode)->i_##field); \
} \
static inline void ext4_set_inode_##name(struct inode *inode, int bit) \
{ \
set_bit(bit + (offset), &EXT4_I(inode)->i_##field); \
} \
static inline void ext4_clear_inode_##name(struct inode *inode, int bit) \
{ \
clear_bit(bit + (offset), &EXT4_I(inode)->i_##field); \
}
EXT4_INODE_BIT_FNS(flag, flags, 0)
#if (BITS_PER_LONG < 64)
EXT4_INODE_BIT_FNS(state, state_flags, 0)
static inline void ext4_clear_state_flags(struct ext4_inode_info *ei)
{
(ei)->i_state_flags = 0;
}
#else
EXT4_INODE_BIT_FNS(state, flags, 32)
static inline void ext4_clear_state_flags(struct ext4_inode_info *ei)
{
/* We depend on the fact that callers will set i_flags */
}
#endif
#else
/* Assume that user mode programs are passing in an ext4fs superblock, not
* a kernel struct super_block. This will allow us to call the feature-test
* macros from user land. */
#define EXT4_SB(sb) (sb)
#endif
#define NEXT_ORPHAN(inode) EXT4_I(inode)->i_dtime
/*
* Codes for operating systems
*/
#define EXT4_OS_LINUX 0
#define EXT4_OS_HURD 1
#define EXT4_OS_MASIX 2
#define EXT4_OS_FREEBSD 3
#define EXT4_OS_LITES 4
/*
* Revision levels
*/
#define EXT4_GOOD_OLD_REV 0 /* The good old (original) format */
#define EXT4_DYNAMIC_REV 1 /* V2 format w/ dynamic inode sizes */
#define EXT4_CURRENT_REV EXT4_GOOD_OLD_REV
#define EXT4_MAX_SUPP_REV EXT4_DYNAMIC_REV
#define EXT4_GOOD_OLD_INODE_SIZE 128
/*
* Feature set definitions
*/
#define EXT4_HAS_COMPAT_FEATURE(sb,mask) \
((EXT4_SB(sb)->s_es->s_feature_compat & cpu_to_le32(mask)) != 0)
#define EXT4_HAS_RO_COMPAT_FEATURE(sb,mask) \
((EXT4_SB(sb)->s_es->s_feature_ro_compat & cpu_to_le32(mask)) != 0)
#define EXT4_HAS_INCOMPAT_FEATURE(sb,mask) \
((EXT4_SB(sb)->s_es->s_feature_incompat & cpu_to_le32(mask)) != 0)
#define EXT4_SET_COMPAT_FEATURE(sb,mask) \
EXT4_SB(sb)->s_es->s_feature_compat |= cpu_to_le32(mask)
#define EXT4_SET_RO_COMPAT_FEATURE(sb,mask) \
EXT4_SB(sb)->s_es->s_feature_ro_compat |= cpu_to_le32(mask)
#define EXT4_SET_INCOMPAT_FEATURE(sb,mask) \
EXT4_SB(sb)->s_es->s_feature_incompat |= cpu_to_le32(mask)
#define EXT4_CLEAR_COMPAT_FEATURE(sb,mask) \
EXT4_SB(sb)->s_es->s_feature_compat &= ~cpu_to_le32(mask)
#define EXT4_CLEAR_RO_COMPAT_FEATURE(sb,mask) \
EXT4_SB(sb)->s_es->s_feature_ro_compat &= ~cpu_to_le32(mask)
#define EXT4_CLEAR_INCOMPAT_FEATURE(sb,mask) \
EXT4_SB(sb)->s_es->s_feature_incompat &= ~cpu_to_le32(mask)
#define EXT4_FEATURE_COMPAT_DIR_PREALLOC 0x0001
#define EXT4_FEATURE_COMPAT_IMAGIC_INODES 0x0002
#define EXT4_FEATURE_COMPAT_HAS_JOURNAL 0x0004
#define EXT4_FEATURE_COMPAT_EXT_ATTR 0x0008
#define EXT4_FEATURE_COMPAT_RESIZE_INODE 0x0010
#define EXT4_FEATURE_COMPAT_DIR_INDEX 0x0020
#define EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER 0x0001
#define EXT4_FEATURE_RO_COMPAT_LARGE_FILE 0x0002
#define EXT4_FEATURE_RO_COMPAT_BTREE_DIR 0x0004
#define EXT4_FEATURE_RO_COMPAT_HUGE_FILE 0x0008
#define EXT4_FEATURE_RO_COMPAT_GDT_CSUM 0x0010
#define EXT4_FEATURE_RO_COMPAT_DIR_NLINK 0x0020
#define EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE 0x0040
#define EXT4_FEATURE_RO_COMPAT_QUOTA 0x0100
#define EXT4_FEATURE_RO_COMPAT_BIGALLOC 0x0200
#define EXT4_FEATURE_RO_COMPAT_METADATA_CSUM 0x0400
#define EXT4_FEATURE_INCOMPAT_COMPRESSION 0x0001
#define EXT4_FEATURE_INCOMPAT_FILETYPE 0x0002
#define EXT4_FEATURE_INCOMPAT_RECOVER 0x0004 /* Needs recovery */
#define EXT4_FEATURE_INCOMPAT_JOURNAL_DEV 0x0008 /* Journal device */
#define EXT4_FEATURE_INCOMPAT_META_BG 0x0010
#define EXT4_FEATURE_INCOMPAT_EXTENTS 0x0040 /* extents support */
#define EXT4_FEATURE_INCOMPAT_64BIT 0x0080
#define EXT4_FEATURE_INCOMPAT_MMP 0x0100
#define EXT4_FEATURE_INCOMPAT_FLEX_BG 0x0200
#define EXT4_FEATURE_INCOMPAT_EA_INODE 0x0400 /* EA in inode */
#define EXT4_FEATURE_INCOMPAT_DIRDATA 0x1000 /* data in dirent */
#define EXT4_FEATURE_INCOMPAT_BG_USE_META_CSUM 0x2000 /* use crc32c for bg */
#define EXT4_FEATURE_INCOMPAT_LARGEDIR 0x4000 /* >2GB or 3-lvl htree */
#define EXT4_FEATURE_INCOMPAT_INLINEDATA 0x8000 /* data in inode */
#define EXT2_FEATURE_COMPAT_SUPP EXT4_FEATURE_COMPAT_EXT_ATTR
#define EXT2_FEATURE_INCOMPAT_SUPP (EXT4_FEATURE_INCOMPAT_FILETYPE| \
EXT4_FEATURE_INCOMPAT_META_BG)
#define EXT2_FEATURE_RO_COMPAT_SUPP (EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER| \
EXT4_FEATURE_RO_COMPAT_LARGE_FILE| \
EXT4_FEATURE_RO_COMPAT_BTREE_DIR)
#define EXT3_FEATURE_COMPAT_SUPP EXT4_FEATURE_COMPAT_EXT_ATTR
#define EXT3_FEATURE_INCOMPAT_SUPP (EXT4_FEATURE_INCOMPAT_FILETYPE| \
EXT4_FEATURE_INCOMPAT_RECOVER| \
EXT4_FEATURE_INCOMPAT_META_BG)
#define EXT3_FEATURE_RO_COMPAT_SUPP (EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER| \
EXT4_FEATURE_RO_COMPAT_LARGE_FILE| \
EXT4_FEATURE_RO_COMPAT_BTREE_DIR)
#define EXT4_FEATURE_COMPAT_SUPP EXT2_FEATURE_COMPAT_EXT_ATTR
#define EXT4_FEATURE_INCOMPAT_SUPP (EXT4_FEATURE_INCOMPAT_FILETYPE| \
EXT4_FEATURE_INCOMPAT_RECOVER| \
EXT4_FEATURE_INCOMPAT_META_BG| \
EXT4_FEATURE_INCOMPAT_EXTENTS| \
EXT4_FEATURE_INCOMPAT_64BIT| \
EXT4_FEATURE_INCOMPAT_FLEX_BG| \
EXT4_FEATURE_INCOMPAT_MMP)
#define EXT4_FEATURE_RO_COMPAT_SUPP (EXT4_FEATURE_RO_COMPAT_SPARSE_SUPER| \
EXT4_FEATURE_RO_COMPAT_LARGE_FILE| \
EXT4_FEATURE_RO_COMPAT_GDT_CSUM| \
EXT4_FEATURE_RO_COMPAT_DIR_NLINK | \
EXT4_FEATURE_RO_COMPAT_EXTRA_ISIZE | \
EXT4_FEATURE_RO_COMPAT_BTREE_DIR |\
EXT4_FEATURE_RO_COMPAT_HUGE_FILE |\
EXT4_FEATURE_RO_COMPAT_BIGALLOC)
/*
* Default values for user and/or group using reserved blocks
*/
#define EXT4_DEF_RESUID 0
#define EXT4_DEF_RESGID 0
#define EXT4_DEF_INODE_READAHEAD_BLKS 32
/*
* Default mount options
*/
#define EXT4_DEFM_DEBUG 0x0001
#define EXT4_DEFM_BSDGROUPS 0x0002
#define EXT4_DEFM_XATTR_USER 0x0004
#define EXT4_DEFM_ACL 0x0008
#define EXT4_DEFM_UID16 0x0010
#define EXT4_DEFM_JMODE 0x0060
#define EXT4_DEFM_JMODE_DATA 0x0020
#define EXT4_DEFM_JMODE_ORDERED 0x0040
#define EXT4_DEFM_JMODE_WBACK 0x0060
#define EXT4_DEFM_NOBARRIER 0x0100
#define EXT4_DEFM_BLOCK_VALIDITY 0x0200
#define EXT4_DEFM_DISCARD 0x0400
#define EXT4_DEFM_NODELALLOC 0x0800
/*
* Default journal batch times
*/
#define EXT4_DEF_MIN_BATCH_TIME 0
#define EXT4_DEF_MAX_BATCH_TIME 15000 /* 15ms */
/*
* Minimum number of groups in a flexgroup before we separate out
* directories into the first block group of a flexgroup
*/
#define EXT4_FLEX_SIZE_DIR_ALLOC_SCHEME 4
/*
* Structure of a directory entry
*/
#define EXT4_NAME_LEN 255
struct ext4_dir_entry {
__le32 inode; /* Inode number */
__le16 rec_len; /* Directory entry length */
__le16 name_len; /* Name length */
char name[EXT4_NAME_LEN]; /* File name */
};
/*
* The new version of the directory entry. Since EXT4 structures are
* stored in intel byte order, and the name_len field could never be
* bigger than 255 chars, it's safe to reclaim the extra byte for the
* file_type field.
*/
struct ext4_dir_entry_2 {
__le32 inode; /* Inode number */
__le16 rec_len; /* Directory entry length */
__u8 name_len; /* Name length */
__u8 file_type;
char name[EXT4_NAME_LEN]; /* File name */
};
/*
* Ext4 directory file types. Only the low 3 bits are used. The
* other bits are reserved for now.
*/
#define EXT4_FT_UNKNOWN 0
#define EXT4_FT_REG_FILE 1
#define EXT4_FT_DIR 2
#define EXT4_FT_CHRDEV 3
#define EXT4_FT_BLKDEV 4
#define EXT4_FT_FIFO 5
#define EXT4_FT_SOCK 6
#define EXT4_FT_SYMLINK 7
#define EXT4_FT_MAX 8
/*
* EXT4_DIR_PAD defines the directory entries boundaries
*
* NOTE: It must be a multiple of 4
*/
#define EXT4_DIR_PAD 4
#define EXT4_DIR_ROUND (EXT4_DIR_PAD - 1)
#define EXT4_DIR_REC_LEN(name_len) (((name_len) + 8 + EXT4_DIR_ROUND) & \
~EXT4_DIR_ROUND)
#define EXT4_MAX_REC_LEN ((1<<16)-1)
/*
* If we ever get support for fs block sizes > page_size, we'll need
* to remove the #if statements in the next two functions...
*/
static inline unsigned int
ext4_rec_len_from_disk(__le16 dlen, unsigned blocksize)
{
unsigned len = le16_to_cpu(dlen);
#if (PAGE_CACHE_SIZE >= 65536)
if (len == EXT4_MAX_REC_LEN || len == 0)
return blocksize;
return (len & 65532) | ((len & 3) << 16);
#else
return len;
#endif
}
static inline __le16 ext4_rec_len_to_disk(unsigned len, unsigned blocksize)
{
if ((len > blocksize) || (blocksize > (1 << 18)) || (len & 3))
BUG();
#if (PAGE_CACHE_SIZE >= 65536)
if (len < 65536)
return cpu_to_le16(len);
if (len == blocksize) {
if (blocksize == 65536)
return cpu_to_le16(EXT4_MAX_REC_LEN);
else
return cpu_to_le16(0);
}
return cpu_to_le16((len & 65532) | ((len >> 16) & 3));
#else
return cpu_to_le16(len);
#endif
}
/*
* Hash Tree Directory indexing
* (c) Daniel Phillips, 2001
*/
#define is_dx(dir) (EXT4_HAS_COMPAT_FEATURE(dir->i_sb, \
EXT4_FEATURE_COMPAT_DIR_INDEX) && \
ext4_test_inode_flag((dir), EXT4_INODE_INDEX))
#define EXT4_DIR_LINK_MAX(dir) (!is_dx(dir) && (dir)->i_nlink >= EXT4_LINK_MAX)
#define EXT4_DIR_LINK_EMPTY(dir) ((dir)->i_nlink == 2 || (dir)->i_nlink == 1)
/* Legal values for the dx_root hash_version field: */
#define DX_HASH_LEGACY 0
#define DX_HASH_HALF_MD4 1
#define DX_HASH_TEA 2
#define DX_HASH_LEGACY_UNSIGNED 3
#define DX_HASH_HALF_MD4_UNSIGNED 4
#define DX_HASH_TEA_UNSIGNED 5
#ifdef __KERNEL__
/* hash info structure used by the directory hash */
struct dx_hash_info
{
u32 hash;
u32 minor_hash;
int hash_version;
u32 *seed;
};
/* 32 and 64 bit signed EOF for dx directories */
#define EXT4_HTREE_EOF_32BIT ((1UL << (32 - 1)) - 1)
#define EXT4_HTREE_EOF_64BIT ((1ULL << (64 - 1)) - 1)
/*
* Control parameters used by ext4_htree_next_block
*/
#define HASH_NB_ALWAYS 1
/*
* Describe an inode's exact location on disk and in memory
*/
struct ext4_iloc
{
struct buffer_head *bh;
unsigned long offset;
ext4_group_t block_group;
};
static inline struct ext4_inode *ext4_raw_inode(struct ext4_iloc *iloc)
{
return (struct ext4_inode *) (iloc->bh->b_data + iloc->offset);
}
/*
* This structure is stuffed into the struct file's private_data field
* for directories. It is where we put information so that we can do
* readdir operations in hash tree order.
*/
struct dir_private_info {
struct rb_root root;
struct rb_node *curr_node;
struct fname *extra_fname;
loff_t last_pos;
__u32 curr_hash;
__u32 curr_minor_hash;
__u32 next_hash;
};
/* calculate the first block number of the group */
static inline ext4_fsblk_t
ext4_group_first_block_no(struct super_block *sb, ext4_group_t group_no)
{
return group_no * (ext4_fsblk_t)EXT4_BLOCKS_PER_GROUP(sb) +
le32_to_cpu(EXT4_SB(sb)->s_es->s_first_data_block);
}
/*
* Special error return code only used by dx_probe() and its callers.
*/
#define ERR_BAD_DX_DIR -75000
void ext4_get_group_no_and_offset(struct super_block *sb, ext4_fsblk_t blocknr,
ext4_group_t *blockgrpp, ext4_grpblk_t *offsetp);
/*
* Timeout and state flag for lazy initialization inode thread.
*/
#define EXT4_DEF_LI_WAIT_MULT 10
#define EXT4_DEF_LI_MAX_START_DELAY 5
#define EXT4_LAZYINIT_QUIT 0x0001
#define EXT4_LAZYINIT_RUNNING 0x0002
/*
* Lazy inode table initialization info
*/
struct ext4_lazy_init {
unsigned long li_state;
struct list_head li_request_list;
struct mutex li_list_mtx;
};
struct ext4_li_request {
struct super_block *lr_super;
struct ext4_sb_info *lr_sbi;
ext4_group_t lr_next_group;
struct list_head lr_request;
unsigned long lr_next_sched;
unsigned long lr_timeout;
};
struct ext4_features {
struct kobject f_kobj;
struct completion f_kobj_unregister;
};
/*
* This structure will be used for multiple mount protection. It will be
* written into the block number saved in the s_mmp_block field in the
* superblock. Programs that check MMP should assume that if
* SEQ_FSCK (or any unknown code above SEQ_MAX) is present then it is NOT safe
* to use the filesystem, regardless of how old the timestamp is.
*/
#define EXT4_MMP_MAGIC 0x004D4D50U /* ASCII for MMP */
#define EXT4_MMP_SEQ_CLEAN 0xFF4D4D50U /* mmp_seq value for clean unmount */
#define EXT4_MMP_SEQ_FSCK 0xE24D4D50U /* mmp_seq value when being fscked */
#define EXT4_MMP_SEQ_MAX 0xE24D4D4FU /* maximum valid mmp_seq value */
struct mmp_struct {
__le32 mmp_magic; /* Magic number for MMP */
__le32 mmp_seq; /* Sequence no. updated periodically */
/*
* mmp_time, mmp_nodename & mmp_bdevname are only used for information
* purposes and do not affect the correctness of the algorithm
*/
__le64 mmp_time; /* Time last updated */
char mmp_nodename[64]; /* Node which last updated MMP block */
char mmp_bdevname[32]; /* Bdev which last updated MMP block */
/*
* mmp_check_interval is used to verify if the MMP block has been
* updated on the block device. The value is updated based on the
* maximum time to write the MMP block during an update cycle.
*/
__le16 mmp_check_interval;
__le16 mmp_pad1;
__le32 mmp_pad2[227];
};
/* arguments passed to the mmp thread */
struct mmpd_data {
struct buffer_head *bh; /* bh from initial read_mmp_block() */
struct super_block *sb; /* super block of the fs */
};
/*
* Check interval multiplier
* The MMP block is written every update interval and initially checked every
* update interval x the multiplier (the value is then adapted based on the
* write latency). The reason is that writes can be delayed under load and we
* don't want readers to incorrectly assume that the filesystem is no longer
* in use.
*/
#define EXT4_MMP_CHECK_MULT 2UL
/*
* Minimum interval for MMP checking in seconds.
*/
#define EXT4_MMP_MIN_CHECK_INTERVAL 5UL
/*
* Maximum interval for MMP checking in seconds.
*/
#define EXT4_MMP_MAX_CHECK_INTERVAL 300UL
/*
* Function prototypes
*/
/*
* Ok, these declarations are also in <linux/kernel.h> but none of the
* ext4 source programs needs to include it so they are duplicated here.
*/
# define NORET_TYPE /**/
# define ATTRIB_NORET __attribute__((noreturn))
# define NORET_AND noreturn,
/* bitmap.c */
extern unsigned int ext4_count_free(char *bitmap, unsigned numchars);
/* balloc.c */
extern unsigned int ext4_block_group(struct super_block *sb,
ext4_fsblk_t blocknr);
extern ext4_grpblk_t ext4_block_group_offset(struct super_block *sb,
ext4_fsblk_t blocknr);
extern int ext4_bg_has_super(struct super_block *sb, ext4_group_t group);
extern unsigned long ext4_bg_num_gdb(struct super_block *sb,
ext4_group_t group);
extern ext4_fsblk_t ext4_new_meta_blocks(handle_t *handle, struct inode *inode,
ext4_fsblk_t goal,
unsigned int flags,
unsigned long *count,
int *errp);
extern int ext4_claim_free_clusters(struct ext4_sb_info *sbi,
s64 nclusters, unsigned int flags);
extern ext4_fsblk_t ext4_count_free_clusters(struct super_block *);
extern void ext4_check_blocks_bitmap(struct super_block *);
extern struct ext4_group_desc * ext4_get_group_desc(struct super_block * sb,
ext4_group_t block_group,
struct buffer_head ** bh);
extern int ext4_should_retry_alloc(struct super_block *sb, int *retries);
extern struct buffer_head *ext4_read_block_bitmap_nowait(struct super_block *sb,
ext4_group_t block_group);
extern int ext4_wait_block_bitmap(struct super_block *sb,
ext4_group_t block_group,
struct buffer_head *bh);
extern struct buffer_head *ext4_read_block_bitmap(struct super_block *sb,
ext4_group_t block_group);
extern void ext4_init_block_bitmap(struct super_block *sb,
struct buffer_head *bh,
ext4_group_t group,
struct ext4_group_desc *desc);
extern unsigned ext4_free_clusters_after_init(struct super_block *sb,
ext4_group_t block_group,
struct ext4_group_desc *gdp);
extern unsigned ext4_num_overhead_clusters(struct super_block *sb,
ext4_group_t block_group,
struct ext4_group_desc *gdp);
ext4_fsblk_t ext4_inode_to_goal_block(struct inode *);
/* dir.c */
extern int __ext4_check_dir_entry(const char *, unsigned int, struct inode *,
struct file *,
struct ext4_dir_entry_2 *,
struct buffer_head *, unsigned int);
#define ext4_check_dir_entry(dir, filp, de, bh, offset) \
unlikely(__ext4_check_dir_entry(__func__, __LINE__, (dir), (filp), \
(de), (bh), (offset)))
extern int ext4_htree_store_dirent(struct file *dir_file, __u32 hash,
__u32 minor_hash,
struct ext4_dir_entry_2 *dirent);
extern void ext4_htree_free_dir_info(struct dir_private_info *p);
/* fsync.c */
extern int ext4_sync_file(struct file *, loff_t, loff_t, int);
extern int ext4_flush_completed_IO(struct inode *);
/* hash.c */
extern int ext4fs_dirhash(const char *name, int len, struct
dx_hash_info *hinfo);
/* ialloc.c */
extern struct inode *ext4_new_inode(handle_t *, struct inode *, umode_t,
const struct qstr *qstr, __u32 goal,
uid_t *owner);
extern void ext4_free_inode(handle_t *, struct inode *);
extern struct inode * ext4_orphan_get(struct super_block *, unsigned long);
extern unsigned long ext4_count_free_inodes(struct super_block *);
extern unsigned long ext4_count_dirs(struct super_block *);
extern void ext4_check_inodes_bitmap(struct super_block *);
extern void ext4_mark_bitmap_end(int start_bit, int end_bit, char *bitmap);
extern int ext4_init_inode_table(struct super_block *sb,
ext4_group_t group, int barrier);
extern void ext4_end_bitmap_read(struct buffer_head *bh, int uptodate);
/* mballoc.c */
extern long ext4_mb_stats;
extern long ext4_mb_max_to_scan;
extern int ext4_mb_init(struct super_block *, int);
extern int ext4_mb_release(struct super_block *);
extern ext4_fsblk_t ext4_mb_new_blocks(handle_t *,
struct ext4_allocation_request *, int *);
extern int ext4_mb_reserve_blocks(struct super_block *, int);
extern void ext4_discard_preallocations(struct inode *);
extern int __init ext4_init_mballoc(void);
extern void ext4_exit_mballoc(void);
extern void ext4_free_blocks(handle_t *handle, struct inode *inode,
struct buffer_head *bh, ext4_fsblk_t block,
unsigned long count, int flags);
extern int ext4_mb_add_groupinfo(struct super_block *sb,
ext4_group_t i, struct ext4_group_desc *desc);
extern int ext4_group_add_blocks(handle_t *handle, struct super_block *sb,
ext4_fsblk_t block, unsigned long count);
extern int ext4_trim_fs(struct super_block *, struct fstrim_range *);
/* inode.c */
struct buffer_head *ext4_getblk(handle_t *, struct inode *,
ext4_lblk_t, int, int *);
struct buffer_head *ext4_bread(handle_t *, struct inode *,
ext4_lblk_t, int, int *);
int ext4_get_block(struct inode *inode, sector_t iblock,
struct buffer_head *bh_result, int create);
extern struct inode *ext4_iget(struct super_block *, unsigned long);
extern int ext4_write_inode(struct inode *, struct writeback_control *);
extern int ext4_setattr(struct dentry *, struct iattr *);
extern int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
struct kstat *stat);
extern void ext4_evict_inode(struct inode *);
extern void ext4_clear_inode(struct inode *);
extern int ext4_sync_inode(handle_t *, struct inode *);
extern void ext4_dirty_inode(struct inode *, int);
extern int ext4_change_inode_journal_flag(struct inode *, int);
extern int ext4_get_inode_loc(struct inode *, struct ext4_iloc *);
extern int ext4_can_truncate(struct inode *inode);
extern void ext4_truncate(struct inode *);
extern int ext4_punch_hole(struct file *file, loff_t offset, loff_t length);
extern int ext4_truncate_restart_trans(handle_t *, struct inode *, int nblocks);
extern void ext4_set_inode_flags(struct inode *);
extern void ext4_get_inode_flags(struct ext4_inode_info *);
extern int ext4_alloc_da_blocks(struct inode *inode);
extern void ext4_set_aops(struct inode *inode);
extern int ext4_writepage_trans_blocks(struct inode *);
extern int ext4_chunk_trans_blocks(struct inode *, int nrblocks);
extern int ext4_discard_partial_page_buffers(handle_t *handle,
struct address_space *mapping, loff_t from,
loff_t length, int flags);
extern int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf);
extern qsize_t *ext4_get_reserved_space(struct inode *inode);
extern void ext4_da_update_reserve_space(struct inode *inode,
int used, int quota_claim);
/* indirect.c */
extern int ext4_ind_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags);
extern ssize_t ext4_ind_direct_IO(int rw, struct kiocb *iocb,
const struct iovec *iov, loff_t offset,
unsigned long nr_segs);
extern int ext4_ind_calc_metadata_amount(struct inode *inode, sector_t lblock);
extern int ext4_ind_trans_blocks(struct inode *inode, int nrblocks, int chunk);
extern void ext4_ind_truncate(struct inode *inode);
/* ioctl.c */
extern long ext4_ioctl(struct file *, unsigned int, unsigned long);
extern long ext4_compat_ioctl(struct file *, unsigned int, unsigned long);
/* migrate.c */
extern int ext4_ext_migrate(struct inode *);
/* namei.c */
extern int ext4_orphan_add(handle_t *, struct inode *);
extern int ext4_orphan_del(handle_t *, struct inode *);
extern int ext4_htree_fill_tree(struct file *dir_file, __u32 start_hash,
__u32 start_minor_hash, __u32 *next_hash);
/* resize.c */
extern int ext4_group_add(struct super_block *sb,
struct ext4_new_group_data *input);
extern int ext4_group_extend(struct super_block *sb,
struct ext4_super_block *es,
ext4_fsblk_t n_blocks_count);
extern int ext4_resize_fs(struct super_block *sb, ext4_fsblk_t n_blocks_count);
/* super.c */
extern int ext4_calculate_overhead(struct super_block *sb);
extern void *ext4_kvmalloc(size_t size, gfp_t flags);
extern void *ext4_kvzalloc(size_t size, gfp_t flags);
extern void ext4_kvfree(void *ptr);
extern __printf(4, 5)
void __ext4_error(struct super_block *, const char *, unsigned int,
const char *, ...);
#define ext4_error(sb, message...) __ext4_error(sb, __func__, \
__LINE__, ## message)
extern __printf(5, 6)
void ext4_error_inode(struct inode *, const char *, unsigned int, ext4_fsblk_t,
const char *, ...);
extern __printf(5, 6)
void ext4_error_file(struct file *, const char *, unsigned int, ext4_fsblk_t,
const char *, ...);
extern void __ext4_std_error(struct super_block *, const char *,
unsigned int, int);
extern __printf(4, 5)
void __ext4_abort(struct super_block *, const char *, unsigned int,
const char *, ...);
#define ext4_abort(sb, message...) __ext4_abort(sb, __func__, \
__LINE__, ## message)
extern __printf(4, 5)
void __ext4_warning(struct super_block *, const char *, unsigned int,
const char *, ...);
#define ext4_warning(sb, message...) __ext4_warning(sb, __func__, \
__LINE__, ## message)
extern __printf(3, 4)
void ext4_msg(struct super_block *, const char *, const char *, ...);
extern void __dump_mmp_msg(struct super_block *, struct mmp_struct *mmp,
const char *, unsigned int, const char *);
#define dump_mmp_msg(sb, mmp, msg) __dump_mmp_msg(sb, mmp, __func__, \
__LINE__, msg)
extern __printf(7, 8)
void __ext4_grp_locked_error(const char *, unsigned int,
struct super_block *, ext4_group_t,
unsigned long, ext4_fsblk_t,
const char *, ...);
#define ext4_grp_locked_error(sb, grp, message...) \
__ext4_grp_locked_error(__func__, __LINE__, (sb), (grp), ## message)
extern void ext4_update_dynamic_rev(struct super_block *sb);
extern int ext4_update_compat_feature(handle_t *handle, struct super_block *sb,
__u32 compat);
extern int ext4_update_rocompat_feature(handle_t *handle,
struct super_block *sb, __u32 rocompat);
extern int ext4_update_incompat_feature(handle_t *handle,
struct super_block *sb, __u32 incompat);
extern ext4_fsblk_t ext4_block_bitmap(struct super_block *sb,
struct ext4_group_desc *bg);
extern ext4_fsblk_t ext4_inode_bitmap(struct super_block *sb,
struct ext4_group_desc *bg);
extern ext4_fsblk_t ext4_inode_table(struct super_block *sb,
struct ext4_group_desc *bg);
extern __u32 ext4_free_group_clusters(struct super_block *sb,
struct ext4_group_desc *bg);
extern __u32 ext4_free_inodes_count(struct super_block *sb,
struct ext4_group_desc *bg);
extern __u32 ext4_used_dirs_count(struct super_block *sb,
struct ext4_group_desc *bg);
extern __u32 ext4_itable_unused_count(struct super_block *sb,
struct ext4_group_desc *bg);
extern void ext4_block_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk);
extern void ext4_inode_bitmap_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk);
extern void ext4_inode_table_set(struct super_block *sb,
struct ext4_group_desc *bg, ext4_fsblk_t blk);
extern void ext4_free_group_clusters_set(struct super_block *sb,
struct ext4_group_desc *bg,
__u32 count);
extern void ext4_free_inodes_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count);
extern void ext4_used_dirs_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count);
extern void ext4_itable_unused_set(struct super_block *sb,
struct ext4_group_desc *bg, __u32 count);
extern __le16 ext4_group_desc_csum(struct ext4_sb_info *sbi, __u32 group,
struct ext4_group_desc *gdp);
extern int ext4_group_desc_csum_verify(struct ext4_sb_info *sbi, __u32 group,
struct ext4_group_desc *gdp);
static inline ext4_fsblk_t ext4_blocks_count(struct ext4_super_block *es)
{
return ((ext4_fsblk_t)le32_to_cpu(es->s_blocks_count_hi) << 32) |
le32_to_cpu(es->s_blocks_count_lo);
}
static inline ext4_fsblk_t ext4_r_blocks_count(struct ext4_super_block *es)
{
return ((ext4_fsblk_t)le32_to_cpu(es->s_r_blocks_count_hi) << 32) |
le32_to_cpu(es->s_r_blocks_count_lo);
}
static inline ext4_fsblk_t ext4_free_blocks_count(struct ext4_super_block *es)
{
return ((ext4_fsblk_t)le32_to_cpu(es->s_free_blocks_count_hi) << 32) |
le32_to_cpu(es->s_free_blocks_count_lo);
}
static inline void ext4_blocks_count_set(struct ext4_super_block *es,
ext4_fsblk_t blk)
{
es->s_blocks_count_lo = cpu_to_le32((u32)blk);
es->s_blocks_count_hi = cpu_to_le32(blk >> 32);
}
static inline void ext4_free_blocks_count_set(struct ext4_super_block *es,
ext4_fsblk_t blk)
{
es->s_free_blocks_count_lo = cpu_to_le32((u32)blk);
es->s_free_blocks_count_hi = cpu_to_le32(blk >> 32);
}
static inline void ext4_r_blocks_count_set(struct ext4_super_block *es,
ext4_fsblk_t blk)
{
es->s_r_blocks_count_lo = cpu_to_le32((u32)blk);
es->s_r_blocks_count_hi = cpu_to_le32(blk >> 32);
}
static inline loff_t ext4_isize(struct ext4_inode *raw_inode)
{
if (S_ISREG(le16_to_cpu(raw_inode->i_mode)))
return ((loff_t)le32_to_cpu(raw_inode->i_size_high) << 32) |
le32_to_cpu(raw_inode->i_size_lo);
else
return (loff_t) le32_to_cpu(raw_inode->i_size_lo);
}
static inline void ext4_isize_set(struct ext4_inode *raw_inode, loff_t i_size)
{
raw_inode->i_size_lo = cpu_to_le32(i_size);
raw_inode->i_size_high = cpu_to_le32(i_size >> 32);
}
static inline
struct ext4_group_info *ext4_get_group_info(struct super_block *sb,
ext4_group_t group)
{
struct ext4_group_info ***grp_info;
long indexv, indexh;
grp_info = EXT4_SB(sb)->s_group_info;
indexv = group >> (EXT4_DESC_PER_BLOCK_BITS(sb));
indexh = group & ((EXT4_DESC_PER_BLOCK(sb)) - 1);
return grp_info[indexv][indexh];
}
/*
* Reading s_groups_count requires using smp_rmb() afterwards. See
* the locking protocol documented in the comments of ext4_group_add()
* in resize.c
*/
static inline ext4_group_t ext4_get_groups_count(struct super_block *sb)
{
ext4_group_t ngroups = EXT4_SB(sb)->s_groups_count;
smp_rmb();
return ngroups;
}
static inline ext4_group_t ext4_flex_group(struct ext4_sb_info *sbi,
ext4_group_t block_group)
{
return block_group >> sbi->s_log_groups_per_flex;
}
static inline unsigned int ext4_flex_bg_size(struct ext4_sb_info *sbi)
{
return 1 << sbi->s_log_groups_per_flex;
}
#define ext4_std_error(sb, errno) \
do { \
if ((errno)) \
__ext4_std_error((sb), __func__, __LINE__, (errno)); \
} while (0)
#ifdef CONFIG_SMP
/* Each CPU can accumulate percpu_counter_batch clusters in their local
* counters. So we need to make sure we have free clusters more
* than percpu_counter_batch * nr_cpu_ids. Also add a window of 4 times.
*/
#define EXT4_FREECLUSTERS_WATERMARK (4 * (percpu_counter_batch * nr_cpu_ids))
#else
#define EXT4_FREECLUSTERS_WATERMARK 0
#endif
static inline void ext4_update_i_disksize(struct inode *inode, loff_t newsize)
{
/*
* XXX: replace with spinlock if seen contended -bzzz
*/
down_write(&EXT4_I(inode)->i_data_sem);
if (newsize > EXT4_I(inode)->i_disksize)
EXT4_I(inode)->i_disksize = newsize;
up_write(&EXT4_I(inode)->i_data_sem);
return ;
}
struct ext4_group_info {
unsigned long bb_state;
struct rb_root bb_free_root;
ext4_grpblk_t bb_first_free; /* first free block */
ext4_grpblk_t bb_free; /* total free blocks */
ext4_grpblk_t bb_fragments; /* nr of freespace fragments */
ext4_grpblk_t bb_largest_free_order;/* order of largest frag in BG */
struct list_head bb_prealloc_list;
#ifdef DOUBLE_CHECK
void *bb_bitmap;
#endif
struct rw_semaphore alloc_sem;
ext4_grpblk_t bb_counters[]; /* Nr of free power-of-two-block
* regions, index is order.
* bb_counters[3] = 5 means
* 5 free 8-block regions. */
};
#define EXT4_GROUP_INFO_NEED_INIT_BIT 0
#define EXT4_GROUP_INFO_WAS_TRIMMED_BIT 1
#define EXT4_MB_GRP_NEED_INIT(grp) \
(test_bit(EXT4_GROUP_INFO_NEED_INIT_BIT, &((grp)->bb_state)))
#define EXT4_MB_GRP_WAS_TRIMMED(grp) \
(test_bit(EXT4_GROUP_INFO_WAS_TRIMMED_BIT, &((grp)->bb_state)))
#define EXT4_MB_GRP_SET_TRIMMED(grp) \
(set_bit(EXT4_GROUP_INFO_WAS_TRIMMED_BIT, &((grp)->bb_state)))
#define EXT4_MB_GRP_CLEAR_TRIMMED(grp) \
(clear_bit(EXT4_GROUP_INFO_WAS_TRIMMED_BIT, &((grp)->bb_state)))
#define EXT4_MAX_CONTENTION 8
#define EXT4_CONTENTION_THRESHOLD 2
static inline spinlock_t *ext4_group_lock_ptr(struct super_block *sb,
ext4_group_t group)
{
return bgl_lock_ptr(EXT4_SB(sb)->s_blockgroup_lock, group);
}
/*
* Returns true if the filesystem is busy enough that attempts to
* access the block group locks has run into contention.
*/
static inline int ext4_fs_is_busy(struct ext4_sb_info *sbi)
{
return (atomic_read(&sbi->s_lock_busy) > EXT4_CONTENTION_THRESHOLD);
}
static inline void ext4_lock_group(struct super_block *sb, ext4_group_t group)
{
spinlock_t *lock = ext4_group_lock_ptr(sb, group);
if (spin_trylock(lock))
/*
* We're able to grab the lock right away, so drop the
* lock contention counter.
*/
atomic_add_unless(&EXT4_SB(sb)->s_lock_busy, -1, 0);
else {
/*
* The lock is busy, so bump the contention counter,
* and then wait on the spin lock.
*/
atomic_add_unless(&EXT4_SB(sb)->s_lock_busy, 1,
EXT4_MAX_CONTENTION);
spin_lock(lock);
}
}
static inline void ext4_unlock_group(struct super_block *sb,
ext4_group_t group)
{
spin_unlock(ext4_group_lock_ptr(sb, group));
}
static inline void ext4_mark_super_dirty(struct super_block *sb)
{
if (EXT4_SB(sb)->s_journal == NULL)
sb->s_dirt =1;
}
/*
* Block validity checking
*/
#define ext4_check_indirect_blockref(inode, bh) \
ext4_check_blockref(__func__, __LINE__, inode, \
(__le32 *)(bh)->b_data, \
EXT4_ADDR_PER_BLOCK((inode)->i_sb))
#define ext4_ind_check_inode(inode) \
ext4_check_blockref(__func__, __LINE__, inode, \
EXT4_I(inode)->i_data, \
EXT4_NDIR_BLOCKS)
/*
* Inodes and files operations
*/
/* dir.c */
extern const struct file_operations ext4_dir_operations;
/* file.c */
extern const struct inode_operations ext4_file_inode_operations;
extern const struct file_operations ext4_file_operations;
extern loff_t ext4_llseek(struct file *file, loff_t offset, int origin);
/* namei.c */
extern const struct inode_operations ext4_dir_inode_operations;
extern const struct inode_operations ext4_special_inode_operations;
extern struct dentry *ext4_get_parent(struct dentry *child);
/* symlink.c */
extern const struct inode_operations ext4_symlink_inode_operations;
extern const struct inode_operations ext4_fast_symlink_inode_operations;
/* block_validity */
extern void ext4_release_system_zone(struct super_block *sb);
extern int ext4_setup_system_zone(struct super_block *sb);
extern int __init ext4_init_system_zone(void);
extern void ext4_exit_system_zone(void);
extern int ext4_data_block_valid(struct ext4_sb_info *sbi,
ext4_fsblk_t start_blk,
unsigned int count);
extern int ext4_check_blockref(const char *, unsigned int,
struct inode *, __le32 *, unsigned int);
/* extents.c */
extern int ext4_ext_tree_init(handle_t *handle, struct inode *);
extern int ext4_ext_writepage_trans_blocks(struct inode *, int);
extern int ext4_ext_index_trans_blocks(struct inode *inode, int nrblocks,
int chunk);
extern int ext4_ext_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags);
extern void ext4_ext_truncate(struct inode *);
extern int ext4_ext_punch_hole(struct file *file, loff_t offset,
loff_t length);
extern void ext4_ext_init(struct super_block *);
extern void ext4_ext_release(struct super_block *);
extern long ext4_fallocate(struct file *file, int mode, loff_t offset,
loff_t len);
extern int ext4_convert_unwritten_extents(struct inode *inode, loff_t offset,
ssize_t len);
extern int ext4_map_blocks(handle_t *handle, struct inode *inode,
struct ext4_map_blocks *map, int flags);
extern int ext4_fiemap(struct inode *inode, struct fiemap_extent_info *fieinfo,
__u64 start, __u64 len);
/* move_extent.c */
extern int ext4_move_extents(struct file *o_filp, struct file *d_filp,
__u64 start_orig, __u64 start_donor,
__u64 len, __u64 *moved_len);
/* page-io.c */
extern int __init ext4_init_pageio(void);
extern void ext4_exit_pageio(void);
extern void ext4_ioend_wait(struct inode *);
extern void ext4_free_io_end(ext4_io_end_t *io);
extern ext4_io_end_t *ext4_init_io_end(struct inode *inode, gfp_t flags);
extern int ext4_end_io_nolock(ext4_io_end_t *io);
extern void ext4_io_submit(struct ext4_io_submit *io);
extern int ext4_bio_write_page(struct ext4_io_submit *io,
struct page *page,
int len,
struct writeback_control *wbc);
/* mmp.c */
extern int ext4_multi_mount_protect(struct super_block *, ext4_fsblk_t);
/* BH_Uninit flag: blocks are allocated but uninitialized on disk */
enum ext4_state_bits {
BH_Uninit /* blocks are allocated but uninitialized on disk */
= BH_JBDPrivateStart,
BH_AllocFromCluster, /* allocated blocks were part of already
* allocated cluster. Note that this flag will
* never, ever appear in a buffer_head's state
* flag. See EXT4_MAP_FROM_CLUSTER to see where
* this is used. */
BH_Da_Mapped, /* Delayed allocated block that now has a mapping. This
* flag is set when ext4_map_blocks is called on a
* delayed allocated block to get its real mapping. */
};
BUFFER_FNS(Uninit, uninit)
TAS_BUFFER_FNS(Uninit, uninit)
BUFFER_FNS(Da_Mapped, da_mapped)
/*
* Add new method to test wether block and inode bitmaps are properly
* initialized. With uninit_bg reading the block from disk is not enough
* to mark the bitmap uptodate. We need to also zero-out the bitmap
*/
#define BH_BITMAP_UPTODATE BH_JBDPrivateStart
static inline int bitmap_uptodate(struct buffer_head *bh)
{
return (buffer_uptodate(bh) &&
test_bit(BH_BITMAP_UPTODATE, &(bh)->b_state));
}
static inline void set_bitmap_uptodate(struct buffer_head *bh)
{
set_bit(BH_BITMAP_UPTODATE, &(bh)->b_state);
}
#define in_range(b, first, len) ((b) >= (first) && (b) <= (first) + (len) - 1)
/* For ioend & aio unwritten conversion wait queues */
#define EXT4_WQ_HASH_SZ 37
#define ext4_ioend_wq(v) (&ext4__ioend_wq[((unsigned long)(v)) %\
EXT4_WQ_HASH_SZ])
#define ext4_aio_mutex(v) (&ext4__aio_mutex[((unsigned long)(v)) %\
EXT4_WQ_HASH_SZ])
extern wait_queue_head_t ext4__ioend_wq[EXT4_WQ_HASH_SZ];
extern struct mutex ext4__aio_mutex[EXT4_WQ_HASH_SZ];
#define EXT4_RESIZING 0
extern int ext4_resize_begin(struct super_block *sb);
extern void ext4_resize_end(struct super_block *sb);
#endif /* __KERNEL__ */
#include "ext4_extents.h"
#endif /* _EXT4_H */
|
paul-chambers/netgear-r7800
|
git_home/linux.git/sourcecode/fs/ext4/ext4.h
|
C
|
gpl-2.0
| 85,209 |
<html>
<head>
<title>RunUO Documentation - Class Overview - ArmorMaterialType</title>
</head>
<body bgcolor="white" style="font-family: Courier New" text="#000000" link="#000000" vlink="#000000" alink="#808080">
<h4><a href="../namespaces/Server.Items.html">Back to Server.Items</a></h4>
<h2>ArmorMaterialType (Enum)</h2>
Cloth = 0,<br>
Leather = 1,<br>
Studded = 2,<br>
Bone = 3,<br>
Spined = 4,<br>
Horned = 5,<br>
Barbed = 6,<br>
Ringmail = 7,<br>
Chainmail = 8,<br>
Plate = 9,<br>
Dragon = 10<br>
</body>
</html>
|
alucardxlx/caoticamente-shards
|
docs/types/ArmorMaterialType.html
|
HTML
|
gpl-2.0
| 633 |
# Stenodict
Stenodict aims to help shape how to use stenography in our modern world.
There is much more to text now than there ever was, between new
weird words, all the way to extended symbols such as emoji. We type cryptic
nonsense in the form of programming languages. We use function keys and movement
keys and modifiers and shortcuts. We have a whole set of problems
to deal with that the *writers of olde* never had to.
If stenography is ever really going to replace a keyboard for everyday use,
people need to use shortcuts, commands, and preferably they shouldn't have to
reinvent the wheel each time they want to do something.
This repository is a set of free, open source stenographic dictionaries to help
you with the task of evolving beyond a traditional keyboard.
## Adding a dictionary
**To submit a dictionary, you can do one of the following:**
1. Send me an email with your dictionary: [email protected]
2. Submit a GitHub issue with the needed information
3. Make a GitHub pull request on the gh-pages branch with your `dictname.md`
To submit a dictionary, you'll need:
- A steno dictionary in JSON or RTF/CRE format, or both.
- To create a description file, formatted like this one, but with your dictionary information filled in, instead. Note: "dictname" below would need to match the name of your actual dictionary, like `dictname.json` or `dictname.rtf`
```md
---
layout: dictionary
title: A Cool Title
version: 1
date: 2016-01-01
filename: dictname
author: My Name
tags: briefs captioning commands linux mac windows program-specific programming shortcuts symbols words
what: One-liner about my cool dictionary
formats:
- json
- rtf
---
## Why
This is a really cool dictionary. I'll describe it in about one paragraph. It's really great because when you use it you can write more words with the steno machine and it makes you cooler.
## How
Here you can extend on how to use the dictionary, offer tips and advice.
Feel free to spread out across multiple paragraphs...
- Use a bulleted list.
- Make your points.
- You can show raw steno: `STKPWHRAO*EUFRPBLGTSDZ`
- `STK`: "and"
And that's why you should use my dictionary!
```
|
morinted/stenodict
|
README.md
|
Markdown
|
gpl-2.0
| 2,170 |
package captiveportal::Controller::Signup;
use Moose;
BEGIN { extends 'captiveportal::PacketFence::Controller::Signup'; }
=head1 NAME
captiveportal::Controller::Root - Root Controller for captiveportal
=head1 DESCRIPTION
[enter your description here]
=cut
=head1 AUTHOR
Inverse inc. <[email protected]>
=head1 COPYRIGHT
Copyright (C) 2005-2015 Inverse inc.
=head1 LICENSE
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
USA.
=cut
__PACKAGE__->meta->make_immutable;
1;
|
louismunro/packetfence
|
html/captive-portal/lib/captiveportal/Controller/Signup.pm
|
Perl
|
gpl-2.0
| 1,110 |
[% title = i18n("release: enabling network") %]
[% INCLUDE header.html %]
<script type="text/javascript">
var waitTime=[% timer %];
var action = function() {
hidebar();
[% IF auto_redirect == "enabled" %]
$('toReplace').innerHTML = "[% i18n("Unable to detect network connectivity. Try restarting your web browser or opening a new tab to see if your access has been succesfully enabled.") | html %]";
[% ELSE %]
$('toReplace').innerHTML = "[% i18n("Your network access should be available. Close your current browser, and open a new one to start browsing.") | html %]";
[% END %]
};
var txt_ie = "[% i18n("Some versions of Internet Explorer may take a while before redirection occur.") | html %]";
var txt_web_notification = "[% i18n("Network access has been granted") %]"
// once the page is loaded
document.observe("dom:loaded", function() {
[% IF auto_redirect == "enabled" %]
// Opera is known to be broken with network detection so we warn the users
if (Prototype.Browser.Opera) {
$('browser_notes').innerHTML = "[% i18n("There are known issues with the automatic redirection on Opera browsers. Please open a new browser window from time to time to see if your access was enabled.") | html %]";
}
detectNetworkAccess.delay([% initial_delay %],
[% retry_delay %], "[% destination_url %]", "[% external_ip %]", "[% image_path %]"
);
//require access to web notifications now so it's ready when the access is activated
initWebNotifications();
[% END %]
});
</script>
<div id="about">
<img src="/content/images/unlock.png" alt="Access granted" />
[% IF auto_redirect == "enabled" %]
<p id="toReplace">[% i18n("Your network access is currently being enabled. Once network connectivity is established you will be automatically redirected.") %]</p>
[% ELSE %]
<p id="toReplace">[% i18n("Your network access is currently being enabled. Please wait...") %]</p>
[% END %]
<p id="browser_notes"></p>
<script type="text/javascript" src="/content/timerbar.js"></script>
<noscript><p>[% i18n("If you have scripting turned off, you will not be automatically redirected. Please enable scripting or open a new browser window from time to time to see if your access was enabled.") %]</p></noscript>
</div>
[%# DO NOT REMOVE! REQUIRED FOR NETWORK ACCESS DETECTION %]
<div id="internet-detection" style="display: none;"><img id="netdetect"/></div>
[% INCLUDE footer.html %]
|
louismunro/packetfence
|
html/captive-portal/templates/release.html
|
HTML
|
gpl-2.0
| 2,517 |
/*
* Template for the Discrete Cosine Transform for 32 samples
* Copyright (c) 2001, 2002 Fabrice Bellard
*
* 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 "dct32.h"
#include "mathops.h"
#if DCT32_FLOAT
# define dct32 ff_dct32_float
# define FIXHR(x) ((float)(x))
# define MULH3(x, y, s) ((s)*(y)*(x))
# define INTFLOAT float
#else
# define dct32 ff_dct32_fixed
# define FIXHR(a) ((int)((a) * (LLN(1)<<32) + 0.5))
# define MULH3(x, y, s) MULH((s)*(x), y)
# define INTFLOAT int
#endif
/* tab[i][j] = 1.0 / (2.0 * cos(pi*(2*k+1) / 2^(6 - j))) */
/* cos(i*pi/64) */
#define COS0_0 FIXHR(0.50060299823519630134/2)
#define COS0_1 FIXHR(0.50547095989754365998/2)
#define COS0_2 FIXHR(0.51544730992262454697/2)
#define COS0_3 FIXHR(0.53104259108978417447/2)
#define COS0_4 FIXHR(0.55310389603444452782/2)
#define COS0_5 FIXHR(0.58293496820613387367/2)
#define COS0_6 FIXHR(0.62250412303566481615/2)
#define COS0_7 FIXHR(0.67480834145500574602/2)
#define COS0_8 FIXHR(0.74453627100229844977/2)
#define COS0_9 FIXHR(0.83934964541552703873/2)
#define COS0_10 FIXHR(0.97256823786196069369/2)
#define COS0_11 FIXHR(1.16943993343288495515/4)
#define COS0_12 FIXHR(1.48416461631416627724/4)
#define COS0_13 FIXHR(2.05778100995341155085/8)
#define COS0_14 FIXHR(3.40760841846871878570/8)
#define COS0_15 FIXHR(10.19000812354805681150/32)
#define COS1_0 FIXHR(0.50241928618815570551/2)
#define COS1_1 FIXHR(0.52249861493968888062/2)
#define COS1_2 FIXHR(0.56694403481635770368/2)
#define COS1_3 FIXHR(0.64682178335999012954/2)
#define COS1_4 FIXHR(0.78815462345125022473/2)
#define COS1_5 FIXHR(1.06067768599034747134/4)
#define COS1_6 FIXHR(1.72244709823833392782/4)
#define COS1_7 FIXHR(5.10114861868916385802/16)
#define COS2_0 FIXHR(0.50979557910415916894/2)
#define COS2_1 FIXHR(0.60134488693504528054/2)
#define COS2_2 FIXHR(0.89997622313641570463/2)
#define COS2_3 FIXHR(2.56291544774150617881/8)
#define COS3_0 FIXHR(0.54119610014619698439/2)
#define COS3_1 FIXHR(1.30656296487637652785/4)
#define COS4_0 FIXHR(0.70710678118654752439/2)
/* butterfly operator */
#define BF(a, b, c, s)\
{\
tmp0 = val##a + val##b;\
tmp1 = val##a - val##b;\
val##a = tmp0;\
val##b = MULH3(tmp1, c, 1<<(s));\
}
#define BF0(a, b, c, s)\
{\
tmp0 = tab[a] + tab[b];\
tmp1 = tab[a] - tab[b];\
val##a = tmp0;\
val##b = MULH3(tmp1, c, 1<<(s));\
}
#define BF1(a, b, c, d)\
{\
BF(a, b, COS4_0, 1);\
BF(c, d,-COS4_0, 1);\
val##c += val##d;\
}
#define BF2(a, b, c, d)\
{\
BF(a, b, COS4_0, 1);\
BF(c, d,-COS4_0, 1);\
val##c += val##d;\
val##a += val##c;\
val##c += val##b;\
val##b += val##d;\
}
#define ADD(a, b) val##a += val##b
/* DCT32 without 1/sqrt(2) coef zero scaling. */
void dct32(INTFLOAT *out, const INTFLOAT *tab)
{
INTFLOAT tmp0, tmp1;
INTFLOAT val0 , val1 , val2 , val3 , val4 , val5 , val6 , val7 ,
val8 , val9 , val10, val11, val12, val13, val14, val15,
val16, val17, val18, val19, val20, val21, val22, val23,
val24, val25, val26, val27, val28, val29, val30, val31;
/* pass 1 */
BF0( 0, 31, COS0_0 , 1);
BF0(15, 16, COS0_15, 5);
/* pass 2 */
BF( 0, 15, COS1_0 , 1);
BF(16, 31,-COS1_0 , 1);
/* pass 1 */
BF0( 7, 24, COS0_7 , 1);
BF0( 8, 23, COS0_8 , 1);
/* pass 2 */
BF( 7, 8, COS1_7 , 4);
BF(23, 24,-COS1_7 , 4);
/* pass 3 */
BF( 0, 7, COS2_0 , 1);
BF( 8, 15,-COS2_0 , 1);
BF(16, 23, COS2_0 , 1);
BF(24, 31,-COS2_0 , 1);
/* pass 1 */
BF0( 3, 28, COS0_3 , 1);
BF0(12, 19, COS0_12, 2);
/* pass 2 */
BF( 3, 12, COS1_3 , 1);
BF(19, 28,-COS1_3 , 1);
/* pass 1 */
BF0( 4, 27, COS0_4 , 1);
BF0(11, 20, COS0_11, 2);
/* pass 2 */
BF( 4, 11, COS1_4 , 1);
BF(20, 27,-COS1_4 , 1);
/* pass 3 */
BF( 3, 4, COS2_3 , 3);
BF(11, 12,-COS2_3 , 3);
BF(19, 20, COS2_3 , 3);
BF(27, 28,-COS2_3 , 3);
/* pass 4 */
BF( 0, 3, COS3_0 , 1);
BF( 4, 7,-COS3_0 , 1);
BF( 8, 11, COS3_0 , 1);
BF(12, 15,-COS3_0 , 1);
BF(16, 19, COS3_0 , 1);
BF(20, 23,-COS3_0 , 1);
BF(24, 27, COS3_0 , 1);
BF(28, 31,-COS3_0 , 1);
/* pass 1 */
BF0( 1, 30, COS0_1 , 1);
BF0(14, 17, COS0_14, 3);
/* pass 2 */
BF( 1, 14, COS1_1 , 1);
BF(17, 30,-COS1_1 , 1);
/* pass 1 */
BF0( 6, 25, COS0_6 , 1);
BF0( 9, 22, COS0_9 , 1);
/* pass 2 */
BF( 6, 9, COS1_6 , 2);
BF(22, 25,-COS1_6 , 2);
/* pass 3 */
BF( 1, 6, COS2_1 , 1);
BF( 9, 14,-COS2_1 , 1);
BF(17, 22, COS2_1 , 1);
BF(25, 30,-COS2_1 , 1);
/* pass 1 */
BF0( 2, 29, COS0_2 , 1);
BF0(13, 18, COS0_13, 3);
/* pass 2 */
BF( 2, 13, COS1_2 , 1);
BF(18, 29,-COS1_2 , 1);
/* pass 1 */
BF0( 5, 26, COS0_5 , 1);
BF0(10, 21, COS0_10, 1);
/* pass 2 */
BF( 5, 10, COS1_5 , 2);
BF(21, 26,-COS1_5 , 2);
/* pass 3 */
BF( 2, 5, COS2_2 , 1);
BF(10, 13,-COS2_2 , 1);
BF(18, 21, COS2_2 , 1);
BF(26, 29,-COS2_2 , 1);
/* pass 4 */
BF( 1, 2, COS3_1 , 2);
BF( 5, 6,-COS3_1 , 2);
BF( 9, 10, COS3_1 , 2);
BF(13, 14,-COS3_1 , 2);
BF(17, 18, COS3_1 , 2);
BF(21, 22,-COS3_1 , 2);
BF(25, 26, COS3_1 , 2);
BF(29, 30,-COS3_1 , 2);
/* pass 5 */
BF1( 0, 1, 2, 3);
BF2( 4, 5, 6, 7);
BF1( 8, 9, 10, 11);
BF2(12, 13, 14, 15);
BF1(16, 17, 18, 19);
BF2(20, 21, 22, 23);
BF1(24, 25, 26, 27);
BF2(28, 29, 30, 31);
/* pass 6 */
ADD( 8, 12);
ADD(12, 10);
ADD(10, 14);
ADD(14, 9);
ADD( 9, 13);
ADD(13, 11);
ADD(11, 15);
out[ 0] = val0;
out[16] = val1;
out[ 8] = val2;
out[24] = val3;
out[ 4] = val4;
out[20] = val5;
out[12] = val6;
out[28] = val7;
out[ 2] = val8;
out[18] = val9;
out[10] = val10;
out[26] = val11;
out[ 6] = val12;
out[22] = val13;
out[14] = val14;
out[30] = val15;
ADD(24, 28);
ADD(28, 26);
ADD(26, 30);
ADD(30, 25);
ADD(25, 29);
ADD(29, 27);
ADD(27, 31);
out[ 1] = val16 + val24;
out[17] = val17 + val25;
out[ 9] = val18 + val26;
out[25] = val19 + val27;
out[ 5] = val20 + val28;
out[21] = val21 + val29;
out[13] = val22 + val30;
out[29] = val23 + val31;
out[ 3] = val24 + val20;
out[19] = val25 + val21;
out[11] = val26 + val22;
out[27] = val27 + val23;
out[ 7] = val28 + val18;
out[23] = val29 + val19;
out[15] = val30 + val17;
out[31] = val31;
}
|
tojo9900/vice
|
src/lib/libffmpeg/libavcodec/dct32_template.c
|
C
|
gpl-2.0
| 7,286 |
// $Id: Flag_Manip.cpp 91368 2010-08-16 13:03:34Z mhengstmengel $
#include "ace/Flag_Manip.h"
#if defined (ACE_LACKS_FCNTL)
# include "ace/OS_NS_stropts.h"
# include "ace/OS_NS_errno.h"
#endif /* ACE_LACKS_FCNTL */
#if !defined (__ACE_INLINE__)
#include "ace/Flag_Manip.inl"
#endif /* __ACE_INLINE__ */
#if defined (CYGWIN32)
# include "ace/os_include/os_termios.h"
#endif /* CYGWIN32 */
ACE_BEGIN_VERSIONED_NAMESPACE_DECL
// Flags are file status flags to turn on.
int
ACE::set_flags (ACE_HANDLE handle, int flags)
{
ACE_TRACE ("ACE::set_flags");
#if defined (ACE_LACKS_FCNTL)
switch (flags)
{
case ACE_NONBLOCK:
// nonblocking argument (1)
// blocking: (0)
{
int nonblock = 1;
return ACE_OS::ioctl (handle, FIONBIO, &nonblock);
}
default:
ACE_NOTSUP_RETURN (-1);
}
#else
int val = ACE_OS::fcntl (handle, F_GETFL, 0);
if (val == -1)
return -1;
// Turn on flags.
ACE_SET_BITS (val, flags);
if (ACE_OS::fcntl (handle, F_SETFL, val) == -1)
return -1;
else
return 0;
#endif /* ACE_LACKS_FCNTL */
}
// Flags are the file status flags to turn off.
int
ACE::clr_flags (ACE_HANDLE handle, int flags)
{
ACE_TRACE ("ACE::clr_flags");
#if defined (ACE_LACKS_FCNTL)
switch (flags)
{
case ACE_NONBLOCK:
// nonblocking argument (1)
// blocking: (0)
{
int nonblock = 0;
return ACE_OS::ioctl (handle, FIONBIO, &nonblock);
}
default:
ACE_NOTSUP_RETURN (-1);
}
#else
int val = ACE_OS::fcntl (handle, F_GETFL, 0);
if (val == -1)
return -1;
// Turn flags off.
ACE_CLR_BITS (val, flags);
if (ACE_OS::fcntl (handle, F_SETFL, val) == -1)
return -1;
else
return 0;
#endif /* ACE_LACKS_FCNTL */
}
ACE_END_VERSIONED_NAMESPACE_DECL
|
hlarsen/TBCPvP
|
dep/acelite/ace/Flag_Manip.cpp
|
C++
|
gpl-2.0
| 1,917 |
/*
* Seven Kingdoms 2: The Fryhtan War
*
* Copyright 1999 Enlight Software Ltd.
*
* 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, see <http://www.gnu.org/licenses/>.
*
*/
// Filename : OTXTRES.CPP
// Description : text resource
#include <otxtres.h>
#include <all.h>
#include <ofiletxt.h>
#include <c99_printf.h>
#include <stdlib.h>
#include <math.h>
#if(defined(SPANISH))
#define THOUSAND_SEPARATOR '.'
#define DECIMAL_SEPARATOR ','
#else
#define THOUSAND_SEPARATOR ','
#define DECIMAL_SEPARATOR '.'
#endif
// some country (like japan insert ',' every four digits)
#define THOUSAND_SEPARATOR_COUNT 3
// format of text resource file
// [<remark>mmmm]text... where mmmm is a 4-character check mark, optional
//
// format of the format string :
// %% a single percent
// %<n>s string, <n> is from 1 to 9, the number in the argument list (eg. %1s)
// %<n>[,f]d interger <f> is format type passed to Misc::format (eg. %2d)
// %<n>[,f]z similar to d, but suppressed on zero
// %<n>[,f]f float <f> is format type passed to Misc::format (eg. %3,1f)
// %<n>p{<s>|<p>} use <s> singular form or <p> plural form, determined by integer argment <n>
// (e.g. %1p{box|boxes})
// %<n>q{<z>|<s>|<p>} use <z> zero form, <s> singular form or <p> plural form, determined by integer argment <n>
// (e.g. %1z%1q{nothing| box| boxes})
// %<n>?{<t>|<f>} integer argument <n> is non-zero use <t>; zero then <f>
// %<n>j{<c1>|<c2>|<c3>...<ci>}
// depend on integer argument <n>, use <c1> on 1, use <c2> on 2
// otherwise use the last argument, <ci>.
// %<n>r roman number, blank if zero
// useage
// 1. font_news.put( ZOOM_X1+10, dy, test_text_res.process( test_text_res.get_format_str(1, "CHM1"), "a", "bb", "ccc") );
// find format str in line 1, and check [CHM1] mark at the beginning of the that line
// the line appear in resource file may look like:
//
// [CHM1]Test 1 : s1(%1s), s2(%2s), s3(%3s) %%
//
// 2. more preferred method is to use a subclass
//
//class GameMenuText : public TextResource
//{
//public:
// void init() { TextResource::init( <hard-coded file name> ); }
//
// // ---------- string -----------//
//
// // non formatted text
// char *quit_text() { return get_format_str( 1, "QUIT" ); }
// char *single_player_text() { return get_format_str( 2, "SING" ); }
//
// // argument string, check mark recognize first 4 chars only
// char *kingdom_name(char *playerName) { return process( get_format_str( 3, "KNAME"), playerName); }
//};
// -------- define constant ----------//
#define MAX_ARG 9
#define CHECK_MARK_BEGIN '['
#define CHECK_MARK_END ']'
enum
{
ARG_TYPE_INT = 1,
ARG_TYPE_STR,
ARG_TYPE_DOUBLE,
};
// --------- define static member ----------//
char TextResource::str_buf[FREE_STR_COUNT][TEXT_RES_STRLEN+1];
int TextResource::free_str_buf = 0;
char TextResource::short_str_buf[FREE_SHORT_STR_COUNT][TEXT_RES_SHORT_STRLEN+1];
int TextResource::free_short_str_buf = 0;
// ------- begin of function TextResource::TextResource -------//
//
TextResource::TextResource()
{
main_text = NULL;
text_count = 0;
text_offset_array = NULL;
res_name[0] = '\0';
}
// ------- end of function TextResource::TextResource -------//
// ------- begin of function TextResource::~TextResource -------//
//
TextResource::~TextResource()
{
deinit();
}
// ------- end of function TextResource::~TextResource -------//
// ------- begin of function TextResource::init -------//
//
void TextResource::init( const char *fileName)
{
deinit(); // free memory
strcpy( res_name, fileName );
load_res(fileName);
}
// ------- end of function TextResource::init -------//
// ------- begin of function TextResource::deinit -------//
//
void TextResource::deinit()
{
if( main_text )
{
mem_del(main_text);
main_text = NULL;
}
if( text_offset_array )
{
mem_del(text_offset_array);
text_offset_array = NULL;
}
text_count = 0;
res_name[0] = '\0';
}
// ------- end of function TextResource::deinit -------//
// ------- begin of function TextResource::load_res -------//
//
void TextResource::load_res(const char *fileName)
{
// open and the whole file
File file;
file.file_open(fileName);
int fileSize = file.file_size();
FileTxt f(&file, fileSize);
main_text = mem_add( fileSize );
// build index and replace '\r' or '\n' to '\0'
text_count = 0;
int guessTextCount = fileSize / 64 + 1; // initial guess, 64 is assumed char per line
text_offset_array = (int *)mem_add( sizeof(int) * guessTextCount );
int offset = 0;
while( !f.is_eof() )
{
f.read_line( main_text+offset, fileSize-offset );
// if a line has check mark, move offset behind ']'
if( main_text[offset] == CHECK_MARK_BEGIN
&& strchr(main_text+offset, CHECK_MARK_END) )
{
offset = strchr(main_text+offset, CHECK_MARK_END) - main_text + 1;
// +1 to skip that CHECK_MARK_END char
}
// build index, allocate space first
if( text_count >= guessTextCount )
{
guessTextCount = text_count + 16;
text_offset_array = (int *)mem_resize( text_offset_array, sizeof(int) * guessTextCount );
}
text_offset_array[text_count] = offset;
offset += strlen(main_text+offset) + 1; // skip the null char
++text_count;
}
}
// ------- end of function TextResource::load_res -------//
// ------- begin of function TextResource::get_format_str --------//
char *TextResource::get_format_str(int textId, const char *checkMark )
{
err_when( !textId && !checkMark ); // cannot be both null
err_when( sizeof(uint32_t) != CHECK_MARK_STRLEN ); // else use strncmp instead
if( textId > 0 && textId <= text_count )
{
char *formatText = main_text + text_offset_array[textId-1];
if( !checkMark // skip mark checking
|| (formatText > main_text
&& formatText[-1] == CHECK_MARK_END
// && strncmp(formatText-1-CHECK_MARK_STRLEN, checkMark, CHECK_MARK_STRLEN) == 0) )
&& *(uint32_t *)(formatText-1-CHECK_MARK_STRLEN) == *(uint32_t *)checkMark) )
{
return formatText;
}
}
err.run("Cannot find string %s in %s", checkMark, res_name );
return NULL;
}
// ------- end of function TextResource::get_format_str --------//
// ------ begin of function TextResource::get_free_str -------//
//
// use str_buf in cycle
// so small recursed call in process() is possible
//
char *TextResource::get_free_str(char* srcStr)
{
err_when( free_str_buf < 0 );
char *rc = str_buf[free_str_buf];
if( ++free_str_buf >= FREE_STR_COUNT )
free_str_buf = 0;
if( srcStr ) // copy src string
{
strncpy( rc, srcStr, FREE_STR_COUNT );
rc[FREE_STR_COUNT] = '\0';
}
return rc;
}
// ------ end of function TextResource::get_free_str -------//
// ------ begin of function TextResource::get_free_short_str -------//
//
// use short_str_buf in cycle
// so simultaneous call in format(), roman() is possible
//
char *TextResource::get_free_short_str(char *srcStr)
{
err_when( free_short_str_buf < 0 );
char *rc = short_str_buf[free_short_str_buf];
if( ++free_short_str_buf >= FREE_SHORT_STR_COUNT )
free_short_str_buf = 0;
if( srcStr ) // copy src string
{
strncpy( rc, srcStr, FREE_SHORT_STR_COUNT );
rc[FREE_SHORT_STR_COUNT] = '\0';
}
return rc;
}
// ------ end of function TextResource::get_free_short_str -------//
//---------- Begin of function TextResource::format --------//
//
// similar to Misc::format, but store in a private storage
//
char* TextResource::format(double inNum, int formatType)
{
char *outBuf = get_free_short_str();
char *outPtr=outBuf;
char floatBuf[35];
char *floatStr;
int i, intDigit; // intDigit = no. of integer digits
intDigit = snprintf( floatBuf, sizeof(floatBuf), "%.0lf", fabs(inNum) * 100.0 );
intDigit -= 2;
floatStr = floatBuf;
#ifdef DEBUG
if( intDigit > 29 ) // integer digits can't exceed 29
err.run( "TextResource::format(), inNum : %e, formatType : %d", inNum, formatType );
#endif
//--------- negetive bracket ------------//
if( inNum < 0 )
*outPtr++ = '(';
//--------- dollar sign ($) ------------//
if( formatType == 2 )
*outPtr++ = '$';
//------- integer number -----------//
for( i=intDigit ; i>0 ; i-- )
{
if( i%THOUSAND_SEPARATOR_COUNT == 0 && i < intDigit )
*outPtr++ = THOUSAND_SEPARATOR;
*outPtr++ = *floatStr++;
}
if( intDigit <= 0 )
*outPtr++ = '0';
//------- dec. place number -----------//
if( inNum > -1000 && inNum < 1000 ) // if the number is less than 1000, add dec. places
{ // if the number is greater than 1000, truncate any dec. places
*outPtr++ = DECIMAL_SEPARATOR;
if( *floatStr && intDigit >= 0 ) // e.g. 0.03 --> str:"3", intDight:-1
*outPtr++ = *floatStr++; // 1st dec. place
else
*outPtr++ = '0'; // add a '0' when intDigit < 0
if( *floatStr ) // 2nd dec. place
*outPtr++ = *floatStr++;
else
*outPtr++ = '0';
}
//--------- percent sign (%) ------------//
if( formatType == 3 )
*outPtr++ = '%';
//--------- negetive bracket ------------//
if( inNum < 0 )
*outPtr++ = ')';
*outPtr++ = '\0';
return outBuf;
}
//---------- End of function TextResource::format --------//
//---------- Begin of function TextResource::format --------//
//
// similar Misc::format, but store in a private storage
//
char* TextResource::format(int inNum, int formatType)
{
char *outBuf = get_free_short_str();
char longBuf[25];
char *outPtr=outBuf;
char *longStr;
int i, intDigit, sign;
if( inNum < 0 )
{
sign = -1;
inNum = -inNum;
}
else
sign = 0;
longStr = ltoa( inNum, longBuf, 10 );
intDigit = strlen(longStr); // no. of integer digits
//--------- negetive bracket ------------//
if( sign < 0 )
*outPtr++ = '(';
//--------- dollar sign ------------//
if( formatType == 2 )
*outPtr++ = '$';
//-------- integer number -----------//
for( i=intDigit ; i>0 ; i-- )
{
if( formatType != 4 ) // no thousand separators for format 4
{
if( i%THOUSAND_SEPARATOR_COUNT == 0 && i < intDigit )
*outPtr++ = THOUSAND_SEPARATOR;
}
*outPtr++ = *longStr++;
}
//--------- percent sign (%) ------------//
if( formatType == 3 )
*outPtr++ = '%';
//--------- negetive bracket ----------//
if( sign < 0 )
*outPtr++ = ')';
*outPtr++ = '\0';
return outBuf;
}
//---------- End of function TextResource::format --------//
//---------- Begin of function TextResource::roman_number --------//
//
char* TextResource::roman_number(int inNum)
{
char *outBuf = get_free_short_str();
char *outPtr = outBuf;
if( inNum >= 4000 )
err.run( "TextRes::roman_number %d", inNum );
if( inNum <= 0 )
{
// return empty string
outPtr[0] = '\0';
return outBuf;
}
char deciStr[12];
itoa( inNum, deciStr, 10 );
int deciLen = strlen( deciStr );
for( int i = 0; i < deciLen; ++i )
{
static const char *unitDigitArray[10] = { "", "I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX" };
static const char *tenDigitArray[10] = { "", "X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC" };
static const char *hundredDigitArray[10] = { "", "C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM" };
static const char *thousandDigitArray[] = { "", "M", "MM", "MMM" }; // 5000?
const char *srcStr = ""; // empty string
switch( deciLen-i )
{
case 1: // unit digit
srcStr = unitDigitArray[deciStr[i]-'0'];
break;
case 2: // ten digit
srcStr = tenDigitArray[deciStr[i]-'0'];
break;
case 3: // hundred digit
srcStr = hundredDigitArray[deciStr[i]-'0'];
break;
case 4: // thousand digit
srcStr = thousandDigitArray[deciStr[i]-'0'];
break;
}
// strcpy
for( ; *srcStr; ++srcStr )
{
*outPtr = *srcStr;
++outPtr;
}
}
*outPtr = '\0'; // null terminate the string
return outBuf;
}
//---------- End of function TextResource::roman_number --------//
// %% a single percent
// %<n>s string, <n> is from 1 to 9, the number in the argument list (eg. %1s)
// %<n>[,f]d interger <f> is format type passed to Misc::format (eg. %2d)
// %<n>[,f]f float <f> is format type passed to Misc::format (eg. %3,1f)
// %<n>p{<s>|<p>} use <s> singular form or <p> plural form, determined by integer argment <n>
// (e.g. %1p{box|boxes})
// %<n>?{<t>|<f>} integer argument <n> is non-zero use <t>; zero then <f>
// %<n>j{<c1>|<c2>|<c3>...<ci>}
// depend on integer argument <n>, use <c1> on 1, use <c2> on 2
// otherwise use the last argument, <ci>.
// %<n>r roman number, blank if zero
//
// VERY IMPORTANT NOTE:
// TextResource::process is not re-entrance
// because str_buf is common, store the intermediate result first
// if a parameter is String type to be casted to char *,
// cast to (char *) explicitly, variable argument cannot handle class object well.
char *TextResource::process( char *formatStr, ... )
{
char *buf;
va_list vl;
va_start( vl, formatStr );
buf = vprocess(formatStr, vl);
va_end(vl);
return buf;
}
char *TextResource::vprocess( char *formatStr, va_list vl )
{
int argCount, nonArgCount;
register char *readPtr, *writePtr;
char argType[MAX_ARG];
memset( argType, 0, sizeof(argType) );
int intArgs[MAX_ARG];
char *strArgs[MAX_ARG];
double floatArgs[MAX_ARG];
// scan the string to identify the type of each argment
argCount = nonArgCount = 0;
for( readPtr = formatStr; *readPtr != '\0'; ++readPtr )
{
if( *readPtr == '%' )
{
char *oldReadPtr = readPtr;
++readPtr;
if( *readPtr == '\0' ) // end of string
break;
else if( *readPtr == '%' ) // single percent
{
nonArgCount++;
}
else if( *readPtr >= '0' && *readPtr <= '9' )
{
// skip numeric
int argId = 0;
for( ; *readPtr >= '0' && *readPtr <= '9'; ++readPtr )
{
argId = argId * 10 + (*readPtr - '0');
}
if( *readPtr == '\0' )
break;
// skip another numeric
int formatId = 0;
if( *readPtr == ',' )
{
++readPtr;
if( *readPtr == '\0')
break;
// skip numeric
for( ; *readPtr >= '0' && *readPtr <= '9'; ++readPtr )
{
formatId = formatId * 10 + (*readPtr - '0');
}
if( *readPtr == '\0' )
break;
}
switch( *readPtr )
{
case 's':
if( argId > 0 && argId <= MAX_ARG )
argType[argId-1] = ARG_TYPE_STR;
break;
case 'f':
if( argId > 0 && argId <= MAX_ARG )
argType[argId-1] = ARG_TYPE_DOUBLE;
break;
case 'd':
case 'r':
case 'z':
if( argId > 0 && argId <= MAX_ARG )
argType[argId-1] = ARG_TYPE_INT;
break;
case 'p':
case 'q':
case '?':
case 'j':
if( argId > 0 && argId <= MAX_ARG )
argType[argId-1] = ARG_TYPE_INT;
// search '}'
char *endBrace = strchr( readPtr+1, '}' );
if( endBrace )
readPtr = endBrace; // keep pointer at the end of format clause
break;
}
if( argId > argCount )
argCount = argId;
}
} // end if *readPtr == '%'
}
if( !argCount && !nonArgCount )
{
return formatStr; // no argument
}
// save the argument
for( int argId = 1; argId <= argCount && argId <= MAX_ARG; ++argId )
{
switch( argType[argId-1] )
{
case ARG_TYPE_INT:
intArgs[argId-1] = va_arg( vl, int );
break;
case ARG_TYPE_STR:
strArgs[argId-1] = va_arg( vl, char *);
break;
case ARG_TYPE_DOUBLE:
floatArgs[argId-1] = va_arg( vl, double );
break;
default:
(void) va_arg( vl, int );
}
}
// format string now
char* oldWritePtr = writePtr = get_free_str();
for( readPtr = formatStr; *readPtr != '\0'; ++readPtr )
{
if( *readPtr == '%' )
{
char *oldReadPtr = readPtr;
++readPtr;
if( *readPtr == '\0' ) // end of string
break;
else if( *readPtr == '%' ) // single percent
{
*writePtr = '%';
++writePtr;
}
else if( *readPtr >= '0' && *readPtr <= '9' )
{
// skip numeric
int argId = 0;
for( ; *readPtr >= '0' && *readPtr <= '9'; ++readPtr )
{
argId = argId * 10 + (*readPtr - '0');
}
if( *readPtr == '\0' )
break;
// skip another numeric
int formatId = 0;
if( *readPtr == ',' )
{
++readPtr;
if( *readPtr == '\0')
break;
// skip numeric
for( ; *readPtr >= '0' && *readPtr <= '9'; ++readPtr )
{
formatId = formatId * 10 + (*readPtr - '0');
}
if( *readPtr == '\0' )
break;
}
switch( *readPtr )
{
case 's': // string
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_STR );
char *strPtr = strArgs[argId-1];
// strcpy, but we need end of string
for( ; *strPtr != '\0'; ++strPtr )
{
*writePtr = *strPtr;
++writePtr;
}
}
break;
case 'f': // float %<n>[,f]f
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_DOUBLE );
char *strPtr = format(floatArgs[argId-1], formatId?formatId:1 ); // default format is 1
// strcpy, but we need end of string
for( ; *strPtr != '\0'; ++strPtr )
{
*writePtr = *strPtr;
++writePtr;
}
}
break;
case 'd': // integer %<n>[,f]d
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr = format(intArgs[argId-1], formatId?formatId:1 ); // default format is 1
// strcpy, but we need end of string
for( ; *strPtr != '\0'; ++strPtr )
{
*writePtr = *strPtr;
++writePtr;
}
}
break;
case 'r': // integer %<n>r
if( argId > 0 && argId < MAX_ARG && intArgs[argId-1] )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr = roman_number(intArgs[argId-1]);
// strcpy, but we need end of string
for( ; *strPtr != '\0'; ++strPtr )
{
*writePtr = *strPtr;
++writePtr;
}
}
break;
case 'z': // integer %<n>[,f]z, suppress when zero
if( argId > 0 && argId <= MAX_ARG && intArgs[argId-1] )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr = format(intArgs[argId-1], formatId?formatId:1 ); // default format is 1
// strcpy, but we need end of string
for( ; *strPtr != '\0'; ++strPtr )
{
*writePtr = *strPtr;
++writePtr;
}
}
break;
case 'p': // plural form %<n>p{<s>|<p>}
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr;
if( intArgs[argId-1] == 0 || intArgs[argId-1] == 1 )
{
// singular form
if( readPtr[1] == '{' )
{
readPtr += 2; // skip "p{"
for( ; *readPtr != '\0' && *readPtr != '|'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
}
else
{
// plural form
if( readPtr[1] == '{'
&& (strPtr = strchr( readPtr+2, '|' )) )
{
readPtr = strPtr+1; // skip '|'
for( ; *readPtr != '\0' && *readPtr != '}'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
}
}
}
else
{
// skip to end of clause
char *strPtr;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
break;
case 'q': // plural form %<n>q{<z>|<s>|<p>}
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr;
if( intArgs[argId-1] == 0 )
{
// zero form
if( readPtr[1] == '{' )
{
readPtr += 2; // skip "q{"
for( ; *readPtr != '\0' && *readPtr != '|'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
}
else if( intArgs[argId-1] == 1 )
{
// singular form
if( readPtr[1] == '{'
&& (strPtr = strchr( readPtr+2, '|' )) )
{
readPtr = strPtr+1; // skip '|'
for( ; *readPtr != '\0' && *readPtr != '|'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
}
else
{
// plural form
if( readPtr[1] == '{'
&& (strPtr = strchr( readPtr+2, '|' ))
&& (strPtr = strchr( strPtr+1, '|')) ) // find second |
{
readPtr = strPtr+1; // skip '|'
for( ; *readPtr != '\0' && *readPtr != '}'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
}
}
}
else
{
// skip to end of clause
char *strPtr;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
break;
case '?': // logical form %<n>?{<t>|<f>}
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr;
if( intArgs[argId-1] )
{
// true
if( readPtr[1] == '{' )
{
readPtr += 2; // skip "?{"
for( ; *readPtr != '\0' && *readPtr != '|'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
}
else
{
// false
if( readPtr[1] == '{'
&& (strPtr = strchr( readPtr+2, '|' )) )
{
readPtr = strPtr+1; // skip '|'
for( ; *readPtr != '\0' && *readPtr != '}'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
}
}
}
else
{
// skip to end of clause
char *strPtr;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
break;
case 'j': // %<n>j{<c1>|<c2>|<c3>...<ci>}
if( argId > 0 && argId <= MAX_ARG )
{
err_when( argType[argId-1] != ARG_TYPE_INT);
char *strPtr = NULL;
// if( intArgs[argId-1] )
if( readPtr[1] == '{' )
{
int a=1;
strPtr = readPtr+2; // skip "j{";
readPtr++; // skip "j";
while( *readPtr != '}' && a != intArgs[argId-1] )
{
++readPtr; // skip '{' or '|'
// skip to next argument
for( ; *readPtr != '\0' && *readPtr != '|' && *readPtr != '}'; ++readPtr );
if( *readPtr == '\0' || *readPtr == '}' )
break; // if } break so strPtr is not updated
strPtr = readPtr+1; // skip '\0','|'
++a;
}
// if a never match intArgs[argId-1], use last phase before }
// copy string
readPtr = strPtr;
for( ; *readPtr != '\0' && *readPtr != '|' && *readPtr != '}'; ++readPtr )
{
*writePtr = *readPtr;
++writePtr;
}
if( *readPtr == '\0' )
break;
// skip to end of clause
if( (strPtr = strchr(readPtr, '}')) )
{
readPtr = strPtr;
}
}
}
else
{
// skip to end of clause
char *strPtr;
if( (strPtr = strchr(readPtr, '}')) )
readPtr = strPtr; // go to '}'
}
break;
} // end case
err_when( argId > argCount ); // but argCount may > MAX_ARG
}
else
{
// unrecognized command, also write a %
*writePtr = '%';
++writePtr;
}
} // end if *readPtr == '%'
else
{
*writePtr = *readPtr;
++writePtr;
}
}
*writePtr = '\0'; // null terminate
err_when( writePtr - oldWritePtr > TEXT_RES_STRLEN );
return oldWritePtr;
}
|
7k2/test-repo
|
src/otxtres.cpp
|
C++
|
gpl-2.0
| 24,944 |
/*
* smdk6400_wm9713.c -- SoC audio for smdk6400
*
* Copyright (C) 2007, Ryu Euiyoul <[email protected]>
*
* Copyright 2007 Wolfson Microelectronics PLC.
* Author: Graeme Gregory
* [email protected] or [email protected]
*
* This program is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version.
*
* Revision history
* 8th Mar 2007 Initial version.
* 20th Sep 2007 Apply at smdk6400
*
*/
#include <linux/module.h>
#include <linux/device.h>
#include <sound/driver.h>
#include <sound/core.h>
#include <sound/pcm.h>
#include <sound/soc.h>
#include <sound/soc-dapm.h>
#include "../codecs/wm9713.h"
#include "../s3c24xx/s3c-pcm.h"
#include "s3c64xx-ac97.h"
static struct snd_soc_machine smdk6400;
static struct snd_soc_dai_link smdk6400_dai[] = {
{
.name = "AC97",
.stream_name = "AC97 HiFi",
.cpu_dai = &s3c6400_ac97_dai[0],
.codec_dai = &wm9713_dai[WM9713_DAI_AC97_HIFI],
},
};
static struct snd_soc_machine smdk6400 = {
.name = "SMDK6400",
.dai_link = smdk6400_dai,
.num_links = ARRAY_SIZE(smdk6400_dai),
};
static struct snd_soc_device smdk6400_snd_ac97_devdata = {
.machine = &smdk6400,
.platform = &s3c24xx_soc_platform,
.codec_dev = &soc_codec_dev_wm9713,
};
static struct platform_device *smdk6400_snd_ac97_device;
static int __init smdk6400_init(void)
{
int ret;
smdk6400_snd_ac97_device = platform_device_alloc("soc-audio", -1);
if (!smdk6400_snd_ac97_device)
return -ENOMEM;
platform_set_drvdata(smdk6400_snd_ac97_device,
&smdk6400_snd_ac97_devdata);
smdk6400_snd_ac97_devdata.dev = &smdk6400_snd_ac97_device->dev;
ret = platform_device_add(smdk6400_snd_ac97_device);
if (ret)
platform_device_put(smdk6400_snd_ac97_device);
return ret;
}
static void __exit smdk6400_exit(void)
{
platform_device_unregister(smdk6400_snd_ac97_device);
}
module_init(smdk6400_init);
module_exit(smdk6400_exit);
/* Module information */
MODULE_AUTHOR("Samsung: Ryu");
MODULE_DESCRIPTION("ALSA SoC WM9713 SMDK6400");
MODULE_LICENSE("GPL");
|
simonclouds/samsung-s3c6410-android.1.0
|
sound/soc/s3c64xx/smdk64xx_wm9713.c
|
C
|
gpl-2.0
| 2,210 |
<?php
/**
* @file
* Contains Drupal\datetime\Type\DateTimeItem.
*/
namespace Drupal\datetime\Type;
use Drupal\Core\Entity\Field\FieldItemBase;
/**
* Defines the 'datetime' entity field item.
*/
class DateTimeItem extends FieldItemBase {
/**
* Field definitions of the contained properties.
*
* @see self::getPropertyDefinitions()
*
* @var array
*/
static $propertyDefinitions;
/**
* Implements ComplexDataInterface::getPropertyDefinitions().
*/
public function getPropertyDefinitions() {
if (!isset(self::$propertyDefinitions)) {
self::$propertyDefinitions['value'] = array(
'type' => 'date',
'label' => t('Date value'),
);
}
return self::$propertyDefinitions;
}
}
|
eugenesia/eugenesia.co.uk
|
core/modules/datetime/lib/Drupal/datetime/Type/DateTimeItem.php
|
PHP
|
gpl-2.0
| 751 |
/*
* Copyright © 2004 Eric Anholt
*
* 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 Eric Anholt not be used in
* advertising or publicity pertaining to distribution of the software without
* specific, written prior permission. Eric Anholt makes no
* representations about the suitability of this software for any purpose. It
* is provided "as is" without express or implied warranty.
*
* ERIC ANHOLT DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
* INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
* EVENT SHALL ERIC ANHOLT 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.
*/
/* $Header: /cvs/xorg/xc/programs/Xserver/miext/cw/cw.h,v 1.14 2005/12/09 18:32:46 ajax Exp $ */
#ifdef HAVE_DIX_CONFIG_H
#include <dix-config.h>
#endif
#include "gcstruct.h"
#include "picturestr.h"
/*
* One of these structures is allocated per GC that gets used with a window with
* backing pixmap.
*/
typedef struct {
GCPtr pBackingGC; /* Copy of the GC but with graphicsExposures
* set FALSE and the clientClip set to
* clip output to the valid regions of the
* backing pixmap. */
unsigned long serialNumber; /* clientClip computed time */
unsigned long stateChanges; /* changes in parent gc since last copy */
GCOps *wrapOps; /* wrapped ops */
GCFuncs *wrapFuncs; /* wrapped funcs */
} cwGCRec, *cwGCPtr;
extern int cwGCIndex;
#define getCwGC(pGC) ((cwGCPtr)(pGC)->devPrivates[cwGCIndex].ptr)
#define setCwGC(pGC,p) ((pGC)->devPrivates[cwGCIndex].ptr = (pointer) (p))
/*
* One of these structures is allocated per Picture that gets used with a
* window with a backing pixmap
*/
typedef struct {
PicturePtr pBackingPicture;
unsigned long serialNumber;
unsigned long stateChanges;
} cwPictureRec, *cwPicturePtr;
#define getCwPicture(pPicture) ((cwPicturePtr)(pPicture)->devPrivates[cwPictureIndex].ptr)
#define setCwPicture(pPicture,p) ((pPicture)->devPrivates[cwPictureIndex].ptr = (pointer) (p))
extern int cwPictureIndex;
extern int cwWindowIndex;
#define cwWindowPrivate(pWindow) ((pWindow)->devPrivates[cwWindowIndex].ptr)
#define getCwPixmap(pWindow) ((PixmapPtr) cwWindowPrivate(pWindow))
#define setCwPixmap(pWindow,pPixmap) (cwWindowPrivate(pWindow) = (pointer) (pPixmap))
#define cwDrawableIsRedirWindow(pDraw) \
((pDraw)->type == DRAWABLE_WINDOW && \
getCwPixmap((WindowPtr) (pDraw)) != NULL)
typedef struct {
/*
* screen func wrappers
*/
CloseScreenProcPtr CloseScreen;
GetImageProcPtr GetImage;
GetSpansProcPtr GetSpans;
CreateGCProcPtr CreateGC;
PaintWindowBackgroundProcPtr PaintWindowBackground;
PaintWindowBorderProcPtr PaintWindowBorder;
CopyWindowProcPtr CopyWindow;
GetWindowPixmapProcPtr GetWindowPixmap;
SetWindowPixmapProcPtr SetWindowPixmap;
#ifdef RENDER
DestroyPictureProcPtr DestroyPicture;
ChangePictureClipProcPtr ChangePictureClip;
DestroyPictureClipProcPtr DestroyPictureClip;
ChangePictureProcPtr ChangePicture;
ValidatePictureProcPtr ValidatePicture;
CompositeProcPtr Composite;
GlyphsProcPtr Glyphs;
CompositeRectsProcPtr CompositeRects;
TrapezoidsProcPtr Trapezoids;
TrianglesProcPtr Triangles;
TriStripProcPtr TriStrip;
TriFanProcPtr TriFan;
RasterizeTrapezoidProcPtr RasterizeTrapezoid;
#endif
} cwScreenRec, *cwScreenPtr;
extern int cwScreenIndex;
#define getCwScreen(pScreen) ((cwScreenPtr)(pScreen)->devPrivates[cwScreenIndex].ptr)
#define setCwScreen(pScreen,p) ((cwScreenPtr)(pScreen)->devPrivates[cwScreenIndex].ptr = (p))
#define CW_OFFSET_XYPOINTS(ppt, npt) do { \
DDXPointPtr _ppt = (DDXPointPtr)(ppt); \
int _i; \
for (_i = 0; _i < npt; _i++) { \
_ppt[_i].x += dst_off_x; \
_ppt[_i].y += dst_off_y; \
} \
} while (0)
#define CW_OFFSET_RECTS(prect, nrect) do { \
int _i; \
for (_i = 0; _i < nrect; _i++) { \
(prect)[_i].x += dst_off_x; \
(prect)[_i].y += dst_off_y; \
} \
} while (0)
#define CW_OFFSET_ARCS(parc, narc) do { \
int _i; \
for (_i = 0; _i < narc; _i++) { \
(parc)[_i].x += dst_off_x; \
(parc)[_i].y += dst_off_y; \
} \
} while (0)
#define CW_OFFSET_XY_DST(x, y) do { \
(x) = (x) + dst_off_x; \
(y) = (y) + dst_off_y; \
} while (0)
#define CW_OFFSET_XY_SRC(x, y) do { \
(x) = (x) + src_off_x; \
(y) = (y) + src_off_y; \
} while (0)
/* cw.c */
DrawablePtr
cwGetBackingDrawable(DrawablePtr pDrawable, int *x_off, int *y_off);
/* cw_render.c */
void
cwInitializeRender (ScreenPtr pScreen);
void
cwFiniRender (ScreenPtr pScreen);
/* cw.c */
void
miInitializeCompositeWrapper(ScreenPtr pScreen);
/* Must be called before miInitializeCompositeWrapper */
void
miDisableCompositeWrapper(ScreenPtr pScreen);
|
theqvd/qvd-nx-libs-3.5.0-32
|
nx-X11/programs/Xserver/miext/cw/cw.h
|
C
|
gpl-2.0
| 5,350 |
<?php
/*
Plugin Name: WordPress Importer
Plugin URI: http://wordpress.org/extend/plugins/wordpress-importer/
Description: Import posts, pages, comments, custom fields, categories, tags and more from a WordPress export file.
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 0.6.1
Text Domain: wordpress-importer
License: GPL version 2 or later - http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/
if ( ! defined( 'WP_LOAD_IMPORTERS' ) )
return;
/** Display verbose errors */
define( 'IMPORT_DEBUG', false );
// Load Importer API
require_once ABSPATH . 'wp-admin/includes/import.php';
if ( ! class_exists( 'WP_Importer' ) ) {
$class_wp_importer = ABSPATH . 'wp-admin/includes/class-wp-importer.php';
if ( file_exists( $class_wp_importer ) )
require $class_wp_importer;
}
// include WXR file parsers
require dirname( __FILE__ ) . '/parsers.php';
/**
* WordPress Importer class for managing the import process of a WXR file
*
* @package WordPress
* @subpackage Importer
*/
if ( class_exists( 'WP_Importer' ) ) {
class WP_Import extends WP_Importer {
var $max_wxr_version = 1.2; // max. supported WXR version
var $id; // WXR attachment ID
// information to import from WXR file
var $version;
var $authors = array();
var $posts = array();
var $terms = array();
var $categories = array();
var $tags = array();
var $base_url = '';
// mappings from old information to new
var $processed_authors = array();
var $author_mapping = array();
var $processed_terms = array();
var $processed_posts = array();
var $post_orphans = array();
var $processed_menu_items = array();
var $menu_item_orphans = array();
var $missing_menu_items = array();
var $fetch_attachments = false;
var $url_remap = array();
var $featured_images = array();
function WP_Import() { /* nothing */ }
/**
* Registered callback function for the WordPress Importer
*
* Manages the three separate stages of the WXR import process
*/
function dispatch() {
$this->header();
$step = empty( $_GET['step'] ) ? 0 : (int) $_GET['step'];
switch ( $step ) {
case 0:
$this->greet();
break;
case 1:
check_admin_referer( 'import-upload' );
if ( $this->handle_upload() )
$this->import_options();
break;
case 2:
check_admin_referer( 'import-wordpress' );
$this->fetch_attachments = ( ! empty( $_POST['fetch_attachments'] ) && $this->allow_fetch_attachments() );
$this->id = (int) $_POST['import_id'];
$file = get_attached_file( $this->id );
set_time_limit(0);
$this->import( $file );
break;
}
$this->footer();
}
/**
* The main controller for the actual import stage.
*
* @param string $file Path to the WXR file for importing
*/
function import( $file ) {
add_filter( 'import_post_meta_key', array( $this, 'is_valid_meta_key' ) );
add_filter( 'http_request_timeout', array( &$this, 'bump_request_timeout' ) );
$this->import_start( $file );
$this->get_author_mapping();
wp_suspend_cache_invalidation( true );
$this->process_categories();
$this->process_tags();
$this->process_terms();
$this->process_posts();
wp_suspend_cache_invalidation( false );
// update incorrect/missing information in the DB
$this->backfill_parents();
$this->backfill_attachment_urls();
$this->remap_featured_images();
$this->import_end();
}
/**
* Parses the WXR file and prepares us for the task of processing parsed data
*
* @param string $file Path to the WXR file for importing
*/
function import_start( $file ) {
if ( ! is_file($file) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
echo __( 'The file does not exist, please try again.', 'wordpress-importer' ) . '</p>';
$this->footer();
die();
}
$import_data = $this->parse( $file );
if ( is_wp_error( $import_data ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
echo esc_html( $import_data->get_error_message() ) . '</p>';
$this->footer();
die();
}
$this->version = $import_data['version'];
$this->get_authors_from_import( $import_data );
$this->posts = $import_data['posts'];
$this->terms = $import_data['terms'];
$this->categories = $import_data['categories'];
$this->tags = $import_data['tags'];
$this->base_url = esc_url( $import_data['base_url'] );
wp_defer_term_counting( true );
wp_defer_comment_counting( true );
do_action( 'import_start' );
}
/**
* Performs post-import cleanup of files and the cache
*/
function import_end() {
wp_import_cleanup( $this->id );
wp_cache_flush();
foreach ( get_taxonomies() as $tax ) {
delete_option( "{$tax}_children" );
_get_term_hierarchy( $tax );
}
wp_defer_term_counting( false );
wp_defer_comment_counting( false );
echo '<p>' . __( 'All done.', 'wordpress-importer' ) . ' <a href="' . admin_url() . '">' . __( 'Have fun!', 'wordpress-importer' ) . '</a>' . '</p>';
echo '<p>' . __( 'Remember to update the passwords and roles of imported users.', 'wordpress-importer' ) . '</p>';
do_action( 'import_end' );
}
/**
* Handles the WXR upload and initial parsing of the file to prepare for
* displaying author import options
*
* @return bool False if error uploading or invalid file, true otherwise
*/
function handle_upload() {
$file = wp_import_handle_upload();
if ( isset( $file['error'] ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
echo esc_html( $file['error'] ) . '</p>';
return false;
} else if ( ! file_exists( $file['file'] ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
printf( __( 'The export file could not be found at <code>%s</code>. It is likely that this was caused by a permissions problem.', 'wordpress-importer' ), esc_html( $file['file'] ) );
echo '</p>';
return false;
}
$this->id = (int) $file['id'];
$import_data = $this->parse( $file['file'] );
if ( is_wp_error( $import_data ) ) {
echo '<p><strong>' . __( 'Sorry, there has been an error.', 'wordpress-importer' ) . '</strong><br />';
echo esc_html( $import_data->get_error_message() ) . '</p>';
return false;
}
$this->version = $import_data['version'];
if ( $this->version > $this->max_wxr_version ) {
echo '<div class="error"><p><strong>';
printf( __( 'This WXR file (version %s) may not be supported by this version of the importer. Please consider updating.', 'wordpress-importer' ), esc_html($import_data['version']) );
echo '</strong></p></div>';
}
$this->get_authors_from_import( $import_data );
return true;
}
/**
* Retrieve authors from parsed WXR data
*
* Uses the provided author information from WXR 1.1 files
* or extracts info from each post for WXR 1.0 files
*
* @param array $import_data Data returned by a WXR parser
*/
function get_authors_from_import( $import_data ) {
if ( ! empty( $import_data['authors'] ) ) {
$this->authors = $import_data['authors'];
// no author information, grab it from the posts
} else {
foreach ( $import_data['posts'] as $post ) {
$login = sanitize_user( $post['post_author'], true );
if ( empty( $login ) ) {
printf( __( 'Failed to import author %s. Their posts will be attributed to the current user.', 'wordpress-importer' ), esc_html( $post['post_author'] ) );
echo '<br />';
continue;
}
if ( ! isset($this->authors[$login]) )
$this->authors[$login] = array(
'author_login' => $login,
'author_display_name' => $post['post_author']
);
}
}
}
/**
* Display pre-import options, author importing/mapping and option to
* fetch attachments
*/
function import_options() {
$j = 0;
?>
<form action="<?php echo admin_url( 'admin.php?import=wordpress&step=2' ); ?>" method="post">
<?php wp_nonce_field( 'import-wordpress' ); ?>
<input type="hidden" name="import_id" value="<?php echo $this->id; ?>" />
<?php if ( ! empty( $this->authors ) ) : ?>
<h3><?php _e( 'Assign Authors', 'wordpress-importer' ); ?></h3>
<p><?php _e( 'To make it easier for you to edit and save the imported content, you may want to reassign the author of the imported item to an existing user of this site. For example, you may want to import all the entries as <code>admin</code>s entries.', 'wordpress-importer' ); ?></p>
<?php if ( $this->allow_create_users() ) : ?>
<p><?php printf( __( 'If a new user is created by WordPress, a new password will be randomly generated and the new user’s role will be set as %s. Manually changing the new user’s details will be necessary.', 'wordpress-importer' ), esc_html( get_option('default_role') ) ); ?></p>
<?php endif; ?>
<ol id="authors">
<?php foreach ( $this->authors as $author ) : ?>
<li><?php $this->author_select( $j++, $author ); ?></li>
<?php endforeach; ?>
</ol>
<?php endif; ?>
<?php if ( $this->allow_fetch_attachments() ) : ?>
<h3><?php _e( 'Import Attachments', 'wordpress-importer' ); ?></h3>
<p>
<input type="checkbox" value="1" name="fetch_attachments" id="import-attachments" />
<label for="import-attachments"><?php _e( 'Download and import file attachments', 'wordpress-importer' ); ?></label>
</p>
<?php endif; ?>
<p class="submit"><input type="submit" class="button" value="<?php esc_attr_e( 'Submit', 'wordpress-importer' ); ?>" /></p>
</form>
<?php
}
/**
* Display import options for an individual author. That is, either create
* a new user based on import info or map to an existing user
*
* @param int $n Index for each author in the form
* @param array $author Author information, e.g. login, display name, email
*/
function author_select( $n, $author ) {
_e( 'Import author:', 'wordpress-importer' );
echo ' <strong>' . esc_html( $author['author_display_name'] );
if ( $this->version != '1.0' ) echo ' (' . esc_html( $author['author_login'] ) . ')';
echo '</strong><br />';
if ( $this->version != '1.0' )
echo '<div style="margin-left:18px">';
$create_users = $this->allow_create_users();
if ( $create_users ) {
if ( $this->version != '1.0' ) {
_e( 'or create new user with login name:', 'wordpress-importer' );
$value = '';
} else {
_e( 'as a new user:', 'wordpress-importer' );
$value = esc_attr( sanitize_user( $author['author_login'], true ) );
}
echo ' <input type="text" name="user_new['.$n.']" value="'. $value .'" /><br />';
}
if ( ! $create_users && $this->version == '1.0' )
_e( 'assign posts to an existing user:', 'wordpress-importer' );
else
_e( 'or assign posts to an existing user:', 'wordpress-importer' );
wp_dropdown_users( array( 'name' => "user_map[$n]", 'multi' => true, 'show_option_all' => __( '- Select -', 'wordpress-importer' ) ) );
echo '<input type="hidden" name="imported_authors['.$n.']" value="' . esc_attr( $author['author_login'] ) . '" />';
if ( $this->version != '1.0' )
echo '</div>';
}
/**
* Map old author logins to local user IDs based on decisions made
* in import options form. Can map to an existing user, create a new user
* or falls back to the current user in case of error with either of the previous
*/
function get_author_mapping() {
if ( ! isset( $_POST['imported_authors'] ) )
return;
$create_users = $this->allow_create_users();
foreach ( (array) $_POST['imported_authors'] as $i => $old_login ) {
// Multisite adds strtolower to sanitize_user. Need to sanitize here to stop breakage in process_posts.
$santized_old_login = sanitize_user( $old_login, true );
$old_id = isset( $this->authors[$old_login]['author_id'] ) ? intval($this->authors[$old_login]['author_id']) : false;
if ( ! empty( $_POST['user_map'][$i] ) ) {
$user = get_userdata( intval($_POST['user_map'][$i]) );
if ( isset( $user->ID ) ) {
if ( $old_id )
$this->processed_authors[$old_id] = $user->ID;
$this->author_mapping[$santized_old_login] = $user->ID;
}
} else if ( $create_users ) {
if ( ! empty($_POST['user_new'][$i]) ) {
$user_id = wp_create_user( $_POST['user_new'][$i], wp_generate_password() );
} else if ( $this->version != '1.0' ) {
$user_data = array(
'user_login' => $old_login,
'user_pass' => wp_generate_password(),
'user_email' => isset( $this->authors[$old_login]['author_email'] ) ? $this->authors[$old_login]['author_email'] : '',
'display_name' => $this->authors[$old_login]['author_display_name'],
'first_name' => isset( $this->authors[$old_login]['author_first_name'] ) ? $this->authors[$old_login]['author_first_name'] : '',
'last_name' => isset( $this->authors[$old_login]['author_last_name'] ) ? $this->authors[$old_login]['author_last_name'] : '',
);
$user_id = wp_insert_user( $user_data );
}
if ( ! is_wp_error( $user_id ) ) {
if ( $old_id )
$this->processed_authors[$old_id] = $user_id;
$this->author_mapping[$santized_old_login] = $user_id;
} else {
printf( __( 'Failed to create new user for %s. Their posts will be attributed to the current user.', 'wordpress-importer' ), esc_html($this->authors[$old_login]['author_display_name']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ' ' . $user_id->get_error_message();
echo '<br />';
}
}
// failsafe: if the user_id was invalid, default to the current user
if ( ! isset( $this->author_mapping[$santized_old_login] ) ) {
if ( $old_id )
$this->processed_authors[$old_id] = (int) get_current_user_id();
$this->author_mapping[$santized_old_login] = (int) get_current_user_id();
}
}
}
/**
* Create new categories based on import information
*
* Doesn't create a new category if its slug already exists
*/
function process_categories() {
$this->categories = apply_filters( 'wp_import_categories', $this->categories );
if ( empty( $this->categories ) )
return;
foreach ( $this->categories as $cat ) {
// if the category already exists leave it alone
$term_id = term_exists( $cat['category_nicename'], 'category' );
if ( $term_id ) {
if ( is_array($term_id) ) $term_id = $term_id['term_id'];
if ( isset($cat['term_id']) )
$this->processed_terms[intval($cat['term_id'])] = (int) $term_id;
continue;
}
$category_parent = empty( $cat['category_parent'] ) ? 0 : category_exists( $cat['category_parent'] );
$category_description = isset( $cat['category_description'] ) ? $cat['category_description'] : '';
$catarr = array(
'category_nicename' => $cat['category_nicename'],
'category_parent' => $category_parent,
'cat_name' => $cat['cat_name'],
'category_description' => $category_description
);
$id = wp_insert_category( $catarr );
if ( ! is_wp_error( $id ) ) {
if ( isset($cat['term_id']) )
$this->processed_terms[intval($cat['term_id'])] = $id;
} else {
printf( __( 'Failed to import category %s', 'wordpress-importer' ), esc_html($cat['category_nicename']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ': ' . $id->get_error_message();
echo '<br />';
continue;
}
}
unset( $this->categories );
}
/**
* Create new post tags based on import information
*
* Doesn't create a tag if its slug already exists
*/
function process_tags() {
$this->tags = apply_filters( 'wp_import_tags', $this->tags );
if ( empty( $this->tags ) )
return;
foreach ( $this->tags as $tag ) {
// if the tag already exists leave it alone
$term_id = term_exists( $tag['tag_slug'], 'post_tag' );
if ( $term_id ) {
if ( is_array($term_id) ) $term_id = $term_id['term_id'];
if ( isset($tag['term_id']) )
$this->processed_terms[intval($tag['term_id'])] = (int) $term_id;
continue;
}
$tag_desc = isset( $tag['tag_description'] ) ? $tag['tag_description'] : '';
$tagarr = array( 'slug' => $tag['tag_slug'], 'description' => $tag_desc );
$id = wp_insert_term( $tag['tag_name'], 'post_tag', $tagarr );
if ( ! is_wp_error( $id ) ) {
if ( isset($tag['term_id']) )
$this->processed_terms[intval($tag['term_id'])] = $id['term_id'];
} else {
printf( __( 'Failed to import post tag %s', 'wordpress-importer' ), esc_html($tag['tag_name']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ': ' . $id->get_error_message();
echo '<br />';
continue;
}
}
unset( $this->tags );
}
/**
* Create new terms based on import information
*
* Doesn't create a term its slug already exists
*/
function process_terms() {
$this->terms = apply_filters( 'wp_import_terms', $this->terms );
if ( empty( $this->terms ) )
return;
foreach ( $this->terms as $term ) {
// if the term already exists in the correct taxonomy leave it alone
$term_id = term_exists( $term['slug'], $term['term_taxonomy'] );
if ( $term_id ) {
if ( is_array($term_id) ) $term_id = $term_id['term_id'];
if ( isset($term['term_id']) )
$this->processed_terms[intval($term['term_id'])] = (int) $term_id;
continue;
}
if ( empty( $term['term_parent'] ) ) {
$parent = 0;
} else {
$parent = term_exists( $term['term_parent'], $term['term_taxonomy'] );
if ( is_array( $parent ) ) $parent = $parent['term_id'];
}
$description = isset( $term['term_description'] ) ? $term['term_description'] : '';
$termarr = array( 'slug' => $term['slug'], 'description' => $description, 'parent' => intval($parent) );
$id = wp_insert_term( $term['term_name'], $term['term_taxonomy'], $termarr );
if ( ! is_wp_error( $id ) ) {
if ( isset($term['term_id']) )
$this->processed_terms[intval($term['term_id'])] = $id['term_id'];
} else {
printf( __( 'Failed to import %s %s', 'wordpress-importer' ), esc_html($term['term_taxonomy']), esc_html($term['term_name']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ': ' . $id->get_error_message();
echo '<br />';
continue;
}
}
unset( $this->terms );
}
/**
* Create new posts based on import information
*
* Posts marked as having a parent which doesn't exist will become top level items.
* Doesn't create a new post if: the post type doesn't exist, the given post ID
* is already noted as imported or a post with the same title and date already exists.
* Note that new/updated terms, comments and meta are imported for the last of the above.
*/
function process_posts() {
$this->posts = apply_filters( 'wp_import_posts', $this->posts );
foreach ( $this->posts as $post ) {
$post = apply_filters( 'wp_import_post_data_raw', $post );
if ( ! post_type_exists( $post['post_type'] ) ) {
printf( __( 'Failed to import “%s”: Invalid post type %s', 'wordpress-importer' ),
esc_html($post['post_title']), esc_html($post['post_type']) );
echo '<br />';
do_action( 'wp_import_post_exists', $post );
continue;
}
if ( isset( $this->processed_posts[$post['post_id']] ) && ! empty( $post['post_id'] ) )
continue;
if ( $post['status'] == 'auto-draft' )
continue;
if ( 'nav_menu_item' == $post['post_type'] ) {
$this->process_menu_item( $post );
continue;
}
$post_type_object = get_post_type_object( $post['post_type'] );
$post_exists = post_exists( $post['post_title'], '', $post['post_date'] );
if ( $post_exists && get_post_type( $post_exists ) == $post['post_type'] ) {
printf( __('%s “%s” already exists.', 'wordpress-importer'), $post_type_object->labels->singular_name, esc_html($post['post_title']) );
echo '<br />';
$comment_post_ID = $post_id = $post_exists;
} else {
$post_parent = (int) $post['post_parent'];
if ( $post_parent ) {
// if we already know the parent, map it to the new local ID
if ( isset( $this->processed_posts[$post_parent] ) ) {
$post_parent = $this->processed_posts[$post_parent];
// otherwise record the parent for later
} else {
$this->post_orphans[intval($post['post_id'])] = $post_parent;
$post_parent = 0;
}
}
// map the post author
$author = sanitize_user( $post['post_author'], true );
if ( isset( $this->author_mapping[$author] ) )
$author = $this->author_mapping[$author];
else
$author = (int) get_current_user_id();
$postdata = array(
'import_id' => $post['post_id'], 'post_author' => $author, 'post_date' => $post['post_date'],
'post_date_gmt' => $post['post_date_gmt'], 'post_content' => $post['post_content'],
'post_excerpt' => $post['post_excerpt'], 'post_title' => $post['post_title'],
'post_status' => $post['status'], 'post_name' => $post['post_name'],
'comment_status' => $post['comment_status'], 'ping_status' => $post['ping_status'],
'guid' => $post['guid'], 'post_parent' => $post_parent, 'menu_order' => $post['menu_order'],
'post_type' => $post['post_type'], 'post_password' => $post['post_password']
);
$original_post_ID = $post['post_id'];
$postdata = apply_filters( 'wp_import_post_data_processed', $postdata, $post );
if ( 'attachment' == $postdata['post_type'] ) {
$remote_url = ! empty($post['attachment_url']) ? $post['attachment_url'] : $post['guid'];
// try to use _wp_attached file for upload folder placement to ensure the same location as the export site
// e.g. location is 2003/05/image.jpg but the attachment post_date is 2010/09, see media_handle_upload()
$postdata['upload_date'] = $post['post_date'];
if ( isset( $post['postmeta'] ) ) {
foreach( $post['postmeta'] as $meta ) {
if ( $meta['key'] == '_wp_attached_file' ) {
if ( preg_match( '%^[0-9]{4}/[0-9]{2}%', $meta['value'], $matches ) )
$postdata['upload_date'] = $matches[0];
break;
}
}
}
$comment_post_ID = $post_id = $this->process_attachment( $postdata, $remote_url );
} else {
$comment_post_ID = $post_id = wp_insert_post( $postdata, true );
do_action( 'wp_import_insert_post', $post_id, $original_post_ID, $postdata, $post );
}
if ( is_wp_error( $post_id ) ) {
printf( __( 'Failed to import %s “%s”', 'wordpress-importer' ),
$post_type_object->labels->singular_name, esc_html($post['post_title']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ': ' . $post_id->get_error_message();
echo '<br />';
continue;
}
if ( $post['is_sticky'] == 1 )
stick_post( $post_id );
}
// map pre-import ID to local ID
$this->processed_posts[intval($post['post_id'])] = (int) $post_id;
if ( ! isset( $post['terms'] ) )
$post['terms'] = array();
$post['terms'] = apply_filters( 'wp_import_post_terms', $post['terms'], $post_id, $post );
// add categories, tags and other terms
if ( ! empty( $post['terms'] ) ) {
$terms_to_set = array();
foreach ( $post['terms'] as $term ) {
// back compat with WXR 1.0 map 'tag' to 'post_tag'
$taxonomy = ( 'tag' == $term['domain'] ) ? 'post_tag' : $term['domain'];
$term_exists = term_exists( $term['slug'], $taxonomy );
$term_id = is_array( $term_exists ) ? $term_exists['term_id'] : $term_exists;
if ( ! $term_id ) {
$t = wp_insert_term( $term['name'], $taxonomy, array( 'slug' => $term['slug'] ) );
if ( ! is_wp_error( $t ) ) {
$term_id = $t['term_id'];
do_action( 'wp_import_insert_term', $t, $term, $post_id, $post );
} else {
printf( __( 'Failed to import %s %s', 'wordpress-importer' ), esc_html($taxonomy), esc_html($term['name']) );
if ( defined('IMPORT_DEBUG') && IMPORT_DEBUG )
echo ': ' . $t->get_error_message();
echo '<br />';
do_action( 'wp_import_insert_term_failed', $t, $term, $post_id, $post );
continue;
}
}
$terms_to_set[$taxonomy][] = intval( $term_id );
}
foreach ( $terms_to_set as $tax => $ids ) {
$tt_ids = wp_set_post_terms( $post_id, $ids, $tax );
do_action( 'wp_import_set_post_terms', $tt_ids, $ids, $tax, $post_id, $post );
}
unset( $post['terms'], $terms_to_set );
}
if ( ! isset( $post['comments'] ) )
$post['comments'] = array();
$post['comments'] = apply_filters( 'wp_import_post_comments', $post['comments'], $post_id, $post );
// add/update comments
if ( ! empty( $post['comments'] ) ) {
$num_comments = 0;
$inserted_comments = array();
foreach ( $post['comments'] as $comment ) {
$comment_id = $comment['comment_id'];
$newcomments[$comment_id]['comment_post_ID'] = $comment_post_ID;
$newcomments[$comment_id]['comment_author'] = $comment['comment_author'];
$newcomments[$comment_id]['comment_author_email'] = $comment['comment_author_email'];
$newcomments[$comment_id]['comment_author_IP'] = $comment['comment_author_IP'];
$newcomments[$comment_id]['comment_author_url'] = $comment['comment_author_url'];
$newcomments[$comment_id]['comment_date'] = $comment['comment_date'];
$newcomments[$comment_id]['comment_date_gmt'] = $comment['comment_date_gmt'];
$newcomments[$comment_id]['comment_content'] = $comment['comment_content'];
$newcomments[$comment_id]['comment_approved'] = $comment['comment_approved'];
$newcomments[$comment_id]['comment_type'] = $comment['comment_type'];
$newcomments[$comment_id]['comment_parent'] = $comment['comment_parent'];
$newcomments[$comment_id]['commentmeta'] = isset( $comment['commentmeta'] ) ? $comment['commentmeta'] : array();
if ( isset( $this->processed_authors[$comment['comment_user_id']] ) )
$newcomments[$comment_id]['user_id'] = $this->processed_authors[$comment['comment_user_id']];
}
ksort( $newcomments );
foreach ( $newcomments as $key => $comment ) {
// if this is a new post we can skip the comment_exists() check
if ( ! $post_exists || ! comment_exists( $comment['comment_author'], $comment['comment_date'] ) ) {
if ( isset( $inserted_comments[$comment['comment_parent']] ) )
$comment['comment_parent'] = $inserted_comments[$comment['comment_parent']];
$comment = wp_filter_comment( $comment );
$inserted_comments[$key] = wp_insert_comment( $comment );
do_action( 'wp_import_insert_comment', $inserted_comments[$key], $comment, $comment_post_ID, $post );
foreach( $comment['commentmeta'] as $meta ) {
$value = maybe_unserialize( $meta['value'] );
add_comment_meta( $inserted_comments[$key], $meta['key'], $value );
}
$num_comments++;
}
}
unset( $newcomments, $inserted_comments, $post['comments'] );
}
if ( ! isset( $post['postmeta'] ) )
$post['postmeta'] = array();
$post['postmeta'] = apply_filters( 'wp_import_post_meta', $post['postmeta'], $post_id, $post );
// add/update post meta
if ( ! empty( $post['postmeta'] ) ) {
foreach ( $post['postmeta'] as $meta ) {
$key = apply_filters( 'import_post_meta_key', $meta['key'], $post_id, $post );
$value = false;
if ( '_edit_last' == $key ) {
if ( isset( $this->processed_authors[intval($meta['value'])] ) )
$value = $this->processed_authors[intval($meta['value'])];
else
$key = false;
}
if ( $key ) {
// export gets meta straight from the DB so could have a serialized string
if ( ! $value )
$value = maybe_unserialize( $meta['value'] );
add_post_meta( $post_id, $key, $value );
do_action( 'import_post_meta', $post_id, $key, $value );
// if the post has a featured image, take note of this in case of remap
if ( '_thumbnail_id' == $key )
$this->featured_images[$post_id] = (int) $value;
}
}
}
}
unset( $this->posts );
}
/**
* Attempt to create a new menu item from import data
*
* Fails for draft, orphaned menu items and those without an associated nav_menu
* or an invalid nav_menu term. If the post type or term object which the menu item
* represents doesn't exist then the menu item will not be imported (waits until the
* end of the import to retry again before discarding).
*
* @param array $item Menu item details from WXR file
*/
function process_menu_item( $item ) {
// skip draft, orphaned menu items
if ( 'draft' == $item['status'] )
return;
$menu_slug = false;
if ( isset($item['terms']) ) {
// loop through terms, assume first nav_menu term is correct menu
foreach ( $item['terms'] as $term ) {
if ( 'nav_menu' == $term['domain'] ) {
$menu_slug = $term['slug'];
break;
}
}
}
// no nav_menu term associated with this menu item
if ( ! $menu_slug ) {
_e( 'Menu item skipped due to missing menu slug', 'wordpress-importer' );
echo '<br />';
return;
}
$menu_id = term_exists( $menu_slug, 'nav_menu' );
if ( ! $menu_id ) {
printf( __( 'Menu item skipped due to invalid menu slug: %s', 'wordpress-importer' ), esc_html( $menu_slug ) );
echo '<br />';
return;
} else {
$menu_id = is_array( $menu_id ) ? $menu_id['term_id'] : $menu_id;
}
foreach ( $item['postmeta'] as $meta )
$$meta['key'] = $meta['value'];
if ( 'taxonomy' == $_menu_item_type && isset( $this->processed_terms[intval($_menu_item_object_id)] ) ) {
$_menu_item_object_id = $this->processed_terms[intval($_menu_item_object_id)];
} else if ( 'post_type' == $_menu_item_type && isset( $this->processed_posts[intval($_menu_item_object_id)] ) ) {
$_menu_item_object_id = $this->processed_posts[intval($_menu_item_object_id)];
} else if ( 'custom' != $_menu_item_type ) {
// associated object is missing or not imported yet, we'll retry later
$this->missing_menu_items[] = $item;
return;
}
if ( isset( $this->processed_menu_items[intval($_menu_item_menu_item_parent)] ) ) {
$_menu_item_menu_item_parent = $this->processed_menu_items[intval($_menu_item_menu_item_parent)];
} else if ( $_menu_item_menu_item_parent ) {
$this->menu_item_orphans[intval($item['post_id'])] = (int) $_menu_item_menu_item_parent;
$_menu_item_menu_item_parent = 0;
}
// wp_update_nav_menu_item expects CSS classes as a space separated string
$_menu_item_classes = maybe_unserialize( $_menu_item_classes );
if ( is_array( $_menu_item_classes ) )
$_menu_item_classes = implode( ' ', $_menu_item_classes );
$args = array(
'menu-item-object-id' => $_menu_item_object_id,
'menu-item-object' => $_menu_item_object,
'menu-item-parent-id' => $_menu_item_menu_item_parent,
'menu-item-position' => intval( $item['menu_order'] ),
'menu-item-type' => $_menu_item_type,
'menu-item-title' => $item['post_title'],
'menu-item-url' => $_menu_item_url,
'menu-item-description' => $item['post_content'],
'menu-item-attr-title' => $item['post_excerpt'],
'menu-item-target' => $_menu_item_target,
'menu-item-classes' => $_menu_item_classes,
'menu-item-xfn' => $_menu_item_xfn,
'menu-item-status' => $item['status']
);
$id = wp_update_nav_menu_item( $menu_id, 0, $args );
if ( $id && ! is_wp_error( $id ) )
$this->processed_menu_items[intval($item['post_id'])] = (int) $id;
}
/**
* If fetching attachments is enabled then attempt to create a new attachment
*
* @param array $post Attachment post details from WXR
* @param string $url URL to fetch attachment from
* @return int|WP_Error Post ID on success, WP_Error otherwise
*/
function process_attachment( $post, $url ) {
if ( ! $this->fetch_attachments )
return new WP_Error( 'attachment_processing_error',
__( 'Fetching attachments is not enabled', 'wordpress-importer' ) );
// if the URL is absolute, but does not contain address, then upload it assuming base_site_url
if ( preg_match( '|^/[\w\W]+$|', $url ) )
$url = rtrim( $this->base_url, '/' ) . $url;
$upload = $this->fetch_remote_file( $url, $post );
if ( is_wp_error( $upload ) )
return $upload;
if ( $info = wp_check_filetype( $upload['file'] ) )
$post['post_mime_type'] = $info['type'];
else
return new WP_Error( 'attachment_processing_error', __('Invalid file type', 'wordpress-importer') );
$post['guid'] = $upload['url'];
// as per wp-admin/includes/upload.php
$post_id = wp_insert_attachment( $post, $upload['file'] );
wp_update_attachment_metadata( $post_id, wp_generate_attachment_metadata( $post_id, $upload['file'] ) );
// remap resized image URLs, works by stripping the extension and remapping the URL stub.
if ( preg_match( '!^image/!', $info['type'] ) ) {
$parts = pathinfo( $url );
$name = basename( $parts['basename'], ".{$parts['extension']}" ); // PATHINFO_FILENAME in PHP 5.2
$parts_new = pathinfo( $upload['url'] );
$name_new = basename( $parts_new['basename'], ".{$parts_new['extension']}" );
$this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
}
return $post_id;
}
/**
* Attempt to download a remote file attachment
*
* @param string $url URL of item to fetch
* @param array $post Attachment details
* @return array|WP_Error Local file location details on success, WP_Error otherwise
*/
function fetch_remote_file( $url, $post ) {
// extract the file name and extension from the url
$file_name = basename( $url );
// get placeholder file in the upload dir with a unique, sanitized filename
$upload = wp_upload_bits( $file_name, 0, '', $post['upload_date'] );
if ( $upload['error'] )
return new WP_Error( 'upload_dir_error', $upload['error'] );
// fetch the remote url and write it to the placeholder file
$headers = wp_get_http( $url, $upload['file'] );
// request failed
if ( ! $headers ) {
@unlink( $upload['file'] );
return new WP_Error( 'import_file_error', __('Remote server did not respond', 'wordpress-importer') );
}
// make sure the fetch was successful
if ( $headers['response'] != '200' ) {
@unlink( $upload['file'] );
return new WP_Error( 'import_file_error', sprintf( __('Remote server returned error response %1$d %2$s', 'wordpress-importer'), esc_html($headers['response']), get_status_header_desc($headers['response']) ) );
}
$filesize = filesize( $upload['file'] );
if ( isset( $headers['content-length'] ) && $filesize != $headers['content-length'] ) {
@unlink( $upload['file'] );
return new WP_Error( 'import_file_error', __('Remote file is incorrect size', 'wordpress-importer') );
}
if ( 0 == $filesize ) {
@unlink( $upload['file'] );
return new WP_Error( 'import_file_error', __('Zero size file downloaded', 'wordpress-importer') );
}
$max_size = (int) $this->max_attachment_size();
if ( ! empty( $max_size ) && $filesize > $max_size ) {
@unlink( $upload['file'] );
return new WP_Error( 'import_file_error', sprintf(__('Remote file is too large, limit is %s', 'wordpress-importer'), size_format($max_size) ) );
}
// keep track of the old and new urls so we can substitute them later
$this->url_remap[$url] = $upload['url'];
$this->url_remap[$post['guid']] = $upload['url']; // r13735, really needed?
// keep track of the destination if the remote url is redirected somewhere else
if ( isset($headers['x-final-location']) && $headers['x-final-location'] != $url )
$this->url_remap[$headers['x-final-location']] = $upload['url'];
return $upload;
}
/**
* Attempt to associate posts and menu items with previously missing parents
*
* An imported post's parent may not have been imported when it was first created
* so try again. Similarly for child menu items and menu items which were missing
* the object (e.g. post) they represent in the menu
*/
function backfill_parents() {
global $wpdb;
// find parents for post orphans
foreach ( $this->post_orphans as $child_id => $parent_id ) {
$local_child_id = $local_parent_id = false;
if ( isset( $this->processed_posts[$child_id] ) )
$local_child_id = $this->processed_posts[$child_id];
if ( isset( $this->processed_posts[$parent_id] ) )
$local_parent_id = $this->processed_posts[$parent_id];
if ( $local_child_id && $local_parent_id )
$wpdb->update( $wpdb->posts, array( 'post_parent' => $local_parent_id ), array( 'ID' => $local_child_id ), '%d', '%d' );
}
// all other posts/terms are imported, retry menu items with missing associated object
$missing_menu_items = $this->missing_menu_items;
foreach ( $missing_menu_items as $item )
$this->process_menu_item( $item );
// find parents for menu item orphans
foreach ( $this->menu_item_orphans as $child_id => $parent_id ) {
$local_child_id = $local_parent_id = 0;
if ( isset( $this->processed_menu_items[$child_id] ) )
$local_child_id = $this->processed_menu_items[$child_id];
if ( isset( $this->processed_menu_items[$parent_id] ) )
$local_parent_id = $this->processed_menu_items[$parent_id];
if ( $local_child_id && $local_parent_id )
update_post_meta( $local_child_id, '_menu_item_menu_item_parent', (int) $local_parent_id );
}
}
/**
* Use stored mapping information to update old attachment URLs
*/
function backfill_attachment_urls() {
global $wpdb;
// make sure we do the longest urls first, in case one is a substring of another
uksort( $this->url_remap, array(&$this, 'cmpr_strlen') );
foreach ( $this->url_remap as $from_url => $to_url ) {
// remap urls in post_content
$wpdb->query( $wpdb->prepare("UPDATE {$wpdb->posts} SET post_content = REPLACE(post_content, %s, %s)", $from_url, $to_url) );
// remap enclosure urls
$result = $wpdb->query( $wpdb->prepare("UPDATE {$wpdb->postmeta} SET meta_value = REPLACE(meta_value, %s, %s) WHERE meta_key='enclosure'", $from_url, $to_url) );
}
}
/**
* Update _thumbnail_id meta to new, imported attachment IDs
*/
function remap_featured_images() {
// cycle through posts that have a featured image
foreach ( $this->featured_images as $post_id => $value ) {
if ( isset( $this->processed_posts[$value] ) ) {
$new_id = $this->processed_posts[$value];
// only update if there's a difference
if ( $new_id != $value )
update_post_meta( $post_id, '_thumbnail_id', $new_id );
}
}
}
/**
* Parse a WXR file
*
* @param string $file Path to WXR file for parsing
* @return array Information gathered from the WXR file
*/
function parse( $file ) {
$parser = new WXR_Parser();
return $parser->parse( $file );
}
// Display import page title
function header() {
echo '<div class="wrap">';
echo '<h2>' . __( 'Import WordPress', 'wordpress-importer' ) . '</h2>';
$updates = get_plugin_updates();
$basename = plugin_basename(__FILE__);
if ( isset( $updates[$basename] ) ) {
$update = $updates[$basename];
echo '<div class="error"><p><strong>';
printf( __( 'A new version of this importer is available. Please update to version %s to ensure compatibility with newer export files.', 'wordpress-importer' ), $update->update->new_version );
echo '</strong></p></div>';
}
}
// Close div.wrap
function footer() {
echo '</div>';
}
/**
* Display introductory text and file upload form
*/
function greet() {
echo '<div class="narrow">';
echo '<p>'.__( 'Howdy! Upload your WordPress eXtended RSS (WXR) file and we’ll import the posts, pages, comments, custom fields, categories, and tags into this site.', 'wordpress-importer' ).'</p>';
echo '<p>'.__( 'Choose a WXR (.xml) file to upload, then click Upload file and import.', 'wordpress-importer' ).'</p>';
wp_import_upload_form( 'admin.php?import=wordpress&step=1' );
echo '</div>';
}
/**
* Decide if the given meta key maps to information we will want to import
*
* @param string $key The meta key to check
* @return string|bool The key if we do want to import, false if not
*/
function is_valid_meta_key( $key ) {
// skip attachment metadata since we'll regenerate it from scratch
// skip _edit_lock as not relevant for import
if ( in_array( $key, array( '_wp_attached_file', '_wp_attachment_metadata', '_edit_lock' ) ) )
return false;
return $key;
}
/**
* Decide whether or not the importer is allowed to create users.
* Default is true, can be filtered via import_allow_create_users
*
* @return bool True if creating users is allowed
*/
function allow_create_users() {
return apply_filters( 'import_allow_create_users', true );
}
/**
* Decide whether or not the importer should attempt to download attachment files.
* Default is true, can be filtered via import_allow_fetch_attachments. The choice
* made at the import options screen must also be true, false here hides that checkbox.
*
* @return bool True if downloading attachments is allowed
*/
function allow_fetch_attachments() {
return apply_filters( 'import_allow_fetch_attachments', true );
}
/**
* Decide what the maximum file size for downloaded attachments is.
* Default is 0 (unlimited), can be filtered via import_attachment_size_limit
*
* @return int Maximum attachment file size to import
*/
function max_attachment_size() {
return apply_filters( 'import_attachment_size_limit', 0 );
}
/**
* Added to http_request_timeout filter to force timeout at 60 seconds during import
* @return int 60
*/
function bump_request_timeout() {
return 60;
}
// return the difference in length between two strings
function cmpr_strlen( $a, $b ) {
return strlen($b) - strlen($a);
}
}
} // class_exists( 'WP_Importer' )
function wordpress_importer_init() {
load_plugin_textdomain( 'wordpress-importer', false, dirname( plugin_basename( __FILE__ ) ) . '/languages' );
/**
* WordPress Importer object for registering the import callback
* @global WP_Import $wp_import
*/
$GLOBALS['wp_import'] = new WP_Import();
register_importer( 'wordpress', 'WordPress', __('Import <strong>posts, pages, comments, custom fields, categories, and tags</strong> from a WordPress export file.', 'wordpress-importer'), array( $GLOBALS['wp_import'], 'dispatch' ) );
}
add_action( 'admin_init', 'wordpress_importer_init' );
|
rebloon/streambase.dev
|
wp-content/themes/saint/includes/wordpress-importer/wordpress-importer.php
|
PHP
|
gpl-2.0
| 42,155 |
<?php
namespace Engelsystem\Test\Unit\Helpers;
use Engelsystem\Config\Config;
use Engelsystem\Helpers\DumpServerServiceProvider;
use Engelsystem\Test\Unit\ServiceProviderTest;
use Symfony\Component\VarDumper\Cloner\VarCloner;
use Symfony\Component\VarDumper\Dumper\CliDumper;
use Symfony\Component\VarDumper\Dumper\ServerDumper;
class DumpServerServiceProviderTest extends ServiceProviderTest
{
/**
* @covers \Engelsystem\Helpers\DumpServerServiceProvider::register
*/
public function testRegisterIfClassExists(): void
{
if (class_exists(ServerDumper::class) === false) {
self::markTestSkipped('ServerDumper class does not exist. Skipping.');
}
$varDumpServerConfig = [
'host' => 'localhost',
'port' => 80,
'enable' => true
];
$config = new Config();
$config->set('var_dump_server', $varDumpServerConfig);
$config->set('environment', 'development');
// mock to test that the code has passed the enabled checks and started to configure the var dump server
$app = $this->getApp(['get']);
$app->expects(self::exactly(3))
->method('get')
->withConsecutive(
['config'],
[CliDumper::class],
[VarCloner::class]
)->willReturnOnConsecutiveCalls(
$config,
new CliDumper(),
new VarCloner()
);
$dumpServiceProvider = new DumpServerServiceProvider($app);
$dumpServiceProvider->register();
}
public function notEnabledDataProvider(): array
{
return [
[false, 'development'],
[false, 'production'],
[true, 'production'],
];
}
/**
* @covers \Engelsystem\Helpers\DumpServerServiceProvider::register
* @dataProvider notEnabledDataProvider
*
* @param bool $enable
* @param string $environment
*/
public function testRegisterShouldNotEnable(bool $enable, string $environment): void
{
$varDumpServerConfig = [
'host' => 'localhost',
'port' => 80,
'enable' => $enable
];
$config = new Config();
$config->set('var_dump_server', $varDumpServerConfig);
$config->set('environment', $environment);
// asset get is called once only
$app = $this->getApp(['get']);
$app->expects(self::once())
->method('get')
->willReturn($config);
$dumpServiceProvider = new DumpServerServiceProvider($app);
$dumpServiceProvider->register();
}
}
|
engelsystem/engelsystem
|
tests/Unit/Helpers/DumpServerServiceProviderTest.php
|
PHP
|
gpl-2.0
| 2,677 |
<?php
/*******************************************************************************
*******************************************************************************
** **
** **
** Copyright 2015-2017 JK Technosoft **
** http://www.jktech.com **
** **
** ProActio is free software; you can redistribute it and/or modify it **
** under the terms of the GNU General Public License (GPL) as published **
** by the Free Software Foundation; either version 2 of the License, or **
** at your option) any later version. **
** **
** ProActio 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. **
** **
** See TNC.TXT for more information regarding the Terms and Conditions **
** of use and alternative licensing options for this software. **
** **
** A copy of the GPL is in GPL.TXT which was provided with this package. **
** **
** See http://www.fsf.org for more information about the GPL. **
** **
** **
*******************************************************************************
*******************************************************************************
*
* {program name}
*
* Known Bugs & Issues:
*
*
* Author:
*
* JK Technosoft
* http://www.jktech.com
* August 11, 2015
*
*
* History:
*
*/
session_start();
require('pdffunc.php');
@$current_user=$_SESSION['username'];
$dt = $_POST['date'];
$pdf= new PDF_TOC('L','mm','A4');
$pdf->startPageNums();
$pdf->AliasNbPages();
$pdf->AddPage();
$pdf->SetFont('Times','',32);
$pdf->Ln(70);
$pdf->Cell(0,1,'Database Table I/O',0,1,'C');
$pdf->SetFont('Times','',19);
include('sqlconnectver2.php');
if($query = mysql_query("SELECT dbuid,dbname,environ FROM configureddb INNER JOIN dbalogin where dbalogin.username ='$current_user'")){
$pdf->AddPage();
$pdf->Ln(3);
$pdf->SetFont('Arial','',20);
$pdf->setFillColor(63,139,202);
$pdf->SetTextColor(253,253,253);
$pdf->Cell(0,10,'List of Databases',1,1,'C',1);
$pdf->TOC_Entry('List of Databases', 0);
$pdf->SetTextColor(0,0,0);
$pdf->SetFont('Times','',14);
while($query_row=mysql_fetch_assoc($query)){
$dbuid=$query_row['dbuid'];
$databaseName =$query_row['dbname'];
$environ =$query_row['environ'];
$pdf->Cell(0,10,'Database:'.$databaseName.' ['.$environ.']',0,1,'L');
}
$userio=mysql_query("SELECT * FROM tableio where date(date) = '$dt'");
if(mysql_num_rows($userio))
{
if($query = mysql_query("SELECT dbuid,dbname FROM configureddb INNER JOIN dbalogin where dbalogin.username ='$current_user'")){
$pdf->SetFont('Arial','',20);
$pdf->setFillColor(63,139,202);
$pdf->SetTextColor(253,253,253);
$pdf->Cell(0,10,'Database Table I/O',1,1,'C',1);
$pdf->TOC_Entry('Database Table I/O', 0);
$pdf->SetTextColor(0,0,0);
while($query_row=mysql_fetch_assoc($query)){
$dbuid=$query_row['dbuid'];
$databaseName =$query_row['dbname'];
$pdf->ln(1);
$connquery=mysql_query("SELECT time(date)as time,date(date) as date,tableioid,createtio,deletetio,readtio,tablename,updatetio FROM tableio WHERE dbid ='$dbuid' and date(date) = '$dt'");
if(mysql_num_rows($connquery)){
$pdf->TOC_Entry($databaseName, 1);
$pdf->SetFont('Arial','B',14);
$pdf->setFillColor(63,139,202);
$pdf->SetTextColor(253,253,253);
$pdf->Cell(0,7,'Database: '.$databaseName,1,1,'C',1);
$pdf->SetTextColor(0,0,0);
$pdf->AddCol('time',30,'TIME','C');
$pdf->AddCol('date',30,'DATE','C');
$pdf->AddCol('tableioid',25,'ID','C');
$pdf->AddCol('tablename',45,'TABLE NAME','C');
$pdf->AddCol('createtio',45,'CREATE');
$pdf->AddCol('deletetio',35,'DELETE');
$pdf->AddCol('readtio',37,'READ');
$pdf->AddCol('updatetio',30,'UPDATE');
$prop=array('HeaderColor'=>array(66,139,202),
'color1'=>array(255,255,255),
'color2'=>array(255,255,255));
$pdf->Table("SELECT time(date)as time,date(date) as date,tableioid,createtio,deletetio,readtio,tablename,updatetio FROM tableio WHERE dbid ='$dbuid' and date(date) = '$dt'",$prop);
$pdf->Ln(5);
}
else
{
$pdf->SetFont('Times','',26);
$pdf->Ln(10);
$pdf->Cell(0,10,'No Matching Records Found For Database '.$databaseName,0,1,'C');
}
}
}
}
else
{
$pdf->SetFont('Times','',26);
$pdf->Ln(30);
$pdf->Cell(0,10,'No Matching Records Found For Any Database ',0,1,'C');
$pdf->SetFont('Times','',20);
}
$pdf->stopPageNums();
$pdf->insertTOC(2);
$pdf->AutoPrint(true);
$pdf->Output();
odbc_close($conn);
mysql_close($connection);
}
?>
|
JKT-OSSCLUB/ProActio
|
Proactio Front/www/tiorep.php
|
PHP
|
gpl-2.0
| 5,452 |
/*!
* MediaElementPlayer
* http://mediaelementjs.com/
*
* Creates a controller bar for HTML5 <video> add <audio> tags
* using jQuery and MediaElement.js (HTML5 Flash/Silverlight wrapper)
*
* Copyright 2010-2013, John Dyer (http://j.hn/)
* License: MIT
*
*/
if (typeof jQuery != "undefined")mejs.$ = jQuery; else if (typeof ender != "undefined")mejs.$ = ender;
(function (f) {
mejs.MepDefaults = {poster: "", showPosterWhenEnded: false, defaultVideoWidth: 480, defaultVideoHeight: 270, videoWidth: -1, videoHeight: -1, defaultAudioWidth: 400, defaultAudioHeight: 30, defaultSeekBackwardInterval: function (a) {
return a.duration * 0.05
}, defaultSeekForwardInterval: function (a) {
return a.duration * 0.05
}, audioWidth: -1, audioHeight: -1, startVolume: 0.8, loop: false, autoRewind: true, enableAutosize: true, alwaysShowHours: false, showTimecodeFrameCount: false, framesPerSecond: 25, autosizeProgress: true, alwaysShowControls: false,
hideVideoControlsOnLoad: false, clickToPlayPause: true, iPadUseNativeControls: false, iPhoneUseNativeControls: false, AndroidUseNativeControls: false, features: ["playpause", "current", "progress", "duration", "tracks", "volume", "fullscreen"], isVideo: true, enableKeyboard: true, pauseOtherPlayers: true, keyActions: [
{keys: [32, 179], action: function (a, b) {
b.paused || b.ended ? a.play() : a.pause()
}},
{keys: [38], action: function (a, b) {
b.setVolume(Math.min(b.volume + 0.1, 1))
}},
{keys: [40], action: function (a, b) {
b.setVolume(Math.max(b.volume -
0.1, 0))
}},
{keys: [37, 227], action: function (a, b) {
if (!isNaN(b.duration) && b.duration > 0) {
if (a.isVideo) {
a.showControls();
a.startControlsTimer()
}
var c = Math.max(b.currentTime - a.options.defaultSeekBackwardInterval(b), 0);
b.setCurrentTime(c)
}
}},
{keys: [39, 228], action: function (a, b) {
if (!isNaN(b.duration) && b.duration > 0) {
if (a.isVideo) {
a.showControls();
a.startControlsTimer()
}
var c = Math.min(b.currentTime + a.options.defaultSeekForwardInterval(b), b.duration);
b.setCurrentTime(c)
}
}},
{keys: [70], action: function (a) {
if (typeof a.enterFullScreen !=
"undefined")a.isFullScreen ? a.exitFullScreen() : a.enterFullScreen()
}}
]};
mejs.mepIndex = 0;
mejs.players = {};
mejs.MediaElementPlayer = function (a, b) {
if (!(this instanceof mejs.MediaElementPlayer))return new mejs.MediaElementPlayer(a, b);
this.$media = this.$node = f(a);
this.node = this.media = this.$media[0];
if (typeof this.node.player != "undefined")return this.node.player; else this.node.player = this;
if (typeof b == "undefined")b = this.$node.data("mejsoptions");
this.options = f.extend({}, mejs.MepDefaults, b);
this.id = "mep_" + mejs.mepIndex++;
mejs.players[this.id] = this;
this.init();
return this
};
mejs.MediaElementPlayer.prototype = {hasFocus: false, controlsAreVisible: true, init: function () {
var a = this, b = mejs.MediaFeatures, c = f.extend(true, {}, a.options, {success: function (d, g) {
a.meReady(d, g)
}, error: function (d) {
a.handleError(d)
}}), e = a.media.tagName.toLowerCase();
a.isDynamic = e !== "audio" && e !== "video";
a.isVideo = a.isDynamic ? a.options.isVideo : e !== "audio" && a.options.isVideo;
if (b.isiPad && a.options.iPadUseNativeControls || b.isiPhone && a.options.iPhoneUseNativeControls) {
a.$media.attr("controls",
"controls");
b.isiPad && a.media.getAttribute("autoplay") !== null && a.play()
} else if (!(b.isAndroid && a.options.AndroidUseNativeControls)) {
a.$media.removeAttr("controls");
a.container = f('<div id="' + a.id + '" class="mejs-container ' + (mejs.MediaFeatures.svg ? "svg" : "no-svg") + '"><div class="mejs-inner"><div class="mejs-mediaelement"></div><div class="mejs-layers"></div><div class="mejs-controls"></div><div class="mejs-clear"></div></div></div>').addClass(a.$media[0].className).insertBefore(a.$media);
a.container.addClass((b.isAndroid ?
"mejs-android " : "") + (b.isiOS ? "mejs-ios " : "") + (b.isiPad ? "mejs-ipad " : "") + (b.isiPhone ? "mejs-iphone " : "") + (a.isVideo ? "mejs-video " : "mejs-audio "));
if (b.isiOS) {
b = a.$media.clone();
a.container.find(".mejs-mediaelement").append(b);
a.$media.remove();
a.$node = a.$media = b;
a.node = a.media = b[0]
} else a.container.find(".mejs-mediaelement").append(a.$media);
a.controls = a.container.find(".mejs-controls");
a.layers = a.container.find(".mejs-layers");
b = a.isVideo ? "video" : "audio";
e = b.substring(0, 1).toUpperCase() + b.substring(1);
a.width = a.options[b + "Width"] > 0 || a.options[b + "Width"].toString().indexOf("%") > -1 ? a.options[b + "Width"] : a.media.style.width !== "" && a.media.style.width !== null ? a.media.style.width : a.media.getAttribute("width") !== null ? a.$media.attr("width") : a.options["default" + e + "Width"];
a.height = a.options[b + "Height"] > 0 || a.options[b + "Height"].toString().indexOf("%") > -1 ? a.options[b + "Height"] : a.media.style.height !== "" && a.media.style.height !== null ? a.media.style.height : a.$media[0].getAttribute("height") !== null ? a.$media.attr("height") :
a.options["default" + e + "Height"];
a.setPlayerSize(a.width, a.height);
c.pluginWidth = a.width;
c.pluginHeight = a.height
}
mejs.MediaElement(a.$media[0], c);
typeof a.container != "undefined" && a.controlsAreVisible && a.container.trigger("controlsshown")
}, showControls: function (a) {
var b = this;
a = typeof a == "undefined" || a;
if (!b.controlsAreVisible) {
if (a) {
b.controls.css("visibility", "visible").stop(true, true).fadeIn(200, function () {
b.controlsAreVisible = true;
b.container.trigger("controlsshown")
});
b.container.find(".mejs-control").css("visibility",
"visible").stop(true, true).fadeIn(200, function () {
b.controlsAreVisible = true
})
} else {
b.controls.css("visibility", "visible").css("display", "block");
b.container.find(".mejs-control").css("visibility", "visible").css("display", "block");
b.controlsAreVisible = true;
b.container.trigger("controlsshown")
}
b.setControlsSize()
}
}, hideControls: function (a) {
var b = this;
a = typeof a == "undefined" || a;
if (!(!b.controlsAreVisible || b.options.alwaysShowControls))if (a) {
b.controls.stop(true, true).fadeOut(200, function () {
f(this).css("visibility",
"hidden").css("display", "block");
b.controlsAreVisible = false;
b.container.trigger("controlshidden")
});
b.container.find(".mejs-control").stop(true, true).fadeOut(200, function () {
f(this).css("visibility", "hidden").css("display", "block")
})
} else {
b.controls.css("visibility", "hidden").css("display", "block");
b.container.find(".mejs-control").css("visibility", "hidden").css("display", "block");
b.controlsAreVisible = false;
b.container.trigger("controlshidden")
}
}, controlsTimer: null, startControlsTimer: function (a) {
var b =
this;
a = typeof a != "undefined" ? a : 1500;
b.killControlsTimer("start");
b.controlsTimer = setTimeout(function () {
b.hideControls();
b.killControlsTimer("hide")
}, a)
}, killControlsTimer: function () {
if (this.controlsTimer !== null) {
clearTimeout(this.controlsTimer);
delete this.controlsTimer;
this.controlsTimer = null
}
}, controlsEnabled: true, disableControls: function () {
this.killControlsTimer();
this.hideControls(false);
this.controlsEnabled = false
}, enableControls: function () {
this.showControls(false);
this.controlsEnabled = true
},
meReady: function (a, b) {
var c = this, e = mejs.MediaFeatures, d = b.getAttribute("autoplay");
d = !(typeof d == "undefined" || d === null || d === "false");
var g;
if (!c.created) {
c.created = true;
c.media = a;
c.domNode = b;
if (!(e.isAndroid && c.options.AndroidUseNativeControls) && !(e.isiPad && c.options.iPadUseNativeControls) && !(e.isiPhone && c.options.iPhoneUseNativeControls)) {
c.buildposter(c, c.controls, c.layers, c.media);
c.buildkeyboard(c, c.controls, c.layers, c.media);
c.buildoverlays(c, c.controls, c.layers, c.media);
c.findTracks();
for (g in c.options.features) {
e =
c.options.features[g];
if (c["build" + e])try {
c["build" + e](c, c.controls, c.layers, c.media)
} catch (k) {
}
}
c.container.trigger("controlsready");
c.setPlayerSize(c.width, c.height);
c.setControlsSize();
if (c.isVideo) {
if (mejs.MediaFeatures.hasTouch)c.$media.bind("touchstart", function () {
if (c.controlsAreVisible)c.hideControls(false); else c.controlsEnabled && c.showControls(false)
}); else {
c.clickToPlayPauseCallback = function () {
if (c.options.clickToPlayPause)c.media.paused ? c.play() : c.pause()
};
c.media.addEventListener("click",
c.clickToPlayPauseCallback, false);
c.container.bind("mouseenter mouseover",function () {
if (c.controlsEnabled)if (!c.options.alwaysShowControls) {
c.killControlsTimer("enter");
c.showControls();
c.startControlsTimer(2500)
}
}).bind("mousemove",function () {
if (c.controlsEnabled) {
c.controlsAreVisible || c.showControls();
c.options.alwaysShowControls || c.startControlsTimer(2500)
}
}).bind("mouseleave", function () {
c.controlsEnabled && !c.media.paused && !c.options.alwaysShowControls && c.startControlsTimer(1E3)
})
}
c.options.hideVideoControlsOnLoad &&
c.hideControls(false);
d && !c.options.alwaysShowControls && c.hideControls();
c.options.enableAutosize && c.media.addEventListener("loadedmetadata", function (j) {
if (c.options.videoHeight <= 0 && c.domNode.getAttribute("height") === null && !isNaN(j.target.videoHeight)) {
c.setPlayerSize(j.target.videoWidth, j.target.videoHeight);
c.setControlsSize();
c.media.setVideoSize(j.target.videoWidth, j.target.videoHeight)
}
}, false)
}
a.addEventListener("play", function () {
for (var j in mejs.players) {
var m = mejs.players[j];
m.id != c.id &&
c.options.pauseOtherPlayers && !m.paused && !m.ended && m.pause();
m.hasFocus = false
}
c.hasFocus = true
}, false);
c.media.addEventListener("ended", function () {
if (c.options.autoRewind)try {
c.media.setCurrentTime(0)
} catch (j) {
}
c.media.pause();
c.setProgressRail && c.setProgressRail();
c.setCurrentRail && c.setCurrentRail();
if (c.options.loop)c.play(); else!c.options.alwaysShowControls && c.controlsEnabled && c.showControls()
}, false);
c.media.addEventListener("loadedmetadata", function () {
c.updateDuration && c.updateDuration();
c.updateCurrent &&
c.updateCurrent();
if (!c.isFullScreen) {
c.setPlayerSize(c.width, c.height);
c.setControlsSize()
}
}, false);
setTimeout(function () {
c.setPlayerSize(c.width, c.height);
c.setControlsSize()
}, 50);
c.globalBind("resize", function () {
c.isFullScreen || mejs.MediaFeatures.hasTrueNativeFullScreen && document.webkitIsFullScreen || c.setPlayerSize(c.width, c.height);
c.setControlsSize()
});
c.media.pluginType == "youtube" && c.container.find(".mejs-overlay-play").hide()
}
d && a.pluginType == "native" && c.play();
if (c.options.success)typeof c.options.success ==
"string" ? window[c.options.success](c.media, c.domNode, c) : c.options.success(c.media, c.domNode, c)
}
}, handleError: function (a) {
this.controls.hide();
this.options.error && this.options.error(a)
}, setPlayerSize: function (a, b) {
if (typeof a != "undefined")this.width = a;
if (typeof b != "undefined")this.height = b;
if (this.height.toString().indexOf("%") > 0 || this.$node.css("max-width") === "100%" || parseInt(this.$node.css("max-width").replace(/px/, ""), 10) / this.$node.offsetParent().width() === 1 || this.$node[0].currentStyle && this.$node[0].currentStyle.maxWidth ===
"100%") {
var c = this.isVideo ? this.media.videoWidth && this.media.videoWidth > 0 ? this.media.videoWidth : this.options.defaultVideoWidth : this.options.defaultAudioWidth, e = this.isVideo ? this.media.videoHeight && this.media.videoHeight > 0 ? this.media.videoHeight : this.options.defaultVideoHeight : this.options.defaultAudioHeight, d = this.container.parent().closest(":visible").width();
c = this.isVideo || !this.options.autosizeProgress ? parseInt(d * e / c, 10) : e;
if (isNaN(c))c = this.container.parent().closest(":visible").height();
if (this.container.parent()[0].tagName.toLowerCase() ===
"body") {
d = f(window).width();
c = f(window).height()
}
if (c != 0 && d != 0) {
this.container.width(d).height(c);
this.$media.add(this.container.find(".mejs-shim")).width("100%").height("100%");
this.isVideo && this.media.setVideoSize && this.media.setVideoSize(d, c);
this.layers.children(".mejs-layer").width("100%").height("100%")
}
} else {
this.container.width(this.width).height(this.height);
this.layers.children(".mejs-layer").width(this.width).height(this.height)
}
d = this.layers.find(".mejs-overlay-play");
c = d.find(".mejs-overlay-button");
d.height(this.container.height() - this.controls.height());
c.css("margin-top", "-" + (c.height() / 2 - this.controls.height() / 2).toString() + "px")
}, setControlsSize: function () {
var a = 0, b = 0, c = this.controls.find(".mejs-time-rail"), e = this.controls.find(".mejs-time-total");
this.controls.find(".mejs-time-current");
this.controls.find(".mejs-time-loaded");
var d = c.siblings(), g = d.last(), k = null;
if (!(!this.container.is(":visible") || !c.length || !c.is(":visible"))) {
if (this.options && !this.options.autosizeProgress)b = parseInt(c.css("width"));
if (b === 0 || !b) {
d.each(function () {
var j = f(this);
if (j.css("position") != "absolute" && j.is(":visible"))a += f(this).outerWidth(true)
});
b = this.controls.width() - a - (c.outerWidth(true) - c.width())
}
do {
c.width(b);
e.width(b - (e.outerWidth(true) - e.width()));
if (g.css("position") != "absolute") {
k = g.position();
b--
}
} while (k != null && k.top > 0 && b > 0);
this.setProgressRail && this.setProgressRail();
this.setCurrentRail && this.setCurrentRail()
}
}, buildposter: function (a, b, c, e) {
var d = f('<div class="mejs-poster mejs-layer"></div>').appendTo(c);
b = a.$media.attr("poster");
if (a.options.poster !== "")b = a.options.poster;
b !== "" && b != null ? this.setPoster(b) : d.hide();
e.addEventListener("play", function () {
d.hide()
}, false);
a.options.showPosterWhenEnded && a.options.autoRewind && e.addEventListener("ended", function () {
d.show()
}, false)
}, setPoster: function (a) {
var b = this.container.find(".mejs-poster"), c = b.find("img");
if (c.length == 0)c = f('<img width="100%" height="100%" />').appendTo(b);
c.attr("src", a);
b.css({"background-image": "url(" + a + ")"})
}, buildoverlays: function (a, b, c, e) {
var d = this;
if (a.isVideo) {
var g = f('<div class="mejs-overlay mejs-layer"><div class="mejs-overlay-loading"><span></span></div></div>').hide().appendTo(c), k = f('<div class="mejs-overlay mejs-layer"><div class="mejs-overlay-error"></div></div>').hide().appendTo(c), j = f('<div class="mejs-overlay mejs-layer mejs-overlay-play"><div class="mejs-overlay-button"></div></div>').appendTo(c).bind("click touchstart", function () {
d.options.clickToPlayPause && e.paused && e.play()
});
e.addEventListener("play", function () {
j.hide();
g.hide();
b.find(".mejs-time-buffering").hide();
k.hide()
}, false);
e.addEventListener("playing", function () {
j.hide();
g.hide();
b.find(".mejs-time-buffering").hide();
k.hide()
}, false);
e.addEventListener("seeking", function () {
g.show();
b.find(".mejs-time-buffering").show()
}, false);
e.addEventListener("seeked", function () {
g.hide();
b.find(".mejs-time-buffering").hide()
}, false);
e.addEventListener("pause", function () {
mejs.MediaFeatures.isiPhone || j.show()
}, false);
e.addEventListener("waiting", function () {
g.show();
b.find(".mejs-time-buffering").show()
},
false);
e.addEventListener("loadeddata", function () {
g.show();
b.find(".mejs-time-buffering").show()
}, false);
e.addEventListener("canplay", function () {
g.hide();
b.find(".mejs-time-buffering").hide()
}, false);
e.addEventListener("error", function () {
g.hide();
b.find(".mejs-time-buffering").hide();
k.show();
k.find("mejs-overlay-error").html("Error loading this resource")
}, false)
}
}, buildkeyboard: function (a, b, c, e) {
this.globalBind("keydown", function (d) {
if (a.hasFocus && a.options.enableKeyboard)for (var g = 0, k = a.options.keyActions.length; g <
k; g++)for (var j = a.options.keyActions[g], m = 0, q = j.keys.length; m < q; m++)if (d.keyCode == j.keys[m]) {
d.preventDefault();
j.action(a, e, d.keyCode);
return false
}
return true
});
this.globalBind("click", function (d) {
a.hasFocus = f(d.target).closest(".mejs-container").length != 0
})
}, findTracks: function () {
var a = this, b = a.$media.find("track");
a.tracks = [];
b.each(function (c, e) {
e = f(e);
a.tracks.push({srclang: e.attr("srclang") ? e.attr("srclang").toLowerCase() : "", src: e.attr("src"), kind: e.attr("kind"), label: e.attr("label") || "", entries: [],
isLoaded: false})
})
}, changeSkin: function (a) {
this.container[0].className = "mejs-container " + a;
this.setPlayerSize(this.width, this.height);
this.setControlsSize()
}, play: function () {
this.load();
this.media.play()
}, pause: function () {
try {
this.media.pause()
} catch (a) {
}
}, load: function () {
this.isLoaded || this.media.load();
this.isLoaded = true
}, setMuted: function (a) {
this.media.setMuted(a)
}, setCurrentTime: function (a) {
this.media.setCurrentTime(a)
}, getCurrentTime: function () {
return this.media.currentTime
}, setVolume: function (a) {
this.media.setVolume(a)
},
getVolume: function () {
return this.media.volume
}, setSrc: function (a) {
this.media.setSrc(a)
}, remove: function () {
var a, b;
for (a in this.options.features) {
b = this.options.features[a];
if (this["clean" + b])try {
this["clean" + b](this)
} catch (c) {
}
}
if (this.isDynamic)this.$node.insertBefore(this.container); else {
this.$media.prop("controls", true);
this.$node.clone().show().insertBefore(this.container);
this.$node.remove()
}
this.media.pluginType !== "native" && this.media.remove();
delete mejs.players[this.id];
typeof this.container ==
"object" && this.container.remove();
this.globalUnbind();
delete this.node.player
}};
(function () {
function a(c, e) {
var d = {d: [], w: []};
f.each((c || "").split(" "), function (g, k) {
var j = k + "." + e;
if (j.indexOf(".") === 0) {
d.d.push(j);
d.w.push(j)
} else d[b.test(k) ? "w" : "d"].push(j)
});
d.d = d.d.join(" ");
d.w = d.w.join(" ");
return d
}
var b = /^((after|before)print|(before)?unload|hashchange|message|o(ff|n)line|page(hide|show)|popstate|resize|storage)\b/;
mejs.MediaElementPlayer.prototype.globalBind = function (c, e, d) {
c = a(c, this.id);
c.d && f(document).bind(c.d, e, d);
c.w && f(window).bind(c.w, e, d)
};
mejs.MediaElementPlayer.prototype.globalUnbind = function (c, e) {
c = a(c, this.id);
c.d && f(document).unbind(c.d, e);
c.w && f(window).unbind(c.w, e)
}
})();
if (typeof jQuery != "undefined")jQuery.fn.mediaelementplayer = function (a) {
a === false ? this.each(function () {
var b = jQuery(this).data("mediaelementplayer");
b && b.remove();
jQuery(this).removeData("mediaelementplayer")
}) : this.each(function () {
jQuery(this).data("mediaelementplayer", new mejs.MediaElementPlayer(this,
a))
});
return this
};
f(document).ready(function () {
f(".mejs-player").mediaelementplayer()
});
window.MediaElementPlayer = mejs.MediaElementPlayer
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {playpauseText: mejs.i18n.t("Play/Pause")});
f.extend(MediaElementPlayer.prototype, {buildplaypause: function (a, b, c, e) {
var d = f('<div class="mejs-button mejs-playpause-button mejs-play" ><button type="button" aria-controls="' + this.id + '" title="' + this.options.playpauseText + '" aria-label="' + this.options.playpauseText + '"></button></div>').appendTo(b).click(function (g) {
g.preventDefault();
e.paused ? e.play() : e.pause();
return false
});
e.addEventListener("play", function () {
d.removeClass("mejs-play").addClass("mejs-pause")
},
false);
e.addEventListener("playing", function () {
d.removeClass("mejs-play").addClass("mejs-pause")
}, false);
e.addEventListener("pause", function () {
d.removeClass("mejs-pause").addClass("mejs-play")
}, false);
e.addEventListener("paused", function () {
d.removeClass("mejs-pause").addClass("mejs-play")
}, false)
}})
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {stopText: "Stop"});
f.extend(MediaElementPlayer.prototype, {buildstop: function (a, b, c, e) {
f('<div class="mejs-button mejs-stop-button mejs-stop"><button type="button" aria-controls="' + this.id + '" title="' + this.options.stopText + '" aria-label="' + this.options.stopText + '"></button></div>').appendTo(b).click(function () {
e.paused || e.pause();
if (e.currentTime > 0) {
e.setCurrentTime(0);
e.pause();
b.find(".mejs-time-current").width("0px");
b.find(".mejs-time-handle").css("left",
"0px");
b.find(".mejs-time-float-current").html(mejs.Utility.secondsToTimeCode(0));
b.find(".mejs-currenttime").html(mejs.Utility.secondsToTimeCode(0));
c.find(".mejs-poster").show()
}
})
}})
})(mejs.$);
(function (f) {
f.extend(MediaElementPlayer.prototype, {buildprogress: function (a, b, c, e) {
f('<div class="mejs-time-rail"><span class="mejs-time-total"><span class="mejs-time-buffering"></span><span class="mejs-time-loaded"></span><span class="mejs-time-current"></span><span class="mejs-time-handle"></span><span class="mejs-time-float"><span class="mejs-time-float-current">00:00</span><span class="mejs-time-float-corner"></span></span></span></div>').appendTo(b);
b.find(".mejs-time-buffering").hide();
var d =
this, g = b.find(".mejs-time-total");
c = b.find(".mejs-time-loaded");
var k = b.find(".mejs-time-current"), j = b.find(".mejs-time-handle"), m = b.find(".mejs-time-float"), q = b.find(".mejs-time-float-current"), p = function (h) {
h = h.originalEvent.changedTouches ? h.originalEvent.changedTouches[0].pageX : h.pageX;
var l = g.offset(), r = g.outerWidth(true), n = 0, o = n = 0;
if (e.duration) {
if (h < l.left)h = l.left; else if (h > r + l.left)h = r + l.left;
o = h - l.left;
n = o / r;
n = n <= 0.02 ? 0 : n * e.duration;
t && n !== e.currentTime && e.setCurrentTime(n);
if (!mejs.MediaFeatures.hasTouch) {
m.css("left",
o);
q.html(mejs.Utility.secondsToTimeCode(n));
m.show()
}
}
}, t = false;
g.bind("mousedown touchstart",function (h) {
if (h.which === 1 || h.which === 0) {
t = true;
p(h);
d.globalBind("mousemove.dur touchmove.dur", function (l) {
p(l)
});
d.globalBind("mouseup.dur touchend.dur", function () {
t = false;
m.hide();
d.globalUnbind(".dur")
});
return false
}
}).bind("mouseenter",function () {
d.globalBind("mousemove.dur", function (h) {
p(h)
});
mejs.MediaFeatures.hasTouch || m.show()
}).bind("mouseleave", function () {
if (!t) {
d.globalUnbind(".dur");
m.hide()
}
});
e.addEventListener("progress", function (h) {
a.setProgressRail(h);
a.setCurrentRail(h)
}, false);
e.addEventListener("timeupdate", function (h) {
a.setProgressRail(h);
a.setCurrentRail(h)
}, false);
d.loaded = c;
d.total = g;
d.current = k;
d.handle = j
}, setProgressRail: function (a) {
var b = a != undefined ? a.target : this.media, c = null;
if (b && b.buffered && b.buffered.length > 0 && b.buffered.end && b.duration)c = b.buffered.end(0) / b.duration; else if (b && b.bytesTotal != undefined && b.bytesTotal > 0 && b.bufferedBytes != undefined)c = b.bufferedBytes / b.bytesTotal;
else if (a && a.lengthComputable && a.total != 0)c = a.loaded / a.total;
if (c !== null) {
c = Math.min(1, Math.max(0, c));
this.loaded && this.total && this.loaded.width(this.total.width() * c)
}
}, setCurrentRail: function () {
if (this.media.currentTime != undefined && this.media.duration)if (this.total && this.handle) {
var a = Math.round(this.total.width() * this.media.currentTime / this.media.duration), b = a - Math.round(this.handle.outerWidth(true) / 2);
this.current.width(a);
this.handle.css("left", b)
}
}})
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {duration: -1, timeAndDurationSeparator: "<span> | </span>"});
f.extend(MediaElementPlayer.prototype, {buildcurrent: function (a, b, c, e) {
f('<div class="mejs-time"><span class="mejs-currenttime">' + (a.options.alwaysShowHours ? "00:" : "") + (a.options.showTimecodeFrameCount ? "00:00:00" : "00:00") + "</span></div>").appendTo(b);
this.currenttime = this.controls.find(".mejs-currenttime");
e.addEventListener("timeupdate", function () {
a.updateCurrent()
}, false)
}, buildduration: function (a, b, c, e) {
if (b.children().last().find(".mejs-currenttime").length > 0)f(this.options.timeAndDurationSeparator + '<span class="mejs-duration">' + (this.options.duration > 0 ? mejs.Utility.secondsToTimeCode(this.options.duration, this.options.alwaysShowHours || this.media.duration > 3600, this.options.showTimecodeFrameCount, this.options.framesPerSecond || 25) : (a.options.alwaysShowHours ? "00:" : "") + (a.options.showTimecodeFrameCount ? "00:00:00" : "00:00")) + "</span>").appendTo(b.find(".mejs-time")); else {
b.find(".mejs-currenttime").parent().addClass("mejs-currenttime-container");
f('<div class="mejs-time mejs-duration-container"><span class="mejs-duration">' + (this.options.duration > 0 ? mejs.Utility.secondsToTimeCode(this.options.duration, this.options.alwaysShowHours || this.media.duration > 3600, this.options.showTimecodeFrameCount, this.options.framesPerSecond || 25) : (a.options.alwaysShowHours ? "00:" : "") + (a.options.showTimecodeFrameCount ? "00:00:00" : "00:00")) + "</span></div>").appendTo(b)
}
this.durationD = this.controls.find(".mejs-duration");
e.addEventListener("timeupdate", function () {
a.updateDuration()
},
false)
}, updateCurrent: function () {
if (this.currenttime)this.currenttime.html(mejs.Utility.secondsToTimeCode(this.media.currentTime, this.options.alwaysShowHours || this.media.duration > 3600, this.options.showTimecodeFrameCount, this.options.framesPerSecond || 25))
}, updateDuration: function () {
this.container.toggleClass("mejs-long-video", this.media.duration > 3600);
if (this.durationD && (this.options.duration > 0 || this.media.duration))this.durationD.html(mejs.Utility.secondsToTimeCode(this.options.duration > 0 ? this.options.duration :
this.media.duration, this.options.alwaysShowHours, this.options.showTimecodeFrameCount, this.options.framesPerSecond || 25))
}})
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {muteText: mejs.i18n.t("Mute Toggle"), hideVolumeOnTouchDevices: true, audioVolume: "horizontal", videoVolume: "vertical"});
f.extend(MediaElementPlayer.prototype, {buildvolume: function (a, b, c, e) {
if (!((mejs.MediaFeatures.isAndroid || mejs.MediaFeatures.isiOS) && this.options.hideVolumeOnTouchDevices)) {
var d = this, g = d.isVideo ? d.options.videoVolume : d.options.audioVolume, k = g == "horizontal" ? f('<div class="mejs-button mejs-volume-button mejs-mute"><button type="button" aria-controls="' +
d.id + '" title="' + d.options.muteText + '" aria-label="' + d.options.muteText + '"></button></div><div class="mejs-horizontal-volume-slider"><div class="mejs-horizontal-volume-total"></div><div class="mejs-horizontal-volume-current"></div><div class="mejs-horizontal-volume-handle"></div></div>').appendTo(b) : f('<div class="mejs-button mejs-volume-button mejs-mute"><button type="button" aria-controls="' + d.id + '" title="' + d.options.muteText + '" aria-label="' + d.options.muteText + '"></button><div class="mejs-volume-slider"><div class="mejs-volume-total"></div><div class="mejs-volume-current"></div><div class="mejs-volume-handle"></div></div></div>').appendTo(b),
j = d.container.find(".mejs-volume-slider, .mejs-horizontal-volume-slider"), m = d.container.find(".mejs-volume-total, .mejs-horizontal-volume-total"), q = d.container.find(".mejs-volume-current, .mejs-horizontal-volume-current"), p = d.container.find(".mejs-volume-handle, .mejs-horizontal-volume-handle"), t = function (n, o) {
if (!j.is(":visible") && typeof o == "undefined") {
j.show();
t(n, true);
j.hide()
} else {
n = Math.max(0, n);
n = Math.min(n, 1);
n == 0 ? k.removeClass("mejs-mute").addClass("mejs-unmute") : k.removeClass("mejs-unmute").addClass("mejs-mute");
if (g == "vertical") {
var s = m.height(), u = m.position(), v = s - s * n;
p.css("top", Math.round(u.top + v - p.height() / 2));
q.height(s - v);
q.css("top", u.top + v)
} else {
s = m.width();
u = m.position();
s = s * n;
p.css("left", Math.round(u.left + s - p.width() / 2));
q.width(Math.round(s))
}
}
}, h = function (n) {
var o = null, s = m.offset();
if (g == "vertical") {
o = m.height();
parseInt(m.css("top").replace(/px/, ""), 10);
o = (o - (n.pageY - s.top)) / o;
if (s.top == 0 || s.left == 0)return
} else {
o = m.width();
o = (n.pageX - s.left) / o
}
o = Math.max(0, o);
o = Math.min(o, 1);
t(o);
o == 0 ? e.setMuted(true) :
e.setMuted(false);
e.setVolume(o)
}, l = false, r = false;
k.hover(function () {
j.show();
r = true
}, function () {
r = false;
!l && g == "vertical" && j.hide()
});
j.bind("mouseover",function () {
r = true
}).bind("mousedown", function (n) {
h(n);
d.globalBind("mousemove.vol", function (o) {
h(o)
});
d.globalBind("mouseup.vol", function () {
l = false;
d.globalUnbind(".vol");
!r && g == "vertical" && j.hide()
});
l = true;
return false
});
k.find("button").click(function () {
e.setMuted(!e.muted)
});
e.addEventListener("volumechange", function () {
if (!l)if (e.muted) {
t(0);
k.removeClass("mejs-mute").addClass("mejs-unmute")
} else {
t(e.volume);
k.removeClass("mejs-unmute").addClass("mejs-mute")
}
}, false);
if (d.container.is(":visible")) {
t(a.options.startVolume);
a.options.startVolume === 0 && e.setMuted(true);
e.pluginType === "native" && e.setVolume(a.options.startVolume)
}
}
}})
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {usePluginFullScreen: true, newWindowCallback: function () {
return""
}, fullscreenText: mejs.i18n.t("Fullscreen")});
f.extend(MediaElementPlayer.prototype, {isFullScreen: false, isNativeFullScreen: false, isInIframe: false, buildfullscreen: function (a, b, c, e) {
if (a.isVideo) {
a.isInIframe = window.location != window.parent.location;
if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
c = function () {
if (a.isFullScreen)if (mejs.MediaFeatures.isFullScreen()) {
a.isNativeFullScreen = true;
a.setControlsSize()
} else {
a.isNativeFullScreen =
false;
a.exitFullScreen()
}
};
mejs.MediaFeatures.hasMozNativeFullScreen ? a.globalBind(mejs.MediaFeatures.fullScreenEventName, c) : a.container.bind(mejs.MediaFeatures.fullScreenEventName, c)
}
var d = this, g = f('<div class="mejs-button mejs-fullscreen-button"><button type="button" aria-controls="' + d.id + '" title="' + d.options.fullscreenText + '" aria-label="' + d.options.fullscreenText + '"></button></div>').appendTo(b);
if (d.media.pluginType === "native" || !d.options.usePluginFullScreen && !mejs.MediaFeatures.isFirefox)g.click(function () {
mejs.MediaFeatures.hasTrueNativeFullScreen &&
mejs.MediaFeatures.isFullScreen() || a.isFullScreen ? a.exitFullScreen() : a.enterFullScreen()
}); else {
var k = null;
if (function () {
var h = document.createElement("x"), l = document.documentElement, r = window.getComputedStyle;
if (!("pointerEvents"in h.style))return false;
h.style.pointerEvents = "auto";
h.style.pointerEvents = "x";
l.appendChild(h);
r = r && r(h, "").pointerEvents === "auto";
l.removeChild(h);
return!!r
}() && !mejs.MediaFeatures.isOpera) {
var j = false, m = function () {
if (j) {
for (var h in q)q[h].hide();
g.css("pointer-events",
"");
d.controls.css("pointer-events", "");
d.media.removeEventListener("click", d.clickToPlayPauseCallback);
j = false
}
}, q = {};
b = ["top", "left", "right", "bottom"];
var p, t = function () {
var h = g.offset().left - d.container.offset().left, l = g.offset().top - d.container.offset().top, r = g.outerWidth(true), n = g.outerHeight(true), o = d.container.width(), s = d.container.height();
for (p in q)q[p].css({position: "absolute", top: 0, left: 0});
q.top.width(o).height(l);
q.left.width(h).height(n).css({top: l});
q.right.width(o - h - r).height(n).css({top: l,
left: h + r});
q.bottom.width(o).height(s - n - l).css({top: l + n})
};
d.globalBind("resize", function () {
t()
});
p = 0;
for (c = b.length; p < c; p++)q[b[p]] = f('<div class="mejs-fullscreen-hover" />').appendTo(d.container).mouseover(m).hide();
g.on("mouseover", function () {
if (!d.isFullScreen) {
var h = g.offset(), l = a.container.offset();
e.positionFullscreenButton(h.left - l.left, h.top - l.top, false);
g.css("pointer-events", "none");
d.controls.css("pointer-events", "none");
d.media.addEventListener("click", d.clickToPlayPauseCallback);
for (p in q)q[p].show();
t();
j = true
}
});
e.addEventListener("fullscreenchange", function () {
d.isFullScreen = !d.isFullScreen;
d.isFullScreen ? d.media.removeEventListener("click", d.clickToPlayPauseCallback) : d.media.addEventListener("click", d.clickToPlayPauseCallback);
m()
});
d.globalBind("mousemove", function (h) {
if (j) {
var l = g.offset();
if (h.pageY < l.top || h.pageY > l.top + g.outerHeight(true) || h.pageX < l.left || h.pageX > l.left + g.outerWidth(true)) {
g.css("pointer-events", "");
d.controls.css("pointer-events", "");
j = false
}
}
})
} else g.on("mouseover",
function () {
if (k !== null) {
clearTimeout(k);
delete k
}
var h = g.offset(), l = a.container.offset();
e.positionFullscreenButton(h.left - l.left, h.top - l.top, true)
}).on("mouseout", function () {
if (k !== null) {
clearTimeout(k);
delete k
}
k = setTimeout(function () {
e.hideFullscreenButton()
}, 1500)
})
}
a.fullscreenBtn = g;
d.globalBind("keydown", function (h) {
if ((mejs.MediaFeatures.hasTrueNativeFullScreen && mejs.MediaFeatures.isFullScreen() || d.isFullScreen) && h.keyCode == 27)a.exitFullScreen()
})
}
}, cleanfullscreen: function (a) {
a.exitFullScreen()
},
containerSizeTimeout: null, enterFullScreen: function () {
var a = this;
if (!(a.media.pluginType !== "native" && (mejs.MediaFeatures.isFirefox || a.options.usePluginFullScreen))) {
f(document.documentElement).addClass("mejs-fullscreen");
normalHeight = a.container.height();
normalWidth = a.container.width();
if (a.media.pluginType === "native")if (mejs.MediaFeatures.hasTrueNativeFullScreen) {
mejs.MediaFeatures.requestFullScreen(a.container[0]);
a.isInIframe && setTimeout(function c() {
if (a.isNativeFullScreen) {
var e = (window.devicePixelRatio ||
1) * f(window).width(), d = screen.width;
Math.abs(d - e) > d * 0.0020 ? a.exitFullScreen() : setTimeout(c, 500)
}
}, 500)
} else if (mejs.MediaFeatures.hasSemiNativeFullScreen) {
a.media.webkitEnterFullscreen();
return
}
if (a.isInIframe) {
var b = a.options.newWindowCallback(this);
if (b !== "")if (mejs.MediaFeatures.hasTrueNativeFullScreen)setTimeout(function () {
if (!a.isNativeFullScreen) {
a.pause();
window.open(b, a.id, "top=0,left=0,width=" + screen.availWidth + ",height=" + screen.availHeight + ",resizable=yes,scrollbars=no,status=no,toolbar=no")
}
},
250); else {
a.pause();
window.open(b, a.id, "top=0,left=0,width=" + screen.availWidth + ",height=" + screen.availHeight + ",resizable=yes,scrollbars=no,status=no,toolbar=no");
return
}
}
a.container.addClass("mejs-container-fullscreen").width("100%").height("100%");
a.containerSizeTimeout = setTimeout(function () {
a.container.css({width: "100%", height: "100%"});
a.setControlsSize()
}, 500);
if (a.media.pluginType === "native")a.$media.width("100%").height("100%"); else {
a.container.find(".mejs-shim").width("100%").height("100%");
a.media.setVideoSize(f(window).width(), f(window).height())
}
a.layers.children("div").width("100%").height("100%");
a.fullscreenBtn && a.fullscreenBtn.removeClass("mejs-fullscreen").addClass("mejs-unfullscreen");
a.setControlsSize();
a.isFullScreen = true
}
}, exitFullScreen: function () {
clearTimeout(this.containerSizeTimeout);
if (this.media.pluginType !== "native" && mejs.MediaFeatures.isFirefox)this.media.setFullscreen(false); else {
if (mejs.MediaFeatures.hasTrueNativeFullScreen && (mejs.MediaFeatures.isFullScreen() ||
this.isFullScreen))mejs.MediaFeatures.cancelFullScreen();
f(document.documentElement).removeClass("mejs-fullscreen");
this.container.removeClass("mejs-container-fullscreen").width(normalWidth).height(normalHeight);
if (this.media.pluginType === "native")this.$media.width(normalWidth).height(normalHeight); else {
this.container.find(".mejs-shim").width(normalWidth).height(normalHeight);
this.media.setVideoSize(normalWidth, normalHeight)
}
this.layers.children("div").width(normalWidth).height(normalHeight);
this.fullscreenBtn.removeClass("mejs-unfullscreen").addClass("mejs-fullscreen");
this.setControlsSize();
this.isFullScreen = false
}
}})
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {startLanguage: "", tracksText: mejs.i18n.t("Captions/Subtitles"), hideCaptionsButtonWhenEmpty: true, toggleCaptionsButtonWhenOnlyOne: false, slidesSelector: ""});
f.extend(MediaElementPlayer.prototype, {hasChapters: false, buildtracks: function (a, b, c, e) {
if (a.tracks.length != 0) {
var d;
if (this.domNode.textTracks)for (d = this.domNode.textTracks.length - 1; d >= 0; d--)this.domNode.textTracks[d].mode = "hidden";
a.chapters = f('<div class="mejs-chapters mejs-layer"></div>').prependTo(c).hide();
a.captions =
f('<div class="mejs-captions-layer mejs-layer"><div class="mejs-captions-position mejs-captions-position-hover"><span class="mejs-captions-text"></span></div></div>').prependTo(c).hide();
a.captionsText = a.captions.find(".mejs-captions-text");
a.captionsButton = f('<div class="mejs-button mejs-captions-button"><button type="button" aria-controls="' + this.id + '" title="' + this.options.tracksText + '" aria-label="' + this.options.tracksText + '"></button><div class="mejs-captions-selector"><ul><li><input type="radio" name="' +
a.id + '_captions" id="' + a.id + '_captions_none" value="none" checked="checked" /><label for="' + a.id + '_captions_none">' + mejs.i18n.t("None") + "</label></li></ul></div></div>").appendTo(b);
for (d = b = 0; d < a.tracks.length; d++)a.tracks[d].kind == "subtitles" && b++;
this.options.toggleCaptionsButtonWhenOnlyOne && b == 1 ? a.captionsButton.on("click", function () {
a.setTrack(a.selectedTrack == null ? a.tracks[0].srclang : "none")
}) : a.captionsButton.hover(function () {
f(this).find(".mejs-captions-selector").css("visibility", "visible")
},
function () {
f(this).find(".mejs-captions-selector").css("visibility", "hidden")
}).on("click", "input[type=radio]", function () {
lang = this.value;
a.setTrack(lang)
});
a.options.alwaysShowControls ? a.container.find(".mejs-captions-position").addClass("mejs-captions-position-hover") : a.container.bind("controlsshown",function () {
a.container.find(".mejs-captions-position").addClass("mejs-captions-position-hover")
}).bind("controlshidden", function () {
e.paused || a.container.find(".mejs-captions-position").removeClass("mejs-captions-position-hover")
});
a.trackToLoad = -1;
a.selectedTrack = null;
a.isLoadingTrack = false;
for (d = 0; d < a.tracks.length; d++)a.tracks[d].kind == "subtitles" && a.addTrackButton(a.tracks[d].srclang, a.tracks[d].label);
a.loadNextTrack();
e.addEventListener("timeupdate", function () {
a.displayCaptions()
}, false);
if (a.options.slidesSelector != "") {
a.slidesContainer = f(a.options.slidesSelector);
e.addEventListener("timeupdate", function () {
a.displaySlides()
}, false)
}
e.addEventListener("loadedmetadata", function () {
a.displayChapters()
}, false);
a.container.hover(function () {
if (a.hasChapters) {
a.chapters.css("visibility",
"visible");
a.chapters.fadeIn(200).height(a.chapters.find(".mejs-chapter").outerHeight())
}
}, function () {
a.hasChapters && !e.paused && a.chapters.fadeOut(200, function () {
f(this).css("visibility", "hidden");
f(this).css("display", "block")
})
});
a.node.getAttribute("autoplay") !== null && a.chapters.css("visibility", "hidden")
}
}, setTrack: function (a) {
var b;
if (a == "none") {
this.selectedTrack = null;
this.captionsButton.removeClass("mejs-captions-enabled")
} else for (b = 0; b < this.tracks.length; b++)if (this.tracks[b].srclang == a) {
this.selectedTrack ==
null && this.captionsButton.addClass("mejs-captions-enabled");
this.selectedTrack = this.tracks[b];
this.captions.attr("lang", this.selectedTrack.srclang);
this.displayCaptions();
break
}
}, loadNextTrack: function () {
this.trackToLoad++;
if (this.trackToLoad < this.tracks.length) {
this.isLoadingTrack = true;
this.loadTrack(this.trackToLoad)
} else {
this.isLoadingTrack = false;
this.checkForTracks()
}
}, loadTrack: function (a) {
var b = this, c = b.tracks[a];
f.ajax({url: c.src, dataType: "text", success: function (e) {
c.entries = typeof e == "string" &&
/<tt\s+xml/ig.exec(e) ? mejs.TrackFormatParser.dfxp.parse(e) : mejs.TrackFormatParser.webvvt.parse(e);
c.isLoaded = true;
b.enableTrackButton(c.srclang, c.label);
b.loadNextTrack();
c.kind == "chapters" && b.media.addEventListener("play", function () {
b.media.duration > 0 && b.displayChapters(c)
}, false);
c.kind == "slides" && b.setupSlides(c)
}, error: function () {
b.loadNextTrack()
}})
}, enableTrackButton: function (a, b) {
if (b === "")b = mejs.language.codes[a] || a;
this.captionsButton.find("input[value=" + a + "]").prop("disabled", false).siblings("label").html(b);
this.options.startLanguage == a && f("#" + this.id + "_captions_" + a).click();
this.adjustLanguageBox()
}, addTrackButton: function (a, b) {
if (b === "")b = mejs.language.codes[a] || a;
this.captionsButton.find("ul").append(f('<li><input type="radio" name="' + this.id + '_captions" id="' + this.id + "_captions_" + a + '" value="' + a + '" disabled="disabled" /><label for="' + this.id + "_captions_" + a + '">' + b + " (loading)</label></li>"));
this.adjustLanguageBox();
this.container.find(".mejs-captions-translations option[value=" + a + "]").remove()
},
adjustLanguageBox: function () {
this.captionsButton.find(".mejs-captions-selector").height(this.captionsButton.find(".mejs-captions-selector ul").outerHeight(true) + this.captionsButton.find(".mejs-captions-translations").outerHeight(true))
}, checkForTracks: function () {
var a = false;
if (this.options.hideCaptionsButtonWhenEmpty) {
for (i = 0; i < this.tracks.length; i++)if (this.tracks[i].kind == "subtitles") {
a = true;
break
}
if (!a) {
this.captionsButton.hide();
this.setControlsSize()
}
}
}, displayCaptions: function () {
if (typeof this.tracks !=
"undefined") {
var a, b = this.selectedTrack;
if (b != null && b.isLoaded)for (a = 0; a < b.entries.times.length; a++)if (this.media.currentTime >= b.entries.times[a].start && this.media.currentTime <= b.entries.times[a].stop) {
this.captionsText.html(b.entries.text[a]);
this.captions.show().height(0);
return
}
this.captions.hide()
}
}, setupSlides: function (a) {
this.slides = a;
this.slides.entries.imgs = [this.slides.entries.text.length];
this.showSlide(0)
}, showSlide: function (a) {
if (!(typeof this.tracks == "undefined" || typeof this.slidesContainer ==
"undefined")) {
var b = this, c = b.slides.entries.text[a], e = b.slides.entries.imgs[a];
if (typeof e == "undefined" || typeof e.fadeIn == "undefined")b.slides.entries.imgs[a] = e = f('<img src="' + c + '">').on("load", function () {
e.appendTo(b.slidesContainer).hide().fadeIn().siblings(":visible").fadeOut()
}); else!e.is(":visible") && !e.is(":animated") && e.fadeIn().siblings(":visible").fadeOut()
}
}, displaySlides: function () {
if (typeof this.slides != "undefined") {
var a = this.slides, b;
for (b = 0; b < a.entries.times.length; b++)if (this.media.currentTime >=
a.entries.times[b].start && this.media.currentTime <= a.entries.times[b].stop) {
this.showSlide(b);
break
}
}
}, displayChapters: function () {
var a;
for (a = 0; a < this.tracks.length; a++)if (this.tracks[a].kind == "chapters" && this.tracks[a].isLoaded) {
this.drawChapters(this.tracks[a]);
this.hasChapters = true;
break
}
}, drawChapters: function (a) {
var b = this, c, e, d = e = 0;
b.chapters.empty();
for (c = 0; c < a.entries.times.length; c++) {
e = a.entries.times[c].stop - a.entries.times[c].start;
e = Math.floor(e / b.media.duration * 100);
if (e + d > 100 || c == a.entries.times.length -
1 && e + d < 100)e = 100 - d;
b.chapters.append(f('<div class="mejs-chapter" rel="' + a.entries.times[c].start + '" style="left: ' + d.toString() + "%;width: " + e.toString() + '%;"><div class="mejs-chapter-block' + (c == a.entries.times.length - 1 ? " mejs-chapter-block-last" : "") + '"><span class="ch-title">' + a.entries.text[c] + '</span><span class="ch-time">' + mejs.Utility.secondsToTimeCode(a.entries.times[c].start) + "–" + mejs.Utility.secondsToTimeCode(a.entries.times[c].stop) + "</span></div></div>"));
d += e
}
b.chapters.find("div.mejs-chapter").click(function () {
b.media.setCurrentTime(parseFloat(f(this).attr("rel")));
b.media.paused && b.media.play()
});
b.chapters.show()
}});
mejs.language = {codes: {af: "Afrikaans", sq: "Albanian", ar: "Arabic", be: "Belarusian", bg: "Bulgarian", ca: "Catalan", zh: "Chinese", "zh-cn": "Chinese Simplified", "zh-tw": "Chinese Traditional", hr: "Croatian", cs: "Czech", da: "Danish", nl: "Dutch", en: "English", et: "Estonian", tl: "Filipino", fi: "Finnish", fr: "French", gl: "Galician", de: "German", el: "Greek", ht: "Haitian Creole", iw: "Hebrew", hi: "Hindi", hu: "Hungarian", is: "Icelandic", id: "Indonesian", ga: "Irish", it: "Italian", ja: "Japanese",
ko: "Korean", lv: "Latvian", lt: "Lithuanian", mk: "Macedonian", ms: "Malay", mt: "Maltese", no: "Norwegian", fa: "Persian", pl: "Polish", pt: "Portuguese", ro: "Romanian", ru: "Russian", sr: "Serbian", sk: "Slovak", sl: "Slovenian", es: "Spanish", sw: "Swahili", sv: "Swedish", tl: "Tagalog", th: "Thai", tr: "Turkish", uk: "Ukrainian", vi: "Vietnamese", cy: "Welsh", yi: "Yiddish"}};
mejs.TrackFormatParser = {webvvt: {pattern_identifier: /^([a-zA-z]+-)?[0-9]+$/, pattern_timecode: /^([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{1,3})?) --\> ([0-9]{2}:[0-9]{2}:[0-9]{2}([,.][0-9]{3})?)(.*)$/,
parse: function (a) {
var b = 0;
a = mejs.TrackFormatParser.split2(a, /\r?\n/);
for (var c = {text: [], times: []}, e, d; b < a.length; b++)if (this.pattern_identifier.exec(a[b])) {
b++;
if ((e = this.pattern_timecode.exec(a[b])) && b < a.length) {
b++;
d = a[b];
for (b++; a[b] !== "" && b < a.length;) {
d = d + "\n" + a[b];
b++
}
d = f.trim(d).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig, "<a href='$1' target='_blank'>$1</a>");
c.text.push(d);
c.times.push({start: mejs.Utility.convertSMPTEtoSeconds(e[1]) == 0 ? 0.2 : mejs.Utility.convertSMPTEtoSeconds(e[1]),
stop: mejs.Utility.convertSMPTEtoSeconds(e[3]), settings: e[5]})
}
}
return c
}}, dfxp: {parse: function (a) {
a = f(a).filter("tt");
var b = 0;
b = a.children("div").eq(0);
var c = b.find("p");
b = a.find("#" + b.attr("style"));
var e, d;
a = {text: [], times: []};
if (b.length) {
d = b.removeAttr("id").get(0).attributes;
if (d.length) {
e = {};
for (b = 0; b < d.length; b++)e[d[b].name.split(":")[1]] = d[b].value
}
}
for (b = 0; b < c.length; b++) {
var g;
d = {start: null, stop: null, style: null};
if (c.eq(b).attr("begin"))d.start = mejs.Utility.convertSMPTEtoSeconds(c.eq(b).attr("begin"));
if (!d.start && c.eq(b - 1).attr("end"))d.start = mejs.Utility.convertSMPTEtoSeconds(c.eq(b - 1).attr("end"));
if (c.eq(b).attr("end"))d.stop = mejs.Utility.convertSMPTEtoSeconds(c.eq(b).attr("end"));
if (!d.stop && c.eq(b + 1).attr("begin"))d.stop = mejs.Utility.convertSMPTEtoSeconds(c.eq(b + 1).attr("begin"));
if (e) {
g = "";
for (var k in e)g += k + ":" + e[k] + ";"
}
if (g)d.style = g;
if (d.start == 0)d.start = 0.2;
a.times.push(d);
d = f.trim(c.eq(b).html()).replace(/(\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[-A-Z0-9+&@#\/%=~_|])/ig,
"<a href='$1' target='_blank'>$1</a>");
a.text.push(d);
if (a.times.start == 0)a.times.start = 2
}
return a
}}, split2: function (a, b) {
return a.split(b)
}};
if ("x\n\ny".split(/\n/gi).length != 3)mejs.TrackFormatParser.split2 = function (a, b) {
var c = [], e = "", d;
for (d = 0; d < a.length; d++) {
e += a.substring(d, d + 1);
if (b.test(e)) {
c.push(e.replace(b, ""));
e = ""
}
}
c.push(e);
return c
}
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {contextMenuItems: [
{render: function (a) {
if (typeof a.enterFullScreen == "undefined")return null;
return a.isFullScreen ? mejs.i18n.t("Turn off Fullscreen") : mejs.i18n.t("Go Fullscreen")
}, click: function (a) {
a.isFullScreen ? a.exitFullScreen() : a.enterFullScreen()
}},
{render: function (a) {
return a.media.muted ? mejs.i18n.t("Unmute") : mejs.i18n.t("Mute")
}, click: function (a) {
a.media.muted ? a.setMuted(false) : a.setMuted(true)
}},
{isSeparator: true},
{render: function () {
return mejs.i18n.t("Download Video")
},
click: function (a) {
window.location.href = a.media.currentSrc
}}
]});
f.extend(MediaElementPlayer.prototype, {buildcontextmenu: function (a) {
a.contextMenu = f('<div class="mejs-contextmenu"></div>').appendTo(f("body")).hide();
a.container.bind("contextmenu", function (b) {
if (a.isContextMenuEnabled) {
b.preventDefault();
a.renderContextMenu(b.clientX - 1, b.clientY - 1);
return false
}
});
a.container.bind("click", function () {
a.contextMenu.hide()
});
a.contextMenu.bind("mouseleave", function () {
a.startContextMenuTimer()
})
}, cleancontextmenu: function (a) {
a.contextMenu.remove()
},
isContextMenuEnabled: true, enableContextMenu: function () {
this.isContextMenuEnabled = true
}, disableContextMenu: function () {
this.isContextMenuEnabled = false
}, contextMenuTimeout: null, startContextMenuTimer: function () {
var a = this;
a.killContextMenuTimer();
a.contextMenuTimer = setTimeout(function () {
a.hideContextMenu();
a.killContextMenuTimer()
}, 750)
}, killContextMenuTimer: function () {
var a = this.contextMenuTimer;
if (a != null) {
clearTimeout(a);
delete a
}
}, hideContextMenu: function () {
this.contextMenu.hide()
}, renderContextMenu: function (a, b) {
for (var c = this, e = "", d = c.options.contextMenuItems, g = 0, k = d.length; g < k; g++)if (d[g].isSeparator)e += '<div class="mejs-contextmenu-separator"></div>'; else {
var j = d[g].render(c);
if (j != null)e += '<div class="mejs-contextmenu-item" data-itemindex="' + g + '" id="element-' + Math.random() * 1E6 + '">' + j + "</div>"
}
c.contextMenu.empty().append(f(e)).css({top: b, left: a}).show();
c.contextMenu.find(".mejs-contextmenu-item").each(function () {
var m = f(this), q = parseInt(m.data("itemindex"), 10), p = c.options.contextMenuItems[q];
typeof p.show !=
"undefined" && p.show(m, c);
m.click(function () {
typeof p.click != "undefined" && p.click(c);
c.contextMenu.hide()
})
});
setTimeout(function () {
c.killControlsTimer("rev3")
}, 100)
}})
})(mejs.$);
(function (f) {
f.extend(mejs.MepDefaults, {postrollCloseText: mejs.i18n.t("Close")});
f.extend(MediaElementPlayer.prototype, {buildpostroll: function (a, b, c) {
var e = this.container.find('link[rel="postroll"]').attr("href");
if (typeof e !== "undefined") {
a.postroll = f('<div class="mejs-postroll-layer mejs-layer"><a class="mejs-postroll-close" onclick="$(this).parent().hide();return false;">' + this.options.postrollCloseText + '</a><div class="mejs-postroll-layer-content"></div></div>').prependTo(c).hide();
this.media.addEventListener("ended",
function () {
f.ajax({dataType: "html", url: e, success: function (d) {
c.find(".mejs-postroll-layer-content").html(d)
}});
a.postroll.show()
}, false)
}
}})
})(mejs.$);
|
glibey/vogroup.com
|
wp-content/plugins/vogroup-employees/libs/jquery.mediaelementplayer/mediaelementplayer.min.js
|
JavaScript
|
gpl-2.0
| 69,211 |
{% extends "pbspy/base.html" %}
{% load i18n %}
{% block content %}
<p>{% trans "You are now registered. An activation email with instructions to activate your account was sent." %}</p>
{% endblock %}
|
Zulan/PBStats
|
civdj/pbspy/templates/registration/registration_complete.html
|
HTML
|
gpl-2.0
| 200 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2021 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
}
*/
#include "CalculationThread.hpp"
#include "Computer/GlideComputer.hpp"
#include "Protection.hpp"
#include "Blackboard/DeviceBlackboard.hpp"
#include "Components.hpp"
#include "Hardware/CPU.hpp"
/**
* Constructor of the CalculationThread class
* @param _glide_computer The GlideComputer used for the CalculationThread
*/
CalculationThread::CalculationThread(GlideComputer &_glide_computer)
:WorkerThread("CalcThread",
#ifdef KOBO
/* throttle more on the Kobo, because the EPaper
screen cannot be updated that often */
std::chrono::milliseconds{900},
#else
std::chrono::milliseconds{450},
#endif
std::chrono::milliseconds{100},
std::chrono::milliseconds{50}),
force(false),
glide_computer(_glide_computer) {
}
void
CalculationThread::SetComputerSettings(const ComputerSettings &new_value)
{
std::lock_guard<Mutex> lock(mutex);
settings_computer = new_value;
}
void
CalculationThread::SetScreenDistanceMeters(double new_value)
{
std::lock_guard<Mutex> lock(mutex);
screen_distance_meters = new_value;
}
/**
* Main loop of the CalculationThread
*/
void
CalculationThread::Tick() noexcept
{
#ifdef HAVE_CPU_FREQUENCY
const ScopeLockCPU cpu;
#endif
bool gps_updated;
// update and transfer master info to glide computer
{
std::lock_guard<Mutex> lock(device_blackboard->mutex);
gps_updated = device_blackboard->Basic().location_available.Modified(glide_computer.Basic().location_available);
// Copy data from DeviceBlackboard to GlideComputerBlackboard
glide_computer.ReadBlackboard(device_blackboard->Basic());
}
bool force;
{
std::lock_guard<Mutex> lock(mutex);
// Copy settings from ComputerSettingsBlackboard to GlideComputerBlackboard
glide_computer.ReadComputerSettings(settings_computer);
force = this->force;
if (force) {
this->force = false;
gps_updated = true;
}
}
glide_computer.Expire();
bool do_idle = false;
if (gps_updated || force)
// perform idle call if time advanced and slow calculations need to be updated
do_idle |= glide_computer.ProcessGPS(force);
// values changed, so copy them back now: ONLY CALCULATED INFO
// should be changed in DoCalculations, so we only need to write
// that one back (otherwise we may write over new data)
{
std::lock_guard<Mutex> lock(device_blackboard->mutex);
device_blackboard->ReadBlackboard(glide_computer.Calculated());
}
// if (new GPS data)
if (gps_updated || force)
// inform map new data is ready
TriggerCalculatedUpdate();
if (do_idle) {
// do slow calculations last, to minimise latency
glide_computer.ProcessIdle();
}
}
void
CalculationThread::ForceTrigger()
{
{
std::lock_guard<Mutex> lock(mutex);
force = true;
}
WorkerThread::Trigger();
}
|
Exadios/xcsoar-exp
|
src/CalculationThread.cpp
|
C++
|
gpl-2.0
| 3,775 |
/*
* Copyright 2015, Red Hat, Inc. and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.zanata.util;
import java.lang.annotation.Annotation;
import java.util.Optional;
import javax.naming.NamingException;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public interface IServiceLocator {
/**
* Returns a BeanHolder for the relevant CDI bean, which must be
* closed when no longer needed (eg end of the calling method).
* This is necessary for correct lifecycle management of dependent
* beans. Destroying a BeanHolder for a non-dependent bean is
* a no-op.
* @param clazz
* @param qualifiers
* @param <T>
* @return
*/
<T> BeanHolder<T> getDependent(Class<T> clazz,
Annotation... qualifiers);
/**
* Resolves a bean by type and qualifiers
* @param clazz type of the requested bean
* @param qualifiers additional qualifiers to distinguish the bean type
* @param <T> bean type
* @return the resolved bean
* @throws IllegalStateException if the bean could not be found.
*/
<T> T getInstance(Class<T> clazz, Annotation... qualifiers);
<T> Optional<T> getOptionalInstance(Class<T> clazz, Annotation... qualifiers);
EntityManager getEntityManager();
EntityManagerFactory getEntityManagerFactory();
<T> T getJndiComponent(String jndiName, Class<T> clazz)
throws NamingException;
}
|
mvehar/zanata-server
|
zanata-war/src/main/java/org/zanata/util/IServiceLocator.java
|
Java
|
gpl-2.0
| 2,364 |
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Dimitry Polivaev
*
* This file author is Dimitry Polivaev
*
* 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, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.view.swing.features.time.mindmapmode;
import javax.swing.ComboBoxEditor;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.DefaultListModel;
import javax.swing.ListCellRenderer;
import javax.swing.ListModel;
import org.freeplane.core.resources.TranslatedObject;
import org.freeplane.core.util.LogUtils;
import org.freeplane.core.util.TextUtils;
import org.freeplane.features.filter.condition.ASelectableCondition;
import org.freeplane.features.filter.condition.IElementaryConditionController;
import org.freeplane.features.format.FormattedDate;
import org.freeplane.features.format.IFormattedObject;
import org.freeplane.features.time.TimeComboBoxEditor;
import org.freeplane.n3.nanoxml.XMLElement;
/**
* @author Dimitry Polivaev
* 21.12.2008
*/
public class ReminderConditionController implements IElementaryConditionController {
static final String FILTER_REMINDER = "filter_reminder";
private final ComboBoxEditor editor = new TimeComboBoxEditor(true);
private final ComboBoxModel values = new DefaultComboBoxModel();
public ReminderConditionController() {
super();
}
public boolean canEditValues(final Object property, final TranslatedObject simpleCond) {
return true;
}
public boolean canHandle(final Object selectedItem) {
if (!(selectedItem instanceof TranslatedObject)) {
return false;
}
final TranslatedObject namedObject = (TranslatedObject) selectedItem;
return namedObject.objectEquals(ReminderConditionController.FILTER_REMINDER);
}
public boolean canSelectValues(final Object property, final TranslatedObject simpleCond) {
if(simpleCond.objectEquals(ReminderConditionLater.FILTER_REMINDER_LATER))
return false;
if(simpleCond.objectEquals(ReminderConditionExecuted.FILTER_REMINDER_EXECUTED))
return false;
return true;
}
public ASelectableCondition createCondition(final Object selectedItem, final TranslatedObject simpleCond,
final Object value, final boolean matchCase,
final boolean matchApproximately) {
return ReminderConditionController.create(simpleCond, (FormattedDate) value);
}
public ComboBoxModel getConditionsForProperty(final Object property) {
return new DefaultComboBoxModel(getTimeConditionNames());
}
public ListModel getFilteredProperties() {
final DefaultListModel list = new DefaultListModel();
list.addElement(TextUtils.createTranslatedString(FILTER_REMINDER));
return list;
}
public Object[] getTimeConditionNames() {
return new TranslatedObject[] {
TextUtils.createTranslatedString(ReminderConditionLater.FILTER_REMINDER_LATER),
TextUtils.createTranslatedString(ReminderConditionExecuted.FILTER_REMINDER_EXECUTED),
TextUtils.createTranslatedString(ReminderCondition.FILTER_REMINDER_AFTER),
TextUtils.createTranslatedString(ReminderCondition.FILTER_REMINDER_BEFORE) };
}
public ComboBoxEditor getValueEditor(Object selectedProperty, TranslatedObject selectedCondition) {
return editor;
}
public ComboBoxModel getValuesForProperty(final Object selectedItem, TranslatedObject simpleCond) {
values.setSelectedItem(FormattedDate.createDefaultFormattedDate(System.currentTimeMillis(), IFormattedObject.TYPE_DATETIME));
return values;
}
public boolean isCaseDependent(final Object property, final TranslatedObject simpleCond) {
return false;
}
public boolean supportsApproximateMatching(final Object property, final TranslatedObject simpleCond) {
return false;
}
public ASelectableCondition loadCondition(final XMLElement element) {
try {
if (element.getName().equalsIgnoreCase(ReminderConditionLater.NAME)) {
return new ReminderConditionLater();
}
if (element.getName().equalsIgnoreCase(ReminderConditionExecuted.NAME)) {
return new ReminderConditionExecuted();
}
if (element.getName().equalsIgnoreCase(ReminderConditionBefore.NAME)) {
final String dateString = element.getAttribute(ReminderCondition.DATE, null);
final FormattedDate date = FormattedDate.createDefaultFormattedDate(Long.parseLong(dateString), IFormattedObject.TYPE_DATETIME);
return new ReminderConditionBefore(date);
}
if (element.getName().equalsIgnoreCase(ReminderConditionAfter.NAME)) {
final String dateString = element.getAttribute(ReminderCondition.DATE, null);
final FormattedDate date = FormattedDate.createDefaultFormattedDate(Long.parseLong(dateString), IFormattedObject.TYPE_DATETIME);
return new ReminderConditionAfter(date);
}
}
catch (final Exception e) {
LogUtils.severe(e);
}
return null;
}
public ListCellRenderer getValueRenderer(Object selectedProperty, TranslatedObject selectedCondition) {
return null;
}
public static ASelectableCondition create(final TranslatedObject simpleCond, final FormattedDate date) {
if (simpleCond.objectEquals(ReminderConditionLater.FILTER_REMINDER_LATER)) {
return new ReminderConditionLater();
}
if (simpleCond.objectEquals(ReminderConditionExecuted.FILTER_REMINDER_EXECUTED)) {
return new ReminderConditionExecuted();
}
if (simpleCond.objectEquals(ReminderCondition.FILTER_REMINDER_AFTER)) {
return new ReminderConditionAfter(date);
}
if (simpleCond.objectEquals(ReminderCondition.FILTER_REMINDER_BEFORE)) {
return new ReminderConditionBefore(date);
}
return null;
}
}
|
fnatter/freeplane-debian-dev
|
freeplane/src/main/java/org/freeplane/view/swing/features/time/mindmapmode/ReminderConditionController.java
|
Java
|
gpl-2.0
| 6,250 |
cmd_fs/splice.o := /opt/buildroot-gcc342/bin/mipsel-linux-uclibc-gcc -Wp,-MD,fs/.splice.o.d -nostdinc -isystem /root/asuswrt-bender/tools/brcm/K26/hndtools-mipsel-uclibc-4.2.4/bin/../lib/gcc/mipsel-linux-uclibc/4.2.4/include -D__KERNEL__ -Iinclude -include include/linux/autoconf.h -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -fno-strict-aliasing -fno-common -O2 -mabi=32 -G 0 -mno-abicalls -fno-pic -pipe -msoft-float -ffreestanding -march=mips32r2 -Wa,-mips32r2 -Wa,--trap -Iinclude/asm-mips/rt2880 -Iinclude/asm-mips/mach-generic -fomit-frame-pointer -gdwarf-2 -fno-stack-protector -membedded-data -muninit-const-in-rodata -funit-at-a-time -Wdeclaration-after-statement -Wno-pointer-sign -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(splice)" -D"KBUILD_MODNAME=KBUILD_STR(splice)" -c -o fs/splice.o fs/splice.c
deps_fs/splice.o := \
fs/splice.c \
include/linux/fs.h \
$(wildcard include/config/dnotify.h) \
$(wildcard include/config/sysfs.h) \
$(wildcard include/config/smp.h) \
$(wildcard include/config/quota.h) \
$(wildcard include/config/inotify.h) \
$(wildcard include/config/security.h) \
$(wildcard include/config/preempt.h) \
$(wildcard include/config/epoll.h) \
$(wildcard include/config/auditsyscall.h) \
$(wildcard include/config/block.h) \
$(wildcard include/config/fs/xip.h) \
$(wildcard include/config/migration.h) \
include/linux/limits.h \
include/linux/ioctl.h \
include/asm/ioctl.h \
include/linux/linkage.h \
include/asm/linkage.h \
include/linux/wait.h \
$(wildcard include/config/lockdep.h) \
include/linux/list.h \
$(wildcard include/config/debug/list.h) \
include/linux/stddef.h \
include/linux/compiler.h \
$(wildcard include/config/enable/must/check.h) \
include/linux/compiler-gcc4.h \
$(wildcard include/config/forced/inlining.h) \
include/linux/compiler-gcc.h \
include/linux/poison.h \
include/linux/prefetch.h \
include/linux/types.h \
$(wildcard include/config/uid16.h) \
$(wildcard include/config/lbd.h) \
$(wildcard include/config/lsf.h) \
$(wildcard include/config/resources/64bit.h) \
include/linux/posix_types.h \
include/asm/posix_types.h \
include/asm/sgidefs.h \
include/asm/types.h \
$(wildcard include/config/highmem.h) \
$(wildcard include/config/64bit/phys/addr.h) \
$(wildcard include/config/64bit.h) \
include/asm/processor.h \
$(wildcard include/config/32bit.h) \
$(wildcard include/config/mips/mt/fpaff.h) \
$(wildcard include/config/cpu/has/prefetch.h) \
include/linux/cpumask.h \
$(wildcard include/config/hotplug/cpu.h) \
include/linux/kernel.h \
$(wildcard include/config/preempt/voluntary.h) \
$(wildcard include/config/debug/spinlock/sleep.h) \
$(wildcard include/config/printk.h) \
$(wildcard include/config/numa.h) \
/root/asuswrt-bender/tools/brcm/K26/hndtools-mipsel-uclibc-4.2.4/bin/../lib/gcc/mipsel-linux-uclibc/4.2.4/include/stdarg.h \
include/linux/bitops.h \
include/asm/bitops.h \
$(wildcard include/config/cpu/mipsr2.h) \
$(wildcard include/config/cpu/mips32.h) \
$(wildcard include/config/cpu/mips64.h) \
include/linux/irqflags.h \
$(wildcard include/config/trace/irqflags.h) \
$(wildcard include/config/trace/irqflags/support.h) \
$(wildcard include/config/x86.h) \
include/asm/irqflags.h \
$(wildcard include/config/mips/mt/smtc.h) \
$(wildcard include/config/irq/cpu.h) \
$(wildcard include/config/mips/mt/smtc/instant/replay.h) \
include/asm/hazards.h \
$(wildcard include/config/cpu/r10000.h) \
$(wildcard include/config/cpu/rm9000.h) \
$(wildcard include/config/cpu/sb1.h) \
include/asm/barrier.h \
$(wildcard include/config/cpu/has/sync.h) \
$(wildcard include/config/cpu/has/wb.h) \
$(wildcard include/config/weak/ordering.h) \
include/asm/bug.h \
$(wildcard include/config/bug.h) \
include/asm/break.h \
include/asm-generic/bug.h \
$(wildcard include/config/generic/bug.h) \
$(wildcard include/config/debug/bugverbose.h) \
include/asm/byteorder.h \
$(wildcard include/config/cpu/mips64/r2.h) \
include/linux/byteorder/little_endian.h \
include/linux/byteorder/swab.h \
include/linux/byteorder/generic.h \
include/asm/cpu-features.h \
$(wildcard include/config/cpu/mipsr2/irq/vi.h) \
$(wildcard include/config/cpu/mipsr2/irq/ei.h) \
include/asm/cpu.h \
include/asm/cpu-info.h \
$(wildcard include/config/sgi/ip27.h) \
$(wildcard include/config/mips/mt.h) \
include/asm/cache.h \
$(wildcard include/config/mips/l1/cache/shift.h) \
include/asm-mips/mach-generic/kmalloc.h \
$(wildcard include/config/dma/coherent.h) \
include/asm-mips/mach-generic/cpu-feature-overrides.h \
include/asm/war.h \
$(wildcard include/config/sgi/ip22.h) \
$(wildcard include/config/sni/rm.h) \
$(wildcard include/config/cpu/r5432.h) \
$(wildcard include/config/sb1/pass/1/workarounds.h) \
$(wildcard include/config/sb1/pass/2/workarounds.h) \
$(wildcard include/config/mips/malta.h) \
$(wildcard include/config/mips/atlas.h) \
$(wildcard include/config/mips/sead.h) \
$(wildcard include/config/cpu/tx49xx.h) \
$(wildcard include/config/momenco/jaguar/atx.h) \
$(wildcard include/config/pmc/yosemite.h) \
$(wildcard include/config/basler/excite.h) \
$(wildcard include/config/momenco/ocelot/3.h) \
include/asm-generic/bitops/non-atomic.h \
include/asm-generic/bitops/fls64.h \
include/asm-generic/bitops/ffz.h \
include/asm-generic/bitops/find.h \
include/asm-generic/bitops/sched.h \
include/asm-generic/bitops/hweight.h \
include/asm-generic/bitops/ext2-non-atomic.h \
include/asm-generic/bitops/le.h \
include/asm-generic/bitops/ext2-atomic.h \
include/asm-generic/bitops/minix.h \
include/linux/log2.h \
$(wildcard include/config/arch/has/ilog2/u32.h) \
$(wildcard include/config/arch/has/ilog2/u64.h) \
include/linux/threads.h \
$(wildcard include/config/nr/cpus.h) \
$(wildcard include/config/base/small.h) \
include/linux/bitmap.h \
include/linux/string.h \
include/asm/string.h \
$(wildcard include/config/cpu/r3000.h) \
include/asm/cachectl.h \
include/asm/mipsregs.h \
$(wildcard include/config/cpu/vr41xx.h) \
$(wildcard include/config/page/size/4kb.h) \
$(wildcard include/config/page/size/16kb.h) \
$(wildcard include/config/page/size/64kb.h) \
include/asm/prefetch.h \
include/asm/system.h \
include/asm/addrspace.h \
$(wildcard include/config/cpu/r4300.h) \
$(wildcard include/config/cpu/r4x00.h) \
$(wildcard include/config/cpu/r5000.h) \
$(wildcard include/config/cpu/rm7000.h) \
$(wildcard include/config/cpu/nevada.h) \
$(wildcard include/config/cpu/r8000.h) \
$(wildcard include/config/cpu/sb1a.h) \
include/asm-mips/mach-generic/spaces.h \
$(wildcard include/config/dma/noncoherent.h) \
include/asm/dsp.h \
include/linux/spinlock.h \
$(wildcard include/config/debug/spinlock.h) \
$(wildcard include/config/debug/lock/alloc.h) \
include/linux/preempt.h \
$(wildcard include/config/debug/preempt.h) \
include/linux/thread_info.h \
include/asm/thread_info.h \
$(wildcard include/config/page/size/8kb.h) \
$(wildcard include/config/debug/stack/usage.h) \
include/linux/stringify.h \
include/linux/bottom_half.h \
include/linux/spinlock_types.h \
include/linux/lockdep.h \
$(wildcard include/config/generic/hardirqs.h) \
$(wildcard include/config/prove/locking.h) \
include/linux/spinlock_types_up.h \
include/linux/spinlock_up.h \
include/linux/spinlock_api_up.h \
include/asm/atomic.h \
include/asm-generic/atomic.h \
include/asm/current.h \
include/linux/kdev_t.h \
include/linux/dcache.h \
$(wildcard include/config/profiling.h) \
include/linux/cache.h \
$(wildcard include/config/arch/has/cache/line/size.h) \
include/linux/rcupdate.h \
include/linux/percpu.h \
include/linux/slab.h \
$(wildcard include/config/slab/debug.h) \
$(wildcard include/config/slub.h) \
$(wildcard include/config/slob.h) \
$(wildcard include/config/debug/slab.h) \
include/linux/gfp.h \
$(wildcard include/config/zone/dma.h) \
$(wildcard include/config/zone/dma32.h) \
include/linux/mmzone.h \
$(wildcard include/config/force/max/zoneorder.h) \
$(wildcard include/config/memory/hotplug.h) \
$(wildcard include/config/arch/populates/node/map.h) \
$(wildcard include/config/discontigmem.h) \
$(wildcard include/config/flat/node/mem/map.h) \
$(wildcard include/config/have/memory/present.h) \
$(wildcard include/config/need/node/memmap/size.h) \
$(wildcard include/config/need/multiple/nodes.h) \
$(wildcard include/config/sparsemem.h) \
$(wildcard include/config/have/arch/early/pfn/to/nid.h) \
$(wildcard include/config/flatmem.h) \
$(wildcard include/config/sparsemem/extreme.h) \
$(wildcard include/config/nodes/span/other/nodes.h) \
$(wildcard include/config/holes/in/zone.h) \
include/linux/numa.h \
$(wildcard include/config/nodes/shift.h) \
include/linux/init.h \
$(wildcard include/config/modules.h) \
$(wildcard include/config/hotplug.h) \
$(wildcard include/config/acpi/hotplug/memory.h) \
include/linux/seqlock.h \
include/linux/nodemask.h \
include/asm/page.h \
$(wildcard include/config/build/elf64.h) \
$(wildcard include/config/limited/dma.h) \
include/linux/pfn.h \
include/asm/io.h \
include/asm-generic/iomap.h \
include/asm/pgtable-bits.h \
$(wildcard include/config/cpu/mips32/r1.h) \
$(wildcard include/config/cpu/tx39xx.h) \
$(wildcard include/config/mips/uncached.h) \
include/asm-mips/mach-generic/ioremap.h \
include/asm-mips/mach-generic/mangle-port.h \
$(wildcard include/config/swap/io/space.h) \
include/asm-generic/memory_model.h \
$(wildcard include/config/out/of/line/pfn/to/page.h) \
include/asm-generic/page.h \
include/linux/memory_hotplug.h \
$(wildcard include/config/have/arch/nodedata/extension.h) \
include/linux/notifier.h \
include/linux/errno.h \
include/asm/errno.h \
include/asm-generic/errno-base.h \
include/linux/mutex.h \
$(wildcard include/config/debug/mutexes.h) \
include/linux/rwsem.h \
$(wildcard include/config/rwsem/generic/spinlock.h) \
include/linux/rwsem-spinlock.h \
include/linux/srcu.h \
include/linux/topology.h \
$(wildcard include/config/sched/smt.h) \
$(wildcard include/config/sched/mc.h) \
include/linux/smp.h \
include/asm/topology.h \
include/asm-mips/mach-generic/topology.h \
include/asm-generic/topology.h \
include/linux/slub_def.h \
include/linux/workqueue.h \
include/linux/timer.h \
$(wildcard include/config/timer/stats.h) \
include/linux/ktime.h \
$(wildcard include/config/ktime/scalar.h) \
include/linux/time.h \
include/linux/jiffies.h \
include/linux/calc64.h \
include/asm/div64.h \
include/asm-generic/div64.h \
include/linux/timex.h \
$(wildcard include/config/time/interpolation.h) \
$(wildcard include/config/no/hz.h) \
include/asm/param.h \
$(wildcard include/config/hz.h) \
include/asm/timex.h \
include/asm-mips/mach-generic/timex.h \
include/linux/kobject.h \
include/linux/sysfs.h \
include/linux/kref.h \
include/asm/percpu.h \
include/asm-generic/percpu.h \
include/linux/namei.h \
include/linux/stat.h \
include/asm/stat.h \
include/linux/radix-tree.h \
include/linux/prio_tree.h \
include/linux/pid.h \
include/asm/semaphore.h \
include/linux/quota.h \
include/linux/dqblk_xfs.h \
include/linux/dqblk_v1.h \
include/linux/dqblk_v2.h \
include/linux/nfs_fs_i.h \
include/linux/nfs.h \
include/linux/sunrpc/msg_prot.h \
include/linux/fcntl.h \
include/asm/fcntl.h \
include/asm-generic/fcntl.h \
include/linux/err.h \
include/linux/file.h \
include/linux/pagemap.h \
include/linux/mm.h \
$(wildcard include/config/sysctl.h) \
$(wildcard include/config/mmu.h) \
$(wildcard include/config/stack/growsup.h) \
$(wildcard include/config/debug/vm.h) \
$(wildcard include/config/shmem.h) \
$(wildcard include/config/split/ptlock/cpus.h) \
$(wildcard include/config/ia64.h) \
$(wildcard include/config/proc/fs.h) \
$(wildcard include/config/debug/pagealloc.h) \
include/linux/capability.h \
include/linux/rbtree.h \
include/linux/debug_locks.h \
$(wildcard include/config/debug/locking/api/selftests.h) \
include/linux/backing-dev.h \
include/linux/mm_types.h \
include/asm/pgtable.h \
include/asm/pgtable-32.h \
include/asm/fixmap.h \
include/asm-generic/pgtable-nopmd.h \
include/asm-generic/pgtable-nopud.h \
include/asm-generic/pgtable.h \
include/linux/page-flags.h \
$(wildcard include/config/s390.h) \
$(wildcard include/config/swap.h) \
include/linux/vmstat.h \
$(wildcard include/config/vm/event/counters.h) \
include/linux/highmem.h \
include/linux/uaccess.h \
include/asm/uaccess.h \
include/asm-generic/uaccess.h \
include/asm/cacheflush.h \
include/asm/kmap_types.h \
$(wildcard include/config/debug/highmem.h) \
include/linux/splice.h \
include/linux/pipe_fs_i.h \
include/linux/mm_inline.h \
include/linux/swap.h \
include/linux/sched.h \
$(wildcard include/config/detect/softlockup.h) \
$(wildcard include/config/keys.h) \
$(wildcard include/config/bsd/process/acct.h) \
$(wildcard include/config/taskstats.h) \
$(wildcard include/config/inotify/user.h) \
$(wildcard include/config/schedstats.h) \
$(wildcard include/config/task/delay/acct.h) \
$(wildcard include/config/blk/dev/io/trace.h) \
$(wildcard include/config/cc/stackprotector.h) \
$(wildcard include/config/sysvipc.h) \
$(wildcard include/config/rt/mutexes.h) \
$(wildcard include/config/task/xacct.h) \
$(wildcard include/config/cpusets.h) \
$(wildcard include/config/compat.h) \
$(wildcard include/config/fault/injection.h) \
include/linux/auxvec.h \
include/asm/auxvec.h \
include/asm/ptrace.h \
$(wildcard include/config/cpu/has/smartmips.h) \
include/asm/isadep.h \
include/asm/mmu.h \
include/asm/cputime.h \
include/asm-generic/cputime.h \
include/linux/sem.h \
include/linux/ipc.h \
$(wildcard include/config/ipc/ns.h) \
include/asm/ipcbuf.h \
include/asm/sembuf.h \
include/linux/signal.h \
include/asm/signal.h \
$(wildcard include/config/trad/signals.h) \
$(wildcard include/config/binfmt/irix.h) \
include/asm-generic/signal.h \
include/asm/sigcontext.h \
include/asm/siginfo.h \
include/asm-generic/siginfo.h \
include/linux/securebits.h \
include/linux/fs_struct.h \
include/linux/completion.h \
include/linux/seccomp.h \
$(wildcard include/config/seccomp.h) \
include/linux/futex.h \
$(wildcard include/config/futex.h) \
include/linux/rtmutex.h \
$(wildcard include/config/debug/rt/mutexes.h) \
include/linux/plist.h \
$(wildcard include/config/debug/pi/list.h) \
include/linux/param.h \
include/linux/resource.h \
include/asm/resource.h \
include/asm-generic/resource.h \
include/linux/hrtimer.h \
$(wildcard include/config/high/res/timers.h) \
include/linux/task_io_accounting.h \
$(wildcard include/config/task/io/accounting.h) \
include/linux/aio.h \
include/linux/aio_abi.h \
include/linux/uio.h \
include/linux/writeback.h \
include/linux/buffer_head.h \
include/linux/module.h \
$(wildcard include/config/modversions.h) \
$(wildcard include/config/unused/symbols.h) \
$(wildcard include/config/module/unload.h) \
$(wildcard include/config/kallsyms.h) \
include/linux/kmod.h \
$(wildcard include/config/kmod.h) \
include/linux/elf.h \
include/linux/elf-em.h \
include/asm/elf.h \
$(wildcard include/config/mips32/n32.h) \
$(wildcard include/config/mips32/o32.h) \
$(wildcard include/config/mips32/compat.h) \
include/linux/moduleparam.h \
include/asm/local.h \
include/asm/module.h \
$(wildcard include/config/cpu/mips32/r2.h) \
$(wildcard include/config/cpu/mips64/r1.h) \
$(wildcard include/config/cpu/r6000.h) \
include/linux/syscalls.h \
$(wildcard include/config/v850.h) \
$(wildcard include/config/asus/sw/qos.h) \
include/linux/config.h \
$(wildcard include/config/h.h) \
include/linux/key.h \
include/linux/security.h \
$(wildcard include/config/security/network.h) \
$(wildcard include/config/security/network/xfrm.h) \
include/linux/binfmts.h \
include/linux/shm.h \
include/asm/shmparam.h \
include/asm/shmbuf.h \
include/linux/msg.h \
include/asm/msgbuf.h \
$(wildcard include/config/cpu/little/endian.h) \
include/linux/xfrm.h \
include/net/flow.h \
$(wildcard include/config/ipv6/mip6.h) \
include/linux/in6.h \
fs/splice.o: $(deps_fs/splice.o)
$(deps_fs/splice.o):
|
smx-smx/dsl-n55u-bender
|
release/src-ra/linux/linux-2.6.21.x/fs/.splice.o.cmd
|
Batchfile
|
gpl-2.0
| 16,975 |
"""
OVERALL CREDIT TO:
t0mm0, Eldorado, VOINAGE, BSTRDMKR, tknorris, smokdpi, TheHighway
urlresolver XBMC Addon
Copyright (C) 2011 t0mm0
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
"""
import re
from lib import helpers
from urlresolver import common
from urlresolver.resolver import UrlResolver, ResolverError
class NxloadResolver(UrlResolver):
name = "nxload"
domains = ["nxload.com"]
pattern = '(?://|\.)(nxload\.com)/(?:embed-)?([0-9a-zA-Z]+)'
def __init__(self):
self.net = common.Net()
def get_media_url(self, host, media_id):
web_url = self.get_url(host, media_id)
headers = {'User-Agent': common.RAND_UA}
html = self.net.http_GET(web_url, headers=headers).content
if html:
match = re.search('''['"]?sources['"]?\s*:\s*\[(.*?)\]''', html, re.DOTALL)
if match:
sources = [(source.rsplit('/', 1).pop(1), source) for source in
re.findall('''['"](.*?)["']''', match.group(1), re.DOTALL)]
return helpers.pick_source(sources) + helpers.append_headers(headers)
raise ResolverError("Video not found")
def get_url(self, host, media_id):
return self._default_get_url(host, media_id)
|
koditr/xbmc-tr-team-turkish-addons
|
script.module.urlresolver/lib/urlresolver/plugins/nxload.py
|
Python
|
gpl-2.0
| 1,879 |
/*******************************************************************************
Intel(R) Gigabit Ethernet Linux driver
Copyright(c) 2007-2009 Intel Corporation.
This program is free software; you can redistribute it and/or modify it
under the terms and conditions of the GNU General Public License,
version 2, as published by the Free Software Foundation.
This program is distributed in the hope it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
more details.
You should have received a copy of the GNU General Public License along with
this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
The full GNU General Public License is included in this distribution in
the file called "COPYING".
Contact Information:
e1000-devel Mailing List <[email protected]>
Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497
*******************************************************************************/
#include <linux/module.h>
#include <linux/types.h>
#include <linux/init.h>
#include <linux/vmalloc.h>
#include <linux/pagemap.h>
#include <linux/netdevice.h>
#include <linux/ipv6.h>
#include <net/checksum.h>
#include <net/ip6_checksum.h>
#include <linux/net_tstamp.h>
#include <linux/mii.h>
#include <linux/ethtool.h>
#include <linux/if_vlan.h>
#include <linux/pci.h>
#include <linux/pci-aspm.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/if_ether.h>
#include <linux/aer.h>
#ifdef CONFIG_IGB_DCA
#include <linux/dca.h>
#endif
#include "igb.h"
#define DRV_VERSION "2.1.0-k2"
char igb_driver_name[] = "igb";
char igb_driver_version[] = DRV_VERSION;
static const char igb_driver_string[] =
"Intel(R) Gigabit Ethernet Network Driver";
static const char igb_copyright[] = "Copyright (c) 2007-2009 Intel Corporation.";
static const struct e1000_info *igb_info_tbl[] = {
[board_82575] = &e1000_82575_info,
};
static struct pci_device_id igb_pci_tbl[] = {
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_COPPER), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_FIBER), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_SERDES), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_SGMII), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82580_COPPER_DUAL), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_NS), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_NS_SERDES), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_FIBER), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_SERDES), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_SERDES_QUAD), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82576_QUAD_COPPER), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82575EB_COPPER), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82575EB_FIBER_SERDES), board_82575 },
{ PCI_VDEVICE(INTEL, E1000_DEV_ID_82575GB_QUAD_COPPER), board_82575 },
/* required last entry */
{0, }
};
MODULE_DEVICE_TABLE(pci, igb_pci_tbl);
void igb_reset(struct igb_adapter *);
static int igb_setup_all_tx_resources(struct igb_adapter *);
static int igb_setup_all_rx_resources(struct igb_adapter *);
static void igb_free_all_tx_resources(struct igb_adapter *);
static void igb_free_all_rx_resources(struct igb_adapter *);
static void igb_setup_mrqc(struct igb_adapter *);
void igb_update_stats(struct igb_adapter *);
static int igb_probe(struct pci_dev *, const struct pci_device_id *);
static void __devexit igb_remove(struct pci_dev *pdev);
static int igb_sw_init(struct igb_adapter *);
static int igb_open(struct net_device *);
static int igb_close(struct net_device *);
static void igb_configure_tx(struct igb_adapter *);
static void igb_configure_rx(struct igb_adapter *);
static void igb_clean_all_tx_rings(struct igb_adapter *);
static void igb_clean_all_rx_rings(struct igb_adapter *);
static void igb_clean_tx_ring(struct igb_ring *);
static void igb_clean_rx_ring(struct igb_ring *);
static void igb_set_rx_mode(struct net_device *);
static void igb_update_phy_info(unsigned long);
static void igb_watchdog(unsigned long);
static void igb_watchdog_task(struct work_struct *);
static netdev_tx_t igb_xmit_frame_adv(struct sk_buff *skb, struct net_device *);
static struct net_device_stats *igb_get_stats(struct net_device *);
static int igb_change_mtu(struct net_device *, int);
static int igb_set_mac(struct net_device *, void *);
static void igb_set_uta(struct igb_adapter *adapter);
static irqreturn_t igb_intr(int irq, void *);
static irqreturn_t igb_intr_msi(int irq, void *);
static irqreturn_t igb_msix_other(int irq, void *);
static irqreturn_t igb_msix_ring(int irq, void *);
#ifdef CONFIG_IGB_DCA
static void igb_update_dca(struct igb_q_vector *);
static void igb_setup_dca(struct igb_adapter *);
#endif /* CONFIG_IGB_DCA */
static bool igb_clean_tx_irq(struct igb_q_vector *);
static int igb_poll(struct napi_struct *, int);
static bool igb_clean_rx_irq_adv(struct igb_q_vector *, int *, int);
static int igb_ioctl(struct net_device *, struct ifreq *, int cmd);
static void igb_tx_timeout(struct net_device *);
static void igb_reset_task(struct work_struct *);
static void igb_vlan_rx_register(struct net_device *, struct vlan_group *);
static void igb_vlan_rx_add_vid(struct net_device *, u16);
static void igb_vlan_rx_kill_vid(struct net_device *, u16);
static void igb_restore_vlan(struct igb_adapter *);
static void igb_rar_set_qsel(struct igb_adapter *, u8 *, u32 , u8);
static void igb_ping_all_vfs(struct igb_adapter *);
static void igb_msg_task(struct igb_adapter *);
static void igb_vmm_control(struct igb_adapter *);
static int igb_set_vf_mac(struct igb_adapter *, int, unsigned char *);
static void igb_restore_vf_multicasts(struct igb_adapter *adapter);
#ifdef CONFIG_PM
static int igb_suspend(struct pci_dev *, pm_message_t);
static int igb_resume(struct pci_dev *);
#endif
static void igb_shutdown(struct pci_dev *);
#ifdef CONFIG_IGB_DCA
static int igb_notify_dca(struct notifier_block *, unsigned long, void *);
static struct notifier_block dca_notifier = {
.notifier_call = igb_notify_dca,
.next = NULL,
.priority = 0
};
#endif
#ifdef CONFIG_NET_POLL_CONTROLLER
/* for netdump / net console */
static void igb_netpoll(struct net_device *);
#endif
#ifdef CONFIG_PCI_IOV
static unsigned int max_vfs = 0;
module_param(max_vfs, uint, 0);
MODULE_PARM_DESC(max_vfs, "Maximum number of virtual functions to allocate "
"per physical function");
#endif /* CONFIG_PCI_IOV */
static pci_ers_result_t igb_io_error_detected(struct pci_dev *,
pci_channel_state_t);
static pci_ers_result_t igb_io_slot_reset(struct pci_dev *);
static void igb_io_resume(struct pci_dev *);
static struct pci_error_handlers igb_err_handler = {
.error_detected = igb_io_error_detected,
.slot_reset = igb_io_slot_reset,
.resume = igb_io_resume,
};
static struct pci_driver igb_driver = {
.name = igb_driver_name,
.id_table = igb_pci_tbl,
.probe = igb_probe,
.remove = __devexit_p(igb_remove),
#ifdef CONFIG_PM
/* Power Managment Hooks */
.suspend = igb_suspend,
.resume = igb_resume,
#endif
.shutdown = igb_shutdown,
.err_handler = &igb_err_handler
};
MODULE_AUTHOR("Intel Corporation, <[email protected]>");
MODULE_DESCRIPTION("Intel(R) Gigabit Ethernet Network Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(DRV_VERSION);
/**
* igb_read_clock - read raw cycle counter (to be used by time counter)
*/
static cycle_t igb_read_clock(const struct cyclecounter *tc)
{
struct igb_adapter *adapter =
container_of(tc, struct igb_adapter, cycles);
struct e1000_hw *hw = &adapter->hw;
u64 stamp = 0;
int shift = 0;
/*
* The timestamp latches on lowest register read. For the 82580
* the lowest register is SYSTIMR instead of SYSTIML. However we never
* adjusted TIMINCA so SYSTIMR will just read as all 0s so ignore it.
*/
if (hw->mac.type == e1000_82580) {
stamp = rd32(E1000_SYSTIMR) >> 8;
shift = IGB_82580_TSYNC_SHIFT;
}
stamp |= (u64)rd32(E1000_SYSTIML) << shift;
stamp |= (u64)rd32(E1000_SYSTIMH) << (shift + 32);
return stamp;
}
#ifdef DEBUG
/**
* igb_get_hw_dev_name - return device name string
* used by hardware layer to print debugging information
**/
char *igb_get_hw_dev_name(struct e1000_hw *hw)
{
struct igb_adapter *adapter = hw->back;
return adapter->netdev->name;
}
/**
* igb_get_time_str - format current NIC and system time as string
*/
static char *igb_get_time_str(struct igb_adapter *adapter,
char buffer[160])
{
cycle_t hw = adapter->cycles.read(&adapter->cycles);
struct timespec nic = ns_to_timespec(timecounter_read(&adapter->clock));
struct timespec sys;
struct timespec delta;
getnstimeofday(&sys);
delta = timespec_sub(nic, sys);
sprintf(buffer,
"HW %llu, NIC %ld.%09lus, SYS %ld.%09lus, NIC-SYS %lds + %09luns",
hw,
(long)nic.tv_sec, nic.tv_nsec,
(long)sys.tv_sec, sys.tv_nsec,
(long)delta.tv_sec, delta.tv_nsec);
return buffer;
}
#endif
/**
* igb_init_module - Driver Registration Routine
*
* igb_init_module is the first routine called when the driver is
* loaded. All it does is register with the PCI subsystem.
**/
static int __init igb_init_module(void)
{
int ret;
printk(KERN_INFO "%s - version %s\n",
igb_driver_string, igb_driver_version);
printk(KERN_INFO "%s\n", igb_copyright);
#ifdef CONFIG_IGB_DCA
dca_register_notify(&dca_notifier);
#endif
ret = pci_register_driver(&igb_driver);
return ret;
}
module_init(igb_init_module);
/**
* igb_exit_module - Driver Exit Cleanup Routine
*
* igb_exit_module is called just before the driver is removed
* from memory.
**/
static void __exit igb_exit_module(void)
{
#ifdef CONFIG_IGB_DCA
dca_unregister_notify(&dca_notifier);
#endif
pci_unregister_driver(&igb_driver);
}
module_exit(igb_exit_module);
#define Q_IDX_82576(i) (((i & 0x1) << 3) + (i >> 1))
/**
* igb_cache_ring_register - Descriptor ring to register mapping
* @adapter: board private structure to initialize
*
* Once we know the feature-set enabled for the device, we'll cache
* the register offset the descriptor ring is assigned to.
**/
static void igb_cache_ring_register(struct igb_adapter *adapter)
{
int i = 0, j = 0;
u32 rbase_offset = adapter->vfs_allocated_count;
switch (adapter->hw.mac.type) {
case e1000_82576:
/* The queues are allocated for virtualization such that VF 0
* is allocated queues 0 and 8, VF 1 queues 1 and 9, etc.
* In order to avoid collision we start at the first free queue
* and continue consuming queues in the same sequence
*/
if (adapter->vfs_allocated_count) {
for (; i < adapter->rss_queues; i++)
adapter->rx_ring[i].reg_idx = rbase_offset +
Q_IDX_82576(i);
for (; j < adapter->rss_queues; j++)
adapter->tx_ring[j].reg_idx = rbase_offset +
Q_IDX_82576(j);
}
case e1000_82575:
case e1000_82580:
default:
for (; i < adapter->num_rx_queues; i++)
adapter->rx_ring[i].reg_idx = rbase_offset + i;
for (; j < adapter->num_tx_queues; j++)
adapter->tx_ring[j].reg_idx = rbase_offset + j;
break;
}
}
static void igb_free_queues(struct igb_adapter *adapter)
{
kfree(adapter->tx_ring);
kfree(adapter->rx_ring);
adapter->tx_ring = NULL;
adapter->rx_ring = NULL;
adapter->num_rx_queues = 0;
adapter->num_tx_queues = 0;
}
/**
* igb_alloc_queues - Allocate memory for all rings
* @adapter: board private structure to initialize
*
* We allocate one ring per queue at run-time since we don't know the
* number of queues at compile-time.
**/
static int igb_alloc_queues(struct igb_adapter *adapter)
{
int i;
adapter->tx_ring = kcalloc(adapter->num_tx_queues,
sizeof(struct igb_ring), GFP_KERNEL);
if (!adapter->tx_ring)
goto err;
adapter->rx_ring = kcalloc(adapter->num_rx_queues,
sizeof(struct igb_ring), GFP_KERNEL);
if (!adapter->rx_ring)
goto err;
for (i = 0; i < adapter->num_tx_queues; i++) {
struct igb_ring *ring = &(adapter->tx_ring[i]);
ring->count = adapter->tx_ring_count;
ring->queue_index = i;
ring->pdev = adapter->pdev;
ring->netdev = adapter->netdev;
/* For 82575, context index must be unique per ring. */
if (adapter->hw.mac.type == e1000_82575)
ring->flags = IGB_RING_FLAG_TX_CTX_IDX;
}
for (i = 0; i < adapter->num_rx_queues; i++) {
struct igb_ring *ring = &(adapter->rx_ring[i]);
ring->count = adapter->rx_ring_count;
ring->queue_index = i;
ring->pdev = adapter->pdev;
ring->netdev = adapter->netdev;
ring->rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE;
ring->flags = IGB_RING_FLAG_RX_CSUM; /* enable rx checksum */
/* set flag indicating ring supports SCTP checksum offload */
if (adapter->hw.mac.type >= e1000_82576)
ring->flags |= IGB_RING_FLAG_RX_SCTP_CSUM;
}
igb_cache_ring_register(adapter);
return 0;
err:
igb_free_queues(adapter);
return -ENOMEM;
}
#define IGB_N0_QUEUE -1
static void igb_assign_vector(struct igb_q_vector *q_vector, int msix_vector)
{
u32 msixbm = 0;
struct igb_adapter *adapter = q_vector->adapter;
struct e1000_hw *hw = &adapter->hw;
u32 ivar, index;
int rx_queue = IGB_N0_QUEUE;
int tx_queue = IGB_N0_QUEUE;
if (q_vector->rx_ring)
rx_queue = q_vector->rx_ring->reg_idx;
if (q_vector->tx_ring)
tx_queue = q_vector->tx_ring->reg_idx;
switch (hw->mac.type) {
case e1000_82575:
/* The 82575 assigns vectors using a bitmask, which matches the
bitmask for the EICR/EIMS/EIMC registers. To assign one
or more queues to a vector, we write the appropriate bits
into the MSIXBM register for that vector. */
if (rx_queue > IGB_N0_QUEUE)
msixbm = E1000_EICR_RX_QUEUE0 << rx_queue;
if (tx_queue > IGB_N0_QUEUE)
msixbm |= E1000_EICR_TX_QUEUE0 << tx_queue;
array_wr32(E1000_MSIXBM(0), msix_vector, msixbm);
q_vector->eims_value = msixbm;
break;
case e1000_82576:
/* 82576 uses a table-based method for assigning vectors.
Each queue has a single entry in the table to which we write
a vector number along with a "valid" bit. Sadly, the layout
of the table is somewhat counterintuitive. */
if (rx_queue > IGB_N0_QUEUE) {
index = (rx_queue & 0x7);
ivar = array_rd32(E1000_IVAR0, index);
if (rx_queue < 8) {
/* vector goes into low byte of register */
ivar = ivar & 0xFFFFFF00;
ivar |= msix_vector | E1000_IVAR_VALID;
} else {
/* vector goes into third byte of register */
ivar = ivar & 0xFF00FFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 16;
}
array_wr32(E1000_IVAR0, index, ivar);
}
if (tx_queue > IGB_N0_QUEUE) {
index = (tx_queue & 0x7);
ivar = array_rd32(E1000_IVAR0, index);
if (tx_queue < 8) {
/* vector goes into second byte of register */
ivar = ivar & 0xFFFF00FF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 8;
} else {
/* vector goes into high byte of register */
ivar = ivar & 0x00FFFFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 24;
}
array_wr32(E1000_IVAR0, index, ivar);
}
q_vector->eims_value = 1 << msix_vector;
break;
case e1000_82580:
/* 82580 uses the same table-based approach as 82576 but has fewer
entries as a result we carry over for queues greater than 4. */
if (rx_queue > IGB_N0_QUEUE) {
index = (rx_queue >> 1);
ivar = array_rd32(E1000_IVAR0, index);
if (rx_queue & 0x1) {
/* vector goes into third byte of register */
ivar = ivar & 0xFF00FFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 16;
} else {
/* vector goes into low byte of register */
ivar = ivar & 0xFFFFFF00;
ivar |= msix_vector | E1000_IVAR_VALID;
}
array_wr32(E1000_IVAR0, index, ivar);
}
if (tx_queue > IGB_N0_QUEUE) {
index = (tx_queue >> 1);
ivar = array_rd32(E1000_IVAR0, index);
if (tx_queue & 0x1) {
/* vector goes into high byte of register */
ivar = ivar & 0x00FFFFFF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 24;
} else {
/* vector goes into second byte of register */
ivar = ivar & 0xFFFF00FF;
ivar |= (msix_vector | E1000_IVAR_VALID) << 8;
}
array_wr32(E1000_IVAR0, index, ivar);
}
q_vector->eims_value = 1 << msix_vector;
break;
default:
BUG();
break;
}
}
/**
* igb_configure_msix - Configure MSI-X hardware
*
* igb_configure_msix sets up the hardware to properly
* generate MSI-X interrupts.
**/
static void igb_configure_msix(struct igb_adapter *adapter)
{
u32 tmp;
int i, vector = 0;
struct e1000_hw *hw = &adapter->hw;
adapter->eims_enable_mask = 0;
/* set vector for other causes, i.e. link changes */
switch (hw->mac.type) {
case e1000_82575:
tmp = rd32(E1000_CTRL_EXT);
/* enable MSI-X PBA support*/
tmp |= E1000_CTRL_EXT_PBA_CLR;
/* Auto-Mask interrupts upon ICR read. */
tmp |= E1000_CTRL_EXT_EIAME;
tmp |= E1000_CTRL_EXT_IRCA;
wr32(E1000_CTRL_EXT, tmp);
/* enable msix_other interrupt */
array_wr32(E1000_MSIXBM(0), vector++,
E1000_EIMS_OTHER);
adapter->eims_other = E1000_EIMS_OTHER;
break;
case e1000_82576:
case e1000_82580:
/* Turn on MSI-X capability first, or our settings
* won't stick. And it will take days to debug. */
wr32(E1000_GPIE, E1000_GPIE_MSIX_MODE |
E1000_GPIE_PBA | E1000_GPIE_EIAME |
E1000_GPIE_NSICR);
/* enable msix_other interrupt */
adapter->eims_other = 1 << vector;
tmp = (vector++ | E1000_IVAR_VALID) << 8;
wr32(E1000_IVAR_MISC, tmp);
break;
default:
/* do nothing, since nothing else supports MSI-X */
break;
} /* switch (hw->mac.type) */
adapter->eims_enable_mask |= adapter->eims_other;
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
igb_assign_vector(q_vector, vector++);
adapter->eims_enable_mask |= q_vector->eims_value;
}
wrfl();
}
/**
* igb_request_msix - Initialize MSI-X interrupts
*
* igb_request_msix allocates MSI-X vectors and requests interrupts from the
* kernel.
**/
static int igb_request_msix(struct igb_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
int i, err = 0, vector = 0;
err = request_irq(adapter->msix_entries[vector].vector,
igb_msix_other, 0, netdev->name, adapter);
if (err)
goto out;
vector++;
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
q_vector->itr_register = hw->hw_addr + E1000_EITR(vector);
if (q_vector->rx_ring && q_vector->tx_ring)
sprintf(q_vector->name, "%s-TxRx-%u", netdev->name,
q_vector->rx_ring->queue_index);
else if (q_vector->tx_ring)
sprintf(q_vector->name, "%s-tx-%u", netdev->name,
q_vector->tx_ring->queue_index);
else if (q_vector->rx_ring)
sprintf(q_vector->name, "%s-rx-%u", netdev->name,
q_vector->rx_ring->queue_index);
else
sprintf(q_vector->name, "%s-unused", netdev->name);
err = request_irq(adapter->msix_entries[vector].vector,
igb_msix_ring, 0, q_vector->name,
q_vector);
if (err)
goto out;
vector++;
}
igb_configure_msix(adapter);
return 0;
out:
return err;
}
static void igb_reset_interrupt_capability(struct igb_adapter *adapter)
{
if (adapter->msix_entries) {
pci_disable_msix(adapter->pdev);
kfree(adapter->msix_entries);
adapter->msix_entries = NULL;
} else if (adapter->flags & IGB_FLAG_HAS_MSI) {
pci_disable_msi(adapter->pdev);
}
}
/**
* igb_free_q_vectors - Free memory allocated for interrupt vectors
* @adapter: board private structure to initialize
*
* This function frees the memory allocated to the q_vectors. In addition if
* NAPI is enabled it will delete any references to the NAPI struct prior
* to freeing the q_vector.
**/
static void igb_free_q_vectors(struct igb_adapter *adapter)
{
int v_idx;
for (v_idx = 0; v_idx < adapter->num_q_vectors; v_idx++) {
struct igb_q_vector *q_vector = adapter->q_vector[v_idx];
adapter->q_vector[v_idx] = NULL;
netif_napi_del(&q_vector->napi);
kfree(q_vector);
}
adapter->num_q_vectors = 0;
}
/**
* igb_clear_interrupt_scheme - reset the device to a state of no interrupts
*
* This function resets the device so that it has 0 rx queues, tx queues, and
* MSI-X interrupts allocated.
*/
static void igb_clear_interrupt_scheme(struct igb_adapter *adapter)
{
igb_free_queues(adapter);
igb_free_q_vectors(adapter);
igb_reset_interrupt_capability(adapter);
}
/**
* igb_set_interrupt_capability - set MSI or MSI-X if supported
*
* Attempt to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static void igb_set_interrupt_capability(struct igb_adapter *adapter)
{
int err;
int numvecs, i;
/* Number of supported queues. */
adapter->num_rx_queues = adapter->rss_queues;
adapter->num_tx_queues = adapter->rss_queues;
/* start with one vector for every rx queue */
numvecs = adapter->num_rx_queues;
/* if tx handler is seperate add 1 for every tx queue */
if (!(adapter->flags & IGB_FLAG_QUEUE_PAIRS))
numvecs += adapter->num_tx_queues;
/* store the number of vectors reserved for queues */
adapter->num_q_vectors = numvecs;
/* add 1 vector for link status interrupts */
numvecs++;
adapter->msix_entries = kcalloc(numvecs, sizeof(struct msix_entry),
GFP_KERNEL);
if (!adapter->msix_entries)
goto msi_only;
for (i = 0; i < numvecs; i++)
adapter->msix_entries[i].entry = i;
err = pci_enable_msix(adapter->pdev,
adapter->msix_entries,
numvecs);
if (err == 0)
goto out;
igb_reset_interrupt_capability(adapter);
/* If we can't do MSI-X, try MSI */
msi_only:
#ifdef CONFIG_PCI_IOV
/* disable SR-IOV for non MSI-X configurations */
if (adapter->vf_data) {
struct e1000_hw *hw = &adapter->hw;
/* disable iov and allow time for transactions to clear */
pci_disable_sriov(adapter->pdev);
msleep(500);
kfree(adapter->vf_data);
adapter->vf_data = NULL;
wr32(E1000_IOVCTL, E1000_IOVCTL_REUSE_VFQ);
msleep(100);
dev_info(&adapter->pdev->dev, "IOV Disabled\n");
}
#endif
adapter->vfs_allocated_count = 0;
adapter->rss_queues = 1;
adapter->flags |= IGB_FLAG_QUEUE_PAIRS;
adapter->num_rx_queues = 1;
adapter->num_tx_queues = 1;
adapter->num_q_vectors = 1;
if (!pci_enable_msi(adapter->pdev))
adapter->flags |= IGB_FLAG_HAS_MSI;
out:
/* Notify the stack of the (possibly) reduced Tx Queue count. */
adapter->netdev->real_num_tx_queues = adapter->num_tx_queues;
return;
}
/**
* igb_alloc_q_vectors - Allocate memory for interrupt vectors
* @adapter: board private structure to initialize
*
* We allocate one q_vector per queue interrupt. If allocation fails we
* return -ENOMEM.
**/
static int igb_alloc_q_vectors(struct igb_adapter *adapter)
{
struct igb_q_vector *q_vector;
struct e1000_hw *hw = &adapter->hw;
int v_idx;
for (v_idx = 0; v_idx < adapter->num_q_vectors; v_idx++) {
q_vector = kzalloc(sizeof(struct igb_q_vector), GFP_KERNEL);
if (!q_vector)
goto err_out;
q_vector->adapter = adapter;
q_vector->itr_shift = (hw->mac.type == e1000_82575) ? 16 : 0;
q_vector->itr_register = hw->hw_addr + E1000_EITR(0);
q_vector->itr_val = IGB_START_ITR;
q_vector->set_itr = 1;
netif_napi_add(adapter->netdev, &q_vector->napi, igb_poll, 64);
adapter->q_vector[v_idx] = q_vector;
}
return 0;
err_out:
while (v_idx) {
v_idx--;
q_vector = adapter->q_vector[v_idx];
netif_napi_del(&q_vector->napi);
kfree(q_vector);
adapter->q_vector[v_idx] = NULL;
}
return -ENOMEM;
}
static void igb_map_rx_ring_to_vector(struct igb_adapter *adapter,
int ring_idx, int v_idx)
{
struct igb_q_vector *q_vector;
q_vector = adapter->q_vector[v_idx];
q_vector->rx_ring = &adapter->rx_ring[ring_idx];
q_vector->rx_ring->q_vector = q_vector;
q_vector->itr_val = adapter->rx_itr_setting;
if (q_vector->itr_val && q_vector->itr_val <= 3)
q_vector->itr_val = IGB_START_ITR;
}
static void igb_map_tx_ring_to_vector(struct igb_adapter *adapter,
int ring_idx, int v_idx)
{
struct igb_q_vector *q_vector;
q_vector = adapter->q_vector[v_idx];
q_vector->tx_ring = &adapter->tx_ring[ring_idx];
q_vector->tx_ring->q_vector = q_vector;
q_vector->itr_val = adapter->tx_itr_setting;
if (q_vector->itr_val && q_vector->itr_val <= 3)
q_vector->itr_val = IGB_START_ITR;
}
/**
* igb_map_ring_to_vector - maps allocated queues to vectors
*
* This function maps the recently allocated queues to vectors.
**/
static int igb_map_ring_to_vector(struct igb_adapter *adapter)
{
int i;
int v_idx = 0;
if ((adapter->num_q_vectors < adapter->num_rx_queues) ||
(adapter->num_q_vectors < adapter->num_tx_queues))
return -ENOMEM;
if (adapter->num_q_vectors >=
(adapter->num_rx_queues + adapter->num_tx_queues)) {
for (i = 0; i < adapter->num_rx_queues; i++)
igb_map_rx_ring_to_vector(adapter, i, v_idx++);
for (i = 0; i < adapter->num_tx_queues; i++)
igb_map_tx_ring_to_vector(adapter, i, v_idx++);
} else {
for (i = 0; i < adapter->num_rx_queues; i++) {
if (i < adapter->num_tx_queues)
igb_map_tx_ring_to_vector(adapter, i, v_idx);
igb_map_rx_ring_to_vector(adapter, i, v_idx++);
}
for (; i < adapter->num_tx_queues; i++)
igb_map_tx_ring_to_vector(adapter, i, v_idx++);
}
return 0;
}
/**
* igb_init_interrupt_scheme - initialize interrupts, allocate queues/vectors
*
* This function initializes the interrupts and allocates all of the queues.
**/
static int igb_init_interrupt_scheme(struct igb_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int err;
igb_set_interrupt_capability(adapter);
err = igb_alloc_q_vectors(adapter);
if (err) {
dev_err(&pdev->dev, "Unable to allocate memory for vectors\n");
goto err_alloc_q_vectors;
}
err = igb_alloc_queues(adapter);
if (err) {
dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
goto err_alloc_queues;
}
err = igb_map_ring_to_vector(adapter);
if (err) {
dev_err(&pdev->dev, "Invalid q_vector to ring mapping\n");
goto err_map_queues;
}
return 0;
err_map_queues:
igb_free_queues(adapter);
err_alloc_queues:
igb_free_q_vectors(adapter);
err_alloc_q_vectors:
igb_reset_interrupt_capability(adapter);
return err;
}
/**
* igb_request_irq - initialize interrupts
*
* Attempts to configure interrupts using the best available
* capabilities of the hardware and kernel.
**/
static int igb_request_irq(struct igb_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
struct e1000_hw *hw = &adapter->hw;
int err = 0;
if (adapter->msix_entries) {
err = igb_request_msix(adapter);
if (!err)
goto request_done;
/* fall back to MSI */
igb_clear_interrupt_scheme(adapter);
if (!pci_enable_msi(adapter->pdev))
adapter->flags |= IGB_FLAG_HAS_MSI;
igb_free_all_tx_resources(adapter);
igb_free_all_rx_resources(adapter);
adapter->num_tx_queues = 1;
adapter->num_rx_queues = 1;
adapter->num_q_vectors = 1;
err = igb_alloc_q_vectors(adapter);
if (err) {
dev_err(&pdev->dev,
"Unable to allocate memory for vectors\n");
goto request_done;
}
err = igb_alloc_queues(adapter);
if (err) {
dev_err(&pdev->dev,
"Unable to allocate memory for queues\n");
igb_free_q_vectors(adapter);
goto request_done;
}
igb_setup_all_tx_resources(adapter);
igb_setup_all_rx_resources(adapter);
} else {
switch (hw->mac.type) {
case e1000_82575:
wr32(E1000_MSIXBM(0),
(E1000_EICR_RX_QUEUE0 |
E1000_EICR_TX_QUEUE0 |
E1000_EIMS_OTHER));
break;
case e1000_82580:
case e1000_82576:
wr32(E1000_IVAR0, E1000_IVAR_VALID);
break;
default:
break;
}
}
if (adapter->flags & IGB_FLAG_HAS_MSI) {
err = request_irq(adapter->pdev->irq, igb_intr_msi, 0,
netdev->name, adapter);
if (!err)
goto request_done;
/* fall back to legacy interrupts */
igb_reset_interrupt_capability(adapter);
adapter->flags &= ~IGB_FLAG_HAS_MSI;
}
err = request_irq(adapter->pdev->irq, igb_intr, IRQF_SHARED,
netdev->name, adapter);
if (err)
dev_err(&adapter->pdev->dev, "Error %d getting interrupt\n",
err);
request_done:
return err;
}
static void igb_free_irq(struct igb_adapter *adapter)
{
if (adapter->msix_entries) {
int vector = 0, i;
free_irq(adapter->msix_entries[vector++].vector, adapter);
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
free_irq(adapter->msix_entries[vector++].vector,
q_vector);
}
} else {
free_irq(adapter->pdev->irq, adapter);
}
}
/**
* igb_irq_disable - Mask off interrupt generation on the NIC
* @adapter: board private structure
**/
static void igb_irq_disable(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
/*
* we need to be careful when disabling interrupts. The VFs are also
* mapped into these registers and so clearing the bits can cause
* issues on the VF drivers so we only need to clear what we set
*/
if (adapter->msix_entries) {
u32 regval = rd32(E1000_EIAM);
wr32(E1000_EIAM, regval & ~adapter->eims_enable_mask);
wr32(E1000_EIMC, adapter->eims_enable_mask);
regval = rd32(E1000_EIAC);
wr32(E1000_EIAC, regval & ~adapter->eims_enable_mask);
}
wr32(E1000_IAM, 0);
wr32(E1000_IMC, ~0);
wrfl();
synchronize_irq(adapter->pdev->irq);
}
/**
* igb_irq_enable - Enable default interrupt generation settings
* @adapter: board private structure
**/
static void igb_irq_enable(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
if (adapter->msix_entries) {
u32 ims = E1000_IMS_LSC | E1000_IMS_DOUTSYNC;
u32 regval = rd32(E1000_EIAC);
wr32(E1000_EIAC, regval | adapter->eims_enable_mask);
regval = rd32(E1000_EIAM);
wr32(E1000_EIAM, regval | adapter->eims_enable_mask);
wr32(E1000_EIMS, adapter->eims_enable_mask);
if (adapter->vfs_allocated_count) {
wr32(E1000_MBVFIMR, 0xFF);
ims |= E1000_IMS_VMMB;
}
if (adapter->hw.mac.type == e1000_82580)
ims |= E1000_IMS_DRSTA;
wr32(E1000_IMS, ims);
} else {
wr32(E1000_IMS, IMS_ENABLE_MASK |
E1000_IMS_DRSTA);
wr32(E1000_IAM, IMS_ENABLE_MASK |
E1000_IMS_DRSTA);
}
}
static void igb_update_mng_vlan(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u16 vid = adapter->hw.mng_cookie.vlan_id;
u16 old_vid = adapter->mng_vlan_id;
if (hw->mng_cookie.status & E1000_MNG_DHCP_COOKIE_STATUS_VLAN) {
/* add VID to filter table */
igb_vfta_set(hw, vid, true);
adapter->mng_vlan_id = vid;
} else {
adapter->mng_vlan_id = IGB_MNG_VLAN_NONE;
}
if ((old_vid != (u16)IGB_MNG_VLAN_NONE) &&
(vid != old_vid) &&
!vlan_group_get_device(adapter->vlgrp, old_vid)) {
/* remove VID from filter table */
igb_vfta_set(hw, old_vid, false);
}
}
/**
* igb_release_hw_control - release control of the h/w to f/w
* @adapter: address of board private structure
*
* igb_release_hw_control resets CTRL_EXT:DRV_LOAD bit.
* For ASF and Pass Through versions of f/w this means that the
* driver is no longer loaded.
*
**/
static void igb_release_hw_control(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl_ext;
/* Let firmware take over control of h/w */
ctrl_ext = rd32(E1000_CTRL_EXT);
wr32(E1000_CTRL_EXT,
ctrl_ext & ~E1000_CTRL_EXT_DRV_LOAD);
}
/**
* igb_get_hw_control - get control of the h/w from f/w
* @adapter: address of board private structure
*
* igb_get_hw_control sets CTRL_EXT:DRV_LOAD bit.
* For ASF and Pass Through versions of f/w this means that
* the driver is loaded.
*
**/
static void igb_get_hw_control(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ctrl_ext;
/* Let firmware know the driver has taken over */
ctrl_ext = rd32(E1000_CTRL_EXT);
wr32(E1000_CTRL_EXT,
ctrl_ext | E1000_CTRL_EXT_DRV_LOAD);
}
/**
* igb_configure - configure the hardware for RX and TX
* @adapter: private board structure
**/
static void igb_configure(struct igb_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
int i;
igb_get_hw_control(adapter);
igb_set_rx_mode(netdev);
igb_restore_vlan(adapter);
igb_setup_tctl(adapter);
igb_setup_mrqc(adapter);
igb_setup_rctl(adapter);
igb_configure_tx(adapter);
igb_configure_rx(adapter);
igb_rx_fifo_flush_82575(&adapter->hw);
/* call igb_desc_unused which always leaves
* at least 1 descriptor unused to make sure
* next_to_use != next_to_clean */
for (i = 0; i < adapter->num_rx_queues; i++) {
struct igb_ring *ring = &adapter->rx_ring[i];
igb_alloc_rx_buffers_adv(ring, igb_desc_unused(ring));
}
adapter->tx_queue_len = netdev->tx_queue_len;
}
/**
* igb_up - Open the interface and prepare it to handle traffic
* @adapter: board private structure
**/
int igb_up(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
int i;
/* hardware has been reset, we need to reload some things */
igb_configure(adapter);
clear_bit(__IGB_DOWN, &adapter->state);
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
napi_enable(&q_vector->napi);
}
if (adapter->msix_entries)
igb_configure_msix(adapter);
/* Clear any pending interrupts. */
rd32(E1000_ICR);
igb_irq_enable(adapter);
/* notify VFs that reset has been completed */
if (adapter->vfs_allocated_count) {
u32 reg_data = rd32(E1000_CTRL_EXT);
reg_data |= E1000_CTRL_EXT_PFRSTD;
wr32(E1000_CTRL_EXT, reg_data);
}
netif_tx_start_all_queues(adapter->netdev);
/* start the watchdog. */
hw->mac.get_link_status = 1;
schedule_work(&adapter->watchdog_task);
return 0;
}
void igb_down(struct igb_adapter *adapter)
{
struct net_device *netdev = adapter->netdev;
struct e1000_hw *hw = &adapter->hw;
u32 tctl, rctl;
int i;
/* signal that we're down so the interrupt handler does not
* reschedule our watchdog timer */
set_bit(__IGB_DOWN, &adapter->state);
/* disable receives in the hardware */
rctl = rd32(E1000_RCTL);
wr32(E1000_RCTL, rctl & ~E1000_RCTL_EN);
/* flush and sleep below */
netif_tx_stop_all_queues(netdev);
/* disable transmits in the hardware */
tctl = rd32(E1000_TCTL);
tctl &= ~E1000_TCTL_EN;
wr32(E1000_TCTL, tctl);
/* flush both disables and wait for them to finish */
wrfl();
msleep(10);
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
napi_disable(&q_vector->napi);
}
igb_irq_disable(adapter);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
netdev->tx_queue_len = adapter->tx_queue_len;
netif_carrier_off(netdev);
/* record the stats before reset*/
igb_update_stats(adapter);
adapter->link_speed = 0;
adapter->link_duplex = 0;
if (!pci_channel_offline(adapter->pdev))
igb_reset(adapter);
igb_clean_all_tx_rings(adapter);
igb_clean_all_rx_rings(adapter);
#ifdef CONFIG_IGB_DCA
/* since we reset the hardware DCA settings were cleared */
igb_setup_dca(adapter);
#endif
}
void igb_reinit_locked(struct igb_adapter *adapter)
{
WARN_ON(in_interrupt());
while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
msleep(1);
igb_down(adapter);
igb_up(adapter);
clear_bit(__IGB_RESETTING, &adapter->state);
}
void igb_reset(struct igb_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
struct e1000_hw *hw = &adapter->hw;
struct e1000_mac_info *mac = &hw->mac;
struct e1000_fc_info *fc = &hw->fc;
u32 pba = 0, tx_space, min_tx_space, min_rx_space;
u16 hwm;
/* Repartition Pba for greater than 9k mtu
* To take effect CTRL.RST is required.
*/
switch (mac->type) {
case e1000_82580:
pba = rd32(E1000_RXPBS);
pba = igb_rxpbs_adjust_82580(pba);
break;
case e1000_82576:
pba = rd32(E1000_RXPBS);
pba &= E1000_RXPBS_SIZE_MASK_82576;
break;
case e1000_82575:
default:
pba = E1000_PBA_34K;
break;
}
if ((adapter->max_frame_size > ETH_FRAME_LEN + ETH_FCS_LEN) &&
(mac->type < e1000_82576)) {
/* adjust PBA for jumbo frames */
wr32(E1000_PBA, pba);
/* To maintain wire speed transmits, the Tx FIFO should be
* large enough to accommodate two full transmit packets,
* rounded up to the next 1KB and expressed in KB. Likewise,
* the Rx FIFO should be large enough to accommodate at least
* one full receive packet and is similarly rounded up and
* expressed in KB. */
pba = rd32(E1000_PBA);
/* upper 16 bits has Tx packet buffer allocation size in KB */
tx_space = pba >> 16;
/* lower 16 bits has Rx packet buffer allocation size in KB */
pba &= 0xffff;
/* the tx fifo also stores 16 bytes of information about the tx
* but don't include ethernet FCS because hardware appends it */
min_tx_space = (adapter->max_frame_size +
sizeof(union e1000_adv_tx_desc) -
ETH_FCS_LEN) * 2;
min_tx_space = ALIGN(min_tx_space, 1024);
min_tx_space >>= 10;
/* software strips receive CRC, so leave room for it */
min_rx_space = adapter->max_frame_size;
min_rx_space = ALIGN(min_rx_space, 1024);
min_rx_space >>= 10;
/* If current Tx allocation is less than the min Tx FIFO size,
* and the min Tx FIFO size is less than the current Rx FIFO
* allocation, take space away from current Rx allocation */
if (tx_space < min_tx_space &&
((min_tx_space - tx_space) < pba)) {
pba = pba - (min_tx_space - tx_space);
/* if short on rx space, rx wins and must trump tx
* adjustment */
if (pba < min_rx_space)
pba = min_rx_space;
}
wr32(E1000_PBA, pba);
}
/* flow control settings */
/* The high water mark must be low enough to fit one full frame
* (or the size used for early receive) above it in the Rx FIFO.
* Set it to the lower of:
* - 90% of the Rx FIFO size, or
* - the full Rx FIFO size minus one full frame */
hwm = min(((pba << 10) * 9 / 10),
((pba << 10) - 2 * adapter->max_frame_size));
fc->high_water = hwm & 0xFFF0; /* 16-byte granularity */
fc->low_water = fc->high_water - 16;
fc->pause_time = 0xFFFF;
fc->send_xon = 1;
fc->current_mode = fc->requested_mode;
/* disable receive for all VFs and wait one second */
if (adapter->vfs_allocated_count) {
int i;
for (i = 0 ; i < adapter->vfs_allocated_count; i++)
adapter->vf_data[i].flags = 0;
/* ping all the active vfs to let them know we are going down */
igb_ping_all_vfs(adapter);
/* disable transmits and receives */
wr32(E1000_VFRE, 0);
wr32(E1000_VFTE, 0);
}
/* Allow time for pending master requests to run */
hw->mac.ops.reset_hw(hw);
wr32(E1000_WUC, 0);
if (hw->mac.ops.init_hw(hw))
dev_err(&pdev->dev, "Hardware Error\n");
if (hw->mac.type == e1000_82580) {
u32 reg = rd32(E1000_PCIEMISC);
wr32(E1000_PCIEMISC,
reg & ~E1000_PCIEMISC_LX_DECISION);
}
igb_update_mng_vlan(adapter);
/* Enable h/w to recognize an 802.1Q VLAN Ethernet packet */
wr32(E1000_VET, ETHERNET_IEEE_VLAN_TYPE);
igb_reset_adaptive(hw);
igb_get_phy_info(hw);
}
static const struct net_device_ops igb_netdev_ops = {
.ndo_open = igb_open,
.ndo_stop = igb_close,
.ndo_start_xmit = igb_xmit_frame_adv,
.ndo_get_stats = igb_get_stats,
.ndo_set_rx_mode = igb_set_rx_mode,
.ndo_set_multicast_list = igb_set_rx_mode,
.ndo_set_mac_address = igb_set_mac,
.ndo_change_mtu = igb_change_mtu,
.ndo_do_ioctl = igb_ioctl,
.ndo_tx_timeout = igb_tx_timeout,
.ndo_validate_addr = eth_validate_addr,
.ndo_vlan_rx_register = igb_vlan_rx_register,
.ndo_vlan_rx_add_vid = igb_vlan_rx_add_vid,
.ndo_vlan_rx_kill_vid = igb_vlan_rx_kill_vid,
#ifdef CONFIG_NET_POLL_CONTROLLER
.ndo_poll_controller = igb_netpoll,
#endif
};
/**
* igb_probe - Device Initialization Routine
* @pdev: PCI device information struct
* @ent: entry in igb_pci_tbl
*
* Returns 0 on success, negative on failure
*
* igb_probe initializes an adapter identified by a pci_dev structure.
* The OS initialization, configuring of the adapter private structure,
* and a hardware reset occur.
**/
static int __devinit igb_probe(struct pci_dev *pdev,
const struct pci_device_id *ent)
{
struct net_device *netdev;
struct igb_adapter *adapter;
struct e1000_hw *hw;
u16 eeprom_data = 0;
static int global_quad_port_a; /* global quad port a indication */
const struct e1000_info *ei = igb_info_tbl[ent->driver_data];
unsigned long mmio_start, mmio_len;
int err, pci_using_dac;
u16 eeprom_apme_mask = IGB_EEPROM_APME;
u32 part_num;
err = pci_enable_device_mem(pdev);
if (err)
return err;
pci_using_dac = 0;
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(64));
if (!err) {
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(64));
if (!err)
pci_using_dac = 1;
} else {
err = pci_set_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
err = pci_set_consistent_dma_mask(pdev, DMA_BIT_MASK(32));
if (err) {
dev_err(&pdev->dev, "No usable DMA "
"configuration, aborting\n");
goto err_dma;
}
}
}
err = pci_request_selected_regions(pdev, pci_select_bars(pdev,
IORESOURCE_MEM),
igb_driver_name);
if (err)
goto err_pci_reg;
pci_enable_pcie_error_reporting(pdev);
pci_set_master(pdev);
pci_save_state(pdev);
err = -ENOMEM;
netdev = alloc_etherdev_mq(sizeof(struct igb_adapter),
IGB_ABS_MAX_TX_QUEUES);
if (!netdev)
goto err_alloc_etherdev;
SET_NETDEV_DEV(netdev, &pdev->dev);
pci_set_drvdata(pdev, netdev);
adapter = netdev_priv(netdev);
adapter->netdev = netdev;
adapter->pdev = pdev;
hw = &adapter->hw;
hw->back = adapter;
adapter->msg_enable = NETIF_MSG_DRV | NETIF_MSG_PROBE;
mmio_start = pci_resource_start(pdev, 0);
mmio_len = pci_resource_len(pdev, 0);
err = -EIO;
hw->hw_addr = ioremap(mmio_start, mmio_len);
if (!hw->hw_addr)
goto err_ioremap;
netdev->netdev_ops = &igb_netdev_ops;
igb_set_ethtool_ops(netdev);
netdev->watchdog_timeo = 5 * HZ;
strncpy(netdev->name, pci_name(pdev), sizeof(netdev->name) - 1);
netdev->mem_start = mmio_start;
netdev->mem_end = mmio_start + mmio_len;
/* PCI config space info */
hw->vendor_id = pdev->vendor;
hw->device_id = pdev->device;
hw->revision_id = pdev->revision;
hw->subsystem_vendor_id = pdev->subsystem_vendor;
hw->subsystem_device_id = pdev->subsystem_device;
/* Copy the default MAC, PHY and NVM function pointers */
memcpy(&hw->mac.ops, ei->mac_ops, sizeof(hw->mac.ops));
memcpy(&hw->phy.ops, ei->phy_ops, sizeof(hw->phy.ops));
memcpy(&hw->nvm.ops, ei->nvm_ops, sizeof(hw->nvm.ops));
/* Initialize skew-specific constants */
err = ei->get_invariants(hw);
if (err)
goto err_sw_init;
/* setup the private structure */
err = igb_sw_init(adapter);
if (err)
goto err_sw_init;
igb_get_bus_info_pcie(hw);
hw->phy.autoneg_wait_to_complete = false;
hw->mac.adaptive_ifs = true;
/* Copper options */
if (hw->phy.media_type == e1000_media_type_copper) {
hw->phy.mdix = AUTO_ALL_MODES;
hw->phy.disable_polarity_correction = false;
hw->phy.ms_type = e1000_ms_hw_default;
}
if (igb_check_reset_block(hw))
dev_info(&pdev->dev,
"PHY reset is blocked due to SOL/IDER session.\n");
netdev->features = NETIF_F_SG |
NETIF_F_IP_CSUM |
NETIF_F_HW_VLAN_TX |
NETIF_F_HW_VLAN_RX |
NETIF_F_HW_VLAN_FILTER;
netdev->features |= NETIF_F_IPV6_CSUM;
netdev->features |= NETIF_F_TSO;
netdev->features |= NETIF_F_TSO6;
netdev->features |= NETIF_F_GRO;
netdev->vlan_features |= NETIF_F_TSO;
netdev->vlan_features |= NETIF_F_TSO6;
netdev->vlan_features |= NETIF_F_IP_CSUM;
netdev->vlan_features |= NETIF_F_IPV6_CSUM;
netdev->vlan_features |= NETIF_F_SG;
if (pci_using_dac)
netdev->features |= NETIF_F_HIGHDMA;
if (hw->mac.type >= e1000_82576)
netdev->features |= NETIF_F_SCTP_CSUM;
adapter->en_mng_pt = igb_enable_mng_pass_thru(hw);
/* before reading the NVM, reset the controller to put the device in a
* known good starting state */
hw->mac.ops.reset_hw(hw);
/* make sure the NVM is good */
if (igb_validate_nvm_checksum(hw) < 0) {
dev_err(&pdev->dev, "The NVM Checksum Is Not Valid\n");
err = -EIO;
goto err_eeprom;
}
/* copy the MAC address out of the NVM */
if (hw->mac.ops.read_mac_addr(hw))
dev_err(&pdev->dev, "NVM Read Error\n");
memcpy(netdev->dev_addr, hw->mac.addr, netdev->addr_len);
memcpy(netdev->perm_addr, hw->mac.addr, netdev->addr_len);
if (!is_valid_ether_addr(netdev->perm_addr)) {
dev_err(&pdev->dev, "Invalid MAC Address\n");
err = -EIO;
goto err_eeprom;
}
setup_timer(&adapter->watchdog_timer, &igb_watchdog,
(unsigned long) adapter);
setup_timer(&adapter->phy_info_timer, &igb_update_phy_info,
(unsigned long) adapter);
INIT_WORK(&adapter->reset_task, igb_reset_task);
INIT_WORK(&adapter->watchdog_task, igb_watchdog_task);
/* Initialize link properties that are user-changeable */
adapter->fc_autoneg = true;
hw->mac.autoneg = true;
hw->phy.autoneg_advertised = 0x2f;
hw->fc.requested_mode = e1000_fc_default;
hw->fc.current_mode = e1000_fc_default;
igb_validate_mdi_setting(hw);
/* Initial Wake on LAN setting If APM wake is enabled in the EEPROM,
* enable the ACPI Magic Packet filter
*/
if (hw->bus.func == 0)
hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_A, 1, &eeprom_data);
else if (hw->mac.type == e1000_82580)
hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_A +
NVM_82580_LAN_FUNC_OFFSET(hw->bus.func), 1,
&eeprom_data);
else if (hw->bus.func == 1)
hw->nvm.ops.read(hw, NVM_INIT_CONTROL3_PORT_B, 1, &eeprom_data);
if (eeprom_data & eeprom_apme_mask)
adapter->eeprom_wol |= E1000_WUFC_MAG;
/* now that we have the eeprom settings, apply the special cases where
* the eeprom may be wrong or the board simply won't support wake on
* lan on a particular port */
switch (pdev->device) {
case E1000_DEV_ID_82575GB_QUAD_COPPER:
adapter->eeprom_wol = 0;
break;
case E1000_DEV_ID_82575EB_FIBER_SERDES:
case E1000_DEV_ID_82576_FIBER:
case E1000_DEV_ID_82576_SERDES:
/* Wake events only supported on port A for dual fiber
* regardless of eeprom setting */
if (rd32(E1000_STATUS) & E1000_STATUS_FUNC_1)
adapter->eeprom_wol = 0;
break;
case E1000_DEV_ID_82576_QUAD_COPPER:
/* if quad port adapter, disable WoL on all but port A */
if (global_quad_port_a != 0)
adapter->eeprom_wol = 0;
else
adapter->flags |= IGB_FLAG_QUAD_PORT_A;
/* Reset for multiple quad port adapters */
if (++global_quad_port_a == 4)
global_quad_port_a = 0;
break;
}
/* initialize the wol settings based on the eeprom settings */
adapter->wol = adapter->eeprom_wol;
device_set_wakeup_enable(&adapter->pdev->dev, adapter->wol);
/* reset the hardware with the new settings */
igb_reset(adapter);
/* let the f/w know that the h/w is now under the control of the
* driver. */
igb_get_hw_control(adapter);
strcpy(netdev->name, "eth%d");
err = register_netdev(netdev);
if (err)
goto err_register;
/* carrier off reporting is important to ethtool even BEFORE open */
netif_carrier_off(netdev);
#ifdef CONFIG_IGB_DCA
if (dca_add_requester(&pdev->dev) == 0) {
adapter->flags |= IGB_FLAG_DCA_ENABLED;
dev_info(&pdev->dev, "DCA enabled\n");
igb_setup_dca(adapter);
}
#endif
dev_info(&pdev->dev, "Intel(R) Gigabit Ethernet Network Connection\n");
/* print bus type/speed/width info */
dev_info(&pdev->dev, "%s: (PCIe:%s:%s) %pM\n",
netdev->name,
((hw->bus.speed == e1000_bus_speed_2500) ? "2.5Gb/s" :
"unknown"),
((hw->bus.width == e1000_bus_width_pcie_x4) ? "Width x4" :
(hw->bus.width == e1000_bus_width_pcie_x2) ? "Width x2" :
(hw->bus.width == e1000_bus_width_pcie_x1) ? "Width x1" :
"unknown"),
netdev->dev_addr);
igb_read_part_num(hw, &part_num);
dev_info(&pdev->dev, "%s: PBA No: %06x-%03x\n", netdev->name,
(part_num >> 8), (part_num & 0xff));
dev_info(&pdev->dev,
"Using %s interrupts. %d rx queue(s), %d tx queue(s)\n",
adapter->msix_entries ? "MSI-X" :
(adapter->flags & IGB_FLAG_HAS_MSI) ? "MSI" : "legacy",
adapter->num_rx_queues, adapter->num_tx_queues);
return 0;
err_register:
igb_release_hw_control(adapter);
err_eeprom:
if (!igb_check_reset_block(hw))
igb_reset_phy(hw);
if (hw->flash_address)
iounmap(hw->flash_address);
err_sw_init:
igb_clear_interrupt_scheme(adapter);
iounmap(hw->hw_addr);
err_ioremap:
free_netdev(netdev);
err_alloc_etherdev:
pci_release_selected_regions(pdev,
pci_select_bars(pdev, IORESOURCE_MEM));
err_pci_reg:
err_dma:
pci_disable_device(pdev);
return err;
}
/**
* igb_remove - Device Removal Routine
* @pdev: PCI device information struct
*
* igb_remove is called by the PCI subsystem to alert the driver
* that it should release a PCI device. The could be caused by a
* Hot-Plug event, or because the driver is going to be removed from
* memory.
**/
static void __devexit igb_remove(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
/* flush_scheduled work may reschedule our watchdog task, so
* explicitly disable watchdog tasks from being rescheduled */
set_bit(__IGB_DOWN, &adapter->state);
del_timer_sync(&adapter->watchdog_timer);
del_timer_sync(&adapter->phy_info_timer);
flush_scheduled_work();
#ifdef CONFIG_IGB_DCA
if (adapter->flags & IGB_FLAG_DCA_ENABLED) {
dev_info(&pdev->dev, "DCA disabled\n");
dca_remove_requester(&pdev->dev);
adapter->flags &= ~IGB_FLAG_DCA_ENABLED;
wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE);
}
#endif
/* Release control of h/w to f/w. If f/w is AMT enabled, this
* would have already happened in close and is redundant. */
igb_release_hw_control(adapter);
unregister_netdev(netdev);
if (!igb_check_reset_block(hw))
igb_reset_phy(hw);
igb_clear_interrupt_scheme(adapter);
#ifdef CONFIG_PCI_IOV
/* reclaim resources allocated to VFs */
if (adapter->vf_data) {
/* disable iov and allow time for transactions to clear */
pci_disable_sriov(pdev);
msleep(500);
kfree(adapter->vf_data);
adapter->vf_data = NULL;
wr32(E1000_IOVCTL, E1000_IOVCTL_REUSE_VFQ);
msleep(100);
dev_info(&pdev->dev, "IOV Disabled\n");
}
#endif
iounmap(hw->hw_addr);
if (hw->flash_address)
iounmap(hw->flash_address);
pci_release_selected_regions(pdev,
pci_select_bars(pdev, IORESOURCE_MEM));
free_netdev(netdev);
pci_disable_pcie_error_reporting(pdev);
pci_disable_device(pdev);
}
/**
* igb_probe_vfs - Initialize vf data storage and add VFs to pci config space
* @adapter: board private structure to initialize
*
* This function initializes the vf specific data storage and then attempts to
* allocate the VFs. The reason for ordering it this way is because it is much
* mor expensive time wise to disable SR-IOV than it is to allocate and free
* the memory for the VFs.
**/
static void __devinit igb_probe_vfs(struct igb_adapter * adapter)
{
#ifdef CONFIG_PCI_IOV
struct pci_dev *pdev = adapter->pdev;
if (adapter->vfs_allocated_count > 7)
adapter->vfs_allocated_count = 7;
if (adapter->vfs_allocated_count) {
adapter->vf_data = kcalloc(adapter->vfs_allocated_count,
sizeof(struct vf_data_storage),
GFP_KERNEL);
/* if allocation failed then we do not support SR-IOV */
if (!adapter->vf_data) {
adapter->vfs_allocated_count = 0;
dev_err(&pdev->dev, "Unable to allocate memory for VF "
"Data Storage\n");
}
}
if (pci_enable_sriov(pdev, adapter->vfs_allocated_count)) {
kfree(adapter->vf_data);
adapter->vf_data = NULL;
#endif /* CONFIG_PCI_IOV */
adapter->vfs_allocated_count = 0;
#ifdef CONFIG_PCI_IOV
} else {
unsigned char mac_addr[ETH_ALEN];
int i;
dev_info(&pdev->dev, "%d vfs allocated\n",
adapter->vfs_allocated_count);
for (i = 0; i < adapter->vfs_allocated_count; i++) {
random_ether_addr(mac_addr);
igb_set_vf_mac(adapter, i, mac_addr);
}
}
#endif /* CONFIG_PCI_IOV */
}
/**
* igb_init_hw_timer - Initialize hardware timer used with IEEE 1588 timestamp
* @adapter: board private structure to initialize
*
* igb_init_hw_timer initializes the function pointer and values for the hw
* timer found in hardware.
**/
static void igb_init_hw_timer(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
switch (hw->mac.type) {
case e1000_82580:
memset(&adapter->cycles, 0, sizeof(adapter->cycles));
adapter->cycles.read = igb_read_clock;
adapter->cycles.mask = CLOCKSOURCE_MASK(64);
adapter->cycles.mult = 1;
/*
* The 82580 timesync updates the system timer every 8ns by 8ns
* and the value cannot be shifted. Instead we need to shift
* the registers to generate a 64bit timer value. As a result
* SYSTIMR/L/H, TXSTMPL/H, RXSTMPL/H all have to be shifted by
* 24 in order to generate a larger value for synchronization.
*/
adapter->cycles.shift = IGB_82580_TSYNC_SHIFT;
/* disable system timer temporarily by setting bit 31 */
wr32(E1000_TSAUXC, 0x80000000);
wrfl();
/* Set registers so that rollover occurs soon to test this. */
wr32(E1000_SYSTIMR, 0x00000000);
wr32(E1000_SYSTIML, 0x80000000);
wr32(E1000_SYSTIMH, 0x000000FF);
wrfl();
/* enable system timer by clearing bit 31 */
wr32(E1000_TSAUXC, 0x0);
wrfl();
timecounter_init(&adapter->clock,
&adapter->cycles,
ktime_to_ns(ktime_get_real()));
/*
* Synchronize our NIC clock against system wall clock. NIC
* time stamp reading requires ~3us per sample, each sample
* was pretty stable even under load => only require 10
* samples for each offset comparison.
*/
memset(&adapter->compare, 0, sizeof(adapter->compare));
adapter->compare.source = &adapter->clock;
adapter->compare.target = ktime_get_real;
adapter->compare.num_samples = 10;
timecompare_update(&adapter->compare, 0);
break;
case e1000_82576:
/*
* Initialize hardware timer: we keep it running just in case
* that some program needs it later on.
*/
memset(&adapter->cycles, 0, sizeof(adapter->cycles));
adapter->cycles.read = igb_read_clock;
adapter->cycles.mask = CLOCKSOURCE_MASK(64);
adapter->cycles.mult = 1;
/**
* Scale the NIC clock cycle by a large factor so that
* relatively small clock corrections can be added or
* substracted at each clock tick. The drawbacks of a large
* factor are a) that the clock register overflows more quickly
* (not such a big deal) and b) that the increment per tick has
* to fit into 24 bits. As a result we need to use a shift of
* 19 so we can fit a value of 16 into the TIMINCA register.
*/
adapter->cycles.shift = IGB_82576_TSYNC_SHIFT;
wr32(E1000_TIMINCA,
(1 << E1000_TIMINCA_16NS_SHIFT) |
(16 << IGB_82576_TSYNC_SHIFT));
/* Set registers so that rollover occurs soon to test this. */
wr32(E1000_SYSTIML, 0x00000000);
wr32(E1000_SYSTIMH, 0xFF800000);
wrfl();
timecounter_init(&adapter->clock,
&adapter->cycles,
ktime_to_ns(ktime_get_real()));
/*
* Synchronize our NIC clock against system wall clock. NIC
* time stamp reading requires ~3us per sample, each sample
* was pretty stable even under load => only require 10
* samples for each offset comparison.
*/
memset(&adapter->compare, 0, sizeof(adapter->compare));
adapter->compare.source = &adapter->clock;
adapter->compare.target = ktime_get_real;
adapter->compare.num_samples = 10;
timecompare_update(&adapter->compare, 0);
break;
case e1000_82575:
/* 82575 does not support timesync */
default:
break;
}
}
/**
* igb_sw_init - Initialize general software structures (struct igb_adapter)
* @adapter: board private structure to initialize
*
* igb_sw_init initializes the Adapter private data structure.
* Fields are initialized based on PCI device information and
* OS network device settings (MTU size).
**/
static int __devinit igb_sw_init(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
struct pci_dev *pdev = adapter->pdev;
pci_read_config_word(pdev, PCI_COMMAND, &hw->bus.pci_cmd_word);
adapter->tx_ring_count = IGB_DEFAULT_TXD;
adapter->rx_ring_count = IGB_DEFAULT_RXD;
adapter->rx_itr_setting = IGB_DEFAULT_ITR;
adapter->tx_itr_setting = IGB_DEFAULT_ITR;
adapter->max_frame_size = netdev->mtu + ETH_HLEN + ETH_FCS_LEN;
adapter->min_frame_size = ETH_ZLEN + ETH_FCS_LEN;
#ifdef CONFIG_PCI_IOV
if (hw->mac.type == e1000_82576)
adapter->vfs_allocated_count = max_vfs;
#endif /* CONFIG_PCI_IOV */
adapter->rss_queues = min_t(u32, IGB_MAX_RX_QUEUES, num_online_cpus());
/*
* if rss_queues > 4 or vfs are going to be allocated with rss_queues
* then we should combine the queues into a queue pair in order to
* conserve interrupts due to limited supply
*/
if ((adapter->rss_queues > 4) ||
((adapter->rss_queues > 1) && (adapter->vfs_allocated_count > 6)))
adapter->flags |= IGB_FLAG_QUEUE_PAIRS;
/* This call may decrease the number of queues */
if (igb_init_interrupt_scheme(adapter)) {
dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
return -ENOMEM;
}
igb_init_hw_timer(adapter);
igb_probe_vfs(adapter);
/* Explicitly disable IRQ since the NIC can be in any state. */
igb_irq_disable(adapter);
set_bit(__IGB_DOWN, &adapter->state);
return 0;
}
/**
* igb_open - Called when a network interface is made active
* @netdev: network interface device structure
*
* Returns 0 on success, negative value on failure
*
* The open entry point is called when a network interface is made
* active by the system (IFF_UP). At this point all resources needed
* for transmit and receive operations are allocated, the interrupt
* handler is registered with the OS, the watchdog timer is started,
* and the stack is notified that the interface is ready.
**/
static int igb_open(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int err;
int i;
/* disallow open during test */
if (test_bit(__IGB_TESTING, &adapter->state))
return -EBUSY;
netif_carrier_off(netdev);
/* allocate transmit descriptors */
err = igb_setup_all_tx_resources(adapter);
if (err)
goto err_setup_tx;
/* allocate receive descriptors */
err = igb_setup_all_rx_resources(adapter);
if (err)
goto err_setup_rx;
/* e1000_power_up_phy(adapter); */
/* before we allocate an interrupt, we must be ready to handle it.
* Setting DEBUG_SHIRQ in the kernel makes it fire an interrupt
* as soon as we call pci_request_irq, so we have to setup our
* clean_rx handler before we do so. */
igb_configure(adapter);
err = igb_request_irq(adapter);
if (err)
goto err_req_irq;
/* From here on the code is the same as igb_up() */
clear_bit(__IGB_DOWN, &adapter->state);
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
napi_enable(&q_vector->napi);
}
/* Clear any pending interrupts. */
rd32(E1000_ICR);
igb_irq_enable(adapter);
/* notify VFs that reset has been completed */
if (adapter->vfs_allocated_count) {
u32 reg_data = rd32(E1000_CTRL_EXT);
reg_data |= E1000_CTRL_EXT_PFRSTD;
wr32(E1000_CTRL_EXT, reg_data);
}
netif_tx_start_all_queues(netdev);
/* start the watchdog. */
hw->mac.get_link_status = 1;
schedule_work(&adapter->watchdog_task);
return 0;
err_req_irq:
igb_release_hw_control(adapter);
/* e1000_power_down_phy(adapter); */
igb_free_all_rx_resources(adapter);
err_setup_rx:
igb_free_all_tx_resources(adapter);
err_setup_tx:
igb_reset(adapter);
return err;
}
/**
* igb_close - Disables a network interface
* @netdev: network interface device structure
*
* Returns 0, this is not allowed to fail
*
* The close entry point is called when an interface is de-activated
* by the OS. The hardware is still under the driver's control, but
* needs to be disabled. A global MAC reset is issued to stop the
* hardware, and all transmit and receive resources are freed.
**/
static int igb_close(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
WARN_ON(test_bit(__IGB_RESETTING, &adapter->state));
igb_down(adapter);
igb_free_irq(adapter);
igb_free_all_tx_resources(adapter);
igb_free_all_rx_resources(adapter);
return 0;
}
/**
* igb_setup_tx_resources - allocate Tx resources (Descriptors)
* @tx_ring: tx descriptor ring (for a specific queue) to setup
*
* Return 0 on success, negative on failure
**/
int igb_setup_tx_resources(struct igb_ring *tx_ring)
{
struct pci_dev *pdev = tx_ring->pdev;
int size;
size = sizeof(struct igb_buffer) * tx_ring->count;
tx_ring->buffer_info = vmalloc(size);
if (!tx_ring->buffer_info)
goto err;
memset(tx_ring->buffer_info, 0, size);
/* round up to nearest 4K */
tx_ring->size = tx_ring->count * sizeof(union e1000_adv_tx_desc);
tx_ring->size = ALIGN(tx_ring->size, 4096);
tx_ring->desc = pci_alloc_consistent(pdev,
tx_ring->size,
&tx_ring->dma);
if (!tx_ring->desc)
goto err;
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
return 0;
err:
vfree(tx_ring->buffer_info);
dev_err(&pdev->dev,
"Unable to allocate memory for the transmit descriptor ring\n");
return -ENOMEM;
}
/**
* igb_setup_all_tx_resources - wrapper to allocate Tx resources
* (Descriptors) for all queues
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
static int igb_setup_all_tx_resources(struct igb_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int i, err = 0;
for (i = 0; i < adapter->num_tx_queues; i++) {
err = igb_setup_tx_resources(&adapter->tx_ring[i]);
if (err) {
dev_err(&pdev->dev,
"Allocation for Tx Queue %u failed\n", i);
for (i--; i >= 0; i--)
igb_free_tx_resources(&adapter->tx_ring[i]);
break;
}
}
for (i = 0; i < IGB_ABS_MAX_TX_QUEUES; i++) {
int r_idx = i % adapter->num_tx_queues;
adapter->multi_tx_table[i] = &adapter->tx_ring[r_idx];
}
return err;
}
/**
* igb_setup_tctl - configure the transmit control registers
* @adapter: Board private structure
**/
void igb_setup_tctl(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 tctl;
/* disable queue 0 which is enabled by default on 82575 and 82576 */
wr32(E1000_TXDCTL(0), 0);
/* Program the Transmit Control Register */
tctl = rd32(E1000_TCTL);
tctl &= ~E1000_TCTL_CT;
tctl |= E1000_TCTL_PSP | E1000_TCTL_RTLC |
(E1000_COLLISION_THRESHOLD << E1000_CT_SHIFT);
igb_config_collision_dist(hw);
/* Enable transmits */
tctl |= E1000_TCTL_EN;
wr32(E1000_TCTL, tctl);
}
/**
* igb_configure_tx_ring - Configure transmit ring after Reset
* @adapter: board private structure
* @ring: tx ring to configure
*
* Configure a transmit ring after a reset.
**/
void igb_configure_tx_ring(struct igb_adapter *adapter,
struct igb_ring *ring)
{
struct e1000_hw *hw = &adapter->hw;
u32 txdctl;
u64 tdba = ring->dma;
int reg_idx = ring->reg_idx;
/* disable the queue */
txdctl = rd32(E1000_TXDCTL(reg_idx));
wr32(E1000_TXDCTL(reg_idx),
txdctl & ~E1000_TXDCTL_QUEUE_ENABLE);
wrfl();
mdelay(10);
wr32(E1000_TDLEN(reg_idx),
ring->count * sizeof(union e1000_adv_tx_desc));
wr32(E1000_TDBAL(reg_idx),
tdba & 0x00000000ffffffffULL);
wr32(E1000_TDBAH(reg_idx), tdba >> 32);
ring->head = hw->hw_addr + E1000_TDH(reg_idx);
ring->tail = hw->hw_addr + E1000_TDT(reg_idx);
writel(0, ring->head);
writel(0, ring->tail);
txdctl |= IGB_TX_PTHRESH;
txdctl |= IGB_TX_HTHRESH << 8;
txdctl |= IGB_TX_WTHRESH << 16;
txdctl |= E1000_TXDCTL_QUEUE_ENABLE;
wr32(E1000_TXDCTL(reg_idx), txdctl);
}
/**
* igb_configure_tx - Configure transmit Unit after Reset
* @adapter: board private structure
*
* Configure the Tx unit of the MAC after a reset.
**/
static void igb_configure_tx(struct igb_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
igb_configure_tx_ring(adapter, &adapter->tx_ring[i]);
}
/**
* igb_setup_rx_resources - allocate Rx resources (Descriptors)
* @rx_ring: rx descriptor ring (for a specific queue) to setup
*
* Returns 0 on success, negative on failure
**/
int igb_setup_rx_resources(struct igb_ring *rx_ring)
{
struct pci_dev *pdev = rx_ring->pdev;
int size, desc_len;
size = sizeof(struct igb_buffer) * rx_ring->count;
rx_ring->buffer_info = vmalloc(size);
if (!rx_ring->buffer_info)
goto err;
memset(rx_ring->buffer_info, 0, size);
desc_len = sizeof(union e1000_adv_rx_desc);
/* Round up to nearest 4K */
rx_ring->size = rx_ring->count * desc_len;
rx_ring->size = ALIGN(rx_ring->size, 4096);
rx_ring->desc = pci_alloc_consistent(pdev, rx_ring->size,
&rx_ring->dma);
if (!rx_ring->desc)
goto err;
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
return 0;
err:
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
dev_err(&pdev->dev, "Unable to allocate memory for "
"the receive descriptor ring\n");
return -ENOMEM;
}
/**
* igb_setup_all_rx_resources - wrapper to allocate Rx resources
* (Descriptors) for all queues
* @adapter: board private structure
*
* Return 0 on success, negative on failure
**/
static int igb_setup_all_rx_resources(struct igb_adapter *adapter)
{
struct pci_dev *pdev = adapter->pdev;
int i, err = 0;
for (i = 0; i < adapter->num_rx_queues; i++) {
err = igb_setup_rx_resources(&adapter->rx_ring[i]);
if (err) {
dev_err(&pdev->dev,
"Allocation for Rx Queue %u failed\n", i);
for (i--; i >= 0; i--)
igb_free_rx_resources(&adapter->rx_ring[i]);
break;
}
}
return err;
}
/**
* igb_setup_mrqc - configure the multiple receive queue control registers
* @adapter: Board private structure
**/
static void igb_setup_mrqc(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 mrqc, rxcsum;
u32 j, num_rx_queues, shift = 0, shift2 = 0;
union e1000_reta {
u32 dword;
u8 bytes[4];
} reta;
static const u8 rsshash[40] = {
0x6d, 0x5a, 0x56, 0xda, 0x25, 0x5b, 0x0e, 0xc2, 0x41, 0x67,
0x25, 0x3d, 0x43, 0xa3, 0x8f, 0xb0, 0xd0, 0xca, 0x2b, 0xcb,
0xae, 0x7b, 0x30, 0xb4, 0x77, 0xcb, 0x2d, 0xa3, 0x80, 0x30,
0xf2, 0x0c, 0x6a, 0x42, 0xb7, 0x3b, 0xbe, 0xac, 0x01, 0xfa };
/* Fill out hash function seeds */
for (j = 0; j < 10; j++) {
u32 rsskey = rsshash[(j * 4)];
rsskey |= rsshash[(j * 4) + 1] << 8;
rsskey |= rsshash[(j * 4) + 2] << 16;
rsskey |= rsshash[(j * 4) + 3] << 24;
array_wr32(E1000_RSSRK(0), j, rsskey);
}
num_rx_queues = adapter->rss_queues;
if (adapter->vfs_allocated_count) {
/* 82575 and 82576 supports 2 RSS queues for VMDq */
switch (hw->mac.type) {
case e1000_82580:
num_rx_queues = 1;
shift = 0;
break;
case e1000_82576:
shift = 3;
num_rx_queues = 2;
break;
case e1000_82575:
shift = 2;
shift2 = 6;
default:
break;
}
} else {
if (hw->mac.type == e1000_82575)
shift = 6;
}
for (j = 0; j < (32 * 4); j++) {
reta.bytes[j & 3] = (j % num_rx_queues) << shift;
if (shift2)
reta.bytes[j & 3] |= num_rx_queues << shift2;
if ((j & 3) == 3)
wr32(E1000_RETA(j >> 2), reta.dword);
}
/*
* Disable raw packet checksumming so that RSS hash is placed in
* descriptor on writeback. No need to enable TCP/UDP/IP checksum
* offloads as they are enabled by default
*/
rxcsum = rd32(E1000_RXCSUM);
rxcsum |= E1000_RXCSUM_PCSD;
if (adapter->hw.mac.type >= e1000_82576)
/* Enable Receive Checksum Offload for SCTP */
rxcsum |= E1000_RXCSUM_CRCOFL;
/* Don't need to set TUOFL or IPOFL, they default to 1 */
wr32(E1000_RXCSUM, rxcsum);
/* If VMDq is enabled then we set the appropriate mode for that, else
* we default to RSS so that an RSS hash is calculated per packet even
* if we are only using one queue */
if (adapter->vfs_allocated_count) {
if (hw->mac.type > e1000_82575) {
/* Set the default pool for the PF's first queue */
u32 vtctl = rd32(E1000_VT_CTL);
vtctl &= ~(E1000_VT_CTL_DEFAULT_POOL_MASK |
E1000_VT_CTL_DISABLE_DEF_POOL);
vtctl |= adapter->vfs_allocated_count <<
E1000_VT_CTL_DEFAULT_POOL_SHIFT;
wr32(E1000_VT_CTL, vtctl);
}
if (adapter->rss_queues > 1)
mrqc = E1000_MRQC_ENABLE_VMDQ_RSS_2Q;
else
mrqc = E1000_MRQC_ENABLE_VMDQ;
} else {
mrqc = E1000_MRQC_ENABLE_RSS_4Q;
}
igb_vmm_control(adapter);
mrqc |= (E1000_MRQC_RSS_FIELD_IPV4 |
E1000_MRQC_RSS_FIELD_IPV4_TCP);
mrqc |= (E1000_MRQC_RSS_FIELD_IPV6 |
E1000_MRQC_RSS_FIELD_IPV6_TCP);
mrqc |= (E1000_MRQC_RSS_FIELD_IPV4_UDP |
E1000_MRQC_RSS_FIELD_IPV6_UDP);
mrqc |= (E1000_MRQC_RSS_FIELD_IPV6_UDP_EX |
E1000_MRQC_RSS_FIELD_IPV6_TCP_EX);
wr32(E1000_MRQC, mrqc);
}
/**
* igb_setup_rctl - configure the receive control registers
* @adapter: Board private structure
**/
void igb_setup_rctl(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 rctl;
rctl = rd32(E1000_RCTL);
rctl &= ~(3 << E1000_RCTL_MO_SHIFT);
rctl &= ~(E1000_RCTL_LBM_TCVR | E1000_RCTL_LBM_MAC);
rctl |= E1000_RCTL_EN | E1000_RCTL_BAM | E1000_RCTL_RDMTS_HALF |
(hw->mac.mc_filter_type << E1000_RCTL_MO_SHIFT);
/*
* enable stripping of CRC. It's unlikely this will break BMC
* redirection as it did with e1000. Newer features require
* that the HW strips the CRC.
*/
rctl |= E1000_RCTL_SECRC;
/* disable store bad packets and clear size bits. */
rctl &= ~(E1000_RCTL_SBP | E1000_RCTL_SZ_256);
/* enable LPE to prevent packets larger than max_frame_size */
rctl |= E1000_RCTL_LPE;
/* disable queue 0 to prevent tail write w/o re-config */
wr32(E1000_RXDCTL(0), 0);
/* Attention!!! For SR-IOV PF driver operations you must enable
* queue drop for all VF and PF queues to prevent head of line blocking
* if an un-trusted VF does not provide descriptors to hardware.
*/
if (adapter->vfs_allocated_count) {
/* set all queue drop enable bits */
wr32(E1000_QDE, ALL_QUEUES);
}
wr32(E1000_RCTL, rctl);
}
static inline int igb_set_vf_rlpml(struct igb_adapter *adapter, int size,
int vfn)
{
struct e1000_hw *hw = &adapter->hw;
u32 vmolr;
/* if it isn't the PF check to see if VFs are enabled and
* increase the size to support vlan tags */
if (vfn < adapter->vfs_allocated_count &&
adapter->vf_data[vfn].vlans_enabled)
size += VLAN_TAG_SIZE;
vmolr = rd32(E1000_VMOLR(vfn));
vmolr &= ~E1000_VMOLR_RLPML_MASK;
vmolr |= size | E1000_VMOLR_LPE;
wr32(E1000_VMOLR(vfn), vmolr);
return 0;
}
/**
* igb_rlpml_set - set maximum receive packet size
* @adapter: board private structure
*
* Configure maximum receivable packet size.
**/
static void igb_rlpml_set(struct igb_adapter *adapter)
{
u32 max_frame_size = adapter->max_frame_size;
struct e1000_hw *hw = &adapter->hw;
u16 pf_id = adapter->vfs_allocated_count;
if (adapter->vlgrp)
max_frame_size += VLAN_TAG_SIZE;
/* if vfs are enabled we set RLPML to the largest possible request
* size and set the VMOLR RLPML to the size we need */
if (pf_id) {
igb_set_vf_rlpml(adapter, max_frame_size, pf_id);
max_frame_size = MAX_JUMBO_FRAME_SIZE;
}
wr32(E1000_RLPML, max_frame_size);
}
static inline void igb_set_vmolr(struct igb_adapter *adapter, int vfn)
{
struct e1000_hw *hw = &adapter->hw;
u32 vmolr;
/*
* This register exists only on 82576 and newer so if we are older then
* we should exit and do nothing
*/
if (hw->mac.type < e1000_82576)
return;
vmolr = rd32(E1000_VMOLR(vfn));
vmolr |= E1000_VMOLR_AUPE | /* Accept untagged packets */
E1000_VMOLR_STRVLAN; /* Strip vlan tags */
/* clear all bits that might not be set */
vmolr &= ~(E1000_VMOLR_BAM | E1000_VMOLR_RSSE);
if (adapter->rss_queues > 1 && vfn == adapter->vfs_allocated_count)
vmolr |= E1000_VMOLR_RSSE; /* enable RSS */
/*
* for VMDq only allow the VFs and pool 0 to accept broadcast and
* multicast packets
*/
if (vfn <= adapter->vfs_allocated_count)
vmolr |= E1000_VMOLR_BAM; /* Accept broadcast */
wr32(E1000_VMOLR(vfn), vmolr);
}
/**
* igb_configure_rx_ring - Configure a receive ring after Reset
* @adapter: board private structure
* @ring: receive ring to be configured
*
* Configure the Rx unit of the MAC after a reset.
**/
void igb_configure_rx_ring(struct igb_adapter *adapter,
struct igb_ring *ring)
{
struct e1000_hw *hw = &adapter->hw;
u64 rdba = ring->dma;
int reg_idx = ring->reg_idx;
u32 srrctl, rxdctl;
/* disable the queue */
rxdctl = rd32(E1000_RXDCTL(reg_idx));
wr32(E1000_RXDCTL(reg_idx),
rxdctl & ~E1000_RXDCTL_QUEUE_ENABLE);
/* Set DMA base address registers */
wr32(E1000_RDBAL(reg_idx),
rdba & 0x00000000ffffffffULL);
wr32(E1000_RDBAH(reg_idx), rdba >> 32);
wr32(E1000_RDLEN(reg_idx),
ring->count * sizeof(union e1000_adv_rx_desc));
/* initialize head and tail */
ring->head = hw->hw_addr + E1000_RDH(reg_idx);
ring->tail = hw->hw_addr + E1000_RDT(reg_idx);
writel(0, ring->head);
writel(0, ring->tail);
/* set descriptor configuration */
if (ring->rx_buffer_len < IGB_RXBUFFER_1024) {
srrctl = ALIGN(ring->rx_buffer_len, 64) <<
E1000_SRRCTL_BSIZEHDRSIZE_SHIFT;
#if (PAGE_SIZE / 2) > IGB_RXBUFFER_16384
srrctl |= IGB_RXBUFFER_16384 >>
E1000_SRRCTL_BSIZEPKT_SHIFT;
#else
srrctl |= (PAGE_SIZE / 2) >>
E1000_SRRCTL_BSIZEPKT_SHIFT;
#endif
srrctl |= E1000_SRRCTL_DESCTYPE_HDR_SPLIT_ALWAYS;
} else {
srrctl = ALIGN(ring->rx_buffer_len, 1024) >>
E1000_SRRCTL_BSIZEPKT_SHIFT;
srrctl |= E1000_SRRCTL_DESCTYPE_ADV_ONEBUF;
}
wr32(E1000_SRRCTL(reg_idx), srrctl);
/* set filtering for VMDQ pools */
igb_set_vmolr(adapter, reg_idx & 0x7);
/* enable receive descriptor fetching */
rxdctl = rd32(E1000_RXDCTL(reg_idx));
rxdctl |= E1000_RXDCTL_QUEUE_ENABLE;
rxdctl &= 0xFFF00000;
rxdctl |= IGB_RX_PTHRESH;
rxdctl |= IGB_RX_HTHRESH << 8;
rxdctl |= IGB_RX_WTHRESH << 16;
wr32(E1000_RXDCTL(reg_idx), rxdctl);
}
/**
* igb_configure_rx - Configure receive Unit after Reset
* @adapter: board private structure
*
* Configure the Rx unit of the MAC after a reset.
**/
static void igb_configure_rx(struct igb_adapter *adapter)
{
int i;
/* set UTA to appropriate mode */
igb_set_uta(adapter);
/* set the correct pool for the PF default MAC address in entry 0 */
igb_rar_set_qsel(adapter, adapter->hw.mac.addr, 0,
adapter->vfs_allocated_count);
/* Setup the HW Rx Head and Tail Descriptor Pointers and
* the Base and Length of the Rx Descriptor Ring */
for (i = 0; i < adapter->num_rx_queues; i++)
igb_configure_rx_ring(adapter, &adapter->rx_ring[i]);
}
/**
* igb_free_tx_resources - Free Tx Resources per Queue
* @tx_ring: Tx descriptor ring for a specific queue
*
* Free all transmit software resources
**/
void igb_free_tx_resources(struct igb_ring *tx_ring)
{
igb_clean_tx_ring(tx_ring);
vfree(tx_ring->buffer_info);
tx_ring->buffer_info = NULL;
/* if not set, then don't free */
if (!tx_ring->desc)
return;
pci_free_consistent(tx_ring->pdev, tx_ring->size,
tx_ring->desc, tx_ring->dma);
tx_ring->desc = NULL;
}
/**
* igb_free_all_tx_resources - Free Tx Resources for All Queues
* @adapter: board private structure
*
* Free all transmit software resources
**/
static void igb_free_all_tx_resources(struct igb_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
igb_free_tx_resources(&adapter->tx_ring[i]);
}
void igb_unmap_and_free_tx_resource(struct igb_ring *tx_ring,
struct igb_buffer *buffer_info)
{
if (buffer_info->dma) {
if (buffer_info->mapped_as_page)
pci_unmap_page(tx_ring->pdev,
buffer_info->dma,
buffer_info->length,
PCI_DMA_TODEVICE);
else
pci_unmap_single(tx_ring->pdev,
buffer_info->dma,
buffer_info->length,
PCI_DMA_TODEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb_any(buffer_info->skb);
buffer_info->skb = NULL;
}
buffer_info->time_stamp = 0;
buffer_info->length = 0;
buffer_info->next_to_watch = 0;
buffer_info->mapped_as_page = false;
}
/**
* igb_clean_tx_ring - Free Tx Buffers
* @tx_ring: ring to be cleaned
**/
static void igb_clean_tx_ring(struct igb_ring *tx_ring)
{
struct igb_buffer *buffer_info;
unsigned long size;
unsigned int i;
if (!tx_ring->buffer_info)
return;
/* Free all the Tx ring sk_buffs */
for (i = 0; i < tx_ring->count; i++) {
buffer_info = &tx_ring->buffer_info[i];
igb_unmap_and_free_tx_resource(tx_ring, buffer_info);
}
size = sizeof(struct igb_buffer) * tx_ring->count;
memset(tx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(tx_ring->desc, 0, tx_ring->size);
tx_ring->next_to_use = 0;
tx_ring->next_to_clean = 0;
}
/**
* igb_clean_all_tx_rings - Free Tx Buffers for all queues
* @adapter: board private structure
**/
static void igb_clean_all_tx_rings(struct igb_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_tx_queues; i++)
igb_clean_tx_ring(&adapter->tx_ring[i]);
}
/**
* igb_free_rx_resources - Free Rx Resources
* @rx_ring: ring to clean the resources from
*
* Free all receive software resources
**/
void igb_free_rx_resources(struct igb_ring *rx_ring)
{
igb_clean_rx_ring(rx_ring);
vfree(rx_ring->buffer_info);
rx_ring->buffer_info = NULL;
/* if not set, then don't free */
if (!rx_ring->desc)
return;
pci_free_consistent(rx_ring->pdev, rx_ring->size,
rx_ring->desc, rx_ring->dma);
rx_ring->desc = NULL;
}
/**
* igb_free_all_rx_resources - Free Rx Resources for All Queues
* @adapter: board private structure
*
* Free all receive software resources
**/
static void igb_free_all_rx_resources(struct igb_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
igb_free_rx_resources(&adapter->rx_ring[i]);
}
/**
* igb_clean_rx_ring - Free Rx Buffers per Queue
* @rx_ring: ring to free buffers from
**/
static void igb_clean_rx_ring(struct igb_ring *rx_ring)
{
struct igb_buffer *buffer_info;
unsigned long size;
unsigned int i;
if (!rx_ring->buffer_info)
return;
/* Free all the Rx ring sk_buffs */
for (i = 0; i < rx_ring->count; i++) {
buffer_info = &rx_ring->buffer_info[i];
if (buffer_info->dma) {
pci_unmap_single(rx_ring->pdev,
buffer_info->dma,
rx_ring->rx_buffer_len,
PCI_DMA_FROMDEVICE);
buffer_info->dma = 0;
}
if (buffer_info->skb) {
dev_kfree_skb(buffer_info->skb);
buffer_info->skb = NULL;
}
if (buffer_info->page_dma) {
pci_unmap_page(rx_ring->pdev,
buffer_info->page_dma,
PAGE_SIZE / 2,
PCI_DMA_FROMDEVICE);
buffer_info->page_dma = 0;
}
if (buffer_info->page) {
put_page(buffer_info->page);
buffer_info->page = NULL;
buffer_info->page_offset = 0;
}
}
size = sizeof(struct igb_buffer) * rx_ring->count;
memset(rx_ring->buffer_info, 0, size);
/* Zero out the descriptor ring */
memset(rx_ring->desc, 0, rx_ring->size);
rx_ring->next_to_clean = 0;
rx_ring->next_to_use = 0;
}
/**
* igb_clean_all_rx_rings - Free Rx Buffers for all queues
* @adapter: board private structure
**/
static void igb_clean_all_rx_rings(struct igb_adapter *adapter)
{
int i;
for (i = 0; i < adapter->num_rx_queues; i++)
igb_clean_rx_ring(&adapter->rx_ring[i]);
}
/**
* igb_set_mac - Change the Ethernet Address of the NIC
* @netdev: network interface device structure
* @p: pointer to an address structure
*
* Returns 0 on success, negative on failure
**/
static int igb_set_mac(struct net_device *netdev, void *p)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct sockaddr *addr = p;
if (!is_valid_ether_addr(addr->sa_data))
return -EADDRNOTAVAIL;
memcpy(netdev->dev_addr, addr->sa_data, netdev->addr_len);
memcpy(hw->mac.addr, addr->sa_data, netdev->addr_len);
/* set the correct pool for the new PF MAC address in entry 0 */
igb_rar_set_qsel(adapter, hw->mac.addr, 0,
adapter->vfs_allocated_count);
return 0;
}
/**
* igb_write_mc_addr_list - write multicast addresses to MTA
* @netdev: network interface device structure
*
* Writes multicast address list to the MTA hash table.
* Returns: -ENOMEM on failure
* 0 on no addresses written
* X on writing X addresses to MTA
**/
static int igb_write_mc_addr_list(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct dev_mc_list *mc_ptr = netdev->mc_list;
u8 *mta_list;
u32 vmolr = 0;
int i;
if (!netdev->mc_count) {
/* nothing to program, so clear mc list */
igb_update_mc_addr_list(hw, NULL, 0);
igb_restore_vf_multicasts(adapter);
return 0;
}
mta_list = kzalloc(netdev->mc_count * 6, GFP_ATOMIC);
if (!mta_list)
return -ENOMEM;
/* set vmolr receive overflow multicast bit */
vmolr |= E1000_VMOLR_ROMPE;
/* The shared function expects a packed array of only addresses. */
mc_ptr = netdev->mc_list;
for (i = 0; i < netdev->mc_count; i++) {
if (!mc_ptr)
break;
memcpy(mta_list + (i*ETH_ALEN), mc_ptr->dmi_addr, ETH_ALEN);
mc_ptr = mc_ptr->next;
}
igb_update_mc_addr_list(hw, mta_list, i);
kfree(mta_list);
return netdev->mc_count;
}
/**
* igb_write_uc_addr_list - write unicast addresses to RAR table
* @netdev: network interface device structure
*
* Writes unicast address list to the RAR table.
* Returns: -ENOMEM on failure/insufficient address space
* 0 on no addresses written
* X on writing X addresses to the RAR table
**/
static int igb_write_uc_addr_list(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
unsigned int vfn = adapter->vfs_allocated_count;
unsigned int rar_entries = hw->mac.rar_entry_count - (vfn + 1);
int count = 0;
/* return ENOMEM indicating insufficient memory for addresses */
if (netdev->uc.count > rar_entries)
return -ENOMEM;
if (netdev->uc.count && rar_entries) {
struct netdev_hw_addr *ha;
list_for_each_entry(ha, &netdev->uc.list, list) {
if (!rar_entries)
break;
igb_rar_set_qsel(adapter, ha->addr,
rar_entries--,
vfn);
count++;
}
}
/* write the addresses in reverse order to avoid write combining */
for (; rar_entries > 0 ; rar_entries--) {
wr32(E1000_RAH(rar_entries), 0);
wr32(E1000_RAL(rar_entries), 0);
}
wrfl();
return count;
}
/**
* igb_set_rx_mode - Secondary Unicast, Multicast and Promiscuous mode set
* @netdev: network interface device structure
*
* The set_rx_mode entry point is called whenever the unicast or multicast
* address lists or the network interface flags are updated. This routine is
* responsible for configuring the hardware for proper unicast, multicast,
* promiscuous mode, and all-multi behavior.
**/
static void igb_set_rx_mode(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
unsigned int vfn = adapter->vfs_allocated_count;
u32 rctl, vmolr = 0;
int count;
/* Check for Promiscuous and All Multicast modes */
rctl = rd32(E1000_RCTL);
/* clear the effected bits */
rctl &= ~(E1000_RCTL_UPE | E1000_RCTL_MPE | E1000_RCTL_VFE);
if (netdev->flags & IFF_PROMISC) {
rctl |= (E1000_RCTL_UPE | E1000_RCTL_MPE);
vmolr |= (E1000_VMOLR_ROPE | E1000_VMOLR_MPME);
} else {
if (netdev->flags & IFF_ALLMULTI) {
rctl |= E1000_RCTL_MPE;
vmolr |= E1000_VMOLR_MPME;
} else {
/*
* Write addresses to the MTA, if the attempt fails
* then we should just turn on promiscous mode so
* that we can at least receive multicast traffic
*/
count = igb_write_mc_addr_list(netdev);
if (count < 0) {
rctl |= E1000_RCTL_MPE;
vmolr |= E1000_VMOLR_MPME;
} else if (count) {
vmolr |= E1000_VMOLR_ROMPE;
}
}
/*
* Write addresses to available RAR registers, if there is not
* sufficient space to store all the addresses then enable
* unicast promiscous mode
*/
count = igb_write_uc_addr_list(netdev);
if (count < 0) {
rctl |= E1000_RCTL_UPE;
vmolr |= E1000_VMOLR_ROPE;
}
rctl |= E1000_RCTL_VFE;
}
wr32(E1000_RCTL, rctl);
/*
* In order to support SR-IOV and eventually VMDq it is necessary to set
* the VMOLR to enable the appropriate modes. Without this workaround
* we will have issues with VLAN tag stripping not being done for frames
* that are only arriving because we are the default pool
*/
if (hw->mac.type < e1000_82576)
return;
vmolr |= rd32(E1000_VMOLR(vfn)) &
~(E1000_VMOLR_ROPE | E1000_VMOLR_MPME | E1000_VMOLR_ROMPE);
wr32(E1000_VMOLR(vfn), vmolr);
igb_restore_vf_multicasts(adapter);
}
/* Need to wait a few seconds after link up to get diagnostic information from
* the phy */
static void igb_update_phy_info(unsigned long data)
{
struct igb_adapter *adapter = (struct igb_adapter *) data;
igb_get_phy_info(&adapter->hw);
}
/**
* igb_has_link - check shared code for link and determine up/down
* @adapter: pointer to driver private info
**/
static bool igb_has_link(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
bool link_active = false;
s32 ret_val = 0;
/* get_link_status is set on LSC (link status) interrupt or
* rx sequence error interrupt. get_link_status will stay
* false until the e1000_check_for_link establishes link
* for copper adapters ONLY
*/
switch (hw->phy.media_type) {
case e1000_media_type_copper:
if (hw->mac.get_link_status) {
ret_val = hw->mac.ops.check_for_link(hw);
link_active = !hw->mac.get_link_status;
} else {
link_active = true;
}
break;
case e1000_media_type_internal_serdes:
ret_val = hw->mac.ops.check_for_link(hw);
link_active = hw->mac.serdes_has_link;
break;
default:
case e1000_media_type_unknown:
break;
}
return link_active;
}
/**
* igb_watchdog - Timer Call-back
* @data: pointer to adapter cast into an unsigned long
**/
static void igb_watchdog(unsigned long data)
{
struct igb_adapter *adapter = (struct igb_adapter *)data;
/* Do the rest outside of interrupt context */
schedule_work(&adapter->watchdog_task);
}
static void igb_watchdog_task(struct work_struct *work)
{
struct igb_adapter *adapter = container_of(work,
struct igb_adapter,
watchdog_task);
struct e1000_hw *hw = &adapter->hw;
struct net_device *netdev = adapter->netdev;
u32 link;
int i;
link = igb_has_link(adapter);
if (link) {
if (!netif_carrier_ok(netdev)) {
u32 ctrl;
hw->mac.ops.get_speed_and_duplex(hw,
&adapter->link_speed,
&adapter->link_duplex);
ctrl = rd32(E1000_CTRL);
/* Links status message must follow this format */
printk(KERN_INFO "igb: %s NIC Link is Up %d Mbps %s, "
"Flow Control: %s\n",
netdev->name,
adapter->link_speed,
adapter->link_duplex == FULL_DUPLEX ?
"Full Duplex" : "Half Duplex",
((ctrl & E1000_CTRL_TFCE) &&
(ctrl & E1000_CTRL_RFCE)) ? "RX/TX" :
((ctrl & E1000_CTRL_RFCE) ? "RX" :
((ctrl & E1000_CTRL_TFCE) ? "TX" : "None")));
/* tweak tx_queue_len according to speed/duplex and
* adjust the timeout factor */
netdev->tx_queue_len = adapter->tx_queue_len;
adapter->tx_timeout_factor = 1;
switch (adapter->link_speed) {
case SPEED_10:
netdev->tx_queue_len = 10;
adapter->tx_timeout_factor = 14;
break;
case SPEED_100:
netdev->tx_queue_len = 100;
/* maybe add some timeout factor ? */
break;
}
netif_carrier_on(netdev);
igb_ping_all_vfs(adapter);
/* link state has changed, schedule phy info update */
if (!test_bit(__IGB_DOWN, &adapter->state))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
}
} else {
if (netif_carrier_ok(netdev)) {
adapter->link_speed = 0;
adapter->link_duplex = 0;
/* Links status message must follow this format */
printk(KERN_INFO "igb: %s NIC Link is Down\n",
netdev->name);
netif_carrier_off(netdev);
igb_ping_all_vfs(adapter);
/* link state has changed, schedule phy info update */
if (!test_bit(__IGB_DOWN, &adapter->state))
mod_timer(&adapter->phy_info_timer,
round_jiffies(jiffies + 2 * HZ));
}
}
igb_update_stats(adapter);
igb_update_adaptive(hw);
for (i = 0; i < adapter->num_tx_queues; i++) {
struct igb_ring *tx_ring = &adapter->tx_ring[i];
if (!netif_carrier_ok(netdev)) {
/* We've lost link, so the controller stops DMA,
* but we've got queued Tx work that's never going
* to get done, so reset controller to flush Tx.
* (Do the reset outside of interrupt context). */
if (igb_desc_unused(tx_ring) + 1 < tx_ring->count) {
adapter->tx_timeout_count++;
schedule_work(&adapter->reset_task);
/* return immediately since reset is imminent */
return;
}
}
/* Force detection of hung controller every watchdog period */
tx_ring->detect_tx_hung = true;
}
/* Cause software interrupt to ensure rx ring is cleaned */
if (adapter->msix_entries) {
u32 eics = 0;
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
eics |= q_vector->eims_value;
}
wr32(E1000_EICS, eics);
} else {
wr32(E1000_ICS, E1000_ICS_RXDMT0);
}
/* Reset the timer */
if (!test_bit(__IGB_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer,
round_jiffies(jiffies + 2 * HZ));
}
enum latency_range {
lowest_latency = 0,
low_latency = 1,
bulk_latency = 2,
latency_invalid = 255
};
/**
* igb_update_ring_itr - update the dynamic ITR value based on packet size
*
* Stores a new ITR value based on strictly on packet size. This
* algorithm is less sophisticated than that used in igb_update_itr,
* due to the difficulty of synchronizing statistics across multiple
* receive rings. The divisors and thresholds used by this fuction
* were determined based on theoretical maximum wire speed and testing
* data, in order to minimize response time while increasing bulk
* throughput.
* This functionality is controlled by the InterruptThrottleRate module
* parameter (see igb_param.c)
* NOTE: This function is called only when operating in a multiqueue
* receive environment.
* @q_vector: pointer to q_vector
**/
static void igb_update_ring_itr(struct igb_q_vector *q_vector)
{
int new_val = q_vector->itr_val;
int avg_wire_size = 0;
struct igb_adapter *adapter = q_vector->adapter;
/* For non-gigabit speeds, just fix the interrupt rate at 4000
* ints/sec - ITR timer value of 120 ticks.
*/
if (adapter->link_speed != SPEED_1000) {
new_val = 976;
goto set_itr_val;
}
if (q_vector->rx_ring && q_vector->rx_ring->total_packets) {
struct igb_ring *ring = q_vector->rx_ring;
avg_wire_size = ring->total_bytes / ring->total_packets;
}
if (q_vector->tx_ring && q_vector->tx_ring->total_packets) {
struct igb_ring *ring = q_vector->tx_ring;
avg_wire_size = max_t(u32, avg_wire_size,
(ring->total_bytes /
ring->total_packets));
}
/* if avg_wire_size isn't set no work was done */
if (!avg_wire_size)
goto clear_counts;
/* Add 24 bytes to size to account for CRC, preamble, and gap */
avg_wire_size += 24;
/* Don't starve jumbo frames */
avg_wire_size = min(avg_wire_size, 3000);
/* Give a little boost to mid-size frames */
if ((avg_wire_size > 300) && (avg_wire_size < 1200))
new_val = avg_wire_size / 3;
else
new_val = avg_wire_size / 2;
set_itr_val:
if (new_val != q_vector->itr_val) {
q_vector->itr_val = new_val;
q_vector->set_itr = 1;
}
clear_counts:
if (q_vector->rx_ring) {
q_vector->rx_ring->total_bytes = 0;
q_vector->rx_ring->total_packets = 0;
}
if (q_vector->tx_ring) {
q_vector->tx_ring->total_bytes = 0;
q_vector->tx_ring->total_packets = 0;
}
}
/**
* igb_update_itr - update the dynamic ITR value based on statistics
* Stores a new ITR value based on packets and byte
* counts during the last interrupt. The advantage of per interrupt
* computation is faster updates and more accurate ITR for the current
* traffic pattern. Constants in this function were computed
* based on theoretical maximum wire speed and thresholds were set based
* on testing data as well as attempting to minimize response time
* while increasing bulk throughput.
* this functionality is controlled by the InterruptThrottleRate module
* parameter (see igb_param.c)
* NOTE: These calculations are only valid when operating in a single-
* queue environment.
* @adapter: pointer to adapter
* @itr_setting: current q_vector->itr_val
* @packets: the number of packets during this measurement interval
* @bytes: the number of bytes during this measurement interval
**/
static unsigned int igb_update_itr(struct igb_adapter *adapter, u16 itr_setting,
int packets, int bytes)
{
unsigned int retval = itr_setting;
if (packets == 0)
goto update_itr_done;
switch (itr_setting) {
case lowest_latency:
/* handle TSO and jumbo frames */
if (bytes/packets > 8000)
retval = bulk_latency;
else if ((packets < 5) && (bytes > 512))
retval = low_latency;
break;
case low_latency: /* 50 usec aka 20000 ints/s */
if (bytes > 10000) {
/* this if handles the TSO accounting */
if (bytes/packets > 8000) {
retval = bulk_latency;
} else if ((packets < 10) || ((bytes/packets) > 1200)) {
retval = bulk_latency;
} else if ((packets > 35)) {
retval = lowest_latency;
}
} else if (bytes/packets > 2000) {
retval = bulk_latency;
} else if (packets <= 2 && bytes < 512) {
retval = lowest_latency;
}
break;
case bulk_latency: /* 250 usec aka 4000 ints/s */
if (bytes > 25000) {
if (packets > 35)
retval = low_latency;
} else if (bytes < 1500) {
retval = low_latency;
}
break;
}
update_itr_done:
return retval;
}
static void igb_set_itr(struct igb_adapter *adapter)
{
struct igb_q_vector *q_vector = adapter->q_vector[0];
u16 current_itr;
u32 new_itr = q_vector->itr_val;
/* for non-gigabit speeds, just fix the interrupt rate at 4000 */
if (adapter->link_speed != SPEED_1000) {
current_itr = 0;
new_itr = 4000;
goto set_itr_now;
}
adapter->rx_itr = igb_update_itr(adapter,
adapter->rx_itr,
adapter->rx_ring->total_packets,
adapter->rx_ring->total_bytes);
adapter->tx_itr = igb_update_itr(adapter,
adapter->tx_itr,
adapter->tx_ring->total_packets,
adapter->tx_ring->total_bytes);
current_itr = max(adapter->rx_itr, adapter->tx_itr);
/* conservative mode (itr 3) eliminates the lowest_latency setting */
if (adapter->rx_itr_setting == 3 && current_itr == lowest_latency)
current_itr = low_latency;
switch (current_itr) {
/* counts and packets in update_itr are dependent on these numbers */
case lowest_latency:
new_itr = 56; /* aka 70,000 ints/sec */
break;
case low_latency:
new_itr = 196; /* aka 20,000 ints/sec */
break;
case bulk_latency:
new_itr = 980; /* aka 4,000 ints/sec */
break;
default:
break;
}
set_itr_now:
adapter->rx_ring->total_bytes = 0;
adapter->rx_ring->total_packets = 0;
adapter->tx_ring->total_bytes = 0;
adapter->tx_ring->total_packets = 0;
if (new_itr != q_vector->itr_val) {
/* this attempts to bias the interrupt rate towards Bulk
* by adding intermediate steps when interrupt rate is
* increasing */
new_itr = new_itr > q_vector->itr_val ?
max((new_itr * q_vector->itr_val) /
(new_itr + (q_vector->itr_val >> 2)),
new_itr) :
new_itr;
/* Don't write the value here; it resets the adapter's
* internal timer, and causes us to delay far longer than
* we should between interrupts. Instead, we write the ITR
* value at the beginning of the next interrupt so the timing
* ends up being correct.
*/
q_vector->itr_val = new_itr;
q_vector->set_itr = 1;
}
return;
}
#define IGB_TX_FLAGS_CSUM 0x00000001
#define IGB_TX_FLAGS_VLAN 0x00000002
#define IGB_TX_FLAGS_TSO 0x00000004
#define IGB_TX_FLAGS_IPV4 0x00000008
#define IGB_TX_FLAGS_TSTAMP 0x00000010
#define IGB_TX_FLAGS_VLAN_MASK 0xffff0000
#define IGB_TX_FLAGS_VLAN_SHIFT 16
static inline int igb_tso_adv(struct igb_ring *tx_ring,
struct sk_buff *skb, u32 tx_flags, u8 *hdr_len)
{
struct e1000_adv_tx_context_desc *context_desc;
unsigned int i;
int err;
struct igb_buffer *buffer_info;
u32 info = 0, tu_cmd = 0;
u32 mss_l4len_idx, l4len;
*hdr_len = 0;
if (skb_header_cloned(skb)) {
err = pskb_expand_head(skb, 0, 0, GFP_ATOMIC);
if (err)
return err;
}
l4len = tcp_hdrlen(skb);
*hdr_len += l4len;
if (skb->protocol == htons(ETH_P_IP)) {
struct iphdr *iph = ip_hdr(skb);
iph->tot_len = 0;
iph->check = 0;
tcp_hdr(skb)->check = ~csum_tcpudp_magic(iph->saddr,
iph->daddr, 0,
IPPROTO_TCP,
0);
} else if (skb_is_gso_v6(skb)) {
ipv6_hdr(skb)->payload_len = 0;
tcp_hdr(skb)->check = ~csum_ipv6_magic(&ipv6_hdr(skb)->saddr,
&ipv6_hdr(skb)->daddr,
0, IPPROTO_TCP, 0);
}
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = E1000_TX_CTXTDESC_ADV(*tx_ring, i);
/* VLAN MACLEN IPLEN */
if (tx_flags & IGB_TX_FLAGS_VLAN)
info |= (tx_flags & IGB_TX_FLAGS_VLAN_MASK);
info |= (skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT);
*hdr_len += skb_network_offset(skb);
info |= skb_network_header_len(skb);
*hdr_len += skb_network_header_len(skb);
context_desc->vlan_macip_lens = cpu_to_le32(info);
/* ADV DTYP TUCMD MKRLOC/ISCSIHEDLEN */
tu_cmd |= (E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT);
if (skb->protocol == htons(ETH_P_IP))
tu_cmd |= E1000_ADVTXD_TUCMD_IPV4;
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
context_desc->type_tucmd_mlhl = cpu_to_le32(tu_cmd);
/* MSS L4LEN IDX */
mss_l4len_idx = (skb_shinfo(skb)->gso_size << E1000_ADVTXD_MSS_SHIFT);
mss_l4len_idx |= (l4len << E1000_ADVTXD_L4LEN_SHIFT);
/* For 82575, context index must be unique per ring. */
if (tx_ring->flags & IGB_RING_FLAG_TX_CTX_IDX)
mss_l4len_idx |= tx_ring->reg_idx << 4;
context_desc->mss_l4len_idx = cpu_to_le32(mss_l4len_idx);
context_desc->seqnum_seed = 0;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = 0;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return true;
}
static inline bool igb_tx_csum_adv(struct igb_ring *tx_ring,
struct sk_buff *skb, u32 tx_flags)
{
struct e1000_adv_tx_context_desc *context_desc;
struct pci_dev *pdev = tx_ring->pdev;
struct igb_buffer *buffer_info;
u32 info = 0, tu_cmd = 0;
unsigned int i;
if ((skb->ip_summed == CHECKSUM_PARTIAL) ||
(tx_flags & IGB_TX_FLAGS_VLAN)) {
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
context_desc = E1000_TX_CTXTDESC_ADV(*tx_ring, i);
if (tx_flags & IGB_TX_FLAGS_VLAN)
info |= (tx_flags & IGB_TX_FLAGS_VLAN_MASK);
info |= (skb_network_offset(skb) << E1000_ADVTXD_MACLEN_SHIFT);
if (skb->ip_summed == CHECKSUM_PARTIAL)
info |= skb_network_header_len(skb);
context_desc->vlan_macip_lens = cpu_to_le32(info);
tu_cmd |= (E1000_TXD_CMD_DEXT | E1000_ADVTXD_DTYP_CTXT);
if (skb->ip_summed == CHECKSUM_PARTIAL) {
__be16 protocol;
if (skb->protocol == cpu_to_be16(ETH_P_8021Q)) {
const struct vlan_ethhdr *vhdr =
(const struct vlan_ethhdr*)skb->data;
protocol = vhdr->h_vlan_encapsulated_proto;
} else {
protocol = skb->protocol;
}
switch (protocol) {
case cpu_to_be16(ETH_P_IP):
tu_cmd |= E1000_ADVTXD_TUCMD_IPV4;
if (ip_hdr(skb)->protocol == IPPROTO_TCP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
else if (ip_hdr(skb)->protocol == IPPROTO_SCTP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_SCTP;
break;
case cpu_to_be16(ETH_P_IPV6):
/* XXX what about other V6 headers?? */
if (ipv6_hdr(skb)->nexthdr == IPPROTO_TCP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_TCP;
else if (ipv6_hdr(skb)->nexthdr == IPPROTO_SCTP)
tu_cmd |= E1000_ADVTXD_TUCMD_L4T_SCTP;
break;
default:
if (unlikely(net_ratelimit()))
dev_warn(&pdev->dev,
"partial checksum but proto=%x!\n",
skb->protocol);
break;
}
}
context_desc->type_tucmd_mlhl = cpu_to_le32(tu_cmd);
context_desc->seqnum_seed = 0;
if (tx_ring->flags & IGB_RING_FLAG_TX_CTX_IDX)
context_desc->mss_l4len_idx =
cpu_to_le32(tx_ring->reg_idx << 4);
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = 0;
i++;
if (i == tx_ring->count)
i = 0;
tx_ring->next_to_use = i;
return true;
}
return false;
}
#define IGB_MAX_TXD_PWR 16
#define IGB_MAX_DATA_PER_TXD (1<<IGB_MAX_TXD_PWR)
static inline int igb_tx_map_adv(struct igb_ring *tx_ring, struct sk_buff *skb,
unsigned int first)
{
struct igb_buffer *buffer_info;
struct pci_dev *pdev = tx_ring->pdev;
unsigned int len = skb_headlen(skb);
unsigned int count = 0, i;
unsigned int f;
i = tx_ring->next_to_use;
buffer_info = &tx_ring->buffer_info[i];
BUG_ON(len >= IGB_MAX_DATA_PER_TXD);
buffer_info->length = len;
/* set time_stamp *before* dma to help avoid a possible race */
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->dma = pci_map_single(pdev, skb->data, len,
PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(pdev, buffer_info->dma))
goto dma_error;
for (f = 0; f < skb_shinfo(skb)->nr_frags; f++) {
struct skb_frag_struct *frag;
count++;
i++;
if (i == tx_ring->count)
i = 0;
frag = &skb_shinfo(skb)->frags[f];
len = frag->size;
buffer_info = &tx_ring->buffer_info[i];
BUG_ON(len >= IGB_MAX_DATA_PER_TXD);
buffer_info->length = len;
buffer_info->time_stamp = jiffies;
buffer_info->next_to_watch = i;
buffer_info->mapped_as_page = true;
buffer_info->dma = pci_map_page(pdev,
frag->page,
frag->page_offset,
len,
PCI_DMA_TODEVICE);
if (pci_dma_mapping_error(pdev, buffer_info->dma))
goto dma_error;
}
tx_ring->buffer_info[i].skb = skb;
tx_ring->buffer_info[first].next_to_watch = i;
return ++count;
dma_error:
dev_err(&pdev->dev, "TX DMA map failed\n");
/* clear timestamp and dma mappings for failed buffer_info mapping */
buffer_info->dma = 0;
buffer_info->time_stamp = 0;
buffer_info->length = 0;
buffer_info->next_to_watch = 0;
buffer_info->mapped_as_page = false;
count--;
/* clear timestamp and dma mappings for remaining portion of packet */
while (count >= 0) {
count--;
i--;
if (i < 0)
i += tx_ring->count;
buffer_info = &tx_ring->buffer_info[i];
igb_unmap_and_free_tx_resource(tx_ring, buffer_info);
}
return 0;
}
static inline void igb_tx_queue_adv(struct igb_ring *tx_ring,
int tx_flags, int count, u32 paylen,
u8 hdr_len)
{
union e1000_adv_tx_desc *tx_desc;
struct igb_buffer *buffer_info;
u32 olinfo_status = 0, cmd_type_len;
unsigned int i = tx_ring->next_to_use;
cmd_type_len = (E1000_ADVTXD_DTYP_DATA | E1000_ADVTXD_DCMD_IFCS |
E1000_ADVTXD_DCMD_DEXT);
if (tx_flags & IGB_TX_FLAGS_VLAN)
cmd_type_len |= E1000_ADVTXD_DCMD_VLE;
if (tx_flags & IGB_TX_FLAGS_TSTAMP)
cmd_type_len |= E1000_ADVTXD_MAC_TSTAMP;
if (tx_flags & IGB_TX_FLAGS_TSO) {
cmd_type_len |= E1000_ADVTXD_DCMD_TSE;
/* insert tcp checksum */
olinfo_status |= E1000_TXD_POPTS_TXSM << 8;
/* insert ip checksum */
if (tx_flags & IGB_TX_FLAGS_IPV4)
olinfo_status |= E1000_TXD_POPTS_IXSM << 8;
} else if (tx_flags & IGB_TX_FLAGS_CSUM) {
olinfo_status |= E1000_TXD_POPTS_TXSM << 8;
}
if ((tx_ring->flags & IGB_RING_FLAG_TX_CTX_IDX) &&
(tx_flags & (IGB_TX_FLAGS_CSUM |
IGB_TX_FLAGS_TSO |
IGB_TX_FLAGS_VLAN)))
olinfo_status |= tx_ring->reg_idx << 4;
olinfo_status |= ((paylen - hdr_len) << E1000_ADVTXD_PAYLEN_SHIFT);
do {
buffer_info = &tx_ring->buffer_info[i];
tx_desc = E1000_TX_DESC_ADV(*tx_ring, i);
tx_desc->read.buffer_addr = cpu_to_le64(buffer_info->dma);
tx_desc->read.cmd_type_len =
cpu_to_le32(cmd_type_len | buffer_info->length);
tx_desc->read.olinfo_status = cpu_to_le32(olinfo_status);
count--;
i++;
if (i == tx_ring->count)
i = 0;
} while (count > 0);
tx_desc->read.cmd_type_len |= cpu_to_le32(IGB_ADVTXD_DCMD);
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
tx_ring->next_to_use = i;
writel(i, tx_ring->tail);
/* we need this if more than one processor can write to our tail
* at a time, it syncronizes IO on IA64/Altix systems */
mmiowb();
}
static int __igb_maybe_stop_tx(struct igb_ring *tx_ring, int size)
{
struct net_device *netdev = tx_ring->netdev;
netif_stop_subqueue(netdev, tx_ring->queue_index);
/* Herbert's original patch had:
* smp_mb__after_netif_stop_queue();
* but since that doesn't exist yet, just open code it. */
smp_mb();
/* We need to check again in a case another CPU has just
* made room available. */
if (igb_desc_unused(tx_ring) < size)
return -EBUSY;
/* A reprieve! */
netif_wake_subqueue(netdev, tx_ring->queue_index);
tx_ring->tx_stats.restart_queue++;
return 0;
}
static int igb_maybe_stop_tx(struct igb_ring *tx_ring, int size)
{
if (igb_desc_unused(tx_ring) >= size)
return 0;
return __igb_maybe_stop_tx(tx_ring, size);
}
netdev_tx_t igb_xmit_frame_ring_adv(struct sk_buff *skb,
struct igb_ring *tx_ring)
{
struct igb_adapter *adapter = netdev_priv(tx_ring->netdev);
unsigned int first;
unsigned int tx_flags = 0;
u8 hdr_len = 0;
int tso = 0, count;
union skb_shared_tx *shtx = skb_tx(skb);
/* need: 1 descriptor per page,
* + 2 desc gap to keep tail from touching head,
* + 1 desc for skb->data,
* + 1 desc for context descriptor,
* otherwise try next time */
if (igb_maybe_stop_tx(tx_ring, skb_shinfo(skb)->nr_frags + 4)) {
/* this is a hard error */
return NETDEV_TX_BUSY;
}
if (unlikely(shtx->hardware)) {
shtx->in_progress = 1;
tx_flags |= IGB_TX_FLAGS_TSTAMP;
}
if (vlan_tx_tag_present(skb) && adapter->vlgrp) {
tx_flags |= IGB_TX_FLAGS_VLAN;
tx_flags |= (vlan_tx_tag_get(skb) << IGB_TX_FLAGS_VLAN_SHIFT);
}
if (skb->protocol == htons(ETH_P_IP))
tx_flags |= IGB_TX_FLAGS_IPV4;
first = tx_ring->next_to_use;
if (skb_is_gso(skb)) {
tso = igb_tso_adv(tx_ring, skb, tx_flags, &hdr_len);
if (tso < 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
}
if (tso)
tx_flags |= IGB_TX_FLAGS_TSO;
else if (igb_tx_csum_adv(tx_ring, skb, tx_flags) &&
(skb->ip_summed == CHECKSUM_PARTIAL))
tx_flags |= IGB_TX_FLAGS_CSUM;
/*
* count reflects descriptors mapped, if 0 or less then mapping error
* has occured and we need to rewind the descriptor queue
*/
count = igb_tx_map_adv(tx_ring, skb, first);
if (!count) {
dev_kfree_skb_any(skb);
tx_ring->buffer_info[first].time_stamp = 0;
tx_ring->next_to_use = first;
return NETDEV_TX_OK;
}
igb_tx_queue_adv(tx_ring, tx_flags, count, skb->len, hdr_len);
/* Make sure there is space in the ring for the next send. */
igb_maybe_stop_tx(tx_ring, MAX_SKB_FRAGS + 4);
return NETDEV_TX_OK;
}
static netdev_tx_t igb_xmit_frame_adv(struct sk_buff *skb,
struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct igb_ring *tx_ring;
int r_idx = 0;
if (test_bit(__IGB_DOWN, &adapter->state)) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
if (skb->len <= 0) {
dev_kfree_skb_any(skb);
return NETDEV_TX_OK;
}
r_idx = skb->queue_mapping & (IGB_ABS_MAX_TX_QUEUES - 1);
tx_ring = adapter->multi_tx_table[r_idx];
/* This goes back to the question of how to logically map a tx queue
* to a flow. Right now, performance is impacted slightly negatively
* if using multiple tx queues. If the stack breaks away from a
* single qdisc implementation, we can look at this again. */
return igb_xmit_frame_ring_adv(skb, tx_ring);
}
/**
* igb_tx_timeout - Respond to a Tx Hang
* @netdev: network interface device structure
**/
static void igb_tx_timeout(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
/* Do the reset outside of interrupt context */
adapter->tx_timeout_count++;
if (hw->mac.type == e1000_82580)
hw->dev_spec._82575.global_device_reset = true;
schedule_work(&adapter->reset_task);
wr32(E1000_EICS,
(adapter->eims_enable_mask & ~adapter->eims_other));
}
static void igb_reset_task(struct work_struct *work)
{
struct igb_adapter *adapter;
adapter = container_of(work, struct igb_adapter, reset_task);
igb_reinit_locked(adapter);
}
/**
* igb_get_stats - Get System Network Statistics
* @netdev: network interface device structure
*
* Returns the address of the device statistics structure.
* The statistics are actually updated from the timer callback.
**/
static struct net_device_stats *igb_get_stats(struct net_device *netdev)
{
/* only return the current stats */
return &netdev->stats;
}
/**
* igb_change_mtu - Change the Maximum Transfer Unit
* @netdev: network interface device structure
* @new_mtu: new value for maximum frame size
*
* Returns 0 on success, negative on failure
**/
static int igb_change_mtu(struct net_device *netdev, int new_mtu)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct pci_dev *pdev = adapter->pdev;
int max_frame = new_mtu + ETH_HLEN + ETH_FCS_LEN;
u32 rx_buffer_len, i;
if ((new_mtu < 68) || (max_frame > MAX_JUMBO_FRAME_SIZE)) {
dev_err(&pdev->dev, "Invalid MTU setting\n");
return -EINVAL;
}
if (max_frame > MAX_STD_JUMBO_FRAME_SIZE) {
dev_err(&pdev->dev, "MTU > 9216 not supported.\n");
return -EINVAL;
}
while (test_and_set_bit(__IGB_RESETTING, &adapter->state))
msleep(1);
/* igb_down has a dependency on max_frame_size */
adapter->max_frame_size = max_frame;
/* NOTE: netdev_alloc_skb reserves 16 bytes, and typically NET_IP_ALIGN
* means we reserve 2 more, this pushes us to allocate from the next
* larger slab size.
* i.e. RXBUFFER_2048 --> size-4096 slab
*/
if (max_frame <= IGB_RXBUFFER_1024)
rx_buffer_len = IGB_RXBUFFER_1024;
else if (max_frame <= MAXIMUM_ETHERNET_VLAN_SIZE)
rx_buffer_len = MAXIMUM_ETHERNET_VLAN_SIZE;
else
rx_buffer_len = IGB_RXBUFFER_128;
if (netif_running(netdev))
igb_down(adapter);
dev_info(&pdev->dev, "changing MTU from %d to %d\n",
netdev->mtu, new_mtu);
netdev->mtu = new_mtu;
for (i = 0; i < adapter->num_rx_queues; i++)
adapter->rx_ring[i].rx_buffer_len = rx_buffer_len;
if (netif_running(netdev))
igb_up(adapter);
else
igb_reset(adapter);
clear_bit(__IGB_RESETTING, &adapter->state);
return 0;
}
/**
* igb_update_stats - Update the board statistics counters
* @adapter: board private structure
**/
void igb_update_stats(struct igb_adapter *adapter)
{
struct net_device_stats *net_stats = igb_get_stats(adapter->netdev);
struct e1000_hw *hw = &adapter->hw;
struct pci_dev *pdev = adapter->pdev;
u32 rnbc;
u16 phy_tmp;
int i;
u64 bytes, packets;
#define PHY_IDLE_ERROR_COUNT_MASK 0x00FF
/*
* Prevent stats update while adapter is being reset, or if the pci
* connection is down.
*/
if (adapter->link_speed == 0)
return;
if (pci_channel_offline(pdev))
return;
bytes = 0;
packets = 0;
for (i = 0; i < adapter->num_rx_queues; i++) {
u32 rqdpc_tmp = rd32(E1000_RQDPC(i)) & 0x0FFF;
adapter->rx_ring[i].rx_stats.drops += rqdpc_tmp;
net_stats->rx_fifo_errors += rqdpc_tmp;
bytes += adapter->rx_ring[i].rx_stats.bytes;
packets += adapter->rx_ring[i].rx_stats.packets;
}
net_stats->rx_bytes = bytes;
net_stats->rx_packets = packets;
bytes = 0;
packets = 0;
for (i = 0; i < adapter->num_tx_queues; i++) {
bytes += adapter->tx_ring[i].tx_stats.bytes;
packets += adapter->tx_ring[i].tx_stats.packets;
}
net_stats->tx_bytes = bytes;
net_stats->tx_packets = packets;
/* read stats registers */
adapter->stats.crcerrs += rd32(E1000_CRCERRS);
adapter->stats.gprc += rd32(E1000_GPRC);
adapter->stats.gorc += rd32(E1000_GORCL);
rd32(E1000_GORCH); /* clear GORCL */
adapter->stats.bprc += rd32(E1000_BPRC);
adapter->stats.mprc += rd32(E1000_MPRC);
adapter->stats.roc += rd32(E1000_ROC);
adapter->stats.prc64 += rd32(E1000_PRC64);
adapter->stats.prc127 += rd32(E1000_PRC127);
adapter->stats.prc255 += rd32(E1000_PRC255);
adapter->stats.prc511 += rd32(E1000_PRC511);
adapter->stats.prc1023 += rd32(E1000_PRC1023);
adapter->stats.prc1522 += rd32(E1000_PRC1522);
adapter->stats.symerrs += rd32(E1000_SYMERRS);
adapter->stats.sec += rd32(E1000_SEC);
adapter->stats.mpc += rd32(E1000_MPC);
adapter->stats.scc += rd32(E1000_SCC);
adapter->stats.ecol += rd32(E1000_ECOL);
adapter->stats.mcc += rd32(E1000_MCC);
adapter->stats.latecol += rd32(E1000_LATECOL);
adapter->stats.dc += rd32(E1000_DC);
adapter->stats.rlec += rd32(E1000_RLEC);
adapter->stats.xonrxc += rd32(E1000_XONRXC);
adapter->stats.xontxc += rd32(E1000_XONTXC);
adapter->stats.xoffrxc += rd32(E1000_XOFFRXC);
adapter->stats.xofftxc += rd32(E1000_XOFFTXC);
adapter->stats.fcruc += rd32(E1000_FCRUC);
adapter->stats.gptc += rd32(E1000_GPTC);
adapter->stats.gotc += rd32(E1000_GOTCL);
rd32(E1000_GOTCH); /* clear GOTCL */
rnbc = rd32(E1000_RNBC);
adapter->stats.rnbc += rnbc;
net_stats->rx_fifo_errors += rnbc;
adapter->stats.ruc += rd32(E1000_RUC);
adapter->stats.rfc += rd32(E1000_RFC);
adapter->stats.rjc += rd32(E1000_RJC);
adapter->stats.tor += rd32(E1000_TORH);
adapter->stats.tot += rd32(E1000_TOTH);
adapter->stats.tpr += rd32(E1000_TPR);
adapter->stats.ptc64 += rd32(E1000_PTC64);
adapter->stats.ptc127 += rd32(E1000_PTC127);
adapter->stats.ptc255 += rd32(E1000_PTC255);
adapter->stats.ptc511 += rd32(E1000_PTC511);
adapter->stats.ptc1023 += rd32(E1000_PTC1023);
adapter->stats.ptc1522 += rd32(E1000_PTC1522);
adapter->stats.mptc += rd32(E1000_MPTC);
adapter->stats.bptc += rd32(E1000_BPTC);
/* used for adaptive IFS */
hw->mac.tx_packet_delta = rd32(E1000_TPT);
adapter->stats.tpt += hw->mac.tx_packet_delta;
hw->mac.collision_delta = rd32(E1000_COLC);
adapter->stats.colc += hw->mac.collision_delta;
adapter->stats.algnerrc += rd32(E1000_ALGNERRC);
adapter->stats.rxerrc += rd32(E1000_RXERRC);
adapter->stats.tncrs += rd32(E1000_TNCRS);
adapter->stats.tsctc += rd32(E1000_TSCTC);
adapter->stats.tsctfc += rd32(E1000_TSCTFC);
adapter->stats.iac += rd32(E1000_IAC);
adapter->stats.icrxoc += rd32(E1000_ICRXOC);
adapter->stats.icrxptc += rd32(E1000_ICRXPTC);
adapter->stats.icrxatc += rd32(E1000_ICRXATC);
adapter->stats.ictxptc += rd32(E1000_ICTXPTC);
adapter->stats.ictxatc += rd32(E1000_ICTXATC);
adapter->stats.ictxqec += rd32(E1000_ICTXQEC);
adapter->stats.ictxqmtc += rd32(E1000_ICTXQMTC);
adapter->stats.icrxdmtc += rd32(E1000_ICRXDMTC);
/* Fill out the OS statistics structure */
net_stats->multicast = adapter->stats.mprc;
net_stats->collisions = adapter->stats.colc;
/* Rx Errors */
/* RLEC on some newer hardware can be incorrect so build
* our own version based on RUC and ROC */
net_stats->rx_errors = adapter->stats.rxerrc +
adapter->stats.crcerrs + adapter->stats.algnerrc +
adapter->stats.ruc + adapter->stats.roc +
adapter->stats.cexterr;
net_stats->rx_length_errors = adapter->stats.ruc +
adapter->stats.roc;
net_stats->rx_crc_errors = adapter->stats.crcerrs;
net_stats->rx_frame_errors = adapter->stats.algnerrc;
net_stats->rx_missed_errors = adapter->stats.mpc;
/* Tx Errors */
net_stats->tx_errors = adapter->stats.ecol +
adapter->stats.latecol;
net_stats->tx_aborted_errors = adapter->stats.ecol;
net_stats->tx_window_errors = adapter->stats.latecol;
net_stats->tx_carrier_errors = adapter->stats.tncrs;
/* Tx Dropped needs to be maintained elsewhere */
/* Phy Stats */
if (hw->phy.media_type == e1000_media_type_copper) {
if ((adapter->link_speed == SPEED_1000) &&
(!igb_read_phy_reg(hw, PHY_1000T_STATUS, &phy_tmp))) {
phy_tmp &= PHY_IDLE_ERROR_COUNT_MASK;
adapter->phy_stats.idle_errors += phy_tmp;
}
}
/* Management Stats */
adapter->stats.mgptc += rd32(E1000_MGTPTC);
adapter->stats.mgprc += rd32(E1000_MGTPRC);
adapter->stats.mgpdc += rd32(E1000_MGTPDC);
}
static irqreturn_t igb_msix_other(int irq, void *data)
{
struct igb_adapter *adapter = data;
struct e1000_hw *hw = &adapter->hw;
u32 icr = rd32(E1000_ICR);
/* reading ICR causes bit 31 of EICR to be cleared */
if (icr & E1000_ICR_DOUTSYNC) {
/* HW is reporting DMA is out of sync */
adapter->stats.doosync++;
}
/* Check for a mailbox event */
if (icr & E1000_ICR_VMMB)
igb_msg_task(adapter);
if (icr & E1000_ICR_LSC) {
hw->mac.get_link_status = 1;
/* guard against interrupt when we're going down */
if (!test_bit(__IGB_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
if (adapter->vfs_allocated_count)
wr32(E1000_IMS, E1000_IMS_LSC |
E1000_IMS_VMMB |
E1000_IMS_DOUTSYNC);
else
wr32(E1000_IMS, E1000_IMS_LSC | E1000_IMS_DOUTSYNC);
wr32(E1000_EIMS, adapter->eims_other);
return IRQ_HANDLED;
}
static void igb_write_itr(struct igb_q_vector *q_vector)
{
u32 itr_val = q_vector->itr_val & 0x7FFC;
if (!q_vector->set_itr)
return;
if (!itr_val)
itr_val = 0x4;
if (q_vector->itr_shift)
itr_val |= itr_val << q_vector->itr_shift;
else
itr_val |= 0x8000000;
writel(itr_val, q_vector->itr_register);
q_vector->set_itr = 0;
}
static irqreturn_t igb_msix_ring(int irq, void *data)
{
struct igb_q_vector *q_vector = data;
/* Write the ITR value calculated from the previous interrupt. */
igb_write_itr(q_vector);
napi_schedule(&q_vector->napi);
return IRQ_HANDLED;
}
#ifdef CONFIG_IGB_DCA
static void igb_update_dca(struct igb_q_vector *q_vector)
{
struct igb_adapter *adapter = q_vector->adapter;
struct e1000_hw *hw = &adapter->hw;
int cpu = get_cpu();
if (q_vector->cpu == cpu)
goto out_no_update;
if (q_vector->tx_ring) {
int q = q_vector->tx_ring->reg_idx;
u32 dca_txctrl = rd32(E1000_DCA_TXCTRL(q));
if (hw->mac.type == e1000_82575) {
dca_txctrl &= ~E1000_DCA_TXCTRL_CPUID_MASK;
dca_txctrl |= dca3_get_tag(&adapter->pdev->dev, cpu);
} else {
dca_txctrl &= ~E1000_DCA_TXCTRL_CPUID_MASK_82576;
dca_txctrl |= dca3_get_tag(&adapter->pdev->dev, cpu) <<
E1000_DCA_TXCTRL_CPUID_SHIFT;
}
dca_txctrl |= E1000_DCA_TXCTRL_DESC_DCA_EN;
wr32(E1000_DCA_TXCTRL(q), dca_txctrl);
}
if (q_vector->rx_ring) {
int q = q_vector->rx_ring->reg_idx;
u32 dca_rxctrl = rd32(E1000_DCA_RXCTRL(q));
if (hw->mac.type == e1000_82575) {
dca_rxctrl &= ~E1000_DCA_RXCTRL_CPUID_MASK;
dca_rxctrl |= dca3_get_tag(&adapter->pdev->dev, cpu);
} else {
dca_rxctrl &= ~E1000_DCA_RXCTRL_CPUID_MASK_82576;
dca_rxctrl |= dca3_get_tag(&adapter->pdev->dev, cpu) <<
E1000_DCA_RXCTRL_CPUID_SHIFT;
}
dca_rxctrl |= E1000_DCA_RXCTRL_DESC_DCA_EN;
dca_rxctrl |= E1000_DCA_RXCTRL_HEAD_DCA_EN;
dca_rxctrl |= E1000_DCA_RXCTRL_DATA_DCA_EN;
wr32(E1000_DCA_RXCTRL(q), dca_rxctrl);
}
q_vector->cpu = cpu;
out_no_update:
put_cpu();
}
static void igb_setup_dca(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
int i;
if (!(adapter->flags & IGB_FLAG_DCA_ENABLED))
return;
/* Always use CB2 mode, difference is masked in the CB driver. */
wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_CB2);
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
q_vector->cpu = -1;
igb_update_dca(q_vector);
}
}
static int __igb_notify_dca(struct device *dev, void *data)
{
struct net_device *netdev = dev_get_drvdata(dev);
struct igb_adapter *adapter = netdev_priv(netdev);
struct pci_dev *pdev = adapter->pdev;
struct e1000_hw *hw = &adapter->hw;
unsigned long event = *(unsigned long *)data;
switch (event) {
case DCA_PROVIDER_ADD:
/* if already enabled, don't do it again */
if (adapter->flags & IGB_FLAG_DCA_ENABLED)
break;
if (dca_add_requester(dev) == 0) {
adapter->flags |= IGB_FLAG_DCA_ENABLED;
dev_info(&pdev->dev, "DCA enabled\n");
igb_setup_dca(adapter);
break;
}
/* Fall Through since DCA is disabled. */
case DCA_PROVIDER_REMOVE:
if (adapter->flags & IGB_FLAG_DCA_ENABLED) {
/* without this a class_device is left
* hanging around in the sysfs model */
dca_remove_requester(dev);
dev_info(&pdev->dev, "DCA disabled\n");
adapter->flags &= ~IGB_FLAG_DCA_ENABLED;
wr32(E1000_DCA_CTRL, E1000_DCA_CTRL_DCA_MODE_DISABLE);
}
break;
}
return 0;
}
static int igb_notify_dca(struct notifier_block *nb, unsigned long event,
void *p)
{
int ret_val;
ret_val = driver_for_each_device(&igb_driver.driver, NULL, &event,
__igb_notify_dca);
return ret_val ? NOTIFY_BAD : NOTIFY_DONE;
}
#endif /* CONFIG_IGB_DCA */
static void igb_ping_all_vfs(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 ping;
int i;
for (i = 0 ; i < adapter->vfs_allocated_count; i++) {
ping = E1000_PF_CONTROL_MSG;
if (adapter->vf_data[i].flags & IGB_VF_FLAG_CTS)
ping |= E1000_VT_MSGTYPE_CTS;
igb_write_mbx(hw, &ping, 1, i);
}
}
static int igb_set_vf_promisc(struct igb_adapter *adapter, u32 *msgbuf, u32 vf)
{
struct e1000_hw *hw = &adapter->hw;
u32 vmolr = rd32(E1000_VMOLR(vf));
struct vf_data_storage *vf_data = &adapter->vf_data[vf];
vf_data->flags |= ~(IGB_VF_FLAG_UNI_PROMISC |
IGB_VF_FLAG_MULTI_PROMISC);
vmolr &= ~(E1000_VMOLR_ROPE | E1000_VMOLR_ROMPE | E1000_VMOLR_MPME);
if (*msgbuf & E1000_VF_SET_PROMISC_MULTICAST) {
vmolr |= E1000_VMOLR_MPME;
*msgbuf &= ~E1000_VF_SET_PROMISC_MULTICAST;
} else {
/*
* if we have hashes and we are clearing a multicast promisc
* flag we need to write the hashes to the MTA as this step
* was previously skipped
*/
if (vf_data->num_vf_mc_hashes > 30) {
vmolr |= E1000_VMOLR_MPME;
} else if (vf_data->num_vf_mc_hashes) {
int j;
vmolr |= E1000_VMOLR_ROMPE;
for (j = 0; j < vf_data->num_vf_mc_hashes; j++)
igb_mta_set(hw, vf_data->vf_mc_hashes[j]);
}
}
wr32(E1000_VMOLR(vf), vmolr);
/* there are flags left unprocessed, likely not supported */
if (*msgbuf & E1000_VT_MSGINFO_MASK)
return -EINVAL;
return 0;
}
static int igb_set_vf_multicasts(struct igb_adapter *adapter,
u32 *msgbuf, u32 vf)
{
int n = (msgbuf[0] & E1000_VT_MSGINFO_MASK) >> E1000_VT_MSGINFO_SHIFT;
u16 *hash_list = (u16 *)&msgbuf[1];
struct vf_data_storage *vf_data = &adapter->vf_data[vf];
int i;
/* salt away the number of multicast addresses assigned
* to this VF for later use to restore when the PF multi cast
* list changes
*/
vf_data->num_vf_mc_hashes = n;
/* only up to 30 hash values supported */
if (n > 30)
n = 30;
/* store the hashes for later use */
for (i = 0; i < n; i++)
vf_data->vf_mc_hashes[i] = hash_list[i];
/* Flush and reset the mta with the new values */
igb_set_rx_mode(adapter->netdev);
return 0;
}
static void igb_restore_vf_multicasts(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
struct vf_data_storage *vf_data;
int i, j;
for (i = 0; i < adapter->vfs_allocated_count; i++) {
u32 vmolr = rd32(E1000_VMOLR(i));
vmolr &= ~(E1000_VMOLR_ROMPE | E1000_VMOLR_MPME);
vf_data = &adapter->vf_data[i];
if ((vf_data->num_vf_mc_hashes > 30) ||
(vf_data->flags & IGB_VF_FLAG_MULTI_PROMISC)) {
vmolr |= E1000_VMOLR_MPME;
} else if (vf_data->num_vf_mc_hashes) {
vmolr |= E1000_VMOLR_ROMPE;
for (j = 0; j < vf_data->num_vf_mc_hashes; j++)
igb_mta_set(hw, vf_data->vf_mc_hashes[j]);
}
wr32(E1000_VMOLR(i), vmolr);
}
}
static void igb_clear_vf_vfta(struct igb_adapter *adapter, u32 vf)
{
struct e1000_hw *hw = &adapter->hw;
u32 pool_mask, reg, vid;
int i;
pool_mask = 1 << (E1000_VLVF_POOLSEL_SHIFT + vf);
/* Find the vlan filter for this id */
for (i = 0; i < E1000_VLVF_ARRAY_SIZE; i++) {
reg = rd32(E1000_VLVF(i));
/* remove the vf from the pool */
reg &= ~pool_mask;
/* if pool is empty then remove entry from vfta */
if (!(reg & E1000_VLVF_POOLSEL_MASK) &&
(reg & E1000_VLVF_VLANID_ENABLE)) {
reg = 0;
vid = reg & E1000_VLVF_VLANID_MASK;
igb_vfta_set(hw, vid, false);
}
wr32(E1000_VLVF(i), reg);
}
adapter->vf_data[vf].vlans_enabled = 0;
}
static s32 igb_vlvf_set(struct igb_adapter *adapter, u32 vid, bool add, u32 vf)
{
struct e1000_hw *hw = &adapter->hw;
u32 reg, i;
/* The vlvf table only exists on 82576 hardware and newer */
if (hw->mac.type < e1000_82576)
return -1;
/* we only need to do this if VMDq is enabled */
if (!adapter->vfs_allocated_count)
return -1;
/* Find the vlan filter for this id */
for (i = 0; i < E1000_VLVF_ARRAY_SIZE; i++) {
reg = rd32(E1000_VLVF(i));
if ((reg & E1000_VLVF_VLANID_ENABLE) &&
vid == (reg & E1000_VLVF_VLANID_MASK))
break;
}
if (add) {
if (i == E1000_VLVF_ARRAY_SIZE) {
/* Did not find a matching VLAN ID entry that was
* enabled. Search for a free filter entry, i.e.
* one without the enable bit set
*/
for (i = 0; i < E1000_VLVF_ARRAY_SIZE; i++) {
reg = rd32(E1000_VLVF(i));
if (!(reg & E1000_VLVF_VLANID_ENABLE))
break;
}
}
if (i < E1000_VLVF_ARRAY_SIZE) {
/* Found an enabled/available entry */
reg |= 1 << (E1000_VLVF_POOLSEL_SHIFT + vf);
/* if !enabled we need to set this up in vfta */
if (!(reg & E1000_VLVF_VLANID_ENABLE)) {
/* add VID to filter table */
igb_vfta_set(hw, vid, true);
reg |= E1000_VLVF_VLANID_ENABLE;
}
reg &= ~E1000_VLVF_VLANID_MASK;
reg |= vid;
wr32(E1000_VLVF(i), reg);
/* do not modify RLPML for PF devices */
if (vf >= adapter->vfs_allocated_count)
return 0;
if (!adapter->vf_data[vf].vlans_enabled) {
u32 size;
reg = rd32(E1000_VMOLR(vf));
size = reg & E1000_VMOLR_RLPML_MASK;
size += 4;
reg &= ~E1000_VMOLR_RLPML_MASK;
reg |= size;
wr32(E1000_VMOLR(vf), reg);
}
adapter->vf_data[vf].vlans_enabled++;
return 0;
}
} else {
if (i < E1000_VLVF_ARRAY_SIZE) {
/* remove vf from the pool */
reg &= ~(1 << (E1000_VLVF_POOLSEL_SHIFT + vf));
/* if pool is empty then remove entry from vfta */
if (!(reg & E1000_VLVF_POOLSEL_MASK)) {
reg = 0;
igb_vfta_set(hw, vid, false);
}
wr32(E1000_VLVF(i), reg);
/* do not modify RLPML for PF devices */
if (vf >= adapter->vfs_allocated_count)
return 0;
adapter->vf_data[vf].vlans_enabled--;
if (!adapter->vf_data[vf].vlans_enabled) {
u32 size;
reg = rd32(E1000_VMOLR(vf));
size = reg & E1000_VMOLR_RLPML_MASK;
size -= 4;
reg &= ~E1000_VMOLR_RLPML_MASK;
reg |= size;
wr32(E1000_VMOLR(vf), reg);
}
return 0;
}
}
return -1;
}
static int igb_set_vf_vlan(struct igb_adapter *adapter, u32 *msgbuf, u32 vf)
{
int add = (msgbuf[0] & E1000_VT_MSGINFO_MASK) >> E1000_VT_MSGINFO_SHIFT;
int vid = (msgbuf[1] & E1000_VLVF_VLANID_MASK);
return igb_vlvf_set(adapter, vid, add, vf);
}
static inline void igb_vf_reset(struct igb_adapter *adapter, u32 vf)
{
/* clear all flags */
adapter->vf_data[vf].flags = 0;
adapter->vf_data[vf].last_nack = jiffies;
/* reset offloads to defaults */
igb_set_vmolr(adapter, vf);
/* reset vlans for device */
igb_clear_vf_vfta(adapter, vf);
/* reset multicast table array for vf */
adapter->vf_data[vf].num_vf_mc_hashes = 0;
/* Flush and reset the mta with the new values */
igb_set_rx_mode(adapter->netdev);
}
static void igb_vf_reset_event(struct igb_adapter *adapter, u32 vf)
{
unsigned char *vf_mac = adapter->vf_data[vf].vf_mac_addresses;
/* generate a new mac address as we were hotplug removed/added */
random_ether_addr(vf_mac);
/* process remaining reset events */
igb_vf_reset(adapter, vf);
}
static void igb_vf_reset_msg(struct igb_adapter *adapter, u32 vf)
{
struct e1000_hw *hw = &adapter->hw;
unsigned char *vf_mac = adapter->vf_data[vf].vf_mac_addresses;
int rar_entry = hw->mac.rar_entry_count - (vf + 1);
u32 reg, msgbuf[3];
u8 *addr = (u8 *)(&msgbuf[1]);
/* process all the same items cleared in a function level reset */
igb_vf_reset(adapter, vf);
/* set vf mac address */
igb_rar_set_qsel(adapter, vf_mac, rar_entry, vf);
/* enable transmit and receive for vf */
reg = rd32(E1000_VFTE);
wr32(E1000_VFTE, reg | (1 << vf));
reg = rd32(E1000_VFRE);
wr32(E1000_VFRE, reg | (1 << vf));
adapter->vf_data[vf].flags = IGB_VF_FLAG_CTS;
/* reply to reset with ack and vf mac address */
msgbuf[0] = E1000_VF_RESET | E1000_VT_MSGTYPE_ACK;
memcpy(addr, vf_mac, 6);
igb_write_mbx(hw, msgbuf, 3, vf);
}
static int igb_set_vf_mac_addr(struct igb_adapter *adapter, u32 *msg, int vf)
{
unsigned char *addr = (char *)&msg[1];
int err = -1;
if (is_valid_ether_addr(addr))
err = igb_set_vf_mac(adapter, vf, addr);
return err;
}
static void igb_rcv_ack_from_vf(struct igb_adapter *adapter, u32 vf)
{
struct e1000_hw *hw = &adapter->hw;
struct vf_data_storage *vf_data = &adapter->vf_data[vf];
u32 msg = E1000_VT_MSGTYPE_NACK;
/* if device isn't clear to send it shouldn't be reading either */
if (!(vf_data->flags & IGB_VF_FLAG_CTS) &&
time_after(jiffies, vf_data->last_nack + (2 * HZ))) {
igb_write_mbx(hw, &msg, 1, vf);
vf_data->last_nack = jiffies;
}
}
static void igb_rcv_msg_from_vf(struct igb_adapter *adapter, u32 vf)
{
struct pci_dev *pdev = adapter->pdev;
u32 msgbuf[E1000_VFMAILBOX_SIZE];
struct e1000_hw *hw = &adapter->hw;
struct vf_data_storage *vf_data = &adapter->vf_data[vf];
s32 retval;
retval = igb_read_mbx(hw, msgbuf, E1000_VFMAILBOX_SIZE, vf);
if (retval) {
/* if receive failed revoke VF CTS stats and restart init */
dev_err(&pdev->dev, "Error receiving message from VF\n");
vf_data->flags &= ~IGB_VF_FLAG_CTS;
if (!time_after(jiffies, vf_data->last_nack + (2 * HZ)))
return;
goto out;
}
/* this is a message we already processed, do nothing */
if (msgbuf[0] & (E1000_VT_MSGTYPE_ACK | E1000_VT_MSGTYPE_NACK))
return;
/*
* until the vf completes a reset it should not be
* allowed to start any configuration.
*/
if (msgbuf[0] == E1000_VF_RESET) {
igb_vf_reset_msg(adapter, vf);
return;
}
if (!(vf_data->flags & IGB_VF_FLAG_CTS)) {
if (!time_after(jiffies, vf_data->last_nack + (2 * HZ)))
return;
retval = -1;
goto out;
}
switch ((msgbuf[0] & 0xFFFF)) {
case E1000_VF_SET_MAC_ADDR:
retval = igb_set_vf_mac_addr(adapter, msgbuf, vf);
break;
case E1000_VF_SET_PROMISC:
retval = igb_set_vf_promisc(adapter, msgbuf, vf);
break;
case E1000_VF_SET_MULTICAST:
retval = igb_set_vf_multicasts(adapter, msgbuf, vf);
break;
case E1000_VF_SET_LPE:
retval = igb_set_vf_rlpml(adapter, msgbuf[1], vf);
break;
case E1000_VF_SET_VLAN:
retval = igb_set_vf_vlan(adapter, msgbuf, vf);
break;
default:
dev_err(&pdev->dev, "Unhandled Msg %08x\n", msgbuf[0]);
retval = -1;
break;
}
msgbuf[0] |= E1000_VT_MSGTYPE_CTS;
out:
/* notify the VF of the results of what it sent us */
if (retval)
msgbuf[0] |= E1000_VT_MSGTYPE_NACK;
else
msgbuf[0] |= E1000_VT_MSGTYPE_ACK;
igb_write_mbx(hw, msgbuf, 1, vf);
}
static void igb_msg_task(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 vf;
for (vf = 0; vf < adapter->vfs_allocated_count; vf++) {
/* process any reset requests */
if (!igb_check_for_rst(hw, vf))
igb_vf_reset_event(adapter, vf);
/* process any messages pending */
if (!igb_check_for_msg(hw, vf))
igb_rcv_msg_from_vf(adapter, vf);
/* process any acks */
if (!igb_check_for_ack(hw, vf))
igb_rcv_ack_from_vf(adapter, vf);
}
}
/**
* igb_set_uta - Set unicast filter table address
* @adapter: board private structure
*
* The unicast table address is a register array of 32-bit registers.
* The table is meant to be used in a way similar to how the MTA is used
* however due to certain limitations in the hardware it is necessary to
* set all the hash bits to 1 and use the VMOLR ROPE bit as a promiscous
* enable bit to allow vlan tag stripping when promiscous mode is enabled
**/
static void igb_set_uta(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
int i;
/* The UTA table only exists on 82576 hardware and newer */
if (hw->mac.type < e1000_82576)
return;
/* we only need to do this if VMDq is enabled */
if (!adapter->vfs_allocated_count)
return;
for (i = 0; i < hw->mac.uta_reg_count; i++)
array_wr32(E1000_UTA, i, ~0);
}
/**
* igb_intr_msi - Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t igb_intr_msi(int irq, void *data)
{
struct igb_adapter *adapter = data;
struct igb_q_vector *q_vector = adapter->q_vector[0];
struct e1000_hw *hw = &adapter->hw;
/* read ICR disables interrupts using IAM */
u32 icr = rd32(E1000_ICR);
igb_write_itr(q_vector);
if (icr & E1000_ICR_DOUTSYNC) {
/* HW is reporting DMA is out of sync */
adapter->stats.doosync++;
}
if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
hw->mac.get_link_status = 1;
if (!test_bit(__IGB_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
napi_schedule(&q_vector->napi);
return IRQ_HANDLED;
}
/**
* igb_intr - Legacy Interrupt Handler
* @irq: interrupt number
* @data: pointer to a network interface device structure
**/
static irqreturn_t igb_intr(int irq, void *data)
{
struct igb_adapter *adapter = data;
struct igb_q_vector *q_vector = adapter->q_vector[0];
struct e1000_hw *hw = &adapter->hw;
/* Interrupt Auto-Mask...upon reading ICR, interrupts are masked. No
* need for the IMC write */
u32 icr = rd32(E1000_ICR);
if (!icr)
return IRQ_NONE; /* Not our interrupt */
igb_write_itr(q_vector);
/* IMS will not auto-mask if INT_ASSERTED is not set, and if it is
* not set, then the adapter didn't send an interrupt */
if (!(icr & E1000_ICR_INT_ASSERTED))
return IRQ_NONE;
if (icr & E1000_ICR_DOUTSYNC) {
/* HW is reporting DMA is out of sync */
adapter->stats.doosync++;
}
if (icr & (E1000_ICR_RXSEQ | E1000_ICR_LSC)) {
hw->mac.get_link_status = 1;
/* guard against interrupt when we're going down */
if (!test_bit(__IGB_DOWN, &adapter->state))
mod_timer(&adapter->watchdog_timer, jiffies + 1);
}
napi_schedule(&q_vector->napi);
return IRQ_HANDLED;
}
static inline void igb_ring_irq_enable(struct igb_q_vector *q_vector)
{
struct igb_adapter *adapter = q_vector->adapter;
struct e1000_hw *hw = &adapter->hw;
if ((q_vector->rx_ring && (adapter->rx_itr_setting & 3)) ||
(!q_vector->rx_ring && (adapter->tx_itr_setting & 3))) {
if (!adapter->msix_entries)
igb_set_itr(adapter);
else
igb_update_ring_itr(q_vector);
}
if (!test_bit(__IGB_DOWN, &adapter->state)) {
if (adapter->msix_entries)
wr32(E1000_EIMS, q_vector->eims_value);
else
igb_irq_enable(adapter);
}
}
/**
* igb_poll - NAPI Rx polling callback
* @napi: napi polling structure
* @budget: count of how many packets we should handle
**/
static int igb_poll(struct napi_struct *napi, int budget)
{
struct igb_q_vector *q_vector = container_of(napi,
struct igb_q_vector,
napi);
int tx_clean_complete = 1, work_done = 0;
#ifdef CONFIG_IGB_DCA
if (q_vector->adapter->flags & IGB_FLAG_DCA_ENABLED)
igb_update_dca(q_vector);
#endif
if (q_vector->tx_ring)
tx_clean_complete = igb_clean_tx_irq(q_vector);
if (q_vector->rx_ring)
igb_clean_rx_irq_adv(q_vector, &work_done, budget);
if (!tx_clean_complete)
work_done = budget;
/* If not enough Rx work done, exit the polling mode */
if (work_done < budget) {
napi_complete(napi);
igb_ring_irq_enable(q_vector);
}
return work_done;
}
/**
* igb_systim_to_hwtstamp - convert system time value to hw timestamp
* @adapter: board private structure
* @shhwtstamps: timestamp structure to update
* @regval: unsigned 64bit system time value.
*
* We need to convert the system time value stored in the RX/TXSTMP registers
* into a hwtstamp which can be used by the upper level timestamping functions
*/
static void igb_systim_to_hwtstamp(struct igb_adapter *adapter,
struct skb_shared_hwtstamps *shhwtstamps,
u64 regval)
{
u64 ns;
/*
* The 82580 starts with 1ns at bit 0 in RX/TXSTMPL, shift this up to
* 24 to match clock shift we setup earlier.
*/
if (adapter->hw.mac.type == e1000_82580)
regval <<= IGB_82580_TSYNC_SHIFT;
ns = timecounter_cyc2time(&adapter->clock, regval);
timecompare_update(&adapter->compare, ns);
memset(shhwtstamps, 0, sizeof(struct skb_shared_hwtstamps));
shhwtstamps->hwtstamp = ns_to_ktime(ns);
shhwtstamps->syststamp = timecompare_transform(&adapter->compare, ns);
}
/**
* igb_tx_hwtstamp - utility function which checks for TX time stamp
* @q_vector: pointer to q_vector containing needed info
* @skb: packet that was just sent
*
* If we were asked to do hardware stamping and such a time stamp is
* available, then it must have been for this skb here because we only
* allow only one such packet into the queue.
*/
static void igb_tx_hwtstamp(struct igb_q_vector *q_vector, struct sk_buff *skb)
{
struct igb_adapter *adapter = q_vector->adapter;
union skb_shared_tx *shtx = skb_tx(skb);
struct e1000_hw *hw = &adapter->hw;
struct skb_shared_hwtstamps shhwtstamps;
u64 regval;
/* if skb does not support hw timestamp or TX stamp not valid exit */
if (likely(!shtx->hardware) ||
!(rd32(E1000_TSYNCTXCTL) & E1000_TSYNCTXCTL_VALID))
return;
regval = rd32(E1000_TXSTMPL);
regval |= (u64)rd32(E1000_TXSTMPH) << 32;
igb_systim_to_hwtstamp(adapter, &shhwtstamps, regval);
skb_tstamp_tx(skb, &shhwtstamps);
}
/**
* igb_clean_tx_irq - Reclaim resources after transmit completes
* @q_vector: pointer to q_vector containing needed info
* returns true if ring is completely cleaned
**/
static bool igb_clean_tx_irq(struct igb_q_vector *q_vector)
{
struct igb_adapter *adapter = q_vector->adapter;
struct igb_ring *tx_ring = q_vector->tx_ring;
struct net_device *netdev = tx_ring->netdev;
struct e1000_hw *hw = &adapter->hw;
struct igb_buffer *buffer_info;
struct sk_buff *skb;
union e1000_adv_tx_desc *tx_desc, *eop_desc;
unsigned int total_bytes = 0, total_packets = 0;
unsigned int i, eop, count = 0;
bool cleaned = false;
i = tx_ring->next_to_clean;
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC_ADV(*tx_ring, eop);
while ((eop_desc->wb.status & cpu_to_le32(E1000_TXD_STAT_DD)) &&
(count < tx_ring->count)) {
for (cleaned = false; !cleaned; count++) {
tx_desc = E1000_TX_DESC_ADV(*tx_ring, i);
buffer_info = &tx_ring->buffer_info[i];
cleaned = (i == eop);
skb = buffer_info->skb;
if (skb) {
unsigned int segs, bytecount;
/* gso_segs is currently only valid for tcp */
segs = skb_shinfo(skb)->gso_segs ?: 1;
/* multiply data chunks by size of headers */
bytecount = ((segs - 1) * skb_headlen(skb)) +
skb->len;
total_packets += segs;
total_bytes += bytecount;
igb_tx_hwtstamp(q_vector, skb);
}
igb_unmap_and_free_tx_resource(tx_ring, buffer_info);
tx_desc->wb.status = 0;
i++;
if (i == tx_ring->count)
i = 0;
}
eop = tx_ring->buffer_info[i].next_to_watch;
eop_desc = E1000_TX_DESC_ADV(*tx_ring, eop);
}
tx_ring->next_to_clean = i;
if (unlikely(count &&
netif_carrier_ok(netdev) &&
igb_desc_unused(tx_ring) >= IGB_TX_QUEUE_WAKE)) {
/* Make sure that anybody stopping the queue after this
* sees the new next_to_clean.
*/
smp_mb();
if (__netif_subqueue_stopped(netdev, tx_ring->queue_index) &&
!(test_bit(__IGB_DOWN, &adapter->state))) {
netif_wake_subqueue(netdev, tx_ring->queue_index);
tx_ring->tx_stats.restart_queue++;
}
}
if (tx_ring->detect_tx_hung) {
/* Detect a transmit hang in hardware, this serializes the
* check with the clearing of time_stamp and movement of i */
tx_ring->detect_tx_hung = false;
if (tx_ring->buffer_info[i].time_stamp &&
time_after(jiffies, tx_ring->buffer_info[i].time_stamp +
(adapter->tx_timeout_factor * HZ)) &&
!(rd32(E1000_STATUS) & E1000_STATUS_TXOFF)) {
/* detected Tx unit hang */
dev_err(&tx_ring->pdev->dev,
"Detected Tx Unit Hang\n"
" Tx Queue <%d>\n"
" TDH <%x>\n"
" TDT <%x>\n"
" next_to_use <%x>\n"
" next_to_clean <%x>\n"
"buffer_info[next_to_clean]\n"
" time_stamp <%lx>\n"
" next_to_watch <%x>\n"
" jiffies <%lx>\n"
" desc.status <%x>\n",
tx_ring->queue_index,
readl(tx_ring->head),
readl(tx_ring->tail),
tx_ring->next_to_use,
tx_ring->next_to_clean,
tx_ring->buffer_info[eop].time_stamp,
eop,
jiffies,
eop_desc->wb.status);
netif_stop_subqueue(netdev, tx_ring->queue_index);
}
}
tx_ring->total_bytes += total_bytes;
tx_ring->total_packets += total_packets;
tx_ring->tx_stats.bytes += total_bytes;
tx_ring->tx_stats.packets += total_packets;
return (count < tx_ring->count);
}
/**
* igb_receive_skb - helper function to handle rx indications
* @q_vector: structure containing interrupt and ring information
* @skb: packet to send up
* @vlan_tag: vlan tag for packet
**/
static void igb_receive_skb(struct igb_q_vector *q_vector,
struct sk_buff *skb,
u16 vlan_tag)
{
struct igb_adapter *adapter = q_vector->adapter;
if (vlan_tag)
vlan_gro_receive(&q_vector->napi, adapter->vlgrp,
vlan_tag, skb);
else
napi_gro_receive(&q_vector->napi, skb);
}
static inline void igb_rx_checksum_adv(struct igb_ring *ring,
u32 status_err, struct sk_buff *skb)
{
skb->ip_summed = CHECKSUM_NONE;
/* Ignore Checksum bit is set or checksum is disabled through ethtool */
if (!(ring->flags & IGB_RING_FLAG_RX_CSUM) ||
(status_err & E1000_RXD_STAT_IXSM))
return;
/* TCP/UDP checksum error bit is set */
if (status_err &
(E1000_RXDEXT_STATERR_TCPE | E1000_RXDEXT_STATERR_IPE)) {
/*
* work around errata with sctp packets where the TCPE aka
* L4E bit is set incorrectly on 64 byte (60 byte w/o crc)
* packets, (aka let the stack check the crc32c)
*/
if ((skb->len == 60) &&
(ring->flags & IGB_RING_FLAG_RX_SCTP_CSUM))
ring->rx_stats.csum_err++;
/* let the stack verify checksum errors */
return;
}
/* It must be a TCP or UDP packet with a valid checksum */
if (status_err & (E1000_RXD_STAT_TCPCS | E1000_RXD_STAT_UDPCS))
skb->ip_summed = CHECKSUM_UNNECESSARY;
dev_dbg(&ring->pdev->dev, "cksum success: bits %08X\n", status_err);
}
static inline void igb_rx_hwtstamp(struct igb_q_vector *q_vector, u32 staterr,
struct sk_buff *skb)
{
struct igb_adapter *adapter = q_vector->adapter;
struct e1000_hw *hw = &adapter->hw;
u64 regval;
/*
* If this bit is set, then the RX registers contain the time stamp. No
* other packet will be time stamped until we read these registers, so
* read the registers to make them available again. Because only one
* packet can be time stamped at a time, we know that the register
* values must belong to this one here and therefore we don't need to
* compare any of the additional attributes stored for it.
*
* If nothing went wrong, then it should have a skb_shared_tx that we
* can turn into a skb_shared_hwtstamps.
*/
if (likely(!(staterr & E1000_RXDADV_STAT_TS)))
return;
if (!(rd32(E1000_TSYNCRXCTL) & E1000_TSYNCRXCTL_VALID))
return;
regval = rd32(E1000_RXSTMPL);
regval |= (u64)rd32(E1000_RXSTMPH) << 32;
igb_systim_to_hwtstamp(adapter, skb_hwtstamps(skb), regval);
}
static inline u16 igb_get_hlen(struct igb_ring *rx_ring,
union e1000_adv_rx_desc *rx_desc)
{
/* HW will not DMA in data larger than the given buffer, even if it
* parses the (NFS, of course) header to be larger. In that case, it
* fills the header buffer and spills the rest into the page.
*/
u16 hlen = (le16_to_cpu(rx_desc->wb.lower.lo_dword.hdr_info) &
E1000_RXDADV_HDRBUFLEN_MASK) >> E1000_RXDADV_HDRBUFLEN_SHIFT;
if (hlen > rx_ring->rx_buffer_len)
hlen = rx_ring->rx_buffer_len;
return hlen;
}
static bool igb_clean_rx_irq_adv(struct igb_q_vector *q_vector,
int *work_done, int budget)
{
struct igb_ring *rx_ring = q_vector->rx_ring;
struct net_device *netdev = rx_ring->netdev;
struct pci_dev *pdev = rx_ring->pdev;
union e1000_adv_rx_desc *rx_desc , *next_rxd;
struct igb_buffer *buffer_info , *next_buffer;
struct sk_buff *skb;
bool cleaned = false;
int cleaned_count = 0;
int current_node = numa_node_id();
unsigned int total_bytes = 0, total_packets = 0;
unsigned int i;
u32 staterr;
u16 length;
u16 vlan_tag;
i = rx_ring->next_to_clean;
buffer_info = &rx_ring->buffer_info[i];
rx_desc = E1000_RX_DESC_ADV(*rx_ring, i);
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
while (staterr & E1000_RXD_STAT_DD) {
if (*work_done >= budget)
break;
(*work_done)++;
skb = buffer_info->skb;
prefetch(skb->data - NET_IP_ALIGN);
buffer_info->skb = NULL;
i++;
if (i == rx_ring->count)
i = 0;
next_rxd = E1000_RX_DESC_ADV(*rx_ring, i);
prefetch(next_rxd);
next_buffer = &rx_ring->buffer_info[i];
length = le16_to_cpu(rx_desc->wb.upper.length);
cleaned = true;
cleaned_count++;
if (buffer_info->dma) {
pci_unmap_single(pdev, buffer_info->dma,
rx_ring->rx_buffer_len,
PCI_DMA_FROMDEVICE);
buffer_info->dma = 0;
if (rx_ring->rx_buffer_len >= IGB_RXBUFFER_1024) {
skb_put(skb, length);
goto send_up;
}
skb_put(skb, igb_get_hlen(rx_ring, rx_desc));
}
if (length) {
pci_unmap_page(pdev, buffer_info->page_dma,
PAGE_SIZE / 2, PCI_DMA_FROMDEVICE);
buffer_info->page_dma = 0;
skb_fill_page_desc(skb, skb_shinfo(skb)->nr_frags++,
buffer_info->page,
buffer_info->page_offset,
length);
if ((page_count(buffer_info->page) != 1) ||
(page_to_nid(buffer_info->page) != current_node))
buffer_info->page = NULL;
else
get_page(buffer_info->page);
skb->len += length;
skb->data_len += length;
skb->truesize += length;
}
if (!(staterr & E1000_RXD_STAT_EOP)) {
buffer_info->skb = next_buffer->skb;
buffer_info->dma = next_buffer->dma;
next_buffer->skb = skb;
next_buffer->dma = 0;
goto next_desc;
}
send_up:
if (staterr & E1000_RXDEXT_ERR_FRAME_ERR_MASK) {
dev_kfree_skb_irq(skb);
goto next_desc;
}
igb_rx_hwtstamp(q_vector, staterr, skb);
total_bytes += skb->len;
total_packets++;
igb_rx_checksum_adv(rx_ring, staterr, skb);
skb->protocol = eth_type_trans(skb, netdev);
skb_record_rx_queue(skb, rx_ring->queue_index);
vlan_tag = ((staterr & E1000_RXD_STAT_VP) ?
le16_to_cpu(rx_desc->wb.upper.vlan) : 0);
igb_receive_skb(q_vector, skb, vlan_tag);
next_desc:
rx_desc->wb.upper.status_error = 0;
/* return some buffers to hardware, one at a time is too slow */
if (cleaned_count >= IGB_RX_BUFFER_WRITE) {
igb_alloc_rx_buffers_adv(rx_ring, cleaned_count);
cleaned_count = 0;
}
/* use prefetched values */
rx_desc = next_rxd;
buffer_info = next_buffer;
staterr = le32_to_cpu(rx_desc->wb.upper.status_error);
}
rx_ring->next_to_clean = i;
cleaned_count = igb_desc_unused(rx_ring);
if (cleaned_count)
igb_alloc_rx_buffers_adv(rx_ring, cleaned_count);
rx_ring->total_packets += total_packets;
rx_ring->total_bytes += total_bytes;
rx_ring->rx_stats.packets += total_packets;
rx_ring->rx_stats.bytes += total_bytes;
return cleaned;
}
/**
* igb_alloc_rx_buffers_adv - Replace used receive buffers; packet split
* @adapter: address of board private structure
**/
void igb_alloc_rx_buffers_adv(struct igb_ring *rx_ring, int cleaned_count)
{
struct net_device *netdev = rx_ring->netdev;
union e1000_adv_rx_desc *rx_desc;
struct igb_buffer *buffer_info;
struct sk_buff *skb;
unsigned int i;
int bufsz;
i = rx_ring->next_to_use;
buffer_info = &rx_ring->buffer_info[i];
bufsz = rx_ring->rx_buffer_len;
while (cleaned_count--) {
rx_desc = E1000_RX_DESC_ADV(*rx_ring, i);
if ((bufsz < IGB_RXBUFFER_1024) && !buffer_info->page_dma) {
if (!buffer_info->page) {
buffer_info->page = netdev_alloc_page(netdev);
if (!buffer_info->page) {
rx_ring->rx_stats.alloc_failed++;
goto no_buffers;
}
buffer_info->page_offset = 0;
} else {
buffer_info->page_offset ^= PAGE_SIZE / 2;
}
buffer_info->page_dma =
pci_map_page(rx_ring->pdev, buffer_info->page,
buffer_info->page_offset,
PAGE_SIZE / 2,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(rx_ring->pdev,
buffer_info->page_dma)) {
buffer_info->page_dma = 0;
rx_ring->rx_stats.alloc_failed++;
goto no_buffers;
}
}
skb = buffer_info->skb;
if (!skb) {
skb = netdev_alloc_skb_ip_align(netdev, bufsz);
if (!skb) {
rx_ring->rx_stats.alloc_failed++;
goto no_buffers;
}
buffer_info->skb = skb;
}
if (!buffer_info->dma) {
buffer_info->dma = pci_map_single(rx_ring->pdev,
skb->data,
bufsz,
PCI_DMA_FROMDEVICE);
if (pci_dma_mapping_error(rx_ring->pdev,
buffer_info->dma)) {
buffer_info->dma = 0;
rx_ring->rx_stats.alloc_failed++;
goto no_buffers;
}
}
/* Refresh the desc even if buffer_addrs didn't change because
* each write-back erases this info. */
if (bufsz < IGB_RXBUFFER_1024) {
rx_desc->read.pkt_addr =
cpu_to_le64(buffer_info->page_dma);
rx_desc->read.hdr_addr = cpu_to_le64(buffer_info->dma);
} else {
rx_desc->read.pkt_addr = cpu_to_le64(buffer_info->dma);
rx_desc->read.hdr_addr = 0;
}
i++;
if (i == rx_ring->count)
i = 0;
buffer_info = &rx_ring->buffer_info[i];
}
no_buffers:
if (rx_ring->next_to_use != i) {
rx_ring->next_to_use = i;
if (i == 0)
i = (rx_ring->count - 1);
else
i--;
/* Force memory writes to complete before letting h/w
* know there are new descriptors to fetch. (Only
* applicable for weak-ordered memory model archs,
* such as IA-64). */
wmb();
writel(i, rx_ring->tail);
}
}
/**
* igb_mii_ioctl -
* @netdev:
* @ifreq:
* @cmd:
**/
static int igb_mii_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct mii_ioctl_data *data = if_mii(ifr);
if (adapter->hw.phy.media_type != e1000_media_type_copper)
return -EOPNOTSUPP;
switch (cmd) {
case SIOCGMIIPHY:
data->phy_id = adapter->hw.phy.addr;
break;
case SIOCGMIIREG:
if (igb_read_phy_reg(&adapter->hw, data->reg_num & 0x1F,
&data->val_out))
return -EIO;
break;
case SIOCSMIIREG:
default:
return -EOPNOTSUPP;
}
return 0;
}
/**
* igb_hwtstamp_ioctl - control hardware time stamping
* @netdev:
* @ifreq:
* @cmd:
*
* Outgoing time stamping can be enabled and disabled. Play nice and
* disable it when requested, although it shouldn't case any overhead
* when no packet needs it. At most one packet in the queue may be
* marked for time stamping, otherwise it would be impossible to tell
* for sure to which packet the hardware time stamp belongs.
*
* Incoming time stamping has to be configured via the hardware
* filters. Not all combinations are supported, in particular event
* type has to be specified. Matching the kind of event packet is
* not supported, with the exception of "all V2 events regardless of
* level 2 or 4".
*
**/
static int igb_hwtstamp_ioctl(struct net_device *netdev,
struct ifreq *ifr, int cmd)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
struct hwtstamp_config config;
u32 tsync_tx_ctl = E1000_TSYNCTXCTL_ENABLED;
u32 tsync_rx_ctl = E1000_TSYNCRXCTL_ENABLED;
u32 tsync_rx_cfg = 0;
bool is_l4 = false;
bool is_l2 = false;
u32 regval;
if (copy_from_user(&config, ifr->ifr_data, sizeof(config)))
return -EFAULT;
/* reserved for future extensions */
if (config.flags)
return -EINVAL;
switch (config.tx_type) {
case HWTSTAMP_TX_OFF:
tsync_tx_ctl = 0;
case HWTSTAMP_TX_ON:
break;
default:
return -ERANGE;
}
switch (config.rx_filter) {
case HWTSTAMP_FILTER_NONE:
tsync_rx_ctl = 0;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L4_EVENT:
case HWTSTAMP_FILTER_PTP_V2_L2_EVENT:
case HWTSTAMP_FILTER_ALL:
/*
* register TSYNCRXCFG must be set, therefore it is not
* possible to time stamp both Sync and Delay_Req messages
* => fall back to time stamping all packets
*/
tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_ALL;
config.rx_filter = HWTSTAMP_FILTER_ALL;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_SYNC:
tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_L4_V1;
tsync_rx_cfg = E1000_TSYNCRXCFG_PTP_V1_SYNC_MESSAGE;
is_l4 = true;
break;
case HWTSTAMP_FILTER_PTP_V1_L4_DELAY_REQ:
tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_L4_V1;
tsync_rx_cfg = E1000_TSYNCRXCFG_PTP_V1_DELAY_REQ_MESSAGE;
is_l4 = true;
break;
case HWTSTAMP_FILTER_PTP_V2_L2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_L4_SYNC:
tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_L2_L4_V2;
tsync_rx_cfg = E1000_TSYNCRXCFG_PTP_V2_SYNC_MESSAGE;
is_l2 = true;
is_l4 = true;
config.rx_filter = HWTSTAMP_FILTER_SOME;
break;
case HWTSTAMP_FILTER_PTP_V2_L2_DELAY_REQ:
case HWTSTAMP_FILTER_PTP_V2_L4_DELAY_REQ:
tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_L2_L4_V2;
tsync_rx_cfg = E1000_TSYNCRXCFG_PTP_V2_DELAY_REQ_MESSAGE;
is_l2 = true;
is_l4 = true;
config.rx_filter = HWTSTAMP_FILTER_SOME;
break;
case HWTSTAMP_FILTER_PTP_V2_EVENT:
case HWTSTAMP_FILTER_PTP_V2_SYNC:
case HWTSTAMP_FILTER_PTP_V2_DELAY_REQ:
tsync_rx_ctl |= E1000_TSYNCRXCTL_TYPE_EVENT_V2;
config.rx_filter = HWTSTAMP_FILTER_PTP_V2_EVENT;
is_l2 = true;
break;
default:
return -ERANGE;
}
if (hw->mac.type == e1000_82575) {
if (tsync_rx_ctl | tsync_tx_ctl)
return -EINVAL;
return 0;
}
/* enable/disable TX */
regval = rd32(E1000_TSYNCTXCTL);
regval &= ~E1000_TSYNCTXCTL_ENABLED;
regval |= tsync_tx_ctl;
wr32(E1000_TSYNCTXCTL, regval);
/* enable/disable RX */
regval = rd32(E1000_TSYNCRXCTL);
regval &= ~(E1000_TSYNCRXCTL_ENABLED | E1000_TSYNCRXCTL_TYPE_MASK);
regval |= tsync_rx_ctl;
wr32(E1000_TSYNCRXCTL, regval);
/* define which PTP packets are time stamped */
wr32(E1000_TSYNCRXCFG, tsync_rx_cfg);
/* define ethertype filter for timestamped packets */
if (is_l2)
wr32(E1000_ETQF(3),
(E1000_ETQF_FILTER_ENABLE | /* enable filter */
E1000_ETQF_1588 | /* enable timestamping */
ETH_P_1588)); /* 1588 eth protocol type */
else
wr32(E1000_ETQF(3), 0);
#define PTP_PORT 319
/* L4 Queue Filter[3]: filter by destination port and protocol */
if (is_l4) {
u32 ftqf = (IPPROTO_UDP /* UDP */
| E1000_FTQF_VF_BP /* VF not compared */
| E1000_FTQF_1588_TIME_STAMP /* Enable Timestamping */
| E1000_FTQF_MASK); /* mask all inputs */
ftqf &= ~E1000_FTQF_MASK_PROTO_BP; /* enable protocol check */
wr32(E1000_IMIR(3), htons(PTP_PORT));
wr32(E1000_IMIREXT(3),
(E1000_IMIREXT_SIZE_BP | E1000_IMIREXT_CTRL_BP));
if (hw->mac.type == e1000_82576) {
/* enable source port check */
wr32(E1000_SPQF(3), htons(PTP_PORT));
ftqf &= ~E1000_FTQF_MASK_SOURCE_PORT_BP;
}
wr32(E1000_FTQF(3), ftqf);
} else {
wr32(E1000_FTQF(3), E1000_FTQF_MASK);
}
wrfl();
adapter->hwtstamp_config = config;
/* clear TX/RX time stamp registers, just to be sure */
regval = rd32(E1000_TXSTMPH);
regval = rd32(E1000_RXSTMPH);
return copy_to_user(ifr->ifr_data, &config, sizeof(config)) ?
-EFAULT : 0;
}
/**
* igb_ioctl -
* @netdev:
* @ifreq:
* @cmd:
**/
static int igb_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
{
switch (cmd) {
case SIOCGMIIPHY:
case SIOCGMIIREG:
case SIOCSMIIREG:
return igb_mii_ioctl(netdev, ifr, cmd);
case SIOCSHWTSTAMP:
return igb_hwtstamp_ioctl(netdev, ifr, cmd);
default:
return -EOPNOTSUPP;
}
}
s32 igb_read_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value)
{
struct igb_adapter *adapter = hw->back;
u16 cap_offset;
cap_offset = pci_find_capability(adapter->pdev, PCI_CAP_ID_EXP);
if (!cap_offset)
return -E1000_ERR_CONFIG;
pci_read_config_word(adapter->pdev, cap_offset + reg, value);
return 0;
}
s32 igb_write_pcie_cap_reg(struct e1000_hw *hw, u32 reg, u16 *value)
{
struct igb_adapter *adapter = hw->back;
u16 cap_offset;
cap_offset = pci_find_capability(adapter->pdev, PCI_CAP_ID_EXP);
if (!cap_offset)
return -E1000_ERR_CONFIG;
pci_write_config_word(adapter->pdev, cap_offset + reg, *value);
return 0;
}
static void igb_vlan_rx_register(struct net_device *netdev,
struct vlan_group *grp)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 ctrl, rctl;
igb_irq_disable(adapter);
adapter->vlgrp = grp;
if (grp) {
/* enable VLAN tag insert/strip */
ctrl = rd32(E1000_CTRL);
ctrl |= E1000_CTRL_VME;
wr32(E1000_CTRL, ctrl);
/* Disable CFI check */
rctl = rd32(E1000_RCTL);
rctl &= ~E1000_RCTL_CFIEN;
wr32(E1000_RCTL, rctl);
} else {
/* disable VLAN tag insert/strip */
ctrl = rd32(E1000_CTRL);
ctrl &= ~E1000_CTRL_VME;
wr32(E1000_CTRL, ctrl);
}
igb_rlpml_set(adapter);
if (!test_bit(__IGB_DOWN, &adapter->state))
igb_irq_enable(adapter);
}
static void igb_vlan_rx_add_vid(struct net_device *netdev, u16 vid)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int pf_id = adapter->vfs_allocated_count;
/* attempt to add filter to vlvf array */
igb_vlvf_set(adapter, vid, true, pf_id);
/* add the filter since PF can receive vlans w/o entry in vlvf */
igb_vfta_set(hw, vid, true);
}
static void igb_vlan_rx_kill_vid(struct net_device *netdev, u16 vid)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int pf_id = adapter->vfs_allocated_count;
s32 err;
igb_irq_disable(adapter);
vlan_group_set_device(adapter->vlgrp, vid, NULL);
if (!test_bit(__IGB_DOWN, &adapter->state))
igb_irq_enable(adapter);
/* remove vlan from VLVF table array */
err = igb_vlvf_set(adapter, vid, false, pf_id);
/* if vid was not present in VLVF just remove it from table */
if (err)
igb_vfta_set(hw, vid, false);
}
static void igb_restore_vlan(struct igb_adapter *adapter)
{
igb_vlan_rx_register(adapter->netdev, adapter->vlgrp);
if (adapter->vlgrp) {
u16 vid;
for (vid = 0; vid < VLAN_GROUP_ARRAY_LEN; vid++) {
if (!vlan_group_get_device(adapter->vlgrp, vid))
continue;
igb_vlan_rx_add_vid(adapter->netdev, vid);
}
}
}
int igb_set_spd_dplx(struct igb_adapter *adapter, u16 spddplx)
{
struct pci_dev *pdev = adapter->pdev;
struct e1000_mac_info *mac = &adapter->hw.mac;
mac->autoneg = 0;
switch (spddplx) {
case SPEED_10 + DUPLEX_HALF:
mac->forced_speed_duplex = ADVERTISE_10_HALF;
break;
case SPEED_10 + DUPLEX_FULL:
mac->forced_speed_duplex = ADVERTISE_10_FULL;
break;
case SPEED_100 + DUPLEX_HALF:
mac->forced_speed_duplex = ADVERTISE_100_HALF;
break;
case SPEED_100 + DUPLEX_FULL:
mac->forced_speed_duplex = ADVERTISE_100_FULL;
break;
case SPEED_1000 + DUPLEX_FULL:
mac->autoneg = 1;
adapter->hw.phy.autoneg_advertised = ADVERTISE_1000_FULL;
break;
case SPEED_1000 + DUPLEX_HALF: /* not supported */
default:
dev_err(&pdev->dev, "Unsupported Speed/Duplex configuration\n");
return -EINVAL;
}
return 0;
}
static int __igb_shutdown(struct pci_dev *pdev, bool *enable_wake)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 ctrl, rctl, status;
u32 wufc = adapter->wol;
#ifdef CONFIG_PM
int retval = 0;
#endif
netif_device_detach(netdev);
if (netif_running(netdev))
igb_close(netdev);
igb_clear_interrupt_scheme(adapter);
#ifdef CONFIG_PM
retval = pci_save_state(pdev);
if (retval)
return retval;
#endif
status = rd32(E1000_STATUS);
if (status & E1000_STATUS_LU)
wufc &= ~E1000_WUFC_LNKC;
if (wufc) {
igb_setup_rctl(adapter);
igb_set_rx_mode(netdev);
/* turn on all-multi mode if wake on multicast is enabled */
if (wufc & E1000_WUFC_MC) {
rctl = rd32(E1000_RCTL);
rctl |= E1000_RCTL_MPE;
wr32(E1000_RCTL, rctl);
}
ctrl = rd32(E1000_CTRL);
/* advertise wake from D3Cold */
#define E1000_CTRL_ADVD3WUC 0x00100000
/* phy power management enable */
#define E1000_CTRL_EN_PHY_PWR_MGMT 0x00200000
ctrl |= E1000_CTRL_ADVD3WUC;
wr32(E1000_CTRL, ctrl);
/* Allow time for pending master requests to run */
igb_disable_pcie_master(hw);
wr32(E1000_WUC, E1000_WUC_PME_EN);
wr32(E1000_WUFC, wufc);
} else {
wr32(E1000_WUC, 0);
wr32(E1000_WUFC, 0);
}
*enable_wake = wufc || adapter->en_mng_pt;
if (!*enable_wake)
igb_shutdown_serdes_link_82575(hw);
/* Release control of h/w to f/w. If f/w is AMT enabled, this
* would have already happened in close and is redundant. */
igb_release_hw_control(adapter);
pci_disable_device(pdev);
return 0;
}
#ifdef CONFIG_PM
static int igb_suspend(struct pci_dev *pdev, pm_message_t state)
{
int retval;
bool wake;
retval = __igb_shutdown(pdev, &wake);
if (retval)
return retval;
if (wake) {
pci_prepare_to_sleep(pdev);
} else {
pci_wake_from_d3(pdev, false);
pci_set_power_state(pdev, PCI_D3hot);
}
return 0;
}
static int igb_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
u32 err;
pci_set_power_state(pdev, PCI_D0);
pci_restore_state(pdev);
err = pci_enable_device_mem(pdev);
if (err) {
dev_err(&pdev->dev,
"igb: Cannot enable PCI device from suspend\n");
return err;
}
pci_set_master(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
if (igb_init_interrupt_scheme(adapter)) {
dev_err(&pdev->dev, "Unable to allocate memory for queues\n");
return -ENOMEM;
}
/* e1000_power_up_phy(adapter); */
igb_reset(adapter);
/* let the f/w know that the h/w is now under the control of the
* driver. */
igb_get_hw_control(adapter);
wr32(E1000_WUS, ~0);
if (netif_running(netdev)) {
err = igb_open(netdev);
if (err)
return err;
}
netif_device_attach(netdev);
return 0;
}
#endif
static void igb_shutdown(struct pci_dev *pdev)
{
bool wake;
__igb_shutdown(pdev, &wake);
if (system_state == SYSTEM_POWER_OFF) {
pci_wake_from_d3(pdev, wake);
pci_set_power_state(pdev, PCI_D3hot);
}
}
#ifdef CONFIG_NET_POLL_CONTROLLER
/*
* Polling 'interrupt' - used by things like netconsole to send skbs
* without having to re-enable interrupts. It's not called while
* the interrupt routine is executing.
*/
static void igb_netpoll(struct net_device *netdev)
{
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
int i;
if (!adapter->msix_entries) {
struct igb_q_vector *q_vector = adapter->q_vector[0];
igb_irq_disable(adapter);
napi_schedule(&q_vector->napi);
return;
}
for (i = 0; i < adapter->num_q_vectors; i++) {
struct igb_q_vector *q_vector = adapter->q_vector[i];
wr32(E1000_EIMC, q_vector->eims_value);
napi_schedule(&q_vector->napi);
}
}
#endif /* CONFIG_NET_POLL_CONTROLLER */
/**
* igb_io_error_detected - called when PCI error is detected
* @pdev: Pointer to PCI device
* @state: The current pci connection state
*
* This function is called after a PCI bus error affecting
* this device has been detected.
*/
static pci_ers_result_t igb_io_error_detected(struct pci_dev *pdev,
pci_channel_state_t state)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igb_adapter *adapter = netdev_priv(netdev);
netif_device_detach(netdev);
if (state == pci_channel_io_perm_failure)
return PCI_ERS_RESULT_DISCONNECT;
if (netif_running(netdev))
igb_down(adapter);
pci_disable_device(pdev);
/* Request a slot slot reset. */
return PCI_ERS_RESULT_NEED_RESET;
}
/**
* igb_io_slot_reset - called after the pci bus has been reset.
* @pdev: Pointer to PCI device
*
* Restart the card from scratch, as if from a cold-boot. Implementation
* resembles the first-half of the igb_resume routine.
*/
static pci_ers_result_t igb_io_slot_reset(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igb_adapter *adapter = netdev_priv(netdev);
struct e1000_hw *hw = &adapter->hw;
pci_ers_result_t result;
int err;
if (pci_enable_device_mem(pdev)) {
dev_err(&pdev->dev,
"Cannot re-enable PCI device after reset.\n");
result = PCI_ERS_RESULT_DISCONNECT;
} else {
pci_set_master(pdev);
pci_restore_state(pdev);
pci_enable_wake(pdev, PCI_D3hot, 0);
pci_enable_wake(pdev, PCI_D3cold, 0);
igb_reset(adapter);
wr32(E1000_WUS, ~0);
result = PCI_ERS_RESULT_RECOVERED;
}
err = pci_cleanup_aer_uncorrect_error_status(pdev);
if (err) {
dev_err(&pdev->dev, "pci_cleanup_aer_uncorrect_error_status "
"failed 0x%0x\n", err);
/* non-fatal, continue */
}
return result;
}
/**
* igb_io_resume - called when traffic can start flowing again.
* @pdev: Pointer to PCI device
*
* This callback is called when the error recovery driver tells us that
* its OK to resume normal operation. Implementation resembles the
* second-half of the igb_resume routine.
*/
static void igb_io_resume(struct pci_dev *pdev)
{
struct net_device *netdev = pci_get_drvdata(pdev);
struct igb_adapter *adapter = netdev_priv(netdev);
if (netif_running(netdev)) {
if (igb_up(adapter)) {
dev_err(&pdev->dev, "igb_up failed after reset\n");
return;
}
}
netif_device_attach(netdev);
/* let the f/w know that the h/w is now under the control of the
* driver. */
igb_get_hw_control(adapter);
}
static void igb_rar_set_qsel(struct igb_adapter *adapter, u8 *addr, u32 index,
u8 qsel)
{
u32 rar_low, rar_high;
struct e1000_hw *hw = &adapter->hw;
/* HW expects these in little endian so we reverse the byte order
* from network order (big endian) to little endian
*/
rar_low = ((u32) addr[0] | ((u32) addr[1] << 8) |
((u32) addr[2] << 16) | ((u32) addr[3] << 24));
rar_high = ((u32) addr[4] | ((u32) addr[5] << 8));
/* Indicate to hardware the Address is Valid. */
rar_high |= E1000_RAH_AV;
if (hw->mac.type == e1000_82575)
rar_high |= E1000_RAH_POOL_1 * qsel;
else
rar_high |= E1000_RAH_POOL_1 << qsel;
wr32(E1000_RAL(index), rar_low);
wrfl();
wr32(E1000_RAH(index), rar_high);
wrfl();
}
static int igb_set_vf_mac(struct igb_adapter *adapter,
int vf, unsigned char *mac_addr)
{
struct e1000_hw *hw = &adapter->hw;
/* VF MAC addresses start at end of receive addresses and moves
* torwards the first, as a result a collision should not be possible */
int rar_entry = hw->mac.rar_entry_count - (vf + 1);
memcpy(adapter->vf_data[vf].vf_mac_addresses, mac_addr, ETH_ALEN);
igb_rar_set_qsel(adapter, mac_addr, rar_entry, vf);
return 0;
}
static void igb_vmm_control(struct igb_adapter *adapter)
{
struct e1000_hw *hw = &adapter->hw;
u32 reg;
/* replication is not supported for 82575 */
if (hw->mac.type == e1000_82575)
return;
/* enable replication vlan tag stripping */
reg = rd32(E1000_RPLOLR);
reg |= E1000_RPLOLR_STRVLAN;
wr32(E1000_RPLOLR, reg);
/* notify HW that the MAC is adding vlan tags */
reg = rd32(E1000_DTXCTL);
reg |= E1000_DTXCTL_VLAN_ADDED;
wr32(E1000_DTXCTL, reg);
if (adapter->vfs_allocated_count) {
igb_vmdq_set_loopback_pf(hw, true);
igb_vmdq_set_replication_pf(hw, true);
} else {
igb_vmdq_set_loopback_pf(hw, false);
igb_vmdq_set_replication_pf(hw, false);
}
}
/* igb_main.c */
|
atgreen/linux-2.6-moxie
|
drivers/net/igb/igb_main.c
|
C
|
gpl-2.0
| 169,058 |
/* smplayer, GUI front-end for mplayer.
Copyright (C) 2006-2015 Ricardo Villalba <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef VERSION_H
#define VERSION_H
#include <QString>
class Version {
public:
static QString printable();
static QString stable();
static QString revision();
static QString with_revision() { return stable() + "." + revision(); }
};
#endif
|
juancrobles/smplayer
|
src/version.h
|
C
|
gpl-2.0
| 1,087 |
#!/bin/sh
if [ -z "$top_srcdir" ]; then
top_srcdir="$(dirname "$0")/../../.."
. "${top_srcdir}/tests/testenv.sh"
fi
srcdir="${top_srcdir}/tests/glade/validity"
find "${top_srcdir}" -name '*.glade' -exec "${srcdir}/check_glade_validity.py" "$@" {} +
|
mairin/anaconda
|
tests/glade/validity/run_check_glade_validity.sh
|
Shell
|
gpl-2.0
| 260 |
# VDSM network functional tests
### Running the tests in a container
This section describes the steps needed to run the functional tests
locally in a container.
Multiple runs may be executed in parallel.
#### Note
All of those tests are running with nmstate backend.
#### Build the container image
To build the container, under the vdsm/docker/network folder, run:
```
sudo make functional
```
Note: Building the container image is needed only if the Dockerfile
changes.
#### Usage examples
- Run to get the help message:
`sudo ./tests/network/functional/run-tests.sh --help`
- Run tests based on nmstate backend:
`sudo ./tests/network/functional/run-tests.sh`
- Run tests based on nmstate backend with nmstate installed from source:
`sudo ./tests/network/functional/run-tests.sh --nmstate-pr=<PR_ID>`
- Run tests based on nmstate backend with local nmstate installed from source:
`sudo ./tests/network/functional/run-tests.sh --nmstate-source=<PATH_TO_NMSTATE_SRC>`
- Open the container shell without executing the test run:
`sudo ./tests/network/functional/run-tests.sh --shell`
- At the container shell, you can run the tests:
```
pytest \
-x \
-vv \
--target-lib \
-m "legacy_switch and nmstate" tests/network/functional
```
- Run tests based on ovs-switch:
`sudo ./tests/network/functional/run-tests.sh --switch-type=ovs`
|
oVirt/vdsm
|
tests/network/functional/README.md
|
Markdown
|
gpl-2.0
| 1,374 |
<?php
$MESS[1] = 'Января';
$MESS[2] = 'Февраля';
$MESS[3] = 'Марта';
$MESS[4] = 'Апреля';
$MESS[5] = 'Мая';
$MESS[6] = 'Июня';
$MESS[7] = 'Июля';
$MESS[8] = 'Августа';
$MESS[9] = 'Сентября';
$MESS[10] = 'Октября';
$MESS[11] = 'Ноября';
$MESS[12] = 'Декабря';
return $MESS;
?>
|
snipesn/UkrYama-2
|
protected/messages/ru/month.php
|
PHP
|
gpl-2.0
| 347 |
import { merge, values } from 'lodash'
import flattenObj from 'flat'
/**
* Converts base and otherClass to a simple key/value object.
*
* Example :
* base =
* base {
* ai: 'Ai(st)',
* d: 'D(f)',
* fld: 'Fld(c)',
* flxs: 'Flxs(0)'
* }
*
* otherClasses =
* base {
* flx: 'Flx(flx1)',
* flxs: '',
* ov: 'Ov(h)'
* }
*
* results: Ai(st) D(f) Fld(c) Flx(flx1) Ov(h)
*
*/
export const flattenThemeClasses = (base, ...otherClasses) => {
return values(
flattenObj(merge({}, base, ...otherClasses))
).join(' ').trim()
}
|
Halcom/zanata-server
|
frontend/src/main/web/src/utils/styleUtils.js
|
JavaScript
|
gpl-2.0
| 559 |
/*
* Copyright (C) 2010-2021 Hendrik Leppkes
* http://www.1f0.de
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "stdafx.h"
#include "CueSheet.h"
#include <algorithm>
#include <sstream>
#include <regex>
using namespace std;
enum class ParserState
{
GLOBAL,
FILE,
TRACK
};
typedef string::value_type char_t;
static char_t up_char(char_t ch)
{
return use_facet<ctype<char_t>>(locale()).toupper(ch);
}
static string toupper(const string &src)
{
string result;
transform(src.begin(), src.end(), back_inserter(result), up_char);
return result;
}
static void str_replace(string &s, const string &search, const string &replace)
{
for (string::size_type pos = 0;; pos += replace.length())
{
pos = s.find(search, pos);
if (pos == string::npos)
break;
s.erase(pos, search.length());
s.insert(pos, replace);
}
}
static string GetCueParam(string line, bool firstWord = false)
{
const string delims(" \t\n\r\"'");
string::size_type idx;
// Find beginning of the command word
idx = line.find_first_not_of(delims);
// Find end of the command word
idx = line.find_first_of(delims, idx);
// Find beginning of param
idx = line.find_first_not_of(delims, idx);
if (idx == string::npos)
return string();
string param = line.substr(idx);
// trim spaces off the end
param = param.substr(0, param.find_last_not_of(delims) + 1);
// replace escaped quotes
str_replace(param, "\\\"", "\"");
if (firstWord)
{
idx = param.find_first_of(delims);
if (idx != string::npos)
param = param.substr(0, idx);
}
return param;
}
static REFERENCE_TIME ParseCueIndex(string line)
{
int index, m, s, f, ret;
ret = sscanf_s(line.c_str(), " INDEX %d %d:%d:%d", &index, &m, &s, &f);
if (ret == 4)
return (m * 60i64 + s) * 10000000i64 + (f * 10000000i64 / 75);
else
return 0;
}
CCueSheet::CCueSheet()
{
}
CCueSheet::~CCueSheet()
{
}
HRESULT CCueSheet::Parse(string cueSheet)
{
DbgLog((LOG_TRACE, 10, L"CCueSheet::Parse(): Parsing Cue Sheet"));
int trackCount = 0;
ParserState state(ParserState::GLOBAL);
stringstream cueSheetStream(cueSheet);
string line;
while (getline(cueSheetStream, line))
{
string word;
(stringstream(line)) >> word;
word = toupper(word);
switch (state)
{
case ParserState::GLOBAL:
if (word == "PERFORMER")
{
m_Performer = GetCueParam(line);
}
else if (word == "TITLE")
{
m_Title = GetCueParam(line);
}
else if (word == "FILE")
{
state = ParserState::FILE;
}
break;
case ParserState::FILE:
case ParserState::TRACK:
if (word == "FILE")
{
DbgLog((LOG_TRACE, 10, L"CCueSheet::Parse(): Multiple FILE segments not supported."));
return E_FAIL;
}
if (word == "TRACK")
{
state = ParserState::TRACK;
trackCount++;
string id = GetCueParam(line, true);
Track track{trackCount - 1, id, "Title " + id, 0, ""};
m_Tracks.push_back(track);
}
else if (state == ParserState::TRACK)
{
if (word == "TITLE")
{
m_Tracks.back().Title = GetCueParam(line);
}
else if (word == "INDEX")
{
m_Tracks.back().Time = ParseCueIndex(line);
}
else if (word == "PERFORMER")
{
m_Tracks.back().Performer = GetCueParam(line);
}
}
break;
}
}
return S_OK;
}
std::string CCueSheet::FormatTrack(Track &track)
{
string trackFormat = track.Id + ". ";
if (!track.Performer.empty())
trackFormat += track.Performer + " - ";
trackFormat += track.Title;
return trackFormat;
}
|
Nevcairiel/LAVFilters
|
common/DSUtilLite/CueSheet.cpp
|
C++
|
gpl-2.0
| 4,888 |
<?php
//adding or removing tags for specified a locations
if ($_POST) {extract($_POST);}
//var_dump($sl_id); exit;
if (is_array($sl_id)==1) {
$id_string="";
foreach ($sl_id as $value) {
$id_string.="$value,";
}
$id_string=substr($id_string, 0, strlen($id_string)-1);
}
else {
$id_string=$sl_id;
}
if ($act=="add_tag") {
//adding tags
//print "UPDATE ".$wpdb->prefix."store_locator SET sl_tags=CONCAT(sl_tags, '".strtolower($sl_tags).", ') WHERE sl_id IN ($id_string)"; exit;
$wpdb->query("UPDATE ".$wpdb->prefix."store_locator SET sl_tags=CONCAT(sl_tags, '".strtolower($sl_tags).", ') WHERE sl_id IN ($id_string)");
}
elseif ($act=="remove_tag") {
//removing tags
if (empty($sl_tags)) {
//if no tag is specified, all tags will be removed from selected locations
$wpdb->query("UPDATE ".$wpdb->prefix."store_locator SET sl_tags='' WHERE sl_id IN ($id_string)");
}
else {
$wpdb->query("UPDATE ".$wpdb->prefix."store_locator SET sl_tags=REPLACE(sl_tags, '$sl_tags,', '') WHERE sl_id IN ($id_string)");
}
}
?>
|
robbiespire/paQui
|
wp-content/plugins/store-locator/tagLocations.php
|
PHP
|
gpl-2.0
| 1,056 |
#!/bin/sh
dirs="krusader krArc iso"
$EXTRACTRC `find . -name \*.rc -o -name \*.ui` >> rc.cpp || exit 11
$EXTRACTRC --tag-group=none --tag=title --tag=category --tag=tooltip --tag=description krusader/useraction_examples.xml >> rc.cpp
$XGETTEXT rc.cpp `find $dirs -name \*.cpp -o -name \*.cc -o -name \*.c -o -name \*.h` -o $podir/krusader.pot
rm -f rc.cpp
|
abika/krusader
|
Messages.sh
|
Shell
|
gpl-2.0
| 356 |
package org.adempiere.context;
/*
* #%L
* de.metas.adempiere.adempiere.base
* %%
* Copyright (C) 2015 metas GmbH
* %%
* 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, see
* <http://www.gnu.org/licenses/gpl-2.0.html>.
* #L%
*/
public interface JMXThreadLocalServerContextProviderMBean
{
String[] getActiveContextsInfo();
}
|
klst-com/metasfresh
|
de.metas.adempiere.adempiere/base/src/main/java/org/adempiere/context/JMXThreadLocalServerContextProviderMBean.java
|
Java
|
gpl-2.0
| 899 |
/*
* Copyright (c) 2010 Dmitry Kazakov <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "kis_update_scheduler.h"
#include "kis_image_config.h"
#include "kis_merge_walker.h"
#include "kis_full_refresh_walker.h"
#include "kis_updater_context.h"
#include "kis_simple_update_queue.h"
#include "kis_strokes_queue.h"
#include "kis_queues_progress_updater.h"
#include <QReadWriteLock>
#include "kis_lazy_wait_condition.h"
//#define DEBUG_BALANCING
#ifdef DEBUG_BALANCING
#define DEBUG_BALANCING_METRICS(decidedFirst, excl) \
qDebug() << "Balance decision:" << decidedFirst \
<< "(" << excl << ")" \
<< "updates:" << m_d->updatesQueue->sizeMetric() \
<< "strokes:" << m_d->strokesQueue->sizeMetric()
#else
#define DEBUG_BALANCING_METRICS(decidedFirst, excl)
#endif
struct KisUpdateScheduler::Private {
Private() : updatesQueue(0), strokesQueue(0),
updaterContext(0), processingBlocked(false),
balancingRatio(1.0),
projectionUpdateListener(0),
progressUpdater(0) {}
KisSimpleUpdateQueue *updatesQueue;
KisStrokesQueue *strokesQueue;
KisUpdaterContext *updaterContext;
bool processingBlocked;
qreal balancingRatio; // updates-queue-size/strokes-queue-size
KisProjectionUpdateListener *projectionUpdateListener;
KisQueuesProgressUpdater *progressUpdater;
QAtomicInt updatesLockCounter;
QReadWriteLock updatesStartLock;
KisLazyWaitCondition updatesFinishedCondition;
};
KisUpdateScheduler::KisUpdateScheduler(KisProjectionUpdateListener *projectionUpdateListener)
: m_d(new Private)
{
updateSettings();
m_d->projectionUpdateListener = projectionUpdateListener;
// The queue will update settings in a constructor itself
m_d->updatesQueue = new KisSimpleUpdateQueue();
m_d->strokesQueue = new KisStrokesQueue();
m_d->updaterContext = new KisUpdaterContext();
connectSignals();
}
KisUpdateScheduler::KisUpdateScheduler()
: m_d(new Private)
{
}
KisUpdateScheduler::~KisUpdateScheduler()
{
delete m_d->updaterContext;
delete m_d->updatesQueue;
delete m_d->strokesQueue;
delete m_d->progressUpdater;
}
void KisUpdateScheduler::connectSignals()
{
connect(m_d->updaterContext, SIGNAL(sigContinueUpdate(const QRect&)),
SLOT(continueUpdate(const QRect&)),
Qt::DirectConnection);
connect(m_d->updaterContext, SIGNAL(sigDoSomeUsefulWork()),
SLOT(doSomeUsefulWork()), Qt::DirectConnection);
connect(m_d->updaterContext, SIGNAL(sigSpareThreadAppeared()),
SLOT(spareThreadAppeared()), Qt::DirectConnection);
}
void KisUpdateScheduler::setProgressProxy(KoProgressProxy *progressProxy)
{
delete m_d->progressUpdater;
m_d->progressUpdater = new KisQueuesProgressUpdater(progressProxy);
}
void KisUpdateScheduler::progressUpdate()
{
if(m_d->progressUpdater) {
QString jobName = m_d->strokesQueue->currentStrokeName();
if(jobName.isEmpty()) {
jobName = "Update";
}
int sizeMetric = m_d->strokesQueue->sizeMetric() + m_d->updatesQueue->sizeMetric();
m_d->progressUpdater->updateProgress(sizeMetric, jobName);
}
}
void KisUpdateScheduler::progressNotifyJobDone()
{
if(m_d->progressUpdater) {
m_d->progressUpdater->notifyJobDone(1);
}
}
void KisUpdateScheduler::updateProjection(KisNodeSP node, const QRect& rc, const QRect &cropRect)
{
m_d->updatesQueue->addUpdateJob(node, rc, cropRect);
processQueues();
}
void KisUpdateScheduler::fullRefreshAsync(KisNodeSP root, const QRect& rc, const QRect &cropRect)
{
m_d->updatesQueue->addFullRefreshJob(root, rc, cropRect);
processQueues();
}
void KisUpdateScheduler::fullRefresh(KisNodeSP root, const QRect& rc, const QRect &cropRect)
{
KisBaseRectsWalkerSP walker = new KisFullRefreshWalker(cropRect);
walker->collectRects(root, rc);
bool needLock = true;
if(m_d->processingBlocked) {
warnImage << "WARNING: Calling synchronous fullRefresh under a scheduler lock held";
warnImage << "We will not assert for now, but please port caller's to strokes";
warnImage << "to avoid this warning";
needLock = false;
}
if(needLock) lock();
m_d->updaterContext->lock();
Q_ASSERT(m_d->updaterContext->isJobAllowed(walker));
m_d->updaterContext->addMergeJob(walker);
m_d->updaterContext->waitForDone();
m_d->updaterContext->unlock();
if(needLock) unlock();
}
KisStrokeId KisUpdateScheduler::startStroke(KisStrokeStrategy *strokeStrategy)
{
KisStrokeId id = m_d->strokesQueue->startStroke(strokeStrategy);
processQueues();
return id;
}
void KisUpdateScheduler::addJob(KisStrokeId id, KisStrokeJobData *data)
{
m_d->strokesQueue->addJob(id, data);
processQueues();
}
void KisUpdateScheduler::endStroke(KisStrokeId id)
{
m_d->strokesQueue->endStroke(id);
processQueues();
}
bool KisUpdateScheduler::cancelStroke(KisStrokeId id)
{
bool result = m_d->strokesQueue->cancelStroke(id);
processQueues();
return result;
}
void KisUpdateScheduler::updateSettings()
{
if(m_d->updatesQueue) {
m_d->updatesQueue->updateSettings();
}
KisImageConfig config;
m_d->balancingRatio = config.schedulerBalancingRatio();
}
void KisUpdateScheduler::lock()
{
m_d->processingBlocked = true;
m_d->updaterContext->waitForDone();
}
void KisUpdateScheduler::unlock()
{
m_d->processingBlocked = false;
processQueues();
}
void KisUpdateScheduler::waitForDone()
{
do {
processQueues();
m_d->updaterContext->waitForDone();
} while(!m_d->updatesQueue->isEmpty() || !m_d->strokesQueue->isEmpty());
}
bool KisUpdateScheduler::tryBarrierLock()
{
if(!m_d->updatesQueue->isEmpty() || !m_d->strokesQueue->isEmpty())
return false;
m_d->processingBlocked = true;
m_d->updaterContext->waitForDone();
if(!m_d->updatesQueue->isEmpty() || !m_d->strokesQueue->isEmpty()) {
m_d->processingBlocked = false;
return false;
}
return true;
}
void KisUpdateScheduler::barrierLock()
{
do {
m_d->processingBlocked = false;
processQueues();
m_d->processingBlocked = true;
m_d->updaterContext->waitForDone();
} while(!m_d->updatesQueue->isEmpty() || !m_d->strokesQueue->isEmpty());
}
void KisUpdateScheduler::processQueues()
{
wakeUpWaitingThreads();
if(m_d->processingBlocked) return;
if(m_d->strokesQueue->needsExclusiveAccess()) {
DEBUG_BALANCING_METRICS("STROKES", "X");
m_d->strokesQueue->processQueue(*m_d->updaterContext,
!m_d->updatesQueue->isEmpty());
if(!m_d->strokesQueue->needsExclusiveAccess()) {
tryProcessUpdatesQueue();
}
}
else if(m_d->balancingRatio * m_d->strokesQueue->sizeMetric() > m_d->updatesQueue->sizeMetric()) {
DEBUG_BALANCING_METRICS("STROKES", "N");
m_d->strokesQueue->processQueue(*m_d->updaterContext,
!m_d->updatesQueue->isEmpty());
tryProcessUpdatesQueue();
}
else {
DEBUG_BALANCING_METRICS("UPDATES", "N");
tryProcessUpdatesQueue();
m_d->strokesQueue->processQueue(*m_d->updaterContext,
!m_d->updatesQueue->isEmpty());
}
progressUpdate();
}
void KisUpdateScheduler::blockUpdates()
{
m_d->updatesFinishedCondition.initWaiting();
m_d->updatesLockCounter.ref();
while(haveUpdatesRunning()) {
m_d->updatesFinishedCondition.wait();
}
m_d->updatesFinishedCondition.endWaiting();
}
void KisUpdateScheduler::unblockUpdates()
{
m_d->updatesLockCounter.deref();
processQueues();
}
void KisUpdateScheduler::wakeUpWaitingThreads()
{
if(m_d->updatesLockCounter && !haveUpdatesRunning()) {
m_d->updatesFinishedCondition.wakeAll();
}
}
void KisUpdateScheduler::tryProcessUpdatesQueue()
{
QReadLocker locker(&m_d->updatesStartLock);
if(m_d->updatesLockCounter) return;
m_d->updatesQueue->processQueue(*m_d->updaterContext);
}
bool KisUpdateScheduler::haveUpdatesRunning()
{
QWriteLocker locker(&m_d->updatesStartLock);
qint32 numMergeJobs, numStrokeJobs;
m_d->updaterContext->getJobsSnapshot(numMergeJobs, numStrokeJobs);
return numMergeJobs;
}
void KisUpdateScheduler::continueUpdate(const QRect &rect)
{
Q_ASSERT(m_d->projectionUpdateListener);
m_d->projectionUpdateListener->notifyProjectionUpdated(rect);
}
void KisUpdateScheduler::doSomeUsefulWork()
{
m_d->updatesQueue->optimize();
}
void KisUpdateScheduler::spareThreadAppeared()
{
progressNotifyJobDone();
processQueues();
}
KisTestableUpdateScheduler::KisTestableUpdateScheduler(KisProjectionUpdateListener *projectionUpdateListener,
qint32 threadCount)
{
updateSettings();
m_d->projectionUpdateListener = projectionUpdateListener;
// The queue will update settings in a constructor itself
m_d->updatesQueue = new KisTestableSimpleUpdateQueue();
m_d->strokesQueue = new KisStrokesQueue();
m_d->updaterContext = new KisTestableUpdaterContext(threadCount);
connectSignals();
}
KisTestableUpdaterContext* KisTestableUpdateScheduler::updaterContext()
{
return dynamic_cast<KisTestableUpdaterContext*>(m_d->updaterContext);
}
KisTestableSimpleUpdateQueue* KisTestableUpdateScheduler::updateQueue()
{
return dynamic_cast<KisTestableSimpleUpdateQueue*>(m_d->updatesQueue);
}
|
wyuka/calligra
|
krita/image/kis_update_scheduler.cpp
|
C++
|
gpl-2.0
| 10,423 |
///
/// \file xmlmap.cc
/// Map an XML node tree according to an XML map file.
/// The map is not fully nested, and provides mostly a
/// flat view, based on the map.
///
/*
Copyright (C) 2010-2012, Chris Frey <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License in the COPYING file at the
root directory of this project for more details.
*/
#include "xmlmap.h"
#include <barry/tzwrapper.h>
#include <libxml++/libxml++.h>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <functional>
#include <stdexcept>
using namespace std;
//////////////////////////////////////////////////////////////////////////////
// XmlNodeSummary
XmlNodeSummary::XmlNodeSummary(xmlpp::Node *node, XmlNodeMapping *mapping)
: m_node(node)
, m_mapping(mapping)
, m_name(node->get_name())
{
CreateSummary();
}
void XmlNodeSummary::ProcessListKey(ostream &os, const Glib::ustring &name)
{
xmlpp::Node::NodeList list = m_node->get_children(name);
xmlpp::Node::NodeList::iterator i = list.begin();
for( int count = 0; i != list.end(); ++i ) {
Glib::ustring content = GetContent(*i);
if( !content.size() )
continue;
if( count )
os << ", ";
os << content;
count++;
}
}
void XmlNodeSummary::ProcessKey(ostream &os, const Glib::ustring &key)
{
if( key.size() == 0 )
return;
switch( key[0] )
{
case '(':
os << "(";
ProcessKey(os, key.substr(1));
os << ") ";
break;
case '$': {
bool comma = false;
Glib::ustring wkey = key;
if( key[key.size()-1] == ',' ) {
comma = true;
wkey = key.substr(0, key.size()-1);
}
Glib::ustring content = GetContent(wkey.substr(1));
os << content;
if( comma && content.size() )
os << ",";
os << " ";
}
break;
case '%':
ProcessListKey(os, key.substr(1));
break;
default:
os << key << " ";
break;
}
}
void XmlNodeSummary::CreateSummary()
{
ostringstream oss;
istringstream iss(m_mapping->Format());
Glib::ustring key;
while( iss >> key ) {
ProcessKey(oss, key);
}
m_summary = oss.str();
}
Glib::ustring XmlNodeSummary::GetContent(const Glib::ustring &child_name) const
{
xmlpp::Node::NodeList list = m_node->get_children(child_name);
if( list.size() ) {
return GetContent(*list.begin());
}
else {
return Glib::ustring();
}
}
Glib::ustring XmlNodeSummary::GetContent(xmlpp::Node *node) const
{
Glib::ustring content_value;
xmlpp::ContentNode *content = dynamic_cast<xmlpp::ContentNode*>(node);
while( !content ) {
xmlpp::Node::NodeList list = node->get_children();
if( !list.size() )
break;
node = *list.begin();
content = dynamic_cast<xmlpp::ContentNode*>(node);
}
if( content ) {
content_value = content->get_content();
}
return content_value;
}
bool XmlNodeSummary::SummaryCompare(const XmlNodeSummary &a,
const XmlNodeSummary &b)
{
return a.Summary() < b.Summary();
}
bool XmlNodeSummary::PathCompare(const XmlNodeSummary &a,
const XmlNodeSummary &b)
{
return a.Path() < b.Path();
}
//////////////////////////////////////////////////////////////////////////////
// XmlNodeMapping
XmlNodeMapping::XmlNodeMapping(const Glib::ustring &node_name,
int priority,
const Glib::ustring &format)
: m_node_key_name(node_name)
, m_priority(priority)
, m_format(format)
{
}
void XmlNodeMapping::AddCompareName(const Glib::ustring &node_name)
{
m_compare_node_names.push_back(node_name);
}
void XmlNodeMapping::AddNode(xmlpp::Node *node)
{
XmlNodeSummary summary(node, this);
m_summaries.push_back(summary);
}
void XmlNodeMapping::SortBySummary()
{
sort(m_summaries.begin(), m_summaries.end(),
&XmlNodeSummary::SummaryCompare);
}
void XmlNodeMapping::SortByPath()
{
sort(m_summaries.begin(), m_summaries.end(),
&XmlNodeSummary::PathCompare);
}
const XmlNodeSummary& XmlNodeMapping::operator[] (int index) const
{
return m_summaries[index];
}
// Parse a compare_name in the format of "name[type]" into
// its component parts, without the brackets.
void XmlNodeMapping::SplitCompareName(const Glib::ustring &compare_name,
Glib::ustring &name,
Glib::ustring &type)
{
size_t pos = compare_name.find('[');
if( pos == Glib::ustring::npos ) {
name = compare_name;
type.clear();
}
else {
name = compare_name.substr(0, pos);
pos++;
while( compare_name[pos] && compare_name[pos] != ']' ) {
type += compare_name[pos];
pos++;
}
}
}
bool Timestamp2Unix(const Glib::ustring &stamp, time_t &result)
{
struct tm split;
bool utc;
if( !Barry::Sync::iso_to_tm(stamp.c_str(), &split, utc) )
return false;
split.tm_isdst = -1;
if( utc )
result = Barry::Sync::utc_mktime(&split);
else
result = mktime(&split);
return result != (time_t)-1;
}
bool TimestampsEqual(const Glib::ustring &content1,
const Glib::ustring &content2)
{
time_t t1, t2;
if( !Timestamp2Unix(content1, t1) || !Timestamp2Unix(content2, t2) ) {
// could throw there, but this is just used to
// pretty up the display, so defaulting to false
// is fine
return false;
}
return t1 == t2;
}
bool XmlNodeMapping::operator== (const XmlNodeMapping &other) const
{
// make sure mapfile data are the same
if( KeyName() != other.KeyName() ||
Priority() != other.Priority() ||
Format() != other.Format() ||
m_compare_node_names != other.m_compare_node_names )
return false;
// if the node counts are different, not equal
if( m_summaries.size() != other.m_summaries.size() )
return false;
// cycle through all compare names, and compare the
// values for those names from each node summary
for( compare_list::const_iterator namei = m_compare_node_names.begin();
namei != m_compare_node_names.end();
++namei )
{
for( summary_list::const_iterator sumi = m_summaries.begin(),
other_sumi = other.m_summaries.begin();
sumi != m_summaries.end() &&
other_sumi != other.m_summaries.end();
++sumi, ++other_sumi )
{
Glib::ustring name, type;
SplitCompareName(*namei, name, type);
Glib::ustring
content1 = sumi->GetContent(name),
content2 = other_sumi->GetContent(name);
if( type == "timestamp" ) {
// compare content as timestamps
if( !TimestampsEqual(content1, content2) )
return false;
}
else {
// compare as raw strings
if( content1 != content2 )
return false;
}
}
}
// all good!
return true;
}
void XmlNodeMapping::Dump(std::ostream &os) const
{
os << m_node_key_name << ": Priority " << m_priority
<< ", Nodes: " << m_summaries.size() << "\n";
os << " Format: " << m_format << "\n";
os << " Compare Names (" << m_compare_node_names.size() << "):\n";
os << " ";
for( compare_list::const_iterator i = m_compare_node_names.begin();
i != m_compare_node_names.end();
++i )
{
if( i != m_compare_node_names.begin() )
os << ", ";
os << (*i);
}
os << "\n";
if( m_summaries.size() ) {
os << " Summaries (" << m_summaries.size() << " nodes):\n";
for( summary_list::const_iterator i = m_summaries.begin();
i != m_summaries.end();
++i )
{
os << " " << i->Name() << " > " << i->Summary() << "\n";
}
}
os << "\n";
}
void XmlNodeMapping::DumpSummaries(std::ostream &os) const
{
for( size_t n = 0; n < size(); n++ ) {
os << m_summaries[n].Summary() << endl;
}
}
//////////////////////////////////////////////////////////////////////////////
// XmlNodeMap
XmlNodeMap::XmlNodeMap(const std::string &type_name,
const std::string &map_filename)
{
LoadMap(type_name, map_filename);
}
XmlNodeMap::XmlNodeMap(const std::string &map_filename)
{
LoadMap(string(), map_filename);
}
// copy constructor - only copies the map data, not the node.
// you must Import as usual
XmlNodeMap::XmlNodeMap(const XmlNodeMap &other)
{
operator=(other);
}
void XmlNodeMap::LoadMap(const std::string &type_name,
const std::string &map_filename)
{
ifstream is(map_filename.c_str());
if( !is )
throw std::runtime_error("Unable to open: " + map_filename);
std::string line;
while( getline(is, line) ) {
if( line[0] == '#' || line[0] == '\t' )
continue;
if( line.size() == 0 )
continue;
string type, key, format;
int priority = -1;
istringstream iss(line);
iss >> type >> key >> priority >> std::ws;
getline(iss, format);
if( !iss ) {
// skip if error
continue;
}
if( type_name.size() && type != type_name ) {
// skip types not for us
continue;
}
ptr_type mapping( new XmlNodeMapping(key, priority, format) );
while( is.peek() == '\t' ) {
getline(is, line);
mapping->AddCompareName(line.substr(1));
}
push_back(mapping);
}
}
void XmlNodeMap::ImportNodes(xmlpp::Node *node, bool purge)
{
if( XmlNodeMapping *mapping = Find(node->get_path()) ) {
mapping->AddNode(node);
return;
}
xmlpp::Node::NodeList list = node->get_children();
xmlpp::Node::NodeList::iterator i = list.begin();
for( ; i != list.end(); ++i ) {
ImportNodes(*i, false);
}
if( purge ) {
PurgeEmpties();
}
}
/// Removes all XmlNodeMappings that contain no node summaries.
/// This lets the caller remove mappings that do not match the
/// XML data that was imported. For example, a map may contain
/// mappings for Contacts and Calendar items, but only one
/// is parsed and imported at once. This function will remove
/// the unused mappings.
void XmlNodeMap::PurgeEmpties()
{
// iterator new_end = remove_if(begin(), end(),
// mem_fun_ref(&XmlNodeMapping::IsEmpty));
// -------------------------------------------------------
// not all compilers compile remove_if() for us, so do it
// manually: find the first empty
iterator new_end = begin();
for( ; new_end != end(); ++new_end ) {
if( new_end->IsEmpty() )
break;
}
if( new_end == end() )
return; // nothing is empty, nothing to purge
// copy the remainder, skipping the empties
iterator good = new_end;
++good;
for( ; good != end(); ++good ) {
if( !good->IsEmpty() ) {
*new_end = *good;
++new_end;
}
}
// done re-implementation of remove_if()
// -------------------------------------------------------
// erase the junk at the end (need to call this whether
// you use remove_if() or not
erase(new_end, end());
}
XmlNodeMapping* XmlNodeMap::Find(const Glib::ustring &node_name)
{
iterator i = begin();
for( ; i != end(); ++i ) {
const Glib::ustring &xpath = node_name;
XmlNodeMapping *mapping = &(*i);
const Glib::ustring &key = mapping->KeyName();
if( xpath.size() == key.size() && xpath == key ) {
return mapping;
}
else if( xpath.size() > key.size() &&
xpath.substr(0, key.size()) == key &&
xpath[key.size()] == '[' )
{
return mapping;
}
}
return 0;
}
void XmlNodeMap::SortBySummary()
{
for_each(begin(), end(), mem_fun_ref(&XmlNodeMapping::SortBySummary));
}
void XmlNodeMap::SortByPath()
{
for_each(begin(), end(), mem_fun_ref(&XmlNodeMapping::SortByPath));
}
void XmlNodeMap::Dump(std::ostream &os, int stop_priority) const
{
const_iterator i = begin();
for( ; i != end(); ++i ) {
if( i->Priority() >= stop_priority )
return;
i->Dump(os);
}
}
XmlNodeMap::iterator XmlNodeMap::priority_end(int stop_priority)
{
iterator i = begin();
for( ; i != end(); ++i ) {
if( i->Priority() >= stop_priority )
return i;
}
return i;
}
void XmlNodeMap::clear()
{
for_each(begin(), end(), mem_fun_ref(&XmlNodeMapping::clear));
}
XmlNodeMap& XmlNodeMap::operator=(const XmlNodeMap &other)
{
const_iterator i = other.begin();
for( ; i != other.end(); ++i ) {
ptr_type p( new XmlNodeMapping(*i) );
p->clear();
push_back(p);
}
return *this;
}
#ifdef XMLMAP
#include <locale>
#include <glibmm.h>
#include <tr1/functional>
using namespace std::tr1;
using namespace std::tr1::placeholders;
int main(int argc, char *argv[])
{
try {
locale loc("");
cin.imbue( loc );
cout.imbue( loc );
xmlpp::DomParser parser;
parser.parse_stream(cin);
XmlNodeMap np("Contact", "0.22/xmlmap");
np.ImportNodes(parser.get_document()->get_root_node());
np.Dump(cout, 99);
np.SortBySummary();
cout << "\n\nCute summary:\n";
for_each(np.begin(), np.priority_end(),
bind( mem_fn(&XmlNodeMapping::DumpSummaries),
_1, ref(cout)));
np.SortByPath();
cout << "\n\nCute summary:\n";
for_each(np.begin(), np.priority_end(),
bind( mem_fn(&XmlNodeMapping::DumpSummaries),
_1, ref(cout)));
}
catch( Glib::ConvertError &e ) {
cerr << e.what() << endl;
return 1;
}
catch( std::exception &e ) {
cerr << e.what() << endl;
return 1;
}
}
#endif
|
tobygray/barry
|
desktop/src/xmlmap.cc
|
C++
|
gpl-2.0
| 12,865 |
/* ScummVM - Graphic Adventure Engine
*
* ScummVM is the legal property of its developers, whose names
* are too numerous to list here. Please refer to the COPYRIGHT
* file distributed with this source distribution.
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "common/debug.h"
#include "common/rational.h"
#include "common/util.h"
#include "common/algorithm.h"
namespace Common {
Rational::Rational() {
_num = 1;
_denom = 1;
}
Rational::Rational(int num) {
_num = num;
_denom = 1;
}
Rational::Rational(int num, int denom) {
assert(denom != 0);
if (denom > 0) {
_num = num;
_denom = denom;
} else {
_num = -num;
_denom = -denom;
}
cancel();
}
void Rational::cancel() {
// Cancel the fraction by dividing both the num and the denom
// by their greatest common divisor.
const int gcd = Common::gcd(_num, _denom);
_num /= gcd;
_denom /= gcd;
}
Rational &Rational::operator=(const Rational &right) {
_num = right._num;
_denom = right._denom;
return *this;
}
Rational &Rational::operator=(int right) {
_num = right;
_denom = 1;
return *this;
}
Rational &Rational::operator+=(const Rational &right) {
// Cancel common factors to avoid unnecessary overflow.
// Note that the result is *not* always normalized.
const int gcd = Common::gcd(_denom, right._denom);
_num = _num * (right._denom / gcd);
_denom = _denom / gcd;
_num += right._num * _denom;
_denom *= right._denom;
cancel();
return *this;
}
Rational &Rational::operator-=(const Rational &right) {
// Cancel common factors to avoid unnecessary overflow.
// Note that the result is *not* always normalized.
const int gcd = Common::gcd(_denom, right._denom);
_num = _num * (right._denom / gcd);
_denom = _denom / gcd;
_num -= right._num * _denom;
_denom *= right._denom;
cancel();
return *this;
}
Rational &Rational::operator*=(const Rational &right) {
// Cross-cancel to avoid unnecessary overflow;
// the result then is automatically normalized
const int gcd1 = Common::gcd(_num, right._denom);
const int gcd2 = Common::gcd(right._num, _denom);
_num = (_num / gcd1) * (right._num / gcd2);
_denom = (_denom / gcd2) * (right._denom / gcd1);
return *this;
}
Rational &Rational::operator/=(const Rational &right) {
return *this *= right.getInverse();
}
Rational &Rational::operator+=(int right) {
return *this += Rational(right);
}
Rational &Rational::operator-=(int right) {
return *this -= Rational(right);
}
Rational &Rational::operator*=(int right) {
return *this *= Rational(right);
}
Rational &Rational::operator/=(int right) {
return *this /= Rational(right);
}
const Rational Rational::operator-() const {
return Rational(-_num, _denom);
}
const Rational Rational::operator+(const Rational &right) const {
Rational tmp = *this;
tmp += right;
return tmp;
}
const Rational Rational::operator-(const Rational &right) const {
Rational tmp = *this;
tmp -= right;
return tmp;
}
const Rational Rational::operator*(const Rational &right) const {
Rational tmp = *this;
tmp *= right;
return tmp;
}
const Rational Rational::operator/(const Rational &right) const {
Rational tmp = *this;
tmp /= right;
return tmp;
}
const Rational Rational::operator+(int right) const {
Rational tmp = *this;
tmp += right;
return tmp;
}
const Rational Rational::operator-(int right) const {
Rational tmp = *this;
tmp -= right;
return tmp;
}
const Rational Rational::operator*(int right) const {
Rational tmp = *this;
tmp *= right;
return tmp;
}
const Rational Rational::operator/(int right) const {
Rational tmp = *this;
tmp /= right;
return tmp;
}
bool Rational::operator==(const Rational &right) const {
return (_num == right._num) && (_denom == right._denom);
}
bool Rational::operator!=(const Rational &right) const {
return (_num != right._num) || (_denom != right._denom);
}
bool Rational::operator>(const Rational &right) const {
return (_num * right._denom) > (right._num * _denom);
}
bool Rational::operator<(const Rational &right) const {
return (_num * right._denom) < (right._num * _denom);
}
bool Rational::operator>=(const Rational &right) const {
return (_num * right._denom) >= (right._num * _denom);
}
bool Rational::operator<=(const Rational &right) const {
return (_num * right._denom) <= (right._num * _denom);
}
bool Rational::operator==(int right) const {
return (_denom == 1) && (_num == right);
}
bool Rational::operator!=(int right) const {
return (_denom != 1) || (_num != right);
}
bool Rational::operator>(int right) const {
return *this > Rational(right, 1);
}
bool Rational::operator<(int right) const {
return *this < Rational(right, 1);
}
bool Rational::operator>=(int right) const {
return *this >= Rational(right, 1);
}
bool Rational::operator<=(int right) const {
return *this <= Rational(right, 1);
}
void Rational::invert() {
assert(_num != 0);
SWAP(_num, _denom);
if (_denom < 0) {
_denom = -_denom;
_num = -_num;
}
}
Rational Rational::getInverse() const {
Rational inverse = *this;
inverse.invert();
return inverse;
}
int Rational::toInt() const {
return _num / _denom;
}
double Rational::toDouble() const {
return ((double)_num) / ((double)_denom);
}
frac_t Rational::toFrac() const {
return (_num * FRAC_ONE) / _denom;
}
const Rational operator+(int left, const Rational &right) {
Rational tmp(left);
tmp += right;
return tmp;
}
const Rational operator-(int left, const Rational &right) {
Rational tmp(left);
tmp -= right;
return tmp;
}
const Rational operator*(int left, const Rational &right) {
Rational tmp(left);
tmp *= right;
return tmp;
}
const Rational operator/(int left, const Rational &right) {
Rational tmp(left);
tmp /= right;
return tmp;
}
void Rational::debugPrint(int debuglevel, const char *caption) const {
debug(debuglevel, "%s %d/%d", caption, _num, _denom);
}
bool operator==(int left, const Rational &right) {
return right == left;
}
bool operator!=(int left, const Rational &right) {
return right != left;
}
bool operator>(int left, const Rational &right) {
return right < left;
}
bool operator<(int left, const Rational &right) {
return right > left;
}
bool operator>=(int left, const Rational &right) {
return right <= left;
}
bool operator<=(int left, const Rational &right) {
return right >= left;
}
} // End of namespace Common
|
chrisws/scummvm
|
common/rational.cpp
|
C++
|
gpl-2.0
| 7,051 |
/*
* arch/arm/mach-tegra/board.h
*
* Copyright (C) 2010 Google, Inc.
* Copyright (C) 2011-2012 NVIDIA Corporation.
*
* Author:
* Colin Cross <[email protected]>
* Erik Gilling <[email protected]>
*
* This software is licensed under the terms of the GNU General Public
* License version 2, as published by the Free Software Foundation, and
* may be copied, distributed, and modified under those terms.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
*/
#ifndef __MACH_TEGRA_BOARD_H
#define __MACH_TEGRA_BOARD_H
#include <linux/types.h>
#include <linux/power_supply.h>
#include <linux/memory.h>
#define ADD_FIXED_VOLTAGE_REG(_name) (&_name##_fixed_voltage_device)
/* Macro for defining fixed voltage regulator */
#define FIXED_VOLTAGE_REG_INIT(_id, _name, _microvolts, _gpio, \
_startup_delay, _enable_high, _enabled_at_boot, \
_valid_ops_mask, _always_on) \
static struct regulator_init_data _name##_initdata = { \
.consumer_supplies = _name##_consumer_supply, \
.num_consumer_supplies = \
ARRAY_SIZE(_name##_consumer_supply), \
.constraints = { \
.valid_ops_mask = _valid_ops_mask , \
.always_on = _always_on, \
}, \
}; \
static struct fixed_voltage_config _name##_config = { \
.supply_name = #_name, \
.microvolts = _microvolts, \
.gpio = _gpio, \
.startup_delay = _startup_delay, \
.enable_high = _enable_high, \
.enabled_at_boot = _enabled_at_boot, \
.init_data = &_name##_initdata, \
}; \
static struct platform_device _name##_fixed_voltage_device = { \
.name = "reg-fixed-voltage", \
.id = _id, \
.dev = { \
.platform_data = &_name##_config, \
}, \
}
#if defined(CONFIG_TEGRA_NVMAP)
#define NVMAP_HEAP_CARVEOUT_IRAM_INIT \
{ .name = "iram", \
.usage_mask = NVMAP_HEAP_CARVEOUT_IRAM, \
.base = TEGRA_IRAM_BASE + TEGRA_RESET_HANDLER_SIZE, \
.size = TEGRA_IRAM_SIZE - TEGRA_RESET_HANDLER_SIZE, \
.buddy_size = 0, /* no buddy allocation for IRAM */ \
}
#endif
/* This information is passed by bootloader */
#define COMMCHIP_UNKNOWN 0
#define COMMCHIP_NOCHIP 1
#define COMMCHIP_BROADCOM_BCM4329 2
#define COMMCHIP BROADCOM_BCM4330 3
#define COMMCHIP_MARVELL_SD8797 4
struct memory_accessor;
void tegra_assert_system_reset(char mode, const char *cmd);
void __init tegra_init_early(void);
void __init tegra_mc_init(void);
void __init tegra_map_common_io(void);
void __init tegra_init_irq(void);
void __init tegra_init_clock(void);
void __init tegra_reserve(unsigned long carveout_size, unsigned long fb_size,
unsigned long fb2_size);
/* FIXME: The following needs to move common.h when arm_soc_desc is
introduced in a future version of the kernel */
#ifdef CONFIG_CACHE_L2X0
void tegra_init_cache(bool init);
#else
static inline void tegra_init_cache(bool init) {}
#endif
void __init tegra_ram_console_debug_reserve(unsigned long ram_console_size);
void __init tegra_ram_console_debug_init(void);
void __init tegra_release_bootloader_fb(void);
void __init tegra_protected_aperture_init(unsigned long aperture);
int __init tegra_init_board_info(void);
void tegra_move_framebuffer(unsigned long to, unsigned long from,
unsigned long size);
void tegra_clear_framebuffer(unsigned long to, unsigned long size);
bool is_tegra_debug_uartport_hs(void);
int get_tegra_uart_debug_port_id(void);
int arb_lost_recovery(int scl_gpio, int sda_gpio);
extern unsigned long tegra_bootloader_fb_start;
extern unsigned long tegra_bootloader_fb_size;
extern unsigned long tegra_bootloader_fb2_start;
extern unsigned long tegra_bootloader_fb2_size;
extern unsigned long tegra_fb_start;
extern unsigned long tegra_fb_size;
extern unsigned long tegra_fb2_start;
extern unsigned long tegra_fb2_size;
extern unsigned long tegra_carveout_start;
extern unsigned long tegra_carveout_size;
extern unsigned long tegra_vpr_start;
extern unsigned long tegra_vpr_size;
extern unsigned long tegra_lp0_vec_start;
extern unsigned long tegra_lp0_vec_size;
extern bool tegra_lp0_vec_relocate;
extern unsigned long tegra_grhost_aperture;
extern struct sys_timer tegra_timer;
enum board_fab {
BOARD_FAB_A = 0,
BOARD_FAB_B,
BOARD_FAB_C,
BOARD_FAB_D,
};
struct board_info {
u16 board_id;
u16 sku;
u8 fab;
u8 major_revision;
u8 minor_revision;
};
enum panel_type {
panel_type_lvds = 0,
panel_type_dsi,
};
enum audio_codec_type {
audio_codec_none,
audio_codec_wm8903,
};
enum image_type {
system_image = 0,
rck_image,
};
void tegra_get_board_info(struct board_info *);
void tegra_get_pmu_board_info(struct board_info *bi);
void tegra_get_display_board_info(struct board_info *bi);
void tegra_get_camera_board_info(struct board_info *bi);
#ifdef CONFIG_TEGRA_CONVSERVATIVE_GOV_ON_EARLYSUPSEND
#define MAX_GOV_NAME_LEN 16
extern char cpufreq_default_gov[][MAX_GOV_NAME_LEN];
extern char *cpufreq_conservative_gov;
void cpufreq_store_default_gov(void);
void cpufreq_restore_default_gov(void);
void cpufreq_change_gov(char *target_gov);
#endif
int get_core_edp(void);
enum panel_type get_panel_type(void);
int tegra_get_modem_id(void);
int tegra_get_commchip_id(void);
enum power_supply_type get_power_supply_type(void);
enum audio_codec_type get_audio_codec_type(void);
int get_maximum_cpu_current_supported(void);
enum image_type get_tegra_image_type(void);
#endif
|
sultanxda/android_kernel_asus_grouper
|
arch/arm/mach-tegra/board.h
|
C
|
gpl-2.0
| 5,534 |
/*
Test Ping Distance.c
Measure and display Ping))) Ultrasonic Distance Sensor distance measurements.
http://learn.parallax.com/propeller-c-simple-devices/sense-distance-ping
*/
#include "simpletools.h" // Include simpletools header
#include "ping.h" // Include ping header
int main() // main function
{
while(1) // Repeat indefinitely
{
int cmDist = ping_cm(15); // Get cm distance from Ping)))
print("cmDist = %d\n", cmDist); // Display distance
pause(200); // Wait 1/5 second
}
}
|
adamwespiser/balapiller
|
SimpleIDE/Learn/Examples/Devices/Sensor/Ping))) Ultrasonic Distance/Test Ping Distance.c
|
C
|
gpl-2.0
| 691 |
/* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2009 University of Washington
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
* Author: Leonard Tracy <[email protected]>
*/
#include "uan-phy-gen.h"
#include "uan-transducer.h"
#include "uan-channel.h"
#include "uan-net-device.h"
#include "ns3/simulator.h"
#include "ns3/traced-callback.h"
#include "ns3/ptr.h"
#include "ns3/trace-source-accessor.h"
#include "ns3/double.h"
#include "ns3/log.h"
#include "ns3/uan-tx-mode.h"
#include "ns3/node.h"
#include "ns3/uinteger.h"
#include "ns3/random-variable.h"
NS_LOG_COMPONENT_DEFINE ("UanPhyGen");
namespace ns3 {
NS_OBJECT_ENSURE_REGISTERED (UanPhyGen);
NS_OBJECT_ENSURE_REGISTERED (UanPhyPerGenDefault);
NS_OBJECT_ENSURE_REGISTERED (UanPhyCalcSinrDefault);
NS_OBJECT_ENSURE_REGISTERED (UanPhyCalcSinrFhFsk);
NS_OBJECT_ENSURE_REGISTERED (UanPhyPerUmodem);
/*************** UanPhyCalcSinrDefault definition *****************/
UanPhyCalcSinrDefault::UanPhyCalcSinrDefault ()
{
}
UanPhyCalcSinrDefault::~UanPhyCalcSinrDefault ()
{
}
TypeId
UanPhyCalcSinrDefault::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::UanPhyCalcSinrDefault")
.SetParent<Object> ()
.AddConstructor<UanPhyCalcSinrDefault> ()
;
return tid;
}
double
UanPhyCalcSinrDefault::CalcSinrDb (Ptr<Packet> pkt,
Time arrTime,
double rxPowerDb,
double ambNoiseDb,
UanTxMode mode,
UanPdp pdp,
const UanTransducer::ArrivalList &arrivalList) const
{
if (mode.GetModType () == UanTxMode::OTHER)
{
NS_LOG_WARN ("Calculating SINR for unsupported modulation type");
}
double intKp = -DbToKp (rxPowerDb); // This packet is in the arrivalList
UanTransducer::ArrivalList::const_iterator it = arrivalList.begin ();
for (; it != arrivalList.end (); it++)
{
intKp += DbToKp (it->GetRxPowerDb ());
}
double totalIntDb = KpToDb (intKp + DbToKp (ambNoiseDb));
NS_LOG_DEBUG ("Calculating SINR: RxPower = " << rxPowerDb << " dB. Number of interferers = " << arrivalList.size () << " Interference + noise power = " << totalIntDb << " dB. SINR = " << rxPowerDb - totalIntDb << " dB.");
return rxPowerDb - totalIntDb;
}
/*************** UanPhyCalcSinrFhFsk definition *****************/
UanPhyCalcSinrFhFsk::UanPhyCalcSinrFhFsk ()
{
}
UanPhyCalcSinrFhFsk::~UanPhyCalcSinrFhFsk ()
{
}
TypeId
UanPhyCalcSinrFhFsk::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::UanPhyCalcSinrFhFsk")
.SetParent<Object> ()
.AddConstructor<UanPhyCalcSinrFhFsk> ()
.AddAttribute ("NumberOfHops",
"Number of frequencies in hopping pattern",
UintegerValue (13),
MakeUintegerAccessor (&UanPhyCalcSinrFhFsk::m_hops),
MakeUintegerChecker<uint32_t> ())
;
return tid;
}
double
UanPhyCalcSinrFhFsk::CalcSinrDb (Ptr<Packet> pkt,
Time arrTime,
double rxPowerDb,
double ambNoiseDb,
UanTxMode mode,
UanPdp pdp,
const UanTransducer::ArrivalList &arrivalList) const
{
if (mode.GetModType () != UanTxMode::FSK)
{
NS_LOG_WARN ("Calculating SINR for unsupported mode type");
}
double ts = 1.0 / mode.GetPhyRateSps ();
double clearingTime = (m_hops - 1.0) * ts;
double csp = pdp.SumTapsFromMaxNc (Seconds (0), Seconds (ts));
//UanPdp::Iterator tmpIt = pdp.GetBegin ();
// Get maximum arrival offset
double maxAmp = -1;
double maxTapDelay = 0.0;
UanPdp::Iterator pit = pdp.GetBegin ();
for (; pit != pdp.GetEnd (); pit++)
{
if (abs (pit->GetAmp ()) > maxAmp)
{
maxAmp = abs (pit->GetAmp ());
maxTapDelay = pit->GetDelay ().GetSeconds ();
}
}
double effRxPowerDb = rxPowerDb + KpToDb (csp);
double isiUpa = rxPowerDb * pdp.SumTapsFromMaxNc (Seconds (ts + clearingTime), Seconds (ts));
UanTransducer::ArrivalList::const_iterator it = arrivalList.begin ();
double intKp = -DbToKp (effRxPowerDb);
for (; it != arrivalList.end (); it++)
{
UanPdp intPdp = it->GetPdp ();
double tDelta = std::abs (arrTime.GetSeconds () + maxTapDelay - it->GetArrivalTime ().GetSeconds ());
// We want tDelta in terms of a single symbol (i.e. if tDelta = 7.3 symbol+clearing
// times, the offset in terms of the arriving symbol power is
// 0.3 symbol+clearing times.
int32_t syms = (uint32_t)( (double) tDelta / (ts + clearingTime));
tDelta = tDelta - syms * (ts + clearingTime);
// Align to pktRx
if (arrTime + Seconds (maxTapDelay) > it->GetArrivalTime ())
{
tDelta = ts + clearingTime - tDelta;
}
double intPower = 0.0;
if (tDelta < ts)
{
intPower += intPdp.SumTapsNc (Seconds (0), Seconds (ts - tDelta));
intPower += intPdp.SumTapsNc (Seconds (ts - tDelta + clearingTime),
Seconds (2 * ts - tDelta + clearingTime));
}
else
{
Time start = Seconds (ts + clearingTime - tDelta);
Time end = start + Seconds (ts);
intPower += intPdp.SumTapsNc (start, end);
start = start + Seconds (ts + clearingTime);
end = start + Seconds (ts);
intPower += intPdp.SumTapsNc (start, end);
}
intKp += DbToKp (it->GetRxPowerDb ()) * intPower;
}
double totalIntDb = KpToDb (isiUpa + intKp + DbToKp (ambNoiseDb));
NS_LOG_DEBUG ("Calculating SINR: RxPower = " << rxPowerDb << " dB. Effective Rx power " << effRxPowerDb << " dB. Number of interferers = " << arrivalList.size () << " Interference + noise power = " << totalIntDb << " dB. SINR = " << effRxPowerDb - totalIntDb << " dB.");
return effRxPowerDb - totalIntDb;
}
/*************** UanPhyPerGenDefault definition *****************/
UanPhyPerGenDefault::UanPhyPerGenDefault ()
{
}
UanPhyPerGenDefault::~UanPhyPerGenDefault ()
{
}
TypeId
UanPhyPerGenDefault::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::UanPhyPerGenDefault")
.SetParent<Object> ()
.AddConstructor<UanPhyPerGenDefault> ()
.AddAttribute ("Threshold", "SINR cutoff for good packet reception",
DoubleValue (8),
MakeDoubleAccessor (&UanPhyPerGenDefault::m_thresh),
MakeDoubleChecker<double> ());
return tid;
}
// Default PER calculation simply compares SINR to a threshold which is configurable
// via an attribute.
double
UanPhyPerGenDefault::CalcPer (Ptr<Packet> pkt, double sinrDb, UanTxMode mode)
{
if (sinrDb >= m_thresh)
{
return 0;
}
else
{
return 1;
}
}
/*************** UanPhyPerUmodem definition *****************/
UanPhyPerUmodem::UanPhyPerUmodem ()
{
}
UanPhyPerUmodem::~UanPhyPerUmodem ()
{
}
TypeId UanPhyPerUmodem::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::UanPhyPerUmodem")
.SetParent<Object> ()
.AddConstructor<UanPhyPerUmodem> ()
;
return tid;
}
double
UanPhyPerUmodem::NChooseK (uint32_t n, uint32_t k)
{
double result;
result = 1.0;
for (uint32_t i = std::max (k,n - k) + 1; i <= n; ++i)
{
result *= i;
}
for (uint32_t i = 2; i <= std::min (k,n - k); ++i)
{
result /= i;
}
return result;
}
double
UanPhyPerUmodem::CalcPer (Ptr<Packet> pkt, double sinr, UanTxMode mode)
{
uint32_t d[] =
{ 12, 14, 16, 18, 20, 22, 24, 26, 28 };
double Bd[] =
{
33, 281, 2179, 15035LLU, 105166LLU, 692330LLU, 4580007LLU, 29692894LLU,
190453145LLU
};
// double Rc = 1.0 / 2.0;
double ebno = std::pow (10.0, sinr / 10.0);
double perror = 1.0 / (2.0 + ebno);
double P[9];
if (sinr >= 10)
{
return 0;
}
if (sinr <= 6)
{
return 1;
}
for (uint32_t r = 0; r < 9; r++)
{
double sumd = 0;
for (uint32_t k = 0; k < d[r]; k++)
{
sumd = sumd + NChooseK (d[r] - 1 + k, k) * std::pow (1 - perror, (double) k);
}
P[r] = std::pow (perror, (double) d[r]) * sumd;
}
double Pb = 0;
for (uint32_t r = 0; r < 8; r++)
{
Pb = Pb + Bd[r] * P[r];
}
// cout << "Pb = " << Pb << endl;
uint32_t bits = pkt->GetSize () * 8;
double Ppacket = 1;
double temp = NChooseK (bits, 0);
temp *= std::pow ( (1 - Pb), (double) bits);
Ppacket -= temp;
temp = NChooseK (288, 1) * Pb * std::pow ( (1 - Pb), bits - 1.0);
Ppacket -= temp;
if (Ppacket > 1)
{
return 1;
}
else
{
return Ppacket;
}
}
/*************** UanPhyGen definition *****************/
UanPhyGen::UanPhyGen ()
: UanPhy (),
m_state (IDLE),
m_channel (0),
m_transducer (0),
m_device (0),
m_mac (0),
m_rxGainDb (0),
m_txPwrDb (0),
m_rxThreshDb (0),
m_ccaThreshDb (0),
m_pktRx (0),
m_cleared (false)
{
}
UanPhyGen::~UanPhyGen ()
{
}
void
UanPhyGen::Clear ()
{
if (m_cleared)
{
return;
}
m_cleared = true;
m_listeners.clear ();
if (m_channel)
{
m_channel->Clear ();
m_channel = 0;
}
if (m_transducer)
{
m_transducer->Clear ();
m_transducer = 0;
}
if (m_device)
{
m_device->Clear ();
m_device = 0;
}
if (m_mac)
{
m_mac->Clear ();
m_mac = 0;
}
if (m_per)
{
m_per->Clear ();
m_per = 0;
}
if (m_sinr)
{
m_sinr->Clear ();
m_sinr = 0;
}
m_pktRx = 0;
}
void
UanPhyGen::DoDispose ()
{
Clear ();
UanPhy::DoDispose ();
}
UanModesList
UanPhyGen::GetDefaultModes (void)
{
UanModesList l;
l.AppendMode (UanTxModeFactory::CreateMode (UanTxMode::FSK,80,80,22000,4000,13,"FSK"));
l.AppendMode (UanTxModeFactory::CreateMode (UanTxMode::PSK,200, 200, 22000, 4000, 4, "QPSK"));
return l;
}
TypeId
UanPhyGen::GetTypeId (void)
{
static TypeId tid = TypeId ("ns3::UanPhyGen")
.SetParent<Object> ()
.AddConstructor<UanPhyGen> ()
.AddAttribute ("CcaThreshold",
"Aggregate energy of incoming signals to move to CCA Busy state dB",
DoubleValue (10),
MakeDoubleAccessor (&UanPhyGen::m_ccaThreshDb),
MakeDoubleChecker<double> ())
.AddAttribute ("RxThreshold",
"Required SNR for signal acquisition in dB",
DoubleValue (10),
MakeDoubleAccessor (&UanPhyGen::m_rxThreshDb),
MakeDoubleChecker<double> ())
.AddAttribute ("TxPower",
"Transmission output power in dB",
DoubleValue (190),
MakeDoubleAccessor (&UanPhyGen::m_txPwrDb),
MakeDoubleChecker<double> ())
.AddAttribute ("RxGain",
"Gain added to incoming signal at receiver",
DoubleValue (0),
MakeDoubleAccessor (&UanPhyGen::m_rxGainDb),
MakeDoubleChecker<double> ())
.AddAttribute ("SupportedModes",
"List of modes supported by this PHY",
UanModesListValue (UanPhyGen::GetDefaultModes ()),
MakeUanModesListAccessor (&UanPhyGen::m_modes),
MakeUanModesListChecker () )
.AddAttribute ("PerModel",
"Functor to calculate PER based on SINR and TxMode",
PointerValue (CreateObject<UanPhyPerGenDefault> ()),
MakePointerAccessor (&UanPhyGen::m_per),
MakePointerChecker<UanPhyPer> ())
.AddAttribute ("SinrModel",
"Functor to calculate SINR based on pkt arrivals and modes",
PointerValue (CreateObject<UanPhyCalcSinrDefault> ()),
MakePointerAccessor (&UanPhyGen::m_sinr),
MakePointerChecker<UanPhyCalcSinr> ())
.AddTraceSource ("RxOk",
"A packet was received successfully",
MakeTraceSourceAccessor (&UanPhyGen::m_rxOkLogger))
.AddTraceSource ("RxError",
"A packet was received unsuccessfully",
MakeTraceSourceAccessor (&UanPhyGen::m_rxErrLogger))
.AddTraceSource ("Tx",
"Packet transmission beginning",
MakeTraceSourceAccessor (&UanPhyGen::m_txLogger))
;
return tid;
}
void
UanPhyGen::SendPacket (Ptr<Packet> pkt, uint32_t modeNum)
{
NS_LOG_DEBUG ("PHY " << m_mac->GetAddress () << ": Transmitting packet");
if (m_state == TX)
{
NS_LOG_DEBUG ("PHY requested to TX while already Transmitting. Dropping packet.");
return;
}
UanTxMode txMode = GetMode (modeNum);
if (m_pktRx != 0)
{
m_minRxSinrDb = -1e30;
m_pktRx = 0;
}
m_transducer->Transmit (Ptr<UanPhy> (this), pkt, m_txPwrDb, txMode);
m_state = TX;
double txdelay = pkt->GetSize () * 8.0 / txMode.GetDataRateBps ();
Simulator::Schedule (Seconds (txdelay), &UanPhyGen::TxEndEvent, this);
NS_LOG_DEBUG ("PHY " << m_mac->GetAddress () << " notifying listeners");
NotifyListenersTxStart (Seconds (txdelay));
m_txLogger (pkt, m_txPwrDb, txMode);
}
void
UanPhyGen::TxEndEvent ()
{
NS_ASSERT (m_state == TX);
if (GetInterferenceDb ( (Ptr<Packet>) 0) > m_ccaThreshDb)
{
m_state = CCABUSY;
NotifyListenersCcaStart ();
}
else
{
m_state = IDLE;
}
}
void
UanPhyGen::RegisterListener (UanPhyListener *listener)
{
m_listeners.push_back (listener);
}
void
UanPhyGen::StartRxPacket (Ptr<Packet> pkt, double rxPowerDb, UanTxMode txMode, UanPdp pdp)
{
switch (m_state)
{
case TX:
NS_ASSERT (false);
break;
case RX:
{
NS_ASSERT (m_pktRx);
double newSinrDb = CalculateSinrDb (m_pktRx, m_pktRxArrTime, m_rxRecvPwrDb, m_pktRxMode, m_pktRxPdp);
m_minRxSinrDb = (newSinrDb < m_minRxSinrDb) ? newSinrDb : m_minRxSinrDb;
NS_LOG_DEBUG ("PHY " << m_mac->GetAddress () << ": Starting RX in RX mode. SINR of pktRx = " << m_minRxSinrDb);
}
break;
case CCABUSY:
case IDLE:
{
NS_ASSERT (!m_pktRx);
bool hasmode = false;
for (uint32_t i = 0; i < GetNModes (); i++)
{
if (txMode.GetUid () == GetMode (i).GetUid ())
{
hasmode = true;
break;
}
}
if (!hasmode)
{
break;
}
double newsinr = CalculateSinrDb (pkt, Simulator::Now (), rxPowerDb, txMode, pdp);
NS_LOG_DEBUG ("PHY " << m_mac->GetAddress () << ": Starting RX in IDLE mode. SINR = " << newsinr);
if (newsinr > m_rxThreshDb)
{
m_state = RX;
m_rxRecvPwrDb = rxPowerDb;
m_minRxSinrDb = newsinr;
m_pktRx = pkt;
m_pktRxArrTime = Simulator::Now ();
m_pktRxMode = txMode;
m_pktRxPdp = pdp;
double txdelay = pkt->GetSize () * 8.0 / txMode.GetDataRateBps ();
Simulator::Schedule (Seconds (txdelay), &UanPhyGen::RxEndEvent, this, pkt, rxPowerDb, txMode);
NotifyListenersRxStart ();
}
}
break;
}
if (m_state == IDLE && GetInterferenceDb ( (Ptr<Packet>) 0) > m_ccaThreshDb)
{
m_state = CCABUSY;
NotifyListenersCcaStart ();
}
}
void
UanPhyGen::RxEndEvent (Ptr<Packet> pkt, double rxPowerDb, UanTxMode txMode)
{
if (pkt != m_pktRx)
{
return;
}
if (GetInterferenceDb ( (Ptr<Packet>) 0) > m_ccaThreshDb)
{
m_state = CCABUSY;
NotifyListenersCcaStart ();
}
else
{
m_state = IDLE;
}
UniformVariable pg;
if (pg.GetValue (0, 1) > m_per->CalcPer (m_pktRx, m_minRxSinrDb, txMode))
{
m_rxOkLogger (pkt, m_minRxSinrDb, txMode);
NotifyListenersRxGood ();
if (!m_recOkCb.IsNull ())
{
m_recOkCb (pkt, m_minRxSinrDb, txMode);
}
}
else
{
m_rxErrLogger (pkt, m_minRxSinrDb, txMode);
NotifyListenersRxBad ();
if (!m_recErrCb.IsNull ())
{
m_recErrCb (pkt, m_minRxSinrDb);
}
}
m_pktRx = 0;
}
void
UanPhyGen::SetReceiveOkCallback (RxOkCallback cb)
{
m_recOkCb = cb;
}
void
UanPhyGen::SetReceiveErrorCallback (RxErrCallback cb)
{
m_recErrCb = cb;
}
bool
UanPhyGen::IsStateIdle (void)
{
return m_state == IDLE;
}
bool
UanPhyGen::IsStateBusy (void)
{
return m_state != IDLE;
}
bool
UanPhyGen::IsStateRx (void)
{
return m_state == RX;
}
bool
UanPhyGen::IsStateTx (void)
{
return m_state == TX;
}
bool
UanPhyGen::IsStateCcaBusy (void)
{
return m_state == CCABUSY;
}
void
UanPhyGen::SetRxGainDb (double gain)
{
m_rxGainDb = gain;
}
void
UanPhyGen::SetTxPowerDb (double txpwr)
{
m_txPwrDb = txpwr;
}
void
UanPhyGen::SetRxThresholdDb (double thresh)
{
m_rxThreshDb = thresh;
}
void
UanPhyGen::SetCcaThresholdDb (double thresh)
{
m_ccaThreshDb = thresh;
}
double
UanPhyGen::GetRxGainDb (void)
{
return m_rxGainDb;
}
double
UanPhyGen::GetTxPowerDb (void)
{
return m_txPwrDb;
}
double
UanPhyGen::GetRxThresholdDb (void)
{
return m_rxThreshDb;
}
double
UanPhyGen::GetCcaThresholdDb (void)
{
return m_ccaThreshDb;
}
Ptr<UanChannel>
UanPhyGen::GetChannel (void) const
{
return m_channel;
}
Ptr<UanNetDevice>
UanPhyGen::GetDevice (void)
{
return m_device;
}
Ptr<UanTransducer>
UanPhyGen::GetTransducer (void)
{
return m_transducer;
}
void
UanPhyGen::SetChannel (Ptr<UanChannel> channel)
{
m_channel = channel;
}
void
UanPhyGen::SetDevice (Ptr<UanNetDevice> device)
{
m_device = device;
}
void
UanPhyGen::SetMac (Ptr<UanMac> mac)
{
m_mac = mac;
}
void
UanPhyGen::SetTransducer (Ptr<UanTransducer> trans)
{
m_transducer = trans;
m_transducer->AddPhy (this);
}
void
UanPhyGen::NotifyTransStartTx (Ptr<Packet> packet, double txPowerDb, UanTxMode txMode)
{
if (m_pktRx)
{
m_minRxSinrDb = -1e30;
}
}
void
UanPhyGen::NotifyIntChange (void)
{
if (m_state == CCABUSY && GetInterferenceDb (Ptr<Packet> ()) < m_ccaThreshDb)
{
m_state = IDLE;
NotifyListenersCcaEnd ();
}
}
double
UanPhyGen::CalculateSinrDb (Ptr<Packet> pkt, Time arrTime, double rxPowerDb, UanTxMode mode, UanPdp pdp)
{
double noiseDb = m_channel->GetNoiseDbHz ( (double) mode.GetCenterFreqHz () / 1000.0) + 10 * log10 (mode.GetBandwidthHz ());
return m_sinr->CalcSinrDb (pkt, arrTime, rxPowerDb, noiseDb, mode, pdp, m_transducer->GetArrivalList ());
}
double
UanPhyGen::GetInterferenceDb (Ptr<Packet> pkt)
{
const UanTransducer::ArrivalList &arrivalList = m_transducer->GetArrivalList ();
UanTransducer::ArrivalList::const_iterator it = arrivalList.begin ();
double interfPower = 0;
for (; it != arrivalList.end (); it++)
{
if (pkt != it->GetPacket ())
{
interfPower += DbToKp (it->GetRxPowerDb ());
}
}
return KpToDb (interfPower);
}
double
UanPhyGen::DbToKp (double db)
{
return pow (10, db / 10.0);
}
double
UanPhyGen::KpToDb (double kp)
{
return 10 * log10 (kp);
}
void
UanPhyGen::NotifyListenersRxStart (void)
{
ListenerList::const_iterator it = m_listeners.begin ();
for (; it != m_listeners.end (); it++)
{
(*it)->NotifyRxStart ();
}
}
void
UanPhyGen::NotifyListenersRxGood (void)
{
ListenerList::const_iterator it = m_listeners.begin ();
for (; it != m_listeners.end (); it++)
{
(*it)->NotifyRxEndOk ();
}
}
void
UanPhyGen::NotifyListenersRxBad (void)
{
ListenerList::const_iterator it = m_listeners.begin ();
for (; it != m_listeners.end (); it++)
{
(*it)->NotifyRxEndError ();
}
}
void
UanPhyGen::NotifyListenersCcaStart (void)
{
ListenerList::const_iterator it = m_listeners.begin ();
for (; it != m_listeners.end (); it++)
{
(*it)->NotifyCcaStart ();
}
}
void
UanPhyGen::NotifyListenersCcaEnd (void)
{
ListenerList::const_iterator it = m_listeners.begin ();
for (; it != m_listeners.end (); it++)
{
(*it)->NotifyCcaEnd ();
}
}
void
UanPhyGen::NotifyListenersTxStart (Time duration)
{
ListenerList::const_iterator it = m_listeners.begin ();
for (; it != m_listeners.end (); it++)
{
(*it)->NotifyTxStart (duration);
}
}
uint32_t
UanPhyGen::GetNModes (void)
{
return m_modes.GetNModes ();
}
UanTxMode
UanPhyGen::GetMode (uint32_t n)
{
NS_ASSERT (n < m_modes.GetNModes ());
return m_modes[n];
}
Ptr<Packet>
UanPhyGen::GetPacketRx (void) const
{
return m_pktRx;
}
} // namespace ns3
|
ciprian-radu/unimap.ns-3noc
|
src/devices/uan/model/uan-phy-gen.cc
|
C++
|
gpl-2.0
| 21,332 |
/* BFD support for the Alpha architecture.
Copyright 1992, 1993, 1998, 2000, 2002 Free Software Foundation, Inc.
This file is part of BFD, the Binary File Descriptor library.
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */
#include "bfd.h"
#include "sysdep.h"
#include "libbfd.h"
#define N(BITS_WORD, BITS_ADDR, NUMBER, PRINT, DEFAULT, NEXT) \
{ \
BITS_WORD, /* bits in a word */ \
BITS_ADDR, /* bits in an address */ \
8, /* 8 bits in a byte */ \
bfd_arch_alpha, \
NUMBER, \
"alpha", \
PRINT, \
3, \
DEFAULT, \
bfd_default_compatible, \
bfd_default_scan, \
NEXT, \
}
#define NN(index) (&arch_info_struct[index])
/* These exist only so that we can resonably disassemble PALcode. */
static const bfd_arch_info_type arch_info_struct[] =
{
N (64, 64, bfd_mach_alpha_ev4, "alpha:ev4", FALSE, NN(1)),
N (64, 64, bfd_mach_alpha_ev5, "alpha:ev5", FALSE, NN(2)),
N (64, 64, bfd_mach_alpha_ev6, "alpha:ev6", FALSE, 0),
};
const bfd_arch_info_type bfd_alpha_arch =
N (64, 64, 0, "alpha", TRUE, NN(0));
|
ryo-on/binutils-2.14-SCO-OpenServer5
|
bfd/cpu-alpha.c
|
C
|
gpl-2.0
| 1,752 |
#pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
// System.Collections.Generic.EqualityComparer`1<System.Object>
struct EqualityComparer_1_t1472;
#include "mscorlib_System_Object.h"
// System.Collections.Generic.EqualityComparer`1<System.Object>
struct EqualityComparer_1_t1472 : public Object_t
{
};
struct EqualityComparer_1_t1472_StaticFields{
// System.Collections.Generic.EqualityComparer`1<T> System.Collections.Generic.EqualityComparer`1<System.Object>::_default
EqualityComparer_1_t1472 * ____default_0;
};
|
Soufien/unityIntoIOSSample
|
SampleProject/il2cpp_output/mscorlib_System_Collections_Generic_EqualityComparer_1_gen.h
|
C
|
gpl-2.0
| 611 |
/*
Copyright_License {
XCSoar Glide Computer - http://www.xcsoar.org/
Copyright (C) 2000-2016 The XCSoar Project
A detailed list of copyright holders can be found in the file "AUTHORS".
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
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 XCSOAR_VALIDITY_HPP
#define XCSOAR_VALIDITY_HPP
#include "Util/Compiler.h"
#include <chrono>
#include <type_traits>
#include <cassert>
#include <cstdint>
/**
* This keeps track when a value was last changed, to check if it was
* updated recently or to see if it has expired. Additionally, it can
* track if the attribute is not set (timestamp is zero).
*/
class Validity {
static constexpr int BITS = 6;
using Duration = std::chrono::duration<uint32_t, std::ratio<1, 1 << BITS>>;
using FloatDuration = std::chrono::duration<double>;
Duration last;
static constexpr Duration Import(double time) noexcept {
return std::chrono::duration_cast<Duration>(FloatDuration(time));
}
static constexpr double Export(Duration i) noexcept {
return std::chrono::duration_cast<FloatDuration>(i).count();
}
public:
/**
* Cheap default constructor without initialization.
*/
Validity() = default;
/**
* Initialize the object with the specified timestamp.
*/
explicit constexpr Validity(double _last) noexcept
:last(Import(_last)) {}
public:
/**
* Clears the time stamp, marking the referenced value "invalid".
*/
void Clear() {
last = Duration::zero();
}
/**
* Updates the time stamp, setting it to the current clock. This
* marks the referenced value as "valid".
*
* @param now the current time stamp in seconds
*/
void Update(double now) {
last = Import(now);
}
/**
* Checks if the time stamp has expired, and calls clear() if so.
*
* @param now the current time stamp in seconds
* @param max_age the maximum age in seconds
* @return true if the value is expired
*/
bool Expire(double _now,
std::chrono::steady_clock::duration _max_age) noexcept {
const auto now = Import(_now);
const auto max_age = std::chrono::duration_cast<Duration>(_max_age);
if (IsValid() &&
(now < last || /* time warp? */
now > last + max_age)) { /* expired? */
Clear();
return true;
} else
/* not expired */
return false;
}
/**
* Checks if the time stamp is older than the given time.
*
* @param now the current time stamp in seconds
* @param max_age the maximum age in seconds
* @return true if the value is expired
*/
bool IsOlderThan(double _now,
std::chrono::steady_clock::duration _max_age) const noexcept {
if (!IsValid())
return true;
const auto now = Import(_now);
const auto max_age = std::chrono::duration_cast<Duration>(_max_age);
return (now < last || /* time warp? */
now > last + max_age); /* expired? */
}
constexpr bool IsValid() const {
return last > Duration::zero();
}
/**
* This function calculates the time difference of the two Validity objects
* @param other The second Validity object
* @return The time difference in seconds
*/
FloatDuration GetTimeDifference(const Validity &other) const noexcept {
assert(IsValid());
assert(other.IsValid());
return std::chrono::duration_cast<FloatDuration>(last - other.last);
}
/**
* Was the value modified since the time the "other" object was
* taken?
*/
constexpr bool Modified(const Validity &other) const {
return last > other.last;
}
constexpr bool operator==(const Validity &other) const {
return last == other.last;
}
constexpr bool operator!=(const Validity &other) const {
return last != other.last;
}
bool Complement(const Validity &other) {
if (!IsValid() && other.IsValid()) {
*this = other;
return true;
} else
return false;
}
/**
* Check this stored Validity object for a time warp and clear if it
* one has occurred. If this object is invalid, it is not
* considered a time warp, even if the current object is valid.
*
* @param current the current "real" time stamp
* @param max_period if time in "current" has advanced more than
* this number of seconds, consider this a time warp, too
* @return true if a time warp has occurred and this object has been
* cleared, false if this object is within range
*/
bool FixTimeWarp(const Validity ¤t,
std::chrono::steady_clock::duration _max_period=std::chrono::minutes(5)) noexcept {
if (!IsValid())
return false;
const auto max_period = std::chrono::duration_cast<Duration>(_max_period);
if (last + max_period < current.last || last > current.last) {
/* out of range, this is a time warp */
Clear();
return true;
}
return false;
}
constexpr operator bool() const {
return IsValid();
}
};
static_assert(std::is_trivial<Validity>::value, "type is not trivial");
#endif
|
fb/XCSoar
|
src/NMEA/Validity.hpp
|
C++
|
gpl-2.0
| 5,671 |
#ifndef ViewApplet_h
#define ViewApplet_h
#include "viewbase.h"
#include <kpanelapplet.h>
class QBoxLayout;
class QHBox;
class QSize;
class Mixer;
class ViewApplet : public ViewBase
{
Q_OBJECT
public:
ViewApplet(QWidget* parent, const char* name, Mixer* mixer, ViewBase::ViewFlags vflags, KPanelApplet::Position pos);
~ViewApplet();
virtual int count();
virtual int advice();
virtual void setMixSet(MixSet *mixset);
virtual QWidget* add(MixDevice *mdw);
virtual void constructionFinished();
virtual void configurationUpdate();
QSize sizeHint() const;
QSizePolicy sizePolicy() const;
virtual void resizeEvent(QResizeEvent*);
signals:
void appletContentChanged();
public slots:
virtual void refreshVolumeLevels();
private:
bool shouldShowIcons(QSize);
QBoxLayout* _layoutMDW;
// Position of the applet (pLeft, pRight, pTop, pBottom)
//KPanelApplet::Position _KMIXposition;
// Orientation of the applet (horizontal or vertical)
Qt::Orientation _viewOrientation;
};
#endif
|
serghei/kde3-kdemultimedia
|
kmix/viewapplet.h
|
C
|
gpl-2.0
| 1,068 |
/*
* Copyright (c) 2011 Raphael Kubo da Costa <[email protected]>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* 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.
*/
#ifndef JSONPARSER_H
#define JSONPARSER_H
#include "kerfuffle/archive.h"
#include <QtCore/QIODevice>
#include <QtCore/QMap>
#include <QtCore/QString>
/**
* Simple parser which reads JSON files and creates @c ArchiveEntry objects
* from it.
*
* The JSON file is expected to follow a specific format that describes an
* archive read by Kerfuffle.
*
* The format consists of a list of dictionaries whose keys are values from the
* EntryMetaDataType enum. The only required key for each entry is FileName;
* other values which are omitted for each entry are assumed to be 0 or false.
*
* Example file:
* @code
* [
* { "FileName": "foo", "IsPasswordProtected": true },
* { "FileName": "aDir/", "IsDirectory": true }
* ]
* @endcode
*
* @author Raphael Kubo da Costa <[email protected]>
*/
class JSONParser
{
public:
typedef QMap<QString, Kerfuffle::ArchiveEntry> JSONArchive;
~JSONParser();
static JSONArchive parse(const QString &json);
static JSONArchive parse(QIODevice *json);
private:
JSONParser();
/**
* Parses each entry in the QVariant obtained from parsing a JSON file and
* creates a @c JSONArchive from them.
*
* If an entry does not have a "FileName" key, it is ignored. Keys which do
* not correspond to a value in the EntryMetaDataType enum are ignored.
*
* @return A new @c JSONArchive corresponding to the parsed JSON file. If a
* parsing error occurs, it is empty.
*/
static JSONArchive createJSONArchive(const QVariant &json);
};
#endif // JSONPARSER_H
|
pombreda/git-anongit.kde.org-ark
|
kerfuffle/tests/jsonparser.h
|
C
|
gpl-2.0
| 2,914 |
// Copyright 2008 Dolphin Emulator Project
// Licensed under GPLv2+
// Refer to the license.txt file included.
#pragma once
#include <string>
#include "Common/ChunkFile.h"
#include "Common/CommonTypes.h"
#include "Core/IOS/Device.h"
#include "Core/IOS/IOS.h"
class PointerWrap;
namespace File
{
class IOFile;
}
namespace IOS
{
namespace HLE
{
std::string BuildFilename(const std::string& wii_path);
void CreateVirtualFATFilesystem();
namespace Device
{
class FileIO : public Device
{
public:
FileIO(Kernel& ios, const std::string& device_name);
IPCCommandResult Close(u32 fd) override;
IPCCommandResult Open(const OpenRequest& request) override;
IPCCommandResult Seek(const SeekRequest& request) override;
IPCCommandResult Read(const ReadWriteRequest& request) override;
IPCCommandResult Write(const ReadWriteRequest& request) override;
IPCCommandResult IOCtl(const IOCtlRequest& request) override;
void PrepareForState(PointerWrap::Mode mode) override;
void DoState(PointerWrap& p) override;
void OpenFile();
private:
enum
{
ISFS_FUNCNULL = 0,
ISFS_FUNCGETSTAT = 1,
ISFS_FUNCREADDIR = 2,
ISFS_FUNCGETATTR = 3,
ISFS_FUNCGETUSAGE = 4
};
enum
{
ISFS_IOCTL_FORMAT = 1,
ISFS_IOCTL_GETSTATS = 2,
ISFS_IOCTL_CREATEDIR = 3,
ISFS_IOCTL_READDIR = 4,
ISFS_IOCTL_SETATTR = 5,
ISFS_IOCTL_GETATTR = 6,
ISFS_IOCTL_DELETE = 7,
ISFS_IOCTL_RENAME = 8,
ISFS_IOCTL_CREATEFILE = 9,
ISFS_IOCTL_SETFILEVERCTRL = 10,
ISFS_IOCTL_GETFILESTATS = 11,
ISFS_IOCTL_GETUSAGE = 12,
ISFS_IOCTL_SHUTDOWN = 13
};
IPCCommandResult GetFileStats(const IOCtlRequest& request);
u32 m_Mode = 0;
u32 m_SeekPos = 0;
std::string m_filepath;
std::shared_ptr<File::IOFile> m_file;
};
} // namespace Device
} // namespace HLE
} // namespace IOS
|
Tinob/Ishiiruka
|
Source/Core/Core/IOS/FS/FileIO.h
|
C
|
gpl-2.0
| 1,829 |
/*
* NET3: Token ring device handling subroutines
*
* 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.
*
* Fixes: 3 Feb 97 Paul Norton <[email protected]> Minor routing fixes.
* Added rif table to /proc/net/tr_rif and rif timeout to
* /proc/sys/net/token-ring/rif_timeout.
* 22 Jun 98 Paul Norton <[email protected]> Rearranged
* tr_header and tr_type_trans to handle passing IPX SNAP and
* 802.2 through the correct layers. Eliminated tr_reformat.
*
*/
#include <asm/uaccess.h>
#include <asm/system.h>
#include <linux/config.h>
#include <linux/module.h>
#include <linux/types.h>
#include <linux/kernel.h>
#include <linux/jiffies.h>
#include <linux/string.h>
#include <linux/mm.h>
#include <linux/socket.h>
#include <linux/in.h>
#include <linux/inet.h>
#include <linux/netdevice.h>
#include <linux/trdevice.h>
#include <linux/skbuff.h>
#include <linux/errno.h>
#include <linux/timer.h>
#include <linux/net.h>
#include <linux/proc_fs.h>
#include <linux/seq_file.h>
#include <linux/init.h>
#include <net/arp.h>
static void tr_add_rif_info(struct trh_hdr *trh, struct net_device *dev);
static void rif_check_expire(unsigned long dummy);
#define TR_SR_DEBUG 0
/*
* Each RIF entry we learn is kept this way
*/
struct rif_cache_s {
unsigned char addr[TR_ALEN];
int iface;
__u16 rcf;
__u16 rseg[8];
struct rif_cache_s *next;
unsigned long last_used;
unsigned char local_ring;
};
#define RIF_TABLE_SIZE 32
/*
* We hash the RIF cache 32 ways. We do after all have to look it
* up a lot.
*/
static struct rif_cache_s *rif_table[RIF_TABLE_SIZE];
static spinlock_t rif_lock = SPIN_LOCK_UNLOCKED;
/*
* Garbage disposal timer.
*/
static struct timer_list rif_timer;
int sysctl_tr_rif_timeout = 60*10*HZ;
static inline unsigned long rif_hash(const unsigned char *addr)
{
unsigned long x;
x = addr[0];
x = (x << 2) ^ addr[1];
x = (x << 2) ^ addr[2];
x = (x << 2) ^ addr[3];
x = (x << 2) ^ addr[4];
x = (x << 2) ^ addr[5];
x ^= x >> 8;
return x & (RIF_TABLE_SIZE - 1);
}
/*
* Put the headers on a token ring packet. Token ring source routing
* makes this a little more exciting than on ethernet.
*/
int tr_header(struct sk_buff *skb, struct net_device *dev, unsigned short type,
void *daddr, void *saddr, unsigned len)
{
struct trh_hdr *trh;
int hdr_len;
/*
* Add the 802.2 SNAP header if IP as the IPv4/IPv6 code calls
* dev->hard_header directly.
*/
if (type == ETH_P_IP || type == ETH_P_IPV6 || type == ETH_P_ARP)
{
struct trllc *trllc=(struct trllc *)(trh+1);
hdr_len = sizeof(struct trh_hdr) + sizeof(struct trllc);
trh = (struct trh_hdr *)skb_push(skb, hdr_len);
trllc = (struct trllc *)(trh+1);
trllc->dsap = trllc->ssap = EXTENDED_SAP;
trllc->llc = UI_CMD;
trllc->protid[0] = trllc->protid[1] = trllc->protid[2] = 0x00;
trllc->ethertype = htons(type);
}
else
{
hdr_len = sizeof(struct trh_hdr);
trh = (struct trh_hdr *)skb_push(skb, hdr_len);
}
trh->ac=AC;
trh->fc=LLC_FRAME;
if(saddr)
memcpy(trh->saddr,saddr,dev->addr_len);
else
memcpy(trh->saddr,dev->dev_addr,dev->addr_len);
/*
* Build the destination and then source route the frame
*/
if(daddr)
{
memcpy(trh->daddr,daddr,dev->addr_len);
tr_source_route(skb,trh,dev);
return(hdr_len);
}
return -hdr_len;
}
/*
* A neighbour discovery of some species (eg arp) has completed. We
* can now send the packet.
*/
int tr_rebuild_header(struct sk_buff *skb)
{
struct trh_hdr *trh=(struct trh_hdr *)skb->data;
struct trllc *trllc=(struct trllc *)(skb->data+sizeof(struct trh_hdr));
struct net_device *dev = skb->dev;
/*
* FIXME: We don't yet support IPv6 over token rings
*/
if(trllc->ethertype != htons(ETH_P_IP)) {
printk("tr_rebuild_header: Don't know how to resolve type %04X addresses ?\n",(unsigned int)htons(trllc->ethertype));
return 0;
}
#ifdef CONFIG_INET
if(arp_find(trh->daddr, skb)) {
return 1;
}
else
#endif
{
tr_source_route(skb,trh,dev);
return 0;
}
}
/*
* Some of this is a bit hackish. We intercept RIF information
* used for source routing. We also grab IP directly and don't feed
* it via SNAP.
*/
unsigned short tr_type_trans(struct sk_buff *skb, struct net_device *dev)
{
struct trh_hdr *trh=(struct trh_hdr *)skb->data;
struct trllc *trllc;
unsigned riflen=0;
skb->mac.raw = skb->data;
if(trh->saddr[0] & TR_RII)
riflen = (ntohs(trh->rcf) & TR_RCF_LEN_MASK) >> 8;
trllc = (struct trllc *)(skb->data+sizeof(struct trh_hdr)-TR_MAXRIFLEN+riflen);
skb_pull(skb,sizeof(struct trh_hdr)-TR_MAXRIFLEN+riflen);
if(*trh->daddr & 0x80)
{
if(!memcmp(trh->daddr,dev->broadcast,TR_ALEN))
skb->pkt_type=PACKET_BROADCAST;
else
skb->pkt_type=PACKET_MULTICAST;
}
else if ( (trh->daddr[0] & 0x01) && (trh->daddr[1] & 0x00) && (trh->daddr[2] & 0x5E))
{
skb->pkt_type=PACKET_MULTICAST;
}
else if(dev->flags & IFF_PROMISC)
{
if(memcmp(trh->daddr, dev->dev_addr, TR_ALEN))
skb->pkt_type=PACKET_OTHERHOST;
}
if ((skb->pkt_type != PACKET_BROADCAST) &&
(skb->pkt_type != PACKET_MULTICAST))
tr_add_rif_info(trh,dev) ;
/*
* Strip the SNAP header from ARP packets since we don't
* pass them through to the 802.2/SNAP layers.
*/
if (trllc->dsap == EXTENDED_SAP &&
(trllc->ethertype == ntohs(ETH_P_IP) ||
trllc->ethertype == ntohs(ETH_P_IPV6) ||
trllc->ethertype == ntohs(ETH_P_ARP)))
{
skb_pull(skb, sizeof(struct trllc));
return trllc->ethertype;
}
return ntohs(ETH_P_802_2);
}
/*
* We try to do source routing...
*/
void tr_source_route(struct sk_buff *skb,struct trh_hdr *trh,struct net_device *dev)
{
int slack;
unsigned int hash;
struct rif_cache_s *entry;
unsigned char *olddata;
static const unsigned char mcast_func_addr[]
= {0xC0,0x00,0x00,0x04,0x00,0x00};
spin_lock_bh(&rif_lock);
/*
* Broadcasts are single route as stated in RFC 1042
*/
if( (!memcmp(&(trh->daddr[0]),&(dev->broadcast[0]),TR_ALEN)) ||
(!memcmp(&(trh->daddr[0]),&(mcast_func_addr[0]), TR_ALEN)) )
{
trh->rcf=htons((((sizeof(trh->rcf)) << 8) & TR_RCF_LEN_MASK)
| TR_RCF_FRAME2K | TR_RCF_LIMITED_BROADCAST);
trh->saddr[0]|=TR_RII;
}
else
{
hash = rif_hash(trh->daddr);
/*
* Walk the hash table and look for an entry
*/
for(entry=rif_table[hash];entry && memcmp(&(entry->addr[0]),&(trh->daddr[0]),TR_ALEN);entry=entry->next);
/*
* If we found an entry we can route the frame.
*/
if(entry)
{
#if TR_SR_DEBUG
printk("source routing for %02X:%02X:%02X:%02X:%02X:%02X\n",trh->daddr[0],
trh->daddr[1],trh->daddr[2],trh->daddr[3],trh->daddr[4],trh->daddr[5]);
#endif
if(!entry->local_ring && (ntohs(entry->rcf) & TR_RCF_LEN_MASK) >> 8)
{
trh->rcf=entry->rcf;
memcpy(&trh->rseg[0],&entry->rseg[0],8*sizeof(unsigned short));
trh->rcf^=htons(TR_RCF_DIR_BIT);
trh->rcf&=htons(0x1fff); /* Issam Chehab <[email protected]> */
trh->saddr[0]|=TR_RII;
#if TR_SR_DEBUG
printk("entry found with rcf %04x\n", entry->rcf);
}
else
{
printk("entry found but without rcf length, local=%02x\n", entry->local_ring);
#endif
}
entry->last_used=jiffies;
}
else
{
/*
* Without the information we simply have to shout
* on the wire. The replies should rapidly clean this
* situation up.
*/
trh->rcf=htons((((sizeof(trh->rcf)) << 8) & TR_RCF_LEN_MASK)
| TR_RCF_FRAME2K | TR_RCF_LIMITED_BROADCAST);
trh->saddr[0]|=TR_RII;
#if TR_SR_DEBUG
printk("no entry in rif table found - broadcasting frame\n");
#endif
}
}
/* Compress the RIF here so we don't have to do it in the driver(s) */
if (!(trh->saddr[0] & 0x80))
slack = 18;
else
slack = 18 - ((ntohs(trh->rcf) & TR_RCF_LEN_MASK)>>8);
olddata = skb->data;
spin_unlock_bh(&rif_lock);
skb_pull(skb, slack);
memmove(skb->data, olddata, sizeof(struct trh_hdr) - slack);
}
/*
* We have learned some new RIF information for our source
* routing.
*/
static void tr_add_rif_info(struct trh_hdr *trh, struct net_device *dev)
{
unsigned int hash, rii_p = 0;
struct rif_cache_s *entry;
spin_lock_bh(&rif_lock);
/*
* Firstly see if the entry exists
*/
if(trh->saddr[0] & TR_RII)
{
trh->saddr[0]&=0x7f;
if (((ntohs(trh->rcf) & TR_RCF_LEN_MASK) >> 8) > 2)
{
rii_p = 1;
}
}
hash = rif_hash(trh->saddr);
for(entry=rif_table[hash];entry && memcmp(&(entry->addr[0]),&(trh->saddr[0]),TR_ALEN);entry=entry->next);
if(entry==NULL)
{
#if TR_SR_DEBUG
printk("adding rif_entry: addr:%02X:%02X:%02X:%02X:%02X:%02X rcf:%04X\n",
trh->saddr[0],trh->saddr[1],trh->saddr[2],
trh->saddr[3],trh->saddr[4],trh->saddr[5],
ntohs(trh->rcf));
#endif
/*
* Allocate our new entry. A failure to allocate loses
* use the information. This is harmless.
*
* FIXME: We ought to keep some kind of cache size
* limiting and adjust the timers to suit.
*/
entry=kmalloc(sizeof(struct rif_cache_s),GFP_ATOMIC);
if(!entry)
{
printk(KERN_DEBUG "tr.c: Couldn't malloc rif cache entry !\n");
spin_unlock_bh(&rif_lock);
return;
}
memcpy(&(entry->addr[0]),&(trh->saddr[0]),TR_ALEN);
entry->iface = dev->ifindex;
entry->next=rif_table[hash];
entry->last_used=jiffies;
rif_table[hash]=entry;
if (rii_p)
{
entry->rcf = trh->rcf & htons((unsigned short)~TR_RCF_BROADCAST_MASK);
memcpy(&(entry->rseg[0]),&(trh->rseg[0]),8*sizeof(unsigned short));
entry->local_ring = 0;
trh->saddr[0]|=TR_RII; /* put the routing indicator back for tcpdump */
}
else
{
entry->local_ring = 1;
}
}
else /* Y. Tahara added */
{
/*
* Update existing entries
*/
if (!entry->local_ring)
if (entry->rcf != (trh->rcf & htons((unsigned short)~TR_RCF_BROADCAST_MASK)) &&
!(trh->rcf & htons(TR_RCF_BROADCAST_MASK)))
{
#if TR_SR_DEBUG
printk("updating rif_entry: addr:%02X:%02X:%02X:%02X:%02X:%02X rcf:%04X\n",
trh->saddr[0],trh->saddr[1],trh->saddr[2],
trh->saddr[3],trh->saddr[4],trh->saddr[5],
ntohs(trh->rcf));
#endif
entry->rcf = trh->rcf & htons((unsigned short)~TR_RCF_BROADCAST_MASK);
memcpy(&(entry->rseg[0]),&(trh->rseg[0]),8*sizeof(unsigned short));
}
entry->last_used=jiffies;
}
spin_unlock_bh(&rif_lock);
}
/*
* Scan the cache with a timer and see what we need to throw out.
*/
static void rif_check_expire(unsigned long dummy)
{
int i;
unsigned long next_interval = jiffies + sysctl_tr_rif_timeout/2;
spin_lock_bh(&rif_lock);
for(i =0; i < RIF_TABLE_SIZE; i++) {
struct rif_cache_s *entry, **pentry;
pentry = rif_table+i;
while((entry=*pentry) != NULL) {
unsigned long expires
= entry->last_used + sysctl_tr_rif_timeout;
if (time_before_eq(expires, jiffies)) {
*pentry = entry->next;
kfree(entry);
} else {
pentry = &entry->next;
if (time_before(expires, next_interval))
next_interval = expires;
}
}
}
spin_unlock_bh(&rif_lock);
mod_timer(&rif_timer, next_interval);
}
/*
* Generate the /proc/net information for the token ring RIF
* routing.
*/
#ifdef CONFIG_PROC_FS
static struct rif_cache_s *rif_get_idx(loff_t pos)
{
int i;
struct rif_cache_s *entry;
loff_t off = 0;
for(i = 0; i < RIF_TABLE_SIZE; i++)
for(entry = rif_table[i]; entry; entry = entry->next) {
if (off == pos)
return entry;
++off;
}
return NULL;
}
static void *rif_seq_start(struct seq_file *seq, loff_t *pos)
{
spin_lock_bh(&rif_lock);
return *pos ? rif_get_idx(*pos - 1) : SEQ_START_TOKEN;
}
static void *rif_seq_next(struct seq_file *seq, void *v, loff_t *pos)
{
int i;
struct rif_cache_s *ent = v;
++*pos;
if (v == SEQ_START_TOKEN) {
i = -1;
goto scan;
}
if (ent->next)
return ent->next;
i = rif_hash(ent->addr);
scan:
while (++i < RIF_TABLE_SIZE) {
if ((ent = rif_table[i]) != NULL)
return ent;
}
return NULL;
}
static void rif_seq_stop(struct seq_file *seq, void *v)
{
spin_unlock_bh(&rif_lock);
}
static int rif_seq_show(struct seq_file *seq, void *v)
{
int j, rcf_len, segment, brdgnmb;
struct rif_cache_s *entry = v;
if (v == SEQ_START_TOKEN)
seq_puts(seq,
"if TR address TTL rcf routing segments\n");
else {
struct net_device *dev = dev_get_by_index(entry->iface);
long ttl = (long) (entry->last_used + sysctl_tr_rif_timeout)
- (long) jiffies;
seq_printf(seq, "%s %02X:%02X:%02X:%02X:%02X:%02X %7li ",
dev?dev->name:"?",
entry->addr[0],entry->addr[1],entry->addr[2],
entry->addr[3],entry->addr[4],entry->addr[5],
ttl/HZ);
if (entry->local_ring)
seq_puts(seq, "local\n");
else {
seq_printf(seq, "%04X", ntohs(entry->rcf));
rcf_len = ((ntohs(entry->rcf) & TR_RCF_LEN_MASK)>>8)-2;
if (rcf_len)
rcf_len >>= 1;
for(j = 1; j < rcf_len; j++) {
if(j==1) {
segment=ntohs(entry->rseg[j-1])>>4;
seq_printf(seq," %03X",segment);
};
segment=ntohs(entry->rseg[j])>>4;
brdgnmb=ntohs(entry->rseg[j-1])&0x00f;
seq_printf(seq,"-%01X-%03X",brdgnmb,segment);
}
seq_putc(seq, '\n');
}
}
return 0;
}
static struct seq_operations rif_seq_ops = {
.start = rif_seq_start,
.next = rif_seq_next,
.stop = rif_seq_stop,
.show = rif_seq_show,
};
static int rif_seq_open(struct inode *inode, struct file *file)
{
return seq_open(file, &rif_seq_ops);
}
static struct file_operations rif_seq_fops = {
.owner = THIS_MODULE,
.open = rif_seq_open,
.read = seq_read,
.llseek = seq_lseek,
.release = seq_release,
};
#endif
/*
* Called during bootup. We don't actually have to initialise
* too much for this.
*/
static int __init rif_init(void)
{
init_timer(&rif_timer);
rif_timer.expires = sysctl_tr_rif_timeout;
rif_timer.data = 0L;
rif_timer.function = rif_check_expire;
add_timer(&rif_timer);
proc_net_fops_create("tr_rif", S_IRUGO, &rif_seq_fops);
return 0;
}
module_init(rif_init);
EXPORT_SYMBOL(tr_source_route);
EXPORT_SYMBOL(tr_type_trans);
|
sarnobat/knoppix
|
net/802/tr.c
|
C
|
gpl-2.0
| 14,355 |
/* (x86-64 only)
* long sys_arch_prctl(int code, unsigned long addr)
*
* On success, arch_prctl() returns 0
* On error, -1 is returned, and errno is set to indicate the error.
*/
#if defined(__i386__) || defined (__x86_64__)
#include "sanitise.h"
#include <asm/prctl.h>
#include <sys/prctl.h>
struct syscall syscall_arch_prctl = {
.name = "arch_prctl",
.flags = AVOID_SYSCALL,
.num_args = 2,
.arg1name = "code",
.arg1type = ARG_OP,
.arg1list = {
.num = 4,
.values = { ARCH_SET_FS, ARCH_GET_FS, ARCH_SET_GS, ARCH_GET_GS },
},
.arg2name = "addr",
.arg2type = ARG_ADDRESS,
.rettype = RET_BORING,
};
#endif
|
geohot/trinity-osxnew
|
syscalls_linux/arch_prctl.c
|
C
|
gpl-2.0
| 626 |
module FeedbackHelper
def format_conference_day( day, name = nil )
if day.instance_of?( Conference_day::Row )
date = day.conference_day
name = day.name
else
date = day
end
if name
"#{name} (#{date})"
else
index = 0
@days.each_with_index do | d, i |
if d.conference_day == date
index = i + 1
break
end
end
"#{local(:day)} #{index} (#{date})"
end
end
end
|
gaudenz/pentabarf-dc13
|
rails/app/helpers/feedback_helper.rb
|
Ruby
|
gpl-2.0
| 465 |
package org.apache.bcel.generic;
/* ====================================================================
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Apache" and "Apache Software Foundation" and
* "Apache BCEL" must not be used to endorse or promote products
* derived from this software without prior written permission. For
* written permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* "Apache BCEL", nor may "Apache" appear in their name, without
* prior written permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
import org.apache.bcel.Constants;
import org.apache.bcel.classfile.*;
import java.util.StringTokenizer;
/**
* Super class for the INVOKExxx family of instructions.
*
* @version $Id: InvokeInstruction.java,v 1.1 2005/12/16 14:11:25 andos Exp $
* @author <A HREF="mailto:[email protected]">M. Dahm</A>
*/
public abstract class InvokeInstruction extends FieldOrMethod
implements ExceptionThrower, TypedInstruction, StackConsumer, StackProducer {
/**
* Empty constructor needed for the Class.newInstance() statement in
* Instruction.readInstruction(). Not to be used otherwise.
*/
InvokeInstruction() {}
/**
* @param index to constant pool
*/
protected InvokeInstruction(short opcode, int index) {
super(opcode, index);
}
/**
* @return mnemonic for instruction with symbolic references resolved
*/
public String toString(ConstantPool cp) {
Constant c = cp.getConstant(index);
StringTokenizer tok = new StringTokenizer(cp.constantToString(c));
return Constants.OPCODE_NAMES[opcode] + " " +
tok.nextToken().replace('.', '/') + tok.nextToken();
}
/**
* Also works for instructions whose stack effect depends on the
* constant pool entry they reference.
* @return Number of words consumed from stack by this instruction
*/
public int consumeStack(ConstantPoolGen cpg) {
String signature = getSignature(cpg);
Type[] args = Type.getArgumentTypes(signature);
int sum;
if(opcode == Constants.INVOKESTATIC)
sum = 0;
else
sum = 1; // this reference
int n = args.length;
for (int i = 0; i < n; i++)
sum += args[i].getSize();
return sum;
}
/**
* Also works for instructions whose stack effect depends on the
* constant pool entry they reference.
* @return Number of words produced onto stack by this instruction
*/
public int produceStack(ConstantPoolGen cpg) {
return getReturnType(cpg).getSize();
}
/** @return return type of referenced method.
*/
public Type getType(ConstantPoolGen cpg) {
return getReturnType(cpg);
}
/** @return name of referenced method.
*/
public String getMethodName(ConstantPoolGen cpg) {
return getName(cpg);
}
/** @return return type of referenced method.
*/
public Type getReturnType(ConstantPoolGen cpg) {
return Type.getReturnType(getSignature(cpg));
}
/** @return argument types of referenced method.
*/
public Type[] getArgumentTypes(ConstantPoolGen cpg) {
return Type.getArgumentTypes(getSignature(cpg));
}
}
|
Yannik/jbe
|
src/org/apache/bcel/generic/InvokeInstruction.java
|
Java
|
gpl-2.0
| 5,273 |
/*
Red Black Trees
(C) 1999 Andrea Arcangeli <[email protected]>
(C) 2002 David Woodhouse <[email protected]>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
linux/lib/rbtree.c
*/
#include <linux/rbtree.h>
#include <linux/export.h>
static void __rb_rotate_left(struct rb_node *node, struct rb_root *root)
{
struct rb_node *right = node->rb_right;
struct rb_node *parent = rb_parent(node);
if ((node->rb_right = right->rb_left))
rb_set_parent(right->rb_left, node);
right->rb_left = node;
rb_set_parent(right, parent);
if (parent)
{
if (node == parent->rb_left)
parent->rb_left = right;
else
parent->rb_right = right;
}
else
root->rb_node = right;
rb_set_parent(node, right);
}
static void __rb_rotate_right(struct rb_node *node, struct rb_root *root)
{
struct rb_node *left = node->rb_left;
struct rb_node *parent = rb_parent(node);
if ((node->rb_left = left->rb_right))
rb_set_parent(left->rb_right, node);
left->rb_right = node;
rb_set_parent(left, parent);
if (parent)
{
if (node == parent->rb_right)
parent->rb_right = left;
else
parent->rb_left = left;
}
else
root->rb_node = left;
rb_set_parent(node, left);
}
void rb_insert_color(struct rb_node *node, struct rb_root *root)
{
struct rb_node *parent, *gparent;
while ((parent = rb_parent(node)) && rb_is_red(parent))
{
gparent = rb_parent(parent);
if (parent == gparent->rb_left)
{
{
register struct rb_node *uncle = gparent->rb_right;
if (uncle && rb_is_red(uncle))
{
rb_set_black(uncle);
rb_set_black(parent);
rb_set_red(gparent);
node = gparent;
continue;
}
}
if (parent->rb_right == node)
{
register struct rb_node *tmp;
__rb_rotate_left(parent, root);
tmp = parent;
parent = node;
node = tmp;
}
rb_set_black(parent);
rb_set_red(gparent);
__rb_rotate_right(gparent, root);
} else {
{
register struct rb_node *uncle = gparent->rb_left;
if (uncle && rb_is_red(uncle))
{
rb_set_black(uncle);
rb_set_black(parent);
rb_set_red(gparent);
node = gparent;
continue;
}
}
if (parent->rb_left == node)
{
register struct rb_node *tmp;
__rb_rotate_right(parent, root);
tmp = parent;
parent = node;
node = tmp;
}
rb_set_black(parent);
rb_set_red(gparent);
__rb_rotate_left(gparent, root);
}
}
rb_set_black(root->rb_node);
}
EXPORT_SYMBOL(rb_insert_color);
static void __rb_erase_color(struct rb_node *node, struct rb_node *parent,
struct rb_root *root)
{
struct rb_node *other;
while ((!node || rb_is_black(node)) && node != root->rb_node)
{
if (parent->rb_left == node)
{
other = parent->rb_right;
if (rb_is_red(other))
{
rb_set_black(other);
rb_set_red(parent);
__rb_rotate_left(parent, root);
other = parent->rb_right;
}
if ((!other->rb_left || rb_is_black(other->rb_left)) &&
(!other->rb_right || rb_is_black(other->rb_right)))
{
rb_set_red(other);
node = parent;
parent = rb_parent(node);
}
else
{
if (!other->rb_right || rb_is_black(other->rb_right))
{
rb_set_black(other->rb_left);
rb_set_red(other);
__rb_rotate_right(other, root);
other = parent->rb_right;
}
rb_set_color(other, rb_color(parent));
rb_set_black(parent);
rb_set_black(other->rb_right);
__rb_rotate_left(parent, root);
node = root->rb_node;
break;
}
}
else
{
other = parent->rb_left;
if (rb_is_red(other))
{
rb_set_black(other);
rb_set_red(parent);
__rb_rotate_right(parent, root);
other = parent->rb_left;
}
if ((!other->rb_left || rb_is_black(other->rb_left)) &&
(!other->rb_right || rb_is_black(other->rb_right)))
{
rb_set_red(other);
node = parent;
parent = rb_parent(node);
}
else
{
if (!other->rb_left || rb_is_black(other->rb_left))
{
rb_set_black(other->rb_right);
rb_set_red(other);
__rb_rotate_left(other, root);
other = parent->rb_left;
}
rb_set_color(other, rb_color(parent));
rb_set_black(parent);
rb_set_black(other->rb_left);
__rb_rotate_right(parent, root);
node = root->rb_node;
break;
}
}
}
if (node)
rb_set_black(node);
}
void rb_erase(struct rb_node *node, struct rb_root *root)
{
struct rb_node *child, *parent;
int color;
if (!node->rb_left)
child = node->rb_right;
else if (!node->rb_right)
child = node->rb_left;
else
{
struct rb_node *old = node, *left;
node = node->rb_right;
while ((left = node->rb_left) != NULL)
node = left;
if (rb_parent(old)) {
if (rb_parent(old)->rb_left == old)
rb_parent(old)->rb_left = node;
else
rb_parent(old)->rb_right = node;
} else
root->rb_node = node;
child = node->rb_right;
parent = rb_parent(node);
color = rb_color(node);
if (parent == old) {
parent = node;
} else {
if (child)
rb_set_parent(child, parent);
parent->rb_left = child;
node->rb_right = old->rb_right;
rb_set_parent(old->rb_right, node);
}
node->rb_parent_color = old->rb_parent_color;
node->rb_left = old->rb_left;
rb_set_parent(old->rb_left, node);
goto color;
}
parent = rb_parent(node);
color = rb_color(node);
if (child)
rb_set_parent(child, parent);
if (parent)
{
if (parent->rb_left == node)
parent->rb_left = child;
else
parent->rb_right = child;
}
else
root->rb_node = child;
color:
if (color == RB_BLACK)
__rb_erase_color(child, parent, root);
}
EXPORT_SYMBOL(rb_erase);
static void rb_augment_path(struct rb_node *node, rb_augment_f func, void *data)
{
struct rb_node *parent;
up:
func(node, data);
parent = rb_parent(node);
if (!parent)
return;
if (node == parent->rb_left && parent->rb_right)
func(parent->rb_right, data);
else if (parent->rb_left)
func(parent->rb_left, data);
node = parent;
goto up;
}
/*
* after inserting @node into the tree, update the tree to account for
* both the new entry and any damage done by rebalance
*/
void rb_augment_insert(struct rb_node *node, rb_augment_f func, void *data)
{
if (node->rb_left)
node = node->rb_left;
else if (node->rb_right)
node = node->rb_right;
rb_augment_path(node, func, data);
}
EXPORT_SYMBOL(rb_augment_insert);
/*
* before removing the node, find the deepest node on the rebalance path
* that will still be there after @node gets removed
*/
struct rb_node *rb_augment_erase_begin(struct rb_node *node)
{
struct rb_node *deepest;
if (!node->rb_right && !node->rb_left)
deepest = rb_parent(node);
else if (!node->rb_right)
deepest = node->rb_left;
else if (!node->rb_left)
deepest = node->rb_right;
else {
deepest = rb_next(node);
/* */
/* Null Pointer Dereference found */
if (deepest != NULL) {
if (deepest->rb_right)
deepest = deepest->rb_right;
else if (rb_parent(deepest) != node)
deepest = rb_parent(deepest);
}
else {
WARN(1, "%s:deepst got null pointer\n", __func__);
}
/* */
}
return deepest;
}
EXPORT_SYMBOL(rb_augment_erase_begin);
/*
* after removal, update the tree to account for the removed entry
* and any rebalance damage.
*/
void rb_augment_erase_end(struct rb_node *node, rb_augment_f func, void *data)
{
if (node)
rb_augment_path(node, func, data);
}
EXPORT_SYMBOL(rb_augment_erase_end);
/*
* This function returns the first node (in sort order) of the tree.
*/
struct rb_node *rb_first(const struct rb_root *root)
{
struct rb_node *n;
n = root->rb_node;
if (!n)
return NULL;
while (n->rb_left)
n = n->rb_left;
return n;
}
EXPORT_SYMBOL(rb_first);
struct rb_node *rb_last(const struct rb_root *root)
{
struct rb_node *n;
n = root->rb_node;
if (!n)
return NULL;
while (n->rb_right)
n = n->rb_right;
return n;
}
EXPORT_SYMBOL(rb_last);
struct rb_node *rb_next(const struct rb_node *node)
{
struct rb_node *parent;
if (rb_parent(node) == node)
return NULL;
/* If we have a right-hand child, go down and then left as far
as we can. */
if (node->rb_right) {
node = node->rb_right;
while (node->rb_left)
node=node->rb_left;
return (struct rb_node *)node;
}
/* No right-hand children. Everything down and left is
smaller than us, so any 'next' node must be in the general
direction of our parent. Go up the tree; any time the
ancestor is a right-hand child of its parent, keep going
up. First time it's a left-hand child of its parent, said
parent is our 'next' node. */
while ((parent = rb_parent(node)) && node == parent->rb_right)
node = parent;
return parent;
}
EXPORT_SYMBOL(rb_next);
struct rb_node *rb_prev(const struct rb_node *node)
{
struct rb_node *parent;
if (rb_parent(node) == node)
return NULL;
/* If we have a left-hand child, go down and then right as far
as we can. */
if (node->rb_left) {
node = node->rb_left;
while (node->rb_right)
node=node->rb_right;
return (struct rb_node *)node;
}
/* No left-hand children. Go up till we find an ancestor which
is a right-hand child of its parent */
while ((parent = rb_parent(node)) && node == parent->rb_left)
node = parent;
return parent;
}
EXPORT_SYMBOL(rb_prev);
void rb_replace_node(struct rb_node *victim, struct rb_node *new,
struct rb_root *root)
{
struct rb_node *parent = rb_parent(victim);
/* Set the surrounding nodes to point to the replacement */
if (parent) {
if (victim == parent->rb_left)
parent->rb_left = new;
else
parent->rb_right = new;
} else {
root->rb_node = new;
}
if (victim->rb_left)
rb_set_parent(victim->rb_left, new);
if (victim->rb_right)
rb_set_parent(victim->rb_right, new);
/* Copy the pointers/colour from the victim to the replacement */
*new = *victim;
}
EXPORT_SYMBOL(rb_replace_node);
|
Volidol1/android_kernel_lge_d605
|
lib/rbtree.c
|
C
|
gpl-2.0
| 10,500 |
#ifndef _LINUX_MMZONE_H
#define _LINUX_MMZONE_H
#ifndef __ASSEMBLY__
#ifndef __GENERATING_BOUNDS_H
#include <linux/spinlock.h>
#include <linux/list.h>
#include <linux/wait.h>
#include <linux/bitops.h>
#include <linux/cache.h>
#include <linux/threads.h>
#include <linux/numa.h>
#include <linux/init.h>
#include <linux/seqlock.h>
#include <linux/nodemask.h>
#include <linux/pageblock-flags.h>
#include <linux/page-flags-layout.h>
#include <linux/atomic.h>
#include <asm/page.h>
/* Free memory management - zoned buddy allocator. */
#ifndef CONFIG_FORCE_MAX_ZONEORDER
#define MAX_ORDER 11
#else
#define MAX_ORDER CONFIG_FORCE_MAX_ZONEORDER
#endif
#define MAX_ORDER_NR_PAGES (1 << (MAX_ORDER - 1))
/*
* PAGE_ALLOC_COSTLY_ORDER is the order at which allocations are deemed
* costly to service. That is between allocation orders which should
* coalesce naturally under reasonable reclaim pressure and those which
* will not.
*/
#define PAGE_ALLOC_COSTLY_ORDER 3
enum {
MIGRATE_UNMOVABLE,
MIGRATE_RECLAIMABLE,
MIGRATE_MOVABLE,
MIGRATE_PCPTYPES, /* the number of types on the pcp lists */
MIGRATE_RESERVE = MIGRATE_PCPTYPES,
#ifdef CONFIG_CMA
/*
* MIGRATE_CMA migration type is designed to mimic the way
* ZONE_MOVABLE works. Only movable pages can be allocated
* from MIGRATE_CMA pageblocks and page allocator never
* implicitly change migration type of MIGRATE_CMA pageblock.
*
* The way to use it is to change migratetype of a range of
* pageblocks to MIGRATE_CMA which can be done by
* __free_pageblock_cma() function. What is important though
* is that a range of pageblocks must be aligned to
* MAX_ORDER_NR_PAGES should biggest page be bigger then
* a single pageblock.
*/
MIGRATE_CMA,
#endif
#ifdef CONFIG_MEMORY_ISOLATION
MIGRATE_ISOLATE, /* can't allocate from here */
#endif
MIGRATE_TYPES
};
/*
* Returns a list which contains the migrate types on to which
* an allocation falls back when the free list for the migrate
* type mtype is depleted.
* The end of the list is delimited by the type MIGRATE_RESERVE.
*/
extern int *get_migratetype_fallbacks(int mtype);
#ifdef CONFIG_CMA
# define is_migrate_cma(migratetype) unlikely((migratetype) == MIGRATE_CMA)
#else
# define is_migrate_cma(migratetype) false
#endif
#define for_each_migratetype_order(order, type) \
for (order = 0; order < MAX_ORDER; order++) \
for (type = 0; type < MIGRATE_TYPES; type++)
extern int page_group_by_mobility_disabled;
static inline int get_pageblock_migratetype(struct page *page)
{
return get_pageblock_flags_group(page, PB_migrate, PB_migrate_end);
}
struct free_area {
struct list_head free_list[MIGRATE_TYPES];
unsigned long nr_free;
};
struct pglist_data;
/*
* zone->lock and zone->lru_lock are two of the hottest locks in the kernel.
* So add a wild amount of padding here to ensure that they fall into separate
* cachelines. There are very few zone structures in the machine, so space
* consumption is not a concern here.
*/
#if defined(CONFIG_SMP)
struct zone_padding {
char x[0];
} ____cacheline_internodealigned_in_smp;
#define ZONE_PADDING(name) struct zone_padding name;
#else
#define ZONE_PADDING(name)
#endif
enum zone_stat_item {
/* First 128 byte cacheline (assuming 64 bit words) */
NR_FREE_PAGES,
NR_LRU_BASE,
NR_INACTIVE_ANON = NR_LRU_BASE, /* must match order of LRU_[IN]ACTIVE */
NR_ACTIVE_ANON, /* " " " " " */
NR_INACTIVE_FILE, /* " " " " " */
NR_ACTIVE_FILE, /* " " " " " */
NR_UNEVICTABLE, /* " " " " " */
NR_MLOCK, /* mlock()ed pages found and moved off LRU */
NR_ANON_PAGES, /* Mapped anonymous pages */
NR_FILE_MAPPED, /* pagecache pages mapped into pagetables.
only modified from process context */
NR_FILE_PAGES,
NR_FILE_DIRTY,
NR_WRITEBACK,
NR_SLAB_RECLAIMABLE,
NR_SLAB_UNRECLAIMABLE,
NR_PAGETABLE, /* used for pagetables */
NR_KERNEL_STACK,
/* Second 128 byte cacheline */
NR_UNSTABLE_NFS, /* NFS unstable pages */
NR_BOUNCE,
NR_VMSCAN_WRITE,
NR_VMSCAN_IMMEDIATE, /* Prioritise for reclaim when writeback ends */
NR_WRITEBACK_TEMP, /* Writeback using temporary buffers */
NR_ISOLATED_ANON, /* Temporary isolated pages from anon lru */
NR_ISOLATED_FILE, /* Temporary isolated pages from file lru */
NR_SHMEM, /* shmem pages (included tmpfs/GEM pages) */
NR_DIRTIED, /* page dirtyings since bootup */
NR_WRITTEN, /* page writings since bootup */
#ifdef CONFIG_NUMA
NUMA_HIT, /* allocated in intended node */
NUMA_MISS, /* allocated in non intended node */
NUMA_FOREIGN, /* was intended here, hit elsewhere */
NUMA_INTERLEAVE_HIT, /* interleaver preferred this zone */
NUMA_LOCAL, /* allocation from local node */
NUMA_OTHER, /* allocation from other node */
#endif
NR_ANON_TRANSPARENT_HUGEPAGES,
NR_FREE_CMA_PAGES,
NR_SWAPCACHE,
NR_VM_ZONE_STAT_ITEMS };
/*
* We do arithmetic on the LRU lists in various places in the code,
* so it is important to keep the active lists LRU_ACTIVE higher in
* the array than the corresponding inactive lists, and to keep
* the *_FILE lists LRU_FILE higher than the corresponding _ANON lists.
*
* This has to be kept in sync with the statistics in zone_stat_item
* above and the descriptions in vmstat_text in mm/vmstat.c
*/
#define LRU_BASE 0
#define LRU_ACTIVE 1
#define LRU_FILE 2
enum lru_list {
LRU_INACTIVE_ANON = LRU_BASE,
LRU_ACTIVE_ANON = LRU_BASE + LRU_ACTIVE,
LRU_INACTIVE_FILE = LRU_BASE + LRU_FILE,
LRU_ACTIVE_FILE = LRU_BASE + LRU_FILE + LRU_ACTIVE,
LRU_UNEVICTABLE,
NR_LRU_LISTS
};
#define for_each_lru(lru) for (lru = 0; lru < NR_LRU_LISTS; lru++)
#define for_each_evictable_lru(lru) for (lru = 0; lru <= LRU_ACTIVE_FILE; lru++)
static inline int is_file_lru(enum lru_list lru)
{
return (lru == LRU_INACTIVE_FILE || lru == LRU_ACTIVE_FILE);
}
static inline int is_active_lru(enum lru_list lru)
{
return (lru == LRU_ACTIVE_ANON || lru == LRU_ACTIVE_FILE);
}
static inline int is_unevictable_lru(enum lru_list lru)
{
return (lru == LRU_UNEVICTABLE);
}
struct zone_reclaim_stat {
/*
* The pageout code in vmscan.c keeps track of how many of the
* mem/swap backed and file backed pages are referenced.
* The higher the rotated/scanned ratio, the more valuable
* that cache is.
*
* The anon LRU stats live in [0], file LRU stats in [1]
*/
unsigned long recent_rotated[2];
unsigned long recent_scanned[2];
};
struct lruvec {
struct list_head lists[NR_LRU_LISTS];
struct zone_reclaim_stat reclaim_stat;
#ifdef CONFIG_MEMCG
struct zone *zone;
#endif
};
/* Mask used at gathering information at once (see memcontrol.c) */
#define LRU_ALL_FILE (BIT(LRU_INACTIVE_FILE) | BIT(LRU_ACTIVE_FILE))
#define LRU_ALL_ANON (BIT(LRU_INACTIVE_ANON) | BIT(LRU_ACTIVE_ANON))
#define LRU_ALL ((1 << NR_LRU_LISTS) - 1)
/* Isolate clean file */
#define ISOLATE_CLEAN ((__force isolate_mode_t)0x1)
/* Isolate unmapped file */
#define ISOLATE_UNMAPPED ((__force isolate_mode_t)0x2)
/* Isolate for asynchronous migration */
#define ISOLATE_ASYNC_MIGRATE ((__force isolate_mode_t)0x4)
/* Isolate unevictable pages */
#define ISOLATE_UNEVICTABLE ((__force isolate_mode_t)0x8)
/* LRU Isolation modes. */
typedef unsigned __bitwise__ isolate_mode_t;
enum zone_watermarks {
WMARK_MIN,
WMARK_LOW,
WMARK_HIGH,
NR_WMARK
};
#define min_wmark_pages(z) (z->watermark[WMARK_MIN])
#define low_wmark_pages(z) (z->watermark[WMARK_LOW])
#define high_wmark_pages(z) (z->watermark[WMARK_HIGH])
struct per_cpu_pages {
int count; /* number of pages in the list */
int high; /* high watermark, emptying needed */
int batch; /* chunk size for buddy add/remove */
/* Lists of pages, one per migrate type stored on the pcp-lists */
struct list_head lists[MIGRATE_PCPTYPES];
};
struct per_cpu_pageset {
struct per_cpu_pages pcp;
#ifdef CONFIG_NUMA
s8 expire;
#endif
#ifdef CONFIG_SMP
s8 stat_threshold;
s8 vm_stat_diff[NR_VM_ZONE_STAT_ITEMS];
#endif
};
#endif /* !__GENERATING_BOUNDS.H */
enum zone_type {
#ifdef CONFIG_ZONE_DMA
/*
* ZONE_DMA is used when there are devices that are not able
* to do DMA to all of addressable memory (ZONE_NORMAL). Then we
* carve out the portion of memory that is needed for these devices.
* The range is arch specific.
*
* Some examples
*
* Architecture Limit
* ---------------------------
* parisc, ia64, sparc <4G
* s390 <2G
* arm Various
* alpha Unlimited or 0-16MB.
*
* i386, x86_64 and multiple other arches
* <16M.
*/
ZONE_DMA,
#endif
#ifdef CONFIG_ZONE_DMA32
/*
* x86_64 needs two ZONE_DMAs because it supports devices that are
* only able to do DMA to the lower 16M but also 32 bit devices that
* can only do DMA areas below 4G.
*/
ZONE_DMA32,
#endif
/*
* Normal addressable memory is in ZONE_NORMAL. DMA operations can be
* performed on pages in ZONE_NORMAL if the DMA devices support
* transfers to all addressable memory.
*/
ZONE_NORMAL,
#ifdef CONFIG_HIGHMEM
/*
* A memory area that is only addressable by the kernel through
* mapping portions into its own address space. This is for example
* used by i386 to allow the kernel to address the memory beyond
* 900MB. The kernel will set up special mappings (page
* table entries on i386) for each page that the kernel needs to
* access.
*/
ZONE_HIGHMEM,
#endif
ZONE_MOVABLE,
__MAX_NR_ZONES
};
#ifndef __GENERATING_BOUNDS_H
struct zone {
/* Fields commonly accessed by the page allocator */
/* zone watermarks, access with *_wmark_pages(zone) macros */
unsigned long watermark[NR_WMARK];
/*
* When free pages are below this point, additional steps are taken
* when reading the number of free pages to avoid per-cpu counter
* drift allowing watermarks to be breached
*/
unsigned long percpu_drift_mark;
/*
* We don't know if the memory that we're going to allocate will be freeable
* or/and it will be released eventually, so to avoid totally wasting several
* GB of ram we must reserve some of the lower zone memory (otherwise we risk
* to run OOM on the lower zones despite there's tons of freeable ram
* on the higher zones). This array is recalculated at runtime if the
* sysctl_lowmem_reserve_ratio sysctl changes.
*/
unsigned long lowmem_reserve[MAX_NR_ZONES];
/*
* This is a per-zone reserve of pages that should not be
* considered dirtyable memory.
*/
unsigned long dirty_balance_reserve;
#ifdef CONFIG_NUMA
int node;
/*
* zone reclaim becomes active if more unmapped pages exist.
*/
unsigned long min_unmapped_pages;
unsigned long min_slab_pages;
#endif
struct per_cpu_pageset __percpu *pageset;
/*
* free areas of different sizes
*/
spinlock_t lock;
int all_unreclaimable; /* All pages pinned */
#if defined CONFIG_COMPACTION || defined CONFIG_CMA
/* Set to true when the PG_migrate_skip bits should be cleared */
bool compact_blockskip_flush;
/* pfns where compaction scanners should start */
unsigned long compact_cached_free_pfn;
unsigned long compact_cached_migrate_pfn;
#endif
#ifdef CONFIG_MEMORY_HOTPLUG
/* see spanned/present_pages for more description */
seqlock_t span_seqlock;
#endif
struct free_area free_area[MAX_ORDER];
#ifndef CONFIG_SPARSEMEM
/*
* Flags for a pageblock_nr_pages block. See pageblock-flags.h.
* In SPARSEMEM, this map is stored in struct mem_section
*/
unsigned long *pageblock_flags;
#endif /* CONFIG_SPARSEMEM */
#ifdef CONFIG_COMPACTION
/*
* On compaction failure, 1<<compact_defer_shift compactions
* are skipped before trying again. The number attempted since
* last failure is tracked with compact_considered.
*/
unsigned int compact_considered;
unsigned int compact_defer_shift;
int compact_order_failed;
#endif
ZONE_PADDING(_pad1_)
/* Fields commonly accessed by the page reclaim scanner */
spinlock_t lru_lock;
struct lruvec lruvec;
unsigned long pages_scanned; /* since last reclaim */
unsigned long flags; /* zone flags, see below */
/* Zone statistics */
atomic_long_t vm_stat[NR_VM_ZONE_STAT_ITEMS];
/*
* The target ratio of ACTIVE_ANON to INACTIVE_ANON pages on
* this zone's LRU. Maintained by the pageout code.
*/
unsigned int inactive_ratio;
ZONE_PADDING(_pad2_)
/* Rarely used or read-mostly fields */
/*
* wait_table -- the array holding the hash table
* wait_table_hash_nr_entries -- the size of the hash table array
* wait_table_bits -- wait_table_size == (1 << wait_table_bits)
*
* The purpose of all these is to keep track of the people
* waiting for a page to become available and make them
* runnable again when possible. The trouble is that this
* consumes a lot of space, especially when so few things
* wait on pages at a given time. So instead of using
* per-page waitqueues, we use a waitqueue hash table.
*
* The bucket discipline is to sleep on the same queue when
* colliding and wake all in that wait queue when removing.
* When something wakes, it must check to be sure its page is
* truly available, a la thundering herd. The cost of a
* collision is great, but given the expected load of the
* table, they should be so rare as to be outweighed by the
* benefits from the saved space.
*
* __wait_on_page_locked() and unlock_page() in mm/filemap.c, are the
* primary users of these fields, and in mm/page_alloc.c
* free_area_init_core() performs the initialization of them.
*/
wait_queue_head_t * wait_table;
unsigned long wait_table_hash_nr_entries;
unsigned long wait_table_bits;
/*
* Discontig memory support fields.
*/
struct pglist_data *zone_pgdat;
/* zone_start_pfn == zone_start_paddr >> PAGE_SHIFT */
unsigned long zone_start_pfn;
/*
* spanned_pages is the total pages spanned by the zone, including
* holes, which is calculated as:
* spanned_pages = zone_end_pfn - zone_start_pfn;
*
* present_pages is physical pages existing within the zone, which
* is calculated as:
* present_pages = spanned_pages - absent_pages(pages in holes);
*
* managed_pages is present pages managed by the buddy system, which
* is calculated as (reserved_pages includes pages allocated by the
* bootmem allocator):
* managed_pages = present_pages - reserved_pages;
*
* So present_pages may be used by memory hotplug or memory power
* management logic to figure out unmanaged pages by checking
* (present_pages - managed_pages). And managed_pages should be used
* by page allocator and vm scanner to calculate all kinds of watermarks
* and thresholds.
*
* Locking rules:
*
* zone_start_pfn and spanned_pages are protected by span_seqlock.
* It is a seqlock because it has to be read outside of zone->lock,
* and it is done in the main allocator path. But, it is written
* quite infrequently.
*
* The span_seq lock is declared along with zone->lock because it is
* frequently read in proximity to zone->lock. It's good to
* give them a chance of being in the same cacheline.
*
* Write access to present_pages and managed_pages at runtime should
* be protected by lock_memory_hotplug()/unlock_memory_hotplug().
* Any reader who can't tolerant drift of present_pages and
* managed_pages should hold memory hotplug lock to get a stable value.
*/
unsigned long spanned_pages;
unsigned long present_pages;
unsigned long managed_pages;
/*
* rarely used fields:
*/
const char *name;
} ____cacheline_internodealigned_in_smp;
typedef enum {
ZONE_RECLAIM_LOCKED, /* prevents concurrent reclaim */
ZONE_OOM_LOCKED, /* zone is in OOM killer zonelist */
ZONE_CONGESTED, /* zone has many dirty pages backed by
* a congested BDI
*/
} zone_flags_t;
static inline void zone_set_flag(struct zone *zone, zone_flags_t flag)
{
set_bit(flag, &zone->flags);
}
static inline int zone_test_and_set_flag(struct zone *zone, zone_flags_t flag)
{
return test_and_set_bit(flag, &zone->flags);
}
static inline void zone_clear_flag(struct zone *zone, zone_flags_t flag)
{
clear_bit(flag, &zone->flags);
}
static inline int zone_is_reclaim_congested(const struct zone *zone)
{
return test_bit(ZONE_CONGESTED, &zone->flags);
}
static inline int zone_is_reclaim_locked(const struct zone *zone)
{
return test_bit(ZONE_RECLAIM_LOCKED, &zone->flags);
}
static inline int zone_is_oom_locked(const struct zone *zone)
{
return test_bit(ZONE_OOM_LOCKED, &zone->flags);
}
static inline unsigned long zone_end_pfn(const struct zone *zone)
{
return zone->zone_start_pfn + zone->spanned_pages;
}
static inline bool zone_spans_pfn(const struct zone *zone, unsigned long pfn)
{
return zone->zone_start_pfn <= pfn && pfn < zone_end_pfn(zone);
}
static inline bool zone_is_initialized(struct zone *zone)
{
return !!zone->wait_table;
}
static inline bool zone_is_empty(struct zone *zone)
{
return zone->spanned_pages == 0;
}
/*
* The "priority" of VM scanning is how much of the queues we will scan in one
* go. A value of 12 for DEF_PRIORITY implies that we will scan 1/4096th of the
* queues ("queue_length >> 12") during an aging round.
*/
#define DEF_PRIORITY 12
/* Maximum number of zones on a zonelist */
#define MAX_ZONES_PER_ZONELIST (MAX_NUMNODES * MAX_NR_ZONES)
#ifdef CONFIG_NUMA
/*
* The NUMA zonelists are doubled because we need zonelists that restrict the
* allocations to a single node for GFP_THISNODE.
*
* [0] : Zonelist with fallback
* [1] : No fallback (GFP_THISNODE)
*/
#define MAX_ZONELISTS 2
/*
* We cache key information from each zonelist for smaller cache
* footprint when scanning for free pages in get_page_from_freelist().
*
* 1) The BITMAP fullzones tracks which zones in a zonelist have come
* up short of free memory since the last time (last_fullzone_zap)
* we zero'd fullzones.
* 2) The array z_to_n[] maps each zone in the zonelist to its node
* id, so that we can efficiently evaluate whether that node is
* set in the current tasks mems_allowed.
*
* Both fullzones and z_to_n[] are one-to-one with the zonelist,
* indexed by a zones offset in the zonelist zones[] array.
*
* The get_page_from_freelist() routine does two scans. During the
* first scan, we skip zones whose corresponding bit in 'fullzones'
* is set or whose corresponding node in current->mems_allowed (which
* comes from cpusets) is not set. During the second scan, we bypass
* this zonelist_cache, to ensure we look methodically at each zone.
*
* Once per second, we zero out (zap) fullzones, forcing us to
* reconsider nodes that might have regained more free memory.
* The field last_full_zap is the time we last zapped fullzones.
*
* This mechanism reduces the amount of time we waste repeatedly
* reexaming zones for free memory when they just came up low on
* memory momentarilly ago.
*
* The zonelist_cache struct members logically belong in struct
* zonelist. However, the mempolicy zonelists constructed for
* MPOL_BIND are intentionally variable length (and usually much
* shorter). A general purpose mechanism for handling structs with
* multiple variable length members is more mechanism than we want
* here. We resort to some special case hackery instead.
*
* The MPOL_BIND zonelists don't need this zonelist_cache (in good
* part because they are shorter), so we put the fixed length stuff
* at the front of the zonelist struct, ending in a variable length
* zones[], as is needed by MPOL_BIND.
*
* Then we put the optional zonelist cache on the end of the zonelist
* struct. This optional stuff is found by a 'zlcache_ptr' pointer in
* the fixed length portion at the front of the struct. This pointer
* both enables us to find the zonelist cache, and in the case of
* MPOL_BIND zonelists, (which will just set the zlcache_ptr to NULL)
* to know that the zonelist cache is not there.
*
* The end result is that struct zonelists come in two flavors:
* 1) The full, fixed length version, shown below, and
* 2) The custom zonelists for MPOL_BIND.
* The custom MPOL_BIND zonelists have a NULL zlcache_ptr and no zlcache.
*
* Even though there may be multiple CPU cores on a node modifying
* fullzones or last_full_zap in the same zonelist_cache at the same
* time, we don't lock it. This is just hint data - if it is wrong now
* and then, the allocator will still function, perhaps a bit slower.
*/
struct zonelist_cache {
unsigned short z_to_n[MAX_ZONES_PER_ZONELIST]; /* zone->nid */
DECLARE_BITMAP(fullzones, MAX_ZONES_PER_ZONELIST); /* zone full? */
unsigned long last_full_zap; /* when last zap'd (jiffies) */
};
#else
#define MAX_ZONELISTS 1
struct zonelist_cache;
#endif
/*
* This struct contains information about a zone in a zonelist. It is stored
* here to avoid dereferences into large structures and lookups of tables
*/
struct zoneref {
struct zone *zone; /* Pointer to actual zone */
int zone_idx; /* zone_idx(zoneref->zone) */
};
/*
* One allocation request operates on a zonelist. A zonelist
* is a list of zones, the first one is the 'goal' of the
* allocation, the other zones are fallback zones, in decreasing
* priority.
*
* If zlcache_ptr is not NULL, then it is just the address of zlcache,
* as explained above. If zlcache_ptr is NULL, there is no zlcache.
* *
* To speed the reading of the zonelist, the zonerefs contain the zone index
* of the entry being read. Helper functions to access information given
* a struct zoneref are
*
* zonelist_zone() - Return the struct zone * for an entry in _zonerefs
* zonelist_zone_idx() - Return the index of the zone for an entry
* zonelist_node_idx() - Return the index of the node for an entry
*/
struct zonelist {
struct zonelist_cache *zlcache_ptr; // NULL or &zlcache
struct zoneref _zonerefs[MAX_ZONES_PER_ZONELIST + 1];
#ifdef CONFIG_NUMA
struct zonelist_cache zlcache; // optional ...
#endif
};
#ifdef CONFIG_HAVE_MEMBLOCK_NODE_MAP
struct node_active_region {
unsigned long start_pfn;
unsigned long end_pfn;
int nid;
};
#endif /* CONFIG_HAVE_MEMBLOCK_NODE_MAP */
#ifndef CONFIG_DISCONTIGMEM
/* The array of struct pages - for discontigmem use pgdat->lmem_map */
extern struct page *mem_map;
#endif
/*
* The pg_data_t structure is used in machines with CONFIG_DISCONTIGMEM
* (mostly NUMA machines?) to denote a higher-level memory zone than the
* zone denotes.
*
* On NUMA machines, each NUMA node would have a pg_data_t to describe
* it's memory layout.
*
* Memory statistics and page replacement data structures are maintained on a
* per-zone basis.
*/
struct bootmem_data;
typedef struct pglist_data {
struct zone node_zones[MAX_NR_ZONES];
struct zonelist node_zonelists[MAX_ZONELISTS];
int nr_zones;
#ifdef CONFIG_FLAT_NODE_MEM_MAP /* means !SPARSEMEM */
struct page *node_mem_map;
#ifdef CONFIG_MEMCG
struct page_cgroup *node_page_cgroup;
#endif
#endif
#ifndef CONFIG_NO_BOOTMEM
struct bootmem_data *bdata;
#endif
#ifdef CONFIG_MEMORY_HOTPLUG
/*
* Must be held any time you expect node_start_pfn, node_present_pages
* or node_spanned_pages stay constant. Holding this will also
* guarantee that any pfn_valid() stays that way.
*
* Nests above zone->lock and zone->size_seqlock.
*/
spinlock_t node_size_lock;
#endif
unsigned long node_start_pfn;
unsigned long node_present_pages; /* total number of physical pages */
unsigned long node_spanned_pages; /* total size of physical page
range, including holes */
int node_id;
nodemask_t reclaim_nodes; /* Nodes allowed to reclaim from */
wait_queue_head_t kswapd_wait;
wait_queue_head_t pfmemalloc_wait;
struct task_struct *kswapd; /* Protected by lock_memory_hotplug() */
int kswapd_max_order;
enum zone_type classzone_idx;
#ifdef CONFIG_NUMA_BALANCING
/*
* Lock serializing the per destination node AutoNUMA memory
* migration rate limiting data.
*/
spinlock_t numabalancing_migrate_lock;
/* Rate limiting time interval */
unsigned long numabalancing_migrate_next_window;
/* Number of pages migrated during the rate limiting time interval */
unsigned long numabalancing_migrate_nr_pages;
#endif
} pg_data_t;
#define node_present_pages(nid) (NODE_DATA(nid)->node_present_pages)
#define node_spanned_pages(nid) (NODE_DATA(nid)->node_spanned_pages)
#ifdef CONFIG_FLAT_NODE_MEM_MAP
#define pgdat_page_nr(pgdat, pagenr) ((pgdat)->node_mem_map + (pagenr))
#else
#define pgdat_page_nr(pgdat, pagenr) pfn_to_page((pgdat)->node_start_pfn + (pagenr))
#endif
#define nid_page_nr(nid, pagenr) pgdat_page_nr(NODE_DATA(nid),(pagenr))
#define node_start_pfn(nid) (NODE_DATA(nid)->node_start_pfn)
#define node_end_pfn(nid) pgdat_end_pfn(NODE_DATA(nid))
static inline unsigned long pgdat_end_pfn(pg_data_t *pgdat)
{
return pgdat->node_start_pfn + pgdat->node_spanned_pages;
}
static inline bool pgdat_is_empty(pg_data_t *pgdat)
{
return !pgdat->node_start_pfn && !pgdat->node_spanned_pages;
}
#include <linux/memory_hotplug.h>
extern struct mutex zonelists_mutex;
void build_all_zonelists(pg_data_t *pgdat, struct zone *zone);
void wakeup_kswapd(struct zone *zone, int order, enum zone_type classzone_idx);
bool zone_watermark_ok(struct zone *z, int order, unsigned long mark,
int classzone_idx, int alloc_flags);
bool zone_watermark_ok_safe(struct zone *z, int order, unsigned long mark,
int classzone_idx, int alloc_flags);
enum memmap_context {
MEMMAP_EARLY,
MEMMAP_HOTPLUG,
};
extern int init_currently_empty_zone(struct zone *zone, unsigned long start_pfn,
unsigned long size,
enum memmap_context context);
extern void lruvec_init(struct lruvec *lruvec);
static inline struct zone *lruvec_zone(struct lruvec *lruvec)
{
#ifdef CONFIG_MEMCG
return lruvec->zone;
#else
return container_of(lruvec, struct zone, lruvec);
#endif
}
#ifdef CONFIG_HAVE_MEMORY_PRESENT
void memory_present(int nid, unsigned long start, unsigned long end);
#else
static inline void memory_present(int nid, unsigned long start, unsigned long end) {}
#endif
#ifdef CONFIG_HAVE_MEMORYLESS_NODES
int local_memory_node(int node_id);
#else
static inline int local_memory_node(int node_id) { return node_id; };
#endif
#ifdef CONFIG_NEED_NODE_MEMMAP_SIZE
unsigned long __init node_memmap_size_bytes(int, unsigned long, unsigned long);
#endif
/*
* zone_idx() returns 0 for the ZONE_DMA zone, 1 for the ZONE_NORMAL zone, etc.
*/
#define zone_idx(zone) ((zone) - (zone)->zone_pgdat->node_zones)
static inline int populated_zone(struct zone *zone)
{
return (!!zone->present_pages);
}
extern int movable_zone;
static inline int zone_movable_is_highmem(void)
{
#if defined(CONFIG_HIGHMEM) && defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
return movable_zone == ZONE_HIGHMEM;
#else
return 0;
#endif
}
static inline int is_highmem_idx(enum zone_type idx)
{
#ifdef CONFIG_HIGHMEM
return (idx == ZONE_HIGHMEM ||
(idx == ZONE_MOVABLE && zone_movable_is_highmem()));
#else
return 0;
#endif
}
static inline int is_normal_idx(enum zone_type idx)
{
return (idx == ZONE_NORMAL);
}
/**
* is_highmem - helper function to quickly check if a struct zone is a
* highmem zone or not. This is an attempt to keep references
* to ZONE_{DMA/NORMAL/HIGHMEM/etc} in general code to a minimum.
* @zone - pointer to struct zone variable
*/
static inline int is_highmem(struct zone *zone)
{
#ifdef CONFIG_HIGHMEM
int zone_off = (char *)zone - (char *)zone->zone_pgdat->node_zones;
return zone_off == ZONE_HIGHMEM * sizeof(*zone) ||
(zone_off == ZONE_MOVABLE * sizeof(*zone) &&
zone_movable_is_highmem());
#else
return 0;
#endif
}
static inline int is_normal(struct zone *zone)
{
return zone == zone->zone_pgdat->node_zones + ZONE_NORMAL;
}
static inline int is_dma32(struct zone *zone)
{
#ifdef CONFIG_ZONE_DMA32
return zone == zone->zone_pgdat->node_zones + ZONE_DMA32;
#else
return 0;
#endif
}
static inline int is_dma(struct zone *zone)
{
#ifdef CONFIG_ZONE_DMA
return zone == zone->zone_pgdat->node_zones + ZONE_DMA;
#else
return 0;
#endif
}
/* These two functions are used to setup the per zone pages min values */
struct ctl_table;
int min_free_kbytes_sysctl_handler(struct ctl_table *, int,
void __user *, size_t *, loff_t *);
extern int sysctl_lowmem_reserve_ratio[MAX_NR_ZONES-1];
int lowmem_reserve_ratio_sysctl_handler(struct ctl_table *, int,
void __user *, size_t *, loff_t *);
int percpu_pagelist_fraction_sysctl_handler(struct ctl_table *, int,
void __user *, size_t *, loff_t *);
int sysctl_min_unmapped_ratio_sysctl_handler(struct ctl_table *, int,
void __user *, size_t *, loff_t *);
int sysctl_min_slab_ratio_sysctl_handler(struct ctl_table *, int,
void __user *, size_t *, loff_t *);
extern int numa_zonelist_order_handler(struct ctl_table *, int,
void __user *, size_t *, loff_t *);
extern char numa_zonelist_order[];
#define NUMA_ZONELIST_ORDER_LEN 16 /* string buffer size */
#ifndef CONFIG_NEED_MULTIPLE_NODES
extern struct pglist_data contig_page_data;
#define NODE_DATA(nid) (&contig_page_data)
#define NODE_MEM_MAP(nid) mem_map
#else /* CONFIG_NEED_MULTIPLE_NODES */
#include <asm/mmzone.h>
#endif /* !CONFIG_NEED_MULTIPLE_NODES */
extern struct pglist_data *first_online_pgdat(void);
extern struct pglist_data *next_online_pgdat(struct pglist_data *pgdat);
extern struct zone *next_zone(struct zone *zone);
/**
* for_each_online_pgdat - helper macro to iterate over all online nodes
* @pgdat - pointer to a pg_data_t variable
*/
#define for_each_online_pgdat(pgdat) \
for (pgdat = first_online_pgdat(); \
pgdat; \
pgdat = next_online_pgdat(pgdat))
/**
* for_each_zone - helper macro to iterate over all memory zones
* @zone - pointer to struct zone variable
*
* The user only needs to declare the zone variable, for_each_zone
* fills it in.
*/
#define for_each_zone(zone) \
for (zone = (first_online_pgdat())->node_zones; \
zone; \
zone = next_zone(zone))
#define for_each_populated_zone(zone) \
for (zone = (first_online_pgdat())->node_zones; \
zone; \
zone = next_zone(zone)) \
if (!populated_zone(zone)) \
; /* do nothing */ \
else
static inline struct zone *zonelist_zone(struct zoneref *zoneref)
{
return zoneref->zone;
}
static inline int zonelist_zone_idx(struct zoneref *zoneref)
{
return zoneref->zone_idx;
}
static inline int zonelist_node_idx(struct zoneref *zoneref)
{
#ifdef CONFIG_NUMA
/* zone_to_nid not available in this context */
return zoneref->zone->node;
#else
return 0;
#endif /* CONFIG_NUMA */
}
/**
* next_zones_zonelist - Returns the next zone at or below highest_zoneidx within the allowed nodemask using a cursor within a zonelist as a starting point
* @z - The cursor used as a starting point for the search
* @highest_zoneidx - The zone index of the highest zone to return
* @nodes - An optional nodemask to filter the zonelist with
* @zone - The first suitable zone found is returned via this parameter
*
* This function returns the next zone at or below a given zone index that is
* within the allowed nodemask using a cursor as the starting point for the
* search. The zoneref returned is a cursor that represents the current zone
* being examined. It should be advanced by one before calling
* next_zones_zonelist again.
*/
struct zoneref *next_zones_zonelist(struct zoneref *z,
enum zone_type highest_zoneidx,
nodemask_t *nodes,
struct zone **zone);
/**
* first_zones_zonelist - Returns the first zone at or below highest_zoneidx within the allowed nodemask in a zonelist
* @zonelist - The zonelist to search for a suitable zone
* @highest_zoneidx - The zone index of the highest zone to return
* @nodes - An optional nodemask to filter the zonelist with
* @zone - The first suitable zone found is returned via this parameter
*
* This function returns the first zone at or below a given zone index that is
* within the allowed nodemask. The zoneref returned is a cursor that can be
* used to iterate the zonelist with next_zones_zonelist by advancing it by
* one before calling.
*/
static inline struct zoneref *first_zones_zonelist(struct zonelist *zonelist,
enum zone_type highest_zoneidx,
nodemask_t *nodes,
struct zone **zone)
{
return next_zones_zonelist(zonelist->_zonerefs, highest_zoneidx, nodes,
zone);
}
/**
* for_each_zone_zonelist_nodemask - helper macro to iterate over valid zones in a zonelist at or below a given zone index and within a nodemask
* @zone - The current zone in the iterator
* @z - The current pointer within zonelist->zones being iterated
* @zlist - The zonelist being iterated
* @highidx - The zone index of the highest zone to return
* @nodemask - Nodemask allowed by the allocator
*
* This iterator iterates though all zones at or below a given zone index and
* within a given nodemask
*/
#define for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, nodemask) \
for (z = first_zones_zonelist(zlist, highidx, nodemask, &zone); \
zone; \
z = next_zones_zonelist(++z, highidx, nodemask, &zone)) \
/**
* for_each_zone_zonelist - helper macro to iterate over valid zones in a zonelist at or below a given zone index
* @zone - The current zone in the iterator
* @z - The current pointer within zonelist->zones being iterated
* @zlist - The zonelist being iterated
* @highidx - The zone index of the highest zone to return
*
* This iterator iterates though all zones at or below a given zone index.
*/
#define for_each_zone_zonelist(zone, z, zlist, highidx) \
for_each_zone_zonelist_nodemask(zone, z, zlist, highidx, NULL)
#ifdef CONFIG_SPARSEMEM
#include <asm/sparsemem.h>
#endif
#if !defined(CONFIG_HAVE_ARCH_EARLY_PFN_TO_NID) && \
!defined(CONFIG_HAVE_MEMBLOCK_NODE_MAP)
static inline unsigned long early_pfn_to_nid(unsigned long pfn)
{
return 0;
}
#endif
#ifdef CONFIG_FLATMEM
#define pfn_to_nid(pfn) (0)
#endif
#ifdef CONFIG_SPARSEMEM
/*
* SECTION_SHIFT #bits space required to store a section #
*
* PA_SECTION_SHIFT physical address to/from section number
* PFN_SECTION_SHIFT pfn to/from section number
*/
#define PA_SECTION_SHIFT (SECTION_SIZE_BITS)
#define PFN_SECTION_SHIFT (SECTION_SIZE_BITS - PAGE_SHIFT)
#define NR_MEM_SECTIONS (1UL << SECTIONS_SHIFT)
#define PAGES_PER_SECTION (1UL << PFN_SECTION_SHIFT)
#define PAGE_SECTION_MASK (~(PAGES_PER_SECTION-1))
#define SECTION_BLOCKFLAGS_BITS \
((1UL << (PFN_SECTION_SHIFT - pageblock_order)) * NR_PAGEBLOCK_BITS)
#if (MAX_ORDER - 1 + PAGE_SHIFT) > SECTION_SIZE_BITS
#error Allocator MAX_ORDER exceeds SECTION_SIZE
#endif
#define pfn_to_section_nr(pfn) ((pfn) >> PFN_SECTION_SHIFT)
#define section_nr_to_pfn(sec) ((sec) << PFN_SECTION_SHIFT)
#define SECTION_ALIGN_UP(pfn) (((pfn) + PAGES_PER_SECTION - 1) & PAGE_SECTION_MASK)
#define SECTION_ALIGN_DOWN(pfn) ((pfn) & PAGE_SECTION_MASK)
struct page;
struct page_cgroup;
struct mem_section {
/*
* This is, logically, a pointer to an array of struct
* pages. However, it is stored with some other magic.
* (see sparse.c::sparse_init_one_section())
*
* Additionally during early boot we encode node id of
* the location of the section here to guide allocation.
* (see sparse.c::memory_present())
*
* Making it a UL at least makes someone do a cast
* before using it wrong.
*/
unsigned long section_mem_map;
/* See declaration of similar field in struct zone */
unsigned long *pageblock_flags;
#ifdef CONFIG_MEMCG
/*
* If !SPARSEMEM, pgdat doesn't have page_cgroup pointer. We use
* section. (see memcontrol.h/page_cgroup.h about this.)
*/
struct page_cgroup *page_cgroup;
unsigned long pad;
#endif
};
#ifdef CONFIG_SPARSEMEM_EXTREME
#define SECTIONS_PER_ROOT (PAGE_SIZE / sizeof (struct mem_section))
#else
#define SECTIONS_PER_ROOT 1
#endif
#define SECTION_NR_TO_ROOT(sec) ((sec) / SECTIONS_PER_ROOT)
#define NR_SECTION_ROOTS DIV_ROUND_UP(NR_MEM_SECTIONS, SECTIONS_PER_ROOT)
#define SECTION_ROOT_MASK (SECTIONS_PER_ROOT - 1)
#ifdef CONFIG_SPARSEMEM_EXTREME
extern struct mem_section *mem_section[NR_SECTION_ROOTS];
#else
extern struct mem_section mem_section[NR_SECTION_ROOTS][SECTIONS_PER_ROOT];
#endif
static inline struct mem_section *__nr_to_section(unsigned long nr)
{
if (!mem_section[SECTION_NR_TO_ROOT(nr)])
return NULL;
return &mem_section[SECTION_NR_TO_ROOT(nr)][nr & SECTION_ROOT_MASK];
}
extern int __section_nr(struct mem_section* ms);
extern unsigned long usemap_size(void);
/*
* We use the lower bits of the mem_map pointer to store
* a little bit of information. There should be at least
* 3 bits here due to 32-bit alignment.
*/
#define SECTION_MARKED_PRESENT (1UL<<0)
#define SECTION_HAS_MEM_MAP (1UL<<1)
#define SECTION_MAP_LAST_BIT (1UL<<2)
#define SECTION_MAP_MASK (~(SECTION_MAP_LAST_BIT-1))
#define SECTION_NID_SHIFT 2
static inline struct page *__section_mem_map_addr(struct mem_section *section)
{
unsigned long map = section->section_mem_map;
map &= SECTION_MAP_MASK;
return (struct page *)map;
}
static inline int present_section(struct mem_section *section)
{
return (section && (section->section_mem_map & SECTION_MARKED_PRESENT));
}
static inline int present_section_nr(unsigned long nr)
{
return present_section(__nr_to_section(nr));
}
static inline int valid_section(struct mem_section *section)
{
return (section && (section->section_mem_map & SECTION_HAS_MEM_MAP));
}
static inline int valid_section_nr(unsigned long nr)
{
return valid_section(__nr_to_section(nr));
}
static inline struct mem_section *__pfn_to_section(unsigned long pfn)
{
return __nr_to_section(pfn_to_section_nr(pfn));
}
#ifndef CONFIG_HAVE_ARCH_PFN_VALID
static inline int pfn_valid(unsigned long pfn)
{
if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
return 0;
return valid_section(__nr_to_section(pfn_to_section_nr(pfn)));
}
#endif
static inline int pfn_present(unsigned long pfn)
{
if (pfn_to_section_nr(pfn) >= NR_MEM_SECTIONS)
return 0;
return present_section(__nr_to_section(pfn_to_section_nr(pfn)));
}
/*
* These are _only_ used during initialisation, therefore they
* can use __initdata ... They could have names to indicate
* this restriction.
*/
#ifdef CONFIG_NUMA
#define pfn_to_nid(pfn) \
({ \
unsigned long __pfn_to_nid_pfn = (pfn); \
page_to_nid(pfn_to_page(__pfn_to_nid_pfn)); \
})
#else
#define pfn_to_nid(pfn) (0)
#endif
#define early_pfn_valid(pfn) pfn_valid(pfn)
void sparse_init(void);
#else
#define sparse_init() do {} while (0)
#define sparse_index_init(_sec, _nid) do {} while (0)
#endif /* CONFIG_SPARSEMEM */
#ifdef CONFIG_NODES_SPAN_OTHER_NODES
bool early_pfn_in_nid(unsigned long pfn, int nid);
#else
#define early_pfn_in_nid(pfn, nid) (1)
#endif
#ifndef early_pfn_valid
#define early_pfn_valid(pfn) (1)
#endif
void memory_present(int nid, unsigned long start, unsigned long end);
unsigned long __init node_memmap_size_bytes(int, unsigned long, unsigned long);
/*
* If it is possible to have holes within a MAX_ORDER_NR_PAGES, then we
* need to check pfn validility within that MAX_ORDER_NR_PAGES block.
* pfn_valid_within() should be used in this case; we optimise this away
* when we have no holes within a MAX_ORDER_NR_PAGES block.
*/
#ifdef CONFIG_HOLES_IN_ZONE
#define pfn_valid_within(pfn) pfn_valid(pfn)
#else
#define pfn_valid_within(pfn) (1)
#endif
#ifdef CONFIG_ARCH_HAS_HOLES_MEMORYMODEL
/*
* pfn_valid() is meant to be able to tell if a given PFN has valid memmap
* associated with it or not. In FLATMEM, it is expected that holes always
* have valid memmap as long as there is valid PFNs either side of the hole.
* In SPARSEMEM, it is assumed that a valid section has a memmap for the
* entire section.
*
* However, an ARM, and maybe other embedded architectures in the future
* free memmap backing holes to save memory on the assumption the memmap is
* never used. The page_zone linkages are then broken even though pfn_valid()
* returns true. A walker of the full memmap must then do this additional
* check to ensure the memmap they are looking at is sane by making sure
* the zone and PFN linkages are still valid. This is expensive, but walkers
* of the full memmap are extremely rare.
*/
int memmap_valid_within(unsigned long pfn,
struct page *page, struct zone *zone);
#else
static inline int memmap_valid_within(unsigned long pfn,
struct page *page, struct zone *zone)
{
return 1;
}
#endif /* CONFIG_ARCH_HAS_HOLES_MEMORYMODEL */
#endif /* !__GENERATING_BOUNDS.H */
#endif /* !__ASSEMBLY__ */
#endif /* _LINUX_MMZONE_H */
|
SM-G920P/Vindicator-S6-Sprint
|
include/linux/mmzone.h
|
C
|
gpl-2.0
| 40,525 |
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (version 1.7.0_67) on Thu Apr 09 10:38:16 MDT 2015 -->
<meta http-equiv="Content-Type" content="text/html" charset="utf-8">
<title>Uses of Class org.apache.solr.handler.ContentStreamLoader (Solr 5.1.0 API)</title>
<meta name="date" content="2015-04-09">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">
</head>
<body>
<script type="text/javascript"><!--
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Uses of Class org.apache.solr.handler.ContentStreamLoader (Solr 5.1.0 API)";
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar_top">
<!-- -->
</a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/handler/ContentStreamLoader.html" title="class in org.apache.solr.handler">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/handler/class-use/ContentStreamLoader.html" target="_top">Frames</a></li>
<li><a href="ContentStreamLoader.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="header">
<h2 title="Uses of Class org.apache.solr.handler.ContentStreamLoader" class="title">Uses of Class<br>org.apache.solr.handler.ContentStreamLoader</h2>
</div>
<div class="classUseContainer">No usage of org.apache.solr.handler.ContentStreamLoader</div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar_bottom">
<!-- -->
</a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="../../../../../overview-summary.html">Overview</a></li>
<li><a href="../package-summary.html">Package</a></li>
<li><a href="../../../../../org/apache/solr/handler/ContentStreamLoader.html" title="class in org.apache.solr.handler">Class</a></li>
<li class="navBarCell1Rev">Use</li>
<li><a href="../package-tree.html">Tree</a></li>
<li><a href="../../../../../deprecated-list.html">Deprecated</a></li>
<li><a href="../../../../../help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="../../../../../index.html?org/apache/solr/handler/class-use/ContentStreamLoader.html" target="_top">Frames</a></li>
<li><a href="ContentStreamLoader.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="../../../../../allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip-navbar_bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
<p class="legalCopy"><small>
<i>Copyright © 2000-2015 Apache Software Foundation. All Rights Reserved.</i>
<script src='../../../../../prettify.js' type='text/javascript'></script>
<script type='text/javascript'>
(function(){
var oldonload = window.onload;
if (typeof oldonload != 'function') {
window.onload = prettyPrint;
} else {
window.onload = function() {
oldonload();
prettyPrint();
}
}
})();
</script>
</small></p>
</body>
</html>
|
swsachith/ANDROPHSY
|
solr/docs/solr-core/org/apache/solr/handler/class-use/ContentStreamLoader.html
|
HTML
|
gpl-2.0
| 4,824 |
{% extends "webgateway/core_html.html" %}
{% load i18n %}
{% load common_filters %}
{% load common_tags %}
{% comment %}
<!--
Copyright (C) 2011-2014 University of Dundee & Open Microscopy Environment.
All rights reserved.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-->
{% endcomment %}
{% block link %}
<!-- overwrite body.css -->
{% endblock %}
{% block script %}
<script type="text/javascript">
$(document).ready(function() {
var show_batch_msg = function(text) {
$("#batch_ann_msg").html(text).show().delay(1200).fadeOut(1000);
}
var show_batch_error = function(text) {
$("#batch_ann_error").html(text + "<div><u>Click to Close</u></div>").show().click(function(){
$(this).hide();
});
}
$("#comments_container").hide_if_empty();
$("#fileanns_container").hide_if_empty();
$("#tags_container").hide_if_empty();
// show a link to the current objects
$("#show_link_btn").click(function(){
$("#link_info_popup").show();
var link_input = $("#link_info_popup input");
link_input.get(0).focus();
link_input.get(0).select();
});
$("#link_info_popup img").click(function(){
$("#link_info_popup").hide();
});
// handle submit of Add Comment form
$("#add_comment_form").ajaxForm({
beforeSubmit: function(data) {
var textArea = $('#add_comment_form textarea');
if ($.trim(textArea.val()).length == 0) {
show_batch_msg("Comment field was empty");
return false;
}
$("#comment_spinner").show();
},
success: function(html) {
$("#comment_spinner").hide();
var $comment = $(html)
$('#comments_container').prepend( $comment ).show();
$(".removeComment", $comment).hide();
var textArea = $('#add_comment_form textarea');
textArea.val('');
show_batch_msg("Comment added to Objects");
OME.filterAnnotationsAddedBy();
},
error: function(html) {
show_batch_msg(html);
$("#comment_spinner").hide();
}
});
$(".dropdown_menu .menu_launch").click(function(e){
$(this).parent().find('ul').css('visibility', 'visible');
$(this).parent().find('.dropdown_menu_options').show();
return false;
});
// on hover-out of the menu itself, hide drop-down menus
$(".dropdown_menu_options").hover(function(){}, function(){
$(this).css('visibility', 'hidden');
}).hide();
// Choose to add tags...
if ($("#add_tags_form").length === 0) {
$("<form id='add_tags_form' title='Tags Selection' action='{% url 'annotate_tags' %}' method='post'>{% csrf_token %}")
.hide().appendTo('body');
}
$("#launch_tags_form").click(function(event) {
$("#add_tags_form").dialog("open");
// load form via AJAX...
var load_url = $(this).attr('href');
$("#add_tags_form").load(load_url);
return false;
});
// set-up the tags form to use dialog
$("#add_tags_form").dialog({
autoOpen: false,
resizable: false,
height: 520,
width: 780,
modal: true,
buttons: {
"Save": function() {
// simply submit the form (AJAX handling set-up above)
$("#add_tags_form").trigger('prepare-submit').submit();
$( this ).dialog( "close" );
},
"Cancel": function() {
$( this ).dialog( "close" );
},
"Reset": function() {
// discard all changes and reload the form
$("#add_tags_form").html('').load($("#launch_tags_form").attr('href'));
}
}
});
$('#add_tags_form').ajaxForm({
beforeSubmit: function(data) {
$("#tagann_spinner").show();
$("#add_tags_form").dialog( "close" );
},
success: function(data) {
$("#add_tags_form").dialog( "close" ); // hide in case it was submitted via 'Enter'
// update the list of tags
var $tag = $(data);
$tag.filter(".tag_annotation_wrapper").each(function(){
$("#"+$(this).attr("id")).remove(); // if this Tag already exists, remove it
$("#tags_container").prepend( this ).show();
});
show_batch_msg("Tags added to Objects");
$(".tooltip", $tag).tooltip_init();
OME.filterAnnotationsAddedBy();
},
error: function(data) {
$("#tagann_spinner").hide();
}
});
// set-up the attachment selection form to use AJAX. (requires jquery.form.js plugin)
if ($("#choose_attachments_form").length === 0) {
$("<form id='choose_attachments_form' title='Choose attachments' action='{% url 'annotate_file' %}' method='post'>{% csrf_token %}")
.hide().appendTo('body');
}
$('#choose_attachments_form').ajaxForm({
beforeSubmit: function(data) {
$("#choose_attachments_form").dialog( "close" );
$("#fileann_spinner").show();
},
success: function(data) {
$("#fileann_spinner").hide();
// update the list of file annotations and hide actions
var $fileanns = $(data);
$fileanns.filter(".file_ann_wrapper").each(function(){
$("#"+$(this).attr("id")).remove(); // if this File already exists, remove it
$("#fileanns_container").prepend( this ).show();
});
$fileanns.tooltip({
items: '.file_ann_wrapper',
content: function() {
return $("span.tooltip_html", $(this)).html();
},
track: true,
show: false,
hide: false
});
show_batch_msg("File Annotation(s) added to Objects");
OME.filterAnnotationsAddedBy();
OME.fileAnnotationCheckboxDynamicallyAdded();
},
error: function(data){
$("#fileann_spinner").hide();
alert("Upload failed [" + data.status + " " + data.statusText + "]");
}
});
// prepare dialog for choosing file to attach...
$("#choose_attachments_form").dialog({
autoOpen: false,
resizable: true,
height: 400,
width:420,
modal: true,
buttons: {
"Accept": function() {
// simply submit the form (AJAX handling set-up above)
$("#choose_attachments_form").submit();
$( this ).dialog( "close" );
},
"Cancel": function() {
$( this ).dialog( "close" );
}
}
});
// show dialog for choosing file to attach...
$("#choose_file_anns").click(function() {
// show dialog first, then do the AJAX call to load files...
var attach_form = $( "#choose_attachments_form" );
attach_form.dialog( "open" );
// load form via AJAX...
var load_url = $(this).attr('href');
attach_form.load(load_url);
return false;
});
$(".tooltip_title").tooltip({
items: '.tooltip_title',
content: function() {
return $("span.tooltip_html", $(this)).html();
},
track: true,
show: false,
hide: false
});
$(".tooltip").tooltip_init();
// bind 'remove' action to various annotations
$("#tags_container").on("click", ".removeTag", function(event){
var url = $(this).attr('url'),
parents = '{{ link_string }}'; // E.g image-123|image-456
OME.removeItem(event, ".tag", url, parents, {{ index }});
return false;
});
$("#fileanns_container").on("click", ".removeFile", function(event) {
var url = $(this).attr('href'),
parents = '{{ link_string }}'; // E.g image-123|image-456
OME.removeItem(event, ".file_ann_wrapper", url, parents, {{ index }});
return false;
});
// delete action (files)
$("#fileanns_container").on("click", ".deleteFile", function(event) {
var url = $(this).attr('href');
OME.deleteItem(event, "file_ann_wrapper", url);
});
// Filtering annotations added by 'me' or 'others' or 'all'
$("#annotationFilter").change(function(){
OME.filterAnnotationsAddedBy();
});
// Rating
// NB: similar functionality on metadata_general.html
$("#add_rating").click(function(){
$(".myRating").toggle();
});
$("#rating_annotations").on("click", ".myRating img", function(event){
var $rating = $(this),
clickX = event.pageX - $rating.offset().left;
var r = (clickX/ $rating.width()) * 5;
r = parseInt(Math.ceil(r));
setRating(r, $rating);
});
// $(".addRating img").click(function(event){
// var $rating = $(this),
// $ratingli = $rating.parent().parent(),
// clickX = event.pageX - $rating.offset().left;
// var r = (clickX/ $rating.width()) * 5;
// r = parseInt(Math.ceil(r));
// var $newR = $ratingli.clone().prependTo("#rating_annotations");
// $newR.removeClass('addRating').addClass('myRating');
// $ratingli.hide();
// setRating(r, $newR.find('img'));
// });
$("#rating_annotations").on("click", ".removeRating", function(event){
event.preventDefault();
var $liMyRating = $(this).parent(),
$ratingimg = $liMyRating.find('img');
$liMyRating.hide();
setRating(0, $ratingimg);
});
var setRating = function(rating, $rating) {
// update rating
if ($rating) {
var rating_src = "{% static 'webclient/image/rating0.png' %}".replace("0.png", rating+".png");
$rating.attr('src', rating_src);
}
$(".ratingCount").text("{{ obj_labels|length }}");
// hide the [+] button if we have set a rating
if (rating > 0) {
$("#add_rating").hide()
} else {
$("#add_rating").show()
}
// update rating annotation
var rating_url = "{% url 'annotate_rating' %}?{{ obj_string }}&index={{ index }}"
rating_url += "&rating=" + rating;
$.post(rating_url, function(data) {
// update summary
$("#ratingsAverage").text(data.average);
$("#ratingsCount").text(data.count);
$("#ratingsSummary").show();
});
}
OME.initToolbarDropdowns();
});
</script>
{% endblock %}
{% block body %}
<!-- Used to check against current selection when loading panel via AJAX -->
<div id="object-ids" style="display:none">{{ link_string }}</div>
<div class="right_tab_inner">
<div id="batch_ann_msg_container">
<div id="batch_ann_msg"></div> <!-- hidden div to show success messages etc -->
<div id="batch_ann_error" title="Click to close"></div>
</div>
<h1 id="batch_ann_title" style="float:left">
Selected
<span class="tooltip_title">
{{ obj_labels|length }} objects:
<span style="width:20px; height:20px; display: inline-block" class="btn_info">   </span>
<span class="tooltip_html" style='display:none'>
{% for label in obj_labels %}
{% if forloop.counter < 20 %}
<div><b>{{ label.type }} {{ label.id}}:</b> {{ label.name|truncateafter:"40" }}</div>
{% else %}
{% if forloop.counter == 20 and obj_labels|length > 20 %}
<div>and <b> {{ obj_labels|length|subtract:20 }}</b> other objects...</div>
{% endif %}
{% endif %}
{% endfor %}
</span>
</span>
</h1>
<div style="position: relative; float: right">
{% include "webclient/annotations/includes/toolbar.html" %}
</div>
<div style="clear:both"></div>
<div>
<h2 style="float: left">
Annotations
</h2>
<select id="annotationFilter" title="Filter by user" data-userId="{{ ome.user.id }}"
style="float: right; width:80px">
<option value="all">Show all</option>
<option value="me">Show added by me</option>
<option value="others">Show added by others</option>
</select>
</div>
<div style="clear:both"></div>
<hr style="margin-top:0" />
{% if annotationBlocked %}
<h3 class="postit_msg">{{ annotationBlocked }}</h3>
{% endif %}
<!-- RATING -->
<div class="annotations_section">
<h2>{% trans "Rating" %}</h2>
{% if not annotationBlocked %}
<a id="add_rating"
{% if userRatingAvg > 0 %}style="display:none"{% endif %} class="btn silver btn_add"><span></span></a>
{% endif %}
<ul id="rating_annotations" class="lnfiles">
<li class="rating {% if not annotationBlocked %}myRating{% endif %}" style="position: relative {% ifequal userRatingAvg 0 %}; display:none{% endifequal %}">
<a><img
{% ifequal userRatingAvg 0 %} src="{% static "webclient/image/rating0.png" %}"{% endifequal %}
{% ifequal userRatingAvg 1 %} src="{% static "webclient/image/rating1.png" %}"{% endifequal %}
{% ifequal userRatingAvg 2 %} src="{% static "webclient/image/rating2.png" %}"{% endifequal %}
{% ifequal userRatingAvg 3 %} src="{% static "webclient/image/rating3.png" %}"{% endifequal %}
{% ifequal userRatingAvg 4 %} src="{% static "webclient/image/rating4.png" %}"{% endifequal %}
{% ifequal userRatingAvg 5 %} src="{% static "webclient/image/rating5.png" %}"{% endifequal %}
/>
<span class="ratingOwner">
(avg of <span class="ratingCount">{{ batchAnns.UserRatings|length }}</span>)
</span>
</a>
{% if not annotationBlocked %}
<a href="#" class="removeRating removeTag" title="Delete rating">X</a>
{% endif %}
</li>
</ul>
<div id="ratingsSummary" {% if not ratings.average %}style="display:none"{% endif %}>
(avg:
<span id="ratingsAverage">{{ ratings.average }}</span>
/ <span id="ratingsCount">{{ ratings.count }}</span>
votes)
</div>
</div>
<hr/>
<!-- TAGS -->
<div class="annotations_section">
<h2>{% trans "Tags" %}</h2>
{% if not annotationBlocked %}
<a id="launch_tags_form" href="{% url 'annotate_tags' %}?{{ obj_string }}&index={{ index }}" class="btn silver btn_add"><span></span></a>
{% endif %}
<div id="tags_container" class="lntags">
{% include "webclient/annotations/tags.html" %}
</div>
</div>
<hr/><!-- Temporary Solution. Not the right way to add borders to elements! -->
<!-- FILES -->
<div class="annotations_section">
<h2>{% trans "Attach" %}:</h2>
{% if not annotationBlocked %}
<a id="choose_file_anns" href="{% url 'annotate_file' %}?{{ obj_string }}&index={{ index }}" class="btn silver btn_add">
<span></span>
</a>
<div class="toolbar">
<input type="button" title="Select Files for Scripts"
class="btn silver btn_script_dark">
<!-- Class "scriptButton" also on <span> as that
is actually what we're clicking on.
-->
<span class="scriptButton"></span>
</div>
<script type="text/javascript">
$(".annotations_section .scriptButton").click(
{webindex: "{% url 'webindex' %}"},
OME.showScriptList
);
</script>
{% endif %}
<img id='fileann_spinner' src="{% static "webgateway/img/spinner.gif" %}" style="display:none"/>
<!-- display existing file annotations -->
<ul id="fileanns_container" class="lnfiles">
{% include "webclient/annotations/fileanns.html" %}
</ul>
<script type="text/javascript">
$(".annotations_section .toolbar input[type=button]").click(
OME.toggleFileAnnotationCheckboxes
);
$("#fileanns_container").on(
"change", "li input[type=checkbox]",
OME.fileAnnotationCheckboxChanged
);
</script>
</div>
<hr/><!-- Temporary Solution. Not the right way to add borders to elements! -->
<!-- COMMENTS -->
{% if not annotationBlocked %}
<div class="annotations_section">
<h2>{% trans "Comment:" %}</h2>
<form id="add_comment_form" action="{% url 'annotate_comment' %}" method="post">{% csrf_token %}
<table>
<tr class="hiddenField"><td>{{ form_comment.image }}</td></tr>
<tr class="hiddenField"><td>{{ form_comment.dataset }}</td></tr>
<tr class="hiddenField"><td>{{ form_comment.project }}</td></tr>
<tr class="hiddenField"><td>{{ form_comment.screen }}</td></tr>
<tr class="hiddenField"><td>{{ form_comment.plate }}</td></tr>
<tr class="hiddenField"><td>{{ form_comment.acquisition }}</td></tr>
<tr class="hiddenField"><td>{{ form_comment.well }}</td></tr>
<tr>
<td>{{ form_comment.comment }}</td>
</tr>
<tr>
<td>
<input type="submit" value="{% trans 'Add Comment' %}" />
<img id='comment_spinner' src="{% static "webgateway/img/spinner.gif" %}" style="display:none"/>
</td>
</tr>
</table>
</form>
<div id="comments_container" class="lncomments">
{% for tann in manager.text_annotations %}
{% include "webclient/annotations/comment.html" %}
{% endfor %}
</div>
<div class="clear"></div>
</div>
{% endif %}
</div>
{% endblock %}
|
tp81/openmicroscopy
|
components/tools/OmeroWeb/omeroweb/webclient/templates/webclient/annotations/batch_annotate.html
|
HTML
|
gpl-2.0
| 22,549 |
--
-- -- unit-protoss-shield-battery
--
DefineAnimations("animations-protoss-shield-battery", {
Still = {
"frame 0", "wait 125",
},
Train = {
"frame 0", "wait 125",
},
})
DefineConstruction("construction-protoss-shield-battery", {
Files = {
File = "terran/units/building construction large.png",
Size = {160, 128}},
ShadowFiles = {
File = "terran/units/building construction large shadow.png",
Size = {128, 128}},
Constructions = {
{Percent = 0,
File = "construction",
Frame = 0},
{Percent = 20,
File = "construction",
Frame = 1},
{Percent = 40,
File = "construction",
Frame = 2},
{Percent = 60,
File = "main",
Frame = 1}}
})
DefineUnitType("unit-protoss-shield-battery", { Name = "Shield Battery",
Image = {"file", "protoss/units/shield battery.png", "size", {96, 64}},
Shadow = {"file", "protoss/units/pgcshad.png", "size", {96, 64}},
Animations = "animations-protoss-shield-battery", Icon = "icon-protoss-shield-battery",
Costs = {"time", 30, "minerals", 100},
RepairHp = 4,
RepairCosts = {"minerals", 1, "gas", 1},
Construction = "construction-protoss-shield-battery",
Speed = 0,
HitPoints = 1000,
DrawLevel = 50,
TileSize = {3, 2}, BoxSize = {95, 63},
SightRange = 1,
Armor = 20, BasicDamage = 0, PiercingDamage = 0, Missile = "missile-none",
Priority = 30, AnnoyComputerFactor = 35,
Points = 160,
BuilderOutside = true,
AutoBuildRate = 2,
Type = "land",
Building = true, VisibleUnderFog = true,
BuildingRules = { { "distance", { Distance = 3, DistanceType = "<", Type = "unit-protoss-pylon"} } },
Sounds = {
"selected", "protoss-cybernetics-core-selected",
"ready", "protoss-building-done",
"help", "protoss-base-attacked",
"dead", "protoss-explosion-large"} } )
|
ElectricPrism/stargus
|
scripts/protoss/unit-protoss-shield-battery.lua
|
Lua
|
gpl-2.0
| 1,812 |
# PopGen 1.1 is A Synthetic Population Generator for Advanced
# Microsimulation Models of Travel Demand
# Copyright (C) 2009, Arizona State University
# See PopGen/License
import MySQLdb
def create_tables(db, project_name, path):
dbc = db.cursor()
print ('Create Database %s' %(project_name))
dbc.execute('Create Database %s' %(project_name))
dbc.close()
db = MySQLdb.connect(user = 'root', passwd = '1234', db = '%s'%(project_name))
dbc = db.cursor()
dbc.execute('''Create Table housing_pums ( pumano int, hhpumsid int,
hhid int, hhtype int,
childpresence int, hhldtype int,
hhldsize int, hhldinc int,
groupquarter int )''')
dbc.execute('''load data local infile '%s/housing_pums.dat' into table housing_pums'''%(path))
dbc.execute('''Create Table person_pums ( pumano int, hhpumsid int,
hhid int, personid int,
gender int, age int,
race int, employment int )''')
dbc.execute('''load data local infile '%s/person_pums.dat' into table person_pums''' %(path))
dbc.execute('''Create Table housing_marginals ( county int, pumano int,
tract int, bg int,
hhtotal int, childpresence1 int,
childpresence2 int, hhldtype1 int,
hhldtype2 int, hhldtype3 int,
hhldtype4 int, hhldtype5 int,
hhldsize1 int, hhldsize2 int,
hhldsize3 int, hhldsize4 int,
hhldsize5 int, hhldsize6 int,
hhldsize7 int, hhldinc1 int,
hhldinc2 int, hhldinc3 int,
hhldinc4 int, hhldinc5 int,
hhldinc6 int, hhldinc7 int,
hhldinc8 int, groupquarter1 int,
groupquarter2 int )''')
dbc.execute('''load data local infile '%s/housing_marginals.dat' into table housing_marginals'''%(path))
dbc.execute('''Create Table person_marginals ( county int, pumano int,
tract int, bg int,
gender1 int, gender2 int,
age1 int, age2 int,
age3 int, age4 int,
age5 int, age6 int,
age7 int, age8 int,
age9 int, age10 int,
race1 int, race2 int,
race3 int, race4 int,
race5 int, race6 int,
race7 int, employment1 int,
employment2 int, employment3 int,
employment4 int )''')
dbc.execute('''load data local infile '%s/person_marginals.dat' into table person_marginals'''%(path))
# Figure out a way to automate this process based on the number of hhtypes and the independent tables must only contain variables corresponding
# to the particular housing type
hhld_variables = 'childpresence, hhldtype, hhldsize, hhldinc'
gq_variables = 'groupquarter'
dbc.execute('''create table hhld_pums select pumano, hhpumsid, hhid, %s from housing_pums where hhtype = 1'''%(hhld_variables))
dbc.execute('''create table gq_pums select pumano, hhpumsid, hhid, %s from housing_pums where hhtype = 2'''%(gq_variables))
dbc.close()
db.commit()
db.close()
if __name__ == '__main__':
db = MySQLdb.connect(user = 'root', passwd = '1234')
# How to pickup the location of the flat-files, this can probably come from the GUI?
path = 'c:/populationsynthesis/command_line_algorithm/northcarolina/data'
create_tables (db, 'northcarolina', path)
db.close()
|
christianurich/VIBe2UrbanSim
|
3rdparty/opus/src/synthesizer/command_line_algorithm/create_mysql_tables.py
|
Python
|
gpl-2.0
| 3,568 |
package com.adriansoghoian.breathemessenger;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
public class NewContactActivity extends ActionBarActivity {
Button addContact;
String contactPinString;
NewContactTask newContactTask;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_contact);
final EditText contactPin = (EditText)findViewById(R.id.contactPin);
Button addContact = (Button)findViewById(R.id.addContact);
addContact.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
contactPinString = contactPin.getText().toString();
newContactTask = new NewContactTask(getApplicationContext());
newContactTask.execute(contactPinString);
}
});
}
public class NewContactTask extends AsyncTask<String, Integer, String> {
List<NameValuePair> nameValuePairs;
Context context;
Contact newContact;
@Override
public String doInBackground(String... params) {
try {
fetchKey(params[0]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return null;
}
public NewContactTask(Context c) {
this.context = c;
}
protected void onPostExecute(String result) {
startActivity(new Intent(getApplicationContext(), ContactListActivity.class));
}
public void fetchKey(String pin) throws UnsupportedEncodingException {
HttpPost httppost = new HttpPost("https://blooming-cliffs-4171.herokuapp.com/user/key");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("pin", pin));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
try {
HttpResponse response = TorWrapper.getInstance().execute(httppost);
HttpEntity entity = response.getEntity();
if (entity != null) {
String responseString = EntityUtils.toString(entity) ;
System.out.println(responseString);
JSONObject responseJSON = new JSONObject(responseString);
String contactKey = responseJSON.get("response").toString();
System.out.println("User fetched with key: " + contactKey);
newContact = new Contact();
newContact.pin = pin;
newContact.pubKey = contactKey;
newContact.save();
System.out.println(newContact.pubKey);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_new_contact, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
|
digideskio/breathe-messenger
|
app/src/main/java/com/adriansoghoian/breathemessenger/NewContactActivity.java
|
Java
|
gpl-2.0
| 4,573 |
#define ADR_BOOTINFO 0x00000ff0
struct BOOTINFO { /* 0x0ff0-0x0fff */
char cyls; /* 启动区读硬盘读到何处为止 */
char leds; /* 启动时键盘的LED的状态 */
char vmode; /* 显卡模式为多少为彩色 */
char reserve;
short scrnx, scrny; /* 画面分辨率 */
char *vram; //图像缓冲区的开始地址
};
|
vandykai/operating-system
|
EZPioneer/src/asmhead.h
|
C
|
gpl-2.0
| 350 |
<?php
global $CONFIG;
$destfile = $CONFIG->pluginspath.'dokuwiki/vendors/dokuwiki/'.$vars['page'];
if (file_exists($destfile)) {
if (strpos($destfile, ".png") === FALSE)
{
include($destfile);
} else {
header("Content-type: image");
echo file_get_contents($destfile);
}
}
?>
|
lorea/dokuwiki
|
views/default/dokuwiki/index.php
|
PHP
|
gpl-2.0
| 310 |
<?php
/**
* OpenSource-SocialNetwork
*
* @package (Informatikon.com).ossn
* @author OSSN Core Team <[email protected]>
* @copyright 2014 iNFORMATIKON TECHNOLOGIES
* @license General Public Licence http://opensource-socialnetwork.com/licence
* @link http://www.opensource-socialnetwork.com/licence
*/
// replace <<host>> with your database host name;
$Ossn->host = '<<host>>';
// replace <<user>> with your database username;
$Ossn->user = '<<user>>';
// replace <<password>> with your database password;
$Ossn->password = '<<password>>';
// replace <<dbname>> with your database name;
$Ossn->database = '<<dbname>>';
|
githubertus/opensource-socialnetwork
|
configurations/ossn.config.db.example.php
|
PHP
|
gpl-2.0
| 660 |
/*-*- Mode: C; c-basic-offset: 8; indent-tabs-mode: nil -*-*/
/***
This file is part of systemd.
Copyright 2014 Lennart Poettering
systemd 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.
systemd 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 systemd; If not, see <http://www.gnu.org/licenses/>.
***/
#include <string.h>
#include "cap-list.h"
#include "missing.h"
#include "parse-util.h"
#include "util.h"
static const struct capability_name* lookup_capability(register const char *str, register unsigned int len);
#include "cap-to-name.h"
#include "cap-from-name.h"
const char *capability_to_name(int id) {
if (id < 0)
return NULL;
if (id >= (int) ELEMENTSOF(capability_names))
return NULL;
return capability_names[id];
}
int capability_from_name(const char *name) {
const struct capability_name *sc;
int r, i;
assert(name);
/* Try to parse numeric capability */
r = safe_atoi(name, &i);
if (r >= 0 && i >= 0)
return i;
/* Try to parse string capability */
sc = lookup_capability(name, strlen(name));
if (!sc)
return -EINVAL;
return sc->id;
}
int capability_list_length(void) {
return (int) ELEMENTSOF(capability_names);
}
|
lnykryn/systemd
|
src/basic/cap-list.c
|
C
|
gpl-2.0
| 1,794 |
/*
* Driver for the PN544 NFC chip.
*
* Copyright (C) Nokia Corporation
*
* Author: Jari Vanhala <[email protected]>
* Contact: Matti Aaltonen <[email protected]>
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#include <linux/completion.h>
#include <linux/crc-ccitt.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/kernel.h>
#include <linux/miscdevice.h>
#include <linux/module.h>
#include <linux/mutex.h>
#include <linux/nfc/pn544.h>
#include <linux/poll.h>
#include <linux/regulator/consumer.h>
#include <linux/serial_core.h> /* for TCGETS */
#include <linux/slab.h>
#define DRIVER_CARD "PN544 NFC"
#define DRIVER_DESC "NFC driver for PN544"
static struct i2c_device_id pn544_id_table[] = {
{ PN544_DRIVER_NAME, 0 },
{ }
};
MODULE_DEVICE_TABLE(i2c, pn544_id_table);
#define HCI_MODE 0
#define FW_MODE 1
enum pn544_state {
PN544_ST_COLD,
PN544_ST_FW_READY,
PN544_ST_READY,
};
enum pn544_irq {
PN544_NONE,
PN544_INT,
};
struct pn544_info {
struct miscdevice miscdev;
struct i2c_client *i2c_dev;
struct regulator_bulk_data regs[3];
enum pn544_state state;
wait_queue_head_t read_wait;
loff_t read_offset;
enum pn544_irq read_irq;
struct mutex read_mutex; /* Serialize read_irq access */
struct mutex mutex; /* Serialize info struct access */
u8 *buf;
size_t buflen;
};
static const char reg_vdd_io[] = "Vdd_IO";
static const char reg_vbat[] = "VBat";
static const char reg_vsim[] = "VSim";
/* sysfs interface */
static ssize_t pn544_test(struct device *dev,
struct device_attribute *attr, char *buf)
{
struct pn544_info *info = dev_get_drvdata(dev);
struct i2c_client *client = info->i2c_dev;
struct pn544_nfc_platform_data *pdata = client->dev.platform_data;
return snprintf(buf, PAGE_SIZE, "%d\n", pdata->test());
}
static int pn544_enable(struct pn544_info *info, int mode)
{
struct pn544_nfc_platform_data *pdata;
struct i2c_client *client = info->i2c_dev;
int r;
r = regulator_bulk_enable(ARRAY_SIZE(info->regs), info->regs);
if (r < 0)
return r;
pdata = client->dev.platform_data;
info->read_irq = PN544_NONE;
if (pdata->enable)
pdata->enable(mode);
if (mode) {
info->state = PN544_ST_FW_READY;
dev_dbg(&client->dev, "now in FW-mode\n");
} else {
info->state = PN544_ST_READY;
dev_dbg(&client->dev, "now in HCI-mode\n");
}
usleep_range(10000, 15000);
return 0;
}
static void pn544_disable(struct pn544_info *info)
{
struct pn544_nfc_platform_data *pdata;
struct i2c_client *client = info->i2c_dev;
pdata = client->dev.platform_data;
if (pdata->disable)
pdata->disable();
info->state = PN544_ST_COLD;
dev_dbg(&client->dev, "Now in OFF-mode\n");
msleep(PN544_RESETVEN_TIME);
info->read_irq = PN544_NONE;
regulator_bulk_disable(ARRAY_SIZE(info->regs), info->regs);
}
static int check_crc(u8 *buf, int buflen)
{
u8 len;
u16 crc;
len = buf[0] + 1;
if (len < 4 || len != buflen || len > PN544_MSG_MAX_SIZE) {
pr_err(PN544_DRIVER_NAME
": CRC; corrupt packet len %u (%d)\n", len, buflen);
print_hex_dump(KERN_DEBUG, "crc: ", DUMP_PREFIX_NONE,
16, 2, buf, buflen, false);
return -EPERM;
}
crc = crc_ccitt(0xffff, buf, len - 2);
crc = ~crc;
if (buf[len-2] != (crc & 0xff) || buf[len-1] != (crc >> 8)) {
pr_err(PN544_DRIVER_NAME ": CRC error 0x%x != 0x%x 0x%x\n",
crc, buf[len-1], buf[len-2]);
print_hex_dump(KERN_DEBUG, "crc: ", DUMP_PREFIX_NONE,
16, 2, buf, buflen, false);
return -EPERM;
}
return 0;
}
static int pn544_i2c_write(struct i2c_client *client, u8 *buf, int len)
{
int r;
if (len < 4 || len != (buf[0] + 1)) {
dev_err(&client->dev, "%s: Illegal message length: %d\n",
__func__, len);
return -EINVAL;
}
if (check_crc(buf, len))
return -EINVAL;
usleep_range(3000, 6000);
r = i2c_master_send(client, buf, len);
dev_dbg(&client->dev, "send: %d\n", r);
if (r == -EREMOTEIO) { /* Retry, chip was in standby */
usleep_range(6000, 10000);
r = i2c_master_send(client, buf, len);
dev_dbg(&client->dev, "send2: %d\n", r);
}
if (r != len)
return -EREMOTEIO;
return r;
}
static int pn544_i2c_read(struct i2c_client *client, u8 *buf, int buflen)
{
int r;
u8 len;
/*
* You could read a packet in one go, but then you'd need to read
* max size and rest would be 0xff fill, so we do split reads.
*/
r = i2c_master_recv(client, &len, 1);
dev_dbg(&client->dev, "recv1: %d\n", r);
if (r != 1)
return -EREMOTEIO;
if (len < PN544_LLC_HCI_OVERHEAD)
len = PN544_LLC_HCI_OVERHEAD;
else if (len > (PN544_MSG_MAX_SIZE - 1))
len = PN544_MSG_MAX_SIZE - 1;
if (1 + len > buflen) /* len+(data+crc16) */
return -EMSGSIZE;
buf[0] = len;
r = i2c_master_recv(client, buf + 1, len);
dev_dbg(&client->dev, "recv2: %d\n", r);
if (r != len)
return -EREMOTEIO;
usleep_range(3000, 6000);
return r + 1;
}
static int pn544_fw_write(struct i2c_client *client, u8 *buf, int len)
{
int r;
dev_dbg(&client->dev, "%s\n", __func__);
if (len < PN544_FW_HEADER_SIZE ||
(PN544_FW_HEADER_SIZE + (buf[1] << 8) + buf[2]) != len)
return -EINVAL;
r = i2c_master_send(client, buf, len);
dev_dbg(&client->dev, "fw send: %d\n", r);
if (r == -EREMOTEIO) { /* Retry, chip was in standby */
usleep_range(6000, 10000);
r = i2c_master_send(client, buf, len);
dev_dbg(&client->dev, "fw send2: %d\n", r);
}
if (r != len)
return -EREMOTEIO;
return r;
}
static int pn544_fw_read(struct i2c_client *client, u8 *buf, int buflen)
{
int r, len;
if (buflen < PN544_FW_HEADER_SIZE)
return -EINVAL;
r = i2c_master_recv(client, buf, PN544_FW_HEADER_SIZE);
dev_dbg(&client->dev, "FW recv1: %d\n", r);
if (r < 0)
return r;
if (r < PN544_FW_HEADER_SIZE)
return -EINVAL;
len = (buf[1] << 8) + buf[2];
if (len == 0) /* just header, no additional data */
return r;
if (len > buflen - PN544_FW_HEADER_SIZE)
return -EMSGSIZE;
r = i2c_master_recv(client, buf + PN544_FW_HEADER_SIZE, len);
dev_dbg(&client->dev, "fw recv2: %d\n", r);
if (r != len)
return -EINVAL;
return r + PN544_FW_HEADER_SIZE;
}
static irqreturn_t pn544_irq_thread_fn(int irq, void *dev_id)
{
struct pn544_info *info = dev_id;
struct i2c_client *client = info->i2c_dev;
BUG_ON(!info);
BUG_ON(irq != info->i2c_dev->irq);
dev_dbg(&client->dev, "IRQ\n");
mutex_lock(&info->read_mutex);
info->read_irq = PN544_INT;
mutex_unlock(&info->read_mutex);
wake_up_interruptible(&info->read_wait);
return IRQ_HANDLED;
}
static enum pn544_irq pn544_irq_state(struct pn544_info *info)
{
enum pn544_irq irq;
mutex_lock(&info->read_mutex);
irq = info->read_irq;
mutex_unlock(&info->read_mutex);
/*
* XXX: should we check GPIO-line status directly?
* return pdata->irq_status() ? PN544_INT : PN544_NONE;
*/
return irq;
}
static ssize_t pn544_read(struct file *file, char __user *buf,
size_t count, loff_t *offset)
{
struct pn544_info *info = container_of(file->private_data,
struct pn544_info, miscdev);
struct i2c_client *client = info->i2c_dev;
enum pn544_irq irq;
size_t len;
int r = 0;
dev_dbg(&client->dev, "%s: info: %p, count: %zu\n", __func__,
info, count);
mutex_lock(&info->mutex);
if (info->state == PN544_ST_COLD) {
r = -ENODEV;
goto out;
}
irq = pn544_irq_state(info);
if (irq == PN544_NONE) {
if (file->f_flags & O_NONBLOCK) {
r = -EAGAIN;
goto out;
}
if (wait_event_interruptible(info->read_wait,
(info->read_irq == PN544_INT))) {
r = -ERESTARTSYS;
goto out;
}
}
if (info->state == PN544_ST_FW_READY) {
len = min(count, info->buflen);
mutex_lock(&info->read_mutex);
r = pn544_fw_read(info->i2c_dev, info->buf, len);
info->read_irq = PN544_NONE;
mutex_unlock(&info->read_mutex);
if (r < 0) {
dev_err(&info->i2c_dev->dev, "FW read failed: %d\n", r);
goto out;
}
print_hex_dump(KERN_DEBUG, "FW read: ", DUMP_PREFIX_NONE,
16, 2, info->buf, r, false);
*offset += r;
if (copy_to_user(buf, info->buf, r)) {
r = -EFAULT;
goto out;
}
} else {
len = min(count, info->buflen);
mutex_lock(&info->read_mutex);
r = pn544_i2c_read(info->i2c_dev, info->buf, len);
info->read_irq = PN544_NONE;
mutex_unlock(&info->read_mutex);
if (r < 0) {
dev_err(&info->i2c_dev->dev, "read failed (%d)\n", r);
goto out;
}
print_hex_dump(KERN_DEBUG, "read: ", DUMP_PREFIX_NONE,
16, 2, info->buf, r, false);
*offset += r;
if (copy_to_user(buf, info->buf, r)) {
r = -EFAULT;
goto out;
}
}
out:
mutex_unlock(&info->mutex);
return r;
}
static unsigned int pn544_poll(struct file *file, poll_table *wait)
{
struct pn544_info *info = container_of(file->private_data,
struct pn544_info, miscdev);
struct i2c_client *client = info->i2c_dev;
int r = 0;
dev_dbg(&client->dev, "%s: info: %p\n", __func__, info);
mutex_lock(&info->mutex);
if (info->state == PN544_ST_COLD) {
r = -ENODEV;
goto out;
}
poll_wait(file, &info->read_wait, wait);
if (pn544_irq_state(info) == PN544_INT) {
r = POLLIN | POLLRDNORM;
goto out;
}
out:
mutex_unlock(&info->mutex);
return r;
}
static ssize_t pn544_write(struct file *file, const char __user *buf,
size_t count, loff_t *ppos)
{
struct pn544_info *info = container_of(file->private_data,
struct pn544_info, miscdev);
struct i2c_client *client = info->i2c_dev;
ssize_t len;
int r;
dev_dbg(&client->dev, "%s: info: %p, count %zu\n", __func__,
info, count);
mutex_lock(&info->mutex);
if (info->state == PN544_ST_COLD) {
r = -ENODEV;
goto out;
}
/*
* XXX: should we detect rset-writes and clean possible
* read_irq state
*/
if (info->state == PN544_ST_FW_READY) {
size_t fw_len;
if (count < PN544_FW_HEADER_SIZE) {
r = -EINVAL;
goto out;
}
len = min(count, info->buflen);
if (copy_from_user(info->buf, buf, len)) {
r = -EFAULT;
goto out;
}
print_hex_dump(KERN_DEBUG, "FW write: ", DUMP_PREFIX_NONE,
16, 2, info->buf, len, false);
fw_len = PN544_FW_HEADER_SIZE + (info->buf[1] << 8) +
info->buf[2];
if (len > fw_len) /* 1 msg at a time */
len = fw_len;
r = pn544_fw_write(info->i2c_dev, info->buf, len);
} else {
if (count < PN544_LLC_MIN_SIZE) {
r = -EINVAL;
goto out;
}
len = min(count, info->buflen);
if (copy_from_user(info->buf, buf, len)) {
r = -EFAULT;
goto out;
}
print_hex_dump(KERN_DEBUG, "write: ", DUMP_PREFIX_NONE,
16, 2, info->buf, len, false);
if (len > (info->buf[0] + 1)) /* 1 msg at a time */
len = info->buf[0] + 1;
r = pn544_i2c_write(info->i2c_dev, info->buf, len);
}
out:
mutex_unlock(&info->mutex);
return r;
}
static long pn544_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
struct pn544_info *info = container_of(file->private_data,
struct pn544_info, miscdev);
struct i2c_client *client = info->i2c_dev;
struct pn544_nfc_platform_data *pdata;
unsigned int val;
int r = 0;
dev_dbg(&client->dev, "%s: info: %p, cmd: 0x%x\n", __func__, info, cmd);
mutex_lock(&info->mutex);
if (info->state == PN544_ST_COLD) {
r = -ENODEV;
goto out;
}
pdata = info->i2c_dev->dev.platform_data;
switch (cmd) {
case PN544_GET_FW_MODE:
dev_dbg(&client->dev, "%s: PN544_GET_FW_MODE\n", __func__);
val = (info->state == PN544_ST_FW_READY);
if (copy_to_user((void __user *)arg, &val, sizeof(val))) {
r = -EFAULT;
goto out;
}
break;
case PN544_SET_FW_MODE:
dev_dbg(&client->dev, "%s: PN544_SET_FW_MODE\n", __func__);
if (copy_from_user(&val, (void __user *)arg, sizeof(val))) {
r = -EFAULT;
goto out;
}
if (val) {
if (info->state == PN544_ST_FW_READY)
break;
pn544_disable(info);
r = pn544_enable(info, FW_MODE);
if (r < 0)
goto out;
} else {
if (info->state == PN544_ST_READY)
break;
pn544_disable(info);
r = pn544_enable(info, HCI_MODE);
if (r < 0)
goto out;
}
file->f_pos = info->read_offset;
break;
case TCGETS:
dev_dbg(&client->dev, "%s: TCGETS\n", __func__);
r = -ENOIOCTLCMD;
break;
default:
dev_err(&client->dev, "Unknown ioctl 0x%x\n", cmd);
r = -ENOIOCTLCMD;
break;
}
out:
mutex_unlock(&info->mutex);
return r;
}
static int pn544_open(struct inode *inode, struct file *file)
{
struct pn544_info *info = container_of(file->private_data,
struct pn544_info, miscdev);
struct i2c_client *client = info->i2c_dev;
int r = 0;
dev_dbg(&client->dev, "%s: info: %p, client %p\n", __func__,
info, info->i2c_dev);
mutex_lock(&info->mutex);
/*
* Only 1 at a time.
* XXX: maybe user (counter) would work better
*/
if (info->state != PN544_ST_COLD) {
r = -EBUSY;
goto out;
}
file->f_pos = info->read_offset;
r = pn544_enable(info, HCI_MODE);
out:
mutex_unlock(&info->mutex);
return r;
}
static int pn544_close(struct inode *inode, struct file *file)
{
struct pn544_info *info = container_of(file->private_data,
struct pn544_info, miscdev);
struct i2c_client *client = info->i2c_dev;
dev_dbg(&client->dev, "%s: info: %p, client %p\n",
__func__, info, info->i2c_dev);
mutex_lock(&info->mutex);
pn544_disable(info);
mutex_unlock(&info->mutex);
return 0;
}
static const struct file_operations pn544_fops = {
.owner = THIS_MODULE,
.llseek = no_llseek,
.read = pn544_read,
.write = pn544_write,
.poll = pn544_poll,
.open = pn544_open,
.release = pn544_close,
.unlocked_ioctl = pn544_ioctl,
};
#ifdef CONFIG_PM
static int pn544_suspend(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct pn544_info *info;
int r = 0;
dev_info(&client->dev, "***\n%s: client %p\n***\n", __func__, client);
info = i2c_get_clientdata(client);
dev_info(&client->dev, "%s: info: %p, client %p\n", __func__,
info, client);
mutex_lock(&info->mutex);
switch (info->state) {
case PN544_ST_FW_READY:
/* Do not suspend while upgrading FW, please! */
r = -EPERM;
break;
case PN544_ST_READY:
/*
* CHECK: Device should be in standby-mode. No way to check?
* Allowing low power mode for the regulator is potentially
* dangerous if pn544 does not go to suspension.
*/
break;
case PN544_ST_COLD:
break;
};
mutex_unlock(&info->mutex);
return r;
}
static int pn544_resume(struct device *dev)
{
struct i2c_client *client = to_i2c_client(dev);
struct pn544_info *info = i2c_get_clientdata(client);
int r = 0;
dev_dbg(&client->dev, "%s: info: %p, client %p\n", __func__,
info, client);
mutex_lock(&info->mutex);
switch (info->state) {
case PN544_ST_READY:
/*
* CHECK: If regulator low power mode is allowed in
* pn544_suspend, we should go back to normal mode
* here.
*/
break;
case PN544_ST_COLD:
break;
case PN544_ST_FW_READY:
break;
};
mutex_unlock(&info->mutex);
return r;
}
static SIMPLE_DEV_PM_OPS(pn544_pm_ops, pn544_suspend, pn544_resume);
#endif
static struct device_attribute pn544_attr =
__ATTR(nfc_test, S_IRUGO, pn544_test, NULL);
static int __devinit pn544_probe(struct i2c_client *client,
const struct i2c_device_id *id)
{
struct pn544_info *info;
struct pn544_nfc_platform_data *pdata;
int r = 0;
dev_dbg(&client->dev, "%s\n", __func__);
dev_dbg(&client->dev, "IRQ: %d\n", client->irq);
/* private data allocation */
info = kzalloc(sizeof(struct pn544_info), GFP_KERNEL);
if (!info) {
dev_err(&client->dev,
"Cannot allocate memory for pn544_info.\n");
r = -ENOMEM;
goto err_info_alloc;
}
info->buflen = max(PN544_MSG_MAX_SIZE, PN544_MAX_I2C_TRANSFER);
info->buf = kzalloc(info->buflen, GFP_KERNEL);
if (!info->buf) {
dev_err(&client->dev,
"Cannot allocate memory for pn544_info->buf.\n");
r = -ENOMEM;
goto err_buf_alloc;
}
info->regs[0].supply = reg_vdd_io;
info->regs[1].supply = reg_vbat;
info->regs[2].supply = reg_vsim;
r = regulator_bulk_get(&client->dev, ARRAY_SIZE(info->regs),
info->regs);
if (r < 0)
goto err_kmalloc;
info->i2c_dev = client;
info->state = PN544_ST_COLD;
info->read_irq = PN544_NONE;
mutex_init(&info->read_mutex);
mutex_init(&info->mutex);
init_waitqueue_head(&info->read_wait);
i2c_set_clientdata(client, info);
pdata = client->dev.platform_data;
if (!pdata) {
dev_err(&client->dev, "No platform data\n");
r = -EINVAL;
goto err_reg;
}
if (!pdata->request_resources) {
dev_err(&client->dev, "request_resources() missing\n");
r = -EINVAL;
goto err_reg;
}
r = pdata->request_resources(client);
if (r) {
dev_err(&client->dev, "Cannot get platform resources\n");
goto err_reg;
}
r = request_threaded_irq(client->irq, NULL, pn544_irq_thread_fn,
IRQF_TRIGGER_RISING | IRQF_ONESHOT, PN544_DRIVER_NAME,
info);
if (r < 0) {
dev_err(&client->dev, "Unable to register IRQ handler\n");
goto err_res;
}
/* If we don't have the test we don't need the sysfs file */
if (pdata->test) {
r = device_create_file(&client->dev, &pn544_attr);
if (r) {
dev_err(&client->dev,
"sysfs registration failed, error %d\n", r);
goto err_irq;
}
}
info->miscdev.minor = MISC_DYNAMIC_MINOR;
info->miscdev.name = PN544_DRIVER_NAME;
info->miscdev.fops = &pn544_fops;
info->miscdev.parent = &client->dev;
r = misc_register(&info->miscdev);
if (r < 0) {
dev_err(&client->dev, "Device registration failed\n");
goto err_sysfs;
}
dev_dbg(&client->dev, "%s: info: %p, pdata %p, client %p\n",
__func__, info, pdata, client);
return 0;
err_sysfs:
if (pdata->test)
device_remove_file(&client->dev, &pn544_attr);
err_irq:
free_irq(client->irq, info);
err_res:
if (pdata->free_resources)
pdata->free_resources();
err_reg:
regulator_bulk_free(ARRAY_SIZE(info->regs), info->regs);
err_kmalloc:
kfree(info->buf);
err_buf_alloc:
kfree(info);
err_info_alloc:
return r;
}
static __devexit int pn544_remove(struct i2c_client *client)
{
struct pn544_info *info = i2c_get_clientdata(client);
struct pn544_nfc_platform_data *pdata = client->dev.platform_data;
dev_dbg(&client->dev, "%s\n", __func__);
misc_deregister(&info->miscdev);
if (pdata->test)
device_remove_file(&client->dev, &pn544_attr);
if (info->state != PN544_ST_COLD) {
if (pdata->disable)
pdata->disable();
info->read_irq = PN544_NONE;
}
free_irq(client->irq, info);
if (pdata->free_resources)
pdata->free_resources();
regulator_bulk_free(ARRAY_SIZE(info->regs), info->regs);
kfree(info->buf);
kfree(info);
return 0;
}
static struct i2c_driver pn544_driver = {
.driver = {
.name = PN544_DRIVER_NAME,
#ifdef CONFIG_PM
.pm = &pn544_pm_ops,
#endif
},
.probe = pn544_probe,
.id_table = pn544_id_table,
.remove = __devexit_p(pn544_remove),
};
static int __init pn544_init(void)
{
int r;
pr_debug(DRIVER_DESC ": %s\n", __func__);
r = i2c_add_driver(&pn544_driver);
if (r) {
pr_err(PN544_DRIVER_NAME ": driver registration failed\n");
return r;
}
return 0;
}
static void __exit pn544_exit(void)
{
i2c_del_driver(&pn544_driver);
pr_info(DRIVER_DESC ", Exiting.\n");
}
module_init(pn544_init);
module_exit(pn544_exit);
MODULE_LICENSE("GPL");
MODULE_DESCRIPTION(DRIVER_DESC);
|
filippz/kernel-adaptation-n950-n9
|
drivers/nfc/pn544.c
|
C
|
gpl-2.0
| 19,659 |
# Copyright (C) 2006, 2012-2015 Red Hat, Inc.
# Copyright (C) 2006 Daniel P. Berrange <[email protected]>
#
# This work is licensed under the GNU GPLv2 or later.
# See the COPYING file in the top-level directory.
from gi.repository import Gio
from gi.repository import GLib
from gi.repository import Gtk
from virtinst import DomainCpu
from virtinst import log
from .lib.inspection import vmmInspection
CSSDATA = """
/* Lighter colored text in some wizard summary fields */
.vmm-lighter {
color: @insensitive_fg_color
}
/* Text on the blue header in our wizards */
.vmm-header-text {
color: white
}
/* Subtext on the blue header in our wizards */
.vmm-header-subtext {
color: #59B0E2
}
/* The blue header */
.vmm-header {
background-color: #0072A8
}
"""
class _SettingsWrapper(object):
"""
Wrapper class to simplify interacting with gsettings APIs.
Basically it allows simple get/set of gconf style paths, and
we internally convert it to the settings nested hierarchy. Makes
client code much smaller.
"""
def __init__(self, settings_id, gsettings_keyfile):
self._root = settings_id
if gsettings_keyfile:
backend = Gio.keyfile_settings_backend_new(gsettings_keyfile, "/")
else:
backend = Gio.SettingsBackend.get_default()
self._settings = Gio.Settings.new_with_backend(self._root, backend)
self._settingsmap = {"": self._settings}
self._handler_map = {}
for child in self._settings.list_children():
childschema = self._root + "." + child
self._settingsmap[child] = Gio.Settings.new_with_backend(
childschema, backend)
###################
# Private helpers #
###################
def _parse_key(self, key):
value = key.strip("/")
settingskey = ""
if "/" in value:
settingskey, value = value.rsplit("/", 1)
return settingskey, value
def _find_settings(self, key):
settingskey, value = self._parse_key(key)
return self._settingsmap[settingskey], value
###############
# Public APIs #
###############
def make_vm_settings(self, key):
"""
Initialize per-VM relocatable schema if necessary
"""
settingskey = self._parse_key(key)[0]
if settingskey in self._settingsmap:
return True
schema = self._root + ".vm"
path = "/" + self._root.replace(".", "/") + key.rsplit("/", 1)[0] + "/"
self._settingsmap[settingskey] = Gio.Settings.new_with_path(
schema, path)
return True
def make_conn_settings(self, key):
"""
Initialize per-conn relocatable schema if necessary
"""
settingskey = self._parse_key(key)[0]
if settingskey in self._settingsmap:
return True
schema = self._root + ".connection"
path = "/" + self._root.replace(".", "/") + key.rsplit("/", 1)[0] + "/"
self._settingsmap[settingskey] = Gio.Settings.new_with_path(
schema, path)
return True
def notify_add(self, key, cb, *args, **kwargs):
settings, key = self._find_settings(key)
def wrapcb(*ignore):
return cb(*args, **kwargs)
ret = settings.connect("changed::%s" % key, wrapcb, *args, **kwargs)
self._handler_map[ret] = settings
return ret
def notify_remove(self, h):
settings = self._handler_map.pop(h)
return settings.disconnect(h)
def get(self, key):
settings, key = self._find_settings(key)
return settings.get_value(key).unpack()
def set(self, key, value, *args, **kwargs):
settings, key = self._find_settings(key)
fmt = settings.get_value(key).get_type_string()
return settings.set_value(key, GLib.Variant(fmt, value),
*args, **kwargs)
class vmmConfig(object):
# key names for saving last used paths
CONFIG_DIR_IMAGE = "image"
CONFIG_DIR_ISO_MEDIA = "isomedia"
CONFIG_DIR_FLOPPY_MEDIA = "floppymedia"
CONFIG_DIR_SCREENSHOT = "screenshot"
CONFIG_DIR_FS = "fs"
# Metadata mapping for browse types. Prob shouldn't go here, but works
# for now.
browse_reason_data = {
CONFIG_DIR_IMAGE: {
"enable_create": True,
"storage_title": _("Locate or create storage volume"),
"local_title": _("Locate existing storage"),
"dialog_type": Gtk.FileChooserAction.SAVE,
"choose_button": Gtk.STOCK_OPEN,
"gsettings_key": "image",
},
CONFIG_DIR_SCREENSHOT: {
"gsettings_key": "screenshot",
},
CONFIG_DIR_ISO_MEDIA: {
"enable_create": False,
"storage_title": _("Locate ISO media volume"),
"local_title": _("Locate ISO media"),
"gsettings_key": "media",
},
CONFIG_DIR_FLOPPY_MEDIA: {
"enable_create": False,
"storage_title": _("Locate floppy media volume"),
"local_title": _("Locate floppy media"),
"gsettings_key": "media",
},
CONFIG_DIR_FS: {
"enable_create": False,
"storage_title": _("Locate directory volume"),
"local_title": _("Locate directory volume"),
"dialog_type": Gtk.FileChooserAction.SELECT_FOLDER,
},
}
CONSOLE_SCALE_NEVER = 0
CONSOLE_SCALE_FULLSCREEN = 1
CONSOLE_SCALE_ALWAYS = 2
_instance = None
@classmethod
def get_instance(cls, *args, **kwargs):
if not cls._instance:
cls._instance = vmmConfig(*args, **kwargs)
return cls._instance
@classmethod
def is_initialized(cls):
return bool(cls._instance)
def __init__(self, BuildConfig, CLITestOptions):
self.appname = "virt-manager"
self.appversion = BuildConfig.version
self.conf_dir = "/org/virt-manager/%s/" % self.appname
self.ui_dir = BuildConfig.ui_dir
self.conf = _SettingsWrapper("org.virt-manager.virt-manager",
CLITestOptions.gsettings_keyfile)
self.CLITestOptions = CLITestOptions
if self.CLITestOptions.xmleditor_enabled:
self.set_xmleditor_enabled(True)
if self.CLITestOptions.enable_libguestfs:
self.set_libguestfs_inspect_vms(True)
if self.CLITestOptions.disable_libguestfs:
self.set_libguestfs_inspect_vms(False)
# We don't create it straight away, since we don't want
# to block the app pending user authorization to access
# the keyring
self._keyring = None
self.default_graphics_from_config = BuildConfig.default_graphics
self.default_hvs = BuildConfig.default_hvs
self.default_storage_format_from_config = "qcow2"
self.default_console_resizeguest = 0
self._objects = []
self.color_insensitive = None
self._init_css()
def _init_css(self):
from gi.repository import Gdk
screen = Gdk.Screen.get_default()
css_provider = Gtk.CssProvider()
css_provider.load_from_data(CSSDATA.encode("utf-8"))
context = Gtk.StyleContext()
context.add_provider_for_screen(screen, css_provider,
Gtk.STYLE_PROVIDER_PRIORITY_USER)
found, color = context.lookup_color("insensitive_fg_color")
if not found: # pragma: no cover
log.debug("Didn't find insensitive_fg_color in theme")
return
self.color_insensitive = color.to_string()
# General app wide helpers (gsettings agnostic)
def get_appname(self):
return self.appname
def get_appversion(self):
return self.appversion
def get_ui_dir(self):
return self.ui_dir
def embeddable_graphics(self):
ret = ["vnc", "spice"]
return ret
def inspection_supported(self):
if not vmmInspection.libguestfs_installed():
return False # pragma: no cover
return self.get_libguestfs_inspect_vms()
def remove_notifier(self, h):
self.conf.notify_remove(h)
# Used for debugging reference leaks, we keep track of all objects
# come and go so we can do a leak report at app shutdown
def add_object(self, obj):
self._objects.append(obj)
def remove_object(self, obj):
self._objects.remove(obj)
def get_objects(self):
return self._objects[:]
#####################################
# Wrappers for setting per-VM value #
#####################################
def _make_pervm_key(self, uuid, key):
return "/vms/%s%s" % (uuid.replace("-", ""), key)
def listen_pervm(self, uuid, key, *args, **kwargs):
key = self._make_pervm_key(uuid, key)
self.conf.make_vm_settings(key)
return self.conf.notify_add(key, *args, **kwargs)
def set_pervm(self, uuid, key, *args, **kwargs):
key = self._make_pervm_key(uuid, key)
self.conf.make_vm_settings(key)
ret = self.conf.set(key, *args, **kwargs)
return ret
def get_pervm(self, uuid, key):
key = self._make_pervm_key(uuid, key)
self.conf.make_vm_settings(key)
return self.conf.get(key)
########################################
# Wrappers for setting per-conn values #
########################################
def _make_perconn_key(self, uri, key):
return "/conns/%s%s" % (uri.replace("/", ""), key)
def listen_perconn(self, uri, key, *args, **kwargs):
key = self._make_perconn_key(uri, key)
self.conf.make_conn_settings(key)
return self.conf.notify_add(key, *args, **kwargs)
def set_perconn(self, uri, key, *args, **kwargs):
key = self._make_perconn_key(uri, key)
self.conf.make_conn_settings(key)
ret = self.conf.set(key, *args, **kwargs)
return ret
def get_perconn(self, uri, key):
key = self._make_perconn_key(uri, key)
self.conf.make_conn_settings(key)
return self.conf.get(key)
###################
# General helpers #
###################
# Manager stats view preferences
def is_vmlist_guest_cpu_usage_visible(self):
return self.conf.get("/vmlist-fields/cpu-usage")
def is_vmlist_host_cpu_usage_visible(self):
return self.conf.get("/vmlist-fields/host-cpu-usage")
def is_vmlist_memory_usage_visible(self):
return self.conf.get("/vmlist-fields/memory-usage")
def is_vmlist_disk_io_visible(self):
return self.conf.get("/vmlist-fields/disk-usage")
def is_vmlist_network_traffic_visible(self):
return self.conf.get("/vmlist-fields/network-traffic")
def set_vmlist_guest_cpu_usage_visible(self, state):
self.conf.set("/vmlist-fields/cpu-usage", state)
def set_vmlist_host_cpu_usage_visible(self, state):
self.conf.set("/vmlist-fields/host-cpu-usage", state)
def set_vmlist_memory_usage_visible(self, state):
self.conf.set("/vmlist-fields/memory-usage", state)
def set_vmlist_disk_io_visible(self, state):
self.conf.set("/vmlist-fields/disk-usage", state)
def set_vmlist_network_traffic_visible(self, state):
self.conf.set("/vmlist-fields/network-traffic", state)
def on_vmlist_guest_cpu_usage_visible_changed(self, cb):
return self.conf.notify_add("/vmlist-fields/cpu-usage", cb)
def on_vmlist_host_cpu_usage_visible_changed(self, cb):
return self.conf.notify_add("/vmlist-fields/host-cpu-usage", cb)
def on_vmlist_memory_usage_visible_changed(self, cb):
return self.conf.notify_add("/vmlist-fields/memory-usage", cb)
def on_vmlist_disk_io_visible_changed(self, cb):
return self.conf.notify_add("/vmlist-fields/disk-usage", cb)
def on_vmlist_network_traffic_visible_changed(self, cb):
return self.conf.notify_add("/vmlist-fields/network-traffic", cb)
# Keys preferences
def get_keys_combination(self):
ret = self.conf.get("/console/grab-keys")
if not ret:
# Left Control + Left Alt
return "65507,65513"
return ret
def set_keys_combination(self, val):
# Val have to be a list of integers
val = ','.join([str(v) for v in val])
self.conf.set("/console/grab-keys", val)
def on_keys_combination_changed(self, cb):
return self.conf.notify_add("/console/grab-keys", cb)
# Confirmation preferences
def get_confirm_forcepoweroff(self):
return self.conf.get("/confirm/forcepoweroff")
def get_confirm_poweroff(self):
return self.conf.get("/confirm/poweroff")
def get_confirm_pause(self):
return self.conf.get("/confirm/pause")
def get_confirm_removedev(self):
return self.conf.get("/confirm/removedev")
def get_confirm_unapplied(self):
return self.conf.get("/confirm/unapplied-dev")
def get_confirm_delstorage(self):
return self.conf.get("/confirm/delete-storage")
def set_confirm_forcepoweroff(self, val):
self.conf.set("/confirm/forcepoweroff", val)
def set_confirm_poweroff(self, val):
self.conf.set("/confirm/poweroff", val)
def set_confirm_pause(self, val):
self.conf.set("/confirm/pause", val)
def set_confirm_removedev(self, val):
self.conf.set("/confirm/removedev", val)
def set_confirm_unapplied(self, val):
self.conf.set("/confirm/unapplied-dev", val)
def set_confirm_delstorage(self, val):
self.conf.set("/confirm/delete-storage", val)
# System tray visibility
def on_view_system_tray_changed(self, cb):
return self.conf.notify_add("/system-tray", cb)
def get_view_system_tray(self):
return self.conf.get("/system-tray")
def set_view_system_tray(self, val):
self.conf.set("/system-tray", val)
# XML editor enabled
def on_xmleditor_enabled_changed(self, cb):
return self.conf.notify_add("/xmleditor-enabled", cb)
def get_xmleditor_enabled(self):
return self.conf.get("/xmleditor-enabled")
def set_xmleditor_enabled(self, val):
self.conf.set("/xmleditor-enabled", val)
# Libguestfs VM inspection
def get_libguestfs_inspect_vms(self):
return self.conf.get("/enable-libguestfs-vm-inspection")
def set_libguestfs_inspect_vms(self, val):
self.conf.set("/enable-libguestfs-vm-inspection", val)
# Stats history and interval length
def get_stats_history_length(self):
return 120
def get_stats_update_interval(self):
if self.CLITestOptions.short_poll:
return .1
interval = self.conf.get("/stats/update-interval")
return max(interval, 1)
def set_stats_update_interval(self, interval):
self.conf.set("/stats/update-interval", interval)
def on_stats_update_interval_changed(self, cb):
return self.conf.notify_add("/stats/update-interval", cb)
# Disable/Enable different stats polling
def get_stats_enable_cpu_poll(self):
return self.conf.get("/stats/enable-cpu-poll")
def get_stats_enable_disk_poll(self):
return self.conf.get("/stats/enable-disk-poll")
def get_stats_enable_net_poll(self):
return self.conf.get("/stats/enable-net-poll")
def get_stats_enable_memory_poll(self):
return self.conf.get("/stats/enable-memory-poll")
def set_stats_enable_cpu_poll(self, val):
self.conf.set("/stats/enable-cpu-poll", val)
def set_stats_enable_disk_poll(self, val):
self.conf.set("/stats/enable-disk-poll", val)
def set_stats_enable_net_poll(self, val):
self.conf.set("/stats/enable-net-poll", val)
def set_stats_enable_memory_poll(self, val):
self.conf.set("/stats/enable-memory-poll", val)
def on_stats_enable_cpu_poll_changed(self, cb, row=None):
return self.conf.notify_add("/stats/enable-cpu-poll", cb, row)
def on_stats_enable_disk_poll_changed(self, cb, row=None):
return self.conf.notify_add("/stats/enable-disk-poll", cb, row)
def on_stats_enable_net_poll_changed(self, cb, row=None):
return self.conf.notify_add("/stats/enable-net-poll", cb, row)
def on_stats_enable_memory_poll_changed(self, cb, row=None):
return self.conf.notify_add("/stats/enable-memory-poll", cb, row)
def get_console_scaling(self):
return self.conf.get("/console/scaling")
def set_console_scaling(self, pref):
self.conf.set("/console/scaling", pref)
def get_console_resizeguest(self):
val = self.conf.get("/console/resize-guest")
if val == -1:
val = self.default_console_resizeguest
return val
def set_console_resizeguest(self, pref):
self.conf.set("/console/resize-guest", pref)
def get_auto_usbredir(self):
return bool(self.conf.get("/console/auto-redirect"))
def set_auto_usbredir(self, state):
self.conf.set("/console/auto-redirect", state)
def get_console_autoconnect(self):
return bool(self.conf.get("/console/autoconnect"))
def set_console_autoconnect(self, val):
return self.conf.set("/console/autoconnect", val)
# Show VM details toolbar
def get_details_show_toolbar(self):
res = self.conf.get("/details/show-toolbar")
if res is None:
res = True # pragma: no cover
return res
def set_details_show_toolbar(self, state):
self.conf.set("/details/show-toolbar", state)
# New VM preferences
def get_graphics_type(self, raw=False):
ret = self.conf.get("/new-vm/graphics-type")
if ret not in ["system", "vnc", "spice"]:
ret = "system" # pragma: no cover
if ret == "system" and not raw:
return self.default_graphics_from_config
return ret
def set_graphics_type(self, gtype):
self.conf.set("/new-vm/graphics-type", gtype.lower())
def get_default_storage_format(self, raw=False):
ret = self.conf.get("/new-vm/storage-format")
if ret not in ["default", "raw", "qcow2"]:
ret = "default" # pragma: no cover
if ret == "default" and not raw:
return self.default_storage_format_from_config
return ret
def set_storage_format(self, typ):
self.conf.set("/new-vm/storage-format", typ.lower())
def get_default_cpu_setting(self):
ret = self.conf.get("/new-vm/cpu-default")
if ret not in DomainCpu.SPECIAL_MODES:
ret = DomainCpu.SPECIAL_MODE_APP_DEFAULT # pragma: no cover
return ret
def set_default_cpu_setting(self, val):
self.conf.set("/new-vm/cpu-default", val.lower())
def get_default_firmware_setting(self):
ret = self.conf.get("/new-vm/firmware")
if ret not in ["default", "uefi"]:
ret = "default" # pragma: no cover
return ret
def set_firmware_setting(self, val):
self.conf.set("/new-vm/firmware", val.lower())
# URL/Media path history
def _url_add_helper(self, gsettings_path, url):
maxlength = 10
urls = self.conf.get(gsettings_path) or []
if urls.count(url) == 0 and len(url) > 0 and not url.isspace():
# The url isn't already in the list, so add it
urls.insert(0, url)
if len(urls) > maxlength:
del urls[len(urls) - 1] # pragma: no cover
self.conf.set(gsettings_path, urls)
def add_container_url(self, url):
self._url_add_helper("/urls/containers", url)
def get_container_urls(self):
return self.conf.get("/urls/containers") or []
def add_media_url(self, url):
self._url_add_helper("/urls/urls", url)
def get_media_urls(self):
return self.conf.get("/urls/urls") or []
def add_iso_path(self, path):
self._url_add_helper("/urls/isos", path)
def get_iso_paths(self):
return self.conf.get("/urls/isos") or []
def on_iso_paths_changed(self, cb):
return self.conf.notify_add("/urls/isos", cb)
# Whether to ask about fixing path permissions
def add_perms_fix_ignore(self, pathlist):
current_list = self.get_perms_fix_ignore() or []
for path in pathlist:
if path in current_list:
continue # pragma: no cover
current_list.append(path)
self.conf.set("/paths/perms-fix-ignore", current_list)
def get_perms_fix_ignore(self):
return self.conf.get("/paths/perms-fix-ignore")
# Manager view connection list
def get_conn_uris(self):
return self.conf.get("/connections/uris") or []
def add_conn_uri(self, uri):
uris = self.get_conn_uris()
if uri not in uris:
uris.insert(len(uris) - 1, uri)
self.conf.set("/connections/uris", uris)
def remove_conn_uri(self, uri):
uris = self.get_conn_uris()
if uri in uris:
uris.remove(uri)
self.conf.set("/connections/uris", uris)
if self.get_conn_autoconnect(uri):
uris = self.conf.get("/connections/autoconnect")
uris.remove(uri)
self.conf.set("/connections/autoconnect", uris)
# Manager default window size
def get_manager_window_size(self):
w = self.conf.get("/manager-window-width")
h = self.conf.get("/manager-window-height")
return (w, h)
def set_manager_window_size(self, w, h):
self.conf.set("/manager-window-width", w)
self.conf.set("/manager-window-height", h)
# URI autoconnect
def get_conn_autoconnect(self, uri):
uris = self.conf.get("/connections/autoconnect")
return ((uris is not None) and (uri in uris))
def set_conn_autoconnect(self, uri, val):
uris = self.conf.get("/connections/autoconnect") or []
if not val and uri in uris:
uris.remove(uri)
elif val and uri not in uris:
uris.append(uri)
self.conf.set("/connections/autoconnect", uris)
# Default directory location dealings
def get_default_directory(self, conn, _type):
ignore = conn
browsedata = self.browse_reason_data.get(_type, {})
key = browsedata.get("gsettings_key", None)
path = None
if key:
path = self.conf.get("/paths/%s-default" % key)
log.debug("directory for type=%s returning=%s", _type, path)
return path
def set_default_directory(self, folder, _type):
browsedata = self.browse_reason_data.get(_type, {})
key = browsedata.get("gsettings_key", None)
if not key:
return # pragma: no cover
log.debug("saving directory for type=%s to %s", key, folder)
self.conf.set("/paths/%s-default" % key, folder)
|
virt-manager/virt-manager
|
virtManager/config.py
|
Python
|
gpl-2.0
| 22,895 |
<?php
require('../autoloader.php');
/*
* This script checks for the availability of domain names
*
* You can specify multiple domain names to be checked
*/
if ($argc <= 1) {
echo "Usage: changepassword <password>\n";
echo "Please enter new password you want to use\n\n";
die();
}
$newpassword = $argv[1];
echo "Changing password\n";
try {
$conn = new Metaregistrar\EPP\metaregEppConnection();
$conn->setNewPassword($newpassword);
// Connect to the EPP server
if ($conn->connect()) {
if (login($conn)) {
echo "Password was changed, you are logged-out automatically\n";
}
}
} catch (Metaregistrar\EPP\eppException $e) {
echo "ERROR: " . $e->getMessage() . "\n\n";
}
|
joshuaocero/php-epp-client
|
Examples/changepassword.php
|
PHP
|
gpl-2.0
| 737 |
/* ===============================================================
Basic Swiper Styles
================================================================*/
.swiper-container,
.swiper_container {
margin:0 auto;
position:relative;
overflow:hidden;
-webkit-backface-visibility:hidden;
-moz-backface-visibility:hidden;
-ms-backface-visibility:hidden;
-o-backface-visibility:hidden;
backface-visibility:hidden;
/* Fix of Webkit flickering */
z-index:1;
}
.swiper-wrapper {
position:relative;
width:100%;
-webkit-transition-property:-webkit-transform, left, top;
-webkit-transition-duration:0s;
-webkit-transform:translate3d(0px,0,0);
-webkit-transition-timing-function:ease;
-moz-transition-property:-moz-transform, left, top;
-moz-transition-duration:0s;
-moz-transform:translate3d(0px,0,0);
-moz-transition-timing-function:ease;
-o-transition-property:-o-transform, left, top;
-o-transition-duration:0s;
-o-transform:translate3d(0px,0,0);
-o-transition-timing-function:ease;
-o-transform:translate(0px,0px);
-ms-transition-property:-ms-transform, left, top;
-ms-transition-duration:0s;
-ms-transform:translate3d(0px,0,0);
-ms-transition-timing-function:ease;
transition-property:transform, left, top;
transition-duration:0s;
transform:translate3d(0px,0,0);
transition-timing-function:ease;
-webkit-box-sizing: content-box;
-moz-box-sizing: content-box;
box-sizing: content-box;
}
.swiper-free-mode > .swiper-wrapper {
-webkit-transition-timing-function: ease-out;
-moz-transition-timing-function: ease-out;
-ms-transition-timing-function: ease-out;
-o-transition-timing-function: ease-out;
transition-timing-function: ease-out;
margin: 0 auto;
}
.swiper-slide {
float: left;
}
/* IE10 Windows Phone 8 Fixes */
.swiper-wp8-horizontal {
-ms-touch-action: pan-y;
}
.swiper-wp8-vertical {
-ms-touch-action: pan-x;
}
|
joysubamarasigan/saladmaster
|
wp-content/themes/jakobi/theme/assets/css/idangerous.swiper.css
|
CSS
|
gpl-2.0
| 1,861 |
/*
* Written by Doug Lea with assistance from members of JCP JSR-166
* Expert Group and released to the public domain, as explained at
* http://creativecommons.org/publicdomain/zero/1.0/
*/
package java.util.concurrent.atomic;
import sun.misc.Unsafe;
/**
* A {@code boolean} value that may be updated atomically. See the
* {@link java.util.concurrent.atomic} package specification for
* description of the properties of atomic variables. An
* {@code AtomicBoolean} is used in applications such as atomically
* updated flags, and cannot be used as a replacement for a
* {@link java.lang.Boolean}.
*
* @since 1.5
* @author Doug Lea
*/
public class AtomicBoolean implements java.io.Serializable {
private static final long serialVersionUID = 4654671469794556979L;
// setup to use Unsafe.compareAndSwapInt for updates
private static final Unsafe unsafe = Unsafe.getUnsafe();
private static final long valueOffset;
static {
try {
valueOffset = unsafe.objectFieldOffset
(AtomicBoolean.class.getDeclaredField("value"));
} catch (Exception ex) { throw new Error(ex); }
}
private volatile int value;
/**
* Creates a new {@code AtomicBoolean} with the given initial value.
*
* @param initialValue the initial value
*/
public AtomicBoolean(boolean initialValue) {
value = initialValue ? 1 : 0;
}
/**
* Creates a new {@code AtomicBoolean} with initial value {@code false}.
*/
public AtomicBoolean() {
}
/**
* Returns the current value.
*
* @return the current value
*/
public final boolean get() {
return value != 0;
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* @param expect the expected value
* @param update the new value
* @return true if successful. False return indicates that
* the actual value was not equal to the expected value.
*/
public final boolean compareAndSet(boolean expect, boolean update) {
int e = expect ? 1 : 0;
int u = update ? 1 : 0;
return unsafe.compareAndSwapInt(this, valueOffset, e, u);
}
/**
* Atomically sets the value to the given updated value
* if the current value {@code ==} the expected value.
*
* <p>May <a href="package-summary.html#Spurious">fail spuriously</a>
* and does not provide ordering guarantees, so is only rarely an
* appropriate alternative to {@code compareAndSet}.
*
* @param expect the expected value
* @param update the new value
* @return true if successful.
*/
public boolean weakCompareAndSet(boolean expect, boolean update) {
int e = expect ? 1 : 0;
int u = update ? 1 : 0;
return unsafe.compareAndSwapInt(this, valueOffset, e, u);
}
/**
* Unconditionally sets to the given value.
*
* @param newValue the new value
*/
public final void set(boolean newValue) {
value = newValue ? 1 : 0;
}
/**
* Eventually sets to the given value.
*
* @param newValue the new value
* @since 1.6
*/
public final void lazySet(boolean newValue) {
int v = newValue ? 1 : 0;
unsafe.putOrderedInt(this, valueOffset, v);
}
/**
* Atomically sets to the given value and returns the previous value.
*
* @param newValue the new value
* @return the previous value
*/
public final boolean getAndSet(boolean newValue) {
for (;;) {
boolean current = get();
if (compareAndSet(current, newValue))
return current;
}
}
/**
* Returns the String representation of the current value.
* @return the String representation of the current value.
*/
public String toString() {
return Boolean.toString(get());
}
}
|
rex-xxx/mt6572_x201
|
libcore/luni/src/main/java/java/util/concurrent/atomic/AtomicBoolean.java
|
Java
|
gpl-2.0
| 3,981 |
/**
* @license Copyright (c) 2003-2019, CKSource - Frederico Knabben. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
CKEDITOR.plugins.setLang( 'language', 'eo', {
button: 'Instali lingvon',
remove: 'Forigi lingvon'
} );
|
commsy/commsy
|
public/ckeditor/language/lang/eo.js
|
JavaScript
|
gpl-2.0
| 286 |
<?php
namespace FluidTYPO3\Builder\CodeGeneration;
/***************************************************************
* Copyright notice
*
* (c) 2014 Claus Due <[email protected]>
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project 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.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script 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.
*
* This copyright notice MUST APPEAR in all copies of the script!
* ************************************************************* */
use TYPO3\CMS\Core\Utility\ExtensionManagementUtility;
use TYPO3\CMS\Core\Utility\GeneralUtility;
use TYPO3\CMS\Extbase\Object\ObjectManagerInterface;
/**
* Class AbstractCodeGenerator
* @package FluidTYPO3\Builder\CodeGeneration
*/
abstract class AbstractCodeGenerator implements CodeGeneratorInterface {
/**
* @var boolean
*/
protected $verbose = TRUE;
/**
* @var boolean
*/
protected $dry = FALSE;
/**
* @var ObjectManagerInterface
*/
protected $objectManager;
/**
* @param ObjectManagerInterface $objectManager
* @return void
*/
public function injectObjectManager(ObjectManagerInterface $objectManager) {
$this->objectManager = $objectManager;
}
/**
* @param boolean $dry
* @return void
*/
public function setDry($dry) {
$this->dry = $dry;
}
/**
* @param boolean $verbose
* @return void
*/
public function setVerbose($verbose) {
$this->verbose = $verbose;
}
/**
* @param string $folderPath
* @return boolean
* @throws \Exception
*/
public function createFolder($folderPath) {
if (TRUE === $this->dry) {
return TRUE;
}
try {
GeneralUtility::mkdir_deep($folderPath);
} catch (\InvalidArgumentException $exception) {
throw new \Exception('Unable to create directory "' . $folderPath . '"', 1371692697);
}
return TRUE;
}
/**
* @param string $filePathAndFilename
* @param string $content
* @return boolean
* @throws \Exception
*/
public function createFile($filePathAndFilename, $content) {
if (TRUE === $this->dry) {
return TRUE;
}
$folderPath = pathinfo($filePathAndFilename, PATHINFO_DIRNAME);
if (FALSE === is_dir($folderPath)) {
$this->createFolder($folderPath);
}
$createdFile = GeneralUtility::writeFile($filePathAndFilename, $content);
if (FALSE === $createdFile) {
throw new \Exception('Unable to create file "' . $filePathAndFilename . '"', 1371695066);
}
return TRUE;
}
/**
* @param string $localRelativePathAndFilename
* @param string $destinationPathAndFilename
* @return boolean
* @throws \Exception
*/
public function copyFile($localRelativePathAndFilename, $destinationPathAndFilename) {
if (TRUE === $this->dry) {
return TRUE;
}
$folderPath = pathinfo($destinationPathAndFilename, PATHINFO_DIRNAME);
if (FALSE === is_dir($folderPath)) {
$this->createFolder($folderPath);
}
$localFile = $this->getBuilderExtensionPath() . $localRelativePathAndFilename;
$fileCopied = copy($localFile, $destinationPathAndFilename);
if (FALSE === $fileCopied) {
throw new \Exception('Unable to copy file "' . $localFile . '" to "' . $destinationPathAndFilename . '"', 1371695897);
}
return TRUE;
}
/**
* @return string
*/
protected function getBuilderExtensionPath() {
return rtrim(ExtensionManagementUtility::extPath('builder'), '/') . '/';
}
/**
* @param string $filePathAndFilename
* @return void
*/
public function save($filePathAndFilename) {
$code = $this->generate();
$this->createFile($filePathAndFilename, $code);
}
/**
* @param string $identifier
* @param array $variables
* @return CodeTemplate
*/
protected function getPreparedCodeTemplate($identifier, $variables) {
/** @var CodeTemplate $template */
$template = $this->objectManager->get('FluidTYPO3\Builder\CodeGeneration\CodeTemplate');
$template->setPath(ExtensionManagementUtility::extPath('builder', 'Resources/Private/CodeTemplates/'));
$template->setIdentifier($identifier);
$template->setVariables($variables);
return $template;
}
}
|
famelo/TYPO3-Base
|
typo3conf/ext/builder/Classes/CodeGeneration/AbstractCodeGenerator.php
|
PHP
|
gpl-2.0
| 4,539 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.